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 a06809b commit 1213a2b
Showing 1 changed file with 37 additions and 3 deletions.
40 changes: 37 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,25 @@ 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")

Check warning on line 119 in certexchange/server.go

View check run for this annotation

Codecov / codecov/patch

certexchange/server.go#L119

Added line #L119 was not covered by tests
}

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

Check warning on line 129 in certexchange/server.go

View check run for this annotation

Codecov / codecov/patch

certexchange/server.go#L128-L129

Added lines #L128 - L129 were not covered by tests
}

// Kill the stream if/when we shutdown the server.
defer context.AfterFunc(ctx, func() { _ = stream.Reset() })()

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

Expand All @@ -129,7 +147,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

Check warning on line 163 in certexchange/server.go

View check run for this annotation

Codecov / codecov/patch

certexchange/server.go#L163

Added line #L163 was not covered by tests
}
s.stopFunc = nil
s.Host.RemoveStreamHandler(FetchProtocolName(s.NetworkName))
s.cancel()

return nil
}

0 comments on commit 1213a2b

Please sign in to comment.