fix: write peer stream messages atomically #484
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.
The sink passed to a libp2p stream will have chunks pulled from it when the previous chunk has read by the underlying transport. This allows the transport to apply backpressure all the way up to the application level without libp2p needing to buffer application data which can be very memory-intensive.
The batch-message writing in #344 introduces a second pushable queue to peer streams - messages from both queues are written to the underlying stream in parallel, removing any guarantees of order or consistency.
Notably if we are writing a
Uint8ArrayList
made of multipleUint8Array
s, the underlying transport will pull the arrays one at a time to avoid a memory copy, if the stream is written to in parallel all bets are off in regard to the order in which the arrays will be sent over the wire.This manifests itself as the remote failing to read a message because the message length is too long - it's read some random garbage from the middle of another message as a varint representing the length of the current message.
The change here is to combine the prefixed and non-prefixed pushable streams with
it-merge
, allowing the messages to be pulled in a predictable way and preserving the ability of the underlying transport to apply backpressure.Also updates all deps to reduce duplication in web bundles.
Notably
multiformats@13
is the TypeScript port and@libp2p/crypto@4
has dropped thenode-forge
dependency.This drops the bundle size from around
132KB
to85KB
Refs: