-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconn.go
More file actions
677 lines (603 loc) · 16.3 KB
/
conn.go
File metadata and controls
677 lines (603 loc) · 16.3 KB
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
package zsocket
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
)
// Conn is a server-side WebSocket connection managed by zsocket.
// It exposes Read/Write methods, JSON helpers, and graceful Close.
// Concurrency: one reader goroutine internally; writes are serialized via writeMu.
//
// NOTE: This MVP supports basic fragmentation (accumulate until FIN). Extensions are not implemented.
type Conn struct {
raw net.Conn
br *bufio.Reader
bw *bufio.Writer
cfg Config
subproto string
isClient bool
readLimit int64
compressionMu sync.RWMutex
compressor Compressor
compressionLevel int
writeCompressionEnable bool
deadlineMu sync.RWMutex
readDeadline time.Time
writeDeadline time.Time
// pong keeper
lastPong atomic.Value // time.Time
closed atomic.Bool
handlerMu sync.RWMutex
pingHandler PingHandler
pongHandler PongHandler
closeHandler CloseHandler
// Ensure only one write at a time.
writeMu sync.Mutex
sendOnce sync.Once
sendQ chan queuedMessage
sendQuit chan struct{}
// Allow readers to stop.
closeOnce sync.Once
}
type queuedMessage struct {
ctx context.Context
mt MessageType
data []byte
res chan error
}
// PingHandler handles incoming ping control frames.
type PingHandler func(appData string) error
// PongHandler handles incoming pong control frames.
type PongHandler func(appData string) error
// CloseHandler handles incoming close control frames.
type CloseHandler func(code CloseCode, text string) error
// newConn wraps a hijacked net.Conn into a zsocket Conn with buffers and starts keepalive if configured.
func newConn(c net.Conn, cfg Config, subproto string, isClient bool) (*Conn, error) {
if cfg.ReadBufferSize <= 0 {
cfg.ReadBufferSize = DefaultConfig().ReadBufferSize
}
if cfg.WriteBufferSize <= 0 {
cfg.WriteBufferSize = DefaultConfig().WriteBufferSize
}
if cfg.ReadLimit < 0 {
cfg.ReadLimit = 0
}
z := &Conn{
raw: c,
br: bufio.NewReaderSize(c, cfg.ReadBufferSize),
bw: bufio.NewWriterSize(c, cfg.WriteBufferSize),
cfg: cfg,
subproto: subproto,
isClient: isClient,
readLimit: cfg.ReadLimit,
compressionLevel: func() int {
if cfg.CompressionLevel == 0 {
return DefaultConfig().CompressionLevel
}
return cfg.CompressionLevel
}(),
sendQuit: make(chan struct{}),
}
if cfg.EnableCompression {
d, err := NewDeflate(z.compressionLevel)
if err != nil {
return nil, err
}
z.compressor = d
z.writeCompressionEnable = true
}
z.lastPong.Store(time.Now())
z.pingHandler = func(appData string) error {
return z.writeControlOpcode(opPong, []byte(appData), time.Time{})
}
z.pongHandler = func(string) error {
z.lastPong.Store(time.Now())
return nil
}
z.closeHandler = func(code CloseCode, text string) error {
return z.writeControlOpcode(opClose, closePayload(code, text), time.Time{})
}
// Start keepalive loop if enabled.
if cfg.PingInterval > 0 && cfg.PongWait > 0 {
go z.keepAlive()
}
return z, nil
}
// EnableWriteCompression enables or disables write-side compression.
func (c *Conn) EnableWriteCompression(enable bool) {
c.compressionMu.Lock()
c.writeCompressionEnable = enable
c.compressionMu.Unlock()
}
// SetCompressionLevel changes the compression level for future messages.
func (c *Conn) SetCompressionLevel(level int) error {
c.compressionMu.Lock()
defer c.compressionMu.Unlock()
if !c.cfg.EnableCompression {
return fmt.Errorf("zsocket: compression not negotiated")
}
d, err := NewDeflate(level)
if err != nil {
return err
}
c.compressor = d
c.compressionLevel = level
return nil
}
// keepAlive periodically sends ping frames and checks for timely pongs.
// If a pong is not received within PongWait, the connection is closed.
func (c *Conn) keepAlive() {
ticker := time.NewTicker(c.cfg.PingInterval)
defer ticker.Stop()
for {
if c.closed.Load() {
return
}
select {
case <-ticker.C:
_ = c.writeControlOpcode(opPing, nil, time.Time{}) // best-effort; ignore error
// check pong freshness
last := c.lastPong.Load().(time.Time)
if time.Since(last) > c.cfg.PongWait {
_ = c.Close(CloseGoingAway, "pong timeout")
return
}
}
}
}
// Subprotocol returns the negotiated subprotocol, if any.
func (c *Conn) Subprotocol() string { return c.subproto }
// RemoteAddr returns the peer network address.
func (c *Conn) RemoteAddr() net.Addr { return c.raw.RemoteAddr() }
// LocalAddr returns the local network address.
func (c *Conn) LocalAddr() net.Addr { return c.raw.LocalAddr() }
// NetConn returns the underlying net.Conn.
func (c *Conn) NetConn() net.Conn { return c.raw }
// UnderlyingConn is an alias for NetConn.
func (c *Conn) UnderlyingConn() net.Conn { return c.raw }
// SetReadLimit sets the maximum message payload size in bytes. 0 means unlimited.
func (c *Conn) SetReadLimit(limit int64) {
if limit < 0 {
limit = 0
}
c.readLimit = limit
}
// SetReadDeadline sets the deadline for future reads.
func (c *Conn) SetReadDeadline(t time.Time) error {
c.deadlineMu.Lock()
c.readDeadline = t
c.deadlineMu.Unlock()
return c.raw.SetReadDeadline(t)
}
// SetWriteDeadline sets the deadline for future writes.
func (c *Conn) SetWriteDeadline(t time.Time) error {
c.deadlineMu.Lock()
c.writeDeadline = t
c.deadlineMu.Unlock()
return c.raw.SetWriteDeadline(t)
}
// PingHandler returns the current ping handler.
func (c *Conn) PingHandler() PingHandler {
c.handlerMu.RLock()
h := c.pingHandler
c.handlerMu.RUnlock()
return h
}
// SetPingHandler sets a custom ping handler. Nil resets the default behavior.
func (c *Conn) SetPingHandler(h PingHandler) {
if h == nil {
h = func(appData string) error {
return c.writeControlOpcode(opPong, []byte(appData), time.Time{})
}
}
c.handlerMu.Lock()
c.pingHandler = h
c.handlerMu.Unlock()
}
// PongHandler returns the current pong handler.
func (c *Conn) PongHandler() PongHandler {
c.handlerMu.RLock()
h := c.pongHandler
c.handlerMu.RUnlock()
return h
}
// SetPongHandler sets a custom pong handler. Nil resets the default behavior.
func (c *Conn) SetPongHandler(h PongHandler) {
if h == nil {
h = func(string) error {
c.lastPong.Store(time.Now())
return nil
}
}
c.handlerMu.Lock()
c.pongHandler = h
c.handlerMu.Unlock()
}
// CloseHandler returns the current close handler.
func (c *Conn) CloseHandler() CloseHandler {
c.handlerMu.RLock()
h := c.closeHandler
c.handlerMu.RUnlock()
return h
}
// SetCloseHandler sets a custom close handler. Nil resets the default behavior.
func (c *Conn) SetCloseHandler(h CloseHandler) {
if h == nil {
h = func(code CloseCode, text string) error {
return c.writeControlOpcode(opClose, closePayload(code, text), time.Time{})
}
}
c.handlerMu.Lock()
c.closeHandler = h
c.handlerMu.Unlock()
}
// Close sends a close frame (best-effort) and closes the connection.
func (c *Conn) Close(code CloseCode, reason string) error {
var err error
c.closeOnce.Do(func() {
c.closed.Store(true)
close(c.sendQuit)
// Send close control frame (best-effort).
_ = c.writeControlOpcode(opClose, closePayload(code, reason), time.Time{})
err = c.raw.Close()
})
return err
}
// EnableSendQueue configures async write queue with backpressure.
func (c *Conn) EnableSendQueue(size int) {
if size <= 0 {
size = 64
}
c.sendOnce.Do(func() {
c.sendQ = make(chan queuedMessage, size)
go c.sendLoop()
})
}
// Send enqueues a message if queue enabled, otherwise writes directly.
func (c *Conn) Send(ctx context.Context, mt MessageType, data []byte) error {
if c.sendQ == nil {
return c.Write(ctx, mt, data)
}
msg := queuedMessage{ctx: ctx, mt: mt, data: append([]byte(nil), data...), res: make(chan error, 1)}
select {
case <-c.sendQuit:
return ErrCloseSent
case <-ctx.Done():
return ctx.Err()
case c.sendQ <- msg:
}
select {
case <-c.sendQuit:
return ErrCloseSent
case <-ctx.Done():
return ctx.Err()
case err := <-msg.res:
return err
}
}
func (c *Conn) sendLoop() {
for {
select {
case <-c.sendQuit:
return
case msg := <-c.sendQ:
msg.res <- c.Write(msg.ctx, msg.mt, msg.data)
}
}
}
// Read reads the next complete message, returning its type and payload.
// It accumulates fragments until FIN=1. Control frames are handled internally.
func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error) {
// Context deadline/timeout support on the underlying conn.
if deadline, ok := ctx.Deadline(); ok {
_ = c.raw.SetReadDeadline(deadline)
defer c.restoreReadDeadline()
} else if d := c.getReadDeadline(); !d.IsZero() {
_ = c.raw.SetReadDeadline(d)
}
var (
msgOpcode byte
full bytes.Buffer
started bool
compressed bool
)
for {
fin, rsv1, opcode, payload, err := readFrame(c.br, c.readLimit, !c.isClient, c.cfg.EnableCompression)
if err != nil {
return 0, nil, err
}
switch opcode {
case opText, opBinary:
if started {
return 0, nil, errFragmentState
}
if rsv1 && !c.cfg.EnableCompression {
return 0, nil, errRSVNonZero
}
compressed = rsv1
msgOpcode = opcode
full.Write(payload)
started = true
if fin {
b := full.Bytes()
if compressed {
b, err = c.decompressData(b)
if err != nil {
return 0, nil, err
}
}
return toMsgType(msgOpcode), b, nil
}
case opContinuation:
if !started {
return 0, nil, errUnexpectedOpcode
}
if rsv1 {
return 0, nil, errRSVNonZero
}
full.Write(payload)
if fin {
b := full.Bytes()
if compressed {
b, err = c.decompressData(b)
if err != nil {
return 0, nil, err
}
}
return toMsgType(msgOpcode), b, nil
}
case opPing:
if err := c.PingHandler()(string(payload)); err != nil {
return 0, nil, err
}
case opPong:
if err := c.PongHandler()(string(payload)); err != nil {
return 0, nil, err
}
case opClose:
code, reason := parseClosePayload(payload)
if err := c.CloseHandler()(code, reason); err != nil {
return 0, nil, err
}
return 0, nil, CloseError{Code: code, Text: reason, Reason: reason}
default:
// Protocol error → close
_ = c.Close(CloseProtocolError, "unsupported opcode")
return 0, nil, fmt.Errorf("zsocket: unsupported opcode %d", opcode)
}
}
}
// Write sends a complete message (text or binary) as a single unfragmented frame.
func (c *Conn) Write(ctx context.Context, mt MessageType, data []byte) error {
if c.closed.Load() {
return ErrCloseSent
}
if mt != TextMessage && mt != BinaryMessage {
return fmt.Errorf("zsocket: invalid message type %d", mt)
}
// Apply write deadline if ctx has one or from config.
if deadline, ok := ctx.Deadline(); ok {
_ = c.raw.SetWriteDeadline(deadline)
defer c.restoreWriteDeadline()
} else if d := c.getWriteDeadline(); !d.IsZero() {
_ = c.raw.SetWriteDeadline(d)
} else if c.cfg.WriteTimeout > 0 {
_ = c.raw.SetWriteDeadline(time.Now().Add(c.cfg.WriteTimeout))
defer c.restoreWriteDeadline()
}
c.writeMu.Lock()
defer c.writeMu.Unlock()
var opcode byte
rsv1 := false
payload := data
if mt == TextMessage {
opcode = opText
} else {
opcode = opBinary
}
if c.shouldCompressWrite() {
var err error
payload, err = c.compressData(data)
if err != nil {
return err
}
rsv1 = true
}
if c.cfg.WriteBufferPool != nil {
if pv := c.cfg.WriteBufferPool.Get(); pv != nil {
if p, ok := pv.(*[]byte); ok && p != nil {
buf := (*p)[:0]
buf = append(buf, payload...)
payload = buf
defer func() {
*p = buf
c.cfg.WriteBufferPool.Put(p)
}()
}
}
}
if err := writeFrame(c.bw, true, opcode, payload, c.isClient, rsv1); err != nil {
return err
}
return c.bw.Flush()
}
// WritePreparedMessage writes a prebuilt message efficiently.
func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error {
if pm == nil {
return fmt.Errorf("zsocket: nil prepared message")
}
return c.Write(context.Background(), pm.messageType, pm.data)
}
// ReadMessage reads next data message.
func (c *Conn) ReadMessage() (MessageType, []byte, error) {
return c.Read(context.Background())
}
// WriteMessage writes one data message.
func (c *Conn) WriteMessage(mt MessageType, data []byte) error {
return c.Write(context.Background(), mt, data)
}
// WriteJSON marshals v to JSON and writes as a text message.
func (c *Conn) WriteJSON(ctx context.Context, v any) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
return c.Write(ctx, TextMessage, b)
}
// ReadJSON reads next message and unmarshals JSON into v.
// It accepts both text and binary frames. If binary, it still tries to decode JSON.
func (c *Conn) ReadJSON(ctx context.Context, v any) error {
mt, b, err := c.Read(ctx)
if err != nil {
return err
}
if mt != TextMessage && mt != BinaryMessage {
return fmt.Errorf("zsocket: unexpected message type %d", mt)
}
return json.Unmarshal(b, v)
}
// WriteControl writes a control frame using message type and deadline.
func (c *Conn) WriteControl(mt MessageType, payload []byte, deadline time.Time) error {
var opcode byte
switch mt {
case CloseMessage:
opcode = opClose
case PingMessage:
opcode = opPing
case PongMessage:
opcode = opPong
default:
return fmt.Errorf("zsocket: invalid control message type %d", mt)
}
return c.writeControlOpcode(opcode, payload, deadline)
}
func (c *Conn) writeControlOpcode(opcode byte, payload []byte, deadline time.Time) error {
if c.closed.Load() {
return ErrCloseSent
}
if !deadline.IsZero() {
_ = c.raw.SetWriteDeadline(deadline)
defer c.restoreWriteDeadline()
} else if d := c.getWriteDeadline(); !d.IsZero() {
_ = c.raw.SetWriteDeadline(d)
}
c.writeMu.Lock()
defer c.writeMu.Unlock()
if err := writeFrame(c.bw, true, opcode, payload, c.isClient, false); err != nil {
return err
}
return c.bw.Flush()
}
func (c *Conn) shouldCompressWrite() bool {
c.compressionMu.RLock()
enabled := c.cfg.EnableCompression && c.writeCompressionEnable && c.compressor != nil
c.compressionMu.RUnlock()
return enabled
}
func (c *Conn) compressData(data []byte) ([]byte, error) {
c.compressionMu.RLock()
cmp := c.compressor
c.compressionMu.RUnlock()
if cmp == nil {
return data, nil
}
return cmp.Compress(data)
}
func (c *Conn) decompressData(data []byte) ([]byte, error) {
c.compressionMu.RLock()
cmp := c.compressor
c.compressionMu.RUnlock()
if cmp == nil {
return nil, fmt.Errorf("zsocket: compression not available")
}
return cmp.Decompress(data)
}
// NextReader returns the next complete message payload as an io.Reader.
func (c *Conn) NextReader() (MessageType, io.Reader, error) {
mt, b, err := c.Read(context.Background())
if err != nil {
return 0, nil, err
}
return mt, bytes.NewReader(b), nil
}
// NextWriter returns a writer for the next message.
func (c *Conn) NextWriter(mt MessageType) (io.WriteCloser, error) {
if mt != TextMessage && mt != BinaryMessage {
return nil, fmt.Errorf("zsocket: invalid message type %d", mt)
}
if c.closed.Load() {
return nil, ErrCloseSent
}
return &connWriter{conn: c, mt: mt}, nil
}
type connWriter struct {
conn *Conn
mt MessageType
buf bytes.Buffer
closed bool
}
func (w *connWriter) Write(p []byte) (int, error) {
if w.closed {
return 0, ErrCloseSent
}
return w.buf.Write(p)
}
func (w *connWriter) Close() error {
if w.closed {
return nil
}
w.closed = true
return w.conn.Write(context.Background(), w.mt, w.buf.Bytes())
}
func (c *Conn) getReadDeadline() time.Time {
c.deadlineMu.RLock()
d := c.readDeadline
c.deadlineMu.RUnlock()
return d
}
func (c *Conn) getWriteDeadline() time.Time {
c.deadlineMu.RLock()
d := c.writeDeadline
c.deadlineMu.RUnlock()
return d
}
func (c *Conn) restoreReadDeadline() {
_ = c.raw.SetReadDeadline(c.getReadDeadline())
}
func (c *Conn) restoreWriteDeadline() {
_ = c.raw.SetWriteDeadline(c.getWriteDeadline())
}
func toMsgType(opcode byte) MessageType {
if opcode == opText {
return TextMessage
}
return BinaryMessage
}
// closePayload builds a close frame payload (2-byte code + optional UTF-8 reason).
func closePayload(code CloseCode, reason string) []byte {
if code == 0 {
return nil
}
// 2 bytes code + reason
buf := make([]byte, 2+len(reason))
binary.BigEndian.PutUint16(buf[:2], uint16(code))
copy(buf[2:], []byte(reason))
return buf
}
// parseClosePayload extracts code & reason from a close frame payload.
func parseClosePayload(p []byte) (CloseCode, string) {
if len(p) < 2 {
return CloseNoStatusRcvd, ""
}
code := CloseCode(binary.BigEndian.Uint16(p[:2]))
reason := string(p[2:])
return code, reason
}