|
| 1 | +import type { PeerUpdate } from "@libp2p/interface"; |
| 2 | +import type { Stream } from "@libp2p/interface/connection"; |
| 3 | +import { Peer } from "@libp2p/interface/peer-store"; |
| 4 | +import { Libp2p } from "@waku/interfaces"; |
| 5 | +import { selectConnection } from "@waku/utils/libp2p"; |
| 6 | +import debug from "debug"; |
| 7 | + |
| 8 | +export class StreamManager { |
| 9 | + private streamPool: Map<string, Promise<Stream>>; |
| 10 | + private log: debug.Debugger; |
| 11 | + |
| 12 | + constructor( |
| 13 | + public multicodec: string, |
| 14 | + public getConnections: Libp2p["getConnections"], |
| 15 | + public addEventListener: Libp2p["addEventListener"] |
| 16 | + ) { |
| 17 | + this.log = debug(`waku:stream-manager:${multicodec}`); |
| 18 | + this.addEventListener( |
| 19 | + "peer:update", |
| 20 | + this.handlePeerUpdateStreamPool.bind(this) |
| 21 | + ); |
| 22 | + this.getStream = this.getStream.bind(this); |
| 23 | + this.streamPool = new Map(); |
| 24 | + } |
| 25 | + |
| 26 | + public async getStream(peer: Peer): Promise<Stream> { |
| 27 | + const peerIdStr = peer.id.toString(); |
| 28 | + const streamPromise = this.streamPool.get(peerIdStr); |
| 29 | + |
| 30 | + if (!streamPromise) { |
| 31 | + return this.newStream(peer); // fallback by creating a new stream on the spot |
| 32 | + } |
| 33 | + |
| 34 | + // We have the stream, let's remove it from the map |
| 35 | + this.streamPool.delete(peerIdStr); |
| 36 | + |
| 37 | + this.prepareNewStream(peer); |
| 38 | + |
| 39 | + const stream = await streamPromise; |
| 40 | + |
| 41 | + if (stream.status === "closed") { |
| 42 | + return this.newStream(peer); // fallback by creating a new stream on the spot |
| 43 | + } |
| 44 | + |
| 45 | + return stream; |
| 46 | + } |
| 47 | + |
| 48 | + private async newStream(peer: Peer): Promise<Stream> { |
| 49 | + const connections = this.getConnections(peer.id); |
| 50 | + const connection = selectConnection(connections); |
| 51 | + if (!connection) { |
| 52 | + throw new Error("Failed to get a connection to the peer"); |
| 53 | + } |
| 54 | + return connection.newStream(this.multicodec); |
| 55 | + } |
| 56 | + |
| 57 | + private prepareNewStream(peer: Peer): void { |
| 58 | + const streamPromise = this.newStream(peer); |
| 59 | + this.streamPool.set(peer.id.toString(), streamPromise); |
| 60 | + } |
| 61 | + |
| 62 | + private handlePeerUpdateStreamPool = (evt: CustomEvent<PeerUpdate>): void => { |
| 63 | + const peer = evt.detail.peer; |
| 64 | + if (peer.protocols.includes(this.multicodec)) { |
| 65 | + this.log(`Optimistically opening a stream to ${peer.id.toString()}`); |
| 66 | + this.prepareNewStream(peer); |
| 67 | + } |
| 68 | + }; |
| 69 | +} |
0 commit comments