@substrat-run/kernel 0.217.0 → 0.218.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 (61) hide show
  1. package/dist/broker-counts.d.ts +108 -0
  2. package/dist/broker-counts.d.ts.map +1 -0
  3. package/dist/broker-counts.js +101 -0
  4. package/dist/broker-counts.js.map +1 -0
  5. package/dist/broker-schema.d.ts.map +1 -1
  6. package/dist/broker-schema.js +58 -0
  7. package/dist/broker-schema.js.map +1 -1
  8. package/dist/broker-shadow.d.ts +258 -0
  9. package/dist/broker-shadow.d.ts.map +1 -0
  10. package/dist/broker-shadow.js +295 -0
  11. package/dist/broker-shadow.js.map +1 -0
  12. package/dist/broker-telemetry.d.ts +3 -2
  13. package/dist/broker-telemetry.d.ts.map +1 -1
  14. package/dist/broker-telemetry.js +7 -5
  15. package/dist/broker-telemetry.js.map +1 -1
  16. package/dist/delivery-broker.d.ts +47 -5
  17. package/dist/delivery-broker.d.ts.map +1 -1
  18. package/dist/delivery-broker.js +115 -60
  19. package/dist/delivery-broker.js.map +1 -1
  20. package/dist/directory-lake-keep.d.ts +9 -0
  21. package/dist/directory-lake-keep.d.ts.map +1 -0
  22. package/dist/directory-lake-keep.js +331 -0
  23. package/dist/directory-lake-keep.js.map +1 -0
  24. package/dist/directory-lake-projection.d.ts +50 -0
  25. package/dist/directory-lake-projection.d.ts.map +1 -0
  26. package/dist/directory-lake-projection.js +143 -0
  27. package/dist/directory-lake-projection.js.map +1 -0
  28. package/dist/directory-lake.d.ts +11 -1
  29. package/dist/directory-lake.d.ts.map +1 -1
  30. package/dist/directory-lake.js +3 -1
  31. package/dist/directory-lake.js.map +1 -1
  32. package/dist/index.d.ts +7 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +7 -0
  35. package/dist/index.js.map +1 -1
  36. package/dist/migration-digest.d.ts +2 -2
  37. package/dist/migration-digest.d.ts.map +1 -1
  38. package/dist/migration-digest.js +4 -2
  39. package/dist/migration-digest.js.map +1 -1
  40. package/dist/migration-fence.d.ts +1 -1
  41. package/dist/migration-fence.js +3 -3
  42. package/dist/migration-fence.js.map +1 -1
  43. package/dist/scope-host.d.ts +26 -1
  44. package/dist/scope-host.d.ts.map +1 -1
  45. package/dist/scope-host.js.map +1 -1
  46. package/dist/spine-guard.d.ts.map +1 -1
  47. package/dist/spine-guard.js +2 -0
  48. package/dist/spine-guard.js.map +1 -1
  49. package/dist/spine-restore.d.ts +14 -2
  50. package/dist/spine-restore.d.ts.map +1 -1
  51. package/dist/spine-restore.js.map +1 -1
  52. package/dist/store-driver-releases.d.ts +3 -1
  53. package/dist/store-driver-releases.d.ts.map +1 -1
  54. package/dist/table-ownership.d.ts +6 -0
  55. package/dist/table-ownership.d.ts.map +1 -1
  56. package/dist/table-ownership.js +17 -3
  57. package/dist/table-ownership.js.map +1 -1
  58. package/dist/vertical-owners.d.ts +1 -1
  59. package/dist/vertical-owners.d.ts.map +1 -1
  60. package/dist/vertical-owners.js.map +1 -1
  61. package/package.json +2 -2
