@@ -12,6 +12,7 @@ import (
1212 "go.sia.tech/core/consensus"
1313 rhp4 "go.sia.tech/core/rhp/v4"
1414 "go.sia.tech/core/types"
15+ "go.sia.tech/coreutils/threadgroup"
1516 "go.sia.tech/coreutils/wallet"
1617 "go.sia.tech/mux/v2"
1718 "go.uber.org/zap"
@@ -128,6 +129,8 @@ type (
128129
129130 // A Server handles incoming RHP4 RPC.
130131 Server struct {
132+ tg * threadgroup.ThreadGroup
133+
131134 hostKey types.PrivateKey
132135 priceTableValidity time.Duration
133136 rpcTimeout time.Duration
@@ -1216,6 +1219,11 @@ func (s *Server) HostKey() types.PrivateKey {
12161219 return s .hostKey
12171220}
12181221
1222+ // Close stops accepting new RPCs and waits for in-flight handlers to complete.
1223+ func (s * Server ) Close () {
1224+ s .tg .Stop ()
1225+ }
1226+
12191227// Serve accepts incoming streams on the provided multiplexer and handles them
12201228func (s * Server ) Serve (t TransportMux , log * zap.Logger ) error {
12211229 defer t .Close ()
@@ -1230,6 +1238,14 @@ func (s *Server) Serve(t TransportMux, log *zap.Logger) error {
12301238 log := log .With (zap .String ("streamID" , hex .EncodeToString (frand .Bytes (4 ))))
12311239 log .Debug ("accepted stream" )
12321240 go func () {
1241+ done , err := s .tg .Add ()
1242+ if err != nil {
1243+ log .Debug ("rejected stream, server is shutting down" )
1244+ rhp4 .WriteResponse (stream , rhp4 .ErrHostShuttingDown .(* rhp4.RPCError ))
1245+ stream .Close ()
1246+ return
1247+ }
1248+ defer done ()
12331249 defer func () {
12341250 if err := stream .Close (); err != nil {
12351251 log .Debug ("failed to close stream" , zap .Error (err ))
@@ -1255,6 +1271,8 @@ func errorDecodingError(f string, p ...any) error {
12551271// NewServer creates a new RHP4 server
12561272func NewServer (pk types.PrivateKey , cm ChainManager , contracts Contractor , wallet Wallet , settings Settings , sectors Sectors , opts ... ServerOption ) * Server {
12571273 s := & Server {
1274+ tg : threadgroup .New (),
1275+
12581276 hostKey : pk ,
12591277 priceTableValidity : 30 * time .Minute ,
12601278 rpcTimeout : 10 * time .Minute ,
0 commit comments