Skip to content

Commit d3347f0

Browse files
committed
refactor(service-automation): move 42 engine bodies into five seam modules
Move-only. The bodies of 42 AutomationEngine methods move unedited into five new modules: dispatch-claims.ts (claiming, settling and reading a dispatch, minting a run id, releasing a suspension; 7 bodies), flow-definitions.ts (canonicalising, unregistering, refusing and rolling back a flow, its runtime states and trigger bindings, and its function, connector and credential surfaces; 12), subflow-guards.ts (finding and refusing what reaches a disabled subflow; 11), consumed-suspension-restore.ts (resolving, restoring, peeking at and inspecting a consumed suspension; 6) and node-text-rendering.ts (the node-type vocabulary checks, a failed node's error variable, and refusal and flow-text rendering; 6). Each method keeps its name, docblock, signature and position in the class and calls its body with a host literal holding exactly the members the body reads; six bodies read none and are called directly. Each async stub drops async and returns the promise the moved function makes. Fields assigned only at their declaration or in the constructor go by value. Six fields a method reassigns go through getters. The four warned-once flags a moved body sets go through get/set pairs, so each write lands on the engine. claimAdvance, validateNodeInputSchemas, refuseInvalidScreenInput and buildSubflowResumeSignal stay in the class, because each reads a name documented as private to engine.ts. pullConnectorSource stays too: a second top-level function of that name would make the bundler rename the public pullConnectorSource export. Seven helpers the moved bodies read gain export in place; index.ts re-exports none of them. The imports only moved bodies read move with them. The ENGINE_SOURCES grep pins read the new modules too. Claude-Session: https://claude.ai/code/session_01Mnj4nkWuhJ18xEdZvb2cjE Co-Authored-By: Claude <noreply@anthropic.com>
1 parent ea6fe00 commit d3347f0

7 files changed

Lines changed: 1634 additions & 772 deletions

File tree

Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The consumed-suspension restore of {@link AutomationEngine}: how a consumed
5+
* suspension's witnesses are resolved, and how a consumed suspension is
6+
* restored along its chain, peeked at or inspected.
7+
*
8+
* [#25222] Slice 7 of the `engine.ts` split, move-only. Each function here is
9+
* the body of the `AutomationEngine` method of the same name, moved unedited.
10+
* The class keeps that method (its name, docblock and position are in the
11+
* published `.d.ts`) and calls the body with a {@link
12+
* ConsumedSuspensionRestoreHost} literal holding exactly the members the body
13+
* reads. An async method's stub is no longer `async`: it returns the promise
14+
* the moved function makes.
15+
*/
16+
17+
import { describeThrownForLog } from './thrown-cause-diagnostics.js';
18+
// The values below (`MAX_RESTORE_CHAIN_HOPS`, `chainEntryOf` and
19+
// `nestedChildRunId`) are read only inside the function bodies, at call time,
20+
// never while a module is evaluating, so the import cycle with ./engine.js is
21+
// safe under ESM live bindings; the tsup bundle is one file and has no cycle.
22+
import {
23+
MAX_RESTORE_CHAIN_HOPS,
24+
chainEntryOf,
25+
nestedChildRunId,
26+
type AutomationEngine,
27+
type ChainRestoreEntry,
28+
type ConsumedSuspension,
29+
type ConsumedSuspensionDropNotice,
30+
type ConsumedSuspensionInspection,
31+
type RunRecord,
32+
type SuspensionRestoreResult,
33+
} from './engine.js';
34+
35+
/**
36+
* The `AutomationEngine` members the moved bodies read, each typed as the class
37+
* member itself, so a renamed or respelled member is a compile error. Each
38+
* function takes the `Pick` of the members its own body reads, and the class
39+
* passes exactly those. Methods go as late-bound closures, so a spy or test
40+
* double set on the instance is still the one called. A field the class assigns
41+
* only at its declaration or in its constructor goes by value, so the value
42+
* passed is the field, including where an async body reads it after an `await`.
43+
* `store` goes through a getter, because `setSuspendedRunStore` reassigns it:
44+
* each read in the body reads the engine's current value, as it did through
45+
* `this`.
46+
*/
47+
export interface ConsumedSuspensionRestoreHost {
48+
readonly consumedSuspensions: AutomationEngine['consumedSuspensions'];
49+
readonly rowSupersedesJournal: AutomationEngine['rowSupersedesJournal'];
50+
readonly resolveRestoreChain: AutomationEngine['resolveRestoreChain'];
51+
readonly restoreOneConsumedSuspension: AutomationEngine['restoreOneConsumedSuspension'];
52+
readonly peekConsumedSuspension: AutomationEngine['peekConsumedSuspension'];
53+
readonly loadSuspendedRunStrict: AutomationEngine['loadSuspendedRunStrict'];
54+
readonly store: AutomationEngine['store'];
55+
readonly resolveConsumedSuspensionWitnesses: AutomationEngine['resolveConsumedSuspensionWitnesses'];
56+
readonly logger: AutomationEngine['logger'];
57+
}
58+
59+
/** The body of {@link AutomationEngine.rowSupersedesJournal}, moved unedited; that method's docblock is its contract. */
60+
export function rowSupersedesJournal(
61+
hot: ConsumedSuspension,
62+
rowPause: { nodeId?: string; correlation?: string },
63+
): boolean {
64+
const samePause =
65+
hot.run.nodeId === rowPause.nodeId &&
66+
(hot.run.correlation ?? undefined) === (rowPause.correlation ?? undefined);
67+
if (samePause) return false;
68+
return hot.persisted === 'landed';
69+
}
70+
71+
/** The body of {@link AutomationEngine.resolveConsumedSuspensionWitnesses}, moved unedited; that method's docblock is its contract. */
72+
export function resolveConsumedSuspensionWitnesses(
73+
this: Pick<ConsumedSuspensionRestoreHost, 'consumedSuspensions' | 'rowSupersedesJournal'>,
74+
runId: string,
75+
terminal: RunRecord | null,
76+
): {
77+
consumed?: ConsumedSuspension;
78+
witness?: 'journal' | 'durable';
79+
dropped?: ConsumedSuspensionDropNotice;
80+
/** The hot copy describes a pause the run has since LEFT. */
81+
staleHot: boolean;
82+
} {
83+
const hot = this.consumedSuspensions.get(runId);
84+
if (!terminal) {
85+
return hot ? { consumed: hot, witness: 'journal', staleHot: false } : { staleHot: false };
86+
}
87+
if (terminal.consumedSuspension) {
88+
const durable: ConsumedSuspension = {
89+
run: terminal.consumedSuspension,
90+
consumedAt: terminal.finishedAt ?? terminal.startedAt,
91+
error: terminal.error ?? '',
92+
};
93+
if (hot && !this.rowSupersedesJournal(hot, durable.run)) {
94+
return { consumed: hot, witness: 'journal', staleHot: false };
95+
}
96+
return { consumed: durable, witness: 'durable', staleHot: hot !== undefined };
97+
}
98+
if (terminal.consumedSuspensionDropped) {
99+
const dropped = terminal.consumedSuspensionDropped;
100+
if (hot && !this.rowSupersedesJournal(hot, dropped)) {
101+
return { consumed: hot, witness: 'journal', dropped, staleHot: false };
102+
}
103+
return { dropped, staleHot: hot !== undefined };
104+
}
105+
if (hot && hot.persisted !== 'landed') {
106+
// The row predates this strand — this process's own write for it
107+
// never reached the store (in flight, or failed and reported at
108+
// `error`). The store's silence says nothing.
109+
return { consumed: hot, witness: 'journal', staleHot: false };
110+
}
111+
// A later terminal record with no snapshot and no drop notice:
112+
// completed, cancelled or cascade-failed after any hot copy was
113+
// taken. Stale by definition.
114+
return { staleHot: hot !== undefined };
115+
}
116+
117+
/** The body of {@link AutomationEngine.restoreConsumedSuspension}, moved unedited; that method's docblock is its contract. */
118+
export async function restoreConsumedSuspension(
119+
this: Pick<ConsumedSuspensionRestoreHost, 'resolveRestoreChain' | 'restoreOneConsumedSuspension'>,
120+
runId: string,
121+
options?: { requestedBy?: string; reason?: string },
122+
): Promise<SuspensionRestoreResult> {
123+
// [#15222] Resolve the nested chain FIRST, read-only. A flat run finds
124+
// nothing here and takes the per-run call below unchanged — same
125+
// guards, same answer, and a result with no `chain` key at all.
126+
//
127+
// A nested one is the whole of this card: the ancestors' pauses were
128+
// consumed by the same cascade and journalled by
129+
// {@link failSuspendedRun}, and re-arming only the run the operator
130+
// named would put the deployment back in the condition the verb exists
131+
// to leave — a leaf that completes into an ancestor which never
132+
// continues. So the chain is one unit of repair, and this is the call
133+
// that makes it one.
134+
const { below, above } = await this.resolveRestoreChain(runId);
135+
if (below.length === 0 && above.length === 0) {
136+
return this.restoreOneConsumedSuspension(runId, options);
137+
}
138+
// DEEPEST FIRST, and the order IS the guarantee: an ancestor becomes
139+
// resumable only after the run it is parked awaiting is parked again,
140+
// so a resume arriving mid-repair delegates into a live child instead
141+
// of continuing past a nested node whose child is terminal.
142+
//
143+
// Every member goes through the SAME per-run call — its own
144+
// `restoring` claim, its own strict live-suspension read, its own
145+
// two-witness read, its own durable park. So the verb's idempotence
146+
// and the #14333 advance claim hold PER RUN in the chain rather than
147+
// once for the chain, and a second chain restore finds every member
148+
// parked and answers `RUN_SUSPENDED` without minting a second pause
149+
// anywhere.
150+
const chain: ChainRestoreEntry[] = [];
151+
for (const memberId of below) {
152+
chain.push(chainEntryOf(memberId, await this.restoreOneConsumedSuspension(memberId, options, runId)));
153+
}
154+
const own = await this.restoreOneConsumedSuspension(runId, options);
155+
chain.push(chainEntryOf(runId, own));
156+
for (const memberId of above) {
157+
chain.push(chainEntryOf(memberId, await this.restoreOneConsumedSuspension(memberId, options, runId)));
158+
}
159+
// The six fields above `chain` keep describing the run the caller
160+
// NAMED, wherever in the chain it sits — a consumer that never heard
161+
// of nesting reads exactly what it always read.
162+
return { ...own, chain };
163+
}
164+
165+
/** The body of {@link AutomationEngine.resolveRestoreChain}, moved unedited; that method's docblock is its contract. */
166+
export async function resolveRestoreChain(this: Pick<ConsumedSuspensionRestoreHost, 'peekConsumedSuspension'>, runId: string): Promise<{ below: string[]; above: string[] }> {
167+
const below: string[] = [];
168+
const above: string[] = [];
169+
const self = await this.peekConsumedSuspension(runId);
170+
if (!self) return { below, above };
171+
172+
let cursor = self;
173+
for (let hops = 0; hops < MAX_RESTORE_CHAIN_HOPS; hops++) {
174+
const childRunId = nestedChildRunId(cursor.run.correlation);
175+
if (childRunId === undefined || childRunId === runId || below.includes(childRunId)) break;
176+
const child = await this.peekConsumedSuspension(childRunId, runId);
177+
if (!child) break;
178+
below.unshift(childRunId);
179+
cursor = child;
180+
}
181+
182+
cursor = self;
183+
for (let hops = 0; hops < MAX_RESTORE_CHAIN_HOPS; hops++) {
184+
const parentRunId = (cursor.run.context as Record<string, unknown> | undefined)?.$parentRunId;
185+
if (typeof parentRunId !== 'string' || !parentRunId) break;
186+
if (parentRunId === runId || above.includes(parentRunId)) break;
187+
const parent = await this.peekConsumedSuspension(parentRunId, runId);
188+
if (!parent) break;
189+
above.push(parentRunId);
190+
cursor = parent;
191+
}
192+
return { below, above };
193+
}
194+
195+
/** The body of {@link AutomationEngine.peekConsumedSuspension}, moved unedited; that method's docblock is its contract. */
196+
export async function peekConsumedSuspension(this: Pick<ConsumedSuspensionRestoreHost, 'loadSuspendedRunStrict' | 'store' | 'resolveConsumedSuspensionWitnesses' | 'logger'>, runId: string, chainOf?: string): Promise<ConsumedSuspension | undefined> {
197+
try {
198+
if (await this.loadSuspendedRunStrict(runId)) return undefined;
199+
const terminal = this.store?.loadTerminal ? await this.store.loadTerminal(runId) : null;
200+
return this.resolveConsumedSuspensionWitnesses(runId, terminal).consumed;
201+
} catch (err) {
202+
if (chainOf !== undefined) {
203+
// #6299 — the driver's own text rides the structured slot.
204+
// #4632 verdict: FUNCTIONAL — the repair is visibly short (the
205+
// `chain` this call returns names only what it reached) and the
206+
// remedy is to re-issue, which is safe per run.
207+
this.logger.warn(
208+
`[automation] restoreConsumedSuspension('${chainOf}') could not read run '${runId}' while ` +
209+
`walking its nested chain, so the walk STOPPED there and nothing beyond it was re-armed ` +
210+
`— the repair this call reports is partial. Nothing was written for that run. Fix the ` +
211+
`store failure in this record's meta, then re-issue the restore: it is idempotent per ` +
212+
`run and puts back only what is still missing.`,
213+
describeThrownForLog(err),
214+
);
215+
}
216+
return undefined;
217+
}
218+
}
219+
220+
/** The body of {@link AutomationEngine.inspectConsumedSuspension}, moved unedited; that method's docblock is its contract. */
221+
export async function inspectConsumedSuspension(this: Pick<ConsumedSuspensionRestoreHost, 'loadSuspendedRunStrict' | 'store' | 'resolveConsumedSuspensionWitnesses'>, runId: string): Promise<ConsumedSuspensionInspection> {
222+
// Already resumable? STRICT read — a store outage throws through.
223+
const live = await this.loadSuspendedRunStrict(runId);
224+
if (live) return { repairable: false, runId, reason: 'RUN_SUSPENDED', nodeId: live.nodeId };
225+
226+
let terminal: RunRecord | null = null;
227+
if (this.store?.loadTerminal) terminal = await this.store.loadTerminal(runId);
228+
229+
const { consumed, witness, dropped } = this.resolveConsumedSuspensionWitnesses(runId, terminal);
230+
if (consumed && witness) {
231+
return {
232+
repairable: true,
233+
runId,
234+
flowName: consumed.run.flowName,
235+
nodeId: consumed.run.nodeId,
236+
...(consumed.run.correlation !== undefined ? { correlation: consumed.run.correlation } : {}),
237+
witness,
238+
consumedAt: consumed.consumedAt,
239+
};
240+
}
241+
if (dropped) return { repairable: false, runId, reason: 'SNAPSHOT_DROPPED', dropped };
242+
return { repairable: false, runId, reason: 'NO_CONSUMED_SUSPENSION' };
243+
}

0 commit comments

Comments
 (0)