@segmentstream/ontology 0.118.0 → 0.120.0
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/CHANGELOG.md +21 -0
- package/dist/analyze.d.ts +8 -1
- package/dist/analyze.js +41 -1
- package/dist/diagnostics.d.ts +3 -3
- package/dist/diagnostics.js +1 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +6 -0
- package/dist/manifest.d.ts +180 -112
- package/dist/manifest.js +6 -0
- package/dist/migrate/model.d.ts +116 -84
- package/dist/nitro-workflows.d.ts +29 -0
- package/dist/nitro-workflows.js +92 -5
- package/dist/ontology.d.ts +0 -5
- package/dist/ontology.js +8 -1
- package/dist/server.js +15 -7
- package/dist/service/chat/delivery.js +2 -0
- package/dist/service/errors.js +4 -3
- package/dist/service/schemas.d.ts +8 -0
- package/dist/service/schemas.js +2 -0
- package/dist/service/workflow-deployment.js +6 -0
- package/dist/service/workflows.d.ts +5 -0
- package/dist/service/workflows.js +150 -6
- package/dist/trigger-actions.d.ts +31 -0
- package/dist/trigger-actions.js +108 -0
- package/dist/trigger-run.d.ts +23 -0
- package/dist/trigger-run.js +49 -0
- package/dist/workflow-runtime.d.ts +15 -0
- package/dist/workflow.d.ts +42 -5
- package/dist/workflow.js +11 -0
- package/dist/workflows.d.ts +1 -0
- package/dist/workflows.js +1 -0
- package/package.json +1 -1
package/dist/ontology.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { analyze, } from "./analyze.js";
|
|
2
2
|
import { formatDiagnostics, InvalidOntology } from "./diagnostics.js";
|
|
3
3
|
import { buildManifest } from "./manifest.js";
|
|
4
|
+
import { withTriggerRunsWorkflows } from "./trigger-actions.js";
|
|
4
5
|
function isOntology(value) {
|
|
5
6
|
return "manifest" in value && "config" in value;
|
|
6
7
|
}
|
|
@@ -16,6 +17,11 @@ export function check(input, options = {}) {
|
|
|
16
17
|
* manifest's roles, whose permissions name entities the rebuilt ontology does not have, and whose
|
|
17
18
|
* `user` table may predate properties this SDK added to the built-in `User`.
|
|
18
19
|
*/
|
|
20
|
+
/** The configuration with the workflows its triggers that run an action are published as. */
|
|
21
|
+
function triggerRunsConfig(config) {
|
|
22
|
+
const workflows = withTriggerRunsWorkflows(config.workflows, config.triggers);
|
|
23
|
+
return workflows === config.workflows ? config : { ...config, workflows };
|
|
24
|
+
}
|
|
19
25
|
export function buildOntology(config, options) {
|
|
20
26
|
const analysis = analyze(config, options);
|
|
21
27
|
const errors = analysis.diagnostics.filter((diagnostic) => diagnostic.severity === "error");
|
|
@@ -27,7 +33,8 @@ export function buildOntology(config, options) {
|
|
|
27
33
|
});
|
|
28
34
|
}
|
|
29
35
|
return {
|
|
30
|
-
|
|
36
|
+
// A trigger that runs an action is served as the workflow it is published as.
|
|
37
|
+
config: triggerRunsConfig(config),
|
|
31
38
|
entities: analysis.entities,
|
|
32
39
|
roles: analysis.roles,
|
|
33
40
|
signIn: analysis.signIn,
|
package/dist/server.js
CHANGED
|
@@ -81,21 +81,29 @@ export function installWorkflowRuntime() {
|
|
|
81
81
|
const { resumeHook } = await import("workflow/api");
|
|
82
82
|
return resumeHook(token, payload);
|
|
83
83
|
},
|
|
84
|
+
hydrateArguments: async (value, run) => {
|
|
85
|
+
const { hydrateWorkflowArguments } = await import("@workflow/core/serialization");
|
|
86
|
+
return hydrateWorkflowArguments(value, run.runId, await runEncryptionKey(run));
|
|
87
|
+
},
|
|
84
88
|
hydrateError: async (value, run, kind) => {
|
|
85
|
-
const { getWorld } = await import("workflow/runtime");
|
|
86
89
|
const { hydrateRunError, hydrateStepError } = await import("@workflow/core/serialization");
|
|
87
|
-
const
|
|
88
|
-
const world = await getWorld();
|
|
89
|
-
const rawKey = await world.getEncryptionKeyForRun?.(run.runId, {
|
|
90
|
-
deploymentId: run.deploymentId,
|
|
91
|
-
});
|
|
92
|
-
const key = rawKey === undefined ? undefined : await importKey(rawKey);
|
|
90
|
+
const key = await runEncryptionKey(run);
|
|
93
91
|
return kind === "step"
|
|
94
92
|
? hydrateStepError(value, run.runId, key)
|
|
95
93
|
: hydrateRunError(value, run.runId, key);
|
|
96
94
|
},
|
|
97
95
|
});
|
|
98
96
|
}
|
|
97
|
+
/** The key the world encrypts a run's data with, or `undefined` when it does not encrypt. */
|
|
98
|
+
async function runEncryptionKey(run) {
|
|
99
|
+
const { getWorld } = await import("workflow/runtime");
|
|
100
|
+
const { importKey } = await import("@workflow/core/encryption");
|
|
101
|
+
const world = await getWorld();
|
|
102
|
+
const rawKey = await world.getEncryptionKeyForRun?.(run.runId, {
|
|
103
|
+
deploymentId: run.deploymentId,
|
|
104
|
+
});
|
|
105
|
+
return rawKey === undefined ? undefined : importKey(rawKey);
|
|
106
|
+
}
|
|
99
107
|
/**
|
|
100
108
|
* Registers the platform's workflow functions, compiled by the Workflow SDK in the server build:
|
|
101
109
|
* the plugin `ontologyWorkflows()` generates calls it at startup with the functions of the file it
|
|
@@ -303,6 +303,7 @@ agent = {}) {
|
|
|
303
303
|
if (reserve.status === "failed") {
|
|
304
304
|
return yield* new ActionRejected({
|
|
305
305
|
message: "This operation was refused. Its idempotency key is consumed.",
|
|
306
|
+
keyConsumed: true,
|
|
306
307
|
});
|
|
307
308
|
}
|
|
308
309
|
return {
|
|
@@ -382,6 +383,7 @@ agent = {}) {
|
|
|
382
383
|
if (outcome.status === "failed") {
|
|
383
384
|
return yield* new ActionRejected({
|
|
384
385
|
message: "The provider refused the message. This operation key is consumed.",
|
|
386
|
+
keyConsumed: true,
|
|
385
387
|
});
|
|
386
388
|
}
|
|
387
389
|
return {
|
package/dist/service/errors.js
CHANGED
|
@@ -490,16 +490,17 @@ export function expectedFailure(error, requestId) {
|
|
|
490
490
|
};
|
|
491
491
|
}
|
|
492
492
|
if (Predicate.isTagged(error, "ActionRejected")) {
|
|
493
|
-
const message =
|
|
493
|
+
const { message, keyConsumed } = error;
|
|
494
494
|
return {
|
|
495
495
|
status: 422,
|
|
496
496
|
body: {
|
|
497
497
|
error: "action_rejected",
|
|
498
|
-
detail: message,
|
|
498
|
+
detail: String(message),
|
|
499
499
|
requestId,
|
|
500
|
-
issues: [{ path: [], message }],
|
|
500
|
+
issues: [{ path: [], message: String(message) }],
|
|
501
501
|
...batchDetails(error),
|
|
502
502
|
...limitDetails(error),
|
|
503
|
+
...(keyConsumed === true ? { key_consumed: true } : {}),
|
|
503
504
|
},
|
|
504
505
|
};
|
|
505
506
|
}
|
|
@@ -591,6 +591,10 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
|
|
|
591
591
|
readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
|
|
592
592
|
readonly connection: Schema.optionalKey<Schema.String>;
|
|
593
593
|
}>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
|
|
594
|
+
readonly action: Schema.optionalKey<Schema.Struct<{
|
|
595
|
+
readonly entity: Schema.String;
|
|
596
|
+
readonly action: Schema.String;
|
|
597
|
+
}>>;
|
|
594
598
|
}>>>;
|
|
595
599
|
readonly toolsets: Schema.optionalKey<Schema.$Array<Schema.Struct<{
|
|
596
600
|
readonly name: Schema.String;
|
|
@@ -913,6 +917,10 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
|
|
|
913
917
|
readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
|
|
914
918
|
readonly connection: Schema.optionalKey<Schema.String>;
|
|
915
919
|
}>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
|
|
920
|
+
readonly action: Schema.optionalKey<Schema.Struct<{
|
|
921
|
+
readonly entity: Schema.String;
|
|
922
|
+
readonly action: Schema.String;
|
|
923
|
+
}>>;
|
|
916
924
|
}>>>>;
|
|
917
925
|
readonly toolsets: Schema.toEncoded<Schema.optionalKey<Schema.$Array<Schema.Struct<{
|
|
918
926
|
readonly name: Schema.String;
|
package/dist/service/schemas.js
CHANGED
|
@@ -612,6 +612,8 @@ export const ErrorSchemas = {
|
|
|
612
612
|
issues: Schema.Array(ValidationIssue),
|
|
613
613
|
batch: Schema.optionalKey(BatchErrorDetails),
|
|
614
614
|
limit: Schema.optionalKey(LimitErrorWire),
|
|
615
|
+
// The idempotency key is spent on an operation that did not happen: retry with a new one.
|
|
616
|
+
key_consumed: Schema.optionalKey(Schema.Literal(true)),
|
|
615
617
|
}),
|
|
616
618
|
rateLimited: errorBody("RateLimited", 429, ["rate_limited"]),
|
|
617
619
|
internal: errorBody("InternalError", 500, ["internal_error"]),
|
|
@@ -95,6 +95,12 @@ export function deploymentWorkflowEngine(engine, observe) {
|
|
|
95
95
|
await requireRun(runId);
|
|
96
96
|
return engine.listSteps(runId, options);
|
|
97
97
|
},
|
|
98
|
+
...(engine.getRunArguments
|
|
99
|
+
? {
|
|
100
|
+
// Only a run of this deployment is read, as getRun answers.
|
|
101
|
+
getRunArguments: async (runId) => (await getRun(runId)) === undefined ? undefined : engine.getRunArguments(runId),
|
|
102
|
+
}
|
|
103
|
+
: {}),
|
|
98
104
|
...(engine.diagnostics
|
|
99
105
|
? {
|
|
100
106
|
diagnostics: async (run, steps) => engine.diagnostics(await requireRun(run.runId), steps),
|
|
@@ -91,6 +91,11 @@ export interface WorkflowEngine {
|
|
|
91
91
|
}) => Promise<WorkflowPage<WorkflowRunRecord>>;
|
|
92
92
|
/** `undefined` when the world has no such run. */
|
|
93
93
|
readonly getRun: (runId: string) => Promise<WorkflowRunRecord | undefined>;
|
|
94
|
+
/**
|
|
95
|
+
* The arguments a run was started with, hydrated: `[input, context]`. `undefined` when the world
|
|
96
|
+
* has no such run. Without it, failed runs cannot be retried.
|
|
97
|
+
*/
|
|
98
|
+
readonly getRunArguments?: (runId: string) => Promise<ReadonlyArray<unknown> | undefined>;
|
|
94
99
|
readonly listSteps: (runId: string, page?: {
|
|
95
100
|
readonly limit?: number;
|
|
96
101
|
readonly cursor?: string;
|
|
@@ -38,7 +38,7 @@ export { WorkflowStepFailed } from "./workflow-errors.js";
|
|
|
38
38
|
import { runtimeCredential } from "./runtime-identity.js";
|
|
39
39
|
import { deploymentWorkflowEngine } from "./workflow-deployment.js";
|
|
40
40
|
import { decodeWorkflowArguments, encodeWorkflowArguments } from "../runtime/workflow-arguments.js";
|
|
41
|
-
import { WorkflowRecoveryUnavailable } from "../runtime/errors.js";
|
|
41
|
+
import { TriggerInputInvalid, WorkflowRecoveryUnavailable } from "../runtime/errors.js";
|
|
42
42
|
import { hasWorkflowError, hydrateWorkflowStepPage, readWorkflowDiagnostics, WORLD_PAGE_SIZE, } from "./workflow-diagnostics.js";
|
|
43
43
|
export { MAX_LISTED_WORKFLOW_EVENTS, WORLD_PAGE_SIZE } from "./workflow-diagnostics.js";
|
|
44
44
|
/**
|
|
@@ -112,6 +112,27 @@ export function worldWorkflowEngine(world, begin = (workflow, args, options) =>
|
|
|
112
112
|
},
|
|
113
113
|
resolveData: "none",
|
|
114
114
|
}),
|
|
115
|
+
getRunArguments: async (runId) => {
|
|
116
|
+
const hydrateArguments = installedWorkflowSdk().hydrateArguments;
|
|
117
|
+
if (hydrateArguments === undefined) {
|
|
118
|
+
throw new Error("The Workflow runtime cannot read a run's arguments.");
|
|
119
|
+
}
|
|
120
|
+
let run;
|
|
121
|
+
try {
|
|
122
|
+
run = await (await world()).runs.get(runId, { resolveData: "all" });
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
if (isRunNotFound(error)) {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
const hydrated = await hydrateArguments(run.input, {
|
|
131
|
+
runId,
|
|
132
|
+
...(run.deploymentId === undefined ? {} : { deploymentId: run.deploymentId }),
|
|
133
|
+
});
|
|
134
|
+
return Array.isArray(hydrated) ? hydrated : [hydrated];
|
|
135
|
+
},
|
|
115
136
|
getRun: async (runId) => {
|
|
116
137
|
try {
|
|
117
138
|
return await (await world()).runs.get(runId, { resolveData: "none" });
|
|
@@ -167,10 +188,24 @@ export function compiledWorkflowId(run) {
|
|
|
167
188
|
const id = run?.workflowId;
|
|
168
189
|
return typeof id === "string" && id !== "" ? id : undefined;
|
|
169
190
|
}
|
|
191
|
+
/**
|
|
192
|
+
* The declaration a workflow is served as: a trigger's that runs an action starts the run function
|
|
193
|
+
* the build compiled for it, which the generated plugin registered; a workflow's own is its `run`.
|
|
194
|
+
*/
|
|
195
|
+
function servedDeclaration(declaration, manifest) {
|
|
196
|
+
if (manifest.action === undefined) {
|
|
197
|
+
return declaration;
|
|
198
|
+
}
|
|
199
|
+
const compiled = platformWorkflows()?.triggerActions?.[manifest.name];
|
|
200
|
+
return compiled === undefined
|
|
201
|
+
? declaration
|
|
202
|
+
: { ...declaration, run: compiled };
|
|
203
|
+
}
|
|
170
204
|
function declaredWorkflows(ontology) {
|
|
171
205
|
const declarations = ontology.config.workflows ?? [];
|
|
172
206
|
return ontology.workflows.flatMap((manifest) => {
|
|
173
|
-
const
|
|
207
|
+
const found = declarations.find((candidate) => nameToWire(candidate.name) === manifest.name);
|
|
208
|
+
const declaration = found === undefined ? undefined : servedDeclaration(found, manifest);
|
|
174
209
|
return declaration === undefined
|
|
175
210
|
? []
|
|
176
211
|
: [
|
|
@@ -418,6 +453,8 @@ function iso(value) {
|
|
|
418
453
|
}
|
|
419
454
|
return value instanceof Date ? value.toISOString() : value;
|
|
420
455
|
}
|
|
456
|
+
/** The statuses of a run that may be started again with its input. */
|
|
457
|
+
const RETRYABLE_RUN_STATUSES = new Set(["failed", "cancelled"]);
|
|
421
458
|
/** Workflow SDK 5 attributes are flat strings; `$` keys belong to the SDK. */
|
|
422
459
|
function startAttributes(startedBy) {
|
|
423
460
|
return Object.fromEntries(Object.entries(startedBy)
|
|
@@ -665,6 +702,37 @@ export function workflowsLayer(options) {
|
|
|
665
702
|
}
|
|
666
703
|
},
|
|
667
704
|
run: async (step, effect) => runStep(await boundWorkflow(step), step, effect),
|
|
705
|
+
runTriggerAction: async (step, input) => {
|
|
706
|
+
const workflow = await boundWorkflow(step);
|
|
707
|
+
const runs = workflow.declaration.runs;
|
|
708
|
+
const trigger = workflow.declaration.triggers[0];
|
|
709
|
+
if (runs === undefined || workflow.manifest.action === undefined) {
|
|
710
|
+
throw new WorkflowStepFailed("WorkflowRunsNoAction", `The workflow ${workflow.manifest.name} is not a trigger that runs an action.`, true);
|
|
711
|
+
}
|
|
712
|
+
const invoke = runs;
|
|
713
|
+
if (trigger?.kind !== "webhook") {
|
|
714
|
+
return runStep(workflow, step, invoke(input));
|
|
715
|
+
}
|
|
716
|
+
// A webhook's run takes the delivery; its trigger maps it to the action's input.
|
|
717
|
+
const map = trigger.input;
|
|
718
|
+
const name = workflow.manifest.name;
|
|
719
|
+
if (typeof map !== "function") {
|
|
720
|
+
throw new WorkflowStepFailed("TriggerInputMissing", `The webhook ${name} declares no input function.`, true);
|
|
721
|
+
}
|
|
722
|
+
// In the step, so that a mapping that throws is reported as the step's failure, with the
|
|
723
|
+
// input function's own error as its cause, and not retried: the delivery stays the same.
|
|
724
|
+
const mapped = Effect.try({
|
|
725
|
+
try: () => map(input),
|
|
726
|
+
catch: (error) => Object.defineProperty(new TriggerInputInvalid({
|
|
727
|
+
trigger: `${name}.${name}`,
|
|
728
|
+
message: `The input function of the webhook ${name} failed on this delivery.`,
|
|
729
|
+
issues: [],
|
|
730
|
+
}), "cause", { value: error, configurable: true }),
|
|
731
|
+
});
|
|
732
|
+
return runStep(workflow, step, Effect.flatMap(mapped, (actionInput) => actionInput === null || actionInput === undefined
|
|
733
|
+
? Effect.succeed({ skipped: true })
|
|
734
|
+
: invoke(actionInput)));
|
|
735
|
+
},
|
|
668
736
|
recoverStarts: async (step, input) => {
|
|
669
737
|
const expected = recoveryWorkflowId();
|
|
670
738
|
if (expected === undefined || step.workflowName !== expected) {
|
|
@@ -948,7 +1016,7 @@ export function workflowsLayer(options) {
|
|
|
948
1016
|
* Starts a run with input in its wire form, as the cron, start and webhook routes receive
|
|
949
1017
|
* it: the run id, or the response that refuses it.
|
|
950
1018
|
*/
|
|
951
|
-
const beginRun = (workflow, input, context) => Effect.gen(function* () {
|
|
1019
|
+
const beginRun = (workflow, input, context, extraAttributes = {}) => Effect.gen(function* () {
|
|
952
1020
|
const requestId = yield* RequestId;
|
|
953
1021
|
const refused = (response) => ({ ok: false, response });
|
|
954
1022
|
// A workflow's input is an object of its fields, whatever its schema accepts.
|
|
@@ -1024,7 +1092,7 @@ export function workflowsLayer(options) {
|
|
|
1024
1092
|
input: input ?? {},
|
|
1025
1093
|
arguments: [decoded.value, context],
|
|
1026
1094
|
reservation: allocated.success,
|
|
1027
|
-
attributes: startAttributes(context.startedBy),
|
|
1095
|
+
attributes: { ...startAttributes(context.startedBy), ...extraAttributes },
|
|
1028
1096
|
commitBy,
|
|
1029
1097
|
})
|
|
1030
1098
|
.pipe(Effect.result);
|
|
@@ -1036,7 +1104,10 @@ export function workflowsLayer(options) {
|
|
|
1036
1104
|
const started = yield* Effect.tryPromise(() => engine.start(admitted
|
|
1037
1105
|
? { workflowId: admitted.workflowId }
|
|
1038
1106
|
: workflow.declaration.run, admitted?.arguments ?? [decoded.value, context], {
|
|
1039
|
-
attributes: admitted?.attributes ??
|
|
1107
|
+
attributes: admitted?.attributes ?? {
|
|
1108
|
+
...startAttributes(context.startedBy),
|
|
1109
|
+
...extraAttributes,
|
|
1110
|
+
},
|
|
1040
1111
|
...(admitted ? { reservation: admitted.reservation } : {}),
|
|
1041
1112
|
})).pipe(Effect.timeoutOrElse({
|
|
1042
1113
|
duration: "15 seconds",
|
|
@@ -1075,7 +1146,7 @@ export function workflowsLayer(options) {
|
|
|
1075
1146
|
return { ok: true, runId: started.success.runId };
|
|
1076
1147
|
});
|
|
1077
1148
|
/** Starts a run and answers 202 with its id, as the cron and start routes do. */
|
|
1078
|
-
const startRun = (workflow, input, context) => Effect.map(beginRun(workflow, input, context), (begun) => begun.ok
|
|
1149
|
+
const startRun = (workflow, input, context, extraAttributes = {}) => Effect.map(beginRun(workflow, input, context, extraAttributes), (begun) => begun.ok
|
|
1079
1150
|
? json({ runId: begun.runId, workflow: workflow.manifest.name }, 202)
|
|
1080
1151
|
: begun.response);
|
|
1081
1152
|
/** Authenticates a workflow route's caller: the platform's workload token, or a principal. */
|
|
@@ -1459,6 +1530,79 @@ export function workflowsLayer(options) {
|
|
|
1459
1530
|
: { kind: "member", userId: caller.principal.id };
|
|
1460
1531
|
return yield* startRun(workflow, fields.input, { startedBy });
|
|
1461
1532
|
})));
|
|
1533
|
+
// A failed or cancelled run, started again with its input, for a caller who may start it.
|
|
1534
|
+
yield* router.add("POST", `${WORKFLOW_BASE_PATH}/workflows/:workflow/runs/:runId/retry`, authorized((caller, request) => Effect.gen(function* () {
|
|
1535
|
+
const requestId = yield* RequestId;
|
|
1536
|
+
const params = yield* HttpRouter.params;
|
|
1537
|
+
const workflow = byName(params.workflow);
|
|
1538
|
+
if (workflow === undefined) {
|
|
1539
|
+
return unknownWorkflow(requestId);
|
|
1540
|
+
}
|
|
1541
|
+
const required = workflowPermission(workflow.manifest.name, "start");
|
|
1542
|
+
if (caller.kind === "principal" &&
|
|
1543
|
+
(caller.caller.kind === "runtime" || !isAllowed(required, caller.principal))) {
|
|
1544
|
+
return toServerResponse(forbidden(requestId, `Retrying a run of this workflow requires ${required}.`));
|
|
1545
|
+
}
|
|
1546
|
+
const workflowName = compiledWorkflowId(workflow.declaration.run);
|
|
1547
|
+
const runId = params.runId ?? "";
|
|
1548
|
+
const run = yield* recorded(() => engine.getRun(runId));
|
|
1549
|
+
if (!run.ok) {
|
|
1550
|
+
return run.refused;
|
|
1551
|
+
}
|
|
1552
|
+
if (run.value === undefined ||
|
|
1553
|
+
workflowName === undefined ||
|
|
1554
|
+
run.value.workflowName !== workflowName) {
|
|
1555
|
+
return toServerResponse(notFound(requestId, "This workflow has no such run."));
|
|
1556
|
+
}
|
|
1557
|
+
if (!RETRYABLE_RUN_STATUSES.has(run.value.status)) {
|
|
1558
|
+
return toServerResponse({
|
|
1559
|
+
status: 409,
|
|
1560
|
+
body: {
|
|
1561
|
+
error: "run_not_retryable",
|
|
1562
|
+
detail: `Only a failed or cancelled run can be retried; this one is ${run.value.status}.`,
|
|
1563
|
+
requestId,
|
|
1564
|
+
},
|
|
1565
|
+
});
|
|
1566
|
+
}
|
|
1567
|
+
if (engine.getRunArguments === undefined) {
|
|
1568
|
+
return toServerResponse(unavailable(requestId));
|
|
1569
|
+
}
|
|
1570
|
+
const read = yield* recorded(() => engine.getRunArguments(runId));
|
|
1571
|
+
if (!read.ok) {
|
|
1572
|
+
return read.refused;
|
|
1573
|
+
}
|
|
1574
|
+
if (read.value === undefined) {
|
|
1575
|
+
return toServerResponse(notFound(requestId, "This workflow has no such run."));
|
|
1576
|
+
}
|
|
1577
|
+
// The run's input as the workflow decoded it, encoded back to the wire form a start takes.
|
|
1578
|
+
const encoded = Schema.encodeUnknownResult(workflow.input)(read.value[0] ?? {});
|
|
1579
|
+
if (encoded._tag === "Failure") {
|
|
1580
|
+
return toServerResponse({
|
|
1581
|
+
status: 409,
|
|
1582
|
+
body: {
|
|
1583
|
+
error: "run_not_retryable",
|
|
1584
|
+
detail: "The run's input no longer fits the workflow's input.",
|
|
1585
|
+
requestId,
|
|
1586
|
+
},
|
|
1587
|
+
});
|
|
1588
|
+
}
|
|
1589
|
+
// The platform names the member it retries for, as it does on a start.
|
|
1590
|
+
const text = yield* request.text.pipe(Effect.orElseSucceed(() => ""));
|
|
1591
|
+
let named;
|
|
1592
|
+
try {
|
|
1593
|
+
named =
|
|
1594
|
+
text.trim() === ""
|
|
1595
|
+
? undefined
|
|
1596
|
+
: JSON.parse(text)?.startedBy;
|
|
1597
|
+
}
|
|
1598
|
+
catch {
|
|
1599
|
+
named = undefined;
|
|
1600
|
+
}
|
|
1601
|
+
const startedBy = caller.kind === "platform"
|
|
1602
|
+
? { kind: "platform", userId: typeof named === "string" ? named : null }
|
|
1603
|
+
: { kind: "member", userId: caller.principal.id };
|
|
1604
|
+
return yield* startRun(workflow, encoded.success, { startedBy }, { retryOf: runId });
|
|
1605
|
+
})));
|
|
1462
1606
|
yield* router.add("GET", `${WORKFLOW_BASE_PATH}/workflows`, authorized((caller) => Effect.sync(() => {
|
|
1463
1607
|
const now = new Date();
|
|
1464
1608
|
return json({
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type AnyActionHandle, type AnyWorkflow } from "./workflow.js";
|
|
2
|
+
/**
|
|
3
|
+
* Triggers listed in `defineOntology({ triggers })`: each runs one action, and is published as a
|
|
4
|
+
* workflow named like it, so that its workflow user, permissions, runs, starts and routes are a
|
|
5
|
+
* workflow's. This module turns them into those workflows; `check` reports what it cannot turn.
|
|
6
|
+
*/
|
|
7
|
+
/** A problem with a trigger listed in `defineOntology({ triggers })`, at `triggers.<name>`. */
|
|
8
|
+
export interface TriggerRunsProblem {
|
|
9
|
+
readonly code: "invalid-trigger" | "trigger_runs_invalid";
|
|
10
|
+
readonly path: string;
|
|
11
|
+
readonly message: string;
|
|
12
|
+
}
|
|
13
|
+
/** Whether a value is an action handle: callable, with its entity's and its own name. */
|
|
14
|
+
export declare function isActionHandle(value: unknown): value is AnyActionHandle;
|
|
15
|
+
/** The wire names of the action a handle names: `{ entity: "lead", action: "notify" }`. */
|
|
16
|
+
export declare function actionNames(handle: AnyActionHandle): {
|
|
17
|
+
readonly entity: string;
|
|
18
|
+
readonly action: string;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The workflows the listed triggers are published as, and the problems of the entries that are
|
|
22
|
+
* not triggers that run an action. A trigger without `runs` belongs in a workflow's `triggers`.
|
|
23
|
+
* A trigger already published among `existing`, as in the configuration `defineOntology` returns,
|
|
24
|
+
* is not published again, so that configuration checks and builds as the one it came from.
|
|
25
|
+
*/
|
|
26
|
+
export declare function triggerRunsWorkflows(triggers: unknown, existing?: unknown): {
|
|
27
|
+
readonly workflows: ReadonlyArray<AnyWorkflow>;
|
|
28
|
+
readonly problems: ReadonlyArray<TriggerRunsProblem>;
|
|
29
|
+
};
|
|
30
|
+
/** The workflows a configuration declares, with those its triggers are published as. */
|
|
31
|
+
export declare function withTriggerRunsWorkflows(workflows: ReadonlyArray<AnyWorkflow> | undefined, triggers: unknown): ReadonlyArray<AnyWorkflow> | undefined;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { nameToWire } from "./authoring-names.js";
|
|
2
|
+
import { webhookDelivery } from "./webhooks.js";
|
|
3
|
+
import { isWorkflowTrigger, WorkflowTypeId, } from "./workflow.js";
|
|
4
|
+
/**
|
|
5
|
+
* The run function a trigger's workflow declares before the build registers its compiled one. It
|
|
6
|
+
* never runs: the service starts the compiled function, and reports a workflow without one.
|
|
7
|
+
*/
|
|
8
|
+
async function uncompiledTriggerRun() {
|
|
9
|
+
throw new Error("A trigger's action runs only through the function the deployment's build compiles for it.");
|
|
10
|
+
}
|
|
11
|
+
/** Whether a value is an action handle: callable, with its entity's and its own name. */
|
|
12
|
+
export function isActionHandle(value) {
|
|
13
|
+
if (typeof value !== "function") {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
const handle = value;
|
|
17
|
+
return typeof handle.entity === "string" && typeof handle.name === "string";
|
|
18
|
+
}
|
|
19
|
+
/** The wire names of the action a handle names: `{ entity: "lead", action: "notify" }`. */
|
|
20
|
+
export function actionNames(handle) {
|
|
21
|
+
return { entity: nameToWire(handle.entity), action: nameToWire(handle.name) };
|
|
22
|
+
}
|
|
23
|
+
/** The action's input schema, which an action trigger's or a cron's run takes. */
|
|
24
|
+
function actionInputSchema(handle) {
|
|
25
|
+
return handle.input;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The workflows the listed triggers are published as, and the problems of the entries that are
|
|
29
|
+
* not triggers that run an action. A trigger without `runs` belongs in a workflow's `triggers`.
|
|
30
|
+
* A trigger already published among `existing`, as in the configuration `defineOntology` returns,
|
|
31
|
+
* is not published again, so that configuration checks and builds as the one it came from.
|
|
32
|
+
*/
|
|
33
|
+
export function triggerRunsWorkflows(triggers, existing) {
|
|
34
|
+
if (triggers === undefined) {
|
|
35
|
+
return { workflows: [], problems: [] };
|
|
36
|
+
}
|
|
37
|
+
if (!Array.isArray(triggers)) {
|
|
38
|
+
return {
|
|
39
|
+
workflows: [],
|
|
40
|
+
problems: [
|
|
41
|
+
{
|
|
42
|
+
code: "invalid-trigger",
|
|
43
|
+
path: "triggers",
|
|
44
|
+
message: "triggers is a list of webhook(…), after(…) and cron(…) that each name runs.",
|
|
45
|
+
},
|
|
46
|
+
],
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
const workflows = [];
|
|
50
|
+
const problems = [];
|
|
51
|
+
const published = new Set((Array.isArray(existing) ? existing : []).flatMap((workflow) => typeof workflow === "object" &&
|
|
52
|
+
workflow !== null &&
|
|
53
|
+
workflow.runs !== undefined
|
|
54
|
+
? [workflow.triggers?.[0]]
|
|
55
|
+
: []));
|
|
56
|
+
triggers.forEach((candidate, index) => {
|
|
57
|
+
if (published.has(candidate)) {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (!isWorkflowTrigger(candidate)) {
|
|
61
|
+
problems.push({
|
|
62
|
+
code: "invalid-trigger",
|
|
63
|
+
path: `triggers[${index}]`,
|
|
64
|
+
message: "is not a trigger; declare it with webhook(…), after(…) or cron(…).",
|
|
65
|
+
});
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const trigger = candidate;
|
|
69
|
+
const path = `triggers.${String(trigger.name)}`;
|
|
70
|
+
const reasons = [];
|
|
71
|
+
if (!isActionHandle(trigger.runs)) {
|
|
72
|
+
reasons.push("runs names the action the trigger runs, as its handle, such as Lead.actions.notify");
|
|
73
|
+
}
|
|
74
|
+
if (typeof trigger.role !== "string" || trigger.role.trim() === "") {
|
|
75
|
+
reasons.push("role names the declared role its runs hold");
|
|
76
|
+
}
|
|
77
|
+
if (trigger.kind === "webhook" && typeof trigger.input !== "function") {
|
|
78
|
+
reasons.push("input maps the delivery to the action's input, or returns null to skip it: " +
|
|
79
|
+
"input: (delivery) => …");
|
|
80
|
+
}
|
|
81
|
+
if (reasons.length > 0) {
|
|
82
|
+
problems.push({
|
|
83
|
+
code: "trigger_runs_invalid",
|
|
84
|
+
path,
|
|
85
|
+
message: `a trigger in defineOntology({ triggers }) runs an action: ${reasons.join("; ")}.`,
|
|
86
|
+
});
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const runs = trigger.runs;
|
|
90
|
+
workflows.push({
|
|
91
|
+
[WorkflowTypeId]: WorkflowTypeId,
|
|
92
|
+
name: trigger.name,
|
|
93
|
+
description: trigger.description,
|
|
94
|
+
role: trigger.role,
|
|
95
|
+
input: (trigger.kind === "webhook" ? webhookDelivery : actionInputSchema(runs)),
|
|
96
|
+
run: uncompiledTriggerRun,
|
|
97
|
+
triggers: [trigger],
|
|
98
|
+
connections: [],
|
|
99
|
+
runs,
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
return { workflows, problems };
|
|
103
|
+
}
|
|
104
|
+
/** The workflows a configuration declares, with those its triggers are published as. */
|
|
105
|
+
export function withTriggerRunsWorkflows(workflows, triggers) {
|
|
106
|
+
const published = triggerRunsWorkflows(triggers, workflows).workflows;
|
|
107
|
+
return published.length === 0 ? workflows : [...(workflows ?? []), ...published];
|
|
108
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The run of a trigger that runs an action, `defineOntology({ triggers })`: the body of the
|
|
3
|
+
* workflow function the build compiles for each such trigger. This module is part of the
|
|
4
|
+
* `workflows` entry, which the Workflow SDK bundles for a runtime without Node built-ins: it imports
|
|
5
|
+
* none, and none of the SDK. Its one step asks the ontology service, through the process's workflow
|
|
6
|
+
* binding, to run the trigger's action as the trigger's workflow user, so a failure is retried as
|
|
7
|
+
* any step's is and a refusal that would repeat is not.
|
|
8
|
+
*/
|
|
9
|
+
/** `runTriggerAction` was called outside a `"use workflow"` body. Marked fatal. */
|
|
10
|
+
export declare class TriggerRunWorkflowRequired extends Error {
|
|
11
|
+
readonly fatal = true;
|
|
12
|
+
constructor();
|
|
13
|
+
}
|
|
14
|
+
/** The service has no binding for trigger actions: an SDK older than the generated workflow. */
|
|
15
|
+
export declare class TriggerRunUnsupported extends Error {
|
|
16
|
+
readonly fatal = true;
|
|
17
|
+
constructor();
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Runs the trigger's action in one step and answers with what the action returned, or
|
|
21
|
+
* `{ skipped: true }` when a webhook's `input` skipped the delivery.
|
|
22
|
+
*/
|
|
23
|
+
export declare function runTriggerAction(input: unknown): Promise<unknown>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { boundStep } from "./workflow-runtime.js";
|
|
2
|
+
/**
|
|
3
|
+
* The run of a trigger that runs an action, `defineOntology({ triggers })`: the body of the
|
|
4
|
+
* workflow function the build compiles for each such trigger. This module is part of the
|
|
5
|
+
* `workflows` entry, which the Workflow SDK bundles for a runtime without Node built-ins: it imports
|
|
6
|
+
* none, and none of the SDK. Its one step asks the ontology service, through the process's workflow
|
|
7
|
+
* binding, to run the trigger's action as the trigger's workflow user, so a failure is retried as
|
|
8
|
+
* any step's is and a refusal that would repeat is not.
|
|
9
|
+
*/
|
|
10
|
+
/** `runTriggerAction` was called outside a `"use workflow"` body. Marked fatal. */
|
|
11
|
+
export class TriggerRunWorkflowRequired extends Error {
|
|
12
|
+
fatal = true;
|
|
13
|
+
constructor() {
|
|
14
|
+
super('runTriggerAction runs only in the "use workflow" body the deployment\'s build compiles for ' +
|
|
15
|
+
"a trigger listed in defineOntology({ triggers }).");
|
|
16
|
+
this.name = "TriggerRunWorkflowRequired";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** The service has no binding for trigger actions: an SDK older than the generated workflow. */
|
|
20
|
+
export class TriggerRunUnsupported extends Error {
|
|
21
|
+
fatal = true;
|
|
22
|
+
constructor() {
|
|
23
|
+
super("The serving ontology service does not run trigger actions; upgrade the ontology SDK.");
|
|
24
|
+
this.name = "TriggerRunUnsupported";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Runs the trigger's action with the run's input, through the service serving this run. */
|
|
28
|
+
async function triggerActionStep(input) {
|
|
29
|
+
"use step";
|
|
30
|
+
const { binding, step } = boundStep();
|
|
31
|
+
if (binding.runTriggerAction === undefined) {
|
|
32
|
+
throw new TriggerRunUnsupported();
|
|
33
|
+
}
|
|
34
|
+
return binding.runTriggerAction(step, input);
|
|
35
|
+
}
|
|
36
|
+
/** Whether this call is inside a `"use workflow"` body, where the Workflow SDK sets its sleep. */
|
|
37
|
+
function insideWorkflow() {
|
|
38
|
+
return (typeof globalThis[Symbol.for("WORKFLOW_SLEEP")] === "function");
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Runs the trigger's action in one step and answers with what the action returned, or
|
|
42
|
+
* `{ skipped: true }` when a webhook's `input` skipped the delivery.
|
|
43
|
+
*/
|
|
44
|
+
export async function runTriggerAction(input) {
|
|
45
|
+
if (!insideWorkflow()) {
|
|
46
|
+
throw new TriggerRunWorkflowRequired();
|
|
47
|
+
}
|
|
48
|
+
return triggerActionStep(input);
|
|
49
|
+
}
|
|
@@ -43,6 +43,11 @@ export interface WorkflowBinding {
|
|
|
43
43
|
readonly expireAgentTask: (step: WorkflowStepContext, taskId: string) => Promise<AgentTaskResult>;
|
|
44
44
|
/** One sweep of the pending action-trigger starts, for the platform's start recovery run. */
|
|
45
45
|
readonly recoverStarts: (step: WorkflowStepContext, input: StartRecoveryInput) => Promise<StartRecoveryOutcome>;
|
|
46
|
+
/**
|
|
47
|
+
* Runs the action of the trigger the run's workflow was published from, with the run's input,
|
|
48
|
+
* as that workflow's user; `{ skipped: true }` when a webhook's `input` returned `null`.
|
|
49
|
+
*/
|
|
50
|
+
readonly runTriggerAction?: (step: WorkflowStepContext, input: unknown) => Promise<unknown>;
|
|
46
51
|
}
|
|
47
52
|
/**
|
|
48
53
|
* The platform's own workflow functions, which `ontologyWorkflows()` writes beside the workspace's
|
|
@@ -52,6 +57,11 @@ export interface WorkflowBinding {
|
|
|
52
57
|
export interface PlatformWorkflows {
|
|
53
58
|
/** Sleeps, then starts the pending starts an action's request left; see `start-recovery.ts`. */
|
|
54
59
|
readonly recoverStarts: (...args: Array<never>) => Promise<unknown>;
|
|
60
|
+
/**
|
|
61
|
+
* The run function the build compiled for each trigger that runs an action, by the wire name
|
|
62
|
+
* of the workflow it is published as; see `trigger-run.ts`.
|
|
63
|
+
*/
|
|
64
|
+
readonly triggerActions?: Readonly<Record<string, (...args: Array<never>) => Promise<unknown>>>;
|
|
55
65
|
}
|
|
56
66
|
/**
|
|
57
67
|
* The Workflow SDK's `start`, world and `resumeHook`, loaded on first use. {@link installWorkflowRuntime}
|
|
@@ -71,6 +81,11 @@ export interface WorkflowSdk {
|
|
|
71
81
|
readonly runId: string;
|
|
72
82
|
}>;
|
|
73
83
|
readonly world: () => Promise<unknown>;
|
|
84
|
+
/** Hydrate a run's workflow arguments, for a retry that starts the run again with them. */
|
|
85
|
+
readonly hydrateArguments?: (value: unknown, run: {
|
|
86
|
+
readonly runId: string;
|
|
87
|
+
readonly deploymentId?: string;
|
|
88
|
+
}) => Promise<unknown>;
|
|
74
89
|
/** Hydrate only an error payload; inputs and outputs stay unresolved. */
|
|
75
90
|
readonly hydrateError?: (value: unknown, run: {
|
|
76
91
|
readonly runId: string;
|