@substrat-run/kernel 0.216.0 → 0.217.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.
Files changed (68) hide show
  1. package/dist/attachment-gate.d.ts +42 -0
  2. package/dist/attachment-gate.d.ts.map +1 -0
  3. package/dist/attachment-gate.js +36 -0
  4. package/dist/attachment-gate.js.map +1 -0
  5. package/dist/broker-erasure.d.ts +51 -0
  6. package/dist/broker-erasure.d.ts.map +1 -0
  7. package/dist/broker-erasure.js +161 -0
  8. package/dist/broker-erasure.js.map +1 -0
  9. package/dist/broker-relay-erasure.d.ts +27 -0
  10. package/dist/broker-relay-erasure.d.ts.map +1 -0
  11. package/dist/broker-relay-erasure.js +115 -0
  12. package/dist/broker-relay-erasure.js.map +1 -0
  13. package/dist/broker-relay.d.ts +292 -0
  14. package/dist/broker-relay.d.ts.map +1 -0
  15. package/dist/broker-relay.js +494 -0
  16. package/dist/broker-relay.js.map +1 -0
  17. package/dist/broker-schema.d.ts +25 -0
  18. package/dist/broker-schema.d.ts.map +1 -0
  19. package/dist/broker-schema.js +198 -0
  20. package/dist/broker-schema.js.map +1 -0
  21. package/dist/broker-telemetry.d.ts +288 -0
  22. package/dist/broker-telemetry.d.ts.map +1 -0
  23. package/dist/broker-telemetry.js +334 -0
  24. package/dist/broker-telemetry.js.map +1 -0
  25. package/dist/cost-rollup.d.ts +6 -0
  26. package/dist/cost-rollup.d.ts.map +1 -1
  27. package/dist/cost-rollup.js +22 -1
  28. package/dist/cost-rollup.js.map +1 -1
  29. package/dist/delivery-broker.d.ts +278 -0
  30. package/dist/delivery-broker.d.ts.map +1 -0
  31. package/dist/delivery-broker.js +516 -0
  32. package/dist/delivery-broker.js.map +1 -0
  33. package/dist/delivery-policy.d.ts +105 -0
  34. package/dist/delivery-policy.d.ts.map +1 -0
  35. package/dist/delivery-policy.js +105 -0
  36. package/dist/delivery-policy.js.map +1 -0
  37. package/dist/index.d.ts +12 -1
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +6 -0
  40. package/dist/index.js.map +1 -1
  41. package/dist/job-run.d.ts +21 -1
  42. package/dist/job-run.d.ts.map +1 -1
  43. package/dist/job-run.js +6 -0
  44. package/dist/job-run.js.map +1 -1
  45. package/dist/outbox-prune.d.ts +8 -1
  46. package/dist/outbox-prune.d.ts.map +1 -1
  47. package/dist/outbox-prune.js +6 -2
  48. package/dist/outbox-prune.js.map +1 -1
  49. package/dist/platform-sweep.d.ts +10 -1
  50. package/dist/platform-sweep.d.ts.map +1 -1
  51. package/dist/platform-sweep.js +37 -1
  52. package/dist/platform-sweep.js.map +1 -1
  53. package/dist/scope-host.d.ts +33 -8
  54. package/dist/scope-host.d.ts.map +1 -1
  55. package/dist/scope-host.js.map +1 -1
  56. package/dist/store-driver-releases.d.ts +9 -2
  57. package/dist/store-driver-releases.d.ts.map +1 -1
  58. package/dist/store-driver-releases.js +12 -7
  59. package/dist/store-driver-releases.js.map +1 -1
  60. package/dist/subject-keys.d.ts +7 -0
  61. package/dist/subject-keys.d.ts.map +1 -1
  62. package/dist/subject-keys.js +29 -5
  63. package/dist/subject-keys.js.map +1 -1
  64. package/dist/subject-redaction.d.ts +7 -0
  65. package/dist/subject-redaction.d.ts.map +1 -1
  66. package/dist/subject-redaction.js +34 -27
  67. package/dist/subject-redaction.js.map +1 -1
  68. package/package.json +2 -2
