actions
36 modules
actions/action_bridge.ts
Bridge from a notification ActionSpec to the SSE EventSpec it pushes as.
Request/response actions are served by the RPC and WS dispatchers (actions/action_rpc.ts, actions/register_action_ws.ts), never as REST routes.
actions/action_codegen.ts
actions/action_dispatcher.ts
ActionDispatcher — symmetric send/receive for JSON-RPC actions.
Wraps a Transports registry and ActionEventEnvironment to provide bidirectional action dispatch via JSON-RPC 2.0.
actions/action_event_data.ts
Action event data types — discriminated union for state machine data.
A discriminated union across the action kinds (request_response, remote_notification, local_call). Each variant narrows the data shape by kind, phase, and step.
actions/action_event_helpers.ts
Action event helper functions — type guards, validators, and data creation.
actions/action_event_types.ts
Action event type definitions — state machine constants and environment interface.
actions/action_event.ts
ActionEvent — state machine for action lifecycle management.
Manages an action through its phases (send_request → receive_response, etc.) and steps (initial → parsed → handling → handled/failed).
actions/action_registry.ts
ActionRegistry — query and filter utility over
ActionSpecUnion[].Vocabulary (see the
docs/directory):*_handled_*— request_response specs the named side receives (so the named side owns the handler). Used by codegen to emit typed handler maps.*_relevant_to_*— the loose "everything this side might encounter" set, used by the typed-Proxy method enums (FrontendActionMethod,BackendActionMethod).broadcast_*— kind-narrowremote_notificationset with thestreams-target exclusion. Today this matches what the broadcast API exposes.backend_initiated_*— forward-looking kind-agnostic version of the broadcast set. Same content today; will diverge when local_calls or backendrequest_responsejoin the backend's typed surface.
Cache discipline:
spec_by_method(Map) and the internal streams-target set lazy-memoize because the Map is consulted per-RPC dispatch (actions/frontend_rpc_client.ts wires it intolookup_action_spec) and the streams set is rebuilt by two public getters. Array-returning getters recompute on each call so callers can mutate the result freely (.sort(),.push(injected)on a copy, etc.) without affecting the registry — codegen is a build-time path where the extra.filter/.mapwork is negligible.actions/action_rpc.ts
Single JSON-RPC 2.0 endpoint from action specs.
create_rpc_endpoint produces
RouteSpec[](GET + POST on one path) with an internal dispatcher. Method name lives in the JSON-RPC envelope (POST body or GET query string), not the URL. Auth is checked per-action inside the dispatcher.Handler signature:
(input: TInput, ctx: ActionContext) => TOutputwhere ActionContext (actions/action_types.ts) provides auth identity, DB, and framework context.actions/action_spec.ts
Action spec types — the canonical source of truth for action contracts.
Extracted from zzz's action system. Action specs define method, kind, auth, side effects, and input/output schemas. actions/action_bridge.ts derives the SSE EventSpec of a notification from one.
A spec is a plain object typed by these interfaces, written with
satisfies(satisfies RequestResponseActionSpec) so its literal types survive; nothing parses a spec at runtime. Itsinputandoutputare@fuzdev/fuz_schemaschemas (AnySchema). The registration-time checks live in actions/compile_action_registry.ts.actions/action_types.ts
Shared type surface for the action system — Action (the composable
{spec, handler?}tuple), the handler context ActionContext and its narrowed tiers, the handler signatures, RpcAction, and the rpc_action binder.Sits above actions/action_spec.ts (the spec interfaces) and below the dispatchers (actions/register_action_ws.ts, actions/action_rpc.ts, actions/perform_action.ts). Extracted so the shared protocol actions (e.g. heartbeat_action) and every action factory can name them without pulling in server-only modules — everything here is type-only but the identity-function binder.
HTTP RPC and WebSocket dispatchers both call into perform_action, and both pass the same ActionContext to the handler. Consumers inject domain deps via factory closures the same way HTTP RPC factories do (see auth/standard_rpc_actions.ts).
actions/broadcast_api.ts
Backend-initiated broadcast notification plumbing — generic across consumers.
Builds a typed
{method_name: (input) => Promise<void>}object from a list of action specs. Each call validates input against the spec, wraps it in a JSON-RPC notification, and either broadcasts to every connection or fans out with a per-connection ACL predicate.Counterpart to register_action_ws: that handles request-scoped dispatch (frontend-initiated), this handles broadcast (backend-initiated). Together they cover the two primitives fuz_app consumers share. Request-scoped streaming (
completion_progress,zap_applyevents) stays onctx.notifyinside a handler — it's socket-scoped, not broadcast.Extracted from zzz's
backend_actions_api.tsto stop the pattern from drifting across consumers.actions/cancel.ts
Shared cancel action — a fuz_app protocol action whose behavior the dispatcher owns, so it is a spec with no handler.
Semantics: the client sends `{jsonrpc, method: 'cancel', params: {request_id}}` to abort an in-flight request on the same socket. register_action_ws intercepts this notification and aborts the matching pending request's
ctx.signal. Unknown ids are no-ops by design — races between response arrival and cancel delivery are safe without extra coordination.There is no handler: cancel semantics are dispatcher-owned (the dispatcher has the
{request_id → AbortController}map, not a handler). Consumers spread cancel_action (or the protocol_actions bundle from actions/protocol.ts) into their server'sactionsarray sospec_by_methodknows about it (enabling input validation on incoming cancels) and so create_rpc_client codegen producesapp.api.cancel()when desired — thoughFrontendWebsocketClient.request({signal})sends the cancel on abort without needing the typed API.Wire format is snake_case
cancelwith{request_id}, not MCP's$/cancelRequestwith{requestId}— fuz_app's WS transport isn't MCP, and adopting MCP's convention would leak protocol-specific framing into the base transport. If an MCP adapter is ever built, the translation layer at the adapter is the right seam.actions/compile_action_registry.ts
Shared registration loop for action-dispatcher endpoints.
create_rpc_endpoint (HTTP RPC) and register_action_ws (WebSocket) both build a
Map<method, RpcAction>from a list of action specs and gate the build on the same checks, in this order (named rather than numbered — "registry-time invariant N" elsewhere in the codebase refers to the RouteAuth cross-axis set in http/auth_shape.ts, a different list):- Schema slots —
inputandoutputeach hold a@fuzdev/fuz_schemaschema (assert_validation_schema); a value that is no schema throws naming the action and the slot. Fires for every spec, before the checks that read the schemas. - Auth-shape cross-axis invariants — per assert_route_auth_invariants in http/auth_shape.ts: roles imply a required actor, no accountless actor, nothing to gate on unrestricted auth (that set's invariants 1, 3, and 4). Fires for every spec with non-null auth.
- Auth-shape biconditional — per assert_route_auth_acting_biconditional in http/auth_shape.ts: `auth.actor !== 'none' ⟺ input declares acting?: ActingActor` (that set's invariant 2). Fires for every spec with non-null auth.
- No
auth.required_scopeon an action —ActionSpec.authis the same RouteAuth a route spec carries, so the field parses here, but only apply_route_specs mounts a guard from it and perform_action never reads it. Declaring it on an action would be a security control that silently does nothing, which is the exact shape token scoping was built to refuse. Rejected loudly instead; actions are governed by the per-method scope gate inside perform_action, which derives the samerpc:<method>capability fromspec.methodrather than trusting a hand-written one. - Rate-limit / account axis —
rate_limit: 'account' | 'both'requiresauth.account === 'required'; without an account on the request there is no key for the per-account bucket. - JSON-RPC §4.2 wire validity —
request_responsespecs whose handler will reach the dispatch map must not use a null schema (literal(null)) for input (the wire format forbids"params": null; use a void schema,s.void, for parameterless methods), nor a void schema for output (a response always carries aresult, which clients validate againstspec.output; use a null schema for methods with nothing to return). - Duplicate method names — JSON-RPC keys on
method, so every spec in the array must declare a uniquemethodregardless of kind / handler presence.
Pre-consolidation each dispatcher inlined these checks; the comment in actions/register_action_ws.ts literally said "mirrors the HTTP RPC registration check" but nothing kept them mirrored. Centralizing the loop closes the most likely future drift surface.
- Schema slots —
actions/connection_closer.ts
Closing live connections — WebSocket and SSE — when the credential behind them is revoked.
Why this exists. A WebSocket and an SSE stream are authorized once, at open. Per-message WebSocket dispatch (actions/perform_action.ts) reloads role grants, never the session or token, and a one-way stream re-reads nothing. So a revocation takes effect on an open connection only when something closes it. ConnectionCloser is that capability, and every revocation handler holds one: the session and token revokes, the revoke-alls, account delete and purge,
/logout,/password, the session and token caps for what they evict, and the role revokes (role_grant_revokeand a self-service disable), which close only the connections an endpoint gated on the revoked role. The auth cleanup holds one too (AuthCleanupDeps.connection_closer): its session sweep closes the connections of each expired session it deletes, after that delete commits.Closing after commit
A revocation runs inside a request transaction, and it must not close a connection until that transaction commits. queue_connection_close defers the close onto the request's post-commit queue (emit_after_commit): it runs after the commit and is dropped on rollback, so a revocation that never happened closes nothing.
Two things rest on that order. A client told "revoked" rechecks its session straight away, and before the commit the row it probes is still there. And connection admission registers a connection and then re-reads its credential (revalidate_resolved_auth): a close that missed the registration must belong to a revocation the re-read can see, which holds only if the close came after the commit.
Why the handlers close directly
The audit listener (create_revocation_guard) closes connections too, but only once the audit row is announced, and a row written outside a transaction (
/login,/password) is fail-open. The handler's own close is the one that runs whatever happens to the audit row, so the closer it holds must reach every transport whose connections outlive their credential. RealtimeCloser is that fan-out, and create_app_backend puts one on AppDeps.The audit listener
create_revocation_guard repeats a revocation's close when its audit row is announced, which covers a revocation emitted by code that holds no closer. create_app_server registers one on
deps.connection_closerwhen it mounts a WebSocket endpoint or the audit stream, so it reaches every member — each WebSocket connection registry and the audit stream registry — through the one fan-out.Twin of the Rust spine's ConnectionCloser, ConnectionCloseTarget, queue_connection_close, RealtimeCloser, and
register_revocation_guard.actions/connection_registry.ts
Backend WebSocket connection registry — manages server-side WebSocket connections with session tracking, revocation support, a per-account connection cap, and two-phase registration.
Two-phase registration
An upgrade resolves its credential before the socket exists, and every revocation closes the connections *registered* under the revoked credential. A one-step registration therefore has a window: a revocation landing between the credential check and the insert closes nothing, and the upgrade is admitted on a dead credential — for the socket's lifetime, since per-message dispatch never re-reads the session or token.
Registration is split to close it:
ConnectionRegistry.register_pendinginserts the entry un-admitted. It is closeable from that instant —close_connectionsmatches pending entries deliberately — and is otherwise inert: it evicts nothing, the cap does not count it, no broadcast /send_to_account/request_connectionreaches it, and the count accessors andis_registereddo not see it (pending_connection_countdoes).- The caller re-checks the credential against the database (revalidate_resolved_auth in auth/resolved_auth.ts).
ConnectionRegistry.admitflips the entry to admitted — or refuses when a revocation closed it in the meantime, evicting nothing. The cap's eviction happens here, so a connection that is never admitted never closes a live one, and any number of pending registrations on one account leave its admitted connections alone.
A revocation whose close ran after step 1 finds the entry, pending or admitted, and closes it; one that committed before step 2 is seen by the re-read, which refuses. Nothing is delivered to a pending entry rather than queued for it, so a refusal never has to promise that a queue a revoked credential would have read is dropped unread, and a broadcast's returned count names only connections that can receive it. The cost is a slightly wider blind spot at connect: a server-initiated message sent between the handshake and admission — one credential re-check later — is not delivered, just as one sent before the handshake is not.
add_connectionstays as the one-step form (register and admit together) for a connection with no revocable credential behind it — tests and harnesses that register a socket directly. An upgrade that authenticated a session or token uses the two-phase form. The twin of the Rustfuz_realtimeConnectionRegistry.Outbound bound
Every frame the server sends a connection goes through one path —
send_to, which responses, error frames and socket-scoped notifications use, and the fan-outs (broadcast,broadcast_filtered,send_to_account,request_connection) — into the connection's WsOutboundWriter (actions/ws_outbound_writer.ts). A send never waits and never throws: one recipient that stopped reading must not slow a producer or another recipient.What waits for a socket is held to a byte budget,
outbound_queue_bytes(DEFAULT_WS_OUTBOUND_QUEUE_BYTES): each waiting frame is charged its UTF-8 length plus OUTBOUND_FRAME_OVERHEAD_BYTES, and a frame is always accepted when nothing is waiting. Nothing counts frames. A frame sent to an idle connection goes straight to the socket; the rest of a burst sent in one synchronous run waits, as does anything sent while the socket's own buffer is backed up.A frame that does not fit closes the connection rather than being dropped alone: the connection is removed in the same synchronous step — the overflowing send does not count it, later sends miss it, the count accessors and the cap no longer see it — its controller is aborted, what was waiting is discarded, and the socket is closed with WS_CLOSE_OUTBOUND_OVERFLOW. Frames already handed to the socket may still reach the client ahead of the close frame; nothing follows it, the response of the request whose handler overflowed the connection included. One
warnline names the connection, its account, and what was waiting; no audit row is written — a client can provoke an overflow at will, and a write per overflow would amplify it.A socket that holds unwritten bytes past WS_WRITE_STALL_TIMEOUT is dropped with no close frame, and removed the same way, with one
warnline. Every other close the registry makes (a revocation, the cap, the shutdown,close_connection) hands the frames still waiting to the socket ahead of its close frame while the socket's buffer is below WS_WRITE_HIGH_WATER_BYTES, discards the rest, and cuts the socket if the close frame is still unwritten after WS_CLOSE_WRITE_TIMEOUT. A reply sent to an otherwise idle connection just before such a close reaches the client; one queued behind a backed-up socket does not.A connection the registry closed or dropped is out of its map, so the per-account cap does not count it while its socket is still closing. What the runtime holds for such a socket is bounded by the writer (actions/ws_outbound_writer.ts, "Closing" and "Runtimes").
The twin of the Rust
fuz_realtimeoutbound queue — same budget, charge, close code and deadlines. Where they differ: the Rust spine discards every frame queued before any close, and queues every frame, where this registry writes the first frame of a run straight through and, at a close that is not an overflow, the waiting frames its socket has room for.Shutdown
close_all_connections— the closeAppServer.closeruns — closes every connection, pending or admitted, with WS_CLOSE_GOING_AWAY, and leaves the registry closing: from then on every registration is born closed. Aregister_pendingoradd_connectioninserts nothing — it aborts the caller's controller and closes the socket with WS_CLOSE_GOING_AWAY at once — so an upgrade still in flight when the server shuts down is closed rather than outliving it. An upgrade registered before the close-all is closed by it; one registered after is born closed; none is admitted. The flag is set in the same synchronous step that closes the live connections, so anadmitthat finds its entry gone and readsis_closing()sees the shutdown — a shutdown is never read as a revocation (a revocation the shutdown overtook reads as the shutdown). Closing is permanent: a closed registry hosts no further connections.actions/frontend_rpc_client.ts
Frontend-only typed RPC client factory.
Bundles the `ActionRegistry + ActionEventEnvironment + Transports + ActionDispatcher + create_rpc_client + create_throwing_api` boilerplate every consumer repeats.
lookup_action_handlerdefaults to() => undefined(HTTP-only frontends rarely need handlers); passoptions.lookup_action_handlerto wire WS-pushedremote_notificationdispatch or areceive_error/local_callhook.Transports: always a FrontendHttpTransport on
path— a read (side_effects: false) goes as aGETunless its input carries a sensitive value ('secret'or'personal') or its URL runs long, both derived fromspecs— and, withws, a FrontendWebsocketTransport over the WebSocket client the caller passes, which everyrequest_responsemethod routes to. The caller builds and connects the client (FrontendWebsocketClient, its URL from to_same_origin_ws_url), so an HTTP-only bundle never imports the socket.Returns both Proxy shapes from one factory call:
api— typed throwing Proxy.await api.foo(input)returns the unwrapped value or throws anErrorcarrying{code, data}from the JSON-RPC error. Use at hot-path call sites.api_result— typed Result-shaped Proxy.await api_result.foo(input)returnsResult<{value}, {error: JsonrpcErrorObject}>. Use when call sites want to inspecterror.data.reasonwithout try/catch — and anywhere allocating anErrorper{ok: false}is wasteful (e.g. reconnect-stormservice_unavailablepaths). Result is the protocol primitive; the throwing form is a wrapper over it. Both share the same underlying transport — pick per call site, no construction cost.
Generic
TApiis the consumer's typed Proxy interface. The `as unknown as TApi` double cast happens inside the helper so call sites get a typed return value without the cast hostility.api's type isThrowingApi<TApi>— the mapped type strips the Result wrapper.const {api, api_result} = create_frontend_rpc_client<MyActionsApi>({ specs: all_specs, }); // hot path: await api.account_verify() // rare branch: const r = await api_result.account_verify(); if (!r.ok) { … }Returns the underlying
peerandenvironmentalongside the two api shapes so advanced consumers (zzz-style frontends needing extra transports / WS notification handlers / action-history wiring) can extend without recreating the bundle.local_callspecs inspecsno-op unlesslookup_action_handlerresolves a handler for the'execute'phase. Frontend-sidelocal_callis uncommon; the factory targets wire-dispatched actions by default.actions/heartbeat.ts
Shared heartbeat action — a fuz_app protocol action carrying both a spec and a handler in one tuple. Consumers spread heartbeat_action (or the protocol_actions bundle from actions/protocol.ts) into the server's
actionsarray so disconnect detection works identically across every repo without per-consumer ping plumbing.The client's activity-aware heartbeat timer (in FrontendWebsocketClient) issues a
heartbeatrequest whenever the connection has been idle for its configured interval; server-side the dispatcher tracks receive time, so incoming heartbeats keep the socket alive without any handler-level state.Parameterless: the input is
void, so absent,null, and{}params are all the no-arg call (to_void_params) and anything else is refused — the same shapes the Rust spine's heartbeat admits viarequire_void_params. The output is an empty object. `{client_ts, server_ts}` fields can be added later if clock-skew telemetry ever matters — the Action container is open for additions without churning consumer call sites.actions/notification_sender.ts
Pushing a server-initiated JSON-RPC notification to an account's live WebSocket connections.
Why the handler context carries it. A notification carries a domain payload (an offer, a revoked grant) that only the handler holds, so the handler builds the message and queues the send after its commit (queue_offer_notification in auth/role_grant_offer_notifications.ts). perform_action puts the sender on every ActionContext, so no action factory takes one and none can be wired with the wrong one: an offer created over HTTP RPC must reach the recipient's sockets on the WebSocket registry, which a sender bound to any other registry would miss silently.
Why a fan-out. create_app_backend puts one RealtimeNotificationSender on
AppDeps.notification_sender, and create_app_server adds every WebSocket connection registry it mounts. The registries are created at mount, after the RPC and WebSocket action factories run, so a sender read at send time is the only one that reaches them. A server mounting no WebSocket endpoint holds an empty fan-out, and its sends reach no one.Twin of the Rust spine's NotificationSender and
NoopNotificationSender; the Rust backend serves one connection registry on every endpoint, which the fan-out stands in for.actions/peer_ping.ts
Shared
peer/pingaction — the protocol action that exercises the server→client request/response direction of ActionPeer.peer/pingisinitiator: 'both': the client→server direction overlaps withheartbeat, but the new direction this action drives is the reverse — a connected client invokespeer/pingover its socket, and the handler turns around and *initiates* apeer/pingrequest back to that same socket (ctx.request_client), awaits the client's echo, validates it against PingResponse, and returns the validated shape. So one client RPC drives the whole round-trip and every outcome surfaces as that RPC's wire response.Public auth. A liveness echo is non-sensitive; the WebSocket upgrade itself still authenticates, so only admitted sockets reach the handler.
No return transport (HTTP RPC). Over HTTP there is no socket to ping —
ctx.request_clientis absent — so the handler refuses withpeer_no_transportrather thanmethod_not_found. That requires the action to be mounted on the HTTP RPC endpoint as well as the WS endpoint (it is, via the spine's full mount); the manifest excludes it as a protocol action so the cross-impl diff stays apples-to-apples.The
data.reasondiscriminators and the PingResponse shape are the cross-impl wire contract — twins of the Rust spine'sREASON_PEER_*constants and PingResponse (parity by test, not codegen).Frontend-safe. Like
heartbeat.ts/cancel.ts, this module names the handler types (ActionContext, RpcAction) type-only from actions/action_types.ts and never imports the dispatch core (action_rpc.ts, which would drag Hono into any frontend that pulls protocol_action_specs). The frontend responder (peer_ping_responder) lives here too so a real frontend can answer the server's probe.actions/peer_request.ts
Server→client peer requests (ActionPeer) — the request/response direction a backend initiates to a connected WebSocket client and awaits a typed reply.
PendingPeerRequests is the correlation registry: it owns the in-flight map (nested
connection_id → request id— the nesting is the per-connection isolation guarantee), id allocation (s{n}-namespaced so a client's own request ids can't collide), the per-request deadline, and the per-connection in-flight cap. It deliberately does not touch the socket — the caller (ConnectionRegistry.request_connection) does the send and threads the reply back viaresolve. This mirrors the Rustfuz_realtime::peersplit (the PendingPeerRequests registry vs the transport that composes it), and keeps the registry pure data so it unit-tests without a live socket.actions/perform_action.ts
Transport-agnostic dispatch core shared by HTTP RPC and WebSocket action dispatchers.
perform_action runs the post-parse pipeline that every action-spec handler must traverse:
- Pre-authorization auth (401) — short-circuits unauthenticated callers
on
'required'axes. - Authorization phase — when
auth.actor !== 'none'(orauth.account !== 'none' && actor === 'none'), resolves the actor via apply_authorization_phase against the resolved credential's account plus the request'sactingselector, read off the raw params byread_acting. Failures fold into a JSON-RPC error envelope. The test-harness escape hatch lives in the caller — passpreset.request_contextto skip the live phase and use a pre-baked context instead. - Post-authorization auth (403) — gates
auth.credential_types, the credential's scope (resolved_auth_scope), andauth.rolesagainst the resolved context. - Rate limit (429) — per-action IP / account throttling, throttle-
requests semantics (every invocation records, regardless of outcome).
Ahead of validation so the budget is charged for malformed params too
— a flood of garbage bodies must cost the sender its quota, not slip
past the limiter on a cheap 400 — and so a throttled caller never pays
for schema work. The account key is the credential's own account
(
request_context.account.id), settled by authentication, so the gate sits behind the authority gates by choice rather than necessity: a caller those gates refuse is answered 403, not 429. - Validate params (400) — first, one walk of object
params(scan_json_value) refuses an own__proto__key at any depth, withdata.reasonparams_proto_key(ERROR_PARAMS_PROTO_KEY), then U+0000 in any string or key, withparams_nul(ERROR_PARAMS_NUL), on every input schema, before it runs; thenspec.inputparses the params (parse) with void /?? {}rules (to_input_params). A refusal is the genericinvalid params, withdata.reasonwhen the first issue's field declares aninvalid_reason(to_invalid_params_error) and the issues, as WireIssues, under DEV only. Runs after the authority gates: a 400 describing the action's input shape to a caller those gates refuse would confirm the method exists and describe how to call it, to a channel that should have learned nothing. Coarse authority facts before fine ones, and no shape disclosure before authority is settled — the same argument that puts the credential gate ahead of the scope gate. The cost: a malformed request from an *authenticated* caller pays for the authorization phase's actor + role_grant reads before being rejected, rather than being turned away by validation first. Not a new DoS lever — the same caller reaches that work anyway by sending well-formed params — but there is no cheap-rejection path for buggy clients. - Dispatch + DEV-only output validation + error normalization —
spec.side_effectspicks transaction (deps.db.transaction) vs pool. Handler throws roll back the transaction; the catch sits outside the transaction boundary. Handler outputs are validated againstspec.outputunder DEV (logs an error on mismatch, never throws, never mutates the result).
The function is pure data — it never touches a Hono context, so HTTP RPC and WS dispatch call into it the same way and bind the discriminated PerformActionResult to their wire shape.
- Pre-authorization auth (401) — short-circuits unauthenticated callers
on
actions/protocol.ts
Canonical bundles of fuz_app's protocol actions —
heartbeat,cancel, andpeer/ping. Spread these into consumer registrations on both sides of the wire so the registries stay symmetric without per-consumer plumbing.Protocol actions are wire-protocol concerns (liveness, abort) shipped by fuz_app, not consumer domain logic. The split is intentional: the server needs
{spec, handler}tuples to drive dispatch; the frontend ActionRegistry only stores specs. The codegeninclude_protocol_actions: falsedefault (in actions/action_codegen.ts) is the third leg of this contract — protocol actions are excluded from generated typed surfaces because consumers spread them in at registration time.Adding a future protocol action (e.g. clock-skew probe, reconnect-resume token) means appending to these arrays in one place; no consumer migration required.
actions/register_action_ws.ts
WebSocket JSON-RPC endpoint — the WS transport binding.
Consumers declare WS endpoints on create_app_server's
ws_endpoints, which mounts each through register_action_ws; call it directly only to mount an endpoint outside that assembly. Tests drive the dispatcher directly via create_ws_test_harness.The upgrade route
One
GET pathroute, its guards in coarse-to-fine order — the route-spec pipeline's, from fuz_auth_guard_resolver:verify_request_source(allowed_origins)— a disallowed origin is refused before the upgrade handshake runs (403).- require_auth — an unauthenticated upgrade is refused (401).
require_token_scope('surface:ws_upgrade')— rule 3: a narrowed token cannot hold a socket (403token_scope_required). Server-initiated pushes (broadcasts, role-grant-offer notifications, peer requests) reach whatever the account's connection reaches, with no per-recipient filter to narrow them by, so a scoped token that could upgrade would observe far more than it was granted.- Authorization phase (run_authorization_phase) — the acting actor
from the
?acting=<uuid>query string (parse_acting; malformed reads as omitted, but a query holding an escape that doesn't decode, in any key, is a 400invalid_query_params— read_request_query_pairs), against the authenticated account, building the RequestContext per-message dispatch reads (400s on actor selection). Multi-actor accounts must supply?acting; single-actor accounts work without it. require_role(required_roles), for a gated endpoint (403).
Only
GETis mounted (Hono servesHEADthrough it), so any other method on the path is the assembled server's 405 (server/unmatched_route.ts), and aGETthe guards admit that asks for no upgrade passes on to its 404. The guards run as middleware ahead ofupgradeWebSocket, whose callback must returnWSEventsand so cannot produce a refusal.Symmetric to create_rpc_endpoint (from actions/action_rpc.ts): both transports parse their wire envelope, then call the shared perform_action core (actions/perform_action.ts) for the post-parse pipeline. WS-specific concerns — connection lifecycle, heartbeat, cancel-notification interception, socket-scoped notify — live in actions/ws_socket_session.ts; everything else (auth gates, input validation, authorization phase, rate limiting, transactional dispatch, DEV output validation, thrown-error normalization) is shared.
Per-message auth
Per-action auth runs inside perform_action on every message via the same gates HTTP RPC uses.
Per-socket lifecycle
Admission (the revocation race), the credential deadline, and the rule that a server-closed socket dispatches nothing are the per-socket half, in actions/ws_socket_session.ts.
actions/room_action_specs.ts
The room verbs' wire: the
room_*request specs, theroom_*notifications the registry fans out, their schemas, refusal reasons, and bounds — the TS twin of the Rust spine'sfuz_actions::roomspecs andfuz_realtime::room_registrynotification shapes.A room is a key (RoomId) the consumer chooses and parses, holding seats (members, each with a random MemberId and a small client-encoded state) and watches (occupancy without a seat). actions/room_registry.ts holds the state and the fan-out; actions/room_actions.ts builds the handlers over it. Every verb is WebSocket-only — a room belongs to a socket — so a consumer mounts them on a WS endpoint and never on an RPC one, actor-required (
actingselects the actor on a multi-actor account), and without side effects (the registry is memory, so no transaction opens).payloadandstateare strings the client encodes, so both twins measure their bounds alike, in UTF-8 bytes, and charge the per-connection limiter their JSON-escaped length (json_escaped_len). Refusals carrydata.reason, theERROR_ROOM_*constants, plusrate_limitedwithdata.retry_after. Every member event carries the room'sseq(actions/room_registry.ts says what it promises).actions/room_actions.ts
The room verbs over RoomRegistry (actions/room_registry.ts): join, leave, send, state, watch, and unwatch, as actions a consumer mounts on a WebSocket endpoint — the TS twin of the Rust spine's
fuz_actions::room.create_room_actions returns the handlers over the specs of actions/room_action_specs.ts. Each is WebSocket-only — mount them on a
ws_endpointsentry, never on an RPC endpoint (a room belongs to a socket; the Rust spine answers themmethod_not_foundover HTTP, and a handler reached without a connection answers the same) — actor-required, and without side effects: the registry is memory, not the database, so no transaction opens for a relayed message. The registry does the work and the fan-out; this module parses, bounds, authorizes, and limits.Seats are keyed by connection and actor: under the dispatcher's
actingselector, a leave, send, or state set acts on the acting actor's own seat, never another actor's on the same socket.The consumer's seams
- RoomAuthorize decides each join and watch:
{allow: false}answersroom_not_found, the same as a room that doesn't exist, so a caller learns nothing of rooms it can't enter; `{allow: true, scope, max_members}carries theRoomScope` the seat or watch is admitted under, for eviction, and an optional member cap below the registry's. It gets the caller's ids and the database, not the request's role grants: authority is read through the database inside the reserve window (RoomAuthorize's doc). - Eviction is the consumer calling
RoomRegistry.evictafter its own authority change commits — from the handler's emit_after_commit — never before. - Rate limits.
room_joinandroom_watchcarry the per-account class (rate_limit: 'account', charged by the dispatcher): each runs the consumer's database authorizer, and one account may hold many sockets. RoomRateLimiter is per connection, outside the account budget: it bounds the count of joins, sends, and state sets, and the bytes of payloads and states as each frame carries them (JSON-escaped, json_escaped_len), because every room-wide byte lands in each member's outbound queue (DEFAULT_WS_OUTBOUND_QUEUE_BYTES) and a member reading slower than its room sends is closed for the overflow. A join stays on it too, since its state and the seats it moves fan out to every member; a watch fans out nothing, so it costs only its account charge. join_extra, a hook whose value the join answers asextra(nullwithout one) — for what a consumer mints per seat.
A join, step by step
The dispatcher's account charge and input parse; refuse a state over the registry's bound; charge the connection's limiter;
reserve_seat(the join is now reachable by evictions); the authorizer; then the request's own signal — a clientcancelof the join, or its socket closing, answersrequest_cancelled— andadmit_seat. A join whose socket closes mid-authorizer keeps running here, unlike the Rust one, whose request future is dropped; its admit refuses (connection_closed, answeredrequest_cancelled), so it seats nothing either way. A watch runs the same steps through the watch halves, without the connection's limiter.- RoomAuthorize decides each join and watch:
actions/room_client.svelte.ts
The frontend side of rooms: RoomClient keeps, for each room a page joins or watches, a reactive RoomState — its members and their state, the caller's own seat — over the WS-only
room_*verbs and theroom_*notifications the server pushes (actions/room_action_specs.ts).Desired state, converged one request at a time
RoomState.join,leave,watch,unwatch, andset_staterecord what the page wants; one runner per room then sends whatever requests close the gap, one at a time. The server dispatches a socket's requests concurrently, so a leave sent right after a join could otherwise reach the registry first (and refuse the join as superseded), and two state sets could land out of order. A burst of calls converges: join, leave, join while the first join is in flight sends that one join, whose seat stands; a leave while seated is sent before the next join. While the socket is down nothing is sent and the wants wait for it.RoomState.sendis the exception: it goes out at once, since a caller that cares about the order of its sends (the WebRTC mesh, rtc/rtc_mesh.svelte.ts) serializes them itself.Every verb runs untracked, so a page may call
joinorwatchfrom an$effect(withleaveorunwatchin its teardown) without the effect depending on the room state the verb reads and writes.Listeners are isolated: one that throws is logged and the others still hear the event, and the join, replay, or teardown that called it carries on.
seqEvery member event carries its room's
seq, and a join or watch answers the room as of aseq. Events can arrive before that answer, so while a room's first answer is outstanding they are buffered; the answer's members are applied, then the buffer replays, dropping every event at or below the answer'sseq. Once a room is live, an event at or below the last appliedseqis dropped, so a connection that both watches a room and sits in it, which the server tells each event once, applies it once. A later answer whoseseqis behind the live stream is not applied over it. A message (which reaches only a seat) that arrives on a live watch while the join is in flight is held, and delivered once the seat is taken.Seats lost, and reconnects
room_seat_lostends a seat the server took:moved(a newer join of the same actor took over,moved_tonaming its room),evicted, orroom_closed. None is rejoined. A socket that closes loses every seat and watch with it, and the client tells them apart: a seat lost to the disconnect is rejoined on the next connection, naming the seat it held (rejoin_of), and a refusal asroom_seat_moved— the actor took a seat elsewhere meanwhile — ends it as moved, so two tabs never trade a seat back and forth. A rejoin refusedrate_limitedis retried after the refusal'sretry_after, still naming the seat, up to ROOM_REJOIN_RATE_LIMITED_RETRIES_MAX times. Watches are taken again.The client learns of a new connection through
RoomRpc.connection, an identity that changes each time the socket opens. The client follows it on its own: its constructor makes an$effect.rootwhose effect reads it and callssync_connection, so a close and a reopen are seen even when they land in one batch, anddisposeends it. On the server the compiler makes$effect.roota no-op, and nothing follows;sync_connectionstays public for that case and for tests, and runs on its own before each request and notification.const rooms = new RoomClient(create_room_rpc(socket));Notifications reach the client through
receive, from the RPC client'slookup_action_handlerfor the'receive'phase (with room_notification_action_specs among the RPC client's specs):lookup_action_handler: (method, phase) => phase === 'receive' && is_room_notification_method(method) ? (event) => rooms.receive(method, event.data.input) : undefineddisposeleaves every seat and drops every watch, for a clean teardown.actions/room_registry.ts
Rooms over the WebSocket connection registry: members seated in a room by key, relayed messages, per-member state, and occupancy watches. The TS twin of the Rust spine's
fuz_realtime::RoomRegistry.A room is a key (RoomId) the consumer chooses — e.g. a voice room keyed by a space id — holding seats and watches. A seat is one actor's membership on one connection, with a random MemberId that clients address each other by (a connection id never reaches the wire) and a small client-encoded state string. Seats are keyed by connection and actor: a connection whose requests act as different actors of one account (the dispatcher's
actingselector) holds a seat per actor, and a leave, send, or state set touches only the acting actor's own seat; an event skips the seat that caused it, not its connection. A watch sees the members without joining; it is one per connection and room, whichever actor last asked for it. The registry relays opaque payloads between members and knows nothing of what they carry. Rooms live in memory and die with the process: a restart drops every room and clients rejoin.The verbs over it — the specs, the authorizer hook, the per-connection limiter — are actions/room_action_specs.ts and actions/room_actions.ts; this module holds the state and the fan-out.
One step, one order
The Rust registry holds rooms, seats, watches, joins in flight, and the per-connection and per-actor indexes under one lock, since exclusivity and eviction span rooms. Here every method runs to completion without an
await, so JavaScript's single thread gives the same guarantee: no check is ever separated from the mutation it guards. Every notification is queued inside that step throughConnectionRegistry.send_to, which never waits, so each room's events carry aseqthat orders them: one counter per room, bumped by every event in the room. A room with no seats and no watches is deleted; a new one starts itsseqagain at zero.seqorders a room's events, and lets a client drop the events at or below the snapshot a join or watch answered; it is not contiguous per client (an addressed message bumps it, and only the addressee sees that one), and it restarts when a room is deleted and created again. Event order across rooms is unspecified; within a room it is theseq.Nothing here waits: a recipient that cannot take a frame is closed for the overflow (WS_CLOSE_OUTBOUND_OVERFLOW) by the connection registry, and its seats are then released like any other disconnect.
Two-phase join
A join is
reserve_seat, the consumer's authorizer, thenadmit_seat. The reserve puts the join in flight before the authorizer reads anything, refused when the socket has already closed, and returns a PendingSeat;admit_seatalways consumes it, and a caller that never reaches the admit callswithdraw(in afinally— the Rust guard's drop). While in flight the join is reachable: an eviction that names its actor or room refuses it, one that names a scope marks it, so the admit refuses when the verdict's scope is that one, and the connection's ownleaveof the room refuses it as superseded. That closes the race of an eviction against an authorizer: a consumer evicts after its write commits, and its authorizer reads under READ COMMITTED, so the eviction either precedes the reserve — then its commit precedes the authorizer's read, which denies — or follows it and reaches the join in flight.The argument holds only for authority the authorizer reads inside that window, after the reserve, from the database. Anything loaded before the reserve — the request's own role grants, which the dispatcher reads before the handler runs — may predate an eviction that also precedes the reserve and so found nothing in flight to reach: the stale read would admit an evicted actor. The authorizer hook (RoomAuthorize) therefore gets the caller's ids and the database, never the request's grants. Watches run the same two phases (
reserve_watch,admit_watch).Unlike the Rust join, whose request future is dropped when its socket closes, a TS join keeps running after the close: the admit refuses it, since the close marks every join in flight on the connection and the admit reads the socket's signal.
The admit seats the member unless it was refused meanwhile, its socket closed, or the room is full. A refused join displaces nothing.
Exclusivity and the rejoin guard
With
exclusivean actor holds one seat across the registry: the newest admitted join wins (two sockets racing settle by which admits last, not which sent first), and the seat it displaces hearsroom_seat_lostwith reasonmovedandmoved_to, the new seat's room. Either way a connection holds one seat per room for each actor; joining again as that actor moves its old seat the same way.A seat whose socket died never hears that it moved. Its client, on reconnecting, rejoins naming the seat it held (
rejoin_of), and must not take back the seat its actor holds now. So an exclusive registry keeps a short per-actor tombstone of seats that ended without a leave: each seat moved away, and each released by its disconnect, which counts as moved once the actor is seated again by any other join. A rejoin naming a moved seat is refused (seat_moved) instead of seated; one naming a seat released by its disconnect and not moved since is seated, as is any other. Tombstones last ROOM_REJOIN_TOMBSTONE_TTL_MS, at most ROOM_REJOIN_TOMBSTONES_PER_ACTOR per actor; past either bound a rejoin is seated like a fresh join.Disconnect
The first seat or watch a connection reserves adds one listener to the connection's socket signal (
ConnectionRegistry.socket_signal— the signal every close path aborts), and the connection keeps it for its life, however many joins and leaves it makes. When the signal aborts, the registry releases every seat (room_member_leftwith reasondisconnected), watch, and join in flight the connection holds — on the next microtask, as the Rust waiter runs as its own task, so a close made inside a fan-out (an overflow) never re-enters the registry mid-step.Eviction
evictis the consumer's call when its own authority changes, made after the change commits: by actor, by actor within a scope, by room, or by scope (RoomEvictTarget), covering seats, watches, and joins in flight alike, so an evicted actor keeps neither a seat nor a watch. Its socket still hears the room while another actor of the same account is seated there or holds the watch, on that actor's own authority.Bounds
Seats are bounded by the rooms' cap (and by one per actor when exclusive), watches per connection, joins in flight by the connection's in-flight request cap, listeners at one per connection, and tombstones as above.
actions/rpc_client.ts
Typed RPC client — creates a Proxy-based API from action specs.
Two tiers of usage:
- Tier 1 (simple, for tx): transport send/receive, Result return. No
environment. - Tier 2 (full, for zzz): ActionEvent lifecycle with
environment.
Pass the consumer's generated
ActionsApiinterface as<TApi>to flow full type safety through without an explicit cast at the call site.- Tier 1 (simple, for tx): transport send/receive, Result return. No
actions/socket.svelte.ts
Frontend WebSocket client — portable, Svelte-reactive, implements WebsocketConnection.
Plain class with
$staterunes (no Cell inheritance, no app coupling). Drop into any SvelteKit frontend as the underlying connection for FrontendWebsocketTransport. Handles auto-reconnect with exponential backoff, respects WS_CLOSE_SESSION_REVOKED (no reconnect loop after the server revokes auth), WS_CLOSE_CONNECTION_LIMIT (no reconnect after the server closes this socket to admit a newer one — closed until the user acts), and WS_CLOSE_PERMISSION_REVOKED (no reconnect after the account lost the role the endpoint requires — closed until the user acts), exposes reactive status for UI indicators, and ships three correctness primitives default-on:FrontendWebsocketClient.request— promise-based JSON-RPC with auto-assigned ids and a pending-id map. Intercepts responses on the message path so request/response correlation is transport-level rather than re-invented per consumer.- Durable queue —
request()calls made while disconnected buffer up to DEFAULT_QUEUE_MAX_SIZE requests and flush on reopen. Overflow rejects withqueue_overflow. RawFrontendWebsocketClient.sendis drop-on-disconnect (fire-and-forget notifications want that). - Activity-aware heartbeat — a shared
heartbeatrequest fires when either direction has been idle for the interval; receive-silence past the receive timeout (DEFAULT_HEARTBEAT_RECEIVE_TIMEOUT, never less than HEARTBEAT_RECEIVE_TIMEOUT_MIN_FACTOR × the interval) closes with WS_CLOSE_CLIENT_HEARTBEAT_TIMEOUT and lets auto-reconnect pick back up.
actions/transports_http.ts
HTTP transport — sends JSON-RPC messages via HTTP POST, or GET for a read whose params can ride the URL.
actions/transports_ws.ts
Frontend WebSocket transport — thin adapter over WebsocketRpcConnection.
Delegates request/response correlation, the durable queue, the heartbeat, and
AbortSignal-driven cancel to the underlying connection (the canonical implementation is FrontendWebsocketClient). The transport's own job is the Transport contract: route inbound server-pushed messages intopeer.receive, send the resulting response back over the socket (the server→client ActionPeer receive loop), and translate the connection'sPromise<R>/ThrownJsonrpcError shape into JsonrpcResponseOrError envelopes. No parallel pending-request map.Inbound
peer/pingrequests are answered directly via the built-in peer_ping_responder — a protocol-liveness concern that works with zero consumer wiring, the same way the server runs theheartbeatecho.actions/transports.ts
Transport abstraction for action communication.
Provides the Transport interface and Transports registry for managing multiple transports with fallback behavior.
actions/ws_endpoint_spec.ts
WsEndpointSpec — the canonical WebSocket endpoint declaration consumed by create_app_server's
ws_endpointsoption (mirror of RpcEndpointSpec for HTTP RPC).Also resolve_ws_endpoints, which fills in the server's
allowed_originsand, for a spec that omits them, the actions of the sole RPC endpoint.Lives in its own module so both server/app_server.ts (which mounts endpoints from these specs) and http/surface.ts (which threads the resolved spec list into surface generation) can import it without a cycle between the two.
actions/ws_outbound_writer.ts
The outbound side of one server WebSocket connection — a byte-budgeted queue of frames, the pump that hands them to the socket, and the deadlines on what the socket has not yet written.
Every frame the server sends a connection goes through
WsOutboundWriter.push: a response, an error frame, a notification, a broadcast, a server-initiated request. ConnectionRegistry owns one writer per connection and is its only caller.What waits
A frame pushed at an idle connection — nothing waiting, nothing unwritten in the runtime's socket buffer, and no other frame pushed in the same synchronous run — goes straight to the socket. Every other frame waits in the writer's queue: the rest of a burst pushed in one synchronous run (a loop with no
awaitin it gives the pump no turn), and anything pushed while the socket's buffer is at or over WS_WRITE_HIGH_WATER_BYTES. The pump hands waiting frames over in order — on the microtask after a push, and whenever the buffer has drained below the high-water mark.What waits is held to the connection's budget (OutboundBudget): each waiting frame is charged its UTF-8 length plus OUTBOUND_FRAME_OVERHEAD_BYTES, and a frame is always admitted when nothing is waiting. A frame handed to the socket is no longer charged — the budget bounds what waits, and the write deadline bounds what is in flight.
A frame that does not fit is reported as an overflow and not queued; the owner closes the connection for it (WS_CLOSE_OUTBOUND_OVERFLOW).
The queue is a linked list: a frame handed to the socket is unlinked, so the writer holds the frames that wait and no others, however long the queue goes without emptying.
Closing
closesends the close frame and takes nothing more. With'flush'it first runs the pump's rule once: waiting frames are handed to the socket while its buffer is below WS_WRITE_HIGH_WATER_BYTES. Whatever still waits is discarded, with either backlog choice. So a frame sent to an otherwise idle connection just before a close reaches the client ahead of the close frame, and a frame queued behind a backed-up socket does not. After a close a socket whose buffer the writer can read ("Runtimes") holds less than the high-water mark plus one frame, and the close frame.Deadlines
- A frame: bytes the socket's buffer still holds WS_WRITE_STALL_TIMEOUT after they were handed to it mean the client is not reading. The writer discards what waits, reports the stall, and cuts the socket with no close frame (the client sees an abnormal close, 1006).
- A close frame: a close still unwritten WS_CLOSE_WRITE_TIMEOUT after
closecuts the socket the same way, so a closed connection whose client stopped reading does not hold its buffered frames for the runtime's own close timeout — where the runtime can cut a socket ("Runtimes").
Runtimes
The buffer is read through the socket Hono's
WSContextwraps (raw):bufferedAmounton Node'sws(and on a web-standardWebSocket),getBufferedAmount()on Bun'sServerWebSocket. A socket that exposes neither reads as never backed up: its frames are still budgeted while they wait for the pump, but nothing detects a stall. The cut isterminate(), which Node'swsand Bun'sServerWebSockethave. A socket with noterminate(a web-standardWebSockethas no way to drop a socket without the closing handshake) is closed at a stall with WS_CLOSE_OUTBOUND_OVERFLOW instead — a frame the client reads only if it starts reading again — and the close deadline cuts nothing: a closed socket whose client is not reading stays in the runtime, holding what its buffer held at the close ("Closing"), until the runtime or the client ends it.actions/ws_socket_session.ts
The per-socket half of the WebSocket endpoint — one upgraded socket, from admission to close.
register_action_ws (actions/register_action_ws.ts) mounts the upgrade route; per upgrade it reads the credential off the Hono context into a WsSocketUpgrade and hands that, with the endpoint-level WsSocketEndpoint, to create_ws_socket_events, whose
WSEventsthe runtime adapter drives. Nothing here reads the Hono context or imports the mount, so a socket is reachable with a fakeWSContextand no app.The WS-specific concerns — connection lifecycle, heartbeat, cancel-notification interception, socket-scoped notify — live here; the relation to create_rpc_endpoint and the shared perform_action core is in the register_action_ws module doc.
Admission: the revocation race
The auth middleware resolves the credential before the handshake, and the socket exists only once
onOpenfires. Every revocation (session revoke, logout, password change, token revoke, account delete) closes the sockets *registered* under what it revoked, so one landing in that gap would close nothing, and the socket would then be admitted on the dead credential and keep it: per-message dispatch re-authorizes the *actor*, never the session or token — and its admission could evict a live socket of the same account past the cap.onOpencloses the gap in three steps: register the connection pending (ConnectionRegistry.register_pending— closeable by every revocation, inert otherwise), re-read the credential, the acting actor, and the role (recheck_admission, which the audit stream shares), thenConnectionRegistry.admit. A revocation whose close ran after the registration found the pending entry, soadmitrefuses; one that committed before the re-read is seen by it. The cap is enforced only byadmit, so a refused upgrade evicts nothing, and pending registrations never count toward it.That argument needs every revocation to close only after its commit — otherwise a close could miss the registration while the re-read still sees the credential alive. Every one does: the revocation handlers queue their close behind the commit (queue_connection_close), and the audit emitter announces a success row to the listeners behind it too. So no interleaving admits a revoked credential;
docs/security.md§Connection Admission says what that rests on.The acting actor the upgrade resolved is re-read beside the credential on every endpoint, gated or not: an actor soft-deleted under its live account keeps the account's sessions and tokens and its own grant rows, so neither the credential nor the role re-read would refuse it. A tombstoned acting actor is refused like a dead credential.
An endpoint gated on
required_rolesre-reads them beside the credential: its upgrade passed the role gate before the socket registered, so a role revocation landing in between would close nothing (aroleclose target matches registrations), and the socket would be admitted without the role for its lifetime. The re-read reads the acting actor's grants afresh and admits on a global grant of any listed role, as the gate did.A refused upgrade is closed with WS_CLOSE_SESSION_REVOKED (4001, the reason a revoked socket gets) for a dead credential or a deleted acting actor, WS_CLOSE_PERMISSION_REVOKED (4006) for a lost role, or WS_CLOSE_INTERNAL_ERROR (1011) when a re-read itself failed — fail closed, never admitted unchecked. The handshake has already answered
101, so a refusal can only be a close frame.Once the server is shutting down (
AppServer.closeran the registry'sclose_all_connections) a refusal is WS_CLOSE_GOING_AWAY instead, so the client reconnects rather than treating its credential as revoked: an upgrade pending at the close-all is closed by it — and its abort makes the refusal that follows the re-read send nothing more, even when the database closed under that re-read — and one that registers after it is born closed and skips the re-read (ConnectionRegistry module doc, "Shutdown").Frames that arrive before admission are queued, not dispatched: nothing runs on a credential that has not been re-read. They dispatch in arrival order once the socket is admitted and
on_socket_openhas completed, and are dropped unread on a refusal. The queue holds at most MAX_PRE_ADMISSION_FRAMES frames and PRE_ADMISSION_QUEUE_BYTES_FACTOR ×max_message_bytesbytes; past either the socket is closed.Credential deadline
Expiry writes nothing a revocation listener could hear, so the socket watches its own credential's expiry (
ResolvedAuth.credential_deadline, the earlier of a session's cookie and row, an API token's row, none for a daemon token or an eternal token). From admission, a timer closes it at the deadline with WS_CLOSE_SESSION_REVOKED (4001) and WS_CLOSE_CREDENTIAL_EXPIRED_REASON. The wait is a chain of timers of at most an hour (schedule_credential_deadline), so a session's 30 days — pastsetTimeout's ceiling — does not fire at once, and each wake-up checks the wall clock too, so a host suspend does not extend the deadline.A server-closed socket dispatches nothing
A runtime adapter can keep delivering inbound frames after the server calls
ws.close(…), until the close handshake completes (@hono/node-serverdoes — up to thewsclose timeout when the client withholds its close frame). So every server-side close — revocation, cap eviction, heartbeat timeout, an oversized message, a refused admission — removes the connection from the registry and aborts the socket's signal *at close time*, andonMessagedrops any frame on a socket that has ended. A connection the registry no longer holds though nothing closed its socket (a bareremove_connection) is ended on its next frame (ConnectionRegistry.is_registered), with WS_CLOSE_INTERNAL_ERROR — it must not linger as a socket that reads everything and answers nothing.