@protobase/workflows 0.94.45 → 0.95.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.
package/dist/index.d.ts CHANGED
@@ -12,7 +12,7 @@ import { ErrorOutput, StepError } from "./run/errors.js";
12
12
  import { Redactor, redacted, secretRedactor, shortestSecret } from "./run/redact.js";
13
13
  import { KeyShape } from "./run/cache/cache-key.js";
14
14
  import { CacheCall, CacheEntry, CacheIdentity, StepCacheStore } from "./run/cache/cache-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";
15
+ import { BlockRun, BlockRunStore, BlockShare, Checkpoint, LoadedRun, ReplayedStep, RunChange, RunStatus, RunStore, SegmentQueue, StepLog, StepRecord, StepStatus, TaskContext, TaskHandler, TaskHandlers, TraceMode, TraceSink } from "./run/port.js";
16
16
  import { EarlierCheckpoint, keptAssigned, rerunCheckpoint, rerunProblem, resultRead } from "./run/rerun.js";
17
17
  import { RerunFrom, rerunFrom } from "./run/rerun-from.js";
18
18
  import { heldBackLog } from "./run/replay.js";
@@ -24,4 +24,4 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
24
24
  import { TypeEntry, Unavailable, typeList } from "./plugin/type-list.js";
25
25
  import { ConnectionSupport, connectionUnavailable } from "./plugin/connection-availability.js";
26
26
  import { CatalogEntry, TypeCatalog, typeCatalog } from "./plugin/type-catalog.js";
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 };
27
+ export { type BlockCache, type BlockRun, type BlockRunStore, type BlockShare, 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 };
@@ -57,6 +57,11 @@ const hit = (entry, input, call) => {
57
57
  };
58
58
  };
59
59
  const ended = async (run, input, call, keep) => {
60
+ const joined = run.joined ? { joined: true } : {};
61
+ if (run.joined) call.logs.push({
62
+ at: call.context.now().toISOString(),
63
+ message: "This step joined the block's run that another visit had started with the same key, instead of starting another"
64
+ });
60
65
  if (run.status === "failed") return {
61
66
  failure: {
62
67
  Error: run.error ?? "States.Runtime",
@@ -64,7 +69,8 @@ const ended = async (run, input, call, keep) => {
64
69
  },
65
70
  input,
66
71
  recorded: true,
67
- run: run.id
72
+ run: run.id,
73
+ ...joined
68
74
  };
69
75
  if (run.blanked) call.logs.push({
70
76
  at: call.context.now().toISOString(),
@@ -84,13 +90,15 @@ const ended = async (run, input, call, keep) => {
84
90
  input,
85
91
  recorded: true,
86
92
  fetchedAt,
87
- run: run.id
93
+ run: run.id,
94
+ ...joined
88
95
  };
89
96
  };
90
97
  /**
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.
98
+ * One try of a Block: the result of an earlier run of it with the same key and identity while that entry serves, else
99
+ * the run of it with that key and identity under way, which this run joins, else a run of its own on its Arguments.
100
+ * This run waits for either. Each try starts or joins at most one run, which a later segment of the try finds again; a
101
+ * result, an empty one too, is kept for `Cache.Ttl`, and a failure is not.
94
102
  */
95
103
  const runBlock = async (state, call) => {
96
104
  const input = await blockInput(state, call);
@@ -124,8 +132,29 @@ const runBlock = async (state, call) => {
124
132
  secrets: key.secrets
125
133
  }));
126
134
  };
135
+ const take = async (run) => {
136
+ if (run.status !== "succeeded" && run.status !== "failed") return waiting;
137
+ if (run.joined && run.status === "succeeded" && !await connected(state, call)) return begin();
138
+ return ended(run, recordedInput, call, keep);
139
+ };
140
+ const begin = async (share) => {
141
+ const count = await blocks.count();
142
+ const full = count >= limits.blockRuns;
143
+ const limit = () => new StepError("States.DataLimitExceeded", `The run started ${count} runs of blocks, the most one run may start (${limits.blockRuns})`);
144
+ if (full && !share) throw limit();
145
+ const run = await blocks.start({
146
+ visit,
147
+ state: call.name,
148
+ input,
149
+ ...share && { share },
150
+ ...full && { joinOnly: true }
151
+ });
152
+ if (!run && full) throw limit();
153
+ if (!run) throw new StepError("States.Runtime", `"${call.name}" is not a Block of the version this run runs`);
154
+ return take(run);
155
+ };
127
156
  const started = await blocks.find(visit);
128
- if (started) return started.status === "succeeded" || started.status === "failed" ? ended(started, recordedInput, call, keep) : waiting;
157
+ if (started) return take(started);
129
158
  const entry = cache && key ? await tolerant(task, "be read", () => cache.store.lookup({
130
159
  runId: call.context.runId,
131
160
  type: key.type,
@@ -133,14 +162,10 @@ const runBlock = async (state, call) => {
133
162
  keys: [key.key]
134
163
  })) : void 0;
135
164
  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;
165
+ return begin(key && key.secrets.length === 0 && cacheSeconds(state.Cache.Ttl) !== void 0 ? {
166
+ key: key.key,
167
+ identity
168
+ } : void 0);
144
169
  };
145
170
  //#endregion
146
171
  export { runBlock };
@@ -1,4 +1,4 @@
1
- import { BlockRun } from "./port.js";
1
+ import { BlockRun, BlockShare } from "./port.js";
2
2
  //#region src/run/context.d.ts
3
3
  /** A scope that cannot go on in this segment: it waits until a time, or the segment's time is up. */
4
4
  export type Paused = {
@@ -23,6 +23,8 @@ export type SegmentBlocks = {
23
23
  visit: string;
24
24
  state: string;
25
25
  input: unknown;
26
+ share?: BlockShare;
27
+ joinOnly?: true;
26
28
  }) => Promise<BlockRun | undefined>;
27
29
  count: () => Promise<number>;
28
30
  };
