@segmentstream/ontology 0.197.1 → 0.198.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 +93 -0
- package/dist/analyze.d.ts +2 -0
- package/dist/analyze.js +17 -0
- package/dist/bin/check.js +12 -0
- package/dist/bin/migrate.js +1 -1
- package/dist/connection.d.ts +109 -6
- package/dist/connection.js +132 -17
- package/dist/diagnostics.d.ts +3 -3
- package/dist/diagnostics.js +2 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/manifest.d.ts +28 -0
- package/dist/manifest.js +6 -0
- package/dist/migrate/apply.d.ts +7 -1
- package/dist/migrate/apply.js +12 -3
- package/dist/migrate/model.d.ts +8 -0
- package/dist/migrate/plan.js +14 -1
- package/dist/owned-workflows.d.ts +10 -0
- package/dist/owned-workflows.js +16 -0
- package/dist/runtime/owner-departures.d.ts +35 -0
- package/dist/runtime/owner-departures.js +64 -0
- package/dist/runtime/pipeline.d.ts +15 -1
- package/dist/runtime/pipeline.js +67 -1
- package/dist/runtime/principals.d.ts +17 -2
- package/dist/runtime/principals.js +33 -2
- package/dist/runtime/service-binding.js +17 -3
- package/dist/runtime/workflow-starts.d.ts +108 -8
- package/dist/runtime/workflow-starts.js +276 -49
- package/dist/service/agent/attachments.js +27 -6
- package/dist/service/agent/authentication.d.ts +5 -0
- package/dist/service/agent/authentication.js +1 -1
- package/dist/service/agent/task-caller.d.ts +4 -2
- package/dist/service/agent/task-caller.js +4 -2
- package/dist/service/authentication.d.ts +7 -0
- package/dist/service/authentication.js +12 -0
- package/dist/service/chat/envelope.d.ts +7 -0
- package/dist/service/chat/envelope.js +15 -0
- package/dist/service/config.d.ts +6 -0
- package/dist/service/connections.d.ts +17 -2
- package/dist/service/connections.js +21 -1
- package/dist/service/errors.js +27 -1
- package/dist/service/member-files.js +6 -0
- package/dist/service/operations.d.ts +8 -0
- package/dist/service/operations.js +11 -4
- package/dist/service/owned-connections.d.ts +80 -0
- package/dist/service/owned-connections.js +488 -0
- package/dist/service/runtime-contract.d.ts +22 -0
- package/dist/service/schemas.d.ts +2 -0
- package/dist/service/service.js +23 -2
- package/dist/service/workflow-errors.d.ts +12 -1
- package/dist/service/workflow-errors.js +15 -2
- package/dist/service/workflows.d.ts +22 -0
- package/dist/service/workflows.js +358 -48
- package/dist/start-recovery-contract.d.ts +17 -1
- package/dist/start-recovery-contract.js +11 -1
- package/dist/start-recovery.js +4 -1
- package/dist/storage/tables.d.ts +15 -0
- package/dist/storage/tables.js +21 -0
- package/dist/workflow.d.ts +20 -2
- package/package.json +1 -1
|
@@ -8,7 +8,10 @@ import { NO_INPUT } from "../analyze.js";
|
|
|
8
8
|
import { ONTOLOGY_QUEUE_NAMESPACE } from "../workflow-topics.js";
|
|
9
9
|
import { actionInputToWire } from "../authoring-input.js";
|
|
10
10
|
import { nameToWire } from "../authoring-names.js";
|
|
11
|
-
import { connectionContext } from "../connection.js";
|
|
11
|
+
import { connectionContext, testTransportOwner, withRunOwner, } from "../connection.js";
|
|
12
|
+
import { declaresOwnedWorkflow, ownedConnectionKeys } from "../owned-workflows.js";
|
|
13
|
+
import { actingConnectionOwner } from "../runtime/pipeline.js";
|
|
14
|
+
import { workflowSubject } from "../runtime/workflow-users.js";
|
|
12
15
|
import { Files } from "../files.js";
|
|
13
16
|
import { canonicalJson } from "../manifest.js";
|
|
14
17
|
import { unavailableFiles } from "../storage/file-access.js";
|
|
@@ -22,11 +25,12 @@ import { isAllowed, workflowPermission } from "../permissions.js";
|
|
|
22
25
|
import { OntologyActions, OntologyReads, OntologyWrites, } from "../runtime.js";
|
|
23
26
|
import { writesOnlyThroughActions } from "../runtime/generated-actions.js";
|
|
24
27
|
import { validate } from "../runtime/validation.js";
|
|
25
|
-
import { triggerContext, WorkflowStartFailed, } from "../runtime/workflow-starts.js";
|
|
26
|
-
import { RECOVERY_CONFIRM_MS, RECOVERY_COVERAGE_MARGIN_MS, RECOVERY_FIRST_SWEEP_MS, } from "../start-recovery-contract.js";
|
|
28
|
+
import { connectionOwnerOf, recordedOwner, runAttributes, triggerContext, WorkflowStartFailed, } from "../runtime/workflow-starts.js";
|
|
29
|
+
import { RECOVERY_CONFIRM_MS, RECOVERY_COVERAGE_MARGIN_MS, RECOVERY_FIRST_SWEEP_MS, RECOVERY_SWEEP_BUDGET_MS, } from "../start-recovery-contract.js";
|
|
27
30
|
import { nextCronTime, } from "../workflow.js";
|
|
28
31
|
import { platformWorkflows, setWorkflowBinding, WORKFLOW_BASE_PATH, workflowSdk, workflowStructures, } from "../workflow-runtime.js";
|
|
29
32
|
import { callbackIdentityToken, StepIdentityToken } from "./workflow-callback.js";
|
|
33
|
+
import { OwnerInactive } from "./workflow-errors.js";
|
|
30
34
|
import { bearerEquals } from "./cron-secret.js";
|
|
31
35
|
import { expireAgentTask, startAgentTask, } from "./agent/task-start.js";
|
|
32
36
|
import { CurrentPrincipal, WORKLOAD_TOKEN_TYPE, withPrincipal, workloadKind, } from "./authentication.js";
|
|
@@ -290,7 +294,7 @@ function recoveryWorkflow() {
|
|
|
290
294
|
* so it covers every request whose transaction deadline falls before that horizon, less a margin.
|
|
291
295
|
* Requests that arrive while a start is in flight wait for it instead of starting their own.
|
|
292
296
|
*/
|
|
293
|
-
export function workflowStarter(ontology, engine, clock = Date.now) {
|
|
297
|
+
export function workflowStarter(ontology, engine, clock = () => Date.now()) {
|
|
294
298
|
const workflows = declaredWorkflows(ontology);
|
|
295
299
|
const capture = (pending) => {
|
|
296
300
|
if (pending.arguments && pending.workflowId) {
|
|
@@ -320,7 +324,7 @@ export function workflowStarter(ontology, engine, clock = Date.now) {
|
|
|
320
324
|
...pending,
|
|
321
325
|
workflowId: id,
|
|
322
326
|
arguments: decodeWorkflowArguments(encodeWorkflowArguments([decoded.value, triggerContext(pending)])),
|
|
323
|
-
attributes: pending.attributes ??
|
|
327
|
+
attributes: pending.attributes ?? runAttributes(triggerContext(pending).startedBy, pending.owner),
|
|
324
328
|
};
|
|
325
329
|
};
|
|
326
330
|
// The horizon of the latest armed recovery run, as this process may rely on it.
|
|
@@ -475,7 +479,7 @@ export function workflowStarter(ontology, engine, clock = Date.now) {
|
|
|
475
479
|
}
|
|
476
480
|
const context = triggerContext(start);
|
|
477
481
|
const started = yield* Effect.tryPromise({
|
|
478
|
-
try: () => engine.start(workflow.declaration.run, [decoded.value, context], { attributes:
|
|
482
|
+
try: () => engine.start(workflow.declaration.run, [decoded.value, context], { attributes: runAttributes(context.startedBy, start.owner) }),
|
|
479
483
|
catch: (cause) => new WorkflowStartFailed({
|
|
480
484
|
reason: "engine",
|
|
481
485
|
message: "The Workflow SDK did not start the run.",
|
|
@@ -496,13 +500,67 @@ function iso(value) {
|
|
|
496
500
|
}
|
|
497
501
|
return value instanceof Date ? value.toISOString() : value;
|
|
498
502
|
}
|
|
503
|
+
/** How long a cron on an owned workflow may take to write one page of rows: what it arms for. */
|
|
504
|
+
const OWNED_PAGE_COMMIT_MS = 10_000;
|
|
505
|
+
/** Until when, from the request's arrival, a cron on an owned workflow starts runs. */
|
|
506
|
+
const OWNED_CRON_START_BUDGET_MS = 25_000;
|
|
507
|
+
/**
|
|
508
|
+
* Until when, from the request's arrival, a cron on an owned workflow reads pages of eligible
|
|
509
|
+
* users. It reads no page after it, so that the request answers and logs what it read before the
|
|
510
|
+
* function's own limit; owners on pages it did not read get no run for that fire.
|
|
511
|
+
*/
|
|
512
|
+
const OWNED_CRON_READ_BUDGET_MS = 40_000;
|
|
513
|
+
/** The pages of eligible users one cron reads at most: 500 each, 100,000 users. */
|
|
514
|
+
const OWNED_CRON_MAX_PAGES = 200;
|
|
499
515
|
/** The statuses of a run that may be started again with its input. */
|
|
500
516
|
const RETRYABLE_RUN_STATUSES = new Set(["failed", "cancelled"]);
|
|
501
|
-
/**
|
|
502
|
-
function
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
517
|
+
/** The run's owner as a run view presents it: the record, never the call kind. */
|
|
518
|
+
function ownerView(attributes) {
|
|
519
|
+
const owner = recordedOwner(attributes);
|
|
520
|
+
return owner === undefined || owner === "invalid"
|
|
521
|
+
? {}
|
|
522
|
+
: { owner: { entity: owner.entity, id: owner.id } };
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* How early a cron delivery may arrive and still be for the instant it precedes. Early deliveries
|
|
526
|
+
* are milliseconds to seconds early; a delivery this much short of the cron's period late is for
|
|
527
|
+
* the next instant.
|
|
528
|
+
*/
|
|
529
|
+
export const CRON_DELIVERY_SKEW_MS = 5_000;
|
|
530
|
+
/** How far back a delivery looks for the instant it is for. */
|
|
531
|
+
const CRON_DELIVERY_LOOKBACK_MS = 60 * 60_000;
|
|
532
|
+
/**
|
|
533
|
+
* The instant a cron delivery is for: the latest at which the expression fires, at most
|
|
534
|
+
* {@link CRON_DELIVERY_SKEW_MS} after the delivery and less than an hour before it. A delivery that
|
|
535
|
+
* arrives a little early, on time, late or again names the same instant. One late by the cron's
|
|
536
|
+
* period less {@link CRON_DELIVERY_SKEW_MS} or more names the next instant and counts as its
|
|
537
|
+
* delivery: each owner gets at most one run per instant, and the instant it missed gets none. A
|
|
538
|
+
* delivery with no such instant, as an operator's far from the schedule, is for the minute it
|
|
539
|
+
* arrived in.
|
|
540
|
+
*/
|
|
541
|
+
export function scheduledMinute(expression, now) {
|
|
542
|
+
const at = now.getTime();
|
|
543
|
+
const latest = at + CRON_DELIVERY_SKEW_MS;
|
|
544
|
+
let fired;
|
|
545
|
+
for (let next = nextCronTime(expression, new Date(at - CRON_DELIVERY_LOOKBACK_MS - 60_000)); next !== undefined && next.getTime() <= latest; next = nextCronTime(expression, next)) {
|
|
546
|
+
if (next.getTime() > at - CRON_DELIVERY_LOOKBACK_MS) {
|
|
547
|
+
fired = next;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return (fired ?? new Date(Math.floor(at / 60_000) * 60_000)).toISOString();
|
|
551
|
+
}
|
|
552
|
+
/** Whether the workflow lists an owned connection, so that its runs have owners. */
|
|
553
|
+
function isOwnedWorkflow(ontology, workflow) {
|
|
554
|
+
return ownedConnectionKeys(ontology.manifest, workflow).length > 0;
|
|
555
|
+
}
|
|
556
|
+
/** The owned keys a run's workflow lists, which its owner's credentials may be used for. */
|
|
557
|
+
function runConnectionOwner(ontology, workflow, owner) {
|
|
558
|
+
return owner === undefined
|
|
559
|
+
? undefined
|
|
560
|
+
: {
|
|
561
|
+
owner: connectionOwnerOf(owner),
|
|
562
|
+
listed: new Set(ownedConnectionKeys(ontology.manifest, workflow)),
|
|
563
|
+
};
|
|
506
564
|
}
|
|
507
565
|
/** Older runs and attributes from other uses carry no ontology start context. */
|
|
508
566
|
function runStartedBy(attributes) {
|
|
@@ -542,6 +600,7 @@ function runView(workflow, record, output) {
|
|
|
542
600
|
startedAt: iso(record.startedAt),
|
|
543
601
|
completedAt: iso(record.completedAt),
|
|
544
602
|
...(startedBy === undefined ? {} : { startedBy }),
|
|
603
|
+
...ownerView(record.attributes),
|
|
545
604
|
error: workflowRunErrorView(record.error, record.errorCode),
|
|
546
605
|
...output,
|
|
547
606
|
};
|
|
@@ -692,11 +751,10 @@ export function workflowsLayer(options) {
|
|
|
692
751
|
}));
|
|
693
752
|
}
|
|
694
753
|
}
|
|
695
|
-
|
|
696
|
-
const
|
|
697
|
-
const recordedWorkflow = async (runId) => {
|
|
754
|
+
const runRecords = new Map();
|
|
755
|
+
const recordedRun = async (runId) => {
|
|
698
756
|
requireDeploymentCapability(options.deployment, "workflows");
|
|
699
|
-
const cached =
|
|
757
|
+
const cached = runRecords.get(runId);
|
|
700
758
|
if (cached !== undefined) {
|
|
701
759
|
return cached;
|
|
702
760
|
}
|
|
@@ -704,11 +762,32 @@ export function workflowsLayer(options) {
|
|
|
704
762
|
if (run === undefined) {
|
|
705
763
|
return undefined;
|
|
706
764
|
}
|
|
707
|
-
if (
|
|
708
|
-
|
|
765
|
+
if (runRecords.size >= 1_000) {
|
|
766
|
+
runRecords.delete(runRecords.keys().next().value);
|
|
767
|
+
}
|
|
768
|
+
const recorded = {
|
|
769
|
+
workflowName: run.workflowName,
|
|
770
|
+
owner: recordedOwner(run.attributes),
|
|
771
|
+
};
|
|
772
|
+
runRecords.set(runId, recorded);
|
|
773
|
+
return recorded;
|
|
774
|
+
};
|
|
775
|
+
const recordedWorkflow = async (runId) => (await recordedRun(runId))?.workflowName;
|
|
776
|
+
/**
|
|
777
|
+
* The owner of a step's run, as the platform recorded it when the run started: the only
|
|
778
|
+
* source of an owner a step has. A run started before owners were recorded has none.
|
|
779
|
+
*/
|
|
780
|
+
const boundOwner = async (workflow, step) => {
|
|
781
|
+
// A workflow that lists no owned key has no owners, whatever an earlier deployment's run
|
|
782
|
+
// recorded: its steps act as the workflow's user.
|
|
783
|
+
if (!isOwnedWorkflow(plan.ontology, workflow.manifest)) {
|
|
784
|
+
return undefined;
|
|
785
|
+
}
|
|
786
|
+
const owner = (await recordedRun(step.workflowRunId))?.owner;
|
|
787
|
+
if (owner === "invalid") {
|
|
788
|
+
throw new WorkflowStepFailed("OwnerUnreadable", "The run records an owner this SDK cannot read; it runs as nobody else.", true);
|
|
709
789
|
}
|
|
710
|
-
|
|
711
|
-
return run.workflowName;
|
|
790
|
+
return owner;
|
|
712
791
|
};
|
|
713
792
|
/** The declared workflow a step's run runs, after checking the run's own record agrees. */
|
|
714
793
|
const boundWorkflow = async (step) => {
|
|
@@ -740,7 +819,10 @@ export function workflowsLayer(options) {
|
|
|
740
819
|
throw new WorkflowStepFailed("WorkflowNotDeclared", "The deployment declares no such workflow.", true);
|
|
741
820
|
}
|
|
742
821
|
},
|
|
743
|
-
run: async (step, effect) =>
|
|
822
|
+
run: async (step, effect) => {
|
|
823
|
+
const workflow = await boundWorkflow(step);
|
|
824
|
+
return runStep(workflow, step, effect, await boundOwner(workflow, step));
|
|
825
|
+
},
|
|
744
826
|
runTriggerAction: async (step, input) => {
|
|
745
827
|
const workflow = await boundWorkflow(step);
|
|
746
828
|
const runs = workflow.declaration.runs;
|
|
@@ -749,8 +831,9 @@ export function workflowsLayer(options) {
|
|
|
749
831
|
throw new WorkflowStepFailed("WorkflowRunsNoAction", `The workflow ${workflow.manifest.name} is not a trigger that runs an action.`, true);
|
|
750
832
|
}
|
|
751
833
|
const invoke = runs;
|
|
834
|
+
const owner = await boundOwner(workflow, step);
|
|
752
835
|
if (trigger?.kind !== "webhook") {
|
|
753
|
-
return runStep(workflow, step, invoke(input));
|
|
836
|
+
return runStep(workflow, step, invoke(input), owner);
|
|
754
837
|
}
|
|
755
838
|
// A webhook's run takes the delivery; its trigger maps it to the action's input.
|
|
756
839
|
const map = trigger.input;
|
|
@@ -770,7 +853,7 @@ export function workflowsLayer(options) {
|
|
|
770
853
|
});
|
|
771
854
|
return runStep(workflow, step, Effect.flatMap(mapped, (actionInput) => actionInput === null || actionInput === undefined
|
|
772
855
|
? Effect.succeed({ skipped: true })
|
|
773
|
-
: invoke(actionInput)));
|
|
856
|
+
: invoke(actionInput)), owner);
|
|
774
857
|
},
|
|
775
858
|
recoverStarts: async (step, input) => {
|
|
776
859
|
const expected = recoveryWorkflowId();
|
|
@@ -785,13 +868,26 @@ export function workflowsLayer(options) {
|
|
|
785
868
|
throw new WorkflowStepFailed("WorkflowMismatch", `The step names workflow ${step.workflowName}, which is not its run's.`, true);
|
|
786
869
|
}
|
|
787
870
|
const requestId = crypto.randomUUID();
|
|
871
|
+
// A cron on an owned workflow writes a row per owner: such an ontology's sweep drains
|
|
872
|
+
// batch after batch for a while, and its run's last sweep arms another run for what is
|
|
873
|
+
// left. Every other ontology's sweep starts one batch, as action triggers need.
|
|
874
|
+
const drains = declaresOwnedWorkflow(plan.ontology.manifest);
|
|
788
875
|
const result = backend.workflowStarts === undefined
|
|
789
876
|
? { started: 0, failed: 0, abandoned: 0, waiting: 0, at: new Date().toISOString() }
|
|
790
877
|
: await Effect.runPromise(backend.workflowStarts.sweep({
|
|
791
878
|
retryAbandoned: false,
|
|
792
879
|
requestId,
|
|
793
880
|
...(input.before === undefined ? {} : { before: input.before }),
|
|
881
|
+
...(drains ? { deadline: Date.now() + RECOVERY_SWEEP_BUDGET_MS } : {}),
|
|
794
882
|
}));
|
|
883
|
+
const rearmed = drains && input.last === true && result.waiting > 0;
|
|
884
|
+
if (rearmed) {
|
|
885
|
+
const armed = await Effect.runPromise(Effect.result(backend.workflowAdmissions?.ensureRecovery(Date.now()) ??
|
|
886
|
+
Effect.fail(new Error("The backend arms no recovery run."))));
|
|
887
|
+
if (armed._tag === "Failure") {
|
|
888
|
+
throw new WorkflowStepFailed("RecoveryUnavailable", "Starts are still waiting and no further recovery run could be armed.");
|
|
889
|
+
}
|
|
890
|
+
}
|
|
795
891
|
console.log(JSON.stringify({
|
|
796
892
|
event: "ontology.workflow.recovery_sweep",
|
|
797
893
|
requestId,
|
|
@@ -799,6 +895,7 @@ export function workflowsLayer(options) {
|
|
|
799
895
|
stepId: step.stepId,
|
|
800
896
|
attempt: step.attempt,
|
|
801
897
|
...result,
|
|
898
|
+
...(rearmed ? { rearmed } : {}),
|
|
802
899
|
}));
|
|
803
900
|
return result;
|
|
804
901
|
},
|
|
@@ -872,22 +969,52 @@ export function workflowsLayer(options) {
|
|
|
872
969
|
throw failure;
|
|
873
970
|
});
|
|
874
971
|
}
|
|
875
|
-
/**
|
|
876
|
-
|
|
972
|
+
/**
|
|
973
|
+
* The principal a step acts as. A run with an owner acts as that member, with the roles,
|
|
974
|
+
* permissions and scopes they hold now, read at each step, and names the workflow as the
|
|
975
|
+
* means; an owner who is no longer an active member fails the step, and the run never falls
|
|
976
|
+
* back to the workflow's user. A run without an owner acts as the workflow's user.
|
|
977
|
+
*/
|
|
978
|
+
const stepPrincipal = (workflow, owner) => Effect.gen(function* () {
|
|
979
|
+
if (owner !== undefined) {
|
|
980
|
+
const member = yield* backend.resolveRunOwner?.(owner.id) ?? Effect.succeed(undefined);
|
|
981
|
+
if (member === undefined || member.kind !== "member") {
|
|
982
|
+
return yield* new OwnerInactive({
|
|
983
|
+
reason: "owner_inactive",
|
|
984
|
+
message: `The owner of this run of ${workflow.manifest.name} is no longer an active ` +
|
|
985
|
+
"member; the run does not act as anyone else.",
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
return {
|
|
989
|
+
...member,
|
|
990
|
+
workflow: {
|
|
991
|
+
name: workflow.manifest.name,
|
|
992
|
+
subject: workflowSubject(options.workspaceId, workflow.manifest.name),
|
|
993
|
+
},
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
const principal = yield* backend.resolveWorkflowUser?.({
|
|
997
|
+
workspaceId: options.workspaceId,
|
|
998
|
+
workflow: workflow.manifest.name,
|
|
999
|
+
}) ?? Effect.succeed(undefined);
|
|
1000
|
+
if (principal === undefined) {
|
|
1001
|
+
return yield* new PermissionDenied({
|
|
1002
|
+
message: `The workflow user of ${workflow.manifest.name} is missing or inactive.`,
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
return principal;
|
|
1006
|
+
});
|
|
1007
|
+
/** Runs one step's effect as the run's owner, or as the workflow's user. */
|
|
1008
|
+
function runStep(workflow, step, effect, owner) {
|
|
877
1009
|
const requestId = crypto.randomUUID();
|
|
878
1010
|
// Capture this invocation's identity before Effect resumes from a shared database socket,
|
|
879
1011
|
// whose async context may not carry the callback token. Each invocation reads it anew.
|
|
880
1012
|
const identityToken = callbackIdentityToken() ?? process.env.VERCEL_OIDC_TOKEN;
|
|
1013
|
+
// Whose credentials the step's owned calls, and its actions', use: the run's recorded
|
|
1014
|
+
// owner's, and only for the owned keys the workflow lists.
|
|
1015
|
+
const runOwner = runConnectionOwner(plan.ontology, workflow.manifest, owner);
|
|
881
1016
|
const program = Effect.gen(function* () {
|
|
882
|
-
const principal = yield*
|
|
883
|
-
workspaceId: options.workspaceId,
|
|
884
|
-
workflow: workflow.manifest.name,
|
|
885
|
-
}) ?? Effect.succeed(undefined);
|
|
886
|
-
if (principal === undefined) {
|
|
887
|
-
return yield* new PermissionDenied({
|
|
888
|
-
message: `The workflow user of ${workflow.manifest.name} is missing or inactive.`,
|
|
889
|
-
});
|
|
890
|
-
}
|
|
1017
|
+
const principal = yield* stepPrincipal(workflow, owner);
|
|
891
1018
|
const caller = Context.make(CurrentPrincipal, {
|
|
892
1019
|
...principal,
|
|
893
1020
|
authenticatedVia: "workflow",
|
|
@@ -923,6 +1050,7 @@ export function workflowsLayer(options) {
|
|
|
923
1050
|
validateOnly: false,
|
|
924
1051
|
identityToken,
|
|
925
1052
|
...(actionOptions ? { options: actionOptions } : {}),
|
|
1053
|
+
runOwner,
|
|
926
1054
|
}));
|
|
927
1055
|
});
|
|
928
1056
|
const result = (outcome) => Effect.map(outcome, (answered) => answered.result);
|
|
@@ -1015,18 +1143,23 @@ export function workflowsLayer(options) {
|
|
|
1015
1143
|
.update(`${step.workflowRunId}:${step.stepId}`)
|
|
1016
1144
|
.digest("hex"),
|
|
1017
1145
|
}) ?? unavailableFiles;
|
|
1018
|
-
|
|
1019
|
-
// as the deployment, such as `workspaceSourceHistory`.
|
|
1020
|
-
const services = Context.make(OntologyReads, reads).pipe(Context.add(CurrentPrincipal, Context.get(caller, CurrentPrincipal)), Context.add(RequestId, requestId), Context.merge(identityToken === undefined
|
|
1021
|
-
? Context.empty()
|
|
1022
|
-
: Context.make(StepIdentityToken, identityToken)), Context.add(Files, files), Context.add(OntologyWrites, writes), Context.add(OntologyActions, actions), Context.merge(connectionContext(workflow.declaration.connections, options.connections({
|
|
1146
|
+
const transport = withRunOwner(options.connections({
|
|
1023
1147
|
identityToken,
|
|
1024
1148
|
audit: {
|
|
1025
1149
|
action: `workflow.${workflow.manifest.name}`,
|
|
1026
1150
|
principalId: principal.id,
|
|
1027
1151
|
requestId,
|
|
1028
1152
|
},
|
|
1029
|
-
}),
|
|
1153
|
+
}), runOwner);
|
|
1154
|
+
// A `Connections.test` transport names whose credential the stubs it answers see.
|
|
1155
|
+
const tested = testTransportOwner(transport);
|
|
1156
|
+
// The workflow user and the step's identity token, for helpers that call the platform
|
|
1157
|
+
// as the deployment, such as `workspaceSourceHistory`.
|
|
1158
|
+
const services = Context.make(OntologyReads, reads).pipe(Context.add(CurrentPrincipal, Context.get(caller, CurrentPrincipal)), Context.add(RequestId, requestId), Context.merge(identityToken === undefined
|
|
1159
|
+
? Context.empty()
|
|
1160
|
+
: Context.make(StepIdentityToken, identityToken)), Context.add(Files, files), Context.add(OntologyWrites, writes), Context.add(OntologyActions, actions), Context.merge(connectionContext(workflow.declaration.connections, transport, tested !== undefined
|
|
1161
|
+
? { files, owner: tested }
|
|
1162
|
+
: { files, owner: runOwner?.owner, listed: runOwner?.listed })));
|
|
1030
1163
|
console.info(JSON.stringify({
|
|
1031
1164
|
event: "ontology.workflow.step.started",
|
|
1032
1165
|
workflow: workflow.manifest.name,
|
|
@@ -1060,8 +1193,13 @@ export function workflowsLayer(options) {
|
|
|
1060
1193
|
* Starts a run with input in its wire form, as the cron, start and webhook routes receive
|
|
1061
1194
|
* it: the run id, or the response that refuses it.
|
|
1062
1195
|
*/
|
|
1063
|
-
const beginRun = (workflow, input,
|
|
1196
|
+
const beginRun = (workflow, input, startContext, extraAttributes = {}, owner) => Effect.gen(function* () {
|
|
1064
1197
|
const requestId = yield* RequestId;
|
|
1198
|
+
// The run's owner is fixed here: the run receives it, and its attributes record it.
|
|
1199
|
+
const context = owner === undefined
|
|
1200
|
+
? startContext
|
|
1201
|
+
: { ...startContext, owner: { entity: owner.entity, id: owner.id } };
|
|
1202
|
+
const attributes = { ...runAttributes(context.startedBy, owner), ...extraAttributes };
|
|
1065
1203
|
const refused = (response) => ({ ok: false, response });
|
|
1066
1204
|
// A workflow's input is an object of its fields, whatever its schema accepts.
|
|
1067
1205
|
const shape = validate(Schema.Record(Schema.String, Schema.Unknown), input ?? {});
|
|
@@ -1136,7 +1274,7 @@ export function workflowsLayer(options) {
|
|
|
1136
1274
|
input: input ?? {},
|
|
1137
1275
|
arguments: [decoded.value, context],
|
|
1138
1276
|
reservation: allocated.success,
|
|
1139
|
-
attributes
|
|
1277
|
+
attributes,
|
|
1140
1278
|
commitBy,
|
|
1141
1279
|
})
|
|
1142
1280
|
.pipe(Effect.result);
|
|
@@ -1148,10 +1286,7 @@ export function workflowsLayer(options) {
|
|
|
1148
1286
|
const started = yield* Effect.tryPromise(() => engine.start(admitted
|
|
1149
1287
|
? { workflowId: admitted.workflowId }
|
|
1150
1288
|
: workflow.declaration.run, admitted?.arguments ?? [decoded.value, context], {
|
|
1151
|
-
attributes: admitted?.attributes ??
|
|
1152
|
-
...startAttributes(context.startedBy),
|
|
1153
|
-
...extraAttributes,
|
|
1154
|
-
},
|
|
1289
|
+
attributes: admitted?.attributes ?? attributes,
|
|
1155
1290
|
...(admitted ? { reservation: admitted.reservation } : {}),
|
|
1156
1291
|
})).pipe(Effect.timeoutOrElse({
|
|
1157
1292
|
duration: "15 seconds",
|
|
@@ -1190,9 +1325,145 @@ export function workflowsLayer(options) {
|
|
|
1190
1325
|
return { ok: true, runId: started.success.runId };
|
|
1191
1326
|
});
|
|
1192
1327
|
/** Starts a run and answers 202 with its id, as the cron and start routes do. */
|
|
1193
|
-
const startRun = (workflow, input, context, extraAttributes = {}) => Effect.map(beginRun(workflow, input, context, extraAttributes), (begun) => begun.ok
|
|
1328
|
+
const startRun = (workflow, input, context, extraAttributes = {}, owner) => Effect.map(beginRun(workflow, input, context, extraAttributes, owner), (begun) => begun.ok
|
|
1194
1329
|
? json({ runId: begun.runId, workflow: workflow.manifest.name }, 202)
|
|
1195
1330
|
: begun.response);
|
|
1331
|
+
/**
|
|
1332
|
+
* A cron on an owned workflow (docs/private-connections-spec.md, "Starting the runs"): reads
|
|
1333
|
+
* the eligible users from SegmentStream 500 at a time, keeps the active members among them,
|
|
1334
|
+
* and writes one pending row per user for the cron's scheduled minute, each after arming the
|
|
1335
|
+
* recovery run that covers it. A repeated delivery writes no second row for a user. It then
|
|
1336
|
+
* starts the rows for as long as its budget lasts, and the recovery run starts the rest, so a
|
|
1337
|
+
* request that dies midway loses no user's run. Each run is a background run that belongs to
|
|
1338
|
+
* its user and acts as them.
|
|
1339
|
+
*/
|
|
1340
|
+
const startOwnedCron = (workflow, trigger, request) => Effect.gen(function* () {
|
|
1341
|
+
const requestId = yield* RequestId;
|
|
1342
|
+
const began = Date.now();
|
|
1343
|
+
const name = workflow.manifest.name;
|
|
1344
|
+
const triggerName = `${name}.${trigger.name}`;
|
|
1345
|
+
const keys = ownedConnectionKeys(plan.ontology.manifest, workflow.manifest);
|
|
1346
|
+
const starts = backend.workflowStarts;
|
|
1347
|
+
const admissions = backend.workflowAdmissions;
|
|
1348
|
+
const identityToken = requestIdentityToken(request) ?? process.env.VERCEL_OIDC_TOKEN;
|
|
1349
|
+
const workflowId = compiledWorkflowId(workflow.declaration.run);
|
|
1350
|
+
const unavailableBecause = (reason, cause) => Effect.as(Effect.logError("ontology.workflow.owned_cron.unavailable", cause).pipe(Effect.annotateLogs({ requestId, workflow: name, trigger: triggerName, reason })), toServerResponse({
|
|
1351
|
+
status: 503,
|
|
1352
|
+
body: {
|
|
1353
|
+
error: "workflow_unavailable",
|
|
1354
|
+
detail: "The workflow's runs could not be started. Quote the request id when you " +
|
|
1355
|
+
"report it.",
|
|
1356
|
+
requestId,
|
|
1357
|
+
},
|
|
1358
|
+
}));
|
|
1359
|
+
if (workflowId === undefined) {
|
|
1360
|
+
return yield* unavailableBecause("not_compiled");
|
|
1361
|
+
}
|
|
1362
|
+
if (options.eligibleOwners === undefined ||
|
|
1363
|
+
starts?.writeOwned === undefined ||
|
|
1364
|
+
starts.startFired === undefined ||
|
|
1365
|
+
admissions === undefined ||
|
|
1366
|
+
backend.activeMembers === undefined ||
|
|
1367
|
+
identityToken === undefined ||
|
|
1368
|
+
identityToken === "") {
|
|
1369
|
+
return yield* unavailableBecause("owned_runs_unavailable");
|
|
1370
|
+
}
|
|
1371
|
+
const decoded = validate(workflow.input, trigger.input ?? {});
|
|
1372
|
+
if (!decoded.ok) {
|
|
1373
|
+
return yield* unavailableBecause("invalid_input");
|
|
1374
|
+
}
|
|
1375
|
+
const fireKey = scheduledMinute(trigger.cron, new Date(began));
|
|
1376
|
+
const startedBy = { kind: "trigger", triggerKind: "cron", trigger: triggerName };
|
|
1377
|
+
let after = null;
|
|
1378
|
+
let eligible = 0;
|
|
1379
|
+
let written = 0;
|
|
1380
|
+
let skipped = 0;
|
|
1381
|
+
let pages = 0;
|
|
1382
|
+
let read = 0;
|
|
1383
|
+
do {
|
|
1384
|
+
const page = yield* Effect.tryPromise(() => options.eligibleOwners({ identityToken, keys, after, requestId })).pipe(Effect.result);
|
|
1385
|
+
if (page._tag === "Failure") {
|
|
1386
|
+
return yield* unavailableBecause("eligible_owners_unavailable", page.failure);
|
|
1387
|
+
}
|
|
1388
|
+
// Every page counts the same users who are not eligible; the first one is kept.
|
|
1389
|
+
if (pages === 0) {
|
|
1390
|
+
skipped += page.success.ineligible;
|
|
1391
|
+
}
|
|
1392
|
+
pages += 1;
|
|
1393
|
+
read += page.success.owners.length;
|
|
1394
|
+
const active = yield* backend.activeMembers(page.success.owners);
|
|
1395
|
+
const owners = page.success.owners.filter((id) => active.has(id));
|
|
1396
|
+
skipped += page.success.owners.length - owners.length;
|
|
1397
|
+
if (owners.length > 0) {
|
|
1398
|
+
// Before a row is written: what this request does not start, the recovery run does.
|
|
1399
|
+
const armed = yield* admissions
|
|
1400
|
+
.ensureRecovery(Date.now() + OWNED_PAGE_COMMIT_MS)
|
|
1401
|
+
.pipe(Effect.result);
|
|
1402
|
+
if (armed._tag === "Failure") {
|
|
1403
|
+
return yield* unavailableBecause("recovery_unavailable", armed.failure);
|
|
1404
|
+
}
|
|
1405
|
+
const rows = [];
|
|
1406
|
+
for (const id of owners) {
|
|
1407
|
+
const owner = { entity: "user", id, call: "background" };
|
|
1408
|
+
const context = { startedBy, owner: { entity: "user", id } };
|
|
1409
|
+
const encoded = yield* Effect.try({
|
|
1410
|
+
try: () => encodeWorkflowArguments([decoded.value, context]),
|
|
1411
|
+
catch: (cause) => cause,
|
|
1412
|
+
}).pipe(Effect.result);
|
|
1413
|
+
if (encoded._tag === "Failure") {
|
|
1414
|
+
return yield* unavailableBecause("invalid_input", encoded.failure);
|
|
1415
|
+
}
|
|
1416
|
+
rows.push({
|
|
1417
|
+
trigger: triggerName,
|
|
1418
|
+
workflow: name,
|
|
1419
|
+
fireKey,
|
|
1420
|
+
owner,
|
|
1421
|
+
input: trigger.input ?? {},
|
|
1422
|
+
workflowId,
|
|
1423
|
+
arguments: [decoded.value, context],
|
|
1424
|
+
attributes: runAttributes(startedBy, owner),
|
|
1425
|
+
});
|
|
1426
|
+
}
|
|
1427
|
+
written += yield* starts.writeOwned(rows);
|
|
1428
|
+
eligible += owners.length;
|
|
1429
|
+
}
|
|
1430
|
+
after = page.success.next;
|
|
1431
|
+
} while (after !== null &&
|
|
1432
|
+
pages < OWNED_CRON_MAX_PAGES &&
|
|
1433
|
+
Date.now() < began + OWNED_CRON_READ_BUDGET_MS);
|
|
1434
|
+
// Pages left unread: the owners on them get no run for this fire.
|
|
1435
|
+
const truncated = after === null ? undefined : pages < OWNED_CRON_MAX_PAGES ? "deadline" : "pages";
|
|
1436
|
+
const fired = eligible === 0
|
|
1437
|
+
? { started: 0, failed: 0, pending: 0 }
|
|
1438
|
+
: yield* starts.startFired({
|
|
1439
|
+
trigger: triggerName,
|
|
1440
|
+
fireKey,
|
|
1441
|
+
requestId,
|
|
1442
|
+
deadline: began + OWNED_CRON_START_BUDGET_MS,
|
|
1443
|
+
});
|
|
1444
|
+
yield* (truncated === undefined ? Effect.logInfo : Effect.logError)("ontology.workflow.owned_cron").pipe(Effect.annotateLogs({
|
|
1445
|
+
requestId,
|
|
1446
|
+
workflow: name,
|
|
1447
|
+
trigger: triggerName,
|
|
1448
|
+
fireKey,
|
|
1449
|
+
...(truncated === undefined ? {} : { truncated, pages, read }),
|
|
1450
|
+
eligible,
|
|
1451
|
+
written,
|
|
1452
|
+
started: fired.started,
|
|
1453
|
+
failed: fired.failed,
|
|
1454
|
+
pending: fired.pending,
|
|
1455
|
+
skipped,
|
|
1456
|
+
durationMs: Date.now() - began,
|
|
1457
|
+
}));
|
|
1458
|
+
return json({
|
|
1459
|
+
workflow: name,
|
|
1460
|
+
trigger: triggerName,
|
|
1461
|
+
eligible,
|
|
1462
|
+
started: fired.started,
|
|
1463
|
+
pending: fired.pending,
|
|
1464
|
+
skipped,
|
|
1465
|
+
}, 202);
|
|
1466
|
+
});
|
|
1196
1467
|
/** Authenticates a workflow route's caller: the platform's workload token, or a principal. */
|
|
1197
1468
|
const authorized = (handle) => (request) => Effect.gen(function* () {
|
|
1198
1469
|
const requestId = yield* RequestId;
|
|
@@ -1229,6 +1500,21 @@ export function workflowsLayer(options) {
|
|
|
1229
1500
|
...(runtime === undefined ? {} : { runtime }),
|
|
1230
1501
|
});
|
|
1231
1502
|
});
|
|
1503
|
+
const owned = (workflow) => isOwnedWorkflow(plan.ontology, workflow.manifest);
|
|
1504
|
+
/**
|
|
1505
|
+
* The owner of a run a caller starts: the member who starts an owned workflow, as an
|
|
1506
|
+
* interactive run, by the rule that selects an action's caller's own credential. The
|
|
1507
|
+
* platform, a service and anyone else start a run with no owner.
|
|
1508
|
+
*/
|
|
1509
|
+
const startingMember = (workflow, caller) => {
|
|
1510
|
+
if (!owned(workflow) || caller.kind !== "principal") {
|
|
1511
|
+
return undefined;
|
|
1512
|
+
}
|
|
1513
|
+
const member = actingConnectionOwner(caller.principal, caller.caller);
|
|
1514
|
+
return member === undefined
|
|
1515
|
+
? undefined
|
|
1516
|
+
: { entity: "user", id: member.id, call: "interactive" };
|
|
1517
|
+
};
|
|
1232
1518
|
const mayRead = (caller, workflow) => caller.kind === "platform" ||
|
|
1233
1519
|
isAllowed(workflowPermission(workflow, "read"), caller.principal);
|
|
1234
1520
|
const unknownWorkflow = (requestId) => toServerResponse(notFound(requestId, "The ontology declares no such workflow."));
|
|
@@ -1272,6 +1558,10 @@ export function workflowsLayer(options) {
|
|
|
1272
1558
|
if (workflow === undefined || trigger === undefined) {
|
|
1273
1559
|
return toServerResponse(notFound(requestId, "The ontology declares no such workflow trigger."));
|
|
1274
1560
|
}
|
|
1561
|
+
// An owned workflow runs once for each eligible user; every other, once.
|
|
1562
|
+
if (owned(workflow)) {
|
|
1563
|
+
return yield* startOwnedCron(workflow, trigger, request);
|
|
1564
|
+
}
|
|
1275
1565
|
return yield* startRun(workflow, trigger.input, {
|
|
1276
1566
|
startedBy: {
|
|
1277
1567
|
kind: "trigger",
|
|
@@ -1604,7 +1894,7 @@ export function workflowsLayer(options) {
|
|
|
1604
1894
|
userId: typeof fields.startedBy === "string" ? fields.startedBy : null,
|
|
1605
1895
|
}
|
|
1606
1896
|
: { kind: "member", userId: caller.principal.id };
|
|
1607
|
-
return yield* startRun(workflow, fields.input, { startedBy });
|
|
1897
|
+
return yield* startRun(workflow, fields.input, { startedBy }, {}, startingMember(workflow, caller));
|
|
1608
1898
|
})));
|
|
1609
1899
|
// A failed or cancelled run, started again with its input, for a caller who may start it.
|
|
1610
1900
|
yield* router.add("POST", `${WORKFLOW_BASE_PATH}/workflows/:workflow/runs/:runId/retry`, authorized((caller, request) => Effect.gen(function* () {
|
|
@@ -1677,7 +1967,27 @@ export function workflowsLayer(options) {
|
|
|
1677
1967
|
const startedBy = caller.kind === "platform"
|
|
1678
1968
|
? { kind: "platform", userId: typeof named === "string" ? named : null }
|
|
1679
1969
|
: { kind: "member", userId: caller.principal.id };
|
|
1680
|
-
|
|
1970
|
+
// A retry belongs to the original run's owner; the retrier is only who started it. The
|
|
1971
|
+
// owner's own retry keeps the original call kind. Anyone else's, another member's, a
|
|
1972
|
+
// service's or the platform's, is background: each owned call then needs the owner's
|
|
1973
|
+
// standing consent. A workflow that no longer lists an owned key has no owners.
|
|
1974
|
+
const original = recordedOwner(run.value.attributes);
|
|
1975
|
+
const owner = original === undefined || original === "invalid"
|
|
1976
|
+
? original
|
|
1977
|
+
: startingMember(workflow, caller)?.id === original.id
|
|
1978
|
+
? original
|
|
1979
|
+
: { ...original, call: "background" };
|
|
1980
|
+
if (owner === "invalid") {
|
|
1981
|
+
return toServerResponse({
|
|
1982
|
+
status: 409,
|
|
1983
|
+
body: {
|
|
1984
|
+
error: "run_not_retryable",
|
|
1985
|
+
detail: "The run records an owner this SDK cannot read.",
|
|
1986
|
+
requestId,
|
|
1987
|
+
},
|
|
1988
|
+
});
|
|
1989
|
+
}
|
|
1990
|
+
return yield* startRun(workflow, encoded.success, { startedBy }, { retryOf: runId }, owned(workflow) ? owner : undefined);
|
|
1681
1991
|
})));
|
|
1682
1992
|
yield* router.add("GET", `${WORKFLOW_BASE_PATH}/workflows`, authorized((caller) => Effect.sync(() => {
|
|
1683
1993
|
const now = new Date();
|
|
@@ -20,12 +20,28 @@ export declare const RECOVERY_CONFIRM_MS = 60000;
|
|
|
20
20
|
export declare const RECOVERY_RETRY_MS: ReadonlyArray<number>;
|
|
21
21
|
/** Coverage the arming request keeps back from the run's horizon, for the start's own latency. */
|
|
22
22
|
export declare const RECOVERY_COVERAGE_MARGIN_MS = 5000;
|
|
23
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* The sweeps one run makes at most. Rows still pending then are left for an operator's sweep, except
|
|
25
|
+
* in an ontology that declares an owned workflow, whose last sweep arms another recovery run.
|
|
26
|
+
*/
|
|
24
27
|
export declare const RECOVERY_MAX_SWEEPS = 32;
|
|
28
|
+
/**
|
|
29
|
+
* How long one sweep of an ontology that declares an owned workflow starts rows, batch after batch,
|
|
30
|
+
* so that a cron's rows for thousands of owners drain in a few sweeps. It stays below the 30-second
|
|
31
|
+
* lease a sweep holds on a row, so that a row whose start failed is not taken again in the same
|
|
32
|
+
* sweep. Every other ontology's sweep starts one batch.
|
|
33
|
+
*/
|
|
34
|
+
export declare const RECOVERY_SWEEP_BUDGET_MS = 20000;
|
|
25
35
|
/** The step's input: the horizon the run answers for, from its second sweep on. */
|
|
26
36
|
export interface StartRecoveryInput {
|
|
27
37
|
/** Count as waiting only the pending rows created before this instant, ISO 8601. */
|
|
28
38
|
readonly before?: string;
|
|
39
|
+
/**
|
|
40
|
+
* This is the run's last sweep ({@link RECOVERY_MAX_SWEEPS}). For an ontology that declares an
|
|
41
|
+
* owned workflow, rows still waiting after it arm another recovery run, so that every row of a
|
|
42
|
+
* cron's fire is started without waiting for another trigger.
|
|
43
|
+
*/
|
|
44
|
+
readonly last?: boolean;
|
|
29
45
|
}
|
|
30
46
|
/** What one sweep did and what is left. */
|
|
31
47
|
export interface StartRecoveryOutcome {
|
|
@@ -22,5 +22,15 @@ export const RECOVERY_RETRY_MS = [
|
|
|
22
22
|
];
|
|
23
23
|
/** Coverage the arming request keeps back from the run's horizon, for the start's own latency. */
|
|
24
24
|
export const RECOVERY_COVERAGE_MARGIN_MS = 5_000;
|
|
25
|
-
/**
|
|
25
|
+
/**
|
|
26
|
+
* The sweeps one run makes at most. Rows still pending then are left for an operator's sweep, except
|
|
27
|
+
* in an ontology that declares an owned workflow, whose last sweep arms another recovery run.
|
|
28
|
+
*/
|
|
26
29
|
export const RECOVERY_MAX_SWEEPS = 32;
|
|
30
|
+
/**
|
|
31
|
+
* How long one sweep of an ontology that declares an owned workflow starts rows, batch after batch,
|
|
32
|
+
* so that a cron's rows for thousands of owners drain in a few sweeps. It stays below the 30-second
|
|
33
|
+
* lease a sweep holds on a row, so that a row whose start failed is not taken again in the same
|
|
34
|
+
* sweep. Every other ontology's sweep starts one batch.
|
|
35
|
+
*/
|
|
36
|
+
export const RECOVERY_SWEEP_BUDGET_MS = 20_000;
|