Files
captoys/client/connect.js
dckc 6c437ec2f1 feat: abandonAll, explicitly, instead of replacing a session on start
Ending a session breaks every reference and pending answer that lives
only in it, so it takes its own update method rather than happening as
a side effect of start. A second start traps again; the clients take
--abandon-all to end the session a previous run left open.

Generated-by: Claude Code (claude-opus-5-5)
2026-11-18 06:43:15 -06:00

67 lines
2.4 KiB
JavaScript

/**
* @file Open a CapTP session to the canister as the principal of a key file.
*/
import { readFile, writeFile } from 'node:fs/promises';
import { HttpAgent, Actor } from '@icp-sdk/core/agent';
import { Ed25519KeyIdentity } from '@icp-sdk/core/identity';
import { openPeer } from './peer.js';
/** The Candid interface in counter.did. */
const idlFactory = ({ IDL }) => {
const Frames = IDL.Vec(IDL.Nat8);
return IDL.Service({
start: IDL.Func([Frames], [Frames], []),
deliver: IDL.Func([Frames], [Frames], []),
abandonAll: IDL.Func([], [], []),
});
};
/** The seed in `path`, or a fresh one written there. */
const keySeed = async path => {
try {
return new Uint8Array(await readFile(path));
} catch (err) {
if (err.code !== 'ENOENT') throw err;
const seed = crypto.getRandomValues(new Uint8Array(32));
await writeFile(path, seed, { mode: 0o600, flag: 'wx' });
return seed;
}
};
/**
* Open a session to `canisterId` at `host` as the principal whose Ed25519
* seed is in `keyFile` (32 bytes, made if missing), logging each update call.
*
* @param {string} host the replica, e.g. https://icp-api.io
* @param {string} canisterId
* @param {string} keyFile
* @param {object} [opts]
* @param {boolean} [opts.abandonAll] first end the principal's open session,
* breaking every reference and pending answer that lives only in it
*/
export const connect = async (host, canisterId, keyFile, { abandonAll = false } = {}) => {
const { hostname } = new URL(host);
const agent = await HttpAgent.create({
host,
identity: Ed25519KeyIdentity.generate(await keySeed(keyFile)),
// A local replica's root key is its own; mainnet's is built in.
shouldFetchRootKey: hostname === '127.0.0.1' || hostname === 'localhost',
});
const actor = Actor.createActor(idlFactory, { agent, canisterId });
if (abandonAll) {
await actor.abandonAll();
console.error(' abandoned the previous session');
}
const carry = async (method, frames) => {
const t0 = performance.now();
const reply = await actor[method](frames);
console.error(` ${method} ${frames.length}B -> ${reply.length}B in ${Math.round(performance.now() - t0)}ms`);
return reply;
};
const module = await WebAssembly.compile(
await readFile(new URL('../zig-out/bin/client.wasm', import.meta.url)),
);
const seed = crypto.getRandomValues(new Uint8Array(64));
return openPeer({ module, seed, carry }, canisterId);
};