fix(ci): make NewRandPort thread-safe (#10921)
* chore: disable AutoTLS in TCP-only transport tests Tests were failing intermittently. Disabling AutoTLS when WebSocket transport is disabled appears to resolve the issue. * fix: make NewRandPort thread-safe Track allocated ports globally to prevent conflicts when tests run in parallel.
Marcin Rataj committed
Aug 18, 2025 at 22:12 UTC
4bafb22b7638de4f3dcd61f992f6724e75f648c4
2 files changed
+33
-7
test/cli/harness/peering.go
+31
-7
@@ -4,6 +4,7 @@ import (
4
"fmt"
5
"math/rand"
6
"net"
7
+ "sync"
8
"testing"
9
10
"github.com/ipfs/kubo/config"
@@ -14,16 +15,39 @@ type Peering struct {
15
To int
16
}
17
18
+var (
19
+ allocatedPorts = make(map[int]struct{})
20
+ portMutex sync.Mutex
21
+)
22
+
23
func NewRandPort() int {
18
- if a, err := net.ResolveTCPAddr("tcp", "localhost:0"); err == nil {
19
- var l *net.TCPListener
20
- if l, err = net.ListenTCP("tcp", a); err == nil {
21
- defer l.Close()
22
- return l.Addr().(*net.TCPAddr).Port
24
+ portMutex.Lock()
25
+ defer portMutex.Unlock()
26
+
27
+ for i := 0; i < 100; i++ {
28
+ l, err := net.Listen("tcp", "localhost:0")
29
+ if err != nil {
30
+ continue
31
+ }
32
+ port := l.Addr().(*net.TCPAddr).Port
33
+ l.Close()
34
+
35
+ if _, used := allocatedPorts[port]; !used {
36
+ allocatedPorts[port] = struct{}{}
37
+ return port
38
}
39
}
25
- n := rand.Int()
26
- return 3000 + (n % 1000)
40
+
41
+ // Fallback to random port if we can't get a unique one from the OS
42
+ for i := 0; i < 1000; i++ {
43
+ port := 30000 + rand.Intn(10000)
44
+ if _, used := allocatedPorts[port]; !used {
45
+ allocatedPorts[port] = struct{}{}
46
+ return port
47
+ }
48
+ }
49
+
50
+ panic("failed to allocate unique port after 1100 attempts")
51
}
52
53
func CreatePeerNodes(t *testing.T, n int, peerings []Peering) (*Harness, Nodes) {
test/cli/transports_test.go
+2
@@ -62,6 +62,8 @@ func TestTransports(t *testing.T) {
62
cfg.Swarm.Transports.Network.WebTransport = config.False
63
cfg.Swarm.Transports.Network.WebRTCDirect = config.False
64
cfg.Swarm.Transports.Network.Websocket = config.False
65
+ // Disable AutoTLS since we're disabling WebSocket transport
66
+ cfg.AutoTLS.Enabled = config.False
67
})
68
})
69
disableRouting(nodes)