@protobase/workflows 0.100.1 → 0.100.3

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,157 @@
1
+ import { limits } from "../limits.js";
2
+ import { taskResource } from "../definition/task-resource.js";
3
+ import { StepError, errorOutput } from "./errors.js";
4
+ import { redacted } from "./redact.js";
5
+ import { evaluateTemplate, recordedArguments } from "./evaluate.js";
6
+ import { runTask } from "./task.js";
7
+ import { newTaskToken, taskTokenHash } from "./task-token.js";
8
+ //#region src/run/waiting-task.ts
9
+ const withToken = (bindings, token) => {
10
+ const states = bindings.states;
11
+ return {
12
+ ...bindings,
13
+ states: {
14
+ ...states,
15
+ context: {
16
+ ...states.context,
17
+ Task: { Token: token }
18
+ }
19
+ }
20
+ };
21
+ };
22
+ /** When a try's next heartbeat is due: from its last one, else from its hand-off; none without `HeartbeatSeconds`. */
23
+ const heartbeatDue = (task) => {
24
+ if (task.heartbeatSeconds === null) return;
25
+ const from = task.heartbeatAt ?? task.handedOffAt ?? task.startedAt;
26
+ return new Date(from.getTime() + task.heartbeatSeconds * 1e3);
27
+ };
28
+ /** Why a waiting try can take no answer now: its time ran out, or a heartbeat is overdue. */
29
+ const overdue = (task, at, timeoutSeconds = Math.round((task.deadline.getTime() - task.startedAt.getTime()) / 1e3)) => {
30
+ if (at >= task.deadline) return {
31
+ error: "States.Timeout",
32
+ cause: `No outside result came within ${timeoutSeconds} seconds`
33
+ };
34
+ const due = heartbeatDue(task);
35
+ if (due && at >= due) return {
36
+ error: "States.HeartbeatTimeout",
37
+ cause: `No heartbeat came within ${task.heartbeatSeconds} seconds`
38
+ };
39
+ };
40
+ /**
41
+ * One try of a Task that waits for an outside result (`<type>.waitForTaskToken`). The first segment to reach it gives
42
+ * the try a token, runs the step type on Arguments that read it as `$states.context.Task.Token`, and marks the token
43
+ * handed off, so a segment after a restart only waits and never hands the work off again. The run then waits, holding
44
+ * no segment, until an answer wakes it, its `TimeoutSeconds` pass (`States.Timeout`, from the hand-off's start) or a
45
+ * heartbeat is overdue (`States.HeartbeatTimeout`). The answer is the Task's result, which `Output` and `Assign` read as
46
+ * `$states.result`, or its failure, under the error the answer names. The token is blanked out of all the run keeps.
47
+ */
48
+ const runWaitingTask = async (state, call) => {
49
+ const { type } = taskResource(state.Resource);
50
+ const template = state.Arguments ?? {};
51
+ if (call.context.replay) return {
52
+ held: true,
53
+ input: redacted(recordedArguments(template, await evaluateTemplate(template, withToken(call.bindings, ""), "Arguments")))
54
+ };
55
+ const tokens = call.context.tokens;
56
+ if (!tokens) throw new StepError("States.Runtime", "This app keeps no waiting Tasks");
57
+ const visit = `${call.scope}|${call.position.seq}`;
58
+ const found = await tokens.find(visit);
59
+ if (found && (found.handedOffAt || found.status !== "waiting")) return settle(found, visit, call);
60
+ const token = newTaskToken();
61
+ call.context.redactor.add(token);
62
+ const startedAt = call.context.now();
63
+ const timeout = state.TimeoutSeconds ?? limits.waitingTaskTimeoutSeconds;
64
+ const hash = await taskTokenHash(token);
65
+ await tokens.begin({
66
+ visit,
67
+ state: call.name,
68
+ hash,
69
+ startedAt,
70
+ deadline: new Date(startedAt.getTime() + timeout * 1e3),
71
+ heartbeatSeconds: state.HeartbeatSeconds ?? null
72
+ });
73
+ const args = await evaluateTemplate(template, withToken(call.bindings, token), "Arguments");
74
+ const input = call.context.redactor.value(redacted(recordedArguments(template, args)));
75
+ const key = `${call.context.runId}/${call.scope}/${call.position.seq}/${hash.slice(0, 16)}`;
76
+ const handOff = {
77
+ ...state,
78
+ Resource: type,
79
+ TimeoutSeconds: Math.min(timeout, limits.taskTimeoutSeconds),
80
+ Cache: false
81
+ };
82
+ try {
83
+ await runTask(call.context, handOff, args, key, call.logs);
84
+ } catch (error) {
85
+ if (!(error instanceof StepError)) throw error;
86
+ const failure = errorOutput(error);
87
+ if (await tokens.close(visit, {
88
+ error: failure.Error,
89
+ cause: failure.Cause
90
+ })) return {
91
+ failure,
92
+ input,
93
+ recorded: true
94
+ };
95
+ return handedOff(visit, call, input);
96
+ }
97
+ call.logs.push({
98
+ at: call.context.now().toISOString(),
99
+ message: `Handed off; waits for an outside result until ${new Date(startedAt.getTime() + timeout * 1e3).toISOString()}`
100
+ });
101
+ return handedOff(visit, call, input);
102
+ };
103
+ const handedOff = async (visit, call, input) => {
104
+ const tokens = call.context.tokens;
105
+ await tokens.handedOff(visit, {
106
+ at: call.context.now(),
107
+ input,
108
+ logs: call.logs.map((line) => ({
109
+ ...line,
110
+ message: call.context.redactor.text(line.message)
111
+ }))
112
+ });
113
+ return settle(await tokens.find(visit), visit, call);
114
+ };
115
+ const settle = async (task, visit, call) => {
116
+ call.logs.splice(0, call.logs.length, ...task.logs);
117
+ const input = task.input;
118
+ if (task.status === "succeeded") {
119
+ call.logs.push({
120
+ at: call.context.now().toISOString(),
121
+ message: `The outside result came at ${task.answeredAt?.toISOString()}`
122
+ });
123
+ return {
124
+ result: task.output ?? null,
125
+ input,
126
+ recorded: true,
127
+ ...task.answeredAt && { fetchedAt: task.answeredAt }
128
+ };
129
+ }
130
+ if (task.status === "failed") return {
131
+ failure: {
132
+ Error: task.error ?? "States.TaskFailed",
133
+ Cause: task.cause ?? ""
134
+ },
135
+ input,
136
+ recorded: true
137
+ };
138
+ const late = overdue(task, call.context.now());
139
+ if (late) {
140
+ if (!await call.context.tokens.close(visit, late, { heartbeatAt: task.heartbeatAt })) return settle(await call.context.tokens.find(visit), visit, call);
141
+ return {
142
+ failure: {
143
+ Error: late.error,
144
+ Cause: late.cause
145
+ },
146
+ input,
147
+ recorded: true
148
+ };
149
+ }
150
+ const due = heartbeatDue(task);
151
+ return {
152
+ kind: "blocked",
153
+ until: due && due < task.deadline ? due : task.deadline
154
+ };
155
+ };
156
+ //#endregion
157
+ export { heartbeatDue, overdue, runWaitingTask };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/workflows",
3
- "version": "0.100.1",
3
+ "version": "0.100.3",
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": {