@sewdn/workflow-server
v0.1.1
Published
The workflow runtime behind HTTP: a fetch-style handler serving the client's RPC group, with authentication as a port and every read through the viewer's gate.
Readme
@sewdn/workflow-server
The workflow runtime behind HTTP. It serves the client's RPC group (WorkflowRpcs of @sewdn/workflow-client) from
a WorkflowRuntime, as a fetch-style handler (Request) => Promise<Response> that any server speaking web Request
and Response can mount (Bun, Deno, a framework's route, Node through an adapter), or as an HTTP effect for an
Effect host. Authentication is a port: the application says who the actor is. Built on effect 4.1.4
(effect/rpc, effect/http).
import { layer as runtimeLayer } from "@sewdn/workflow-runtime";
import { layerFromConfig } from "@sewdn/workflow-store-postgres";
import { toWebHandler } from "@sewdn/workflow-server";
const server = toWebHandler({
runtime: runtimeLayer({ workspaceId, genesis, queryGates }).pipe(
Layer.provide(Layer.merge(layerFromConfig(connection, { schema: "workflow" }), directory)),
),
// the actor with the roles the application vouches for, or undefined: 401
authenticate: async ({ headers, cookies }) => sessionActor(cookies.session),
});
Bun.serve({ port: 8080, fetch: server.handler }); // or route "/workflow" of the application's own server
// at shutdown: await server.dispose() (closes the pool and the runtime)On the page:
import { createWorkflowClient, layerHttp } from "@sewdn/workflow-client";
const client = createWorkflowClient({
client: layerHttp({
url: "/workflow",
fetch: (input, init) => fetch(input, { ...init, credentials: "include" }),
}),
});The wire
Every call is a POST to the handler's URL with newline-delimited JSON (RpcSerialization.ndjson); the response is a
stream of lines. A streaming call, changes, keeps its response open and sends one line per commit, so no WebSocket
is needed and the handler works wherever a streamed response does. Any other method is answered 405. A browser keeps
one HTTP/1.1 connection busy per open changes; behind HTTP/2 that costs nothing.
Trust
| What | On the server |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Who acts | Authentication.authenticate(request), once per request, before any call runs; a refusal is 401 with { "code": "unauthenticated" } and runs nothing |
| A command's options.actor | replaced by the authenticated actor (the client still sends one; it is ignored) |
| query's viewer | replaced by the authenticated actor |
| workflow.draft, workflow.draft-history | through query (the facade's draft, draftHistory) as the authenticated actor: that person's own undo and redo tops; the runtime refuses a viewer without the workflow.author right (external people under the stock rule) with query.not-found |
| The typed reads (world, runs, run, …) | each is the runtime's query by reference (workflow.world, …) with the actor as viewer, so the gate table (queryGates) applies; a closed run reads as none, a closed list as query.not-found |
| changes | refused to an external actor (actor.external): commits carry every event of the workspace; streamed to everyone else |
| seed, rebuild | not served (a defect, NotServed; the facade's client.defect): a host runs them on its runtime, in process |
| catchUp | served: it only brings this process's projections up to the stream |
The engine refuses every command of an external actor (actor.external), rollBack included. A server that shows
anything to people outside the organisation must give the runtime a gate table: without one, every read is open to
every authenticated actor.
How the actor reaches the handlers: the HTTP layer gives each authenticated request a random session key in the
header x-workflow-session (replacing any the client sent) and removes it when the response ends; the RPC handlers
look the actor up by that key. A key the client makes up names no session (the call dies with NoSession).
Exports
| Export | What |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| toWebHandler({ runtime, authenticate }) | { handler, dispose }: the server as (Request) => Promise<Response>; authenticate a function or a layer |
| Authentication | the port: authenticate(request: RequestInfo) => Effect<Actor, Unauthenticated> |
| layerAuthentication(f) | the port from an Effect function |
| authenticationFromPromise(f) | the port from (request) => Actor \| undefined (or a promise of it); a throw is a defect (500) |
| RequestInfo | { method, url, headers, cookies } (header names in lower case); the body is never shown |
| makeHttpApp | an Effect host's HTTP effect (needs Scope, WorkflowRuntime, Authentication) |
| layerHttpApp | the same as a WorkflowHttpApp service |
| layerRoute(path) | registers it as the POST route path of the HttpRouter in context |
| layerServerHandlers | the RPC handlers behind the trust boundary (needs WorkflowRuntime, Sessions), for a custom protocol |
Deployment shape
Nothing is deployed from this repository. The intended shape:
- Several processes can serve one workspace on the same PostgreSQL schema. Writers append with the expected
sequence and decide again on conflict. PostgreSQL wakes the event feed through LISTEN/NOTIFY, with polling as
a fallback. A client can resume against any process by passing its last received sequence to
changes(after). - Storage:
@sewdn/workflow-store-postgres, one PostgreSQL schema per store. Runmigrateat deploy time, or providelayerMigrateunder the ports (an advisory lock makes concurrent starts migrate once). - Reactions (triggers, notifications, timers) are not started by the server: compose an orchestrator
(
WorkflowOrchestratorof@sewdn/workflow-runtime, e.g.layerOutboxOrchestratoron the PostgreSQL outbox and timers) beside the runtime in the same process, with the application'sNotifierand handlers, and fork itsrun. - People: the
Directoryport is the application's (who exists, their roles); the actor comes from the application's session, with the roles it vouches for. - In front: TLS, CORS, request size limits and rate limits belong to the reverse proxy or the application's server; the handler sets no CORS headers. Mount it on a path of the application's own origin to avoid CORS.
Tests
bun run typecheck
bun run test # bun test srcsrc/http.test.ts: the client's suite (clientSuiteof@sewdn/workflow-client/testing) over HTTP, the server on the memory adapter, behindBun.serveon a free port.src/postgres.test.ts: the same suite with the server on the PostgreSQL adapter: PGlite in process, or a real server whenWORKFLOW_TEST_POSTGRES_URLnames one (postgres://user:[email protected]:5432/postgres).src/server.test.ts: the trust boundary (the payload's actor and viewer ignored, gates on every read,changesclosed to external viewers, host operations not served, 401 and 405), through the publictoWebHandler.
Over HTTP the suite leaves out seed and rebuild, which the server does not serve.
