add WASM browser module and browser demo
This commit is contained in:
461
browser/host/zig-p2p.js
Normal file
461
browser/host/zig-p2p.js
Normal file
@@ -0,0 +1,461 @@
|
||||
/**
|
||||
* zig-p2p Browser Host
|
||||
*
|
||||
* Loads the WASM module, provides platform APIs, and manages WebRTC
|
||||
* connections. The entire P2P protocol (Noise, DHT, messaging, wire
|
||||
* envelope) runs inside WASM — this is a thin glue layer.
|
||||
*
|
||||
* Usage:
|
||||
* import { ZigP2P } from './zig-p2p.js';
|
||||
*
|
||||
* const p2p = await ZigP2P.load('/zig-p2p.wasm', {
|
||||
* signalingUrl: 'ws://localhost:8080',
|
||||
* iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
|
||||
* });
|
||||
*
|
||||
* p2p.onMessage((peerId, appId, data) => { ... });
|
||||
* await p2p.connectToPeer('remote-peer-id');
|
||||
* p2p.send(peerId, 0x03, new Uint8Array([1, 2, 3]));
|
||||
*/
|
||||
|
||||
import { createPlatformEnv } from './platform-env.js';
|
||||
import { WebRTCHost } from './webrtc-host.js';
|
||||
import { SignalingClient } from './signaling.js';
|
||||
import { FileHost } from './file-host.js';
|
||||
|
||||
export class ZigP2P {
|
||||
/** @type {WebAssembly.Instance} */
|
||||
#wasmInstance;
|
||||
/** @type {WebAssembly.Memory} */
|
||||
#memory;
|
||||
/** @type {object} WASM exports */
|
||||
#exports;
|
||||
/** @type {number} WASM P2P instance ID */
|
||||
#instanceId;
|
||||
/** @type {WebRTCHost} */
|
||||
#webrtcHost;
|
||||
/** @type {SignalingClient} */
|
||||
#signaling;
|
||||
/** @type {number | null} update interval handle */
|
||||
#updateTimer = null;
|
||||
/** @type {Function[]} message handlers */
|
||||
#messageHandlers = [];
|
||||
/** @type {Function[]} connection handlers */
|
||||
#connectionHandlers = [];
|
||||
/** @type {Function[]} file event handlers */
|
||||
#fileEventHandlers = [];
|
||||
/** @type {FileHost} */
|
||||
#fileHost;
|
||||
/** @type {boolean} */
|
||||
#destroyed = false;
|
||||
/** @type {number} WASM pointer for event polling buffer */
|
||||
#eventBufPtr = 0;
|
||||
/** @type {number} */
|
||||
#eventBufLen = 0;
|
||||
/** @type {Map<number, number>} channelId → channelId (identity, for reverse lookup from peerId) */
|
||||
#peerIdToChannel = new Map(); // peerId hex → channelId
|
||||
|
||||
/**
|
||||
* Load the WASM module and initialize the P2P library.
|
||||
*
|
||||
* @param {string | URL | ArrayBuffer} wasmSource - URL to .wasm file, or raw bytes
|
||||
* @param {object} config
|
||||
* @param {string} config.signalingUrl - WebSocket URL of the signaling server
|
||||
* @param {string} [config.peerId] - Peer ID for signaling (random if not set)
|
||||
* @param {number} [config.listenPort=0] - Port (unused in browser, passed to WASM init)
|
||||
* @param {RTCConfiguration} [config.rtcConfig] - WebRTC ICE configuration
|
||||
* @param {number} [config.updateIntervalMs=16] - How often to call wasm_p2p_update
|
||||
* @returns {Promise<ZigP2P>}
|
||||
*/
|
||||
static async load(wasmSource, config) {
|
||||
const instance = new ZigP2P();
|
||||
await instance.#init(wasmSource, config);
|
||||
return instance;
|
||||
}
|
||||
|
||||
async #init(wasmSource, config) {
|
||||
const {
|
||||
signalingUrl,
|
||||
peerId = crypto.randomUUID(),
|
||||
listenPort = 0,
|
||||
rtcConfig,
|
||||
updateIntervalMs = 16,
|
||||
} = config;
|
||||
|
||||
// 1. Create WebRTC host and file host
|
||||
this.#webrtcHost = new WebRTCHost(rtcConfig);
|
||||
let memory;
|
||||
this.#fileHost = new FileHost(() => memory);
|
||||
|
||||
// 2. Create platform env with WebRTC + file wiring
|
||||
const env = {
|
||||
...createPlatformEnv(() => memory),
|
||||
...this.#fileHost.getEnvBindings(),
|
||||
};
|
||||
|
||||
// Wire datachannel extern "env" functions to the WebRTC host
|
||||
env.js_datachannel_send = (channelId, dataPtr, dataLen) => {
|
||||
const data = new Uint8Array(memory.buffer, dataPtr, dataLen);
|
||||
return this.#webrtcHost.send(channelId, data);
|
||||
};
|
||||
env.js_datachannel_close = (channelId) => {
|
||||
this.#webrtcHost.closeChannel(channelId);
|
||||
};
|
||||
env.js_datachannel_buffered_amount = (channelId) => {
|
||||
return this.#webrtcHost.bufferedAmount(channelId);
|
||||
};
|
||||
|
||||
// 3. Load WASM module
|
||||
let wasmBytes;
|
||||
if (wasmSource instanceof ArrayBuffer) {
|
||||
wasmBytes = wasmSource;
|
||||
} else {
|
||||
const response = await fetch(wasmSource);
|
||||
wasmBytes = await response.arrayBuffer();
|
||||
}
|
||||
|
||||
const { instance } = await WebAssembly.instantiate(wasmBytes, { env });
|
||||
this.#wasmInstance = instance;
|
||||
this.#exports = instance.exports;
|
||||
memory = instance.exports.memory;
|
||||
this.#memory = memory;
|
||||
|
||||
// 4. Initialize P2P instance in WASM
|
||||
this.#instanceId = this.#exports.wasm_p2p_init(listenPort);
|
||||
if (this.#instanceId < 0) {
|
||||
throw new Error('Failed to initialize P2P instance in WASM');
|
||||
}
|
||||
|
||||
// 5. Bind WebRTC host to WASM exports
|
||||
this.#webrtcHost.bind(
|
||||
{ ...this.#exports, memory: this.#memory },
|
||||
this.#instanceId
|
||||
);
|
||||
|
||||
// 6. Connect to signaling server
|
||||
this.#signaling = new SignalingClient(signalingUrl, peerId);
|
||||
this.#webrtcHost.bindSignaling(this.#signaling);
|
||||
await this.#signaling.connect();
|
||||
|
||||
// 7. Allocate event polling buffer (reused every tick)
|
||||
// 2MB to support large file chunks (up to 1MB+ per message)
|
||||
this.#eventBufPtr = this.#exports.wasm_alloc(2097152);
|
||||
this.#eventBufLen = 2097152;
|
||||
|
||||
// 8. Start update loop
|
||||
this.#updateTimer = setInterval(() => {
|
||||
if (!this.#destroyed) {
|
||||
this.#exports.wasm_p2p_update(this.#instanceId);
|
||||
this.#drainEvents();
|
||||
}
|
||||
}, updateIntervalMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to a remote peer via WebRTC (through signaling server).
|
||||
* @param {string} remotePeerId - The remote peer's signaling ID
|
||||
* @returns {Promise<number>} Channel ID
|
||||
*/
|
||||
async connectToPeer(remotePeerId) {
|
||||
return this.#webrtcHost.connectToPeer(remotePeerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the 32-byte P2P PeerId for a given WebRTC channel.
|
||||
* @param {number} channelId - The WebRTC channel ID
|
||||
* @returns {Uint8Array | null} 32-byte PeerId, or null on failure
|
||||
*/
|
||||
getPeerIdForChannel(channelId) {
|
||||
if (this.#destroyed) return null;
|
||||
const outPtr = this.#exports.wasm_alloc(32);
|
||||
if (!outPtr) return null;
|
||||
try {
|
||||
const result = this.#exports.wasm_get_peer_id_for_channel(
|
||||
this.#instanceId,
|
||||
channelId,
|
||||
outPtr
|
||||
);
|
||||
if (result !== 0) return null;
|
||||
const bytes = new Uint8Array(32);
|
||||
bytes.set(new Uint8Array(this.#memory.buffer, outPtr, 32));
|
||||
return bytes;
|
||||
} finally {
|
||||
this.#exports.wasm_free(outPtr, 32);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message to a peer.
|
||||
* @param {Uint8Array} peerId - 32-byte peer ID
|
||||
* @param {number} appId - Application ID byte
|
||||
* @param {Uint8Array} data - Message payload
|
||||
* @returns {boolean} true on success
|
||||
*/
|
||||
send(peerId, appId, data) {
|
||||
if (this.#destroyed) return false;
|
||||
|
||||
// Allocate WASM memory for peer ID + data
|
||||
const peerPtr = this.#exports.wasm_alloc(peerId.length);
|
||||
const dataPtr = this.#exports.wasm_alloc(data.length);
|
||||
if (!peerPtr || !dataPtr) return false;
|
||||
|
||||
try {
|
||||
new Uint8Array(this.#memory.buffer, peerPtr, peerId.length).set(peerId);
|
||||
new Uint8Array(this.#memory.buffer, dataPtr, data.length).set(data);
|
||||
const result = this.#exports.wasm_p2p_send(
|
||||
this.#instanceId,
|
||||
peerPtr,
|
||||
appId,
|
||||
dataPtr,
|
||||
data.length
|
||||
);
|
||||
return result === 0;
|
||||
} finally {
|
||||
this.#exports.wasm_free(peerPtr, peerId.length);
|
||||
this.#exports.wasm_free(dataPtr, data.length);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a message handler.
|
||||
* @param {(peerId: Uint8Array, appId: number, data: Uint8Array) => void} handler
|
||||
*/
|
||||
onMessage(handler) {
|
||||
this.#messageHandlers.push(handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a connection handler.
|
||||
* @param {(peerId: string, channelId: number) => void} handler
|
||||
*/
|
||||
onConnection(handler) {
|
||||
this.#connectionHandlers.push(handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a pre-formatted direct message on a DataChannel, bypassing WASM.
|
||||
* The data must include the [0xFF][app_id] prefix. Use for high-throughput
|
||||
* data (file chunks) where WASM alloc/copy overhead is wasteful.
|
||||
* @param {number} channelId - The WebRTC channel ID
|
||||
* @param {Uint8Array} data - Complete message including 0xFF prefix
|
||||
* @returns {boolean} true on success
|
||||
*/
|
||||
sendDirect(channelId, data) {
|
||||
if (this.#destroyed) return false;
|
||||
return this.#webrtcHost.sendDirect(channelId, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a handler for direct messages (bypasses WASM).
|
||||
* @param {(channelId: number, appId: number, payload: Uint8Array) => void} handler
|
||||
*/
|
||||
onDirectMessage(handler) {
|
||||
this.#webrtcHost.registerDirectHandler(handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all active channel IDs.
|
||||
* @returns {number[]}
|
||||
*/
|
||||
getChannelIds() {
|
||||
return this.#webrtcHost.getChannelIds();
|
||||
}
|
||||
|
||||
/** @returns {number} Library version from WASM */
|
||||
get version() {
|
||||
return this.#exports.wasm_version();
|
||||
}
|
||||
|
||||
/** @returns {string} This peer's signaling ID */
|
||||
get peerId() {
|
||||
return this.#signaling.peerId;
|
||||
}
|
||||
|
||||
/** @returns {boolean} Whether connected to signaling server */
|
||||
get signalingConnected() {
|
||||
return this.#signaling.connected;
|
||||
}
|
||||
|
||||
/** @returns {number} Number of active WebRTC channels */
|
||||
get channelCount() {
|
||||
return this.#webrtcHost.channelCount;
|
||||
}
|
||||
|
||||
/** @returns {number} Total buffered bytes across all DataChannels (for flow control) */
|
||||
get totalBufferedAmount() {
|
||||
return this.#webrtcHost.totalBufferedAmount;
|
||||
}
|
||||
|
||||
/** Drain pending events from the WASM P2P event queue. */
|
||||
#drainEvents() {
|
||||
if (!this.#eventBufPtr) return;
|
||||
for (let i = 0; i < 4096; i++) {
|
||||
const n = this.#exports.wasm_poll_event(
|
||||
this.#instanceId,
|
||||
this.#eventBufPtr,
|
||||
this.#eventBufLen
|
||||
);
|
||||
if (n <= 0) break;
|
||||
|
||||
const buf = new Uint8Array(this.#memory.buffer, this.#eventBufPtr, n);
|
||||
const eventType = buf[0];
|
||||
|
||||
if (eventType === 1 && n >= 34) {
|
||||
// message_received: [1][app_id:1][peer_id:32][data:N]
|
||||
const appId = buf[1];
|
||||
const peerId = new Uint8Array(buf.slice(2, 34));
|
||||
const data = new Uint8Array(buf.slice(34, n));
|
||||
for (const handler of this.#messageHandlers) {
|
||||
try { handler(peerId, appId, data); } catch {}
|
||||
}
|
||||
} else if (eventType === 2 && n >= 33) {
|
||||
// peer_connected: [2][peer_id:32]
|
||||
const peerId = new Uint8Array(buf.slice(1, 33));
|
||||
const peerHex = Array.from(peerId.slice(0, 8))
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
for (const handler of this.#connectionHandlers) {
|
||||
try { handler(peerHex, 0); } catch {}
|
||||
}
|
||||
}
|
||||
// type 3 (peer_disconnected) — not wired yet
|
||||
else if (eventType === 4 && n >= 13) {
|
||||
// file_shared: [4][session_id:8 LE][path_len:4 LE][path:N]
|
||||
const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n);
|
||||
const sessionId = view.getBigUint64(1, true);
|
||||
const pathLen = view.getUint32(9, true);
|
||||
const path = new TextDecoder().decode(buf.slice(13, 13 + pathLen));
|
||||
for (const handler of this.#fileEventHandlers) {
|
||||
try { handler({ type: 'shared', sessionId, path }); } catch {}
|
||||
}
|
||||
} else if (eventType === 5 && n >= 13) {
|
||||
// file_download_started: [5][session_id:8 LE][name_len:4 LE][name:N]
|
||||
const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n);
|
||||
const sessionId = view.getBigUint64(1, true);
|
||||
const nameLen = view.getUint32(9, true);
|
||||
const name = new TextDecoder().decode(buf.slice(13, 13 + nameLen));
|
||||
for (const handler of this.#fileEventHandlers) {
|
||||
try { handler({ type: 'download_started', sessionId, name }); } catch {}
|
||||
}
|
||||
} else if (eventType === 6 && n >= 9) {
|
||||
// file_download_completed: [6][session_id:8 LE]
|
||||
const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n);
|
||||
const sessionId = view.getBigUint64(1, true);
|
||||
for (const handler of this.#fileEventHandlers) {
|
||||
try { handler({ type: 'download_completed', sessionId }); } catch {}
|
||||
}
|
||||
} else if (eventType === 7 && n >= 9) {
|
||||
// file_download_failed: [7][session_id:8 LE]
|
||||
const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n);
|
||||
const sessionId = view.getBigUint64(1, true);
|
||||
for (const handler of this.#fileEventHandlers) {
|
||||
try { handler({ type: 'download_failed', sessionId }); } catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// File Transfer API
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* Register a file event handler.
|
||||
* @param {(event: { type: string, sessionId: bigint, path?: string, name?: string }) => void} handler
|
||||
*/
|
||||
onFileEvent(handler) {
|
||||
this.#fileEventHandlers.push(handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Share a file with connected peers.
|
||||
*
|
||||
* For small files (<50MB): materializes into WASM memory and registers
|
||||
* with the Zig file manager (full hashing + session management).
|
||||
*
|
||||
* For large files: registers the File handle for streaming JS-level
|
||||
* transfer (no WASM hashing, no full memory copy).
|
||||
*
|
||||
* @param {File} file - Browser File object to share
|
||||
* @returns {Promise<{ virtualPath: string, size: number }>}
|
||||
*/
|
||||
async shareFile(file) {
|
||||
if (this.#destroyed) throw new Error('Instance destroyed');
|
||||
|
||||
const MATERIALIZE_THRESHOLD = 50 * 1024 * 1024; // 50MB
|
||||
const virtualPath = this.#fileHost.registerBrowserFile(file);
|
||||
|
||||
if (file.size <= MATERIALIZE_THRESHOLD) {
|
||||
// Small file: materialize and register with WASM file manager
|
||||
await this.#fileHost.materializeFile(virtualPath);
|
||||
const pathBytes = new TextEncoder().encode(virtualPath);
|
||||
const pathPtr = this.#exports.wasm_alloc(pathBytes.length);
|
||||
if (!pathPtr) throw new Error('WASM alloc failed');
|
||||
|
||||
try {
|
||||
new Uint8Array(this.#memory.buffer, pathPtr, pathBytes.length).set(pathBytes);
|
||||
const sessionId = this.#exports.wasm_file_share(
|
||||
this.#instanceId,
|
||||
pathPtr,
|
||||
pathBytes.length
|
||||
);
|
||||
// wasm_file_share returns -1n (i64) on error; valid session IDs are
|
||||
// u64 values that may appear negative in signed BigInt when > 2^63.
|
||||
if (sessionId === -1n) throw new Error('Failed to share file');
|
||||
} finally {
|
||||
this.#exports.wasm_free(pathPtr, pathBytes.length);
|
||||
}
|
||||
}
|
||||
// Large files: File handle is stored in FileHost for streaming reads.
|
||||
// The JS-level transfer (demo.js) reads via fileHost.readFileChunk().
|
||||
|
||||
return { virtualPath, size: file.size };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a completed download as a Blob for saving.
|
||||
* @param {string} name - File name (virtual path)
|
||||
* @returns {Blob | null}
|
||||
*/
|
||||
getDownloadBlob(name) {
|
||||
return this.#fileHost.getFileBlob(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a browser download for a completed file.
|
||||
* @param {string} name - File name
|
||||
*/
|
||||
downloadToDesktop(name) {
|
||||
const blob = this.#fileHost.getFileBlob(name);
|
||||
if (!blob) return;
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = name;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
/** @returns {FileHost} The file host for advanced use */
|
||||
get fileHost() {
|
||||
return this.#fileHost;
|
||||
}
|
||||
|
||||
/** Shut down everything. */
|
||||
destroy() {
|
||||
this.#destroyed = true;
|
||||
if (this.#updateTimer !== null) {
|
||||
clearInterval(this.#updateTimer);
|
||||
this.#updateTimer = null;
|
||||
}
|
||||
this.#webrtcHost.destroy();
|
||||
this.#signaling.disconnect();
|
||||
if (this.#instanceId >= 0) {
|
||||
this.#exports.wasm_p2p_deinit(this.#instanceId);
|
||||
}
|
||||
if (this.#eventBufPtr) {
|
||||
this.#exports.wasm_free(this.#eventBufPtr, this.#eventBufLen);
|
||||
this.#eventBufPtr = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user