@@ -1,5 +1,5 @@
1
1
  import { Definition } from "../definition/types.js";
2
- import { TaskCache } from "./cache/cache-port.js";
2
+ import { CacheIdentity, TaskCache } from "./cache/cache-port.js";
3
3
  //#region src/run/port.d.ts
4
4
  /**
5
5
  * How a step ended: `succeeded`, `retrying` (it failed and a retrier tries it again), `caught` (it failed and a
@@ -39,6 +39,8 @@ export type StepRecord = {
39
39
  run?: string;
40
40
  /** A Block's step whose result was an earlier one the cache kept, so its steps did not run. */
41
41
  reused?: true;
42
+ /** A Block's step that joined a run of the block another visit had started with the same key, instead of starting one. */
43
+ joined?: true;
42
44
  };
43
45
  /** What a replay takes of a step of the run it replays, as that run's trace keeps it. */
44
46
  export type ReplayedStep = Pick<StepRecord, 'scope' | 'seq' | 'state' | 'status' | 'attempt' | 'output' | 'error' | 'cause'>;
@@ -174,7 +176,7 @@ export type SegmentQueue<Db> = {
174
176
  schedule(db: Db, runId: string, at?: Date): Promise<void>;
175
177
  wake(db: Db, runId: string): Promise<void>;
176
178
  };
177
- /** A block's run as the run that started it sees it. */
179
+ /** A block's run as a run that started or joined it sees it; `joined` when another run started it. */
178
180
  export type BlockRun = {
179
181
  id: string;
180
182
  status: RunStatus;
@@ -183,20 +185,35 @@ export type BlockRun = {
183
185
  cause?: string | null;
184
186
  finishedAt?: Date | null;
185
187
  blanked?: boolean | null;
188
+ joined?: boolean;
189
+ };
190
+ /** What a block's run that may be shared is shared by: its cache key, and the identity its entry is kept under. */
191
+ export type BlockShare = {
192
+ key: string;
193
+ identity: CacheIdentity;
186
194
  };
187
195
  /**
188
196
  * 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
197
  * (`visit`), whose tenant, workflow, version and trace setting it takes from that run.
190
198
  */
191
199
  export type BlockRunStore<Db> = {
200
+ /** The run this visit started, else the one it joined. */
192
201
  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. */
202
+ /**
203
+ * Starts it and queues its first segment, or the one of this visit started already; undefined when `state` is no Block
204
+ * of the run's version. With `share`, a run of the same key and identity under way is joined instead of started: it
205
+ * wakes this run too as it ends. With `joinOnly` too, it only joins: undefined when no such run is under way.
206
+ */
194
207
  start(db: Db, run: {
195
208
  parent: string;
196
209
  visit: string;
197
210
  state: string;
198
211
  input: unknown;
212
+ share?: BlockShare;
213
+ joinOnly?: true;
199
214
  }): Promise<BlockRun | undefined>;
215
+ /** The runs that joined `run`, to wake as it ends. */
216
+ waiters(db: Db, run: string): Promise<string[]>;
200
217
  /** The block runs `parent` started. */
201
218
  count(db: Db, parent: string): Promise<number>;
202
219
  };
@@ -119,7 +119,8 @@ const runResultState = async (state, call) => {
119
119
  fetchedAt: now
120
120
  },
121
121
  ..."run" in ran && ran.run !== void 0 && { run: ran.run },
122
- ..."reused" in ran && ran.reused && { reused: true }
122
+ ..."reused" in ran && ran.reused && { reused: true },
123
+ ..."joined" in ran && ran.joined && { joined: true }
123
124
  };
124
125
  const recoverable = "held" in ran ? { ...state.Catch && { Catch: state.Catch } } : state;
125
126
  if ("failure" in ran) return {
@@ -26,7 +26,10 @@ const createRunner = ({ store, queue, tasks, cache, blocks, secrets = {}, trace,
26
26
  segment: async (db, runId, signal) => {
27
27
  const run = await store.load(db, runId);
28
28
  if (!run) return;
29
- const wake = async () => void (run.blockOf && await queue.wake(db, run.blockOf));
29
+ const wake = async () => {
30
+ if (run.blockOf) await queue.wake(db, run.blockOf);
31
+ for (const parent of await blocks?.waiters(db, runId) ?? []) await queue.wake(db, parent);
32
+ };
30
33
  if (ended.has(run.status)) return wake();
31
34
  await store.update(db, runId, { status: "running" });
32
35
  const definition = runDefinition(run);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/workflows",
3
- "version": "0.94.45",
3
+ "version": "0.95.1",
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": {