/** * @file The client peer (`zig-out/bin/client.wasm`) driven over a canister's * `start` and `deliver` update calls. */ const { freeze } = Object; const decoder = new TextDecoder(); const encoder = new TextEncoder(); /** * @typedef {(method: 'start' | 'deliver', frames: Uint8Array) => Promise} Carry * one update call: the frames out, the frames in the reply */ /** * Instantiate the client peer and open a session to `canisterId`. * * @param {object} io * @param {WebAssembly.Module} io.module the compiled client.wasm * @param {Uint8Array} io.seed 64 bytes of fresh entropy * @param {Carry} io.carry * @param {string} canisterId the canister's principal, as text */ export const openPeer = async ({ module, seed, carry }, canisterId) => { const { exports: wasm } = await WebAssembly.instantiate(module, { env: { report: (ptr, len) => console.error(readText(ptr, len)) }, }); const memory = () => new Uint8Array(wasm.memory.buffer); const readText = (ptr, len) => decoder.decode(memory().slice(ptr, ptr + len)); /** Copy `bytes` into wasm memory for the length of `fn`. */ const withBytes = (bytes, fn) => { const ptr = wasm.client_alloc(bytes.length || 1); memory().set(bytes, ptr); try { return fn(ptr, bytes.length); } finally { wasm.client_free(ptr, bytes.length || 1); } }; const staged = () => memory().slice(wasm.client_out_ptr(), wasm.client_out_ptr() + wasm.client_out_len()); const check = (status, what) => { if (status !== 0) throw Error(`${what}: ${decoder.decode(staged())}`); }; /** * Carry staged frames until the canister has nothing more to say. The * first call of a session is `start`. */ let method = 'start'; const pump = async () => { for (;;) { const frames = staged(); if (frames.length === 0) return; const reply = await carry(method, frames); method = 'deliver'; check(withBytes(reply, wasm.client_feed), 'feed'); check(wasm.client_outbound(), 'outbound'); } }; check(withBytes(seed, wasm.client_init), 'init'); check(withBytes(encoder.encode(canisterId), wasm.client_dial), 'dial'); await pump(); if (!wasm.client_session_open()) throw Error('session did not open'); const slotOf = (status, what) => { if (status < 0) throw Error(`${what}: ${decoder.decode(staged())}`); return status; }; /** Stage what the Host queued, then carry it until the canister is quiet. */ const flush = async () => { check(wasm.client_outbound(), 'outbound'); await pump(); }; /** Read a settled answer, or throw. */ const valueOf = slot => { const kind = wasm.client_result_kind(slot); if (kind === 0) throw Error(`answer ${slot} still pending after the canister went quiet`); if (kind === 3) { check(wasm.client_result_broken(slot), 'broken'); throw Error(`answer ${slot} broke: ${decoder.decode(staged())}`); } if (kind === 4) return undefined; return kind === 2 ? Number(wasm.client_result_integer(slot)) : { slot }; }; /** * An answer: what `fetch` or `send` will settle to. Sends can target one * before it settles; nothing crosses the wire until `flush`. * * @typedef {{ slot: number }} Answer */ return freeze({ /** @returns {Answer} the capability published as `name` */ fetch: name => ({ slot: slotOf(withBytes(encoder.encode(name), (p, n) => wasm.client_fetch(p, n)), 'fetch') }), /** * Send `verb` to `target`, without waiting for it to settle. * * @param {Answer} target * @param {string} verb * @param {...(string | bigint | Answer)} args strings, integers, and * answers that have settled to references * @returns {Answer} `target`'s answer */ send: (target, verb, ...args) => { for (const arg of args) { if (typeof arg === 'string') check(withBytes(encoder.encode(arg), wasm.client_arg_text), 'argument'); else if (typeof arg === 'bigint') check(wasm.client_arg_integer(arg), 'argument'); else check(wasm.client_arg_reference(arg.slot), 'argument'); } const status = withBytes(encoder.encode(verb), (p, n) => wasm.client_send(target.slot, p, n)); return { slot: slotOf(status, 'send') }; }, flush, /** @param {Answer} answer */ valueOf: answer => valueOf(answer.slot), }); };