@protobase/workflows 0.71.5 → 0.71.6

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,6 +12,7 @@ import { KeyShape } from "./run/cache/cache-key.js";
12
12
  import { CacheCall, CacheEntry, CacheIdentity, StepCacheStore } from "./run/cache/cache-port.js";
13
13
  import { LoadedRun, RunChange, RunStatus, RunStore, SavedStep, SegmentQueue, StepLog, StepRecord, StepStatus, TaskContext, TaskHandler, TaskHandlers } from "./run/port.js";
14
14
  import { EarlierStep, rerunSteps } from "./run/rerun.js";
15
+ import { heldBackLog } from "./run/replay.js";
15
16
  import { Runner, RunnerPort, createRunner } from "./run/runner.js";
16
17
  import { SegmentInput, runSegment } from "./run/segment.js";
17
18
  import { LoadedPlugin, loadPlugins } from "./plugin/load-plugins.js";
@@ -20,4 +21,4 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
20
21
  import { TypeEntry, Unavailable, typeList } from "./plugin/type-list.js";
21
22
  import { ConnectionSupport, connectionUnavailable } from "./plugin/connection-availability.js";
22
23
  import { CatalogEntry, TypeCatalog, typeCatalog } from "./plugin/type-catalog.js";
23
- export { type CacheCall, type CacheEntry, type CacheIdentity, type CatalogEntry, type Catcher, type CheckOptions, type ChoiceRule, type ChoiceState, type ConnectionSupport, type Definition, type EarlierStep, type ErrorOutput, type KeyShape, type LoadedPlugin, type LoadedRun, type Machine, type MapState, type Problem, type Redactor, type Retrier, type RunChange, type RunStatus, type RunStore, type Runner, type RunnerPort, type SavedStep, type SegmentInput, type SegmentQueue, type State, type StateMachine, type StepCacheStore, StepError, type StepLog, type StepRecord, type StepStatus, type StepWiring, type TaskContext, type TaskHandler, type TaskHandlers, type TaskState, type Trigger, type TriggerCheck, type TypeCatalog, type TypeEntry, type Unavailable, checkDefinition, connectionUnavailable, createRunner, definitionSchema, limits, loadPlugins, nestingDepth, problemText, redacted, rerunSteps, runSegment, secretRedactor, shortestSecret, stepHandlers, triggerChecks, typeCatalog, typeList, usedConnections };
24
+ export { type CacheCall, type CacheEntry, type CacheIdentity, type CatalogEntry, type Catcher, type CheckOptions, type ChoiceRule, type ChoiceState, type ConnectionSupport, type Definition, type EarlierStep, type ErrorOutput, type KeyShape, type LoadedPlugin, type LoadedRun, type Machine, type MapState, type Problem, type Redactor, type Retrier, type RunChange, type RunStatus, type RunStore, type Runner, type RunnerPort, type SavedStep, type SegmentInput, type SegmentQueue, type State, type StateMachine, type StepCacheStore, StepError, type StepLog, type StepRecord, type StepStatus, type StepWiring, type TaskContext, type TaskHandler, type TaskHandlers, type TaskState, type Trigger, type TriggerCheck, type TypeCatalog, type TypeEntry, type Unavailable, checkDefinition, connectionUnavailable, createRunner, definitionSchema, heldBackLog, limits, loadPlugins, nestingDepth, problemText, redacted, rerunSteps, runSegment, secretRedactor, shortestSecret, stepHandlers, triggerChecks, typeCatalog, typeList, usedConnections };
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ import { checkDefinition } from "./definition/check-definition.js";
7
7
  import { StepError } from "./run/errors.js";
8
8
  import { redacted, secretRedactor, shortestSecret } from "./run/redact.js";
9
9
  import { rerunSteps } from "./run/rerun.js";
10
+ import { heldBackLog } from "./run/replay.js";
10
11
  import { runSegment } from "./run/segment.js";
11
12
  import { createRunner } from "./run/runner.js";
12
13
  import { loadPlugins } from "./plugin/load-plugins.js";
@@ -15,4 +16,4 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
15
16
  import { typeList } from "./plugin/type-list.js";
16
17
  import { connectionUnavailable } from "./plugin/connection-availability.js";
17
18
  import { typeCatalog } from "./plugin/type-catalog.js";