@@ -0,0 +1,516 @@
1
+ /**
2
+ * The delivery broker (K-74, rfc/broker-and-tenant-isolation.md §4): one per (tenant, app), and the
3
+ * owner of every message a scope sends once the scope has handed it off.
4
+ *
5
+ * Not the local PEER broker (`@substrat-run/adapter-sqlite/vertical-broker`, #1706), which stands in
6
+ * for the router on a call between apps. This one takes custody of what a commit left behind.
7
+ *
8
+ * What lives here is what both adapters share, so they cannot drift:
9
+ *
10
+ * - **The message** a scope hands off (`BrokerMessage`): an outbox row the scope emitted, or a
11
+ * platform intent it raised, carried whole as its row's JSON. The broker does not interpret it.
12
+ * - **The scope's half** (`handoffBatch`, `advanceMarks`): which rows are due for handoff past the
13
+ * scope's marks, and how far an answer moves them. A mark is the greatest id handed off and
14
+ * acknowledged, per kind. Ids are the kernel's ulid, which only increases within a process and is
15
+ * seeded from the scope's newest id on wake, so `id > mark` is the same watermark
16
+ * `readScopeTimeline` walks. Nothing is written to the scope's own tables: the marks are a cache
17
+ * of what the broker holds (`BrokerStore.marks` is the authority), so a scope that lost them asks.
18
+ * - **The broker's store** (`BrokerStore`): its own SQLite, which both adapters have, behind the
19
+ * three operations it needs. Acceptance is idempotent by message id, so a handoff repeated after a
20
+ * lost acknowledgement stores nothing twice and is acknowledged again.
21
+ *
22
+ * Delivery is effectively once inside the platform: dedup by id at every hop. Toward the internet it
23
+ * is at least once (K-74). A broker delivers to the receivers it was given, one delivery per
24
+ * (message, receiver), each under its subscription's policy (`delivery-policy.ts`, A4); with none it
25
+ * holds what it accepted, bounded by `BROKER_HELD_RETENTION_MS`, until A5's shadow recorder and the
26
+ * real receivers arrive. Its tables are `broker-schema.ts`.
27
+ */
28
+ import { migrateBrokerStore } from './broker-schema.js';
29
+ import { eraseSubjectFromBroker, screenErasedSubjects, } from './broker-erasure.js';
30
+ import { BROKER_TIMING, DEFAULT_DELIVERY_POLICY, backoffMs, classifyFailure, resolvePolicy, } from './delivery-policy.js';
31
+ import { emittedHere } from './scope-copy.js';
32
+ export const BROKER_MESSAGE_KINDS = ['event', 'intent'];
33
+ /** How many rows of each kind one handoff carries. A larger backlog follows in the next one. */
34
+ export const HANDOFF_BATCH = 50;
35
+ /** How many due messages one delivery pass attempts before it yields. */
36
+ export const BROKER_DELIVERY_BATCH = 50;
37
+ /** The waits after each failed handoff, as the scope retries it from its own alarm. */
38
+ export const HANDOFF_RETRY_MS = [1_000, 5_000, 30_000, 2 * 60_000, 10 * 60_000];
39
+ /** How long a settled message is kept, for a duplicate handoff to find it (`BrokerTiming.deliveredRetentionMs`). */
40
+ export const BROKER_DELIVERED_RETENTION_MS = BROKER_TIMING.deliveredRetentionMs;
41
+ /** How long a message nobody delivers is held (no receiver yet): the K-70 bound until A5 exists. */
42
+ export const BROKER_HELD_RETENTION_MS = BROKER_TIMING.heldRetentionMs;
43
+ /** The wait after `attempts` failures, on a schedule: its last step repeats. */
44
+ export const retryAfter = (schedule, attempts) => schedule[Math.min(Math.max(attempts, 1), schedule.length) - 1];
45
+ /** The broker's name in its namespace: one per (tenant, app). */
46
+ export const brokerName = (tenantId, app) => `${tenantId}/${app}`;
47
+ /**
48
+ * The reads a handoff makes, one per kind, past the scope's marks. Every row is the scope's own:
49
+ * `emittedHere` leaves out what a copy carried in, for intents as for events. (A copy's intents were
50
+ * settled at load as not carried; one minted at the source after its last event compares above the
51
+ * copy's key and is handed off once, settled. A5's comparison is where that would show.)
52
+ */
53
+ export function handoffQueries(marks, limit = HANDOFF_BATCH) {
54
+ return [
55
+ {
56
+ kind: 'event',
57
+ sql: `SELECT * FROM _substrat_outbox WHERE id > ? AND ${emittedHere()} ORDER BY id LIMIT ?`,
58
+ params: [marks.event ?? '', limit],
59
+ },
60
+ {
61
+ kind: 'intent',
62
+ sql: `SELECT id, kind, payload, requested_by, impersonation, requested_at
63
+ FROM _substrat_platform_requests WHERE id > ? AND ${emittedHere()} ORDER BY id LIMIT ?`,
64
+ params: [marks.intent ?? '', limit],
65
+ },
66
+ ];
67
+ }
68
+ /** A handoff read's rows, as the messages they become. */
69
+ export function messagesOf(kind, rows, ids) {
70
+ return rows.map((row) => ({
71
+ id: String(row.id),
72
+ kind,
73
+ tenantId: ids.tenantId,
74
+ scopeId: ids.scopeId,
75
+ type: String(kind === 'event' ? row.type : row.kind),
76
+ body: JSON.stringify(row),
77
+ committedAt: String(kind === 'event' ? row.occurred_at : row.requested_at),
78
+ }));
79
+ }
80
+ /**
81
+ * How far an answer moves the marks: per kind, over the longest run of the batch, in id order, that
82
+ * the broker acknowledged. A gap stops it, so an unacknowledged message is handed off again rather
83
+ * than skipped.
84
+ */
85
+ export function advanceMarks(marks, sent, answer) {
86
+ const acked = new Set(answer.acked);
87
+ const next = { ...marks };
88
+ for (const kind of BROKER_MESSAGE_KINDS) {
89
+ for (const m of sent.filter((s) => s.kind === kind).sort((a, b) => (a.id < b.id ? -1 : 1))) {
90
+ if (!acked.has(m.id))
91
+ break;
92
+ next[kind] = m.id;
93
+ }
94
+ }
95
+ return next;
96
+ }
97
+ /** What `BrokerStore.held` probes per statement: under the Durable Object's 100 bound parameters. */
98
+ const HELD_PROBE_CHUNK = 50;
99
+ /** A delivery is open while the broker still owes it: pending, or dead and resendable. */
100
+ const OPEN = "('pending', 'dead')";
101
+ /** A pending delivery may go now only as its lane's head: no lower message id open in its (receiver, lane). */
102
+ const LANE_HEAD = `(d.lane IS NULL OR NOT EXISTS (
103
+ SELECT 1 FROM broker_deliveries e
104
+ WHERE e.receiver = d.receiver AND e.lane = d.lane AND e.state IN ${OPEN} AND e.message_id < d.message_id))`;
105
+ /** How many settled messages one prune deletes; the rest go in the next. */
106
+ const PRUNE_BATCH = 500;
107
+ /**
108
+ * The broker's store (schema: `broker-schema.ts`). Each method is synchronous over `BrokerSql`, and
109
+ * each that writes runs in one transaction.
110
+ *
111
+ * A message is stored once (`broker_messages`, its content) and owed once per receiver
112
+ * (`broker_deliveries`, its fate there), so a receiver that fails or is paused holds back only its
113
+ * own deliveries. Ordering is per (receiver, key): only a lane's head is ever due, so a message stuck
114
+ * on key 17 holds back key 17 at that receiver and nothing else. A dead head keeps its lane stopped,
115
+ * since delivering past it would break the order the receiver asked for: the later messages of that
116
+ * key wait, spending nothing, until the dead letter is resent and delivered, discarded, or expires.
117
+ */
118
+ export class BrokerStore {
119
+ sql;
120
+ policies;
121
+ receivers;
122
+ timing;
123
+ random;
124
+ constructor(sql, opts) {
125
+ this.sql = sql;
126
+ this.policies = new Map(opts.subscriptions.map((s) => [s.name, resolvePolicy(s.policy)]));
127
+ if (this.policies.size !== opts.subscriptions.length)
128
+ throw new Error('BrokerStore: two subscriptions share a name');
129
+ this.receivers = JSON.stringify([...this.policies.keys()]);
130
+ this.timing = { ...BROKER_TIMING, ...opts.timing };
131
+ this.random = opts.random ?? Math.random;
132
+ migrateBrokerStore(sql);
133
+ // A store opened with receivers over rows held while it had none: those still inside their bound
134
+ // become due, from when they arrived, at every receiver it has now. One past it is dropped first,
135
+ // as the prune would have, so it is never sent (its marks stay).
136
+ if (this.policies.size) {
137
+ const now = (opts.now ?? Date.now)();
138
+ sql.transaction(() => {
139
+ this.pruneHeld(now);
140
+ const held = sql.all(`SELECT id, ordering_key, received_at FROM broker_messages m
141
+ WHERE NOT EXISTS (SELECT 1 FROM broker_deliveries d WHERE d.message_id = m.id)`);
142
+ for (const m of held)
143
+ this.owe(m.id, m.ordering_key, m.received_at);
144
+ });
145
+ }
146
+ }
147
+ /** The deliveries a new message is owed: one per receiver, due at `at`. */
148
+ owe(id, key, at) {
149
+ for (const [receiver, policy] of this.policies) {
150
+ this.sql.run(`INSERT OR IGNORE INTO broker_deliveries (message_id, receiver, lane, state, next_at) VALUES (?, ?, ?, 'pending', ?)`, id, receiver, policy.ordered ? key : null, at);
151
+ }
152
+ }
153
+ /** Take custody. Idempotent by id; every id handed in is acknowledged, a duplicate too. */
154
+ accept(messages, now) {
155
+ return this.sql.transaction(() => {
156
+ // #3484: an erased subject's content is refused before it is stored, however late the handoff.
157
+ for (const m of screenErasedSubjects(this.sql, messages)) {
158
+ const known = this.sql.all('SELECT 1 FROM broker_messages WHERE id = ?', m.id).length > 0;
159
+ if (!known) {
160
+ this.sql.run(`INSERT INTO broker_messages (id, kind, tenant_id, scope_id, type, body, committed_at, received_at, ordering_key)
161
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, m.id, m.kind, m.tenantId, m.scopeId, m.type, m.body, m.committedAt, now, m.key ?? null);
162
+ this.owe(m.id, m.key ?? null, now);
163
+ }
164
+ this.sql.run(`INSERT INTO broker_marks (tenant_id, scope_id, kind, mark) VALUES (?, ?, ?, ?)
165
+ ON CONFLICT (tenant_id, scope_id, kind) DO UPDATE SET mark = MAX(mark, excluded.mark)`, m.tenantId, m.scopeId, m.kind, m.id);
166
+ }
167
+ return { acked: messages.map((m) => m.id) };
168
+ });
169
+ }
170
+ /** #3484: one message as the store holds it now, or null when it holds none by that id. */
171
+ current(id) {
172
+ const r = this.sql.all('SELECT id, kind, tenant_id, scope_id, type, body, committed_at, ordering_key FROM broker_messages WHERE id = ?', id)[0];
173
+ if (!r)
174
+ return null;
175
+ return {
176
+ id: r.id,
177
+ kind: r.kind,
178
+ tenantId: r.tenant_id,
179
+ scopeId: r.scope_id,
180
+ type: r.type,
181
+ body: r.body,
182
+ committedAt: r.committed_at,
183
+ ...(r.ordering_key === null ? {} : { key: r.ordering_key }),
184
+ };
185
+ }
186
+ /** #3484: erase one subject from what this store holds, dead letters included, in one transaction. */
187
+ eraseSubject(target) {
188
+ return this.sql.transaction(() => eraseSubjectFromBroker(this.sql, target));
189
+ }
190
+ marks(tenantId, scopeId) {
191
+ const rows = this.sql.all('SELECT kind, mark FROM broker_marks WHERE tenant_id = ? AND scope_id = ?', tenantId, scopeId);
192
+ return Object.fromEntries(rows.map((r) => [r.kind, r.mark]));
193
+ }
194
+ /**
195
+ * The deliveries due at `now`, oldest due first: pending, at a receiver this store has and that is
196
+ * neither paused nor slowed, and the head of their lane. `skip` names deliveries already attempted
197
+ * this pass (`deliveryKey`), so a wait of zero is not attempted twice in one pass.
198
+ */
199
+ due(now, limit = BROKER_DELIVERY_BATCH, skip = []) {
200
+ return this.sql
201
+ .all(`SELECT d.message_id, d.receiver, d.attempts,
202
+ m.kind, m.tenant_id, m.scope_id, m.type, m.body, m.committed_at, m.ordering_key
203
+ FROM broker_deliveries d
204
+ JOIN broker_messages m ON m.id = d.message_id
205
+ LEFT JOIN broker_receivers r ON r.receiver = d.receiver
206
+ WHERE d.state = 'pending' AND d.next_at <= ?
207
+ AND d.receiver IN (SELECT value FROM json_each(?))
208
+ AND (r.blocked_until IS NULL OR r.blocked_until <= ?)
209
+ AND ${LANE_HEAD}
210
+ AND (d.message_id || ' ' || d.receiver) NOT IN (SELECT value FROM json_each(?))
211
+ ORDER BY d.next_at, d.message_id LIMIT ?`, now, this.receivers, now, JSON.stringify(skip), limit)
212
+ .map((r) => ({
213
+ receiver: r.receiver,
214
+ attempts: r.attempts,
215
+ message: {
216
+ id: r.message_id,
217
+ kind: r.kind,
218
+ tenantId: r.tenant_id,
219
+ scopeId: r.scope_id,
220
+ type: r.type,
221
+ body: r.body,
222
+ committedAt: r.committed_at,
223
+ ...(r.ordering_key === null ? {} : { key: r.ordering_key }),
224
+ },
225
+ }));
226
+ }
227
+ /** Whether a receiver is paused or slowed at `now`: nothing is sent to it. */
228
+ blocked(receiver, now) {
229
+ const row = this.sql.all('SELECT blocked_until FROM broker_receivers WHERE receiver = ?', receiver)[0];
230
+ return row?.blocked_until != null && row.blocked_until > now;
231
+ }
232
+ /**
233
+ * Whether a delivery `due` returned may still go now: still pending, its receiver neither paused
234
+ * nor slowed, and still its lane's head. A pass asks right before each send, because a handoff (or
235
+ * a resend) that commits while an earlier send awaits can put a lower id at the head of its lane.
236
+ */
237
+ sendable(id, receiver, now) {
238
+ if (this.blocked(receiver, now))
239
+ return false;
240
+ return (this.sql.all(`SELECT 1 FROM broker_deliveries d WHERE d.message_id = ? AND d.receiver = ? AND d.state = 'pending' AND ${LANE_HEAD}`, id, receiver).length > 0);
241
+ }
242
+ /** A delivery landed: it settles, and the receiver's pause, if any, is over. */
243
+ delivered(id, receiver, now) {
244
+ this.sql.transaction(() => {
245
+ this.sql.run(`UPDATE broker_deliveries SET state = 'delivered', next_at = NULL, settled_at = ?, last_error = NULL, last_status = NULL
246
+ WHERE message_id = ? AND receiver = ? AND state = 'pending'`, now, id, receiver);
247
+ this.sql.run('DELETE FROM broker_receivers WHERE receiver = ?', receiver);
248
+ });
249
+ }
250
+ /** A delivery failed, as `classifyFailure` read it. Says what follows for that delivery. */
251
+ failed(id, receiver, failure, now) {
252
+ return this.sql.transaction(() => {
253
+ const row = this.sql.all("SELECT attempts FROM broker_deliveries WHERE message_id = ? AND receiver = ? AND state = 'pending'", id, receiver)[0];
254
+ const r = this.sql.all('SELECT failures, open, pause_ms, blocked_until FROM broker_receivers WHERE receiver = ?', receiver)[0] ?? { failures: 0, open: 0, pause_ms: null, blocked_until: null };
255
+ const status = failure.status ?? null;
256
+ if (failure.kind === 'slow') {
257
+ // Not a failure: nothing spent, the run toward a pause unchanged; the receiver waits.
258
+ const wait = Math.min(failure.afterMs ?? this.timing.slowDownMs, this.timing.maxSlowDownMs);
259
+ const until = Math.max(r.blocked_until ?? 0, now + wait);
260
+ this.saveReceiver(receiver, { ...r, blocked_until: until });
261
+ if (row) {
262
+ this.sql.run('UPDATE broker_deliveries SET next_at = ?, last_error = ?, last_status = ? WHERE message_id = ? AND receiver = ?', now + wait, failure.error, status, id, receiver);
263
+ }
264
+ return 'slow';
265
+ }
266
+ if (failure.kind === 'fail') {
267
+ // The receiver answered: it is up, and this message will never land there.
268
+ this.sql.run('DELETE FROM broker_receivers WHERE receiver = ?', receiver);
269
+ }
270
+ else if (r.open) {
271
+ // A failed probe: paused again, for longer.
272
+ const pause = Math.min((r.pause_ms ?? this.timing.pauseMs) * 2, this.timing.maxPauseMs);
273
+ this.saveReceiver(receiver, { failures: r.failures + 1, open: 1, pause_ms: pause, blocked_until: now + pause });
274
+ }
275
+ else if (r.failures + 1 >= this.timing.pauseAfterFailures) {
276
+ this.saveReceiver(receiver, { failures: r.failures + 1, open: 1, pause_ms: this.timing.pauseMs, blocked_until: now + this.timing.pauseMs });
277
+ }
278
+ else {
279
+ this.saveReceiver(receiver, { ...r, failures: r.failures + 1 });
280
+ }
281
+ if (!row)
282
+ return 'retry';
283
+ const attempts = row.attempts + 1;
284
+ const policy = this.policies.get(receiver) ?? DEFAULT_DELIVERY_POLICY;
285
+ if (failure.kind === 'fail' || attempts >= policy.attempts) {
286
+ this.sql.run(`UPDATE broker_deliveries SET state = 'dead', attempts = ?, next_at = NULL, dead_at = ?, last_error = ?, last_status = ?
287
+ WHERE message_id = ? AND receiver = ?`, attempts, now, failure.error, status, id, receiver);
288
+ return 'dead';
289
+ }
290
+ this.sql.run('UPDATE broker_deliveries SET attempts = ?, next_at = ?, last_error = ?, last_status = ? WHERE message_id = ? AND receiver = ?', attempts, now + backoffMs(policy, attempts, this.random), failure.error, status, id, receiver);
291
+ return 'retry';
292
+ });
293
+ }
294
+ saveReceiver(receiver, r) {
295
+ this.sql.run(`INSERT INTO broker_receivers (receiver, failures, open, pause_ms, blocked_until) VALUES (?, ?, ?, ?, ?)
296
+ ON CONFLICT (receiver) DO UPDATE SET failures = excluded.failures, open = excluded.open,
297
+ pause_ms = excluded.pause_ms, blocked_until = excluded.blocked_until`, receiver, r.failures, r.open, r.pause_ms, r.blocked_until);
298
+ }
299
+ /**
300
+ * The dead letters at `now`, oldest first; `content` adds each message's body. One past its
301
+ * retention is not listed, whether or not a prune has expired it yet.
302
+ */
303
+ deadLetters(opts, now) {
304
+ const rows = this.sql.all(`SELECT d.message_id, d.receiver, d.attempts, d.dead_at, d.last_error, d.last_status, d.resends,
305
+ m.kind, m.tenant_id, m.scope_id, m.type, m.body, m.committed_at, m.ordering_key
306
+ FROM broker_deliveries d JOIN broker_messages m ON m.id = d.message_id
307
+ WHERE d.state = 'dead' AND d.dead_at > ? AND (? IS NULL OR d.receiver = ?)
308
+ ORDER BY d.dead_at, d.message_id LIMIT ?`, now - this.timing.deadLetterRetentionMs, opts.receiver ?? null, opts.receiver ?? null, opts.limit ?? 50);
309
+ return rows.map((r) => ({
310
+ messageId: r.message_id,
311
+ receiver: r.receiver,
312
+ kind: r.kind,
313
+ type: r.type,
314
+ tenantId: r.tenant_id,
315
+ scopeId: r.scope_id,
316
+ committedAt: r.committed_at,
317
+ key: r.ordering_key,
318
+ attempts: r.attempts,
319
+ lastError: r.last_error,
320
+ lastStatus: r.last_status,
321
+ deadAt: r.dead_at,
322
+ expiresAt: r.dead_at + this.timing.deadLetterRetentionMs,
323
+ resends: r.resends,
324
+ ...(opts.content ? { body: r.body } : {}),
325
+ }));
326
+ }
327
+ /**
328
+ * Resend a dead letter: due now, with its attempts afresh, back at the head of its lane. Only a
329
+ * dead delivery inside its retention moves, so a resend repeated, sent after the message landed, or
330
+ * after the dead letter expired, changes nothing and the receiver gets it at most once. `receiver` omitted: at every receiver where it is dead. Returns how
331
+ * many deliveries it moved.
332
+ */
333
+ resend(id, receiver, now) {
334
+ return this.settleDead(`UPDATE broker_deliveries SET state = 'pending', attempts = 0, next_at = ?, dead_at = NULL, resends = resends + 1`, id, receiver, now);
335
+ }
336
+ /** Discard a dead letter: it settles, and its lane moves on. Idempotent as `resend` is. */
337
+ discard(id, receiver, now) {
338
+ return this.settleDead(`UPDATE broker_deliveries SET state = 'discarded', settled_at = ?`, id, receiver, now);
339
+ }
340
+ settleDead(update, id, receiver, now) {
341
+ return this.sql.transaction(() => {
342
+ const where = "WHERE message_id = ? AND state = 'dead' AND dead_at > ? AND (? IS NULL OR receiver = ?)";
343
+ const args = [id, now - this.timing.deadLetterRetentionMs, receiver ?? null, receiver ?? null];
344
+ const n = this.sql.all(`SELECT COUNT(*) AS n FROM broker_deliveries ${where}`, ...args)[0];
345
+ this.sql.run(`${update} ${where}`, now, ...args);
346
+ return Number(n?.n ?? 0);
347
+ });
348
+ }
349
+ /**
350
+ * Epoch ms the store next has work: the earliest of the next delivery that can go (a lane's head, at
351
+ * a receiver it has, after the receiver's pause or slow-down) and the moment a kept row's bound runs
352
+ * out (a settled message's `deliveredRetentionMs`, a dead letter's `deadLetterRetentionMs`, a held
353
+ * message's `heldRetentionMs`). Null only when it holds nothing, so an idle broker arms nothing and
354
+ * a busy one never keeps a row past its bound for want of an alarm. A message waiting behind its
355
+ * lane's head is not work: the head's settling is what wakes it.
356
+ */
357
+ nextWakeAt() {
358
+ const row = this.sql.all(`SELECT
359
+ (SELECT MIN(MAX(d.next_at, COALESCE(r.blocked_until, 0)))
360
+ FROM broker_deliveries d LEFT JOIN broker_receivers r ON r.receiver = d.receiver
361
+ WHERE d.state = 'pending' AND d.receiver IN (SELECT value FROM json_each(?)) AND ${LANE_HEAD}) AS due,
362
+ (SELECT MIN(last) FROM (SELECT MAX(settled_at) AS last FROM broker_deliveries
363
+ GROUP BY message_id HAVING SUM(state IN ${OPEN}) = 0)) AS settled,
364
+ (SELECT MIN(dead_at) FROM broker_deliveries WHERE state = 'dead') AS dead,
365
+ (SELECT MIN(received_at) FROM broker_messages m
366
+ WHERE NOT EXISTS (SELECT 1 FROM broker_deliveries d WHERE d.message_id = m.id)) AS held`, this.receivers)[0];
367
+ const times = [
368
+ row?.due ?? null,
369
+ row?.settled == null ? null : row.settled + this.timing.deliveredRetentionMs,
370
+ row?.dead == null ? null : row.dead + this.timing.deadLetterRetentionMs,
371
+ row?.held == null ? null : row.held + this.timing.heldRetentionMs,
372
+ ].filter((t) => t !== null);
373
+ return times.length ? Math.min(...times) : null;
374
+ }
375
+ /**
376
+ * Drop what the bounds say has been kept long enough (K-70). A dead letter past its bound expires,
377
+ * which settles it as of when it died, so its message goes in the same prune and its lane moves on.
378
+ * Marks stay: they are one row per scope and kind.
379
+ */
380
+ prune(now) {
381
+ this.sql.transaction(() => {
382
+ this.sql.run("UPDATE broker_deliveries SET state = 'expired', settled_at = dead_at WHERE state = 'dead' AND dead_at <= ?", now - this.timing.deadLetterRetentionMs);
383
+ const settled = this.sql.all(`SELECT message_id FROM broker_deliveries GROUP BY message_id
384
+ HAVING SUM(state IN ${OPEN}) = 0 AND MAX(settled_at) <= ? LIMIT ?`, now - this.timing.deliveredRetentionMs, PRUNE_BATCH);
385
+ if (settled.length) {
386
+ const ids = JSON.stringify(settled.map((s) => s.message_id));
387
+ this.sql.run('DELETE FROM broker_deliveries WHERE message_id IN (SELECT value FROM json_each(?))', ids);
388
+ this.sql.run('DELETE FROM broker_messages WHERE id IN (SELECT value FROM json_each(?))', ids);
389
+ }
390
+ this.pruneHeld(now);
391
+ });
392
+ }
393
+ /** Drop the held messages (no delivery row) past `heldRetentionMs`. */
394
+ pruneHeld(now) {
395
+ this.sql.run(`DELETE FROM broker_messages WHERE received_at <= ?
396
+ AND NOT EXISTS (SELECT 1 FROM broker_deliveries d WHERE d.message_id = broker_messages.id)`, now - this.timing.heldRetentionMs);
397
+ }
398
+ /**
399
+ * #3474: which of `ids` the store already holds, so a receipt can tell a new message from a repeated
400
+ * handoff. Primary-key reads only, in chunks under the Durable Object's bound-parameter limit.
401
+ */
402
+ held(ids) {
403
+ const found = new Set();
404
+ for (let i = 0; i < ids.length; i += HELD_PROBE_CHUNK) {
405
+ const chunk = ids.slice(i, i + HELD_PROBE_CHUNK);
406
+ const rows = this.sql.all(`SELECT id FROM broker_messages WHERE id IN (${chunk.map(() => '?').join(', ')})`, ...chunk);
407
+ for (const r of rows)
408
+ found.add(r.id);
409
+ }
410
+ return found;
411
+ }
412
+ /**
413
+ * #3474: the broker's state in one read — what `pending()` counts and its oldest arrival, the
414
+ * receivers whose breaker is open, and the dead letters. Run once per wake and after each pass,
415
+ * never on a handoff.
416
+ */
417
+ stats() {
418
+ const row = this.sql.all(`SELECT COUNT(*) AS depth, MIN(m.received_at) AS oldest,
419
+ (SELECT COUNT(*) FROM broker_receivers WHERE open = 1) AS paused,
420
+ (SELECT COUNT(*) FROM broker_deliveries WHERE state = 'dead') AS dead
421
+ FROM broker_messages m
422
+ WHERE NOT EXISTS (SELECT 1 FROM broker_deliveries d WHERE d.message_id = m.id)
423
+ OR EXISTS (SELECT 1 FROM broker_deliveries d WHERE d.message_id = m.id AND d.state = 'pending')`)[0];
424
+ return {
425
+ depth: Number(row?.depth ?? 0),
426
+ oldestAt: row?.oldest ?? null,
427
+ pausedReceivers: Number(row?.paused ?? 0),
428
+ deadLetters: Number(row?.dead ?? 0),
429
+ };
430
+ }
431
+ /** #3474: whether a receiver's breaker is open (paused, as against slowed). One primary-key read. */
432
+ paused(receiver) {
433
+ return this.sql.all('SELECT open FROM broker_receivers WHERE receiver = ?', receiver)[0]?.open === 1;
434
+ }
435
+ /**
436
+ * #3474: when a delivery can next be attempted: its own `next_at`, or the receiver's pause or
437
+ * slow-down if that ends later; null when none is scheduled. Two primary-key reads in one statement.
438
+ */
439
+ nextAttemptAt(id, receiver) {
440
+ const row = this.sql.all(`SELECT d.next_at, r.blocked_until FROM broker_deliveries d
441
+ LEFT JOIN broker_receivers r ON r.receiver = d.receiver
442
+ WHERE d.message_id = ? AND d.receiver = ?`, id, receiver)[0];
443
+ if (row?.next_at == null)
444
+ return null;
445
+ return Math.max(row.next_at, row.blocked_until ?? 0);
446
+ }
447
+ /** #3474: the receivers whose breaker is open now, so a reporter that woke knows which pauses it inherits. */
448
+ openReceivers() {
449
+ return this.sql.all('SELECT receiver FROM broker_receivers WHERE open = 1').map((r) => r.receiver);
450
+ }
451
+ /** How many messages it holds that some receiver is still owed (held, or pending somewhere). */
452
+ pending() {
453
+ const row = this.sql.all(`SELECT COUNT(*) AS n FROM broker_messages m
454
+ WHERE NOT EXISTS (SELECT 1 FROM broker_deliveries d WHERE d.message_id = m.id)
455
+ OR EXISTS (SELECT 1 FROM broker_deliveries d WHERE d.message_id = m.id AND d.state = 'pending')`)[0];
456
+ return Number(row?.n ?? 0);
457
+ }
458
+ }
459
+ /** A delivery's key in a pass's `skip` list. */
460
+ const deliveryKey = (d) => `${d.message.id} ${d.receiver}`;
461
+ /**
462
+ * One delivery pass over a store, for both adapters: attempt each due delivery once, record the
463
+ * outcome, and say when the next is due. A receiver's throw is a failure of that delivery alone,
464
+ * read by `classifyFailure`. The pass re-reads what is due as it goes, so the message behind a lane's
465
+ * head goes in the same pass once the head landed, and a receiver that a failure paused (or a probe
466
+ * that failed) is sent nothing more in it. At most `limit` attempts. It prunes first (`prune`).
467
+ */
468
+ export async function runDeliveryPass(store, receivers, now, limit = BROKER_DELIVERY_BATCH, observer) {
469
+ let delivered = 0;
470
+ let failed = 0;
471
+ let deadLettered = 0;
472
+ // Attempted this pass. One `due` returned but no longer sendable is not in it: it may go later in
473
+ // the pass, once the head that overtook it has landed.
474
+ const tried = [];
475
+ // First, so a dead letter that expired releases its lane to this pass.
476
+ store.prune(now());
477
+ // `due` only returns what `sendable` admits, so a round attempts something unless a send raced it;
478
+ // the rounds are bounded all the same.
479
+ for (let round = 0; round < limit && tried.length < limit; round++) {
480
+ const batch = store.due(now(), limit - tried.length, tried);
481
+ if (!batch.length)
482
+ break;
483
+ for (const d of batch) {
484
+ if (tried.length >= limit)
485
+ break;
486
+ const receiver = receivers[d.receiver];
487
+ if (!receiver || !store.sendable(d.message.id, d.receiver, now()))
488
+ continue;
489
+ tried.push(deliveryKey(d));
490
+ // #3484: read again just before it goes. A delivery awaits its receiver, and an erasure can run
491
+ // meanwhile; the rest of a batch read before it must go as the store now holds it.
492
+ const message = store.current(d.message.id);
493
+ if (!message)
494
+ continue;
495
+ const startedAt = now();
496
+ try {
497
+ await receiver.deliver(message);
498
+ }
499
+ catch (err) {
500
+ const outcome = store.failed(d.message.id, d.receiver, classifyFailure(err), now());
501
+ if (outcome === 'dead')
502
+ deadLettered++;
503
+ else
504
+ failed++;
505
+ observer?.attempted(d, outcome, startedAt, now());
506
+ continue;
507
+ }
508
+ // Outside the receiver's `try`: a storage error here is the broker's, never the receiver's failure.
509
+ store.delivered(d.message.id, d.receiver, now());
510
+ delivered++;
511
+ observer?.attempted(d, 'delivered', startedAt, now());
512
+ }
513
+ }
514
+ return { delivered, failed, deadLettered, nextAt: store.nextWakeAt() };
515
+ }
516
+ //# sourceMappingURL=delivery-broker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delivery-broker.js","sourceRoot":"","sources":["../src/delivery-broker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EACL,sBAAsB,EACtB,oBAAoB,GAGrB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,aAAa,EACb,uBAAuB,EACvB,SAAS,EACT,eAAe,EACf,aAAa,GA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AAE,SAAS,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,CAAC;gBAClD,SAAS;YACX,CAAC;YACD,oGAAoG;YACpG,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,CAAC;YACjD,SAAS,EAAE,CAAC;YACZ,QAAQ,EAAE,SAAS,CAAC,CAAC,EAAE,WAAW,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,CAAC;QACxD,CAAC;IACH,CAAC;IACD,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,KAAK,CAAC,UAAU,EAAE,EAAE,CAAC;AACzE,CAAC"}
@@ -0,0 +1,105 @@
1
+ /**
2
+ * What the delivery broker does when a delivery fails (K-74, rfc/broker-and-tenant-isolation.md
3
+ * §4.5–§4.6): the receiver's policy per subscription, and what the platform decides when nobody
4
+ * declared anything.
5
+ *
6
+ * | Who | Decides |
7
+ * |---|---|
8
+ * | The receiver, per subscription | `DeliveryPolicy`: attempts, a growing backoff with jitter, whether it needs order |
9
+ * | The platform, undeclared | `BrokerTiming`: the pause per receiver, the slow-down, how long a dead letter is kept; and `classifyFailure`: which failures retry |
10
+ *
11
+ * The sender's half (time to live, whether a repeat is safe, the ordering key) is the message's: the
12
+ * key travels as `BrokerMessage.key`, set at handoff.
13
+ *
14
+ * **Which failures retry** (`classifyFailure`). A receiver throws; what it throws decides:
15
+ * - a `429`, or anything carrying `retryAfterMs` (`Retry-After`), is **slow down**: not a failure. No
16
+ * attempt is spent and the run toward a pause does not grow; the receiver is sent nothing until the
17
+ * wait passes.
18
+ * - any other `4xx` (but `408`), or a schema error (a `ZodError`, or `permanent: true`), **fails at
19
+ * once**: the message goes to dead letter with one attempt spent. The receiver answered, so the run
20
+ * toward a pause resets.
21
+ * - a `5xx`, a `408`, a timeout, or a throw that says nothing (a network error), is **retried**: one
22
+ * attempt spent, the next after the policy's backoff, and one more toward the receiver's pause.
23
+ *
24
+ * **Pause per receiver** (circuit breaker). After `pauseAfterFailures` retried failures in a row to
25
+ * one receiver, the broker sends it nothing for `pauseMs`. The first delivery after that is the one
26
+ * probe: it spends its message's attempt like any send. A success resumes everything; a failure
27
+ * pauses again for twice as long, up to `maxPauseMs`. While paused, messages wait and spend no
28
+ * attempts, so a receiver that is down does not exhaust what was sent to it.
29
+ */
30
+ /** A receiver's policy for one subscription. */
31
+ export interface DeliveryPolicy {
32
+ /** Attempts before the message goes to dead letter. */
33
+ attempts: number;
34
+ /** The wait after the n-th failure: `initialMs * multiplier^(n-1)`, at most `maxMs`. */
35
+ backoff: {
36
+ initialMs: number;
37
+ multiplier: number;
38
+ maxMs: number;
39
+ };
40
+ /** The part of each wait drawn at random, 0 to 1: a wait of `w` becomes one in `[w * (1 - jitter), w]`. */
41
+ jitter: number;
42
+ /** Deliver in order per the sender's key: one lane per (receiver, key). A message with no key is unordered. */
43
+ ordered: boolean;
44
+ }
45
+ /** A policy as a subscription declares it: every field optional, the rest the platform's. */
46
+ export type DeliveryPolicyInput = Partial<Omit<DeliveryPolicy, 'backoff'>> & {
47
+ backoff?: Partial<DeliveryPolicy['backoff']>;
48
+ };
49
+ /** The platform's policy where a subscription declares none: 1 s, 4 s, 16 s, … to 10 min, 8 attempts, unordered. */
50
+ export declare const DEFAULT_DELIVERY_POLICY: DeliveryPolicy;
51
+ /** A declared policy over the platform's defaults. */
52
+ export declare const resolvePolicy: (input?: DeliveryPolicyInput) => DeliveryPolicy;
53
+ /** What the platform decides for every receiver of one broker. A host option; these are production's. */
54
+ export interface BrokerTiming {
55
+ /** Retried failures in a row that pause a receiver. */
56
+ pauseAfterFailures: number;
57
+ /** The first pause; a failed probe doubles it. */
58
+ pauseMs: number;
59
+ maxPauseMs: number;
60
+ /** The slow-down after a `429` that names no `Retry-After`. */
61
+ slowDownMs: number;
62
+ /** The most a `Retry-After` is honoured for. */
63
+ maxSlowDownMs: number;
64
+ /** How long a dead letter is kept, to be resent or discarded. */
65
+ deadLetterRetentionMs: number;
66
+ /** How long a settled message is kept, for a duplicate handoff to find it. */
67
+ deliveredRetentionMs: number;
68
+ /** How long a message is held when the broker had no receiver for it (the K-70 bound until A5). */
69
+ heldRetentionMs: number;
70
+ }
71
+ export declare const BROKER_TIMING: BrokerTiming;
72
+ /** The wait after `attempts` failures under a policy, `random` drawing the jitter (0 ≤ r < 1). */
73
+ export declare function backoffMs(policy: DeliveryPolicy, attempts: number, random: () => number): number;
74
+ /**
75
+ * What a receiver throws to say how a delivery failed. Any throw is a failure; this one says which
76
+ * kind. Its fields are read by shape, so an error that crossed an RPC hop with them still counts.
77
+ */
78
+ export declare class DeliveryFailure extends Error {
79
+ readonly status?: number;
80
+ readonly retryAfterMs?: number;
81
+ readonly permanent?: boolean;
82
+ constructor(message: string, detail?: {
83
+ status?: number;
84
+ retryAfterMs?: number;
85
+ permanent?: boolean;
86
+ });
87
+ }
88
+ /** How the broker treats one failed delivery. */
89
+ export type FailureClass = {
90
+ kind: 'retry';
91
+ error: string;
92
+ status?: number;
93
+ } | {
94
+ kind: 'fail';
95
+ error: string;
96
+ status?: number;
97
+ } | {
98
+ kind: 'slow';
99
+ error: string;
100
+ status?: number;
101
+ afterMs?: number;
102
+ };
103
+ /** The platform's reading of a receiver's throw (see the header). */
104
+ export declare function classifyFailure(err: unknown): FailureClass;
105
+ //# sourceMappingURL=delivery-policy.d.ts.map