@sewdn/workflow-temporal
v0.1.1
Published
The workflow orchestrator on Temporal: one Temporal workflow per run drives its deadlines, handlers and notifications through the runtime; and the pure engine inside Temporal's workflow sandbox.
Readme
@sewdn/workflow-temporal
The WorkflowOrchestrator port of @sewdn/workflow-runtime on Temporal: one Temporal
workflow per run drives the run's deadlines, its triggers' handlers and its notifications. And a showcase of the
pure engine running inside Temporal's deterministic workflow sandbox. Built on the Temporal TypeScript SDK 1.26.0
(@temporalio/client, worker, workflow, activity, common) and effect 4.1.4.
The run's event stream stays the only truth. A run workflow holds nothing the stream does not say: it reads the
stream through an activity, fires deadlines and delivers reactions through activities, and the runtime's command
ids and the reactions read model make every step safe to repeat.
import { WorkflowOrchestrator } from "@sewdn/workflow-runtime";
import { layerTemporalCluster, layerTemporalOrchestrator } from "@sewdn/workflow-temporal";
const orchestrator = layerTemporalOrchestrator().pipe(
Layer.provide(layerTemporalCluster({ address: "127.0.0.1:7233", taskQueue: "workflows" })),
);
// beside the runtime, its stores, a Notifier and the bound TriggerHandlers:
const program = Effect.gen(function* () {
const orchestration = yield* WorkflowOrchestrator;
yield* orchestration.run; // until the scope closes
});| Export | What it is |
| ------------------------------------- | ---------------------------------------------------------------------------------------------- |
| layerTemporalOrchestrator(config?) | WorkflowOrchestrator on Temporal; needs the runtime's services and TemporalCluster |
| makeTemporalOrchestrator(config?) | the same as a scoped effect (the orchestrator suite's MakeOrchestrator) |
| layerTemporalCluster(options) | TemporalCluster: a client and a worker connection to address, closed with the scope |
| runWorkflowId(cluster, stream, run) | <idPrefix><stream>/<runId>, the id of a run's workflow |
| makeActivities(services, retry) | the run workflow's activities over a context of the runtime's services |
| runWorkflowBundle() | the run workflow bundled for the sandbox (webpack, once per process) |
| viewer, runViews | the showcase's pure computation: fold commits with evolve, view phases and available actions |
| showcaseWorkflowBundle() | the showcase workflow (engineRunViews) bundled with the engine |
How it works
- One workflow per run, id
<idPrefix><stream>/<runId>, for the run's whole life.catchUpreads the stream after the adapter's checkpoint (checkpointsrow<stream>#temporal) and sends each run a commit touched acommittedsignal withsignalWithStart, which starts the workflow when it is not running (a rollback signals every run of the world). Each signalled run is registered (<stream>#temporal/<runId>).rundoes this after every commit of the runtime'schanges. - A step of the workflow: the
observeactivity (observeRunfrom the cursor), thefireDeadlineactivity while the run's next deadline moment is due by the runtime's clock (undertimerCommandIdwith the stream's rollback generation, then a new look), then thedeliveractivity for each pending reaction or notification that is due. A step follows every signal, everypassupdate, and Temporal's timer:condition(() => woken, due - now), wheredueis the next deadline moment or retry. The timer is cancelled when the condition wins. passcatches up, then sends every registered workflow apassupdate, which returns once a step that began after it has ended: what was due at the runtime's clock is done. A workflow that has closed is unregistered.- Time is the runtime's: the
observeactivity reports the runtime clock's now, and due is judged against it, so a host or a test that moves its clock moves the orchestration. Temporal's timers only wake the workflow. - Retries: a failed handler or notification is recorded as
retryingand tried again whenretry(the outbox adapter's schedule, by the runtime's clock) says, orgiven-up. Temporal's own activity retry policy (activityRetry) is for activities that failed: a store unreachable, a worker gone. - History is bounded with
continueAsNew({ stream, runId, cursor, lastTouch, segment, pacing })aftersegmentEverysteps (or when Temporal suggests it), once the workflow is idle: nothing pending, no pass waiting. - The workflow ends when its run no longer runs and nothing is pending; a later commit (a rollback that revives the run) starts it again from the checkpoint.
- Workers: an orchestrator instance hosts a worker for its task queue, in its scope, with activities over the
runtime and stores in its context (their
Clocktoo). The SDK refuses two workers on one task queue in one process: instances of one process share it, and its activities run on the newest instance. Activities may use Effect; the workflow code may not (below).
TemporalOrchestratorConfig: retry (default exponential from 1 second, five retries), segmentEvery (200),
activityTimeout (1 minute), activityRetry (initialInterval 1 second, maximumInterval 1 minute,
maximumAttempts unlimited), worker (maxCachedWorkflows, stickyQueueScheduleToStartTimeout,
shutdownGraceTime).
The sandbox
The run workflow (src/workflows/orchestrate.ts) is plain TypeScript over @temporalio/workflow and the types of
src/contract.ts: no Effect, no runtime, no clock of its own. The showcase workflow (src/showcase/workflows.ts)
loads the pure engine into the sandbox as it is: it folds the commits it is signalled with evolve and computes
runPhases and availableActions after each. Nothing in the engine was refused: its Ajv validator compiles
schemas with generated functions, and the sandbox (a vm context) allows that, under Bun and under Node. The engine
takes "now" from each commit, so the fold inside equals the fold outside.
Bun or Node
The worker runs under Bun 1.4 (the SDK supports Bun from 1.4.0; it warns that stack trace collection is disabled)
and under Node 24. The tests run with bun test; a host may run its workers on either.
When to use which orchestrator
| Orchestrator | Use it when | Infrastructure |
| ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Outbox (layerOutboxOrchestrator, the default) | Handlers are short (a mail, a calendar entry); one database is all you want to run; a browser host, the CLI or tests | None beyond the stores: the outbox and scheduler tables in the same database, leases shared by any number of processes |
| Effect's durable engine (workflow-durable, S3c) | A handler must wait (hours, days, an answer from outside) and you want it in-process, on Effect, on the same PostgreSQL | The same PostgreSQL with Effect cluster's message storage; runner processes. Its API is marked unstable |
| Temporal (this package) | You already run Temporal, or want what it brings: its UI and visibility of every run's work, its retries and timers at scale, workers in other languages beside these | A Temporal cluster with its own database (or Temporal Cloud) and worker processes hosting this package's activities next to the runtime and its stores; the stores stay yours |
All three pass the same orchestrator suite and leave the same stream behind.
Running the demo
The demo is the test suites. A disposable local dev server (the official CLI image, in-memory, bound to 127.0.0.1):
bun run temporal:up # docker run … temporalio/temporal:1.10.1 server start-dev --ip 0.0.0.0 --headless
bun run test:temporal # TEMPORAL_ADDRESS=127.0.0.1:7233 bun test src
bun run temporal:down # docker stop; the container is removed (--rm)src/orchestrator.test.ts: the orchestrator suite of@sewdn/workflow-runtime/testingon this adapter (the memory adapter's stores, a task queue per case,segmentEvery: 5so it crossescontinueAsNew); its streams equal the outbox adapter's reference run. WithWORKFLOW_TEST_POSTGRES_URLit also runs the suite on PostgreSQL with a second process polling workflow tasks. Every history is replayed against the run workflow.src/handover.test.ts: with both services configured, two processes share a task queue and PostgreSQL schema. The second process delivers a deadline notification after the first exits, without repeating the first process's notification.src/showcase/showcase.test.ts: the engine inside the workflow equals the engine outside, for two scenarios, and the history replays.src/workflows/orchestrate.test.tsand the showcase's replay test: Temporal's replay test against recorded histories (*.history.json), without a cluster.RECORD_HISTORY=1 bun run test:temporalrecords them again.
bun test src without TEMPORAL_ADDRESS runs the replay tests and skips the rest, saying so. Nothing here deploys
anything.
