Skip to content

Commit

Permalink
Wait for cleanup on certexchange server shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
Stebalien committed Jul 8, 2024
1 parent 3b6ea9e commit 9ecbcc0
Showing 1 changed file with 34 additions and 3 deletions.
37 changes: 34 additions & 3 deletions certexchange/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"runtime/debug"
"sync"
"time"

"github.com/filecoin-project/go-f3/certstore"
Expand All @@ -28,7 +29,8 @@ type Server struct {
Host host.Host
Store *certstore.Store

cancel context.CancelFunc
runningLk sync.RWMutex
stopFunc context.CancelFunc
}

func (s *Server) withDeadline(ctx context.Context) (context.Context, context.CancelFunc) {
Expand Down Expand Up @@ -111,9 +113,22 @@ func (s *Server) handleRequest(ctx context.Context, stream network.Stream) (_err

// Start the server.
func (s *Server) Start() error {
s.runningLk.Lock()
defer s.runningLk.Unlock()
if s.stopFunc != nil {
return fmt.Errorf("certificate exchange already running")
}

ctx, cancel := context.WithCancel(context.Background())
s.cancel = cancel
s.stopFunc = cancel
s.Host.SetStreamHandler(FetchProtocolName(s.NetworkName), func(stream network.Stream) {
s.runningLk.RLock()
defer s.runningLk.RUnlock()
if s.stopFunc == nil {
_ = stream.Reset()
return
}

ctx, cancel := s.withDeadline(ctx)
defer cancel()

Expand All @@ -129,7 +144,23 @@ func (s *Server) Start() error {

// Stop the server.
func (s *Server) Stop() error {
// Ask the handlers to cancel/stop.
s.runningLk.RLock()
cancel := s.stopFunc
s.runningLk.RUnlock()
if cancel == nil {
return nil
}
cancel()

// Wait and finish shutdown.
s.runningLk.Lock()
defer s.runningLk.Unlock()
if s.stopFunc == nil {
return nil
}
s.stopFunc = nil
s.Host.RemoveStreamHandler(FetchProtocolName(s.NetworkName))
s.cancel()

return nil
}

0 comments on commit 9ecbcc0

Please sign in to comment.