@protobase/workflows 0.99.16 → 0.100.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.
Files changed (48) hide show
  1. package/dist/definition/check-aws.js +80 -0
  2. package/dist/definition/check-definition.d.ts +4 -0
  3. package/dist/definition/check-definition.js +27 -10
  4. package/dist/definition/check-reads.js +9 -4
  5. package/dist/definition/check-schema.js +19 -7
  6. package/dist/definition/dataflow/check-dataflow.js +36 -0
  7. package/dist/definition/dataflow/dependencies.d.ts +17 -0
  8. package/dist/definition/dataflow/dependencies.js +88 -0
  9. package/dist/definition/expression-fields.d.ts +5 -0
  10. package/dist/definition/expression-fields.js +1 -0
  11. package/dist/definition/expressions.d.ts +5 -0
  12. package/dist/definition/graph.js +1 -1
  13. package/dist/definition/parts.d.ts +21 -0
  14. package/dist/definition/parts.js +21 -0
  15. package/dist/definition/pins/check-pins.js +40 -0
  16. package/dist/definition/pins/pin-sources.d.ts +33 -0
  17. package/dist/definition/pins/pin-sources.js +78 -0
  18. package/dist/definition/pins/pin-type.d.ts +19 -0
  19. package/dist/definition/pins/pin-type.js +61 -0
  20. package/dist/definition/pins/references.d.ts +32 -0
  21. package/dist/definition/pins/references.js +118 -0
  22. package/dist/definition/pins/resolve-schema.d.ts +21 -0
  23. package/dist/definition/pins/resolve-schema.js +62 -0
  24. package/dist/definition/reads.js +17 -10
  25. package/dist/definition/schema.d.ts +285 -191
  26. package/dist/definition/schema.js +275 -245
  27. package/dist/definition/types.d.ts +16 -4
  28. package/dist/definition/types.js +5 -0
  29. package/dist/definition/visible.js +6 -4
  30. package/dist/index.d.ts +11 -3
  31. package/dist/index.js +12 -3
  32. package/dist/plugin/index.d.ts +2 -1
  33. package/dist/plugin/index.js +2 -1
  34. package/dist/plugin/value-check.d.ts +9 -0
  35. package/dist/plugin/value-check.js +24 -0
  36. package/dist/run/block-state.js +1 -1
  37. package/dist/run/context.d.ts +2 -1
  38. package/dist/run/dataflow.js +183 -0
  39. package/dist/run/position.js +16 -11
  40. package/dist/run/recovery.js +22 -3
  41. package/dist/run/rerun-from.d.ts +8 -5
  42. package/dist/run/rerun-from.js +61 -5
  43. package/dist/run/rerun.d.ts +4 -3
  44. package/dist/run/rerun.js +16 -7
  45. package/dist/run/result-states.js +3 -3
  46. package/dist/run/scope.js +5 -4
  47. package/dist/run/segment.js +5 -2
  48. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,16 +1,25 @@
1
1
  import { limits } from "./limits.js";
2
- import { definitionSchema } from "./definition/schema.js";
2
+ import { dataflowDefinitionSchema, definitionSchema } from "./definition/schema.js";
3
3
  import { problemText } from "./definition/problem.js";
4
+ import { expressionSource } from "./definition/expressions.js";
5
+ import { assignedNames } from "./definition/expression-fields.js";
4
6
  import { allStates, blockDefinition, findBlock, innerMachine } from "./definition/inner.js";
5
7
  import { usedConnections } from "./definition/used-connections.js";
6
8
  import { nestingDepth } from "./nesting.js";
9
+ import { fits, pinType, pinTypeText } from "./definition/pins/pin-type.js";
10
+ import { resolveSchema, schemaAt } from "./definition/pins/resolve-schema.js";
11
+ import { inputSchema, referenceSchema, resultSchema, resultState, stepStatusSchema, triggerSchema } from "./definition/pins/pin-sources.js";
12
+ import { expressionReferences, parseReference, readText, referenceValue } from "./definition/pins/references.js";
13
+ import { dependsOn, machineDependencies } from "./definition/dataflow/dependencies.js";
14
+ import { orderOf } from "./definition/types.js";
7
15
  import { checkDefinition } from "./definition/check-definition.js";
16
+ import { definitionFromParts, partOfProblem, partsOfDefinition } from "./definition/parts.js";
8
17
  import { definitionWarnings } from "./definition/check-warnings.js";
9
18
  import { StepError } from "./run/errors.js";
10
19
  import { redacted, secretRedactor, shortestSecret } from "./run/redact.js";
11
20
  import { keptAssigned, rerunCheckpoint, rerunProblem, resultRead } from "./run/rerun.js";
12
- import { rerunFrom } from "./run/rerun-from.js";
13
21
  import { heldBackLog } from "./run/replay.js";
22
+ import { rerunFrom } from "./run/rerun-from.js";
14
23
  import { runSegment } from "./run/segment.js";
