@protobase/workflows 0.87.1 → 0.88.0

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.
@@ -0,0 +1,28 @@
1
+ import { stateExpressions } from "./expression-fields.js";
2
+ import { expressionParsed } from "./check-reads.js";
3
+ //#region src/definition/block-reads.ts
4
+ const ownStates = (machine) => Object.values(machine.States).flatMap((state) => [state, ...state.Type === "Map" ? ownStates(state.ItemProcessor) : []]);
5
+ const within = (path, outer) => outer.every((key, index) => path[index] === key);
6
+ /**
7
+ * What the steps of a block's processor read of what it is given, from their expressions: each read of
8
+ * `$states.context.Execution.Input` as the path of names after it, cut where the path stops being plain names, and
9
+ * each secret by name. A path inside another one read is left out, as its value is part of that one's.
10
+ */
11
+ const blockReads = (processor) => {
12
+ const input = [];
13
+ const secrets = /* @__PURE__ */ new Set();
14
+ for (const state of ownStates(processor)) for (const { source } of stateExpressions(state)) for (const read of expressionParsed(source)?.states ?? []) {
15
+ if (read[0] !== "context") continue;
16
+ if (read[1] === "Execution" && read[2] === "Input") input.push(read.slice(3));
17
+ if (read[1] === "Secrets" && read[2] !== void 0) secrets.add(read[2]);
18
+ }
19
+ const sorted = input.sort((a, b) => a.length - b.length);
20
+ const kept = [];
21
+ for (const path of sorted) if (!kept.some((outer) => within(path, outer))) kept.push(path);
22
+ return {
23
+ input: kept.sort((a, b) => JSON.stringify(a) < JSON.stringify(b) ? -1 : 1),
24
+ secrets: [...secrets].sort()
25
+ };
26
+ };
27
+ //#endregion
28
+ export { blockReads };
@@ -0,0 +1,33 @@
1
+ import { limits } from "../limits.js";
2
+ import { fieldPath } from "./problem.js";
3
+ import { templateExpressions } from "./expressions.js";
4
+ import { expressionParsed } from "./check-reads.js";
5
+ import { cacheSeconds } from "../run/cache/cache-ttl.js";
6
+ //#region src/definition/check-block.ts
7
+ const secretArguments = (state, where) => [...templateExpressions(state.Arguments, ["Arguments"]), ...templateExpressions(state.Cache.Key, ["Cache", "Key"])].flatMap(({ path, source }) => {
8
+ if (!expressionParsed(source)?.states.some((read) => read[0] === "context" && read[1] === "Secrets")) return [];
9
+ return [{
10
+ state: where,
11
+ field: fieldPath(path),
12
+ message: "reads a secret, which a block would keep in its run; read it inside the block as $states.context.Secrets.<NAME>"
13
+ }];
14
+ });
15
+ /**
16
+ * Why a Block cannot be saved beside what every state is checked for: a time to live that is no duration of up to 30
17
+ * days, Arguments or a Key that read a secret, and more Blocks around it than `limits.blockDepth`.
18
+ */
19
+ const blockProblems = (state, where, depth) => {
20
+ const problems = [];
21
+ if (cacheSeconds(state.Cache.Ttl) === void 0) problems.push({
22
+ state: where,
23
+ field: "Cache.Ttl",
24
+ message: `is no time to live: give seconds from 1, or text such as "10 minutes", "1 hour" or "2 days", at most ${limits.cacheMaxSeconds / 86400} days`
25
+ });
26
+ if (depth > limits.blockDepth) problems.push({
27
+ state: where,
28
+ message: `is inside ${depth - 1} other Blocks, more than the ${limits.blockDepth - 1} a Block may be in`
29
+ });
30
+ return [...problems, ...secretArguments(state, where)];
31
+ };
32
+ //#endregion
33
+ export { blockProblems };
@@ -7,8 +7,10 @@ import { edges, reachable } from "./graph.js";
7
7
  import { reservedVariables } from "./names.js";
8
8
  import { builtInFunctions } from "./reads.js";
9
9
  import { readProblems } from "./check-reads.js";
10
+ import { allStates } from "./inner.js";
10
11
  import { connectionProblems } from "./used-connections.js";
11
12
  import { visibleVariables } from "./visible.js";
13
+ import { blockProblems } from "./check-block.js";
12
14
  import { nestingDepth } from "../nesting.js";
13
15
  //#region src/definition/check-definition.ts
14
16
  const missingArguments = (state, options) => {
@@ -71,23 +73,33 @@ const machineProblems = (machine, scope, options) => {
71
73
  for (const { field, source, place } of stateExpressions(state)) for (const message of readProblems(source, {
72
74
  place,
73
75
  visible: visible.get(name),
74
- firstOfItem
76
+ firstOfItem,
77
+ inBlock: scope.blocks > 0
75
78
  })) problems.push({
76
79
  state: where(name),
77
80
  field,
78
81
  message
79
82
  });
80
83
  if (state.Type === "Map") problems.push(...machineProblems(state.ItemProcessor, {
84
+ ...scope,
81
85
  path: [...scope.path, name],
82
86
  outer: visible.get(name),
83
87
  item: true
84
88
  }, options));
89
+ if (state.Type === "Block") {
90
+ problems.push(...blockProblems(state, where(name), scope.blocks + 1));
91
+ problems.push(...machineProblems(state.Processor, {
92
+ path: [...scope.path, name],
93
+ outer: /* @__PURE__ */ new Set(),
94
+ item: false,
95
+ blocks: scope.blocks + 1
96
+ }, options));
97
+ }
85
98
  }
86
99
  return problems;
87
100
  };
