UNPKG

@libp2p/floodsub

Version:

libp2p-floodsub, also known as pubsub-flood or just dumbsub, this implementation of pubsub focused on delivering an API for Publish/Subscribe, but with no CastTree Forming (it just floods the network).

78 lines 2.33 kB
import { pbStream } from '@libp2p/utils'; import { TypedEventEmitter } from 'main-event'; import { RPC } from "./message/rpc.js"; /** * Thin wrapper around a peer's inbound / outbound pubsub streams */ export class PeerStreams extends TypedEventEmitter { peerId; /** * An AbortController for controlled shutdown of the inbound stream */ shutDownController; // messages sent by the remote inboundPb; // messages we send outboundPb; constructor(peerId) { super(); this.peerId = peerId; this.shutDownController = new AbortController(); } attachInboundStream(stream, streamOpts) { this.inboundPb = pbStream(stream, streamOpts).pb(RPC); Promise.resolve().then(async () => { while (true) { if (this.inboundPb == null) { return; } const message = await this.inboundPb.read({ signal: this.shutDownController.signal }); this.safeDispatchEvent('message', { detail: message }); } }) .catch(err => { this.inboundPb?.unwrap().unwrap().abort(err); }); } attachOutboundStream(stream, streamOpts) { this.outboundPb = pbStream(stream, streamOpts).pb(RPC); } /** * Send a message to this peer */ write(message) { if (this.outboundPb == null) { return; } this.outboundPb.write(message, { signal: this.shutDownController.signal }) .catch(err => { this.outboundPb?.unwrap().unwrap().abort(err); }); } /** * Closes the open connection to peer */ close() { this.shutDownController.abort(); Promise.all([ this.inboundPb?.unwrap().unwrap().close() .catch(err => { this.inboundPb?.unwrap().unwrap().abort(err); }), this.outboundPb?.unwrap().unwrap().close() .catch(err => { this.inboundPb?.unwrap().unwrap().abort(err); }) ]) .finally(() => { this.safeDispatchEvent('close'); }); } } //# sourceMappingURL=peer-streams.js.map