15
24
  import { createRunner } from "./run/runner.js";
16
25
  import { loadPlugins } from "./plugin/load-plugins.js";
@@ -19,4 +28,4 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
19
28
  import { typeList } from "./plugin/type-list.js";
20
29
  import { connectionUnavailable } from "./plugin/connection-availability.js";
21
30
  import { typeCatalog } from "./plugin/type-catalog.js";
22
- export { StepError, allStates, blockDefinition, checkDefinition, connectionUnavailable, createRunner, definitionSchema, definitionWarnings, findBlock, heldBackLog, innerMachine, keptAssigned, limits, loadPlugins, nestingDepth, problemText, redacted, rerunCheckpoint, rerunFrom, rerunProblem, resultRead, runSegment, secretRedactor, shortestSecret, stepHandlers, triggerChecks, typeCatalog, typeList, usedConnections };
31
+ export { StepError, allStates, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, innerMachine, inputSchema, keptAssigned, limits, loadPlugins, machineDependencies, nestingDepth, orderOf, parseReference, partOfProblem, partsOfDefinition, pinType, pinTypeText, problemText, readText, redacted, referenceSchema, referenceValue, rerunCheckpoint, rerunFrom, rerunProblem, resolveSchema, resultRead, resultSchema, resultState, runSegment, schemaAt, secretRedactor, shortestSecret, stepHandlers, stepStatusSchema, triggerChecks, triggerSchema, typeCatalog, typeList, usedConnections };
@@ -6,5 +6,6 @@ import { definePlugin, pluginApi } from "./define-plugin.js";
6
6
  import { AddressRefusedError, ResponseTooLargeError, fetchMaxBytes } from "./fetch-errors.js";
7
7
  import { isFileValue } from "./file-value.js";
8
8
  import { isStoredFile } from "./stored-file.js";
9
+ import { valueProblems } from "./value-check.js";
9
10
  import { webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties } from "./webhook-input.js";
10
- export { AddressRefusedError, type ConnectionDeclaration, ConnectionError, type FileValue, type JsonSchema, type OAuthEndpoints, type Plugin, type PluginConnection, type PluginFetch, type PluginFetchInit, type PluginFiles, type PluginMail, type PluginMailMessage, type PluginRecords, type PluginServices, type PluginStorage, type PollEvery, type PollingTrigger, type ReadyTrigger, ResponseTooLargeError, type StepContext, StepError, type StepType, type StorageTarget, type StoredFile, type TriggerContext, type TriggerItem, type TriggerType, type WebhookEvent, type WebhookItem, type WebhookTrigger, definePlugin, fetchMaxBytes, isFileValue, isStoredFile, pluginApi, webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties };
11
+ export { AddressRefusedError, type ConnectionDeclaration, ConnectionError, type FileValue, type JsonSchema, type OAuthEndpoints, type Plugin, type PluginConnection, type PluginFetch, type PluginFetchInit, type PluginFiles, type PluginMail, type PluginMailMessage, type PluginRecords, type PluginServices, type PluginStorage, type PollEvery, type PollingTrigger, type ReadyTrigger, ResponseTooLargeError, type StepContext, StepError, type StepType, type StorageTarget, type StoredFile, type TriggerContext, type TriggerItem, type TriggerType, type WebhookEvent, type WebhookItem, type WebhookTrigger, definePlugin, fetchMaxBytes, isFileValue, isStoredFile, pluginApi, valueProblems, webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties };
@@ -4,5 +4,6 @@ import { ConnectionError } from "./connection-error.js";
4
4
  import { AddressRefusedError, ResponseTooLargeError, fetchMaxBytes } from "./fetch-errors.js";
5
5
  import { isFileValue } from "./file-value.js";
6
6
  import { isStoredFile } from "./stored-file.js";
7
+ import { valueProblems } from "./value-check.js";
7
8
  import { webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties } from "./webhook-input.js";