@@ -0,0 +1,108 @@
1
+ /**
2
+ * #3474 (rfc/broker-and-tenant-isolation.md §9.2, K-70): the delivery broker's EXACT counts, kept per
3
+ * UTC day in its own SQLite and shipped to the lake. Analytics Engine samples at volume, which is
4
+ * enough for trends and alarms (`broker-telemetry.ts`) and not for billing. These are counted in the
5
+ * same transaction as the decision they count, so a count is a fact about the store, never an
6
+ * estimate.
7
+ *
8
+ * **What is counted**, per (day, tenant, scope, channel, receiver, outcome): a message `received`
9
+ * (once, at its first acceptance; a duplicate handoff counts nothing; receiver `''`), and per
10
+ * receiver a delivery `delivered`, an attempt `retried` (a failure the broker will try again; a
11
+ * slow-down spends nothing and counts nothing), a delivery gone `dead`, a dead letter `resent` or
12
+ * `discarded` by a person, and one `expired` unresent. Never content: ids, the channel and the
13
+ * receiver's name.
14
+ *
15
+ * **Shipped, then bounded (K-70).** A row is shipped when its count moves past what the lake has: it
16
+ * carries its whole count, so the lake keeps a key's latest version (`BrokerLakeRow`, the directory's
17
+ * outbox shape, dataset `broker_count_days`). What was shipped is recorded as the count shipped, not
18
+ * as "shipped": a count that moved while the ship was in flight goes again. Shipping is at most
19
+ * every `BROKER_COUNT_SHIP_MS` (D-77's five minutes), from the broker's own alarm, so K-69 holds.
20
+ * A day is dropped once the lake has all of it and it is older than `BROKER_COUNT_KEEP_DAYS` (the
21
+ * current and the previous billing period, as the directory keeps meter days); a day never shipped,
22
+ * because no lake was ever bound, is dropped at `BROKER_COUNT_MAX_DAYS`, so an unbound broker is
23
+ * bounded too.
24
+ *
25
+ * Its table is step 5 of `broker-schema.ts`.
26
+ */
27
+ import type { BrokerMessageKind, BrokerSql } from './delivery-broker.js';
28
+ /** What happened, as a count names it. */
29
+ export type BrokerCountOutcome = 'received' | 'delivered' | 'retried' | 'dead' | 'resent' | 'discarded' | 'expired';
30
+ export declare const BROKER_COUNT_OUTCOMES: readonly BrokerCountOutcome[];
31
+ /**
32
+ * The Pipelines stream binding a broker ships its counts through, on the app's script. No binding, no
33
+ * ship: the counts are kept, bounded by `BROKER_COUNT_MAX_DAYS`, and the lake has none of them.
34
+ */
35
+ export declare const BROKER_LAKE_BINDING = "SUBSTRAT_BROKER_LAKE";
36
+ /** The least time between two ships of one broker's counts: D-77's freshness bound. */
37
+ export declare const BROKER_COUNT_SHIP_MS: number;
38
+ /** Days kept once the lake has them all: the current and the previous billing period. */
39
+ export declare const BROKER_COUNT_KEEP_DAYS = 62;
40
+ /** Days kept whatever the lake has: the bound of a broker that never had a lake to ship to. */
41
+ export declare const BROKER_COUNT_MAX_DAYS = 400;
42
+ /** Rows one ship carries; a larger backlog follows in the next. */
43
+ export declare const BROKER_COUNT_SHIP_BATCH = 500;
44
+ /** One count to add. `receiver` is `''` for what is not about a receiver (`received`). */
45
+ export interface BrokerCount {
46
+ tenantId: string;
47
+ scopeId: string;
48
+ channel: BrokerMessageKind;
49
+ receiver: string;
50
+ outcome: BrokerCountOutcome;
51
+ n: number;
52
+ }
53
+ /** One day's count, as the store keeps it. */
54
+ export interface BrokerCountDay extends BrokerCount {
55
+ /** The UTC day, `YYYY-MM-DD`. */
56
+ day: string;
57
+ /** How much of `n` the lake has. */
58
+ shipped: number;
59
+ }
60
+ /** The UTC day of an epoch-ms instant. */
61
+ export declare const utcDay: (at: number) => string;
62
+ /** Add counts for the day of `now`. Run inside the transaction that made the decision counted. */
63
+ export declare function addBrokerCounts(sql: BrokerSql, counts: readonly BrokerCount[], now: number): void;
64
+ /** The counts on or after `since` (a UTC day), oldest first: what a billing read or a test asks. */
65
+ export declare function readBrokerCounts(sql: BrokerSql, since?: string): BrokerCountDay[];
66
+ /** The rows the lake does not have all of yet, oldest change first. */
67
+ export declare function unshippedBrokerCounts(sql: BrokerSql, limit?: number): BrokerCountDay[];
68
+ /** Record that the lake has each row up to the count it was shipped with. Never moves one back. */
69
+ export declare function markBrokerCountsShipped(sql: BrokerSql, rows: readonly BrokerCountDay[]): void;
70
+ /** When the next ship is due: `BROKER_COUNT_SHIP_MS` after the oldest unshipped change, or null with none. */
71
+ export declare function nextBrokerCountShipAt(sql: BrokerSql): number | null;
72
+ /** Drop the days the bounds say are kept long enough. Run in the store's prune. */
73
+ export declare function pruneBrokerCounts(sql: BrokerSql, now: number): void;
74
+ /**
75
+ * One count as the lake gets it: the directory outbox's row shape (`DirectoryLakeRow`), dataset
76
+ * `broker_count_days`, keyed by (day, tenant, app, scope, channel, receiver, outcome). A key's latest
77
+ * version (the greatest `count`) is its count.
78
+ */
79
+ export interface BrokerLakeRow {
80
+ dataset: 'broker_count_days';
81
+ rowKey: string;
82
+ tenantId: string;
83
+ scopeId: string;
84
+ /** The UTC day counted. */
85
+ at: string;
86
+ /** The outcome counted. */
87
+ kind: BrokerCountOutcome;
88
+ actor: null;
89
+ capturedAt: string;
90
+ /** The count, a JSON object text: `{ day, tenant_id, app, scope_id, channel, receiver, outcome, n }`. */
91
+ row: string;
92
+ }
93
+ /**
94
+ * Where a broker's counts go: a Pipelines stream on the Durable Object, a recorder in a test. Like
95
+ * `DirectoryLakeSink`, `ship` MUST be durable before it resolves: a resolved ship is what marks the
96
+ * counts shipped, and lets a day be dropped.
97
+ */
98
+ export interface BrokerLakeSink {
99
+ ship(rows: BrokerLakeRow[]): Promise<void>;
100
+ }
101
+ /** The lake rows for some counts of one app's broker. */
102
+ export declare function brokerLakeRows(rows: readonly BrokerCountDay[], app: string, capturedAt: string): BrokerLakeRow[];
103
+ /**
104
+ * Ship one batch of what the lake does not have, and mark it. A sink that throws marks nothing: the
105
+ * rows go again at the next ship. Returns how many rows went.
106
+ */
107
+ export declare function shipBrokerCounts(sql: BrokerSql, sink: BrokerLakeSink, app: string, now: number): Promise<number>;
108
+ //# sourceMappingURL=broker-counts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"broker-counts.d.ts","sourceRoot":"","sources":["../src/broker-counts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEzE,0CAA0C;AAC1C,MAAM,MAAM,kBAAkB,GAAG,UAAU,GAAG,WAAW,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,GAAG,WAAW,GAAG,SAAS,CAAC;AAEpH,eAAO,MAAM,qBAAqB,EAAE,SAAS,kBAAkB,EAAmF,CAAC;AAEnJ;;;GAGG;AACH,eAAO,MAAM,mBAAmB,yBAAyB,CAAC;AAE1D,uFAAuF;AACvF,eAAO,MAAM,oBAAoB,QAAa,CAAC;AAC/C,yFAAyF;AACzF,eAAO,MAAM,sBAAsB,KAAK,CAAC;AACzC,+FAA+F;AAC/F,eAAO,MAAM,qBAAqB,MAAM,CAAC;AACzC,mEAAmE;AACnE,eAAO,MAAM,uBAAuB,MAAM,CAAC;AAE3C,0FAA0F;AAC1F,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,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IACX,2BAA2B;IAC3B,IAAI,EAAE,kBAAkB,CAAC;IACzB,KAAK,EAAE,IAAI,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;IACnB,yGAAyG;IACzG,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,IAAI,CAAC,IAAI,EAAE,aAAa,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5C;AAED,yDAAyD;AACzD,wBAAgB,cAAc,CAAC,IAAI,EAAE,SAAS,cAAc,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,aAAa,EAAE,CAchH;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAMtH"}
@@ -0,0 +1,101 @@
1
+ export const BROKER_COUNT_OUTCOMES = ['received', 'delivered', 'retried', 'dead', 'resent', 'discarded', 'expired'];
2
+ /**
3
+ * The Pipelines stream binding a broker ships its counts through, on the app's script. No binding, no
4
+ * ship: the counts are kept, bounded by `BROKER_COUNT_MAX_DAYS`, and the lake has none of them.
5
+ */
6
+ export const BROKER_LAKE_BINDING = 'SUBSTRAT_BROKER_LAKE';
7
+ /** The least time between two ships of one broker's counts: D-77's freshness bound. */
8
+ export const BROKER_COUNT_SHIP_MS = 5 * 60_000;
9
+ /** Days kept once the lake has them all: the current and the previous billing period. */
10
+ export const BROKER_COUNT_KEEP_DAYS = 62;
11
+ /** Days kept whatever the lake has: the bound of a broker that never had a lake to ship to. */
12
+ export const BROKER_COUNT_MAX_DAYS = 400;
13
+ /** Rows one ship carries; a larger backlog follows in the next. */
14
+ export const BROKER_COUNT_SHIP_BATCH = 500;
15
+ /** The UTC day of an epoch-ms instant. */
16
+ export const utcDay = (at) => new Date(at).toISOString().slice(0, 10);
17
+ /** Add counts for the day of `now`. Run inside the transaction that made the decision counted. */
18
+ export function addBrokerCounts(sql, counts, now) {
19
+ const day = utcDay(now);
20
+ for (const c of counts) {
21
+ if (c.n <= 0)
22
+ continue;
23
+ sql.run(`INSERT INTO broker_count_days (day, tenant_id, scope_id, channel, receiver, outcome, n, updated_at)
24
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
25
+ ON CONFLICT (day, tenant_id, scope_id, channel, receiver, outcome)
26
+ DO UPDATE SET n = n + excluded.n, updated_at = excluded.updated_at`, day, c.tenantId, c.scopeId, c.channel, c.receiver, c.outcome, c.n, now);
27
+ }
28
+ }
29
+ const dayOf = (r) => ({
30
+ day: r.day,
31
+ tenantId: r.tenant_id,
32
+ scopeId: r.scope_id,
33
+ channel: r.channel,
34
+ receiver: r.receiver,
35
+ outcome: r.outcome,
36
+ n: Number(r.n),
37
+ shipped: Number(r.shipped_n),
38
+ });
39
+ /** The counts on or after `since` (a UTC day), oldest first: what a billing read or a test asks. */
40
+ export function readBrokerCounts(sql, since = '0000-00-00') {
41
+ return sql
42
+ .all(`SELECT day, tenant_id, scope_id, channel, receiver, outcome, n, shipped_n FROM broker_count_days
43
+ WHERE day >= ? ORDER BY day, tenant_id, scope_id, channel, receiver, outcome`, since)
44
+ .map(dayOf);
45
+ }
46
+ /** The rows the lake does not have all of yet, oldest change first. */
47
+ export function unshippedBrokerCounts(sql, limit = BROKER_COUNT_SHIP_BATCH) {
48
+ return sql
49
+ .all(`SELECT day, tenant_id, scope_id, channel, receiver, outcome, n, shipped_n FROM broker_count_days
50
+ WHERE n > shipped_n ORDER BY updated_at LIMIT ?`, limit)
51
+ .map(dayOf);
52
+ }
53
+ /** Record that the lake has each row up to the count it was shipped with. Never moves one back. */
54
+ export function markBrokerCountsShipped(sql, rows) {
55
+ sql.transaction(() => {
56
+ for (const r of rows) {
57
+ sql.run(`UPDATE broker_count_days SET shipped_n = MAX(shipped_n, ?)
58
+ WHERE day = ? AND tenant_id = ? AND scope_id = ? AND channel = ? AND receiver = ? AND outcome = ?`, r.n, r.day, r.tenantId, r.scopeId, r.channel, r.receiver, r.outcome);
59
+ }
60
+ });
61
+ }
62
+ /** When the next ship is due: `BROKER_COUNT_SHIP_MS` after the oldest unshipped change, or null with none. */
63
+ export function nextBrokerCountShipAt(sql) {
64
+ const row = sql.all('SELECT MIN(updated_at) AS at FROM broker_count_days WHERE n > shipped_n')[0];
65
+ return row?.at == null ? null : Number(row.at) + BROKER_COUNT_SHIP_MS;
66
+ }
67
+ /** Drop the days the bounds say are kept long enough. Run in the store's prune. */
68
+ export function pruneBrokerCounts(sql, now) {
69
+ const day = (days) => utcDay(now - days * 86_400_000);
70
+ sql.run('DELETE FROM broker_count_days WHERE day < ? AND n = shipped_n', day(BROKER_COUNT_KEEP_DAYS));
71
+ sql.run('DELETE FROM broker_count_days WHERE day < ?', day(BROKER_COUNT_MAX_DAYS));
72
+ }
73
+ /** The lake rows for some counts of one app's broker. */
74
+ export function brokerLakeRows(rows, app, capturedAt) {
75
+ return rows.map((r) => ({
76
+ dataset: 'broker_count_days',
77
+ rowKey: JSON.stringify([r.day, r.tenantId, app, r.scopeId, r.channel, r.receiver, r.outcome]),
78
+ tenantId: r.tenantId,
79
+ scopeId: r.scopeId,
80
+ at: r.day,
81
+ kind: r.outcome,
82
+ actor: null,
83
+ capturedAt,
84
+ row: JSON.stringify({
85
+ day: r.day, tenant_id: r.tenantId, app, scope_id: r.scopeId, channel: r.channel, receiver: r.receiver, outcome: r.outcome, n: r.n,
86
+ }),
87
+ }));
88
+ }
89
+ /**
90
+ * Ship one batch of what the lake does not have, and mark it. A sink that throws marks nothing: the
91
+ * rows go again at the next ship. Returns how many rows went.
92
+ */
93
+ export async function shipBrokerCounts(sql, sink, app, now) {
94
+ const rows = unshippedBrokerCounts(sql);
95
+ if (rows.length === 0)
96
+ return 0;
97
+ await sink.ship(brokerLakeRows(rows, app, new Date(now).toISOString()));
98
+ markBrokerCountsShipped(sql, rows);
99
+ return r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BAAkB,CAAC,GAAG,EAAE,SAAS,GAAG,IAAI,CAWvD"}
1
+ {"version":3,"file":"broker-schema.d.ts","sourceRoot":"","sources":["../src/broker-schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEtD,6DAA6D;AAC7D,MAAM,WAAW,gBAAgB;IAC/B,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;CACxC;AAED,eAAO,MAAM,aAAa,EAAE,SAAS,gBAAgB,EA+OpD,CAAC;AAEF,kFAAkF;AAClF,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,SAAS,GAAG,IAAI,CAWvD"}
@@ -179,6 +179,64 @@ export const BROKER_SCHEMA = [
179
179
  'CREATE INDEX broker_waits_resume ON broker_waits (resume_next_at) WHERE resume_next_at IS NOT NULL',
180
180
  ],
181
181
  },
182
+ {
183
+ by: '#3471 (A5): the mode a message was handed off under, the shadow recorder and its windows',
184
+ // `broker-shadow.ts`. Ids, types and times only: no table here holds a message's body.
185
+ statements: [
186
+ // 'shadow' | 'live', or NULL for a handoff that named no mode (every receiver, as A1–A4).
187
+ // Which receivers a held message is owed when receivers appear is read from it.
188
+ 'ALTER TABLE broker_messages ADD COLUMN handoff_mode TEXT',
189
+ // One row per message the recorder got: the message row without its body, and when.
190
+ `CREATE TABLE broker_shadow_records (
191
+ message_id TEXT PRIMARY KEY,
192
+ kind TEXT NOT NULL,
193
+ tenant_id TEXT NOT NULL,
194
+ scope_id TEXT NOT NULL,
195
+ type TEXT NOT NULL,
196
+ committed_at TEXT NOT NULL,
197
+ received_at INTEGER NOT NULL,
198
+ recorded_at INTEGER NOT NULL
199
+ )`,
200
+ 'CREATE INDEX broker_shadow_records_scope ON broker_shadow_records (scope_id, kind, message_id)',
201
+ 'CREATE INDEX broker_shadow_records_age ON broker_shadow_records (recorded_at)',
202
+ // Where each scope's comparison window starts: the marks its handoff was seeded at.
203
+ `CREATE TABLE broker_shadow_starts (
204
+ tenant_id TEXT NOT NULL,
205
+ scope_id TEXT NOT NULL,
206
+ kind TEXT NOT NULL,
207
+ start_after TEXT NOT NULL,
208
+ started_at INTEGER NOT NULL,
209
+ PRIMARY KEY (tenant_id, scope_id, kind)
210
+ )`,
211
+ ],
212
+ },
213
+ {
214
+ by: '#3474: the trace a message was committed under, and the exact counts the lake keeps',
215
+ statements: [
216
+ // The W3C trace id (#3386) of the request whose commit handed the message off, when the
217
+ // handoff ran inside it, and the invocation that wrote the outbox row (#1525's
218
+ // correlation, which joins to the trace through the invocation's own line). Ids only.
219
+ 'ALTER TABLE broker_messages ADD COLUMN trace_id TEXT',
220
+ 'ALTER TABLE broker_messages ADD COLUMN invocation_id TEXT',
221
+ // Exact counts per UTC day (`broker-counts.ts`): `n` counted, `shipped_n` of it in the lake.
222
+ `CREATE TABLE broker_count_days (
223
+ day TEXT NOT NULL,
224
+ tenant_id TEXT NOT NULL,
225
+ scope_id TEXT NOT NULL,
226
+ channel TEXT NOT NULL,
227
+ -- '' for a count that is not about a receiver (received)
228
+ receiver TEXT NOT NULL,
229
+ -- received | delivered | retried | dead | resent | discarded | expired
230
+ outcome TEXT NOT NULL,
231
+ n INTEGER NOT NULL DEFAULT 0,
232
+ shipped_n INTEGER NOT NULL DEFAULT 0,
233
+ -- epoch ms the count last moved: when it is due to ship
234
+ updated_at INTEGER NOT NULL,
235
+ PRIMARY KEY (day, tenant_id, scope_id, channel, receiver, outcome)
236
+ )`,
237
+ 'CREATE INDEX broker_count_days_unshipped ON broker_count_days (updated_at) WHERE n > shipped_n',
238
+ ],
239
+ },
182
240
  ];
