@onlineapps/conn-orch-orchestrator
v8.0.1
Published
Workflow orchestration connector for OA Drive - handles message routing and workflow execution
Maintainers
Readme
Status: current Owns: the execution of one workflow step inside a business service, and the routing or completion that follows it
Uniform: library/orchestration
Duty sections that apply:
all: L-MAIN, L-ENGINES, L-TESTS, L-TEST-SCRIPT, L-PACK-TESTS, L-PINS, L-NO-FILE-RANGE, L-CHANGELOG, L-PACK-CHANGELOG, L-README, L-README-REGION, L-CONSUMER
@onlineapps/conn-orch-orchestrator
Workflow orchestration coordinator. A business service hands it one inbound workflow message; the orchestrator executes the step that belongs to that service, records the result into the unified cookbook, and either routes the workflow to the next step or completes it.
Everything below is derived from src/ (src/index.js, src/WorkflowOrchestrator.js).
Installation
npm install @onlineapps/conn-orch-orchestratorExports
const { WorkflowOrchestrator, create, VERSION } = require('@onlineapps/conn-orch-orchestrator');| Export | Kind | Notes |
|---|---|---|
| WorkflowOrchestrator | class | the orchestrator itself |
| create(config) | function | new WorkflowOrchestrator(config), nothing more |
| VERSION | string | read from package.json, never a hand-kept literal |
There is no default export and no OrchestratorConnector.
Constructor
The orchestrator takes injected dependencies only — it reads no environment
variable and opens no connection of its own (process.env does not appear anywhere in
src/).
const { create } = require('@onlineapps/conn-orch-orchestrator');
const orchestrator = create({
mqClient, // required
registryClient, // required
invoker, // required — { async invokeOperation({...}) }
cookbook, // required — must expose validateCookbook() and createRouter()
logger, // required — must expose info(), warn(), error(), debug()
errorHandler, // required — classifyError(error) -> error type
operationMutatesLookup, // required — the operation spec; see below
cache // optional — enables read-through step cache
});Each requirement below is enforced in the constructor and throws immediately:
| Key | Required | What is checked |
|---|---|---|
| mqClient | yes | present |
| registryClient | yes | present |
| invoker | yes | present and typeof invoker.invokeOperation === 'function' |
| cookbook | yes | present, and cookbook.createRouter is a function whose result exposes routeToService(serviceName, message) |
| logger | yes | present and exposes all four of info, warn, error, debug as functions — the constructor names the first missing one (connector-logger-contract 001) |
| errorHandler | yes | present and typeof errorHandler.classifyError === 'function' — the single classifier of record; the orchestrator keeps no status map of its own |
| operationMutatesLookup | yes | present and a function — the only view of an operation's specification (mutates, sensitive_input_fields, retry); an absent hook would disable the §8 scrub in silence, so it is refused, not defaulted |
| cache | no | when absent, no step result is ever cached |
| maxRetryAttempts, retryBaseDelay, retryMaxDelay, retryBackoffMultiplier | refused | retired in 8.0.0 — the retry window of a step is the policy of its operation (§ Step retry policy below), not a constructor number; any of these keys, whatever its value, throws [WorkflowOrchestrator] Retired config key - config.<key> is no longer read … so a number nobody reads is never accepted in silence |
| serviceDiscoveryCacheTTL | no | lifetime in ms of the router's cached registry answer about a service, named once as SERVICE_DISCOVERY_CACHE_TTL_MS (300000) — the default applies to an absent value only; an explicit one is validated: an integer ≥ 0, where 0 is a value meaning no discovery cache, and anything else is refused by key name. It is handed to cookbook.createRouter next to logger; @onlineapps/cookbook-router requires it |
amqpUrl and storageUrl are not accepted: passing only those throws
mqClient is required. The MQ connection belongs to the injected mqClient.
invoker contract
async invokeOperation({ operation, input, envelope, workflow_id, correlation_id, step_id,
sensitive_input_fields })
-> { status, result } | { status, error }sensitive_input_fields (string[], since d.1271) is the recipe's sensitive-input rule —
cookbook._system.sensitive_input_fields of the message, unique, sorted, a fresh copy per call;
[] when the recipe declares nothing. It is the rule only, never the consumption record, and
input still carries the full value for the owning step (secretbox.md §8). It is the basis
of the wrapper's placeholder guard (conf delivery-ws-platform-events 005 (II)).
Typically { invokeOperation: serviceWrapper.invokeOperation.bind(serviceWrapper) }.
Dispatch is in-process, so a step can only reach handlers of the service that is
running the cookbook. This replaced the retired apiMapper HTTP-loopback path.
The one public method
await orchestrator.processWorkflowMessage(message, serviceName)message carries workflow_id, cookbook (the unified cookbook), current_step
(a step_id), a required correlation_id, and optionally tenant_id /
workspace_id / person_id which override cookbook._system. cookbook._system
must carry the recipe's sensitive-input rule, sensitive_input_fields (see
Sensitive step input). serviceName is the
service consuming the message. It is required and must be a non-empty string: anything else is
refused with a thrown error before the message is read — nothing is routed, published or
invoked (d.1042).
Everything else on the class is private (_-prefixed) and not part of the contract:
there is no processStep, no handleControlFlow, no routeToNextService, no
completeWorkflow, no handleWorkflowFailure, and no statistics API — the class
keeps no counters, so getStats() / resetStats() do not exist.
Return values
| Situation | Returns |
|---|---|
| step executed, workflow routed on or completed | { success: true, workflow_id, step_id, result } |
| step belongs to another service (message re-routed there) | { skipped: true, reason: 'wrong_service' } |
| control-flow step naming another service (message re-routed there) | { skipped: true, reason: 'wrong_service_control_flow' } |
| retryable failure, republished to <serviceName>.workflow after the policy's delay | { retrying: true, attempt, nextAttempt } |
| retries exhausted, error not retryable, or no step to carry a policy | { dlq: true, workflow_id, current_step, attempts, error_ref } |
| step completed, its hand-off failed — recorded as publish_pending (see below) | { publish_pending: true, workflow_id, step_id, next_step, target_queue, error_ref } |
| error classified DECLINED — a rule refused the run | { declined: true, workflow_id, current_step, attempts, error_ref } |
| the cookbook's epilogue step executed (see below) | { success: true, workflow_id, step_id, result, epilogue: true } |
| terminal failure (dlq or declined), and the hand-off of the epilogue step failed — recorded as publish_pending | the terminal return above plus publish_pending: true, next_step, target_queue, publish_pending_error_ref |
What it publishes
Every workflow.* name below is COMPOSED, never typed here:
queueConfig.queueName('workflow', <key>) from @onlineapps/mq-client-core, the package
that declares those queues with their arguments, TTL and dead-letter route. A name typed
twice diverges the day one side renames it, and the publish then goes to a queue nobody
declared — silently.
workflow.progress→ monitoring after every completed step and every retry attempt (publishToMonitoringWorkflowfrom@onlineapps/mq-client-core); a failure to publish monitoring is logged as a warning and never fails the step.- next step →
router.routeToService(step.service, message), for a task and a control-flow step alike. A step withoutserviceis refused by name (see Control-flow steps); there is no shared queue for it (docs/governance/confirmations/cookbook-execution-owner.md002). - last step →
workflow.completed, carryingapi_output(the last step'soutput),stepsas astep_id-keyed map, the final cookbook and thedeliveryblock. It is the run's single TERMINAL message: published once, after the last step. - last step BEFORE the
delivery.on_resultstep →workflow.delivery_requested, the same envelope withstatus: "delivery_requested". It hands the run over to the Delivery Dispatcher while the run is still going: the step that records how the delivery went waits for a result that does not exist yet. When the dispatcher returnsdelivery_result, that step runs and the run ends onworkflow.completed, carrying the recorded outcome indelivery._result— a report of a finished run, not a request to deliver it again. A cookbook withoutdelivery.on_resultnever publishes here. (Owner decision 2026-09-14,api/docs/governance/confirmations/delivery-receipt-chain.md002, restated by 003.) - unrecoverable failure →
workflow.failed(the DLQ), with the full cookbook including_execution.retry_history. - step completed, hand-off failed →
workflow.failedas apublish_pendingrecord (confdocs/governance/confirmations/step-publish-failure.md001). The step's handler had already returned, so whatever fails in the hand-off that follows — the publish to the next step (through the router), ofworkflow.completedor ofworkflow.delivery_requested, transient or permanent, or the registry lookup of the next step's service — does NOT fail the step, and the step is never executed again: no retry, and nothing a requeue would run twice. The hand-off is prepared first (a defect there, such as a next step naming no service, is still a failure of the step) and then published; the record's BODY is that prepared message, unchanged — for a next stepcurrent_stepis the next step and the cookbook carries the completed step with itsoutputand_execution.status: 'completed'— plus an objectpublish_pending{completed_step,completed_step_index,next_step,target_queue,error_type,error_code,error_ref,error,retries_exhausted,buffered,sent,at} andfailed_at(the time of the write).erroris the hand-off error's text redacted by value (§ Sensitive step input, d.1284) — as is theerrorblock of the monitoring event and the orchestrator's ERROR lines about the failed hand-off ([PUBLISH] ✗ Failed to publish …,[DLQ] Step … recording publish_pending); the verdict (error_type,retries_exhausted) is taken from the original error. A requeue topublish_pending.target_queuetherefore runs the next step only.bufferedandsentare copied from the error of@onlineapps/mq-client-core(a boolean, ornullwhen the error does not say — never derived):bufferedsays whether the library's memory buffer holds a copy,sentwhether the hand-off frame left the client (confdocs/governance/confirmations/step-publish-failure.md003).sent: true= the frame left the client, so the broker may have delivered it — a requeue is the operator's decision after checking the next step's effect.sentsays nothing about whether the broker kept the frame: a frame the broker refused after it arrived also carriestrue, and the refusal is itserror_type: 'PUBLISH_PERMANENT'. Monitoring getsevent_type: 'progress',status: 'publish_pending'with anerrorblock andpublish_pending: { next_step, target_queue, sent }; the epilogue does not start, because the run has not ended. The hand-off and the record are published with{ bufferOnFailure: false }: the record is the durable copy, and a second one in the MQ library's memory buffer would be sent again after a reconnect. If the record itself cannot be written, the ORIGINAL hand-off error is thrown to the caller and the step is still not retried (a redelivery is the consumer-rail dedup's, confmq-consumer-contract009). - a run REFUSED by a rule (
DECLINED) publishes nothing here: it ends with a singlemonitoring.workfloweventevent_type: 'declined', because a refusal is not a failure and must not raise the DLQ dashboard's threshold (owner decision 2026-09-23,/docs/governance/confirmations/workflow-failed-status-projection.md004). - a cookbook declaring
global_error_handler: { strategy: 'compensate', compensationStep }gets its epilogue step routed right AFTER either terminal failure above (theworkflow.failedpublish, or thedeclinedevent), with the failure written intoglobal_error_handler._failure(step_id,service,operation,error_type,error_code,details— always all six,nullwhere the error carries no value; in scope as{{global_error_handler._failure.…}}). A retried error never starts it, and neither does a failing epilogue. The epilogue has its own end: it publishes noworkflow.completedand no hand-over — only its step events, each carryingphase: 'epilogue', so a reader of the trace sees them as after the end. The ordinary step order never leads into the epilogue step (the cookbook keeps it last). (Owner decision 2026-09-26,/docs/governance/confirmations/meditest-manual-trigger.md009.) The epilogue hand-off is the same kind of hand-off as the one after a completed step (/docs/governance/confirmations/step-publish-failure.md002): it is published with{ bufferOnFailure: false }, and when it fails the orchestrator writes ONEpublish_pendingrecord whose body is the prepared epilogue message and whose object carriesfailed_step/failed_step_index— the step that failed, nevercompleted_step— andnext_step= the epilogue step. Nothing leavesprocessWorkflowMessage, so the failed step is not delivered and run again; after the DLQ branch the run then holds two records inworkflow.failed(thefailedone first, thepublish_pendingone second), afterdeclinedonly thepublish_pendingone. A requeue of that record topublish_pending.target_queueruns the epilogue once. The answer to the source then leaves with the requeue, not at once (002 § Conditions). Its monitoring event (progress/publish_pending) leaves after the run's terminal event, so it carriesphase: 'epilogue'like every other event after the end; the one after a completed step carries nophase. The record's body is the epilogue message:current_stepis the declaredcompensationStep, which is how a reader of the dead letter tells the phase.
correlation_id is mandatory on every inbound message. A missing one is not tolerated:
the orchestrator throws MISSING_CORRELATION_ID (statusCode 400, type VALIDATION),
so the message goes straight to the DLQ rather than being silently redelivered
(/docs/biz/70-contracts/workflow-message.md). cookbook._system.sensitive_input_fields
is mandatory the same way — MISSING_SENSITIVE_INPUT_FIELDS, refused after the cookbook
passed validation (a rejected cookbook keeps COOKBOOK_REJECTED); a malformed
cookbook._system.sensitive_unresolved is INVALID_SENSITIVE_UNRESOLVED.
Cookbook format (V2.1)
steps must be an array, and every step must carry step_id. Both older shapes
fail fast rather than being tolerated. The refusal is not the orchestrator's: every
inbound message passes its cookbook to the injected cookbook.validateCookbook(), and with
@onlineapps/cookbook-core behind it the message is that package's. Its stable parts:
- a cookbook recognised as an older format — a step with
idinstead ofstep_id, orstepsas an object keyed by step_id (V2.0), with noversion; or aversionof1.x.x/2.0.x→V1 format (…)/V2.0 format (…)followed byis BANNED - V2.1 is the only format this validator reads. - the same shapes under
version: "2.1.0"are held to the V2.1 schema → a step withidgivesForbidden field 'id',stepsas an object givesInvalid type for 'steps'
The full wording belongs to cookbook-core; the format itself is
docs/biz/40-cookbooks/format.md.
Task step
{
step_id: 'create-invoice',
type: 'task',
service: 'invoicing', // required for task steps — missing one fails fast
operation: 'create-invoice', // required for task steps — no fallback to step_id
input: { number: '{{api_input.number}}' }
}A task step whose operation is missing or an empty string stops the run before the
invoker is called and before a cache key is computed. On the message path cookbook-core
refuses it first, by its schema: Missing required field 'operation' (an empty string:
Invalid value for 'operation'). The orchestrator's own
[WorkflowOrchestrator] Step '<id>' has no operation - a task step must name the operation
to invoke (cookbook-core schema TaskStep.required) is the backstop for a validator injected
in cookbook-core's place that lets such a step through. The same holds for a step nested in
foreach / switch / fork_join / steps. Until 5.0.0 the name fell back to step_id,
which invoked an operation the service does not know and keyed the read cache by a
different string.
input is resolved before the call: {{api_input.x}}, {{steps.<step_id>.output.x}},
{{current.x}} (inside foreach), and helper calls such as
{{normalizeString(api_input.text)}} resolved from cookbook.templateHelpers. A step
whose value is a single {{…}} expression keeps its non-string type.
Both halves of the resolution belong to @onlineapps/cookbook-core, the package that owns
the cookbook format: resolveReferencesWith() walks the value, resolveReferencePath()
reads a PATH. What this connector supplies is the one part that is genuinely its own — the
EVALUATOR of a single expression, which also knows helper calls (helper registry,
ContentResolver, I/O) and is therefore asynchronous. The local walk (resolveValue) lived
here until d.377b and is gone: one semantics, one implementation, at the owner of the format.
Two consequences of that semantics are worth stating, because the local walk got both wrong while it existed:
- Addressing a step by position is refused at the ROOT of the path, and only there.
{{steps[0].output.x}}does not resolve;{{api_input.steps.0.label}}— business data that happens to carry astepskey — does. - A resolved value is inserted as text. A value containing
$&,$`or$'lands in a surrounding string exactly as it reads, rather than being expanded as a replacement pattern.
The syntax itself — every shape, the type-preserving whole-value form, and the rule that an
unresolvable reference survives as literal text — is documented in
docs/biz/40-cookbooks/variable-references.md.
A non-2xx envelope from the invoker becomes a thrown error carrying statusCode,
errorCode and details[] — the input of the retry/DLQ classification below.
Control flow
_executeControlFlowStep dispatches on step.type and its default branch throws
Unsupported control-flow step type - "<type>". Expected: steps|foreach|switch|fork_join.
Those four are the whole set. There is no if type (branching is switch), and the
fork type is spelled fork_join, not fork-join.
Every control-flow step, nested ones included, MUST carry service — the service that
executes it (docs/governance/confirmations/cookbook-execution-owner.md 002). A top-level
step that reached another service is re-routed to the queue of the one it names. A nested
step runs in-process in the service of the step it is nested in, so its service must be
that service. A nested task's operation declaration is read before dispatch like a top-level
one's (mutates, sensitive_input_fields, retry) and refused by name in the same way; its
retry is validated but not applied — the retry budget of a nested task is the policy of the
control-flow step above it (the platform default: a control-flow step has no operation to
declare one on, § Step retry policy). A step without service, or a nested one naming another service, fails fast
([WorkflowOrchestrator] FAIL-FAST: <type> step '<step_id>' in workflow '<workflow_id>' …)
and the run goes to workflow.failed.
Retrying a control-flow step — nested tasks that succeeded are not run again
A control-flow step is retried as a whole (the message of the step is republished, § Error
classification and retries). Until 8.0.0 that re-ran every nested task inside it, the ones
that had already succeeded included: a write that returned 200 beside a read that returned
503 was executed a second time on the next attempt (d.1274/2, a double write). Since 8.0.0
(d.1303, owner's word) every nested task that returns 2xx leaves a checkpoint in the
execution copy of the recipe, in the control-flow step's _execution.checkpoints:
"_execution": {
"status": "retrying",
"retry_history": [ … ],
"checkpoints": {
"group.write": { "output": { … }, "input_hash": "<sha256 of the resolved input>", "completed_at": "…" },
"each[2].write": { … },
"route.inner.write": { … }
}
}The key is the path of the nested step from the control-flow step down — <step>.<nested>,
a foreach iteration as <step>[i], nested control-flow steps chained — so a foreach
checkpoints per iteration, a fork_join per branch and a switch the step of the chosen
case. On the next attempt a nested task whose path has a checkpoint is not run: its
output is taken from the checkpoint (INFO line Nested step completed in an earlier
attempt, not run again), so the control-flow step returns the same shape and a later
{{steps.<step>.output…}} resolves as if nothing had been retried. The nested task that
failed, and every one after it, run as before. The skipped step still counts as having
consumed its sensitive_input_fields (it did, in the earlier attempt), so the next step's
message carries [REDACTED] exactly as after a real run.
The checkpoint is checked against the step's resolved input: the same message resolves
to the same input, so a different hash means the message was edited between attempts (a
requeue with a changed payload) or a template helper does not return the same value twice
— the checkpoint is then discarded with a WARN line (Nested step checkpoint discarded)
and the step runs again; an output is never taken for an input it was not produced from.
TIMEOUT on a nested writing operation still goes straight to workflow.failed (no retry,
no checkpoint consulted); the DLQ entry of a control-flow step names the nested tasks that
had completed in completed_nested_steps (paths only — the values sit in
_execution.checkpoints, redacted by the recipe rule in every observer copy, like output).
When the control-flow step completes, the spent map is dropped from its _execution: the
step's output carries every nested result. A top-level task step has no checkpoints —
retrying it is retrying the step itself.
steps — sequential group
{ step_id: 'group', type: 'steps', service: 'hello-service', steps: [ /* nested steps */ ] }Returns { type: 'steps', step_id, order: [...stepIds], results: { <step_id>: output } }.
A non-array steps fails fast.
foreach — iterate
{
step_id: 'each-item',
type: 'foreach',
service: 'hello-service',
iterator: '{{api_input.items}}', // must resolve to an array
body: [ /* nested steps, at least one */ ]
}The keys are iterator and body (not items/step). Each iteration adds current
(the item) and index to the context. Returns
{ type: 'foreach', step_id, count, iterations: [{ index, item, outputs }] }.
An iterator that does not resolve to an array, or an empty/missing body, fails fast.
switch — select one branch
{
step_id: 'by-priority',
type: 'switch',
service: 'hello-service',
expression: '{{api_input.priority}}', // template, $api_input.*/$steps.* or a plain path
cases: { high: { /* step */ }, low: { /* step */ } },
default: { /* step */ } // optional
}expression accepts a {{…}} template, a $api_input.x / $steps.x / $.path form,
or a plain dotted path. A dotted path that cannot be resolved throws
Switch expression could not be resolved; a string without a dot is taken as a literal.
The resolved value is stringified (null becomes 'null') and looked up in cases;
default is used when no case matches. With neither, the step returns
{ type: 'switch', step_id, expression, value, selectedCase: null, result: null } —
otherwise selectedCase is the matched key (or 'default') and result is the nested
step's output. A missing cases object fails fast.
fork_join — run branches in parallel
{
step_id: 'enrich',
type: 'fork_join',
service: 'hello-service',
branches: { validate: { /* step */ }, score: { /* step */ } }, // object, ≥ 1 branch
join: { strategy: 'merge' } // required, no default
}Every branch always runs, and join.strategy decides what the STEP's result is out of
their outputs. The step waits for EVERY branch to settle (Promise.allSettled), never for
the first rejection: when one or more branches fail, the step's error is the first declared
branch whose error is of class TIMEOUT and carries mutates: true (a writing operation
whose attempt deadline ran out — the step then goes straight to workflow.failed as
timeout_on_mutating_operation, see § Error classification and retries), otherwise the first rejected branch in
declaration order. The chosen error keeps its shape; the other branches' errors travel in
its details.branch_failures[] (branch, step_id, operation, error_type, error_code,
status_code, message, details), beside the chosen error's own details (a plain object
is spread next to it, an array or a scalar sits under the key details). A running branch is
never cancelled — there is no cancellation mechanism; it runs to its end and its result is
simply not read. Until 8.0.0 the branches ran through Promise.all: the step failed with the
FIRST rejection, the other branches kept running and their errors were dropped, so a reading
branch failing early with TRANSIENT republished the whole step while a writing branch was
still running towards its TIMEOUT — a second run beside it (d.1277). Returns
{ type: 'fork_join', step_id, join: { strategy }, branches: { <name>: output }, result },
where branches keeps the full named record whatever the strategy and result is the
joined value:
| join.strategy | result |
|---|---|
| merge | the branch outputs folded into one object, in declaration order (a later branch wins a colliding key) |
| first | the FIRST declared branch's output |
| last | the LAST declared branch's output |
| all | the named branch record, i.e. the same value as branches |
| custom | refused — the schema declares the value but no field to carry the custom join |
The vocabulary is the cookbook schema's (cookbook.v2.schema.json → ForkJoinStep →
join → strategy), and the executor refuses a value outside it rather than trusting that
validation ran. A missing branches object, an empty one, and a step with no
join.strategy all fail fast — before any branch is spent.
Step-result cache and operationMutatesLookup
With a cache connector injected, a task step that is not marked as mutating is
served read-through under
workflow:step:<step.service>:<operation>:t<tenant_id>:w<workspace_id>:p<person_id>:<sha256 of caller+service+operation+input+api_input>with cache.set(key, result, STEP_CACHE_TTL_SECONDS) — the entry's lifetime in seconds,
declared once in src/WorkflowOrchestrator.js and passed as the number the cache
connector reads (@onlineapps/conn-base-cache accepts a TTL only as a finite positive
number; anything else silently falls back to its own defaultTTL). Control-flow steps
are never cached.
Who is asking is part of the key — tenant, workspace and person — because the
cached value is that caller's result: service + operation + input say only WHAT ran
and WITH WHAT, never FOR WHOM. The workspace is the step's effective one, i.e. the
per-step workspace_id where the step declares one and the run-wide value otherwise —
the same value that goes in the invocation envelope. The person is there for the same
reason as the tenancy: a handler may read ctx.person_id, so the same operation with
the same input can answer differently per person. A message carrying no tenancy or no
person is neither rejected nor completed here: the key spells it tnone / wnone /
pnone, a value of its own that never collides with a real id, and whether the
operation needs tenancy at all is decided by the receiver
(@onlineapps/service-wrapper → ContextBuilder._validateTenancy, per bundle_scope).
Those segments sit AFTER <step.service>, so the invalidation pattern below still
matches every key.
A step counts as mutating when the REQUIRED operationMutatesLookup hook says so — mutates
has ONE source, the operation's declaration in config/service/operations.json; a mutates
key on the cookbook step is not read (until 8.0.0 step.mutates === true overrode the
declaration — a second copy of the declaration's column, the same thing conf
step-error-classification 001 refuses for retry in a recipe; 0 recipes carried it,
measured d.1313, and cookbook-core now refuses the key by the step's name). The hook's
mutates must be a boolean when present —
the same rule the registration contract (@onlineapps/service-validator-core) applies; a
present "yes", 1 or null is refused by the operation's name
([WorkflowOrchestrator] Invalid operation spec - "mutates" of operation '<op>' must be a
boolean; got …), before the handler runs, for a top-level and a nested task alike (d.1309).
An absent key reads as false, as does an operation the hook does not know:
/**
* @param {string} executingServiceName Name of the service running the cookbook.
* @param {Object} step The cookbook step about to execute.
* @returns {{ mutates?: boolean, resource_type?: string|null,
* sensitive_input_fields?: string[],
* retry?: { max_attempts: number, delays_ms: number[] } }|null|undefined}
*/
operationMutatesLookup(executingServiceName, step)The hook is typically wired by @onlineapps/service-wrapper from the service's
operations.json. It is the orchestrator's ONLY view of an operation's
specification — registryClient answers getService() (the registry projection
summary), never a spec — so the cache decision below, the sensitive_input_fields
scrub of the next section and the step retry policy (§ Step retry policy) all read
this one record.
{ mutates: true }— the read cache is bypassed, and after a 2xx handler result the orchestrator callscache.deleteByPattern('workflow:step:<step.service>:*').{ mutates: false },nullorundefined— treated as a read.- A non-empty
sensitive_input_fieldsalso keeps the step off the read cache, whatevermutatessays. The two are independent properties of one record: an operation can read and still take a secret on its input. Serving such a step from the cache would skip the execution, and with it the record of what was consumed, so the scrub of the next section would have nothing to erase and the value would travel on in the cookbook. resource_typeis not consumed by the orchestrator.- If the hook throws, the error is logged as a warning and re-thrown — a
misconfigured
operations.jsonsurfaces at runtime instead of silently drifting (/docs/standards/ARCHITECTURE_PRINCIPLES.md, Fail-Fast). - The hook is REQUIRED: construction without it throws
[WorkflowOrchestrator] Missing dependency - operationMutatesLookup(executingServiceName, step) is required. Until 4.0.0 it was optional, and its absence read as "no opinion" while it actually turned the §8 scrub off without a word (automation-gates.md§5).
const operations = {
'get-invoice': { mutates: false, resource_type: 'invoice' },
'update-invoice': { mutates: true, resource_type: 'invoice' }
};
const orchestrator = create({
mqClient, registryClient, invoker, cookbook, cache, logger,
operationMutatesLookup: (executingServiceName, step) => {
const spec = operations[step.operation];
return {
mutates: !!(spec && spec.mutates === true),
resource_type: spec ? spec.resource_type : null,
sensitive_input_fields: spec ? spec.sensitive_input_fields : undefined,
retry: spec ? spec.retry : undefined
};
}
});Sensitive step input — what a step leaves behind
Contract: /docs/architecture/secretbox.md §8. An
operation declares the input fields that carry a secret at operation level, beside
input/output:
"set-secret": {
"mutates": true,
"sensitive_input_fields": ["value"],
"input": { "type": "object", "properties": { "ref": {}, "value": {} } }
}The value cannot be taken out of the execution message — the handler is what encrypts and stores it. What the orchestrator guarantees is the other half, in two copies with two rules:
- The recipe rule comes from the envelope. The submitter (gateway, scheduler) reads
every operation of the recipe once, through
collectCookbookSensitiveFields({ cookbook, readServiceSpec })of@onlineapps/infrastructure-tools— the same reader the monitoring consumer uses — and writes the answer into the cookbook's system block:cookbook._system.sensitive_input_fields: string[](the union of every operation's declaration, unique, sorted;[]when none declares any) andcookbook._system.sensitive_unresolved: string[](theservice.operationnames whose specification could not be read). The orchestrator only applies the rule: throughoperationMutatesLookupit sees the declarations of the service it runs in, never those of another service's step. A message withoutsensitive_input_fields, or with one that is not an array of non-empty strings, is refused by name —MISSING_SENSITIVE_INPUT_FIELDS(status400, typeVALIDATION, no retry), after the cookbook passed validation. A non-emptysensitive_unresolvedmeans placeholder plus note, the step runs (owner's word,delivery-ws-platform-events005 (III), the scheduler's policy ofscheduler025 (1)): in every observer copy each step of such an operation, nested ones included, carries[REDACTED]in place of its wholeinputandoutput, the key itself in_systemis the note the copy carries on, and a warning is logged; the execution copy stays whole. A missingsensitive_unresolvedreads as empty; a malformed one isINVALID_SENSITIVE_UNRESOLVED. - Every observer copy is redacted by that rule from the first copy on, united with
the fields this message's own steps consumed: the
progressevent after a completed step — itscookbookand its top-leveloutputalike —, theretryanddeclinedevents, thefailedevent and the durableworkflow.failedrecord (also when the message failed before any step ran: a missingcorrelation_id, a rejected cookbook, a throwing lookup, a malformed declaration), the run's outcome envelope (workflow.completed/workflow.delivery_requested,api_outputincluded) and the monitoring event of apublish_pendingrecord. The copy the epilogue step starts from is that terminal copy: an epilogue step that needed a declared field gets[REDACTED]. - The failure text is redacted by value (owner's word,
delivery-ws-platform-events004): the key-name redaction cannot see inside a sentence, so every value found under a field the rule or the consumption names — in the cookbook as it arrived, indelivery, and in the resolved input of the steps this message ran — is replaced by[REDACTED]wherever the failure is copied for an observer:error.message,error.details(any string at any depth), the stack in the orchestrator's failure log lines, thedeclined/retry/failedevents,retry_historyin every observer copy, and the failure written for the epilogue. Strings match whole (length ≥ 1), numbers as text, by plain substring replacement after the error was classified. The attempt record written to_execution.retry_historytakes the same redacted text and details, so the execution copy (the retry's republished message, the next step's message, the body of apublish_pendingrecord) carries no declared value in its retry history either (owner's word, d.1277): the history is not a handler's input, no step reads it. What the execution copy keeps as it came is the input —api_inputand the step'sinput— until the owning step consumed it (next bullet). - Every execution copy keeps the value until the owning step consumed it. Every task
execution — top level or nested in
foreach/steps/switch/fork_join— goes through one place, and that place records the field names the operation declares, before the input is dispatched, so a step that fails after dispatch counts as having consumed it. The message of the next step, the republished message of a retry and the body of apublish_pendingrecord (which is that next-step message) have only the consumed fields replaced by[REDACTED], wherever they sit —api_input, the step's owninput, a stepoutputechoing it, at any depth. A later step referencing{{api_input.<field>}}of a consumed field therefore resolves to[REDACTED], which is the point; a field a later step owns still travels to it. - Fields neither the rule nor a consumed declaration names are untouched, and a recipe
whose rule is
[]with operations declaring nothing leaves the cookbook exactly as it was.
Boundaries, stated rather than implied:
- A retry keeps the value. The republished message is the execution message of the
next attempt, and the handler still needs the value. The
monitoring.workflowretryevent published beside it does not carry it. - A DLQ record does not.
workflow.failedwaits for a human, so it is durable storage; the consequence is deliberate — a run requeued from the DLQ resumes with[REDACTED]and has to be submitted again, not resurrected. This holds whichever step failed, the owning one or one before it. Thepublish_pendingrecord is the exception on record: its body is the next step's execution message and carries the value until a requeue delivers it (owner's open question). - A value under another name passes. The redaction matches by key name: a secret
reaching the owning step as
{{api_input.other}}is redacted under the step'svalueand not underother. The owner decided (delivery-ws-platform-events005 (I)) that the alias is not added to the rule and the execution copy is never redacted for it; the shape stays a recorded finding (tests/unit/d1226-sensitive-observer-copies.test.jsB1/B3). - A requeued
[REDACTED]is the wrapper's to refuse, not this package's (delivery-ws-platform-events005 (II)). - A malformed declaration is refused.
sensitive_input_fieldsthat is not an array of unique non-empty field names raises[WorkflowOrchestrator] Invalid operation spec - …— the same rule the registration contract (@onlineapps/service-validator-core) applies, a duplicate name included (d.1293) andnullincluded (d.1302: only an ABSENT key means "no declaration", exactly as forretry); skipping it would let the secret travel on with nobody told (automation-gates.md§5). Every reading of an operation's declaration goes through ONE helper (_stepDeclarations) — the specification lookup itself (operationMutatesLookupthrowing, e.g. an unreadableoperations.json),mutates,sensitive_input_fieldsandretry— for the top-level step before its handler runs and for every nested task before dispatch. A refusal or a failed lookup carriesdeclaration: trueand leaves the step of the recipe without a retry policy, wherever in the recipe it was raised — a nested task's refusal included:workflow.failedat once, the handler never ran, and no retry whatever class the classifier gives the error (d.1293/d.1302/d.1309/d.1311). The DLQ reason still follows the class: a refusal is a plainError, which the platform classifier callsUNKNOWN, so the reason isnon_retryable_unknown;no_retry_policyappears only when the class would otherwise be retried (TRANSIENT,TIMEOUT,RATE_LIMIT— e.g. a lookup that fails on a timeout) — § Error classification and retries. - A step taking a secret is never served from the read cache. A cached answer means
the step does not run, and a step that does not run consumes nothing — the scrub would
have nothing to erase. The guard reads the declaration, not
mutates. - The redaction itself is not implemented here.
REDACTED_PLACEHOLDERandredactSensitiveDeepcome from@onlineapps/logger-contract, the single platform implementation every layer that logs, traces or persists an input uses; this package only decides WHEN to call it. - The orchestrator writes no raw step input anywhere:
Task step executedlogs the step, service, operation and a booleaninputResolved, never the input itself.
Error classification and retries
An error is classified by exactly one of two owners, and never by both:
- A failed publish carries its verdict with it.
@onlineapps/mq-client-coreanswers every publish failure withTransientPublishError,PermanentPublishErrororQueueNotFoundError, each holding the decision as a booleanretryable, and the client wraps it inPublishError— once, or twice when the library's own publish retries were spent.publishFailureVerdict()walks the wholecausechain to the transport class and takes that verdict as it stands (PUBLISH_TRANSIENT/PUBLISH_PERMANENT); the injected classifier is not asked (since d.728; the full chain since d.1119). - Everything else is classified by
errorHandler.classifyError(error). There is no fallback toerror.type, no fallback toerror.statusCode, and no status map in this package: the injected@onlineapps/conn-infra-error-handler(overerror-handler-core) is the single classifier of record, and a missing one is refused in the constructor rather than worked around.
WHAT the class decides depends on the phase. Before the step's handler ran, it is the
retry decision below. After the handler returned, it only describes the cause in the
publish_pending record (see What it publishes): a completed step is never retried.
Until 2026-09-13 this branch tested for classify(), a method the connector has never
exposed, so the test was always false and a private status map of its own answered
instead — a second rail that had drifted (it knew nothing of 401, 408 or 429, so a
rate-limited step was never retried). The map is gone rather than repaired
(change-discipline.md, One rail per concern); the status → type table lives with the
classifier, in Error Handling Standard.
Retryable types are TRANSIENT, TIMEOUT and RATE_LIMIT — that list IS in this
package, because it is this package that decides retry vs DLQ. DECLINED is neither:
a rule refused the run, so the step gets _execution.status: 'declined' with declined_at,
nothing enters retry_history and nothing goes to workflow.failed. The refusal codes stay
with the service that throws them; here only the class decides. A retry waits the delay
the step's retry policy names for the attempt that just failed (next section) and
republishes the message to <serviceName>.workflow with the cookbook updated in place. One
exception to a retryable class: TIMEOUT — the attempt deadline the wrapper enforces ran
out — on a step whose operation mutates (mutates: true, the same flag the read cache
reads) is not retried and goes straight to workflow.failed, because a JavaScript handler
cannot be stopped and a second run beside it risks a double write; a reading operation's
TIMEOUT is retried as any other (conf step-error-classification 005). The ERROR line
naming the step, the operation, the service and details.timeout_ms (when the wrapper sends
it) tells the operator to check the write before a requeue. The same holds for an operation
nested in a control-flow step (foreach, steps, switch, fork_join): the error a task
raises carries mutates, step_id and operation of the operation that failed, so the
whole control-flow step goes to workflow.failed, and the ERROR line names the nested step
and the step it is nested in.
Every attempt appends a record to steps[i]._execution.retry_history
(attempt, error, error_ref, error_type, error_code, status_code,
details[], at); error and details are the failure text redacted by value
(§ Sensitive step input, d.1277), in the execution copy as in every observer copy, while
error_type, error_code and status_code come from the original error. Stack traces go
to the log under error_ref, not into the message.
The DLQ entry adds { dlq_entered: true, reason, error_type, error_code,
total_attempts, at }, where reason is max_retries_exceeded,
non_retryable_<type> or timeout_on_mutating_operation — or no_retry_policy when the
class would be retried but there is no policy to retry under: the failure came before any
step was known, or the step's declaration was refused or its lookup failed
(declaration: true, d.1293/d.1311). The class is read first: a class that is not retried
gives non_retryable_<type> with or without a policy — a rejected cookbook and an unknown
current_step are VALIDATION (non_retryable_validation), a refused declaration is a plain
Error the platform classifier calls UNKNOWN (non_retryable_unknown). Either way nothing
is retried: no step or no readable declaration, no policy — a refused declaration is never
retried under the platform default it tried to replace. After a requeue the
attempt counter restarts from the last
requeued record.
Step retry policy — how many attempts, and how long between them
Owner decisions: step-error-classification
002 (variant B — per service, progressive) and 004 (the values). Code: src/retryPolicy.js.
The retry window of a step is the policy of its operation, read from the same
operationMutatesLookup record as mutates and sensitive_input_fields:
Platform default — an operation that declares nothing retries under
DEFAULT_RETRY_POLICY: 5 attempts (the first plus four retries) with delays 1 s, 4 s, 16 s, 60 s after attempts 1–4 — dense at first, sparser as the outage lasts, so a source that is briefly unreachable (Meditest, SERVANT) is given a real chance to come back without flooding the broker or the source. The ceiling is 60 s: no delay in any policy may exceed it (MAX_RETRY_DELAY_MS, read from@onlineapps/handler-contractstepLimits(1.2.0); this README only copies the value).Declared per operation — a service writes its own sequence on the operation in
config/service/operations.json, besidemutatesandsensitive_input_fields:"read-requests": { "handler": "handlers/v3/readRequests#readRequests", "mutates": false, "resource_type": null, "bundle_scope": "workspace", "retry": { "max_attempts": 5, "delays_ms": [1000, 4000, 16000, 60000] } }max_attemptsis an integer from 1 toMAX_RETRY_ATTEMPTS= 10 (1= never retry,delays_ms: []);delays_mshas exactlymax_attempts − 1entries, each an integer from 1 toMAX_RETRY_DELAY_MS= 60000 ms; no other key is allowed. Both limits are values of@onlineapps/handler-contractstepLimits(1.2.0) — this README only copies them. The hook hands it on asretry(the wrapper reads it from the record — a wrapper that does not yet forward the key leaves every operation on the platform default). Only an ABSENT key (undefined) means "no declaration";retry: nullis a value and a malformed one. Every shape rule here —nullincluded (d.1289), and the attempt range 1..MAX_RETRY_ATTEMPTSwith it (d.1393, d.1397) — is the one theoperations.jsoncheck of@onlineapps/service-validator-coreapplies (it runs in Tier-1 and CI), and a count above the ceiling is refused on both rails in the same words:retry.max_attempts <N> exceeds MAX_RETRY_ATTEMPTS <ceiling> - Expected: 1..<ceiling> (handler-contract stepLimits; worst chain must stay under the scheduler run timeout). Fix: lower max_attempts or split the step(validator-core carriesretry.max_attemptsas the finding's field and the rest as its reason) — one declaration reads the same on both rails. Neither ceiling is the orchestrator's own:src/retryPolicy.jstakesMAX_RETRY_DELAY_MSandMAX_RETRY_ATTEMPTSfrom@onlineapps/handler-contract, the one owner of the step limits, keeps no copy, and refuses to load when the installed contract does not export both as positive integers (confhandler-contract002 and 003, d.1381, d.1397). The attempt ceiling exists so the worst chain of one step — every attempt at its longest deadline, every delay at its longest — stays under the scheduler run timeout.A malformed declaration is refused by name, before the handler runs — the step goes to
workflow.failedwith[WorkflowOrchestrator] Invalid retry declaration - operation '<op>' of service '<svc>': <rule>. Fix: …in its attempt record. It is never replaced by the default in silence: a service that wanted ten attempts and misspelt a key would otherwise get five and nothing would say so.A control-flow step (
foreach,fork_join) and a hand-off of a step that belongs to another service (a publish the transport called retryable, confstep-publish-failure001) retry under the platform default: there is no operation of this service to declare anything on.Where the policy shows: the
Step failed, attempt n/<max_attempts>line, themax_attemptsof everyprogressevent withstatus: 'retry'(monitoring-events.md), theScheduling retry <n+1> in <delay>msline withdelayas a value, andtotal_attemptsof the DLQ record. Themessage_dlqevent is NOT this policy: it is@onlineapps/mq-client-core's own delivery budget, spent only whenprocessWorkflowMessage()itself throws.Not here, on purpose: a
retrykey in a cookbook step (001 refuses it — it would be a second copy of the platform's Retry column; the recipe validator is to refuse it) and the constructor options of 7.x (RETIRED_RETRY_OPTIONS, refused by name).
Testing
Two tiers, two runners — a npm test pouští oba za sebou, protože regrese je
unit I integration (.claude/rules/service-refactoring.md #4):
npm test # test:unit && test:integration (integrace potřebuje živý broker)Unit (jest.config.js) needs no environment and runs anywhere:
npm run test:unitIntegration (jest.integration.config.js) runs against the live RabbitMQ AND the
live Redis, and is never skipped: missing environment or an unreachable broker aborts
the run in tests/integration/setup.js before a single test is collected. The tier
isolates itself in a throwaway vhost that tests/integration/teardown.js drops
afterwards, so it never touches the shared workflow.* queues of the running stack;
cache entries go under a per-run key prefix (tests/config.js, redis.keyPrefix).
RABBITMQ_HOST=127.0.0.1 RABBITMQ_PORT=33023 RABBITMQ_MGMT_PORT=33024 \
RABBITMQ_USER=guest RABBITMQ_PASS=guest \
REDIS_URL=redis://127.0.0.1:33030 npm run test:integrationThe values come from api/infra/.env (RABBITMQ_PORT, RABBITMQ_MGMT_PORT,
RABBITMQ_DEFAULT_USER, RABBITMQ_DEFAULT_PASS) and from
api/config/env-active/shared.env (REDIS_URL, whose port is the host-side
REDIS_PORT of the stack). The Redis endpoint is ONE value, never a host beside a
port: @onlineapps/conn-base-cache refuses host / port by name. The user needs the
management tag, because creating and dropping the vhost goes through the management
API. Every key the tier requires is listed in tests/config.js
(REQUIRED_ENV_KEYS) and a missing one fails the run by name.
Tiché atrapy sousedů (logger, monitoring), které konstruktory konektorů od pinů
vlny vyžadují, mají jedno místo: tests/helpers/silentDoubles.js.
Documentation
- Connectors Architecture
- Workflow Architecture
- Workflow message contract
- Cookbook variable references
- Error Handling Standard
- Generated API reference:
API.md(npm run docs)
Release history lives in git (git log -- shared/connector/conn-orch-orchestrator),
not in a hand-kept table here.
