diff --git a/.gitignore b/.gitignore index cbcf859..392ab09 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ zig-pkg/ .dfx/ node_modules/ .icp/ +*.key diff --git a/README.md b/README.md index f5de607..bcf11c9 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # A Counter in a canister, over OCapN -An Internet Computer canister hosts a Counter as an [OCapN](https://github.com/ocapn/ocapn) peer, and a client calls `incr` and `decr` on it over CapTP, pipelined, in one update call. Both peers are [glowcap](https://github.com/glowcap-org/glowcap) compiled to WebAssembly; this is an exploratory prototype for [vattr97#5](https://github.com/dckc/vattr97/issues/5), canisters as vats. +An Internet Computer canister hosts counters as an [OCapN](https://github.com/ocapn/ocapn) peer: a client makes one, calls `incr` and `decr` on it over CapTP, pipelined, and keeps it in a home that survives a canister upgrade. Both peers are [glowcap](https://github.com/glowcap-org/glowcap) compiled to WebAssembly; this is an exploratory prototype for [vattr97#5](https://github.com/dckc/vattr97/issues/5), canisters as vats. ## Getting started @@ -10,29 +10,51 @@ You need [Nix](https://nixos.org/) with flakes; it supplies Zig 0.17.1 and Node. nix develop (cd client && npm ci --ignore-scripts) export DO_NOT_TRACK=1 # icp-cli reports usage by default -npx --prefix client icp network start -d -npx --prefix client icp deploy -y -node client/counter.mjs http://127.0.0.1:4960 "$(npx --prefix client icp canister status counter --id-only)" +icp() { npx --prefix client icp "$@"; } +icp network start -d +icp deploy -y counter --args "(blob \"$(head -c32 /dev/urandom | od -An -tx1 | tr -d ' \n' | sed 's/../\\&/g')\")" +ID=$(icp canister status counter --id-only) +node client/counter.mjs http://127.0.0.1:4960 $ID alice.key init c1 +icp canister install counter --mode upgrade -y +node client/counter.mjs http://127.0.0.1:4960 $ID alice.key use c1 incr value ``` -The output shows each update call and each answer: +The output shows each update call and each answer; after the upgrade, Alice's counter picks up where it left off: ``` - start 329B -> 345B in 300ms + start 329B -> 345B in 319ms session open - deliver 539B -> 725B in 271ms + deliver 551B -> 807B in 258ms incr 1 incr 2 decr 1 + deliver 180B -> 120B in 247ms +kept as c1 +Canister counter installed successfully + start 329B -> 345B in 295ms +session open + deliver 363B -> 538B in 261ms +incr 2 +value 2 ``` -`npx --prefix client icp network stop` stops the local network. `zig build test` runs the same exchange in memory. +With another key file, `use c1` breaks: that home is someone else's. `icp network stop` stops the local network. `zig build test` runs the same story in memory. + +## Homes, not swiss numbers + +Nodes on a canister's subnet can read its state, so a canister can't keep a swiss number secret. Authority here starts instead with the caller principal, whose signature the Internet Computer checks: + +- `fetch("home")` answers the caller's own home, a durable store of named objects: `init(name, object)` and `get(name)`. It's made the first time the caller asks. +- `fetch("makeCounter")` answers the one public maker; `make()` answers a fresh counter at zero. +- The anonymous principal is refused, since everyone who uses it would share one home. + +Homes, counters, and the canister's CapTP identity live in a [Loam](https://github.com/glowcap-org/glowcap) store whose engine ([stable_log.zig](src/stable_log.zig)) appends each committed transaction to stable memory, the part of a canister's state that survives an upgrade; `post_upgrade` replays it. CapTP sessions live in the heap, so an upgrade ends them, and a client starts a new one and fetches its home again. ## One update call per round trip -- **The wire.** The canister's Candid interface is two update methods, `start` and `deliver`, each taking and returning a `blob` of CapTP frames in Syrup byte-string envelopes ([counter.did](counter.did)). The OCapN locator transport is `icp`, its designator the canister's principal. +- **The wire.** The canister's Candid interface is two update methods, `start` and `deliver`, each taking and returning a `blob` of CapTP frames in Syrup byte-string envelopes, and an install argument of 32 bytes of entropy ([counter.did](counter.did)). The OCapN locator transport is `icp`, its designator the canister's principal. - **Sessions.** The canister keeps one CapTP session per caller principal, so the Internet Computer's request signature is what tells sessions apart. `start` carries the caller's `op:start-session`. -- **Pipelining.** The client sends to the fetch's answer before it settles, so the handshake is one call and the fetch plus every send is another: about 2.6 s on mainnet, 0.6 s on icp-cli's local network. +- **Pipelining.** The client sends to an answer before it settles, so the handshake is one call and making a counter plus every send to it is another: about 2.6 s on mainnet, 0.6 s on icp-cli's local network. Keeping it with `init` takes a third, since the client passes only settled references as arguments. - **Answer releases** (`op:gc-answer`) ride ahead of the client's next message rather than costing a call of their own. - **No server push.** The canister can only answer what a call delivers; promise resolutions it learns of later would need a query to poll. @@ -47,8 +69,8 @@ decr 1 ## Known gaps -- **Seeds are not secret.** The canister derives its CapTP keys from its id and install time. Nothing in a canister is secret from its subnet's nodes anyway, but a real deployment would draw from `raw_rand`. -- **Upgrades forget everything.** Sessions and the count live in the Wasm heap, which a code upgrade discards; nothing uses stable memory. -- **One session per principal.** A second `start` from the same caller traps; the Node client mints a fresh identity per run. -- **The canister pays for every call** and admits any caller; it should refuse strangers before doing work (`canister_inspect_message`). +- **The entropy is not secret** from the subnet's nodes, nor from whoever installs; nothing rests on it but the CapTP keys. A real deployment would draw it from `raw_rand` in a first call after install. +- **One session per principal.** A second `start` from the same caller traps until an upgrade clears sessions; a client that loses its session can't reconnect with the same key. +- **No removal or collection.** A home holds 8 names and can't drop one; Loam garbage collection never runs. +- **The canister pays for every call** and admits any signed caller; it should refuse strangers before doing work (`canister_inspect_message`). - **Third-party handoffs** need gift ids from entropy and dials to other peers; the canister refuses both. diff --git a/build.zig b/build.zig index 3818d5f..14de412 100644 --- a/build.zig +++ b/build.zig @@ -29,7 +29,7 @@ pub fn build(b: *std.Build) void { }), }); canister.entry = .disabled; - canister.root_module.export_symbol_names = &.{ "canister_init", "canister_update start", "canister_update deliver" }; + canister.root_module.export_symbol_names = &.{ "canister_init", "canister_post_upgrade", "canister_update start", "canister_update deliver" }; const canister_step = b.step("canister", "Build the canister to zig-out/bin/counter.wasm"); canister_step.dependOn(&b.addInstallArtifact(canister, .{}).step); diff --git a/client/counter.mjs b/client/counter.mjs index d5a8764..981fd2e 100644 --- a/client/counter.mjs +++ b/client/counter.mjs @@ -2,17 +2,23 @@ /** * @file Call the Counter canister over OCapN. */ -const HELP = `usage: counter.mjs HOST CANISTER_ID [VERB...] +const HELP = `usage: counter.mjs HOST CANISTER_ID KEY_FILE init NAME + counter.mjs HOST CANISTER_ID KEY_FILE use NAME [VERB...] -Open a CapTP session to the canister, fetch "counter", and send it each -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. -A fresh Ed25519 identity makes each run its own caller, so its own session.`; +Open a CapTP session to the canister as the principal whose Ed25519 seed is +in KEY_FILE (32 bytes, made if missing), then: -import { readFile } from 'node:fs/promises'; + init NAME make a counter, count on it (incr incr decr), and keep it in + your home under NAME + use NAME get the counter kept under NAME and send it each VERB + (incr, decr, value; default: incr value) + +Each run's sends are pipelined: one update call after the handshake, plus +one for init. HOST is the replica, e.g. http://127.0.0.1:4960, or +https://icp-api.io.`; + +import { readFile, writeFile } from 'node:fs/promises'; import { HttpAgent, Actor } from '@icp-sdk/core/agent'; -import { IDL } from '@icp-sdk/core/candid'; import { Ed25519KeyIdentity } from '@icp-sdk/core/identity'; import { openPeer } from './peer.js'; @@ -25,18 +31,30 @@ const idlFactory = ({ IDL }) => { }); }; -const main = async ([host, canisterId, ...verbs]) => { - if (!host || !canisterId) { +/** 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; + } +}; + +const main = async ([host, canisterId, keyFile, command, name, ...verbs]) => { + if (!name || !['init', 'use'].includes(command)) { console.error(HELP); process.exitCode = 2; return; } - const local = new URL(host).hostname === '127.0.0.1' || new URL(host).hostname === 'localhost'; + const { hostname } = new URL(host); const agent = await HttpAgent.create({ host, - identity: Ed25519KeyIdentity.generate(), + identity: Ed25519KeyIdentity.generate(await keySeed(keyFile)), // A local replica's root key is its own; mainnet's is built in. - shouldFetchRootKey: local, + shouldFetchRootKey: hostname === '127.0.0.1' || hostname === 'localhost', }); const actor = Actor.createActor(idlFactory, { agent, canisterId }); const carry = async (method, frames) => { @@ -52,12 +70,23 @@ const main = async ([host, canisterId, ...verbs]) => { const peer = await openPeer({ module, seed, carry }, canisterId); console.log('session open'); - // Pipelined: the sends target the fetch's answer before it settles, so - // the fetch and every send cross in one update call. - const counter = peer.fetch('counter'); - 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)); + const home = peer.fetch('home'); + /** Send each verb without waiting, then print each answer. */ + const countOn = async (counter, sends) => { + const answers = sends.map(verb => [verb, peer.send(counter, verb)]); + await peer.flush(); + for (const [verb, answer] of answers) console.log(verb, peer.valueOf(answer)); + }; + if (command === 'init') { + const counter = peer.send(peer.fetch('makeCounter'), 'make'); + await countOn(counter, ['incr', 'incr', 'decr']); + const kept = peer.send(home, 'init', name, counter); + await peer.flush(); + peer.valueOf(kept); + console.log(`kept as ${name}`); + } else { + await countOn(peer.send(home, 'get', name), verbs.length ? verbs : ['incr', 'value']); + } }; main(process.argv.slice(2)).catch(err => { diff --git a/client/peer.js b/client/peer.js index dcbfd59..b3025d3 100644 --- a/client/peer.js +++ b/client/peer.js @@ -79,6 +79,7 @@ export const openPeer = async ({ module, seed, carry }, canisterId) => { 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`); + if (kind === 4) return undefined; return kind === 2 ? Number(wasm.client_result_integer(slot)) : { slot }; }; @@ -92,10 +93,25 @@ export const openPeer = async ({ module, seed, carry }, canisterId) => { 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') }), - /** @returns {Answer} `target`'s answer to `verb` */ - send: (target, verb) => ({ - slot: slotOf(withBytes(encoder.encode(verb), (p, n) => wasm.client_send(target.slot, p, n)), 'send'), - }), + /** + * Send `verb` to `target` with the arguments in `args`: at most one + * string, then at most one settled reference. + * + * @param {Answer} target + * @param {string} verb + * @param {...(string | Answer)} args + * @returns {Answer} `target`'s answer + */ + send: (target, verb, ...args) => { + const text = args.find(arg => typeof arg === 'string'); + const object = args.find(arg => typeof arg === 'object'); + const status = withBytes(encoder.encode(verb), (verbPtr, verbLen) => + withBytes(encoder.encode(text ?? ''), (textPtr, textLen) => + wasm.client_send(target.slot, verbPtr, verbLen, textPtr, text === undefined ? -1 : textLen, object ? object.slot : -1), + ), + ); + return { slot: slotOf(status, 'send') }; + }, flush, /** @param {Answer} answer */ valueOf: answer => valueOf(answer.slot), diff --git a/counter.did b/counter.did index f30e4c1..aee5bf2 100644 --- a/counter.did +++ b/counter.did @@ -1,7 +1,8 @@ -// Each blob is CapTP frames in Syrup byte-string envelopes. -service : { +// Each blob of frames is CapTP frames in Syrup byte-string envelopes. +// Install with 32 bytes of fresh entropy. +service : (entropy : blob) -> { // Open the caller's session with its `op:start-session`. - start : (blob) -> (blob); + start : (frames : blob) -> (blob); // Carry later frames on the caller's session. - deliver : (blob) -> (blob); + deliver : (frames : blob) -> (blob); } diff --git a/src/canister.zig b/src/canister.zig index 5fb4904..4a90820 100644 --- a/src/canister.zig +++ b/src/canister.zig @@ -1,21 +1,19 @@ -//! A canister that hosts a Counter as an OCapN peer. Each caller principal -//! gets one CapTP session: `start` opens it with the caller's -//! `op:start-session`, and `deliver` carries later frames. Each update -//! call's reply carries whatever frames the canister has for that caller. +//! A canister that hosts a counter maker and a home per caller as an OCapN +//! peer. Each caller principal gets one CapTP session: `start` opens it with +//! the caller's `op:start-session`, and `deliver` carries later frames. Each +//! update call's reply carries whatever frames the canister has for that +//! caller. The anonymous principal is refused: it would share one home. //! -//! A trap rolls back the whole update, Host state included, so a frame that -//! breaks the session leaves the canister as it was before the call. +//! Install with 32 bytes of fresh entropy as the argument (one Candid +//! `blob`). Homes, counters, and the peer's identity then live in stable +//! memory and survive upgrades; sessions do not. +//! +//! A trap rolls back the whole message, heap and stable memory alike. const std = @import("std"); -const glowcap = @import("glowcap"); const candid = @import("candid.zig"); -const link = @import("link.zig"); const principal = @import("principal.zig"); -const Counter = @import("counter.zig").Counter; - -const model = glowcap.ocapn.model; -const Host = glowcap.driver.core.Host; -const HostSession = glowcap.driver.core.HostSession; +const Node = @import("node.zig").Node(Stable); /// The Internet Computer System API, for 32-bit Wasm. /// @see https://docs.internetcomputer.org/references/ic-interface-spec/#system-api @@ -29,10 +27,35 @@ const ic0 = struct { extern "ic0" fn canister_self_size() u32; extern "ic0" fn canister_self_copy(dst: u32, offset: u32, size: u32) void; extern "ic0" fn time() u64; + extern "ic0" fn stable64_size() u64; + extern "ic0" fn stable64_grow(new_pages: u64) u64; + extern "ic0" fn stable64_read(dst: u64, offset: u64, size: u64) void; + extern "ic0" fn stable64_write(offset: u64, src: u64, size: u64) void; extern "ic0" fn trap(src: u32, size: u32) noreturn; extern "ic0" fn debug_print(src: u32, size: u32) void; }; +/// Stable memory, addressed in bytes. +const Stable = struct { + const page = 64 * 1024; + + pub fn size(_: *const Stable) u64 { + return ic0.stable64_size() * page; + } + pub fn grow(_: *Stable, min_size: u64) !void { + const pages = std.math.divCeil(u64, min_size, page) catch unreachable; + const have = ic0.stable64_size(); + if (pages <= have) return; + if (ic0.stable64_grow(pages - have) == std.math.maxInt(u64)) return error.StableMemoryFull; + } + pub fn read(_: *const Stable, offset: u64, out: []u8) void { + ic0.stable64_read(@intFromPtr(out.ptr), offset, out.len); + } + pub fn write(_: *Stable, offset: u64, bytes: []const u8) void { + ic0.stable64_write(offset, @intFromPtr(bytes.ptr), bytes.len); + } +}; + pub const std_options: std.Options = .{ .logFn = log, .enable_segfault_handler = false, @@ -59,100 +82,89 @@ fn trapWith(comptime what: []const u8, err: anyerror) noreturn { } const gpa = std.heap.wasm_allocator; -const frame_cap = 64 * 1024; -/// The Host lives here, at an address that never moves, for the canister's -/// lifetime; canister memory persists between calls (not across upgrades). -var host: Host = undefined; -var sessions: std.StringHashMapUnmanaged(*HostSession) = .empty; +/// The Node lives here, at an address that never moves, until an upgrade. +var node: Node = undefined; +var stable: Stable = .{}; +var self_text: [64]u8 = undefined; + +fn copied(comptime size: fn () callconv(.c) u32, comptime copy: fn (u32, u32, u32) callconv(.c) void) ![]u8 { + const len = size(); + const bytes = try gpa.alloc(u8, len); + copy(@intFromPtr(bytes.ptr), 0, len); + return bytes; +} + +/// The canister's principal, as text: its OCapN designator. +fn designator() ![]const u8 { + const id = try copied(ic0.canister_self_size, ic0.canister_self_copy); + defer gpa.free(id); + return principal.text(id, &self_text); +} + +/// Seeds this run's session keys from `nonce` and the time. Not secret, but +/// sessions end with the run, and each run's root differs. +fn sessionRoot(nonce: []const u8) [32]u8 { + var root: [32]u8 = undefined; + var kdf = std.crypto.hash.Blake3.initKdf("icp-ocapn-counter session root v1", .{}); + kdf.update(nonce); + kdf.update(std.mem.asBytes(&ic0.time())); + kdf.final(&root); + return root; +} fn init() !void { - const self_len = ic0.canister_self_size(); - const self_id = try gpa.alloc(u8, self_len); - ic0.canister_self_copy(@intFromPtr(self_id.ptr), 0, self_len); + const arg = try copied(ic0.msg_arg_data_size, ic0.msg_arg_data_copy); + defer gpa.free(arg); + const entropy = candid.decodeBlob(arg) catch return error.InstallWith32BytesOfEntropy; + if (entropy.len != 32) return error.InstallWith32BytesOfEntropy; + try node.create(gpa, &stable, entropy[0..32].*, sessionRoot(entropy), try designator()); +} - // Not secret: every replica, and anyone who knows the install time, can - // derive these. A real deployment would draw them from `raw_rand`. - var durable_seed: [32]u8 = undefined; - var session_root: [32]u8 = undefined; - var kdf = std.crypto.hash.Blake3.initKdf("icp-ocapn-counter durable seed v0", .{}); - kdf.update(self_id); - kdf.update(std.mem.asBytes(&ic0.time())); - kdf.final(&durable_seed); - kdf = std.crypto.hash.Blake3.initKdf("icp-ocapn-counter session root v0", .{}); - kdf.update(&durable_seed); - kdf.final(&session_root); +fn postUpgrade() !void { + try node.revive(gpa, &stable, sessionRoot(""), try designator()); +} - host = try Host.init(gpa, durable_seed, session_root, Host.Options.init(.unchecked, frame_cap)); - _ = try host.defineTransport(link.profile); - _ = try host.publish("counter", Counter, .{}); +const Verb = enum { start, deliver }; +/// The anonymous principal's one byte. +const anonymous = 0x04; - var text: [64]u8 = undefined; - const designator = try principal.text(self_id, &text); - try host.setAdvertisedLocator(.{ .transport = link.transport, .designator = designator, .hints = model.Hints.emptyFalse() }); +fn exchange(comptime verb: Verb) !void { + const caller = try copied(ic0.msg_caller_size, ic0.msg_caller_copy); + defer gpa.free(caller); + if (std.mem.eql(u8, caller, &.{anonymous})) return error.AnonymousCaller; + const arg = try copied(ic0.msg_arg_data_size, ic0.msg_arg_data_copy); + defer gpa.free(arg); + const frames = try candid.decodeBlob(arg); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + switch (verb) { + .start => try node.start(caller, frames, &out), + .deliver => try node.deliver(caller, frames, &out), + } + var reply: std.ArrayList(u8) = .empty; + defer reply.deinit(gpa); + try candid.encodeBlob(gpa, out.items, &reply); + ic0.msg_reply_data_append(@intFromPtr(reply.items.ptr), reply.items.len); + ic0.msg_reply(); } fn canisterInit() callconv(.c) void { init() catch |err| trapWith("init", err); } - -fn argBlob() ![]u8 { - const len = ic0.msg_arg_data_size(); - const message = try gpa.alloc(u8, len); - ic0.msg_arg_data_copy(@intFromPtr(message.ptr), 0, len); - return message; +fn canisterPostUpgrade() callconv(.c) void { + postUpgrade() catch |err| trapWith("post_upgrade", err); } - -fn caller() ![]u8 { - const len = ic0.msg_caller_size(); - const id = try gpa.alloc(u8, len); - ic0.msg_caller_copy(@intFromPtr(id.ptr), 0, len); - return id; -} - -/// Feed the caller's frames to `session`, then reply with what it has queued. -fn exchange(session: *HostSession, message: []const u8) !void { - try host.feedBytes(session, try candid.decodeBlob(message)); - try link.settle(&host, .flush); - var frames: std.ArrayList(u8) = .empty; - defer frames.deinit(gpa); - try link.drainOutbound(gpa, session, &frames); - var reply: std.ArrayList(u8) = .empty; - defer reply.deinit(gpa); - try candid.encodeBlob(gpa, frames.items, &reply); - ic0.msg_reply_data_append(@intFromPtr(reply.items.ptr), reply.items.len); - ic0.msg_reply(); -} - -fn start() !void { - const who = try caller(); - const entry = try sessions.getOrPut(gpa, who); - if (entry.found_existing) return error.SessionAlreadyStarted; - entry.value_ptr.* = try host.openAcceptedAdvertised(link.transport); - const message = try argBlob(); - defer gpa.free(message); - try exchange(entry.value_ptr.*, message); -} - -fn deliver() !void { - const who = try caller(); - defer gpa.free(who); - const session = sessions.get(who) orelse return error.NoSessionForCaller; - const message = try argBlob(); - defer gpa.free(message); - try exchange(session, message); -} - fn canisterStart() callconv(.c) void { - start() catch |err| trapWith("start", err); + exchange(.start) catch |err| trapWith("start", err); } - fn canisterDeliver() callconv(.c) void { - deliver() catch |err| trapWith("deliver", err); + exchange(.deliver) catch |err| trapWith("deliver", err); } comptime { @export(&canisterInit, .{ .name = "canister_init" }); + @export(&canisterPostUpgrade, .{ .name = "canister_post_upgrade" }); @export(&canisterStart, .{ .name = "canister_update start" }); @export(&canisterDeliver, .{ .name = "canister_update deliver" }); } diff --git a/src/client.zig b/src/client.zig index 29f475a..11d36b6 100644 --- a/src/client.zig +++ b/src/client.zig @@ -42,6 +42,7 @@ const Result = union(enum) { reference: model.Reference, integer: i64, broken, + void, }; const max_slots = 64; @@ -55,6 +56,7 @@ fn record(ctx: ?*anyopaque, resolution: actors.Resolution) void { .fulfilled => |value| switch (value) { .reference => |ref| .{ .reference = ref }, .integer => |n| .{ .integer = n }, + .void => .void, else => .broken, }, .broken, .give => .broken, @@ -144,12 +146,28 @@ export fn client_fetch(name: [*]const u8, len: usize) i32 { return watch(vow) catch |err| failSlot(err); } -/// Send `verb`, with no arguments, to what slot `target` holds: a settled -/// reference, or a pending answer, in which case the send rides the -/// promise without waiting for it. Returns the answer's slot. -export fn client_send(target: u32, verb: [*]const u8, len: usize) i32 { +/// Send `verb` to what slot `target` holds: a settled reference, or a +/// pending answer, in which case the send rides the promise without waiting +/// for it. The arguments are the string `text`, if `text_len` is not +/// negative, then the reference slot `object` holds, if `object` is not +/// negative. Returns the answer's slot. +export fn client_send(target: u32, verb: [*]const u8, len: usize, text: [*]const u8, text_len: i32, object: i32) i32 { if (target >= slot_count) return failSlot(error.NoSuchSlot); - const msg: actors.Message = .{ .verb = verb[0..len], .args = &.{} }; + var args: [2]model.Argument = undefined; + var count: usize = 0; + if (text_len >= 0) { + args[count] = .{ .string = text[0..@intCast(text_len)] }; + count += 1; + } + if (object >= 0) { + if (object >= slot_count) return failSlot(error.NoSuchSlot); + args[count] = switch (results[@intCast(object)]) { + .reference => |ref| .{ .reference = ref }, + else => return failSlot(error.NotAReference), + }; + count += 1; + } + const msg: actors.Message = .{ .verb = verb[0..len], .args = args[0..count] }; const vow = switch (results[target]) { .reference => |ref| host.send(session.?, ref, msg), .pending => host.vowSend(vows[target], msg), @@ -158,7 +176,7 @@ export fn client_send(target: u32, verb: [*]const u8, len: usize) i32 { return watch(vow) catch |err| failSlot(err); } -/// 0 pending, 1 a reference, 2 an integer, 3 broken. +/// 0 pending, 1 a reference, 2 an integer, 3 broken, 4 void. export fn client_result_kind(slot: u32) u32 { return @intFromEnum(std.meta.activeTag(results[slot])); } diff --git a/src/counter.zig b/src/counter.zig deleted file mode 100644 index 4e6c2c7..0000000 --- a/src/counter.zig +++ /dev/null @@ -1,21 +0,0 @@ -//! A counter: `incr` and `decr` change it by one, `value` reads it, and each -//! replies with the count after the change. - -const glowcap = @import("glowcap"); - -const actors = glowcap.actors; -const model = glowcap.ocapn.model; - -pub const Counter = struct { - count: i64 = 0, - - pub fn handle(self: *Counter, turn: *actors.Turn, msg: actors.Delivery) !model.Argument { - _ = turn; - if (msg.is("incr")) { - self.count += 1; - } else if (msg.is("decr")) { - self.count -= 1; - } else if (!msg.is("value")) return error.NoSuchMethod; - return .{ .integer = self.count }; - } -}; diff --git a/src/node.zig b/src/node.zig new file mode 100644 index 0000000..559d871 --- /dev/null +++ b/src/node.zig @@ -0,0 +1,401 @@ +//! The canister's OCapN peer, apart from the Internet Computer's System API. +//! Each caller principal has a home: a durable store of named objects in +//! Loam on stable memory, which `fetch("home")` answers on that caller's +//! session. `fetch("makeCounter")` answers the one public counter maker. +//! Homes, counters, and the peer's identity survive an upgrade; CapTP +//! sessions live in the heap and do not. +//! +//! Nothing in a canister is secret from its subnet's nodes, so no authority +//! here rests on an unguessable name: a home is reached only through the +//! session of the principal whose signature the Internet Computer checked. +//! +//! Stable memory holds a `Header` at offset 0 and the Loam log at +//! `log_base`. + +const std = @import("std"); +const glowcap = @import("glowcap"); +const link = @import("link.zig"); +const StableLog = @import("stable_log.zig").StableLog; + +const model = glowcap.ocapn.model; +const core = glowcap.loam.core; +const hosting = glowcap.loam.hosting; +const driver = glowcap.driver.core; +const Host = driver.Host; +const HostSession = driver.HostSession; + +pub const log_base = 4096; +const frame_cap = 64 * 1024; + +/// What `fetch` names to get the caller's home. +pub const home_name = "home"; +/// What `fetch` names to get the counter maker. +pub const maker_name = "makeCounter"; +const maker_key: [16]u8 = blk: { + var key: [16]u8 = @splat(0); + @memcpy(key[0..maker_name.len], maker_name); + break :blk key; +}; + +const Header = extern struct { + magic: [8]u8 = header_magic.*, + durable_seed: [32]u8, + store_id: u64, +}; +const header_magic = "ICPOCAP3"; + +const counter_schema = 1; +const home_schema = 2; +const maker_schema = 3; +/// Names in one home, each up to `max_name` bytes. +const max_names = 8; +const max_name = 32; +/// A home's payload: the 16-byte index key of its principal, then each name +/// as a length byte and its bytes; edge `i` is the object named `i`th. +const home_max_payload = 16 + max_names * (1 + max_name); +const schemas = [_]core.Schema{ + .{ .id = counter_schema, .version = 1, .max_payload = 8, .max_edges = 0 }, + .{ .id = home_schema, .version = 1, .max_payload = home_max_payload, .max_edges = max_names, .name_offset = 0 }, + .{ .id = maker_schema, .version = 1, .max_payload = 16, .max_edges = 0, .name_offset = 0 }, +}; +const limits: core.Store.Limits = .{ + .records = .{ .max_record_bytes = 512, .max_edges = max_names }, + .cache_slots = 16, + .max_leases = 16, + .resident_bytes = 16 * 1024, + .max_changes = 8, + .staging_bytes = 8 * 1024, +}; +const behaviors = [_]hosting.Behavior{ + .{ .schema = counter_schema, .invoke = counter }, + .{ .schema = home_schema, .invoke = home }, + .{ .schema = maker_schema, .invoke = maker }, +}; + +/// A counter: `incr` and `decr` propose the next count, which counts only +/// once Loam commits it; `value` reads it. Each answers the count. +fn counter(call: *hosting.Call, state: core.RecordView, verb: []const u8, args: []const driver.Value) !driver.Value { + if (args.len != 0) return error.InvalidArguments; + if (state.payload.len != 8) return error.InvalidCounter; + const count = std.mem.readInt(i64, state.payload[0..8], .little); + const next = if (std.mem.eql(u8, verb, "incr")) + count + 1 + else if (std.mem.eql(u8, verb, "decr")) + count - 1 + else if (std.mem.eql(u8, verb, "value")) + return .{ .integer = count } + else + return error.NoSuchMethod; + const payload = try call.arena().alloc(u8, 8); + std.mem.writeInt(i64, payload[0..8], next, .little); + call.replace(payload); + return .{ .integer = next }; +} + +/// The index key of `principal`'s home. +fn homeKey(principal: []const u8) [16]u8 { + var key: [16]u8 = undefined; + std.crypto.hash.Blake3.hash(principal, &key, .{}); + return key; +} + +/// Where `name` is among a home's names, if it is. +fn find(payload: []const u8, name: []const u8) !?usize { + var at: usize = 16; + var index: usize = 0; + while (at < payload.len) : (index += 1) { + const len = payload[at]; + if (at + 1 + len > payload.len) return error.InvalidHome; + if (std.mem.eql(u8, payload[at + 1 ..][0..len], name)) return index; + at += 1 + len; + } + return null; +} + +/// A home: `init(name, object)` keeps a durable object under a new name; +/// `get(name)` answers what is kept there. +fn home(call: *hosting.Call, state: core.RecordView, verb: []const u8, args: []const driver.Value) !driver.Value { + if (args.len < 1 or args[0] != .string) return error.InvalidArguments; + const name = args[0].string; + const found = try find(state.payload, name); + if (std.mem.eql(u8, verb, "get")) { + if (args.len != 1) return error.InvalidArguments; + return .{ .capability = try call.edge(found orelse return error.NoSuchName) }; + } else if (std.mem.eql(u8, verb, "init")) { + if (args.len != 2 or args[1] != .capability) return error.InvalidArguments; + if (found != null) return error.NameTaken; + if (name.len > max_name) return error.NameTooLong; + if (state.edge_count == max_names) return error.HomeFull; + const keeping = try call.arena().create(Keeping); + keeping.* = .{ .call = call, .name = try call.arena().dupe(u8, name), .edge = try call.capture(args[1].capability) }; + call.transaction = .{ .context = keeping, .stage = Keeping.stage }; + return .{ .void = {} }; + } else return error.NoSuchMethod; +} + +/// One `init` call: the home, with one more name and edge. +const Keeping = struct { + call: *hosting.Call, + name: []const u8, + edge: core.Edge, + + fn stage(context: *anyopaque, store: *core.Store) !void { + const self: *Keeping = @ptrCast(@alignCast(context)); + const view = self.call.view; + const arena = self.call.arena(); + const payload = try std.mem.concat(arena, u8, &.{ view.payload, &.{@intCast(self.name.len)}, self.name }); + const edges = try arena.alloc(core.Edge, view.edge_count + 1); + for (edges[0..view.edge_count], 0..) |*edge, i| edge.* = try view.edgeAt(i); + edges[view.edge_count] = self.edge; + try store.putCopying(.{ .id = view.id, .revision = 0, .schema = home_schema, .payload = payload, .edges = edges, .rooted = true }, view.revision); + } +}; + +/// The maker: `make()` answers a new counter at zero. +fn maker(call: *hosting.Call, _: core.RecordView, verb: []const u8, args: []const driver.Value) !driver.Value { + if (args.len != 0) return error.InvalidArguments; + if (!std.mem.eql(u8, verb, "make")) return error.NoSuchMethod; + const making = try call.arena().create(Making); + making.* = .{ .call = call }; + call.transaction = .{ .context = making, .stage = Making.stage }; + call.result = Making.result; + call.context = making; + return .{ .void = {} }; +} + +/// One `make` call, from staging to its answer. +const Making = struct { + call: *hosting.Call, + counter: ?driver.Capability = null, + + /// Records and capabilities exist only once Loam opens the call's batch. + fn stage(context: *anyopaque, store: *core.Store) !void { + const self: *Making = @ptrCast(@alignCast(context)); + const id = try store.allocateId(); + try store.putCopying(.{ .id = id, .revision = 0, .schema = counter_schema, .payload = &@as([8]u8, @splat(0)) }, null); + self.counter = try self.call.propose(id); + } + + fn result(call: *hosting.Call) !driver.Value { + const self: *Making = @ptrCast(@alignCast(call.context.?)); + return .{ .capability = self.counter orelse return error.NotStaged }; + } +}; + +pub fn Node(comptime Memory: type) type { + return struct { + const Self = @This(); + const Log = StableLog(Memory); + const Fetched = enum { home, maker }; + const Waiting = struct { fetch: Host.PublicationFetch, what: Fetched }; + + gpa: std.mem.Allocator, + memory: *Memory, + host: Host, + log: Log, + store: core.Store, + attachment: *hosting.Attachment, + /// Each caller's session, by principal. + sessions: std.StringHashMapUnmanaged(*HostSession) = .empty, + /// Answers `fetch` of `home_name` and `maker_name`, once storage is + /// free to. + homes: Host.PublicationLookup, + waiting: [8]?Waiting = @splat(null), + lookups: u64 = 0, + + /// Install: record the durable seed, make the maker, then serve. `designator` is the + /// canister's principal as text; `session_root` seeds this run's + /// session keys. + pub fn create(self: *Self, gpa: std.mem.Allocator, memory: *Memory, durable_seed: [32]u8, session_root: [32]u8, designator: []const u8) !void { + if (memory.size() < log_base) try memory.grow(log_base); + const header: Header = .{ .durable_seed = durable_seed, .store_id = std.mem.readInt(u64, durable_seed[0..8], .little) }; + memory.write(0, std.mem.asBytes(&header)); + try self.open(gpa, memory, header, session_root, designator); + errdefer self.deinit(); + _ = try self.makeIndexed(maker_schema, maker_key); + } + + /// After an upgrade: reopen what `create` recorded. + pub fn revive(self: *Self, gpa: std.mem.Allocator, memory: *Memory, session_root: [32]u8, designator: []const u8) !void { + var header: Header = undefined; + if (memory.size() < log_base) return error.NotInstalled; + memory.read(0, std.mem.asBytes(&header)); + if (!std.mem.eql(u8, &header.magic, header_magic)) return error.NotInstalled; + try self.open(gpa, memory, header, session_root, designator); + } + + fn open(self: *Self, gpa: std.mem.Allocator, memory: *Memory, header: Header, session_root: [32]u8, designator: []const u8) !void { + self.* = .{ + .gpa = gpa, + .memory = memory, + .host = try Host.init(gpa, header.durable_seed, session_root, Host.Options.init(.unchecked, frame_cap)), + .log = undefined, + .store = undefined, + .attachment = undefined, + .homes = .{ .context = self, .idle = idle, .start = admit, .cancel = cancel }, + }; + errdefer self.host.deinit(); + _ = try self.host.defineTransport(link.profile); + try self.host.setAdvertisedLocator(.{ .transport = link.transport, .designator = designator, .hints = model.Hints.emptyFalse() }); + + self.log = try Log.init(gpa, memory, log_base, @enumFromInt(header.store_id), core.backend.min_capacity_bytes); + errdefer self.log.deinit(); + self.store = try core.Store.init(gpa, try self.log.open(), &schemas, limits); + errdefer self.store.deinit() catch {}; + self.attachment = try hosting.Attachment.create(gpa, &self.host, &self.store, &behaviors, .{}); + errdefer self.attachment.destroy() catch {}; + try self.host.setPublicationLookup(&self.homes); + } + + /// Tear down the heap side, as an upgrade does; stable memory stays. + pub fn deinit(self: *Self) void { + for (&self.waiting) |*slot| if (slot.*) |*waiting| waiting.fetch.abandon(); + self.waiting = @splat(null); + self.host.clearPublicationLookup(&self.homes) catch {}; + self.attachment.destroy() catch {}; + self.host.deinit(); + self.store.deinit() catch {}; + self.log.deinit(); + var keys = self.sessions.keyIterator(); + while (keys.next()) |key| self.gpa.free(key.*); + self.sessions.deinit(self.gpa); + } + + /// Open `caller`'s session with its `op:start-session` and append the + /// canister's frames to `reply`. + pub fn start(self: *Self, caller: []const u8, frames: []const u8, reply: *std.ArrayList(u8)) !void { + if (self.sessions.contains(caller)) return error.SessionAlreadyStarted; + const key = try self.gpa.dupe(u8, caller); + errdefer self.gpa.free(key); + const session = try self.host.openAcceptedAdvertised(link.transport); + try self.sessions.put(self.gpa, key, session); + try self.exchange(session, frames, reply); + } + + /// Carry later frames on `caller`'s session. + pub fn deliver(self: *Self, caller: []const u8, frames: []const u8, reply: *std.ArrayList(u8)) !void { + const session = self.sessions.get(caller) orelse return error.NoSessionForCaller; + try self.exchange(session, frames, reply); + } + + /// Feed `frames`, run the turns, homes, and storage work they need + /// until nothing is pending, then drain what the session has queued. + fn exchange(self: *Self, session: *HostSession, frames: []const u8, reply: *std.ArrayList(u8)) !void { + try self.host.feedBytes(session, frames); + var slot: [1]hosting.Worker.Slot = undefined; + var worker: hosting.Worker = .init(&slot, self.log.readerCapacity()); + for (0..64) |_| { + try link.settle(&self.host, .flush); + _ = try self.host.vat.driveIngressBudgeted(.local, 64); + try self.answerHomes(); + try self.attachment.advance(); + try worker.drive(self.attachment, &self.log); + if (!self.attachment.hasPendingWork() and idle(self)) break; + } else return error.StorageDidNotQuiesce; + try link.settle(&self.host, .flush); + try link.drainOutbound(self.gpa, session, reply); + } + + fn idle(context: *anyopaque) bool { + const self: *Self = @ptrCast(@alignCast(context)); + for (self.waiting) |slot| if (slot != null) return false; + return true; + } + + /// Take a fetch of `home_name` or `maker_name` to answer between turns. + fn admit(context: *anyopaque, name: []const u8, fetch: Host.PublicationFetch) Host.PublicationLookup.Admission { + const self: *Self = @ptrCast(@alignCast(context)); + const what: Fetched = if (std.mem.eql(u8, name, home_name)) .home else if (std.mem.eql(u8, name, maker_name)) .maker else return .unhandled; + for (&self.waiting) |*slot| if (slot.* == null) { + slot.* = .{ .fetch = fetch, .what = what }; + return .accepted; + }; + return .{ .refused = error.FetchCapacity }; + } + + fn cancel(context: *anyopaque, cancellation: Host.PublicationLookup.Cancellation) void { + const self: *Self = @ptrCast(@alignCast(context)); + for (&self.waiting) |*slot| if (slot.*) |*waiting| { + const matches = switch (cancellation) { + .origin => |origin| std.meta.eql(waiting.fetch.origin(), origin), + .local_shutdown => true, + }; + if (matches) { + waiting.fetch.abandon(); + slot.* = null; + } + }; + } + + /// Answer each waiting fetch: the maker, or the caller's home, made + /// first if the caller has none. + fn answerHomes(self: *Self) !void { + for (&self.waiting) |*slot| if (slot.*) |*waiting| { + if (self.store.phase != .idle) return; + const fetch = &waiting.fetch; + const key = switch (waiting.what) { + .maker => maker_key, + .home => homeKey(switch (fetch.origin()) { + .peer => |peer| self.callerOf(peer), + .local => null, + } orelse { + try fetch.complete(.missing); + slot.* = null; + continue; + }), + }; + const ref = try self.restoreIndexed(switch (waiting.what) { + .maker => maker_schema, + .home => home_schema, + }, key); + defer self.host.releaseCapabilityTerminal(ref, null); + try fetch.complete(.{ .found = ref }); + slot.* = null; + }; + } + + fn callerOf(self: *Self, peer: anytype) ?[]const u8 { + var entries = self.sessions.iterator(); + while (entries.next()) |entry| if (std.meta.eql(entry.value_ptr.*.peer_handle, peer)) return entry.key_ptr.*; + return null; + } + + /// The record indexed under `key`, restored; a home is made on first use. + fn restoreIndexed(self: *Self, schema: u64, key: [16]u8) !driver.Capability { + const meta = self.store.metadata; + self.lookups += 1; + const id = switch (self.log.lookup(.{ + .ticket = .{ .store = meta.store, .incarnation = meta.incarnation, .revision = meta.revision, .sequence = self.lookups }, + .name = .{ .schema = schema, .bytes = key }, + })) { + .found => |id| id, + .missing => if (schema == home_schema) try self.makeIndexed(schema, key) else return error.NotInstalled, + .failed => |err| return err, + }; + const lease = switch (try self.store.acquire(id)) { + .ready => |lease| lease, + .read => |read| blk: { + try self.store.completeRead(read.ticket, self.log.read(read)); + break :blk (try self.store.acquire(id)).ready; + }, + }; + defer self.store.release(lease) catch {}; + return self.attachment.restore(lease); + } + + /// A rooted record of `schema`, indexed under `key`, in a transaction + /// of its own. + fn makeIndexed(self: *Self, schema: u64, key: [16]u8) !core.ObjectId { + const store = &self.store; + try store.begin(); + errdefer store.abort() catch {}; + const id = try store.allocateId(); + try store.putCopying(.{ .id = id, .revision = 0, .schema = schema, .payload = &key, .rooted = true }, null); + const ticket = try store.prepare(); + const outcome = self.log.commit(try store.beginWrite(ticket)); + try store.completeWrite(ticket, outcome); + if (outcome != .committed) return error.CommitFailed; + return id; + } + }; +} diff --git a/src/pair_test.zig b/src/pair_test.zig index b850bd6..b681174 100644 --- a/src/pair_test.zig +++ b/src/pair_test.zig @@ -1,10 +1,11 @@ -//! A client and a canister-shaped server, each a byte-fed Host, exchanging -//! frames one request/response at a time, as update calls carry them. +//! A client and the canister's peer exchanging frames one request/response +//! at a time, as update calls carry them, across an upgrade. const std = @import("std"); const glowcap = @import("glowcap"); const link = @import("link.zig"); -const Counter = @import("counter.zig").Counter; +const stable_log = @import("stable_log.zig"); +const Node = @import("node.zig").Node(stable_log.TestMemory); const actors = glowcap.actors; const model = glowcap.ocapn.model; @@ -14,93 +15,162 @@ const HostSession = glowcap.driver.core.HostSession; const frame_cap = 64 * 1024; const canister_id = "uxrrr-q7777-77774-qaaaq-cai"; -fn locator() model.PeerLocator { - return .{ .transport = link.transport, .designator = canister_id, .hints = model.Hints.emptyFalse() }; -} - -/// One update call: the client's queued frames go in, the server's come back. -fn roundTrip(gpa: std.mem.Allocator, client: *Host, dialed: *HostSession, server: *Host, accepted: *HostSession) !bool { - var request: std.ArrayList(u8) = .empty; - defer request.deinit(gpa); - try link.settle(client, .hold); - try link.drainOutbound(gpa, dialed, &request); - if (request.items.len == 0) return false; - - try server.feedBytes(accepted, request.items); - try link.settle(server, .flush); - var reply: std.ArrayList(u8) = .empty; - defer reply.deinit(gpa); - try link.drainOutbound(gpa, accepted, &reply); - - try client.feedBytes(dialed, reply.items); - try link.settle(client, .hold); - return true; -} - -const CapturedRef = struct { - ref: ?model.Reference = null, +const Answer = struct { + value: union(enum) { pending, reference: model.Reference, integer: i64, string: []const u8, void, broken: []const u8 } = .pending, + buf: [128]u8 = undefined, fn record(ctx: ?*anyopaque, resolution: actors.Resolution) void { - const self: *CapturedRef = @ptrCast(@alignCast(ctx.?)); - if (resolution == .fulfilled and resolution.fulfilled == .reference) - self.ref = resolution.fulfilled.reference; + const self: *Answer = @ptrCast(@alignCast(ctx.?)); + self.value = switch (resolution) { + .fulfilled => |value| switch (value) { + .reference => |ref| .{ .reference = ref }, + .integer => |n| .{ .integer = n }, + .void => .void, + .string => |text| blk: { + @memcpy(self.buf[0..text.len], text); + break :blk .{ .string = self.buf[0..text.len] }; + }, + else => .{ .broken = "unexpected value" }, + }, + .broken => |reason| blk: { + const n = @min(reason.detail.len, self.buf.len); + @memcpy(self.buf[0..n], reason.detail[0..n]); + break :blk .{ .broken = self.buf[0..n] }; + }, + .give => .{ .broken = "give" }, + }; } }; -const CapturedInt = struct { - value: ?i64 = null, - fn record(ctx: ?*anyopaque, resolution: actors.Resolution) void { - const self: *CapturedInt = @ptrCast(@alignCast(ctx.?)); - if (resolution == .fulfilled and resolution.fulfilled == .integer) - self.value = resolution.fulfilled.integer; +/// Waiting for the session to open. +const Opened = struct { + fn done(_: Opened, client: *Client) bool { + return client.session.sessionOpen(); } }; -fn call(gpa: std.mem.Allocator, client: *Host, dialed: *HostSession, server: *Host, accepted: *HostSession, counter: model.Reference, verb: []const u8) !i64 { - var got = CapturedInt{}; - const vow = try client.send(dialed, counter, .{ .verb = verb, .args = &.{} }); - try client.vowOn(vow, .{ .ctx = &got, .func = CapturedInt.record }); - var rounds: usize = 0; - while (got.value == null) : (rounds += 1) { - if (rounds == 8) return error.CallDidNotSettle; - _ = try roundTrip(gpa, client, dialed, server, accepted); +/// Waiting for every answer to settle. +const Settled = struct { + answers: []const Answer, + fn done(self: Settled, _: *Client) bool { + for (self.answers) |answer| if (answer.value == .pending) return false; + return true; } - return got.value.?; +}; + +/// A client peer with one session to the canister. +const Client = struct { + host: Host, + session: *HostSession, + caller: []const u8, + started: bool = false, + + fn open(self: *Client, gpa: std.mem.Allocator, seed: u8, caller: []const u8) !void { + self.* = .{ .host = try Host.init(gpa, @splat(seed), @splat(seed +% 1), Host.Options.init(.unchecked, frame_cap)), .session = undefined, .caller = caller }; + _ = try self.host.defineTransport(link.profile); + try self.host.ensureAdvertisedLocator(link.transport); + self.session = try self.host.openDialedLocator(.{ .transport = link.transport, .designator = canister_id, .hints = model.Hints.emptyFalse() }); + } + + /// Carry queued frames as update calls until `done(waiting)`; return how + /// many calls that took. Frames still queued then, such as releases, + /// ride with the next call rather than costing one of their own. + fn flush(self: *Client, gpa: std.mem.Allocator, node: *Node, waiting: anytype) !usize { + var calls: usize = 0; + while (!waiting.done(self)) { + var request: std.ArrayList(u8) = .empty; + defer request.deinit(gpa); + try link.settle(&self.host, .hold); + try link.drainOutbound(gpa, self.session, &request); + if (request.items.len == 0) return error.NothingToCarry; + var reply: std.ArrayList(u8) = .empty; + defer reply.deinit(gpa); + if (self.started) { + try node.deliver(self.caller, request.items, &reply); + } else { + try node.start(self.caller, request.items, &reply); + self.started = true; + } + calls += 1; + try self.host.feedBytes(self.session, reply.items); + try link.settle(&self.host, .hold); + } + return calls; + } + + /// Send each verb, without waiting, to what `target` will settle to; + /// watch each answer in `answers`. + fn sendAll(self: *Client, target: u64, verbs: []const []const u8, answers: []Answer) !void { + for (verbs, answers[0..verbs.len]) |verb, *answer| { + const vow = try self.host.vowSend(target, .{ .verb = verb, .args = &.{} }); + try self.host.vowOn(vow, .{ .ctx = answer, .func = Answer.record }); + } + } +}; + +fn expectCounts(want: []const i64, answers: []const Answer) !void { + for (want, answers[0..want.len]) |n, answer| switch (answer.value) { + .integer => |got| try std.testing.expectEqual(n, got), + .broken => |why| { + std.debug.print("broken: {s}\n", .{why}); + return error.Broken; + }, + else => return error.NotAnInteger, + }; } -test "incr and decr a counter, one request/response per round" { +fn send(client: *Client, target: u64, verb: []const u8, args: []const model.Argument) !u64 { + return client.host.vowSend(target, .{ .verb = verb, .args = args }); +} + +test "a caller's home keeps a counter across an upgrade; sessions start over" { const gpa = std.testing.allocator; - const options = Host.Options.init(.unchecked, frame_cap); + var memory: stable_log.TestMemory = .{ .gpa = gpa }; + defer memory.bytes.deinit(gpa); - var server = try Host.init(gpa, @splat(0x51), @splat(0x52), options); - defer server.deinit(); - _ = try server.defineTransport(link.profile); - _ = try server.publish("counter", Counter, .{}); - try server.setAdvertisedLocator(locator()); - const accepted = try server.openAcceptedAdvertised(link.transport); + var node: Node = undefined; + try node.create(gpa, &memory, @splat(0x51), @splat(0x52), canister_id); - var client = try Host.init(gpa, @splat(0x61), @splat(0x62), options); - defer client.deinit(); - _ = try client.defineTransport(link.profile); - try client.ensureAdvertisedLocator(link.transport); - const dialed = try client.openDialedLocator(locator()); + // Alice makes a counter and counts on it, pipelined on the maker. + var alice: Client = undefined; + try alice.open(gpa, 0x61, "alice"); + defer alice.host.deinit(); + try std.testing.expectEqual(@as(usize, 1), try alice.flush(gpa, &node, Opened{})); + const made = try send(&alice, try alice.host.fetch(alice.session, "makeCounter"), "make", &.{}); + var answers: [8]Answer = @splat(.{}); + try alice.host.vowOn(made, .{ .ctx = &answers[0], .func = Answer.record }); + try alice.sendAll(made, &.{ "incr", "incr", "decr", "incr" }, answers[1..]); + try std.testing.expectEqual(@as(usize, 1), try alice.flush(gpa, &node, Settled{ .answers = answers[0..5] })); + try expectCounts(&.{ 1, 2, 1, 2 }, answers[1..]); - var rounds: usize = 0; - while (!dialed.sessionOpen()) : (rounds += 1) { - if (rounds == 4) return error.HandshakeDidNotFinish; - _ = try roundTrip(gpa, &client, dialed, &server, accepted); - } - try std.testing.expect(accepted.sessionOpen()); + // She keeps it in her home under "c1". + answers[5] = .{}; + const kept = try send(&alice, try alice.host.fetch(alice.session, "home"), "init", &.{ .{ .string = "c1" }, .{ .reference = answers[0].value.reference } }); + try alice.host.vowOn(kept, .{ .ctx = &answers[5], .func = Answer.record }); + try std.testing.expectEqual(@as(usize, 1), try alice.flush(gpa, &node, Settled{ .answers = answers[5..6] })); + try std.testing.expect(answers[5].value == .void); - var fetched = CapturedRef{}; - try client.vowOn(try client.fetch(dialed, "counter"), .{ .ctx = &fetched, .func = CapturedRef.record }); - rounds = 0; - while (fetched.ref == null) : (rounds += 1) { - if (rounds == 4) return error.FetchDidNotSettle; - _ = try roundTrip(gpa, &client, dialed, &server, accepted); - } - const counter = fetched.ref.?; + // The upgrade: the heap goes, stable memory stays. + node.deinit(); + try node.revive(gpa, &memory, @splat(0x54), canister_id); + defer node.deinit(); - try std.testing.expectEqual(@as(i64, 1), try call(gpa, &client, dialed, &server, accepted, counter, "incr")); - try std.testing.expectEqual(@as(i64, 2), try call(gpa, &client, dialed, &server, accepted, counter, "incr")); - try std.testing.expectEqual(@as(i64, 1), try call(gpa, &client, dialed, &server, accepted, counter, "decr")); + // Alice, in a new session, finds her counter where she left it. + var again: Client = undefined; + try again.open(gpa, 0x62, "alice"); + defer again.host.deinit(); + try std.testing.expectEqual(@as(usize, 1), try again.flush(gpa, &node, Opened{})); + answers = @splat(.{}); + try again.sendAll(try send(&again, try again.host.fetch(again.session, "home"), "get", &.{.{ .string = "c1" }}), &.{ "incr", "value" }, &answers); + try std.testing.expectEqual(@as(usize, 1), try again.flush(gpa, &node, Settled{ .answers = answers[0..2] })); + try expectCounts(&.{ 3, 3 }, &answers); + + // Bob's home is his own: nothing under "c1" there. + var bob: Client = undefined; + try bob.open(gpa, 0x71, "bob"); + defer bob.host.deinit(); + _ = try bob.flush(gpa, &node, Opened{}); + answers = @splat(.{}); + try bob.sendAll(try send(&bob, try bob.host.fetch(bob.session, "home"), "get", &.{.{ .string = "c1" }}), &.{"value"}, &answers); + _ = try bob.flush(gpa, &node, Settled{ .answers = answers[0..1] }); + try std.testing.expect(answers[0].value == .broken); }