ChainSafe / js-libp2p-gossipsub

TypeScript implementation of Gossipsub
Apache License 2.0
151 stars 43 forks source link

fix: write peer stream messages atomically #484

Closed achingbrain closed 9 months ago

achingbrain commented 9 months ago

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 multiple Uint8Arrays, 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 the node-forge dependency.

This drops the bundle size from around 132KB to 85KB

Refs:

wemeetagain commented 9 months ago

The e2e tests are consistently failing :thinking:

codecov-commenter commented 9 months ago

Codecov Report

Attention: 1 lines in your changes are missing coverage. Please review.

Comparison is base (b77e6ca) 81.36% compared to head (ca2ab09) 81.40%. Report is 1 commits behind head on master.

Files Patch % Lines
test/utils/msgId.ts 50.00% 1 Missing :warning:
Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #484 +/- ## ========================================== + Coverage 81.36% 81.40% +0.03% ========================================== Files 48 48 Lines 12321 12325 +4 Branches 1301 1301 ========================================== + Hits 10025 10033 +8 + Misses 2296 2292 -4 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.