feat: Counter over glowcap's byte-fed Host, one request/response per round

An in-memory client and canister-shaped server exchange CapTP frames
in Syrup byte-string envelopes, as update calls will carry them.

Generated-by: Claude Code (claude-opus-5-5)
This commit is contained in:
dckc committed 2026-11-18 05:37:48 -06:00
commit 6348422012
8 files changed
+272

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
//! 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 };
}
};
+60
View File
@@ -0,0 +1,60 @@
//! Carry one CapTP session's frames in request/response messages, as the
//! Internet Computer's update calls do, over glowcap's byte-fed Host.
const std = @import("std");
const glowcap = @import("glowcap");
const Host = glowcap.driver.core.Host;
const HostSession = glowcap.driver.core.HostSession;
const stream_framing = glowcap.foundation.stream_framing;
const model = glowcap.ocapn.model;
/// The OCapN transport symbol for a canister.
pub const transport = "icp";
/// How a Host reads `icp` locators. The designator is the canister's
/// principal: the Internet Computer routes calls to it and certifies its
/// replies, but CapTP sees an address, not a key it can check. Each message
/// carries frames in the byte-stream envelope (ADR-0012), so one call can
/// carry several.
pub const profile: model.transport.Metadata = .{
.symbol = transport,
.designator_scheme = .address,
};
/// Append every frame `session` has queued to `out`, each as a Syrup byte
/// string (`len:body`), the envelope `Host.feedBytes` reads on the far side.
pub fn drainOutbound(gpa: std.mem.Allocator, session: *HostSession, out: *std.ArrayList(u8)) !void {
while (try session.takeOutbound()) |frame_value| {
var frame = frame_value;
defer frame.deinit();
var prefix: [stream_framing.prefix_buffer_bytes]u8 = undefined;
try out.appendSlice(gpa, stream_framing.renderPrefix(&prefix, frame.bytes().len));
try out.appendSlice(gpa, frame.bytes());
}
}
pub const SettleError = error{
/// A handoff asked for a gift id; this embedding supplies no entropy.
GiftIdUnsupported,
/// The Host asked to dial a third party; a canister cannot.
DialUnsupported,
};
/// Run `host`'s queued actions until it is quiet. A flush needs no work here,
/// because the caller drains every session it fed after this returns.
pub fn settle(host: *Host) !void {
while (true) {
const action = (try host.nextAction()) orelse {
// Held answer releases leave at a park; this is the park.
if (try host.flushHeldReleases()) continue;
return;
};
switch (action) {
.flush, .settled, .failed, .resume_work, .close => {},
.need_gift_id => return error.GiftIdUnsupported,
.dial => return error.DialUnsupported,
.cancel_dial => |d| try host.dialCancelled(d.ticket, d.route_index),
}
}
}
+106
View File
@@ -0,0 +1,106 @@
//! 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.
const std = @import("std");
const glowcap = @import("glowcap");
const link = @import("link.zig");
const Counter = @import("counter.zig").Counter;
const actors = glowcap.actors;
const model = glowcap.ocapn.model;
const Host = glowcap.driver.core.Host;
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);
try link.drainOutbound(gpa, dialed, &request);
if (request.items.len == 0) return false;
try server.feedBytes(accepted, request.items);
try link.settle(server);
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);
return true;
}
const CapturedRef = struct {
ref: ?model.Reference = null,
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 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;
}
};
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);
}
return got.value.?;
}
test "incr and decr a counter, one request/response per round" {
const gpa = std.testing.allocator;
const options = Host.Options.init(.unchecked, frame_cap);
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 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());
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());
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.?;
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"));
}