diff --git a/.machine_readable/contractiles/Justfile b/.machine_readable/contractiles/Justfile index fc47171a..372e058b 100644 --- a/.machine_readable/contractiles/Justfile +++ b/.machine_readable/contractiles/Justfile @@ -130,6 +130,10 @@ security-test: binding-inventory: bash tests/binding_inventory.sh +# Native-connector pilot: C, Rust and Julia through ps_invoke (proven-amqp). +native-connector-smoke: + bash tests/native_connector_smoke.sh + e2e: bash tests/e2e.sh diff --git a/Justfile b/Justfile index fc47171a..372e058b 100644 --- a/Justfile +++ b/Justfile @@ -130,6 +130,10 @@ security-test: binding-inventory: bash tests/binding_inventory.sh +# Native-connector pilot: C, Rust and Julia through ps_invoke (proven-amqp). +native-connector-smoke: + bash tests/native_connector_smoke.sh + e2e: bash tests/e2e.sh diff --git a/ffi/zig/connector/ps_connector.zig b/ffi/zig/connector/ps_connector.zig new file mode 100644 index 00000000..95be3c64 --- /dev/null +++ b/ffi/zig/connector/ps_connector.zig @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +// +// ps_connector.zig -- the uniform native-connector dispatcher (pilot). +// +// A protocol exports three C symbols: +// +// uint32_t ps_abi_version(void); +// const char * ps_manifest(void); // the Idris2-emitted manifest, NUL-terminated +// uint8_t ps_invoke(uint16_t fn_tag, const ps_value *args, uint32_t n, +// ps_value *out); +// +// A connector in any language binds only those three, reads the manifest to +// learn the function table, and calls through ps_invoke. One connector per +// language then serves every protocol that exports this surface. +// +// The function table, kind tags, status tags and value-cell layout all come +// from the protocol's generated `_abi_gen.zig`, which tools/gen-abi.sh +// renders from the Idris2 `ABI.Connector` module. `Dispatcher` checks +// at comptime that every table entry names a real export whose Zig parameter +// types match the Idris2 kinds, so drift is a build error, not a runtime bug. +// +// The Zig code here is FFI only (pure Zig). The ABI it is checked against is +// pure Idris2. + +const std = @import("std"); + +/// One argument or result cell. 32 bytes on every target (see the +/// PS_VALUE_* layout constants in the generated file). +pub const Value = extern struct { + kind: u8, + _pad: [7]u8 = [_]u8{0} ** 7, + word: u64 align(8) = 0, + addr: u64 = 0, + len: u64 = 0, +}; + +/// Logical kind of a Zig parameter or result type. +fn kindOf(comptime T: type) []const u8 { + if (T == void) return "VOID"; + if (T == c_int or T == i32) return "I32"; + if (T == u8) return "U8"; + if (T == u16) return "U16"; + if (T == u32) return "U32"; + if (T == u64) return "U64"; + @compileError("ps_connector: unsupported type " ++ @typeName(T)); +} + +fn isBytesPtr(comptime T: type) bool { + return T == [*]const u8; +} + +/// The space-separated logical kinds of a function's parameters. A +/// `[*]const u8` followed by a `u32` is one BYTES argument. +fn paramKinds(comptime F: type) []const u8 { + const params = @typeInfo(F).@"fn".params; + comptime var out: []const u8 = ""; + comptime var i: usize = 0; + inline while (i < params.len) { + const P = params[i].type.?; + const k = if (isBytesPtr(P)) blk: { + if (i + 1 >= params.len or params[i + 1].type.? != u32) + @compileError("ps_connector: a [*]const u8 parameter must be followed by its u32 length"); + i += 2; + break :blk "BYTES"; + } else blk: { + i += 1; + break :blk kindOf(P); + }; + out = if (out.len == 0) k else out ++ " " ++ k; + } + return out; +} + +fn logicalArity(comptime kinds: []const u8) usize { + if (kinds.len == 0) return 0; + return std.mem.count(u8, kinds, " ") + 1; +} + +const empty_bytes = [_]u8{0}; + +/// Build the dispatcher for one protocol. +/// impl -- the protocol's Zig file (`@This()`), holding the exports +/// prefix -- the export prefix, e.g. "amqp_" +/// gen -- the generated `_abi_gen.zig` +pub fn Dispatcher(comptime impl: type, comptime prefix: []const u8, comptime gen: type) type { + return struct { + comptime { + if (@sizeOf(Value) != gen.PS_VALUE_SIZE) @compileError("ABI drift: ps_value size"); + if (@alignOf(Value) != gen.PS_VALUE_ALIGN) @compileError("ABI drift: ps_value align"); + if (@offsetOf(Value, "kind") != gen.PS_VALUE_OFF_KIND) @compileError("ABI drift: ps_value.kind"); + if (@offsetOf(Value, "word") != gen.PS_VALUE_OFF_WORD) @compileError("ABI drift: ps_value.word"); + if (@offsetOf(Value, "addr") != gen.PS_VALUE_OFF_ADDR) @compileError("ABI drift: ps_value.addr"); + if (@offsetOf(Value, "len") != gen.PS_VALUE_OFF_LEN) @compileError("ABI drift: ps_value.len"); + + @setEvalBranchQuota(200_000); + for (gen.FNS, 0..) |f, i| { + if (f.tag != i + 1) @compileError("ABI drift: FN tags must run 1..n in order, at " ++ f.name); + const sym = prefix ++ f.name; + if (!@hasDecl(impl, sym)) @compileError("ABI drift: Idris2 lists " ++ sym ++ " but Zig has no such export"); + const F = @TypeOf(@field(impl, sym)); + const ret = kindOf(@typeInfo(F).@"fn".return_type.?); + if (!std.mem.eql(u8, ret, f.ret)) + @compileError("ABI drift: " ++ sym ++ " returns " ++ ret ++ ", Idris2 says " ++ f.ret); + const got = paramKinds(F); + if (!std.mem.eql(u8, got, f.kinds)) + @compileError("ABI drift: " ++ sym ++ " takes (" ++ got ++ "), Idris2 says (" ++ f.kinds ++ ")"); + } + } + + fn status(comptime name: []const u8) u8 { + return @field(gen, "STATUS_" ++ name); + } + + fn kindTag(comptime name: []const u8) u8 { + return @field(gen, "KIND_" ++ name); + } + + fn decodeInt(comptime P: type, comptime kname: []const u8, v: Value) ?P { + if (v.kind != kindTag(kname)) return null; + if (P == c_int or P == i32) { + // I32 travels sign-extended in the u64 word. Decode it with + // plain integer arithmetic: words up to maxInt(i32) are the + // non-negatives, words from 0xFFFF_FFFF_8000_0000 up are the + // two's-complement negatives, and anything between is RANGE. + const max: u64 = std.math.maxInt(i32); + const neg_floor: u64 = 0xFFFF_FFFF_8000_0000; + if (v.word <= max) return @intCast(v.word); + if (v.word < neg_floor) return null; + const mag: i64 = @intCast(~v.word); // 0 ..= maxInt(i32) + return @intCast(-mag - 1); + } + if (v.word > std.math.maxInt(P)) return null; + return @intCast(v.word); + } + + fn call(comptime f: gen.FnSig, args: ?[*]const Value, n: u32, out: *Value) u8 { + const func = @field(impl, prefix ++ f.name); + const F = @TypeOf(func); + const params = @typeInfo(F).@"fn".params; + const arity = comptime logicalArity(f.kinds); + if (n != arity) return status("ARITY"); + if (arity > 0 and args == null) return status("NULL_PTR"); + + var tuple: std.meta.ArgsTuple(F) = undefined; + comptime var pi: usize = 0; + comptime var li: usize = 0; + inline while (pi < params.len) { + const P = params[pi].type.?; + const v = args.?[li]; + if (comptime isBytesPtr(P)) { + if (v.kind != kindTag("BYTES")) return status("KIND_MISMATCH"); + if (v.len > std.math.maxInt(u32)) return status("RANGE"); + if (v.addr == 0 and v.len != 0) return status("NULL_PTR"); + if (v.addr > std.math.maxInt(usize)) return status("RANGE"); + tuple[pi] = if (v.addr == 0) &empty_bytes else @ptrFromInt(@as(usize, @intCast(v.addr))); + tuple[pi + 1] = @intCast(v.len); + pi += 2; + } else { + const kname = comptime kindOf(P); + if (v.kind != kindTag(kname)) return status("KIND_MISMATCH"); + tuple[pi] = decodeInt(P, kname, v) orelse return status("RANGE"); + pi += 1; + } + li += 1; + } + + const R = @typeInfo(F).@"fn".return_type.?; + const r = @call(.auto, func, tuple); + out.* = .{ .kind = kindTag(comptime kindOf(R)) }; + if (R == c_int or R == i32) { + // Sign-extend to u64 with plain integer arithmetic. + const wide: i64 = r; + out.word = if (wide >= 0) @intCast(wide) else ~@as(u64, @intCast(-(wide + 1))); + } else if (R != void) { + out.word = r; + } + return status("OK"); + } + + /// Body of the protocol's `ps_invoke` export. + pub fn invoke(tag: u16, args: ?[*]const Value, n: u32, out: ?*Value) u8 { + const o = out orelse return status("NULL_PTR"); + inline for (gen.FNS) |f| { + if (f.tag == tag) return call(f, args, n, o); + } + return status("UNKNOWN_FN"); + } + }; +} diff --git a/native-connectors/README.adoc b/native-connectors/README.adoc new file mode 100644 index 00000000..97b2d4a0 --- /dev/null +++ b/native-connectors/README.adoc @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) += Native connectors (pilot) + +This is the pilot of the uniform connector surface. It is meant to replace +the hand-copied tag tables in `bindings//`. Nothing there is +deleted yet: the owner reviews this shape first. + +== The idea + +A protocol library exports three C symbols and nothing else is bound: + +[source,c] +---- +uint32_t ps_abi_version(void); +const char * ps_manifest(void); +uint8_t ps_invoke(uint16_t fn_tag, const ps_value *args, uint32_t n, ps_value *out); +---- + +`ps_manifest` returns text emitted by the protocol's Idris2 ABI. It holds +the enum tags, the value-cell layout, the kind and status tags, and one `FN` +line per callable function: + +---- +FN 2 create I32 vhost:BYTES frame_max:U32 channel_max:U16 heartbeat:U16 +---- + +A connector reads the manifest when it opens the library. So one connector +per language serves every protocol, and adding a protocol or a function +needs no connector change. + +== Where each part lives + +[cols="1,2",options="header"] +|=== +| Part | File +| ABI (pure Idris2) | `protocols/proven-amqp/src/AMQPABI/Connector.idr`, printed by `AMQPABI/Emit.idr` +| Rendering | `tools/gen-abi.sh` writes the `FNS` table and `MANIFEST` into `amqp_abi_gen.zig`, only for protocols that emit `FN` lines +| FFI (pure Zig) | `ffi/zig/connector/ps_connector.zig` (shared dispatcher), plus three exports at the end of `protocols/proven-amqp/ffi/zig/src/amqp.zig` +| Connectors | `c/`, `rust/`, `julia/ProvenConnector/` +|=== + +The Zig dispatcher checks every Idris2 signature against the real `amqp_*` +export at comptime. A changed parameter type, a missing export or a +reordered table fails `zig build`. It also checks the value-cell layout. + +Each connector checks the manifest layout against its own `ps_value` when +it opens the library, and refuses a mismatch. + +`ps_invoke` checks arity, kinds, integer ranges and null buffers before it +calls anything. Its statuses are `OK`, `UNKNOWN_FN`, `ARITY`, +`KIND_MISMATCH`, `RANGE` and `NULL_PTR`, with the tags given in the manifest. + +== Running the smoke tests + +---- +# From the repository root. +(cd protocols/proven-amqp/ffi/zig && zig build -Doptimize=ReleaseSafe) +LIB=$PWD/protocols/proven-amqp/ffi/zig/zig-out/lib/libproven_amqp.so +# C +cc -std=c11 -Wall -Wextra -o /tmp/ps-smoke native-connectors/c/smoke.c native-connectors/c/ps_connector.c -ldl && /tmp/ps-smoke "$LIB" +# Rust +PS_AMQP_LIB="$LIB" cargo test --manifest-path native-connectors/rust/Cargo.toml +# Julia +PS_AMQP_LIB="$LIB" julia --project=native-connectors/julia/ProvenConnector -e 'using Pkg; Pkg.test()' +---- + +`just native-connector-smoke` runs all three. + +== Limits of the pilot + +* Only proven-amqp exports the surface. +* Loading is POSIX `dlopen` only. Windows `LoadLibrary` is not done. +* Results are integers or void. No function returns a buffer yet. +* Verification: the Rust connector is to be verified with Creusot + (Pearlite contracts) and Verus (`3-practice/PROOF-POLICY.adoc` ยง1.2 in + standards). Both are PENDING. The first obligation to scope is that + `Library::call` passes `ps_invoke` only cells that match the manifest + signature. The `unsafe` dlopen and FFI seam is a Kani candidate. Today + the evidence is the smoke tests and the Zig comptime guard. diff --git a/native-connectors/c/ps_connector.c b/native-connectors/c/ps_connector.c new file mode 100644 index 00000000..23f6f63f --- /dev/null +++ b/native-connectors/c/ps_connector.c @@ -0,0 +1,143 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) */ +/* + * ps_connector.c -- loader for the uniform proven-servers connector surface. + * POSIX dlopen only (Linux, macOS, BSD). + */ +#include "ps_connector.h" + +#include +#include +#include +#include + +static const char *const kind_names[PS_KIND_COUNT] = { + "VOID", "I32", "U8", "U16", "U32", "U64", "BYTES" +}; + +static void set_err(char *err, size_t errlen, const char *msg, const char *detail) { + if (err && errlen) snprintf(err, errlen, "%s%s%s", msg, detail ? ": " : "", detail ? detail : ""); +} + +/* Find a line whose first two fields are a and b; return a pointer just past + * them (at the separating space), or NULL. */ +static const char *find_line(const char *text, const char *a, const char *b) { + size_t la = strlen(a); + size_t lb = strlen(b); + const char *p = text; + while (p && *p) { + if (strncmp(p, a, la) == 0 && p[la] == ' ' && strncmp(p + la + 1, b, lb) == 0 && + (p[la + 1 + lb] == ' ' || p[la + 1 + lb] == '\n' || p[la + 1 + lb] == '\0')) + return p + la + 1 + lb; + p = strchr(p, '\n'); + if (p) p++; + } + return NULL; +} + +int ps_const(const ps_lib *lib, const char *kind, const char *name, uint64_t *out) { + const char *p = find_line(lib->text, kind, name); + if (!p || *p != ' ') return 0; + char *end = NULL; + unsigned long long v = strtoull(p + 1, &end, 10); + if (end == p + 1) return 0; + *out = (uint64_t)v; + return 1; +} + +uint16_t ps_fn_tag(const ps_lib *lib, const char *name) { + /* FN ... : the name is the third field. */ + size_t ln = strlen(name); + const char *p = lib->text; + while (p && *p) { + if (strncmp(p, "FN ", 3) == 0) { + char *end = NULL; + unsigned long tag = strtoul(p + 3, &end, 10); + if (end && *end == ' ' && strncmp(end + 1, name, ln) == 0 && end[1 + ln] == ' ') + return (uint16_t)tag; + } + p = strchr(p, '\n'); + if (p) p++; + } + return 0; +} + +int ps_open(ps_lib *lib, const char *path, char *err, size_t errlen) { + memset(lib, 0, sizeof *lib); + lib->dl = dlopen(path, RTLD_NOW | RTLD_LOCAL); + if (!lib->dl) { set_err(err, errlen, "dlopen failed", dlerror()); return -1; } + *(void **)&lib->abi_version = dlsym(lib->dl, "ps_abi_version"); + *(void **)&lib->manifest = dlsym(lib->dl, "ps_manifest"); + *(void **)&lib->invoke = dlsym(lib->dl, "ps_invoke"); + if (!lib->abi_version || !lib->manifest || !lib->invoke) { + set_err(err, errlen, "library does not export the ps_* connector surface", path); + ps_close(lib); + return -1; + } + if (lib->abi_version() != PS_CONNECTOR_ABI) { + set_err(err, errlen, "unsupported connector ABI version", NULL); + ps_close(lib); + return -1; + } + lib->text = lib->manifest(); + + static const struct { const char *name; uint64_t want; } layout[] = { + { "PS_VALUE_SIZE", sizeof(ps_value) }, + { "PS_VALUE_ALIGN", _Alignof(ps_value) }, + { "PS_VALUE_OFF_KIND", offsetof(ps_value, kind) }, + { "PS_VALUE_OFF_WORD", offsetof(ps_value, word) }, + { "PS_VALUE_OFF_ADDR", offsetof(ps_value, addr) }, + { "PS_VALUE_OFF_LEN", offsetof(ps_value, len) }, + }; + for (size_t i = 0; i < sizeof layout / sizeof layout[0]; i++) { + uint64_t got; + if (!ps_const(lib, "LAYOUT", layout[i].name, &got) || got != layout[i].want) { + set_err(err, errlen, "manifest layout does not match ps_value", layout[i].name); + ps_close(lib); + return -1; + } + } + for (int k = 0; k < PS_KIND_COUNT; k++) { + uint64_t tag; + if (!ps_const(lib, "KIND", kind_names[k], &tag) || tag > 255) { + set_err(err, errlen, "manifest lacks kind tag", kind_names[k]); + ps_close(lib); + return -1; + } + lib->kind_tag[k] = (uint8_t)tag; + } + return 0; +} + +void ps_close(ps_lib *lib) { + if (lib->dl) dlclose(lib->dl); + memset(lib, 0, sizeof *lib); +} + +ps_value ps_int(const ps_lib *lib, ps_kind kind, int64_t v) { + ps_value c; + memset(&c, 0, sizeof c); + c.kind = lib->kind_tag[kind]; + c.word = (uint64_t)v; + return c; +} + +ps_value ps_bytes(const ps_lib *lib, const void *ptr, size_t len) { + ps_value c; + memset(&c, 0, sizeof c); + c.kind = lib->kind_tag[PS_BYTES]; + c.addr = (uint64_t)(uintptr_t)ptr; + c.len = (uint64_t)len; + return c; +} + +uint8_t ps_call(const ps_lib *lib, const char *name, const ps_value *args, + uint32_t n, ps_value *out) { + uint16_t tag = ps_fn_tag(lib, name); + uint64_t unknown = 1; + if (tag == 0) { + ps_const(lib, "STATUS", "UNKNOWN_FN", &unknown); + return (uint8_t)unknown; + } + return lib->invoke(tag, args, n, out); +} diff --git a/native-connectors/c/ps_connector.h b/native-connectors/c/ps_connector.h new file mode 100644 index 00000000..438fc8ef --- /dev/null +++ b/native-connectors/c/ps_connector.h @@ -0,0 +1,74 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) */ +/* + * ps_connector.h -- native C connector for the uniform proven-servers surface. + * + * A protocol library exports ps_abi_version, ps_manifest and ps_invoke + * (see ffi/zig/connector/ps_connector.zig). This connector binds only those + * three. Function tags, kind tags, status tags and the value-cell layout are + * read from the Idris2-emitted manifest at open time; nothing about any + * protocol is hard-coded here, so the same connector serves every protocol. + * + * ps_open refuses a library whose manifest layout differs from ps_value. + */ +#ifndef PS_CONNECTOR_H +#define PS_CONNECTOR_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Connector ABI version this connector speaks. */ +#define PS_CONNECTOR_ABI 1u + +typedef struct ps_value { + uint8_t kind; + uint8_t _pad[7]; + uint64_t word; /* integer payload; I32 is sign-extended */ + uint64_t addr; /* BYTES: buffer address */ + uint64_t len; /* BYTES: buffer length */ +} ps_value; + +/* Logical kinds. Their wire tags come from the manifest (KIND lines). */ +typedef enum ps_kind { + PS_VOID, PS_I32, PS_U8, PS_U16, PS_U32, PS_U64, PS_BYTES, PS_KIND_COUNT +} ps_kind; + +typedef struct ps_lib { + void *dl; + uint32_t (*abi_version)(void); + const char *(*manifest)(void); + uint8_t (*invoke)(uint16_t, const ps_value *, uint32_t, ps_value *); + const char *text; /* manifest, static lifetime in the library */ + uint8_t kind_tag[PS_KIND_COUNT]; +} ps_lib; + +/* Open a protocol library. Returns 0 on success; on failure writes a + * message to err (if non-NULL) and returns -1. */ +int ps_open(ps_lib *lib, const char *path, char *err, size_t errlen); +void ps_close(ps_lib *lib); + +/* Look up `KIND NAME VALUE` in the manifest (e.g. "EXCH", "TOPIC"). + * Returns 1 and sets *out when found, 0 otherwise. */ +int ps_const(const ps_lib *lib, const char *kind, const char *name, uint64_t *out); + +/* Function tag for NAME (without protocol prefix), or 0 if absent. */ +uint16_t ps_fn_tag(const ps_lib *lib, const char *name); + +/* Argument constructors. */ +ps_value ps_int(const ps_lib *lib, ps_kind kind, int64_t v); +ps_value ps_bytes(const ps_lib *lib, const void *ptr, size_t len); + +/* Call NAME. Returns the ps_invoke status (0 = OK); 1 (UNKNOWN_FN) when the + * name is not in the manifest. */ +uint8_t ps_call(const ps_lib *lib, const char *name, const ps_value *args, + uint32_t n, ps_value *out); + +#ifdef __cplusplus +} +#endif + +#endif /* PS_CONNECTOR_H */ diff --git a/native-connectors/c/smoke.c b/native-connectors/c/smoke.c new file mode 100644 index 00000000..0f03bcce --- /dev/null +++ b/native-connectors/c/smoke.c @@ -0,0 +1,77 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) */ +/* + * smoke.c -- C connector smoke test against proven-amqp. + * Usage: smoke /path/to/libproven_amqp.so + */ +#include "ps_connector.h" + +#include +#include + +static int failures = 0; + +#define CHECK(cond, what) \ + do { \ + if (cond) { printf("ok %s\n", what); } \ + else { printf("FAIL %s\n", what); failures++; } \ + } while (0) + +static uint64_t status(const ps_lib *lib, const char *name) { + uint64_t v = 255; + ps_const(lib, "STATUS", name, &v); + return v; +} + +int main(int argc, char **argv) { + if (argc != 2) { fprintf(stderr, "usage: %s LIB\n", argv[0]); return 2; } + ps_lib lib; + char err[256]; + if (ps_open(&lib, argv[1], err, sizeof err) != 0) { fprintf(stderr, "%s\n", err); return 1; } + + ps_value out; + uint64_t ok = status(&lib, "OK"); + + CHECK(ps_call(&lib, "abi_version", NULL, 0, &out) == ok && out.word == 1, "abi_version == 1"); + + const char *vhost = "/"; + ps_value create_args[4] = { + ps_bytes(&lib, vhost, strlen(vhost)), ps_int(&lib, PS_U32, 131072), + ps_int(&lib, PS_U16, 16), ps_int(&lib, PS_U16, 60), + }; + CHECK(ps_call(&lib, "create", create_args, 4, &out) == ok && (int64_t)out.word >= 0, "create returns a slot"); + int64_t slot = (int64_t)out.word; + + ps_value open_args[2] = { ps_int(&lib, PS_I32, slot), ps_int(&lib, PS_U16, 1) }; + CHECK(ps_call(&lib, "channel_open", open_args, 2, &out) == ok && out.word == 0, "channel_open accepted"); + + uint64_t channel_open = 0; + ps_const(&lib, "BROKER", "CHANNEL_OPEN", &channel_open); + ps_value slot_arg = ps_int(&lib, PS_I32, slot); + CHECK(ps_call(&lib, "state", &slot_arg, 1, &out) == ok && out.word == channel_open, "state is BROKER CHANNEL_OPEN"); + + uint64_t topic = 0; + ps_const(&lib, "EXCH", "TOPIC", &topic); + const char *key = "stock.usd.nyse"; + const char *pat = "stock.*.nyse"; + ps_value rm_args[3] = { + ps_bytes(&lib, key, strlen(key)), ps_bytes(&lib, pat, strlen(pat)), ps_int(&lib, PS_U8, (int64_t)topic), + }; + CHECK(ps_call(&lib, "routing_match", rm_args, 3, &out) == ok && out.word == 1, "topic routing_match"); + + CHECK(ps_call(&lib, "destroy", &slot_arg, 1, &out) == ok, "destroy (VOID result)"); + + /* The dispatcher's own checks. */ + CHECK(lib.invoke(9999, NULL, 0, &out) == status(&lib, "UNKNOWN_FN"), "unknown tag rejected"); + CHECK(ps_call(&lib, "state", NULL, 0, &out) == status(&lib, "ARITY"), "wrong arity rejected"); + ps_value wrong_kind = ps_int(&lib, PS_U8, 0); + CHECK(ps_call(&lib, "state", &wrong_kind, 1, &out) == status(&lib, "KIND_MISMATCH"), "wrong kind rejected"); + ps_value too_big = ps_int(&lib, PS_U16, 70000); + ps_value range_args[2] = { slot_arg, too_big }; + CHECK(ps_call(&lib, "channel_open", range_args, 2, &out) == status(&lib, "RANGE"), "out-of-range u16 rejected"); + CHECK(lib.invoke(ps_fn_tag(&lib, "state"), &slot_arg, 1, NULL) == status(&lib, "NULL_PTR"), "null out rejected"); + + ps_close(&lib); + printf("%s (%d failure%s)\n", failures ? "FAILED" : "PASSED", failures, failures == 1 ? "" : "s"); + return failures ? 1 : 0; +} diff --git a/native-connectors/julia/ProvenConnector/.gitignore b/native-connectors/julia/ProvenConnector/.gitignore new file mode 100644 index 00000000..0b35561b --- /dev/null +++ b/native-connectors/julia/ProvenConnector/.gitignore @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MPL-2.0 +# Pkg.test regenerates this; a package does not pin its manifest. +Manifest.toml diff --git a/native-connectors/julia/ProvenConnector/Project.toml b/native-connectors/julia/ProvenConnector/Project.toml new file mode 100644 index 00000000..35540913 --- /dev/null +++ b/native-connectors/julia/ProvenConnector/Project.toml @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +name = "ProvenConnector" +uuid = "c3b6cbca-1928-4d88-903d-3f2d6b650aad" +version = "0.1.0" + +[deps] +Libdl = "8f399da3-3557-5675-b5ff-fb832c97cbdb" + +[extras] +Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + +[targets] +test = ["Test"] diff --git a/native-connectors/julia/ProvenConnector/src/ProvenConnector.jl b/native-connectors/julia/ProvenConnector/src/ProvenConnector.jl new file mode 100644 index 00000000..1e9c1594 --- /dev/null +++ b/native-connectors/julia/ProvenConnector/src/ProvenConnector.jl @@ -0,0 +1,199 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) + +""" +Native Julia connector for the uniform proven-servers surface. + +A protocol library exports `ps_abi_version`, `ps_manifest` and `ps_invoke` +(see `ffi/zig/connector/ps_connector.zig`). This module binds only those +three. Function tags, kind tags, status tags and the value-cell layout are +read from the Idris2-emitted manifest at open time, so one connector serves +every protocol. +""" +module ProvenConnector + +using Libdl + +export Library, call, constant, signature, close_library, PSError + +const CONNECTOR_ABI = UInt32(1) + +"One argument or result cell; layout checked against the manifest at open." +struct Value + kind::UInt8 + pad::NTuple{7,UInt8} + word::UInt64 + addr::UInt64 + len::UInt64 +end +Value(kind::UInt8; word::UInt64 = UInt64(0), addr::UInt64 = UInt64(0), len::UInt64 = UInt64(0)) = + Value(kind, ntuple(_ -> 0x00, 7), word, addr, len) + +const KIND_NAMES = ("VOID", "I32", "U8", "U16", "U32", "U64", "BYTES") + +struct FnSig + tag::UInt16 + name::String + ret::String + args::Vector{Pair{String,String}} +end + +struct PSError <: Exception + msg::String + status::String +end +PSError(msg) = PSError(msg, "") +Base.showerror(io::IO, e::PSError) = print(io, "PSError: ", e.msg) + +mutable struct Library + handle::Ptr{Cvoid} + invoke::Ptr{Cvoid} + manifest::String + consts::Dict{Tuple{String,String},UInt64} + fns::Dict{String,FnSig} + kind_tag::Dict{String,UInt8} + tag_kind::Dict{UInt8,String} + status_name::Dict{UInt8,String} +end + +"Open a protocol library and validate its manifest." +function Library(path::AbstractString) + h = Libdl.dlopen(path) + abi = Libdl.dlsym(h, :ps_abi_version; throw_error = false) + man = Libdl.dlsym(h, :ps_manifest; throw_error = false) + inv = Libdl.dlsym(h, :ps_invoke; throw_error = false) + if abi === nothing || man === nothing || inv === nothing + Libdl.dlclose(h) + throw(PSError("$path does not export the ps_* connector surface")) + end + v = ccall(abi, UInt32, ()) + if v != CONNECTOR_ABI + Libdl.dlclose(h) + throw(PSError("connector ABI $v, this module speaks $CONNECTOR_ABI")) + end + text = unsafe_string(ccall(man, Cstring, ())) + lib = Library(h, inv, text, Dict(), Dict(), Dict(), Dict(), Dict()) + try + parse_manifest!(lib) + catch + Libdl.dlclose(h) + rethrow() + end + finalizer(close_library, lib) + return lib +end + +function close_library(lib::Library) + if lib.handle != C_NULL + Libdl.dlclose(lib.handle) + lib.handle = C_NULL + end + nothing +end + +function parse_manifest!(lib::Library) + for line in split(lib.manifest, '\n'; keepempty = false) + f = split(line, ' ') + if f[1] == "FN" + length(f) >= 4 || throw(PSError("short FN line: $line")) + args = Pair{String,String}[] + for a in f[5:end] + n, k = split(a, ':') + k in KIND_NAMES || throw(PSError("bad kind: $line")) + push!(args, String(n) => String(k)) + end + f[4] in KIND_NAMES || throw(PSError("bad kind: $line")) + lib.fns[String(f[3])] = FnSig(parse(UInt16, f[2]), String(f[3]), String(f[4]), args) + elseif length(f) == 3 + v = tryparse(UInt64, f[3]) + v === nothing || (lib.consts[(String(f[1]), String(f[2]))] = v) + end + end + for (name, want) in (("PS_VALUE_SIZE", sizeof(Value)), + ("PS_VALUE_OFF_KIND", fieldoffset(Value, 1)), + ("PS_VALUE_OFF_WORD", fieldoffset(Value, 3)), + ("PS_VALUE_OFF_ADDR", fieldoffset(Value, 4)), + ("PS_VALUE_OFF_LEN", fieldoffset(Value, 5))) + get(lib.consts, ("LAYOUT", name), nothing) == want || + throw(PSError("layout $name does not match Value")) + end + for k in KIND_NAMES + t = get(lib.consts, ("KIND", k), nothing) + t === nothing && throw(PSError("no KIND $k")) + lib.kind_tag[k] = UInt8(t) + lib.tag_kind[UInt8(t)] = k + end + for ((kind, name), v) in lib.consts + kind == "STATUS" && (lib.status_name[UInt8(v)] = name) + end + "OK" in values(lib.status_name) || throw(PSError("no STATUS OK")) + lib +end + +"A `KIND NAME VALUE` manifest constant, or `nothing`." +constant(lib::Library, kind::AbstractString, name::AbstractString) = + get(lib.consts, (String(kind), String(name)), nothing) + +signature(lib::Library, name::AbstractString) = get(lib.fns, String(name), nothing) + +"Byte buffers whose `pointer` addresses their own logical bytes." +const DenseBytes = Union{Vector{UInt8},Base.CodeUnits{UInt8,String}} + +"Copy a byte view or other non-dense byte array into a fresh `Vector{UInt8}`." +bytes_arg(a) = a isa AbstractString ? codeunits(String(a)) : + (a isa AbstractVector{UInt8} && !(a isa DenseBytes)) ? Vector{UInt8}(a) : a + +const INT_KINDS = Dict("I32" => Int32, "U8" => UInt8, "U16" => UInt16, "U32" => UInt32, "U64" => UInt64) + +function cell(lib::Library, kind::String, x) + if kind == "BYTES" + b = x isa AbstractString ? codeunits(String(x)) : x + b isa DenseBytes || + throw(PSError("BYTES cell needs a String or a dense byte vector, got $(typeof(b))")) + return Value(lib.kind_tag["BYTES"]; addr = UInt64(UInt(pointer(b))), len = UInt64(length(b))) + end + T = INT_KINDS[kind] + v = convert(T, x) # throws InexactError when out of range + word = T === Int32 ? reinterpret(UInt64, Int64(v)) : UInt64(v) + return Value(lib.kind_tag[kind]; word = word) +end + +""" + invoke_raw(lib, tag, cells, roots...) + +Call by tag without the manifest check. `roots` are kept alive for the call. +Returns `(status_name, out::Value)`. +""" +function invoke_raw(lib::Library, tag::Integer, cells::Vector{Value}, roots...) + lib.handle == C_NULL && throw(PSError("library is closed")) + out = Ref(Value(0x00)) + st = GC.@preserve cells roots begin + ccall(lib.invoke, UInt8, (UInt16, Ptr{Value}, UInt32, Ptr{Value}), + UInt16(tag), isempty(cells) ? Ptr{Value}(C_NULL) : pointer(cells), + UInt32(length(cells)), out) + end + return get(lib.status_name, st, "UNKNOWN"), out[] +end + +""" + call(lib, name, args...) + +Call NAME, checked against the manifest signature. Strings and byte vectors +pass as BYTES. Returns `nothing` for a VOID result, else the integer. +""" +function call(lib::Library, name::AbstractString, args...) + sig = signature(lib, name) + sig === nothing && throw(PSError("no function $name in manifest")) + length(args) == length(sig.args) || + throw(PSError("$name takes $(length(sig.args)) arguments, got $(length(args))")) + bufs = Any[bytes_arg(a) for a in args] + cells = Value[cell(lib, k, b) for ((_, k), b) in zip(sig.args, bufs)] + st, out = invoke_raw(lib, sig.tag, cells, bufs) + st == "OK" || throw(PSError("ps_invoke status $st", st)) + k = lib.tag_kind[out.kind] + k == "VOID" && return nothing + T = INT_KINDS[k] + return T === Int32 ? Int32(reinterpret(Int64, out.word)) : T(out.word) +end + +end # module diff --git a/native-connectors/julia/ProvenConnector/test/runtests.jl b/native-connectors/julia/ProvenConnector/test/runtests.jl new file mode 100644 index 00000000..3b9d69a3 --- /dev/null +++ b/native-connectors/julia/ProvenConnector/test/runtests.jl @@ -0,0 +1,49 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +# +# Smoke test against proven-amqp. Set PS_AMQP_LIB to the built +# libproven_amqp shared library; the tests are skipped when it is unset. + +using Test +using ProvenConnector +using ProvenConnector: invoke_raw, cell, Value + +path = get(ENV, "PS_AMQP_LIB", "") +if isempty(path) + @info "PS_AMQP_LIB not set; skipping" +else + lib = Library(path) + @testset "proven-amqp through ps_invoke" begin + @test call(lib, "abi_version") == UInt32(1) + slot = call(lib, "create", "/", 131072, 16, 60) + @test slot isa Int32 && slot >= 0 + @test call(lib, "channel_open", slot, 1) == 0x00 + @test call(lib, "state", slot) == UInt8(constant(lib, "BROKER", "CHANNEL_OPEN")) + topic = constant(lib, "EXCH", "TOPIC") + @test call(lib, "routing_match", "stock.usd.nyse", "stock.*.nyse", topic) == 0x01 + # A strided view passes its logical bytes, not its parent's. + key = Vector{UInt8}("sxtxoxcxkx.xuxsxdx.xnxyxsxex") + @test call(lib, "routing_match", view(key, 1:2:length(key)), "stock.*.nyse", topic) == 0x01 + @test call(lib, "destroy", slot) === nothing + @test [n for (n, _) in signature(lib, "create").args] == ["vhost", "frame_max", "channel_max", "heartbeat"] + end + @testset "rejections" begin + @test_throws PSError call(lib, "nope") + @test_throws PSError call(lib, "state") + @test_throws InexactError call(lib, "channel_open", 0, 70000) + state = signature(lib, "state").tag + @test invoke_raw(lib, 9999, Value[])[1] == "UNKNOWN_FN" + @test invoke_raw(lib, state, Value[])[1] == "ARITY" + @test invoke_raw(lib, state, [cell(lib, "U8", 0)])[1] == "KIND_MISMATCH" + big = Value(lib.kind_tag["U16"]; word = UInt64(70000)) + @test invoke_raw(lib, signature(lib, "channel_open").tag, [cell(lib, "I32", 0), big])[1] == "RANGE" + nul = Value(lib.kind_tag["BYTES"]; len = UInt64(4)) + @test invoke_raw(lib, signature(lib, "routing_match").tag, [nul, nul, cell(lib, "U8", 2)])[1] == "NULL_PTR" + end + close_library(lib) + @testset "closed" begin + @test_throws PSError call(lib, "abi_version") + close_library(lib) # repeated cleanup is a no-op + @test lib.handle == C_NULL + end +end diff --git a/native-connectors/rust/Cargo.lock b/native-connectors/rust/Cargo.lock new file mode 100644 index 00000000..4465880d --- /dev/null +++ b/native-connectors/rust/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "proven-connector" +version = "0.1.0" diff --git a/native-connectors/rust/Cargo.toml b/native-connectors/rust/Cargo.toml new file mode 100644 index 00000000..e97d3f56 --- /dev/null +++ b/native-connectors/rust/Cargo.toml @@ -0,0 +1,11 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +[package] +name = "proven-connector" +version = "0.1.0" +edition = "2021" +license = "MPL-2.0" +description = "Native Rust connector for the uniform proven-servers ps_* surface" +publish = false + +[dependencies] diff --git a/native-connectors/rust/src/lib.rs b/native-connectors/rust/src/lib.rs new file mode 100644 index 00000000..304056a2 --- /dev/null +++ b/native-connectors/rust/src/lib.rs @@ -0,0 +1,467 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) + +//! Native Rust connector for the uniform proven-servers surface. +//! +//! A protocol library exports `ps_abi_version`, `ps_manifest` and +//! `ps_invoke` (see `ffi/zig/connector/ps_connector.zig`). This crate binds +//! only those three. Function tags, kind tags, status tags and the value-cell +//! layout are read from the Idris2-emitted manifest when the library is +//! opened, so one connector serves every protocol. No dependencies; POSIX +//! `dlopen` only. + +use std::collections::HashMap; +use std::ffi::{c_char, c_int, c_void, CStr, CString}; +use std::fmt; +use std::marker::PhantomData; + +/// Connector ABI version this crate speaks. +pub const CONNECTOR_ABI: u32 = 1; + +/// One argument or result cell, laid out as the manifest's `PS_VALUE_*` +/// constants say (checked in [`Library::open`]). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct Value { + pub kind: u8, + pub pad: [u8; 7], + pub word: u64, + pub addr: u64, + pub len: u64, +} + +/// Logical argument / result kinds. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kind { + Void, + I32, + U8, + U16, + U32, + U64, + Bytes, +} + +impl Kind { + const ALL: [Kind; 7] = [ + Kind::Void, + Kind::I32, + Kind::U8, + Kind::U16, + Kind::U32, + Kind::U64, + Kind::Bytes, + ]; + + fn name(self) -> &'static str { + match self { + Kind::Void => "VOID", + Kind::I32 => "I32", + Kind::U8 => "U8", + Kind::U16 => "U16", + Kind::U32 => "U32", + Kind::U64 => "U64", + Kind::Bytes => "BYTES", + } + } + + fn parse(s: &str) -> Option { + Kind::ALL.into_iter().find(|k| k.name() == s) + } +} + +/// An argument. `Bytes` borrows its buffer for the duration of the call. +#[derive(Clone, Copy, Debug)] +pub enum Arg<'a> { + I32(i32), + U8(u8), + U16(u16), + U32(u32), + U64(u64), + Bytes(&'a [u8]), +} + +impl Arg<'_> { + fn kind(&self) -> Kind { + match self { + Arg::I32(_) => Kind::I32, + Arg::U8(_) => Kind::U8, + Arg::U16(_) => Kind::U16, + Arg::U32(_) => Kind::U32, + Arg::U64(_) => Kind::U64, + Arg::Bytes(_) => Kind::Bytes, + } + } +} + +/// A function's result. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ret { + Void, + I32(i32), + U8(u8), + U16(u16), + U32(u32), + U64(u64), +} + +impl Ret { + /// The result as an `i64`, or `None` for `Void`. + pub fn as_i64(self) -> Option { + match self { + Ret::Void => None, + Ret::I32(v) => Some(v.into()), + Ret::U8(v) => Some(v.into()), + Ret::U16(v) => Some(v.into()), + Ret::U32(v) => Some(v.into()), + Ret::U64(v) => i64::try_from(v).ok(), + } + } +} + +/// One entry of the manifest's function table. +#[derive(Clone, Debug)] +pub struct FnSig { + pub tag: u16, + pub name: String, + pub ret: Kind, + pub args: Vec<(String, Kind)>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + Open(String), + Manifest(String), + NoSuchFunction(String), + /// The arguments do not match the manifest signature. + BadArgs(String), + /// `ps_invoke` returned a non-OK status (by manifest name). + Status(String, u8), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Open(m) => write!(f, "open: {m}"), + Error::Manifest(m) => write!(f, "manifest: {m}"), + Error::NoSuchFunction(n) => write!(f, "no function {n} in manifest"), + Error::BadArgs(m) => write!(f, "bad arguments: {m}"), + Error::Status(n, s) => write!(f, "ps_invoke status {n} ({s})"), + } + } +} + +impl std::error::Error for Error {} + +const RTLD_NOW: c_int = 2; + +extern "C" { + fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void; + // dlsym returns `void *`. Each ps_* export is bound through its own typed + // declaration, so the null pointer arrives as `None` (guaranteed by the + // nullable-pointer layout of `Option`) and no transmute is needed. + // The three bindings differ only in the pointee type of the result, which + // the C ABI does not distinguish, so the clashing-declarations lint is + // allowed for them alone. + #[allow(clashing_extern_declarations)] + #[link_name = "dlsym"] + fn dlsym_abi(handle: *mut c_void, symbol: *const c_char) -> Option; + #[allow(clashing_extern_declarations)] + #[link_name = "dlsym"] + fn dlsym_manifest(handle: *mut c_void, symbol: *const c_char) -> Option; + #[allow(clashing_extern_declarations)] + #[link_name = "dlsym"] + fn dlsym_invoke(handle: *mut c_void, symbol: *const c_char) -> Option; + fn dlclose(handle: *mut c_void) -> c_int; + fn dlerror() -> *const c_char; +} + +type AbiFn = unsafe extern "C" fn() -> u32; +type ManifestFn = unsafe extern "C" fn() -> *const c_char; +type InvokeFn = unsafe extern "C" fn(u16, *const Value, u32, *mut Value) -> u8; + +/// An opened protocol library. +pub struct Library { + handle: *mut c_void, + invoke: InvokeFn, + manifest: String, + consts: HashMap<(String, String), u64>, + fns: HashMap, + kind_tag: HashMap, + tag_kind: HashMap, + status_name: HashMap, + _not_send: PhantomData<*mut ()>, +} + +fn last_dl_error() -> String { + // SAFETY: dlerror returns NULL or a valid C string owned by libc. + unsafe { + let p = dlerror(); + if p.is_null() { + "unknown dlopen error".into() + } else { + CStr::from_ptr(p).to_string_lossy().into_owned() + } + } +} + +impl Library { + /// Open a protocol library and validate its manifest. + /// + /// # Safety + /// + /// Loading runs the library's initialisers and unloading runs its + /// finalisers. The caller must ensure both are sound for `path`, and that + /// its `ps_*` exports follow the connector contract. The manifest checks + /// catch layout and table drift; they are not a safety guarantee. + pub unsafe fn open(path: &str) -> Result { + let cpath = CString::new(path).map_err(|e| Error::Open(e.to_string()))?; + // SAFETY: cpath is a valid NUL-terminated string. + let handle = unsafe { dlopen(cpath.as_ptr(), RTLD_NOW) }; + if handle.is_null() { + return Err(Error::Open(last_dl_error())); + } + let missing = + |name: &CStr| Error::Open(format!("{path} does not export {}", name.to_string_lossy())); + // SAFETY: handle is a live dlopen handle and each name is NUL-terminated. + // The ps_* exports have these C signatures by contract + // (ffi/zig/connector/ps_connector.zig). + let resolved = unsafe { + match ( + dlsym_abi(handle, c"ps_abi_version".as_ptr()), + dlsym_manifest(handle, c"ps_manifest".as_ptr()), + dlsym_invoke(handle, c"ps_invoke".as_ptr()), + ) { + (Some(a), Some(m), Some(i)) => Ok((a, m, i)), + (None, _, _) => Err(missing(c"ps_abi_version")), + (_, None, _) => Err(missing(c"ps_manifest")), + (_, _, None) => Err(missing(c"ps_invoke")), + } + }; + let (abi, man, invoke) = match resolved { + Ok(t) => t, + Err(e) => { + // SAFETY: handle came from dlopen and is closed once. + unsafe { dlclose(handle) }; + return Err(e); + } + }; + // SAFETY: calling the library's own exports. + let version = unsafe { abi() }; + if version != CONNECTOR_ABI { + // SAFETY: handle came from dlopen and is closed once. + unsafe { dlclose(handle) }; + return Err(Error::Open(format!( + "connector ABI {version}, this crate speaks {CONNECTOR_ABI}" + ))); + } + // SAFETY: calling the library's own export. + let mp = unsafe { man() }; + if mp.is_null() { + // SAFETY: handle came from dlopen and is closed once. + unsafe { dlclose(handle) }; + return Err(Error::Manifest("ps_manifest returned NULL".into())); + } + // SAFETY: mp is non-null; ps_manifest returns a static NUL-terminated string. + let manifest = unsafe { CStr::from_ptr(mp) }.to_string_lossy().into_owned(); + let mut lib = Library { + handle, + invoke, + manifest, + consts: HashMap::new(), + fns: HashMap::new(), + kind_tag: HashMap::new(), + tag_kind: HashMap::new(), + status_name: HashMap::new(), + _not_send: PhantomData, + }; + lib.parse_manifest()?; + Ok(lib) + } + + fn parse_manifest(&mut self) -> Result<(), Error> { + for line in self.manifest.lines() { + let f: Vec<&str> = line.split(' ').collect(); + if f.first() == Some(&"FN") { + if f.len() < 4 { + return Err(Error::Manifest(format!("short FN line: {line}"))); + } + let tag: u16 = f[1] + .parse() + .map_err(|_| Error::Manifest(format!("bad tag: {line}")))?; + let ret = Kind::parse(f[3]) + .ok_or_else(|| Error::Manifest(format!("bad kind: {line}")))?; + let mut args = Vec::new(); + for a in &f[4..] { + let (n, k) = a + .split_once(':') + .ok_or_else(|| Error::Manifest(format!("bad arg: {line}")))?; + let k = Kind::parse(k) + .ok_or_else(|| Error::Manifest(format!("bad kind: {line}")))?; + args.push((n.to_string(), k)); + } + self.fns.insert( + f[2].to_string(), + FnSig { + tag, + name: f[2].to_string(), + ret, + args, + }, + ); + } else if f.len() == 3 { + if let Ok(v) = f[2].parse::() { + self.consts.insert((f[0].to_string(), f[1].to_string()), v); + } + } + } + for (name, want) in [ + ("PS_VALUE_SIZE", std::mem::size_of::()), + ("PS_VALUE_ALIGN", std::mem::align_of::()), + ("PS_VALUE_OFF_KIND", std::mem::offset_of!(Value, kind)), + ("PS_VALUE_OFF_WORD", std::mem::offset_of!(Value, word)), + ("PS_VALUE_OFF_ADDR", std::mem::offset_of!(Value, addr)), + ("PS_VALUE_OFF_LEN", std::mem::offset_of!(Value, len)), + ] { + if self.constant("LAYOUT", name) != Some(want as u64) { + return Err(Error::Manifest(format!( + "layout {name} does not match Value" + ))); + } + } + for k in Kind::ALL { + let tag = self + .constant("KIND", k.name()) + .and_then(|v| u8::try_from(v).ok()) + .ok_or_else(|| Error::Manifest(format!("no KIND {}", k.name())))?; + self.kind_tag.insert(k, tag); + self.tag_kind.insert(tag, k); + } + for ((kind, name), v) in &self.consts { + if kind == "STATUS" { + if let Ok(t) = u8::try_from(*v) { + self.status_name.insert(t, name.clone()); + } + } + } + if !self.status_name.values().any(|n| n == "OK") { + return Err(Error::Manifest("no STATUS OK".into())); + } + Ok(()) + } + + /// The raw Idris2-emitted manifest. + pub fn manifest(&self) -> &str { + &self.manifest + } + + /// A `KIND NAME VALUE` constant, e.g. `constant("EXCH", "TOPIC")`. + pub fn constant(&self, kind: &str, name: &str) -> Option { + self.consts + .get(&(kind.to_string(), name.to_string())) + .copied() + } + + /// The signature of NAME, if the manifest lists it. + pub fn signature(&self, name: &str) -> Option<&FnSig> { + self.fns.get(name) + } + + /// Every function the manifest lists. + pub fn functions(&self) -> impl Iterator { + self.fns.values() + } + + /// Call NAME with ARGS, checked against the manifest signature first. + pub fn call(&self, name: &str, args: &[Arg<'_>]) -> Result { + let sig = self + .fns + .get(name) + .ok_or_else(|| Error::NoSuchFunction(name.into()))?; + if sig.args.len() != args.len() { + return Err(Error::BadArgs(format!( + "{name} takes {} arguments, got {}", + sig.args.len(), + args.len() + ))); + } + for ((pname, k), a) in sig.args.iter().zip(args) { + if a.kind() != *k { + return Err(Error::BadArgs(format!( + "{name}: {pname} is {}, got {}", + k.name(), + a.kind().name() + ))); + } + } + let cells: Vec = args.iter().map(|a| self.cell(a)).collect(); + // SAFETY: `cells` and the slices they point into outlive the call. + unsafe { self.invoke_raw(sig.tag, &cells) } + } + + /// Build one value cell for ARG. + pub fn cell(&self, arg: &Arg<'_>) -> Value { + let mut v = Value { + kind: self.kind_tag[&arg.kind()], + ..Value::default() + }; + match *arg { + Arg::I32(x) => v.word = i64::from(x) as u64, + Arg::U8(x) => v.word = x.into(), + Arg::U16(x) => v.word = x.into(), + Arg::U32(x) => v.word = x.into(), + Arg::U64(x) => v.word = x, + Arg::Bytes(b) => { + v.addr = b.as_ptr() as usize as u64; + v.len = b.len() as u64; + } + } + v + } + + /// Call by tag with prepared cells, without the manifest check. Used to + /// exercise the dispatcher's own validation. + /// + /// # Safety + /// Every BYTES cell must point at memory valid for its length for the + /// duration of the call. + pub unsafe fn invoke_raw(&self, tag: u16, cells: &[Value]) -> Result { + let mut out = Value::default(); + let n = u32::try_from(cells.len()).map_err(|_| Error::BadArgs("too many".into()))?; + let ptr = if cells.is_empty() { + std::ptr::null() + } else { + cells.as_ptr() + }; + let st = (self.invoke)(tag, ptr, n, &mut out); + let st_name = self + .status_name + .get(&st) + .cloned() + .unwrap_or_else(|| "UNKNOWN".into()); + if st_name != "OK" { + return Err(Error::Status(st_name, st)); + } + let kind = self + .tag_kind + .get(&out.kind) + .copied() + .ok_or_else(|| Error::Manifest(format!("unknown result kind {}", out.kind)))?; + Ok(match kind { + Kind::Void => Ret::Void, + Kind::I32 => Ret::I32(out.word as i64 as i32), + Kind::U8 => Ret::U8(out.word as u8), + Kind::U16 => Ret::U16(out.word as u16), + Kind::U32 => Ret::U32(out.word as u32), + Kind::U64 => Ret::U64(out.word), + Kind::Bytes => return Err(Error::Manifest("BYTES result".into())), + }) + } +} + +impl Drop for Library { + fn drop(&mut self) { + // SAFETY: handle came from dlopen and is closed exactly once. + unsafe { dlclose(self.handle) }; + } +} diff --git a/native-connectors/rust/tests/amqp_smoke.rs b/native-connectors/rust/tests/amqp_smoke.rs new file mode 100644 index 00000000..55445d73 --- /dev/null +++ b/native-connectors/rust/tests/amqp_smoke.rs @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) + +//! Smoke test against proven-amqp. Set PS_AMQP_LIB to the built +//! libproven_amqp shared library; the test is skipped (with a message) when +//! it is unset. + +use proven_connector::{Arg, Error, Library, Ret, Value}; + +fn lib() -> Option { + let path = match std::env::var("PS_AMQP_LIB") { + Ok(p) => p, + Err(_) => { + eprintln!("PS_AMQP_LIB not set; skipping"); + return None; + } + }; + // SAFETY: PS_AMQP_LIB names the proven-amqp build from this repo, whose + // initialisers and finalisers are trivial and whose ps_* exports are + // generated from the Idris2 connector table. + Some(unsafe { Library::open(&path) }.expect("open proven-amqp")) +} + +#[test] +fn amqp_session_round_trip() { + let Some(lib) = lib() else { return }; + assert_eq!(lib.call("abi_version", &[]).unwrap(), Ret::U32(1)); + + let slot = match lib + .call( + "create", + &[ + Arg::Bytes(b"/"), + Arg::U32(131072), + Arg::U16(16), + Arg::U16(60), + ], + ) + .unwrap() + { + Ret::I32(s) => s, + other => panic!("create returned {other:?}"), + }; + assert!(slot >= 0); + + assert_eq!( + lib.call("channel_open", &[Arg::I32(slot), Arg::U16(1)]) + .unwrap(), + Ret::U8(0) + ); + let channel_open = lib.constant("BROKER", "CHANNEL_OPEN").unwrap() as u8; + assert_eq!( + lib.call("state", &[Arg::I32(slot)]).unwrap(), + Ret::U8(channel_open) + ); + + let topic = lib.constant("EXCH", "TOPIC").unwrap() as u8; + assert_eq!( + lib.call( + "routing_match", + &[ + Arg::Bytes(b"stock.usd.nyse"), + Arg::Bytes(b"stock.*.nyse"), + Arg::U8(topic) + ] + ) + .unwrap(), + Ret::U8(1) + ); + + assert_eq!(lib.call("destroy", &[Arg::I32(slot)]).unwrap(), Ret::Void); +} + +#[test] +fn manifest_lists_every_signature() { + let Some(lib) = lib() else { return }; + let create = lib.signature("create").unwrap(); + let kinds: Vec<_> = create.args.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(kinds, ["vhost", "frame_max", "channel_max", "heartbeat"]); + assert!(lib.functions().count() >= 24); +} + +#[test] +fn connector_and_dispatcher_reject_bad_calls() { + let Some(lib) = lib() else { return }; + assert!(matches!( + lib.call("nope", &[]), + Err(Error::NoSuchFunction(_)) + )); + assert!(matches!(lib.call("state", &[]), Err(Error::BadArgs(_)))); + assert!(matches!( + lib.call("state", &[Arg::U8(0)]), + Err(Error::BadArgs(_)) + )); + + // Bypass the connector's own check to reach the Zig dispatcher. + let state = lib.signature("state").unwrap().tag; + let wrong = lib.cell(&Arg::U8(0)); + // SAFETY: no BYTES cells. + unsafe { + assert!(matches!(lib.invoke_raw(9999, &[]), Err(Error::Status(n, _)) if n == "UNKNOWN_FN")); + assert!(matches!(lib.invoke_raw(state, &[]), Err(Error::Status(n, _)) if n == "ARITY")); + assert!( + matches!(lib.invoke_raw(state, &[wrong]), Err(Error::Status(n, _)) if n == "KIND_MISMATCH") + ); + } + let open = lib.signature("channel_open").unwrap().tag; + let mut too_big = lib.cell(&Arg::U16(0)); + too_big.word = 70_000; + let null_bytes = Value { + len: 4, + ..lib.cell(&Arg::Bytes(b"")) + }; + let rm = lib.signature("routing_match").unwrap().tag; + let topic = lib.cell(&Arg::U8(2)); + // SAFETY: the null BYTES cell is rejected before any read. + unsafe { + assert!(matches!( + lib.invoke_raw(open, &[lib.cell(&Arg::I32(0)), too_big]), + Err(Error::Status(n, _)) if n == "RANGE" + )); + let mut null_cell = null_bytes; + null_cell.addr = 0; + assert!(matches!( + lib.invoke_raw(rm, &[null_cell, null_cell, topic]), + Err(Error::Status(n, _)) if n == "NULL_PTR" + )); + } +} diff --git a/protocols/proven-amqp/ffi/zig/build.zig b/protocols/proven-amqp/ffi/zig/build.zig index 1274467b..7dfd48a3 100644 --- a/protocols/proven-amqp/ffi/zig/build.zig +++ b/protocols/proven-amqp/ffi/zig/build.zig @@ -11,10 +11,18 @@ pub fn build(b: *std.Build) void { const optimize = b.standardOptimizeOption(.{}); // -- Shared library ------------------------------------------------------- + // Shared uniform-connector dispatcher (repository-level ffi/zig/connector). + const ps_connector = b.createModule(.{ + .root_source_file = b.path("../../../../ffi/zig/connector/ps_connector.zig"), + .target = target, + .optimize = optimize, + }); + const lib_module = b.createModule(.{ .root_source_file = b.path("src/amqp.zig"), .target = target, .optimize = optimize, + .imports = &.{.{ .name = "ps_connector", .module = ps_connector }}, }); const shared_lib = b.addLibrary(.{ .name = "proven_amqp", @@ -28,6 +36,7 @@ pub fn build(b: *std.Build) void { .root_source_file = b.path("src/amqp.zig"), .target = target, .optimize = optimize, + .imports = &.{.{ .name = "ps_connector", .module = ps_connector }}, }); const static_lib = b.addLibrary(.{ .name = "proven_amqp", @@ -41,6 +50,7 @@ pub fn build(b: *std.Build) void { .root_source_file = b.path("src/amqp.zig"), .target = target, .optimize = optimize, + .imports = &.{.{ .name = "ps_connector", .module = ps_connector }}, }); const test_module = b.createModule(.{ .root_source_file = b.path("test/amqp_test.zig"), diff --git a/protocols/proven-amqp/ffi/zig/src/amqp.zig b/protocols/proven-amqp/ffi/zig/src/amqp.zig index a8a91068..969e97f3 100644 --- a/protocols/proven-amqp/ffi/zig/src/amqp.zig +++ b/protocols/proven-amqp/ffi/zig/src/amqp.zig @@ -1042,3 +1042,33 @@ comptime { if (@sizeOf(@TypeOf(sessions)) > 16 * 1024 * 1024) @compileError("pool 'sessions' exceeds the 16 MiB budget; heap-allocate or shrink (see audits/proof-panic-attack-2026-06-23.md)"); } + +// ========================================================================= +// Uniform native-connector surface (pilot) +// ========================================================================= +// +// Three symbols any language can bind: the connector ABI version, the +// Idris2-emitted manifest (function table and tags), and one dispatcher that +// calls the amqp_* exports above by tag. The dispatcher checks, at comptime, +// that every Idris2 signature in amqp_abi_gen.zig matches the real export. +// See ffi/zig/connector/ps_connector.zig at the repository root. + +const ps = @import("ps_connector"); +const Dispatch = ps.Dispatcher(@This(), "amqp_", gen); + +/// Uniform connector ABI version (from AMQPABI.Connector.connectorAbiVersion). +pub export fn ps_abi_version() callconv(.c) u32 { + return gen.CONNECTOR_ABI; +} + +/// The Idris2-emitted manifest, NUL-terminated, with static lifetime. +pub export fn ps_manifest() callconv(.c) [*:0]const u8 { + return gen.MANIFEST.ptr; +} + +/// Call the function with tag `fn_tag` on `n` argument cells. The return +/// value is a ps_invoke status (STATUS_* in amqp_abi_gen.zig); on STATUS_OK +/// the function's result is in `out`. +pub export fn ps_invoke(fn_tag: u16, args: ?[*]const ps.Value, n: u32, out: ?*ps.Value) callconv(.c) u8 { + return Dispatch.invoke(fn_tag, args, n, out); +} diff --git a/protocols/proven-amqp/ffi/zig/src/amqp_abi_gen.zig b/protocols/proven-amqp/ffi/zig/src/amqp_abi_gen.zig index bc0b546c..46b1234c 100644 --- a/protocols/proven-amqp/ffi/zig/src/amqp_abi_gen.zig +++ b/protocols/proven-amqp/ffi/zig/src/amqp_abi_gen.zig @@ -40,3 +40,135 @@ pub const BROKER_CHANNEL_OPEN: u8 = 2; pub const BROKER_CONSUMING: u8 = 3; pub const BROKER_PUBLISHING: u8 = 4; pub const BROKER_DISCONNECTING: u8 = 5; +pub const CONNECTOR_ABI: u8 = 1; +pub const PS_VALUE_SIZE: usize = 32; +pub const PS_VALUE_ALIGN: usize = 8; +pub const PS_VALUE_OFF_KIND: usize = 0; +pub const PS_VALUE_OFF_WORD: usize = 8; +pub const PS_VALUE_OFF_ADDR: usize = 16; +pub const PS_VALUE_OFF_LEN: usize = 24; +pub const KIND_VOID: u8 = 0; +pub const KIND_I32: u8 = 1; +pub const KIND_U8: u8 = 2; +pub const KIND_U16: u8 = 3; +pub const KIND_U32: u8 = 4; +pub const KIND_U64: u8 = 5; +pub const KIND_BYTES: u8 = 6; +pub const STATUS_OK: u8 = 0; +pub const STATUS_UNKNOWN_FN: u8 = 1; +pub const STATUS_ARITY: u8 = 2; +pub const STATUS_KIND_MISMATCH: u8 = 3; +pub const STATUS_RANGE: u8 = 4; +pub const STATUS_NULL_PTR: u8 = 5; + +pub const FnSig = struct { tag: u16, name: []const u8, ret: []const u8, kinds: []const u8 }; + +pub const FNS = [_]FnSig{ + .{ .tag = 1, .name = "abi_version", .ret = "U32", .kinds = "" }, + .{ .tag = 2, .name = "create", .ret = "I32", .kinds = "BYTES U32 U16 U16" }, + .{ .tag = 3, .name = "destroy", .ret = "VOID", .kinds = "I32" }, + .{ .tag = 4, .name = "state", .ret = "U8", .kinds = "I32" }, + .{ .tag = 5, .name = "can_publish", .ret = "U8", .kinds = "I32" }, + .{ .tag = 6, .name = "can_consume", .ret = "U8", .kinds = "I32" }, + .{ .tag = 7, .name = "channel_open", .ret = "U8", .kinds = "I32 U16" }, + .{ .tag = 8, .name = "channel_close", .ret = "U8", .kinds = "I32 U16" }, + .{ .tag = 9, .name = "channel_count", .ret = "U16", .kinds = "I32" }, + .{ .tag = 10, .name = "exchange_declare", .ret = "U8", .kinds = "I32 U16 BYTES U8 U8 U8 U8" }, + .{ .tag = 11, .name = "queue_declare", .ret = "U8", .kinds = "I32 U16 BYTES U8 U8 U8" }, + .{ .tag = 12, .name = "queue_bind", .ret = "U8", .kinds = "I32 U16 BYTES BYTES BYTES" }, + .{ .tag = 13, .name = "basic_publish", .ret = "U8", .kinds = "I32 U16 BYTES BYTES BYTES U8 U8 U8" }, + .{ .tag = 14, .name = "basic_consume", .ret = "U8", .kinds = "I32 U16 BYTES BYTES U8 U8" }, + .{ .tag = 15, .name = "basic_cancel", .ret = "U8", .kinds = "I32 U16 BYTES" }, + .{ .tag = 16, .name = "basic_ack", .ret = "U8", .kinds = "I32 U16 U64 U8" }, + .{ .tag = 17, .name = "basic_nack", .ret = "U8", .kinds = "I32 U16 U64 U8 U8" }, + .{ .tag = 18, .name = "basic_reject", .ret = "U8", .kinds = "I32 U16 U64 U8" }, + .{ .tag = 19, .name = "basic_qos", .ret = "U8", .kinds = "I32 U16 U16 U32 U8" }, + .{ .tag = 20, .name = "consumer_count", .ret = "U32", .kinds = "I32" }, + .{ .tag = 21, .name = "disconnect", .ret = "U8", .kinds = "I32" }, + .{ .tag = 22, .name = "cleanup", .ret = "U8", .kinds = "I32" }, + .{ .tag = 23, .name = "can_transition", .ret = "U8", .kinds = "U8 U8" }, + .{ .tag = 24, .name = "routing_match", .ret = "U8", .kinds = "BYTES BYTES U8" }, +}; + +/// The full Idris-emitted manifest, served verbatim by ps_manifest(). +pub const MANIFEST: [:0]const u8 = + \\ABI_VERSION 1 + \\FRAME METHOD 0 + \\FRAME HEADER 1 + \\FRAME BODY 2 + \\FRAME HEARTBEAT 3 + \\CLASS CONNECTION 0 + \\CLASS CHANNEL 1 + \\CLASS EXCHANGE 2 + \\CLASS QUEUE 3 + \\CLASS BASIC 4 + \\CLASS TX 5 + \\CLASS CONFIRM 6 + \\EXCH DIRECT 0 + \\EXCH FANOUT 1 + \\EXCH TOPIC 2 + \\EXCH HEADERS 3 + \\DMODE NON_PERSISTENT 0 + \\DMODE PERSISTENT 1 + \\SEV CHANNEL_LEVEL 0 + \\SEV CONNECTION_LEVEL 1 + \\CONN IDLE 0 + \\CONN NEGOTIATING 1 + \\CONN TUNING_OK 2 + \\CONN OPEN 3 + \\CONN CLOSING 4 + \\CHAN CLOSED 0 + \\CHAN OPENING 1 + \\CHAN CH_OPEN 2 + \\CHAN CH_CLOSING 3 + \\BROKER IDLE 0 + \\BROKER CONNECTED 1 + \\BROKER CHANNEL_OPEN 2 + \\BROKER CONSUMING 3 + \\BROKER PUBLISHING 4 + \\BROKER DISCONNECTING 5 + \\CONNECTOR ABI 1 + \\LAYOUT PS_VALUE_SIZE 32 + \\LAYOUT PS_VALUE_ALIGN 8 + \\LAYOUT PS_VALUE_OFF_KIND 0 + \\LAYOUT PS_VALUE_OFF_WORD 8 + \\LAYOUT PS_VALUE_OFF_ADDR 16 + \\LAYOUT PS_VALUE_OFF_LEN 24 + \\KIND VOID 0 + \\KIND I32 1 + \\KIND U8 2 + \\KIND U16 3 + \\KIND U32 4 + \\KIND U64 5 + \\KIND BYTES 6 + \\STATUS OK 0 + \\STATUS UNKNOWN_FN 1 + \\STATUS ARITY 2 + \\STATUS KIND_MISMATCH 3 + \\STATUS RANGE 4 + \\STATUS NULL_PTR 5 + \\FN 1 abi_version U32 + \\FN 2 create I32 vhost:BYTES frame_max:U32 channel_max:U16 heartbeat:U16 + \\FN 3 destroy VOID slot:I32 + \\FN 4 state U8 slot:I32 + \\FN 5 can_publish U8 slot:I32 + \\FN 6 can_consume U8 slot:I32 + \\FN 7 channel_open U8 slot:I32 channel:U16 + \\FN 8 channel_close U8 slot:I32 channel:U16 + \\FN 9 channel_count U16 slot:I32 + \\FN 10 exchange_declare U8 slot:I32 channel:U16 name:BYTES exch_type:U8 durable:U8 auto_delete:U8 internal:U8 + \\FN 11 queue_declare U8 slot:I32 channel:U16 name:BYTES durable:U8 exclusive:U8 auto_delete:U8 + \\FN 12 queue_bind U8 slot:I32 channel:U16 queue:BYTES exchange:BYTES routing_key:BYTES + \\FN 13 basic_publish U8 slot:I32 channel:U16 exchange:BYTES routing_key:BYTES body:BYTES delivery_mode:U8 priority:U8 mandatory:U8 + \\FN 14 basic_consume U8 slot:I32 channel:U16 queue:BYTES consumer_tag:BYTES no_ack:U8 exclusive:U8 + \\FN 15 basic_cancel U8 slot:I32 channel:U16 consumer_tag:BYTES + \\FN 16 basic_ack U8 slot:I32 channel:U16 delivery_tag:U64 multiple:U8 + \\FN 17 basic_nack U8 slot:I32 channel:U16 delivery_tag:U64 multiple:U8 requeue:U8 + \\FN 18 basic_reject U8 slot:I32 channel:U16 delivery_tag:U64 requeue:U8 + \\FN 19 basic_qos U8 slot:I32 channel:U16 prefetch_count:U16 prefetch_size:U32 global:U8 + \\FN 20 consumer_count U32 slot:I32 + \\FN 21 disconnect U8 slot:I32 + \\FN 22 cleanup U8 slot:I32 + \\FN 23 can_transition U8 from:U8 to:U8 + \\FN 24 routing_match U8 routing_key:BYTES pattern:BYTES exch_type:U8 +; diff --git a/protocols/proven-amqp/proven-amqp-abigen.ipkg b/protocols/proven-amqp/proven-amqp-abigen.ipkg index 69b4e320..d11c5ae9 100644 --- a/protocols/proven-amqp/proven-amqp-abigen.ipkg +++ b/protocols/proven-amqp/proven-amqp-abigen.ipkg @@ -18,4 +18,5 @@ modules = AMQP.Types , AMQP.Session , AMQPABI.Layout , AMQPABI.Foreign + , AMQPABI.Connector , AMQPABI.Emit diff --git a/protocols/proven-amqp/proven-amqp.ipkg b/protocols/proven-amqp/proven-amqp.ipkg index 8acb5997..5d186bdd 100644 --- a/protocols/proven-amqp/proven-amqp.ipkg +++ b/protocols/proven-amqp/proven-amqp.ipkg @@ -11,4 +11,4 @@ sourcedir = "src" main = Main executable = "proven-amqp" -modules = AMQP, AMQP.Types, AMQP.Properties, AMQP.Exchange, AMQP.Queue, AMQP.Session, AMQP.Frame, AMQPABI.Layout, AMQPABI.Transitions, AMQPABI.Foreign +modules = AMQP, AMQP.Types, AMQP.Properties, AMQP.Exchange, AMQP.Queue, AMQP.Session, AMQP.Frame, AMQPABI.Layout, AMQPABI.Transitions, AMQPABI.Foreign, AMQPABI.Connector diff --git a/protocols/proven-amqp/src/AMQPABI/Connector.idr b/protocols/proven-amqp/src/AMQPABI/Connector.idr new file mode 100644 index 00000000..c7be3c84 --- /dev/null +++ b/protocols/proven-amqp/src/AMQPABI/Connector.idr @@ -0,0 +1,175 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- AMQPABI.Connector: the uniform-connector signature table (pilot). +-- +-- Every function a native connector may call through `ps_invoke` is listed +-- here once, with its logical argument kinds. AMQPABI.Emit prints the table +-- as `FN` manifest lines; tools/gen-abi.sh renders them into +-- amqp_abi_gen.zig, and a comptime guard in the shared Zig dispatcher +-- (ffi/zig/connector/ps_connector.zig) checks every entry against the real +-- `amqp_*` export. A mismatch is a build error. +-- +-- A `KBytes` argument is one logical argument that the Zig export takes as a +-- (pointer, u32 length) pair. Function tags are positions in `signatures`, +-- starting at 1, so appending keeps existing tags stable. + +module AMQPABI.Connector + +%default total + +||| Logical argument / result kinds carried by a `ps_invoke` value cell. +public export +data Kind = KVoid | KI32 | KU8 | KU16 | KU32 | KU64 | KBytes + +||| Wire tag for each kind (the `kind` byte of a value cell). +public export +kindToTag : Kind -> Bits8 +kindToTag KVoid = 0 +kindToTag KI32 = 1 +kindToTag KU8 = 2 +kindToTag KU16 = 3 +kindToTag KU32 = 4 +kindToTag KU64 = 5 +kindToTag KBytes = 6 + +||| Manifest spelling of each kind. +public export +kindName : Kind -> String +kindName KVoid = "VOID" +kindName KI32 = "I32" +kindName KU8 = "U8" +kindName KU16 = "U16" +kindName KU32 = "U32" +kindName KU64 = "U64" +kindName KBytes = "BYTES" + +||| Every kind, in tag order (drives the KIND manifest lines). +public export +allKinds : List Kind +allKinds = [KVoid, KI32, KU8, KU16, KU32, KU64, KBytes] + +||| Version of the uniform connector ABI (ps_abi_version, ps_manifest, +||| ps_invoke, and the value-cell layout). Distinct from the AMQP abiVersion. +public export +connectorAbiVersion : Bits8 +connectorAbiVersion = 1 + +||| Result of `ps_invoke` itself (not of the called function). +public export +data Status = SOk | SUnknownFn | SArity | SKindMismatch | SRange | SNullPtr + +public export +statusToTag : Status -> Bits8 +statusToTag SOk = 0 +statusToTag SUnknownFn = 1 +statusToTag SArity = 2 +statusToTag SKindMismatch = 3 +statusToTag SRange = 4 +statusToTag SNullPtr = 5 + +statusName : Status -> String +statusName SOk = "OK" +statusName SUnknownFn = "UNKNOWN_FN" +statusName SArity = "ARITY" +statusName SKindMismatch = "KIND_MISMATCH" +statusName SRange = "RANGE" +statusName SNullPtr = "NULL_PTR" + +allStatuses : List Status +allStatuses = [SOk, SUnknownFn, SArity, SKindMismatch, SRange, SNullPtr] + +||| The value cell, 32 bytes on every target: kind byte, 7 zero bytes, then +||| three native-endian u64 words. `word` carries an integer (an I32 is +||| stored sign-extended to 64 bits); for BYTES, `addr` is the buffer address +||| and `len` its length. Using a u64 address keeps the layout the same on +||| 32-bit and 64-bit targets. +public export +valueLayout : List (String, Nat) +valueLayout = + [ ("PS_VALUE_SIZE", 32), ("PS_VALUE_ALIGN", 8) + , ("PS_VALUE_OFF_KIND", 0), ("PS_VALUE_OFF_WORD", 8) + , ("PS_VALUE_OFF_ADDR", 16), ("PS_VALUE_OFF_LEN", 24) ] + +||| One callable function: its name without the `amqp_` prefix, its result +||| kind, and its named logical arguments. +public export +record Sig where + constructor MkSig + sigName : String + sigRet : Kind + sigArgs : List (String, Kind) + +||| The callable surface of proven-amqp, in tag order (tag = position + 1). +public export +signatures : List Sig +signatures = + [ MkSig "abi_version" KU32 [] + , MkSig "create" KI32 + [("vhost", KBytes), ("frame_max", KU32), ("channel_max", KU16), ("heartbeat", KU16)] + , MkSig "destroy" KVoid [("slot", KI32)] + , MkSig "state" KU8 [("slot", KI32)] + , MkSig "can_publish" KU8 [("slot", KI32)] + , MkSig "can_consume" KU8 [("slot", KI32)] + , MkSig "channel_open" KU8 [("slot", KI32), ("channel", KU16)] + , MkSig "channel_close" KU8 [("slot", KI32), ("channel", KU16)] + , MkSig "channel_count" KU16 [("slot", KI32)] + , MkSig "exchange_declare" KU8 + [ ("slot", KI32), ("channel", KU16), ("name", KBytes), ("exch_type", KU8) + , ("durable", KU8), ("auto_delete", KU8), ("internal", KU8) ] + , MkSig "queue_declare" KU8 + [ ("slot", KI32), ("channel", KU16), ("name", KBytes) + , ("durable", KU8), ("exclusive", KU8), ("auto_delete", KU8) ] + , MkSig "queue_bind" KU8 + [ ("slot", KI32), ("channel", KU16), ("queue", KBytes) + , ("exchange", KBytes), ("routing_key", KBytes) ] + , MkSig "basic_publish" KU8 + [ ("slot", KI32), ("channel", KU16), ("exchange", KBytes) + , ("routing_key", KBytes), ("body", KBytes), ("delivery_mode", KU8) + , ("priority", KU8), ("mandatory", KU8) ] + , MkSig "basic_consume" KU8 + [ ("slot", KI32), ("channel", KU16), ("queue", KBytes) + , ("consumer_tag", KBytes), ("no_ack", KU8), ("exclusive", KU8) ] + , MkSig "basic_cancel" KU8 + [("slot", KI32), ("channel", KU16), ("consumer_tag", KBytes)] + , MkSig "basic_ack" KU8 + [("slot", KI32), ("channel", KU16), ("delivery_tag", KU64), ("multiple", KU8)] + , MkSig "basic_nack" KU8 + [ ("slot", KI32), ("channel", KU16), ("delivery_tag", KU64) + , ("multiple", KU8), ("requeue", KU8) ] + , MkSig "basic_reject" KU8 + [("slot", KI32), ("channel", KU16), ("delivery_tag", KU64), ("requeue", KU8)] + , MkSig "basic_qos" KU8 + [ ("slot", KI32), ("channel", KU16), ("prefetch_count", KU16) + , ("prefetch_size", KU32), ("global", KU8) ] + , MkSig "consumer_count" KU32 [("slot", KI32)] + , MkSig "disconnect" KU8 [("slot", KI32)] + , MkSig "cleanup" KU8 [("slot", KI32)] + , MkSig "can_transition" KU8 [("from", KU8), ("to", KU8)] + , MkSig "routing_match" KU8 + [("routing_key", KBytes), ("pattern", KBytes), ("exch_type", KU8)] + ] + +argText : (String, Kind) -> String +argText (n, k) = " " ++ n ++ ":" ++ kindName k + +sigLine : Nat -> Sig -> String +sigLine tag s = + "FN " ++ show tag ++ " " ++ sigName s ++ " " ++ kindName (sigRet s) + ++ concatMap argText (sigArgs s) + +numbered : Nat -> List Sig -> List String +numbered _ [] = [] +numbered n (s :: ss) = sigLine n s :: numbered (S n) ss + +||| Manifest lines for the connector surface: the connector ABI version, the +||| value-cell layout, the kind and status tags, then one `FN` line per +||| signature. +public export +connectorLines : List String +connectorLines = + ("CONNECTOR ABI " ++ show connectorAbiVersion) + :: map (\(n, v) => "LAYOUT " ++ n ++ " " ++ show v) valueLayout + ++ map (\k => "KIND " ++ kindName k ++ " " ++ show (kindToTag k)) allKinds + ++ map (\s => "STATUS " ++ statusName s ++ " " ++ show (statusToTag s)) allStatuses + ++ numbered 1 signatures diff --git a/protocols/proven-amqp/src/AMQPABI/Emit.idr b/protocols/proven-amqp/src/AMQPABI/Emit.idr index f853ffe9..d45c25aa 100644 --- a/protocols/proven-amqp/src/AMQPABI/Emit.idr +++ b/protocols/proven-amqp/src/AMQPABI/Emit.idr @@ -4,6 +4,8 @@ -- AMQPABI.Emit: ABI tag-manifest emitter (single source of truth). -- Prints `KIND NAME DECIMAL` lines from the proven *ToTag encoders; -- tools/gen-abi.sh renders them into amqp_abi_gen.zig for the comptime guard. +-- It then prints AMQPABI.Connector.connectorLines (CONNECTOR, KIND and FN +-- lines), the signature table the uniform ps_invoke dispatcher is checked against. module AMQPABI.Emit @@ -11,6 +13,7 @@ import AMQP.Types import AMQP.Session import AMQPABI.Layout import AMQPABI.Foreign +import AMQPABI.Connector %default total @@ -58,4 +61,4 @@ manifest = covering main : IO () -main = traverse_ putStrLn manifest +main = traverse_ putStrLn (manifest ++ connectorLines) diff --git a/tests/native_connector_smoke.sh b/tests/native_connector_smoke.sh new file mode 100755 index 00000000..d8e4d79b --- /dev/null +++ b/tests/native_connector_smoke.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +# +# Native-connector pilot smoke test: build proven-amqp's Zig library, then +# drive it through ps_invoke from the C, Rust and Julia connectors in +# native-connectors/. Needs zig, cc, cargo and julia. + +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +for tool in zig cc cargo julia; do + command -v "$tool" >/dev/null 2>&1 || { echo "ERROR: $tool is required" >&2; exit 127; } +done + +AMQP="protocols/proven-amqp/ffi/zig" +# ReleaseSafe, not Debug: under Debug several amqp_* exports reserve 2.7-13.6 MB +# of stack (the session pool is copied), which overflows an 8 MB main thread. +# That is a pre-existing issue in amqp.zig, reported separately. +(cd "$AMQP" && zig build -Doptimize=ReleaseSafe) +LIB="$ROOT/$AMQP/zig-out/lib/libproven_amqp.so" +[[ -f "$LIB" ]] || { echo "ERROR: $LIB was not built" >&2; exit 1; } + +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +echo "==> C connector" +cc -std=c11 -Wall -Wextra -Werror -o "$WORK/smoke" \ + native-connectors/c/smoke.c native-connectors/c/ps_connector.c -ldl +"$WORK/smoke" "$LIB" + +echo "==> Rust connector" +PS_AMQP_LIB="$LIB" CARGO_TARGET_DIR="$WORK/rust" \ + cargo test --quiet --locked --manifest-path native-connectors/rust/Cargo.toml + +echo "==> Julia connector" +PS_AMQP_LIB="$LIB" JULIA_DEPOT_PATH="$WORK/julia:" \ + julia --project=native-connectors/julia/ProvenConnector -e 'using Pkg; Pkg.test()' + +echo "Native connector smoke tests passed (proven-amqp only)." diff --git a/tools/gen-abi.sh b/tools/gen-abi.sh index 325d293f..0d97a6c1 100644 --- a/tools/gen-abi.sh +++ b/tools/gen-abi.sh @@ -41,8 +41,33 @@ render_zig() { # awk ' $1=="ABI_VERSION" { printf "pub const ABI_VERSION: u32 = %s;\n\n", $2; next } $1=="LAYOUT" { printf "pub const %s: usize = %s;\n", $2, $3; next } + $1=="FN" { + # FN :... -> one ps_invoke table row. + kinds = "" + for (i = 5; i <= NF; i++) { split($i, a, ":"); kinds = kinds (i > 5 ? " " : "") a[2] } + fns[++nfn] = sprintf(" .{ .tag = %s, .name = \"%s\", .ret = \"%s\", .kinds = \"%s\" },", $2, $3, $4, kinds) + next + } { printf "pub const %s_%s: u8 = %s;\n", $1, $2, $3 } + END { + if (nfn == 0) exit + # Uniform-connector surface: emitted only for protocols whose Emit + # prints FN lines, so every other generated file stays byte-identical. + print "" + print "pub const FnSig = struct { tag: u16, name: []const u8, ret: []const u8, kinds: []const u8 };" + print "" + print "pub const FNS = [_]FnSig{" + for (i = 1; i <= nfn; i++) print fns[i] + print "};" + } ' <<< "$MANIFEST" + if grep -q "^FN " <<< "$MANIFEST"; then + echo "" + echo "/// The full Idris-emitted manifest, served verbatim by ps_manifest()." + echo "pub const MANIFEST: [:0]const u8 =" + sed "s/^/ \\\\\\\\/" <<< "$MANIFEST" + echo ";" + fi } > "$ZIG_OUT" } @@ -80,6 +105,7 @@ gen_protocol() { #