-
Notifications
You must be signed in to change notification settings - Fork 12
/
pending_call_registry.go
96 lines (83 loc) · 2.23 KB
/
pending_call_registry.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
package enigma
import (
"context"
"sync"
"time"
)
type (
pendingCall struct {
Response *socketInput
ID int
Done chan error
receiveTimestamp time.Time
messageSize int
}
pendingCallRegistry struct {
callIDSeq int
mutex sync.Mutex
pendingCalls map[int]*pendingCall
terminalError error
}
reservedRequestIDKey struct{}
)
func (q *pendingCallRegistry) takeRequestID() int {
q.mutex.Lock()
defer q.mutex.Unlock()
q.callIDSeq++
return q.callIDSeq
}
func (q *pendingCallRegistry) registerPendingCall(ctx context.Context) *pendingCall {
q.mutex.Lock()
defer q.mutex.Unlock()
reservedRequestID := ctx.Value(reservedRequestIDKey{})
var id int
if reservedRequestID != nil {
id = reservedRequestID.(int)
} else {
q.callIDSeq++
id = q.callIDSeq
}
pendingCall := &pendingCall{Done: make(chan error, 10), ID: id}
q.pendingCalls[id] = pendingCall
return pendingCall
}
func (q *pendingCallRegistry) removePendingCall(id int) *pendingCall {
q.mutex.Lock()
defer q.mutex.Unlock()
pendingCall := q.pendingCalls[id]
delete(q.pendingCalls, id)
return pendingCall
}
func newPendingCallRegistry() *pendingCallRegistry {
return &pendingCallRegistry{callIDSeq: 0, pendingCalls: make(map[int]*pendingCall)}
}
// Creates a new context that contains a reserved JSON RPC protocol level request id.
// It can be for instance be useful when the request id used for upcoming call needs to be known.
func (q *pendingCallRegistry) WithReservedRequestID(ctx context.Context) (context.Context, int) {
q.mutex.Lock()
defer q.mutex.Unlock()
q.callIDSeq++
id := q.callIDSeq
newContext := context.WithValue(ctx, reservedRequestIDKey{}, id)
return newContext, id
}
func (q *pendingCallRegistry) closedWithError() error {
q.mutex.Lock()
defer q.mutex.Unlock()
return q.terminalError
}
func (q *pendingCallRegistry) closeAllPendingCallsWithError(err error) {
q.mutex.Lock()
defer q.mutex.Unlock()
oldPendingCalls := q.pendingCalls
q.pendingCalls = make(map[int]*pendingCall)
q.terminalError = err
for _, pendingCall := range oldPendingCalls {
pendingCall.Done <- err
}
}
func (q *pendingCallRegistry) pendingCallCount() int {
q.mutex.Lock()
defer q.mutex.Unlock()
return len(q.pendingCalls)
}