18
- export { StepError, checkDefinition, connectionUnavailable, createRunner, definitionSchema, limits, loadPlugins, nestingDepth, problemText, redacted, rerunSteps, runSegment, secretRedactor, shortestSecret, stepHandlers, triggerChecks, typeCatalog, typeList, usedConnections };
19
+ export { StepError, checkDefinition, connectionUnavailable, createRunner, definitionSchema, heldBackLog, limits, loadPlugins, nestingDepth, problemText, redacted, rerunSteps, runSegment, secretRedactor, shortestSecret, stepHandlers, triggerChecks, typeCatalog, typeList, usedConnections };
@@ -71,8 +71,13 @@ export type PluginMail = {
71
71
  };
72
72
  /** The sign-in a step or trigger declared, bound by its workflow; it names no other. */
73
73
  export type PluginConnection = {
74
- /** A current access token; throws `ConnectionError` when the workflow has no working sign-in for it. */
75
- accessToken(): Promise<string>;
74
+ /**
75
+ * A current access token; throws `ConnectionError` when the workflow has no working sign-in for it. `refresh` gets a
76
+ * new one even before the current one expires, for a token the provider refused.
77
+ */
78
+ accessToken(options?: {
79
+ refresh?: boolean;
80
+ }): Promise<string>;
76
81
  };
77
82
  /** What the app gives every hook of a plugin: its guarded requests, records, files and mail. */
