feat(client): pipeline sends on the fetch's answer

Sends target an answer before it settles (Host.vowSend), so the fetch
and every send cross in one update call. Add icp.yaml for icp-cli, the
successor to dfx.

Generated-by: Claude Code (claude-opus-5-5)
This commit is contained in:
dckc committed 2026-11-18 05:53:10 -06:00
1 parent 1177fc86b6
commit da6c3f02ce
7 files changed
+197 -58

No files matched your search

+1
View File
@@ -3,3 +3,4 @@ zig-out/
zig-pkg/ zig-pkg/
.dfx/ .dfx/
node_modules/ node_modules/
.icp/
+9 -7
View File
@@ -4,8 +4,9 @@
*/ */
const HELP = `usage: counter.mjs HOST CANISTER_ID [VERB...] const HELP = `usage: counter.mjs HOST CANISTER_ID [VERB...]
Open a CapTP session to the canister, fetch "counter", and send each VERB Open a CapTP session to the canister, fetch "counter", and send it each
(incr, decr, value; default: incr incr decr), printing each answer. VERB (incr, decr, value; default: incr incr decr) without waiting for the
fetch, then print each answer.
HOST is the replica, e.g. http://127.0.0.1:4959, or https://icp-api.io. HOST is the replica, e.g. http://127.0.0.1:4959, or https://icp-api.io.
A fresh Ed25519 identity makes each run its own caller, so its own session.`; A fresh Ed25519 identity makes each run its own caller, so its own session.`;
@@ -51,11 +52,12 @@ const main = async ([host, canisterId, ...verbs]) => {
const peer = await openPeer({ module, seed, carry }, canisterId); const peer = await openPeer({ module, seed, carry }, canisterId);
console.log('session open'); console.log('session open');
await peer.fetch('counter'); // Pipelined: the sends target the fetch's answer before it settles, so
console.log('fetched counter'); // the fetch and every send cross in one update call.
for (const verb of verbs.length ? verbs : ['incr', 'incr', 'decr']) { const counter = peer.fetch('counter');
console.log(verb, await peer.send(verb)); const answers = (verbs.length ? verbs : ['incr', 'incr', 'decr']).map(verb => [verb, peer.send(counter, verb)]);
} await peer.flush();
for (const [verb, answer] of answers) console.log(verb, peer.valueOf(answer));
}; };
main(process.argv.slice(2)).catch(err => { main(process.argv.slice(2)).catch(err => {
+94
View File
@@ -7,6 +7,9 @@
"name": "icp-ocapn-counter-client", "name": "icp-ocapn-counter-client",
"dependencies": { "dependencies": {
"@icp-sdk/core": "6.1.1" "@icp-sdk/core": "6.1.1"
},
"devDependencies": {
"@icp-sdk/icp-cli": "1.8.0"
} }
}, },
"node_modules/@dfinity/cbor": { "node_modules/@dfinity/cbor": {
@@ -29,6 +32,97 @@
"asn1js": "^3.0.7" "asn1js": "^3.0.7"
} }
}, },
"node_modules/@icp-sdk/icp-cli": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli/-/icp-cli-1.8.0.tgz",
"integrity": "sha512-5wdTxakBoYKqCVvApwlEgZZat9Y0qPxvrPVO31eAem2IO3+Xu3gn/k4EAHb9K9DTfCKyJ+Ll2O8Nm5GEPUldpQ==",
"dev": true,
"hasInstallScript": true,
"license": "Apache-2.0",
"bin": {
"icp": "bin/icp.js"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"@icp-sdk/icp-cli-darwin-arm64": "1.8.0",
"@icp-sdk/icp-cli-darwin-x64": "1.8.0",
"@icp-sdk/icp-cli-linux-arm64": "1.8.0",
"@icp-sdk/icp-cli-linux-x64": "1.8.0",
"@icp-sdk/icp-cli-win32-x64": "1.8.0"
}
},
"node_modules/@icp-sdk/icp-cli-darwin-arm64": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-darwin-arm64/-/icp-cli-darwin-arm64-1.8.0.tgz",
"integrity": "sha512-4RO/r1p1h74wuePwat0vMPfYagzFO2CiYmAR33ZnrPfo22aGVcdwldpePZYBV8egjq7BMnI2LPY3UVLVHnSing==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
]
},
"node_modules/@icp-sdk/icp-cli-darwin-x64": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-darwin-x64/-/icp-cli-darwin-x64-1.8.0.tgz",
"integrity": "sha512-+/MDaDmleZ43kY14dvMHGxxSIW7Z+brccSqy6Vr+CwvRWqJcDG6QzwYXqk+owgLcmTrF11vufMhZbWN7n/yv0g==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
]
},
"node_modules/@icp-sdk/icp-cli-linux-arm64": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-linux-arm64/-/icp-cli-linux-arm64-1.8.0.tgz",
"integrity": "sha512-E/unBg0Kh8jfdf9IWVdbTP5FeMMtnQSDo1Cw+qb1WfX0lYYsFndS6bLW4KujKloETPKBwUPrH9gGc2AjDDhlKQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@icp-sdk/icp-cli-linux-x64": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-linux-x64/-/icp-cli-linux-x64-1.8.0.tgz",
"integrity": "sha512-f6NSdFIrr2eSmNe0JjQWedaiRkJWqCTbaS6GjZFbPtRnd52Eb+Ichrom2zmx/4CZ/DW71BfU9iE8D+OFTDsyow==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@icp-sdk/icp-cli-win32-x64": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-win32-x64/-/icp-cli-win32-x64-1.8.0.tgz",
"integrity": "sha512-4x3JZwLljFNK67c3ClYDbluE2Lw98q5pE+Jomn0wq8MqGV/UqtQHdKeWqB73NWdeaeuGar3Hl15i81gxJJXAGg==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"win32"
]
},
"node_modules/@noble/curves": { "node_modules/@noble/curves": {
"version": "2.4.0", "version": "2.4.0",
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz", "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz",
+3
View File
@@ -4,5 +4,8 @@
"type": "module", "type": "module",
"dependencies": { "dependencies": {
"@icp-sdk/core": "6.1.1" "@icp-sdk/core": "6.1.1"
},
"devDependencies": {
"@icp-sdk/icp-cli": "1.8.0"
} }
} }
+30 -18
View File
@@ -65,27 +65,39 @@ export const openPeer = async ({ module, seed, carry }, canisterId) => {
await pump(); await pump();
if (!wasm.client_session_open()) throw Error('session did not open'); if (!wasm.client_session_open()) throw Error('session did not open');
/** Wait for the pending call's answer, carrying frames as needed. */ const slotOf = (status, what) => {
const settle = async () => { 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(); await pump();
const kind = wasm.client_result_kind(); };
if (kind === 0) throw Error('no answer after the canister went quiet'); /** Read a settled answer, or throw. */
if (kind === 3) throw Error('broken'); const valueOf = slot => {
return kind; const kind = wasm.client_result_kind(slot);
if (kind === 0) throw Error(`answer ${slot} still pending after the canister went quiet`);
if (kind === 3) throw Error(`answer ${slot} broke`);
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({ return freeze({
/** Fetch the capability published as `name` and make it the target. */ /** @returns {Answer} the capability published as `name` */
async fetch(name) { fetch: name => ({ slot: slotOf(withBytes(encoder.encode(name), (p, n) => wasm.client_fetch(p, n)), 'fetch') }),
check(withBytes(encoder.encode(name), wasm.client_fetch), 'fetch'); /** @returns {Answer} `target`'s answer to `verb` */
await settle(); send: (target, verb) => ({
check(wasm.client_adopt(), 'adopt'); slot: slotOf(withBytes(encoder.encode(verb), (p, n) => wasm.client_send(target.slot, p, n)), 'send'),
}, }),
/** Send `verb` to the target; resolve to its integer answer. */ flush,
async send(verb) { /** @param {Answer} answer */
check(withBytes(encoder.encode(verb), wasm.client_send), 'send'); valueOf: answer => valueOf(answer.slot),
await settle();
return Number(wasm.client_result_integer());
},
}); });
}; };
+15
View File
@@ -0,0 +1,15 @@
canisters:
- name: counter
build:
steps:
- type: script
commands:
- zig build canister
- cp zig-out/bin/counter.wasm "$ICP_WASM_OUTPUT_PATH"
networks:
- name: local
mode: managed
gateway:
bind: 127.0.0.1
port: 4960
+45 -33
View File
@@ -36,18 +36,22 @@ var host: Host = undefined;
var session: ?*HostSession = null; var session: ?*HostSession = null;
var out: std.ArrayList(u8) = .empty; var out: std.ArrayList(u8) = .empty;
/// What the last call settled to, read with `client_result_*`. /// What each question settled to, by slot: the handle JavaScript holds.
const Result = union(enum) { const Result = union(enum) {
pending, pending,
reference: model.Reference, reference: model.Reference,
integer: i64, integer: i64,
broken, broken,
}; };
var result: Result = .pending;
const max_slots = 64;
var results: [max_slots]Result = undefined;
var vows: [max_slots]u64 = undefined;
var slot_count: usize = 0;
fn record(ctx: ?*anyopaque, resolution: actors.Resolution) void { fn record(ctx: ?*anyopaque, resolution: actors.Resolution) void {
_ = ctx; const slot: *Result = @ptrCast(@alignCast(ctx.?));
result = switch (resolution) { slot.* = switch (resolution) {
.fulfilled => |value| switch (value) { .fulfilled => |value| switch (value) {
.reference => |ref| .{ .reference = ref }, .reference => |ref| .{ .reference = ref },
.integer => |n| .{ .integer = n }, .integer => |n| .{ .integer = n },
@@ -57,12 +61,29 @@ fn record(ctx: ?*anyopaque, resolution: actors.Resolution) void {
}; };
} }
/// Watch `vow` in a fresh slot; return the slot's index.
fn watch(vow: u64) !i32 {
if (slot_count == max_slots) return error.OutOfSlots;
const index = slot_count;
results[index] = .pending;
vows[index] = vow;
try host.vowOn(vow, .{ .ctx = &results[index], .func = record });
slot_count += 1;
return @intCast(index);
}
fn fail(err: anyerror) u32 { fn fail(err: anyerror) u32 {
out.clearRetainingCapacity(); out.clearRetainingCapacity();
out.appendSlice(gpa, @errorName(err)) catch {}; out.appendSlice(gpa, @errorName(err)) catch {};
return 1; return 1;
} }
/// `fail`, for exports that return a slot index on success.
fn failSlot(err: anyerror) i32 {
_ = fail(err);
return -1;
}
export fn client_alloc(len: usize) ?[*]u8 { export fn client_alloc(len: usize) ?[*]u8 {
const buf = gpa.alloc(u8, len) catch return null; const buf = gpa.alloc(u8, len) catch return null;
return buf.ptr; return buf.ptr;
@@ -117,42 +138,33 @@ export fn client_session_open() bool {
} }
/// Ask the canister's bootstrap object for the capability it publishes as /// Ask the canister's bootstrap object for the capability it publishes as
/// `name`; the reference settles into the result. /// `name`. Returns the answer's slot.
export fn client_fetch(name: [*]const u8, len: usize) u32 { export fn client_fetch(name: [*]const u8, len: usize) i32 {
result = .pending; const vow = host.fetch(session.?, name[0..len]) catch |err| return failSlot(err);
const vow = host.fetch(session.?, name[0..len]) catch |err| return fail(err); return watch(vow) catch |err| failSlot(err);
host.vowOn(vow, .{ .ctx = null, .func = record }) catch |err| return fail(err);
return client_outbound();
} }
var counter: ?model.Reference = null; /// Send `verb`, with no arguments, to what slot `target` holds: a settled
/// reference, or a pending answer, in which case the send rides the
/// Keep the fetched reference as the target of `client_send`. /// promise without waiting for it. Returns the answer's slot.
export fn client_adopt() u32 { export fn client_send(target: u32, verb: [*]const u8, len: usize) i32 {
counter = switch (result) { if (target >= slot_count) return failSlot(error.NoSuchSlot);
.reference => |ref| ref, const msg: actors.Message = .{ .verb = verb[0..len], .args = &.{} };
else => return fail(error.NotAReference), const vow = switch (results[target]) {
}; .reference => |ref| host.send(session.?, ref, msg),
return 0; .pending => host.vowSend(vows[target], msg),
} else => return failSlot(error.NotAReference),
} catch |err| return failSlot(err);
/// Send `verb`, with no arguments, to the adopted reference; its answer return watch(vow) catch |err| failSlot(err);
/// settles into the result.
export fn client_send(verb: [*]const u8, len: usize) u32 {
result = .pending;
const target = counter orelse return fail(error.NothingAdopted);
const vow = host.send(session.?, target, .{ .verb = verb[0..len], .args = &.{} }) catch |err| return fail(err);
host.vowOn(vow, .{ .ctx = null, .func = record }) catch |err| return fail(err);
return client_outbound();
} }
/// 0 pending, 1 a reference, 2 an integer, 3 broken. /// 0 pending, 1 a reference, 2 an integer, 3 broken.
export fn client_result_kind() u32 { export fn client_result_kind(slot: u32) u32 {
return @intFromEnum(std.meta.activeTag(result)); return @intFromEnum(std.meta.activeTag(results[slot]));
} }
export fn client_result_integer() i64 { export fn client_result_integer(slot: u32) i64 {
return switch (result) { return switch (results[slot]) {
.integer => |n| n, .integer => |n| n,
else => 0, else => 0,
}; };