holepunch-hop
Version:
data interface to HOP
46 lines (34 loc) • 2.14 kB
Markdown
# Plan: Upgrade Network Messaging to Protomux
The current implementation uses raw TCP-like streams from Hyperswarm, which are subject to fragmentation. This causes `JSON.parse` to fail when a partial JSON chunk is received. We will transition to using **Protomux** to handle message framing and parsing.
## Proposed Changes
### 1. Update Imports
- Add `import Protomux from 'protomux'`
- Add `import c from 'compact-encoding'`
### 2. Track Peer Channels
- Add `this.peerChannels = new Map()` to the `NetworkPeers` constructor in `src/network/peers.js`.
- This map will store the Protomux message objects for each peer.
### 3. Initialize Protomux in `listenNetwork`
- In `listenNetwork`, for every new connection:
- Initialize a Protomux instance: `const mux = Protomux.from(conn)`.
- Create a dedicated channel: `const channel = mux.createChannel({ protocol: 'holepunch-hop' })`.
- Add a JSON message type to the channel.
- Set the `onmessage` handler to `this.assessData(publicKey, msg)`.
- Store the message sender in `this.peerChannels`.
- Open the channel.
- Remove the raw `conn.on('data', ...)` listener.
### 4. Refactor `assessData`
- Modify `assessData` to handle the already-parsed JSON object.
- Keep support for `Buffer` input to ensure backward compatibility or handle edge cases.
### 5. Update Write Methods
- Update all methods that write to the network (`writeTonetwork`, `writeTonetworkTopic`, etc.):
- Use `this.peerChannels.get(publickey).send(data)` instead of `this.peerConnect[publickey].write(JSON.stringify(data))`.
- Add checks to ensure the channel exists before sending.
### 6. Cleanup
- Ensure channels are removed from `this.peerChannels` when a connection is closed or errors.
## Verification Plan
### Automated Tests
- Run existing tests: `npm test`.
- Verify that `ECONNRESET` and `SyntaxError` (from partial JSON) are no longer occurring during high-traffic or large-payload tests.
### Manual Verification
- Check logs for any Protomux-related errors.
- Ensure all message types (`private-chart`, `private-cue-space`, etc.) are still correctly handled in `assessData`.