8
- export { AddressRefusedError, ConnectionError, ResponseTooLargeError, StepError, definePlugin, fetchMaxBytes, isFileValue, isStoredFile, pluginApi, webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties };
9
+ export { AddressRefusedError, ConnectionError, ResponseTooLargeError, StepError, definePlugin, fetchMaxBytes, isFileValue, isStoredFile, pluginApi, valueProblems, webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties };
@@ -0,0 +1,9 @@
1
+ import { JsonSchema } from "./context.js";
2
+ //#region src/plugin/value-check.d.ts
3
+ /**
4
+ * Why `value` does not fit `schema`, a JSON Schema an argument gave, such as the body an HTTP answer was declared to
5
+ * have: one line per problem naming where it is (`body.ip must be string`); a schema that does not compile is one, and
6
+ * so is an asynchronous one (`$async`), whose answer would come later. Empty when it fits.
7
+ */
8
+ export declare const valueProblems: (schema: JsonSchema, value: unknown, name?: string) => string[];
9
+ //#endregion
@@ -0,0 +1,24 @@
1
+ import { Ajv } from "ajv";
2
+ //#region src/plugin/value-check.ts
3
+ /**
4
+ * Why `value` does not fit `schema`, a JSON Schema an argument gave, such as the body an HTTP answer was declared to
5
+ * have: one line per problem naming where it is (`body.ip must be string`); a schema that does not compile is one, and
6
+ * so is an asynchronous one (`$async`), whose answer would come later. Empty when it fits.
7
+ */
8
+ const valueProblems = (schema, value, name = "value") => {
9
+ if (schema.$async === true) return ["the schema is asynchronous ($async), which a value is not checked against"];
10
+ const ajv = new Ajv({
11
+ allErrors: true,
12
+ strict: false
13
+ });
14
+ let validate;
15
+ try {
16
+ validate = ajv.compile(schema);
17
+ } catch (error) {
18
+ return [`the schema is not valid JSON Schema: ${error instanceof Error ? error.message : String(error)}`];
19
+ }
20
+ if (validate(value)) return [];
21
+ return (validate.errors ?? []).map((error) => `${[name, ...error.instancePath.split("/").slice(1)].join(".")} ${error.message}`);
22
+ };
23
+ //#endregion
24
+ export { valueProblems };
@@ -4,10 +4,10 @@ import { cacheSeconds } from "./cache/cache-ttl.js";
4
4
  import { nestingDepth } from "../nesting.js";
5
5
  import { StepError } from "./errors.js";
6
6
  import { redacted } from "./redact.js";
7
+ import { evaluateKept, evaluateTemplate } from "./evaluate.js";
7
8
  import { jsonBytes } from "./json-bytes.js";
8
9
  import { blockKey } from "./cache/block-key.js";
9
10
  import { tolerant } from "./cache/tolerant.js";
10
- import { evaluateKept, evaluateTemplate } from "./evaluate.js";
11
11
  //#region src/run/block-state.ts
12
12
  /** Who a block's entry is kept under: the run's tenant, its version's saver and enabler, and every account it binds. */
