@proofoftech/flowsafe 0.19.0 → 0.20.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 +25 -0
- package/README.md +15 -0
- package/deployment-identity-protocol.d.mts +45 -1
- package/deployment-identity-protocol.mjs +169 -5
- package/dist/agent-host/index.d.ts +1 -1
- package/dist/agent-host/index.d.ts.map +1 -1
- package/dist/agent-host/index.js.map +1 -1
- package/dist/agent-host/router.d.ts.map +1 -1
- package/dist/agent-host/router.js +6 -2
- package/dist/agent-host/router.js.map +1 -1
- package/dist/agent-host/thread-host.d.ts +11 -0
- package/dist/agent-host/thread-host.d.ts.map +1 -1
- package/dist/agent-host/thread-host.js +53 -1
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/agent-host/thread-topology.d.ts +35 -1
- package/dist/agent-host/thread-topology.d.ts.map +1 -1
- package/dist/agent-host/thread-topology.js +103 -7
- package/dist/agent-host/thread-topology.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +19 -4
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +58 -28
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/approval-api/d1-store.d.ts.map +1 -1
- package/dist/approval-api/d1-store.js +6 -3
- package/dist/approval-api/d1-store.js.map +1 -1
- package/dist/approval-api/principal-identity.d.ts +32 -0
- package/dist/approval-api/principal-identity.d.ts.map +1 -0
- package/dist/approval-api/principal-identity.js +69 -0
- package/dist/approval-api/principal-identity.js.map +1 -0
- package/dist/approval-api/principal.d.ts +9 -12
- package/dist/approval-api/principal.d.ts.map +1 -1
- package/dist/approval-api/principal.js +9 -45
- package/dist/approval-api/principal.js.map +1 -1
- package/dist/approval-api/router.d.ts.map +1 -1
- package/dist/approval-api/router.js +9 -1
- package/dist/approval-api/router.js.map +1 -1
- package/dist/approval-api/service.d.ts +19 -0
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +41 -10
- package/dist/approval-api/service.js.map +1 -1
- package/dist/approval-api/types.d.ts +12 -0
- package/dist/approval-api/types.d.ts.map +1 -1
- package/dist/approval-api/types.js +12 -0
- package/dist/approval-api/types.js.map +1 -1
- package/dist/background-tasks/host.d.ts +127 -14
- package/dist/background-tasks/host.d.ts.map +1 -1
- package/dist/background-tasks/host.js +579 -50
- package/dist/background-tasks/host.js.map +1 -1
- package/dist/background-tasks/index.d.ts +2 -2
- package/dist/background-tasks/index.d.ts.map +1 -1
- package/dist/background-tasks/index.js +11 -6
- package/dist/background-tasks/index.js.map +1 -1
- package/dist/background-tasks/routes.d.ts +19 -2
- package/dist/background-tasks/routes.d.ts.map +1 -1
- package/dist/background-tasks/routes.js +4 -4
- package/dist/background-tasks/routes.js.map +1 -1
- package/dist/deployment-identity-protocol.d.ts +2 -2
- package/dist/deployment-identity-protocol.d.ts.map +1 -1
- package/dist/deployment-identity-protocol.js +1 -1
- package/dist/deployment-identity-protocol.js.map +1 -1
- package/dist/do-runner/cause-chain.d.ts +53 -0
- package/dist/do-runner/cause-chain.d.ts.map +1 -0
- package/dist/do-runner/cause-chain.js +96 -0
- package/dist/do-runner/cause-chain.js.map +1 -0
- package/dist/do-runner/d1-storage.d.ts +109 -5
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +289 -44
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/deployment-identity.d.ts +29 -5
- package/dist/do-runner/deployment-identity.d.ts.map +1 -1
- package/dist/do-runner/deployment-identity.js +23 -6
- package/dist/do-runner/deployment-identity.js.map +1 -1
- package/dist/do-runner/do-error-response.d.ts +4 -23
- package/dist/do-runner/do-error-response.d.ts.map +1 -1
- package/dist/do-runner/do-error-response.js +19 -24
- package/dist/do-runner/do-error-response.js.map +1 -1
- package/dist/do-runner/do-status-error.d.ts +37 -0
- package/dist/do-runner/do-status-error.d.ts.map +1 -0
- package/dist/do-runner/do-status-error.js +42 -0
- package/dist/do-runner/do-status-error.js.map +1 -0
- package/dist/do-runner/durable-object.d.ts +2 -1
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +205 -19
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/execution-fence.d.ts +335 -0
- package/dist/do-runner/execution-fence.d.ts.map +1 -0
- package/dist/do-runner/execution-fence.js +534 -0
- package/dist/do-runner/execution-fence.js.map +1 -0
- package/dist/do-runner/index.d.ts +10 -3
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +16 -3
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/init.d.ts +82 -1
- package/dist/do-runner/init.d.ts.map +1 -1
- package/dist/do-runner/init.js +58 -3
- package/dist/do-runner/init.js.map +1 -1
- package/dist/do-runner/inventory.d.ts +294 -0
- package/dist/do-runner/inventory.d.ts.map +1 -0
- package/dist/do-runner/inventory.js +811 -0
- package/dist/do-runner/inventory.js.map +1 -0
- package/dist/do-runner/notification-predicate.d.ts +8 -0
- package/dist/do-runner/notification-predicate.d.ts.map +1 -0
- package/dist/do-runner/notification-predicate.js +9 -0
- package/dist/do-runner/notification-predicate.js.map +1 -0
- package/dist/do-runner/runtime.d.ts +83 -0
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +131 -4
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/start-idempotency.d.ts +508 -0
- package/dist/do-runner/start-idempotency.d.ts.map +1 -0
- package/dist/do-runner/start-idempotency.js +886 -0
- package/dist/do-runner/start-idempotency.js.map +1 -0
- package/dist/goals/objective-routes.d.ts +14 -0
- package/dist/goals/objective-routes.d.ts.map +1 -1
- package/dist/goals/objective-routes.js +45 -24
- package/dist/goals/objective-routes.js.map +1 -1
- package/dist/host-kit/do-run-topology.d.ts +15 -0
- package/dist/host-kit/do-run-topology.d.ts.map +1 -1
- package/dist/host-kit/do-run-topology.js +22 -1
- package/dist/host-kit/do-run-topology.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +11 -0
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +343 -62
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/host-approval-service.d.ts +20 -0
- package/dist/host-kit/host-approval-service.d.ts.map +1 -1
- package/dist/host-kit/host-approval-service.js +6 -0
- package/dist/host-kit/host-approval-service.js.map +1 -1
- package/dist/host-kit/index.d.ts +2 -2
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +1 -1
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/run-route-error.d.ts +18 -0
- package/dist/host-kit/run-route-error.d.ts.map +1 -1
- package/dist/host-kit/run-route-error.js +23 -0
- package/dist/host-kit/run-route-error.js.map +1 -1
- package/dist/host-kit/run-router.d.ts +58 -1
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js +120 -11
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/host-kit/stream-router.d.ts.map +1 -1
- package/dist/host-kit/stream-router.js +18 -9
- package/dist/host-kit/stream-router.js.map +1 -1
- package/dist/schedules/router.d.ts +15 -0
- package/dist/schedules/router.d.ts.map +1 -1
- package/dist/schedules/router.js +47 -17
- package/dist/schedules/router.js.map +1 -1
- package/dist/schedules/tick.d.ts +13 -0
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +59 -39
- package/dist/schedules/tick.js.map +1 -1
- package/dist/signal-providers/host-do.d.ts +12 -1
- package/dist/signal-providers/host-do.d.ts.map +1 -1
- package/dist/signal-providers/host-do.js +28 -3
- package/dist/signal-providers/host-do.js.map +1 -1
- package/dist/signal-providers/webhook-route.d.ts +14 -0
- package/dist/signal-providers/webhook-route.d.ts.map +1 -1
- package/dist/signal-providers/webhook-route.js +28 -5
- package/dist/signal-providers/webhook-route.js.map +1 -1
- package/dist/signals/notification-dispatch.d.ts +13 -0
- package/dist/signals/notification-dispatch.d.ts.map +1 -1
- package/dist/signals/notification-dispatch.js +20 -1
- package/dist/signals/notification-dispatch.js.map +1 -1
- package/dist/signals/notifications-d1.d.ts +8 -0
- package/dist/signals/notifications-d1.d.ts.map +1 -1
- package/dist/signals/notifications-d1.js +15 -9
- package/dist/signals/notifications-d1.js.map +1 -1
- package/dist/signals/thread-do-routes.d.ts.map +1 -1
- package/dist/signals/thread-do-routes.js +86 -18
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +1 -1
- package/scripts/seed-deployment-identity.mjs +22 -4
|
@@ -0,0 +1,886 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Owner-bound idempotent start — the reservation that makes "start this once"
|
|
3
|
+
// mean once, across retries, isolates, and deployments.
|
|
4
|
+
//
|
|
5
|
+
// WHY it exists: a run start is the moment a deployment commits to spending
|
|
6
|
+
// money. The first step of a workflow can wire funds, file an order, or call a
|
|
7
|
+
// paid API, and every layer between a caller and that step is allowed to lose a
|
|
8
|
+
// RESPONSE without losing the WORK — a Worker eviction, a client timeout, a
|
|
9
|
+
// load balancer retry, an operator re-running a script. Without a reservation
|
|
10
|
+
// the only honest answer to "did my start land?" is "retry and find out", and
|
|
11
|
+
// that answer charges the card twice.
|
|
12
|
+
//
|
|
13
|
+
// The reservation is what a key BUYS: a durable row, written before anything
|
|
14
|
+
// executes, that says which run this key already means. A retry carrying the
|
|
15
|
+
// same key does not start a second run — it finds the first one and is told
|
|
16
|
+
// what happened to it.
|
|
17
|
+
//
|
|
18
|
+
// THE TAXONOMY IS THE CONTRACT. Eight structured reason codes say what flowsafe
|
|
19
|
+
// KNOWS, because the caller's next action differs for each and a collapsed code
|
|
20
|
+
// would make them all "retry". Five are reservation-decision refusals:
|
|
21
|
+
//
|
|
22
|
+
// IDEMPOTENT_START_OWNER_MISMATCH (403) this key is somebody else's. Keys are
|
|
23
|
+
// owner-scoped, so one tenant principal
|
|
24
|
+
// cannot probe, hijack, or collide with
|
|
25
|
+
// another's — and never learns more than
|
|
26
|
+
// "not yours".
|
|
27
|
+
// IDEMPOTENT_START_TARGET_MISMATCH (409) the key is yours but names a
|
|
28
|
+
// different workflow/agent than last time.
|
|
29
|
+
// Reusing a key across targets is a caller
|
|
30
|
+
// bug, and silently honouring it would make
|
|
31
|
+
// one key mean two different charges.
|
|
32
|
+
// IDEMPOTENT_START_PENDING (503) the run this key names is RUNNING right
|
|
33
|
+
// now. Retryable, and legitimately unbounded:
|
|
34
|
+
// the first persisted summary lands at the
|
|
35
|
+
// first suspend or terminal state, so a long
|
|
36
|
+
// live run has no summary yet and is not lost.
|
|
37
|
+
// `pendingSince` lets a caller reason about
|
|
38
|
+
// how long, without this package pretending a
|
|
39
|
+
// timeout would be safe.
|
|
40
|
+
// IDEMPOTENT_START_UNRESOLVABLE (409) the claim was taken, nothing persisted,
|
|
41
|
+
// and nothing is running. Whether a side
|
|
42
|
+
// effect fired before the crash is UNKNOWABLE
|
|
43
|
+
// to flowsafe. So it refuses, and says so, and
|
|
44
|
+
// never re-executes on its own. A host that
|
|
45
|
+
// investigates and decides to re-run does it
|
|
46
|
+
// with a FRESH key — a deliberate second
|
|
47
|
+
// charge, not one this package invented.
|
|
48
|
+
// IDEMPOTENT_START_ALREADY_SETTLED (409) the run finished and its summary has
|
|
49
|
+
// aged out. The reservation deliberately
|
|
50
|
+
// OUTLIVES the snapshot so this answer exists
|
|
51
|
+
// at all; the alternative is a purged run
|
|
52
|
+
// looking exactly like a fresh key.
|
|
53
|
+
//
|
|
54
|
+
// Three complete the public keyed-start taxonomy:
|
|
55
|
+
//
|
|
56
|
+
// IDEMPOTENT_START_UNSUPPORTED (503) a keyed start reached a deployment whose
|
|
57
|
+
// host did not wire a reservation store.
|
|
58
|
+
// INVALID_START_IDEMPOTENCY_REQUEST (400) the keyed input was malformed.
|
|
59
|
+
// IDEMPOTENT_START_UNREADABLE (503) the reservation store could not be read
|
|
60
|
+
// or contained a row this build cannot parse.
|
|
61
|
+
//
|
|
62
|
+
// The seven-member `StartReservationRefusal` union recognized by
|
|
63
|
+
// `isStartReservationRefusal` includes everything above except UNREADABLE,
|
|
64
|
+
// which propagates separately as an integrity or availability failure.
|
|
65
|
+
//
|
|
66
|
+
// NO TIMER ANYWHERE. Two of those branches are separated by a LIVENESS PROBE,
|
|
67
|
+
// never by elapsed time. A timer would have to guess a bound on legitimate
|
|
68
|
+
// in-flight work, and every guess is wrong in the expensive direction: too
|
|
69
|
+
// short and a long live run is declared dead, inviting a fresh key and a second
|
|
70
|
+
// charge; too long and a genuinely crashed start wedges its key. The probe asks
|
|
71
|
+
// the run's own host whether it is executing, which is the question a timer was
|
|
72
|
+
// only ever approximating.
|
|
73
|
+
//
|
|
74
|
+
// THE CLAIM IS THE SERIALIZER. `reserve()` decides which runId a key means;
|
|
75
|
+
// `claim()` decides who gets to START it. The claim is one conditional UPDATE,
|
|
76
|
+
// so exactly one caller changes a row and every other caller reads the outcome
|
|
77
|
+
// instead of racing it. That matters most where Durable Object serialization
|
|
78
|
+
// cannot help: agent runs live in thread objects keyed by threadId, so two
|
|
79
|
+
// same-key starts naming different threads are two different objects with no
|
|
80
|
+
// shared lock at all. This CAS is the only thing between them.
|
|
81
|
+
//
|
|
82
|
+
// RUN IDS ARE NEVER MINTED HERE. Run ids are server-minted, at the host's own
|
|
83
|
+
// existing mint sites; the reservation STORES one and hands the same id back to
|
|
84
|
+
// every later caller. A store that generated ids would be a second minting
|
|
85
|
+
// authority, and the whole rule is that there is exactly one.
|
|
86
|
+
import { EXECUTION_PRINCIPAL_KINDS, isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal-identity.js';
|
|
87
|
+
import { missingTableReadsEmpty } from './cause-chain.js';
|
|
88
|
+
import { DoStatusError } from './do-status-error.js';
|
|
89
|
+
import { isExecutionFenceRefusal } from './execution-fence.js';
|
|
90
|
+
import { isPathSafeId } from './path-safe-id.js';
|
|
91
|
+
/**
|
|
92
|
+
* The reservation table — flowsafe-owned, so outside the `mastra_%` schema
|
|
93
|
+
* guard, and created lazily by the first `reserve()` rather than by the
|
|
94
|
+
* provisioning protocol. Unlike the execution fence (whose ABSENCE has to read
|
|
95
|
+
* as a state, so provisioning writes an explicit row), an absent reservation
|
|
96
|
+
* table simply means no key has ever been used on this deployment, which is
|
|
97
|
+
* indistinguishable from an empty one.
|
|
98
|
+
*/
|
|
99
|
+
export const START_IDEMPOTENCY_TABLE = 'flowsafe_start_idempotency';
|
|
100
|
+
export const START_RESERVATION_STATES = [
|
|
101
|
+
'reserved',
|
|
102
|
+
'started',
|
|
103
|
+
'terminal',
|
|
104
|
+
];
|
|
105
|
+
export const START_TARGET_KINDS = ['workflow', 'agent'];
|
|
106
|
+
/**
|
|
107
|
+
* The key names a reservation owned by a different principal.
|
|
108
|
+
*
|
|
109
|
+
* 403 rather than 404: the caller sent a syntactically valid key it is simply
|
|
110
|
+
* not entitled to, and this is the one refusal whose body deliberately carries
|
|
111
|
+
* nothing else — not the owner, not the target, not the run. A key is guessable
|
|
112
|
+
* by construction (hosts derive them from order ids and request ids), so this
|
|
113
|
+
* response is reachable by probing, and everything it does not say is something
|
|
114
|
+
* a prober does not learn.
|
|
115
|
+
*/
|
|
116
|
+
export class StartReservationOwnerMismatchError extends DoStatusError {
|
|
117
|
+
status = 403;
|
|
118
|
+
reason;
|
|
119
|
+
constructor(key) {
|
|
120
|
+
super(`idempotency key '${key}' belongs to another principal`);
|
|
121
|
+
this.name = 'StartReservationOwnerMismatchError';
|
|
122
|
+
this.reason = { code: 'IDEMPOTENT_START_OWNER_MISMATCH' };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* The caller's own key, pointed at a different workflow or agent than the one
|
|
127
|
+
* it reserved. 409, and it DOES name the reservation's target: the caller owns
|
|
128
|
+
* this key, so telling it what the key already means is telling it about its
|
|
129
|
+
* own state, and a caller that reused a key by accident needs exactly that to
|
|
130
|
+
* find the bug.
|
|
131
|
+
*/
|
|
132
|
+
export class StartReservationTargetMismatchError extends DoStatusError {
|
|
133
|
+
status = 409;
|
|
134
|
+
reason;
|
|
135
|
+
constructor(key, reservation) {
|
|
136
|
+
super(`idempotency key '${key}' already names ${reservation.targetKind} '${reservation.targetId}'`);
|
|
137
|
+
this.name = 'StartReservationTargetMismatchError';
|
|
138
|
+
this.reason = {
|
|
139
|
+
code: 'IDEMPOTENT_START_TARGET_MISMATCH',
|
|
140
|
+
targetKind: reservation.targetKind,
|
|
141
|
+
targetId: reservation.targetId,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The key's run is executing right now. 503 for the same reason every
|
|
147
|
+
* operator-transient refusal in this package is: the condition is real, it is
|
|
148
|
+
* nobody's mistake, and it clears on its own — so a client that honours
|
|
149
|
+
* retry semantics converges instead of giving up.
|
|
150
|
+
*/
|
|
151
|
+
export class IdempotentStartPendingError extends DoStatusError {
|
|
152
|
+
status = 503;
|
|
153
|
+
reason;
|
|
154
|
+
constructor(reservation) {
|
|
155
|
+
super(`run '${reservation.runId}' for this idempotency key is still starting`);
|
|
156
|
+
this.name = 'IdempotentStartPendingError';
|
|
157
|
+
this.reason = {
|
|
158
|
+
code: 'IDEMPOTENT_START_PENDING',
|
|
159
|
+
runId: reservation.runId,
|
|
160
|
+
pendingSince: reservation.updatedAt,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The claim was taken, nothing persisted, and nothing is running.
|
|
166
|
+
*
|
|
167
|
+
* This is the refusal that refuses to guess. The message is written for the
|
|
168
|
+
* human who will read it in a log at 3am, because the decision it asks for is
|
|
169
|
+
* a judgement call this package cannot make: a side effect may or may not have
|
|
170
|
+
* fired before the crash, and only the host knows whether its first step is the
|
|
171
|
+
* kind that charges.
|
|
172
|
+
*/
|
|
173
|
+
export class IdempotentStartUnresolvableError extends DoStatusError {
|
|
174
|
+
status = 409;
|
|
175
|
+
reason;
|
|
176
|
+
constructor(reservation) {
|
|
177
|
+
super(`run '${reservation.runId}' for this idempotency key was claimed but never persisted and is not running — investigate whether its first step already took effect before re-running with a fresh key`);
|
|
178
|
+
this.name = 'IdempotentStartUnresolvableError';
|
|
179
|
+
this.reason = {
|
|
180
|
+
code: 'IDEMPOTENT_START_UNRESOLVABLE',
|
|
181
|
+
runId: reservation.runId,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* The run finished and its summary has aged out of retention. 409 and never a
|
|
187
|
+
* re-execution: a key whose run completed is spent, and the fact that nobody
|
|
188
|
+
* can still read the OUTCOME does not make the WORK un-done.
|
|
189
|
+
*/
|
|
190
|
+
export class IdempotentStartAlreadySettledError extends DoStatusError {
|
|
191
|
+
status = 409;
|
|
192
|
+
reason;
|
|
193
|
+
constructor(reservation) {
|
|
194
|
+
super(`run '${reservation.runId}' for this idempotency key already completed and its summary has expired`);
|
|
195
|
+
this.name = 'IdempotentStartAlreadySettledError';
|
|
196
|
+
this.reason = {
|
|
197
|
+
code: 'IDEMPOTENT_START_ALREADY_SETTLED',
|
|
198
|
+
runId: reservation.runId,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/** A malformed idempotency key or reservation request — the caller's to fix. */
|
|
203
|
+
export class InvalidStartIdempotencyRequestError extends DoStatusError {
|
|
204
|
+
status = 400;
|
|
205
|
+
reason;
|
|
206
|
+
constructor(message) {
|
|
207
|
+
super(message);
|
|
208
|
+
this.name = 'InvalidStartIdempotencyRequestError';
|
|
209
|
+
this.reason = { code: 'INVALID_START_IDEMPOTENCY_REQUEST' };
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* A start carried a key onto a deployment whose host never wired the
|
|
214
|
+
* reservation store.
|
|
215
|
+
*
|
|
216
|
+
* 503, and never a silent pass-through. Honouring the request without a
|
|
217
|
+
* reservation would answer an exactly-once REQUEST with at-least-once
|
|
218
|
+
* BEHAVIOUR, which is worse than refusing: the caller would have every reason
|
|
219
|
+
* to believe a retry is safe, and no way to find out it is not. The condition
|
|
220
|
+
* is a wiring fault an operator fixes, so it reads as transient rather than as
|
|
221
|
+
* the caller's mistake.
|
|
222
|
+
*/
|
|
223
|
+
export class StartIdempotencyUnsupportedError extends DoStatusError {
|
|
224
|
+
status = 503;
|
|
225
|
+
reason;
|
|
226
|
+
constructor() {
|
|
227
|
+
super('idempotent starts are not configured on this deployment — wire a StartIdempotencyStore before accepting idempotencyKey');
|
|
228
|
+
this.name = 'StartIdempotencyUnsupportedError';
|
|
229
|
+
this.reason = { code: 'IDEMPOTENT_START_UNSUPPORTED' };
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Recognize the five reservation-decision refusals:
|
|
234
|
+
*
|
|
235
|
+
* - `IDEMPOTENT_START_OWNER_MISMATCH` (403)
|
|
236
|
+
* - `IDEMPOTENT_START_TARGET_MISMATCH` (409)
|
|
237
|
+
* - `IDEMPOTENT_START_PENDING` (503)
|
|
238
|
+
* - `IDEMPOTENT_START_UNRESOLVABLE` (409)
|
|
239
|
+
* - `IDEMPOTENT_START_ALREADY_SETTLED` (409)
|
|
240
|
+
*
|
|
241
|
+
* The guard also recognizes `IDEMPOTENT_START_UNSUPPORTED` keyed admission
|
|
242
|
+
* (503) and malformed reservation input (400,
|
|
243
|
+
* `INVALID_START_IDEMPOTENCY_REQUEST`).
|
|
244
|
+
*
|
|
245
|
+
* Unsupported wiring remains in this guard because the keyed request is
|
|
246
|
+
* intentionally refused at admission instead of being executed without its
|
|
247
|
+
* exactly-once guarantee. `StartReservationUnreadableError` is deliberately
|
|
248
|
+
* outside it: unreadable storage is an integrity or availability failure, not
|
|
249
|
+
* a reservation decision, and propagates through the shared `DoStatusError`
|
|
250
|
+
* renderer with `IDEMPOTENT_START_UNREADABLE` and its 503 status. A false
|
|
251
|
+
* answer never permits an unkeyed start: a `StartReservationUnreadableError`
|
|
252
|
+
* must still propagate as 503.
|
|
253
|
+
*/
|
|
254
|
+
export function isStartReservationRefusal(error) {
|
|
255
|
+
return (error instanceof StartReservationOwnerMismatchError ||
|
|
256
|
+
error instanceof StartReservationTargetMismatchError ||
|
|
257
|
+
error instanceof IdempotentStartPendingError ||
|
|
258
|
+
error instanceof IdempotentStartUnresolvableError ||
|
|
259
|
+
error instanceof IdempotentStartAlreadySettledError ||
|
|
260
|
+
error instanceof StartIdempotencyUnsupportedError ||
|
|
261
|
+
error instanceof InvalidStartIdempotencyRequestError);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Rows affected by a write, read from D1's `{ meta: { changes } }` envelope.
|
|
265
|
+
* Restated here for the same reason execution-fence.ts restates it: every
|
|
266
|
+
* surface that reserves must be able to import this module without dragging
|
|
267
|
+
* the D1 storage adapter (and @mastra/cloudflare-d1 with it) into its bundle.
|
|
268
|
+
*
|
|
269
|
+
* That bundle rule is why the imports at the top of this file are what they
|
|
270
|
+
* are. Four are import-free leaves (principal-identity, cause-chain,
|
|
271
|
+
* do-status-error, path-safe-id) and the fifth, execution-fence, imports only
|
|
272
|
+
* leaves and the shared provisioning protocol. Nothing on that graph can cycle
|
|
273
|
+
* back here, which matters more than usual: the eight DoStatusError subclasses
|
|
274
|
+
* in this module are evaluated at module load, so an import edge that came
|
|
275
|
+
* back around would meet a class expression still in its temporal dead zone.
|
|
276
|
+
*/
|
|
277
|
+
function changesOf(result) {
|
|
278
|
+
const changes = result?.meta
|
|
279
|
+
?.changes;
|
|
280
|
+
return typeof changes === 'number' ? changes : 0;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* One reservation store per DATABASE, keyed on the BINDING — the same memo, for
|
|
284
|
+
* the same reason, as `executionFenceFor`: the router that reserves, the
|
|
285
|
+
* topology that claims, the runtime that settles, and the purge that reaps must
|
|
286
|
+
* all be looking at one table, and keying on an env object would hand two
|
|
287
|
+
* databases the same store the first time a host mutated env across requests.
|
|
288
|
+
*/
|
|
289
|
+
const startIdempotencyStores = new WeakMap();
|
|
290
|
+
export function startIdempotencyFor(db) {
|
|
291
|
+
const existing = startIdempotencyStores.get(db);
|
|
292
|
+
if (existing)
|
|
293
|
+
return existing;
|
|
294
|
+
const store = new StartIdempotencyStore(db);
|
|
295
|
+
startIdempotencyStores.set(db, store);
|
|
296
|
+
return store;
|
|
297
|
+
}
|
|
298
|
+
const STATE_CHECK = START_RESERVATION_STATES.map((state) => `'${state}'`).join(', ');
|
|
299
|
+
const TARGET_CHECK = START_TARGET_KINDS.map((kind) => `'${kind}'`).join(', ');
|
|
300
|
+
/**
|
|
301
|
+
* Built from the principal vocabulary rather than hand-written, so a kind added
|
|
302
|
+
* to `EXECUTION_PRINCIPAL_KINDS` cannot leave this constraint behind. The
|
|
303
|
+
* failure a stale literal would cause is not a compile error and not a rejected
|
|
304
|
+
* write on an existing deployment: `CREATE TABLE IF NOT EXISTS` is a no-op
|
|
305
|
+
* against a table that already exists, so the drift would show up only as an
|
|
306
|
+
* INSERT refused on whichever database happened to be created after the new
|
|
307
|
+
* kind shipped.
|
|
308
|
+
*/
|
|
309
|
+
const OWNER_KIND_CHECK = EXECUTION_PRINCIPAL_KINDS.map((kind) => `'${kind}'`).join(', ');
|
|
310
|
+
/**
|
|
311
|
+
* The reservation schema.
|
|
312
|
+
*
|
|
313
|
+
* The CHECK constraints are load-bearing, not decoration: every compare-and-set
|
|
314
|
+
* below is stated as `WHERE ... AND state = '<literal>'`, which is only a TOTAL
|
|
315
|
+
* decision while the column cannot hold a fourth value. A row hand-edited into
|
|
316
|
+
* an unknown state would otherwise be a reservation no CAS can advance and no
|
|
317
|
+
* purge can reap — a permanently wedged key.
|
|
318
|
+
*/
|
|
319
|
+
export const START_IDEMPOTENCY_DDL = `CREATE TABLE IF NOT EXISTS ${START_IDEMPOTENCY_TABLE} (
|
|
320
|
+
key TEXT PRIMARY KEY,
|
|
321
|
+
owner_kind TEXT NOT NULL CHECK (owner_kind IN (${OWNER_KIND_CHECK})),
|
|
322
|
+
owner_id TEXT NOT NULL,
|
|
323
|
+
target_kind TEXT NOT NULL CHECK (target_kind IN (${TARGET_CHECK})),
|
|
324
|
+
target_id TEXT NOT NULL,
|
|
325
|
+
run_id TEXT NOT NULL,
|
|
326
|
+
thread_id TEXT,
|
|
327
|
+
state TEXT NOT NULL CHECK (state IN (${STATE_CHECK})),
|
|
328
|
+
created_at INTEGER NOT NULL,
|
|
329
|
+
updated_at INTEGER NOT NULL
|
|
330
|
+
)`;
|
|
331
|
+
/**
|
|
332
|
+
* `run_id` is how the RUNTIME finds a reservation (terminal reconcile knows the
|
|
333
|
+
* run, never the key) and how the purge pairs a reservation with the snapshot
|
|
334
|
+
* it outlived. Without the index both degrade to a table scan on every terminal
|
|
335
|
+
* run.
|
|
336
|
+
*/
|
|
337
|
+
export const START_IDEMPOTENCY_RUN_INDEX_DDL = `CREATE INDEX IF NOT EXISTS ${START_IDEMPOTENCY_TABLE}_run
|
|
338
|
+
ON ${START_IDEMPOTENCY_TABLE} (run_id)`;
|
|
339
|
+
/** The purge's own access path: terminal rows past the key-validity horizon. */
|
|
340
|
+
export const START_IDEMPOTENCY_STATE_INDEX_DDL = `CREATE INDEX IF NOT EXISTS ${START_IDEMPOTENCY_TABLE}_state
|
|
341
|
+
ON ${START_IDEMPOTENCY_TABLE} (state, updated_at)`;
|
|
342
|
+
function isStartReservationState(value) {
|
|
343
|
+
return (typeof value === 'string' &&
|
|
344
|
+
START_RESERVATION_STATES.includes(value));
|
|
345
|
+
}
|
|
346
|
+
function isStartTargetKind(value) {
|
|
347
|
+
return (typeof value === 'string' &&
|
|
348
|
+
START_TARGET_KINDS.includes(value));
|
|
349
|
+
}
|
|
350
|
+
function isEpochMs(value) {
|
|
351
|
+
return typeof value === 'number' && Number.isFinite(value);
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Project a stored row, or refuse it.
|
|
355
|
+
*
|
|
356
|
+
* A malformed row throws rather than reading as absent, and that direction is
|
|
357
|
+
* deliberate: "there is no reservation" is the answer that STARTS A RUN, so it
|
|
358
|
+
* must never be reachable from a row this build cannot parse. The CHECK
|
|
359
|
+
* constraints make this unreachable on a database this package created; it
|
|
360
|
+
* exists for the one that was hand-edited.
|
|
361
|
+
*
|
|
362
|
+
* The TIMESTAMPS are in that strict set too, rather than coerced to 0 as an
|
|
363
|
+
* unparseable number once was. Neither column is decoration: `updated_at` is
|
|
364
|
+
* the horizon the purge measures from, so a corrupt one on a terminal row reads
|
|
365
|
+
* as epoch 0 and makes the reservation immediately reapable — which deletes a
|
|
366
|
+
* spent key early and turns the next retry of it into a fresh start. It is also
|
|
367
|
+
* `pendingSince` on a live claim, where 0 tells an operator a run has been
|
|
368
|
+
* starting since 1970. Refusing the row keeps both faults visible as the 503
|
|
369
|
+
* they are.
|
|
370
|
+
*/
|
|
371
|
+
function reservationFromRow(row) {
|
|
372
|
+
const { key, owner_kind: ownerKind, owner_id: ownerId, target_kind: targetKind, target_id: targetId, run_id: runId, thread_id: threadId, state, created_at: createdAt, updated_at: updatedAt, } = row;
|
|
373
|
+
if (typeof key !== 'string' ||
|
|
374
|
+
!isExecutionPrincipalKind(ownerKind) ||
|
|
375
|
+
!isExecutionPrincipalId(ownerId) ||
|
|
376
|
+
!isStartTargetKind(targetKind) ||
|
|
377
|
+
typeof targetId !== 'string' ||
|
|
378
|
+
!isPathSafeId(runId) ||
|
|
379
|
+
!isStartReservationState(state) ||
|
|
380
|
+
!isEpochMs(createdAt) ||
|
|
381
|
+
!isEpochMs(updatedAt)) {
|
|
382
|
+
throw new StartReservationUnreadableError(typeof key === 'string' ? key : '(unknown)');
|
|
383
|
+
}
|
|
384
|
+
return {
|
|
385
|
+
key,
|
|
386
|
+
owner: { kind: ownerKind, id: ownerId },
|
|
387
|
+
targetKind,
|
|
388
|
+
targetId,
|
|
389
|
+
runId,
|
|
390
|
+
...(isPathSafeId(threadId) ? { threadId } : {}),
|
|
391
|
+
state,
|
|
392
|
+
createdAt,
|
|
393
|
+
updatedAt,
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* A reservation exists but cannot be understood, or the table could not be
|
|
398
|
+
* read. 503 and never "no reservation": the absent answer is the one that
|
|
399
|
+
* starts a run, so an unreadable store degrades CLOSED exactly as an unreadable
|
|
400
|
+
* fence does.
|
|
401
|
+
*/
|
|
402
|
+
export class StartReservationUnreadableError extends DoStatusError {
|
|
403
|
+
status = 503;
|
|
404
|
+
reason;
|
|
405
|
+
constructor(key, options) {
|
|
406
|
+
super(`start reservation '${key}' is not readable`, options);
|
|
407
|
+
this.name = 'StartReservationUnreadableError';
|
|
408
|
+
this.reason = { code: 'IDEMPOTENT_START_UNREADABLE' };
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* SQLite/D1's "no such table", for THIS store's table: the reservation table is
|
|
413
|
+
* created lazily by the first `reserve()`, so its absence means no key has ever
|
|
414
|
+
* been used here and there is nothing to find.
|
|
415
|
+
*
|
|
416
|
+
* The rule itself — bounded, cycle-safe, and matched at the ROOT of the cause
|
|
417
|
+
* chain only — lives in cause-chain.ts, shared with the fence store. Root-only
|
|
418
|
+
* is the load-bearing half: a missing-table link mentioned part-way down a
|
|
419
|
+
* chain describes a fault that merely PASSED this table on its way out (a
|
|
420
|
+
* failed migration, an adapter reporting the last thing it saw), and concluding
|
|
421
|
+
* "no reservations exist" from that would start a run.
|
|
422
|
+
*
|
|
423
|
+
* Kept local because every consumer is in this store; the drain inventory uses
|
|
424
|
+
* `missingTableReadsEmpty` directly with `START_IDEMPOTENCY_TABLE`.
|
|
425
|
+
*/
|
|
426
|
+
function isMissingReservationTable(error) {
|
|
427
|
+
return missingTableReadsEmpty(error, START_IDEMPOTENCY_TABLE);
|
|
428
|
+
}
|
|
429
|
+
function assertKey(key) {
|
|
430
|
+
if (!isPathSafeId(key)) {
|
|
431
|
+
throw new InvalidStartIdempotencyRequestError("idempotencyKey must be a URL-path-safe identifier (letters, digits, '.', '_', '~', '-'; 1-200 chars)");
|
|
432
|
+
}
|
|
433
|
+
return key;
|
|
434
|
+
}
|
|
435
|
+
function assertOwner(owner) {
|
|
436
|
+
if (owner === null || typeof owner !== 'object') {
|
|
437
|
+
throw new InvalidStartIdempotencyRequestError('reservation owner must be an execution principal');
|
|
438
|
+
}
|
|
439
|
+
const { kind, id } = owner;
|
|
440
|
+
if (!isExecutionPrincipalKind(kind) || !isExecutionPrincipalId(id)) {
|
|
441
|
+
throw new InvalidStartIdempotencyRequestError('reservation owner must be an execution principal');
|
|
442
|
+
}
|
|
443
|
+
return { kind, id };
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* The deployment's start reservations, over the SAME D1 database its snapshots,
|
|
447
|
+
* its resource owners, and its execution fence live in — so a reservation
|
|
448
|
+
* cannot be separated from the run it reserves by any binding mistake.
|
|
449
|
+
*/
|
|
450
|
+
export class StartIdempotencyStore {
|
|
451
|
+
#db;
|
|
452
|
+
#now;
|
|
453
|
+
#ready;
|
|
454
|
+
constructor(db, options = {}) {
|
|
455
|
+
this.#db = db;
|
|
456
|
+
this.#now = options.now ?? Date.now;
|
|
457
|
+
if (options.ready) {
|
|
458
|
+
this.#ready = options.ready;
|
|
459
|
+
}
|
|
460
|
+
else {
|
|
461
|
+
let ready;
|
|
462
|
+
this.#ready = () => {
|
|
463
|
+
ready ??= this.#createSchema().catch((error) => {
|
|
464
|
+
ready = undefined;
|
|
465
|
+
throw error;
|
|
466
|
+
});
|
|
467
|
+
return ready;
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Decide which run this key means, creating the reservation if it is new.
|
|
473
|
+
*
|
|
474
|
+
* INSERT OR IGNORE then READ BACK — the resource-ownership idiom, and the
|
|
475
|
+
* only shape that is correct without a transaction: the insert is the race,
|
|
476
|
+
* the read-back is the result, and every caller that lost the insert reads
|
|
477
|
+
* the winner's row rather than its own intention. Two callers can therefore
|
|
478
|
+
* never both believe they created the reservation, whatever order their
|
|
479
|
+
* statements interleave in, and neither needs to know it raced.
|
|
480
|
+
*
|
|
481
|
+
* This is the ONE method that may create the table. A reservation is the
|
|
482
|
+
* first write anything here makes, so the schema belongs on its path and
|
|
483
|
+
* nowhere else — in particular not on `read`, where lazy DDL would turn the
|
|
484
|
+
* deployment's read-only drain inventory into a write.
|
|
485
|
+
*/
|
|
486
|
+
async reserve(request) {
|
|
487
|
+
const key = assertKey(request.key);
|
|
488
|
+
const owner = assertOwner(request.owner);
|
|
489
|
+
if (!isStartTargetKind(request.targetKind)) {
|
|
490
|
+
throw new InvalidStartIdempotencyRequestError(`target kind must be one of ${START_TARGET_KINDS.join(', ')}`);
|
|
491
|
+
}
|
|
492
|
+
if (!isPathSafeId(request.targetId)) {
|
|
493
|
+
throw new InvalidStartIdempotencyRequestError('target id must be a URL-path-safe identifier');
|
|
494
|
+
}
|
|
495
|
+
// The thread is the agent run's ADDRESS, so requiring it for agents and
|
|
496
|
+
// rejecting it for workflows is not tidiness: an agent reservation without
|
|
497
|
+
// one is a run a retry can never reach, and a workflow reservation WITH one
|
|
498
|
+
// is a second, silently divergent copy of an address that is already
|
|
499
|
+
// derivable from (workflowId, runId).
|
|
500
|
+
if (request.targetKind === 'agent') {
|
|
501
|
+
if (!isPathSafeId(request.threadId)) {
|
|
502
|
+
throw new InvalidStartIdempotencyRequestError('an agent start reservation requires a URL-path-safe threadId');
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
else if (request.threadId !== undefined) {
|
|
506
|
+
throw new InvalidStartIdempotencyRequestError('threadId applies only to agent start reservations');
|
|
507
|
+
}
|
|
508
|
+
await this.#ready();
|
|
509
|
+
const candidateRunId = request.mintRunId();
|
|
510
|
+
if (!isPathSafeId(candidateRunId)) {
|
|
511
|
+
throw new InvalidStartIdempotencyRequestError('the host minted a runId that is not URL-path-safe');
|
|
512
|
+
}
|
|
513
|
+
const now = this.#now();
|
|
514
|
+
const inserted = changesOf(await this.#db
|
|
515
|
+
.prepare(`INSERT OR IGNORE INTO ${START_IDEMPOTENCY_TABLE}
|
|
516
|
+
(key, owner_kind, owner_id, target_kind, target_id, run_id,
|
|
517
|
+
thread_id, state, created_at, updated_at)
|
|
518
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 'reserved', ?, ?)`)
|
|
519
|
+
.bind(key, owner.kind, owner.id, request.targetKind, request.targetId, candidateRunId, request.threadId ?? null, now, now)
|
|
520
|
+
.run());
|
|
521
|
+
const stored = await this.read(key);
|
|
522
|
+
if (stored === undefined) {
|
|
523
|
+
// The row was written and is already gone: the purge cannot reach a row
|
|
524
|
+
// this young, so this is a storage fault, not a reservation state.
|
|
525
|
+
throw new StartReservationUnreadableError(key);
|
|
526
|
+
}
|
|
527
|
+
// Owner FIRST, always. A caller that is not the owner must learn nothing
|
|
528
|
+
// about the target, and checking the target first would leak it through the
|
|
529
|
+
// choice of refusal.
|
|
530
|
+
if (stored.owner.kind !== owner.kind || stored.owner.id !== owner.id) {
|
|
531
|
+
throw new StartReservationOwnerMismatchError(key);
|
|
532
|
+
}
|
|
533
|
+
if (stored.targetKind !== request.targetKind ||
|
|
534
|
+
stored.targetId !== request.targetId) {
|
|
535
|
+
throw new StartReservationTargetMismatchError(key, stored);
|
|
536
|
+
}
|
|
537
|
+
// Both signals must agree before this caller believes it created the row.
|
|
538
|
+
// `changes` alone would trust the adapter's bookkeeping; the id comparison
|
|
539
|
+
// alone would trust that two mints never collide. Requiring both makes the
|
|
540
|
+
// false answer the SAFE one — a creator misread as a replayer takes the
|
|
541
|
+
// replay path and converges, while the reverse would start a second run.
|
|
542
|
+
return {
|
|
543
|
+
reservation: stored,
|
|
544
|
+
created: inserted > 0 && stored.runId === candidateRunId,
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Take the claim: `reserved` -> `started`, for this exact run.
|
|
549
|
+
*
|
|
550
|
+
* ONE conditional UPDATE, and the whole cross-isolate serialization of the
|
|
551
|
+
* feature. Exactly one caller changes a row; every other caller sees zero
|
|
552
|
+
* changes and must go and find out what the winner did rather than starting
|
|
553
|
+
* anything. The `run_id` predicate rides along so a claim can never land on a
|
|
554
|
+
* row that was rewritten underneath it.
|
|
555
|
+
*
|
|
556
|
+
* Never creates the table: a claim can only ever follow a reserve, which did.
|
|
557
|
+
*/
|
|
558
|
+
async claim(key, runId) {
|
|
559
|
+
return this.#casState(key, runId, 'reserved', 'started');
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Give the claim back: `started` -> `reserved`, for this exact run.
|
|
563
|
+
*
|
|
564
|
+
* The ONLY backwards transition, and it exists for exactly one caller: a
|
|
565
|
+
* start the EXECUTION FENCE refused. That refusal is special because it is
|
|
566
|
+
* provably pre-execution — the fence is read before the run lock and before
|
|
567
|
+
* any storage write — so the claim it consumed bought nothing and holding on
|
|
568
|
+
* to it would manufacture an UNRESOLVABLE reservation out of an operator
|
|
569
|
+
* action. Leaving the claim taken would mean a deployment that drained,
|
|
570
|
+
* migrated, and reopened had permanently poisoned every key that happened to
|
|
571
|
+
* be in flight.
|
|
572
|
+
*
|
|
573
|
+
* It is deliberately NOT used for other start failures. Anything that reached
|
|
574
|
+
* the runtime's execution path may have taken effect, and a rollback there
|
|
575
|
+
* would hand the next retry a fresh run — the exact double-charge this whole
|
|
576
|
+
* module exists to prevent.
|
|
577
|
+
*/
|
|
578
|
+
async release(key, runId) {
|
|
579
|
+
return this.#casState(key, runId, 'started', 'reserved');
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Terminal reconcile, keyed by RUN rather than by key: the runtime observes a
|
|
583
|
+
* run reaching a terminal state and has no idea which key (if any) named it.
|
|
584
|
+
*
|
|
585
|
+
* Idempotent by construction (`state <> 'terminal'`), so the several places a
|
|
586
|
+
* run can reach terminal — completing, failing, being cancelled, timing out —
|
|
587
|
+
* can all call it without coordinating, and a re-entry after a crash is a
|
|
588
|
+
* no-op rather than a conflict.
|
|
589
|
+
*
|
|
590
|
+
* Returns the number of reservations settled, which is 0 for the overwhelming
|
|
591
|
+
* majority of runs (nobody used a key) and 1 for the rest.
|
|
592
|
+
*/
|
|
593
|
+
async settleRun(runId) {
|
|
594
|
+
if (!isPathSafeId(runId))
|
|
595
|
+
return 0;
|
|
596
|
+
try {
|
|
597
|
+
return changesOf(await this.#db
|
|
598
|
+
.prepare(`UPDATE ${START_IDEMPOTENCY_TABLE}
|
|
599
|
+
SET state = 'terminal', updated_at = ?
|
|
600
|
+
WHERE run_id = ? AND state <> 'terminal'`)
|
|
601
|
+
.bind(this.#now(), runId)
|
|
602
|
+
.run());
|
|
603
|
+
}
|
|
604
|
+
catch (error) {
|
|
605
|
+
// A database with no reservation table has no reservation to settle. Any
|
|
606
|
+
// other fault is real and must not be mistaken for "nothing to do".
|
|
607
|
+
if (isMissingReservationTable(error))
|
|
608
|
+
return 0;
|
|
609
|
+
throw new StartReservationUnreadableError(runId, { cause: error });
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Read one reservation. A PURE read: no lazy DDL, no upsert, nothing that
|
|
614
|
+
* would make consulting a key mutate the database — which is what lets a
|
|
615
|
+
* read-only drain inventory and every replay path use it freely, and what
|
|
616
|
+
* keeps a read-only replica or a revoked-write incident a degrade rather than
|
|
617
|
+
* an outage.
|
|
618
|
+
*
|
|
619
|
+
* An absent TABLE reads as an absent reservation, because on a deployment
|
|
620
|
+
* where no key has ever been used those are the same fact.
|
|
621
|
+
*/
|
|
622
|
+
async read(key) {
|
|
623
|
+
const safeKey = assertKey(key);
|
|
624
|
+
let rows;
|
|
625
|
+
try {
|
|
626
|
+
rows = (await this.#db
|
|
627
|
+
.prepare(`SELECT key, owner_kind, owner_id, target_kind, target_id, run_id,
|
|
628
|
+
thread_id, state, created_at, updated_at
|
|
629
|
+
FROM ${START_IDEMPOTENCY_TABLE} WHERE key = ?`)
|
|
630
|
+
.bind(safeKey)
|
|
631
|
+
.all()).results;
|
|
632
|
+
}
|
|
633
|
+
catch (error) {
|
|
634
|
+
if (isMissingReservationTable(error))
|
|
635
|
+
return undefined;
|
|
636
|
+
throw new StartReservationUnreadableError(safeKey, { cause: error });
|
|
637
|
+
}
|
|
638
|
+
const row = rows[0];
|
|
639
|
+
return row === undefined ? undefined : reservationFromRow(row);
|
|
640
|
+
}
|
|
641
|
+
/** Create the table and its two access paths. Only `reserve()` reaches this. */
|
|
642
|
+
async #createSchema() {
|
|
643
|
+
await this.#db.prepare(START_IDEMPOTENCY_DDL).run();
|
|
644
|
+
await this.#db.prepare(START_IDEMPOTENCY_RUN_INDEX_DDL).run();
|
|
645
|
+
await this.#db.prepare(START_IDEMPOTENCY_STATE_INDEX_DDL).run();
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Every reservation naming one of these runs, for the purge and the
|
|
649
|
+
* inventory. Chunked by the caller; this method binds exactly what it is
|
|
650
|
+
* given, so a caller must respect D1's 100-parameter statement limit.
|
|
651
|
+
*/
|
|
652
|
+
async reservationsForRuns(runIds) {
|
|
653
|
+
const safeRunIds = runIds.filter((runId) => isPathSafeId(runId));
|
|
654
|
+
if (safeRunIds.length === 0)
|
|
655
|
+
return [];
|
|
656
|
+
const placeholders = safeRunIds.map(() => '?').join(', ');
|
|
657
|
+
let rows;
|
|
658
|
+
try {
|
|
659
|
+
rows = (await this.#db
|
|
660
|
+
.prepare(`SELECT key, owner_kind, owner_id, target_kind, target_id, run_id,
|
|
661
|
+
thread_id, state, created_at, updated_at
|
|
662
|
+
FROM ${START_IDEMPOTENCY_TABLE} WHERE run_id IN (${placeholders})`)
|
|
663
|
+
.bind(...safeRunIds)
|
|
664
|
+
.all()).results;
|
|
665
|
+
}
|
|
666
|
+
catch (error) {
|
|
667
|
+
if (isMissingReservationTable(error))
|
|
668
|
+
return [];
|
|
669
|
+
throw new StartReservationUnreadableError('(run lookup)', {
|
|
670
|
+
cause: error,
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
return rows.map((row) => reservationFromRow(row));
|
|
674
|
+
}
|
|
675
|
+
async #casState(key, runId, from, to) {
|
|
676
|
+
const safeKey = assertKey(key);
|
|
677
|
+
if (!isPathSafeId(runId)) {
|
|
678
|
+
throw new InvalidStartIdempotencyRequestError('reservation runId must be a URL-path-safe identifier');
|
|
679
|
+
}
|
|
680
|
+
try {
|
|
681
|
+
return (changesOf(await this.#db
|
|
682
|
+
.prepare(`UPDATE ${START_IDEMPOTENCY_TABLE}
|
|
683
|
+
SET state = ?, updated_at = ?
|
|
684
|
+
WHERE key = ? AND run_id = ? AND state = ?`)
|
|
685
|
+
.bind(to, this.#now(), safeKey, runId, from)
|
|
686
|
+
.run()) > 0);
|
|
687
|
+
}
|
|
688
|
+
catch (error) {
|
|
689
|
+
// No table means no reservation, so no transition happened — which is
|
|
690
|
+
// exactly what `false` says, and the caller's replay path handles it.
|
|
691
|
+
if (isMissingReservationTable(error))
|
|
692
|
+
return false;
|
|
693
|
+
throw new StartReservationUnreadableError(safeKey, { cause: error });
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* Resolve an idempotency key into "start this run" or "replay that one".
|
|
699
|
+
*
|
|
700
|
+
* The order of the checks below IS the semantics:
|
|
701
|
+
*
|
|
702
|
+
* 1. Reserve. A brand-new key that also wins the claim is the only path that
|
|
703
|
+
* starts anything.
|
|
704
|
+
* 2. Persisted state, BEFORE the reservation's own state. A run that persisted
|
|
705
|
+
* is answerable whatever the reservation says, and reading the row's state
|
|
706
|
+
* first would let a stale `started` refuse a retry whose run is sitting
|
|
707
|
+
* right there, finished.
|
|
708
|
+
* 3. `reserved` with nothing persisted means the first caller died between the
|
|
709
|
+
* insert and the claim, having executed nothing — so this caller may take
|
|
710
|
+
* the claim and proceed with the SAME runId. That convergence is what makes
|
|
711
|
+
* a crashed reservation self-healing instead of a wedged key.
|
|
712
|
+
* 4. `started` with nothing persisted is the only ambiguous state in the
|
|
713
|
+
* system, and the liveness probe is what resolves it.
|
|
714
|
+
* 5. `terminal` with nothing persisted is a completed run whose summary aged
|
|
715
|
+
* out. Spent, never re-run.
|
|
716
|
+
*
|
|
717
|
+
* Throws the applicable structured taxonomy errors; a surface renders them
|
|
718
|
+
* through `doErrorResponse` (or its router's equivalent) with no re-mapping.
|
|
719
|
+
* Across the public keyed-start surface the eight codes are the five decision
|
|
720
|
+
* refusals — IDEMPOTENT_START_OWNER_MISMATCH (403),
|
|
721
|
+
* IDEMPOTENT_START_TARGET_MISMATCH (409), IDEMPOTENT_START_PENDING
|
|
722
|
+
* (503), IDEMPOTENT_START_UNRESOLVABLE (409), and
|
|
723
|
+
* IDEMPOTENT_START_ALREADY_SETTLED (409) — plus IDEMPOTENT_START_UNSUPPORTED
|
|
724
|
+
* (503), INVALID_START_IDEMPOTENCY_REQUEST (400), and
|
|
725
|
+
* IDEMPOTENT_START_UNREADABLE (503).
|
|
726
|
+
*/
|
|
727
|
+
export async function beginIdempotentStart(store, request, surface, fence) {
|
|
728
|
+
const { reservation, created } = await store.reserve(request);
|
|
729
|
+
if (created && (await store.claim(reservation.key, reservation.runId))) {
|
|
730
|
+
return { kind: 'start', reservation };
|
|
731
|
+
}
|
|
732
|
+
const decision = await resolveExistingReservation(store, reservation, surface);
|
|
733
|
+
if (decision.kind === 'replay') {
|
|
734
|
+
await rebindProofRun(fence, decision.reservation);
|
|
735
|
+
}
|
|
736
|
+
return decision;
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Re-assert a proof-only fence's binding to the run this key already made.
|
|
740
|
+
*
|
|
741
|
+
* The binding is written by `RunnerRuntime.start`, which a REPLAY never
|
|
742
|
+
* reaches — so without this, a proof run whose fence lost its `proof_run_id`
|
|
743
|
+
* (the fence was moved away and back onto the same key while its run survived)
|
|
744
|
+
* would be a run the deployment can read but can no longer RESUME: proof-only
|
|
745
|
+
* admits existing work only for `proof_run_id`, and there would be none.
|
|
746
|
+
*
|
|
747
|
+
* Every guard lives in `recordProofRun`'s own CAS, which is why this can be
|
|
748
|
+
* unconditional and best-effort: it changes nothing unless the fence is in
|
|
749
|
+
* proof-only under EXACTLY this key with the slot empty or already holding this
|
|
750
|
+
* run. A different key, a different state, a different proof run — all are zero
|
|
751
|
+
* rows and no harm. A failure is swallowed rather than raised, because the
|
|
752
|
+
* caller is being handed the persisted state of a run that already happened,
|
|
753
|
+
* and refusing that read would answer a successful retry with an error while
|
|
754
|
+
* changing nothing about the run.
|
|
755
|
+
*/
|
|
756
|
+
async function rebindProofRun(fence, reservation) {
|
|
757
|
+
if (fence === undefined || fence === 'none')
|
|
758
|
+
return;
|
|
759
|
+
try {
|
|
760
|
+
// The reservation KEY is passed as the fence's PROOF KEY: proof-only
|
|
761
|
+
// nominates one idempotency key, and `admitsRunStart` admits the start
|
|
762
|
+
// carrying it — so the two identifiers are the same string by construction,
|
|
763
|
+
// and a rebind for any other key is the zero-row no-op described above.
|
|
764
|
+
await fence.recordProofRun(reservation.key, reservation.runId);
|
|
765
|
+
}
|
|
766
|
+
catch (error) {
|
|
767
|
+
console.error(JSON.stringify({
|
|
768
|
+
type: 'start-reservation-proof-rebind-failed',
|
|
769
|
+
key: reservation.key,
|
|
770
|
+
runId: reservation.runId,
|
|
771
|
+
error: error instanceof Error ? error.message : String(error),
|
|
772
|
+
}));
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
async function resolveExistingReservation(store, observed, surface) {
|
|
776
|
+
const persisted = await surface.persisted(observed);
|
|
777
|
+
if (persisted !== undefined) {
|
|
778
|
+
return { kind: 'replay', reservation: observed, persisted };
|
|
779
|
+
}
|
|
780
|
+
if (observed.state === 'reserved') {
|
|
781
|
+
if (await store.claim(observed.key, observed.runId)) {
|
|
782
|
+
return { kind: 'start', reservation: observed };
|
|
783
|
+
}
|
|
784
|
+
// The claim was taken between the read and here. Re-read rather than
|
|
785
|
+
// assuming: the winner may already have persisted, in which case the right
|
|
786
|
+
// answer is its outcome and not a refusal.
|
|
787
|
+
const current = await store.read(observed.key);
|
|
788
|
+
if (current === undefined || current.runId !== observed.runId) {
|
|
789
|
+
// The reservation vanished or was replaced under us. Refusing is the only
|
|
790
|
+
// safe answer — a caller that retries gets a clean reserve, while
|
|
791
|
+
// silently starting here would start a run under an id nothing reserved.
|
|
792
|
+
throw new StartReservationUnreadableError(observed.key);
|
|
793
|
+
}
|
|
794
|
+
return resolveClaimedReservation(current, surface);
|
|
795
|
+
}
|
|
796
|
+
return resolveClaimedReservation(observed, surface);
|
|
797
|
+
}
|
|
798
|
+
async function resolveClaimedReservation(reservation, surface) {
|
|
799
|
+
if (reservation.state === 'terminal') {
|
|
800
|
+
throw new IdempotentStartAlreadySettledError(reservation);
|
|
801
|
+
}
|
|
802
|
+
if (await surface.live(reservation)) {
|
|
803
|
+
throw new IdempotentStartPendingError(reservation);
|
|
804
|
+
}
|
|
805
|
+
throw new IdempotentStartUnresolvableError(reservation);
|
|
806
|
+
}
|
|
807
|
+
/**
|
|
808
|
+
* Give back a claim that the EXECUTION FENCE refused, then re-throw.
|
|
809
|
+
*
|
|
810
|
+
* Homed here, beside the state machine, rather than written out at each start
|
|
811
|
+
* site: the rollback is only correct for this one error family, and a copy that
|
|
812
|
+
* widened its catch — to "any start failure", say — would hand the next retry a
|
|
813
|
+
* fresh run after a start that may well have executed. Keeping the predicate
|
|
814
|
+
* and the CAS in one function is what stops that widening from being a one-line
|
|
815
|
+
* edit somebody makes in a hurry.
|
|
816
|
+
*
|
|
817
|
+
* THE CLASS INVARIANT THIS RELIES ON. Giving a claim back is only sound for a
|
|
818
|
+
* failure that provably executed NOTHING, and that is a property of the two
|
|
819
|
+
* fence refusal codes rather than of the JavaScript class carrying them:
|
|
820
|
+
*
|
|
821
|
+
* EXECUTION_FENCED is authored at a gate — the run object's start
|
|
822
|
+
* route, before any of its own reads or writes,
|
|
823
|
+
* and `RunnerRuntime.#assertStartFence`, before
|
|
824
|
+
* the run lock and before core mints anything.
|
|
825
|
+
* EXECUTION_FENCE_UNREADABLE is authored by the fence READ that fronts those
|
|
826
|
+
* same gates, which is even earlier.
|
|
827
|
+
*
|
|
828
|
+
* Neither code is reachable from anywhere past the point of execution, so a
|
|
829
|
+
* refusal carrying one is pre-execution wherever it was observed.
|
|
830
|
+
*
|
|
831
|
+
* Which is why the predicate is `isExecutionFenceRefusal` — the widened one,
|
|
832
|
+
* which admits the wire rebuild — and NOT `instanceof ExecutionFencedError`.
|
|
833
|
+
* Both of this function's callers sit on the far side of a Durable Object
|
|
834
|
+
* boundary in every DO-backed host: the run object throws, `doErrorResponse`
|
|
835
|
+
* renders, and `doSummary` (or the agent topology's `errorFrom`) rebuilds a
|
|
836
|
+
* `RunRouteError` carrying the same status and the same structured reason but
|
|
837
|
+
* not the same class. An instanceof-only test would answer "not a fence
|
|
838
|
+
* refusal" for exactly the deployments this rollback exists to protect, and a
|
|
839
|
+
* drained-then-reopened deployment would find every key that was in flight
|
|
840
|
+
* permanently stuck at UNRESOLVABLE. In-process hosts (a `{ storage }` runtime
|
|
841
|
+
* wired straight into the router) do throw the class, so both shapes are live
|
|
842
|
+
* and one predicate has to cover them.
|
|
843
|
+
*
|
|
844
|
+
* The rollback itself is best-effort: it runs while the deployment is already
|
|
845
|
+
* refusing to execute, so its own failure must not replace the fence's refusal
|
|
846
|
+
* with a storage error the caller cannot act on. A rollback that does not land
|
|
847
|
+
* leaves an UNRESOLVABLE reservation — recoverable by investigation — while a
|
|
848
|
+
* swallowed fence refusal would leave the caller believing the deployment is
|
|
849
|
+
* broken rather than fenced.
|
|
850
|
+
*/
|
|
851
|
+
export async function rollbackFencedStart(store, key, runId, error) {
|
|
852
|
+
if (isExecutionFenceRefusal(error)) {
|
|
853
|
+
try {
|
|
854
|
+
await store.release(key, runId);
|
|
855
|
+
}
|
|
856
|
+
catch (rollbackError) {
|
|
857
|
+
console.error(JSON.stringify({
|
|
858
|
+
type: 'start-reservation-rollback-failed',
|
|
859
|
+
key,
|
|
860
|
+
runId,
|
|
861
|
+
error: rollbackError instanceof Error
|
|
862
|
+
? rollbackError.message
|
|
863
|
+
: String(rollbackError),
|
|
864
|
+
}));
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
throw error;
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Resolve a surface's reservation wiring, refusing a key the host cannot
|
|
871
|
+
* honour.
|
|
872
|
+
*
|
|
873
|
+
* `undefined` is admitted alongside `'none'` for the same reason
|
|
874
|
+
* `readExecutionFence` admits it — a wiring that arrives through an object the
|
|
875
|
+
* host may not have populated — and means the same thing: no store. What it
|
|
876
|
+
* does NOT mean is "ignore the key", which is why this throws rather than
|
|
877
|
+
* returning undefined. A start carrying an idempotency key onto an unwired
|
|
878
|
+
* deployment is a request this host cannot answer truthfully.
|
|
879
|
+
*/
|
|
880
|
+
export function requireStartIdempotency(wiring) {
|
|
881
|
+
if (wiring === undefined || wiring === 'none') {
|
|
882
|
+
throw new StartIdempotencyUnsupportedError();
|
|
883
|
+
}
|
|
884
|
+
return wiring;
|
|
885
|
+
}
|
|
886
|
+
//# sourceMappingURL=start-idempotency.js.map
|