@statewalker/webrun-streams-signaling
v0.5.2
Published
Generic P2P signaling/connection-setup (PeerManager, QrSignaling, RoomManager) yielding ByteChannels
Readme
@statewalker/webrun-streams-signaling
What it is
Connection-setup helpers for peer-to-peer links. Each one runs a handshake and hands back an
established ByteChannel (send / recv / closed / close, declared by this package).
PeerManager runs WebRTC offer/answer/ICE over a signaling transport you supply; QrSignaling
pairs two devices without a server by exchanging compact QR strings; RoomManager joins a
LiveKit-style room and opens a channel per participant. What runs on the channel afterwards —
typically webrun-rpc's port stack, through messageTargetOverByteChannel — is up to you.
Why it exists
Every peer-to-peer transport needs the same preliminary step: find the peer, exchange session
descriptions and ICE candidates, and wait for a data channel to open. That step is separate from
moving bytes. This package does only that step and stops at a ByteChannel, so any byte protocol
can run on the result. It contains no signaling server (STUN/TURN/rendezvous); these are clients.
Vendor code stays out of the import graph: native WebRTC is reached through an injectable factory
and LiveKit through a structural RoomLike interface and a roomFactory, so the package can be
tested with in-memory mocks and livekit-client is only needed if you use RoomManager.
How to use
pnpm add @statewalker/webrun-streams-signaling
# only for RoomManager:
pnpm add livekit-clientlivekit-client (^2.18.3) is an optional peer dependency; the package never imports it, you
pass () => new Room(). One entry point, ., ESM only. It targets browsers: it uses
RTCPeerConnection (unless you inject rtc), crypto.getRandomValues, btoa / atob. In Node,
pass an rtc factory from a WebRTC implementation.
Exports
| Export | Purpose |
| --- | --- |
| new PeerManager(signaling, options?) | WebRTC connections keyed by peer id over a SignalingTransport. connect(peerId): Promise<ByteChannel>, onConnection((peerId, ch) => void): () => void, close(). |
| PeerManagerOptions | WebRtcConnectionOptions plus onError?: (error, peerId) => void, called when a connection fails with no caller to tell (a signal it rejects, an inbound channel that never opens). |
| new QrSignaling(options?) | Serverless pairing. offer(): Promise<{ qr, accept(answerQr): Promise<ByteChannel> }>, answer(offerQr): Promise<{ qr, channel }>, getSessionId(). |
| QrSignalingOptions | { sessionId?: string; connection?: WebRtcConnectionOptions }. |
| new RoomManager(options: RoomManagerOptions) | Room membership. join(room), participants(): AsyncIterable<string>, channelTo(peerId, options?): Promise<ByteChannel> (a byteChannelFromRoom channel), leave(). |
| new PeerConnection(role, options?) | One WebRTC connection's lifecycle, which PeerManager and QrSignaling build on. connect(), handleSignal(msg), open(): Promise<ByteChannel>, waitForIceGathering(), getLocalDescription(), getCollectedCandidates(), getState(), getRole(), hasRemoteDescription(), getDataChannel(), on / off, close(). |
| byteChannelFromDataChannel(dc) | Wrap an RTCDataChannel as a ByteChannel, with the data channel's bufferedAmount and a whenDrained() that waits for bufferedamountlow. |
| byteChannelFromRoom(room, peerId, options?) | A ByteChannel to one participant of a RoomLike, on its own data topic (options.topic, default DEFAULT_ROOM_TOPIC). It closes when the room disconnects, the participant leaves, the peer's channel closes, a reliable publish fails, or a send exceeds options.maxFrameBytes (default DEFAULT_ROOM_MAX_FRAME_BYTES), so whatever runs on it learns the other end is gone. Packets and goodbye follow webrun-streams-livekit's conventions. |
| ByteChannelFromRoomOptions | { topic?: string; maxFrameBytes?: number }. |
| DEFAULT_ROOM_TOPIC, DEFAULT_ROOM_MAX_FRAME_BYTES | "webrun/port-stack" and 64_000, the same defaults as webrun-streams-livekit. |
| messageTargetOverByteChannel(channel, options?) | A ByteChannel as { target, signal, maxMessageSize } for webrun-rpc's overPipe: a MessageTarget of bytes, a signal aborted when the channel closes, and the payload ceiling (DEFAULT_MAX_MESSAGE_SIZE, 16 KiB − 256, what every browser pair delivers over a data channel; pass maxMessageSize: 12 * 1024 for a byteChannelFromRoom channel). target also has the channel's bufferedAmount and whenDrained(), so overPipe with frameSize paces its frames by the transport. It must be the channel's only reader. |
| DRAIN_LOW_WATER | 256 * 1024. The channels' whenDrained() resolves once bufferedAmount is at most this. |
| ByteChannel | The channel type: send, recv, closed, close, and optional bufferedAmount / whenDrained(). It used to come from @statewalker/webrun-streams; it is declared here since emulateMux was removed. |
| generateSessionId(), createCompressedSignal(...), parseCompressedSignal(signal), encodeSignal(signal), decodeSignal(text) | The pure QR payload functions. |
Types and constants: SignalingTransport (localId, send(to, msg),
onMessage(handler): () => void), SignalingMessage (offer / answer / candidate /
ready), SessionDescription, IceCandidate, PeerRole, ConnectionState,
PeerConnectionEvents (stateChange, signal, open, close, error),
WebRtcConnectionOptions, RtcPeerConnectionFactory, DEFAULT_ICE_SERVERS (two Google STUN
servers), CompressedSignal, RoomLike, RoomParticipantLike, RoomLocalParticipantLike,
RoomManagerOptions (url, getToken(room), roomFactory), ROOM_EVENT (the four LiveKit
event names used), ParticipantInfo (exported, not used by any API here).
WebRtcConnectionOptions:
| option | default | meaning |
| --- | --- | --- |
| iceServers | DEFAULT_ICE_SERVERS | ICE servers. |
| connectionTimeout | 30000 ms | How long open() waits for the data channel (for QrSignaling's initiator, from accept). |
| iceGatheringTimeout | 5000 ms | How long QrSignaling waits for ICE gathering before using what it has. |
| channelLabel | "webrun-data" | Data channel label. |
| ordered | true | Ordered delivery. |
| maxRetransmits | unset | Retransmit limit for unreliable mode. |
| rtc | new RTCPeerConnection(config) | Factory for the peer connection. |
Examples
PeerManager: dial a peer over your signaling channel, then multiplex
The SignalingTransport below is an in-memory bus, so both peers run in one page; in an
application it wraps your WebSocket or other rendezvous channel.
import { msgpackCodec } from "@statewalker/webrun-msgpack";
import { connect, overPipe, serve } from "@statewalker/webrun-rpc";
import {
messageTargetOverByteChannel,
PeerManager,
type SignalingMessage,
type SignalingTransport,
} from "@statewalker/webrun-streams-signaling";
function signalingBus() {
const handlers = new Map<string, (from: string, msg: SignalingMessage) => void>();
return (localId: string): SignalingTransport => ({
localId,
send: (to, msg) => queueMicrotask(() => handlers.get(to)?.(localId, msg)),
onMessage(handler) {
handlers.set(localId, handler);
return () => handlers.delete(localId);
},
});
}
const bus = signalingBus();
const a = new PeerManager(bus("A"));
const b = new PeerManager(bus("B"));
b.onConnection((peerId, channel) => {
const { target, signal, maxMessageSize } = messageTargetOverByteChannel(channel);
void serve(
{ mux: overPipe(target, { codec: msgpackCodec, side: "responder", signal, maxMessageSize }) },
async function* echo(input) {
for await (const chunk of input) yield chunk;
},
);
});
const pipe = messageTargetOverByteChannel(await a.connect("B"));
const { call, close } = await connect({
mux: overPipe(pipe.target, {
codec: msgpackCodec,
side: "initiator",
signal: pipe.signal,
maxMessageSize: pipe.maxMessageSize,
}),
});
for await (const chunk of call([new TextEncoder().encode("ping")])) {
console.log(new TextDecoder().decode(chunk)); // "ping"
}
await close();
a.close();
b.close();QrSignaling: pair two devices without a server
import { QrSignaling } from "@statewalker/webrun-streams-signaling";
// Device A
const deviceA = new QrSignaling();
const { qr: offerQr, accept } = await deviceA.offer(); // show offerQr as a QR code
// Device B, after scanning offerQr
const deviceB = new QrSignaling();
const { qr: answerQr, channel: channelB } = await deviceB.answer(offerQr); // show answerQr
// Device A, after scanning answerQr
const channelA = await accept(answerQr);This flow does not currently complete against a real WebRTC stack; see
What answer() waits for.
RoomManager: one channel per participant
import { Room } from "livekit-client";
import { RoomManager } from "@statewalker/webrun-streams-signaling";
const rooms = new RoomManager({
url: "wss://livekit.example.com",
getToken: (room) => fetch(`/token?room=${room}`).then((r) => r.text()),
roomFactory: () => new Room(),
});
await rooms.join("room1");
for await (const peerId of rooms.participants()) {
const channel = await rooms.channelTo(peerId);
channel.send(new Uint8Array([5, 5]));
}
// participants() does not end until leave() is calledInternals
SignalingTransport / QR strings / LiveKit room (you provide)
│ offer, answer, ICE candidates
▼
PeerConnection ── RTCPeerConnection (or your `rtc` factory)
│ data channel opens
▼
ByteChannel ── send / recv / closed / close
│
▼
the port stack (messageTargetOverByteChannel) or any byte protocol (you run)How PeerManager routes signals
Each peer id maps to one PeerConnection. connect(peerId) creates an initiator, creates the
data channel and offer, and resolves when the channel opens. An inbound offer from an unknown
peer creates a responder; onConnection handlers are called when its channel opens. Answers and
candidates from unknown peers are ignored. Candidates that arrive before the remote description
is set are queued and applied after it. When ICE gathering completes, a { type: "ready" }
signal is sent; receivers ignore it. A connection is closed and forgotten when its data channel
closes, when its state becomes failed or closed, when its channel does not open, or when it
rejects a signal; the peer's next offer then starts a new responder. A connection makes one
offer, so a new offer from a peer means it started over (for example it reloaded before ICE
reported a failure here): if this side answered that peer before, or dialed it and already applied
its answer, the old connection is closed and the offer starts a new responder at once. An offer
to a connection that is still waiting for its answer is glare: both dials fail (reported through
onError on this side) and must be retried. connect(peerId) replaces any existing connection to
that peer.
What answer() waits for
QrSignaling sends everything in one payload: it waits for ICE gathering (up to
iceGatheringTimeout), then packs the SDP and all gathered candidates. offer() returns the
offer QR and an accept that applies the answer. answer(), however, awaits the responder's data
channel before it returns the answer QR. With a real WebRTC stack that channel opens only after
the initiator has applied the answer, which needs the answer QR. So answer() rejects with
Connection timeout after <connectionTimeout>ms instead of returning, and the flow in the example
above does not complete. The test suite uses a mock RTCPeerConnection that opens the channel as
soon as both descriptions are set on one side, so it does not exercise this ordering.
offer() does not wait for its channel: accept does, so connectionTimeout counts from
accept, not from the offer, and the people scanning the codes can take as long as they need.
If applying the answer fails, accept closes the connection and rejects.
How QR payloads stay small
createCompressedSignal keeps only the SDP lines needed to connect (v=, o=, s=, t=,
m=, c=, a=group:, a=ice-ufrag:, a=ice-pwd:, a=fingerprint:, a=setup:, a=mid:,
a=sctp-port:, a=max-message-size:) and packs each candidate into a |-separated string,
dropping the attributes after typ. A candidate that carries raddr, rport or tcptype (a
srflx, relay or TCP candidate) is kept raw instead, prefixed R:, with only those attributes, and
so is a candidate that does not parse. A null sdpMLineIndex travels as an empty field, so 0
stays 0. encodeSignal is URL-safe base64 of the
JSON, without padding. parseCompressedSignal throws Unsupported protocol version: <v> for any
version other than 1, and a malformed packed candidate throws
Invalid compressed candidate: <text>.
How the channels behave
- Both channels buffer inbound bytes from the moment they are created, so data that arrives
before your
for awaitstarts is not lost. byteChannelFromDataChannelsetsbinaryType = "arraybuffer"and copies every inbound payload. A non-byte message (a string) ends the channel, as does asendthat throws (a closed channel, or Chrome's full 16 MiB send queue): either way the stream above lost a message.closedresolves on the data channel'scloseevent or onclose(); asendafter that is ignored. It setsbufferedAmountLowThresholdtoDRAIN_LOW_WATER;whenDrained()resolves onbufferedamountlowor when the channel ends.messageTargetOverByteChannel'swhenDrained()is the channel's, and resolves at once over a channel without one or once the pipe has ended.byteChannelFromRoompublishes withreliable: truetodestinationIdentities: [peerId]on its topic, and acceptsdataReceivedevents from that participant on that topic only; packets with no participant, from anyone else, or on another topic are ignored, so several channels to one participant can share a room on different topics. It ends when the room disconnects, the participant leaves, a reliable publish fails, asendexceedsmaxFrameBytes(thatsendthrowsRangeError), or the peer's goodbye arrives. When it ends on this side (close(), an oversizedsend, a failed publish) it publishes an empty goodbye on<topic>/close, the same convention aswebrun-streams-livekit'sCLOSE_TOPIC, so the peer's channel ends although the room stays connected. The topic, goodbye and frame ceiling matchmessageTargetOverLiveKit's defaults, so the port stack over this channel talks to one over that adapter.bufferedAmountcounts bytes whose publish has not settled;whenDrained()resolves once that is at mostDRAIN_LOW_WATER.
What RoomManager tracks
participants() yields the identities already in the room when join returns, then each one
that joins, and ends at leave(). Departures are not reported. Only the most recently created
participants() iterator receives new joiners. channelTo() before join() throws
channelTo() before join().
Failure modes
PeerConnection.open()rejects withConnection timeout after <n>ms, with the data channel's error, or withConnection failedwhen the connection state becomesfailed.connect()on a responder throwsconnect() should only be called by initiator; an offer to an initiator throwsReceived offer but not in responder role; an answer to a responder throwsReceived answer but not in initiator role.PeerManager: a failedconnect()rejects and forgets the connection. A failure with no caller (an offer during glare, malformed SDP or candidates, an inbound channel that never opens) closes and forgets the connection and goes toonError; withoutonErrorit is dropped. Either wayonConnectionis not called for it.PeerConnection.open()also rejects withConnection closed before the data channel openedwhen the connection is closed first.
Dependencies
One runtime dependency, @statewalker/webrun-streams at runtime, for newMessagePipe: the pipe module every transport adapter shares (listeners, delivery, life, the byte check, the frame ceiling, drain, close), so a pipe rule is fixed once for all of them (#151). The target is a MessageTarget by shape and carries its own closeSignal and maxMessageSize, so overPipe(target, { codec, side }) needs nothing else. ByteChannel is declared here, and messageTargetOverByteChannel
takes an optional maxFrameBytes.
@statewalker/webrun-rpc, -msgpack and -streams-conformance are dev dependencies of the tests:
tests/conformance.test.ts runs the conformance suite over messageTargetOverByteChannel and the
port stack, on byteChannelFromDataChannel and on byteChannelFromRoom (in-process stand-ins for
the data channel and the room). livekit-client is an optional peer, used only through the
RoomLike shape you inject. A neutrality test (tests/neutrality.test.ts) keeps the source from
importing anything else.
License
MIT