183
241
  /** Run the steps a broker's database has not run yet, each in one transaction. */
184
242
  export function migrateBrokerStore(sql) {
@@ -1 +1 @@
1
- {"version":3,"file":"broker-schema.js","sourceRoot":"","sources":["../src/broker-schema.ts"],"names":[],"mappings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AAS,CAAC,CAAC;YACzE,GAAG,CAAC,GAAG,CAAC,sCAAsC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;QACzD,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC"}
@@ -0,0 +1,258 @@
1
+ /**
2
+ * A5 (#3471, rfc/broker-and-tenant-isolation.md §4.7): the broker in shadow beside the drain, the
3
+ * comparison of the two, and the switch that makes the broker the real path for a tenant.
4
+ *
5
+ * **Three modes, per tenant**, decided by the control plane (`DELIVERY_BROKER_SHADOW`,
6
+ * `DELIVERY_BROKER_LIVE`) and told to each scope on the answer to its wake (`wake.broker`):
7
+ *
8
+ * - `off`: the scope hands nothing off. The drain is the only path, as before A1.
9
+ * - `shadow`: the scope hands off, and the broker delivers every message to the recorder alone
10
+ * (`SHADOW_RECEIVER`). The recorder writes one row into the broker's own database and does
11
+ * nothing else: no consumer runs, no intent is executed, no call leaves. The drain stays the real
12
+ * path.
13
+ * - `live`: as `shadow`, and each intent is also owed to the real receiver (`LIVE_RECEIVER`), which
14
+ * asks the platform's drain engine to run that scope's intents now and holds the delivery until
15
+ * the intent is settled. The control plane stops driving that tenant's young intents itself; the
16
+ * broker is the one that asks. Events keep their existing path in every mode until their real
17
+ * receivers are hosted (the lake as a subscriber, A6; the relay, A3's hosted half), and are only
18
+ * recorded.
19
+ *
20
+ * **Which receivers a message is owed is fixed when the broker accepts it**, from the mode the
21
+ * scope handed it off under (`receiversFor`), and stored with the message (`handoff_mode`). That is
22
+ * the whole of the shadow guarantee: a message handed off in shadow has no delivery row at the real
23
+ * receiver, so no later pass, mode change or restart can send it there. A message handed off live
24
+ * keeps its live delivery after a cut-back, and the live receiver is idempotent on the intent's own
25
+ * state, so the drain taking it back and the broker finishing it never run it twice.
26
+ *
27
+ * **The recorder stores no content.** A record is the broker's own message row without its body —
28
+ * its id, kind, scope, type and commit time — plus when the recorder got it. A subject's erasure has
29
+ * nothing in it to redact (`broker-erasure.ts` reaches the bodies the broker holds, which this never
30
+ * copies).
31
+ *
32
+ * **The comparison** pairs, per (tenant, app), what the recorder got with what the drain did, read
33
+ * from each scope's own rows at comparison time (`witnessQueries`): an intent the drain settled
34
+ * (`settled_at`), an event it shipped to the lake (`drained_at`). Nothing is written on the drain's
35
+ * path to make that possible. The window starts at each scope's handoff start (the marks it was
36
+ * seeded at when the mode went on, `ShadowRecorder.start`) and ends `graceMs` ago: a message
37
+ * younger than that is in flight on one side or both, and is counted apart.
38
+ */
39
+ import type { BrokerMessage, BrokerMessageKind, BrokerSql, DeliveryReceiver, HandoffMarks } from './delivery-broker.js';
40
+ export type DeliveryMode = 'off' | 'shadow' | 'live';
41
+ export declare const DELIVERY_MODES: readonly DeliveryMode[];
42
+ export declare const isDeliveryMode: (v: unknown) => v is DeliveryMode;
43
+ /** The recorder's subscription: every message handed off in shadow or live. */
44
+ export declare const SHADOW_RECEIVER = "shadow";
45
+ /** The real receiver's subscription: intents handed off live. */
46
+ export declare const LIVE_RECEIVER = "live";
47
+ /**
48
+ * The env var a script sets to hand off whatever the control plane says, owing every receiver as
49
+ * A1–A4 did: `always`. For a test worker or a self-hosted script with no control plane to ask. The
50
+ * uploader never sets it.
51
+ */
52
+ export declare const DELIVERY_HANDOFF_ENV = "SUBSTRAT_DELIVERY_HANDOFF";
53
+ /** What a handoff says about the messages it carries (`DeliveryBroker.handOff`'s second argument). */
54
+ export interface HandOffOptions {
55
+ /** The mode the scope handed them off under. Absent (a scope from before A5, a harness): every receiver. */
56
+ mode?: 'shadow' | 'live';
57
+ /**
58
+ * The marks this scope began handing off after, when its mode last went on: the comparison's
59
+ * window starts there (`ShadowRecorder.start`). Sent, with no messages if need be, until the broker
60
+ * has acknowledged one handoff carrying it.
61
+ */
62
+ start?: {
63
+ tenantId: string;
64
+ scopeId: string;
65
+ after: HandoffMarks;
66
+ };
67
+ }
68
+ /**
69
+ * The receivers a message is owed, from the mode it was handed off under: `undefined` is every
70
+ * receiver the store has (no mode: A1–A4's behaviour). Only names the store knows are owed.
71
+ */
72
+ export declare function receiversFor(mode: string | null | undefined, kind: BrokerMessageKind): readonly string[] | undefined;
73
+ /** How long a record is kept: the week the comparison is read over, and a day. */
74
+ export declare const SHADOW_RETENTION_MS: number;
75
+ /** How young a message may be and still be in flight on either side: the drain's 15-minute pass, and the lake's 5. */
76
+ export declare const SHADOW_GRACE_MS: number;
77
+ /** One message as the recorder got it. No body, by construction. */
78
+ export interface ShadowRecord {
79
+ id: string;
80
+ kind: BrokerMessageKind;
81
+ tenantId: string;
82
+ scopeId: string;
83
+ type: string;
84
+ committedAt: string;
85
+ /** Epoch ms the broker accepted it, and the recorder got it. */
86
+ receivedAt: number;
87
+ recordedAt: number;
88
+ }
89
+ /** A scope the recorder has a window for. */
90
+ export interface ShadowScope {
91
+ tenantId: string;
92
+ scopeId: string;
93
+ /** The marks its handoff started after, per kind. */
94
+ start: HandoffMarks;
95
+ /** Epoch ms the window began. */
96
+ startedAt: number;
97
+ }
98
+ /**
99
+ * The recorder (the `SHADOW_RECEIVER` subscription) and the windows its comparison reads, over the
100
+ * broker's own database (`broker_shadow_records`, `broker_shadow_starts`; schema step 5).
101
+ */
102
+ export declare class ShadowRecorder {
103
+ private readonly sql;
104
+ private readonly retentionMs;
105
+ constructor(sql: BrokerSql, opts?: {
106
+ retentionMs?: number;
107
+ });
108
+ /**
109
+ * The receiver: one row, copied from the broker's message row without its body. It writes nothing
110
+ * else anywhere and calls nothing: in shadow this is all a delivery does. Idempotent by id.
111
+ */
112
+ receiver(now: () => number): DeliveryReceiver;
113
+ /** A scope's window starts after `marks`: a new start replaces the last, since the mode went on again. */
114
+ start(tenantId: string, scopeId: string, marks: HandoffMarks, now: number): void;
115
+ /** The scopes with a window, in scope id order, after `cursor`. */
116
+ scopes(limit: number, cursor?: string): ShadowScope[];
117
+ /** One scope's records inside its window: ids past its start, committed before `before`, at most `limit` per kind. */
118
+ records(scope: ShadowScope, before: string, limit: number): ShadowRecord[];
119
+ /** Drop records past their retention (K-70). Windows stay: one row per scope and kind. */
120
+ prune(now: number): void;
121
+ /** Epoch ms the oldest record's retention runs out, or null when it holds none. */
122
+ nextWakeAt(): number | null;
123
+ }
124
+ /** What the drain did with one message, as its scope's own rows say. */
125
+ export interface DeliveryWitness {
126
+ id: string;
127
+ kind: BrokerMessageKind;
128
+ committedAt: string;
129
+ /** When the drain delivered it (the intent's `settled_at`, the event's `drained_at`), or null while it has not. */
130
+ deliveredAt: string | null;
131
+ }
132
+ /**
133
+ * The scope's half of the comparison: its own messages past `after`, committed before `before`,
134
+ * with what the drain did with each. Two reads by primary key range, both `emittedHere`, as the
135
+ * handoff's own reads are, so the two sides count the same rows.
136
+ */
137
+ export declare function witnessQueries(after: HandoffMarks, before: string, limit: number): {
138
+ kind: BrokerMessageKind;
139
+ sql: string;
140
+ params: unknown[];
141
+ }[];
142
+ /** A witness read's rows, as witnesses. */
143
+ export declare function witnessesOf(kind: BrokerMessageKind, rows: readonly Record<string, unknown>[]): DeliveryWitness[];
144
+ /** Latency, in ms from commit: how many, the median, the 95th percentile and the worst. */
145
+ export interface LatencyStats {
146
+ n: number;
147
+ p50: number;
148
+ p95: number;
149
+ max: number;
150
+ }
151
+ /** One kind's comparison. */
152
+ export interface KindComparison {
153
+ /** Messages in the window on either side. */
154
+ compared: number;
155
+ /** Delivered by both. */
156
+ both: number;
157
+ /** Delivered by the drain, never recorded by the broker: a handoff that did not happen, or was lost. */
158
+ drainOnly: number;
159
+ /** Recorded by the broker, not delivered by the drain (yet): the drain is behind, or has no path for it here. */
160
+ brokerOnly: number;
161
+ /** Delivered by neither: pending on both sides. */
162
+ neither: number;
163
+ /** The first ids of each difference, for an operator to look up. */
164
+ drainOnlyIds: string[];
165
+ brokerOnlyIds: string[];
166
+ latencyMs: {
167
+ drain: LatencyStats | null;
168
+ broker: LatencyStats | null;
169
+ };
170
+ }
171
+ /** How many ids of each difference a comparison names. */
172
+ export declare const COMPARISON_SAMPLE = 20;
173
+ /**
174
+ * Pair what the recorder got with what the drain did, for one kind. A record and a witness are the
175
+ * same message by id. Latency is from the message's commit: to the drain's delivery, and to the
176
+ * recorder's (which is the broker's whole path: handoff, store, pass).
177
+ */
178
+ export declare function compareKind(records: readonly ShadowRecord[], witnesses: readonly DeliveryWitness[]): KindComparison;
179
+ /** A scope whose witness could not be read, so its messages are not in the comparison. */
180
+ export interface UnreadScope {
181
+ scopeId: string;
182
+ error: string;
183
+ }
184
+ /** The comparison for one (tenant, app), as staff read it. Ids, types and times only. */
185
+ export interface DeliveryComparison {
186
+ tenantId: string;
187
+ app: string;
188
+ /** Epoch ms it was read, and the window's end as an instant: younger messages are in flight. */
189
+ at: number;
190
+ before: string;
191
+ /** Scopes compared, and those whose witness could not be read. */
192
+ scopes: number;
193
+ unread: UnreadScope[];
194
+ /** A scope or a kind held more than one read takes: the counts are a floor. */
195
+ truncated: boolean;
196
+ /** Where the next page of scopes starts, or null. */
197
+ nextCursor: string | null;
198
+ event: KindComparison;
199
+ intent: KindComparison;
200
+ }
201
+ /** How many messages of each kind one scope contributes to one read. */
202
+ export declare const COMPARISON_PER_SCOPE = 1000;
203
+ /** How many scopes one comparison read covers; `nextCursor` names the rest. */
204
+ export declare const COMPARISON_SCOPES = 50;
205
+ /** One scope's witness, however the broker reaches its scope. */
206
+ export type WitnessReader = (scope: ShadowScope, before: string, limit: number) => Promise<DeliveryWitness[]>;
207
+ /**
208
+ * The comparison, both adapters' brokers: each scope with a window, its records against its
209
+ * witness. A scope whose witness throws is named in `unread`, never counted as all broker-only.
210
+ */
211
+ export declare function compareDeliveries(recorder: ShadowRecorder, witness: WitnessReader, ids: {
212
+ tenantId: string;
213
+ app: string;
214
+ }, opts: {
215
+ now: number;
216
+ graceMs?: number;
217
+ cursor?: string;
218
+ scopes?: number;
219
+ perScope?: number;
220
+ }): Promise<DeliveryComparison>;
221
+ /** Where an intent stands in its scope, as the live receiver asks it. */
222
+ export type IntentState = 'pending' | 'settled' | 'absent';
223
+ /** The reads `intentStateQuery` makes: one primary-key read. */
224
+ export declare const intentStateQuery: (id: string) => {
225
+ sql: string;
226
+ params: unknown[];
227
+ };
228
+ /** An intent's state from `intentStateQuery`'s rows. */
229
+ export declare const intentStateOf: (rows: readonly {
230
+ status?: unknown;
231
+ }[]) => IntentState;
232
+ /** What the platform answered the live receiver's ask: it ran (or queued) the drain, or the tenant is not live. */
233
+ export type DriveAnswer = 'driven' | 'not-live';
234
+ export interface LiveIntentReceiverDeps {
235
+ /** The intent's state in its scope, now. */
236
+ state(message: BrokerMessage): Promise<IntentState>;
237
+ /** Ask the platform's drain engine to run this scope's intents. Throws when the ask did not land. */
238
+ drive(message: BrokerMessage): Promise<DriveAnswer>;
239
+ /** The waits between looks at the intent after asking; their sum is how long one attempt waits. */
240
+ settleWaitsMs?: readonly number[];
241
+ sleep?: (ms: number) => Promise<void>;
242
+ }
243
+ /** The live receiver's default looks after an ask: half a second, then one, two and four. */
244
+ export declare const LIVE_SETTLE_WAITS_MS: readonly number[];
245
+ /**
246
+ * The real receiver (`LIVE_RECEIVER`): an intent is delivered once it is no longer pending in its
247
+ * scope. The broker does not run the intent itself; the drain engine does, as it always has, so an
248
+ * intent is executed by one engine whichever path asked, and the ask is idempotent on the intent's
249
+ * own state. A settled or absent intent is delivered at once (another driver took it). A pending
250
+ * one is asked for and looked at again; still pending, the attempt fails and the broker retries it
251
+ * under its policy. An event is never owed here (`receiversFor`), and is delivered as a no-op if one
252
+ * ever is.
253
+ *
254
+ * `not-live`: the platform says this tenant is not live (a cut-back). The intent is the drain's
255
+ * again, and the delivery settles here, so the broker never asks twice for what it no longer owns.
256
+ */
257
+ export declare function liveIntentReceiver(deps: LiveIntentReceiverDeps): DeliveryReceiver;
258
+ //# sourceMappingURL=broker-shadow.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"broker-shadow.d.ts","sourceRoot":"","sources":["../src/broker-shadow.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,OAAO,KAAK,EAAE,aAAa,E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