-
Notifications
You must be signed in to change notification settings - Fork 1
/
decision_cache.go
100 lines (88 loc) · 2.24 KB
/
decision_cache.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package decision
import (
"sync"
"time"
)
type assignmentResult struct {
result *VisitorAssignments
idType string
err error
}
type allVisitorAssignments struct {
Standard *VisitorAssignments
Anonymous *VisitorAssignments
DecisionGroup *VisitorAssignments
}
func getCache(
environmentID string,
visitorID string,
anonymousID string,
decisionGroup string,
enableReconciliation bool,
getCacheHandler func(environmentID string, id string) (*VisitorAssignments, error)) (*allVisitorAssignments, error) {
cacheChan := make(chan (*assignmentResult))
allAssignments := &allVisitorAssignments{
Standard: &VisitorAssignments{
Assignments: map[string]*VisitorCache{},
},
}
var err error
var nbRoutines = 1
fetchCacheForID := func(c chan (*assignmentResult), id string, idType string) {
logger.Logf(InfoLevel, "getting assignment cache for %s: %s", idType, id)
newAssignments, err := getCacheHandler(environmentID, id)
c <- &assignmentResult{
result: newAssignments,
idType: idType,
err: err,
}
}
go fetchCacheForID(cacheChan, visitorID, "standard")
if enableReconciliation {
nbRoutines++
go fetchCacheForID(cacheChan, anonymousID, "anonymous")
}
if decisionGroup != "" {
nbRoutines++
go fetchCacheForID(cacheChan, decisionGroup, "decisionGroup")
}
for i := 0; i < nbRoutines; i++ {
r := <-cacheChan
switch r.idType {
case "standard":
allAssignments.Standard = r.result
case "anonymous":
allAssignments.Anonymous = r.result
case "decisionGroup":
allAssignments.DecisionGroup = r.result
}
err = r.err
}
return allAssignments, err
}
// Saves a set of cache assignments for a specific id type and using cache handlers
func saveCacheAssignments(
wg *sync.WaitGroup,
handlers DecisionHandlers,
envID string,
id string,
idType string,
assignments map[string]*VisitorCache,
) {
if len(assignments) == 0 || id == "" {
return
}
wg.Add(1)
now := time.Now()
go func() {
defer wg.Done()
logger.Logf(InfoLevel, "saving assignments cache for %s: %s", idType, id)
err := handlers.SaveCache(envID, id, &VisitorAssignments{
Timestamp: now.Unix(),
Assignments: assignments,
})
if err != nil {
logger.Logf(ErrorLevel, "error occurred on cache saving for %s: %v", id, err)
}
}()
}