fed-sx-m1: Step 8b-route — http_server:route/1 pure dispatch + ok/not_found helpers + 11 tests
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 30s

This commit is contained in:
2026-05-28 08:06:01 +00:00
parent 81efa1d8f0
commit b45ea2aa16
3 changed files with 172 additions and 1 deletions

View File

@@ -0,0 +1,49 @@
-module(http_server).
-export([route/1, ok_response/1, not_found_response/0, welcome_body/0]).
%% HTTP request router per design §16.1.
%%
%% Request shape (mirrors what the SX-side `http-listen` builds and
%% the http:listen/2 BIF bridge marshals into a proplist):
%% [{method, Binary}, {path, Binary}, {query, Binary},
%% {headers, [{Name, Value}, ...]}, {body, Binary}]
%%
%% Response shape:
%% [{status, Integer}, {headers, [{Name, Value}, ...]}, {body, Binary}]
%%
%% Real dispatch (actor docs, outbox listings, /activity POST,
%% /.well-known/sx-capabilities, etc.) lands in Step 8c+. Step 8b
%% wires the route/1 shape and a single hello-world handler that
%% proves the request→response round-trip.
%%
%% Method/path comparison uses integer-segment binaries because
%% `<<"GET">>` truncates to a single byte in this port.
route(Req) ->
M = field(method, Req),
P = field(path, Req),
dispatch(M, P).
%% 71 69 84 = "GET" | 47 = "/"
dispatch(<<71, 69, 84>>, <<47>>) ->
ok_response(welcome_body());
dispatch(_, _) ->
not_found_response().
%% "fed-sx kernel m1\n" — 17 bytes, hand-spelled.
%% f e d - s x _ k e r n e l _ m 1 \n
welcome_body() ->
<<102,101,100,45,115,120,32,107,101,114,110,101,108,32,109,49,10>>.
ok_response(Body) ->
[{status, 200}, {headers, []}, {body, Body}].
not_found_response() ->
[{status, 404}, {headers, []},
{body, <<110,111,116,32,102,111,117,110,100,10>>}]. % "not found\n"
%% Internal property-list field lookup. Returns nil when missing
%% so the route falls into the not_found arm gracefully.
field(K, [{K, V} | _]) -> V;
field(K, [_ | Rest]) -> field(K, Rest);
field(_, []) -> nil.

120
next/tests/http_route.sh Executable file
View File

