@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.
- 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/import/http-connection.d.ts +12 -0
- package/dist/definition/import/http-connection.js +84 -0
- package/dist/definition/import/http-task.js +130 -0
- package/dist/definition/import/import-machine.d.ts +13 -0
- package/dist/definition/import/import-machine.js +58 -0
- package/dist/definition/import/result-shape.js +113 -0
- 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 +7 -3
- package/dist/index.js +4 -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
|
@@ -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,9 @@ 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 { ConnectionHeader, ConnectionHeaders } from "./definition/import/http-connection.js";
|
|
16
|
+
import { importStateMachine } from "./definition/import/import-machine.js";
|
|
17
|
+
import { taskResource, waitSuffix, waitsForToken } from "./definition/task-resource.js";
|
|
15
18
|
import { assignedNames } from "./definition/expression-fields.js";
|
|
16
19
|
import { Dependencies, dependsOn, machineDependencies } from "./definition/dataflow/dependencies.js";
|
|
17
20
|
import { limits } from "./limits.js";
|
|
@@ -20,11 +23,12 @@ import { ErrorOutput, StepError } from "./run/errors.js";
|
|
|
20
23
|
import { Redactor, redacted, secretRedactor, shortestSecret } from "./run/redact.js";
|
|
21
24
|
import { KeyShape } from "./run/cache/cache-key.js";
|
|
22
25
|
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";
|
|
26
|
+
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
27
|
import { EarlierCheckpoint, keptAssigned, rerunCheckpoint, rerunProblem, resultRead } from "./run/rerun.js";
|
|
25
28
|
import { RerunFrom, rerunFrom } from "./run/rerun-from.js";
|
|
26
29
|
import { heldBackLog } from "./run/replay.js";
|
|
27
|
-
import {
|
|
30
|
+
import { taskTokenHash, tokenPattern } from "./run/task-token.js";
|
|
31
|
+
import { AnswerRefusal, Runner, RunnerPort, createRunner } from "./run/runner.js";
|
|
28
32
|
import { SegmentInput, runSegment } from "./run/segment.js";
|
|
29
33
|
import { LoadedPlugin, loadPlugins } from "./plugin/load-plugins.js";
|
|
30
34
|
import { StepWiring, stepHandlers } from "./plugin/step-handlers.js";
|
|
@@ -32,4 +36,4 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
|
|
|
32
36
|
import { TypeEntry, Unavailable, typeList } from "./plugin/type-list.js";
|
|
33
37
|
import { ConnectionSupport, connectionUnavailable } from "./plugin/connection-availability.js";
|
|
34
38
|
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 };
|
|
39
|
+
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 ConnectionHeader, type ConnectionHeaders, 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, importStateMachine, 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";
|
|
@@ -15,10 +16,12 @@ import { orderOf } from "./definition/types.js";
|
|
|
15
16
|
import { checkDefinition } from "./definition/check-definition.js";
|
|
16
17
|
import { definitionFromParts, partOfProblem, partsOfDefinition } from "./definition/parts.js";
|
|
17
18
|
import { definitionWarnings } from "./definition/check-warnings.js";
|
|
19
|
+
import { importStateMachine } from "./definition/import/import-machine.js";
|
|
18
20
|
import { StepError } from "./run/errors.js";
|
|
19
21
|
import { redacted, secretRedactor, shortestSecret } from "./run/redact.js";
|
|
20
22
|
import { keptAssigned, rerunCheckpoint, rerunProblem, resultRead } from "./run/rerun.js";
|
|
21
23
|
import { heldBackLog } from "./run/replay.js";
|
|
24
|
+
import { taskTokenHash, tokenPattern } from "./run/task-token.js";
|
|
22
25
|
import { rerunFrom } from "./run/rerun-from.js";
|
|
23
26
|
import { runSegment } from "./run/segment.js";
|
|
24
27
|
import { createRunner } from "./run/runner.js";
|
|
@@ -28,4 +31,4 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
|
|
|
28
31
|
import { typeList } from "./plugin/type-list.js";
|
|
29
32
|
import { connectionUnavailable } from "./plugin/connection-availability.js";
|
|
30
33
|
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 };
|
|
34
|
+
export { StepError, allStates, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, importStateMachine, 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 };
|