From ccceb4a0b35f234dec4bc5ad3bd1a9cf37510a5a Mon Sep 17 00:00:00 2001 From: giles Date: Thu, 28 May 2026 11:39:48 +0000 Subject: [PATCH] =?UTF-8?q?fed-sx-m1:=20Step=208c-post-publish-srv=20?= =?UTF-8?q?=E2=80=94=20gen=5Fserver-wrapped=20nx=5Fkernel=20(start=5Flink?= =?UTF-8?q?=20+=20publish/query/log=5Ftip)=20+=2011=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- next/kernel/nx_kernel.erl | 57 +++++++++++++++ next/tests/nx_kernel_server.sh | 127 +++++++++++++++++++++++++++++++++ plans/fed-sx-milestone-1.md | 4 +- 3 files changed, 187 insertions(+), 1 deletion(-) create mode 100755 next/tests/nx_kernel_server.sh diff --git a/next/kernel/nx_kernel.erl b/next/kernel/nx_kernel.erl index 6c41b203..d16b7983 100644 --- a/next/kernel/nx_kernel.erl +++ b/next/kernel/nx_kernel.erl @@ -1,8 +1,12 @@ -module(nx_kernel). +-behaviour(gen_server). -export([new/3, publish/2, actor_id/1, log_state/1, log_tip/1, key_spec/1, actor_state/1, projections/1, next_published/1, with_projections/2]). +-export([start_link/3, publish/1, query/0, log_tip/0, + with_projections/1, stop/0]). +-export([init/1, handle_call/3, handle_cast/2, handle_info/2]). %% Kernel orchestrator — the long-lived runtime state held by the %% running fed-sx instance. The HTTP layer (Step 8c-post-publish @@ -80,3 +84,56 @@ field(_, []) -> nil. set(K, V, []) -> [{K, V}]; set(K, V, [{K, _} | Rest]) -> [{K, V} | Rest]; set(K, V, [P | Rest]) -> [P | set(K, V, Rest)]. + +%% ── gen_server wrapper ────────────────────────────────────────── +%% +%% Mirrors the registry / projection gen_server patterns from +%% Steps 5b and 7b. Same port quirks: raw Pid return, no `?MODULE` +%% macro, spawned processes don't persist across separate +%% erlang-eval-ast calls — tests inline start_link with operations. + +start_link(ActorId, KeySpec, ActorStateProplist) -> + Pid = gen_server:start_link(nx_kernel, + [ActorId, KeySpec, ActorStateProplist]), + erlang:register(nx_kernel, Pid), + Pid. + +stop() -> + R = gen_server:call(nx_kernel, '$gen_stop'), + erlang:unregister(nx_kernel), + R. + +publish(Request) -> + gen_server:call(nx_kernel, {publish, Request}). + +query() -> + gen_server:call(nx_kernel, get_state). + +log_tip() -> + gen_server:call(nx_kernel, get_log_tip). + +with_projections(Names) -> + gen_server:call(nx_kernel, {set_projections, Names}). + +%% gen_server callbacks + +init([ActorId, KeySpec, AS]) -> + {ok, new(ActorId, KeySpec, AS)}. + +handle_call({publish, Request}, _From, State) -> + case publish(Request, State) of + {ok, Result, NewState} -> + {reply, {ok, Result}, NewState}; + {error, Reason, SameState} -> + {reply, {error, Reason}, SameState} + end; +handle_call(get_state, _From, State) -> + {reply, State, State}; +handle_call(get_log_tip, _From, State) -> + {reply, log_tip(State), State}; +handle_call({set_projections, Names}, _From, State) -> + {reply, ok, with_projections(Names, State)}. + +handle_cast(_, S) -> {noreply, S}. + +handle_info(_, S) -> {noreply, S}. diff --git a/next/tests/nx_kernel_server.sh b/next/tests/nx_kernel_server.sh new file mode 100755 index 00000000..82134d86 --- /dev/null +++ b/next/tests/nx_kernel_server.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +# next/tests/nx_kernel_server.sh — Step 8c-post-publish-srv tests. +# +# Exercises the gen_server-wrapped nx_kernel. Same port quirks +# as registry/projection gen_servers: each test inlines start_link +# with operations. 10 cases. + +set -uo pipefail +cd "$(git rev-parse --show-toplevel)" + +SX_SERVER="${SX_SERVER:-hosts/ocaml/_build/default/bin/sx_server.exe}" +if [ ! -x "$SX_SERVER" ]; then + SX_SERVER="/root/rose-ash/hosts/ocaml/_build/default/bin/sx_server.exe" +fi +if [ ! -x "$SX_SERVER" ]; then + echo "ERROR: sx_server.exe not found." >&2 + exit 1 +fi + +VERBOSE="${1:-}" +PASS=0; FAIL=0; ERRORS="" +TMPFILE=$(mktemp); trap "rm -f $TMPFILE" EXIT + +# Shared prelude — KS/AS bindings + start_link + a Req binding. +PRELUDE='KM = <<1,2,3,4>>, KS = [{key_id,k1},{algorithm,ed25519},{value,KM}], AS = [{public_keys,[[{id,k1},{created,0},{value,KM}]]}], nx_kernel:start_link(alice, KS, AS), Req = [{type,create},{object,nil}],' + +cat > "$TMPFILE" < ok; _ -> bad end\") :name)") + +;; After one publish, log_tip = 1 +(epoch 13) +(eval "(erlang-eval-ast \"${PRELUDE} nx_kernel:publish(Req), nx_kernel:log_tip()\")") + +;; Two publishes -> log_tip = 2 (next_published counter avoids replay) +(epoch 14) +(eval "(erlang-eval-ast \"${PRELUDE} nx_kernel:publish(Req), nx_kernel:publish(Req), nx_kernel:log_tip()\")") + +;; query/0 returns a state proplist with the right actor_id +(epoch 15) +(eval "(get (erlang-eval-ast \"${PRELUDE} S = nx_kernel:query(), nx_kernel:actor_id(S) =:= alice\") :name)") + +;; with_projections/1 sets the projection list, visible via query +(epoch 16) +(eval "(get (erlang-eval-ast \"${PRELUDE} nx_kernel:with_projections([px]), S = nx_kernel:query(), nx_kernel:projections(S) =:= [px]\") :name)") + +;; Bad key in state -> publish returns {error, bad_signature}; log_tip unchanged +(epoch 17) +(eval "(get (erlang-eval-ast \"OtherKM = <<9,9,9,9>>, KS = [{key_id,k1},{algorithm,ed25519},{value,OtherKM}], AS = [{public_keys,[[{id,k1},{created,0},{value,<<1,2,3,4>>}]]}], nx_kernel:start_link(alice, KS, AS), Req = [{type,create},{object,nil}], R = nx_kernel:publish(Req), Tip = nx_kernel:log_tip(), case {R, Tip} of {{error, bad_signature}, 0} -> ok; _ -> bad end\") :name)") + +;; State persists across multiple gen_server calls in one expression +(epoch 18) +(eval "(get (erlang-eval-ast \"${PRELUDE} nx_kernel:publish(Req), Tip1 = nx_kernel:log_tip(), nx_kernel:publish(Req), Tip2 = nx_kernel:log_tip(), {Tip1, Tip2} =:= {1, 2}\") :name)") +EPOCHS + +OUTPUT=$(timeout 240 "$SX_SERVER" < "$TMPFILE" 2>/dev/null) + +check() { + local epoch="$1" desc="$2" expected="$3" + local actual + actual=$(echo "$OUTPUT" | awk -v e="$epoch" ' + $0 ~ "^\\(ok-len " e " " { getline; print; exit } + $0 ~ "^\\(ok " e " " { print; exit } + $0 ~ "^\\(error " e " " { print; exit } + ') + [ -z "$actual" ] && actual="" + if echo "$actual" | grep -qF -- "$expected"; then + PASS=$((PASS+1)) + [ "$VERBOSE" = "-v" ] && echo " ok $desc" + else + FAIL=$((FAIL+1)) + ERRORS+=" FAIL [$desc] (epoch $epoch) expected: $expected | actual: $actual +" + fi +} + +check 2 "gen_server loaded" "gen_server" +check 7 "nx_kernel module loaded" "nx_kernel" +check 10 "start_link registered Pid" "true" +check 11 "fresh log_tip = 0" "0" +check 12 "publish/1 happy path" "ok" +check 13 "tip = 1 after one publish" "1" +check 14 "tip = 2 after two publishes" "2" +check 15 "query returns state w/ actor_id" "true" +check 16 "with_projections persists" "true" +check 17 "bad key fails, tip unchanged" "ok" +check 18 "state persists across calls" "true" + +TOTAL=$((PASS+FAIL)) +if [ $FAIL -eq 0 ]; then + echo "ok $PASS/$TOTAL next/tests/nx_kernel_server.sh passed" +else + echo "FAIL $PASS/$TOTAL passed, $FAIL failed:" + echo "$ERRORS" +fi +[ $FAIL -eq 0 ] diff --git a/plans/fed-sx-milestone-1.md b/plans/fed-sx-milestone-1.md index 56944f29..5ea66a9d 100644 --- a/plans/fed-sx-milestone-1.md +++ b/plans/fed-sx-milestone-1.md @@ -515,7 +515,8 @@ publish(ActorId, ActivityRequest) -> - [x] **8c-proj** — Routes GET `/projections` (list stub) + GET `/projections/{name}` (state stub) via `match_prefix`. Bare-path list endpoint dispatches before the prefix clause. `next/tests/http_projections.sh` (11 cases). Registry-backed implementation deferred. - [x] **8c-post-auth** — `route/2(Req, Cfg)` adds POST `/activity` with bearer-token check. Cfg `:publish_token` is the expected token; missing / wrong / malformed Authorization all return 401. Authorized requests get a stub 200 ("published (stub)"). `next/tests/http_post_activity.sh` (13 cases). - [x] **8c-post-publish-pure** — `next/kernel/nx_kernel.erl` — pure-functional kernel orchestrator. `new/3(ActorId, KeySpec, ActorState)` builds the runtime state; `publish/2(Request, State)` calls `outbox:publish` with a Context derived from state, advances log + next_published on success. `next/tests/nx_kernel_pure.sh` (12 cases). -- [ ] **8c-post-publish-srv** — gen_server wrapper around nx_kernel that the HTTP layer can call from POST `/activity` handler. +- [x] **8c-post-publish-srv** — gen_server wrapper around nx_kernel: `start_link/3`, named-process `publish/1`, `query/0`, `log_tip/0`, `with_projections/1`, `stop/0`. `next/tests/nx_kernel_server.sh` (11 cases). HTTP layer integration follows. +- [ ] **8c-post-publish-http** — Wire the gen-server-backed `nx_kernel:publish/1` into `http_server` POST `/activity` handler. - [ ] **8d** — Content negotiation by Accept header: application/activity+json (default), application/cbor, application/json, application/sx. **Deliverables:** @@ -990,6 +991,7 @@ A few things still under-specified; resolve as work begins. Newest first. One line per sub-deliverable commit. Erlang conformance gate (`bash lib/erlang/conformance.sh`) must remain 729/729 on every entry. +- **2026-05-28** — Step 8c-post-publish-srv: `nx_kernel.erl` extended with gen_server callbacks + named-process API. `start_link/3(ActorId, KeySpec, ActorState)` spawns the worker and registers under the literal `nx_kernel` atom; `publish/1(Request)` calls into `handle_call({publish, Request}, ...)` which delegates to the pure `publish/2` and reflects the new state back into the server. `query/0` returns the full state proplist; `log_tip/0` is a direct accessor; `with_projections/1` mutates the projections list. Same port quirks as Step 5b/7b documented (raw Pid return, no `?MODULE`, processes don't persist across separate `erlang-eval-ast` calls — tests inline start_link with operations). `next/tests/nx_kernel_server.sh` 11/11. Erlang conformance 729/729. - **2026-05-28** — Step 8c-post-publish-pure: `next/kernel/nx_kernel.erl` — pure-functional kernel orchestrator that wraps `outbox:publish/2` with a long-lived runtime state. `new/3(ActorId, KeySpec, ActorState)` initialises state with an empty log + monotonic `:next_published` counter. `publish/2(Request, State)` builds the publish Context from state, calls outbox:publish, and on success advances `:log` and increments `:next_published`. The counter solves the "same Request published twice" replay collision — each call gets a distinct `:published` timestamp, so the canonical-bytes CID differs and stage_replay doesn't halt. On failure (e.g. bad key), state is returned unchanged. Step 8c-post-publish split into pure (done) + srv (gen_server wrapper) sub-deliverables. `next/tests/nx_kernel_pure.sh` 12/12. Erlang conformance 729/729. - **2026-05-28** — Step 8c-post-auth: POST `/activity` route + bearer-token auth via new `route/2(Req, Cfg)` variant. Cfg's `:publish_token` is the expected bearer; mismatched / missing / malformed (no "Bearer " prefix) / empty-token Authorization all surface as 401 `unauthorized_response/0`. `route/1` is a backwards-compatible wrapper with empty Cfg — any POST `/activity` over `route/1` is 401 by design (no token configured). `Bearer ` prefix stripped via the same `match_prefix` helper used elsewhere. Real publish wiring deferred to `8c-post-publish` (needs the kernel orchestrator that holds logs / actor keys / projection list). `next/tests/http_post_activity.sh` 13/13. Erlang conformance 729/729. - **2026-05-28** — Step 8c-proj: routes GET `/projections` (list stub returning `projections: (empty)\n`) + GET `/projections/{name}` (state stub returning `projection: \n`). Bare-path list clause dispatches before the prefix clause so `/projections` and `/projections/{name}` are distinguishable. All three dynamic-prefix routes (actors / artifacts / projections) compose cleanly — verified by a single combined-route test asserting all return 200 with distinct prefixes. Registry-backed implementation deferred — needs a running registry process at route time. `next/tests/http_projections.sh` 11/11. Erlang conformance 729/729.