/
subscriptions.go
424 lines (363 loc) · 10.6 KB
/
subscriptions.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package braidhttp
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
"go.uber.org/multierr"
"redwood.dev/errors"
"redwood.dev/log"
"redwood.dev/process"
"redwood.dev/state"
"redwood.dev/swarm/prototree"
"redwood.dev/types"
"redwood.dev/utils"
)
type httpReadableSubscription struct {
stream io.ReadCloser
peer *peerConn
private bool
}
var _ prototree.ReadableSubscription = (*httpReadableSubscription)(nil)
func (s *httpReadableSubscription) Read() (_ prototree.SubscriptionMsg, err error) {
defer func() { s.peer.UpdateConnStats(err == nil) }()
r := bufio.NewReader(s.stream)
bs, err := r.ReadBytes(byte('\n'))
if err != nil {
return prototree.SubscriptionMsg{}, err
}
bs = bytes.TrimPrefix(bs, []byte("data: "))
bs = bytes.Trim(bs, "\n ")
var msg prototree.SubscriptionMsg
err = json.Unmarshal(bs, &msg)
if err != nil {
return prototree.SubscriptionMsg{}, err
}
return msg, nil
}
func (c *httpReadableSubscription) Close() error {
return c.peer.Close()
}
type httpWritableSubscription struct {
process.Process
log.Logger
w http.ResponseWriter
r *http.Request
stateURI string
closeOnce sync.Once
}
var _ prototree.WritableSubscriptionImpl = (*httpWritableSubscription)(nil)
func newHTTPWritableSubscription(
stateURI string,
w http.ResponseWriter,
r *http.Request,
) *httpWritableSubscription {
return &httpWritableSubscription{
Process: *process.New("sub impl (" + TransportName + ") " + stateURI),
Logger: log.NewLogger(TransportName),
stateURI: stateURI,
w: w,
r: r,
}
}
func (sub *httpWritableSubscription) Start() error {
err := sub.Process.Start()
if err != nil {
return err
}
defer sub.Process.Autoclose()
// Set the headers related to event streaming
sub.w.Header().Set("Content-Type", "text/event-stream")
sub.w.Header().Set("Cache-Control", "no-cache")
sub.w.Header().Set("Connection", "keep-alive")
sub.w.Header().Set("Transfer-Encoding", "chunked")
// Listen to the closing of the http connection via the CloseNotifier
notify := sub.w.(http.CloseNotifier).CloseNotify()
sub.Process.Go(nil, "", func(ctx context.Context) {
select {
case <-ctx.Done():
case <-notify:
}
})
sub.w.(http.Flusher).Flush()
return nil
}
func (sub *httpWritableSubscription) Close() (err error) {
sub.Infof(0, "%v writable subscription closed (%v)", TransportName, sub.stateURI)
return sub.Process.Close()
}
func (sub *httpWritableSubscription) Put(ctx context.Context, msg prototree.SubscriptionMsg) (err error) {
bs, err := json.Marshal(msg)
if err != nil {
return err
}
// This is encoded using HTTP's SSE format
event := []byte("data: " + string(bs) + "\n\n")
n, err := sub.w.Write(event)
if err != nil {
return err
} else if n < len(event) {
return errors.New("error writing message to http peer: didn't write enough")
}
sub.w.(http.Flusher).Flush()
return nil
}
func (sub httpWritableSubscription) String() string {
return TransportName + " (" + sub.stateURI + ")"
}
const (
wsWriteWait = 10 * time.Second // Time allowed to write a message to the peer.
wsPongWait = 10 * time.Second // Time allowed to read the next pong message from the peer.
wsPingPeriod = 5 * time.Second // Send pings to peer with this period. Must be less than wsPongWait.
)
var (
newline = []byte{'\n'}
space = []byte{' '}
wsUpgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(*http.Request) bool { return true },
}
)
type wsWritableSubscription struct {
process.Process
log.Logger
wsConn *websocket.Conn
addresses []types.Address
writableSubscriptionOpener writableSubscriptionOpener
stateURIs types.Set[string]
messages *utils.Mailbox[wsMessage]
writeMu sync.Mutex
startOnce sync.Once
closed bool
closeOnce sync.Once
}
type writableSubscriptionOpener interface {
HandleWritableSubscriptionOpened(
req prototree.SubscriptionRequest,
writeSubImplFactory prototree.WritableSubscriptionImplFactory,
) (<-chan struct{}, error)
}
type wsMessage struct {
msgType int
data []byte
}
var _ prototree.WritableSubscriptionImpl = (*wsWritableSubscription)(nil)
func newWSWritableSubscription(
stateURI string,
wsConn *websocket.Conn,
addresses []types.Address,
writableSubscriptionOpener writableSubscriptionOpener,
) *wsWritableSubscription {
return &wsWritableSubscription{
Process: *process.New("sub impl (ws) " + stateURI),
Logger: log.NewLogger(TransportName),
stateURIs: types.NewSet[string]([]string{stateURI}),
wsConn: wsConn,
addresses: addresses,
writableSubscriptionOpener: writableSubscriptionOpener,
messages: utils.NewMailbox[wsMessage](300), // @@TODO: configurable?
}
}
func (sub *wsWritableSubscription) Start() (err error) {
sub.startOnce.Do(func() {
err = sub.Process.Start()
if err != nil {
return
}
defer sub.Process.Autoclose()
// Say hello
sub.write(websocket.PingMessage, nil)
var (
ticker = time.NewTicker(wsPingPeriod)
chWriteClosed = make(chan struct{})
chReadClosed = make(chan struct{})
)
sub.Process.Go(nil, "write", func(ctx context.Context) {
defer close(chWriteClosed)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-chReadClosed:
return
case <-sub.messages.Notify():
err := sub.writePendingMessages(ctx)
if err != nil {
return
}
case <-ticker.C:
sub.messages.Deliver(wsMessage{websocket.PingMessage, nil})
}
}
})
sub.Process.Go(nil, "read", func(ctx context.Context) {
defer close(chReadClosed)
for {
select {
case <-ctx.Done():
return
case <-chWriteClosed:
return
default:
}
msg, err := sub.read()
if err != nil {
sub.Errorf("error reading from websocket: %v", err)
return
}
if msg.msgType == websocket.CloseMessage {
return
} else if msg.msgType == websocket.PingMessage {
sub.messages.Deliver(wsMessage{websocket.PongMessage, nil})
continue
} else if msg.msgType == websocket.PongMessage {
continue
} else if msg.msgType == websocket.BinaryMessage {
sub.Errorf("websocket subscription received unexpected binary message")
continue
}
var addSubMsg struct {
Params struct {
StateURI string `json:"stateURI"`
Keypath state.Keypath `json:"keypath"`
SubscriptionType prototree.SubscriptionType `json:"subscriptionType"`
FromTxID string `json:"fromTxID"`
} `json:"params"`
}
err = json.Unmarshal(msg.data, &addSubMsg)
if err != nil {
sub.Errorf("got bad multiplexed subscription request: %v", err)
continue
}
sub.Infof(0, "incoming websocket subscription (state uri: %v)", addSubMsg.Params.StateURI)
if sub.stateURIs.Contains(addSubMsg.Params.StateURI) {
continue
}
sub.stateURIs.Add(addSubMsg.Params.StateURI)
var fetchHistoryOpts prototree.FetchHistoryOpts
if addSubMsg.Params.FromTxID != "" {
fromTxID, err := state.VersionFromHex(addSubMsg.Params.FromTxID)
if err != nil {
sub.Errorf("could not parse fromTxID: %v", err)
continue
}
fetchHistoryOpts = prototree.FetchHistoryOpts{FromTxID: fromTxID}
}
_, err = sub.writableSubscriptionOpener.HandleWritableSubscriptionOpened(
prototree.SubscriptionRequest{
StateURI: addSubMsg.Params.StateURI,
Keypath: addSubMsg.Params.Keypath,
Type: addSubMsg.Params.SubscriptionType,
FetchHistoryOpts: &fetchHistoryOpts,
Addresses: types.NewSet[types.Address](sub.addresses),
},
func() (prototree.WritableSubscriptionImpl, error) { return sub, nil },
)
if err != nil {
sub.Errorf("bad incoming websocket subscription request: %v", err)
continue
}
}
})
})
return err
}
var (
pingMessage = []byte("ping")
pongMessage = []byte("pong")
)
func (sub *wsWritableSubscription) read() (m wsMessage, err error) {
sub.wsConn.SetReadDeadline(time.Now().Add(wsPongWait))
msgType, bs, err := sub.wsConn.ReadMessage()
if err == io.EOF {
return wsMessage{websocket.CloseMessage, nil}, nil
} else if _, is := err.(*websocket.CloseError); is {
return wsMessage{websocket.CloseMessage, nil}, nil
} else if err != nil {
return wsMessage{}, err
}
switch msgType {
case websocket.PingMessage, websocket.PongMessage, websocket.CloseMessage:
return wsMessage{msgType, bs}, nil
}
bs = bytes.TrimSpace(bs)
if bytes.Equal(bs, pingMessage) {
return wsMessage{websocket.PingMessage, nil}, nil
} else if bytes.Equal(bs, pongMessage) {
return wsMessage{websocket.PongMessage, nil}, nil
} else {
return wsMessage{websocket.TextMessage, bs}, nil
}
}
func (sub *wsWritableSubscription) writePendingMessages(ctx context.Context) error {
for _, msg := range sub.messages.RetrieveAll() {
select {
case <-ctx.Done():
return context.Canceled
default:
}
err := sub.write(msg.msgType, msg.data)
if err != nil {
return err
}
}
return nil
}
func (sub *wsWritableSubscription) write(messageType int, bytes []byte) error {
sub.writeMu.Lock()
defer sub.writeMu.Unlock()
if sub.closed && messageType != websocket.CloseMessage {
return nil
}
sub.wsConn.SetWriteDeadline(time.Now().Add(wsWriteWait))
switch messageType {
case websocket.TextMessage:
bytes = append(bytes, '\n')
case websocket.PingMessage:
messageType = websocket.TextMessage
bytes = []byte("ping\n")
case websocket.PongMessage:
messageType = websocket.TextMessage
bytes = []byte("pong\n")
}
err := sub.wsConn.WriteMessage(messageType, bytes)
if err != nil {
return errors.Wrapf(err, "while writing to websocket client")
}
return nil
}
func (sub *wsWritableSubscription) Close() error {
var err error
sub.closeOnce.Do(func() {
sub.writeMu.Lock()
sub.closed = true
sub.writeMu.Unlock()
sub.Infof(0, "ws writable subscription closed")
_ = sub.write(websocket.CloseMessage, []byte{})
err = multierr.Combine(
sub.wsConn.Close(),
sub.Process.Close(),
)
})
return err
}
func (sub *wsWritableSubscription) Put(ctx context.Context, msg prototree.SubscriptionMsg) (err error) {
bs, err := json.Marshal(msg)
if err != nil {
sub.Errorf("error marshaling message json: %v", err)
return err
}
sub.messages.Deliver(wsMessage{websocket.TextMessage, bs})
return nil
}
func (sub wsWritableSubscription) String() string {
return fmt.Sprintf("websocket %v", sub.stateURIs.Slice())
}