-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
rpccanceler.go
71 lines (58 loc) · 1.36 KB
/
rpccanceler.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
package libkb
import (
"sync"
"golang.org/x/net/context"
)
type RPCCancelerReason uint
const (
RPCCancelerReasonLogout RPCCancelerReason = 1 << iota
RPCCancelerReasonBackground
RPCCancelerReasonMax
)
const RPCCancelerReasonAll = RPCCancelerReasonMax - 1
type RPCCancelerKey string
func NewRPCCancelerKey() RPCCancelerKey {
return RPCCancelerKey(RandStringB64(3))
}
type liveContext struct {
ctx context.Context
cancelFn context.CancelFunc
reason RPCCancelerReason
}
type RPCCanceler struct {
sync.Mutex
liveCtxs map[RPCCancelerKey]liveContext
}
func NewRPCCanceler() *RPCCanceler {
return &RPCCanceler{
liveCtxs: make(map[RPCCancelerKey]liveContext),
}
}
func (r *RPCCanceler) RegisterContext(ctx context.Context, reason RPCCancelerReason) (context.Context, RPCCancelerKey) {
r.Lock()
defer r.Unlock()
var lc liveContext
lc.ctx, lc.cancelFn = context.WithCancel(ctx)
id := NewRPCCancelerKey()
lc.reason = reason
r.liveCtxs[id] = lc
return lc.ctx, id
}
func (r *RPCCanceler) UnregisterContext(id RPCCancelerKey) {
r.Lock()
defer r.Unlock()
if lc, ok := r.liveCtxs[id]; ok {
lc.cancelFn()
delete(r.liveCtxs, id)
}
}
func (r *RPCCanceler) CancelLiveContexts(reason RPCCancelerReason) {
r.Lock()
defer r.Unlock()
for id, liveCtx := range r.liveCtxs {
if liveCtx.reason&reason != 0 {
liveCtx.cancelFn()
delete(r.liveCtxs, id)
}
}
}