/
stream.go
342 lines (289 loc) · 6.86 KB
/
stream.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package rpcc
import (
"context"
"encoding/json"
"errors"
"sync"
)
// ErrStreamClosing indicates that the operation is illegal because
// the stream is closing and there are no pending messages.
var ErrStreamClosing = &closeError{msg: "rpcc: the stream is closing"}
// message contains the invoked method name, data and next func.
type message struct {
method string
data []byte
next func()
}
// messageBuffer is an unbounded channel of message.
type messageBuffer struct {
c chan *message
mu sync.Mutex // Protects following.
backlog []*message
}
func newMessageBuffer() *messageBuffer {
return &messageBuffer{
c: make(chan *message, 1),
}
}
// store the message in ch, if empty, otherwise in queue.
func (b *messageBuffer) store(m *message) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.backlog) == 0 {
select {
case b.c <- m:
return
default:
}
}
b.backlog = append(b.backlog, m)
}
// load moves a message from the queue into ch.
func (b *messageBuffer) load() {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.backlog) > 0 {
select {
case b.c <- b.backlog[0]:
b.backlog[0] = nil // Remove reference from underlying array.
b.backlog = b.backlog[1:]
default:
}
}
}
// clear removes all messages from buffer.
func (b *messageBuffer) clear() {
b.mu.Lock()
backlog := b.backlog
b.backlog = nil
b.mu.Unlock()
select {
case m := <-b.c:
m.next()
default:
}
for _, m := range backlog {
m.next()
}
}
func (b *messageBuffer) get() <-chan *message {
return b.c
}
// Stream represents a stream of notifications for a certain method.
type Stream interface {
// Ready returns a channel that is closed when a message is
// ready to be received via RecvMsg. Ready indicates that a call
// to RecvMsg is non-blocking.
//
// Ready must not be called concurrently while relying on the
// non-blocking behavior of RecvMsg. In this case both
// goroutines will be competing for the same message and one
// will block until the next message is available.
//
// Calling Close on the Stream will close the Ready channel
// indefinitely, pending messages may still be received via
// RecvMsg.
//
// Ready is provided for use in select statements.
Ready() <-chan struct{}
// RecvMsg unmarshals pending messages onto m. Blocks until the
// next message is received, context is canceled or stream is
// closed.
//
// When m is a *[]byte the message will not be decoded and the
// raw bytes are copied into m.
RecvMsg(m interface{}) error
// Close closes the stream and no new messages will be received.
// RecvMsg will return ErrStreamClosing once all pending messages
// have been received.
Close() error
}
// NewStream creates a new stream that listens to notifications from the
// RPC server. This function is called by generated code.
func NewStream(ctx context.Context, method string, conn *Conn) (Stream, error) {
if ctx == nil {
ctx = context.Background()
}
return newStreamClient(ctx, method, conn)
}
func newStreamClient(ctx context.Context, method string, conn *Conn) (*streamClient, error) {
s := &streamClient{
conn: conn,
method: method,
ctx: ctx,
mbuf: newMessageBuffer(),
ready: make(chan struct{}),
done: make(chan struct{}),
}
remove, err := conn.listen(method, s)
if err != nil {
return nil, err
}
s.remove = remove
go s.watch()
return s, nil
}
type streamClient struct {
// Used to sync streams.
conn *Conn
method string
// User provided context.
ctx context.Context
// mbuf stores all incoming messages
// until they are ready to be received.
mbuf *messageBuffer
readyMu sync.Mutex // Protects following.
ready chan struct{}
seq uint64
readyClosed bool
mu sync.Mutex // Protects following.
remove func() // Unsubscribes from messages.
done chan struct{}
err error
}
func (s *streamClient) watch() {
select {
case <-s.ctx.Done():
s.close(s.ctx.Err())
case <-s.conn.ctx.Done():
s.close(s.conn.err)
case <-s.done:
}
}
func (s *streamClient) Ready() <-chan struct{} {
s.readyMu.Lock()
defer s.readyMu.Unlock()
return s.ready
}
func (s *streamClient) RecvMsg(m interface{}) (err error) {
msg, err := s.recv()
if err != nil {
return err
}
if m, ok := m.(*[]byte); ok {
*m = append(*m, msg.data...)
return nil
}
return json.Unmarshal(msg.data, m)
}
func (s *streamClient) recv() (m *message, err error) {
userCancelled := func() bool {
select {
case <-s.ctx.Done():
return true
default:
return false
}
}
select {
case <-s.done:
// Give precedence for user cancellation.
if userCancelled() {
return nil, s.ctx.Err()
}
// Send all messages before returning error.
select {
case m = <-s.mbuf.get():
default:
return nil, s.err
}
case m = <-s.mbuf.get():
// Give precedence for user cancellation.
if userCancelled() {
return nil, s.ctx.Err()
}
}
m.next()
return m, nil
}
func (s *streamClient) write(m message) {
s.readyMu.Lock()
defer s.readyMu.Unlock()
if s.seq == 0 && !s.readyClosed {
// Close the ready channel
// until the buffer is empty.
close(s.ready)
}
s.seq++ // Keep track of pending messages.
seq := s.seq
next := m.next
m.next = func() {
s.readyMu.Lock()
if s.seq == seq && !s.readyClosed {
// This was the last message, open a blocking
// ready-channel and reset pending status.
s.ready = make(chan struct{})
s.seq = 0
}
s.readyMu.Unlock()
// Prime the next item (if any).
s.mbuf.load()
if next != nil {
next() // Call the prior next func.
}
}
s.mbuf.store(&m)
}
func (s *streamClient) close(err error) error {
s.mu.Lock()
remove := s.remove
s.remove = nil
s.mu.Unlock()
if remove == nil {
return errors.New("rpcc: the stream is already closed")
}
if err == nil {
err = ErrStreamClosing
}
remove() // Unsubscribe to prevent new messages.
s.err = err // Set err before cancel as reads are protected by context.
close(s.done)
// Unblock the ready channel.
s.readyMu.Lock()
s.readyClosed = true
if s.seq == 0 {
close(s.ready)
}
s.readyMu.Unlock()
return nil
}
// Close closes the stream client.
func (s *streamClient) Close() error {
return s.close(nil)
}
type streamWriter interface {
write(message)
}
// streamClients handles multiple streams and allows the
// same message to be sent to one or more streamSender.
type streamClients struct {
mu sync.Mutex
seq uint64
writers map[uint64]streamWriter
}
func newStreamClients() *streamClients {
return &streamClients{
writers: make(map[uint64]streamWriter),
}
}
func (s *streamClients) add(w streamWriter) (seq uint64) {
s.mu.Lock()
seq = s.seq
s.seq++
s.writers[seq] = w
s.mu.Unlock()
return seq
}
func (s *streamClients) remove(seq uint64) {
s.mu.Lock()
delete(s.writers, seq)
s.mu.Unlock()
}
func (s *streamClients) write(method string, args []byte) {
m := message{method: method, data: args}
s.mu.Lock()
for _, w := range s.writers {
w.write(m)
}
s.mu.Unlock()
}