@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,811 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// The deployment drain inventory — the read an operator holds a fence open on
|
|
3
|
+
// while they prove this deployment is safe to leave behind.
|
|
4
|
+
//
|
|
5
|
+
// WHY it exists. The fence (execution-fence.ts) can stop a deployment minting
|
|
6
|
+
// work, but stopping is not finishing. A migration only becomes safe at the
|
|
7
|
+
// moment nobody can point at a run, an approval, a queued task, or a due
|
|
8
|
+
// dispatch that this deployment still owes. Before this module the only way to
|
|
9
|
+
// answer that was to name the tables you happened to remember and count them by
|
|
10
|
+
// hand — an answer whose failure mode is silence: a table nobody thought of
|
|
11
|
+
// holds a suspended run, the migration proceeds, and two deployments resume it.
|
|
12
|
+
//
|
|
13
|
+
// THE TAXONOMY IS THE CONTRACT, and completeness is the product. What is sold
|
|
14
|
+
// here is not a set of queries; it is the claim that these queries are ALL of
|
|
15
|
+
// them. That claim cannot be maintained by care, so it is maintained by the
|
|
16
|
+
// census: `FLOWSAFE_TABLES` below maps every flowsafe-owned table to either an
|
|
17
|
+
// inventory category or a written reason it holds no work, and the census test
|
|
18
|
+
// (do-runner/mastra-schema-guard.test.ts) fails CI when a table — ours or a new
|
|
19
|
+
// one arriving with a @mastra/core bump — appears in neither list. A future
|
|
20
|
+
// author adding a work-holding table therefore cannot ship it silently: they
|
|
21
|
+
// must either inventory it or state, in more than twenty characters, why an
|
|
22
|
+
// operator draining a deployment may ignore it. The guarantee an operator reads
|
|
23
|
+
// off an empty inventory is only ever as good as that obligation.
|
|
24
|
+
//
|
|
25
|
+
// TWO CLASSES, because a drain proof defined over everything can never pass.
|
|
26
|
+
// `work` is what must reach empty: runs, approvals awaiting a decision, queued
|
|
27
|
+
// tasks, due dispatches, unsettled reservations. `standing` is configuration
|
|
28
|
+
// that ARMS future work — schedules, provider subscriptions — and by design it
|
|
29
|
+
// never empties; a deployment with three cron schedules is drainable, and
|
|
30
|
+
// demanding otherwise would make the proof unreachable rather than strict.
|
|
31
|
+
//
|
|
32
|
+
// ZERO SIDE EFFECTS, MECHANICALLY. Every read here is a bare SELECT. Nothing
|
|
33
|
+
// calls `#ensureSchema`, because a lazy `CREATE TABLE IF NOT EXISTS` is a WRITE
|
|
34
|
+
// and the whole value of this surface is that an operator can run it against a
|
|
35
|
+
// deployment they are about to copy without changing what they are copying. A
|
|
36
|
+
// missing table is not a fault but an empty category (`missingTableReadsEmpty`,
|
|
37
|
+
// shared with the fence and the reservation store) — every table here is
|
|
38
|
+
// created lazily by the first feature that uses it, so "absent" and "holds
|
|
39
|
+
// nothing" are the same sentence. The database seam this module accepts
|
|
40
|
+
// (`InventoryDatabase`) deliberately has no `run()`: the read-only property is
|
|
41
|
+
// in the TYPE, not only in the review.
|
|
42
|
+
//
|
|
43
|
+
// WHY NOT REUSE THE EXISTING READERS. Every domain already has a list method —
|
|
44
|
+
// `statusFor`, the run-router's GET, `manager.listTasks`, the schedule store's
|
|
45
|
+
// `listTriggers`. None of them is usable here, and not for style reasons: each
|
|
46
|
+
// either initializes schema on the way in, or advances a cursor, or reaches a
|
|
47
|
+
// Durable Object that would wake and re-arm an alarm. An inventory built on
|
|
48
|
+
// them would perturb the very deployment it is measuring. So the queries below
|
|
49
|
+
// are new and pure, and each one's predicate is derived from the production
|
|
50
|
+
// reader or purge that owns the same notion — the terminal-run SQL is literally
|
|
51
|
+
// the retention purge's fragment, the due-notification predicate is
|
|
52
|
+
// `listDueNotifications`'s, the deferred-dispatch predicate is the schedule
|
|
53
|
+
// store's own dispatch guard — so "finished" cannot come to mean one thing to
|
|
54
|
+
// the code that acts and another to the code that certifies.
|
|
55
|
+
import { DEPLOYMENT_SENTINEL_TABLE, EXECUTION_FENCE_TABLE, } from '#deployment-identity-protocol';
|
|
56
|
+
import { APPROVALS_TABLE, OPEN_STATUSES } from '../approval-api/types.js';
|
|
57
|
+
import { missingTableReadsEmpty } from './cause-chain.js';
|
|
58
|
+
import { BACKGROUND_TASK_TERMINAL_STATUSES, RESOURCE_OWNER_TABLE, RUN_TERMINAL_SNAPSHOT_SQL, RUN_TERMINAL_STATUSES, } from './d1-storage.js';
|
|
59
|
+
import { DoStatusError } from './do-status-error.js';
|
|
60
|
+
import { EXECUTION_FENCE_SUSPEND_KEY, } from './execution-fence.js';
|
|
61
|
+
import { DUE_NOTIFICATION_SQL } from './notification-predicate.js';
|
|
62
|
+
import { START_IDEMPOTENCY_TABLE, START_RESERVATION_STATES, } from './start-idempotency.js';
|
|
63
|
+
import { validateTablePrefix } from './table-prefix.js';
|
|
64
|
+
/**
|
|
65
|
+
* The Mastra-owned tables this module reads, spelled here because they belong
|
|
66
|
+
* to a layer this file may not import from.
|
|
67
|
+
*
|
|
68
|
+
* `mastra_schedules` and `mastra_schedule_triggers` are created by
|
|
69
|
+
* `schedules/schedules-d1.ts`, and `mastra_notifications` by
|
|
70
|
+
* `signals/notifications-d1.ts` — both of which are built ON do-runner, so
|
|
71
|
+
* importing their storage modules would close a cycle and pull their runtime
|
|
72
|
+
* dependencies into the public `./do-runner` graph. The pending-notification
|
|
73
|
+
* predicate is therefore single-homed in the import-free
|
|
74
|
+
* `do-runner/notification-predicate.ts` leaf, which both readers can safely
|
|
75
|
+
* import. The census test can see both sides at once, and crosses every name
|
|
76
|
+
* below against the storage inventory the schema guard pins, so a rename fails
|
|
77
|
+
* there rather than turning a category permanently empty.
|
|
78
|
+
* `mastra_workflow_snapshot` and `mastra_background_tasks` come from the
|
|
79
|
+
* @mastra/cloudflare-d1 adapter and are pinned the same way.
|
|
80
|
+
*/
|
|
81
|
+
const SNAPSHOT_TABLE = 'mastra_workflow_snapshot';
|
|
82
|
+
const BACKGROUND_TASKS_TABLE = 'mastra_background_tasks';
|
|
83
|
+
const NOTIFICATIONS_TABLE = 'mastra_notifications';
|
|
84
|
+
const SCHEDULES_TABLE = 'mastra_schedules';
|
|
85
|
+
const SCHEDULE_TRIGGERS_TABLE = 'mastra_schedule_triggers';
|
|
86
|
+
/**
|
|
87
|
+
* The subscription registry's table. Same reason as the block above:
|
|
88
|
+
* `signal-providers/subscription-d1.ts` imports do-runner, so the name travels
|
|
89
|
+
* to the census rather than to this file.
|
|
90
|
+
*/
|
|
91
|
+
const SIGNAL_SUBSCRIPTIONS_INVENTORY_TABLE = 'flowsafe_signal_subscriptions';
|
|
92
|
+
/**
|
|
93
|
+
* Every category name, in the order the index reports them: work first, then
|
|
94
|
+
* standing.
|
|
95
|
+
*/
|
|
96
|
+
export const INVENTORY_CATEGORIES = [
|
|
97
|
+
'runs',
|
|
98
|
+
'approvals-waiting',
|
|
99
|
+
'schedule-deferred-dispatches',
|
|
100
|
+
'pending-notifications',
|
|
101
|
+
'background-tasks',
|
|
102
|
+
'resource-owners',
|
|
103
|
+
'start-reservations',
|
|
104
|
+
'schedules',
|
|
105
|
+
'signal-subscriptions',
|
|
106
|
+
];
|
|
107
|
+
/**
|
|
108
|
+
* THE FLOWSAFE TABLE CENSUS. Every `flowsafe_`-prefixed table this package
|
|
109
|
+
* creates, mapped to an inventory category or to a justified exclusion.
|
|
110
|
+
*
|
|
111
|
+
* It exists because the schema guard's `mastra_%` sweep cannot see these: they
|
|
112
|
+
* are not created by `createD1Storage`, and two of them (the deployment
|
|
113
|
+
* sentinel and the fence) are created by the provisioning protocol before any
|
|
114
|
+
* runtime code runs. Without an explicit list, a flowsafe table holding
|
|
115
|
+
* suspended work could be added, purged, documented, and shipped without ever
|
|
116
|
+
* meeting the question this module exists to answer.
|
|
117
|
+
*
|
|
118
|
+
* ADDING A TABLE: add it here in the same change. The census test fails until
|
|
119
|
+
* you do, and it fails again if you claim an exclusion in fewer than twenty
|
|
120
|
+
* characters.
|
|
121
|
+
*/
|
|
122
|
+
export const FLOWSAFE_TABLES = [
|
|
123
|
+
{
|
|
124
|
+
table: APPROVALS_TABLE,
|
|
125
|
+
purpose: 'the durable approval queue — one record per suspended decision',
|
|
126
|
+
accounting: { category: 'approvals-waiting' },
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
table: DEPLOYMENT_SENTINEL_TABLE,
|
|
130
|
+
purpose: 'the ownership sentinel naming the tenant this database belongs to',
|
|
131
|
+
accounting: {
|
|
132
|
+
excluded: 'deployment identity, not work: one row written once at provisioning, read to prove the bindings match the database. It is COPIED by a migration, never drained.',
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
{
|
|
136
|
+
table: EXECUTION_FENCE_TABLE,
|
|
137
|
+
purpose: 'the deployment execution fence — one row holding its state',
|
|
138
|
+
accounting: {
|
|
139
|
+
excluded: 'the control this inventory is read under. Its single row is the instrument, not a measurement: counting it would make every drain proof fail on the fence that is holding the drain open.',
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
table: 'flowsafe_notification_sequence',
|
|
144
|
+
purpose: 'the monotonic insertion ordinal the notification inbox orders by',
|
|
145
|
+
accounting: {
|
|
146
|
+
excluded: 'a single counter row, not a unit of work. The notifications it orders are inventoried under pending-notifications; the counter itself has nothing to finish and is re-derivable from the inbox.',
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
table: RESOURCE_OWNER_TABLE,
|
|
151
|
+
purpose: 'the resource-ownership registry — who holds a run, thread, resource, or schedule',
|
|
152
|
+
accounting: { category: 'resource-owners' },
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
table: SIGNAL_SUBSCRIPTIONS_INVENTORY_TABLE,
|
|
156
|
+
purpose: 'armed provider subscriptions routing external signals to threads',
|
|
157
|
+
accounting: { category: 'signal-subscriptions' },
|
|
158
|
+
},
|
|
159
|
+
{
|
|
160
|
+
table: START_IDEMPOTENCY_TABLE,
|
|
161
|
+
purpose: 'owner-bound start reservations — one row per idempotency key',
|
|
162
|
+
accounting: { category: 'start-reservations' },
|
|
163
|
+
},
|
|
164
|
+
];
|
|
165
|
+
/** The largest page an inventory read will return, whatever `limit` asks for. */
|
|
166
|
+
export const INVENTORY_MAX_LIMIT = 200;
|
|
167
|
+
/** The page size used when `limit` is absent. */
|
|
168
|
+
export const INVENTORY_DEFAULT_LIMIT = 100;
|
|
169
|
+
/** Longest `cursor` string accepted, before it is parsed. */
|
|
170
|
+
const MAX_CURSOR_LENGTH = 1_024;
|
|
171
|
+
/**
|
|
172
|
+
* Bound parameters D1 accepts in ONE statement. The retention purge caps its
|
|
173
|
+
* own batch against the same limit (d1-storage.ts).
|
|
174
|
+
*/
|
|
175
|
+
export const D1_MAX_BOUND_PARAMETERS = 100;
|
|
176
|
+
/**
|
|
177
|
+
* Bound parameters the run-owner lookup spends on anything OTHER than run ids.
|
|
178
|
+
*
|
|
179
|
+
* Zero today: `resource_kind = 'run'` is a SQL literal, not a bind. It is named
|
|
180
|
+
* rather than assumed because the slice size below is `cap - this`, and a
|
|
181
|
+
* future predicate that binds a value would otherwise push the statement one
|
|
182
|
+
* parameter over the limit with nothing to catch it.
|
|
183
|
+
*/
|
|
184
|
+
export const RUN_OWNER_FIXED_BINDINGS = 0;
|
|
185
|
+
/**
|
|
186
|
+
* Run ids per owner-lookup statement: the full parameter budget, less whatever
|
|
187
|
+
* the statement spends on its own predicate. 100 - 0 = 100, so a maximum page
|
|
188
|
+
* (INVENTORY_MAX_LIMIT = 200) costs exactly two statements.
|
|
189
|
+
*/
|
|
190
|
+
export const RUN_OWNER_LOOKUP_CHUNK = D1_MAX_BOUND_PARAMETERS - RUN_OWNER_FIXED_BINDINGS;
|
|
191
|
+
/**
|
|
192
|
+
* A malformed inventory request: an unknown category, an unparseable cursor, or
|
|
193
|
+
* a cursor whose shape does not match the category it was sent to.
|
|
194
|
+
*
|
|
195
|
+
* 400 rather than a silent restart from the beginning. A cursor that quietly
|
|
196
|
+
* resets would make a sweep re-read rows it had already counted and never
|
|
197
|
+
* reach the end, and an operator watching for two consecutive empty sweeps
|
|
198
|
+
* would wait forever without being told why.
|
|
199
|
+
*/
|
|
200
|
+
export class InvalidInventoryRequestError extends DoStatusError {
|
|
201
|
+
status = 400;
|
|
202
|
+
reason;
|
|
203
|
+
constructor(message) {
|
|
204
|
+
super(message);
|
|
205
|
+
this.name = 'InvalidInventoryRequestError';
|
|
206
|
+
this.reason = { code: 'INVALID_INVENTORY_REQUEST' };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/** Is this a category the inventory serves? */
|
|
210
|
+
export function isInventoryCategory(value) {
|
|
211
|
+
return INVENTORY_CATEGORIES.includes(value);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* The state a pure D1 query cannot see, declared rather than omitted.
|
|
215
|
+
*
|
|
216
|
+
* THE SWEEP BEHIND THIS LIST. Every key a Durable Object in this package writes
|
|
217
|
+
* was checked against the categories above, and all but one is backed by a row
|
|
218
|
+
* a query here already returns:
|
|
219
|
+
*
|
|
220
|
+
* `flowsafe:run-owner-recovery:v1` — DECLARED below. It is written BEFORE the
|
|
221
|
+
* D1 owner row, so a crash between the two leaves a run with no D1 record at
|
|
222
|
+
* all.
|
|
223
|
+
*
|
|
224
|
+
* `flowsafe:agent-thread-binding:v1` / `flowsafe:agent-run:v1:*` — a thread's
|
|
225
|
+
* binding to its agent run and that run's own state. Both name a run whose
|
|
226
|
+
* ownership is RESERVED in D1 BEFORE execution begins
|
|
227
|
+
* (agent-host/thread-host.ts, durable-object.ts) and settled only AFTER a
|
|
228
|
+
* summary has persisted. The engine also writes a `running` snapshot as the
|
|
229
|
+
* run starts, so an executing run is normally reported under `runs` on its own
|
|
230
|
+
* — but that snapshot lands INSIDE `runtime.start`, after the reservation, and
|
|
231
|
+
* the unsettled reservation is what covers the gap between the two as well as
|
|
232
|
+
* any later moment the snapshot is behind the run. `resource-owners` is a WORK
|
|
233
|
+
* category for exactly that reason: an unsettled reservation means a start
|
|
234
|
+
* that has not durably settled, whatever the snapshot currently says.
|
|
235
|
+
* (Pinned behaviourally by inventory.test.ts's ownership-ordering test, which
|
|
236
|
+
* fails if settlement ever moves ahead of the persisted summary.)
|
|
237
|
+
*
|
|
238
|
+
* `flowsafe:suspension-deadline:v1` — an armed wake for a run that is
|
|
239
|
+
* suspended, and therefore nonterminal, and therefore under `runs`.
|
|
240
|
+
*
|
|
241
|
+
* `flowsafe:maintenance-health:v1`, `flowsafe:maintenance-nonces:v1`,
|
|
242
|
+
* `flowsafe:maintenance-deadline-cursor:v1` — the maintenance object's own
|
|
243
|
+
* health, replay protection, and scan position. None is a unit of work: they
|
|
244
|
+
* describe the sweeper, not what it sweeps.
|
|
245
|
+
*/
|
|
246
|
+
export const INVENTORY_UNENUMERABLE = [
|
|
247
|
+
{
|
|
248
|
+
name: 'run-owner-recovery-journal',
|
|
249
|
+
holds: 'a run whose Durable Object journalled its recovery key but had not yet written its D1 owner row',
|
|
250
|
+
because: 'the journal lives in the run object own storage; D1 has no row for it yet, so no query over this database can observe it',
|
|
251
|
+
bound: '60,000 ms (60 seconds), the RUN_OWNER_RECOVERY_DELAY_MS cadence in do-runner/durable-object.ts: the object reconciles the journal on its next wake, after which the run appears under `runs` (or has finished). Two sweeps at least that far apart therefore cover the window.',
|
|
252
|
+
},
|
|
253
|
+
{
|
|
254
|
+
name: 'persisted-idle-signals',
|
|
255
|
+
holds: 'signals a draining deployment persisted instead of waking a run for',
|
|
256
|
+
because: 'a persisted signal is written into agent MEMORY as a message, carrying no consumption marker any predicate could test — it is indistinguishable, in storage, from ordinary conversation history',
|
|
257
|
+
bound: 'none is needed: these are deliberately NOT drainable. The fence degrades an idle wake to a persist precisely so the signal survives the migration and is picked up by the deployment that takes over, so an operator must not wait for them to disappear.',
|
|
258
|
+
},
|
|
259
|
+
];
|
|
260
|
+
/**
|
|
261
|
+
* The rule that turns inventory readings into a decision.
|
|
262
|
+
*
|
|
263
|
+
* Stated in the index response, and repeated in the route doc, because every
|
|
264
|
+
* dangerous use of this surface is a use that skips it: one empty sweep is not
|
|
265
|
+
* a proof, and an empty sweep taken under `migration-locked` is not even a
|
|
266
|
+
* measurement of a drain.
|
|
267
|
+
*/
|
|
268
|
+
export const INVENTORY_DRAIN_PROOF = {
|
|
269
|
+
reading: 'Every reading is a point-in-time observation, not a snapshot: rows can enter or leave work categories while draining admits work. Empty results cannot over-count, and keyset pagination never skips a row that existed before the sweep started.',
|
|
270
|
+
proof: 'The proof is TWO consecutive full sweeps, at least 60,000 ms (60 seconds) apart — the RUN_OWNER_RECOVERY_DELAY_MS cadence in do-runner/durable-object.ts — in which every `work` category returns no entries. One sweep cannot cover the Durable Object journal window; two, spaced that far, can.',
|
|
271
|
+
reachableFrom: ['draining'],
|
|
272
|
+
note: "The two-sweep proof is taken from 'draining', where work can finish. A host that needs a hard guarantee can re-sweep once after transitioning to 'migration-locked': an empty post-lock sweep is conclusive; a non-empty one means work is still outstanding, either because it entered after the proof or because the lock parked it before it finished. Return to draining and repeat the proof. An inventory read taken under 'migration-locked' measures what the fence parked rather than what the deployment would otherwise be doing.",
|
|
273
|
+
};
|
|
274
|
+
/** Every category's descriptor, in index order. */
|
|
275
|
+
export const INVENTORY_CATEGORY_DESCRIPTORS = [
|
|
276
|
+
{
|
|
277
|
+
category: 'runs',
|
|
278
|
+
class: 'work',
|
|
279
|
+
table: SNAPSHOT_TABLE,
|
|
280
|
+
holds: 'a workflow or agent run that has not reached a terminal state (cancelled and timed_out count as live until their lifecycle cleanup completes)',
|
|
281
|
+
},
|
|
282
|
+
{
|
|
283
|
+
category: 'approvals-waiting',
|
|
284
|
+
class: 'work',
|
|
285
|
+
table: APPROVALS_TABLE,
|
|
286
|
+
holds: 'an approval still awaiting a decision — pending, claimed, or escalated',
|
|
287
|
+
},
|
|
288
|
+
{
|
|
289
|
+
category: 'schedule-deferred-dispatches',
|
|
290
|
+
class: 'work',
|
|
291
|
+
table: SCHEDULE_TRIGGERS_TABLE,
|
|
292
|
+
holds: 'a schedule fire that was claimed and deferred but never dispatched; settled fire history in the same table is excluded',
|
|
293
|
+
},
|
|
294
|
+
{
|
|
295
|
+
category: 'pending-notifications',
|
|
296
|
+
class: 'work',
|
|
297
|
+
table: NOTIFICATIONS_TABLE,
|
|
298
|
+
holds: 'an agent-inbox notification that is pending and already due for dispatch',
|
|
299
|
+
},
|
|
300
|
+
{
|
|
301
|
+
category: 'background-tasks',
|
|
302
|
+
class: 'work',
|
|
303
|
+
table: BACKGROUND_TASKS_TABLE,
|
|
304
|
+
holds: 'a background task that has not settled — queued, running, or suspended (including parked by the fence)',
|
|
305
|
+
},
|
|
306
|
+
{
|
|
307
|
+
category: 'resource-owners',
|
|
308
|
+
class: 'work',
|
|
309
|
+
table: RESOURCE_OWNER_TABLE,
|
|
310
|
+
holds: 'an ownership reservation that was taken but never settled or released',
|
|
311
|
+
},
|
|
312
|
+
{
|
|
313
|
+
category: 'start-reservations',
|
|
314
|
+
class: 'work',
|
|
315
|
+
table: START_IDEMPOTENCY_TABLE,
|
|
316
|
+
holds: 'an idempotency key that has been reserved or claimed but whose run has not settled',
|
|
317
|
+
},
|
|
318
|
+
{
|
|
319
|
+
category: 'schedules',
|
|
320
|
+
class: 'standing',
|
|
321
|
+
table: SCHEDULES_TABLE,
|
|
322
|
+
holds: 'a schedule that will arm future work — standing configuration a migration carries, never drains',
|
|
323
|
+
},
|
|
324
|
+
{
|
|
325
|
+
category: 'signal-subscriptions',
|
|
326
|
+
class: 'standing',
|
|
327
|
+
table: SIGNAL_SUBSCRIPTIONS_INVENTORY_TABLE,
|
|
328
|
+
holds: 'an armed provider subscription routing an external resource to a thread — carried, not drained',
|
|
329
|
+
},
|
|
330
|
+
];
|
|
331
|
+
/** The whole no-category answer, assembled once. */
|
|
332
|
+
export const INVENTORY_INDEX = {
|
|
333
|
+
categories: INVENTORY_CATEGORY_DESCRIPTORS,
|
|
334
|
+
unenumerable: INVENTORY_UNENUMERABLE,
|
|
335
|
+
drainProof: INVENTORY_DRAIN_PROOF,
|
|
336
|
+
};
|
|
337
|
+
function placeholdersFor(values) {
|
|
338
|
+
return values.map(() => '?').join(', ');
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* A keyset predicate over an arbitrary number of key columns, written as
|
|
342
|
+
* nested comparisons rather than SQLite's row-value syntax.
|
|
343
|
+
*
|
|
344
|
+
* Row values (`(a, b) > (?, ?)`) would be shorter and SQLite has supported them
|
|
345
|
+
* since 3.15, but the expansion below is what every index in this package is
|
|
346
|
+
* already shaped for and what any SQLite the adapter might sit on understands.
|
|
347
|
+
* The shape is strictly-greater at every level, so a cursor never re-reads its
|
|
348
|
+
* own row and never skips the one after it.
|
|
349
|
+
*/
|
|
350
|
+
function keysetPredicate(columns) {
|
|
351
|
+
const clauses = [];
|
|
352
|
+
for (let index = 0; index < columns.length; index += 1) {
|
|
353
|
+
const equalities = columns
|
|
354
|
+
.slice(0, index)
|
|
355
|
+
.map((column) => `${column} = ?`)
|
|
356
|
+
.join(' AND ');
|
|
357
|
+
const greater = `${columns[index]} > ?`;
|
|
358
|
+
clauses.push(equalities === '' ? greater : `(${equalities} AND ${greater})`);
|
|
359
|
+
}
|
|
360
|
+
return `(${clauses.join(' OR ')})`;
|
|
361
|
+
}
|
|
362
|
+
/** The bindings `keysetPredicate` expects, for one cursor. */
|
|
363
|
+
function keysetBindings(cursor) {
|
|
364
|
+
const binds = [];
|
|
365
|
+
for (let index = 0; index < cursor.length; index += 1) {
|
|
366
|
+
for (let prefix = 0; prefix < index; prefix += 1) {
|
|
367
|
+
binds.push(cursor[prefix]);
|
|
368
|
+
}
|
|
369
|
+
binds.push(cursor[index]);
|
|
370
|
+
}
|
|
371
|
+
return binds;
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Parse a caller's cursor into the key it names, refusing anything that is not
|
|
375
|
+
* exactly one key for THIS category.
|
|
376
|
+
*
|
|
377
|
+
* Refusing rather than ignoring: a cursor from a different category, or one
|
|
378
|
+
* that lost a component, would resume the scan somewhere the caller did not
|
|
379
|
+
* ask for — and a sweep that silently restarts is a sweep that never proves
|
|
380
|
+
* emptiness.
|
|
381
|
+
*/
|
|
382
|
+
function parseCursor(cursor, category, arity) {
|
|
383
|
+
if (cursor === undefined || cursor === '')
|
|
384
|
+
return undefined;
|
|
385
|
+
if (cursor.length > MAX_CURSOR_LENGTH) {
|
|
386
|
+
throw new InvalidInventoryRequestError('inventory cursor exceeds limit');
|
|
387
|
+
}
|
|
388
|
+
let parsed;
|
|
389
|
+
try {
|
|
390
|
+
parsed = JSON.parse(cursor);
|
|
391
|
+
}
|
|
392
|
+
catch {
|
|
393
|
+
throw new InvalidInventoryRequestError(`inventory cursor for '${category}' is not valid JSON`);
|
|
394
|
+
}
|
|
395
|
+
if (!Array.isArray(parsed) ||
|
|
396
|
+
parsed.length !== arity ||
|
|
397
|
+
!parsed.every((part) => typeof part === 'string')) {
|
|
398
|
+
throw new InvalidInventoryRequestError(`inventory cursor for '${category}' must name ${String(arity)} key component(s)`);
|
|
399
|
+
}
|
|
400
|
+
return parsed;
|
|
401
|
+
}
|
|
402
|
+
function clampLimit(limit) {
|
|
403
|
+
if (limit === undefined)
|
|
404
|
+
return INVENTORY_DEFAULT_LIMIT;
|
|
405
|
+
if (!Number.isFinite(limit) || !Number.isInteger(limit) || limit < 1) {
|
|
406
|
+
throw new InvalidInventoryRequestError('inventory limit must be a positive integer');
|
|
407
|
+
}
|
|
408
|
+
return Math.min(limit, INVENTORY_MAX_LIMIT);
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Project one row's non-key columns, dropping anything absent.
|
|
412
|
+
*
|
|
413
|
+
* NULL columns are omitted rather than reported as `null`, the same rule the
|
|
414
|
+
* fence's reading payload follows: a caller reading `runId: null` off a
|
|
415
|
+
* deferred dispatch would have to know that null means "not dispatched" rather
|
|
416
|
+
* than "column missing", and the absent field says it without ambiguity.
|
|
417
|
+
*/
|
|
418
|
+
function detailOf(row, keys, flags) {
|
|
419
|
+
const detail = {};
|
|
420
|
+
for (const [column, value] of Object.entries(row)) {
|
|
421
|
+
if (keys.includes(column))
|
|
422
|
+
continue;
|
|
423
|
+
if (value === null || value === undefined)
|
|
424
|
+
continue;
|
|
425
|
+
if (flags.includes(column)) {
|
|
426
|
+
detail[column] = value !== 0;
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
if (typeof value === 'string' ||
|
|
430
|
+
typeof value === 'number' ||
|
|
431
|
+
typeof value === 'boolean') {
|
|
432
|
+
detail[column] = value;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
return detail;
|
|
436
|
+
}
|
|
437
|
+
function keyOf(row, keys) {
|
|
438
|
+
return keys.map((column) => String(row[column] ?? ''));
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* 1 when a background task's suspend payload carries the fence marker.
|
|
442
|
+
*
|
|
443
|
+
* Written once and used in both the projection and the aggregate so a row
|
|
444
|
+
* flagged on the page and a row counted in the total can never be decided by
|
|
445
|
+
* two different expressions. `json_valid` guards a NULL or malformed payload,
|
|
446
|
+
* which json_extract would otherwise throw on — a tool free to suspend with any
|
|
447
|
+
* payload it likes is a tool that could otherwise wedge this sweep.
|
|
448
|
+
*/
|
|
449
|
+
function fenceParkedSql() {
|
|
450
|
+
return `CASE WHEN json_valid(suspend_payload)
|
|
451
|
+
AND json_extract(suspend_payload, '$."${EXECUTION_FENCE_SUSPEND_KEY}"') IS NOT NULL
|
|
452
|
+
THEN 1 ELSE 0 END`;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Decorate a page of runs with the principal that owns each one.
|
|
456
|
+
*
|
|
457
|
+
* A SECOND query rather than a join, for two reasons that both point the same
|
|
458
|
+
* way. The ownership registry belongs to the approval layer and a deployment
|
|
459
|
+
* that never wired it has no such table — a join would turn its absence into a
|
|
460
|
+
* failure of the `runs` category, which is the one category a drain proof
|
|
461
|
+
* cannot do without. And the annotation is decoration: an operator deciding
|
|
462
|
+
* whether to lock needs the run, and wants the owner. So a missing table, and
|
|
463
|
+
* only a missing table, degrades to unannotated rows rather than to no rows.
|
|
464
|
+
*
|
|
465
|
+
* Ownership is keyed by run id alone (`resource_kind = 'run'`), so the lookup
|
|
466
|
+
* takes the page's run ids — never an unbounded scan.
|
|
467
|
+
*
|
|
468
|
+
* CHUNKED, because a page can be larger than one statement may bind. A caller
|
|
469
|
+
* asking for `limit=200` (INVENTORY_MAX_LIMIT, a real knob) would otherwise
|
|
470
|
+
* build a 200-parameter `IN` list, which real D1 refuses outright while
|
|
471
|
+
* node:sqlite — with its 32766-variable ceiling — accepts happily. That
|
|
472
|
+
* combination is the worst one available: the suite stays green and the route
|
|
473
|
+
* answers a generic 500 on the deployment an operator is trying to drain.
|
|
474
|
+
*/
|
|
475
|
+
async function annotateRunOwners(db, entries) {
|
|
476
|
+
if (entries.length === 0)
|
|
477
|
+
return;
|
|
478
|
+
// key = [workflow_name, run_id]; ownership is keyed on the run id.
|
|
479
|
+
const runIds = entries.map((entry) => entry.key[1] ?? '');
|
|
480
|
+
const owners = new Map();
|
|
481
|
+
for (let offset = 0; offset < runIds.length; offset += RUN_OWNER_LOOKUP_CHUNK) {
|
|
482
|
+
const slice = runIds.slice(offset, offset + RUN_OWNER_LOOKUP_CHUNK);
|
|
483
|
+
let rows;
|
|
484
|
+
try {
|
|
485
|
+
({ results: rows } = await db
|
|
486
|
+
.prepare(`SELECT resource_id, owner_kind, owner_id
|
|
487
|
+
FROM ${RESOURCE_OWNER_TABLE}
|
|
488
|
+
WHERE resource_kind = 'run'
|
|
489
|
+
AND resource_id IN (${placeholdersFor(slice)})`)
|
|
490
|
+
.bind(...slice)
|
|
491
|
+
.all());
|
|
492
|
+
}
|
|
493
|
+
catch (error) {
|
|
494
|
+
// A deployment with no ownership registry has none for ANY slice, so the
|
|
495
|
+
// whole annotation is abandoned rather than the current chunk: continuing
|
|
496
|
+
// would re-throw the same absence once per hundred rows.
|
|
497
|
+
if (missingTableReadsEmpty(error, RESOURCE_OWNER_TABLE))
|
|
498
|
+
return;
|
|
499
|
+
throw error;
|
|
500
|
+
}
|
|
501
|
+
for (const row of rows) {
|
|
502
|
+
const kind = row.owner_kind;
|
|
503
|
+
const id = row.owner_id;
|
|
504
|
+
if (typeof kind !== 'string' || typeof id !== 'string')
|
|
505
|
+
continue;
|
|
506
|
+
owners.set(String(row.resource_id), `${kind}:${id}`);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
for (const entry of entries) {
|
|
510
|
+
const owner = owners.get(entry.key[1] ?? '');
|
|
511
|
+
if (owner !== undefined)
|
|
512
|
+
entry.detail.owner = owner;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* The deployment's read-only work inventory over one D1 database — the same
|
|
517
|
+
* database its runs, approvals, and fence live in, so what it reports and what
|
|
518
|
+
* the fence governs cannot be two different deployments.
|
|
519
|
+
*/
|
|
520
|
+
export class DeploymentInventory {
|
|
521
|
+
#db;
|
|
522
|
+
#prefix;
|
|
523
|
+
#now;
|
|
524
|
+
constructor(db, options = {}) {
|
|
525
|
+
this.#db = db;
|
|
526
|
+
this.#prefix =
|
|
527
|
+
validateTablePrefix(options.tablePrefix, 'tablePrefix') ?? '';
|
|
528
|
+
this.#now = options.now ?? Date.now;
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* What this deployment can be asked about, what it cannot answer, and the
|
|
532
|
+
* rule for reading an empty answer.
|
|
533
|
+
*
|
|
534
|
+
* A constant, and deliberately not a query: the index is the CONTRACT, and a
|
|
535
|
+
* contract that changed with the data would let an operator conclude that a
|
|
536
|
+
* category they cannot see does not apply to them.
|
|
537
|
+
*/
|
|
538
|
+
index() {
|
|
539
|
+
return INVENTORY_INDEX;
|
|
540
|
+
}
|
|
541
|
+
/** One page of one category. */
|
|
542
|
+
async read(category, options = {}) {
|
|
543
|
+
const descriptor = INVENTORY_CATEGORY_DESCRIPTORS.find((entry) => entry.category === category);
|
|
544
|
+
if (!descriptor) {
|
|
545
|
+
throw new InvalidInventoryRequestError(`unknown inventory category '${String(category)}'`);
|
|
546
|
+
}
|
|
547
|
+
const query = this.#queryFor(category);
|
|
548
|
+
const table = this.#tableFor(descriptor);
|
|
549
|
+
const cursor = parseCursor(options.cursor, category, query.key.length);
|
|
550
|
+
const limit = clampLimit(options.limit);
|
|
551
|
+
const base = {
|
|
552
|
+
category,
|
|
553
|
+
class: descriptor.class,
|
|
554
|
+
table,
|
|
555
|
+
};
|
|
556
|
+
let rows;
|
|
557
|
+
try {
|
|
558
|
+
rows = await this.#page(table, query, cursor, limit);
|
|
559
|
+
}
|
|
560
|
+
catch (error) {
|
|
561
|
+
// A table nothing has created yet holds nothing. Every table here is made
|
|
562
|
+
// lazily by the first feature that writes it, so the absence is the same
|
|
563
|
+
// observation as an empty scan — and answering it with a fault would make
|
|
564
|
+
// a fresh deployment undrainable.
|
|
565
|
+
if (missingTableReadsEmpty(error, table))
|
|
566
|
+
return { ...base, entries: [] };
|
|
567
|
+
throw error;
|
|
568
|
+
}
|
|
569
|
+
const entries = rows.map((row) => ({
|
|
570
|
+
key: keyOf(row, query.key),
|
|
571
|
+
detail: detailOf(row, query.key, query.flags ?? []),
|
|
572
|
+
}));
|
|
573
|
+
await query.annotate?.(this.#db, entries);
|
|
574
|
+
// A cursor is offered only when the page filled: a short page reached the
|
|
575
|
+
// end of the category as of this read, and that is the observation the
|
|
576
|
+
// drain proof is built on.
|
|
577
|
+
const next = entries.length === limit ? entries[entries.length - 1] : undefined;
|
|
578
|
+
const counted = cursor === undefined ? await this.#counts(table, query) : undefined;
|
|
579
|
+
return {
|
|
580
|
+
...base,
|
|
581
|
+
entries,
|
|
582
|
+
...(next === undefined ? {} : { cursor: JSON.stringify(next.key) }),
|
|
583
|
+
...(counted === undefined ? {} : counted),
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
/** Every category's first page, for a caller sweeping the whole deployment. */
|
|
587
|
+
async sweep(options = {}) {
|
|
588
|
+
const pages = [];
|
|
589
|
+
for (const descriptor of INVENTORY_CATEGORY_DESCRIPTORS) {
|
|
590
|
+
pages.push(await this.read(descriptor.category, {
|
|
591
|
+
...(options.limit === undefined ? {} : { limit: options.limit }),
|
|
592
|
+
}));
|
|
593
|
+
}
|
|
594
|
+
return pages;
|
|
595
|
+
}
|
|
596
|
+
#tableFor(descriptor) {
|
|
597
|
+
// The prefix belongs to the Mastra-owned storage domains only — the same
|
|
598
|
+
// split createD1Storage and the retention purges take. A flowsafe registry
|
|
599
|
+
// is never prefixed, so prefixing it here would read an empty category on
|
|
600
|
+
// every prefixed deployment.
|
|
601
|
+
return descriptor.table.startsWith('mastra_')
|
|
602
|
+
? `${this.#prefix}${descriptor.table}`
|
|
603
|
+
: descriptor.table;
|
|
604
|
+
}
|
|
605
|
+
async #page(table, query, cursor, limit) {
|
|
606
|
+
const projection = [...query.key, ...query.detail].join(', ');
|
|
607
|
+
const keyset = cursor === undefined ? '' : ` AND ${keysetPredicate(query.key)}`;
|
|
608
|
+
const { results } = await this.#db
|
|
609
|
+
.prepare(`SELECT ${projection}
|
|
610
|
+
FROM ${table}
|
|
611
|
+
WHERE ${query.where}${keyset}
|
|
612
|
+
ORDER BY ${query.key.join(', ')}
|
|
613
|
+
LIMIT ?`)
|
|
614
|
+
.bind(...(query.detailBinds ?? []), ...query.binds, ...(cursor === undefined ? [] : keysetBindings(cursor)), limit)
|
|
615
|
+
.all();
|
|
616
|
+
return results;
|
|
617
|
+
}
|
|
618
|
+
async #counts(table, query) {
|
|
619
|
+
const extra = query.totals ?? [];
|
|
620
|
+
// `count` is always "rows in this category", even when the aggregate scans
|
|
621
|
+
// wider: a category that widens `countWhere` re-applies its own predicate
|
|
622
|
+
// through `countExpression`.
|
|
623
|
+
const total = query.countExpression ?? 'COUNT(*)';
|
|
624
|
+
const { results } = await this.#db
|
|
625
|
+
.prepare(`SELECT ${total} AS total${extra.length === 0 ? '' : `, ${extra.join(', ')}`}
|
|
626
|
+
FROM ${table}
|
|
627
|
+
WHERE ${query.countWhere ?? query.where}`)
|
|
628
|
+
.bind(...(query.countExpressionBinds ?? []), ...(query.totalsBinds ?? []), ...(query.countBinds ?? query.binds))
|
|
629
|
+
.all();
|
|
630
|
+
const row = results[0];
|
|
631
|
+
if (row === undefined)
|
|
632
|
+
return undefined;
|
|
633
|
+
const totals = {};
|
|
634
|
+
for (const [column, value] of Object.entries(row)) {
|
|
635
|
+
if (column === 'total')
|
|
636
|
+
continue;
|
|
637
|
+
totals[column] = typeof value === 'number' ? value : 0;
|
|
638
|
+
}
|
|
639
|
+
return {
|
|
640
|
+
count: typeof row.total === 'number' ? row.total : 0,
|
|
641
|
+
...(Object.keys(totals).length === 0 ? {} : { totals }),
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
#queryFor(category) {
|
|
645
|
+
switch (category) {
|
|
646
|
+
case 'runs':
|
|
647
|
+
return {
|
|
648
|
+
key: ['workflow_name', 'run_id'],
|
|
649
|
+
detail: [
|
|
650
|
+
// The same json_valid guard the retention purge uses, for the same
|
|
651
|
+
// reason: json_extract THROWS on malformed JSON, and one corrupt
|
|
652
|
+
// snapshot must not abort the sweep that is trying to account for
|
|
653
|
+
// the deployment.
|
|
654
|
+
`CASE WHEN json_valid(snapshot)
|
|
655
|
+
THEN json_extract(snapshot, '$.status') END AS status`,
|
|
656
|
+
'updatedAt',
|
|
657
|
+
],
|
|
658
|
+
// The predicate is the NEGATION of the retention purge's own terminal
|
|
659
|
+
// fragment, so "finished" means one thing on this deployment. An
|
|
660
|
+
// unclassifiable snapshot (invalid JSON, or valid JSON with no
|
|
661
|
+
// status) counts as WORK: a row nobody can prove is finished is
|
|
662
|
+
// exactly the row a migration must not walk away from.
|
|
663
|
+
where: `CASE WHEN json_valid(snapshot)
|
|
664
|
+
THEN CASE WHEN (${RUN_TERMINAL_SNAPSHOT_SQL}) THEN 0 ELSE 1 END
|
|
665
|
+
ELSE 1 END`,
|
|
666
|
+
binds: RUN_TERMINAL_STATUSES,
|
|
667
|
+
annotate: annotateRunOwners,
|
|
668
|
+
};
|
|
669
|
+
case 'approvals-waiting':
|
|
670
|
+
// OPEN_STATUSES, not just 'pending': a claimed or escalated approval is
|
|
671
|
+
// still undecided, and its run is still suspended behind it. The same
|
|
672
|
+
// set the store's open-uniqueness index and decide()'s CAS ride on.
|
|
673
|
+
return {
|
|
674
|
+
key: ['id'],
|
|
675
|
+
detail: ['workflow_id', 'run_id', 'step_key', 'status', 'created_at'],
|
|
676
|
+
where: `status IN (${placeholdersFor(OPEN_STATUSES)})`,
|
|
677
|
+
binds: OPEN_STATUSES,
|
|
678
|
+
};
|
|
679
|
+
case 'schedule-deferred-dispatches':
|
|
680
|
+
// 'deferred' is the ONLY outcome that is still work. The same table
|
|
681
|
+
// holds every settled fire under schedule-trigger retention, and a
|
|
682
|
+
// predicate that matched those would keep this category permanently
|
|
683
|
+
// non-empty and make the drain unprovable. The schedule store's own
|
|
684
|
+
// dispatch reads guard on exactly this value.
|
|
685
|
+
return {
|
|
686
|
+
key: ['id'],
|
|
687
|
+
detail: ['scheduleId', 'runId', 'scheduledFireAt', 'actualFireAt'],
|
|
688
|
+
where: "outcome = 'deferred'",
|
|
689
|
+
binds: [],
|
|
690
|
+
};
|
|
691
|
+
case 'pending-notifications': {
|
|
692
|
+
const now = new Date(this.#now()).toISOString();
|
|
693
|
+
// listDueNotifications' predicate, verbatim in meaning: pending AND
|
|
694
|
+
// (deliverAt or summaryAt has come due). A pending row that is not yet
|
|
695
|
+
// due is NOT work a drain can finish — no dispatch pass will select
|
|
696
|
+
// it — so it stays out of the page and is reported as `notDue`
|
|
697
|
+
// instead. That total also covers pending rows carrying NEITHER
|
|
698
|
+
// timestamp, which no dispatch pass will ever select at all.
|
|
699
|
+
const due = DUE_NOTIFICATION_SQL;
|
|
700
|
+
return {
|
|
701
|
+
key: ['thread_id', 'id'],
|
|
702
|
+
detail: ['source', 'kind', 'priority', 'agentId', 'deliverAt'],
|
|
703
|
+
where: due,
|
|
704
|
+
binds: [now, now],
|
|
705
|
+
// The aggregate scans every PENDING row so `notDue` can exist at
|
|
706
|
+
// all — but `count` re-applies the due predicate, so it still means
|
|
707
|
+
// what it means in every other category: rows in this one.
|
|
708
|
+
countWhere: "status = 'pending'",
|
|
709
|
+
countBinds: [],
|
|
710
|
+
countExpression: `SUM(CASE WHEN ${due} THEN 1 ELSE 0 END)`,
|
|
711
|
+
countExpressionBinds: [now, now],
|
|
712
|
+
totals: [`SUM(CASE WHEN ${due} THEN 0 ELSE 1 END) AS notDue`],
|
|
713
|
+
totalsBinds: [now, now],
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
case 'background-tasks':
|
|
717
|
+
// Nonterminal is the complement of what the background-task TTL reaps,
|
|
718
|
+
// so a task this reports as outstanding is exactly a task retention
|
|
719
|
+
// will not touch.
|
|
720
|
+
return {
|
|
721
|
+
key: ['id'],
|
|
722
|
+
detail: [
|
|
723
|
+
'status',
|
|
724
|
+
'tool_name',
|
|
725
|
+
'agent_id',
|
|
726
|
+
'run_id',
|
|
727
|
+
// The distinction that decides an operator's next move: a task
|
|
728
|
+
// parked BY THE FENCE resumes itself when the deployment reopens,
|
|
729
|
+
// while a task suspended by its own tool is waiting for something
|
|
730
|
+
// external and will still be waiting after the migration.
|
|
731
|
+
`${fenceParkedSql()} AS fenceSuspended`,
|
|
732
|
+
],
|
|
733
|
+
flags: ['fenceSuspended'],
|
|
734
|
+
where: `status NOT IN (${placeholdersFor(BACKGROUND_TASK_TERMINAL_STATUSES)})`,
|
|
735
|
+
binds: BACKGROUND_TASK_TERMINAL_STATUSES,
|
|
736
|
+
totals: [`SUM(${fenceParkedSql()}) AS fenceSuspended`],
|
|
737
|
+
};
|
|
738
|
+
case 'resource-owners':
|
|
739
|
+
// A non-null reservation token is an ownership claim that was taken and
|
|
740
|
+
// never settled — settleReservation is what clears it, and `owner()`
|
|
741
|
+
// deliberately reads only rows where it is already NULL.
|
|
742
|
+
//
|
|
743
|
+
// The token itself is never projected: it is the value a settle races
|
|
744
|
+
// on, and an inventory is a read, not a way to learn one.
|
|
745
|
+
return {
|
|
746
|
+
key: ['resource_kind', 'resource_id'],
|
|
747
|
+
detail: ['owner_kind', 'owner_id'],
|
|
748
|
+
where: 'reservation_token IS NOT NULL',
|
|
749
|
+
binds: [],
|
|
750
|
+
};
|
|
751
|
+
case 'start-reservations': {
|
|
752
|
+
// Everything except 'terminal' — derived from the reservation state
|
|
753
|
+
// list rather than spelled, so a new state joins this category by
|
|
754
|
+
// default instead of vanishing from it.
|
|
755
|
+
const unsettled = START_RESERVATION_STATES.filter((state) => state !== 'terminal');
|
|
756
|
+
return {
|
|
757
|
+
key: ['key'],
|
|
758
|
+
detail: [
|
|
759
|
+
'state',
|
|
760
|
+
'owner_kind',
|
|
761
|
+
'owner_id',
|
|
762
|
+
'target_kind',
|
|
763
|
+
'target_id',
|
|
764
|
+
'run_id',
|
|
765
|
+
// The agent surface's address. Present for agent reservations only,
|
|
766
|
+
// and omitted rather than nulled for workflow ones — a retry of an
|
|
767
|
+
// agent key that cannot be routed to a thread is unreachable, so
|
|
768
|
+
// the field's absence is information.
|
|
769
|
+
'thread_id',
|
|
770
|
+
'updated_at',
|
|
771
|
+
],
|
|
772
|
+
where: `state IN (${placeholdersFor(unsettled)})`,
|
|
773
|
+
binds: unsettled,
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
case 'schedules':
|
|
777
|
+
// Standing configuration: every row, including paused ones. A paused
|
|
778
|
+
// schedule arms nothing today and everything the day it resumes, and a
|
|
779
|
+
// reconciling operator needs to see both.
|
|
780
|
+
return {
|
|
781
|
+
key: ['id'],
|
|
782
|
+
detail: [
|
|
783
|
+
'status',
|
|
784
|
+
'nextFireAt',
|
|
785
|
+
`CASE WHEN json_valid(target)
|
|
786
|
+
THEN json_extract(target, '$.type') END AS targetType`,
|
|
787
|
+
`CASE WHEN json_valid(target)
|
|
788
|
+
THEN COALESCE(
|
|
789
|
+
json_extract(target, '$.workflowId'),
|
|
790
|
+
json_extract(target, '$.agentId')
|
|
791
|
+
) END AS targetId`,
|
|
792
|
+
],
|
|
793
|
+
where: '1 = 1',
|
|
794
|
+
binds: [],
|
|
795
|
+
};
|
|
796
|
+
case 'signal-subscriptions':
|
|
797
|
+
return {
|
|
798
|
+
key: ['id'],
|
|
799
|
+
detail: [
|
|
800
|
+
'provider_id',
|
|
801
|
+
'thread_id',
|
|
802
|
+
'external_resource_id',
|
|
803
|
+
'subscribed_at',
|
|
804
|
+
],
|
|
805
|
+
where: '1 = 1',
|
|
806
|
+
binds: [],
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
//# sourceMappingURL=inventory.js.map
|