@proofoftech/flowsafe 0.20.0 → 0.21.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 +81 -0
- package/README.md +55 -8
- 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 +837 -332
- 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 +239 -62
- package/dist/agent-host/thread-topology.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +90 -6
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +371 -29
- 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 +10 -14
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +49 -22
- 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 +7 -13
- package/dist/background-tasks/d1-storage.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 +31 -157
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +933 -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 +462 -175
- 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.map +1 -1
- package/dist/do-runner/execution-context.js +1 -0
- 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 +67 -13
- 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 +602 -494
- 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.map +1 -1
- package/dist/host-kit/approval-bridge.js +10 -7
- 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 +110 -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 +570 -143
- 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.map +1 -1
- package/dist/schedules/tick.js +7 -1
- 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 +1 -6
- 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 +96 -5
- package/dist/signals/notification-dispatch.d.ts.map +1 -1
- package/dist/signals/notification-dispatch.js +418 -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 +252 -73
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +6 -3
- package/patches/@mastra__core@1.53.0.patch +54 -0
- package/scripts/seed-deployment-identity.mjs +12 -5
|
@@ -25,10 +25,14 @@
|
|
|
25
25
|
// `now`, so INTEGER is the faithful encoding and numeric `<` is a correct
|
|
26
26
|
// timestamp comparison (the trigger TTL rides this, purgeExpiredScheduleTriggers).
|
|
27
27
|
import { normalizeScheduleTarget, SchedulesStorage, } from '@mastra/core/storage';
|
|
28
|
+
import { EXECUTION_FENCE_TABLE } from '#deployment-identity-protocol';
|
|
28
29
|
import { APPROVAL_ROLES, canonicalResourceOwner, createResourceOwnershipSchema, RESOURCE_OWNERSHIP_TABLE, } from '../approval-api/index.js';
|
|
30
|
+
import { assertMutationEpoch, ExecutionFenceUnreadableError, normalizeMutationEpoch, } from '../do-runner/execution-admission.js';
|
|
31
|
+
import { admitsWorkAuthoring, captureExecutionFenceAdmissionSchema, decodeExecutionFenceAdmissionRow, ExecutionFencedError, ExecutionFenceStore, executionFenceAdmissionSql, executionFenceAdmissionValues, } from '../do-runner/execution-fence.js';
|
|
29
32
|
import { isPathSafeId } from '../do-runner/path-safe-id.js';
|
|
30
33
|
import { validateTablePrefix } from '../do-runner/table-prefix.js';
|
|
31
34
|
import { d1Changes, jsonOrNull, parseJsonOrUndefined, } from '../signals/d1-shared.js';
|
|
35
|
+
import { FENCED_SCHEDULE_STORAGE, ScheduleMutationConflictError, ScheduleMutationOutcomeUnknownError, } from './mutation-contract.js';
|
|
32
36
|
const AGENT_DISPATCH_OUTCOME_BY_ACTION = {
|
|
33
37
|
wake: 'succeeded',
|
|
34
38
|
deliver: 'delivered',
|
|
@@ -65,6 +69,179 @@ export function parseScheduleAgentDispatchReceipt(value) {
|
|
|
65
69
|
: {}),
|
|
66
70
|
});
|
|
67
71
|
}
|
|
72
|
+
const SCHEDULE_COLUMNS = [
|
|
73
|
+
'id',
|
|
74
|
+
'target',
|
|
75
|
+
'cron',
|
|
76
|
+
'timezone',
|
|
77
|
+
'status',
|
|
78
|
+
'nextFireAt',
|
|
79
|
+
'lastFireAt',
|
|
80
|
+
'lastRunId',
|
|
81
|
+
'createdAt',
|
|
82
|
+
'updatedAt',
|
|
83
|
+
'metadata',
|
|
84
|
+
'ownerType',
|
|
85
|
+
'ownerId',
|
|
86
|
+
'creatorRole',
|
|
87
|
+
];
|
|
88
|
+
function mutationUnknown(cause) {
|
|
89
|
+
return new ScheduleMutationOutcomeUnknownError({ cause });
|
|
90
|
+
}
|
|
91
|
+
function mutationRecord(value) {
|
|
92
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
93
|
+
throw new Error('schedule mutation result is malformed');
|
|
94
|
+
}
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
97
|
+
function captureScheduleResult(value) {
|
|
98
|
+
const result = mutationRecord(value);
|
|
99
|
+
if ('success' in result && result.success !== true) {
|
|
100
|
+
throw new Error('schedule mutation statement did not succeed');
|
|
101
|
+
}
|
|
102
|
+
const rows = result.results;
|
|
103
|
+
if (!Array.isArray(rows))
|
|
104
|
+
throw new Error('schedule mutation rows are missing');
|
|
105
|
+
const captured = Array.from({ length: rows.length }, (_, index) => {
|
|
106
|
+
if (!Object.hasOwn(rows, index))
|
|
107
|
+
throw new Error('schedule mutation row is missing');
|
|
108
|
+
const row = mutationRecord(rows[index]);
|
|
109
|
+
return Object.freeze(Object.fromEntries(Object.getOwnPropertyNames(row).map((key) => [key, row[key]])));
|
|
110
|
+
});
|
|
111
|
+
const meta = 'meta' in result ? mutationRecord(result.meta) : undefined;
|
|
112
|
+
const hasChanges = meta !== undefined && 'changes' in meta;
|
|
113
|
+
return {
|
|
114
|
+
rows: captured,
|
|
115
|
+
hasChanges,
|
|
116
|
+
changes: hasChanges ? meta.changes : undefined,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function captureScheduleBatch(value, length) {
|
|
120
|
+
if (!Array.isArray(value) || value.length !== length) {
|
|
121
|
+
throw new Error('schedule mutation batch cardinality is invalid');
|
|
122
|
+
}
|
|
123
|
+
return Array.from({ length }, (_, index) => {
|
|
124
|
+
if (!Object.hasOwn(value, index))
|
|
125
|
+
throw new Error('schedule mutation result is missing');
|
|
126
|
+
return captureScheduleResult(value[index]);
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
function scheduleChanges(result, returning) {
|
|
130
|
+
if (!result)
|
|
131
|
+
throw new Error('schedule mutation result is missing');
|
|
132
|
+
const { rows, hasChanges, changes } = result;
|
|
133
|
+
if ((returning && rows.length > 1) ||
|
|
134
|
+
(!returning && (rows.length !== 0 || !hasChanges)) ||
|
|
135
|
+
(hasChanges &&
|
|
136
|
+
(typeof changes !== 'number' ||
|
|
137
|
+
!Number.isSafeInteger(changes) ||
|
|
138
|
+
changes < 0 ||
|
|
139
|
+
(returning && changes !== rows.length))))
|
|
140
|
+
throw new Error('schedule mutation changes contradict its evidence');
|
|
141
|
+
return returning ? rows.length : changes;
|
|
142
|
+
}
|
|
143
|
+
function singleScheduleRow(result) {
|
|
144
|
+
if (!result)
|
|
145
|
+
throw new Error('schedule mutation result is missing');
|
|
146
|
+
if (result.rows.length > 1)
|
|
147
|
+
throw new Error('schedule mutation returned multiple rows');
|
|
148
|
+
return result.rows[0];
|
|
149
|
+
}
|
|
150
|
+
function sameScheduleFields(row, expected) {
|
|
151
|
+
return Object.entries(expected).every(([key, value]) => Object.hasOwn(row, key) && row[key] === value);
|
|
152
|
+
}
|
|
153
|
+
function requireScheduleFields(row, expected) {
|
|
154
|
+
if (!row || !sameScheduleFields(row, expected)) {
|
|
155
|
+
throw new Error('schedule mutation returned a different row');
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
function mutationScheduleRow(row) {
|
|
159
|
+
const text = ['id', 'target', 'cron', 'status'];
|
|
160
|
+
const nullableText = [
|
|
161
|
+
'timezone',
|
|
162
|
+
'lastRunId',
|
|
163
|
+
'metadata',
|
|
164
|
+
'ownerType',
|
|
165
|
+
'ownerId',
|
|
166
|
+
'creatorRole',
|
|
167
|
+
];
|
|
168
|
+
const numeric = ['nextFireAt', 'createdAt', 'updatedAt'];
|
|
169
|
+
const nullableNumeric = ['lastFireAt', 'deletionRequestedAt'];
|
|
170
|
+
if (text.some((key) => typeof row[key] !== 'string') ||
|
|
171
|
+
nullableText.some((key) => row[key] !== null && typeof row[key] !== 'string') ||
|
|
172
|
+
numeric.some((key) => typeof row[key] !== 'number' || !Number.isFinite(row[key])) ||
|
|
173
|
+
nullableNumeric.some((key) => row[key] !== null &&
|
|
174
|
+
(typeof row[key] !== 'number' || !Number.isFinite(row[key])))) {
|
|
175
|
+
throw new Error('schedule mutation row is malformed');
|
|
176
|
+
}
|
|
177
|
+
return row;
|
|
178
|
+
}
|
|
179
|
+
function captureSchedule(schedule) {
|
|
180
|
+
const { id, target, cron, timezone, status, nextFireAt, lastFireAt, lastRunId, createdAt, updatedAt, metadata, ownerType, ownerId, creatorRole, } = schedule;
|
|
181
|
+
return {
|
|
182
|
+
id,
|
|
183
|
+
target: JSON.stringify(target),
|
|
184
|
+
cron,
|
|
185
|
+
timezone: timezone ?? null,
|
|
186
|
+
status,
|
|
187
|
+
nextFireAt,
|
|
188
|
+
lastFireAt: lastFireAt ?? null,
|
|
189
|
+
lastRunId: lastRunId ?? null,
|
|
190
|
+
createdAt,
|
|
191
|
+
updatedAt,
|
|
192
|
+
metadata: jsonOrNull(metadata),
|
|
193
|
+
ownerType: ownerType ?? null,
|
|
194
|
+
ownerId: ownerId ?? null,
|
|
195
|
+
creatorRole: creatorRole ?? null,
|
|
196
|
+
deletionRequestedAt: null,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
function captureSchedulePatch(patch) {
|
|
200
|
+
const { cron, timezone, status, nextFireAt, metadata, target, ownerType, ownerId, } = patch;
|
|
201
|
+
return {
|
|
202
|
+
updatedAt: Date.now(),
|
|
203
|
+
...(cron !== undefined ? { cron } : {}),
|
|
204
|
+
...(timezone !== undefined ? { timezone: timezone ?? null } : {}),
|
|
205
|
+
...(status !== undefined ? { status } : {}),
|
|
206
|
+
...(nextFireAt !== undefined ? { nextFireAt } : {}),
|
|
207
|
+
...(metadata !== undefined ? { metadata: jsonOrNull(metadata) } : {}),
|
|
208
|
+
...(target !== undefined ? { target: JSON.stringify(target) } : {}),
|
|
209
|
+
...(ownerType !== undefined ? { ownerType: ownerType ?? null } : {}),
|
|
210
|
+
...(ownerId !== undefined ? { ownerId: ownerId ?? null } : {}),
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
function requiresOpenFence(operation) {
|
|
214
|
+
return (operation === 'create' || operation === 'update' || operation === 'resume');
|
|
215
|
+
}
|
|
216
|
+
function scheduleMutationGuard(prepared) {
|
|
217
|
+
return executionFenceAdmissionSql({
|
|
218
|
+
callerEpoch: '?1',
|
|
219
|
+
semantic: prepared.semantic.map((_, index) => `?${index + 2}`),
|
|
220
|
+
schema: '?12',
|
|
221
|
+
statePredicate: requiresOpenFence(prepared.operation)
|
|
222
|
+
? "f.state COLLATE BINARY = 'open'"
|
|
223
|
+
: '1',
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
function deletionFacts(result) {
|
|
227
|
+
const row = singleScheduleRow(result);
|
|
228
|
+
if (!row ||
|
|
229
|
+
['schedules', 'triggers', 'deferred', 'owners'].some((key) => typeof row[key] !== 'number' ||
|
|
230
|
+
!Number.isSafeInteger(row[key]) ||
|
|
231
|
+
row[key] < 0))
|
|
232
|
+
throw new Error('schedule deletion facts are malformed');
|
|
233
|
+
const facts = row;
|
|
234
|
+
if (facts.schedules > 1 ||
|
|
235
|
+
facts.owners > 1 ||
|
|
236
|
+
facts.deferred > facts.triggers ||
|
|
237
|
+
(facts.deletion_requested_at !== null &&
|
|
238
|
+
(typeof facts.deletion_requested_at !== 'number' ||
|
|
239
|
+
!Number.isFinite(facts.deletion_requested_at))) ||
|
|
240
|
+
(facts.schedules === 0 && facts.deletion_requested_at !== null)) {
|
|
241
|
+
throw new Error('schedule deletion facts are inconsistent');
|
|
242
|
+
}
|
|
243
|
+
return facts;
|
|
244
|
+
}
|
|
68
245
|
function rowToSchedule(row) {
|
|
69
246
|
const target = parseJsonOrUndefined(row.target);
|
|
70
247
|
const schedule = {
|
|
@@ -128,16 +305,130 @@ function rowToTrigger(row) {
|
|
|
128
305
|
* no adapter change.
|
|
129
306
|
*/
|
|
130
307
|
export class D1SchedulesStorage extends SchedulesStorage {
|
|
308
|
+
[FENCED_SCHEDULE_STORAGE];
|
|
131
309
|
#db;
|
|
310
|
+
#fence;
|
|
311
|
+
#mutationBatch;
|
|
132
312
|
#schedules;
|
|
133
313
|
#triggers;
|
|
134
314
|
#ready;
|
|
315
|
+
#authoringReady;
|
|
135
316
|
constructor(db, tablePrefix = '') {
|
|
136
317
|
super();
|
|
137
318
|
const prefix = validateTablePrefix(tablePrefix) ?? '';
|
|
138
319
|
this.#db = db;
|
|
320
|
+
this.#fence = new ExecutionFenceStore(db);
|
|
139
321
|
this.#schedules = `${prefix}mastra_schedules`;
|
|
140
322
|
this.#triggers = `${prefix}mastra_schedule_triggers`;
|
|
323
|
+
const batch = db.batch;
|
|
324
|
+
if (typeof batch === 'function') {
|
|
325
|
+
this.#mutationBatch = (statements) => Reflect.apply(batch, db, [statements]);
|
|
326
|
+
this[FENCED_SCHEDULE_STORAGE] = Object.freeze({
|
|
327
|
+
database: db,
|
|
328
|
+
createOwnedSchedule: this.createOwnedSchedule.bind(this),
|
|
329
|
+
updateSchedule: this.updateSchedule.bind(this),
|
|
330
|
+
pauseSchedule: this.pauseSchedule.bind(this),
|
|
331
|
+
resumeSchedule: this.resumeSchedule.bind(this),
|
|
332
|
+
deleteOwnedSchedule: this.deleteOwnedSchedule.bind(this),
|
|
333
|
+
observeScheduleMutation: this.observeScheduleMutation.bind(this),
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
async #prepareMutation(epoch, operation) {
|
|
338
|
+
if (!this.#mutationBatch) {
|
|
339
|
+
throw new Error('D1SchedulesStorage requires database.batch() for schedule mutations');
|
|
340
|
+
}
|
|
341
|
+
if (!this.#authoringReady) {
|
|
342
|
+
this.#authoringReady = this.#ensureSchema()
|
|
343
|
+
.then(() => this.#fence.seed('open'))
|
|
344
|
+
.catch((error) => {
|
|
345
|
+
this.#authoringReady = undefined;
|
|
346
|
+
throw error;
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
await this.#authoringReady;
|
|
350
|
+
const observation = await this.#fence.readForAdmission();
|
|
351
|
+
const semantic = executionFenceAdmissionValues(observation);
|
|
352
|
+
assertMutationEpoch(observation.reading, epoch);
|
|
353
|
+
if (requiresOpenFence(operation) &&
|
|
354
|
+
!admitsWorkAuthoring(observation.reading)) {
|
|
355
|
+
throw new ExecutionFencedError(observation.reading.state);
|
|
356
|
+
}
|
|
357
|
+
let schema;
|
|
358
|
+
try {
|
|
359
|
+
const captured = captureScheduleResult(await this.#db
|
|
360
|
+
.prepare(`PRAGMA table_xinfo(${EXECUTION_FENCE_TABLE})`)
|
|
361
|
+
.all());
|
|
362
|
+
schema = await captureExecutionFenceAdmissionSchema({
|
|
363
|
+
results: captured.rows,
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
catch (cause) {
|
|
367
|
+
throw new ExecutionFenceUnreadableError('execution fence schema is not readable', { cause });
|
|
368
|
+
}
|
|
369
|
+
return {
|
|
370
|
+
epoch,
|
|
371
|
+
operation,
|
|
372
|
+
semantic,
|
|
373
|
+
schema,
|
|
374
|
+
bindings: [epoch ?? null, ...semantic, schema],
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
#mutationDiagnostics() {
|
|
378
|
+
return [
|
|
379
|
+
this.#db.prepare(`SELECT * FROM ${EXECUTION_FENCE_TABLE} LIMIT 2`),
|
|
380
|
+
this.#db.prepare(`PRAGMA table_xinfo(${EXECUTION_FENCE_TABLE})`),
|
|
381
|
+
];
|
|
382
|
+
}
|
|
383
|
+
async #executeMutation(prepared, statements, returningSlots, changesSlot) {
|
|
384
|
+
let results;
|
|
385
|
+
let writes;
|
|
386
|
+
try {
|
|
387
|
+
if (!this.#mutationBatch)
|
|
388
|
+
throw new Error('schedule mutation batch is unavailable');
|
|
389
|
+
results = captureScheduleBatch(await this.#mutationBatch([...statements]), statements.length);
|
|
390
|
+
writes = returningSlots.reduce((count, slot) => count + scheduleChanges(results[slot], true), 0);
|
|
391
|
+
if (changesSlot !== undefined)
|
|
392
|
+
writes += scheduleChanges(results[changesSlot], false);
|
|
393
|
+
}
|
|
394
|
+
catch (cause) {
|
|
395
|
+
throw mutationUnknown(cause);
|
|
396
|
+
}
|
|
397
|
+
let current;
|
|
398
|
+
let semantic;
|
|
399
|
+
let schema;
|
|
400
|
+
const schemaResult = results[1];
|
|
401
|
+
try {
|
|
402
|
+
const row = singleScheduleRow(results[0]);
|
|
403
|
+
if (!row)
|
|
404
|
+
throw new Error('execution fence singleton is missing');
|
|
405
|
+
current = decodeExecutionFenceAdmissionRow(row);
|
|
406
|
+
semantic = executionFenceAdmissionValues(current);
|
|
407
|
+
if (!schemaResult)
|
|
408
|
+
throw new Error('execution fence schema result is missing');
|
|
409
|
+
schema = await captureExecutionFenceAdmissionSchema({
|
|
410
|
+
results: schemaResult.rows,
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
catch (cause) {
|
|
414
|
+
const unreadable = new ExecutionFenceUnreadableError('execution fence state is not readable', { cause });
|
|
415
|
+
throw writes === 0 ? unreadable : mutationUnknown(unreadable);
|
|
416
|
+
}
|
|
417
|
+
try {
|
|
418
|
+
assertMutationEpoch(current.reading, prepared.epoch);
|
|
419
|
+
if (requiresOpenFence(prepared.operation) &&
|
|
420
|
+
!admitsWorkAuthoring(current.reading)) {
|
|
421
|
+
throw new ExecutionFencedError(current.reading.state);
|
|
422
|
+
}
|
|
423
|
+
if (semantic.some((value, index) => value !== prepared.semantic[index]) ||
|
|
424
|
+
schema !== prepared.schema) {
|
|
425
|
+
throw new ScheduleMutationConflictError('fence-changed');
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
catch (cause) {
|
|
429
|
+
throw writes === 0 ? cause : mutationUnknown(cause);
|
|
430
|
+
}
|
|
431
|
+
return results;
|
|
141
432
|
}
|
|
142
433
|
/**
|
|
143
434
|
* Lazy, memoized schema creation — the same clear-on-failure promise memo the
|
|
@@ -225,47 +516,104 @@ export class D1SchedulesStorage extends SchedulesStorage {
|
|
|
225
516
|
async init() {
|
|
226
517
|
await this.#ensureSchema();
|
|
227
518
|
}
|
|
228
|
-
async createSchedule(schedule) {
|
|
229
|
-
|
|
519
|
+
async createSchedule(schedule, context) {
|
|
520
|
+
const epoch = normalizeMutationEpoch(context?.mutationEpoch);
|
|
521
|
+
const row = captureSchedule(schedule);
|
|
522
|
+
const prepared = await this.#prepareMutation(epoch, 'create');
|
|
523
|
+
const results = await this.#executeMutation(prepared, [
|
|
524
|
+
...this.#mutationDiagnostics(),
|
|
525
|
+
this.#db
|
|
526
|
+
.prepare(`SELECT id FROM ${this.#schedules} WHERE id COLLATE BINARY = ?1 LIMIT 2`)
|
|
527
|
+
.bind(row.id),
|
|
528
|
+
this.#insertScheduleStatement(row, prepared),
|
|
529
|
+
], [3]);
|
|
230
530
|
try {
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
531
|
+
const existing = singleScheduleRow(results[2]);
|
|
532
|
+
if (existing)
|
|
533
|
+
requireScheduleFields(existing, { id: row.id });
|
|
534
|
+
const created = singleScheduleRow(results[3]);
|
|
535
|
+
if (created) {
|
|
536
|
+
if (existing)
|
|
537
|
+
throw new Error('schedule insertion contradicts existing id');
|
|
538
|
+
requireScheduleFields(created, { ...row });
|
|
539
|
+
return rowToSchedule(mutationScheduleRow(created));
|
|
236
540
|
}
|
|
237
|
-
|
|
541
|
+
if (!existing)
|
|
542
|
+
throw new Error('schedule insertion has no outcome');
|
|
238
543
|
}
|
|
239
|
-
|
|
544
|
+
catch (cause) {
|
|
545
|
+
throw mutationUnknown(cause);
|
|
546
|
+
}
|
|
547
|
+
throw new Error(`schedule ${row.id} already exists`);
|
|
240
548
|
}
|
|
241
549
|
/**
|
|
242
550
|
* Flowsafe facade create: schedule row, owner row, and the deployment count
|
|
243
551
|
* cap share one D1 transaction. The schedules domain and resource registry
|
|
244
552
|
* must therefore use the same binding.
|
|
245
553
|
*/
|
|
246
|
-
async createOwnedSchedule(schedule, owner, maxSchedules) {
|
|
247
|
-
const
|
|
554
|
+
async createOwnedSchedule(schedule, owner, maxSchedules, context) {
|
|
555
|
+
const epoch = normalizeMutationEpoch(context?.mutationEpoch);
|
|
556
|
+
const row = captureSchedule(schedule);
|
|
557
|
+
const safeOwner = canonicalResourceOwner(owner === null || typeof owner !== 'object'
|
|
558
|
+
? owner
|
|
559
|
+
: { kind: owner.kind, id: owner.id });
|
|
248
560
|
if (!Number.isSafeInteger(maxSchedules) || maxSchedules < 0) {
|
|
249
561
|
throw new Error('maxSchedules must be a nonnegative safe integer');
|
|
250
562
|
}
|
|
251
|
-
await this.#
|
|
252
|
-
const
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
563
|
+
const prepared = await this.#prepareMutation(epoch, 'create');
|
|
564
|
+
const results = await this.#executeMutation(prepared, [
|
|
565
|
+
...this.#mutationDiagnostics(),
|
|
566
|
+
this.#db
|
|
567
|
+
.prepare(`SELECT COUNT(*) AS total,
|
|
568
|
+
EXISTS(SELECT 1 FROM ${this.#schedules} WHERE id COLLATE BINARY = ?1) AS id_exists
|
|
569
|
+
FROM ${this.#schedules}`)
|
|
570
|
+
.bind(row.id),
|
|
571
|
+
this.#insertScheduleStatement(row, prepared, maxSchedules),
|
|
258
572
|
this.#db
|
|
259
573
|
.prepare(`INSERT INTO ${RESOURCE_OWNERSHIP_TABLE}
|
|
260
574
|
(resource_kind, resource_id, owner_kind, owner_id)
|
|
261
|
-
SELECT 'schedule',
|
|
575
|
+
SELECT 'schedule', ?13, ?14, ?15
|
|
262
576
|
WHERE changes() = 1
|
|
263
|
-
AND EXISTS (SELECT 1 FROM ${this.#schedules} WHERE id = ?)
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
577
|
+
AND EXISTS (SELECT 1 FROM ${this.#schedules} WHERE id COLLATE BINARY = ?13)
|
|
578
|
+
AND ${scheduleMutationGuard(prepared)}
|
|
579
|
+
RETURNING resource_kind, resource_id, owner_kind, owner_id, reservation_token`)
|
|
580
|
+
.bind(...prepared.bindings, row.id, safeOwner.kind, safeOwner.id),
|
|
581
|
+
], [3, 4]);
|
|
582
|
+
try {
|
|
583
|
+
const facts = singleScheduleRow(results[2]);
|
|
584
|
+
if (!facts ||
|
|
585
|
+
typeof facts.total !== 'number' ||
|
|
586
|
+
!Number.isSafeInteger(facts.total) ||
|
|
587
|
+
facts.total < 0 ||
|
|
588
|
+
(facts.id_exists !== 0 && facts.id_exists !== 1)) {
|
|
589
|
+
throw new Error('schedule creation facts are malformed');
|
|
590
|
+
}
|
|
591
|
+
const created = singleScheduleRow(results[3]);
|
|
592
|
+
const owned = singleScheduleRow(results[4]);
|
|
593
|
+
if (created) {
|
|
594
|
+
if (facts.total >= maxSchedules || facts.id_exists !== 0)
|
|
595
|
+
throw new Error('schedule insertion contradicts its cap or id');
|
|
596
|
+
requireScheduleFields(created, { ...row });
|
|
597
|
+
requireScheduleFields(owned, {
|
|
598
|
+
resource_kind: 'schedule',
|
|
599
|
+
resource_id: row.id,
|
|
600
|
+
owner_kind: safeOwner.kind,
|
|
601
|
+
owner_id: safeOwner.id,
|
|
602
|
+
reservation_token: null,
|
|
603
|
+
});
|
|
604
|
+
return rowToSchedule(mutationScheduleRow(created));
|
|
605
|
+
}
|
|
606
|
+
if (owned)
|
|
607
|
+
throw new Error('zero schedule insertion acquired an owner');
|
|
608
|
+
if (facts.total >= maxSchedules)
|
|
609
|
+
return null;
|
|
610
|
+
if (facts.id_exists !== 1)
|
|
611
|
+
throw new Error('schedule insertion has no outcome');
|
|
612
|
+
}
|
|
613
|
+
catch (cause) {
|
|
614
|
+
throw mutationUnknown(cause);
|
|
615
|
+
}
|
|
616
|
+
throw new Error(`schedule ${row.id} already exists`);
|
|
269
617
|
}
|
|
270
618
|
async getSchedule(id) {
|
|
271
619
|
await this.#ensureSchema();
|
|
@@ -329,60 +677,107 @@ export class D1SchedulesStorage extends SchedulesStorage {
|
|
|
329
677
|
const { results } = await bound.all();
|
|
330
678
|
return results.map(rowToSchedule);
|
|
331
679
|
}
|
|
332
|
-
async updateSchedule(id, patch) {
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
const
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
680
|
+
async updateSchedule(id, patch, context) {
|
|
681
|
+
const epoch = normalizeMutationEpoch(context?.mutationEpoch);
|
|
682
|
+
return this.#updateSchedule(id, captureSchedulePatch(patch), epoch, 'update');
|
|
683
|
+
}
|
|
684
|
+
async pauseSchedule(id, context) {
|
|
685
|
+
const epoch = normalizeMutationEpoch(context?.mutationEpoch);
|
|
686
|
+
return this.#updateSchedule(id, { status: 'paused', updatedAt: Date.now() }, epoch, 'pause');
|
|
687
|
+
}
|
|
688
|
+
async resumeSchedule(id, mutation, context) {
|
|
689
|
+
const epoch = normalizeMutationEpoch(context?.mutationEpoch);
|
|
690
|
+
const { expectedCron, expectedTimezone, nextFireAt } = mutation;
|
|
691
|
+
return this.#updateSchedule(id, { status: 'active', nextFireAt, updatedAt: Date.now() }, epoch, 'resume', {
|
|
692
|
+
cron: expectedCron,
|
|
693
|
+
timezone: expectedTimezone ?? null,
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
async #updateSchedule(id, patch, epoch, operation, expected) {
|
|
697
|
+
const fields = Object.entries(patch);
|
|
698
|
+
const prepared = await this.#prepareMutation(epoch, operation);
|
|
699
|
+
const idParameter = fields.length + 13;
|
|
700
|
+
// Targeted writes preserve columns advanced by a concurrent fire claim.
|
|
701
|
+
const sets = fields.map(([key], index) => `${key} = ?${index + 13}`);
|
|
702
|
+
const results = await this.#executeMutation(prepared, [
|
|
703
|
+
...this.#mutationDiagnostics(),
|
|
704
|
+
this.#db
|
|
705
|
+
.prepare(`SELECT * FROM ${this.#schedules} WHERE id COLLATE BINARY = ?1 LIMIT 2`)
|
|
706
|
+
.bind(id),
|
|
707
|
+
this.#db
|
|
708
|
+
.prepare(`UPDATE ${this.#schedules} SET ${sets.join(', ')}
|
|
709
|
+
WHERE id COLLATE BINARY = ?${idParameter} AND deletionRequestedAt IS NULL
|
|
710
|
+
${expected ? `AND cron COLLATE BINARY = ?${idParameter + 1} AND timezone COLLATE BINARY IS ?${idParameter + 2}` : ''}
|
|
711
|
+
AND ${scheduleMutationGuard(prepared)} RETURNING *`)
|
|
712
|
+
.bind(...prepared.bindings, ...fields.map(([, value]) => value), id, ...(expected ? [expected.cron, expected.timezone] : [])),
|
|
713
|
+
], [3]);
|
|
714
|
+
let missing;
|
|
715
|
+
let changed = false;
|
|
716
|
+
try {
|
|
717
|
+
const previous = singleScheduleRow(results[2]);
|
|
718
|
+
const updated = singleScheduleRow(results[3]);
|
|
719
|
+
if (previous) {
|
|
720
|
+
requireScheduleFields(previous, { id });
|
|
721
|
+
mutationScheduleRow(previous);
|
|
722
|
+
}
|
|
723
|
+
missing = !previous || previous.deletionRequestedAt !== null;
|
|
724
|
+
if (updated) {
|
|
725
|
+
if (missing ||
|
|
726
|
+
(expected &&
|
|
727
|
+
!sameScheduleFields(previous, expected))) {
|
|
728
|
+
throw new Error('schedule update contradicts its prior row');
|
|
729
|
+
}
|
|
730
|
+
requireScheduleFields(updated, { ...previous, ...patch, id });
|
|
731
|
+
return rowToSchedule(mutationScheduleRow(updated));
|
|
732
|
+
}
|
|
733
|
+
changed =
|
|
734
|
+
!missing &&
|
|
735
|
+
expected !== undefined &&
|
|
736
|
+
!sameScheduleFields(previous, expected);
|
|
737
|
+
if (!missing && !changed)
|
|
738
|
+
throw new Error('schedule update has no outcome');
|
|
739
|
+
}
|
|
740
|
+
catch (cause) {
|
|
741
|
+
throw mutationUnknown(cause);
|
|
742
|
+
}
|
|
743
|
+
if (changed)
|
|
744
|
+
throw new ScheduleMutationConflictError('schedule-changed');
|
|
745
|
+
throw new Error(`schedule ${id} not found`);
|
|
746
|
+
}
|
|
747
|
+
async observeScheduleMutation(id, operation, context) {
|
|
748
|
+
const epoch = normalizeMutationEpoch(context?.mutationEpoch);
|
|
749
|
+
if (operation !== 'pause' && operation !== 'resume')
|
|
750
|
+
throw new Error('schedule mutation observation is invalid');
|
|
751
|
+
const prepared = await this.#prepareMutation(epoch, operation);
|
|
752
|
+
const results = await this.#executeMutation(prepared, [
|
|
753
|
+
...this.#mutationDiagnostics(),
|
|
754
|
+
this.#db
|
|
755
|
+
.prepare(`SELECT * FROM ${this.#schedules} WHERE id COLLATE BINARY = ?1 LIMIT 2`)
|
|
756
|
+
.bind(id),
|
|
757
|
+
this.#db
|
|
758
|
+
.prepare(`SELECT * FROM ${this.#schedules}
|
|
759
|
+
WHERE id COLLATE BINARY = ?13 AND deletionRequestedAt IS NULL
|
|
760
|
+
AND ${scheduleMutationGuard(prepared)} LIMIT 2`)
|
|
761
|
+
.bind(...prepared.bindings, id),
|
|
762
|
+
], []);
|
|
763
|
+
try {
|
|
764
|
+
const previous = singleScheduleRow(results[2]);
|
|
765
|
+
const observed = singleScheduleRow(results[3]);
|
|
766
|
+
if (previous) {
|
|
767
|
+
requireScheduleFields(previous, { id });
|
|
768
|
+
mutationScheduleRow(previous);
|
|
769
|
+
}
|
|
770
|
+
if (!previous || previous.deletionRequestedAt !== null) {
|
|
771
|
+
if (observed)
|
|
772
|
+
throw new Error('schedule observation contradicts absence');
|
|
773
|
+
return null;
|
|
774
|
+
}
|
|
775
|
+
requireScheduleFields(observed, previous);
|
|
776
|
+
return rowToSchedule(mutationScheduleRow(observed));
|
|
777
|
+
}
|
|
778
|
+
catch (cause) {
|
|
779
|
+
throw mutationUnknown(cause);
|
|
780
|
+
}
|
|
386
781
|
}
|
|
387
782
|
async updateScheduleNextFire(id, expectedNextFireAt, newNextFireAt, lastFireAt, lastRunId) {
|
|
388
783
|
await this.#ensureSchema();
|
|
@@ -564,52 +959,113 @@ export class D1SchedulesStorage extends SchedulesStorage {
|
|
|
564
959
|
}
|
|
565
960
|
throw new Error('agent schedule dispatch could not be force-discarded');
|
|
566
961
|
}
|
|
567
|
-
async deleteSchedule(id) {
|
|
568
|
-
await this.deleteOwnedSchedule(id);
|
|
962
|
+
async deleteSchedule(id, context) {
|
|
963
|
+
await this.deleteOwnedSchedule(id, context);
|
|
569
964
|
}
|
|
570
965
|
/** Delete an authorized facade schedule and its owner in one transaction. */
|
|
571
|
-
async deleteOwnedSchedule(id) {
|
|
572
|
-
|
|
573
|
-
const
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
966
|
+
async deleteOwnedSchedule(id, context) {
|
|
967
|
+
const epoch = normalizeMutationEpoch(context?.mutationEpoch);
|
|
968
|
+
const now = Date.now();
|
|
969
|
+
const prepared = await this.#prepareMutation(epoch, 'delete');
|
|
970
|
+
const guard = scheduleMutationGuard(prepared);
|
|
971
|
+
const results = await this.#executeMutation(prepared, [
|
|
972
|
+
...this.#mutationDiagnostics(),
|
|
973
|
+
this.#deletionFactsStatement(id),
|
|
578
974
|
this.#db
|
|
579
975
|
.prepare(`UPDATE ${this.#schedules}
|
|
580
|
-
SET status = 'paused', updatedAt =
|
|
976
|
+
SET status = 'paused', updatedAt = ?13,
|
|
581
977
|
deletionRequestedAt = CASE
|
|
582
978
|
WHEN EXISTS (
|
|
583
979
|
SELECT 1 FROM ${this.#triggers}
|
|
584
|
-
WHERE scheduleId = ? AND outcome = 'deferred'
|
|
585
|
-
) THEN COALESCE(deletionRequestedAt, ?)
|
|
980
|
+
WHERE scheduleId COLLATE BINARY = ?14 AND outcome = 'deferred'
|
|
981
|
+
) THEN COALESCE(deletionRequestedAt, ?13)
|
|
586
982
|
ELSE NULL
|
|
587
983
|
END
|
|
588
|
-
WHERE id =
|
|
589
|
-
|
|
984
|
+
WHERE id COLLATE BINARY = ?14 AND ${guard}
|
|
985
|
+
RETURNING id, status, updatedAt, deletionRequestedAt`)
|
|
986
|
+
.bind(...prepared.bindings, now, id),
|
|
590
987
|
this.#db
|
|
591
988
|
.prepare(`DELETE FROM ${this.#triggers}
|
|
592
|
-
WHERE scheduleId = ?
|
|
989
|
+
WHERE scheduleId COLLATE BINARY = ?13 AND ${guard}
|
|
593
990
|
AND NOT EXISTS (
|
|
594
991
|
SELECT 1 FROM ${this.#schedules}
|
|
595
|
-
WHERE id = ? AND deletionRequestedAt IS NOT NULL
|
|
992
|
+
WHERE id COLLATE BINARY = ?13 AND deletionRequestedAt IS NOT NULL
|
|
596
993
|
)`)
|
|
597
|
-
.bind(
|
|
994
|
+
.bind(...prepared.bindings, id),
|
|
598
995
|
this.#db
|
|
599
996
|
.prepare(`DELETE FROM ${this.#schedules}
|
|
600
|
-
WHERE id = ? AND deletionRequestedAt IS NULL
|
|
601
|
-
|
|
997
|
+
WHERE id COLLATE BINARY = ?13 AND deletionRequestedAt IS NULL
|
|
998
|
+
AND ${guard} RETURNING id`)
|
|
999
|
+
.bind(...prepared.bindings, id),
|
|
602
1000
|
this.#db
|
|
603
1001
|
.prepare(`DELETE FROM ${RESOURCE_OWNERSHIP_TABLE}
|
|
604
|
-
WHERE resource_kind = 'schedule' AND resource_id = ?
|
|
605
|
-
AND NOT EXISTS (SELECT 1 FROM ${this.#schedules} WHERE id = ?)
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
1002
|
+
WHERE resource_kind COLLATE BINARY = 'schedule' AND resource_id COLLATE BINARY = ?13
|
|
1003
|
+
AND NOT EXISTS (SELECT 1 FROM ${this.#schedules} WHERE id COLLATE BINARY = ?13)
|
|
1004
|
+
AND ${guard}
|
|
1005
|
+
RETURNING resource_kind, resource_id, owner_kind, owner_id, reservation_token`)
|
|
1006
|
+
.bind(...prepared.bindings, id),
|
|
1007
|
+
this.#deletionFactsStatement(id),
|
|
1008
|
+
], [3, 5, 6], 4);
|
|
1009
|
+
try {
|
|
1010
|
+
const before = deletionFacts(results[2]);
|
|
1011
|
+
const after = deletionFacts(results[7]);
|
|
1012
|
+
const pending = before.schedules === 1 && before.deferred > 0;
|
|
1013
|
+
const marker = pending ? (before.deletion_requested_at ?? now) : null;
|
|
1014
|
+
if (results[3].rows.length !== before.schedules ||
|
|
1015
|
+
scheduleChanges(results[4], false) !==
|
|
1016
|
+
(pending ? 0 : before.triggers) ||
|
|
1017
|
+
results[5].rows.length !== (pending ? 0 : before.schedules) ||
|
|
1018
|
+
results[6].rows.length !== (pending ? 0 : before.owners)) {
|
|
1019
|
+
throw new Error('schedule deletion writes contradict its prior state');
|
|
1020
|
+
}
|
|
1021
|
+
if (before.schedules === 1)
|
|
1022
|
+
requireScheduleFields(results[3].rows[0], {
|
|
1023
|
+
id,
|
|
1024
|
+
status: 'paused',
|
|
1025
|
+
updatedAt: now,
|
|
1026
|
+
deletionRequestedAt: marker,
|
|
1027
|
+
});
|
|
1028
|
+
for (const row of results[5].rows)
|
|
1029
|
+
requireScheduleFields(row, { id });
|
|
1030
|
+
for (const row of results[6].rows) {
|
|
1031
|
+
requireScheduleFields(row, {
|
|
1032
|
+
resource_kind: 'schedule',
|
|
1033
|
+
resource_id: id,
|
|
1034
|
+
});
|
|
1035
|
+
if (typeof row.owner_kind !== 'string' ||
|
|
1036
|
+
typeof row.owner_id !== 'string' ||
|
|
1037
|
+
(row.reservation_token !== null &&
|
|
1038
|
+
typeof row.reservation_token !== 'string')) {
|
|
1039
|
+
throw new Error('schedule deletion owner is malformed');
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
const expected = pending
|
|
1043
|
+
? { ...before, deletion_requested_at: marker }
|
|
1044
|
+
: {
|
|
1045
|
+
schedules: 0,
|
|
1046
|
+
deletion_requested_at: null,
|
|
1047
|
+
triggers: 0,
|
|
1048
|
+
deferred: 0,
|
|
1049
|
+
owners: 0,
|
|
1050
|
+
};
|
|
1051
|
+
if (!sameScheduleFields({ ...after }, expected))
|
|
1052
|
+
throw new Error('schedule deletion did not converge');
|
|
1053
|
+
return pending ? 'pending' : 'deleted';
|
|
1054
|
+
}
|
|
1055
|
+
catch (cause) {
|
|
1056
|
+
throw mutationUnknown(cause);
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
#deletionFactsStatement(id) {
|
|
1060
|
+
return this.#db
|
|
1061
|
+
.prepare(`SELECT
|
|
1062
|
+
(SELECT COUNT(*) FROM ${this.#schedules} WHERE id COLLATE BINARY = ?1) AS schedules,
|
|
1063
|
+
(SELECT deletionRequestedAt FROM ${this.#schedules} WHERE id COLLATE BINARY = ?1) AS deletion_requested_at,
|
|
1064
|
+
(SELECT COUNT(*) FROM ${this.#triggers} WHERE scheduleId COLLATE BINARY = ?1) AS triggers,
|
|
1065
|
+
(SELECT COUNT(*) FROM ${this.#triggers} WHERE scheduleId COLLATE BINARY = ?1 AND outcome = 'deferred') AS deferred,
|
|
1066
|
+
(SELECT COUNT(*) FROM ${RESOURCE_OWNERSHIP_TABLE}
|
|
1067
|
+
WHERE resource_kind COLLATE BINARY = 'schedule' AND resource_id COLLATE BINARY = ?1) AS owners`)
|
|
1068
|
+
.bind(id);
|
|
613
1069
|
}
|
|
614
1070
|
async recordTrigger(trigger) {
|
|
615
1071
|
await this.#ensureSchema();
|
|
@@ -754,43 +1210,14 @@ export class D1SchedulesStorage extends SchedulesStorage {
|
|
|
754
1210
|
AND resource_id NOT IN (SELECT id FROM ${this.#schedules})`),
|
|
755
1211
|
]);
|
|
756
1212
|
}
|
|
757
|
-
|
|
758
|
-
async #insertSchedule(schedule) {
|
|
759
|
-
await this.#insertScheduleStatement(schedule).run();
|
|
760
|
-
}
|
|
761
|
-
#insertScheduleStatement(schedule, maxSchedules) {
|
|
762
|
-
const columns = `(
|
|
763
|
-
id, target, cron, timezone, status, nextFireAt, lastFireAt,
|
|
764
|
-
lastRunId, createdAt, updatedAt, metadata, ownerType, ownerId,
|
|
765
|
-
creatorRole
|
|
766
|
-
)`;
|
|
767
|
-
const values = [
|
|
768
|
-
schedule.id,
|
|
769
|
-
JSON.stringify(schedule.target),
|
|
770
|
-
schedule.cron,
|
|
771
|
-
schedule.timezone ?? null,
|
|
772
|
-
schedule.status,
|
|
773
|
-
schedule.nextFireAt,
|
|
774
|
-
schedule.lastFireAt ?? null,
|
|
775
|
-
schedule.lastRunId ?? null,
|
|
776
|
-
schedule.createdAt,
|
|
777
|
-
schedule.updatedAt,
|
|
778
|
-
jsonOrNull(schedule.metadata),
|
|
779
|
-
schedule.ownerType ?? null,
|
|
780
|
-
schedule.ownerId ?? null,
|
|
781
|
-
schedule.creatorRole ?? null,
|
|
782
|
-
];
|
|
783
|
-
if (maxSchedules === undefined) {
|
|
784
|
-
return this.#db
|
|
785
|
-
.prepare(`INSERT INTO ${this.#schedules} ${columns}
|
|
786
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
787
|
-
.bind(...values);
|
|
788
|
-
}
|
|
1213
|
+
#insertScheduleStatement(row, prepared, maxSchedules) {
|
|
789
1214
|
return this.#db
|
|
790
|
-
.prepare(`INSERT INTO ${this.#schedules} ${
|
|
791
|
-
SELECT
|
|
792
|
-
WHERE (
|
|
793
|
-
|
|
1215
|
+
.prepare(`INSERT INTO ${this.#schedules} (${SCHEDULE_COLUMNS.join(', ')})
|
|
1216
|
+
SELECT ${SCHEDULE_COLUMNS.map((_, index) => `?${index + 13}`).join(', ')}
|
|
1217
|
+
WHERE ${scheduleMutationGuard(prepared)}
|
|
1218
|
+
${maxSchedules === undefined ? '' : `AND (SELECT COUNT(*) FROM ${this.#schedules}) < ?27`}
|
|
1219
|
+
ON CONFLICT (id) DO NOTHING RETURNING *`)
|
|
1220
|
+
.bind(...prepared.bindings, ...SCHEDULE_COLUMNS.map((key) => row[key]), ...(maxSchedules === undefined ? [] : [maxSchedules]));
|
|
794
1221
|
}
|
|
795
1222
|
}
|
|
796
1223
|
//# sourceMappingURL=schedules-d1.js.map
|