-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconn.go
More file actions
270 lines (233 loc) · 7.35 KB
/
Copy pathconn.go
File metadata and controls
270 lines (233 loc) · 7.35 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
// Package voidbus provides net.Conn implementation for VoidBus connections.
//
// voidBusConn implements message-oriented semantics:
// - Read: returns ONE complete message (reassembled, decoded) per call
// - Write: writes ONE complete message (encoded, fragmented, sent across multiple channels)
// - Deadline: timeout for complete message reassembly/encoding/sending
//
// Read semantics:
// - Each Read returns exactly one complete message
// - Returns n = len(complete_message)
// - If buffer is smaller than message, returns ErrBufferTooSmall with n = required_size
// - User should allocate buffer >= required_size and retry
package voidbus
import (
"context"
"errors"
"net"
"os"
"sync"
"time"
"github.com/Script-OS/VoidBus/channel"
)
// ErrBufferTooSmall indicates the user buffer is smaller than the complete message.
// n returned by Read indicates the required buffer size.
var ErrBufferTooSmall = errors.New("voidbus: buffer too small for complete message")
// SendInfo holds information about the last sent message.
type SendInfo struct {
Channels []string // Channel IDs used for sending fragments
CodecChain []string // Codec codes used for encoding
CodecHash [32]byte // Codec chain hash
FragmentCnt int // Number of fragments
DataSize int // Original data size
}
// voidBusConn implements net.Conn for VoidBus connections.
// Message-oriented semantics: each Read/Write operates on a complete message.
type voidBusConn struct {
bus *Bus
channelID string // The channel ID used for negotiation (assigned by Bus)
channelType channel.ChannelType // The channel type
// Receive state (no partial read support - complete message per Read)
recvMu sync.Mutex
recvChan chan []byte // Complete message channel (from bus receive loop)
// Deadline
readDeadline time.Time
writeDeadline time.Time
// Address info
localAddr net.Addr
remoteAddr net.Addr
// State
closed bool
closeMu sync.Mutex
// Last send info (for channel/codec chain display)
lastSendMu sync.Mutex
lastSend *SendInfo
}
// Read reads ONE complete message from the connection.
// Returns n = size of complete message (reassembled, decoded).
// If buffer is smaller than message, returns ErrBufferTooSmall with n = required_size.
// No partial read - each Read returns exactly one complete message.
func (c *voidBusConn) Read(b []byte) (n int, err error) {
c.recvMu.Lock()
defer c.recvMu.Unlock()
// Check if closed
c.closeMu.Lock()
if c.closed {
c.closeMu.Unlock()
return 0, net.ErrClosed
}
c.closeMu.Unlock()
// Wait for complete message
// If no deadline set (zero value), wait indefinitely
if c.readDeadline.IsZero() {
select {
case data := <-c.recvChan:
// Complete message arrived
if len(data) > len(b) {
// Buffer too small, return required size
return len(data), ErrBufferTooSmall
}
copy(b, data)
return len(data), nil
case <-c.bus.stopChan:
return 0, net.ErrClosed
}
}
// Wait with deadline
select {
case data := <-c.recvChan:
// Complete message arrived
if len(data) > len(b) {
// Buffer too small, return required size
return len(data), ErrBufferTooSmall
}
copy(b, data)
return len(data), nil
case <-time.After(time.Until(c.readDeadline)):
// Return net.Conn compliant timeout error
return 0, &net.OpError{
Op: "read",
Net: "voidbus",
Source: c.localAddr,
Addr: c.remoteAddr,
Err: os.ErrDeadlineExceeded,
}
case <-c.bus.stopChan:
return 0, net.ErrClosed
}
}
// Write writes ONE complete message to the connection.
// Returns n = size of the original message (before encoding/fragmentation).
// VoidBus internally handles: encoding, fragmentation, multi-channel distribution.
func (c *voidBusConn) Write(b []byte) (n int, err error) {
// Check write deadline
if !c.writeDeadline.IsZero() && time.Now().After(c.writeDeadline) {
return 0, &net.OpError{
Op: "write",
Net: "voidbus",
Source: c.localAddr,
Addr: c.remoteAddr,
Err: os.ErrDeadlineExceeded,
}
}
// Check if closed
c.closeMu.Lock()
if c.closed {
c.closeMu.Unlock()
return 0, net.ErrClosed
}
c.closeMu.Unlock()
// Use bus SendWithContext (handles encoding, fragmentation, multi-channel)
ctx := context.Background()
if !c.writeDeadline.IsZero() {
var cancel context.CancelFunc
ctx, cancel = context.WithDeadline(ctx, c.writeDeadline)
defer cancel()
}
// In debug mode, use sendInternalWithInfo to get detailed send information
if c.bus.config.DebugMode {
info, err := c.bus.sendInternalWithInfo(ctx, b)
if err != nil {
return 0, err
}
if info != nil {
c.setLastSendInfo(info)
}
return len(b), nil
}
// Normal mode: use sendInternal (no overhead for tracking)
if err := c.bus.sendInternal(ctx, b); err != nil {
return 0, err
}
// Return original message size
return len(b), nil
}
// Close closes the connection.
// Calls bus.Stop() which closes all channels (unblocking Receive loops)
// and waits for all goroutines to exit.
func (c *voidBusConn) Close() error {
c.closeMu.Lock()
defer c.closeMu.Unlock()
if c.closed {
return nil
}
c.closed = true
// Stop the bus: closes all channels in pool → unblocks receiveLoop → waits for exit
// Note: For client mode, this stops the entire bus
// For server mode, each client has its own clientBus
c.bus.Stop()
return nil
}
// LocalAddr returns the local network address.
func (c *voidBusConn) LocalAddr() net.Addr {
return c.localAddr
}
// RemoteAddr returns the remote network address.
func (c *voidBusConn) RemoteAddr() net.Addr {
return c.remoteAddr
}
// SetDeadline sets the read and write deadlines.
// ReadDeadline: timeout for complete message reassembly.
// WriteDeadline: timeout for complete message encoding/sending.
func (c *voidBusConn) SetDeadline(t time.Time) error {
c.readDeadline = t
c.writeDeadline = t
return nil
}
// SetReadDeadline sets the deadline for complete message reassembly.
func (c *voidBusConn) SetReadDeadline(t time.Time) error {
c.readDeadline = t
return nil
}
// SetWriteDeadline sets the deadline for complete message encoding/sending.
func (c *voidBusConn) SetWriteDeadline(t time.Time) error {
c.writeDeadline = t
return nil
}
// ChannelID returns the channel ID used for this connection.
func (c *voidBusConn) ChannelID() string {
return c.channelID
}
// GetLastSendInfo returns information about the last sent message.
// Returns nil if no message has been sent yet.
// Contains: Channels (IDs used), CodecChain (codes), FragmentCnt, DataSize.
func (c *voidBusConn) GetLastSendInfo() *SendInfo {
c.lastSendMu.Lock()
defer c.lastSendMu.Unlock()
return c.lastSend
}
// setLastSendInfo updates the last send info (internal method).
func (c *voidBusConn) setLastSendInfo(info *SendInfo) {
c.lastSendMu.Lock()
c.lastSend = info
c.lastSendMu.Unlock()
}
// newVoidBusConn creates a new VoidBus connection.
func newVoidBusConn(bus *Bus, channelID string, chType channel.ChannelType, recvChan chan []byte) *voidBusConn {
conn := &voidBusConn{
bus: bus,
channelID: channelID,
channelType: chType,
recvChan: recvChan,
}
// Set addresses based on channel type
if channelID != "" {
network := "voidbus-" + string(chType)
conn.localAddr = NewVoidBusAddr(network, channelID)
conn.remoteAddr = NewVoidBusAddr(network, channelID)
} else {
conn.localAddr = NewVoidBusAddr("voidbus", "")
conn.remoteAddr = NewVoidBusAddr("voidbus", "")
}
return conn
}