@protobase/workflows 0.100.0 → 0.100.2
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/definition/check-aws.js +2 -3
- package/dist/definition/check-definition.js +44 -16
- package/dist/definition/check-reads.js +9 -5
- package/dist/definition/pins/pin-sources.d.ts +4 -1
- package/dist/definition/pins/pin-sources.js +15 -3
- package/dist/definition/schema.js +6 -1
- package/dist/definition/task-resource.d.ts +16 -0
- package/dist/definition/task-resource.js +19 -0
- package/dist/definition/types.d.ts +4 -2
- package/dist/definition/used-connections.js +2 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.js +3 -1
- package/dist/limits.d.ts +8 -0
- package/dist/limits.js +8 -0
- package/dist/run/context.d.ts +13 -1
- package/dist/run/port.d.ts +81 -0
- package/dist/run/result-states.js +3 -0
- package/dist/run/runner.d.ts +21 -2
- package/dist/run/runner.js +79 -1
- package/dist/run/segment.d.ts +4 -2
- package/dist/run/segment.js +2 -1
- package/dist/run/task-token.d.ts +6 -0
- package/dist/run/task-token.js +9 -0
- package/dist/run/waiting-task.js +157 -0
- package/package.json +1 -1
|
@@ -14,7 +14,6 @@ const awsFields = {
|
|
|
14
14
|
ResultWriter: "is a distributed Map's writer, which does not run here",
|
|
15
15
|
ToleratedFailureCount: "is a distributed Map's, which does not run here",
|
|
16
16
|
ToleratedFailurePercentage: "is a distributed Map's, which does not run here",
|
|
17
|
-
HeartbeatSeconds: "does not run here: a step type ends or fails within its TimeoutSeconds",
|
|
18
17
|
Credentials: "does not run here: a step signs in through the connection its type declares"
|
|
19
18
|
};
|
|
20
19
|
const stateProblems = (states, path) => {
|
|
@@ -59,8 +58,8 @@ const stateProblems = (states, path) => {
|
|
|
59
58
|
};
|
|
60
59
|
/**
|
|
61
60
|
* What a state machine from Step Functions holds that this app does not run, each named: JSONPath (its query
|
|
62
|
-
* language by default), its service tasks, the HTTP task included, Parallel, a distributed Map,
|
|
63
|
-
*
|
|
61
|
+
* language by default), its service tasks, the HTTP task included, Parallel, a distributed Map, credentials and a whole-run
|
|
62
|
+
* timeout. Empty for a machine this app can check further.
|
|
64
63
|
*/
|
|
65
64
|
const awsProblems = (definition) => {
|
|
66
65
|
const machine = isObject(definition) && isObject(definition.stateMachine) ? definition.stateMachine : void 0;
|
|
@@ -9,6 +9,7 @@ import { reservedVariables } from "./names.js";
|
|
|
9
9
|
import { builtInFunctions } from "./reads.js";
|
|
10
10
|
import { readProblems } from "./check-reads.js";
|
|
11
11
|
import { allStates } from "./inner.js";
|
|
12
|
+
import { taskResource } from "./task-resource.js";
|
|
12
13
|
import { connectionProblems } from "./used-connections.js";
|
|
13
14
|
import { visibleVariables } from "./visible.js";
|
|
14
15
|
import { blockProblems } from "./check-block.js";
|
|
@@ -18,11 +19,29 @@ import { dataflowProblems, dataflowVisible } from "./dataflow/check-dataflow.js"
|
|
|
18
19
|
import { orderOf } from "./types.js";
|
|
19
20
|
//#region src/definition/check-definition.ts
|
|
20
21
|
const missingArguments = (state, options) => {
|
|
21
|
-
const needed = options.required?.[state.Resource] ?? [];
|
|
22
|
+
const needed = options.required?.[taskResource(state.Resource).type] ?? [];
|
|
22
23
|
if (expressionSource(state.Arguments) !== void 0) return [];
|
|
23
24
|
const given = typeof state.Arguments === "object" && state.Arguments !== null ? state.Arguments : {};
|
|
24
25
|
return needed.filter((name) => given[name] === void 0 || given[name] === "");
|
|
25
26
|
};
|
|
27
|
+
const waitProblems = (state) => {
|
|
28
|
+
const { waits } = taskResource(state.Resource);
|
|
29
|
+
if (!waits) return [...state.TimeoutSeconds !== void 0 && state.TimeoutSeconds > limits.taskTimeoutSeconds ? [{
|
|
30
|
+
field: "TimeoutSeconds",
|
|
31
|
+
message: `is ${state.TimeoutSeconds}, more than the ${limits.taskTimeoutSeconds} seconds a step type runs; only a Task whose Resource ends in .waitForTaskToken waits longer`
|
|
32
|
+
}] : [], ...state.HeartbeatSeconds !== void 0 ? [{
|
|
33
|
+
field: "HeartbeatSeconds",
|
|
34
|
+
message: "is for a Task whose Resource ends in .waitForTaskToken, whose outside executor sends heartbeats; this step type ends or fails within its TimeoutSeconds"
|
|
35
|
+
}] : []];
|
|
36
|
+
const timeout = state.TimeoutSeconds ?? limits.waitingTaskTimeoutSeconds;
|
|
37
|
+
return [...state.HeartbeatSeconds !== void 0 && state.HeartbeatSeconds >= timeout ? [{
|
|
38
|
+
field: "HeartbeatSeconds",
|
|
39
|
+
message: `is ${state.HeartbeatSeconds}, which must be less than the Task's TimeoutSeconds (${timeout})`
|
|
40
|
+
}] : [], ...state.Cache === true ? [{
|
|
41
|
+
field: "Cache",
|
|
42
|
+
message: "is true, but a Task that waits for an outside result hands its work off on every try and caches nothing"
|
|
43
|
+
}] : []];
|
|
44
|
+
};
|
|
26
45
|
const machineProblems = (machine, scope, options) => {
|
|
27
46
|
const problems = [];
|
|
28
47
|
const where = (name) => [...scope.path, name].join("/");
|
|
@@ -61,33 +80,42 @@ const machineProblems = (machine, scope, options) => {
|
|
|
61
80
|
message: `cannot assign $${variable}, which an outer state assigns already`
|
|
62
81
|
});
|
|
63
82
|
}
|
|
64
|
-
|
|
83
|
+
const task = state.Type === "Task" ? taskResource(state.Resource) : void 0;
|
|
84
|
+
if (task && options.unavailable && Object.hasOwn(options.unavailable, task.type)) problems.push({
|
|
65
85
|
state: where(name),
|
|
66
86
|
field: "Resource",
|
|
67
|
-
message: `"${
|
|
87
|
+
message: `"${task.type}" cannot run in this app: ${options.unavailable[task.type]}`
|
|
68
88
|
});
|
|
69
|
-
else if (
|
|
89
|
+
else if (task && !options.resources.includes(task.type)) problems.push({
|
|
70
90
|
state: where(name),
|
|
71
91
|
field: "Resource",
|
|
72
|
-
message: `"${
|
|
92
|
+
message: `"${task.type}" is not a step type; use one of ${options.resources.join(", ")}${task.waits ? ", followed by .waitForTaskToken" : ""}`
|
|
73
93
|
});
|
|
74
94
|
if (state.Type === "Task") for (const missing of missingArguments(state, options)) problems.push({
|
|
75
95
|
state: where(name),
|
|
76
96
|
field: `Arguments.${missing}`,
|
|
77
|
-
message: `is missing; ${
|
|
97
|
+
message: `is missing; ${task.type} needs it`
|
|
78
98
|
});
|
|
79
|
-
|
|
80
|
-
for (const { field, source, place } of stateExpressions(state)) for (const message of readProblems(source, {
|
|
81
|
-
place,
|
|
82
|
-
visible: visible.get(name),
|
|
83
|
-
firstOfItem,
|
|
84
|
-
inBlock: scope.blocks > 0,
|
|
85
|
-
...data && { steps }
|
|
86
|
-
})) problems.push({
|
|
99
|
+
if (state.Type === "Task") for (const problem of waitProblems(state)) problems.push({
|
|
87
100
|
state: where(name),
|
|
88
|
-
|
|
89
|
-
message
|
|
101
|
+
...problem
|
|
90
102
|
});
|
|
103
|
+
const firstOfItem = scope.item && (data || name === machine.StartAt);
|
|
104
|
+
for (const { field, source, place } of stateExpressions(state)) {
|
|
105
|
+
const token = Boolean(task?.waits) && /^Arguments($|[.[])/.test(field);
|
|
106
|
+
for (const message of readProblems(source, {
|
|
107
|
+
place,
|
|
108
|
+
visible: visible.get(name),
|
|
109
|
+
firstOfItem,
|
|
110
|
+
inBlock: scope.blocks > 0,
|
|
111
|
+
token,
|
|
112
|
+
...data && { steps }
|
|
113
|
+
})) problems.push({
|
|
114
|
+
state: where(name),
|
|
115
|
+
field,
|
|
116
|
+
message
|
|
117
|
+
});
|
|
118
|
+
}
|
|
91
119
|
if (state.Type === "Map") problems.push(...machineProblems(state.ItemProcessor, {
|
|
92
120
|
...scope,
|
|
93
121
|
path: [...scope.path, name],
|
|
@@ -9,10 +9,14 @@ const statesFields = {
|
|
|
9
9
|
error: "errorOutput"
|
|
10
10
|
};
|
|
11
11
|
const startsWith = (path, prefix) => prefix.every((name, index) => path[index] === name);
|
|
12
|
-
const contextProblem = (path, steps) => {
|
|
12
|
+
const contextProblem = (path, steps, token) => {
|
|
13
13
|
const rest = path.slice(1);
|
|
14
14
|
if (startsWith(rest, ["Secrets"])) return rest.length >= 2 ? void 0 : "reads $states.context.Secrets as a whole; read one secret by its name, such as $states.context.Secrets.API_TOKEN";
|
|
15
15
|
if (contextReads.some((read) => startsWith(rest, read))) return void 0;
|
|
16
|
+
if (startsWith(rest, ["Task"])) {
|
|
17
|
+
if (!token) return "reads $states.context.Task, which only the Arguments of a Task whose Resource ends in .waitForTaskToken read, as $states.context.Task.Token";
|
|
18
|
+
return startsWith(rest, ["Task", "Token"]) && rest.length === 2 ? void 0 : "reads $states.context.Task, whose only field is Token";
|
|
19
|
+
}
|
|
16
20
|
if (steps && startsWith(rest, ["Steps"])) {
|
|
17
21
|
if (rest[1] === void 0) return "reads $states.context.Steps as a whole; read one state's status by its name, such as $states.context.Steps.Save.Status";
|
|
18
22
|
return steps.has(rest[1]) ? void 0 : `reads $states.context.Steps.${rest[1]}, but there is no state ${rest[1]} here or around it`;
|
|
@@ -28,10 +32,10 @@ const expressionParsed = (source) => {
|
|
|
28
32
|
/**
|
|
29
33
|
* Why an expression breaks the named-reads profile, if it does: it must parse, read no implicit input, read
|
|
30
34
|
* `$states.input` only in the first state of a Map's item processor, read of `$states.context` only the run's input,
|
|
31
|
-
* start time and secrets by name (inside a Block, not the start time),
|
|
32
|
-
* before it assigns.
|
|
35
|
+
* start time and secrets by name (inside a Block, not the start time), with `token` a waiting Task's token too, and
|
|
36
|
+
* read only variables a state that can run before it assigns.
|
|
33
37
|
*/
|
|
34
|
-
const readProblems = (source, { place, visible, firstOfItem, inBlock = false, steps }) => {
|
|
38
|
+
const readProblems = (source, { place, visible, firstOfItem, inBlock = false, steps, token = false }) => {
|
|
35
39
|
if (source.length > limits.expressionLength) return [`is ${source.length} characters long, more than the ${limits.expressionLength} an expression may be`];
|
|
36
40
|
const parsed = parse(source);
|
|
37
41
|
if ("error" in parsed) return [`does not parse: ${parsed.error.message}${parsed.error.position === void 0 ? "" : ` (at character ${parsed.error.position})`}`];
|
|
@@ -48,7 +52,7 @@ const readProblems = (source, { place, visible, firstOfItem, inBlock = false, st
|
|
|
48
52
|
"StartTime"
|
|
49
53
|
])) 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");
|
|
50
54
|
else if (field === "context") {
|
|
51
|
-
const problem = contextProblem(path, steps);
|
|
55
|
+
const problem = contextProblem(path, steps, token);
|
|
52
56
|
if (problem) problems.push(problem);
|
|
53
57
|
} 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)");
|
|
54
58
|
else if (field === "") problems.push("reads $states as a whole; read one of its fields");
|
|
@@ -11,7 +11,10 @@ export type PinSchemas = {
|
|
|
11
11
|
};
|
|
12
12
|
/** The state outside any Block that keeps its whole result in `variable`, when exactly one does; its name. */
|
|
13
13
|
export declare const resultState: (machine: Machine, variable: string) => [string, State] | undefined;
|
|
14
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* A Task's result as its type gives it, with what its arguments name filled in; undefined for any other state, an
|
|
16
|
+
* unknown type, or a Task that waits for an outside result, which is what its executor sends back.
|
|
17
|
+
*/
|
|
15
18
|
export declare const resultSchema: (state: State, schemas: PinSchemas) => {
|
|
16
19
|
[x: string]: unknown;
|
|
17
20
|
} | undefined;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { expressionSource } from "../expressions.js";
|
|
2
2
|
import { innerMachine } from "../inner.js";
|
|
3
|
+
import { taskResource } from "../task-resource.js";
|
|
3
4
|
import { resolveSchema, schemaAt } from "./resolve-schema.js";
|
|
4
5
|
//#region src/definition/pins/pin-sources.ts
|
|
5
6
|
const argumentsOf = (state) => {
|
|
@@ -19,8 +20,15 @@ const resultState = (machine, variable) => {
|
|
|
19
20
|
const [name, state] = keeping[0];
|
|
20
21
|
return expressionSource(state.Assign[variable])?.trim() === "$states.result" ? [name, state] : void 0;
|
|
21
22
|
};
|
|
22
|
-
/**
|
|
23
|
-
|
|
23
|
+
/**
|
|
24
|
+
* A Task's result as its type gives it, with what its arguments name filled in; undefined for any other state, an
|
|
25
|
+
* unknown type, or a Task that waits for an outside result, which is what its executor sends back.
|
|
26
|
+
*/
|
|
27
|
+
const resultSchema = (state, schemas) => {
|
|
28
|
+
if (state.Type !== "Task") return;
|
|
29
|
+
const { type, waits } = taskResource(state.Resource);
|
|
30
|
+
return !waits && schemas.outputs[type] ? resolveSchema(schemas.outputs[type], argumentsOf(state), schemas.records) : void 0;
|
|
31
|
+
};
|
|
24
32
|
/** The run's input as the trigger gives it, with what its input names filled in; undefined for a manual workflow. */
|
|
25
33
|
const triggerSchema = (definition, schemas) => {
|
|
26
34
|
const [id, input] = Object.entries(definition.trigger ?? {})[0] ?? [];
|
|
@@ -55,7 +63,11 @@ const referenceSchema = (definition, reference, schemas) => {
|
|
|
55
63
|
return found && schemaAt(resultSchema(found[1], schemas), path);
|
|
56
64
|
};
|
|
57
65
|
/** A Task's input as its type takes it, with what its arguments name filled in, such as the record a records step writes. */
|
|
58
|
-
const inputSchema = (state, schemas) =>
|
|
66
|
+
const inputSchema = (state, schemas) => {
|
|
67
|
+
if (state.Type !== "Task") return;
|
|
68
|
+
const { type } = taskResource(state.Resource);
|
|
69
|
+
return schemas.inputs[type] ? resolveSchema(schemas.inputs[type], argumentsOf(state), schemas.records) : void 0;
|
|
70
|
+
};
|
|
59
71
|
/** Every Task of a machine outside any Block, with its path, the ones in Maps too: a Block's steps read only its own input. */
|
|
60
72
|
/** Every Block of a machine outside any other Block, with its path, the ones in Maps too. */
|
|
61
73
|
const blocksOutsideBlocks = (machine, scope = []) => Object.entries(machine.States).flatMap(([name, state]) => {
|
|
@@ -151,7 +151,12 @@ const schemaFor = (order) => {
|
|
|
151
151
|
TimeoutSeconds: {
|
|
152
152
|
type: "integer",
|
|
153
153
|
minimum: 1,
|
|
154
|
-
maximum: limits.
|
|
154
|
+
maximum: limits.waitingTaskTimeoutSeconds
|
|
155
|
+
},
|
|
156
|
+
HeartbeatSeconds: {
|
|
157
|
+
type: "integer",
|
|
158
|
+
minimum: 1,
|
|
159
|
+
maximum: limits.waitingTaskTimeoutSeconds
|
|
155
160
|
},
|
|
156
161
|
Cache: { type: "boolean" }
|
|
157
162
|
}, {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { State } from "./types.js";
|
|
2
|
+
//#region src/definition/task-resource.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* The States Language's suffix for a Task that hands its work off and waits for an outside result: its step type gets
|
|
5
|
+
* the try's token as `$states.context.Task.Token`, and the Task ends when someone sends that token back with a result
|
|
6
|
+
* or a failure, or when its `TimeoutSeconds` or `HeartbeatSeconds` pass.
|
|
7
|
+
*/
|
|
8
|
+
export declare const waitSuffix = ".waitForTaskToken";
|
|
9
|
+
/** A Task's step type, and whether it waits for an outside result once that type handed the work off. */
|
|
10
|
+
export declare const taskResource: (resource: string) => {
|
|
11
|
+
type: string;
|
|
12
|
+
waits: boolean;
|
|
13
|
+
};
|
|
14
|
+
/** Whether a state is a Task that waits for an outside result. */
|
|
15
|
+
export declare const waitsForToken: (state: State) => boolean;
|
|
16
|
+
//#endregion
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region src/definition/task-resource.ts
|
|
2
|
+
/**
|
|
3
|
+
* The States Language's suffix for a Task that hands its work off and waits for an outside result: its step type gets
|
|
4
|
+
* the try's token as `$states.context.Task.Token`, and the Task ends when someone sends that token back with a result
|
|
5
|
+
* or a failure, or when its `TimeoutSeconds` or `HeartbeatSeconds` pass.
|
|
6
|
+
*/
|
|
7
|
+
const waitSuffix = ".waitForTaskToken";
|
|
8
|
+
/** A Task's step type, and whether it waits for an outside result once that type handed the work off. */
|
|
9
|
+
const taskResource = (resource) => resource.endsWith(".waitForTaskToken") ? {
|
|
10
|
+
type: resource.slice(0, -17),
|
|
11
|
+
waits: true
|
|
12
|
+
} : {
|
|
13
|
+
type: resource,
|
|
14
|
+
waits: false
|
|
15
|
+
};
|
|
16
|
+
/** Whether a state is a Task that waits for an outside result. */
|
|
17
|
+
const waitsForToken = (state) => state.Type === "Task" && taskResource(state.Resource).waits;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { taskResource, waitSuffix, waitsForToken };
|
|
@@ -31,14 +31,16 @@ export type PassState = Common & Flow & {
|
|
|
31
31
|
Type: 'Pass';
|
|
32
32
|
};
|
|
33
33
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
34
|
+
* A Task runs its step type, `Resource`; one whose Resource ends in `.waitForTaskToken` then waits for an outside
|
|
35
|
+
* result, with heartbeats at most `HeartbeatSeconds` apart. `Cache` turns its step type's result cache on (`true`,
|
|
36
|
+
* forced when the type does not offer it) or off (`false`); without it, the type decides.
|
|
36
37
|
*/
|
|
37
38
|
export type TaskState = Common & Flow & {
|
|
38
39
|
Type: 'Task';
|
|
39
40
|
Resource: string;
|
|
40
41
|
Arguments?: Template;
|
|
41
42
|
TimeoutSeconds?: number;
|
|
43
|
+
HeartbeatSeconds?: number;
|
|
42
44
|
Cache?: boolean;
|
|
43
45
|
Retry?: Retrier[];
|
|
44
46
|
Catch?: Catcher[];
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { allStates } from "./inner.js";
|
|
2
|
+
import { taskResource } from "./task-resource.js";
|
|
2
3
|
//#region src/definition/used-connections.ts
|
|
3
4
|
/** 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] : []);
|
|
5
|
+
const resources = (machine) => allStates(machine).flatMap(([, state]) => state.Type === "Task" ? [taskResource(state.Resource).type] : []);
|
|
5
6
|
/**
|
|
6
7
|
* The connections `<plugin>:<connection>` a definition's trigger and steps sign in with, given the connection each
|
|
7
8
|
* type uses by its id (`connectionOf`).
|
package/dist/index.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ import { PinKind, PinType, fits, pinType, pinTypeText } from "./definition/pins/
|
|
|
12
12
|
import { definitionWarnings } from "./definition/check-warnings.js";
|
|
13
13
|
import { allStates, blockDefinition, findBlock, innerMachine } from "./definition/inner.js";
|
|
14
14
|
import { usedConnections } from "./definition/used-connections.js";
|
|
15
|
+
import { taskResource, waitSuffix, waitsForToken } from "./definition/task-resource.js";
|
|
15
16
|
import { assignedNames } from "./definition/expression-fields.js";
|
|
16
17
|
import { Dependencies, dependsOn, machineDependencies } from "./definition/dataflow/dependencies.js";
|
|
17
18
|
import { limits } from "./limits.js";
|
|
@@ -20,11 +21,12 @@ import { ErrorOutput, StepError } from "./run/errors.js";
|
|
|
20
21
|
import { Redactor, redacted, secretRedactor, shortestSecret } from "./run/redact.js";
|
|
21
22
|
import { KeyShape } from "./run/cache/cache-key.js";
|
|
22
23
|
import { CacheCall, CacheEntry, CacheIdentity, StepCacheStore } from "./run/cache/cache-port.js";
|
|
23
|
-
import { BlockRun, BlockRunStore, BlockShare, Checkpoint, LoadedRun, ReplayedStep, RunChange, RunStatus, RunStore, SegmentQueue, StepLog, StepRecord, StepStatus, TaskContext, TaskHandler, TaskHandlers, TraceMode, TraceSink } from "./run/port.js";
|
|
24
|
+
import { BlockRun, BlockRunStore, BlockShare, Checkpoint, KeptAnswer, LoadedRun, ReplayedStep, RunChange, RunStatus, RunStore, SegmentQueue, StepLog, StepRecord, StepStatus, TaskAnswer, TaskContext, TaskHandler, TaskHandlers, TaskTokenStore, TraceMode, TraceSink, WaitingTask } from "./run/port.js";
|
|
24
25
|
import { EarlierCheckpoint, keptAssigned, rerunCheckpoint, rerunProblem, resultRead } from "./run/rerun.js";
|
|
25
26
|
import { RerunFrom, rerunFrom } from "./run/rerun-from.js";
|
|
26
27
|
import { heldBackLog } from "./run/replay.js";
|
|
27
|
-
import {
|
|
28
|
+
import { taskTokenHash, tokenPattern } from "./run/task-token.js";
|
|
29
|
+
import { AnswerRefusal, Runner, RunnerPort, createRunner } from "./run/runner.js";
|
|
28
30
|
import { SegmentInput, runSegment } from "./run/segment.js";
|
|
29
31
|
import { LoadedPlugin, loadPlugins } from "./plugin/load-plugins.js";
|
|
30
32
|
import { StepWiring, stepHandlers } from "./plugin/step-handlers.js";
|
|
@@ -32,4 +34,4 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
|
|
|
32
34
|
import { TypeEntry, Unavailable, typeList } from "./plugin/type-list.js";
|
|
33
35
|
import { ConnectionSupport, connectionUnavailable } from "./plugin/connection-availability.js";
|
|
34
36
|
import { CatalogEntry, TypeCatalog, typeCatalog } from "./plugin/type-catalog.js";
|
|
35
|
-
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 DefinitionParts, type Dependencies, type EarlierCheckpoint, type ErrorOutput, type KeyShape, type LoadedPlugin, type LoadedRun, type Machine, type MapState, type Order, type PinKind, type PinSchemas, type PinType, type Problem, type ReadBase, type RecordSchemas, type RecordUse, type Redactor, type Reference, 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, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, innerMachine, inputSchema, keptAssigned, limits, loadPlugins, machineDependencies, nestingDepth, orderOf, parseReference, partOfProblem, partsOfDefinition, pinType, pinTypeText, problemText, readText, redacted, referenceSchema, referenceValue, rerunCheckpoint, rerunFrom, rerunProblem, resolveSchema, resultRead, resultSchema, resultState, runSegment, schemaAt, secretRedactor, shortestSecret, stepHandlers, stepStatusSchema, triggerChecks, triggerSchema, typeCatalog, typeList, usedConnections };
|
|
37
|
+
export { type AnswerRefusal, 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 DefinitionParts, type Dependencies, type EarlierCheckpoint, type ErrorOutput, type KeptAnswer, type KeyShape, type LoadedPlugin, type LoadedRun, type Machine, type MapState, type Order, type PinKind, type PinSchemas, type PinType, type Problem, type ReadBase, type RecordSchemas, type RecordUse, type Redactor, type Reference, 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 TaskAnswer, type TaskContext, type TaskHandler, type TaskHandlers, type TaskState, type TaskTokenStore, type TraceMode, type TraceSink, type Trigger, type TriggerCheck, type TypeCatalog, type TypeEntry, type Unavailable, type WaitingTask, allStates, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, innerMachine, inputSchema, keptAssigned, limits, loadPlugins, machineDependencies, nestingDepth, orderOf, parseReference, partOfProblem, partsOfDefinition, pinType, pinTypeText, problemText, readText, redacted, referenceSchema, referenceValue, rerunCheckpoint, rerunFrom, rerunProblem, resolveSchema, resultRead, resultSchema, resultState, runSegment, schemaAt, secretRedactor, shortestSecret, stepHandlers, stepStatusSchema, taskResource, taskTokenHash, tokenPattern, triggerChecks, triggerSchema, typeCatalog, typeList, usedConnections, waitSuffix, waitsForToken };
|
package/dist/index.js
CHANGED
|
@@ -4,6 +4,7 @@ import { problemText } from "./definition/problem.js";
|
|
|
4
4
|
import { expressionSource } from "./definition/expressions.js";
|
|
5
5
|
import { assignedNames } from "./definition/expression-fields.js";
|
|
6
6
|
import { allStates, blockDefinition, findBlock, innerMachine } from "./definition/inner.js";
|
|
7
|
+
import { taskResource, waitSuffix, waitsForToken } from "./definition/task-resource.js";
|
|
7
8
|
import { usedConnections } from "./definition/used-connections.js";
|
|
8
9
|
import { nestingDepth } from "./nesting.js";
|
|
9
10
|
import { fits, pinType, pinTypeText } from "./definition/pins/pin-type.js";
|
|
@@ -19,6 +20,7 @@ import { StepError } from "./run/errors.js";
|
|
|
19
20
|
import { redacted, secretRedactor, shortestSecret } from "./run/redact.js";
|
|
20
21
|
import { keptAssigned, rerunCheckpoint, rerunProblem, resultRead } from "./run/rerun.js";
|
|
21
22
|
import { heldBackLog } from "./run/replay.js";
|
|
23
|
+
import { taskTokenHash, tokenPattern } from "./run/task-token.js";
|
|
22
24
|
import { rerunFrom } from "./run/rerun-from.js";
|
|
23
25
|
import { runSegment } from "./run/segment.js";
|
|
24
26
|
import { createRunner } from "./run/runner.js";
|
|
@@ -28,4 +30,4 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
|
|
|
28
30
|
import { typeList } from "./plugin/type-list.js";
|
|
29
31
|
import { connectionUnavailable } from "./plugin/connection-availability.js";
|
|
30
32
|
import { typeCatalog } from "./plugin/type-catalog.js";
|
|
31
|
-
export { StepError, allStates, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, innerMachine, inputSchema, keptAssigned, limits, loadPlugins, machineDependencies, nestingDepth, orderOf, parseReference, partOfProblem, partsOfDefinition, pinType, pinTypeText, problemText, readText, redacted, referenceSchema, referenceValue, rerunCheckpoint, rerunFrom, rerunProblem, resolveSchema, resultRead, resultSchema, resultState, runSegment, schemaAt, secretRedactor, shortestSecret, stepHandlers, stepStatusSchema, triggerChecks, triggerSchema, typeCatalog, typeList, usedConnections };
|
|
33
|
+
export { StepError, allStates, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, innerMachine, inputSchema, keptAssigned, limits, loadPlugins, machineDependencies, nestingDepth, orderOf, parseReference, partOfProblem, partsOfDefinition, pinType, pinTypeText, problemText, readText, redacted, referenceSchema, referenceValue, rerunCheckpoint, rerunFrom, rerunProblem, resolveSchema, resultRead, resultSchema, resultState, runSegment, schemaAt, secretRedactor, shortestSecret, stepHandlers, stepStatusSchema, taskResource, taskTokenHash, tokenPattern, triggerChecks, triggerSchema, typeCatalog, typeList, usedConnections, waitSuffix, waitsForToken };
|
package/dist/limits.d.ts
CHANGED
|
@@ -11,6 +11,14 @@ export declare const limits: {
|
|
|
11
11
|
/** The longest a Task may run before it fails with `States.Timeout`, and its default. */
|
|
12
12
|
readonly taskTimeoutSeconds: 300;
|
|
13
13
|
readonly defaultTaskTimeoutSeconds: 300;
|
|
14
|
+
/**
|
|
15
|
+
* The longest a Task that waits for an outside result (`.waitForTaskToken`) waits, from its hand-off, and its default:
|
|
16
|
+
* 366 days, as a Wait. Its `HeartbeatSeconds` is less.
|
|
17
|
+
*/
|
|
18
|
+
readonly waitingTaskTimeoutSeconds: number;
|
|
19
|
+
/** An outside failure's error name and cause, as Step Functions' SendTaskFailure takes them. */
|
|
20
|
+
readonly taskErrorLength: 256;
|
|
21
|
+
readonly taskCauseLength: 32768;
|
|
14
22
|
/** The longest wait one Wait state may give in seconds: 366 days. */
|
|
15
23
|
readonly waitSeconds: number;
|
|
16
24
|
/** Retries of one retrier after the first try, and the longest wait between two. */
|
package/dist/limits.js
CHANGED
|
@@ -11,6 +11,14 @@ const limits = {
|
|
|
11
11
|
/** The longest a Task may run before it fails with `States.Timeout`, and its default. */
|
|
12
12
|
taskTimeoutSeconds: 300,
|
|
13
13
|
defaultTaskTimeoutSeconds: 300,
|
|
14
|
+
/**
|
|
15
|
+
* The longest a Task that waits for an outside result (`.waitForTaskToken`) waits, from its hand-off, and its default:
|
|
16
|
+
* 366 days, as a Wait. Its `HeartbeatSeconds` is less.
|
|
17
|
+
*/
|
|
18
|
+
waitingTaskTimeoutSeconds: 31622400,
|
|
19
|
+
/** An outside failure's error name and cause, as Step Functions' SendTaskFailure takes them. */
|
|
20
|
+
taskErrorLength: 256,
|
|
21
|
+
taskCauseLength: 32768,
|
|
14
22
|
/** The longest wait one Wait state may give in seconds: 366 days. */
|
|
15
23
|
waitSeconds: 31622400,
|
|
16
24
|
/** Retries of one retrier after the first try, and the longest wait between two. */
|
package/dist/run/context.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BlockRun, BlockShare } from "./port.js";
|
|
1
|
+
import { BlockRun, BlockShare, TaskTokenStore, WaitingTask } 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 = {
|
|
@@ -17,6 +17,18 @@ export type ScopeOutcome = {
|
|
|
17
17
|
error: string;
|
|
18
18
|
cause: string;
|
|
19
19
|
} | Paused;
|
|
20
|
+
/** A run's waiting Tasks' tokens, as its segment reaches them. */
|
|
21
|
+
export type SegmentTokens = {
|
|
22
|
+
find: (visit: string) => Promise<WaitingTask | undefined>;
|
|
23
|
+
begin: (task: Omit<Parameters<TaskTokenStore<unknown>['begin']>[1], 'run'>) => Promise<void>;
|
|
24
|
+
handedOff: (visit: string, done: Parameters<TaskTokenStore<unknown>['handedOff']>[3]) => Promise<void>;
|
|
25
|
+
close: (visit: string, failure: {
|
|
26
|
+
error: string;
|
|
27
|
+
cause: string;
|
|
28
|
+
}, seen?: {
|
|
29
|
+
heartbeatAt: Date | null;
|
|
30
|
+
}) => Promise<boolean>;
|
|
31
|
+
};
|
|
20
32
|
/** A run's blocks' runs, as its segment reaches them. */
|
|
21
33
|
export type SegmentBlocks = {
|
|
22
34
|
find: (visit: string) => Promise<BlockRun | undefined>;
|
package/dist/run/port.d.ts
CHANGED
|
@@ -217,6 +217,87 @@ export type BlockRunStore<Db> = {
|
|
|
217
217
|
/** The block runs `parent` started. */
|
|
218
218
|
count(db: Db, parent: string): Promise<number>;
|
|
219
219
|
};
|
|
220
|
+
/**
|
|
221
|
+
* A try of a Task that waits for an outside result, as its token keeps it: `waiting` until an answer or the Task's end
|
|
222
|
+
* (its time ran out, or its hand-off failed) settles it, which no later answer changes. `handedOffAt` is null until the
|
|
223
|
+
* step type handed the work off, so a segment that stopped before hands it off again with a new token. `input` and
|
|
224
|
+
* `logs` are what the hand-off recorded, with the token blanked out, which the try's step records once it ends.
|
|
225
|
+
*/
|
|
226
|
+
export type WaitingTask = {
|
|
227
|
+
status: 'waiting' | 'succeeded' | 'failed';
|
|
228
|
+
startedAt: Date;
|
|
229
|
+
handedOffAt: Date | null;
|
|
230
|
+
/** When its `TimeoutSeconds` pass, from its start. */
|
|
231
|
+
deadline: Date;
|
|
232
|
+
heartbeatSeconds: number | null;
|
|
233
|
+
heartbeatAt: Date | null;
|
|
234
|
+
input?: unknown;
|
|
235
|
+
logs: StepLog[];
|
|
236
|
+
output?: unknown;
|
|
237
|
+
error?: string | null;
|
|
238
|
+
cause?: string | null;
|
|
239
|
+
answeredAt?: Date | null;
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* What an outside executor sends with a token, as Step Functions' SendTaskSuccess, SendTaskFailure and SendTaskHeartbeat
|
|
243
|
+
* take it: a success's `output` is a string of JSON.
|
|
244
|
+
*/
|
|
245
|
+
export type TaskAnswer = {
|
|
246
|
+
kind: 'success';
|
|
247
|
+
output: string;
|
|
248
|
+
} | {
|
|
249
|
+
kind: 'failure';
|
|
250
|
+
error: string;
|
|
251
|
+
cause: string;
|
|
252
|
+
} | {
|
|
253
|
+
kind: 'heartbeat';
|
|
254
|
+
};
|
|
255
|
+
/** An answer as a try keeps it: a success's output parsed. */
|
|
256
|
+
export type KeptAnswer = Exclude<TaskAnswer, {
|
|
257
|
+
kind: 'success';
|
|
258
|
+
}> | {
|
|
259
|
+
kind: 'success';
|
|
260
|
+
output: unknown;
|
|
261
|
+
};
|
|
262
|
+
/**
|
|
263
|
+
* Where waiting Tasks' tokens are kept, by the run and its try of the Task (`visit`). A token is kept only as its hash
|
|
264
|
+
* (`hash`), which an answer finds it by; the token itself is never kept.
|
|
265
|
+
*/
|
|
266
|
+
export type TaskTokenStore<Db> = {
|
|
267
|
+
find(db: Db, run: string, visit: string): Promise<WaitingTask | undefined>;
|
|
268
|
+
/** Keeps a try's token, replacing that of the same try whose hand-off never finished. */
|
|
269
|
+
begin(db: Db, task: {
|
|
270
|
+
run: string;
|
|
271
|
+
visit: string;
|
|
272
|
+
state: string;
|
|
273
|
+
hash: string;
|
|
274
|
+
startedAt: Date;
|
|
275
|
+
deadline: Date;
|
|
276
|
+
heartbeatSeconds: number | null;
|
|
277
|
+
}): Promise<void>;
|
|
278
|
+
/** Marks the try handed off, with what its hand-off recorded: from now on a segment only waits for its answer. */
|
|
279
|
+
handedOff(db: Db, run: string, visit: string, done: {
|
|
280
|
+
at: Date;
|
|
281
|
+
input: unknown;
|
|
282
|
+
logs: StepLog[];
|
|
283
|
+
}): Promise<void>;
|
|
284
|
+
/**
|
|
285
|
+
* Ends a waiting try without an answer, with its failure: false when an answer settled it first, or, with `seen`, when
|
|
286
|
+
* a heartbeat came since the one `seen` holds, so that a timeout never ends a try a heartbeat just renewed.
|
|
287
|
+
*/
|
|
288
|
+
close(db: Db, run: string, visit: string, failure: {
|
|
289
|
+
error: string;
|
|
290
|
+
cause: string;
|
|
291
|
+
}, seen?: {
|
|
292
|
+
heartbeatAt: Date | null;
|
|
293
|
+
}): Promise<boolean>;
|
|
294
|
+
/** The try a token opens, by the token's hash, with its run. */
|
|
295
|
+
byHash(db: Db, hash: string): Promise<(WaitingTask & {
|
|
296
|
+
run: string;
|
|
297
|
+
}) | undefined>;
|
|
298
|
+
/** Takes an answer for a try still waiting: a heartbeat marks its time, a success or failure settles it; false when it no longer waits. */
|
|
299
|
+
answer(db: Db, hash: string, answer: KeptAnswer, at: Date): Promise<boolean>;
|
|
300
|
+
};
|
|
220
301
|
/** Which runs keep a trace: every run, only those that fail, or none. */
|
|
221
302
|
export type TraceMode = NonNullable<Definition['trace']>;
|
|
222
303
|
/**
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { limits } from "../limits.js";
|
|
2
|
+
import { taskResource } from "../definition/task-resource.js";
|
|
2
3
|
import { StepError, errorOutput } from "./errors.js";
|
|
3
4
|
import { redacted } from "./redact.js";
|
|
4
5
|
import { evaluateAssign, evaluateKept, evaluateTemplate, recordedArguments } from "./evaluate.js";
|
|
@@ -10,8 +11,10 @@ import { stepFunctions } from "./step-functions.js";
|
|
|
10
11
|
import { visibleVariables } from "./step-input.js";
|
|
11
12
|
import { emptyTask, heldBack, heldBackLog, replayedOutcome } from "./replay.js";
|
|
12
13
|
import { runTask } from "./task.js";
|
|
14
|
+
import { runWaitingTask } from "./waiting-task.js";
|
|
13
15
|
//#region src/run/result-states.ts
|
|
14
16
|
const task = async (state, call) => {
|
|
17
|
+
if (taskResource(state.Resource).waits) return runWaitingTask(state, call);
|
|
15
18
|
const args = await evaluateTemplate(state.Arguments ?? {}, call.bindings, "Arguments");
|
|
16
19
|
const key = `${call.context.runId}/${call.scope}/${call.position.seq - call.position.attempt + 1}`;
|
|
17
20
|
const input = redacted(recordedArguments(state.Arguments ?? {}, args));
|
package/dist/run/runner.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { StepCacheStore } from "./cache/cache-port.js";
|
|
2
|
-
import { BlockRunStore, LoadedRun, RunStore, SegmentQueue, StepRecord, TaskHandlers, TraceMode, TraceSink } from "./port.js";
|
|
2
|
+
import { BlockRunStore, LoadedRun, RunStore, SegmentQueue, StepRecord, TaskAnswer, TaskHandlers, TaskTokenStore, 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
|
|
@@ -14,6 +14,8 @@ export type RunnerPort<Db> = {
|
|
|
14
14
|
cache?: StepCacheStore;
|
|
15
15
|
/** Where blocks' runs are kept; without it a Block fails. */
|
|
16
16
|
blocks?: BlockRunStore<Db>;
|
|
17
|
+
/** Where waiting Tasks' tokens are kept; without it a Task that waits for an outside result fails. */
|
|
18
|
+
tokens?: TaskTokenStore<Db>;
|
|
17
19
|
secrets?: Readonly<Record<string, string>>;
|
|
18
20
|
trace?: TraceSink;
|
|
19
21
|
traceMode?: TraceMode;
|
|
@@ -21,14 +23,31 @@ export type RunnerPort<Db> = {
|
|
|
21
23
|
budgetMs?: number;
|
|
22
24
|
maxSteps?: number;
|
|
23
25
|
};
|
|
26
|
+
/**
|
|
27
|
+
* Why an answer to a waiting Task is refused, by the name Step Functions gives it: a token that is not one
|
|
28
|
+
* (`InvalidToken`), no try with this token (`TaskDoesNotExist`), a try that ended or whose run ended (`TaskTimedOut`),
|
|
29
|
+
* and a result or failure too large to keep (`InvalidOutput`).
|
|
30
|
+
*/
|
|
31
|
+
export type AnswerRefusal = {
|
|
32
|
+
error: 'InvalidToken' | 'TaskDoesNotExist' | 'TaskTimedOut' | 'InvalidOutput';
|
|
33
|
+
message: string;
|
|
34
|
+
};
|
|
24
35
|
/**
|
|
25
36
|
* The workflow runner over a port. `start` queues a run's first segment in `db`, which may be the caller's
|
|
26
37
|
* transaction, so the run starts when it commits; `segment` is what the queue's job runs.
|
|
27
38
|
*/
|
|
28
|
-
export declare const createRunner: <Db>({ store, queue, tasks, cache, blocks, secrets, trace, traceMode, now, budgetMs, maxSteps }: RunnerPort<Db>) => {
|
|
39
|
+
export declare const createRunner: <Db>({ store, queue, tasks, cache, blocks, tokens, secrets, trace, traceMode, now, budgetMs, maxSteps }: RunnerPort<Db>) => {
|
|
29
40
|
start: (db: Db, runId: string) => Promise<void>;
|
|
30
41
|
/** The steps an ended run's trace holds, which a re-run from one of them starts from: undefined when it kept none. */
|
|
31
42
|
readTrace: (runId: string) => Promise<readonly StepRecord[] | undefined>;
|
|
43
|
+
/**
|
|
44
|
+
* Takes an outside executor's answer to the waiting Task a token was given to: its result or failure, which wakes
|
|
45
|
+
* the run, or a heartbeat. The token is the only proof of who may answer, so it is never kept, only its hash. Gives
|
|
46
|
+
* the run it answered, or why it was refused.
|
|
47
|
+
*/
|
|
48
|
+
answerTask: (db: Db, token: string, answer: TaskAnswer) => Promise<{
|
|
49
|
+
run: string;
|
|
50
|
+
} | AnswerRefusal>;
|
|
32
51
|
/** Puts the steps a re-run from a step keeps of an earlier run at the start of `run`'s trace, as the run keeps one. */
|
|
33
52
|
keepSteps: (run: Pick<LoadedRun, "id" | "definition" | "trace">, steps: readonly StepRecord[]) => Promise<void> | undefined;
|
|
34
53
|
/**
|
package/dist/run/runner.js
CHANGED
|
@@ -1,21 +1,89 @@
|
|
|
1
1
|
import { limits } from "../limits.js";
|
|
2
2
|
import { blockDefinition } from "../definition/inner.js";
|
|
3
|
+
import { nestingDepth } from "../nesting.js";
|
|
3
4
|
import { blankedMark, secretRedactor } from "./redact.js";
|
|
5
|
+
import { taskTokenHash, tokenPattern } from "./task-token.js";
|
|
6
|
+
import { overdue } from "./waiting-task.js";
|
|
4
7
|
import { runSegment } from "./segment.js";
|
|
5
8
|
//#region src/run/runner.ts
|
|
6
9
|
const ended = /* @__PURE__ */ new Set(["succeeded", "failed"]);
|
|
10
|
+
const keptAnswer = (answer) => {
|
|
11
|
+
const invalid = (message) => ({
|
|
12
|
+
error: "InvalidOutput",
|
|
13
|
+
message
|
|
14
|
+
});
|
|
15
|
+
if (answer.kind === "success") {
|
|
16
|
+
const bytes = new TextEncoder().encode(answer.output).length;
|
|
17
|
+
if (bytes > limits.valueBytes) return invalid(`The output is ${bytes} bytes, over the ${limits.valueBytes / 1024} KiB a step keeps`);
|
|
18
|
+
let output;
|
|
19
|
+
try {
|
|
20
|
+
output = JSON.parse(answer.output);
|
|
21
|
+
} catch {
|
|
22
|
+
return invalid("The output is not JSON: send the result as a string of JSON, as SendTaskSuccess takes it");
|
|
23
|
+
}
|
|
24
|
+
if (nestingDepth(output, limits.inputDepth) > limits.inputDepth) return invalid(`The output nests more than ${limits.inputDepth} levels`);
|
|
25
|
+
return {
|
|
26
|
+
kind: "success",
|
|
27
|
+
output
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
if (answer.kind === "failure" && answer.error.length > limits.taskErrorLength) return invalid(`The error is ${answer.error.length} characters, more than ${limits.taskErrorLength}`);
|
|
31
|
+
if (answer.kind === "failure" && answer.cause.length > limits.taskCauseLength) return invalid(`The cause is ${answer.cause.length} characters, more than ${limits.taskCauseLength}`);
|
|
32
|
+
return answer;
|
|
33
|
+
};
|
|
7
34
|
const runDefinition = (run, definition = run.definition) => run.blockState ? blockDefinition(definition, run.blockState) : definition;
|
|
8
35
|
const blankedOut = (output) => (JSON.stringify(output) ?? "").includes(blankedMark);
|
|
9
36
|
/**
|
|
10
37
|
* The workflow runner over a port. `start` queues a run's first segment in `db`, which may be the caller's
|
|
11
38
|
* transaction, so the run starts when it commits; `segment` is what the queue's job runs.
|
|
12
39
|
*/
|
|
13
|
-
const createRunner = ({ store, queue, tasks, cache, blocks, secrets = {}, trace, traceMode = "all", now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
|
|
40
|
+
const createRunner = ({ store, queue, tasks, cache, blocks, tokens, secrets = {}, trace, traceMode = "all", now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
|
|
14
41
|
secretRedactor(Object.values(secrets));
|
|
15
42
|
return {
|
|
16
43
|
start: (db, runId) => queue.schedule(db, runId),
|
|
17
44
|
/** The steps an ended run's trace holds, which a re-run from one of them starts from: undefined when it kept none. */
|
|
18
45
|
readTrace: async (runId) => await trace?.read(runId) ?? void 0,
|
|
46
|
+
/**
|
|
47
|
+
* Takes an outside executor's answer to the waiting Task a token was given to: its result or failure, which wakes
|
|
48
|
+
* the run, or a heartbeat. The token is the only proof of who may answer, so it is never kept, only its hash. Gives
|
|
49
|
+
* the run it answered, or why it was refused.
|
|
50
|
+
*/
|
|
51
|
+
answerTask: async (db, token, answer) => {
|
|
52
|
+
if (!tokenPattern.test(token)) return {
|
|
53
|
+
error: "InvalidToken",
|
|
54
|
+
message: "This is not a task token"
|
|
55
|
+
};
|
|
56
|
+
const kept = keptAnswer(answer);
|
|
57
|
+
if (!("kind" in kept)) return kept;
|
|
58
|
+
const hash = await taskTokenHash(token);
|
|
59
|
+
const found = tokens && await tokens.byHash(db, hash);
|
|
60
|
+
if (!found) return {
|
|
61
|
+
error: "TaskDoesNotExist",
|
|
62
|
+
message: "No waiting Task was given this token"
|
|
63
|
+
};
|
|
64
|
+
const closed = {
|
|
65
|
+
error: "TaskTimedOut",
|
|
66
|
+
message: "The Task this token was given to has ended"
|
|
67
|
+
};
|
|
68
|
+
if (found.status !== "waiting") return closed;
|
|
69
|
+
const run = await store.load(db, found.run);
|
|
70
|
+
if (!run || ended.has(run.status)) return {
|
|
71
|
+
error: "TaskTimedOut",
|
|
72
|
+
message: "The run of the Task this token was given to has ended"
|
|
73
|
+
};
|
|
74
|
+
const at = now();
|
|
75
|
+
const late = overdue(found, at);
|
|
76
|
+
if (late) {
|
|
77
|
+
await queue.wake(db, found.run);
|
|
78
|
+
return {
|
|
79
|
+
error: "TaskTimedOut",
|
|
80
|
+
message: `The Task this token was given to has ended: ${late.cause}`
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
if (!await tokens.answer(db, hash, kept, at)) return closed;
|
|
84
|
+
if (answer.kind !== "heartbeat") await queue.wake(db, found.run);
|
|
85
|
+
return { run: found.run };
|
|
86
|
+
},
|
|
19
87
|
/** Puts the steps a re-run from a step keeps of an earlier run at the start of `run`'s trace, as the run keeps one. */
|
|
20
88
|
keepSteps: (run, steps) => trace?.write(run.id, steps, { mode: run.trace ?? run.definition.trace ?? traceMode }),
|
|
21
89
|
/**
|
|
@@ -50,6 +118,15 @@ const createRunner = ({ store, queue, tasks, cache, blocks, secrets = {}, trace,
|
|
|
50
118
|
}),
|
|
51
119
|
count: () => blocks.count(db, runId)
|
|
52
120
|
};
|
|
121
|
+
const taskTokens = tokens && {
|
|
122
|
+
find: (visit) => tokens.find(db, runId, visit),
|
|
123
|
+
begin: (task) => tokens.begin(db, {
|
|
124
|
+
...task,
|
|
125
|
+
run: runId
|
|
126
|
+
}),
|
|
127
|
+
handedOff: (visit, done) => tokens.handedOff(db, runId, visit, done),
|
|
128
|
+
close: (visit, failure, seen) => tokens.close(db, runId, visit, failure, seen)
|
|
129
|
+
};
|
|
53
130
|
const segment = {
|
|
54
131
|
runId,
|
|
55
132
|
definition,
|
|
@@ -60,6 +137,7 @@ const createRunner = ({ store, queue, tasks, cache, blocks, secrets = {}, trace,
|
|
|
60
137
|
tasks,
|
|
61
138
|
...cache && { cache },
|
|
62
139
|
...blockRuns && { blocks: blockRuns },
|
|
140
|
+
...taskTokens && { tokens: taskTokens },
|
|
63
141
|
signal,
|
|
64
142
|
now,
|
|
65
143
|
budgetMs,
|
package/dist/run/segment.d.ts
CHANGED
|
@@ -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, SegmentBlocks } from "./context.js";
|
|
6
|
+
import { ScopeOutcome, SegmentBlocks, SegmentTokens } from "./context.js";
|
|
7
7
|
//#region src/run/segment.d.ts
|
|
8
8
|
export type SegmentInput = {
|
|
9
9
|
runId: string;
|
|
@@ -28,6 +28,8 @@ export type SegmentInput = {
|
|
|
28
28
|
replayed?: Replayed;
|
|
29
29
|
/** The run's blocks' runs; without it a Block fails. */
|
|
30
30
|
blocks?: SegmentBlocks;
|
|
31
|
+
/** The run's waiting Tasks' tokens; without them a Task that waits for an outside result fails. */
|
|
32
|
+
tokens?: SegmentTokens;
|
|
31
33
|
signal: AbortSignal;
|
|
32
34
|
now?: () => Date;
|
|
33
35
|
/** How long the segment takes new steps. Default `limits.segmentMs`. */
|
|
@@ -46,5 +48,5 @@ export type SegmentOutcome = (ScopeOutcome | {
|
|
|
46
48
|
* (a Wait, a retry's delay), or yields once its time is up, saving its checkpoints on the way and as it pauses.
|
|
47
49
|
* `superseded` when another segment saved a newer checkpoint first.
|
|
48
50
|
*/
|
|
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>;
|
|
51
|
+
export declare const runSegment: ({ runId, definition, input, startedAt, secrets, redactor, saved, save, keep, tasks, cache, replayed, blocks, tokens, signal, now, budgetMs, maxSteps }: SegmentInput) => Promise<SegmentOutcome>;
|
|
50
52
|
//#endregion
|
package/dist/run/segment.js
CHANGED
|
@@ -11,7 +11,7 @@ import { replayOf } from "./replay-of.js";
|
|
|
11
11
|
* (a Wait, a retry's delay), or yields once its time is up, saving its checkpoints on the way and as it pauses.
|
|
12
12
|
* `superseded` when another segment saved a newer checkpoint first.
|
|
13
13
|
*/
|
|
14
|
-
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 }) => {
|
|
14
|
+
const runSegment = async ({ runId, definition, input, startedAt, secrets, redactor, saved, save, keep, tasks, cache, replayed, blocks, tokens, signal, now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
|
|
15
15
|
const latest = new Map(saved.map((checkpoint) => [checkpoint.scope, checkpoint]));
|
|
16
16
|
const after = new Map(saved.map((checkpoint) => [checkpoint.scope, checkpoint.seq]));
|
|
17
17
|
const steps = [];
|
|
@@ -55,6 +55,7 @@ const runSegment = async ({ runId, definition, input, startedAt, secrets, redact
|
|
|
55
55
|
} },
|
|
56
56
|
...replayed && { replay: replayOf(replayed) },
|
|
57
57
|
...blocks && { blocks },
|
|
58
|
+
...tokens && { tokens },
|
|
58
59
|
signal,
|
|
59
60
|
now,
|
|
60
61
|
deadline: Date.now() + budgetMs,
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
//#region src/run/task-token.d.ts
|
|
2
|
+
/** A task token: 32 random bytes in base64url, which grants answering one try of one waiting Task. */
|
|
3
|
+
export declare const tokenPattern: RegExp;
|
|
4
|
+
/** What a token is kept and found by: its SHA-256, in hex. */
|
|
5
|
+
export declare const taskTokenHash: (token: string) => Promise<string>;
|
|
6
|
+
//#endregion
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
//#region src/run/task-token.ts
|
|
2
|
+
/** A task token: 32 random bytes in base64url, which grants answering one try of one waiting Task. */
|
|
3
|
+
const tokenPattern = /^[A-Za-z0-9_-]{43}$/;
|
|
4
|
+
/** A new task token. */
|
|
5
|
+
const newTaskToken = () => btoa(String.fromCharCode(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)))).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
|
|
6
|
+
/** What a token is kept and found by: its SHA-256, in hex. */
|
|
7
|
+
const taskTokenHash = async (token) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token)))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
8
|
+
//#endregion
|
|
9
|
+
export { newTaskToken, taskTokenHash, tokenPattern };
|
|
@@ -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.
|
|
3
|
+
"version": "0.100.2",
|
|
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": {
|