54
54
domain* : Domain
55
55
numThreads: int
56
56
loggers: seq [Logger ]
57
- reusePort* : Option [bool ]
58
- # when false, will fail if --threads is passed or if 2
59
- # processes bind to same address/port. We use an Option to avoid
60
- # breaking code that relies on `Settings(port: port)`
57
+ reusePort: bool
58
+ # # controlls whether to fail with "Address already in use".
59
+ # # This is currently ignored if multiple threads are spawned.
61
60
62
61
HttpBeastDefect * = ref object of Defect
63
62
@@ -67,14 +66,15 @@ const
67
66
proc initSettings * (port: Port = Port (8080 ),
68
67
bindAddr: string = " " ,
69
68
numThreads: int = 0 ,
70
- domain = Domain .AF_INET , reusePort = true ): Settings =
69
+ domain = Domain .AF_INET ,
70
+ reusePort = false ): Settings =
71
71
Settings (
72
72
port: port,
73
73
bindAddr: bindAddr,
74
74
domain: domain,
75
75
numThreads: numThreads,
76
76
loggers: getHandlers (),
77
- reusePort: some ( reusePort) ,
77
+ reusePort: reusePort,
78
78
)
79
79
80
80
proc initData (fdKind: FdKind , ip = " " ): Data =
@@ -321,7 +321,7 @@ proc eventLoop(params: (OnRequest, Settings)) =
321
321
322
322
let server = newSocket (settings.domain)
323
323
server.setSockOpt (OptReuseAddr , true )
324
- server.setSockOpt (OptReusePort , settings.reusePort. get ( true ) )
324
+ server.setSockOpt (OptReusePort , settings.reusePort)
325
325
server.bindAddr (settings.port, settings.bindAddr)
326
326
server.listen ()
327
327
server.getFd ().setBlocking (false )
@@ -477,8 +477,13 @@ proc run*(onRequest: OnRequest, settings: Settings) =
477
477
when compileOption (" threads" ):
478
478
var threads = newSeq [Thread [(OnRequest , Settings )]](numThreads)
479
479
for i in 0 ..< numThreads:
480
+ var settings2 = settings
481
+ if numThreads > 1 : settings2.reusePort = true
482
+ # TODO : in future work, we can honor `reusePort = false` by
483
+ # attempting to bind to the port, and then on success spawn the threads
484
+ # with `reusePort = false`.
480
485
createThread [(OnRequest , Settings )](
481
- threads[i], eventLoop, (onRequest, settings )
486
+ threads[i], eventLoop, (onRequest, settings2 )
482
487
)
483
488
echo (" Listening on port " , settings.port) # This line is used in the tester to signal readiness.
484
489
joinThreads (threads)
0 commit comments