Debian Codegraph @

test/bridge.go

raw symbols SCIP
1 package test
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7 "math/rand"
8 "net"
9 "sync"
10 "time"
11
12 "github.com/pion/transport/v2/deadline"
13 )
14
15 const (
16 tickWait = 10 * time.Microsecond
17 udpString = "udp"
18 )
19
20 var (
21 errIOTimeout = errors.New("i/o timeout")
22 errBridgeConnClosed = errors.New("bridgeConn closed")
23 errBridgeAlreadyClosed = errors.New("bridge has already been closed")
24 errInverseArrayWithOne = errors.New("inverse requires more than one item in the array")
25 errBadLossChanceRange = errors.New("loss must be < 100 && > 0")
26 )
27
28 type bridgeConnAddr int
29
30 func (a bridgeConnAddr) Network() string {
31 return udpString
32 }
33
34 func (a bridgeConnAddr) String() string {
35 return fmt.Sprintf("a%d", a)
36 }
37
38 // bridgeConn is a net.Conn that represents an endpoint of the bridge.
39 type bridgeConn struct {
40 br *Bridge
41 id int
42 closeReq bool
43 closing bool
44 closed bool
45 mutex sync.RWMutex
46 readCh chan []byte
47 lossChance int
48 readDeadline *deadline.Deadline
49 writeDeadline *deadline.Deadline
50 }
51
52 type netError struct {
53 error
54 timeout, temporary bool
55 }
56
57 func (e *netError) Timeout() bool {
58 return e.timeout
59 }
60
61 func (e *netError) Temporary() bool {
62 return e.temporary
63 }
64
65 // Read reads data, block until the data becomes available.
66 func (conn *bridgeConn) Read(b []byte) (int, error) {
67 select {
68 case <-conn.readDeadline.Done():
69 return 0, &netError{errIOTimeout, true, true}
70 default:
71 }
72
73 select {
74 case data, ok := <-conn.readCh:
75 if !ok {
76 return 0, io.EOF
77 }
78 n := copy(b, data)
79 return n, nil
80 case <-conn.readDeadline.Done():
81 return 0, &netError{errIOTimeout, true, true}
82 }
83 }
84
85 // Write writes data to the bridge.
86 func (conn *bridgeConn) Write(b []byte) (int, error) {
87 select {
88 case <-conn.writeDeadline.Done():
89 return 0, &netError{errIOTimeout, true, true}
90 default:
91 }
92
93 if rand.Intn(100) < conn.lossChance { //nolint:gosec
94 return len(b), nil
95 }
96
97 if !conn.br.Push(b, conn.id) {
98 return 0, &netError{errBridgeConnClosed, false, false}
99 }
100 return len(b), nil
101 }
102
103 // Close closes the bridge (releases resources used).
104 func (conn *bridgeConn) Close() error {
105 conn.mutex.Lock()
106 defer conn.mutex.Unlock()
107
108 if conn.closeReq {
109 return &netError{errBridgeAlreadyClosed, false, false}
110 }
111
112 conn.closeReq = true
113 conn.closing = true
114 return nil
115 }
116
117 // LocalAddr is not used
118 func (conn *bridgeConn) LocalAddr() net.Addr {
119 return bridgeConnAddr(conn.id)
120 }
121
122 // RemoteAddr is not used
123 func (conn *bridgeConn) RemoteAddr() net.Addr { return nil }
124
125 // SetDeadline sets deadline of Read/Write operation.
126 // Setting zero means no deadline.
127 func (conn *bridgeConn) SetDeadline(t time.Time) error {
128 conn.writeDeadline.Set(t)
129 conn.readDeadline.Set(t)
130 return nil
131 }
132
133 // SetReadDeadline sets deadline of Read operation.
134 // Setting zero means no deadline.
135 func (conn *bridgeConn) SetReadDeadline(t time.Time) error {
136 conn.readDeadline.Set(t)
137 return nil
138 }
139
140 // SetWriteDeadline sets deadline of Write operation.
141 // Setting zero means no deadline.
142 func (conn *bridgeConn) SetWriteDeadline(t time.Time) error {
143 conn.writeDeadline.Set(t)
144 return nil
145 }
146
147 func (conn *bridgeConn) isClosed() bool {
148 conn.mutex.RLock()
149 defer conn.mutex.RUnlock()
150
151 return conn.closed
152 }
153
154 // Bridge represents a network between the two endpoints.
155 type Bridge struct {
156 mutex sync.RWMutex
157 conn0 *bridgeConn
158 conn1 *bridgeConn
159
160 queue0to1 [][]byte
161 queue1to0 [][]byte
162
163 dropNWrites0 int
164 dropNWrites1 int
165 reorderNWrites0 int
166 reorderNWrites1 int
167 stack0 [][]byte
168 stack1 [][]byte
169 filterCB0 func([]byte) bool
170 filterCB1 func([]byte) bool
171 err error // last error
172 }
173
174 func inverse(s [][]byte) error {
175 if len(s) < 2 {
176 return errInverseArrayWithOne
177 }
178
179 for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
180 s[i], s[j] = s[j], s[i]
181 }
182 return nil
183 }
184
185 // drop n packets from the slice starting from offset
186 func drop(s [][]byte, offset, n int) [][]byte {
187 if offset+n > len(s) {
188 n = len(s) - offset
189 }
190 return append(s[:offset], s[offset+n:]...)
191 }
192
193 // NewBridge creates a new bridge with two endpoints.
194 func NewBridge() *Bridge {
195 br := &Bridge{
196 queue0to1: make([][]byte, 0),
197 queue1to0: make([][]byte, 0),
198 }
199
200 br.conn0 = &bridgeConn{
201 br: br,
202 id: 0,
203 readCh: make(chan []byte),
204 readDeadline: deadline.New(),
205 writeDeadline: deadline.New(),
206 }
207 br.conn1 = &bridgeConn{
208 br: br,
209 id: 1,
210 readCh: make(chan []byte),
211 readDeadline: deadline.New(),
212 writeDeadline: deadline.New(),
213 }
214
215 return br
216 }
217
218 // GetConn0 returns an endpoint of the bridge, conn0.
219 func (br *Bridge) GetConn0() net.Conn {
220 return br.conn0
221 }
222
223 // GetConn1 returns an endpoint of the bridge, conn1.
224 func (br *Bridge) GetConn1() net.Conn {
225 return br.conn1
226 }
227
228 // Len returns number of queued packets.
229 func (br *Bridge) Len(fromID int) int {
230 br.mutex.Lock()
231 defer br.mutex.Unlock()
232
233 if fromID == 0 {
234 return len(br.queue0to1)
235 }
236 return len(br.queue1to0)
237 }
238
239 // Push pushes a packet into the specified queue.
240 func (br *Bridge) Push(packet []byte, fromID int) bool { //nolint:gocognit
241 d := make([]byte, len(packet))
242 copy(d, packet)
243
244 // Push rate should be limited as same as Tick rate.
245 // Otherwise, queue grows too fast on free running Write.
246 time.Sleep(tickWait)
247
248 br.mutex.Lock()
249 defer br.mutex.Unlock()
250
251 br.conn0.mutex.Lock()
252 br.conn1.mutex.Lock()
253 closing0 := br.conn0.closing
254 closing1 := br.conn1.closing
255 br.conn1.mutex.Unlock()
256 br.conn0.mutex.Unlock()
257
258 if closing0 || closing1 {
259 if fromID == 0 && closing0 {
260 return false
261 }
262 if fromID == 1 && closing1 {
263 return false
264 }
265 return true
266 }
267
268 if fromID == 0 {
269 switch {
270 case br.dropNWrites0 > 0:
271 br.dropNWrites0--
272 // fmt.Printf("br: dropped a packet of size %d (rem: %d for q0)\n", len(d), br.dropNWrites0) // nolint
273 case br.reorderNWrites0 > 0:
274 br.reorderNWrites0--
275 br.stack0 = append(br.stack0, d)
276 // fmt.Printf("stack0 size: %d\n", len(br.stack0)) // nolint
277 if br.reorderNWrites0 == 0 {
278 if err := inverse(br.stack0); err == nil {
279 // fmt.Printf("stack0 reordered!\n") // nolint
280 br.queue0to1 = append(br.queue0to1, br.stack0...)
281 } else {
282 br.err = err
283 }
284 }
285 case br.filterCB0 != nil && !br.filterCB0(d):
286 // fmt.Printf("br: filtered out a packet of size %d (q0)\n", len(d)) // nolint
287 default:
288 // fmt.Printf("br: routed a packet of size %d (q0)\n", len(d)) // nolint
289 br.queue0to1 = append(br.queue0to1, d)
290 }
291 } else {
292 switch {
293 case br.dropNWrites1 > 0:
294 br.dropNWrites1--
295 // fmt.Printf("br: dropped a packet of size %d (rem: %d for q1)\n", len(d), br.dropNWrites0) // nolint
296 case br.reorderNWrites1 > 0:
297 br.reorderNWrites1--
298 br.stack1 = append(br.stack1, d)
299 if br.reorderNWrites1 == 0 {
300 if err := inverse(br.stack1); err != nil {
301 br.err = err
302 }
303 br.queue1to0 = append(br.queue1to0, br.stack1...)
304 }
305 case br.filterCB1 != nil && !br.filterCB1(d):
306 // fmt.Printf("br: filtered out a packet of size %d (q1)\n", len(d)) // nolint
307 default:
308 // fmt.Printf("br: routed a packet of size %d (q1)\n", len(d)) // nolint
309 br.queue1to0 = append(br.queue1to0, d)
310 }
311 }
312 return true
313 }
314
315 // Reorder inverses the order of packets currently in the specified queue.
316 func (br *Bridge) Reorder(fromID int) error {
317 br.mutex.Lock()
318 defer br.mutex.Unlock()
319
320 if fromID == 0 {
321 return inverse(br.queue0to1)
322 }
323 return inverse(br.queue1to0)
324 }
325
326 // Drop drops the specified number of packets from the given offset index
327 // of the specified queue.
328 func (br *Bridge) Drop(fromID, offset, n int) {
329 br.mutex.Lock()
330 defer br.mutex.Unlock()
331
332 if fromID == 0 {
333 br.queue0to1 = drop(br.queue0to1, offset, n)
334 } else {
335 br.queue1to0 = drop(br.queue1to0, offset, n)
336 }
337 }
338
339 // DropNextNWrites drops the next n packets that will be written
340 // to the specified queue.
341 func (br *Bridge) DropNextNWrites(fromID, n int) {
342 br.mutex.Lock()
343 defer br.mutex.Unlock()
344
345 if fromID == 0 {
346 br.dropNWrites0 = n
347 } else {
348 br.dropNWrites1 = n
349 }
350 }
351
352 // ReorderNextNWrites drops the next n packets that will be written
353 // to the specified queue.
354 func (br *Bridge) ReorderNextNWrites(fromID, n int) {
355 br.mutex.Lock()
356 defer br.mutex.Unlock()
357
358 if fromID == 0 {
359 br.reorderNWrites0 = n
360 } else {
361 br.reorderNWrites1 = n
362 }
363 }
364
365 func (br *Bridge) clear() {
366 br.mutex.Lock()
367 defer br.mutex.Unlock()
368
369 br.queue1to0 = nil
370 br.queue0to1 = nil
371 }
372
373 // Tick attempts to hand a packet from the queue for each directions, to readers,
374 // if there are waiting on the queue. If there's no reader, it will return
375 // immediately.
376 func (br *Bridge) Tick() int {
377 br.mutex.Lock()
378 defer br.mutex.Unlock()
379
380 br.conn0.mutex.Lock()
381 if br.conn0.closing && !br.conn0.closed && len(br.queue1to0) == 0 {
382 br.conn0.closed = true
383 close(br.conn0.readCh)
384 }
385 br.conn0.mutex.Unlock()
386 br.conn1.mutex.Lock()
387 if br.conn1.closing && !br.conn1.closed && len(br.queue0to1) == 0 {
388 br.conn1.closed = true
389 close(br.conn1.readCh)
390 }
391 br.conn1.mutex.Unlock()
392
393 var n int
394 if len(br.queue0to1) > 0 && !br.conn1.isClosed() {
395 select {
396 case br.conn1.readCh <- br.queue0to1[0]:
397 n++
398 // fmt.Printf("conn1 received data (%d bytes)\n", len(br.queue0to1[0])) // nolint
399 br.queue0to1 = br.queue0to1[1:]
400 default:
401 }
402 }
403
404 if len(br.queue1to0) > 0 && !br.conn0.isClosed() {
405 select {
406 case br.conn0.readCh <- br.queue1to0[0]:
407 n++
408 // fmt.Printf("conn0 received data (%d bytes)\n", len(br.queue1to0[0])) // nolint
409 br.queue1to0 = br.queue1to0[1:]
410 default:
411 }
412 }
413
414 return n
415 }
416
417 // Process repeats tick() calls until no more outstanding packet in the queues.
418 func (br *Bridge) Process() {
419 for {
420 time.Sleep(tickWait)
421 br.Tick()
422 if br.Len(0) == 0 && br.Len(1) == 0 {
423 break
424 }
425 }
426 }
427
428 // SetLossChance sets the probability of writes being discard (to introduce artificial loss)
429 func (br *Bridge) SetLossChance(chance int) error {
430 if chance > 100 || chance < 0 {
431 return errBadLossChanceRange
432 }
433
434 rand.Seed(time.Now().UTC().UnixNano())
435 br.conn0.lossChance = chance
436 br.conn1.lossChance = chance
437 return nil
438 }
439
440 // Filter filters (drops) packets based on return value of the given callback.
441 func (br *Bridge) Filter(fromID int, cb func([]byte) bool) {
442 br.mutex.Lock()
443 defer br.mutex.Unlock()
444
445 if fromID == 0 {
446 br.filterCB0 = cb
447 } else {
448 br.filterCB1 = cb
449 }
450 }