-
Notifications
You must be signed in to change notification settings - Fork 660
/
unary_snowflake.go
77 lines (61 loc) · 1.88 KB
/
unary_snowflake.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package snowball
import "fmt"
var _ Unary = (*unarySnowflake)(nil)
func newUnarySnowflake(alphaPreference, alphaConfidence, beta int) unarySnowflake {
return unarySnowflake{
alphaPreference: alphaPreference,
alphaConfidence: alphaConfidence,
beta: beta,
}
}
// unarySnowflake is the implementation of a unary snowflake instance
type unarySnowflake struct {
// beta is the number of consecutive successful queries required for
// finalization.
beta int
// alphaPreference is the threshold required to update the preference
alphaPreference int
// alphaConfidence is the threshold required to increment the confidence counter
alphaConfidence int
// confidence tracks the number of successful polls in a row that have
// returned the preference
confidence int
// finalized prevents the state from changing after the required number of
// consecutive polls has been reached
finalized bool
}
func (sf *unarySnowflake) RecordPoll(count int) {
if count < sf.alphaConfidence {
sf.RecordUnsuccessfulPoll()
return
}
sf.confidence++
sf.finalized = sf.finalized || sf.confidence >= sf.beta
}
func (sf *unarySnowflake) RecordUnsuccessfulPoll() {
sf.confidence = 0
}
func (sf *unarySnowflake) Finalized() bool {
return sf.finalized
}
func (sf *unarySnowflake) Extend(choice int) Binary {
return &binarySnowflake{
binarySlush: binarySlush{preference: choice},
confidence: sf.confidence,
alphaPreference: sf.alphaPreference,
alphaConfidence: sf.alphaConfidence,
beta: sf.beta,
finalized: sf.finalized,
}
}
func (sf *unarySnowflake) Clone() Unary {
newSnowflake := *sf
return &newSnowflake
}
func (sf *unarySnowflake) String() string {
return fmt.Sprintf("SF(Confidence = %d, Finalized = %v)",
sf.confidence,
sf.finalized)
}