-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream.go
More file actions
275 lines (226 loc) · 7.5 KB
/
Copy pathstream.go
File metadata and controls
275 lines (226 loc) · 7.5 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
package netpipe
import (
"encoding/binary"
"fmt"
"net"
"sync"
"time"
"github.com/google/uuid"
)
// Stream wire format (per chunk, inside the framing body):
//
// [16 bytes: stream UUID][4 bytes: chunk index][4 bytes: total chunks][N bytes: chunk data]
//
// The flagStream bit is set on every chunk frame. The receiver buffers
// chunks keyed by stream UUID and fires the OnStream callback once all
// chunks for a stream have arrived.
const (
// flagStream marks a frame as part of a chunked stream.
flagStream byte = 0x02
// streamHeaderSize = 16 (UUID) + 4 (chunk index) + 4 (total chunks)
streamHeaderSize = 24
// DefaultChunkSize is the default chunk body size (64 KB).
DefaultChunkSize = 64 * 1024
)
// ---------------------------------------------------------------------------
// Stream reassembly buffer - used by both server and client
// ---------------------------------------------------------------------------
// streamBuffer collects chunks for in-progress streams.
type streamBuffer struct {
mu sync.Mutex
streams map[string]*streamState // key = stream UUID hex
perClient map[string]int // key = client/peer ID → active stream count
maxPerClient int // 0 = unlimited
}
// streamState tracks one in-progress stream.
type streamState struct {
total uint32
received uint32
chunks map[uint32][]byte // index → chunk data
createdAt time.Time
clientID string // who started this stream
}
// maxPendingStreams limits how many incomplete streams can exist at once.
const maxPendingStreams = 256
// streamTimeout is how long an incomplete stream can sit before being cleaned up.
const streamTimeout = 60 * time.Second
func newStreamBuffer() *streamBuffer {
return &streamBuffer{
streams: make(map[string]*streamState),
perClient: make(map[string]int),
}
}
// addChunk stores a chunk and returns the fully reassembled data if this
// was the last missing chunk. Returns (nil, false) if still waiting.
// clientID is used for per-client stream limits.
func (sb *streamBuffer) addChunk(streamID string, index, total uint32, data []byte) ([]byte, bool) {
return sb.addChunkFrom("", streamID, index, total, data)
}
// addChunkFrom is like addChunk but tracks which client sent it.
func (sb *streamBuffer) addChunkFrom(clientID, streamID string, index, total uint32, data []byte) ([]byte, bool) {
if total == 0 || index >= total {
return nil, false
}
sb.mu.Lock()
defer sb.mu.Unlock()
// clean up expired streams
now := time.Now()
for id, s := range sb.streams {
if now.Sub(s.createdAt) > streamTimeout {
if s.clientID != "" {
sb.perClient[s.clientID]--
if sb.perClient[s.clientID] <= 0 {
delete(sb.perClient, s.clientID)
}
}
delete(sb.streams, id)
}
}
state, ok := sb.streams[streamID]
if !ok {
// reject if global limit hit
if len(sb.streams) >= maxPendingStreams {
return nil, false
}
// reject if per-client limit hit
if sb.maxPerClient > 0 && clientID != "" && sb.perClient[clientID] >= sb.maxPerClient {
return nil, false
}
state = &streamState{
total: total,
chunks: make(map[uint32][]byte, total),
createdAt: now,
clientID: clientID,
}
sb.streams[streamID] = state
if clientID != "" {
sb.perClient[clientID]++
}
}
if state.total != total {
return nil, false
}
if _, exists := state.chunks[index]; exists {
return nil, false
}
chunkCopy := make([]byte, len(data))
copy(chunkCopy, data)
state.chunks[index] = chunkCopy
state.received++
if state.received < state.total {
return nil, false
}
// reassemble in order
totalSize := 0
for _, c := range state.chunks {
totalSize += len(c)
}
assembled := make([]byte, 0, totalSize)
for i := uint32(0); i < state.total; i++ {
assembled = append(assembled, state.chunks[i]...)
}
// clean up
if state.clientID != "" {
sb.perClient[state.clientID]--
if sb.perClient[state.clientID] <= 0 {
delete(sb.perClient, state.clientID)
}
}
delete(sb.streams, streamID)
return assembled, true
}
// ---------------------------------------------------------------------------
// Send-side: split data into chunks and write
// ---------------------------------------------------------------------------
// writeStream splits data into chunks and sends each as a flagStream frame.
// TCP only - uses writeMessage for framing.
func writeStream(conn net.Conn, data []byte, chunkSize int) error {
if chunkSize <= 0 {
chunkSize = DefaultChunkSize
}
streamID := uuid.New()
idBytes, err := streamID.MarshalBinary() // 16 bytes
if err != nil {
return fmt.Errorf("netpipe: stream uuid: %w", err)
}
totalChunks := (len(data) + chunkSize - 1) / chunkSize
if totalChunks == 0 {
totalChunks = 1 // send at least one chunk for empty data
}
for i := 0; i < totalChunks; i++ {
start := i * chunkSize
end := start + chunkSize
if end > len(data) {
end = len(data)
}
chunk := data[start:end]
// build stream header: [16B UUID][4B index][4B total]
header := make([]byte, streamHeaderSize)
copy(header[:16], idBytes)
binary.BigEndian.PutUint32(header[16:20], uint32(i))
binary.BigEndian.PutUint32(header[20:24], uint32(totalChunks))
// body = stream header + chunk data
body := make([]byte, streamHeaderSize+len(chunk))
copy(body[:streamHeaderSize], header)
copy(body[streamHeaderSize:], chunk)
if err := writeMessage(conn, flagStream, body); err != nil {
return fmt.Errorf("netpipe: stream chunk %d/%d: %w", i+1, totalChunks, err)
}
}
return nil
}
// writeStreamUDP splits data into chunks and sends each as a UDP packet
// with the flagStream flag.
func writeStreamUDPClient(conn net.Conn, data []byte, chunkSize int) error {
if chunkSize <= 0 {
chunkSize = DefaultChunkSize
}
streamID := uuid.New()
idBytes, err := streamID.MarshalBinary()
if err != nil {
return fmt.Errorf("netpipe: stream uuid: %w", err)
}
totalChunks := (len(data) + chunkSize - 1) / chunkSize
if totalChunks == 0 {
totalChunks = 1
}
for i := 0; i < totalChunks; i++ {
start := i * chunkSize
end := start + chunkSize
if end > len(data) {
end = len(data)
}
chunk := data[start:end]
header := make([]byte, streamHeaderSize)
copy(header[:16], idBytes)
binary.BigEndian.PutUint32(header[16:20], uint32(i))
binary.BigEndian.PutUint32(header[20:24], uint32(totalChunks))
// UDP packet: [1B flags][24B stream header][NB chunk]
packet := make([]byte, 1+streamHeaderSize+len(chunk))
packet[0] = flagStream
copy(packet[1:1+streamHeaderSize], header)
copy(packet[1+streamHeaderSize:], chunk)
if _, err := conn.Write(packet); err != nil {
return fmt.Errorf("netpipe: stream udp chunk %d/%d: %w", i+1, totalChunks, err)
}
}
return nil
}
// ---------------------------------------------------------------------------
// Receive-side: parse stream header from body
// ---------------------------------------------------------------------------
// parseStreamBody extracts the stream UUID, chunk index, total, and chunk data
// from a flagStream frame body.
func parseStreamBody(body []byte) (streamID string, index, total uint32, chunk []byte, err error) {
if len(body) < streamHeaderSize {
return "", 0, 0, nil, fmt.Errorf("netpipe: stream body too short (%d bytes)", len(body))
}
var uid uuid.UUID
if err := uid.UnmarshalBinary(body[:16]); err != nil {
return "", 0, 0, nil, fmt.Errorf("netpipe: stream uuid parse: %w", err)
}
index = binary.BigEndian.Uint32(body[16:20])
total = binary.BigEndian.Uint32(body[20:24])
chunk = body[streamHeaderSize:]
return uid.String(), index, total, chunk, nil
}