-
Notifications
You must be signed in to change notification settings - Fork 0
/
context-store.go
68 lines (58 loc) · 1.35 KB
/
context-store.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
package models
import (
"context"
"github.com/wufe/polo/pkg/utils"
)
type contextStore struct {
utils.RWLocker
contexts map[string]*contextAndCancel
}
type contextAndCancel struct {
Context context.Context
Cancel context.CancelFunc
}
func NewContextStore(mutexBuilder utils.MutexBuilder) *contextStore {
return &contextStore{
RWLocker: mutexBuilder(),
contexts: make(map[string]*contextAndCancel),
}
}
func (s *contextStore) Named(key string) struct {
With func(context.Context, context.CancelFunc) struct{ Delete func() }
} {
return struct {
With func(context.Context, context.CancelFunc) struct{ Delete func() }
}{
With: func(c context.Context, cf context.CancelFunc) struct{ Delete func() } {
del := s.Add(key, c, cf)
return struct{ Delete func() }{
Delete: del,
}
},
}
}
func (s *contextStore) Add(key string, ctx context.Context, cancel context.CancelFunc) func() {
s.Lock()
defer s.Unlock()
s.contexts[key] = &contextAndCancel{
Context: ctx,
Cancel: cancel,
}
return func() {
s.Del(key)
}
}
func (s *contextStore) Del(key string) {
s.Lock()
defer s.Unlock()
delete(s.contexts, key)
}
func (s *contextStore) TryGet(key string) (context.Context, context.CancelFunc, bool) {
s.RLock()
defer s.RUnlock()
ctx, exists := s.contexts[key]
if exists {
return ctx.Context, ctx.Cancel, exists
}
return nil, nil, false
}