-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnode.go
More file actions
936 lines (828 loc) · 21.1 KB
/
Copy pathnode.go
File metadata and controls
936 lines (828 loc) · 21.1 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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
// Copyright (C) 2025, Lux Industries Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package zap
import (
"context"
"crypto/tls"
"encoding/binary"
"errors"
"fmt"
"io"
"log/slog"
"net"
"sync"
"time"
"github.com/luxfi/mdns"
)
// Node is a ZAP node that combines mDNS discovery with zero-copy RPC.
type Node struct {
nodeID string
serviceType string
port int
noDiscovery bool
tlsCfg *tls.Config // nil = plaintext
// Discovery
discovery *mdns.Discovery
// Network
listener net.Listener
conns map[string]*Conn
connsMu sync.RWMutex
// Handlers
handlers map[uint16]Handler
handlersMu sync.RWMutex
// Lifecycle
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
logger *slog.Logger
}
// Conn is a ZAP connection to a peer.
type Conn struct {
NodeID string
Addr string
conn net.Conn
mu sync.Mutex
// Request/response correlation
reqID uint32
reqIDMu sync.Mutex
pending map[uint32]chan *Message
pendMu sync.Mutex
}
// Handler handles incoming ZAP messages.
type Handler func(ctx context.Context, from string, msg *Message) (*Message, error)
// NodeConfig configures a ZAP node.
type NodeConfig struct {
NodeID string
ServiceType string // e.g., "_luxd._tcp", "_fhed._tcp"
Port int
Metadata map[string]string
Logger *slog.Logger
NoDiscovery bool // Disable mDNS discovery (use ConnectDirect only)
TLS *tls.Config // optional PQ-TLS 1.3; nil = plaintext
}
// NewNode creates a new ZAP node.
func NewNode(cfg NodeConfig) *Node {
if cfg.Logger == nil {
cfg.Logger = slog.Default()
}
ctx, cancel := context.WithCancel(context.Background())
return &Node{
nodeID: cfg.NodeID,
serviceType: cfg.ServiceType,
port: cfg.Port,
noDiscovery: cfg.NoDiscovery,
tlsCfg: cfg.TLS,
conns: make(map[string]*Conn),
handlers: make(map[uint16]Handler),
ctx: ctx,
cancel: cancel,
logger: cfg.Logger,
}
}
// Start starts the node (discovery + listener).
func (n *Node) Start() error {
// Start TCP listener
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", n.port))
if err != nil {
return fmt.Errorf("failed to listen: %w", err)
}
if n.tlsCfg != nil {
ln = tls.NewListener(ln, n.tlsCfg)
}
n.listener = ln
// Accept connections
n.wg.Add(1)
go n.acceptLoop()
// Start mDNS discovery (unless disabled)
if !n.noDiscovery {
n.discovery = mdns.New(n.serviceType, n.nodeID, n.port,
mdns.WithLogger(n.logger),
)
n.discovery.OnPeer(n.handlePeerEvent)
if err := n.discovery.Start(); err != nil {
n.listener.Close()
return fmt.Errorf("failed to start discovery: %w", err)
}
}
n.logger.Info("ZAP node started",
"nodeID", n.nodeID,
"service", n.serviceType,
"port", n.port,
)
return nil
}
// Stop stops the node.
func (n *Node) Stop() {
n.cancel()
if n.discovery != nil {
n.discovery.Stop()
}
if n.listener != nil {
n.listener.Close()
}
// Close all connections
n.connsMu.Lock()
for _, conn := range n.conns {
conn.conn.Close()
}
n.conns = make(map[string]*Conn)
n.connsMu.Unlock()
n.wg.Wait()
n.logger.Info("ZAP node stopped", "nodeID", n.nodeID)
}
// Handle registers a handler for a message type.
func (n *Node) Handle(msgType uint16, handler Handler) {
n.handlersMu.Lock()
n.handlers[msgType] = handler
n.handlersMu.Unlock()
}
// Send sends a ZAP message to a peer.
func (n *Node) Send(ctx context.Context, peerID string, msg *Message) error {
conn, err := n.getOrConnect(peerID)
if err != nil {
return err
}
return conn.Send(msg)
}
// Reserved header fields for request/response correlation
// These are the first 8 bytes of every Call message
const (
FieldReqID = 0 // uint32 - request ID for correlation
FieldReqFlag = 4 // uint32 - 1=request, 2=response
ReqFlagReq = 1
ReqFlagResp = 2
)
// Call sends a request and waits for a response.
func (n *Node) Call(ctx context.Context, peerID string, msg *Message) (*Message, error) {
conn, err := n.getOrConnect(peerID)
if err != nil {
return nil, err
}
// Initialize pending map if needed
conn.pendMu.Lock()
if conn.pending == nil {
conn.pending = make(map[uint32]chan *Message)
}
conn.pendMu.Unlock()
// Get next request ID
conn.reqIDMu.Lock()
conn.reqID++
reqID := conn.reqID
conn.reqIDMu.Unlock()
// Create response channel
respCh := make(chan *Message, 1)
conn.pendMu.Lock()
conn.pending[reqID] = respCh
conn.pendMu.Unlock()
defer func() {
conn.pendMu.Lock()
delete(conn.pending, reqID)
conn.pendMu.Unlock()
}()
// Wrap message with request ID header
// We inject the reqID into the first 8 bytes
origBytes := msg.Bytes()
wrappedBytes := make([]byte, len(origBytes)+8)
binary.LittleEndian.PutUint32(wrappedBytes[0:4], reqID)
binary.LittleEndian.PutUint32(wrappedBytes[4:8], ReqFlagReq)
copy(wrappedBytes[8:], origBytes)
// Send wrapped request
conn.mu.Lock()
err = writeMessage(conn.conn, wrappedBytes)
conn.mu.Unlock()
if err != nil {
return nil, err
}
// Wait for response
select {
case resp := <-respCh:
return resp, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// Broadcast sends a message to all connected peers.
func (n *Node) Broadcast(ctx context.Context, msg *Message) map[string]error {
n.connsMu.RLock()
peers := make([]string, 0, len(n.conns))
for id := range n.conns {
peers = append(peers, id)
}
n.connsMu.RUnlock()
results := make(map[string]error)
var mu sync.Mutex
var wg sync.WaitGroup
for _, peerID := range peers {
wg.Add(1)
go func(id string) {
defer wg.Done()
err := n.Send(ctx, id, msg)
mu.Lock()
results[id] = err
mu.Unlock()
}(peerID)
}
wg.Wait()
return results
}
// Peers returns connected peer IDs.
func (n *Node) Peers() []string {
n.connsMu.RLock()
defer n.connsMu.RUnlock()
peers := make([]string, 0, len(n.conns))
for id := range n.conns {
peers = append(peers, id)
}
return peers
}
// NodeID returns this node's ID.
func (n *Node) NodeID() string {
return n.nodeID
}
func (n *Node) acceptLoop() {
defer n.wg.Done()
for {
conn, err := n.listener.Accept()
if err != nil {
select {
case <-n.ctx.Done():
return
default:
n.logger.Error("Accept error", "error", err)
continue
}
}
n.wg.Add(1)
go n.handleConn(conn)
}
}
func (n *Node) handleConn(netConn net.Conn) {
defer n.wg.Done()
defer netConn.Close()
// Set initial read deadline for handshake
netConn.SetReadDeadline(time.Now().Add(10 * time.Second))
// Read handshake to get peer ID (simple: 64-byte node ID as bytes)
var peerID string
{
msg, err := readMessage(netConn)
if err != nil {
n.logger.Debug("Handshake read error", "error", err)
return
}
// Node ID is stored as raw bytes at offset 0, length at offset 60
root := msg.Root()
idLen := root.Uint32(60)
if idLen > 0 && idLen <= 60 {
idBytes := make([]byte, idLen)
for i := uint32(0); i < idLen; i++ {
idBytes[i] = root.Uint8(int(i))
}
peerID = string(idBytes)
}
}
// Check for duplicate BEFORE sending handshake response
// This way the outgoing side will get EOF and know we rejected
n.connsMu.Lock()
if existing, ok := n.conns[peerID]; ok {
n.connsMu.Unlock()
n.logger.Debug("Duplicate connection rejected", "peerID", peerID, "existing", existing.Addr)
return // Don't send handshake - outgoing side will get EOF
}
n.connsMu.Unlock()
// Send our handshake
{
b := NewBuilder(128)
obj := b.StartObject(64)
// Write node ID as raw bytes
idBytes := []byte(n.nodeID)
for i, c := range idBytes {
if i >= 60 {
break
}
obj.SetUint8(i, c)
}
obj.SetUint32(60, uint32(len(idBytes)))
obj.FinishAsRoot()
if err := writeMessage(netConn, b.Finish()); err != nil {
return
}
}
// Re-check after handshake (another connection might have been established while we were sending)
n.connsMu.Lock()
if existing, ok := n.conns[peerID]; ok {
n.connsMu.Unlock()
n.logger.Debug("Duplicate connection rejected (race)", "peerID", peerID, "existing", existing.Addr)
return
}
conn := &Conn{
NodeID: peerID,
Addr: netConn.RemoteAddr().String(),
conn: netConn,
pending: make(map[uint32]chan *Message),
}
n.conns[peerID] = conn
n.connsMu.Unlock()
n.logger.Info("Peer connected", "peerID", peerID, "addr", conn.Addr)
defer func() {
n.connsMu.Lock()
// Only delete if this is still our connection (avoid deleting a newer connection)
if cur, ok := n.conns[peerID]; ok && cur == conn {
delete(n.conns, peerID)
}
n.connsMu.Unlock()
n.logger.Info("Peer disconnected", "peerID", peerID)
}()
// Handle messages
for {
select {
case <-n.ctx.Done():
return
default:
}
// Set read deadline so we can check for context cancellation
netConn.SetReadDeadline(time.Now().Add(1 * time.Second))
data, err := readMessageRaw(netConn)
if err != nil {
if errors.Is(err, io.EOF) {
return
}
// Check if it's a timeout - that's ok, just continue
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
continue
}
n.logger.Debug("Read error", "peerID", peerID, "error", err)
return
}
// Check if this is a Call request/response (has 8-byte header)
if len(data) >= 8 {
reqFlag := binary.LittleEndian.Uint32(data[4:8])
if reqFlag == ReqFlagResp {
// Response to a pending Call - route to waiting goroutine
reqID := binary.LittleEndian.Uint32(data[0:4])
msg, err := Parse(data[8:])
if err == nil {
conn.pendMu.Lock()
if ch, ok := conn.pending[reqID]; ok {
select {
case ch <- msg:
default:
}
}
conn.pendMu.Unlock()
}
continue
} else if reqFlag == ReqFlagReq {
// Incoming Call request - handle and send response
reqID := binary.LittleEndian.Uint32(data[0:4])
msg, err := Parse(data[8:])
if err != nil {
continue
}
msgType := msg.Flags() >> 8
n.handlersMu.RLock()
handler, ok := n.handlers[msgType]
n.handlersMu.RUnlock()
if ok {
resp, err := handler(n.ctx, peerID, msg)
if err != nil {
n.logger.Error("Handler error", "peerID", peerID, "msgType", msgType, "error", err)
continue
}
if resp != nil {
// Send response with correlation header
respBytes := resp.Bytes()
wrappedResp := make([]byte, len(respBytes)+8)
binary.LittleEndian.PutUint32(wrappedResp[0:4], reqID)
binary.LittleEndian.PutUint32(wrappedResp[4:8], ReqFlagResp)
copy(wrappedResp[8:], respBytes)
conn.mu.Lock()
writeErr := writeMessage(netConn, wrappedResp)
conn.mu.Unlock()
if writeErr != nil {
n.logger.Debug("Write error", "peerID", peerID, "error", writeErr)
return
}
}
}
continue
}
}
// Regular message (no correlation header) - use standard handler
msg, err := Parse(data)
if err != nil {
continue
}
// Get message type from flags (upper 8 bits)
msgType := msg.Flags() >> 8
n.handlersMu.RLock()
handler, ok := n.handlers[msgType]
n.handlersMu.RUnlock()
if ok {
resp, err := handler(n.ctx, peerID, msg)
if err != nil {
n.logger.Error("Handler error", "peerID", peerID, "msgType", msgType, "error", err)
continue
}
if resp != nil {
conn.mu.Lock()
writeErr := writeMessage(netConn, resp.Bytes())
conn.mu.Unlock()
if writeErr != nil {
n.logger.Debug("Write error", "peerID", peerID, "error", writeErr)
return
}
}
}
}
}
func (n *Node) handlePeerEvent(peer *mdns.Peer, joined bool) {
if joined {
n.logger.Info("Peer discovered", "peerID", peer.NodeID, "addr", peer.Address())
// Deterministic connection rule: LOWER node ID always initiates
// This prevents races when both sides try to connect simultaneously
if n.nodeID < peer.NodeID {
addr := peer.Address()
go func() {
// Use ConnectDirect with the discovered address
if err := n.ConnectDirect(addr); err != nil {
n.logger.Debug("Failed to connect to discovered peer",
"peerID", peer.NodeID, "addr", addr, "error", err)
}
}()
}
// If our ID is higher, we wait for them to connect to us
} else {
n.logger.Info("Peer lost", "peerID", peer.NodeID)
n.connsMu.Lock()
if conn, ok := n.conns[peer.NodeID]; ok {
conn.conn.Close()
delete(n.conns, peer.NodeID)
}
n.connsMu.Unlock()
}
}
func (n *Node) getOrConnect(peerID string) (*Conn, error) {
n.connsMu.RLock()
conn, ok := n.conns[peerID]
n.connsMu.RUnlock()
if ok {
return conn, nil
}
// Look up peer via discovery
peers := n.discovery.Peers()
var peer *mdns.Peer
for _, p := range peers {
if p.NodeID == peerID {
peer = p
break
}
}
if peer == nil {
return nil, fmt.Errorf("peer not found: %s", peerID)
}
// Connect
addr := peer.Address()
netConn, err := net.DialTimeout("tcp", addr, 5*time.Second)
if err != nil {
return nil, fmt.Errorf("failed to connect to %s: %w", addr, err)
}
if n.tlsCfg != nil {
netConn = tls.Client(netConn, n.tlsCfg)
}
// Send handshake (node ID as raw bytes)
{
b := NewBuilder(128)
obj := b.StartObject(64)
idBytes := []byte(n.nodeID)
for i, c := range idBytes {
if i >= 60 {
break
}
obj.SetUint8(i, c)
}
obj.SetUint32(60, uint32(len(idBytes)))
obj.FinishAsRoot()
if err := writeMessage(netConn, b.Finish()); err != nil {
netConn.Close()
return nil, err
}
}
// Read handshake response
{
msg, err := readMessage(netConn)
if err != nil {
netConn.Close()
return nil, err
}
root := msg.Root()
idLen := root.Uint32(60)
var remotePeerID string
if idLen > 0 && idLen <= 60 {
idBytes := make([]byte, idLen)
for i := uint32(0); i < idLen; i++ {
idBytes[i] = root.Uint8(int(i))
}
remotePeerID = string(idBytes)
}
if remotePeerID != peerID {
netConn.Close()
return nil, fmt.Errorf("peer ID mismatch: expected %s, got %s", peerID, remotePeerID)
}
}
conn = &Conn{
NodeID: peerID,
Addr: addr,
conn: netConn,
pending: make(map[uint32]chan *Message),
}
// Check if we already have a connection (race with incoming connection)
n.connsMu.Lock()
if existing, ok := n.conns[peerID]; ok {
n.connsMu.Unlock()
netConn.Close()
return existing, nil // Use existing connection
}
n.conns[peerID] = conn
n.connsMu.Unlock()
n.logger.Info("Connected to peer", "peerID", peerID, "addr", addr)
// Start receive loop
n.wg.Add(1)
go func() {
defer n.wg.Done()
defer func() {
n.connsMu.Lock()
// Only delete if this is still our connection
if cur, ok := n.conns[peerID]; ok && cur == conn {
delete(n.conns, peerID)
}
n.connsMu.Unlock()
}()
for {
select {
case <-n.ctx.Done():
return
default:
}
// Set read deadline so we can check for context cancellation
netConn.SetReadDeadline(time.Now().Add(1 * time.Second))
data, err := readMessageRaw(netConn)
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
continue
}
return
}
// Check if this is a Call response (has 8-byte header with response flag)
if len(data) >= 8 {
reqFlag := binary.LittleEndian.Uint32(data[4:8])
if reqFlag == ReqFlagResp {
// Route response to waiting goroutine
reqID := binary.LittleEndian.Uint32(data[0:4])
msg, err := Parse(data[8:])
if err == nil {
conn.pendMu.Lock()
if ch, ok := conn.pending[reqID]; ok {
select {
case ch <- msg:
default:
}
}
conn.pendMu.Unlock()
}
continue
}
}
// Regular message - use standard handler
msg, err := Parse(data)
if err != nil {
continue
}
msgType := msg.Flags() >> 8
n.handlersMu.RLock()
handler, ok := n.handlers[msgType]
n.handlersMu.RUnlock()
if ok {
handler(n.ctx, peerID, msg)
}
}
}()
return conn, nil
}
// ConnectDirect connects directly to a peer at the given address (bypasses mDNS).
func (n *Node) ConnectDirect(addr string) error {
netConn, err := net.DialTimeout("tcp", addr, 5*time.Second)
if err != nil {
return fmt.Errorf("failed to connect to %s: %w", addr, err)
}
if n.tlsCfg != nil {
netConn = tls.Client(netConn, n.tlsCfg)
}
// Send handshake
{
b := NewBuilder(128)
obj := b.StartObject(64)
idBytes := []byte(n.nodeID)
for i, c := range idBytes {
if i >= 60 {
break
}
obj.SetUint8(i, c)
}
obj.SetUint32(60, uint32(len(idBytes)))
obj.FinishAsRoot()
if err := writeMessage(netConn, b.Finish()); err != nil {
netConn.Close()
return err
}
}
// Read handshake response
var peerID string
{
msg, err := readMessage(netConn)
if err != nil {
netConn.Close()
return err
}
root := msg.Root()
idLen := root.Uint32(60)
if idLen > 0 && idLen <= 60 {
idBytes := make([]byte, idLen)
for i := uint32(0); i < idLen; i++ {
idBytes[i] = root.Uint8(int(i))
}
peerID = string(idBytes)
}
}
if peerID == "" {
netConn.Close()
return fmt.Errorf("invalid peer handshake")
}
conn := &Conn{
NodeID: peerID,
Addr: addr,
conn: netConn,
pending: make(map[uint32]chan *Message),
}
// Check if we already have a connection (race with incoming connection)
n.connsMu.Lock()
if _, ok := n.conns[peerID]; ok {
n.connsMu.Unlock()
netConn.Close()
return nil // Already connected, that's fine
}
n.conns[peerID] = conn
n.connsMu.Unlock()
n.logger.Info("Connected to peer", "peerID", peerID, "addr", addr)
// Start receive loop
n.wg.Add(1)
go func() {
defer n.wg.Done()
defer func() {
n.connsMu.Lock()
// Only delete if this is still our connection
if cur, ok := n.conns[peerID]; ok && cur == conn {
delete(n.conns, peerID)
}
n.connsMu.Unlock()
n.logger.Info("Peer disconnected", "peerID", peerID)
}()
for {
select {
case <-n.ctx.Done():
return
default:
}
// Set read deadline so we can check for context cancellation
netConn.SetReadDeadline(time.Now().Add(1 * time.Second))
data, err := readMessageRaw(netConn)
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
continue
}
return
}
// Check if this is a Call request/response (has 8-byte header)
if len(data) >= 8 {
reqFlag := binary.LittleEndian.Uint32(data[4:8])
if reqFlag == ReqFlagResp {
// Response to a pending Call - route to waiting goroutine
reqID := binary.LittleEndian.Uint32(data[0:4])
msg, err := Parse(data[8:])
if err == nil {
conn.pendMu.Lock()
if ch, ok := conn.pending[reqID]; ok {
select {
case ch <- msg:
default:
}
}
conn.pendMu.Unlock()
}
continue
} else if reqFlag == ReqFlagReq {
// Incoming Call request - handle and send response
reqID := binary.LittleEndian.Uint32(data[0:4])
msg, err := Parse(data[8:])
if err != nil {
continue
}
msgType := msg.Flags() >> 8
n.handlersMu.RLock()
handler, ok := n.handlers[msgType]
n.handlersMu.RUnlock()
if ok {
resp, err := handler(n.ctx, peerID, msg)
if err != nil {
n.logger.Error("Handler error", "peerID", peerID, "msgType", msgType, "error", err)
continue
}
if resp != nil {
// Send response with correlation header
respBytes := resp.Bytes()
wrappedResp := make([]byte, len(respBytes)+8)
binary.LittleEndian.PutUint32(wrappedResp[0:4], reqID)
binary.LittleEndian.PutUint32(wrappedResp[4:8], ReqFlagResp)
copy(wrappedResp[8:], respBytes)
conn.mu.Lock()
writeErr := writeMessage(netConn, wrappedResp)
conn.mu.Unlock()
if writeErr != nil {
return
}
}
}
continue
}
}
// Regular message (no correlation header) - use standard handler
msg, err := Parse(data)
if err != nil {
continue
}
msgType := msg.Flags() >> 8
n.handlersMu.RLock()
handler, ok := n.handlers[msgType]
n.handlersMu.RUnlock()
if ok {
resp, err := handler(n.ctx, peerID, msg)
if err != nil {
n.logger.Error("Handler error", "peerID", peerID, "msgType", msgType, "error", err)
continue
}
if resp != nil {
conn.mu.Lock()
writeErr := writeMessage(netConn, resp.Bytes())
conn.mu.Unlock()
if writeErr != nil {
return
}
}
}
}
}()
return nil
}
// Send sends a message over the connection.
func (c *Conn) Send(msg *Message) error {
c.mu.Lock()
defer c.mu.Unlock()
return writeMessage(c.conn, msg.Bytes())
}
// Recv receives a message from the connection.
func (c *Conn) Recv() (*Message, error) {
c.mu.Lock()
defer c.mu.Unlock()
return readMessage(c.conn)
}
// Wire format: [4 bytes length][message bytes]
func writeMessage(w io.Writer, data []byte) error {
var lenBuf [4]byte
binary.LittleEndian.PutUint32(lenBuf[:], uint32(len(data)))
if _, err := w.Write(lenBuf[:]); err != nil {
return err
}
_, err := w.Write(data)
return err
}
func readMessage(r io.Reader) (*Message, error) {
data, err := readMessageRaw(r)
if err != nil {
return nil, err
}
return Parse(data)
}
func readMessageRaw(r io.Reader) ([]byte, error) {
var lenBuf [4]byte
if _, err := io.ReadFull(r, lenBuf[:]); err != nil {
return nil, err
}
length := binary.LittleEndian.Uint32(lenBuf[:])
if length > 10*1024*1024 { // 10MB max
return nil, errors.New("message too large")
}
data := make([]byte, length)
if _, err := io.ReadFull(r, data); err != nil {
return nil, err
}
return data, nil
}