324 lines
9.3 KiB
JavaScript
324 lines
9.3 KiB
JavaScript
/**
|
|
* WebRTC host — manages RTCPeerConnection and DataChannel instances
|
|
* on behalf of the WASM module.
|
|
*
|
|
* The WASM side sees channels as integer IDs. This host maps those IDs
|
|
* to browser RTCDataChannel objects and routes events back to WASM via
|
|
* the exported callback functions.
|
|
*/
|
|
|
|
export class WebRTCHost {
|
|
/** @type {Map<number, RTCDataChannel>} channel_id → DataChannel */
|
|
#channels = new Map();
|
|
/** @type {Map<number, boolean>} channelId → true if we created the offer */
|
|
#channelRoles = new Map();
|
|
/** @type {Map<string, RTCPeerConnection>} remote_peer_id → PeerConnection */
|
|
#peerConnections = new Map();
|
|
/** @type {number} next channel ID to assign */
|
|
#nextChannelId = 1;
|
|
/** @type {RTCConfiguration} */
|
|
#rtcConfig;
|
|
/** @type {object | null} WASM exports (set after load) */
|
|
#wasm = null;
|
|
/** @type {number} WASM instance ID */
|
|
#instanceId = 0;
|
|
/** @type {import('./signaling.js').SignalingClient | null} */
|
|
#signaling = null;
|
|
/** @type {Array<(channelId: number, appId: number, payload: Uint8Array) => void>} */
|
|
#directHandlers = [];
|
|
/** Direct message prefix byte — distinguishes from P2P-framed messages */
|
|
static DIRECT_PREFIX = 0xFF;
|
|
|
|
/**
|
|
* @param {RTCConfiguration} [rtcConfig] - ICE server configuration
|
|
*/
|
|
constructor(rtcConfig) {
|
|
this.#rtcConfig = rtcConfig || {
|
|
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Bind to WASM exports so we can call back into the module.
|
|
* @param {object} wasmExports - The WASM module's exports
|
|
* @param {number} instanceId - The P2P instance ID in WASM
|
|
*/
|
|
bind(wasmExports, instanceId) {
|
|
this.#wasm = wasmExports;
|
|
this.#instanceId = instanceId;
|
|
}
|
|
|
|
/**
|
|
* Bind to a signaling client for SDP/ICE exchange.
|
|
* @param {import('./signaling.js').SignalingClient} signaling
|
|
*/
|
|
bindSignaling(signaling) {
|
|
this.#signaling = signaling;
|
|
|
|
signaling.on('offer', (msg) => this.handleOffer(msg.from, msg.sdp));
|
|
signaling.on('answer', (msg) => this.handleAnswer(msg.from, msg.sdp));
|
|
signaling.on('candidate', (msg) =>
|
|
this.handleCandidate(msg.from, msg.candidate, msg.sdpMid)
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Initiate a WebRTC connection to a remote peer.
|
|
* @param {string} remotePeerId - The remote peer's signaling ID
|
|
* @returns {Promise<number>} The channel ID assigned to this connection
|
|
*/
|
|
async connectToPeer(remotePeerId) {
|
|
const pc = this.#createPeerConnection(remotePeerId);
|
|
const dc = pc.createDataChannel('zig-p2p', {
|
|
protocol: 'zig-p2p',
|
|
ordered: true,
|
|
});
|
|
|
|
const channelId = this.#registerChannel(dc);
|
|
this.#channelRoles.set(channelId, true); // outbound = initiator
|
|
this.#setupDataChannel(dc, channelId);
|
|
|
|
const offer = await pc.createOffer();
|
|
await pc.setLocalDescription(offer);
|
|
|
|
this.#signaling?.sendOffer(remotePeerId, pc.localDescription.sdp);
|
|
return channelId;
|
|
}
|
|
|
|
/**
|
|
* Handle an incoming SDP offer from a remote peer.
|
|
* @param {string} fromPeerId
|
|
* @param {string} sdp
|
|
*/
|
|
async handleOffer(fromPeerId, sdp) {
|
|
const pc = this.#createPeerConnection(fromPeerId);
|
|
|
|
pc.ondatachannel = (event) => {
|
|
const dc = event.channel;
|
|
const channelId = this.#registerChannel(dc);
|
|
this.#channelRoles.set(channelId, false); // inbound = responder
|
|
this.#setupDataChannel(dc, channelId);
|
|
};
|
|
|
|
await pc.setRemoteDescription({ type: 'offer', sdp });
|
|
const answer = await pc.createAnswer();
|
|
await pc.setLocalDescription(answer);
|
|
|
|
this.#signaling?.sendAnswer(fromPeerId, pc.localDescription.sdp);
|
|
}
|
|
|
|
/**
|
|
* Handle an incoming SDP answer.
|
|
* @param {string} fromPeerId
|
|
* @param {string} sdp
|
|
*/
|
|
async handleAnswer(fromPeerId, sdp) {
|
|
const pc = this.#peerConnections.get(fromPeerId);
|
|
if (!pc) {
|
|
console.warn('[webrtc] Got answer from unknown peer:', fromPeerId);
|
|
return;
|
|
}
|
|
await pc.setRemoteDescription({ type: 'answer', sdp });
|
|
}
|
|
|
|
/**
|
|
* Handle an incoming ICE candidate.
|
|
* @param {string} fromPeerId
|
|
* @param {string} candidate
|
|
* @param {string} sdpMid
|
|
*/
|
|
async handleCandidate(fromPeerId, candidate, sdpMid) {
|
|
const pc = this.#peerConnections.get(fromPeerId);
|
|
if (!pc) return;
|
|
await pc.addIceCandidate({ candidate, sdpMid });
|
|
}
|
|
|
|
/**
|
|
* Send data on a channel (called by WASM via extern "env").
|
|
* @param {number} channelId
|
|
* @param {Uint8Array} data
|
|
* @returns {number} 0 on success, -1 on error
|
|
*/
|
|
send(channelId, data) {
|
|
const dc = this.#channels.get(channelId);
|
|
if (!dc || dc.readyState !== 'open') return -1;
|
|
try {
|
|
dc.send(data);
|
|
return 0;
|
|
} catch {
|
|
return -1;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Close a channel (called by WASM via extern "env").
|
|
* @param {number} channelId
|
|
*/
|
|
closeChannel(channelId) {
|
|
const dc = this.#channels.get(channelId);
|
|
if (dc) {
|
|
dc.close();
|
|
this.#channels.delete(channelId);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get buffered amount for a channel (called by WASM via extern "env").
|
|
* @param {number} channelId
|
|
* @returns {number}
|
|
*/
|
|
bufferedAmount(channelId) {
|
|
const dc = this.#channels.get(channelId);
|
|
return dc ? dc.bufferedAmount : 0;
|
|
}
|
|
|
|
/** Close all connections and clean up. */
|
|
destroy() {
|
|
for (const dc of this.#channels.values()) {
|
|
dc.close();
|
|
}
|
|
this.#channels.clear();
|
|
this.#channelRoles.clear();
|
|
for (const pc of this.#peerConnections.values()) {
|
|
pc.close();
|
|
}
|
|
this.#peerConnections.clear();
|
|
}
|
|
|
|
/** @returns {number} Number of active channels */
|
|
get channelCount() {
|
|
return this.#channels.size;
|
|
}
|
|
|
|
/** @returns {number[]} All active channel IDs */
|
|
getChannelIds() {
|
|
return [...this.#channels.keys()];
|
|
}
|
|
|
|
/**
|
|
* Get total buffered amount across all channels (for flow control).
|
|
* @returns {number} Sum of all DataChannel bufferedAmount values
|
|
*/
|
|
get totalBufferedAmount() {
|
|
let total = 0;
|
|
for (const dc of this.#channels.values()) {
|
|
total += dc.bufferedAmount;
|
|
}
|
|
return total;
|
|
}
|
|
|
|
/**
|
|
* Send a pre-formatted direct message on a DataChannel.
|
|
* The caller must include the [0xFF][app_id] prefix in the data.
|
|
* This avoids an extra copy for large payloads.
|
|
* @param {number} channelId
|
|
* @param {Uint8Array} data - Complete message including 0xFF prefix
|
|
* @returns {boolean} true on success
|
|
*/
|
|
sendDirect(channelId, data) {
|
|
const dc = this.#channels.get(channelId);
|
|
if (!dc || dc.readyState !== 'open') return false;
|
|
try {
|
|
dc.send(data);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Register a handler for direct messages (0xFF-prefixed).
|
|
* Handler receives (channelId, appId, payload).
|
|
* @param {(channelId: number, appId: number, payload: Uint8Array) => void} handler
|
|
*/
|
|
registerDirectHandler(handler) {
|
|
this.#directHandlers.push(handler);
|
|
}
|
|
|
|
// -- Private helpers --
|
|
|
|
#createPeerConnection(remotePeerId) {
|
|
// Close existing connection to same peer if any
|
|
const existing = this.#peerConnections.get(remotePeerId);
|
|
if (existing) existing.close();
|
|
|
|
const pc = new RTCPeerConnection(this.#rtcConfig);
|
|
this.#peerConnections.set(remotePeerId, pc);
|
|
|
|
pc.onicecandidate = (event) => {
|
|
if (event.candidate) {
|
|
this.#signaling?.sendCandidate(
|
|
remotePeerId,
|
|
event.candidate.candidate,
|
|
event.candidate.sdpMid
|
|
);
|
|
}
|
|
};
|
|
|
|
pc.onconnectionstatechange = () => {
|
|
if (pc.connectionState === 'failed' || pc.connectionState === 'closed') {
|
|
this.#peerConnections.delete(remotePeerId);
|
|
}
|
|
};
|
|
|
|
return pc;
|
|
}
|
|
|
|
#registerChannel(dc) {
|
|
const channelId = this.#nextChannelId++;
|
|
this.#channels.set(channelId, dc);
|
|
return channelId;
|
|
}
|
|
|
|
#setupDataChannel(dc, channelId) {
|
|
dc.binaryType = 'arraybuffer';
|
|
|
|
dc.onopen = () => {
|
|
const isInitiator = this.#channelRoles.get(channelId) ?? false;
|
|
this.#wasm?.wasm_on_datachannel_open(this.#instanceId, channelId, isInitiator ? 1 : 0);
|
|
};
|
|
|
|
dc.onmessage = (event) => {
|
|
const data = new Uint8Array(event.data);
|
|
|
|
// Direct message path: 0xFF prefix → JS handlers only, never enters WASM.
|
|
// This eliminates 3 alloc+copy cycles per message through the WASM stack.
|
|
if (data.length >= 2 && data[0] === WebRTCHost.DIRECT_PREFIX) {
|
|
const appId = data[1];
|
|
const payload = data.subarray(2);
|
|
for (const handler of this.#directHandlers) {
|
|
try { handler(channelId, appId, payload); } catch {}
|
|
}
|
|
return;
|
|
}
|
|
|
|
// P2P-framed message → route through WASM
|
|
if (!this.#wasm) return;
|
|
const ptr = this.#wasm.wasm_alloc(data.length);
|
|
if (!ptr) {
|
|
console.warn('[webrtc] Failed to allocate WASM memory for message');
|
|
return;
|
|
}
|
|
const wasmBuf = new Uint8Array(this.#wasm.memory.buffer, ptr, data.length);
|
|
wasmBuf.set(data);
|
|
this.#wasm.wasm_on_datachannel_message(
|
|
this.#instanceId,
|
|
channelId,
|
|
ptr,
|
|
data.length
|
|
);
|
|
this.#wasm.wasm_free(ptr, data.length);
|
|
};
|
|
|
|
dc.onclose = () => {
|
|
this.#wasm?.wasm_on_datachannel_close(this.#instanceId, channelId);
|
|
this.#channels.delete(channelId);
|
|
this.#channelRoles.delete(channelId);
|
|
};
|
|
|
|
dc.onerror = () => {
|
|
this.#wasm?.wasm_on_datachannel_error(this.#instanceId, channelId);
|
|
};
|
|
}
|
|
}
|