writeonce/docs/examples/writeonce-framework/router/router.wo
shoney.arickathil 82713e4010 feat: framework v1 slice 2 — the remaining ledger, ten items
- After seam: interface After + Aw + use_after; dispatch funnels every
  response (handler/short-circuit/404/405) through the after chain;
  the WS 101 sentinel skips it (never serialized)
- http/secure.wo: SecurityHeaders (nosniff/DENY/referrer; HSTS stays
  at the TLS proxy), Cors (preflight 204 before + origin stamp after,
  one class both halves), HostAllow (421), client_ip (XFF parsing —
  peer VERIFY stays story 35)
- http/nego.wo: accepts() (exact, type/*, */*; q stripped not ranked),
  etag_for (quoted base64 sha256), with_etag (If-None-Match -> 304)
- router: *rest wildcard (last segment, empty rest matches), Group
  (prefix + routes + group middleware) + Gmw prefix-scoped entries,
  App.mount; new App fields carry defaults so standing ctor literals
  keep compiling
- Req grows ctx bag; parse rejects duplicate Content-Length (400,
  RFC 9112 §6.3)
- web-app exercises all of it; gate grows 26 -> 38 checks (wildcards,
  group+ctx, etag+304, 406/200 negotiation, sec headers, 421,
  preflight+origin stamp, dup-CL 400)
- ledger rows flipped; dep graph section 3 grown (slice-2 done nodes,
  crypto gate cleared, cookie/CSRF/session/webhook/JWT now ready)
- merges: chat-ws-lifecycle (digests for ETag; WS + lifecycle ride
  along) + site-sample (second consumer gate); battery 13/13

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-23 06:45:51 +02:00

146 lines
4.8 KiB
Text

-- router/router.wo — the handler model and the route table.
--
-- No function values in this language, by doctrine — so a handler is a
-- CLASS satisfying the Handler interface (its fields are the closure
-- substitute), dispatched structurally (ICALL). A class missing `handle`
-- is a compile error (WO-E205). Middleware is its own interface because
-- the signature differs: `before` returns `?Resp` — nil means continue,
-- a Resp short-circuits (401 gates, redirects).
pub interface Handler {
fn handle(req: Req) -> Resp
}
-- `mut req`: middleware may WRITE the request — auth attaches the
-- authenticated principal (req.principal) for downstream handlers.
pub interface Middleware {
fn before(mut req: Req) -> ?Resp
}
-- framework v1 slice 2: the response half of the chain. `after` runs on
-- EVERY response leaving dispatch — handler answers, middleware
-- short-circuits, the framework 404/405 — so security headers and CORS
-- reach all of them. It mutates, never replaces (no ?Resp: an after that
-- could swallow the response would be a second handler).
pub interface After {
fn after(req: Req, mut r: Resp)
}
-- Wrapper record, same reason as Mw/Route.
pub class Aw {
a: After
}
-- One route: method + pattern + the handler value. Built with a ctor
-- literal at the registration site (`Route { method: "GET", pattern:
-- "/products/:id", h: ProductShow {} }`) — the exact ownership shape the
-- conformance corpus pins (run/container-owned-move).
pub class Route {
method: Text
pattern: Text
h: Handler
}
-- Middleware wrapper record, same shape as Route for the same reason.
pub class Mw {
m: Middleware
}
-- Request-line logging, the one middleware every framework ships: method +
-- path to stderr, never short-circuits. `pad` is the record-class ctor
-- convention (every stateless handler carries one Int field).
pub class Logging {
pad: Int
fn before(mut req: Req) -> ?Resp {
print_err("${req.method} ${req.path}");
return nil;
}
}
-- Does `pattern` match `path`? Fills `params` with :name captures.
-- Segments split on '/', empties dropped (so "/a//b" == "/a/b" and the
-- root "/" is the empty segment list). First mismatch wins; a :segment
-- captures anything non-empty. A LAST segment `*name` (framework v1
-- slice 2) captures the whole rest — zero or more segments, re-joined
-- with '/' — so "/files/*path" matches "/files" (path = "") and
-- "/files/a/b" (path = "a/b"). A `*` anywhere else never matches:
-- precedence stays registration order, wildcards last by construction.
pub fn route_match(pattern: Text, path: Text, mut params: map<Text, Text>) -> Bool {
let ps = split(pattern, "/");
let xs = split(path, "/");
let psegs: multi Text = [];
for s in ps { if s != "" { push(psegs, s); } }
let xsegs: multi Text = [];
for s in xs { if s != "" { push(xsegs, s); } }
let np = len(psegs);
let wild = false;
if np > 0 {
if starts_with(psegs[np - 1], "*") { wild = true; }
}
if wild == false {
if np != len(xsegs) { return false; }
} else {
if len(xsegs) < np - 1 { return false; }
}
let i = 0;
while i < np {
let p = psegs[i];
if wild and i == np - 1 {
let rest = "";
let j = i;
while j < len(xsegs) {
if rest == "" { rest = xsegs[j]; } else { rest = "${rest}/${xsegs[j]}"; }
j = j + 1;
}
params[substr(p, 1, len(p) - 1)] = rest;
return true;
}
if starts_with(p, "*") { return false; }
let x = xsegs[i];
if starts_with(p, ":") {
params[substr(p, 1, len(p) - 1)] = x;
} else {
if p != x { return false; }
}
i = i + 1;
}
return true;
}
-- framework v1 slice 2: a route GROUP — a prefix plus its own routes and
-- its own before-middleware, mounted into an App in one move. The group
-- prefixes patterns at REGISTRATION (the mount is a plain move); its
-- middleware becomes prefix-scoped on the App: it runs only for paths
-- under the prefix, after the global chain, before the route scan.
pub class Group {
prefix: Text
routes: multi Route = []
middleware: multi Mw = []
fn get(pattern: Text, take h: Handler) {
push(self.routes, Route { method: "GET", pattern: "${self.prefix}${pattern}", h: h });
}
fn post(pattern: Text, take h: Handler) {
push(self.routes, Route { method: "POST", pattern: "${self.prefix}${pattern}", h: h });
}
fn put(pattern: Text, take h: Handler) {
push(self.routes, Route { method: "PUT", pattern: "${self.prefix}${pattern}", h: h });
}
fn delete_(pattern: Text, take h: Handler) {
push(self.routes, Route { method: "DELETE", pattern: "${self.prefix}${pattern}", h: h });
}
fn use_mw(take m: Mw) {
push(self.middleware, m);
}
}
-- A prefix-scoped middleware entry on the App (what mounting a group's
-- middleware becomes).
pub class Gmw {
prefix: Text
m: Middleware
}