-
Notifications
You must be signed in to change notification settings - Fork 1
/
allocation.go
72 lines (58 loc) · 1.65 KB
/
allocation.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
package decision
import (
"errors"
"github.com/spaolacci/murmur3"
)
var VisitorNotTrackedError = errors.New("Visitor untracked")
func genHashFloat(visitorID string, vgID string) (float32, error) {
hash := murmur3.New32()
_, err := hash.Write([]byte(vgID + visitorID))
if err != nil {
return 0, err
}
hashed := hash.Sum32()
return float32(hashed % 100), nil
}
// getRandomAllocation returns a random allocation for a variationGroup
func getRandomAllocation(visitorID string, decisionGroup string, variationGroup *VariationGroup, isCumulativeAlloc bool) (*Variation, error) {
// performance shortcut to prevent hash generation
if len(variationGroup.Variations) == 1 && variationGroup.Variations[0].Allocation == 100 {
return variationGroup.Variations[0], nil
}
// Use decision group by default for decision hash, otherwise use visitor ID
decisionID := visitorID
if decisionGroup != "" {
decisionID = decisionGroup
}
z, err := genHashFloat(decisionID, variationGroup.ID)
if err != nil {
return nil, err
}
sumAlloc := float32(0)
for _, v := range variationGroup.Variations {
sumAlloc += v.Allocation
if isCumulativeAlloc {
sumAlloc = v.Allocation
}
if z < sumAlloc {
return v, nil
}
}
// If no variation alloc, returns empty
return nil, VisitorNotTrackedError
}
func isVisitorInBucket(visitorID string, campaign *Campaign) (bool, error) {
if campaign == nil {
return false, errors.New("campaign is null")
}
z, err := genHashFloat(visitorID, "")
if err != nil {
return false, err
}
for _, br := range campaign.BucketRanges {
if z >= float32(br[0]) && z < float32(br[1]) {
return true, nil
}
}
return false, nil
}