From fe624a6abfc55cc3efe9ed0050a7d1c26c2a5070 Mon Sep 17 00:00:00 2001 From: Marten Seemann Date: Sun, 9 Jan 2022 15:29:48 +0400 Subject: [PATCH] respect the context when opening a new stream in the base host --- p2p/host/blank/blank_host.go | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/p2p/host/blank/blank_host.go b/p2p/host/blank/blank_host.go index 09cc99e9d3..62380adefd 100644 --- a/p2p/host/blank/blank_host.go +++ b/p2p/host/blank/blank_host.go @@ -203,10 +203,24 @@ func (h *BaseHost) NewStream(ctx context.Context, p peer.ID, protos ...protocol. return nil, err } - selected, err := msmux.SelectOneOf(protocol.ConvertToStrings(protos), s) - if err != nil { + // Negotiate the protocol in the background, obeying the context. + var selected string + errCh := make(chan error, 1) + go func() { + selected, err = msmux.SelectOneOf(protocol.ConvertToStrings(protos), s) + errCh <- err + }() + select { + case err = <-errCh: + if err != nil { + s.Reset() + return nil, err + } + case <-ctx.Done(): s.Reset() - return nil, err + // wait for `SelectOneOf` to error out because of resetting the stream. + <-errCh + return nil, ctx.Err() } selpid := protocol.ID(selected)