@protobase/workflows 0.76.3 → 0.77.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -35,5 +35,18 @@ const reachable = (machine) => {
35
35
  }
36
36
  return seen;
37
37
  };
38
+ /** The states reached from `start` along the edges, `start` itself included. */
39
+ const reachedFrom = (machine, start) => {
40
+ const seen = /* @__PURE__ */ new Set();
41
+ const stack = [start];
42
+ while (stack.length > 0) {
43
+ const name = stack.pop();
44
+ const state = machine.States[name];
45
+ if (seen.has(name) || !state) continue;
46
+ seen.add(name);
47
+ stack.push(...edges(state).map((edge) => edge.target));
48
+ }
49
+ return seen;
50
+ };
38
51
  //#endregion
39
- export { edges, reachable };
52
+ export { edges, reachable, reachedFrom };
@@ -48,6 +48,9 @@ export declare const definitionSchema: {
48
48
  readonly connections: {
49
49
  readonly $ref: "#/definitions/connections";
50
50
  };
51
+ readonly trace: {
52
+ readonly enum: readonly ["all", "failed", "none"];
53
+ };
51
54
  };
52
55
  };
53
56
  readonly connections: {
@@ -127,7 +127,12 @@ const definitionSchema = {
127
127
  properties: {
128
128
  trigger: { $ref: "#/definitions/trigger" },
129
129
  stateMachine: { $ref: "#/definitions/stateMachine" },
130
- connections: { $ref: "#/definitions/connections" }
130
+ connections: { $ref: "#/definitions/connections" },
131
+ trace: { enum: [
132
+ "all",
133
+ "failed",
134
+ "none"
135
+ ] }
131
136
  }
132
137
  },
133
138
  connections: {
@@ -90,12 +90,14 @@ export type Trigger = {
90
90
  [type: `${string}:${string}`]: Record<string, unknown>;
91
91
  };
92
92
  /**
93
- * A workflow definition: its trigger, the state machine a run runs from `StartAt`, and the connected account each
94
- * connection `<plugin>:<connection>` of its types signs in with, by the account's id.
93
+ * A workflow definition: its trigger, the state machine a run runs from `StartAt`, the connected account each
94
+ * connection `<plugin>:<connection>` of its types signs in with, by the account's id, and which of its runs keep a
95
+ * trace (`all`, `failed` or `none`), when it says, over the app's default.
95
96
  */
96
97
  export type Definition = {
97
98
  trigger: Trigger;
98
99
  stateMachine: StateMachine;
99
100
  connections?: Record<string, string>;
101
+ trace?: 'all' | 'failed' | 'none';
100
102
  };
101
103
  //#endregion
@@ -1,4 +1,4 @@
1
- import { edges } from "./graph.js";
1
+ import { reachedFrom } from "./graph.js";
2
2
  //#region src/definition/visible.ts
3
3
  const passedOn = (state) => {
4
4
  const own = Object.keys("Assign" in state && state.Assign || {});
@@ -23,18 +23,6 @@ const passedOn = (state) => {
23
23
  });
24
24
  return along;
25
25
  };
26
- const reachedFrom = (machine, start) => {
27
- const seen = /* @__PURE__ */ new Set();
28
- const stack = [start];
29
- while (stack.length > 0) {
30
- const name = stack.pop();
31
- const state = machine.States[name];
32
- if (seen.has(name) || !state) continue;
33
- seen.add(name);
34
- stack.push(...edges(state).map((edge) => edge.target));
35
- }
36
- return seen;
37
- };
38
26
  /**
39
27
  * The variables each state of a machine may read: those of the outer scopes, and each one assigned on an edge some path
40
28
  * from `StartAt` takes before it. A state's own Assign takes effect from the next state on, and only along the edges
package/dist/index.d.ts CHANGED
@@ -10,8 +10,9 @@ import { ErrorOutput, StepError } from "./run/errors.js";
10
10
  import { Redactor, redacted, secretRedactor, shortestSecret } from "./run/redact.js";
11
11
  import { KeyShape } from "./run/cache/cache-key.js";
12
12
  import { CacheCall, CacheEntry, CacheIdentity, StepCacheStore } from "./run/cache/cache-port.js";
13
- import { LoadedRun, RunChange, RunStatus, RunStore, SavedStep, SegmentQueue, StepLog, StepRecord, StepStatus, TaskContext, TaskHandler, TaskHandlers } from "./run/port.js";
14
- import { EarlierStep, keptAssigned, rerunFromSteps, rerunSteps, resultRead } from "./run/rerun.js";
13
+ import { Checkpoint, LoadedRun, ReplayedStep, RunChange, RunStatus, RunStore, SegmentQueue, StepLog, StepRecord, StepStatus, TaskContext, TaskHandler, TaskHandlers, TraceMode, TraceSink } from "./run/port.js";
14
+ import { EarlierCheckpoint, keptAssigned, rerunCheckpoint, rerunProblem, resultRead } from "./run/rerun.js";
15
+ import { RerunFrom, rerunFrom } from "./run/rerun-from.js";
15
16
  import { heldBackLog } from "./run/replay.js";
16
17
  import { Runner, RunnerPort, createRunner } from "./run/runner.js";
17
18
  import { SegmentInput, runSegment } from "./run/segment.js";
@@ -21,4 +22,4 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
21
22
  import { TypeEntry, Unavailable, typeList } from "./plugin/type-list.js";
22
23
  import { ConnectionSupport, connectionUnavailable } from "./plugin/connection-availability.js";
23
24
  import { CatalogEntry, TypeCatalog, typeCatalog } from "./plugin/type-catalog.js";
24
- export { type CacheCall, type CacheEntry, type CacheIdentity, type CatalogEntry, type Catcher, type CheckOptions, type ChoiceRule, type ChoiceState, type ConnectionSupport, type Definition, type EarlierStep, type ErrorOutput, type KeyShape, type LoadedPlugin, type LoadedRun, type Machine, type MapState, type Problem, type Redactor, type Retrier, type RunChange, type RunStatus, type RunStore, type Runner, type RunnerPort, type SavedStep, type SegmentInput, type SegmentQueue, type State, type StateMachine, type StepCacheStore, StepError, type StepLog, type StepRecord, type StepStatus, type StepWiring, type TaskContext, type TaskHandler, type TaskHandlers, type TaskState, type Trigger, type TriggerCheck, type TypeCatalog, type TypeEntry, type Unavailable, checkDefinition, connectionUnavailable, createRunner, definitionSchema, heldBackLog, keptAssigned, limits, loadPlugins, nestingDepth, problemText, redacted, rerunFromSteps, rerunSteps, resultRead, runSegment, secretRedactor, shortestSecret, stepHandlers, triggerChecks, typeCatalog, typeList, usedConnections };
25
+ export { type CacheCall, type CacheEntry, type CacheIdentity, type CatalogEntry, type Catcher, type CheckOptions, type Checkpoint, type ChoiceRule, type ChoiceState, type ConnectionSupport, type Definition, type EarlierCheckpoint, type ErrorOutput, type KeyShape, type LoadedPlugin, type LoadedRun, type Machine, type MapState, type Problem, type Redactor, type ReplayedStep, type RerunFrom, type Retrier, type RunChange, type RunStatus, type RunStore, type Runner, type RunnerPort, type SegmentInput, type SegmentQueue, type State, type StateMachine, type StepCacheStore, StepError, type StepLog, type StepRecord, type StepStatus, type StepWiring, type TaskContext, type TaskHandler, type TaskHandlers, type TaskState, type TraceMode, type TraceSink, type Trigger, type TriggerCheck, type TypeCatalog, type TypeEntry, type Unavailable, checkDefinition, connectionUnavailable, createRunner, definitionSchema, heldBackLog, keptAssigned, limits, loadPlugins, nestingDepth, problemText, redacted, rerunCheckpoint, rerunFrom, rerunProblem, resultRead, runSegment, secretRedactor, shortestSecret, stepHandlers, triggerChecks, typeCatalog, typeList, usedConnections };
package/dist/index.js CHANGED
@@ -6,7 +6,8 @@ import { nestingDepth } from "./nesting.js";
6
6
  import { checkDefinition } from "./definition/check-definition.js";
7
7
  import { StepError } from "./run/errors.js";
8
8
  import { redacted, secretRedactor, shortestSecret } from "./run/redact.js";
9
- import { keptAssigned, rerunFromSteps, rerunSteps, resultRead } from "./run/rerun.js";
9
+ import { keptAssigned, rerunCheckpoint, rerunProblem, resultRead } from "./run/rerun.js";
10
+ import { rerunFrom } from "./run/rerun-from.js";
10
11
  import { heldBackLog } from "./run/replay.js";
11
12
  import { runSegment } from "./run/segment.js";
12
13
  import { createRunner } from "./run/runner.js";
@@ -16,4 +17,4 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
16
17
  import { typeList } from "./plugin/type-list.js";
17
18
  import { connectionUnavailable } from "./plugin/connection-availability.js";
18
19
  import { typeCatalog } from "./plugin/type-catalog.js";
19
- export { StepError, checkDefinition, connectionUnavailable, createRunner, definitionSchema, heldBackLog, keptAssigned, limits, loadPlugins, nestingDepth, problemText, redacted, rerunFromSteps, rerunSteps, resultRead, runSegment, secretRedactor, shortestSecret, stepHandlers, triggerChecks, typeCatalog, typeList, usedConnections };
20
+ export { StepError, checkDefinition, connectionUnavailable, createRunner, definitionSchema, heldBackLog, keptAssigned, limits, loadPlugins, nestingDepth, problemText, redacted, rerunCheckpoint, rerunFrom, rerunProblem, resultRead, runSegment, secretRedactor, shortestSecret, stepHandlers, triggerChecks, typeCatalog, typeList, usedConnections };
package/dist/limits.d.ts CHANGED
@@ -22,7 +22,7 @@ export declare const limits: {
22
22
  readonly mapItems: 10000;
23
23
  /** Steps one run may take, every attempt and every Map item's steps counted. */
24
24
  readonly runSteps: 50000;
25
- /** The size of each value a step saves (its input, output and variables), as JSON. */
25
+ /** The size of each value a step keeps in place (its input, output and variables), as JSON. */
26
26
  readonly valueBytes: number;
27
27
  /** Log lines one step keeps, and the length of each. */
28
28
  readonly logLines: 100;
package/dist/limits.js CHANGED
@@ -22,8 +22,8 @@ const limits = {
22
22
  mapItems: 1e4,
23
23
  /** Steps one run may take, every attempt and every Map item's steps counted. */
24
24
  runSteps: 5e4,
25
- /** The size of each value a step saves (its input, output and variables), as JSON. */
26
- valueBytes: 1048576,
25
+ /** The size of each value a step keeps in place (its input, output and variables), as JSON. */
26
+ valueBytes: 262144,
27
27
  /** Log lines one step keeps, and the length of each. */
28
28
  logLines: 100,
29
29
  logLineLength: 1e3,
@@ -33,7 +33,7 @@ const limits = {
33
33
  /** How long one segment runs steps before it hands the rest of the run to the next segment. */
34
34
  segmentMs: 6e4,
35
35
  /** A run's input: its size as JSON and how deeply its arrays and objects nest. */
36
- inputBytes: 1048576,
36
+ inputBytes: 262144,
37
37
  inputDepth: 64,
38
38
  /** A cached step result: the longest it serves, how long one a workflow forced on serves, its size as JSON, and the entries one step type keeps per tenant. */
39
39
  cacheMaxSeconds: 2592e3,
@@ -6,17 +6,24 @@ import { TaskCache } from "./cache/cache-port.js";
6
6
  * catcher went on elsewhere) or `failed` (nothing caught it, so its scope failed).
7
7
  */
8
8
  export type StepStatus = 'succeeded' | 'retrying' | 'caught' | 'failed';
9
- /** What the runner reads of a saved step to know where its scope stands. */
10
- export type SavedStep = {
11
- /** The scope the step ran in: `''` for the run itself, `Each.3[0]` for item 0 of the Map `Each` that was step 3. */
9
+ export type StepLog = {
10
+ at: string;
11
+ message: string;
12
+ };
13
+ /**
14
+ * One step as a run's trace keeps it: its scope (`''` for the run itself, `Each.3[0]` for item 0 of the Map `Each` that
15
+ * was step 3), its number within the scope, its state, type, try, status, input, output, assigned variables, the state it
16
+ * goes on to, logs and timing, with every secret redacted. `recorded` when the step made a checkpoint of its own.
17
+ */
18
+ export type StepRecord = {
12
19
  scope: string;
13
- /** The step's number within its scope, from 0: with the scope, the step's key, saved once. */
14
20
  seq: number;
15
21
  state: string;
22
+ type: string;
16
23
  status: StepStatus;
17
24
  attempt: number;
25
+ input?: unknown;
18
26
  output?: unknown;
19
- /** The variables the step assigned. */
20
27
  assigned?: Record<string, unknown>;
21
28
  /** The state its scope goes on to; `null` when the scope ended or failed, or for a try that is retried. */
22
29
  next: string | null;
@@ -24,18 +31,45 @@ export type SavedStep = {
24
31
  resumeAt?: Date | null;
25
32
  error?: string | null;
26
33
  cause?: string | null;
27
- };
28
- export type StepLog = {
29
- at: string;
30
- message: string;
31
- };
32
- /** All a step records: what the runner reads, and its type, input, logs and timing, with every secret redacted. */
33
- export type StepRecord = SavedStep & {
34
- type: string;
35
- input?: unknown;
36
34
  logs: StepLog[];
37
35
  startedAt: Date;
38
36
  finishedAt: Date;
37
+ recorded: boolean;
38
+ };
39
+ /** What a replay takes of a step of the run it replays, as that run's trace keeps it. */
40
+ export type ReplayedStep = Pick<StepRecord, 'scope' | 'seq' | 'state' | 'status' | 'attempt' | 'output' | 'error' | 'cause'>;
41
+ /**
42
+ * Where one scope stands, as a checkpoint saves it: all a later segment needs to take the scope up without running its
43
+ * earlier steps again. It names the step that made it, and holds the state the scope goes on to with that state's input
44
+ * (or the scope's output once it ended), its variables, the try and earlier errors of a state being retried, and the
45
+ * clock its next steps read as `$now`.
46
+ */
47
+ export type Checkpoint = {
48
+ scope: string;
49
+ /** The number of the step that made it, within its scope: with the scope, its key. */
50
+ seq: number;
51
+ /** The step that made it: its state, type and status. */
52
+ state: string;
53
+ type: string;
54
+ status: StepStatus;
55
+ /** When that step ended: for a Task, when its result was fetched. */
56
+ fetchedAt: Date;
57
+ /** The state the scope goes on to, which may be the same one retried; `null` once the scope ended. */
58
+ next: string | null;
59
+ /** The next state's input, or the scope's output once it ended. */
60
+ value?: unknown;
61
+ variables: Record<string, unknown>;
62
+ /** The try of the next state, from 1, and the errors of its earlier tries. */
63
+ attempt: number;
64
+ failures: string[];
65
+ /** The visits of each state the scope began so far, which a replay matches its steps by. */
66
+ visits: Record<string, number>;
67
+ /** The next state may not run before this time. */
68
+ resumeAt?: Date | null;
69
+ /** What `$now` gives the scope's next steps: the time of its last recorded step, its last wait's end, or the run's start. */
70
+ clock: Date;
71
+ /** The `seq` of the scope's checkpoint the segment took it up from, -1 for none: a save is refused when a newer one is there. */
72
+ after: number;
39
73
  };
40
74
  /** What a step type's handler gets beside its arguments. */
41
75
  export type TaskContext = {
@@ -60,6 +94,10 @@ export type TaskContext = {
60
94
  /**
61
95
  * A step type, which a Task names as its `Resource`: it takes the Task's evaluated `Arguments` and returns its result.
62
96
  * It throws a `StepError` to fail with an error name of its own; any other error is `States.TaskFailed`.
97
+ *
98
+ * A call changes the world, such as a mail sent or a record written, unless `writes` says it does not with these
99
+ * arguments: a call that changes the world is recorded, so it never happens twice in a run, and a read is done again
100
+ * after a crash before the next checkpoint.
63
101
  */
64
102
  export type TaskHandler = ((args: unknown, context: TaskContext) => Promise<unknown>) & {
65
103
  /** Whether a call with these arguments changes the outside world, never throwing; a replay calls none that does. Absent or anything but `false`: it does. */
@@ -67,16 +105,17 @@ export type TaskHandler = ((args: unknown, context: TaskContext) => Promise<unkn
67
105
  };
68
106
  /** The interpreter's back end: the step types by the name a Task's `Resource` gives. */
69
107
  export type TaskHandlers = Readonly<Record<string, TaskHandler>>;
70
- /** A run as the runner loads it: its pinned definition, its input and when it started. */
108
+ /** A run as the runner loads it: its pinned definition, its input, when it started, and its own trace setting, if any. */
71
109
  export type LoadedRun = {
72
110
  id: string;
73
111
  definition: Definition;
74
112
  input: unknown;
75
113
  status: RunStatus;
76
114
  startedAt: Date;
115
+ trace?: TraceMode | null;
77
116
  /**
78
117
  * The run this one replays, with the definition it ran: its steps that write are not called but give what that
79
- * run's steps gave; null when that run is gone, so they give nothing. Absent: no replay.
118
+ * run's steps gave, as its trace keeps them; null when that run is gone, so they give nothing. Absent: no replay.
80
119
  */
81
120
  replayOf?: {
82
121
  id: string;
@@ -99,23 +138,40 @@ export type RunChange = {
99
138
  cause: string;
100
139
  };
101
140
  /**
102
- * Where runs and their steps are kept, in the database or transaction `Db` the caller gives: the first part of the
141
+ * Where runs and their checkpoints are kept, in the database or transaction `Db` the caller gives: the first part of the
103
142
  * runner's port.
104
143
  */
105
144
  export type RunStore<Db> = {
106
145
  load(db: Db, runId: string): Promise<LoadedRun | undefined>;
107
- /** Every step the run saved, in each scope's order; the record's input and logs are not needed. */
108
- steps(db: Db, runId: string): Promise<SavedStep[]>;
146
+ /** The latest checkpoint of each scope of the run. */
147
+ checkpoints(db: Db, runId: string): Promise<Checkpoint[]>;
109
148
  /**
110
- * Saves steps in one guarded statement: false when any of their scopes and seqs is taken already, and those are left
111
- * as the other segment saved them.
149
+ * Saves checkpoints all or none, each replacing its scope's earlier ones: false when any scope has one newer than
150
+ * the one it follows (`after`), and then none is saved.
112
151
  */
113
- save(db: Db, runId: string, steps: readonly StepRecord[]): Promise<boolean>;
114
- /** Changes the run unless it has ended already. */
152
+ save(db: Db, runId: string, checkpoints: readonly Checkpoint[]): Promise<boolean>;
153
+ /** Changes the run unless it has ended already; a run that ends drops its checkpoints. */
115
154
  update(db: Db, runId: string, change: RunChange): Promise<void>;
116
155
  };
117
156
  /** The jobs queue: the second part of the port, which runs a segment of the run at `at`, or as soon as it can. */
118
157
  export type SegmentQueue<Db> = {
119
158
  schedule(db: Db, runId: string, at?: Date): Promise<void>;
120
159
  };
160
+ /** Which runs keep a trace: every run, only those that fail, or none. */
161
+ export type TraceMode = NonNullable<Definition['trace']>;
162
+ /**
163
+ * Where runs' traces go, outside the database: each segment hands over the steps it ran, with every input and output,
164
+ * before each checkpoint after them is saved and once it stops. `write` resolves once they are kept, and on the segment that ended the run (`ended`)
165
+ * once the whole trace is, so the runner queues the next segment or ends the run only then and no part comes after the
166
+ * trace is joined; it never rejects, since a trace that cannot be written does not stop the run. With `failed`, a run
167
+ * that succeeded keeps no trace. `read` gives an ended run's steps, as a replay of it takes them: undefined when it kept
168
+ * no trace.
169
+ */
170
+ export type TraceSink = {
171
+ write(runId: string, steps: readonly StepRecord[], segment: {
172
+ mode: TraceMode;
173
+ ended?: 'succeeded' | 'failed';
174
+ }): Promise<void>;
175
+ read(runId: string): Promise<readonly StepRecord[] | undefined>;
176
+ };
121
177
  //#endregion
@@ -1,14 +1,19 @@
1
1
  //#region src/run/position.ts
2
- const startPosition = (machine, input) => ({
2
+ const startPosition = (machine, input, clock) => ({
3
3
  kind: "at",
4
4
  seq: 0,
5
5
  state: machine.StartAt,
6
6
  input,
7
7
  variables: {},
8
8
  attempt: 1,
9
- failures: []
9
+ failures: [],
10
+ visits: {},
11
+ clock
10
12
  });
11
- /** The position after a saved step. */
13
+ /**
14
+ * The position after a step. A recorded step moves the clock to when it ended, and a step with a time to go on at moves
15
+ * it to that time; any other step leaves it, so a step run again after a crash reads the same `$now`.
16
+ */
12
17
  const advance = (position, step) => {
13
18
  if (position.kind !== "at") return position;
14
19
  const seq = step.seq + 1;
@@ -16,6 +21,11 @@ const advance = (position, step) => {
16
21
  ...position.variables,
17
22
  ...step.assigned
18
23
  };
24
+ const clock = step.resumeAt ?? (step.recorded ? step.finishedAt : position.clock);
25
+ const visits = step.attempt === 1 ? {
26
+ ...position.visits,
27
+ [step.state]: (position.visits[step.state] ?? 0) + 1
28
+ } : position.visits;
19
29
  if (step.status === "failed") return {
20
30
  kind: "failed",
21
31
  seq,
@@ -26,8 +36,10 @@ const advance = (position, step) => {
26
36
  ...position,
27
37
  seq,
28
38
  variables,
39
+ visits,
29
40
  attempt: position.attempt + 1,
30
41
  failures: [...position.failures, step.error ?? ""],
42
+ clock,
31
43
  ...step.resumeAt && { resumeAt: step.resumeAt }
32
44
  };
33
45
  const output = step.output === void 0 ? null : step.output;
@@ -46,10 +58,71 @@ const advance = (position, step) => {
46
58
  variables,
47
59
  attempt: 1,
48
60
  failures: [],
61
+ visits,
62
+ clock,
49
63
  ...step.resumeAt && { resumeAt: step.resumeAt }
50
64
  };
51
65
  };
52
- /** Where a scope stands after the steps it saved, in their order. */
53
- const foldPosition = (machine, input, steps) => steps.reduce(advance, startPosition(machine, input));
66
+ /** Which visit of its state the step at `position` belongs to, from 0: a retry's visit began with its first try. */
67
+ const visitOf = (position) => (position.visits[position.state] ?? 0) - (position.attempt > 1 ? 1 : 0);
68
+ /** The checkpoint of a scope at `position`, after `step`, which made it; `clock` is the scope's before the step. */
69
+ const checkpointOf = (position, step, clock) => {
70
+ const made = {
71
+ scope: step.scope,
72
+ seq: step.seq,
73
+ state: step.state,
74
+ type: step.type,
75
+ status: step.status,
76
+ fetchedAt: step.finishedAt
77
+ };
78
+ if (position.kind === "ended") return {
79
+ ...made,
80
+ next: null,
81
+ value: position.output,
82
+ variables: position.variables,
83
+ attempt: 1,
84
+ failures: [],
85
+ visits: {},
86
+ clock,
87
+ ...position.resumeAt && { resumeAt: position.resumeAt }
88
+ };
89
+ return {
90
+ ...made,
91
+ next: position.state,
92
+ value: position.input,
93
+ variables: position.variables,
94
+ attempt: position.attempt,
95
+ failures: position.failures,
96
+ visits: position.visits,
97
+ clock: position.clock,
98
+ ...position.resumeAt && { resumeAt: position.resumeAt }
99
+ };
100
+ };
101
+ /** Where a scope stands after its latest checkpoint. */
102
+ const positionOf = (checkpoint) => {
103
+ const seq = checkpoint.seq + 1;
104
+ if (checkpoint.next !== null) {
105
+ const { next: state, value: input = null, variables, attempt, failures, visits, clock, resumeAt } = checkpoint;
106
+ return {
107
+ kind: "at",
108
+ seq,
109
+ state,
110
+ input,
111
+ variables,
112
+ attempt,
113
+ failures,
114
+ visits,
115
+ clock,
116
+ ...resumeAt && { resumeAt }
117
+ };
118
+ }
119
+ return {
120
+ kind: "ended",
121
+ seq,
122
+ output: checkpoint.value ?? null,
123
+ variables: checkpoint.variables,
124
+ ...checkpoint.resumeAt && { resumeAt: checkpoint.resumeAt }
125
+ };
126
+ };
54
127
  //#endregion
55
- export { advance, foldPosition, startPosition };
128
+ export { advance, checkpointOf, positionOf, startPosition, visitOf };
@@ -9,6 +9,8 @@ const visitAt = (rows, state, seq) => {
9
9
  const begun = rows.filter((row) => row.state === state && row.attempt === 1 && row.seq < seq).length;
10
10
  return rows.some((row) => row.seq === seq - 1 && row.state === state && row.status === "retrying") ? begun - 1 : begun;
11
11
  };
12
+ /** A Map item's scope as a replay matches it: its Map's name, the Map's visit in the scope around it and the item's index. */
13
+ const itemScope = (outer, name, visit, index) => `${outer ? `${outer}/` : ""}${encodeURIComponent(name)}#${visit}[${index}]`;
12
14
  /**
13
15
  * A scope named by each Map's visit rather than its step's number, so states added or removed before a Map do not
14
16
  * change the names of its items' scopes; a scope with no steps yet, such as the run's own while the Map that starts it
@@ -17,23 +19,17 @@ const visitAt = (rows, state, seq) => {
17
19
  const logicalScope = (scope, visit) => {
18
20
  if (scope === "") return "";
19
21
  let parent = "";
20
- const names = [];
22
+ let logical = "";
21
23
  for (const segment of scope.split("/")) {
22
24
  const [, name, seq, index] = segmentPattern.exec(segment) ?? [];
23
25
  if (name === void 0) return;
24
- names.push(`${name}#${visit(parent, decodeURIComponent(name), Number(seq))}[${index}]`);
26
+ logical = itemScope(logical, decodeURIComponent(name), visit(parent, decodeURIComponent(name), Number(seq)), Number(index));
25
27
  parent = parent ? `${parent}/${segment}` : segment;
26
28
  }
27
- return names.join("/");
29
+ return logical;
28
30
  };
29
- const keyOf = (logical, state, visit) => `${logical}|${encodeURIComponent(state)}|${visit}`;
30
31
  /** What a step is matched by between a run and its replay: its scope by visits, its state, and its visit of that state. */
31
- const matchKey = (rows, scope, state, seq) => {
32
- const visit = (at, name, from) => visitAt(rows.get(at) ?? [], name, from);
33
- const logical = logicalScope(scope, visit);
34
- if (logical === void 0) return;
35
- return keyOf(logical, state, visit(scope, state, seq));
36
- };
32
+ const visitKey = (logical, state, visit) => `${logical}|${encodeURIComponent(state)}|${visit}`;
37
33
  /**
38
34
  * The visit of each step of a run, by its scope and seq, counted in one pass over the steps in seq order: what
39
35
  * `visitAt` gives each of them, without scanning its scope again for every step.
@@ -74,11 +70,11 @@ const visitOutcomes = (steps) => {
74
70
  for (const step of sorted) {
75
71
  if (!scopes.has(step.scope)) scopes.set(step.scope, logicalScope(step.scope, visit));
76
72
  const logical = scopes.get(step.scope);
77
- if (logical !== void 0) outcomes.set(keyOf(logical, step.state, visits.get(`${step.scope}|${step.seq}`)), step);
73
+ if (logical !== void 0) outcomes.set(visitKey(logical, step.state, visits.get(`${step.scope}|${step.seq}`)), step);
78
74
  }
79
75
  return outcomes;
80
76
  };
81
77
  /** The Map names a scope runs inside, outermost first. */
82
78
  const mapNames = (scope) => scope === "" ? [] : scope.split("/").map((segment) => decodeURIComponent(segmentPattern.exec(segment)?.[1] ?? ""));
83
79
  //#endregion
84
- export { mapNames, matchKey, rowsByScope, visitOutcomes };
80
+ export { itemScope, mapNames, visitKey, visitOutcomes };
@@ -1,9 +1,9 @@
1
1
  import { Definition } from "../definition/types.js";
2
- import { SavedStep } from "./port.js";
2
+ import { ReplayedStep } from "./port.js";
3
3
  //#region src/run/replay-of.d.ts
4
- /** The run a replay replays: the definition it ran and its steps. */
4
+ /** The run a replay replays: the definition it ran and its steps, as its trace keeps them. */
5
5
  export type Replayed = {
6
6
  definition: Definition;
7
- steps: readonly SavedStep[];
7
+ steps: readonly ReplayedStep[];
8
8
  };
9
9
  //#endregion
@@ -1,21 +1,9 @@
1
- import { rowsByScope, visitOutcomes } from "./replay-match.js";
1
+ import { visitOutcomes } from "./replay-match.js";
2
2
  //#region src/run/replay-of.ts
3
- /**
4
- * What a replay matches its held-back steps by: the replayed run's last try of each visit, the definition it ran,
5
- * and the replay's own steps so far, by scope, which `seen` adds to as the replay saves them.
6
- */
7
- const replayOf = (replayed, saved) => {
8
- const seen = rowsByScope(saved);
9
- return {
10
- outcomes: visitOutcomes(replayed.steps),
11
- machine: replayed.definition.stateMachine,
12
- seen,
13
- add: (step) => {
14
- const rows = seen.get(step.scope);
15
- if (rows) rows.push(step);
16
- else seen.set(step.scope, [step]);
17
- }
18
- };
19
- };
3
+ /** What a replay matches its held-back steps by: the replayed run's last try of each visit, and the definition it ran. */
4
+ const replayOf = (replayed) => ({
5
+ outcomes: visitOutcomes(replayed.steps),
6
+ machine: replayed.definition.stateMachine
7
+ });
20
8
  //#endregion
21
9
  export { replayOf };
@@ -1,4 +1,4 @@
1
- import { mapNames, matchKey } from "./replay-match.js";
1
+ import { mapNames, visitKey } from "./replay-match.js";
2
2
  //#region src/run/replay.ts
3
3
  /** The log line of a step a replay held back, which the run's page marks it by. */
4
4
  const heldBackLog = "Not sent: replay";
@@ -14,13 +14,13 @@ const stateIn = (machine, maps, name) => {
14
14
  return inner?.States[name];
15
15
  };
16
16
  /**
17
- * What a held-back step takes from the replayed run's step of the same state and visit of it in the same scope: its
17
+ * What a held-back step takes from the replayed run's step of the same state and visit of it in the same scope, as
18
+ * `logical` names it by visits: its
18
19
  * error, or its result, which only a Task that did not shape it with `Output` saved as it was. Undefined when that
19
20
  * run has no such step, its step was still retrying, or saved its result shaped.
20
21
  */
21
22
  const replayedOutcome = (replay, at) => {
22
- const key = matchKey(replay.seen, at.scope, at.name, at.seq);
23
- const step = key === void 0 ? void 0 : replay.outcomes.get(key);
23
+ const step = replay.outcomes.get(visitKey(at.logical, at.name, at.visit));
24
24
  if (!step || step.status === "retrying") return;
25
25
  if (step.status !== "succeeded") return { failure: {
26
26
  Error: step.error ?? "States.Runtime",
@@ -0,0 +1,21 @@
1
+ import { Machine } from "../definition/types.js";
2
+ import { Checkpoint, StepRecord } from "./port.js";
3
+ //#region src/run/rerun-from.d.ts
4
+ /** What a re-run from a step starts from: the run's checkpoint at that step, none when it is the first, and the trace entries it keeps. */
5
+ export type RerunFrom = {
6
+ checkpoint?: Checkpoint;
7
+ kept: StepRecord[];
8
+ };
9
+ /**
10
+ * Where a re-run from `state`, a state of the workflow itself and not of a Map, of an ended run whose trace holds
11
+ * `steps` goes on: the root steps before the state's first visit stay as they ran, and are folded into the run's
12
+ * checkpoint at that state with the variables they assigned, so it and everything after it run again on `machine`, the
13
+ * workflow's version now, at `clock`. `ran` is the version the earlier run ran. The steps kept, with the items of the
14
+ * Maps among them, go into the re-run's trace. Returns the problem instead when the run never reached the state, the
15
+ * version does not have it or starts elsewhere, or the trace does not hold every step before it, as for a re-run that
16
+ * went on from a checkpoint.
17
+ */
18
+ export declare const rerunFrom: (machine: Machine, ran: Machine, steps: readonly StepRecord[], state: string, clock: Date) => RerunFrom | {
19
+ problem: string;
20
+ };
21
+ //#endregion
@@ -0,0 +1,51 @@
1
+ import { keptAssigned } from "./rerun.js";
2
+ import { advance, checkpointOf, startPosition } from "./position.js";
3
+ //#region src/run/rerun-from.ts
4
+ const revived = (step) => ({
5
+ ...step,
6
+ startedAt: new Date(step.startedAt),
7
+ finishedAt: new Date(step.finishedAt),
8
+ ...step.resumeAt && { resumeAt: new Date(step.resumeAt) }
9
+ });
10
+ const mapSeq = (scope) => Number(/\.(\d+)\[\d+\]$/.exec(scope.split("/")[0])?.[1]);
11
+ /**
12
+ * Where a re-run from `state`, a state of the workflow itself and not of a Map, of an ended run whose trace holds
13
+ * `steps` goes on: the root steps before the state's first visit stay as they ran, and are folded into the run's
14
+ * checkpoint at that state with the variables they assigned, so it and everything after it run again on `machine`, the
15
+ * workflow's version now, at `clock`. `ran` is the version the earlier run ran. The steps kept, with the items of the
16
+ * Maps among them, go into the re-run's trace. Returns the problem instead when the run never reached the state, the
17
+ * version does not have it or starts elsewhere, or the trace does not hold every step before it, as for a re-run that
18
+ * went on from a checkpoint.
19
+ */
20
+ const rerunFrom = (machine, ran, steps, state, clock) => {
21
+ const unique = [...new Map(steps.map((step) => [`${step.scope}\n${step.seq}`, revived(step)])).values()];
22
+ const own = unique.filter((step) => step.scope === "").sort((a, b) => a.seq - b.seq);
23
+ const from = own.findIndex((step) => step.state === state);
24
+ if (from === -1) return { problem: `The run never reached state "${state}"` };
25
+ if (!Object.hasOwn(machine.States, state)) return { problem: `The workflow no longer has state "${state}"` };
26
+ if (from === 0 && machine.StartAt !== state) return { problem: `The workflow no longer starts at state "${state}"` };
27
+ const before = own.slice(0, from);
28
+ if (before.some((step, index) => step.seq !== index)) return { problem: `The run's trace does not hold every step before state "${state}"` };
29
+ if (before.length === 0) return { kept: [] };
30
+ let position = startPosition(machine, null, clock);
31
+ for (const step of before) position = advance(position, {
32
+ ...step,
33
+ assigned: keptAssigned(machine, ran, step) ?? step.assigned ?? {}
34
+ });
35
+ if (position.kind !== "at" || position.state !== state) return { problem: `The run's trace does not lead to state "${state}"` };
36
+ const { resumeAt: _, ...made } = checkpointOf(position, before.at(-1), clock);
37
+ const checkpoint = {
38
+ ...made,
39
+ attempt: 1,
40
+ failures: [],
41
+ clock,
42
+ after: -1
43
+ };
44
+ const seqs = new Set(before.map((step) => step.seq));
45
+ return {
46
+ checkpoint,
47
+ kept: unique.filter((step) => step.scope === "" ? seqs.has(step.seq) : seqs.has(mapSeq(step.scope)))
48
+ };
49
+ };
50
+ //#endregion
51
+ export { rerunFrom };