88
- const stateNames = (machine) => Object.entries(machine.States).flatMap(([name, state]) => [name, ...state.Type === "Map" ? stateNames(state.ItemProcessor) : []]);
89
101
  const wholeProblems = (definition) => {
90
- const names = stateNames(definition.stateMachine);
102
+ const names = allStates(definition.stateMachine).map(([name]) => name);
91
103
  const problems = [];
92
104
  if (names.length > limits.states) problems.push({
93
105
  field: "stateMachine.States",
@@ -97,7 +109,7 @@ const wholeProblems = (definition) => {
97
109
  for (const name of names) {
98
110
  if (seen.has(name)) problems.push({
99
111
  state: name,
100
- message: "is a state name used twice; names are unique across the whole state machine, Maps included"
112
+ message: "is a state name used twice; names are unique across the whole state machine, Maps and Blocks included"
101
113
  });
102
114
  seen.add(name);
103
115
  }
@@ -122,7 +134,8 @@ const checkDefinition = (definition, options) => {
122
134
  ...machineProblems(document.stateMachine, {
123
135
  path: [],
124
136
  outer: /* @__PURE__ */ new Set(),
125
- item: false
137
+ item: false,
138
+ blocks: 0
126
139
  }, options)
127
140
  ];
128
141
  };
@@ -15,12 +15,18 @@ const contextProblem = (path) => {
15
15
  if (contextReads.some((read) => startsWith(rest, read))) return void 0;
16
16
  return `reads $states.${path.join(".")}; $states.context holds only Execution.Input, Execution.StartTime and Secrets.<NAME>`;
17
17
  };
18
+ /** The reads of an expression, or undefined when it does not parse. */
19
+ const expressionParsed = (source) => {
20
+ const parsed = parse(source);
21
+ return "error" in parsed ? void 0 : expressionReads(parsed.expression);
22
+ };
18
23
  /**
19
24
  * Why an expression breaks the named-reads profile, if it does: it must parse, read no implicit input, read
20
25
  * `$states.input` only in the first state of a Map's item processor, read of `$states.context` only the run's input,
21
- * start time and secrets by name, and read only variables a state that can run before it assigns.
26
+ * start time and secrets by name (inside a Block, not the start time), and read only variables a state that can run
27
+ * before it assigns.
22
28
  */
23
- const readProblems = (source, { place, visible, firstOfItem }) => {
29
+ const readProblems = (source, { place, visible, firstOfItem, inBlock = false }) => {
24
30
  if (source.length > limits.expressionLength) return [`is ${source.length} characters long, more than the ${limits.expressionLength} an expression may be`];
25
31
  const parsed = parse(source);
26
32
  if ("error" in parsed) return [`does not parse: ${parsed.error.message}${parsed.error.position === void 0 ? "" : ` (at character ${parsed.error.position})`}`];
@@ -31,7 +37,12 @@ const readProblems = (source, { place, visible, firstOfItem }) => {
31
37
  const [field = ""] = path;
32
38
  if (field === "input" && firstOfItem) continue;
33
39
  if (field !== "" && field === statesFields[place]) continue;
34
- if (field === "context") {
40
+ if (field === "context" && inBlock && startsWith(path, [
41
+ "context",
42
+ "Execution",
43
+ "StartTime"
44
+ ])) problems.push("reads $states.context.Execution.StartTime, which inside a Block is its own run's start, not part of what it is cached by");
45
+ else if (field === "context") {
35
46
  const problem = contextProblem(path);
36
47
  if (problem) problems.push(problem);
37
48
  } else if (field === "input") problems.push("reads $states.input, which only the first state of a Map's item processor may read (as the item)");
@@ -43,4 +54,4 @@ const readProblems = (source, { place, visible, firstOfItem }) => {
43
54
  return [...new Set(problems)];
44
55
  };
45
56
  //#endregion
46
- export { readProblems };
57
+ export { expressionParsed, readProblems };
@@ -17,7 +17,7 @@ const located = (pointer) => {
17
17
  if (part === "States" && index + 1 < parts.length) {
18
18
  state.push(parts[++index]);
19
19
  field = [];
20
- } else if (part === "ItemProcessor" && parts[index + 1] === "States") continue;
20
+ } else if ((part === "ItemProcessor" || part === "Processor") && parts[index + 1] === "States") continue;
21
21
  else field.push(part);
22
22
  }
23
23
  return {
@@ -30,7 +30,7 @@ const message = (error) => {
30
30
  if (error.keyword === "required") return `${error.params.missingProperty} is missing`;
31
31
  if (error.keyword === "minItems") return `is missing; it needs at least ${String(error.params.limit)}`;
32
32
  if (error.keyword === "const") return `must be ${JSON.stringify(error.params.allowedValue)}`;
33
- if (error.keyword === "discriminator") return "must be one of Task, Choice, Pass, Map, Wait, Succeed and Fail";
33
+ if (error.keyword === "discriminator") return "must be one of Task, Choice, Pass, Map, Block, Wait, Succeed and Fail";
34
34
  if (error.keyword === "pattern" && error.instancePath === "/trigger") return "names a trigger type <plugin>:<key>, such as app:record, or manual";
35
35
  if (error.keyword === "pattern" && error.instancePath.endsWith("/Assign")) return "names a variable with letters, digits and _, starting with a letter";
36
36
  if (error.keyword === "pattern") return "must be an expression written as {% ... %}";
@@ -0,0 +1,10 @@
1
+ import { Problem } from "./problem.js";
2
+ import { Definition } from "./types.js";
3
+ //#region src/definition/check-warnings.d.ts
4
+ /**
5
+ * What a save goes through with but its author should know, each on the state it concerns: a state that reads, after a
6
+ * Wait, a variable a Block assigned before it, whose value may have expired by then. It reads a draft as it stands, so an
7
+ * editor can show them before the definition can be saved.
8
+ */
9
+ export declare const definitionWarnings: (definition: Definition) => Problem[];
10
+ //#endregion
@@ -0,0 +1,57 @@
1
+ import { stateExpressions } from "./expression-fields.js";
2
+ import { edges } from "./graph.js";
3
+ import { expressionParsed } from "./check-reads.js";
4
+ import { innerMachine } from "./inner.js";
5
+ //#region src/definition/check-warnings.ts
6
+ const reachedAvoiding = (machine, start, avoid) => {
7
+ const seen = /* @__PURE__ */ new Set();
8
+ const stack = [start];
9
+ while (stack.length > 0) {
10
+ const name = stack.pop();
11
+ const state = machine.States[name];
12
+ if (seen.has(name) || name === avoid || !state) continue;
13
+ seen.add(name);
14
+ stack.push(...edges(state).map((edge) => edge.target));
15
+ }
16
+ return seen;
17
+ };
18
+ const readVariables = (state) => {
19
+ const names = new Set(stateExpressions(state).flatMap(({ source }) => [...expressionParsed(source)?.variables ?? []]));
20
+ if (state.Type === "Map") for (const inner of Object.values(state.ItemProcessor?.States ?? {})) for (const name of readVariables(inner)) names.add(name);
21
+ return names;
22
+ };
23
+ const machineWarnings = (machine, path) => {
24
+ const where = (name) => [...path, name].join("/");
25
+ const warnings = [];
26
+ for (const [name, state] of Object.entries(machine.States)) {
27
+ const inner = innerMachine(state);
28
+ if (inner) warnings.push(...machineWarnings(inner, [...path, name]));
29
+ if (state.Type !== "Block" || state.Next === void 0 || !state.Assign) continue;
30
+ const assigned = new Set(Object.keys(state.Assign));
31
+ const waits = [...reachedAvoiding(machine, state.Next, name)].filter((other) => machine.States[other].Type === "Wait");
32
+ const warned = /* @__PURE__ */ new Set();
33
+ for (const wait of waits) {
34
+ const after = machine.States[wait];
35
+ if (!("Next" in after) || after.Next === void 0) continue;
36
+ for (const reader of reachedAvoiding(machine, after.Next, name)) {
37
+ const read = [...readVariables(machine.States[reader])].filter((variable) => assigned.has(variable));
38
+ if (read.length === 0 || warned.has(reader)) continue;
39
+ warned.add(reader);
40
+ const names = read.map((variable) => `$${variable}`).join(", ");
41
+ warnings.push({
42
+ state: where(reader),
43
+ message: `reads ${names} after the Wait "${wait}", and the Block "${name}" set it before that Wait. If it holds something that expires, such as a signed link, it may have expired by then: set it after the Wait instead. If it holds what the block stored, you can leave it.`
44
+ });
45
+ }
46
+ }
47
+ }
48
+ return warnings;
49
+ };
50
+ /**
51
+ * What a save goes through with but its author should know, each on the state it concerns: a state that reads, after a
52
+ * Wait, a variable a Block assigned before it, whose value may have expired by then. It reads a draft as it stands, so an
53
+ * editor can show them before the definition can be saved.
54
+ */
55
+ const definitionWarnings = (definition) => machineWarnings(definition.stateMachine, []);
56
+ //#endregion
57
+ export { definitionWarnings };
@@ -11,7 +11,7 @@ const stateExpressions = (state) => {
11
11
  place
12
12
  });
13
13
  };
14
- const after = state.Type === "Task" || state.Type === "Map" ? "result" : "state";
14
+ const after = state.Type === "Task" || state.Type === "Map" || state.Type === "Block" ? "result" : "state";
15
15
  if (state.Type === "Fail") {
16
16
  add(state.Error, ["Error"], "state");
17
17
  add(state.Cause, ["Cause"], "state");
@@ -21,6 +21,10 @@ const stateExpressions = (state) => {
21
21
  if ("Assign" in state) add(state.Assign, ["Assign"], after);
22
22
  if (state.Type === "Task") add(state.Arguments, ["Arguments"], "state");
23
23
  if (state.Type === "Map") add(state.Items, ["Items"], "state");
24
+ if (state.Type === "Block") {
25
+ add(state.Arguments, ["Arguments"], "state");
26
+ add(state.Cache?.Key, ["Cache", "Key"], "state");
27
+ }
24
28
  if (state.Type === "Wait") {
25
29
  add(state.Seconds, ["Seconds"], "state");
26
30
  add(state.Timestamp, ["Timestamp"], "state");
@@ -0,0 +1,11 @@
1
+ import { BlockState, Definition, Machine, State } from "./types.js";
2
+ //#region src/definition/inner.d.ts
3
+ /** The steps a state holds: a Map's item processor or a Block's processor; none for any other state. */
4
+ export declare const innerMachine: (state: State | undefined) => Machine | undefined;
5
+ /** Every state of a machine with its name, the ones inside Maps and Blocks too, outer ones first. */
6
+ export declare const allStates: (machine: Machine) => [string, State][];
7
+ /** The Block named `name` anywhere in a machine; names are unique across the document. */
8
+ export declare const findBlock: (machine: Machine, name: string) => BlockState | undefined;
9
+ /** The definition a block's run runs: the Block `name`'s processor as its state machine; undefined when it has no such Block. */
10
+ export declare const blockDefinition: (definition: Definition, name: string) => Definition | undefined;
11
+ //#endregion
@@ -0,0 +1,29 @@
1
+ //#region src/definition/inner.ts
2
+ /** The steps a state holds: a Map's item processor or a Block's processor; none for any other state. */
3
+ const innerMachine = (state) => {
4
+ if (state?.Type === "Map") return state.ItemProcessor;
5
+ if (state?.Type === "Block") return state.Processor;
6
+ };
7
+ /** Every state of a machine with its name, the ones inside Maps and Blocks too, outer ones first. */
8
+ const allStates = (machine) => Object.entries(machine.States).flatMap(([name, state]) => {
9
+ const inner = innerMachine(state);
10
+ return [[name, state], ...inner ? allStates(inner) : []];
11
+ });
12
+ /** The Block named `name` anywhere in a machine; names are unique across the document. */
13
+ const findBlock = (machine, name) => {
14
+ const found = allStates(machine).find(([other]) => other === name)?.[1];
15
+ return found?.Type === "Block" ? found : void 0;
16
+ };
17
+ /** The definition a block's run runs: the Block `name`'s processor as its state machine; undefined when it has no such Block. */
18
+ const blockDefinition = (definition, name) => {
19
+ const block = findBlock(definition.stateMachine, name);
20
+ return block && {
21
+ ...definition,
22
+ stateMachine: {
23
+ ...block.Processor,
24
+ QueryLanguage: "JSONata"
25
+ }
26
+ };
27
+ };
28
+ //#endregion
29
+ export { allStates, blockDefinition, findBlock, innerMachine };
@@ -269,6 +269,28 @@ export declare const definitionSchema: {
269
269
  type: string;
270
270
  additionalProperties: boolean;
271
271
  required: string[];
272
+ }, {
273
+ properties: {
274
+ Type: {
275
+ const: string;
276
+ };
277
+ Comment: {
278
+ type: string;
279
+ };
280
+ Output: {};
281
+ Assign: {
282
+ type: string;
283
+ propertyNames: {
284
+ pattern: string;
285
+ };
286
+ };
287
+ QueryLanguage: {
288
+ const: string;
289
+ };
290
+ };
291
+ type: string;
292
+ additionalProperties: boolean;
293
+ required: string[];
272
294
  }];
273
295
  };
274
296
  };
@@ -265,6 +265,24 @@ const definitionSchema = {
265
265
  }, {
266
266
  required: ["ItemProcessor", "Items"],
267
267
  ...nextOrEnd
268
+ }),
269
+ state("Block", {
270
+ ...flow,
271
+ ...recovery,
272
+ Arguments: {},
273
+ Processor: { $ref: "#/definitions/machine" },
274
+ Cache: {
275
+ type: "object",
276
+ additionalProperties: false,
277
+ required: ["Ttl"],
278
+ properties: {
279
+ Ttl: { type: ["integer", "string"] },
280
+ Key: {}
281
+ }
282
+ }
283
+ }, {
284
+ required: ["Processor", "Cache"],
285
+ ...nextOrEnd
268
286
  })
269
287
  ]
270
288
  }
@@ -73,7 +73,27 @@ export type MapState = Common & Flow & {
73
73
  Retry?: Retrier[];
74
74
  Catch?: Catcher[];
75
75
  };
76
- export type State = PassState | TaskState | ChoiceState | WaitState | SucceedState | FailState | MapState;
76
+ /**
77
+ * A block's cache: how long a result serves (a duration such as `1 hour`, or seconds; at most 30 days), and an optional
78
+ * key whose value, as JSON, replaces the default key: the values of its input its steps read.
79
+ */
80
+ export type BlockCache = {
81
+ Ttl: string | number;
82
+ Key?: Template;
83
+ };
84
+ /**
85
+ * Steps wrapped into one: its `Processor` runs as a run of its own on the evaluated `Arguments` as that run's input, once
86
+ * while its key stays the same, its result cached for `Cache.Ttl`.
87
+ */
88
+ export type BlockState = Common & Flow & {
89
+ Type: 'Block';
90
+ Arguments?: Template;
91
+ Processor: Machine;
92
+ Cache: BlockCache;
93
+ Retry?: Retrier[];
94
+ Catch?: Catcher[];
95
+ };
96
+ export type State = PassState | TaskState | ChoiceState | WaitState | SucceedState | FailState | MapState | BlockState;
77
97
  /** States and where they start: a whole state machine, or a Map's item processor. */
78
98
  export type Machine = {
79
99
  StartAt: string;
@@ -1,5 +1,7 @@
1
+ import { allStates } from "./inner.js";
1
2
  //#region src/definition/used-connections.ts
2
- const resources = (machine) => Object.values(machine.States).flatMap((state) => state.Type === "Task" ? [state.Resource] : state.Type === "Map" ? resources(state.ItemProcessor) : []);
3
+ /** Every Task's step type, the ones inside Maps and Blocks too. */
4
+ const resources = (machine) => allStates(machine).flatMap(([, state]) => state.Type === "Task" ? [state.Resource] : []);
3
5
  /**
4
6
  * The connections `<plugin>:<connection>` a definition's trigger and steps sign in with, given the connection each
5
7
  * type uses by its id (`connectionOf`).
@@ -17,4 +19,4 @@ const connectionProblems = (definition, connectionOf) => {
17
19
  }));
18
20
  };
19
21
  //#endregion
20
- export { connectionProblems, usedConnections };
22
+ export { connectionProblems, resources, usedConnections };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  import { Problem, problemText } from "./definition/problem.js";
2
- import { Catcher, ChoiceRule, ChoiceState, Definition, Machine, MapState, Retrier, State, StateMachine, TaskState, Trigger } from "./definition/types.js";
2
+ import { BlockCache, BlockState, Catcher, ChoiceRule, ChoiceState, Definition, Machine, MapState, Retrier, State, StateMachine, TaskState, Trigger } from "./definition/types.js";
3
3
  import { TriggerCheck } from "./definition/check-trigger.js";
4
4
  import { CheckOptions, checkDefinition } from "./definition/check-definition.js";
5
5
  import { definitionSchema } from "./definition/schema.js";
6
+ import { definitionWarnings } from "./definition/check-warnings.js";
7
+ import { allStates, blockDefinition, findBlock, innerMachine } from "./definition/inner.js";
6
8
  import { usedConnections } from "./definition/used-connections.js";
7
9
  import { limits } from "./limits.js";
8
10
  import { nestingDepth } from "./nesting.js";
@@ -10,7 +12,7 @@ import { ErrorOutput, StepError } from "./run/errors.js";
10
12
  import { Redactor, redacted, secretRedactor, shortestSecret } from "./run/redact.js";
11
13
  import { KeyShape } from "./run/cache/cache-key.js";
12
14
  import { CacheCall, CacheEntry, CacheIdentity, StepCacheStore } from "./run/cache/cache-port.js";
13
- import { Checkpoint, LoadedRun, ReplayedStep, RunChange, RunStatus, RunStore, SegmentQueue, StepLog, StepRecord, StepStatus, TaskContext, TaskHandler, TaskHandlers, TraceMode, TraceSink } from "./run/port.js";
15
+ import { BlockRun, BlockRunStore, Checkpoint, LoadedRun, ReplayedStep, RunChange, RunStatus, RunStore, SegmentQueue, StepLog, StepRecord, StepStatus, TaskContext, TaskHandler, TaskHandlers, TraceMode, TraceSink } from "./run/port.js";
14
16
  import { EarlierCheckpoint, keptAssigned, rerunCheckpoint, rerunProblem, resultRead } from "./run/rerun.js";
15
17
  import { RerunFrom, rerunFrom } from "./run/rerun-from.js";
16
18
  import { heldBackLog } from "./run/replay.js";
@@ -22,4 +24,4 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
22
24
  import { TypeEntry, Unavailable, typeList } from "./plugin/type-list.js";
23
25
  import { ConnectionSupport, connectionUnavailable } from "./plugin/connection-availability.js";
24
26
  import { CatalogEntry, TypeCatalog, typeCatalog } from "./plugin/type-catalog.js";
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 };
27
+ export { type BlockCache, type BlockRun, type BlockRunStore, type BlockState, 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, 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 };
package/dist/index.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import { limits } from "./limits.js";
2
2
  import { definitionSchema } from "./definition/schema.js";
3
3
  import { problemText } from "./definition/problem.js";
4
+ import { allStates, blockDefinition, findBlock, innerMachine } from "./definition/inner.js";
4
5
  import { usedConnections } from "./definition/used-connections.js";
5
6
  import { nestingDepth } from "./nesting.js";
6
7
  import { checkDefinition } from "./definition/check-definition.js";
8
+ import { definitionWarnings } from "./definition/check-warnings.js";
7
9
  import { StepError } from "./run/errors.js";
8
10
  import { redacted, secretRedactor, shortestSecret } from "./run/redact.js";
9
11
  import { keptAssigned, rerunCheckpoint, rerunProblem, resultRead } from "./run/rerun.js";
@@ -17,4 +19,4 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
17
19
  import { typeList } from "./plugin/type-list.js";
18
20
  import { connectionUnavailable } from "./plugin/connection-availability.js";
19
21
  import { typeCatalog } from "./plugin/type-catalog.js";
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 };
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 };
package/dist/limits.d.ts CHANGED
@@ -18,6 +18,11 @@ export declare const limits: {
18
18
  readonly retryDelaySeconds: number;
19
19
  /** Items a Map runs at once; 0 or none means this limit. */
20
20
  readonly mapConcurrency: 20;
21
+ /** Blocks nested in one another, and the runs of blocks one run starts. */
22
+ readonly blockDepth: 4;
23
+ readonly blockRuns: 1000;
24
+ /** The longest a run waits for its block's run before it looks again; the block's run wakes it as it ends. */
25
+ readonly blockWaitSeconds: number;
21
26
  /** Items one Map takes. */
22
27
  readonly mapItems: 10000;
23
28
  /** Steps one run may take, every attempt and every Map item's steps counted. */
package/dist/limits.js CHANGED
@@ -18,6 +18,11 @@ const limits = {
18
18
  retryDelaySeconds: 86400,
19
19
  /** Items a Map runs at once; 0 or none means this limit. */
20
20
  mapConcurrency: 20,
21
+ /** Blocks nested in one another, and the runs of blocks one run starts. */
22
+ blockDepth: 4,
23
+ blockRuns: 1e3,
24
+ /** The longest a run waits for its block's run before it looks again; the block's run wakes it as it ends. */
25
+ blockWaitSeconds: 86400,
21
26
  /** Items one Map takes. */
22
27
  mapItems: 1e4,
23
28
  /** Steps one run may take, every attempt and every Map item's steps counted. */
@@ -1,6 +1,7 @@
1
1
  import { limits } from "../limits.js";
2
2
  import { jsonBytes } from "../run/json-bytes.js";
3
3
  import { cacheKey } from "../run/cache/cache-key.js";
4
+ import { tolerant } from "../run/cache/tolerant.js";
4
5
  import { trackReads } from "../run/cache/read-tracker.js";
5
6
  //#region src/plugin/cached-run.ts
6
7
  /** A result a step took from `earlier`: the cache keeps its entry as it is. */
@@ -11,23 +12,6 @@ var Reused = class {
11
12
  }
12
13
  };
13
14
  const reuse = (output) => new Reused(output);
14
- const late = Symbol("late");
15
- const tolerant = async (task, what, call) => {
16
- let timer;
17
- const timeout = new Promise((resolve) => timer = setTimeout(resolve, limits.cacheLookupMs, late));
18
- try {
19
- const result = await Promise.race([call(), timeout]);
20
- if (result !== late) return result;
21
- task.log(`The cache took too long to ${what}; the step ran without it`);
22
- return;
23
- } catch (error) {
24
- if (task.signal.aborted) throw error;
25
- task.log(`The cache could not ${what}; the step ran without it`);
26
- return;
27
- } finally {
28
- clearTimeout(timer);
29
- }
30
- };
31
15
  const watched = (services, mailbox, actsAs, used) => {
32
16
  const mark = (name, target) => {
33
17
  if (actsAs.includes(name)) return target;
@@ -1,5 +1,6 @@
1
1
  import { StepError } from "../run/errors.js";
2
2
  import { cachePlan } from "./cache-plan.js";
3
+ import { ConnectionError } from "./connection-error.js";
3
4
  import { cachedRun, reuse } from "./cached-run.js";
4
5
  import { writesFor } from "./writes.js";
5
6
  import { Ajv } from "ajv";
@@ -42,7 +43,20 @@ const handler = (id, type, wiring) => {
42
43
  if (connection && plan.identity.connection) await connection.accessToken();
43
44
  return cachedRun(plan, id, parts, task, run);
44
45
  };
45
- return Object.assign(call, { writes: (input) => input !== null && typeof input === "object" && !Array.isArray(input) ? writesFor(type, input) : true });
46
+ const connected = async (task) => {
47
+ if (type.connection === void 0) return true;
48
+ try {
49
+ await wiring.connection(id, type.connection, task).accessToken();
50
+ return true;
51
+ } catch (error) {
52
+ if (error instanceof ConnectionError) return false;
53
+ throw error;
54
+ }
55
+ };
56
+ return Object.assign(call, {
57
+ connected,
58
+ writes: (input) => input !== null && typeof input === "object" && !Array.isArray(input) ? writesFor(type, input) : true
59
+ });
46
60
  };
47
61
  /** The runner's step types from the plugins' steps, each checking its input against its schema before it runs. */
48
62
  const stepHandlers = (plugins, wiring) => Object.fromEntries(plugins.flatMap((plugin) => Object.entries(plugin.steps ?? {}).map(([key, type]) => [`${plugin.name}:${key}`, handler(`${plugin.name}:${key}`, type, wiring)])));
@@ -0,0 +1,146 @@
1
+ import { limits } from "../limits.js";
2
+ import { resources } from "../definition/used-connections.js";
3
+ import { cacheSeconds } from "./cache/cache-ttl.js";
4
+ import { nestingDepth } from "../nesting.js";
5
+ import { StepError } from "./errors.js";
6
+ import { redacted } from "./redact.js";
7
+ import { jsonBytes } from "./json-bytes.js";
8
+ import { blockKey } from "./cache/block-key.js";
9
+ import { tolerant } from "./cache/tolerant.js";
10
+ import { evaluateKept, evaluateTemplate } from "./evaluate.js";
11
+ //#region src/run/block-state.ts
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
+ const identity = {
14
+ saver: true,
15
+ enabler: true,
16
+ bindings: true
17
+ };
18
+ const taskContext = (call) => ({
19
+ runId: call.context.runId,
20
+ signal: call.context.signal,
21
+ idempotencyKey: `${call.context.runId}/${call.scope}/${call.position.seq}`,
22
+ log: (message) => void call.logs.push({
23
+ at: call.context.now().toISOString(),
24
+ message: call.context.redactor.text(message)
25
+ }),
26
+ redact: call.context.redactor.text,
27
+ secret: call.context.redactor.add
28
+ });
29
+ const connected = async (state, call) => {
30
+ for (const type of new Set(resources(state.Processor))) {
31
+ const check = call.context.tasks[type]?.connected;
32
+ if (check && !await check(taskContext(call))) return false;
33
+ }
34
+ return true;
35
+ };
36
+ const blockInput = async (state, call) => {
37
+ const args = await evaluateTemplate(state.Arguments ?? {}, call.bindings, "Arguments");
38
+ if (JSON.stringify(call.context.redactor.value(args)) !== JSON.stringify(args)) throw new StepError("States.Runtime", "Arguments: holds a secret's value, which the block's run would keep; read the secret inside the block as $states.context.Secrets.<NAME>");
39
+ const bytes = jsonBytes(args);
40
+ if (bytes > limits.inputBytes) throw new StepError("States.DataLimitExceeded", `Arguments: ${bytes} bytes as JSON, over the ${limits.inputBytes / 1024} KiB a run's input may be`);
41
+ if (nestingDepth(args, limits.inputDepth) > limits.inputDepth) throw new StepError("States.DataLimitExceeded", `Arguments: nest more than ${limits.inputDepth} levels`);
42
+ return args;
43
+ };
44
+ const hit = (entry, input, call) => {
45
+ const kept = entry.output;
46
+ call.logs.push({
47
+ at: call.context.now().toISOString(),
48
+ message: `An earlier result from ${entry.cachedAt.toISOString()} was in the cache`
49
+ });
50
+ return {
51
+ result: kept.value ?? null,
52
+ input,
53
+ recorded: true,
54
+ fetchedAt: entry.cachedAt,
55
+ run: kept.run,
56
+ reused: true
57
+ };
58
+ };
59
+ const ended = async (run, input, call, keep) => {
60
+ if (run.status === "failed") return {
61
+ failure: {
62
+ Error: run.error ?? "States.Runtime",
63
+ Cause: run.cause ?? ""
64
+ },
65
+ input,
66
+ recorded: true,
67
+ run: run.id
68
+ };
69
+ if (run.blanked) call.logs.push({
70
+ at: call.context.now().toISOString(),
71
+ message: "The result was not cached: its run's output held a secret"
72
+ });
73
+ else await keep({
74
+ ...run.output !== void 0 && run.output !== null && { value: run.output },
75
+ run: run.id
76
+ });
77
+ const fetchedAt = run.finishedAt ?? call.context.now();
78
+ call.logs.push({
79
+ at: call.context.now().toISOString(),
80
+ message: `The block's run fetched its result at ${fetchedAt.toISOString()}`
81
+ });
82
+ return {
83
+ result: run.output ?? null,
84
+ input,
85
+ recorded: true,
86
+ fetchedAt,
87
+ run: run.id
88
+ };
89
+ };
90
+ /**
91
+ * One try of a Block: the result of an earlier run of it with the same key and identity while that entry serves, else a
92
+ * run of its own on its Arguments, which this run waits for. Each try starts at most one run, which a later segment of
93
+ * the try finds again; a result, an empty one too, is kept for `Cache.Ttl`, and a failure is not.
94
+ */
95
+ const runBlock = async (state, call) => {
96
+ const input = await blockInput(state, call);
97
+ const recordedInput = redacted(input);
98
+ if (call.context.replay) return {
99
+ held: true,
100
+ input: recordedInput
101
+ };
102
+ const blocks = call.context.blocks;
103
+ if (!blocks) throw new StepError("States.Runtime", "This app keeps no runs of blocks");
104
+ const waiting = {
105
+ kind: "blocked",
106
+ until: new Date(call.context.now().getTime() + limits.blockWaitSeconds * 1e3)
107
+ };
108
+ const visit = `${call.scope}|${call.position.seq}`;
109
+ const task = taskContext(call);
110
+ const cache = call.context.cache;
111
+ const custom = state.Cache.Key === void 0 ? void 0 : { value: await evaluateKept(state.Cache.Key, call.bindings, "Cache.Key") };
112
+ const key = cache && await blockKey(state, input, custom, cache.nameSecrets);
113
+ const keep = async (kept) => {
114
+ const seconds = cacheSeconds(state.Cache.Ttl);
115
+ if (!cache || !key || seconds === void 0) return;
116
+ await tolerant(task, "be written", () => cache.store.write({
117
+ runId: call.context.runId,
118
+ type: key.type,
119
+ identity,
120
+ key: key.key,
121
+ shape: { custom: true },
122
+ output: kept,
123
+ seconds,
124
+ secrets: key.secrets
125
+ }));
126
+ };
127
+ const started = await blocks.find(visit);
128
+ if (started) return started.status === "succeeded" || started.status === "failed" ? ended(started, recordedInput, call, keep) : waiting;
129
+ const entry = cache && key ? await tolerant(task, "be read", () => cache.store.lookup({
130
+ runId: call.context.runId,
131
+ type: key.type,
132
+ identity,
133
+ keys: [key.key]
134
+ })) : void 0;
135
+ if (entry && entry.secretsChanged.length === 0 && await connected(state, call)) return hit(entry, recordedInput, call);
136
+ const count = await blocks.count();
137
+ if (count >= limits.blockRuns) throw new StepError("States.DataLimitExceeded", `The run started ${count} runs of blocks, the most one run may start (${limits.blockRuns})`);
138
+ if (!await blocks.start({
139
+ visit,
140
+ state: call.name,
141
+ input
142
+ })) throw new StepError("States.Runtime", `"${call.name}" is not a Block of the version this run runs`);
143
+ return waiting;
144
+ };
145
+ //#endregion
146
+ export { runBlock };
@@ -0,0 +1,29 @@
1
+ import { blockReads } from "../../definition/block-reads.js";
2
+ import { canonicalJson } from "./canonical.js";
3
+ import { at, cacheKey } from "./cache-key.js";
4
+ //#region src/run/cache/block-key.ts
5
+ const hex = (bytes) => [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
6
+ /** The cache type of a Block: its processor's SHA-256, so its entries are its own and a changed block starts afresh. */
7
+ const blockType = async (state) => `block:${hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonicalJson(state.Processor))))}`;
8
+ /**
9
+ * The cache key of one visit of a Block, as `cacheKey` makes it: over the values of its input (`args`) that its steps
10
+ * read, by path, and the names of the secrets they read, or over the value of its `Key` when it has one (`custom`).
11
+ * `secrets` names every secret the entry depends on, whose change the store tells. Undefined when the value has no JSON form.
12
+ */
13
+ const blockKey = async (state, args, custom, nameSecrets) => {
14
+ const type = await blockType(state);
15
+ const reads = blockReads(state.Processor);
16
+ const value = custom ? { key: custom.value ?? null } : {
17
+ input: reads.input.map((path) => [path, ...at(args, path)]),
18
+ secrets: reads.secrets
19
+ };
20
+ const key = await cacheKey(type, { custom: true }, value, nameSecrets);
21
+ if (!key) return;
22
+ return {
23
+ type,
24
+ key: key.key,
25
+ secrets: [.../* @__PURE__ */ new Set([...key.secrets, ...reads.secrets])].sort()
26
+ };
27
+ };
28
+ //#endregion
29
+ export { blockKey, blockType };
@@ -37,4 +37,4 @@ const cacheKey = async (type, shape, value, nameSecrets) => {
37
37
  };
38
38
  };
39
39
  //#endregion
40
- export { cacheKey };
40
+ export { at, cacheKey };
@@ -3,11 +3,13 @@ import { KeyShape } from "./cache-key.js";
3
3
  //#region src/run/cache/cache-port.d.ts
4
4
  /**
5
5
  * Who a cached result was made as, beside the run's tenant, which every entry is kept under: the account the run's
6
- * version binds to the type's `connection` (`<plugin>:<name>`), the person who saved it (`saver`, as records act), and
7
- * the person who turned it on (`enabler`, as the mailbox sends). The store reads them from the run, never from the step.
6
+ * version binds to the type's `connection` (`<plugin>:<name>`), or with `bindings` every account it binds, as a Block's
7
+ * steps may sign in with any; the person who saved it (`saver`, as records act), and the person who turned it on
8
+ * (`enabler`, as the mailbox sends). The store reads them from the run, never from the step.
8
9
  */
9
10
  export type CacheIdentity = {
10
11
  connection?: string;
12
+ bindings?: boolean;
11
13
  saver: boolean;
12
14
  enabler: boolean;
13
15
  };
@@ -0,0 +1,21 @@
1
+ import { limits } from "../../limits.js";
2
+ //#region src/run/cache/tolerant.ts
3
+ const late = Symbol("late");
4
+ const tolerant = async (task, what, call) => {
5
+ let timer;
6
+ const timeout = new Promise((resolve) => timer = setTimeout(resolve, limits.cacheLookupMs, late));
7
+ try {
8
+ const result = await Promise.race([call(), timeout]);
9
+ if (result !== late) return result;
10
+ task.log(`The cache took too long to ${what}; the step ran without it`);
11
+ return;
12
+ } catch (error) {
13
+ if (task.signal.aborted) throw error;
14
+ task.log(`The cache could not ${what}; the step ran without it`);
15
+ return;
16
+ } finally {
17
+ clearTimeout(timer);
18
+ }
19
+ };
20
+ //#endregion
21
+ export { tolerant };
@@ -1,3 +1,4 @@
1
+ import { BlockRun } from "./port.js";
1
2
  //#region src/run/context.d.ts
2
3
  /** A scope that cannot go on in this segment: it waits until a time, or the segment's time is up. */
3
4
  export type Paused = {
@@ -15,4 +16,14 @@ export type ScopeOutcome = {
15
16
  error: string;
16
17
  cause: string;
17
18
  } | Paused;
19
+ /** A run's blocks' runs, as its segment reaches them. */
20
+ export type SegmentBlocks = {
21
+ find: (visit: string) => Promise<BlockRun | undefined>;
22
+ start: (run: {
23
+ visit: string;
24
+ state: string;
25
+ input: unknown;
26
+ }) => Promise<BlockRun | undefined>;
27
+ count: () => Promise<number>;
28
+ };
18
29
  //#endregion
@@ -35,6 +35,10 @@ export type StepRecord = {
35
35
  startedAt: Date;
36
36
  finishedAt: Date;
37
37
  recorded: boolean;
38
+ /** A Block's step: the block's run that gave its result, the one that made the cached entry on a hit. */
39
+ run?: string;
40
+ /** A Block's step whose result was an earlier one the cache kept, so its steps did not run. */
41
+ reused?: true;
38
42
  };
39
43
  /** What a replay takes of a step of the run it replays, as that run's trace keeps it. */
40
44
  export type ReplayedStep = Pick<StepRecord, 'scope' | 'seq' | 'state' | 'status' | 'attempt' | 'output' | 'error' | 'cause'>;
@@ -102,6 +106,8 @@ export type TaskContext = {
102
106
  export type TaskHandler = ((args: unknown, context: TaskContext) => Promise<unknown>) & {
103
107
  /** 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. */
104
108
  writes?: (args: unknown) => boolean;
109
+ /** For a type that signs in through a connection: whether the run may still use its account, as a call would find. */
110
+ connected?: (context: TaskContext) => Promise<boolean>;
105
111
  };
106
112
  /** The interpreter's back end: the step types by the name a Task's `Resource` gives. */
107
113
  export type TaskHandlers = Readonly<Record<string, TaskHandler>>;
@@ -121,6 +127,10 @@ export type LoadedRun = {
121
127
  id: string;
122
128
  definition: Definition;
123
129
  } | null;
130
+ /** A block's run: the run that started it, which it wakes as it ends; null for a replay or re-run of one. */
131
+ blockOf?: string | null;
132
+ /** A block's run, or a replay or re-run of one: the Block whose processor it runs, of `definition`. */
133
+ blockState?: string | null;
124
134
  };
125
135
  export type RunStatus = 'queued' | 'running' | 'waiting' | 'succeeded' | 'failed';
126
136
  /** What changes on a run as a segment ends. */
@@ -129,9 +139,12 @@ export type RunChange = {
129
139
  } | {
130
140
  status: 'waiting';
131
141
  resumeAt: Date;
132
- } | {
142
+ } |
143
+ /** `blanked`: the output held a secret, which it keeps blanked out. */
144
+ {
133
145
  status: 'succeeded';
134
146
  output: unknown;
147
+ blanked: boolean;
135
148
  } | {
136
149
  status: 'failed';
137
150
  error: string;
@@ -153,9 +166,39 @@ export type RunStore<Db> = {
153
166
  /** Changes the run unless it has ended already; a run that ends drops its checkpoints. */
154
167
  update(db: Db, runId: string, change: RunChange): Promise<void>;
155
168
  };
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. */
169
+ /**
170
+ * The jobs queue: the second part of the port, which runs a segment of the run at `at`, or as soon as it can; `wake`
171
+ * runs one as soon as it can even when one waits for a later time.
172
+ */
157
173
  export type SegmentQueue<Db> = {
158
174
  schedule(db: Db, runId: string, at?: Date): Promise<void>;
175
+ wake(db: Db, runId: string): Promise<void>;
176
+ };
177
+ /** A block's run as the run that started it sees it. */
178
+ export type BlockRun = {
179
+ id: string;
180
+ status: RunStatus;
181
+ output?: unknown;
182
+ error?: string | null;
183
+ cause?: string | null;
184
+ finishedAt?: Date | null;
185
+ blanked?: boolean | null;
186
+ };
187
+ /**
188
+ * Where blocks' runs are kept: each is a run of its own, started by a run (`parent`) on one try of one of its Blocks
189
+ * (`visit`), whose tenant, workflow, version and trace setting it takes from that run.
190
+ */
191
+ export type BlockRunStore<Db> = {
192
+ find(db: Db, parent: string, visit: string): Promise<BlockRun | undefined>;
193
+ /** Starts it and queues its first segment, or the one of this visit started already; undefined when `state` is no Block of the run's version. */
194
+ start(db: Db, run: {
195
+ parent: string;
196
+ visit: string;
197
+ state: string;
198
+ input: unknown;
199
+ }): Promise<BlockRun | undefined>;
200
+ /** The block runs `parent` started. */
201
+ count(db: Db, parent: string): Promise<number>;
159
202
  };
160
203
  /** Which runs keep a trace: every run, only those that fail, or none. */
161
204
  export type TraceMode = NonNullable<Definition['trace']>;
@@ -6,6 +6,8 @@ const redacted = (value) => {
6
6
  if (typeof value !== "object" || value === null) return value;
7
7
  return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, secretKey.test(key) ? "[redacted]" : redacted(item)]));
8
8
  };
9
+ /** What a secret's value is replaced by, wherever it appears. */
10
+ const blankedMark = "[redacted]";
9
11
  /** Secret values shorter than this are refused, so blanking them never blanks ordinary text. */
10
12
  const shortestSecret = 8;
11
13
  const urlEncoded = (text) => {
@@ -28,7 +30,7 @@ const secretRedactor = (secrets) => {
28
30
  for (const form of [secret, urlEncoded(secret)]) if (form !== void 0 && !ordered.includes(form)) ordered.push(form);
29
31
  ordered.sort((a, b) => b.length - a.length);
30
32
  };
31
- const text = (input) => ordered.reduce((result, secret) => result.replaceAll(secret, "[redacted]"), input);
33
+ const text = (input) => ordered.reduce((result, secret) => result.replaceAll(secret, blankedMark), input);
32
34
  const value = (input) => {
33
35
  if (ordered.length === 0) return input;
34
36
  if (typeof input === "string") return text(input);
@@ -50,4 +52,4 @@ const secretRedactor = (secrets) => {
50
52
  };
51
53
  };
52
54
  //#endregion
53
- export { redacted, secretRedactor, shortestSecret };
55
+ export { blankedMark, redacted, secretRedactor, shortestSecret };
@@ -16,7 +16,7 @@ const stateIn = (machine, maps, name) => {
16
16
  /**
17
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
18
  * `logical` names it by visits: its
19
- * error, or its result, which only a Task that did not shape it with `Output` saved as it was. Undefined when that
19
+ * error, or its result, which only a Task or Block that did not shape it with `Output` saved as it was. Undefined when that
20
20
  * run has no such step, its step was still retrying, or saved its result shaped.
21
21
  */
22
22
  const replayedOutcome = (replay, at) => {
@@ -27,7 +27,7 @@ const replayedOutcome = (replay, at) => {
27
27
  Cause: step.cause ?? ""
28
28
  } };
29
29
  const state = stateIn(replay.machine, mapNames(at.scope), at.name);
30
- if (state?.Type !== "Task" || state.Output !== void 0) return;
30
+ if (state?.Type !== "Task" && state?.Type !== "Block" || state.Output !== void 0) return;
31
31
  return { result: step.output ?? null };
32
32
  };
33
33
  /** A held-back step the replayed run gave nothing for: a null output, on to its next state. */
@@ -4,6 +4,7 @@ import { redacted } from "./redact.js";
4
4
  import { emptyTask, heldBack, heldBackLog, replayedOutcome } from "./replay.js";
5
5
  import { jsonBytes } from "./json-bytes.js";
6
6
  import { evaluateAssign, evaluateKept, evaluateTemplate, recordedArguments } from "./evaluate.js";
7
+ import { runBlock } from "./block-state.js";
7
8
  import { fanOut } from "./fan-out.js";
8
9
  import { recover } from "./recovery.js";
9
10
  import { stepFunctions } from "./step-functions.js";
@@ -72,6 +73,7 @@ const map = async (state, call) => {
72
73
  const attempt = async (state, call) => {
73
74
  try {
74
75
  if (state.Type === "Task") return await task(state, call);
76
+ if (state.Type === "Block") return await runBlock(state, call);
75
77
  return await map(state, call);
76
78
  } catch (error) {
77
79
  if (!(error instanceof StepError)) throw error;
@@ -102,25 +104,30 @@ const withReplayed = async (state, call) => {
102
104
  };
103
105
  };
104
106
  /**
105
- * A Task or a Map: its result shaped by `Output` and `Assign`, which read it as `$states.result`; a failure,
106
- * its own or an item's, goes to its retriers and catchers. In a recorded Task's `Output` and `Assign`, `$now` is when
107
- * its result was fetched, which the checkpoint keeps as the scope's clock.
107
+ * A Task, a Map or a Block: its result shaped by `Output` and `Assign`, which read it as `$states.result`; a failure,
108
+ * its own or an item's, goes to its retriers and catchers. In a recorded Task's or a Block's `Output` and `Assign`,
109
+ * `$now` is when its result was fetched; the checkpoint keeps when the step ended as the scope's clock.
108
110
  */
109
111
  const runResultState = async (state, call) => {
110
112
  const ran = await withReplayed(state, call);
111
113
  if ("kind" in ran) return ran;
112
114
  const now = call.context.now();
113
- const recorded = { ...ran.recorded && {
114
- recorded: true,
115
- fetchedAt: now
116
- } };
115
+ const fetchedAt = "fetchedAt" in ran && ran.fetchedAt || now;
116
+ const recorded = {
117
+ ...ran.recorded && {
118
+ recorded: true,
119
+ fetchedAt: now
120
+ },
121
+ ..."run" in ran && ran.run !== void 0 && { run: ran.run },
122
+ ..."reused" in ran && ran.reused && { reused: true }
123
+ };
117
124
  const recoverable = "held" in ran ? { ...state.Catch && { Catch: state.Catch } } : state;
118
125
  if ("failure" in ran) return {
119
126
  ...await recover(recoverable, call.position, ran.failure, call.bindings, now, call.logs),
120
127
  ...ran.input !== void 0 && { input: ran.input },
121
128
  ...recorded
122
129
  };
123
- const { now: fetched, millis } = stepFunctions(ran.recorded ? now : call.position.clock, "");
130
+ const { now: fetched, millis } = stepFunctions(ran.recorded ? fetchedAt : call.position.clock, "");
124
131
  const after = {
125
132
  ...call.bindings,
126
133
  now: fetched,
@@ -1,5 +1,5 @@
1
1
  import { StepCacheStore } from "./cache/cache-port.js";
2
- import { LoadedRun, RunStore, SegmentQueue, StepRecord, TaskHandlers, TraceMode, TraceSink } from "./port.js";
2
+ import { BlockRunStore, LoadedRun, RunStore, SegmentQueue, StepRecord, TaskHandlers, TraceMode, TraceSink } from "./port.js";
3
3
  //#region src/run/runner.d.ts
4
4
  /**
5
5
  * The runner's port: where runs are kept, the queue that runs their segments, the step types, the secrets expressions
@@ -10,8 +10,10 @@ export type RunnerPort<Db> = {
10
10
  store: RunStore<Db>;
11
11
  queue: SegmentQueue<Db>;
12
12
  tasks: TaskHandlers;
13
- /** Where step types that cache keep their results. */
13
+ /** Where step types that cache keep their results, and Blocks theirs. */
14
14
  cache?: StepCacheStore;
15
+ /** Where blocks' runs are kept; without it a Block fails. */
16
+ blocks?: BlockRunStore<Db>;
15
17
  secrets?: Readonly<Record<string, string>>;
16
18
  trace?: TraceSink;
17
19
  traceMode?: TraceMode;
@@ -23,7 +25,7 @@ export type RunnerPort<Db> = {
23
25
  * The workflow runner over a port. `start` queues a run's first segment in `db`, which may be the caller's
24
26
  * transaction, so the run starts when it commits; `segment` is what the queue's job runs.
25
27
  */
26
- export declare const createRunner: <Db>({ store, queue, tasks, cache, secrets, trace, traceMode, now, budgetMs, maxSteps }: RunnerPort<Db>) => {
28
+ export declare const createRunner: <Db>({ store, queue, tasks, cache, blocks, secrets, trace, traceMode, now, budgetMs, maxSteps }: RunnerPort<Db>) => {
27
29
  start: (db: Db, runId: string) => Promise<void>;
28
30
  /** The steps an ended run's trace holds, which a re-run from one of them starts from: undefined when it kept none. */
29
31
  readTrace: (runId: string) => Promise<readonly StepRecord[] | undefined>;
@@ -1,13 +1,16 @@
1
1
  import { limits } from "../limits.js";
2
- import { secretRedactor } from "./redact.js";
2
+ import { blockDefinition } from "../definition/inner.js";
3
+ import { blankedMark, secretRedactor } from "./redact.js";
3
4
  import { runSegment } from "./segment.js";
4
5
  //#region src/run/runner.ts
5
6
  const ended = /* @__PURE__ */ new Set(["succeeded", "failed"]);
7
+ const runDefinition = (run, definition = run.definition) => run.blockState ? blockDefinition(definition, run.blockState) : definition;
8
+ const blankedOut = (output) => (JSON.stringify(output) ?? "").includes(blankedMark);
6
9
  /**
7
10
  * The workflow runner over a port. `start` queues a run's first segment in `db`, which may be the caller's
8
11
  * transaction, so the run starts when it commits; `segment` is what the queue's job runs.
9
12
  */
10
- const createRunner = ({ store, queue, tasks, cache, secrets = {}, trace, traceMode = "all", now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
13
+ const createRunner = ({ store, queue, tasks, cache, blocks, secrets = {}, trace, traceMode = "all", now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
11
14
  secretRedactor(Object.values(secrets));
12
15
  return {
13
16
  start: (db, runId) => queue.schedule(db, runId),
@@ -22,25 +25,45 @@ const createRunner = ({ store, queue, tasks, cache, secrets = {}, trace, traceMo
22
25
  */
23
26
  segment: async (db, runId, signal) => {
24
27
  const run = await store.load(db, runId);
25
- if (!run || ended.has(run.status)) return;
28
+ if (!run) return;
29
+ const wake = async () => void (run.blockOf && await queue.wake(db, run.blockOf));
30
+ if (ended.has(run.status)) return wake();
26
31
  await store.update(db, runId, { status: "running" });
32
+ const definition = runDefinition(run);
33
+ if (!definition) {
34
+ await store.update(db, runId, {
35
+ status: "failed",
36
+ error: "States.Runtime",
37
+ cause: `The Block "${run.blockState}" is not in this version of the workflow`
38
+ });
39
+ return wake();
40
+ }
27
41
  const redactor = secretRedactor(Object.values(secrets));
42
+ const blockRuns = blocks && {
43
+ find: (visit) => blocks.find(db, runId, visit),
44
+ start: (block) => blocks.start(db, {
45
+ parent: runId,
46
+ ...block
47
+ }),
48
+ count: () => blocks.count(db, runId)
49
+ };
28
50
  const segment = {
29
51
  runId,
30
- definition: run.definition,
52
+ definition,
31
53
  input: run.input,
32
54
  startedAt: run.startedAt,
33
55
  secrets,
34
56
  redactor,
35
57
  tasks,
36
58
  ...cache && { cache },
59
+ ...blockRuns && { blocks: blockRuns },
37
60
  signal,
38
61
  now,
39
62
  budgetMs,
40
63
  maxSteps
41
64
  };
42
65
  const replayed = run.replayOf === void 0 ? void 0 : {
43
- definition: run.replayOf?.definition ?? run.definition,
66
+ definition: runDefinition(run, run.replayOf?.definition) ?? definition,
44
67
  steps: run.replayOf ? await trace?.read(run.replayOf.id) ?? [] : []
45
68
  };
46
69
  const mode = run.trace ?? run.definition.trace ?? traceMode;
@@ -62,11 +85,13 @@ const createRunner = ({ store, queue, tasks, cache, secrets = {}, trace, traceMo
62
85
  if (outcome.kind === "superseded") return traced();
63
86
  if (outcome.kind === "ended") {
64
87
  await traced("succeeded");
88
+ const output = redactor.value(outcome.output);
65
89
  await store.update(db, runId, {
66
90
  status: "succeeded",
67
- output: redactor.value(outcome.output)
91
+ output,
92
+ blanked: blankedOut(output)
68
93
  });
69
- return;
94
+ return wake();
70
95
  }
71
96
  if (outcome.kind === "failed") {
72
97
  await traced("failed");
@@ -75,7 +100,7 @@ const createRunner = ({ store, queue, tasks, cache, secrets = {}, trace, traceMo
75
100
  error: redactor.text(outcome.error),
76
101
  cause: redactor.text(outcome.cause)
77
102
  });
78
- return;
103
+ return wake();
79
104
  }
80
105
  await traced();
81
106
  if (outcome.kind === "yielded") return queue.schedule(db, runId);
@@ -3,7 +3,7 @@ import { Redactor } from "./redact.js";
3
3
  import { StepCacheStore } from "./cache/cache-port.js";
4
4
  import { Checkpoint, StepRecord, TaskHandlers } from "./port.js";
5
5
  import { Replayed } from "./replay-of.js";
6
- import { ScopeOutcome } from "./context.js";
6
+ import { ScopeOutcome, SegmentBlocks } from "./context.js";
7
7
  //#region src/run/segment.d.ts
8
8
  export type SegmentInput = {
9
9
  runId: string;
@@ -26,6 +26,8 @@ export type SegmentInput = {
26
26
  cache?: StepCacheStore;
27
27
  /** In a replay, the run it replays, with its steps from its trace. */
28
28
  replayed?: Replayed;
29
+ /** The run's blocks' runs; without it a Block fails. */
30
+ blocks?: SegmentBlocks;
29
31
  signal: AbortSignal;
30
32
  now?: () => Date;
31
33
  /** How long the segment takes new steps. Default `limits.segmentMs`. */
@@ -44,5 +46,5 @@ export type SegmentOutcome = (ScopeOutcome | {
44
46
  * (a Wait, a retry's delay), or yields once its time is up, saving its checkpoints on the way and as it pauses.
45
47
  * `superseded` when another segment saved a newer checkpoint first.
46
48
  */
47
- export declare const runSegment: ({ runId, definition, input, startedAt, secrets, redactor, saved, save, keep, tasks, cache, replayed, signal, now, budgetMs, maxSteps }: SegmentInput) => Promise<SegmentOutcome>;
49
+ export declare const runSegment: ({ runId, definition, input, startedAt, secrets, redactor, saved, save, keep, tasks, cache, replayed, blocks, signal, now, budgetMs, maxSteps }: SegmentInput) => Promise<SegmentOutcome>;
48
50
  //#endregion
@@ -9,7 +9,7 @@ import { runScope } from "./scope.js";
9
9
  * (a Wait, a retry's delay), or yields once its time is up, saving its checkpoints on the way and as it pauses.
10
10
  * `superseded` when another segment saved a newer checkpoint first.
11
11
  */
12
- const runSegment = async ({ runId, definition, input, startedAt, secrets, redactor, saved, save, keep, tasks, cache, replayed, signal, now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
12
+ const runSegment = async ({ runId, definition, input, startedAt, secrets, redactor, saved, save, keep, tasks, cache, replayed, blocks, signal, now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
13
13
  const latest = new Map(saved.map((checkpoint) => [checkpoint.scope, checkpoint]));
14
14
  const after = new Map(saved.map((checkpoint) => [checkpoint.scope, checkpoint.seq]));
15
15
  const steps = [];
@@ -52,6 +52,7 @@ const runSegment = async ({ runId, definition, input, startedAt, secrets, redact
52
52
  nameSecrets: secretNamer(secrets)
53
53
  } },
54
54
  ...replayed && { replay: replayOf(replayed) },
55
+ ...blocks && { blocks },
55
56
  signal,
56
57
  now,
57
58
  deadline: Date.now() + budgetMs,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/workflows",
3
- "version": "0.87.1",
3
+ "version": "0.88.0",
4
4
  "description": "Workflows as state machines with JSONata expressions: their check, a runner that saves only what a run needs to go on and traces every step, and the plugin interface for trigger and step types.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {