Skip to content

Commit

Permalink
fix: ensure proper cleanup of cache fallback iter
Browse files Browse the repository at this point in the history
  • Loading branch information
2color committed Dec 16, 2024
1 parent 41922af commit 06cef21
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion server_cached_router.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,14 +123,22 @@ type cacheFallbackIter struct {
// It's a bit complex because it ensures we continue iterating without blocking on the FindPeers call.
func NewCacheFallbackIter(sourceIter iter.ResultIter[types.Record], router cachedRouter, ctx context.Context) *cacheFallbackIter {
ctx, cancel := context.WithCancel(ctx)
return &cacheFallbackIter{
iter := &cacheFallbackIter{
sourceIter: sourceIter,
router: router,
ctx: ctx,
cancel: cancel,
findPeersResult: make(chan types.PeerRecord),
ongoingLookups: atomic.Int32{},
}

// Add a goroutine to handle context cancellation
go func() {
<-ctx.Done()
iter.Close()
}()

return iter
}

func (it *cacheFallbackIter) Next() bool {
Expand Down Expand Up @@ -203,6 +211,11 @@ func (it *cacheFallbackIter) dispatchFindPeer(record types.PeerRecord) {

peersIt, err := it.router.FindPeers(ctx, *record.ID, 1)

// Check if the parent context is done before sending
if it.ctx.Err() != nil {
return // Exit early if the parent context is done
}

if err != nil {
it.findPeersResult <- record // pass back the record with no addrs
return
Expand Down

0 comments on commit 06cef21

Please sign in to comment.