-
Notifications
You must be signed in to change notification settings - Fork 204
Expand file tree
/
Copy pathselection_test.go
More file actions
1494 lines (1230 loc) · 49.1 KB
/
selection_test.go
File metadata and controls
1494 lines (1230 loc) · 49.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
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
//go:build !js
package ice
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/pion/logging"
"github.com/pion/stun/v3"
"github.com/pion/transport/v4/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
selectionTestPassword = "pwd"
selectionTestRemoteUfrag = "remote"
selectionTestLocalUfrag = "local"
)
func sendUntilDone(t *testing.T, writingConn, readingConn net.Conn, maxAttempts int) bool {
t.Helper()
testMessage := []byte("Hello World")
testBuffer := make([]byte, len(testMessage))
readDone, readDoneCancel := context.WithCancel(context.Background())
go func() {
_, err := readingConn.Read(testBuffer)
if errors.Is(err, io.EOF) {
return
}
require.NoError(t, err)
require.True(t, bytes.Equal(testMessage, testBuffer))
readDoneCancel()
}()
attempts := 0
for {
select {
case <-time.After(5 * time.Millisecond):
if attempts > maxAttempts {
return false
}
_, err := writingConn.Write(testMessage)
require.NoError(t, err)
attempts++
case <-readDone.Done():
return true
}
}
}
func TestBindingRequestHandler(t *testing.T) {
defer test.CheckRoutines(t)()
defer test.TimeOut(time.Second * 30).Stop()
var switchToNewCandidatePair, controlledLoggingFired atomic.Value
oneHour := time.Hour
keepaliveInterval := time.Millisecond * 20
aNotifier, aConnected := onConnected()
bNotifier, bConnected := onConnected()
controllingAgent, err := NewAgent(&AgentConfig{
NetworkTypes: []NetworkType{NetworkTypeUDP4, NetworkTypeUDP6},
MulticastDNSMode: MulticastDNSModeDisabled,
KeepaliveInterval: &keepaliveInterval,
CheckInterval: &oneHour,
BindingRequestHandler: func(_ *stun.Message, _, _ Candidate, _ *CandidatePair) bool {
controlledLoggingFired.Store(true)
return false
},
})
require.NoError(t, err)
require.NoError(t, controllingAgent.OnConnectionStateChange(aNotifier))
controlledAgent, err := NewAgent(&AgentConfig{
NetworkTypes: []NetworkType{NetworkTypeUDP4},
MulticastDNSMode: MulticastDNSModeDisabled,
KeepaliveInterval: &keepaliveInterval,
CheckInterval: &oneHour,
BindingRequestHandler: func(_ *stun.Message, _, _ Candidate, _ *CandidatePair) bool {
// Don't switch candidate pair until we are ready
val, ok := switchToNewCandidatePair.Load().(bool)
return ok && val
},
})
require.NoError(t, err)
require.NoError(t, controlledAgent.OnConnectionStateChange(bNotifier))
controlledConn, controllingConn := connect(t, controlledAgent, controllingAgent)
<-aConnected
<-bConnected
// Assert we have connected and can send data
require.True(t, sendUntilDone(t, controlledConn, controllingConn, 100))
// Take the lock on the controlling Agent and unset state
assert.NoError(t, controlledAgent.loop.Run(controlledAgent.loop, func(_ context.Context) {
for net, cs := range controlledAgent.remoteCandidates {
for _, c := range cs {
require.NoError(t, c.close())
}
delete(controlledAgent.remoteCandidates, net)
}
for _, c := range controlledAgent.localCandidates[NetworkTypeUDP4] {
cast, ok := c.(*CandidateHost)
require.True(t, ok)
cast.remoteCandidateCaches = sync.Map{}
}
controlledAgent.setSelectedPair(nil)
controlledAgent.checklist = make([]*CandidatePair, 0)
}))
// Assert that Selected Candidate pair has only been unset on Controlled side
candidatePair, err := controlledAgent.GetSelectedCandidatePair()
assert.Nil(t, candidatePair)
assert.NoError(t, err)
candidatePair, err = controllingAgent.GetSelectedCandidatePair()
assert.NotNil(t, candidatePair)
assert.NoError(t, err)
// Sending will fail, we no longer have a selected candidate pair
require.False(t, sendUntilDone(t, controlledConn, controllingConn, 20))
// Send STUN Binding requests until a new Selected Candidate Pair has been set by BindingRequestHandler
switchToNewCandidatePair.Store(true)
for {
controllingAgent.requestConnectivityCheck()
candidatePair, err = controlledAgent.GetSelectedCandidatePair()
require.NoError(t, err)
if candidatePair != nil {
break
}
time.Sleep(time.Millisecond * 5)
}
// We have a new selected candidate pair because of BindingRequestHandler, test that it works
require.True(t, sendUntilDone(t, controllingConn, controlledConn, 100))
fired, ok := controlledLoggingFired.Load().(bool)
require.True(t, ok)
require.True(t, fired)
closePipe(t, controllingConn, controlledConn)
}
// copied from pion/webrtc's peerconnection_go_test.go.
type testICELogger struct {
lastErrorMessage string
}
func (t *testICELogger) Trace(string) {}
func (t *testICELogger) Tracef(string, ...any) {}
func (t *testICELogger) Debug(string) {}
func (t *testICELogger) Debugf(string, ...any) {}
func (t *testICELogger) Info(string) {}
func (t *testICELogger) Infof(string, ...any) {}
func (t *testICELogger) Warn(string) {}
func (t *testICELogger) Warnf(string, ...any) {}
func (t *testICELogger) Error(msg string) { t.lastErrorMessage = msg }
func (t *testICELogger) Errorf(format string, args ...any) {
t.lastErrorMessage = fmt.Sprintf(format, args...)
}
type testICELoggerFactory struct {
logger *testICELogger
}
func (t *testICELoggerFactory) NewLogger(string) logging.LeveledLogger {
return t.logger
}
func TestControllingSelector_IsNominatable_LogsInvalidType(t *testing.T) {
testLogger := &testICELogger{}
loggerFactory := &testICELoggerFactory{logger: testLogger}
sel := &controllingSelector{
agent: &Agent{},
log: loggerFactory.NewLogger("test"),
}
sel.Start()
c := hostCandidate()
c.candidateBase.candidateType = CandidateTypeUnspecified
got := sel.isNominatable(c)
require.False(t, got)
require.Contains(t, testLogger.lastErrorMessage, "Invalid candidate type")
require.Contains(t, testLogger.lastErrorMessage, "Unknown candidate type") // from c.Type().String()
}
func TestControllingSelector_NominatePair_BuildError(t *testing.T) {
testLogger := &testICELogger{}
loggerFactory := &testICELoggerFactory{logger: testLogger}
// selector with an Agent with ufrags to make an oversized username
// (username = remoteUfrag + ":" + localUfrag) since oversized username causes
// stun.NewUsername(...) inside stun.Build to fail.
long := strings.Repeat("x", 300) // > 255 each side
sel := &controllingSelector{
agent: &Agent{
remoteUfrag: long,
localUfrag: long,
remotePwd: "pwd", // any non-empty value is fine
tieBreaker: 0,
},
log: loggerFactory.NewLogger("test"),
}
sel.Start()
p := newCandidatePair(hostCandidate(), hostCandidate(), true)
sel.nominatePair(p)
require.NotEmpty(t, testLogger.lastErrorMessage, "expected error log from nominatePair on Build failure")
}
type pingNoIOCand struct{ candidateBase }
func newPingNoIOCand() *pingNoIOCand {
return &pingNoIOCand{
candidateBase: candidateBase{
candidateType: CandidateTypeHost,
component: ComponentRTP,
},
}
}
func (d *pingNoIOCand) writeTo(b []byte, _ Candidate) (int, error) { return len(b), nil }
func bareAgentForPing() *Agent {
return &Agent{
hostAcceptanceMinWait: time.Hour,
srflxAcceptanceMinWait: time.Hour,
prflxAcceptanceMinWait: time.Hour,
relayAcceptanceMinWait: time.Hour,
checklist: []*CandidatePair{},
pairsByID: make(map[uint64]*CandidatePair),
keepaliveInterval: time.Second,
checkInterval: time.Second,
connectionStateNotifier: &handlerNotifier{
done: make(chan struct{}),
connectionStateFunc: func(ConnectionState) {},
}, //nolint formatting
candidateNotifier: &handlerNotifier{
done: make(chan struct{}),
candidateFunc: func(Candidate) {},
}, //nolint formatting
selectedCandidatePairNotifier: &handlerNotifier{
done: make(chan struct{}),
candidatePairFunc: func(*CandidatePair) {},
}, //nolint formatting
}
}
func bigStr() string { return strings.Repeat("x", 40000) }
func TestControllingSelector_PingCandidate_BuildError(t *testing.T) {
a := bareAgentForPing()
// make Username really big so stun.Build returns an error.
a.remoteUfrag = bigStr()
a.localUfrag = bigStr()
a.remotePwd = selectionTestPassword
a.tieBreaker = 1
testLogger := &testICELogger{}
sel := &controllingSelector{agent: a, log: testLogger}
sel.Start()
local := newPingNoIOCand()
remote := newPingNoIOCand()
sel.PingCandidate(local, remote)
require.NotEmpty(t, testLogger.lastErrorMessage, "expected error to be logged from stun.Build")
}
func TestControlledSelector_PingCandidate_BuildError(t *testing.T) {
a := bareAgentForPing()
a.remoteUfrag = bigStr()
a.localUfrag = bigStr()
a.remotePwd = selectionTestPassword
a.tieBreaker = 1
testLogger := &testICELogger{}
sel := &controlledSelector{agent: a, log: testLogger}
sel.Start()
local := newPingNoIOCand()
remote := newPingNoIOCand()
sel.PingCandidate(local, remote)
require.NotEmpty(t, testLogger.lastErrorMessage, "expected error to be logged from stun.Build")
}
type warnTestLogger struct {
warned bool
}
func (l *warnTestLogger) Trace(string) {}
func (l *warnTestLogger) Tracef(string, ...any) {}
func (l *warnTestLogger) Debug(string) {}
func (l *warnTestLogger) Debugf(string, ...any) {}
func (l *warnTestLogger) Info(string) {}
func (l *warnTestLogger) Infof(string, ...any) {}
func (l *warnTestLogger) Warn(string) { l.warned = true }
func (l *warnTestLogger) Warnf(string, ...any) { l.warned = true }
func (l *warnTestLogger) Error(string) {}
func (l *warnTestLogger) Errorf(string, ...any) {}
type dummyNoIOCand struct{ candidateBase }
func newDummyNoIOCand(t CandidateType) *dummyNoIOCand {
return &dummyNoIOCand{
candidateBase: candidateBase{
candidateType: t,
component: ComponentRTP,
},
}
}
func (d *dummyNoIOCand) writeTo(p []byte, _ Candidate) (int, error) { return len(p), nil }
func TestControlledSelector_HandleSuccessResponse_UnknownTxID(t *testing.T) {
logger := &warnTestLogger{}
ag := &Agent{log: logger}
sel := &controlledSelector{agent: ag, log: logger}
sel.Start()
local := newDummyNoIOCand(CandidateTypeHost)
remote := newDummyNoIOCand(CandidateTypeHost)
var m stun.Message
copy(m.TransactionID[:], []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12})
sel.HandleSuccessResponse(&m, local, remote, nil)
require.True(t, logger.warned, "expected Warnf to be called for unknown TransactionID (hitting !ok branch)")
}
// TestControlledSelector_NoTriggeredCheckAfterConnected verifies that once a pair
// is in Succeeded state with a selected pair, HandleBindingRequest does NOT send
// a triggered check (PingCandidate). Before the fix, every inbound Binding Request
// unconditionally called PingCandidate, creating a ping-pong busy loop at 1/RTT.
func TestControlledSelector_NoTriggeredCheckAfterConnected(t *testing.T) {
agent := bareAgentForPing()
agent.log = logging.NewDefaultLoggerFactory().NewLogger("test")
agent.remoteUfrag = selectionTestRemoteUfrag
agent.localUfrag = selectionTestLocalUfrag
agent.remotePwd = selectionTestPassword
agent.localPwd = selectionTestPassword
agent.tieBreaker = 1
agent.isControlling.Store(false)
agent.onConnected = make(chan struct{})
agent.setSelector()
selector, ok := agent.getSelector().(*controlledSelector)
require.True(t, ok, "expected controlledSelector")
local := newPingNoIOCand()
local.candidateBase.networkType = NetworkTypeUDP4
local.candidateBase.resolvedAddr = &net.UDPAddr{IP: net.ParseIP("192.168.1.1"), Port: 10000}
remote := newPingNoIOCand()
remote.candidateBase.networkType = NetworkTypeUDP4
remote.candidateBase.resolvedAddr = &net.UDPAddr{IP: net.ParseIP("192.168.1.2"), Port: 20000}
pair := agent.addPair(local, remote)
pair.state = CandidatePairStateSucceeded
agent.setSelectedPair(pair)
// Record requests sent before calling HandleBindingRequest.
sentBefore := pair.RequestsSent()
// Build a STUN Binding Request (no USE-CANDIDATE).
msg, err := stun.Build(stun.BindingRequest,
stun.TransactionID,
stun.NewUsername(agent.localUfrag+":"+agent.remoteUfrag),
stun.NewShortTermIntegrity(agent.localPwd),
stun.Fingerprint,
)
require.NoError(t, err)
// Call HandleBindingRequest multiple times — simulates repeated inbound requests.
for range 10 {
selector.HandleBindingRequest(msg, local, remote)
}
// No triggered checks should have been sent since the pair is already connected.
assert.Equal(t, sentBefore, pair.RequestsSent(),
"triggered check should not be sent for a succeeded+selected pair")
}
// TestControlledSelector_TriggeredCheckDuringChecking verifies that a triggered
// check IS sent when the pair is not yet in Succeeded state (normal ICE checking).
func TestControlledSelector_TriggeredCheckDuringChecking(t *testing.T) {
agent := bareAgentForPing()
agent.log = logging.NewDefaultLoggerFactory().NewLogger("test")
agent.remoteUfrag = selectionTestRemoteUfrag
agent.localUfrag = selectionTestLocalUfrag
agent.remotePwd = selectionTestPassword
agent.localPwd = selectionTestPassword
agent.tieBreaker = 1
agent.isControlling.Store(false)
agent.onConnected = make(chan struct{})
agent.setSelector()
selector, ok := agent.getSelector().(*controlledSelector)
require.True(t, ok, "expected controlledSelector")
local := newPingNoIOCand()
local.candidateBase.networkType = NetworkTypeUDP4
local.candidateBase.resolvedAddr = &net.UDPAddr{IP: net.ParseIP("192.168.1.1"), Port: 10000}
remote := newPingNoIOCand()
remote.candidateBase.networkType = NetworkTypeUDP4
remote.candidateBase.resolvedAddr = &net.UDPAddr{IP: net.ParseIP("192.168.1.2"), Port: 20000}
pair := agent.addPair(local, remote)
// Pair is in Waiting state (not Succeeded), no selected pair — normal ICE checking.
sentBefore := pair.RequestsSent()
msg, err := stun.Build(stun.BindingRequest,
stun.TransactionID,
stun.NewUsername(agent.localUfrag+":"+agent.remoteUfrag),
stun.NewShortTermIntegrity(agent.localPwd),
stun.Fingerprint,
)
require.NoError(t, err)
selector.HandleBindingRequest(msg, local, remote)
assert.Greater(t, pair.RequestsSent(), sentBefore,
"triggered check should be sent during ICE checking phase")
}
func TestAutomaticRenomination(t *testing.T) { //nolint:maintidx
report := test.CheckRoutines(t)
defer report()
t.Run("Configuration", func(t *testing.T) {
t.Run("WithAutomaticRenomination enables feature", func(t *testing.T) {
agent, err := NewAgentWithOptions(
WithRenomination(DefaultNominationValueGenerator()),
WithAutomaticRenomination(5*time.Second),
)
require.NoError(t, err)
defer func() {
require.NoError(t, agent.Close())
}()
assert.True(t, agent.automaticRenomination)
assert.Equal(t, 5*time.Second, agent.renominationInterval)
assert.True(t, agent.enableRenomination)
})
t.Run("Default interval when zero", func(t *testing.T) {
agent, err := NewAgentWithOptions(
WithRenomination(DefaultNominationValueGenerator()),
WithAutomaticRenomination(0),
)
require.NoError(t, err)
defer func() {
require.NoError(t, agent.Close())
}()
assert.True(t, agent.automaticRenomination)
assert.Equal(t, 3*time.Second, agent.renominationInterval)
})
})
t.Run("Quality Assessment", func(t *testing.T) {
agent, err := NewAgent(&AgentConfig{})
require.NoError(t, err)
defer func() {
require.NoError(t, agent.Close())
}()
localHost, err := NewCandidateHost(&CandidateHostConfig{
Network: "udp",
Address: "192.168.1.1",
Port: 10000,
Component: 1,
})
require.NoError(t, err)
remoteHost, err := NewCandidateHost(&CandidateHostConfig{
Network: "udp",
Address: "192.168.1.2",
Port: 20000,
Component: 1,
})
require.NoError(t, err)
localRelay, err := NewCandidateRelay(&CandidateRelayConfig{
Network: "udp",
Address: "10.0.0.1",
Port: 30000,
Component: 1,
RelAddr: "192.168.1.1",
RelPort: 10000,
})
require.NoError(t, err)
remoteRelay, err := NewCandidateRelay(&CandidateRelayConfig{
Network: "udp",
Address: "10.0.0.2",
Port: 40000,
Component: 1,
RelAddr: "192.168.1.2",
RelPort: 20000,
})
require.NoError(t, err)
t.Run("Host pair scores higher than relay pair", func(t *testing.T) {
hostPair := newCandidatePair(localHost, remoteHost, true)
hostPair.state = CandidatePairStateSucceeded
hostPair.UpdateRoundTripTime(10 * time.Millisecond)
relayPair := newCandidatePair(localRelay, remoteRelay, true)
relayPair.state = CandidatePairStateSucceeded
relayPair.UpdateRoundTripTime(10 * time.Millisecond)
hostScore := agent.evaluateCandidatePairQuality(hostPair)
relayScore := agent.evaluateCandidatePairQuality(relayPair)
assert.Greater(t, hostScore, relayScore,
"Host pair should score higher than relay pair with same RTT")
})
t.Run("Lower RTT scores higher", func(t *testing.T) {
pair1 := newCandidatePair(localHost, remoteHost, true)
pair1.state = CandidatePairStateSucceeded
pair1.UpdateRoundTripTime(5 * time.Millisecond)
pair2 := newCandidatePair(localHost, remoteHost, true)
pair2.state = CandidatePairStateSucceeded
pair2.UpdateRoundTripTime(50 * time.Millisecond)
score1 := agent.evaluateCandidatePairQuality(pair1)
score2 := agent.evaluateCandidatePairQuality(pair2)
assert.Greater(t, score1, score2,
"Pair with lower RTT should score higher")
})
})
t.Run("Should Renominate Logic", func(t *testing.T) {
agent, err := NewAgent(&AgentConfig{})
require.NoError(t, err)
defer func() {
require.NoError(t, agent.Close())
}()
localHost, err := NewCandidateHost(&CandidateHostConfig{
Network: "udp",
Address: "192.168.1.1",
Port: 10000,
Component: 1,
})
require.NoError(t, err)
remoteHost, err := NewCandidateHost(&CandidateHostConfig{
Network: "udp",
Address: "192.168.1.2",
Port: 20000,
Component: 1,
})
require.NoError(t, err)
localRelay, err := NewCandidateRelay(&CandidateRelayConfig{
Network: "udp",
Address: "10.0.0.1",
Port: 30000,
Component: 1,
RelAddr: "192.168.1.1",
RelPort: 10000,
})
require.NoError(t, err)
remoteRelay, err := NewCandidateRelay(&CandidateRelayConfig{
Network: "udp",
Address: "10.0.0.2",
Port: 40000,
Component: 1,
RelAddr: "192.168.1.2",
RelPort: 20000,
})
require.NoError(t, err)
t.Run("Should renominate relay to host", func(t *testing.T) {
relayPair := newCandidatePair(localRelay, remoteRelay, true)
relayPair.state = CandidatePairStateSucceeded
relayPair.UpdateRoundTripTime(50 * time.Millisecond)
hostPair := newCandidatePair(localHost, remoteHost, true)
hostPair.state = CandidatePairStateSucceeded
hostPair.UpdateRoundTripTime(45 * time.Millisecond) // Similar RTT
shouldSwitch := agent.shouldRenominate(relayPair, hostPair)
assert.True(t, shouldSwitch,
"Should renominate from relay to host even with similar RTT")
})
t.Run("Should renominate for RTT improvement > 10ms", func(t *testing.T) {
// Create different host candidates for pair2 to avoid same-pair check
localHost2, err := NewCandidateHost(&CandidateHostConfig{
Network: "udp",
Address: "192.168.1.3",
Port: 10001,
Component: 1,
})
require.NoError(t, err)
pair1 := newCandidatePair(localHost, remoteHost, true)
pair1.state = CandidatePairStateSucceeded
pair1.UpdateRoundTripTime(50 * time.Millisecond)
pair2 := newCandidatePair(localHost2, remoteHost, true)
pair2.state = CandidatePairStateSucceeded
pair2.UpdateRoundTripTime(30 * time.Millisecond) // 20ms improvement
shouldSwitch := agent.shouldRenominate(pair1, pair2)
assert.True(t, shouldSwitch,
"Should renominate for RTT improvement > 10ms")
})
t.Run("Should not renominate for small RTT improvement", func(t *testing.T) {
// Create different host candidates for pair2 to avoid same-pair check
localHost2, err := NewCandidateHost(&CandidateHostConfig{
Network: "udp",
Address: "192.168.1.3",
Port: 10001,
Component: 1,
})
require.NoError(t, err)
pair1 := newCandidatePair(localHost, remoteHost, true)
pair1.state = CandidatePairStateSucceeded
pair1.UpdateRoundTripTime(50 * time.Millisecond)
pair2 := newCandidatePair(localHost2, remoteHost, true)
pair2.state = CandidatePairStateSucceeded
pair2.UpdateRoundTripTime(45 * time.Millisecond) // Only 5ms improvement
shouldSwitch := agent.shouldRenominate(pair1, pair2)
assert.False(t, shouldSwitch,
"Should not renominate for RTT improvement < 10ms")
})
t.Run("Should not renominate to same pair", func(t *testing.T) {
pair := newCandidatePair(localHost, remoteHost, true)
pair.state = CandidatePairStateSucceeded
shouldSwitch := agent.shouldRenominate(pair, pair)
assert.False(t, shouldSwitch,
"Should not renominate to the same pair")
})
t.Run("Should not renominate to non-succeeded pair", func(t *testing.T) {
currentPair := newCandidatePair(localHost, remoteHost, true)
currentPair.state = CandidatePairStateSucceeded
candidatePair := newCandidatePair(localHost, remoteHost, true)
candidatePair.state = CandidatePairStateInProgress
shouldSwitch := agent.shouldRenominate(currentPair, candidatePair)
assert.False(t, shouldSwitch,
"Should not renominate to non-succeeded pair")
})
})
t.Run("Find Best Candidate Pair", func(t *testing.T) {
agent, err := NewAgent(&AgentConfig{})
require.NoError(t, err)
defer func() {
require.NoError(t, agent.Close())
}()
// Create candidates
localHost, err := NewCandidateHost(&CandidateHostConfig{
Network: "udp",
Address: "192.168.1.1",
Port: 10000,
Component: 1,
})
require.NoError(t, err)
remoteHost, err := NewCandidateHost(&CandidateHostConfig{
Network: "udp",
Address: "192.168.1.2",
Port: 20000,
Component: 1,
})
require.NoError(t, err)
localRelay, err := NewCandidateRelay(&CandidateRelayConfig{
Network: "udp",
Address: "10.0.0.1",
Port: 30000,
Component: 1,
RelAddr: "192.168.1.1",
RelPort: 10000,
})
require.NoError(t, err)
remoteRelay, err := NewCandidateRelay(&CandidateRelayConfig{
Network: "udp",
Address: "10.0.0.2",
Port: 40000,
Component: 1,
RelAddr: "192.168.1.2",
RelPort: 20000,
})
require.NoError(t, err)
ctx := context.Background()
err = agent.loop.Run(ctx, func(context.Context) {
// Add pairs to checklist
hostPair := agent.addPair(localHost, remoteHost)
hostPair.state = CandidatePairStateSucceeded
hostPair.UpdateRoundTripTime(10 * time.Millisecond)
relayPair := agent.addPair(localRelay, remoteRelay)
relayPair.state = CandidatePairStateSucceeded
relayPair.UpdateRoundTripTime(50 * time.Millisecond)
// Find best should return host pair
best := agent.findBestCandidatePair()
assert.NotNil(t, best)
assert.Equal(t, hostPair, best,
"Best pair should be the host pair with lower latency")
})
require.NoError(t, err)
})
}
func TestAutomaticRenominationIntegration(t *testing.T) { //nolint:cyclop
report := test.CheckRoutines(t)
defer report()
t.Run("Automatic renomination triggers after interval", func(t *testing.T) {
// Create agents with automatic renomination enabled
aAgent, err := NewAgentWithOptions(
WithRenomination(DefaultNominationValueGenerator()),
WithAutomaticRenomination(100*time.Millisecond), // Short interval for testing
)
require.NoError(t, err)
defer func() {
require.NoError(t, aAgent.Close())
}()
bAgent, err := NewAgentWithOptions(
WithRenomination(DefaultNominationValueGenerator()),
)
require.NoError(t, err)
defer func() {
require.NoError(t, bAgent.Close())
}()
// Start gathering candidates
err = aAgent.OnCandidate(func(c Candidate) {
if c != nil {
t.Logf("Agent A gathered candidate: %s", c)
}
})
require.NoError(t, err)
err = bAgent.OnCandidate(func(c Candidate) {
if c != nil {
t.Logf("Agent B gathered candidate: %s", c)
}
})
require.NoError(t, err)
require.NoError(t, aAgent.GatherCandidates())
require.NoError(t, bAgent.GatherCandidates())
// Wait for gathering to complete
time.Sleep(100 * time.Millisecond)
// Exchange credentials
aUfrag, aPwd, err := aAgent.GetLocalUserCredentials()
require.NoError(t, err)
bUfrag, bPwd, err := bAgent.GetLocalUserCredentials()
require.NoError(t, err)
// Get candidates
aCandidates, err := aAgent.GetLocalCandidates()
require.NoError(t, err)
bCandidates, err := bAgent.GetLocalCandidates()
require.NoError(t, err)
// Verify we have candidates
if len(aCandidates) == 0 || len(bCandidates) == 0 {
t.Skip("No candidates gathered, skipping integration test")
}
require.NoError(t, aAgent.startConnectivityChecks(true, bUfrag, bPwd))
require.NoError(t, bAgent.startConnectivityChecks(false, aUfrag, aPwd))
// Exchange candidates
for _, c := range aCandidates {
cpCand, copyErr := c.copy()
require.NoError(t, copyErr)
require.NoError(t, bAgent.AddRemoteCandidate(cpCand))
}
for _, c := range bCandidates {
cpCand, copyErr := c.copy()
require.NoError(t, copyErr)
require.NoError(t, aAgent.AddRemoteCandidate(cpCand))
}
// Wait for initial connection
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Wait for connection on both agents
select {
case <-aAgent.onConnected:
case <-ctx.Done():
require.Fail(t, "Agent A failed to connect")
}
select {
case <-bAgent.onConnected:
case <-ctx.Done():
require.Fail(t, "Agent B failed to connect")
}
// Record initial selected pairs
initialAPair, err := aAgent.GetSelectedCandidatePair()
require.NoError(t, err)
require.NotNil(t, initialAPair)
// Note: In a real scenario, automatic renomination would trigger
// when a better path becomes available (e.g., relay -> direct).
// For this test, we're just verifying the mechanism is in place.
// Wait to see if automatic renomination check runs
// (it should run but may not renominate if no better pair exists)
time.Sleep(200 * time.Millisecond)
// The automatic renomination check should have run at least once
// We can't easily verify renomination occurred without simulating
// network changes, but we can verify the feature is enabled
assert.True(t, aAgent.automaticRenomination)
assert.True(t, aAgent.enableRenomination)
})
}
func TestKeepAliveCandidatesForRenomination(t *testing.T) {
report := test.CheckRoutines(t)
defer report()
// Create test candidates that don't require real network I/O
createTestCandidates := func() (Candidate, Candidate, Candidate) {
local1 := newPingNoIOCand()
local1.candidateBase.networkType = NetworkTypeUDP4
local1.candidateBase.resolvedAddr = &net.UDPAddr{IP: net.ParseIP("192.168.1.1"), Port: 10000}
local2 := newPingNoIOCand()
local2.candidateBase.networkType = NetworkTypeUDP4
local2.candidateBase.resolvedAddr = &net.UDPAddr{IP: net.ParseIP("192.168.1.3"), Port: 10001}
remote := newPingNoIOCand()
remote.candidateBase.networkType = NetworkTypeUDP4
remote.candidateBase.resolvedAddr = &net.UDPAddr{IP: net.ParseIP("192.168.1.2"), Port: 20000}
return local1, local2, remote
}
t.Run("Only pings all candidates when automatic renomination enabled", func(t *testing.T) {
localHost1, localHost2, remoteHost := createTestCandidates()
// Test with automatic renomination DISABLED
agentWithoutAutoRenom := bareAgentForPing()
agentWithoutAutoRenom.log = logging.NewDefaultLoggerFactory().NewLogger("test")
agentWithoutAutoRenom.remoteUfrag = selectionTestRemoteUfrag
agentWithoutAutoRenom.localUfrag = selectionTestLocalUfrag
agentWithoutAutoRenom.remotePwd = selectionTestPassword
agentWithoutAutoRenom.tieBreaker = 1
agentWithoutAutoRenom.isControlling.Store(true)
agentWithoutAutoRenom.setSelector()
// Add pairs - one selected (succeeded) and one alternate (succeeded)
pair1 := agentWithoutAutoRenom.addPair(localHost1, remoteHost)
pair1.state = CandidatePairStateSucceeded
pair1.UpdateRoundTripTime(10 * time.Millisecond)
// Don't set selected pair for the "without renomination" agent
pair2 := agentWithoutAutoRenom.addPair(localHost2, remoteHost)
pair2.state = CandidatePairStateSucceeded
pair2.UpdateRoundTripTime(50 * time.Millisecond)
// keepAliveCandidatesForRenomination should do nothing when automatic renomination is disabled
agentWithoutAutoRenom.keepAliveCandidatesForRenomination()
// Since automatic renomination is off, the function should not ping anything
// We can't easily verify no pings were sent, but we verify the function completes
// Test with automatic renomination ENABLED
agentWithAutoRenom := bareAgentForPing()
agentWithAutoRenom.log = logging.NewDefaultLoggerFactory().NewLogger("test")
agentWithAutoRenom.automaticRenomination = true
agentWithAutoRenom.enableRenomination = true
agentWithAutoRenom.renominationInterval = 100 * time.Millisecond
agentWithAutoRenom.remoteUfrag = selectionTestRemoteUfrag
agentWithAutoRenom.localUfrag = selectionTestLocalUfrag
agentWithAutoRenom.remotePwd = selectionTestPassword
agentWithAutoRenom.tieBreaker = 1
agentWithAutoRenom.isControlling.Store(true)
agentWithAutoRenom.setSelector()
// Add pairs with different states
pair1 = agentWithAutoRenom.addPair(localHost1, remoteHost)
pair1.state = CandidatePairStateSucceeded
pair1.UpdateRoundTripTime(10 * time.Millisecond)
// Don't set selected pair for this test
pair2 = agentWithAutoRenom.addPair(localHost2, remoteHost)
pair2.state = CandidatePairStateSucceeded
pair2.UpdateRoundTripTime(50 * time.Millisecond)
// Call keepAliveCandidatesForRenomination - should ping all pairs
agentWithAutoRenom.keepAliveCandidatesForRenomination()
// Verify both pairs remain in succeeded state (not changed by the function)
assert.Equal(t, CandidatePairStateSucceeded, pair1.state)
assert.Equal(t, CandidatePairStateSucceeded, pair2.state)
})
t.Run("Pings succeeded pairs unlike pingAllCandidates", func(t *testing.T) {
localHost1, localHost2, remoteHost := createTestCandidates()
agent := bareAgentForPing()
agent.log = logging.NewDefaultLoggerFactory().NewLogger("test")
agent.automaticRenomination = true
agent.enableRenomination = true
agent.renominationInterval = 100 * time.Millisecond
agent.remoteUfrag = selectionTestRemoteUfrag
agent.localUfrag = selectionTestLocalUfrag
agent.remotePwd = selectionTestPassword
agent.tieBreaker = 1
agent.isControlling.Store(true)
agent.setSelector()
// Create a pair in succeeded state
pair := agent.addPair(localHost1, remoteHost)
pair.state = CandidatePairStateSucceeded
pair.UpdateRoundTripTime(10 * time.Millisecond)
// Create another pair in succeeded state
pair2 := agent.addPair(localHost2, remoteHost)
pair2.state = CandidatePairStateSucceeded
pair2.UpdateRoundTripTime(50 * time.Millisecond)
// keepAliveCandidatesForRenomination should ping succeeded pairs
// (pingAllCandidates would skip them)
agent.keepAliveCandidatesForRenomination()
// Pairs should still be in succeeded state
assert.Equal(t, CandidatePairStateSucceeded, pair.state)
assert.Equal(t, CandidatePairStateSucceeded, pair2.state)
})
t.Run("Transitions waiting pairs to in-progress", func(t *testing.T) {
localHost1, _, remoteHost := createTestCandidates()