@@ -0,0 +1,120 @@
#!/usr/bin/env bash
# next/tests/http_route.sh — Step 8b acceptance test.
#
# Exercises http_server:route/1 — pure (Request) -> Response
# proplist dispatch. The actual HTTP listener (which would call
# this via the http:listen/2 BIF bridge) is wired in Step 8c+.
# 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
cat > "$TMPFILE" <<'EPOCHS'
(epoch 1)
(load "lib/erlang/tokenizer.sx")
(load "lib/erlang/parser.sx")
(load "lib/erlang/parser-core.sx")
(load "lib/erlang/parser-expr.sx")
(load "lib/erlang/parser-module.sx")
(load "lib/erlang/transpile.sx")
(load "lib/erlang/runtime.sx")
(load "lib/erlang/vm/dispatcher.sx")
(epoch 2)
(eval "(get (erlang-load-module (file-read \"next/kernel/http_server.erl\")) :name)")
;; GET / -> 200
(epoch 10)
(eval "(get (erlang-eval-ast \"Req = [{method, <<71,69,84>>}, {path, <<47>>}], case http_server:route(Req) of [{status, 200} | _] -> ok; _ -> bad end\") :name)")
;; GET / body is the welcome message
(epoch 11)
(eval "(get (erlang-eval-ast \"Req = [{method, <<71,69,84>>}, {path, <<47>>}], R = http_server:route(Req), case R of [_, _, {body, B}] -> B =:= http_server:welcome_body(); _ -> false end\") :name)")
;; POST / -> 404 (only GET / is known)
(epoch 12)
(eval "(get (erlang-eval-ast \"Req = [{method, <<80,79,83,84>>}, {path, <<47>>}], case http_server:route(Req) of [{status, 404} | _] -> ok; _ -> bad end\") :name)")
;; GET /unknown -> 404
(epoch 13)
(eval "(get (erlang-eval-ast \"Req = [{method, <<71,69,84>>}, {path, <<47,102,111,111>>}], case http_server:route(Req) of [{status, 404} | _] -> ok; _ -> bad end\") :name)")
;; Missing fields -> 404 (graceful)
(epoch 14)
(eval "(get (erlang-eval-ast \"case http_server:route([]) of [{status, 404} | _] -> ok; _ -> bad end\") :name)")
;; Response always has :status, :headers, :body
(epoch 15)
(eval "(erlang-eval-ast \"R = http_server:not_found_response(), length(R)\")")
;; ok_response sets the right status
(epoch 16)
(eval "(erlang-eval-ast \"R = http_server:ok_response(<<104,105>>), case R of [{status, 200} | _] -> 200; _ -> nope end\")")
;; ok_response carries the supplied body
(epoch 17)
(eval "(get (erlang-eval-ast \"R = http_server:ok_response(<<104,105>>), case R of [_, _, {body, B}] -> B =:= <<104,105>>; _ -> false end\") :name)")
;; not_found body present (non-empty)
(epoch 18)
(eval "(get (erlang-eval-ast \"R = http_server:not_found_response(), case R of [_, _, {body, B}] -> byte_size(B) > 0; _ -> false end\") :name)")
;; welcome_body is non-empty
(epoch 19)
(eval "(get (erlang-eval-ast \"byte_size(http_server:welcome_body()) > 0\") :name)")
EPOCHS
OUTPUT=$(timeout 60 "$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="<no output for epoch $epoch>"
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 "module load name" "http_server"
check 10 "GET / -> 200" "ok"
check 11 "GET / body is welcome" "true"
check 12 "POST / -> 404" "ok"
check 13 "GET /unknown -> 404" "ok"
check 14 "missing fields -> 404" "ok"
check 15 "response has 3 entries" "3"
check 16 "ok_response status = 200" "200"
check 17 "ok_response carries body" "true"
check 18 "not_found body non-empty" "true"
check 19 "welcome body non-empty" "true"
TOTAL=$((PASS+FAIL))
if [ $FAIL -eq 0 ]; then
echo "ok $PASS/$TOTAL next/tests/http_route.sh passed"
else
echo "FAIL $PASS/$TOTAL passed, $FAIL failed:"
echo "$ERRORS"
fi
[ $FAIL -eq 0 ]

View File

@@ -507,7 +507,8 @@ publish(ActorId, ActivityRequest) ->
**Sub-deliverables:**
- [x] **8a**`http:listen/2` BIF wrapper in `lib/erlang/runtime.sx` (the briefing's allowed exception). Validates args, bridges Erlang handler funs to SX-callable lambdas via `er-of-sx`/`er-to-sx`, delegates to the native `http-listen` primitive in `bin/sx_server.ml`. Tests verify registration + arg validation (not the blocking listen loop). `next/tests/http_listen_bif.sh` (5 cases).
- [ ] **8b**`next/kernel/http_server.erl`: `start/1(Port)` spawns an Erlang process hosting `http:listen/2`, routes requests via `route/1`. Returns the Pid for shutdown.
- [x] **8b-route**`next/kernel/http_server.erl`: pure `route/1` dispatch + `ok_response/1`, `not_found_response/0`, `welcome_body/0`. GET / returns welcome; everything else returns 404 (graceful for missing fields). `next/tests/http_route.sh` (11 cases).
- [ ] **8b-start**`start/1(Port)` spawns an Erlang process hosting `http:listen/2`, requires the dict↔proplist marshaling bridge in the BIF wrapper.
- [ ] **8c**`route/1`: dispatch table for GET /actors/{id}, /outbox, /artifacts/{cid}, /projections, POST /activity (Step 6e auth via bearer token), /.well-known/sx-capabilities, /.well-known/webfinger.
- [ ] **8d** — Content negotiation by Accept header: application/activity+json (default), application/cbor, application/json, application/sx.
@@ -983,6 +984,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 8b-route: `next/kernel/http_server.erl` — pure `route/1` request→response dispatch. Request shape `[{method, Bin}, {path, Bin}, ...]`; response `[{status, N}, {headers, []}, {body, Bin}]`. GET / returns 200 with hand-spelled "fed-sx kernel m1" body; everything else returns 404 with "not found" body. Method/path binaries spelled byte-by-byte (string-literal segments would truncate). Split former 8b into 8b-route (done) + 8b-start (needs dict↔proplist marshaling bridge in the BIF wrapper before the spawned `http:listen` call gets useful request fields). `next/tests/http_route.sh` 11/11. Erlang conformance 729/729.
- **2026-05-28** — Step 8a: `http:listen/2` BIF wrapper added to `lib/erlang/runtime.sx` (the briefing's single allowed scope exception). The BIF takes `(Port, Handler)`, validates Port is an integer and Handler is an Erlang fun (else `badarg`), then builds an SX-callable bridge lambda that marshals request dict↔Erlang term via `er-of-sx`/`er-to-sx` and calls `er-apply-fun` on the handler. Delegates to the native `http-listen` primitive (registered in `bin/sx_server.ml`, native-only). Tests verify registration + arg validation paths (the blocking listen loop itself is not exercised — production callers spawn an Erlang process to host the call). `next/tests/http_listen_bif.sh` 5/5; Erlang conformance preserved at 729/729 despite the runtime.sx edit. Step 8 broken into 8a8d on the plan.
- **2026-05-28** — Step 7c: `outbox:publish` now broadcasts the signed activity to every projection process named in `Context`'s `:projections` entry — fired immediately after `log:append`, via `projection:async_fold`. Missing/nil/empty list is a no-op (preserves the Step 6d-publish contract). Stage halts (replay duplicate, sig failure) suppress the broadcast — projection state stays at zero while the activity is rejected. `next/tests/outbox_broadcast.sh` 14/14 covers single + multi projection fan-out, three-publish accumulation, replay-skip, sig-skip, and the projection receiving the post-sign Signed envelope (not the pre-sign skeleton). Erlang conformance 729/729.
- **2026-05-28** — Step 7b: `projection.erl` extended with gen_server callbacks + per-projection named-process API. `start_link/3(Name, InitialState, FoldFn)` spawns and registers under the supplied atom; `async_fold/2(Name, Activity)` casts a fold message; `query/1(Name)` synchronously returns the current state. Same port quirks as registry gen_server (Step 5b): raw Pid return, no `?MODULE` macro, processes don't survive between separate `erlang-eval-ast` calls — tests inline start_link with operations. Two named projections are independent. Snapshot persistence deferred to a later sub-step (needs SX-source eval + on-disk state). `next/tests/projection_server.sh` 11/11. Erlang conformance 729/729.