@sewdn/workflow-client
v0.1.1
Published
The workflow client: every operation of the runtime as one RPC group, in-process, web worker and HTTP transports, and a promise facade for hosts that do not write Effect.
Readme
@sewdn/workflow-client
The workflow client: every operation of the runtime (WorkflowRuntimeService of @sewdn/workflow-runtime) as
one RPC group, a transport that serves it in the same process, and a promise facade for hosts that do not write
Effect. Built on effect 4.1.4 (effect/rpc). Runs in browsers, Node and Bun.
The RPC group (src/rpcs.ts)
WorkflowRpcs holds one RPC per operation:
| RPC | Payload | Success | Error |
| -------------------------------------- | ----------------------------- | ------------------------------- | ------------------ |
| one per engine command (startRun, …) | { input, options } | Executed of the command value | ExecuteError |
| pluginCommand | { command, input, options } | Executed of JSON | ExecuteError |
| query | { query, params, viewer? } | JSON | QueryError |
| rollBack | { toSequence, options } | Executed<void> | ExecuteError |
| seed | { commits } | number | SeedError |
| world, sequence | none | World, number | QueryError |
| runs | { query? } | RunSummary[] | QueryError |
| run | { runId } | Option of the row | StoreUnavailable |
| overview, phases | { runId } | Option, at the clock's now | WriteError |
| history | { runId } | LogLine[] | StoreUnavailable |
| taskList | { personId } | TaskList, at the clock's now | QueryError |
| commits | { query? } ({ after? }) | CommitSummary[] (live ones) | QueryError |
| catchUp, rebuild | none | number, void | WriteError |
| changes (stream) | { after? } | Change | QueryError |
A command RPC is named as the engine command (ENGINE_COMMANDS); its input is that command's input and
options the runtime's ExecuteOptions. One RPC per command gives each command its own payload and value type on
the client. src/schemas.test.ts checks, at compile time, that every command's input and value schema has the
engine's type (both ways, and the same key paths).
The errors are the runtime's own schema errors: CommandRefused { refusal } (the engine's { ok, code, params }),
CommandIdReused, SequenceConflict, StoreUnavailable, StorageFull.
In one process the reads that answer no Option never fail with CommandRefused; a server
(@sewdn/workflow-server) answers each read through the authenticated viewer's gate, and refuses a closed one with
query.not-found (a closed run is none, as one that does not exist), and changes to an external viewer with
actor.external.
changes gives { _tag: "Subscribed", sequence } with the starting sequence, then one
{ _tag: "Committed", stream, sequence, commandId, events } per later commit in sequence order.
The facade's client.changes() starts at the current sequence. Pass the last sequence you processed to
client.changes(after) to replay the missed commits before returning to live delivery.
Schemas: small shapes are written out. Shapes the engine owns and has no schema for yet (a definition's content, a
task template, a migration plan, the run views, the world) are JSON under the engine's type; the engine checks a
command's input and refuses a bad one with an input.* code.
Plugin commands and queries (src/plugin-client.ts)
A plugin's commands and queries cross two generic RPCs, so the group stays one static definition and no transport depends on the application's plugin list:
pluginCommand { command: "<plugin>.<name>", input: Json, options }: the server decodes the input with the command's schema (plugin.invalid-input { command, path }when it does not fit), decides it with its chained engine commands in one append, and answers the value as JSON encoded by the value schema.query { query, params: Json, viewer? }: any query of the runtime by reference, an engine query (workflow.world,workflow.runs,workflow.run, …ENGINE_QUERY_PARAMS) or a plugin's (<plugin>.<name>). With a gate table (WorkflowRuntimeConfig.queryGates) the runtime needs the viewer and answers what the viewer's gate lets through; a closed query, a missing gate and a missing viewer all answerquery.not-found. In one process (and in a worker) the viewer travels in the payload; a server transport takes it from the session, never from the client. The typed reads (world,runs, …) are the host's own and never gated: what an external viewer sees goes throughquery.changesis not gated either.
The types come from the plugin's definition, the same object the runtime and the React provider are given:
// Effect
const docket = pluginClient(yield * WorkflowRpcClient, docketPlugin);
const { value } = yield * docket.execute("create-series", { label }, options); // value: { seriesId: string }
const meetings = yield * docket.query("meetings", { seriesId }, { viewer }); // QueryResult<typeof docketPlugin, "meetings">
// the facade
const docket = client.plugin(docketPlugin);
const { value } = await docket.execute("create-series", { label }, { actor, commandId });
const meetings = await docket.query("meetings", { seriesId }, { viewer });execute checks the input with the command's schema before sending (InvalidRequest; the facade's
client.invalid-request) and decodes the value with the value schema; query does the same with the params and
the result schemas. An answer that does not fit its schema is a defect (a client and a server on different versions
of the plugin), so a gate that answers a part of a result answers it in the result's shape. A command name or a query
name the plugin does not have is a compile error (CommandName<P>, QueryName<P>); the server refuses one that
arrives anyway (plugin.unknown-command, plugin.unknown-query). A plugin's own refusal is plugin.refused
{ command, ref, params }, and a plugin's command check refuses any command with command.vetoed { command, ref,
params }; withPluginCopy of @sewdn/workflow-engine words both through the plugin's copy, selected by ref.
Transports
layerHandlers: the server side of the group over theWorkflowRuntimein context.layerInProcess: Layer<WorkflowRpcClient, never, WorkflowRuntime>: the client and the server joined in memory. Every message is serialised and parsed again with the JSON serialization, as a wire would.layerWorker({ spawn }): Layer<WorkflowRpcClient, WorkerError>: the page side of the web worker transport (below).layerHttp({ url, fetch? }): Layer<WorkflowRpcClient>: the client over a@sewdn/workflow-serverhandler (below).@sewdn/workflow-client/worker:serveWorkflowWorker(from)andlayerWorkerServer(from), the worker side.
WorkflowRpcClient is the Effect client (RpcClient of the group): client.startRun({ input, options }),
client.run({ runId }), client.changes({}).
The web worker transport (src/worker-client.ts, src/worker.ts)
The runtime and its ports run in a dedicated worker; the page talks to it through Effect's worker RPC protocol
(RpcClient.layerProtocolWorker, RpcServer.layerProtocolWorkerRunner, the browser worker platform of
@effect/platform-browser). Messages are structured clones of the group's JSON encoding.
// workflow.worker.ts: the entry the application bundles as its worker
import { serveWorkflowWorker } from "@sewdn/workflow-client/worker";
serveWorkflowWorker({ ports: myWorkerSafePorts, config: { workspaceId, genesis } }); // or { runtime }
// the page
import { createWorkflowClient, layerWorker } from "@sewdn/workflow-client";
const client = createWorkflowClient({
client: layerWorker({
spawn: () => new Worker(new URL("./workflow.worker.ts", import.meta.url), { type: "module" }),
}),
});- Create the
Workerinsidespawn, not before: the layer calls it once it listens, and the worker's ready message sent earlier can be lost (Bun does not queue it). - One worker holds the runtime and its state: the pool has one member, which takes any number of requests at once
(the open
changesstream is a request). Two clients on two workers do not share a world. - The actor travels in the payload, as in process; a worker is not a trust boundary.
Use @sewdn/workflow-runtime/memory for an ephemeral worker. For browser persistence, the
@sewdn/workflow-store-localstorage package exports layerIndexedDb({ namespace }) for environments
with IndexedDB, Web Locks and BroadcastChannel. The stock demo uses it on the page. The package's
layer adapter needs access to the page's synchronous Storage API. A server can use PostgreSQL.
The HTTP transport (src/http-client.ts)
layerHttp({ url, fetch? }) sends every call as a POST to url with newline-delimited JSON
(RpcClient.layerProtocolHttp, RpcSerialization.ndjson); changes keeps its response open and reads one line per
commit. fetch defaults to the global one; pass a wrapper to add an Authorization header or
credentials: "include". The facade reports HTTP 401 as client.unauthenticated and other non-2xx responses as client.transport.
The server takes the actor and the viewer from its own authentication: the actor of a command's options and the
viewer of a query are still sent (the schemas require them) and ignored. seed and rebuild are not served over
HTTP (client.defect): a host runs them on its runtime.
The client's suite (@sewdn/workflow-client/testing)
clientSuite(name, transport) registers the facade's and the Effect client's cases (bun test) for any transport:
transport.layer({ config, clock, session }) builds the Effect client over a runtime of config on fresh storage,
the runtime on clock; session.actor is who the transport authenticates (the suite sets it to the actor each
command is given as; a transport without a trust boundary ignores it). hostOperations: false leaves out seed and
rebuild. src/client.test.ts runs it in process on the memory and localStorage adapters; @sewdn/workflow-server
runs it over HTTP. settableClock() is the clock the suite sets.
The facade (src/facade.ts)
import { createWorkflowClient, isWorkflowClientError } from "@sewdn/workflow-client";
const client = createWorkflowClient({ ports: myPortsLayer, config: { workspaceId, genesis } });
// or { runtime: myRuntimeLayer }, or { client: myWorkflowRpcClientLayer } for another transport
// config.now: () => number is the runtime's clock, for a host that does not provide Effect's Clock
try {
// an engine command, or a plugin's `{ name: "<plugin>.<name>", input }` (its value JSON; `client.plugin(p)` types it)
const { value: runId } = await client.execute(
{ name: "startRun", input: { definitionId, subject: { title } } },
{ actor, commandId },
);
} catch (error) {
if (isWorkflowClientError(error) && error.code === "run.not-found") error.params.runId;
}
// any query by reference, as a viewer: what an external person may see goes through here
const runs = await client.query("workflow.runs", { status: "running" }, { viewer });
// what a rollback would undo: the live commits recorded after an instant (the seed and undone commits left out)
const since = await client.commits({ after: "2031-02-03T00:00:00.000Z" });
// a draft as an editor reads it (the viewer's undo and redo tops), and its history, which stays after the publish;
// both go through the gated `query` (`workflow.draft`, `workflow.draft-history`) and refuse non-authors
const draft = await client.draft(versionId, { viewer }); // { version, revision, undo?, redo? }
const lines = await client.draftHistory({ versionId, after: 10, limit: 50 }, { viewer });
// an empty stream seeded with commits decided elsewhere (ids as strings, events as { type, version, payload })
await client.seed([{ commandId: "import-1", actor, events }]);
for await (const change of client.changes()) {
/* first Subscribed, then Committed per commit; break to unsubscribe */
}
await client.dispose();Reactions
On ports and a configuration, the facade can run the reactions in this process too, through the runtime's
WorkflowOrchestrator port on its outbox adapter (layerOutboxOrchestrator): triggers to
their handlers, notifications to a notifier, timers at the runtime's clock (config.now). The ports must also provide
the Outbox and the Scheduler (the memory and localStorage adapters do), and a Notifier unless one is given here.
const client = createWorkflowClient({
ports: memoryLayer({ directory }),
config: { workspaceId, genesis, now: () => clock.now() },
reactions: {
// resolve: delivered; reject with NotificationRejected: final; any other rejection: retried by the policy
notifier: async (notification) => inbox.push(notification),
// by trigger command, as plain async code; context.execute issues a command back (causation filled in)
handlers: { "notifications.notify": async (reaction, context) => {} },
config: { pollEvery: "5 seconds" }, // batch, lease, retry, poll: OutboxOrchestratorConfig
},
});
clock.advance(days(3));
await client.reactions.pass(); // the timers due now have fired and their notifications reached the notifierThe facade forks the orchestrator's loop (run: a pass after every commit and every pollEvery); reactions.pass() waits for a
pass the loop is making, then makes its own, so what was due when it was asked is done when it resolves. Handlers the
ports bind (layerPlugins) stay bound; one given here for the same command takes its place. A notification's
params carry the effect's effectId and occurredAt (as in run.runtimeEffects). Only a facade built with
reactions has client.reactions; its type says so.
A promise rejects with a WorkflowClientError: an Error that is a WorkflowFailure, a code with parameters.
kind: "refused" carries the engine's refusal code and parameters; kind: "runtime" the codes
runtime.command-id-reused, runtime.sequence-conflict, runtime.stream-not-empty, runtime.invalid-event,
runtime.store-unavailable, runtime.storage-full;
kind: "client" the codes client.invalid-request (options or input do not fit their schema; nothing was sent),
client.unauthenticated, client.transport, client.unavailable (the layers could not be built) and client.defect.
workflowClientError(failure, cause?) builds one, for a layer over the client that fails the way the client does.
Scripts
bun run typecheck
bun run test # bun test src
bun run build # tsc -p tsconfig.build.json