-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.go
338 lines (267 loc) · 6.4 KB
/
connection.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
package omnistreams
import (
"context"
"errors"
"log"
"sync"
)
type Transport interface {
Read(context.Context) ([]byte, error)
Write(context.Context, []byte) error
}
type Connection struct {
nextStreamId uint32
streams map[uint32]*Stream
streamCh chan *Stream
mut *sync.Mutex
transport Transport
recvWindowUpdateCh chan windowUpdateEvent
eventCh chan Event
wg *sync.WaitGroup
}
type Event interface{}
type StreamCreatedEvent struct{}
type StreamDeletedEvent struct{}
type DebugEvent int
func NewConnection(transport Transport, isClient bool) *Connection {
streams := make(map[uint32]*Stream)
mut := &sync.Mutex{}
streamCh := make(chan *Stream)
// TODO: Once we break compatibility with muxado, maybe switch this to
// match WebTransport, which uses even numbered stream IDs for clients
var nextStreamId uint32 = 2
if isClient {
nextStreamId = 1
}
recvWindowUpdateCh := make(chan windowUpdateEvent)
c := &Connection{
nextStreamId: nextStreamId,
streams: streams,
streamCh: streamCh,
mut: mut,
transport: transport,
recvWindowUpdateCh: recvWindowUpdateCh,
wg: &sync.WaitGroup{},
}
go func() {
ctx := context.Background()
for {
msgBytes, err := transport.Read(ctx)
if err != nil {
log.Println("Error transport.Read", err)
break
}
//if msgType != websocket.MessageBinary {
// fmt.Println("Invalid message type")
// break
//}
frame, err := unpackFrame(msgBytes)
if err != nil {
log.Println("Error unpackFrame", err)
break
}
c.handleFrame(frame)
}
// TODO: not sure why this lock is here. Seems dangerous
mut.Lock()
defer mut.Unlock()
for _, stream := range c.streams {
err := stream.Close()
if err != nil {
log.Println(err)
}
}
close(c.streamCh)
if c.eventCh != nil {
close(c.eventCh)
}
c.eventCh = nil
go func() {
// Wait until all streams are done to close this channel
c.wg.Wait()
close(recvWindowUpdateCh)
}()
}()
go func() {
for evt := range recvWindowUpdateCh {
err := c.sendFrame(&frame{
frameType: FrameTypeWindowIncrease,
streamId: evt.streamId,
windowIncrease: evt.windowUpdate,
})
if err != nil {
log.Println(err)
}
}
}()
return c
}
func (c *Connection) Events() chan Event {
eventCh := make(chan Event, 1)
c.eventCh = eventCh
return eventCh
}
func (c *Connection) AcceptStream() (*Stream, error) {
strm, ok := <-c.streamCh
if !ok {
return nil, errors.New("Connection closed")
}
return strm, nil
}
func (c *Connection) OpenStream() (*Stream, error) {
c.mut.Lock()
streamId := c.nextStreamId
c.nextStreamId += 2
c.mut.Unlock()
stream := c.newStream(streamId, true)
return stream, nil
}
func (c *Connection) sendFrame(frame *frame) error {
//c.mut.Lock()
//fmt.Println("Send frame")
//fmt.Println(frame)
//c.mut.Unlock()
packedFrame := packFrame(frame)
err := c.transport.Write(context.Background(), packedFrame)
if err != nil {
return err
}
return nil
}
func (c *Connection) handleFrame(f *frame) {
//c.mut.Lock()
//fmt.Println("Receive frame")
//fmt.Printf("%+v\n", f)
//c.mut.Unlock()
c.mut.Lock()
stream, streamExists := c.streams[f.streamId]
c.mut.Unlock()
switch f.frameType {
case FrameTypeMessage:
fallthrough
case FrameTypeData:
if !streamExists {
// If syn isn't set this is likely a packet for a recently RST stream; ignore the frame
// TODO: might want to have more advanced logic. Maybe keeping streams unavailable for
// a while so we can specifically detect send on RST stream conditions
if !f.syn {
break
}
stream = c.newStream(f.streamId, false)
//Dash.Set("stream-queue-len", 1)
c.streamCh <- stream
}
stream.recvCh <- f.data
if f.fin {
close(stream.recvCh)
close(stream.remoteCloseCh)
// TODO: make sure streams aren't leaking. Removed this because it was preventing
// window increases from being received on half-closed streams
//delete(c.streams, f.streamId)
}
case FrameTypeWindowIncrease:
if !streamExists {
log.Println("FrameTypeWindowIncrease: no such stream", f.streamId)
} else {
stream.updateWindow(f.windowIncrease)
}
case FrameTypeReset:
log.Println("FrameTypeReset:", f.errorCode)
if !streamExists {
log.Println("FrameTypeReset: no such stream", f.streamId)
} else {
// TODO: this might be leaking now
//c.mut.Lock()
//delete(c.streams, f.streamId)
//c.mut.Unlock()
err := stream.Close()
if err != nil {
log.Println("FrameTypeReset:", err)
}
}
case FrameTypeGoAway:
log.Println("FrameTypeGoAway:", f.errorCode)
close(c.streamCh)
// TODO: clean up all streams
default:
log.Println("Frame type not implemented:", f.frameType)
}
}
func (c *Connection) newStream(streamId uint32, syn bool) *Stream {
c.wg.Add(1)
sendCh := make(chan []byte)
stream := NewStream(streamId, sendCh, c.recvWindowUpdateCh)
readClosed := false
writeClosed := false
checkClosed := func() {
if readClosed && writeClosed {
c.mut.Lock()
delete(c.streams, streamId)
c.mut.Unlock()
c.wg.Done()
if c.eventCh != nil {
c.eventCh <- &StreamDeletedEvent{}
}
}
}
// TODO: I think these goroutines can be combined somewhat. Also need
// to make sure they don't leak
go func() {
LOOP:
for {
select {
case msg := <-sendCh:
frm := &frame{
frameType: FrameTypeData,
streamId: streamId,
syn: syn,
data: msg,
}
if syn {
syn = false
}
err := c.sendFrame(frm)
if err != nil {
log.Println("<-sendCh:", err)
break LOOP
}
case <-stream.closeWriteCh:
err := c.sendFrame(&frame{
frameType: FrameTypeData,
streamId: streamId,
syn: false,
fin: true,
})
if err != nil {
log.Println("<-stream.closeWriteCh:", err)
}
writeClosed = true
checkClosed()
break LOOP
}
}
}()
go func() {
select {
case <-stream.remoteCloseCh:
case <-stream.closeReadCh:
err := c.sendFrame(&frame{
frameType: FrameTypeReset,
streamId: streamId,
errorCode: 42,
})
if err != nil {
log.Println("<-stream.closeReadCh:", err)
}
}
readClosed = true
checkClosed()
}()
c.mut.Lock()
c.streams[streamId] = stream
c.mut.Unlock()
if c.eventCh != nil {
c.eventCh <- &StreamCreatedEvent{}
}
return stream
}