78
83
  export type PluginServices = {
@@ -1,6 +1,7 @@
1
1
  import { StepError } from "../run/errors.js";
2
2
  import { cachePlan } from "./cache-plan.js";
3
3
  import { cachedRun, reuse } from "./cached-run.js";
4
+ import { writesFor } from "./writes.js";
4
5
  import { Ajv } from "ajv";
5
6
  //#region src/plugin/step-handlers.ts
6
7
  const ajv = new Ajv({
@@ -10,7 +11,7 @@ const ajv = new Ajv({
10
11
  const handler = (id, type, wiring) => {
11
12
  const validate = ajv.compile(type.input);
12
13
  const prefix = type.errorPrefix ?? "Step";
13
- return async (input, task) => {
14
+ const call = async (input, task) => {
14
15
  if (!validate(input)) {
15
16
  const problems = (validate.errors ?? []).map((error) => `${error.instancePath.slice(1).replaceAll("/", ".") || "Arguments"} ${error.message}`);
16
17
  throw new StepError(`${prefix}.InvalidArguments`, problems.join("; "));
@@ -41,6 +42,7 @@ const handler = (id, type, wiring) => {
41
42
  if (connection && plan.identity.connection) await connection.accessToken();
42
43
  return cachedRun(plan, id, parts, task, run);
43
44
  };
45
+ return Object.assign(call, { writes: (input) => input !== null && typeof input === "object" && !Array.isArray(input) ? writesFor(type, input) : true });
44
46
  };
45
47
  /** The runner's step types from the plugins' steps, each checking its input against its schema before it runs. */
46
48
  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)])));
@@ -22,6 +22,8 @@ export type TypeEntry = {
22
22
  default?: boolean;
23
23
  disclaimer?: string;
24
24
  };
25
+ /** Whether a step type's call changes the outside world, so a replay does not call it: `by_input` when that depends on its input. */
26
+ writes?: boolean | 'by_input';
25
27
  /** False when this app cannot run it, with the reason; a definition that uses it is not saved. */
26
28
  available: boolean;
27
29
  reason?: string;
@@ -12,7 +12,8 @@ const entry = (plugin, key, type) => ({
12
12
  name: type.connection,
13
13
  ...plugin.connections[type.connection]
14
14
  } },
15
- ..."cache" in type && type.cache && { cache: advice(type.cache) }
15
+ ..."cache" in type && type.cache && { cache: advice(type.cache) },
16
+ ...!("kind" in type) && { writes: typeof type.writes === "function" ? "by_input" : type.writes !== false }
16
17
  });
17
18
  const advice = ({ choice, default: on, disclaimer }) => ({
18
19
  choice,
@@ -20,6 +20,12 @@ export type StepType = Described & {
20
20
  errorPrefix?: string;
21
21
  /** Its result cache; without it the engine keeps and looks up nothing for it unless a workflow forces it on. */
22
22
  cache?: StepCache;
23
+ /**
24
+ * Whether a call changes the outside world, such as sending mail or writing a record: a replay of a run calls no type
25
+ * that writes, and runs those that do not. It must be accurate. Undeclared, a function that throws or one that gives
26
+ * anything but `false`: it writes.
27
+ */
28
+ writes?: boolean | ((input: Record<string, unknown>) => boolean);
23
29
  run: (context: StepContext) => Promise<unknown>;
24
30
  };
25
31
  /** What every trigger type has: its description, and a check of its input beyond its schema, such as a cron's fields. */
@@ -0,0 +1,12 @@
1
+ //#region src/plugin/writes.ts
2
+ /** Whether a call of `type` with `input` writes: only a declared `false`, or a function that gives `false`, reads. */
3
+ const writesFor = (type, input) => {
4
+ if (typeof type.writes !== "function") return type.writes !== false;
5
+ try {
6
+ return type.writes(input) !== false;
7
+ } catch {
8
+ return true;
9
+ }
10
+ };
11
+ //#endregion
12
+ export { writesFor };
@@ -61,7 +61,10 @@ export type TaskContext = {
61
61
  * A step type, which a Task names as its `Resource`: it takes the Task's evaluated `Arguments` and returns its result.
62
62
  * It throws a `StepError` to fail with an error name of its own; any other error is `States.TaskFailed`.
63
63
  */
64
- export type TaskHandler = (args: unknown, context: TaskContext) => Promise<unknown>;
64
+ export type TaskHandler = ((args: unknown, context: TaskContext) => Promise<unknown>) & {
65
+ /** 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. */
66
+ writes?: (args: unknown) => boolean;
67
+ };
65
68
  /** The interpreter's back end: the step types by the name a Task's `Resource` gives. */
66
69
  export type TaskHandlers = Readonly<Record<string, TaskHandler>>;
67
70
  /** A run as the runner loads it: its pinned definition, its input and when it started. */
@@ -71,6 +74,11 @@ export type LoadedRun = {
71
74
  input: unknown;
72
75
  status: RunStatus;
73
76
  startedAt: Date;
77
+ /**
78
+ * The run this one replays: its steps that write are not called but give what that run's steps gave; null when that
79
+ * run is gone, so they give nothing. Absent: no replay.
80
+ */
81
+ replayOf?: string | null;
74
82
  };
75
83
  export type RunStatus = 'queued' | 'running' | 'waiting' | 'succeeded' | 'failed';
76
84
  /** What changes on a run as a segment ends. */
@@ -35,7 +35,8 @@ const advance = (position, step) => {
35
35
  kind: "ended",
36
36
  seq,
37
37
  output,
38
- variables
38
+ variables,
39
+ ...step.resumeAt && { resumeAt: step.resumeAt }
39
40
  };
40
41
  return {
41
42
  kind: "at",
@@ -0,0 +1,4 @@
1
+ //#region src/run/replay.d.ts
2
+ /** The log line of a step a replay held back, which the run's page marks it by. */
3
+ export declare const heldBackLog = "Not sent: replay";
4
+ //#endregion
@@ -0,0 +1,39 @@
1
+ //#region src/run/replay.ts
2
+ /** The log line of a step a replay held back, which the run's page marks it by. */
3
+ const heldBackLog = "Not sent: replay";
4
+ const keyOf = (scope, seq) => `${scope}#${seq}`;
5
+ const replayedSteps = (steps) => new Map(steps.map((step) => [keyOf(step.scope, step.seq), step]));
6
+ /** Whether a replay holds back this call: anything but its type saying `false`, it writes. */
7
+ const heldBack = (context, handler, args) => Boolean(context.replay) && handler?.writes?.(args) !== false;
8
+ /**
9
+ * A Task a replay holds back: it ends as the replayed run's step of the same scope, number and state ended, with its
10
+ * output and variables, or with a null output and on to its next state when that run has no such step.
11
+ */
12
+ const replayedTask = (context, state, at, input, logs) => {
13
+ logs.push({
14
+ at: context.now().toISOString(),
15
+ message: heldBackLog
16
+ });
17
+ const step = context.replay?.steps.get(keyOf(at.scope, at.seq));
18
+ if (!step || step.state !== at.name) return {
19
+ kind: "step",
20
+ status: "succeeded",
21
+ next: state.Next ?? null,
22
+ input,
23
+ output: null,
24
+ logs
25
+ };
26
+ return {
27
+ kind: "step",
28
+ status: step.status,
29
+ next: step.next,
30
+ input,
31
+ output: step.output ?? null,
32
+ ...step.assigned && { assigned: step.assigned },
33
+ ...step.error != null && { error: step.error },
34
+ ...step.cause != null && { cause: step.cause },
35
+ logs
36
+ };
37
+ };
38
+ //#endregion
39
+ export { heldBack, heldBackLog, replayedSteps, replayedTask };
@@ -1,6 +1,7 @@
1
1
  import { limits } from "../limits.js";
2
2
  import { StepError, errorOutput } from "./errors.js";
3
3
  import { redacted } from "./redact.js";
4
+ import { heldBack, replayedTask } from "./replay.js";
4
5
  import { jsonBytes } from "./json-bytes.js";
5
6
  import { evaluateAssign, evaluateKept, evaluateTemplate, recordedArguments } from "./evaluate.js";
6
7
  import { fanOut } from "./fan-out.js";
@@ -12,6 +13,10 @@ const task = async (state, call) => {
12
13
  const args = await evaluateTemplate(state.Arguments ?? {}, call.bindings, "Arguments");
13
14
  const key = `${call.context.runId}/${call.scope}/${call.position.seq - call.position.attempt + 1}`;
14
15
  const input = redacted(recordedArguments(state.Arguments ?? {}, args));
16
+ if (heldBack(call.context, call.context.tasks[state.Resource], args)) return {
17
+ held: true,
18
+ input
19
+ };
15
20
  return runTask(call.context, state, args, key, call.logs).then((result) => ({
16
21
  result,
17
22
  input
@@ -78,6 +83,11 @@ const attempt = async (state, call) => {
78
83
  const runResultState = async (state, call) => {
79
84
  const ran = await attempt(state, call);
80
85
  if ("kind" in ran) return ran;
86
+ if ("held" in ran) return replayedTask(call.context, state, {
87
+ scope: call.scope,
88
+ seq: call.position.seq,
89
+ name: call.name
90
+ }, ran.input, call.logs);
81
91
  const now = call.context.now();
82
92
  if ("failure" in ran) return {
83
93
  ...await recover(state, call.position, ran.failure, call.bindings, now, call.logs),
@@ -34,8 +34,10 @@ const createRunner = ({ store, queue, tasks, cache, secrets = {}, now = () => /*
34
34
  budgetMs,
35
35
  maxSteps
36
36
  };
37
+ const replayed = run.replayOf === void 0 ? void 0 : run.replayOf === null ? [] : await store.steps(db, run.replayOf);
37
38
  const outcome = await runSegment({
38
39
  ...segment,
40
+ ...replayed && { replayed },
39
41
  saved: await store.steps(db, runId),
40
42
  save: (steps) => store.save(db, runId, steps)
41
43
  });
package/dist/run/scope.js CHANGED
@@ -68,15 +68,21 @@ const withinLimits = (record) => {
68
68
  const runScope = async (context, machine, scope, input, outer) => {
69
69
  let position = foldPosition(machine, input, context.saved.get(scope) ?? []);
70
70
  for (;;) {
71
- if (position.kind === "ended") return {
72
- kind: "ended",
73
- output: position.output
74
- };
75
71
  if (position.kind === "failed") return {
76
72
  kind: "failed",
77
73
  error: position.error,
78
74
  cause: position.cause
79
75
  };
76
+ if (position.kind === "ended") {
77
+ if (position.resumeAt && position.resumeAt > context.now()) return {
78
+ kind: "blocked",
79
+ until: position.resumeAt
80
+ };
81
+ return {
82
+ kind: "ended",
83
+ output: position.output
84
+ };
85
+ }
80
86
  if (context.superseded()) throw new SupersededError(`Scope "${scope}" stopped: another segment saved a step of this run first`);
81
87
  if (position.resumeAt && position.resumeAt > context.now()) return {
82
88
  kind: "blocked",
@@ -21,6 +21,8 @@ export type SegmentInput = {
21
21
  tasks: TaskHandlers;
22
22
  /** Where step types that cache keep their results; none keeps nothing. */
23
23
  cache?: StepCacheStore;
24
+ /** In a replay, the steps of the run it replays. */
25
+ replayed?: readonly SavedStep[];
24
26
  signal: AbortSignal;
25
27
  now?: () => Date;
26
28
  /** How long the segment takes new steps. Default `limits.segmentMs`. */
@@ -32,7 +34,7 @@ export type SegmentInput = {
32
34
  * Runs a run's steps from where its saved steps leave it to its next wait: it ends or fails, waits until a time
33
35
  * (a Wait, a retry's delay), or yields once its time is up. `superseded` when another segment saved a step first.
34
36
  */
35
- export declare const runSegment: ({ runId, definition, input, startedAt, secrets, redactor, saved, save, tasks, cache, signal, now, budgetMs, maxSteps }: SegmentInput) => Promise<ScopeOutcome | {
37
+ export declare const runSegment: ({ runId, definition, input, startedAt, secrets, redactor, saved, save, tasks, cache, replayed, signal, now, budgetMs, maxSteps }: SegmentInput) => Promise<ScopeOutcome | {
36
38
  kind: "superseded";
37
39
  }>;
38
40
  //#endregion
@@ -1,5 +1,6 @@
1
1
  import { limits } from "../limits.js";
2
2
  import { SupersededError } from "./errors.js";
3
+ import { replayedSteps } from "./replay.js";
3
4
  import { secretNamer } from "./cache/secret-names.js";
4
5
  import { runScope } from "./scope.js";
5
6
  //#region src/run/segment.ts
@@ -7,7 +8,7 @@ import { runScope } from "./scope.js";
7
8
  * Runs a run's steps from where its saved steps leave it to its next wait: it ends or fails, waits until a time
8
9
  * (a Wait, a retry's delay), or yields once its time is up. `superseded` when another segment saved a step first.
9
10
  */
10
- const runSegment = async ({ runId, definition, input, startedAt, secrets, redactor, saved, save, tasks, cache, signal, now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
11
+ const runSegment = async ({ runId, definition, input, startedAt, secrets, redactor, saved, save, tasks, cache, replayed, signal, now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
11
12
  const byScope = /* @__PURE__ */ new Map();
12
13
  for (const step of [...saved].sort((a, b) => a.seq - b.seq)) {
13
14
  const steps = byScope.get(step.scope);
@@ -38,6 +39,7 @@ const runSegment = async ({ runId, definition, input, startedAt, secrets, redact
38
39
  store: cache,
39
40
  nameSecrets: secretNamer(secrets)
40
41
  } },
42
+ ...replayed && { replay: { steps: replayedSteps(replayed) } },
41
43
  signal,
42
44
  now,
43
45
  deadline: Date.now() + budgetMs,
@@ -78,19 +78,27 @@ const waitUntil = async (state, call) => {
78
78
  if (at.getTime() - now.getTime() > limits.waitSeconds * 1e3) throw new StepError("States.QueryEvaluationError", `Timestamp: gave ${JSON.stringify(timestamp)}, more than ${limits.waitSeconds} seconds from now`);
79
79
  return at;
80
80
  };
81
- /** A Wait saves its step at once, with the time the next state may run: the segment ends there, and the queue wakes the run. */
81
+ /** A Wait saves its step at once, with the time the next state may run: the segment ends there, and the queue wakes the run. A replay does not wait. */
82
82
  const runWait = async (state, call) => {
83
83
  const resumeAt = await waitUntil(state, call);
84
- return {
84
+ const step = {
85
85
  kind: "step",
86
86
  status: "succeeded",
87
87
  next: nextOf(state),
88
88
  input: call.position.input,
89
89
  output: await outputOf(state, call),
90
90
  assigned: await evaluateAssign(state.Assign, call.bindings),
91
- resumeAt,
92
91
  logs: call.logs
93
92
  };
93
+ if (!call.context.replay) return {
94
+ ...step,
95
+ resumeAt
96
+ };
97
+ call.logs.push({
98
+ at: call.context.now().toISOString(),
99
+ message: "Not waited: replay"
100
+ });
101
+ return step;
94
102
  };
95
103
  const runFail = async (state, call) => {
96
104
  const text = async (value, field) => value === void 0 ? void 0 : String(await evaluateKept(value, call.bindings, field));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/workflows",
3
- "version": "0.71.5",
3
+ "version": "0.71.6",
4
4
  "description": "Workflows as state machines with JSONata expressions: their check, a runner that saves every step, and the plugin interface for trigger and step types.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {