@proofoftech/flowsafe 0.20.0 → 0.22.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 +101 -0
- package/README.md +55 -10
- package/deployment-identity-protocol.d.mts +28 -3
- package/deployment-identity-protocol.mjs +275 -21
- package/dist/agent-host/router.d.ts.map +1 -1
- package/dist/agent-host/router.js +11 -2
- package/dist/agent-host/router.js.map +1 -1
- package/dist/agent-host/thread-host.d.ts +3 -1
- package/dist/agent-host/thread-host.d.ts.map +1 -1
- package/dist/agent-host/thread-host.js +858 -351
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/agent-host/thread-topology.d.ts +8 -0
- package/dist/agent-host/thread-topology.d.ts.map +1 -1
- package/dist/agent-host/thread-topology.js +243 -64
- package/dist/agent-host/thread-topology.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +89 -14
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +369 -44
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/agent-runner/index.d.ts +1 -1
- package/dist/agent-runner/index.d.ts.map +1 -1
- package/dist/agent-runner/index.js.map +1 -1
- package/dist/approval-api/actor-context.d.ts +4 -0
- package/dist/approval-api/actor-context.d.ts.map +1 -1
- package/dist/approval-api/actor-context.js +53 -5
- package/dist/approval-api/actor-context.js.map +1 -1
- package/dist/approval-api/principal.d.ts +1 -1
- package/dist/approval-api/principal.js +1 -1
- package/dist/approval-api/retention.d.ts +1 -2
- package/dist/approval-api/retention.d.ts.map +1 -1
- package/dist/approval-api/retention.js.map +1 -1
- package/dist/approval-api/service.d.ts +13 -20
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +52 -28
- package/dist/approval-api/service.js.map +1 -1
- package/dist/audit-export/index.d.ts +2 -2
- package/dist/audit-export/index.js +2 -2
- package/dist/background-tasks/d1-storage.d.ts +4 -3
- package/dist/background-tasks/d1-storage.d.ts.map +1 -1
- package/dist/background-tasks/d1-storage.js +8 -14
- package/dist/background-tasks/d1-storage.js.map +1 -1
- package/dist/background-tasks/host.d.ts.map +1 -1
- package/dist/background-tasks/host.js +3 -2
- package/dist/background-tasks/host.js.map +1 -1
- package/dist/do-runner/constants.d.ts +3 -0
- package/dist/do-runner/constants.d.ts.map +1 -0
- package/dist/do-runner/constants.js +3 -0
- package/dist/do-runner/constants.js.map +1 -0
- package/dist/do-runner/d1-storage.d.ts +34 -158
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +935 -402
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +472 -185
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/execution-admission.d.ts +114 -0
- package/dist/do-runner/execution-admission.d.ts.map +1 -0
- package/dist/do-runner/execution-admission.js +206 -0
- package/dist/do-runner/execution-admission.js.map +1 -0
- package/dist/do-runner/execution-context.d.ts +5 -1
- package/dist/do-runner/execution-context.d.ts.map +1 -1
- package/dist/do-runner/execution-context.js +6 -1
- package/dist/do-runner/execution-context.js.map +1 -1
- package/dist/do-runner/execution-fence.d.ts +74 -30
- package/dist/do-runner/execution-fence.d.ts.map +1 -1
- package/dist/do-runner/execution-fence.js +684 -120
- package/dist/do-runner/execution-fence.js.map +1 -1
- package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
- package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
- package/dist/do-runner/fenced-workflow-capability.js +3 -0
- package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
- package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
- package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
- package/dist/do-runner/fenced-workflows-d1.js +894 -0
- package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
- package/dist/do-runner/index.d.ts +13 -8
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +6 -2
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
- package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
- package/dist/do-runner/initial-admission-refusal.js +41 -0
- package/dist/do-runner/initial-admission-refusal.js.map +1 -0
- package/dist/do-runner/inventory.d.ts +2 -1
- package/dist/do-runner/inventory.d.ts.map +1 -1
- package/dist/do-runner/inventory.js +28 -39
- package/dist/do-runner/inventory.js.map +1 -1
- package/dist/do-runner/notification-predicate.d.ts +7 -7
- package/dist/do-runner/notification-predicate.d.ts.map +1 -1
- package/dist/do-runner/notification-predicate.js +134 -7
- package/dist/do-runner/notification-predicate.js.map +1 -1
- package/dist/do-runner/run-lifecycle.d.ts +20 -1
- package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
- package/dist/do-runner/run-lifecycle.js +69 -15
- package/dist/do-runner/run-lifecycle.js.map +1 -1
- package/dist/do-runner/run-provenance.d.ts +38 -0
- package/dist/do-runner/run-provenance.d.ts.map +1 -0
- package/dist/do-runner/run-provenance.js +152 -0
- package/dist/do-runner/run-provenance.js.map +1 -0
- package/dist/do-runner/run-storage-tables.d.ts +2 -0
- package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
- package/dist/do-runner/run-storage-tables.js +4 -0
- package/dist/do-runner/run-storage-tables.js.map +1 -0
- package/dist/do-runner/run-terminal-state.d.ts +29 -0
- package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
- package/dist/do-runner/run-terminal-state.js +105 -0
- package/dist/do-runner/run-terminal-state.js.map +1 -0
- package/dist/do-runner/runtime.d.ts +108 -46
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +927 -438
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/start-idempotency.d.ts +35 -258
- package/dist/do-runner/start-idempotency.d.ts.map +1 -1
- package/dist/do-runner/start-idempotency.js +606 -498
- package/dist/do-runner/start-idempotency.js.map +1 -1
- package/dist/do-runner/start-reservation-contract.d.ts +103 -0
- package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
- package/dist/do-runner/start-reservation-contract.js +338 -0
- package/dist/do-runner/start-reservation-contract.js.map +1 -0
- package/dist/do-runner/suspension-deadline.d.ts +4 -11
- package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
- package/dist/do-runner/suspension-deadline.js +8 -12
- package/dist/do-runner/suspension-deadline.js.map +1 -1
- package/dist/do-runner/table-prefix.d.ts.map +1 -1
- package/dist/do-runner/table-prefix.js +2 -1
- package/dist/do-runner/table-prefix.js.map +1 -1
- package/dist/do-runner/testing.d.ts +3 -0
- package/dist/do-runner/testing.d.ts.map +1 -0
- package/dist/do-runner/testing.js +3 -0
- package/dist/do-runner/testing.js.map +1 -0
- package/dist/do-runner/thread-do.d.ts +2 -1
- package/dist/do-runner/thread-do.d.ts.map +1 -1
- package/dist/do-runner/thread-do.js +14 -10
- package/dist/do-runner/thread-do.js.map +1 -1
- package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
- package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
- package/dist/do-runner/workflow-snapshot-row.js +97 -0
- package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
- package/dist/goals/objective-routes.d.ts +1 -5
- package/dist/goals/objective-routes.d.ts.map +1 -1
- package/dist/goals/objective-routes.js +32 -53
- package/dist/goals/objective-routes.js.map +1 -1
- package/dist/host-kit/approval-bridge.d.ts +8 -8
- package/dist/host-kit/approval-bridge.d.ts.map +1 -1
- package/dist/host-kit/approval-bridge.js +18 -15
- package/dist/host-kit/approval-bridge.js.map +1 -1
- package/dist/host-kit/do-response.d.ts +16 -0
- package/dist/host-kit/do-response.d.ts.map +1 -1
- package/dist/host-kit/do-response.js +181 -0
- package/dist/host-kit/do-response.js.map +1 -1
- package/dist/host-kit/do-run-topology.d.ts +2 -14
- package/dist/host-kit/do-run-topology.d.ts.map +1 -1
- package/dist/host-kit/do-run-topology.js +31 -24
- package/dist/host-kit/do-run-topology.js.map +1 -1
- package/dist/host-kit/env-vars.d.ts.map +1 -1
- package/dist/host-kit/env-vars.js +5 -6
- package/dist/host-kit/env-vars.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +38 -6
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +115 -93
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/host-approval-service.d.ts +4 -14
- package/dist/host-kit/host-approval-service.d.ts.map +1 -1
- package/dist/host-kit/host-approval-service.js +23 -40
- package/dist/host-kit/host-approval-service.js.map +1 -1
- package/dist/host-kit/index.d.ts +7 -1
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +4 -0
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/run-route-error.d.ts +3 -17
- package/dist/host-kit/run-route-error.d.ts.map +1 -1
- package/dist/host-kit/run-route-error.js +4 -24
- package/dist/host-kit/run-route-error.js.map +1 -1
- package/dist/host-kit/run-router.d.ts +6 -2
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js +93 -80
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/host-kit/thread-topology.d.ts +1 -1
- package/dist/host-kit/thread-topology.d.ts.map +1 -1
- package/dist/host-kit/thread-topology.js +7 -3
- package/dist/host-kit/thread-topology.js.map +1 -1
- package/dist/internal-error-response.d.ts.map +1 -1
- package/dist/internal-error-response.js +16 -6
- package/dist/internal-error-response.js.map +1 -1
- package/dist/schedules/index.d.ts +1 -0
- package/dist/schedules/index.d.ts.map +1 -1
- package/dist/schedules/index.js +1 -7
- package/dist/schedules/index.js.map +1 -1
- package/dist/schedules/mutation-contract.d.ts +38 -0
- package/dist/schedules/mutation-contract.d.ts.map +1 -0
- package/dist/schedules/mutation-contract.js +21 -0
- package/dist/schedules/mutation-contract.js.map +1 -0
- package/dist/schedules/router.d.ts +11 -19
- package/dist/schedules/router.d.ts.map +1 -1
- package/dist/schedules/router.js +130 -49
- package/dist/schedules/router.js.map +1 -1
- package/dist/schedules/schedules-d1.d.ts +11 -5
- package/dist/schedules/schedules-d1.d.ts.map +1 -1
- package/dist/schedules/schedules-d1.js +571 -144
- package/dist/schedules/schedules-d1.js.map +1 -1
- package/dist/schedules/storage.d.ts +0 -7
- package/dist/schedules/storage.d.ts.map +1 -1
- package/dist/schedules/storage.js +0 -27
- package/dist/schedules/storage.js.map +1 -1
- package/dist/schedules/tick.d.ts +1 -8
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +15 -20
- package/dist/schedules/tick.js.map +1 -1
- package/dist/signal-providers/webhook-route.d.ts +1 -1
- package/dist/signal-providers/webhook-route.d.ts.map +1 -1
- package/dist/signal-providers/webhook-route.js +99 -109
- package/dist/signal-providers/webhook-route.js.map +1 -1
- package/dist/signals/d1-shared.d.ts +11 -8
- package/dist/signals/d1-shared.d.ts.map +1 -1
- package/dist/signals/d1-shared.js +2 -7
- package/dist/signals/d1-shared.js.map +1 -1
- package/dist/signals/index.d.ts +1 -1
- package/dist/signals/index.d.ts.map +1 -1
- package/dist/signals/index.js +1 -1
- package/dist/signals/index.js.map +1 -1
- package/dist/signals/notification-dispatch.d.ts +84 -4
- package/dist/signals/notification-dispatch.d.ts.map +1 -1
- package/dist/signals/notification-dispatch.js +365 -53
- package/dist/signals/notification-dispatch.js.map +1 -1
- package/dist/signals/notifications-d1.d.ts +6 -1
- package/dist/signals/notifications-d1.d.ts.map +1 -1
- package/dist/signals/notifications-d1.js +215 -10
- package/dist/signals/notifications-d1.js.map +1 -1
- package/dist/signals/router.d.ts +6 -4
- package/dist/signals/router.d.ts.map +1 -1
- package/dist/signals/router.js +49 -84
- package/dist/signals/router.js.map +1 -1
- package/dist/signals/thread-do-routes.d.ts +2 -0
- package/dist/signals/thread-do-routes.d.ts.map +1 -1
- package/dist/signals/thread-do-routes.js +250 -81
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +9 -7
- package/scripts/seed-deployment-identity.mjs +27 -6
|
@@ -0,0 +1,894 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/// <reference types="node" />
|
|
3
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
4
|
+
import { WorkflowsStorageD1 } from '@mastra/cloudflare-d1';
|
|
5
|
+
import { EXECUTION_FENCE_TABLE } from '#deployment-identity-protocol';
|
|
6
|
+
import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal-identity.js';
|
|
7
|
+
import { DoStatusError } from './do-status-error.js';
|
|
8
|
+
import { assertMutationEpoch, ExecutionFenceUnreadableError, InvalidExecutionIdentityError, normalizeD1RunExecutionIdentity, normalizeMutationEpoch, normalizeStartIdentity, RunAdmissionConflictError, } from './execution-admission.js';
|
|
9
|
+
import { admitsRunStart, captureExecutionFenceAdmissionSchema, decodeExecutionFenceAdmissionRow, ExecutionFencedError, executionFenceAdmissionSql, executionFenceAdmissionValues, validateExecutionFenceAdmissionSchema, } from './execution-fence.js';
|
|
10
|
+
import { FENCED_WORKFLOW_STORAGE, } from './fenced-workflow-capability.js';
|
|
11
|
+
import { definitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
|
|
12
|
+
import { isPathSafeId } from './path-safe-id.js';
|
|
13
|
+
import { hasDisputedSettlement, parseRunLifecycle, projectTerminalLifecycle, RUN_LIFECYCLE_CONTEXT_KEY, RunLifecycleBlockedError, terminalCleanupFor, } from './run-lifecycle.js';
|
|
14
|
+
import { decodeInitialRunProvenance, decodeProgressRunProvenance, } from './run-provenance.js';
|
|
15
|
+
import { RESOURCE_OWNER_TABLE } from './run-storage-tables.js';
|
|
16
|
+
import { isRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
|
|
17
|
+
import { decodeStartReservationAdmissionResult, START_IDEMPOTENCY_TABLE, StartReservationOwnerMismatchError, StartReservationTargetMismatchError, validateStartReservationAdmissionSchema, } from './start-idempotency.js';
|
|
18
|
+
import { captureReservation, sameReservationIdentity, } from './start-reservation-contract.js';
|
|
19
|
+
import { validateTablePrefix } from './table-prefix.js';
|
|
20
|
+
import { decodeRawWorkflowSnapshotResult, prepareRawWorkflowSnapshotRead, readRawWorkflowSnapshot, snapshotResultRows, } from './workflow-snapshot-row.js';
|
|
21
|
+
const PROVENANCE = 'flowsafe.runProvenance';
|
|
22
|
+
/** @internal Match the pinned standalone resolver's property-presence precedence. */
|
|
23
|
+
export function captureD1DomainConfig(config) {
|
|
24
|
+
if ('client' in config) {
|
|
25
|
+
const client = config.client;
|
|
26
|
+
const tablePrefix = validateTablePrefix(config.tablePrefix);
|
|
27
|
+
return { client, tablePrefix };
|
|
28
|
+
}
|
|
29
|
+
if ('binding' in config) {
|
|
30
|
+
const binding = config.binding;
|
|
31
|
+
const tablePrefix = validateTablePrefix(config.tablePrefix);
|
|
32
|
+
return { binding, tablePrefix };
|
|
33
|
+
}
|
|
34
|
+
const { accountId, apiToken, databaseId, tablePrefix } = config;
|
|
35
|
+
return {
|
|
36
|
+
accountId,
|
|
37
|
+
apiToken,
|
|
38
|
+
databaseId,
|
|
39
|
+
tablePrefix: validateTablePrefix(tablePrefix),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function admissionDatabase(value) {
|
|
43
|
+
return (value !== null &&
|
|
44
|
+
typeof value === 'object' &&
|
|
45
|
+
'prepare' in value &&
|
|
46
|
+
typeof value.prepare === 'function' &&
|
|
47
|
+
'batch' in value &&
|
|
48
|
+
typeof value.batch === 'function');
|
|
49
|
+
}
|
|
50
|
+
function record(value) {
|
|
51
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
52
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
function assertInitialSnapshot(value, runId) {
|
|
56
|
+
const snapshot = record(value);
|
|
57
|
+
if (snapshot.status !== 'pending' ||
|
|
58
|
+
snapshot.runId !== runId ||
|
|
59
|
+
!Array.isArray(snapshot.activePaths) ||
|
|
60
|
+
snapshot.activePaths.length !== 0)
|
|
61
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
62
|
+
for (const field of [
|
|
63
|
+
'activeStepsPath',
|
|
64
|
+
'suspendedPaths',
|
|
65
|
+
'waitingPaths',
|
|
66
|
+
'resumeLabels',
|
|
67
|
+
]) {
|
|
68
|
+
if (Object.keys(record(snapshot[field])).length !== 0)
|
|
69
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function captureInitialProvenance(value) {
|
|
73
|
+
const { version, startToken, attemptToken, requestedBy, requestedByKind, resumeCounts, mutationEpoch, startIdentity: rawIdentity, agentStart: rawAgent, initialAdmission, } = record(value);
|
|
74
|
+
if (!Array.isArray(resumeCounts) || resumeCounts.length !== 0)
|
|
75
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
76
|
+
const startIdentity = rawIdentity === undefined ? undefined : normalizeStartIdentity(rawIdentity);
|
|
77
|
+
const agentStart = rawAgent === undefined
|
|
78
|
+
? undefined
|
|
79
|
+
: { threaded: record(rawAgent).threaded };
|
|
80
|
+
// Caller accessors run before the stored-data decoder's error translation.
|
|
81
|
+
const captured = {
|
|
82
|
+
version,
|
|
83
|
+
startToken,
|
|
84
|
+
attemptToken,
|
|
85
|
+
requestedBy,
|
|
86
|
+
requestedByKind,
|
|
87
|
+
resumeCounts: [],
|
|
88
|
+
mutationEpoch,
|
|
89
|
+
startIdentity,
|
|
90
|
+
agentStart,
|
|
91
|
+
initialAdmission,
|
|
92
|
+
};
|
|
93
|
+
try {
|
|
94
|
+
return decodeInitialRunProvenance(captured, 'absent');
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function captureAdmission(source) {
|
|
101
|
+
record(source);
|
|
102
|
+
const { execution: rawExecution, attemptToken, mutationEpoch: rawEpoch, startIdentity: rawIdentity, requestContext, fence, reservationStore, reservation: rawReservation, proof: rawProof, runOwnerGuard: rawGuard, onInitialWriteAttempt, } = source;
|
|
103
|
+
record(requestContext);
|
|
104
|
+
const fenceMethods = record(fence);
|
|
105
|
+
if (!['usesDatabase', 'seed', 'readForAdmission'].every((method) => typeof fenceMethods[method] === 'function'))
|
|
106
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
107
|
+
if (reservationStore !== undefined) {
|
|
108
|
+
const methods = record(reservationStore);
|
|
109
|
+
if (!['usesDatabase', 'readForAdmission'].every((method) => typeof methods[method] === 'function'))
|
|
110
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
111
|
+
}
|
|
112
|
+
if (rawProof !== undefined)
|
|
113
|
+
record(rawProof);
|
|
114
|
+
if (rawGuard !== undefined)
|
|
115
|
+
record(rawGuard);
|
|
116
|
+
const execution = normalizeD1RunExecutionIdentity(rawExecution);
|
|
117
|
+
const mutationEpoch = normalizeMutationEpoch(rawEpoch);
|
|
118
|
+
const startIdentity = rawIdentity === undefined ? undefined : normalizeStartIdentity(rawIdentity);
|
|
119
|
+
if (!isPathSafeId(attemptToken) ||
|
|
120
|
+
typeof onInitialWriteAttempt !== 'function' ||
|
|
121
|
+
(reservationStore === undefined) !== (rawReservation === undefined))
|
|
122
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
123
|
+
const reservation = rawReservation === undefined
|
|
124
|
+
? undefined
|
|
125
|
+
: captureReservation(rawReservation, 'started');
|
|
126
|
+
if (reservation) {
|
|
127
|
+
if (!startIdentity)
|
|
128
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
129
|
+
if (reservation.owner.kind !== startIdentity.owner.kind ||
|
|
130
|
+
reservation.owner.id !== startIdentity.owner.id)
|
|
131
|
+
throw new StartReservationOwnerMismatchError(reservation.key);
|
|
132
|
+
if (reservation.targetKind !== startIdentity.target.kind ||
|
|
133
|
+
reservation.targetId !== startIdentity.target.id)
|
|
134
|
+
throw new StartReservationTargetMismatchError(reservation.key, reservation);
|
|
135
|
+
if (reservation.runId !== execution.runId ||
|
|
136
|
+
reservation.threadId !==
|
|
137
|
+
(startIdentity.target.kind === 'agent'
|
|
138
|
+
? startIdentity.target.threadId
|
|
139
|
+
: undefined))
|
|
140
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
141
|
+
}
|
|
142
|
+
if (startIdentity?.target.kind === 'workflow' &&
|
|
143
|
+
startIdentity.target.id !== execution.workflowId)
|
|
144
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
145
|
+
let proof;
|
|
146
|
+
if (rawProof !== undefined) {
|
|
147
|
+
const { key, mutationEpoch: suppliedEpoch, transitionRevision: suppliedRevision, } = rawProof;
|
|
148
|
+
const proofEpoch = normalizeMutationEpoch(suppliedEpoch);
|
|
149
|
+
const transitionRevision = normalizeMutationEpoch(suppliedRevision);
|
|
150
|
+
if (!isPathSafeId(key) ||
|
|
151
|
+
proofEpoch === undefined ||
|
|
152
|
+
transitionRevision === undefined ||
|
|
153
|
+
(reservation && key !== reservation.key))
|
|
154
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
155
|
+
proof = Object.freeze({
|
|
156
|
+
key,
|
|
157
|
+
mutationEpoch: proofEpoch,
|
|
158
|
+
transitionRevision,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
const runOwnerGuard = rawGuard === undefined
|
|
162
|
+
? undefined
|
|
163
|
+
: Object.freeze({
|
|
164
|
+
owner: normalizeStartIdentity({
|
|
165
|
+
owner: rawGuard.owner,
|
|
166
|
+
target: { kind: 'workflow', id: execution.workflowId },
|
|
167
|
+
}).owner,
|
|
168
|
+
reservationToken: rawGuard.reservationToken,
|
|
169
|
+
});
|
|
170
|
+
if (runOwnerGuard && runOwnerGuard.reservationToken !== attemptToken)
|
|
171
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
172
|
+
const { [PROVENANCE]: rawProvenance, ...application } = requestContext;
|
|
173
|
+
const provenance = captureInitialProvenance(rawProvenance);
|
|
174
|
+
if (provenance.startToken !== execution.startToken ||
|
|
175
|
+
provenance.attemptToken !== attemptToken ||
|
|
176
|
+
provenance.mutationEpoch !== mutationEpoch ||
|
|
177
|
+
JSON.stringify(provenance.startIdentity) !== JSON.stringify(startIdentity))
|
|
178
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
179
|
+
const contextRunId = application.runId;
|
|
180
|
+
const contextWorkflow = application['breakwater.workflowScope'];
|
|
181
|
+
if ((contextRunId !== undefined && contextRunId !== execution.runId) ||
|
|
182
|
+
(contextWorkflow !== undefined && contextWorkflow !== execution.workflowId))
|
|
183
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
184
|
+
const context = record(JSON.parse(JSON.stringify(application)));
|
|
185
|
+
if (context.runId !== contextRunId ||
|
|
186
|
+
context['breakwater.workflowScope'] !== contextWorkflow)
|
|
187
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
188
|
+
return Object.freeze({
|
|
189
|
+
execution,
|
|
190
|
+
attemptToken,
|
|
191
|
+
mutationEpoch,
|
|
192
|
+
startIdentity,
|
|
193
|
+
requestContext: Object.freeze({ ...context, [PROVENANCE]: provenance }),
|
|
194
|
+
fence,
|
|
195
|
+
reservationStore,
|
|
196
|
+
reservation,
|
|
197
|
+
proof,
|
|
198
|
+
runOwnerGuard,
|
|
199
|
+
onInitialWriteAttempt,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
function sameReservation(actual, expected, execution) {
|
|
203
|
+
return (actual !== undefined &&
|
|
204
|
+
sameReservationIdentity(actual, expected) &&
|
|
205
|
+
actual.state === expected.state &&
|
|
206
|
+
actual.updatedAt === expected.updatedAt &&
|
|
207
|
+
(execution === undefined
|
|
208
|
+
? actual.binding.kind === expected.binding.kind
|
|
209
|
+
: actual.binding.kind === 'bound' &&
|
|
210
|
+
sameFields({ ...actual.binding.execution }, { ...execution })));
|
|
211
|
+
}
|
|
212
|
+
function sameFields(actual, expected) {
|
|
213
|
+
return Object.keys(expected).every((key) => Object.hasOwn(actual, key) && actual[key] === expected[key]);
|
|
214
|
+
}
|
|
215
|
+
function reservationPredicate(reservation, bind, qualifier = '', runReference) {
|
|
216
|
+
return `${qualifier}key = ${bind(reservation.key)} AND ${qualifier}run_id = ${runReference ?? bind(reservation.runId)}
|
|
217
|
+
AND ${qualifier}owner_kind = ${bind(reservation.owner.kind)} AND ${qualifier}owner_id = ${bind(reservation.owner.id)}
|
|
218
|
+
AND ${qualifier}target_kind = ${bind(reservation.targetKind)} AND ${qualifier}target_id = ${bind(reservation.targetId)} AND ${qualifier}thread_id IS ${bind(reservation.threadId ?? null)}
|
|
219
|
+
AND ${qualifier}created_at = ${bind(reservation.createdAt)} AND ${qualifier}updated_at = ${bind(reservation.updatedAt)} AND ${qualifier}state = 'started'
|
|
220
|
+
AND ${qualifier}start_token = '' AND ${qualifier}start_table_prefix IS NULL AND ${qualifier}start_workflow_id IS NULL`;
|
|
221
|
+
}
|
|
222
|
+
function captureBatchResults(value, length) {
|
|
223
|
+
if (!Array.isArray(value) || value.length !== length)
|
|
224
|
+
throw new Error('initial batch cardinality is invalid');
|
|
225
|
+
return Array.from({ length }, (_, index) => {
|
|
226
|
+
if (!Object.hasOwn(value, index))
|
|
227
|
+
throw new Error('initial batch is missing a result');
|
|
228
|
+
return captureStatementResult(value[index]);
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
function captureStatementResult(result) {
|
|
232
|
+
const results = snapshotResultRows(result).map((row) => Object.freeze(Object.fromEntries(Object.getOwnPropertyNames(row).map((key) => [key, row[key]]))));
|
|
233
|
+
const meta = record(result).meta;
|
|
234
|
+
const hasChanges = meta !== undefined && 'changes' in record(meta);
|
|
235
|
+
return {
|
|
236
|
+
results,
|
|
237
|
+
...(hasChanges ? { meta: { changes: record(meta).changes } } : {}),
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
function terminalizationUnreadable(cause) {
|
|
241
|
+
return new ExecutionFenceUnreadableError('initial admission cannot be terminalized', { cause });
|
|
242
|
+
}
|
|
243
|
+
function terminalizationSnapshot(row) {
|
|
244
|
+
const snapshot = record(JSON.parse(row.snapshot));
|
|
245
|
+
if (!isRunStatus(snapshot.status) ||
|
|
246
|
+
typeof snapshot.runId !== 'string' ||
|
|
247
|
+
snapshot.runId !== row.runId)
|
|
248
|
+
throw new Error('stored workflow snapshot is malformed');
|
|
249
|
+
const context = snapshot.requestContext === undefined
|
|
250
|
+
? {}
|
|
251
|
+
: record(snapshot.requestContext);
|
|
252
|
+
const rawProvenance = context[PROVENANCE];
|
|
253
|
+
if (rawProvenance === undefined || record(rawProvenance).version === 1)
|
|
254
|
+
return { snapshot, context, provenance: undefined, lifecycle: undefined };
|
|
255
|
+
const provenance = decodeProgressRunProvenance(rawProvenance);
|
|
256
|
+
const lifecycle = parseRunLifecycle(context[RUN_LIFECYCLE_CONTEXT_KEY]);
|
|
257
|
+
return { snapshot, context, provenance, lifecycle };
|
|
258
|
+
}
|
|
259
|
+
function sameStart(actual, expected) {
|
|
260
|
+
return (actual.startToken === expected.startToken &&
|
|
261
|
+
actual.mutationEpoch === expected.mutationEpoch &&
|
|
262
|
+
actual.agentStart?.threaded === expected.agentStart?.threaded &&
|
|
263
|
+
actual.startIdentity?.owner.kind === expected.startIdentity?.owner.kind &&
|
|
264
|
+
actual.startIdentity?.owner.id === expected.startIdentity?.owner.id &&
|
|
265
|
+
actual.startIdentity?.target.kind === expected.startIdentity?.target.kind &&
|
|
266
|
+
actual.startIdentity?.target.id === expected.startIdentity?.target.id &&
|
|
267
|
+
(actual.startIdentity?.target.kind === 'agent'
|
|
268
|
+
? actual.startIdentity.target.threadId
|
|
269
|
+
: undefined) ===
|
|
270
|
+
(expected.startIdentity?.target.kind === 'agent'
|
|
271
|
+
? expected.startIdentity.target.threadId
|
|
272
|
+
: undefined));
|
|
273
|
+
}
|
|
274
|
+
function prepareTerminalization(source, tablePrefix) {
|
|
275
|
+
const { expected: rawExpected, execution: rawExecution, attemptToken, nowMs, } = record(source);
|
|
276
|
+
const execution = normalizeD1RunExecutionIdentity(rawExecution);
|
|
277
|
+
const { tablePrefix: expectedPrefix, workflowId, runId, resourceId, snapshot, createdAt, updatedAt, } = record(rawExpected);
|
|
278
|
+
if (expectedPrefix !== tablePrefix ||
|
|
279
|
+
execution.tablePrefix !== tablePrefix ||
|
|
280
|
+
workflowId !== execution.workflowId ||
|
|
281
|
+
runId !== execution.runId ||
|
|
282
|
+
(resourceId !== null && typeof resourceId !== 'string') ||
|
|
283
|
+
typeof snapshot !== 'string' ||
|
|
284
|
+
typeof createdAt !== 'string' ||
|
|
285
|
+
typeof updatedAt !== 'string' ||
|
|
286
|
+
!isPathSafeId(attemptToken) ||
|
|
287
|
+
typeof nowMs !== 'number' ||
|
|
288
|
+
!Number.isSafeInteger(nowMs) ||
|
|
289
|
+
nowMs < 0)
|
|
290
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
291
|
+
let nowIso;
|
|
292
|
+
try {
|
|
293
|
+
nowIso = new Date(nowMs).toISOString();
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
297
|
+
}
|
|
298
|
+
const expected = Object.freeze({
|
|
299
|
+
tablePrefix,
|
|
300
|
+
workflowId,
|
|
301
|
+
runId,
|
|
302
|
+
resourceId,
|
|
303
|
+
snapshot,
|
|
304
|
+
createdAt,
|
|
305
|
+
updatedAt,
|
|
306
|
+
});
|
|
307
|
+
let parsed;
|
|
308
|
+
try {
|
|
309
|
+
parsed = terminalizationSnapshot(expected);
|
|
310
|
+
}
|
|
311
|
+
catch (error) {
|
|
312
|
+
throw terminalizationUnreadable(error);
|
|
313
|
+
}
|
|
314
|
+
const { provenance, lifecycle, context } = parsed;
|
|
315
|
+
if (!provenance ||
|
|
316
|
+
provenance.startToken !== execution.startToken ||
|
|
317
|
+
provenance.attemptToken !== attemptToken ||
|
|
318
|
+
provenance.initialAdmission !== true ||
|
|
319
|
+
provenance.resumeCounts.length !== 0 ||
|
|
320
|
+
lifecycle?.terminal ||
|
|
321
|
+
provenance.requestedBy !== provenance.startIdentity?.owner.id ||
|
|
322
|
+
provenance.requestedByKind !== provenance.startIdentity?.owner.kind ||
|
|
323
|
+
(context.runId !== undefined && context.runId !== runId) ||
|
|
324
|
+
(context['breakwater.workflowScope'] !== undefined &&
|
|
325
|
+
context['breakwater.workflowScope'] !== workflowId) ||
|
|
326
|
+
(provenance.startIdentity?.target.kind === 'workflow' &&
|
|
327
|
+
provenance.startIdentity.target.id !== workflowId))
|
|
328
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
329
|
+
assertInitialSnapshot(parsed.snapshot, runId);
|
|
330
|
+
try {
|
|
331
|
+
decodeInitialRunProvenance(context[PROVENANCE], 'present');
|
|
332
|
+
}
|
|
333
|
+
catch (error) {
|
|
334
|
+
throw terminalizationUnreadable(error);
|
|
335
|
+
}
|
|
336
|
+
const nextProvenance = { ...record(context[PROVENANCE]) };
|
|
337
|
+
delete nextProvenance.initialAdmission;
|
|
338
|
+
const nextContext = {
|
|
339
|
+
...context,
|
|
340
|
+
[PROVENANCE]: nextProvenance,
|
|
341
|
+
};
|
|
342
|
+
let fields = terminalStateUpdate({
|
|
343
|
+
status: 'failed',
|
|
344
|
+
error: {
|
|
345
|
+
name: 'StartOutcomeUnknown',
|
|
346
|
+
message: 'Start interrupted before a durable execution outcome was recorded; external effects may have occurred. This run will not be automatically re-executed.',
|
|
347
|
+
},
|
|
348
|
+
});
|
|
349
|
+
let cleanup;
|
|
350
|
+
const intent = lifecycle?.transitionIntent;
|
|
351
|
+
if (intent) {
|
|
352
|
+
if (hasDisputedSettlement(lifecycle))
|
|
353
|
+
throw new RunLifecycleBlockedError({
|
|
354
|
+
code: 'DISPUTED_SETTLEMENT',
|
|
355
|
+
message: 'run termination is blocked while an economic operation is disputed',
|
|
356
|
+
});
|
|
357
|
+
try {
|
|
358
|
+
const next = projectTerminalLifecycle(lifecycle, intent.status, nowMs, intent.replayPrincipals);
|
|
359
|
+
nextContext[RUN_LIFECYCLE_CONTEXT_KEY] = next;
|
|
360
|
+
fields = {
|
|
361
|
+
...terminalStateFields(intent.status),
|
|
362
|
+
error: {
|
|
363
|
+
name: intent.status === 'cancelled'
|
|
364
|
+
? 'RunCancelledError'
|
|
365
|
+
: 'RunTimedOutError',
|
|
366
|
+
message: next.terminal.error.message,
|
|
367
|
+
},
|
|
368
|
+
};
|
|
369
|
+
cleanup = terminalCleanupFor(next);
|
|
370
|
+
}
|
|
371
|
+
catch (error) {
|
|
372
|
+
throw terminalizationUnreadable(error);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
const replacement = Object.freeze({
|
|
376
|
+
...expected,
|
|
377
|
+
updatedAt: nowIso,
|
|
378
|
+
snapshot: JSON.stringify({
|
|
379
|
+
...parsed.snapshot,
|
|
380
|
+
...fields,
|
|
381
|
+
requestContext: nextContext,
|
|
382
|
+
timestamp: nowMs,
|
|
383
|
+
}),
|
|
384
|
+
});
|
|
385
|
+
return { expected, replacement, provenance, cleanup };
|
|
386
|
+
}
|
|
387
|
+
/** Owned initial admission and repair; unscoped persistence delegates to the adapter. */
|
|
388
|
+
export class FencedWorkflowsStorageD1 extends WorkflowsStorageD1 {
|
|
389
|
+
[FENCED_WORKFLOW_STORAGE];
|
|
390
|
+
#admission;
|
|
391
|
+
#scopes = new AsyncLocalStorage();
|
|
392
|
+
constructor(config) {
|
|
393
|
+
const captured = captureD1DomainConfig(config);
|
|
394
|
+
super(captured);
|
|
395
|
+
if ('binding' in captured && admissionDatabase(captured.binding)) {
|
|
396
|
+
const database = captured.binding;
|
|
397
|
+
const tablePrefix = (captured.tablePrefix ?? '').toLowerCase();
|
|
398
|
+
this.#admission = Object.freeze({
|
|
399
|
+
database,
|
|
400
|
+
tablePrefix,
|
|
401
|
+
withInitialAdmission: (input, createRun) => this.#withInitialAdmission(input, createRun),
|
|
402
|
+
readSnapshot: (address) => readRawWorkflowSnapshot(database, {
|
|
403
|
+
tablePrefix,
|
|
404
|
+
workflowId: address.workflowId,
|
|
405
|
+
runId: address.runId,
|
|
406
|
+
}, { missingTable: 'empty' }),
|
|
407
|
+
terminalizeInitialAdmission: (request) => this.#terminalizeInitialAdmission(request),
|
|
408
|
+
});
|
|
409
|
+
this[FENCED_WORKFLOW_STORAGE] = this.#admission;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
withInitialTerminalizationLock(_workflowName, _runId, operation) {
|
|
413
|
+
return operation();
|
|
414
|
+
}
|
|
415
|
+
async #terminalizeInitialAdmission(source) {
|
|
416
|
+
const capability = this.#admission;
|
|
417
|
+
if (!capability)
|
|
418
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
419
|
+
const frame = prepareTerminalization(source, capability.tablePrefix);
|
|
420
|
+
const { expected, replacement, cleanup, provenance } = frame;
|
|
421
|
+
const { database } = capability;
|
|
422
|
+
return this.withInitialTerminalizationLock(expected.workflowId, expected.runId, async () => {
|
|
423
|
+
const readback = async () => {
|
|
424
|
+
const row = await readRawWorkflowSnapshot(database, expected, {
|
|
425
|
+
missingTable: 'error',
|
|
426
|
+
});
|
|
427
|
+
if (!row)
|
|
428
|
+
return { kind: 'conflict' };
|
|
429
|
+
if (sameFields({ ...row }, { ...replacement }))
|
|
430
|
+
return {
|
|
431
|
+
kind: 'already-terminalized',
|
|
432
|
+
row,
|
|
433
|
+
...(cleanup ? { cleanup } : {}),
|
|
434
|
+
};
|
|
435
|
+
const current = terminalizationSnapshot(row);
|
|
436
|
+
if (current.provenance &&
|
|
437
|
+
sameStart(current.provenance, provenance) &&
|
|
438
|
+
current.snapshot.status !== 'pending') {
|
|
439
|
+
const currentCleanup = terminalCleanupFor(current.lifecycle);
|
|
440
|
+
return {
|
|
441
|
+
kind: 'progressed',
|
|
442
|
+
row,
|
|
443
|
+
...(currentCleanup ? { cleanup: currentCleanup } : {}),
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
return { kind: 'conflict', row };
|
|
447
|
+
};
|
|
448
|
+
let result;
|
|
449
|
+
try {
|
|
450
|
+
result = await database
|
|
451
|
+
.prepare(`UPDATE "${expected.tablePrefix}mastra_workflow_snapshot"
|
|
452
|
+
SET snapshot = ?1, updatedAt = ?2
|
|
453
|
+
WHERE workflow_name = ?3 AND run_id = ?4
|
|
454
|
+
AND snapshot = ?5 AND createdAt IS ?6 AND updatedAt IS ?7
|
|
455
|
+
AND resourceId IS ?8
|
|
456
|
+
RETURNING workflow_name, run_id, resourceId, snapshot, createdAt, updatedAt`)
|
|
457
|
+
.bind(replacement.snapshot, replacement.updatedAt, expected.workflowId, expected.runId, expected.snapshot, expected.createdAt, expected.updatedAt, expected.resourceId)
|
|
458
|
+
.all();
|
|
459
|
+
}
|
|
460
|
+
catch (error) {
|
|
461
|
+
try {
|
|
462
|
+
const recovered = await readback();
|
|
463
|
+
if (recovered.kind !== 'conflict')
|
|
464
|
+
return recovered;
|
|
465
|
+
}
|
|
466
|
+
catch {
|
|
467
|
+
/* The write's original uncertainty remains authoritative. */
|
|
468
|
+
}
|
|
469
|
+
throw terminalizationUnreadable(error);
|
|
470
|
+
}
|
|
471
|
+
try {
|
|
472
|
+
const captured = captureStatementResult(result);
|
|
473
|
+
const row = decodeRawWorkflowSnapshotResult(captured, expected);
|
|
474
|
+
const changes = captured.meta?.changes;
|
|
475
|
+
if (captured.meta &&
|
|
476
|
+
(!Number.isSafeInteger(changes) ||
|
|
477
|
+
changes !== captured.results.length))
|
|
478
|
+
throw new Error('terminalization changes disagree with returned rows');
|
|
479
|
+
if (!row)
|
|
480
|
+
return await readback();
|
|
481
|
+
if (!sameFields({ ...row }, { ...replacement }))
|
|
482
|
+
throw new Error('terminalization returned a different row');
|
|
483
|
+
return { kind: 'terminalized', row, ...(cleanup ? { cleanup } : {}) };
|
|
484
|
+
}
|
|
485
|
+
catch (error) {
|
|
486
|
+
throw terminalizationUnreadable(error);
|
|
487
|
+
}
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
async #withInitialAdmission(source, createRun) {
|
|
491
|
+
const parent = this.#scopes.getStore();
|
|
492
|
+
if (parent) {
|
|
493
|
+
parent.failed = true;
|
|
494
|
+
parent.failure = new InvalidExecutionIdentityError('admission');
|
|
495
|
+
throw parent.failure;
|
|
496
|
+
}
|
|
497
|
+
const input = captureAdmission(source);
|
|
498
|
+
const capability = this.#admission;
|
|
499
|
+
if (!capability ||
|
|
500
|
+
typeof createRun !== 'function' ||
|
|
501
|
+
input.execution.tablePrefix !== capability.tablePrefix ||
|
|
502
|
+
!input.fence.usesDatabase(capability.database) ||
|
|
503
|
+
(input.reservationStore &&
|
|
504
|
+
!input.reservationStore.usesDatabase(capability.database)))
|
|
505
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
506
|
+
const scope = {
|
|
507
|
+
input,
|
|
508
|
+
open: true,
|
|
509
|
+
attempted: false,
|
|
510
|
+
failed: false,
|
|
511
|
+
};
|
|
512
|
+
try {
|
|
513
|
+
return await this.#scopes.run(scope, async () => {
|
|
514
|
+
const value = await Reflect.apply(createRun, undefined, []);
|
|
515
|
+
if (scope.failed)
|
|
516
|
+
throw scope.failure;
|
|
517
|
+
if (!scope.witness) {
|
|
518
|
+
throw new ExecutionFenceUnreadableError('initial run admission has no persistence witness');
|
|
519
|
+
}
|
|
520
|
+
return { value, witness: scope.witness };
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
finally {
|
|
524
|
+
scope.open = false;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
async persistWorkflowSnapshot(args) {
|
|
528
|
+
const scope = this.#scopes.getStore();
|
|
529
|
+
if (!scope)
|
|
530
|
+
return super.persistWorkflowSnapshot(args);
|
|
531
|
+
if (!scope.open ||
|
|
532
|
+
scope.attempted ||
|
|
533
|
+
args.workflowName !== scope.input.execution.workflowId ||
|
|
534
|
+
args.runId !== scope.input.execution.runId) {
|
|
535
|
+
scope.failed = true;
|
|
536
|
+
scope.failure = new InvalidExecutionIdentityError('admission');
|
|
537
|
+
throw scope.failure;
|
|
538
|
+
}
|
|
539
|
+
scope.attempted = true;
|
|
540
|
+
try {
|
|
541
|
+
Reflect.apply(scope.input.onInitialWriteAttempt, undefined, []);
|
|
542
|
+
const { row, nowMs } = this.#initialRow(args, scope.input);
|
|
543
|
+
scope.witness = await this.#insert(scope.input, row, nowMs);
|
|
544
|
+
}
|
|
545
|
+
catch (error) {
|
|
546
|
+
scope.failed = true;
|
|
547
|
+
scope.failure = error;
|
|
548
|
+
throw error;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
#initialRow(args, input) {
|
|
552
|
+
const { snapshot: original, resourceId, createdAt, updatedAt } = args;
|
|
553
|
+
const snapshot = { ...original };
|
|
554
|
+
assertInitialSnapshot(snapshot, input.execution.runId);
|
|
555
|
+
const provenance = decodeInitialRunProvenance({ ...record(input.requestContext[PROVENANCE]), initialAdmission: true }, 'present');
|
|
556
|
+
snapshot.requestContext = {
|
|
557
|
+
...input.requestContext,
|
|
558
|
+
[PROVENANCE]: provenance,
|
|
559
|
+
};
|
|
560
|
+
const nowMs = Date.now();
|
|
561
|
+
if (!Number.isSafeInteger(nowMs) || nowMs < 0)
|
|
562
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
563
|
+
const nowIso = new Date(nowMs).toISOString();
|
|
564
|
+
const resource = resourceId;
|
|
565
|
+
const serializedResource = resource == null
|
|
566
|
+
? null
|
|
567
|
+
: resource instanceof Date
|
|
568
|
+
? resource.toISOString()
|
|
569
|
+
: typeof resource === 'object'
|
|
570
|
+
? JSON.stringify(resource)
|
|
571
|
+
: resource;
|
|
572
|
+
if (serializedResource !== null && typeof serializedResource !== 'string')
|
|
573
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
574
|
+
const contextBytes = JSON.stringify(snapshot.requestContext);
|
|
575
|
+
const bytes = JSON.stringify(snapshot);
|
|
576
|
+
const serialized = record(JSON.parse(bytes));
|
|
577
|
+
assertInitialSnapshot(serialized, input.execution.runId);
|
|
578
|
+
if (JSON.stringify(serialized.requestContext) !== contextBytes)
|
|
579
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
580
|
+
const serializedContext = record(serialized.requestContext);
|
|
581
|
+
decodeInitialRunProvenance(serializedContext[PROVENANCE], 'present');
|
|
582
|
+
if ((serializedContext.runId !== undefined &&
|
|
583
|
+
serializedContext.runId !== input.execution.runId) ||
|
|
584
|
+
(serializedContext['breakwater.workflowScope'] !== undefined &&
|
|
585
|
+
serializedContext['breakwater.workflowScope'] !==
|
|
586
|
+
input.execution.workflowId))
|
|
587
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
588
|
+
const created = createdAt ? createdAt.toISOString() : nowIso;
|
|
589
|
+
const updated = updatedAt ? updatedAt.toISOString() : nowIso;
|
|
590
|
+
if (typeof created !== 'string' || typeof updated !== 'string')
|
|
591
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
592
|
+
const row = Object.freeze({
|
|
593
|
+
tablePrefix: input.execution.tablePrefix,
|
|
594
|
+
workflowId: input.execution.workflowId,
|
|
595
|
+
runId: input.execution.runId,
|
|
596
|
+
resourceId: serializedResource,
|
|
597
|
+
snapshot: bytes,
|
|
598
|
+
createdAt: created,
|
|
599
|
+
updatedAt: updated,
|
|
600
|
+
});
|
|
601
|
+
return { row, nowMs };
|
|
602
|
+
}
|
|
603
|
+
async #insert(input, row, nowMs) {
|
|
604
|
+
const capability = this.#admission;
|
|
605
|
+
if (!capability)
|
|
606
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
607
|
+
const { database } = capability;
|
|
608
|
+
await input.fence.seed('open');
|
|
609
|
+
const observed = await input.fence.readForAdmission();
|
|
610
|
+
const semanticValues = executionFenceAdmissionValues(observed);
|
|
611
|
+
let schema;
|
|
612
|
+
try {
|
|
613
|
+
schema = await captureExecutionFenceAdmissionSchema(await database
|
|
614
|
+
.prepare(`PRAGMA table_xinfo(${EXECUTION_FENCE_TABLE})`)
|
|
615
|
+
.all());
|
|
616
|
+
}
|
|
617
|
+
catch (cause) {
|
|
618
|
+
throw new ExecutionFenceUnreadableError('initial admission requires current fence schema', { cause });
|
|
619
|
+
}
|
|
620
|
+
if (input.reservation &&
|
|
621
|
+
!sameReservation(await input.reservationStore?.readForAdmission(input.reservation.key), input.reservation))
|
|
622
|
+
throw new RunAdmissionConflictError('reservation-changed');
|
|
623
|
+
const values = [];
|
|
624
|
+
const bind = (value) => {
|
|
625
|
+
values.push(value);
|
|
626
|
+
return `?${values.length}`;
|
|
627
|
+
};
|
|
628
|
+
const fields = [
|
|
629
|
+
row.workflowId,
|
|
630
|
+
row.runId,
|
|
631
|
+
row.resourceId,
|
|
632
|
+
row.snapshot,
|
|
633
|
+
row.createdAt,
|
|
634
|
+
row.updatedAt,
|
|
635
|
+
].map(bind);
|
|
636
|
+
const epoch = bind(input.mutationEpoch ?? null);
|
|
637
|
+
const semantic = semanticValues.map(bind);
|
|
638
|
+
const schemaParameter = bind(schema);
|
|
639
|
+
const proofRevision = bind(input.proof?.transitionRevision ?? null);
|
|
640
|
+
const proofKey = bind(input.proof?.key ?? null);
|
|
641
|
+
const reservation = input.reservation
|
|
642
|
+
? `AND EXISTS (SELECT 1 FROM ${START_IDEMPOTENCY_TABLE} AS r WHERE ${reservationPredicate(input.reservation, bind, 'r.', fields[1])})`
|
|
643
|
+
: '';
|
|
644
|
+
const proofEpoch = bind(input.proof?.mutationEpoch ?? null);
|
|
645
|
+
const owner = input.runOwnerGuard
|
|
646
|
+
? `AND EXISTS (SELECT 1 FROM ${RESOURCE_OWNER_TABLE} AS o WHERE o.resource_kind = 'run' AND o.resource_id = ${fields[1]}
|
|
647
|
+
AND o.owner_kind = ${bind(input.runOwnerGuard.owner.kind)} AND o.owner_id = ${bind(input.runOwnerGuard.owner.id)}
|
|
648
|
+
AND (o.reservation_token IS NULL OR o.reservation_token = ${bind(input.runOwnerGuard.reservationToken)}))`
|
|
649
|
+
: '';
|
|
650
|
+
const fencePredicate = executionFenceAdmissionSql({
|
|
651
|
+
callerEpoch: epoch,
|
|
652
|
+
semantic,
|
|
653
|
+
schema: schemaParameter,
|
|
654
|
+
statePredicate: `f.state COLLATE BINARY = 'open' OR
|
|
655
|
+
(f.state COLLATE BINARY = 'proof-only' AND f.proof_key COLLATE BINARY = ${proofKey}
|
|
656
|
+
AND f.transition_revision = ${proofRevision} AND f.mutation_epoch = ${proofEpoch}
|
|
657
|
+
AND f.proof_run_id IS NULL AND f.proof_table_prefix IS NULL
|
|
658
|
+
AND f.proof_workflow_id IS NULL AND f.proof_start_token IS NULL)`,
|
|
659
|
+
});
|
|
660
|
+
const statements = [
|
|
661
|
+
database
|
|
662
|
+
.prepare(`INSERT INTO "${row.tablePrefix}mastra_workflow_snapshot"
|
|
663
|
+
(workflow_name, run_id, resourceId, snapshot, createdAt, updatedAt)
|
|
664
|
+
SELECT ${fields.join(', ')}
|
|
665
|
+
WHERE ${fencePredicate} ${reservation} ${owner}
|
|
666
|
+
ON CONFLICT (workflow_name, run_id) DO NOTHING
|
|
667
|
+
RETURNING workflow_name, run_id, resourceId, snapshot, createdAt, updatedAt`)
|
|
668
|
+
.bind(...values),
|
|
669
|
+
];
|
|
670
|
+
if (input.reservation) {
|
|
671
|
+
const keyValues = [
|
|
672
|
+
input.execution.startToken,
|
|
673
|
+
row.tablePrefix,
|
|
674
|
+
row.workflowId,
|
|
675
|
+
];
|
|
676
|
+
const predicate = reservationPredicate(input.reservation, (value) => {
|
|
677
|
+
keyValues.push(value);
|
|
678
|
+
return `?${keyValues.length}`;
|
|
679
|
+
});
|
|
680
|
+
statements.push(database
|
|
681
|
+
.prepare(`UPDATE ${START_IDEMPOTENCY_TABLE}
|
|
682
|
+
SET start_token = ?1, start_table_prefix = ?2, start_workflow_id = ?3
|
|
683
|
+
WHERE changes() = 1 AND ${predicate} RETURNING *`)
|
|
684
|
+
.bind(...keyValues));
|
|
685
|
+
}
|
|
686
|
+
statements.push(database
|
|
687
|
+
.prepare(`UPDATE ${EXECUTION_FENCE_TABLE}
|
|
688
|
+
SET proof_run_id = ?1, proof_table_prefix = ?2, proof_workflow_id = ?3, proof_start_token = ?4, updated_at = ?5
|
|
689
|
+
WHERE changes() = 1 AND id = 'deployment' AND state = 'proof-only' AND proof_key = ?6
|
|
690
|
+
AND mutation_epoch = ?7 AND transition_revision = ?8
|
|
691
|
+
AND proof_run_id IS NULL AND proof_table_prefix IS NULL AND proof_workflow_id IS NULL AND proof_start_token IS NULL RETURNING *`)
|
|
692
|
+
.bind(row.runId, row.tablePrefix, row.workflowId, input.execution.startToken, nowMs, input.proof?.key ?? null, input.proof?.mutationEpoch ?? null, input.proof?.transitionRevision ?? null));
|
|
693
|
+
let result;
|
|
694
|
+
try {
|
|
695
|
+
result = await database.batch(statements);
|
|
696
|
+
}
|
|
697
|
+
catch (error) {
|
|
698
|
+
try {
|
|
699
|
+
if (await this.#converged(database, input, row, observed, nowMs))
|
|
700
|
+
return Object.freeze({ execution: input.execution, row });
|
|
701
|
+
}
|
|
702
|
+
catch {
|
|
703
|
+
/* The write failure remains the cause of an uncertain outcome. */
|
|
704
|
+
}
|
|
705
|
+
throw new ExecutionFenceUnreadableError('initial run admission outcome is not readable', { cause: error });
|
|
706
|
+
}
|
|
707
|
+
const positive = this.#decodeBatch(result, input, row, observed, nowMs);
|
|
708
|
+
if (positive)
|
|
709
|
+
return Object.freeze({ execution: input.execution, row });
|
|
710
|
+
const refusal = await this.#diagnoseZero(database, input, observed);
|
|
711
|
+
throw definitiveInitialAdmissionRefusal(input.execution, refusal);
|
|
712
|
+
}
|
|
713
|
+
#decodeBatch(result, input, row, observed, nowMs) {
|
|
714
|
+
try {
|
|
715
|
+
const captured = captureBatchResults(result, input.reservation ? 3 : 2);
|
|
716
|
+
const counts = captured.map(({ results, meta }) => {
|
|
717
|
+
if (results.length > 1 ||
|
|
718
|
+
(meta &&
|
|
719
|
+
(!Number.isSafeInteger(meta.changes) ||
|
|
720
|
+
meta.changes !== results.length)))
|
|
721
|
+
throw new Error('initial statement changes contradict returned rows');
|
|
722
|
+
return results.length;
|
|
723
|
+
});
|
|
724
|
+
if (counts[0] === 0) {
|
|
725
|
+
if (counts.some((count) => count !== 0))
|
|
726
|
+
throw new Error('zero INSERT changed a participant');
|
|
727
|
+
return false;
|
|
728
|
+
}
|
|
729
|
+
const actual = decodeRawWorkflowSnapshotResult(captured[0], input.execution);
|
|
730
|
+
if (!actual || !sameFields({ ...actual }, { ...row }))
|
|
731
|
+
throw new Error('initial INSERT returned different bytes');
|
|
732
|
+
if (input.reservation &&
|
|
733
|
+
!sameReservation(decodeStartReservationAdmissionResult(captured[1]), input.reservation, input.execution))
|
|
734
|
+
throw new Error('initial binding is inconsistent');
|
|
735
|
+
const proofRows = snapshotResultRows(captured[captured.length - 1]);
|
|
736
|
+
const proofRow = proofRows[0];
|
|
737
|
+
if (observed.reading.state === 'proof-only') {
|
|
738
|
+
if (proofRows.length !== 1 ||
|
|
739
|
+
proofRow === undefined ||
|
|
740
|
+
!sameFields({ ...decodeExecutionFenceAdmissionRow(proofRow).raw }, {
|
|
741
|
+
...observed.raw,
|
|
742
|
+
proof_run_id: row.runId,
|
|
743
|
+
proof_table_prefix: row.tablePrefix,
|
|
744
|
+
proof_workflow_id: row.workflowId,
|
|
745
|
+
proof_start_token: input.execution.startToken,
|
|
746
|
+
updated_at: nowMs,
|
|
747
|
+
}))
|
|
748
|
+
throw new Error('initial proof binding is inconsistent');
|
|
749
|
+
}
|
|
750
|
+
else if (proofRows.length !== 0)
|
|
751
|
+
throw new Error('open admission changed proof');
|
|
752
|
+
return true;
|
|
753
|
+
}
|
|
754
|
+
catch (error) {
|
|
755
|
+
throw new ExecutionFenceUnreadableError('initial run admission batch result is not readable', { cause: error });
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
async #converged(database, input, row, observed, nowMs) {
|
|
759
|
+
const raw = prepareRawWorkflowSnapshotRead(database, input.execution);
|
|
760
|
+
const statements = [raw.statement];
|
|
761
|
+
if (input.reservation)
|
|
762
|
+
statements.push(database
|
|
763
|
+
.prepare(`SELECT * FROM ${START_IDEMPOTENCY_TABLE} WHERE key = ? LIMIT 2`)
|
|
764
|
+
.bind(input.reservation.key));
|
|
765
|
+
if (observed.reading.state === 'proof-only')
|
|
766
|
+
statements.push(database.prepare(`SELECT * FROM ${EXECUTION_FENCE_TABLE} LIMIT 2`));
|
|
767
|
+
if (input.reservation)
|
|
768
|
+
statements.push(database.prepare(`PRAGMA table_xinfo(${START_IDEMPOTENCY_TABLE})`));
|
|
769
|
+
if (observed.reading.state === 'proof-only')
|
|
770
|
+
statements.push(database.prepare(`PRAGMA table_xinfo(${EXECUTION_FENCE_TABLE})`));
|
|
771
|
+
const results = captureBatchResults(await database.batch(statements), statements.length);
|
|
772
|
+
let index = 0;
|
|
773
|
+
const actual = decodeRawWorkflowSnapshotResult(results[index++], raw.address);
|
|
774
|
+
const reservation = input.reservation
|
|
775
|
+
? decodeStartReservationAdmissionResult(results[index++])
|
|
776
|
+
: undefined;
|
|
777
|
+
const proofRows = observed.reading.state === 'proof-only'
|
|
778
|
+
? snapshotResultRows(results[index++])
|
|
779
|
+
: undefined;
|
|
780
|
+
if (input.reservation)
|
|
781
|
+
validateStartReservationAdmissionSchema(results[index++]);
|
|
782
|
+
if (proofRows)
|
|
783
|
+
await validateExecutionFenceAdmissionSchema(results[index++]);
|
|
784
|
+
if (!actual ||
|
|
785
|
+
!sameFields({ ...actual }, { ...row }) ||
|
|
786
|
+
(input.reservation &&
|
|
787
|
+
!sameReservation(reservation, input.reservation, input.execution)))
|
|
788
|
+
return false;
|
|
789
|
+
const snapshot = record(JSON.parse(actual.snapshot));
|
|
790
|
+
const provenance = decodeInitialRunProvenance(record(snapshot.requestContext)[PROVENANCE], 'present');
|
|
791
|
+
if (provenance.startToken !== input.execution.startToken ||
|
|
792
|
+
provenance.attemptToken !== input.attemptToken)
|
|
793
|
+
return false;
|
|
794
|
+
const proofRow = proofRows?.[0];
|
|
795
|
+
return (!proofRows ||
|
|
796
|
+
(proofRows.length === 1 &&
|
|
797
|
+
proofRow !== undefined &&
|
|
798
|
+
sameFields({ ...decodeExecutionFenceAdmissionRow(proofRow).raw }, {
|
|
799
|
+
...observed.raw,
|
|
800
|
+
proof_run_id: row.runId,
|
|
801
|
+
proof_table_prefix: row.tablePrefix,
|
|
802
|
+
proof_workflow_id: row.workflowId,
|
|
803
|
+
proof_start_token: input.execution.startToken,
|
|
804
|
+
updated_at: nowMs,
|
|
805
|
+
})));
|
|
806
|
+
}
|
|
807
|
+
async #diagnoseZero(database, input, observed) {
|
|
808
|
+
try {
|
|
809
|
+
const [current, snapshot, reservation, owner] = await Promise.all([
|
|
810
|
+
input.fence.readForAdmission(),
|
|
811
|
+
readRawWorkflowSnapshot(database, input.execution, {
|
|
812
|
+
missingTable: 'error',
|
|
813
|
+
}),
|
|
814
|
+
input.reservation
|
|
815
|
+
? input.reservationStore?.readForAdmission(input.reservation.key)
|
|
816
|
+
: undefined,
|
|
817
|
+
input.runOwnerGuard
|
|
818
|
+
? this.#readOwner(database, input.execution.runId)
|
|
819
|
+
: undefined,
|
|
820
|
+
]);
|
|
821
|
+
if (reservation && input.reservation) {
|
|
822
|
+
if (reservation.owner.kind !== input.reservation.owner.kind ||
|
|
823
|
+
reservation.owner.id !== input.reservation.owner.id)
|
|
824
|
+
return new StartReservationOwnerMismatchError(input.reservation.key);
|
|
825
|
+
if (reservation.targetKind !== input.reservation.targetKind ||
|
|
826
|
+
reservation.targetId !== input.reservation.targetId)
|
|
827
|
+
return new StartReservationTargetMismatchError(input.reservation.key, reservation);
|
|
828
|
+
}
|
|
829
|
+
if (input.runOwnerGuard &&
|
|
830
|
+
(!owner ||
|
|
831
|
+
owner.owner_kind !== input.runOwnerGuard.owner.kind ||
|
|
832
|
+
owner.owner_id !== input.runOwnerGuard.owner.id ||
|
|
833
|
+
(owner.reservation_token !== null &&
|
|
834
|
+
owner.reservation_token !== input.attemptToken)))
|
|
835
|
+
return new RunAdmissionConflictError('run-owner-changed');
|
|
836
|
+
if (input.reservation && !sameReservation(reservation, input.reservation))
|
|
837
|
+
return new RunAdmissionConflictError('reservation-changed');
|
|
838
|
+
assertMutationEpoch(current.reading, input.mutationEpoch);
|
|
839
|
+
const stateAllowsStart = admitsRunStart(current.reading, input.proof?.key);
|
|
840
|
+
const proofRoundMatches = current.reading.state !== 'proof-only' ||
|
|
841
|
+
(input.proof !== undefined &&
|
|
842
|
+
current.reading.mutationEpoch === input.proof.mutationEpoch &&
|
|
843
|
+
current.reading.transitionRevision ===
|
|
844
|
+
input.proof.transitionRevision);
|
|
845
|
+
const proofSlotUnbound = current.raw.proof_run_id === null &&
|
|
846
|
+
current.raw.proof_table_prefix === null &&
|
|
847
|
+
current.raw.proof_workflow_id === null &&
|
|
848
|
+
current.raw.proof_start_token === null;
|
|
849
|
+
if (!stateAllowsStart ||
|
|
850
|
+
!proofRoundMatches ||
|
|
851
|
+
(current.reading.state === 'proof-only' && !proofSlotUnbound))
|
|
852
|
+
return new ExecutionFencedError(current.reading.state, 'initial run admission');
|
|
853
|
+
if (snapshot)
|
|
854
|
+
return new RunAdmissionConflictError('run-exists');
|
|
855
|
+
const { updated_at: _previousTime, ...previous } = observed.raw;
|
|
856
|
+
return new RunAdmissionConflictError(sameFields({ ...current.raw }, previous)
|
|
857
|
+
? 'admission-raced'
|
|
858
|
+
: 'fence-changed');
|
|
859
|
+
}
|
|
860
|
+
catch (error) {
|
|
861
|
+
if (error instanceof DoStatusError &&
|
|
862
|
+
error.reason?.code === 'MUTATION_EPOCH_MISMATCH')
|
|
863
|
+
return error;
|
|
864
|
+
return new ExecutionFenceUnreadableError('initial run admission readback is not readable', { cause: error });
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
async #readOwner(database, runId) {
|
|
868
|
+
const rows = snapshotResultRows(await database
|
|
869
|
+
.prepare(`SELECT resource_kind, resource_id, owner_kind, owner_id, reservation_token FROM ${RESOURCE_OWNER_TABLE} WHERE resource_kind = 'run' AND resource_id = ? LIMIT 2`)
|
|
870
|
+
.bind(runId)
|
|
871
|
+
.all());
|
|
872
|
+
if (rows.length > 1)
|
|
873
|
+
throw new Error('run owner is not a singleton');
|
|
874
|
+
const row = rows[0];
|
|
875
|
+
if (!row)
|
|
876
|
+
return undefined;
|
|
877
|
+
const captured = {
|
|
878
|
+
resource_kind: row.resource_kind,
|
|
879
|
+
resource_id: row.resource_id,
|
|
880
|
+
owner_kind: row.owner_kind,
|
|
881
|
+
owner_id: row.owner_id,
|
|
882
|
+
reservation_token: row.reservation_token,
|
|
883
|
+
};
|
|
884
|
+
if (captured.resource_kind !== 'run' ||
|
|
885
|
+
captured.resource_id !== runId ||
|
|
886
|
+
!isExecutionPrincipalKind(captured.owner_kind) ||
|
|
887
|
+
!isExecutionPrincipalId(captured.owner_id) ||
|
|
888
|
+
(captured.reservation_token !== null &&
|
|
889
|
+
!isPathSafeId(captured.reservation_token)))
|
|
890
|
+
throw new Error('run owner row is malformed');
|
|
891
|
+
return captured;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
//# sourceMappingURL=fenced-workflows-d1.js.map
|