fix: abort async operations #3152
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Some async operations do not accept an abort signal. This means calling code can fail to abort a long-running operation if the abort signal fires it's "abort" event while execution is suspended.
For example in the following code the signal can fire while the directory is being created and this code would be none the wiser:
Instead we need to check if the signal is aborted before starting the async operation (to prevent doing needless work), and after, in case it aborted while the onward call was happening.
This still waits for the operation to complete before checking the signal to see if it has been aborted. Instead we can use
raceSignal
to throw immediately, though the operation will continue in the background.Synchronous operations have a similar problem when they are able to return optional promises, since the result may be awaited on. In this case we still need to check if the signal was aborted, though we only need to do it once.
This PR applies the above patterns to
@libp2p/crypto
keys,@libp2p/peer-store
operations and@libp2p/kad-dht
to ensure the.provide
and.findProviders
operations can be successfully aborted.