@fabricorg/platform-temporal
v4.5.0
Published
Temporal binding contracts for governed TechFabric Platform actions and sagas.
Readme
@fabricorg/platform-temporal
Host-side Temporal binding for governed Platform actions. Activities invoke the public governed Host boundary with stable workflow/step idempotency, carry workflow evidence, and map saga/approval messages to signals. Temporal supplies durable orchestration; Platform invocation and event records remain canonical audit evidence. This package does not call handlers or make Platform a workflow authority.
temporalWorkflowStartClient() adapts the official @temporalio/client WorkflowClient; all direct Temporal packages in an application must remain on the family-supported version line.
SagaWorkflowRegistry maps saga action IDs to workflow types and task queues without process-global
registration. createTemporalSagaDispatcher() starts the parent under the Host's stable workflow ID
with Temporal's use-existing conflict policy. createSagaParentActivities() exposes explicit durable
progress, approval-parking, cancellation, completion, and compensation-failure callbacks; workflows
must finalize the canonical parent invocation through those activities rather than treating Temporal
history as the audit ledger.
createSagaParentActivities() attaches a distinct stable lifecycleId to each progress step,
approval gate, cancellation, completion, and failure. sagaParentActivityIdentity() accepts an
optional occurrence discriminator for callers constructing those identities directly, while
sagaChildCausation() produces stable child causation. A durable lifecycle adapter uses these
identities to make a retried or replayed activity idempotent. SAGA_SIGNALS declares
the stable signal names (saga.proceed, saga.cancel, saga.approval) a workflow may register
handlers for.
Signal identity and the saga signal inbox
A sender may deliver the same signal more than once, for example when it retries
client.signal() after a timeout. SagaSignalEnvelope has an optional signalId that
identifies one logical signal; reuse the same value on every redelivery, such as a
webhook delivery ID or an approval decision ID. createSagaSignalDispatcher() forwards the
whole envelope and throws on a blank signalId before sending.
createSagaSignalInbox() is the receiving side. It has no Temporal import and reads no
clock, randomness or process-global state, so it can run inside workflow code:
import * as wf from "@temporalio/workflow";
import { createSagaSignalInbox, SAGA_SIGNALS, type SagaSignalEnvelope } from "@fabricorg/platform-temporal";
const inbox = createSagaSignalInbox(input.inbox); // the previous run's inbox.snapshot(), if any
wf.setHandler(wf.defineSignal<[SagaSignalEnvelope]>(SAGA_SIGNALS.approval), (envelope) => {
inbox.receive(envelope);
});
if (await wf.condition(() => inbox.pending(SAGA_SIGNALS.approval) > 0, "1 day")) {
const approval = inbox.take(SAGA_SIGNALS.approval);
}receive()buffers envelopes FIFO per signal name and returnsfalse, dropping the envelope, when itssignalIdwas already received under any signal name.- Envelopes without a
signalIdare buffered and not deduplicated. - Dedup state belongs to the inbox instance, so it lasts for one workflow run. To keep it
across continue-as-new, pass
inbox.snapshot()into the next run and hand it back tocreateSagaSignalInbox(). The snapshot carries both the seen IDs and any envelope that was accepted but not yet taken; carrying onlyseenSignalIds()would drop those envelopes and then reject their redelivery. - The remembered ID set grows with each distinct
signalIdand is not pruned, so continue-as-new does not shrink it. Forgetting an ID would let its redelivery through.
Declared compensation and child refusals
runCompensatedSaga() runs steps in order and, when one fails, runs the accumulated reversals
newest-first, then throws SagaCompensationError. Its result.failedStep and each failed
CompensationRecord keep their error text, and also carry an optional failure
(SagaStepFailure, { code, data? }) when the governed child resolved failed with a declared
business refusal: Platform Host 8.21.0 or later reports it as failure for an action that declares
failureSchema. A workflow can branch on failure.code; it means only that the child's handler
returned that refusal on the execution that settled the child failed. The activity result is
untyped, so the binding accepts failure only on a failed result, only as a fixed code and an
optional plain JSON object, and keeps a copy. A thrown activity, a policy block or another status
supplies no failure.
Passing result.compensated to the parent's fail lifecycle activity does not copy child detail
into the parent ledger on Platform Host 8.21.0 or later: createDurableSagaParentLifecycle() leaves
each record's failure member out of the SagaParentFailed v1 event and writes the rest as before,
so a retry from a worker without this field matches the recorded evidence. An older Host writes the
member into the event, and a retry of that fail() on an upgraded Host is then refused as
contradictory evidence, so upgrade every Host that records saga parent failure before deploying
workers with this release. Temporal history keeps the activity results, including failure,
outside Host's stored-record erasure.
Awaited saga children
Enable awaitedSagaChildren on a Platform Host with a store that supports awaited children. The
application's Temporal workflow chooses which declared step to admit, when to close admission,
and how to respond to child outcomes. Use createTemporalAwaitedSagaActivities() to call the
optional Host controller from the parent workflow. Give each logical occurrence a stable key,
including each iteration of a repeated step. After closure, propose settlement against the version
of the snapshot the workflow reviewed. If Host returns review_required or stop_required,
review the returned snapshot before retrying. To honor a recorded stop, call
settleAwaitedSaga({ ...scope, snapshotVersion: reviewed.version, useRecordedStop: true }). The
activity retrieves the authoritative stop inside the Worker and Host checks the version during
settlement. The workflow only needs the recorded stop kind and the version it reviewed.
The activities return an allow-listed snapshot with reservation IDs, occurrence keys, outcome
kinds, disposition kinds, reconciliation flags, and the opaque version. Child results, actor
identities, detailed evidence, and disposition payloads stay in Host. A workflow that needs
additional information can register a projectSnapshot callback on the Worker. For example,
this callback exposes whether an assignment result was confirmed without returning the result.
const parentActivities = createTemporalAwaitedSagaActivities(controller, authority, {
projectSnapshot(snapshot) {
const assignment = snapshot.children.find(({ reservation }) => reservation.stepId === "assign");
const outcome = assignment?.outcome;
return { assigned: outcome?.kind === "succeeded" && outcome.result?.assigned === true };
},
});
// A workflow reads the selected value from snapshot.projection?.assigned.Temporal history retains the projection and activity arguments. Use opaque occurrence keys, redacted parameter values or references, and projections limited to fields safe for workflow history.
Pass the SDK's activityInfo function to createTemporalAwaitedSagaAuthority() in the Worker
process. Use the same authority object for Worker activities and Host authorization. The callback
extracts the namespace, workflow ID, run ID, and workflow type from Temporal's activity context.
In the Host's authorize callback, call authority.read(proof) and compare all four fields to the
trusted execution binding for the scoped parent and its certified declaration. Establish the binding
from the trusted parent starter or an explicitly authorized successor before allowing parent
activities. The parent ID and scope in the workflow input identify the record to authorize. A
workflow with the same input and a different run needs its own explicit authorization.
Wire createTemporalAwaitedChildTransport(client, registry) into Host as the awaited child
transport. Register a dedicated child workflow type and task queue for each supported action. The
child workflow calls executeAwaitedSagaChild() with no arguments, using the activity from
createTemporalAwaitedChildActivities(client, registry, authority, controller). Give the activity
retry time to wait for Host to record the exact start receipt. Host verifies the admitted
reservation and run, and checks the registered authorizeChildExecution callback before it
executes the governed invocation. For a Worker and Host in the same process, authorize the child
by comparing authority.read(proof) to the receipt and the trusted namespace and workflow type
for the action.
import { activityInfo } from "@temporalio/activity";
import type { AwaitedSagaOptions } from "@fabricorg/platform-host";
import {
createTemporalAwaitedChildActivities,
createTemporalAwaitedChildTransport,
createTemporalAwaitedSagaActivities,
createTemporalAwaitedSagaAuthority,
} from "@fabricorg/platform-temporal";
const authority = createTemporalAwaitedSagaAuthority(activityInfo);
const transport = createTemporalAwaitedChildTransport(client, childRegistry);
// Configure Host with transport, a certified parent authorization callback, and this child authorization callback.
const authorizeChildExecution: AwaitedSagaOptions["authorizeChildExecution"] = async ({ authority: proof, request, receipt }) => {
const run = authority.read(proof);
return run !== undefined && run.namespace === client.options.namespace &&
run.workflowId === receipt.workflowId && run.runId === receipt.runId &&
run.workflowType === childRegistry.require(request.actionId).workflowType;
};
// Register these activities on the appropriate Workers after creating Host.
const controller = host.awaitedSagaChildren;
if (!controller) throw new Error("Awaited sagas are disabled");
const parentActivities = createTemporalAwaitedSagaActivities(controller, authority);
const childActivities = createTemporalAwaitedChildActivities(client, childRegistry, authority, controller);The transport starts the reserved workflow ID with FAIL for an active ID and REJECT_DUPLICATE
for a retained closed ID. It includes only the route identifiers in fixed Temporal start metadata.
Protect start access to the registered queue and namespace and keep child workflows on their
original run. Before replacing an action's registry entry, drain its outstanding children under the original entry.
Keep the original workflow type, task queue, and Workers available until their outcomes are durable. The metadata correlates the run with a reservation. The Host receipt and Worker
activity context authorize execution. Recovery checks the exact run after Host records its
receipt. A confirmed closed run whose child still has no durable outcome or authorized continuation
requires Host reconciliation. A lookup miss might hide a delayed start or an expired execution.
Recovery preserves that uncertainty and relies on observation after the first start attempt. Keep
the namespace retention greater than the client's bounded start request window.
Use createTemporalAwaitedSagaParentObserver(client, WorkflowNotFoundError) and
createTemporalAwaitedSagaWakeup(client, WorkflowNotFoundError) from a trusted Host recovery worker.
Resolve the exact run from the parent's persisted bindingId and call the returned functions from
the Host's observeParent and wakeParent hooks. The observer checks whether the exact run remains
active so Host can recognize a closed or missing parent without resending an unchanged wake. A
paused run remains eligible for a wake when it resumes. The wake-up sends an empty
AWAITED_SAGA_WAKE_SIGNAL to the running parent. The workflow should read the
Host snapshot after a wake signal or a bounded timeout and use the same durable evidence if the
signal is lost or delivered more than once. Temporal history retains activity inputs and outputs
independently of Host's stored-record erasure.