13
13
  const identity = {
@@ -7,10 +7,11 @@ export type Paused = {
7
7
  } | {
8
8
  kind: 'yielded';
9
9
  };
10
- /** How a scope ended in this segment. */
10
+ /** How a scope ended in this segment, with the variables it assigned when it ended. */
11
11
  export type ScopeOutcome = {
12
12
  kind: 'ended';
13
13
  output: unknown;
14
+ variables?: Record<string, unknown>;
14
15
  } | {
15
16
  kind: 'failed';
16
17
  error: string;
@@ -0,0 +1,183 @@
1
+ import { limits } from "../limits.js";
2
+ import { dependsOn, machineDependencies } from "../definition/dataflow/dependencies.js";
3
+ import { StepError } from "./errors.js";
4
+ import { evaluateTemplate } from "./evaluate.js";
5
+ import { caughtVariable } from "./recovery.js";
6
+ import { stepFunctions } from "./step-functions.js";
7
+ import { runScope } from "./scope.js";
8
+ //#region src/run/dataflow.ts
9
+ /** A state run on its own: its scope's one state, which ends the scope, as it ends in sequence order with `End`. */
10
+ const alone = (name, state) => ({
11
+ StartAt: name,
12
+ States: { [name]: state.Type === "Fail" ? state : {
13
+ ...state,
14
+ End: true
15
+ } }
16
+ });
17
+ const failedStatus = (error, cause) => ({
18
+ Status: error === "States.Timeout" ? "TIMED_OUT" : "FAILED",
19
+ Error: error,
20
+ Cause: cause
21
+ });
22
+ /** The scope a state of a dataflow machine runs under: the machine's, then the state's name. */
23
+ const scopeOf = (where, name) => `${where ? `${where}/` : ""}${encodeURIComponent(name)}`;
24
+ /**
25
+ * Runs a machine in dataflow order: each state, under a scope of its own, once every state it reads from has ended, as
26
+ * many at once as are ready, up to `limits.mapConcurrency`. A state is skipped when one it reads from did not succeed and
27
+ * its Condition does not read that one's Status, or when its Condition is false. An uncaught failure fails the scope at
28
+ * once: the states running, those of Maps inside them too, finish the step they are in and take no other. A Map item's
29
+ * states read the statuses of the states around their Map as well as each other's. The scope ends with the output of the states
30
+ * no other reads from, by name, or that one state's alone. A state that waits, or one the segment's time stops, pauses
31
+ * the scope once nothing else can go on; the next segment takes each state up from its own checkpoint.
32
+ */
33
+ const runDataflow = async (context, machine, where, input, outer, clock) => {
34
+ const dependencies = machineDependencies(machine);
35
+ const names = Object.keys(machine.States);
36
+ const statuses = Object.create(null);
37
+ const variables = {};
38
+ const outputs = /* @__PURE__ */ new Map();
39
+ const steps = Object.assign(Object.create(null), context.stateContext.Steps);
40
+ const local = Object.create(context, { stateContext: {
41
+ value: {
42
+ ...context.stateContext,
43
+ Steps: steps
44
+ },
45
+ enumerable: true
46
+ } });
47
+ const stop = () => Object.defineProperty(local, "deadline", {
48
+ value: 0,
49
+ writable: true,
50
+ enumerable: true
51
+ });
52
+ const running = /* @__PURE__ */ new Map();
53
+ const paused = [];
54
+ const held = /* @__PURE__ */ new Set();
55
+ let failure;
56
+ const ready = (name) => [...dependsOn(dependencies.get(name))].every((other) => statuses[other] !== void 0);
57
+ const settle = (name, status) => {
58
+ statuses[name] = status;
59
+ steps[name] = status;
60
+ };
61
+ const skip = (name, cause) => settle(name, {
62
+ Status: "SKIPPED",
63
+ Error: null,
64
+ Cause: cause
65
+ });
66
+ const runs = async (name, own) => {
67
+ const failed = [...dependsOn(own)].find((other) => statuses[other].Status !== "SUCCEEDED" && !own.handled.has(other));
68
+ if (failed !== void 0) {
69
+ skip(name, `reads ${failed}, which ended ${statuses[failed].Status}`);
70
+ return false;
71
+ }
72
+ const condition = machine.States[name].Condition;
73
+ if (condition === void 0) return true;
74
+ const bindings = {
75
+ ...outer,
76
+ ...variables,
77
+ ...stepFunctions(clock, `${context.runId}/${scopeOf(where.scope, name)}/condition`),
78
+ states: {
79
+ input,
80
+ context: local.stateContext
81
+ }
82
+ };
83
+ if (await evaluateTemplate(condition, bindings, "Condition")) return true;
84
+ skip(name, "its Condition is false");
85
+ return false;
86
+ };
87
+ const start = (name) => {
88
+ const scope = {
89
+ scope: scopeOf(where.scope, name),
90
+ logical: scopeOf(where.logical, name)
91
+ };
92
+ running.set(name, runScope(local, alone(name, machine.States[name]), scope, input, {
93
+ ...outer,
94
+ ...variables
95
+ }, clock).then((outcome) => ({
96
+ name,
97
+ outcome
98
+ })));
99
+ };
100
+ const ended = (name, outcome) => {
101
+ if (outcome.kind === "ended") {
102
+ const { [caughtVariable]: caught, ...assigned } = outcome.variables ?? {};
103
+ Object.assign(variables, assigned);
104
+ outputs.set(name, outcome.output);
105
+ const error = caught;
106
+ settle(name, error ? failedStatus(error.Error, error.Cause) : {
107
+ Status: "SUCCEEDED",
108
+ Error: null,
109
+ Cause: null
110
+ });
111
+ } else if (outcome.kind === "failed") {
112
+ settle(name, failedStatus(outcome.error, outcome.cause));
113
+ failure ??= {
114
+ Error: outcome.error,
115
+ Cause: outcome.cause
116
+ };
117
+ stop();
118
+ } else {
119
+ held.add(name);
120
+ paused.push(outcome);
121
+ }
122
+ };
123
+ const startReady = async () => {
124
+ for (let skipped = true; skipped && !failure;) {
125
+ skipped = false;
126
+ for (const name of names) {
127
+ if (statuses[name] || running.has(name) || held.has(name) || !ready(name) || running.size >= limits.mapConcurrency) continue;
128
+ try {
129
+ if (context.saved.has(scopeOf(where.scope, name)) || await runs(name, dependencies.get(name))) start(name);
130
+ else skipped = true;
131
+ } catch (error) {
132
+ if (!(error instanceof StepError)) throw error;
133
+ ended(name, {
134
+ kind: "failed",
135
+ error: error.error,
136
+ cause: error.reason
137
+ });
138
+ return;
139
+ }
140
+ }
141
+ }
142
+ };
143
+ try {
144
+ for (;;) {
145
+ await startReady();
146
+ if (running.size === 0) break;
147
+ const { name, outcome } = await Promise.race(running.values());
148
+ running.delete(name);
149
+ ended(name, outcome);
150
+ }
151
+ } catch (error) {
152
+ stop();
153
+ await Promise.allSettled(running.values());
154
+ throw error;
155
+ }
156
+ if (failure) return {
157
+ kind: "failed",
158
+ error: failure.Error,
159
+ cause: failure.Cause
160
+ };
161
+ if (paused.length > 0) {
162
+ const until = paused.flatMap((outcome) => outcome.kind === "blocked" ? [outcome.until] : []);
163
+ return paused.some((outcome) => outcome.kind === "yielded") || until.length === 0 ? { kind: "yielded" } : {
164
+ kind: "blocked",
165
+ until: new Date(Math.min(...until.map((date) => date.getTime())))
166
+ };
167
+ }
168
+ const unended = names.find((name) => !statuses[name]);
169
+ if (unended !== void 0) return {
170
+ kind: "failed",
171
+ error: "States.Runtime",
172
+ cause: `${unended} never became ready to run`
173
+ };
174
+ const read = new Set([...dependencies.values()].flatMap((own) => [...dependsOn(own)]));
175
+ const last = names.filter((name) => !read.has(name) && outputs.has(name));
176
+ return {
177
+ kind: "ended",
178
+ output: last.length === 1 ? outputs.get(last[0]) : Object.fromEntries(last.map((name) => [name, outputs.get(name)])),
179
+ variables
180
+ };
181
+ };
182
+ //#endregion
183
+ export { alone, runDataflow, scopeOf };
@@ -1,15 +1,20 @@
1
+ import { StepError } from "./errors.js";
1
2
  //#region src/run/position.ts
2
- const startPosition = (machine, input, clock) => ({
3
- kind: "at",
4
- seq: 0,
5
- state: machine.StartAt,
6
- input,
7
- variables: {},
8
- attempt: 1,
9
- failures: [],
10
- visits: {},
11
- clock
12
- });
3
+ /** Where a machine in sequence order starts, which a save made sure it names; one in data order starts each state alone. */
4
+ const startPosition = (machine, input, clock) => {
5
+ if (machine.StartAt === void 0) throw new StepError("States.Runtime", "The state machine names no StartAt to start from");
6
+ return {
7
+ kind: "at",
8
+ seq: 0,
9
+ state: machine.StartAt,
10
+ input,
11
+ variables: {},
12
+ attempt: 1,
13
+ failures: [],
14
+ visits: {},
15
+ clock
16
+ };
17
+ };
13
18
  /**
14
19
  * 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
20
  * it to that time; any other step leaves it, so a step run again after a crash reads the same `$now`.
@@ -10,6 +10,11 @@ const retryDelaySeconds = (retrier, retries) => {
10
10
  const delay = (retrier.IntervalSeconds ?? 1) * (retrier.BackoffRate ?? 2) ** retries;
11
11
  return Math.min(delay, retrier.MaxDelaySeconds ?? limits.retryDelaySeconds);
12
12
  };
13
+ /**
14
+ * The variable a catcher without `Next` keeps the error it caught in, which a dataflow state's Status reads: a name no
15
+ * definition can assign, as an assigned name starts with a letter.
16
+ */
17
+ const caughtVariable = "__caught";
13
18
  const caught = async (catcher, failure, bindings, logs) => {
14
19
  const after = {
15
20
  ...bindings,
@@ -19,12 +24,26 @@ const caught = async (catcher, failure, bindings, logs) => {
19
24
  }
20
25
  };
21
26
  const output = catcher.Output === void 0 ? failure : await evaluateKept(catcher.Output, after, "Output");
22
- return {
27
+ const assigned = await evaluateAssign(catcher.Assign, after);
28
+ if (catcher.Next !== void 0) return {
23
29
  kind: "step",
24
30
  status: "caught",
25
31
  next: catcher.Next,
26
32
  output,
27
- assigned: await evaluateAssign(catcher.Assign, after),
33
+ assigned,
34
+ error: failure.Error,
35
+ cause: failure.Cause,
36
+ logs
37
+ };
38
+ return {
39
+ kind: "step",
40
+ status: "caught",
41
+ next: null,
42
+ output,
43
+ assigned: {
44
+ ...assigned,
45
+ [caughtVariable]: failure
46
+ },
28
47
  error: failure.Error,
29
48
  cause: failure.Cause,
30
49
  logs
@@ -73,4 +92,4 @@ const recover = async (state, position, failure, bindings, now, logs) => {
73
92
  });
74
93
  };
75
94
  //#endregion
76
- export { recover, retryDelaySeconds };
95
+ export { caughtVariable, recover, retryDelaySeconds };
@@ -1,9 +1,12 @@
1
- import { Machine } from "../definition/types.js";
1
+ import { Machine, Order } from "../definition/types.js";
2
2
  import { Checkpoint, StepRecord } from "./port.js";
3
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. */
4
+ /**
5
+ * What a re-run from a step starts from: the run's checkpoints the steps it keeps make, none when it keeps none, and
6
+ * the trace entries it keeps.
7
+ */
5
8
  export type RerunFrom = {
6
- checkpoint?: Checkpoint;
9
+ checkpoints: Checkpoint[];
7
10
  kept: StepRecord[];
8
11
  };
9
12
  /**
@@ -13,9 +16,9 @@ export type RerunFrom = {
13
16
  * workflow's version now, at `clock`. `ran` is the version the earlier run ran. The steps kept, with the items of the
14
17
  * Maps among them, go into the re-run's trace. Returns the problem instead when the run never reached the state, the
15
18
  * 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.
19
+ * went on from a checkpoint. In data order (`order`), see `dataRerunFrom`.
17
20
  */
18
- export declare const rerunFrom: (machine: Machine, ran: Machine, steps: readonly StepRecord[], state: string, clock: Date) => RerunFrom | {
21
+ export declare const rerunFrom: (machine: Machine, ran: Machine, steps: readonly StepRecord[], state: string, clock: Date, order?: Order) => RerunFrom | {
19
22
  problem: string;
20
23
  };
21
24
  //#endregion
@@ -1,5 +1,7 @@
1
+ import { dependsOn, machineDependencies } from "../definition/dataflow/dependencies.js";
1
2
  import { keptAssigned } from "./rerun.js";
2
3
  import { advance, checkpointOf, startPosition } from "./position.js";
4
+ import { alone, scopeOf } from "./dataflow.js";
3
5
  //#region src/run/rerun-from.ts
4
6
  const revived = (step) => ({
5
7
  ...step,
@@ -15,9 +17,10 @@ const mapSeq = (scope) => Number(/\.(\d+)\[\d+\]$/.exec(scope.split("/")[0])?.[1
15
17
  * workflow's version now, at `clock`. `ran` is the version the earlier run ran. The steps kept, with the items of the
16
18
  * Maps among them, go into the re-run's trace. Returns the problem instead when the run never reached the state, the
17
19
  * 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.
20
+ * went on from a checkpoint. In data order (`order`), see `dataRerunFrom`.
19
21
  */
20
- const rerunFrom = (machine, ran, steps, state, clock) => {
22
+ const rerunFrom = (machine, ran, steps, state, clock, order = "sequence") => {
23
+ if (order === "data") return dataRerunFrom(machine, ran, steps, state, clock);
21
24
  const unique = [...new Map(steps.map((step) => [`${step.scope}\n${step.seq}`, revived(step)])).values()];
22
25
  const own = unique.filter((step) => step.scope === "").sort((a, b) => a.seq - b.seq);
23
26
  const from = own.findIndex((step) => step.state === state);
@@ -26,7 +29,10 @@ const rerunFrom = (machine, ran, steps, state, clock) => {
26
29
  if (from === 0 && machine.StartAt !== state) return { problem: `The workflow no longer starts at state "${state}"` };
27
30
  const before = own.slice(0, from);
28
31
  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: [] };
32
+ if (before.length === 0) return {
33
+ checkpoints: [],
34
+ kept: []
35
+ };
30
36
  let position = startPosition(machine, null, clock);
31
37
  for (const step of before) position = advance(position, {
32
38
  ...step,
@@ -42,9 +48,59 @@ const rerunFrom = (machine, ran, steps, state, clock) => {
42
48
  after: -1
43
49
  };
44
50
  const seqs = new Set(before.map((step) => step.seq));
51
+ const kept = unique.filter((step) => step.scope === "" ? seqs.has(step.seq) : seqs.has(mapSeq(step.scope)));
52
+ return {
53
+ checkpoints: [checkpoint],
54
+ kept
55
+ };
56
+ };
57
+ /**
58
+ * Where a re-run from `state` of an ended run in data order goes on: each other state that ended and reads nothing,
59
+ * through others either, of `state` stays as it ran, with its own scope's checkpoint made from its steps and the steps
60
+ * of the Maps in it kept in the trace; `state`, every state after it and every state that did not end run again on
61
+ * `machine`. Returns the problem instead when the run never reached the state, the version does not have it, or the
62
+ * trace does not hold every step of a state it keeps.
63
+ */
64
+ const dataRerunFrom = (machine, ran, steps, state, clock) => {
65
+ const latest = [...new Map(steps.map((step) => [`${step.scope}\n${step.seq}`, revived(step)])).values()];
66
+ if (!Object.hasOwn(machine.States, state)) return { problem: `The workflow no longer has state "${state}"` };
67
+ if (!latest.some((step) => step.scope === scopeOf("", state))) return { problem: `The run never reached state "${state}"` };
68
+ const dependencies = machineDependencies(machine);
69
+ const after = /* @__PURE__ */ new Set([state]);
70
+ for (let grew = true; grew;) {
71
+ grew = false;
72
+ for (const [name, own] of dependencies) {
73
+ if (after.has(name) || ![...dependsOn(own)].some((other) => after.has(other))) continue;
74
+ after.add(name);
75
+ grew = true;
76
+ }
77
+ }
78
+ const checkpoints = [];
79
+ const kept = [];
80
+ for (const [name, own] of Object.entries(machine.States)) {
81
+ if (after.has(name)) continue;
82
+ const scope = scopeOf("", name);
83
+ const mine = latest.filter((step) => step.scope === scope).sort((a, b) => a.seq - b.seq);
84
+ if (mine.length === 0) continue;
85
+ if (mine.some((step, index) => step.seq !== index)) return { problem: `The run's trace does not hold every step of state "${name}"` };
86
+ let position = startPosition(alone(name, own), null, clock);
87
+ for (const step of mine) position = advance(position, {
88
+ ...step,
89
+ assigned: keptAssigned(machine, ran, {
90
+ ...step,
91
+ scope: ""
92
+ }) ?? step.assigned ?? {}
93
+ });
94
+ if (position.kind !== "ended" || position.resumeAt && position.resumeAt > clock) continue;
95
+ checkpoints.push({
96
+ ...checkpointOf(position, mine.at(-1), clock),
97
+ after: -1
98
+ });
99
+ kept.push(...latest.filter((step) => step.scope === scope || step.scope.startsWith(`${scope}/`)));
100
+ }
45
101
  return {
46
- checkpoint,
47
- kept: unique.filter((step) => step.scope === "" ? seqs.has(step.seq) : seqs.has(mapSeq(step.scope)))
102
+ checkpoints,
103
+ kept
48
104
  };
49
105
  };
50
106
  //#endregion
@@ -1,16 +1,17 @@
1
- import { Machine } from "../definition/types.js";
1
+ import { Machine, Order } from "../definition/types.js";
2
2
  import { Checkpoint } from "./port.js";
3
3
  //#region src/run/rerun.d.ts
4
4
  /** What a re-run reads of a failed run's checkpoint to know where its scope goes on. */
5
5
  export type EarlierCheckpoint = Pick<Checkpoint, 'scope' | 'next'>;
6
6
  /**
7
7
  * The problem with re-running a failed run whose scopes stand at `checkpoints` on `machine`, the workflow's version
8
- * now: a scope that would go on at a state, or in a Map, the version does not have; undefined when there is none.
8
+ * now, in `order`: a scope that would go on at a state, or in a Map, the version does not have, or one of the other
9
+ * order; undefined when there is none.
9
10
  * Scopes that ended stay as they ran.
10
11
  * A re-run goes on from each scope's last checkpoint, as a run does after a crash: the steps since run again, the
11
12
  * recorded ones before it never.
12
13
  */
13
- export declare const rerunProblem: (machine: Machine, checkpoints: readonly EarlierCheckpoint[]) => string | undefined;
14
+ export declare const rerunProblem: (machine: Machine, checkpoints: readonly EarlierCheckpoint[], order?: Order) => string | undefined;
14
15
  /** A failed run's checkpoint as its re-run, started at `clock`, takes it up: the state it goes on at from its first try, now. */
15
16
  export declare const rerunCheckpoint: <C extends Checkpoint>({ resumeAt: _, ...checkpoint }: C, clock: Date) => Omit<C, "resumeAt"> & {
16
17
  attempt: number;
package/dist/run/rerun.js CHANGED
@@ -1,13 +1,19 @@
1
1
  import { expressionSource } from "../definition/expressions.js";
2
2
  //#region src/run/rerun.ts
3
- const machineOf = (machine, scope) => {
3
+ const itemPart = /^(.*)\.\d+\[\d+\]$/;
4
+ const machineOf = (machine, scope, order) => {
4
5
  if (scope === "") return machine;
5
6
  let inner = machine;
6
7
  for (const part of scope.split("/")) {
7
- const match = /^(.*)\.\d+\[\d+\]$/.exec(part);
8
- if (!match) throw new Error(`"${scope}" is not the scope of a Map item`);
9
- const name = decodeURIComponent(match[1]);
8
+ const item = itemPart.exec(part);
9
+ const name = decodeURIComponent(item ? item[1] : part);
10
10
  const state = inner.States[name];
11
+ if (!item) {
12
+ if (order !== "data") return `The run goes on at state "${name}" as data order runs it, and the workflow now runs in sequence`;
13
+ if (!state) return `The run goes on at state "${name}", which the workflow no longer has`;
14
+ inner = { States: { [name]: state } };
15
+ continue;
16
+ }
11
17
  if (state?.Type !== "Map") return `The run goes on in the Map "${name}"${scope.includes("/") ? ` of ${scope}` : ""}, which the workflow no longer has`;
12
18
  inner = state.ItemProcessor;
13
19
  }
@@ -15,15 +21,18 @@ const machineOf = (machine, scope) => {
15
21
  };
16
22
  /**
17
23
  * The problem with re-running a failed run whose scopes stand at `checkpoints` on `machine`, the workflow's version
18
- * now: a scope that would go on at a state, or in a Map, the version does not have; undefined when there is none.
24
+ * now, in `order`: a scope that would go on at a state, or in a Map, the version does not have, or one of the other
25
+ * order; undefined when there is none.
19
26
  * Scopes that ended stay as they ran.
20
27
  * A re-run goes on from each scope's last checkpoint, as a run does after a crash: the steps since run again, the
21
28
  * recorded ones before it never.
22
29
  */
23
- const rerunProblem = (machine, checkpoints) => {
30
+ const rerunProblem = (machine, checkpoints, order = "sequence") => {
31
+ const ranIn = checkpoints.some(({ scope }) => scope !== "" && !itemPart.test(scope.split("/")[0])) ? "data" : "sequence";
32
+ if (checkpoints.length > 0 && ranIn !== order) return `The run ran in ${ranIn} order, and the workflow now runs in ${order} order; switch it back to re-run it`;
24
33
  for (const { scope, next } of checkpoints) {
25
34
  if (next === null) continue;
26
- const inner = machineOf(machine, scope);
35
+ const inner = machineOf(machine, scope, order);
27
36
  if (typeof inner === "string") return inner;
28
37
  if (!Object.hasOwn(inner.States, next)) return `The run goes on at state "${next}"${scope ? ` in ${scope}` : ""}, which the workflow no longer has`;
29
38
  }
@@ -1,14 +1,14 @@
1
1
  import { limits } from "../limits.js";
2
2
  import { StepError, errorOutput } from "./errors.js";
3
3
  import { redacted } from "./redact.js";
4
- import { emptyTask, heldBack, heldBackLog, replayedOutcome } from "./replay.js";
5
- import { jsonBytes } from "./json-bytes.js";
6
4
  import { evaluateAssign, evaluateKept, evaluateTemplate, recordedArguments } from "./evaluate.js";
5
+ import { recover } from "./recovery.js";
6
+ import { jsonBytes } from "./json-bytes.js";
7
7
  import { runBlock } from "./block-state.js";
8
8
  import { fanOut } from "./fan-out.js";
9
- import { recover } from "./recovery.js";
10
9
  import { stepFunctions } from "./step-functions.js";
11
10
  import { visibleVariables } from "./step-input.js";
11
+ import { emptyTask, heldBack, heldBackLog, replayedOutcome } from "./replay.js";
12
12
  import { runTask } from "./task.js";
13
13
  //#region src/run/result-states.ts
14
14
  const task = async (state, call) => {
package/dist/run/scope.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { limits } from "../limits.js";
2
2
  import { StepError, SupersededError } from "./errors.js";
3
- import { advance, checkpointOf, positionOf, startPosition, visitOf } from "./position.js";
4
- import { itemScope } from "./replay-match.js";
5
3
  import { jsonBytes } from "./json-bytes.js";
4
+ import { advance, checkpointOf, positionOf, startPosition, visitOf } from "./position.js";
6
5
  import { bindingsOf, innerScope } from "./step-input.js";
6
+ import { itemScope } from "./replay-match.js";
7
7
  import { runResultState } from "./result-states.js";
8
8
  import { runChoice, runFail, runPass, runWait } from "./simple-states.js";
9
9
  //#region src/run/scope.ts
@@ -89,7 +89,8 @@ const runScope = async (context, machine, where, input, outer, clock) => {
89
89
  };
90
90
  return {
91
91
  kind: "ended",
92
- output: position.output
92
+ output: position.output,
93
+ variables: position.variables
93
94
  };
94
95
  }
95
96
  if (context.superseded()) throw new SupersededError(`Scope "${scope}" stopped: another segment saved a step of this run first`);
@@ -112,7 +113,7 @@ const runScope = async (context, machine, where, input, outer, clock) => {
112
113
  scope: innerScope(scope, name, from.seq, index),
113
114
  logical: itemScope(logical, name, visit, index)
114
115
  });
115
- const runItem = (inner, index, value, seen) => runScope(context, inner, item(index), value, seen, from.clock);
116
+ const runItem = (inner, index, value, seen) => context.runMachine(context, inner, item(index), value, seen, from.clock);
116
117
  const call = {
117
118
  context,
118
119
  name,
@@ -1,8 +1,10 @@
1
1
  import { limits } from "../limits.js";
2
+ import { orderOf } from "../definition/types.js";
2
3
  import { SupersededError } from "./errors.js";
4
+ import { runScope } from "./scope.js";
5
+ import { runDataflow } from "./dataflow.js";
3
6
  import { secretNamer } from "./cache/secret-names.js";
4
7
  import { replayOf } from "./replay-of.js";
5
- import { runScope } from "./scope.js";
6
8
  //#region src/run/segment.ts
7
9
  /**
8
10
  * Runs a run's steps from where its checkpoints leave it to its next wait: it ends or fails, waits until a time
@@ -63,11 +65,12 @@ const runSegment = async ({ runId, definition, input, startedAt, secrets, redact
63
65
  },
64
66
  trace: (step) => void steps.push(step),
65
67
  superseded: () => superseded,
68
+ runMachine: orderOf(definition) === "data" ? runDataflow : runScope,
66
69
  steps: { count: saved.reduce((count, checkpoint) => count + checkpoint.seq + 1, 0) },
67
70
  maxSteps
68
71
  };
69
72
  try {
70
- const outcome = await runScope(context, definition.stateMachine, {
73
+ const outcome = await context.runMachine(context, definition.stateMachine, {
71
74
  scope: "",
72
75
  logical: ""
73
76
  }, input, {}, startedAt);