@substrat-run/kernel 0.217.0 → 0.219.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/dist/attachment-text.d.ts +89 -0
- package/dist/attachment-text.d.ts.map +1 -1
- package/dist/attachment-text.js +134 -1
- package/dist/attachment-text.js.map +1 -1
- package/dist/broker-counts.d.ts +108 -0
- package/dist/broker-counts.d.ts.map +1 -0
- package/dist/broker-counts.js +101 -0
- package/dist/broker-counts.js.map +1 -0
- package/dist/broker-schema.d.ts.map +1 -1
- package/dist/broker-schema.js +58 -0
- package/dist/broker-schema.js.map +1 -1
- package/dist/broker-shadow.d.ts +258 -0
- package/dist/broker-shadow.d.ts.map +1 -0
- package/dist/broker-shadow.js +295 -0
- package/dist/broker-shadow.js.map +1 -0
- package/dist/broker-telemetry.d.ts +3 -2
- package/dist/broker-telemetry.d.ts.map +1 -1
- package/dist/broker-telemetry.js +7 -5
- package/dist/broker-telemetry.js.map +1 -1
- package/dist/delivery-broker.d.ts +47 -5
- package/dist/delivery-broker.d.ts.map +1 -1
- package/dist/delivery-broker.js +115 -60
- package/dist/delivery-broker.js.map +1 -1
- package/dist/directory-lake-keep.d.ts +9 -0
- package/dist/directory-lake-keep.d.ts.map +1 -0
- package/dist/directory-lake-keep.js +331 -0
- package/dist/directory-lake-keep.js.map +1 -0
- package/dist/directory-lake-projection.d.ts +50 -0
- package/dist/directory-lake-projection.d.ts.map +1 -0
- package/dist/directory-lake-projection.js +143 -0
- package/dist/directory-lake-projection.js.map +1 -0
- package/dist/directory-lake.d.ts +11 -1
- package/dist/directory-lake.d.ts.map +1 -1
- package/dist/directory-lake.js +3 -1
- package/dist/directory-lake.js.map +1 -1
- package/dist/index.d.ts +9 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/dist/migration-digest.d.ts +2 -2
- package/dist/migration-digest.d.ts.map +1 -1
- package/dist/migration-digest.js +4 -2
- package/dist/migration-digest.js.map +1 -1
- package/dist/migration-fence.d.ts +1 -1
- package/dist/migration-fence.js +3 -3
- package/dist/migration-fence.js.map +1 -1
- package/dist/scope-host.d.ts +26 -1
- package/dist/scope-host.d.ts.map +1 -1
- package/dist/scope-host.js.map +1 -1
- package/dist/spine-guard.d.ts.map +1 -1
- package/dist/spine-guard.js +2 -0
- package/dist/spine-guard.js.map +1 -1
- package/dist/spine-restore.d.ts +14 -2
- package/dist/spine-restore.d.ts.map +1 -1
- package/dist/spine-restore.js.map +1 -1
- package/dist/store-driver-releases.d.ts +3 -1
- package/dist/store-driver-releases.d.ts.map +1 -1
- package/dist/table-ownership.d.ts +6 -0
- package/dist/table-ownership.d.ts.map +1 -1
- package/dist/table-ownership.js +17 -3
- package/dist/table-ownership.js.map +1 -1
- package/dist/vertical-owners.d.ts +1 -1
- package/dist/vertical-owners.d.ts.map +1 -1
- package/dist/vertical-owners.js.map +1 -1
- package/package.json +2 -2
package/dist/broker-schema.js
CHANGED
|
@@ -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":"AAuBA,MAAM,CAAC,MAAM,aAAa,GAAgC;IACxD;QACE,EAAE,EAAE,4CAA4C;QAChD,UAAU,EAAE;YACV;;;;;;;;;;;;;SAaG;YACH,uGAAuG;YACvG;;;;;;SAMG;SACJ;KACF;IACD;QACE,EAAE,EAAE,0FAA0F;QAC9F,UAAU,EAAE;YACV,0FAA0F;YAC1F,0DAA0D;YAC1D,8FAA8F;YAC9F,2FAA2F;YAC3F;;;;;;;;;;;;;;;;;;;;SAoBG;YACH,2FAA2F;YAC3F,oFAAoF;YACpF;iEAC2D;YAC3D,yFAAyF;YACzF,iFAAiF;YACjF;;;;;;;;;;SAUG;YACH,uFAAuF;YACvF;;;;;;;sFAOgF;YAChF,gCAAgC;YAChC,kDAAkD;YAClD,iDAAiD;YACjD,oDAAoD;YACpD,sDAAsD;SACvD;KACF;IACD;QACE,EAAE,EAAE,0EAA0E;QAC9E,UAAU,EAAE;YACV,oFAAoF;YACpF;;;;;;SAMG;SACJ;KACF;IACD;QACE,EAAE,EAAE,iDAAiD;QACrD,iGAAiG;QACjG,+FAA+F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F,MAAM,UAAU,kBAAkB,CAAC,GAAc;IAC/C,GAAG,CAAC,GAAG,CAAC,qEAAqE,CAAC,CAAC;IAC/E,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAsB,mCAAmC,CAAC,CAAC,CAAC,CAAC,CAAC;IACjF,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,EAAE,OAAO,IAAI,CAAC,CAAC,CAAC;IACtC,IAAI,CAAC,GAAG;QAAE,GAAG,CAAC,GAAG,CAAC,gDAAgD,CAAC,CAAC;IACpE,KAAK,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QAChD,GAAG,CAAC,WAAW,CAAC,GAAG,EAAE;YACnB,KAAK,MAAM,SAAS,IAAI,aAAa,CAAC,CAAC,CAAE,CAAC,UAAU;gBAAE,GAAG,CAAC,GAAG,CAAC,SAAS,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,aAA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AgE;AAChE,eAAO,MAAM,gBAAgB,OAAQ,MAAM,KAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,EAAE,CAAA;CAG5E,CAAC;AAEH,wDAAwD;AACxD,eAAO,MAAM,aAAa,SAAU,SAAS;IAAE,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,EAAE,KAAG,WACgB,CAAC;AAEvF,mHAAmH;AACnH,MAAM,MAAM,WAAW,GAAG,QAAQ,GAAG,UAAU,CAAC;AAEhD,MAAM,WAAW,sBAAsB;IACrC,4CAA4C;IAC5C,KAAK,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IACpD,qGAAqG;IACrG,KAAK,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IACpD,mGAAmG;IACnG,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACvC;AAED,6FAA6F;AAC7F,eAAO,MAAM,oBAAoB,EAAE,SAAS,MAAM,EAA+B,CAAC;AAElF;;;;;;;;;;;GAWG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,sBAAsB,GAAG,gBAAgB,CAgBjF"}
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import { DeliveryFailure } from './delivery-policy.js';
|
|
2
|
+
import { emittedHere } from './scope-copy.js';
|
|
3
|
+
export const DELIVERY_MODES = ['off', 'shadow', 'live'];
|
|
4
|
+
export const isDeliveryMode = (v) => typeof v === 'string' && DELIVERY_MODES.includes(v);
|
|
5
|
+
/** The recorder's subscription: every message handed off in shadow or live. */
|
|
6
|
+
export const SHADOW_RECEIVER = 'shadow';
|
|
7
|
+
/** The real receiver's subscription: intents handed off live. */
|
|
8
|
+
export const LIVE_RECEIVER = 'live';
|
|
9
|
+
/**
|
|
10
|
+
* The env var a script sets to hand off whatever the control plane says, owing every receiver as
|
|
11
|
+
* A1–A4 did: `always`. For a test worker or a self-hosted script with no control plane to ask. The
|
|
12
|
+
* uploader never sets it.
|
|
13
|
+
*/
|
|
14
|
+
export const DELIVERY_HANDOFF_ENV = 'SUBSTRAT_DELIVERY_HANDOFF';
|
|
15
|
+
/**
|
|
16
|
+
* The receivers a message is owed, from the mode it was handed off under: `undefined` is every
|
|
17
|
+
* receiver the store has (no mode: A1–A4's behaviour). Only names the store knows are owed.
|
|
18
|
+
*/
|
|
19
|
+
export function receiversFor(mode, kind) {
|
|
20
|
+
if (mode === 'shadow')
|
|
21
|
+
return [SHADOW_RECEIVER];
|
|
22
|
+
if (mode === 'live')
|
|
23
|
+
return kind === 'intent' ? [SHADOW_RECEIVER, LIVE_RECEIVER] : [SHADOW_RECEIVER];
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
/** How long a record is kept: the week the comparison is read over, and a day. */
|
|
27
|
+
export const SHADOW_RETENTION_MS = 8 * 24 * 60 * 60_000;
|
|
28
|
+
/** 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. */
|
|
29
|
+
export const SHADOW_GRACE_MS = 20 * 60_000;
|
|
30
|
+
/** How many records one prune deletes; the rest go in the next. */
|
|
31
|
+
const SHADOW_PRUNE_BATCH = 500;
|
|
32
|
+
/**
|
|
33
|
+
* The recorder (the `SHADOW_RECEIVER` subscription) and the windows its comparison reads, over the
|
|
34
|
+
* broker's own database (`broker_shadow_records`, `broker_shadow_starts`; schema step 5).
|
|
35
|
+
*/
|
|
36
|
+
export class ShadowRecorder {
|
|
37
|
+
sql;
|
|
38
|
+
retentionMs;
|
|
39
|
+
constructor(sql, opts = {}) {
|
|
40
|
+
this.sql = sql;
|
|
41
|
+
this.retentionMs = opts.retentionMs ?? SHADOW_RETENTION_MS;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The receiver: one row, copied from the broker's message row without its body. It writes nothing
|
|
45
|
+
* else anywhere and calls nothing: in shadow this is all a delivery does. Idempotent by id.
|
|
46
|
+
*/
|
|
47
|
+
receiver(now) {
|
|
48
|
+
return {
|
|
49
|
+
deliver: async (m) => {
|
|
50
|
+
this.sql.run(`INSERT OR IGNORE INTO broker_shadow_records (message_id, kind, tenant_id, scope_id, type, committed_at, received_at, recorded_at)
|
|
51
|
+
SELECT id, kind, tenant_id, scope_id, type, committed_at, received_at, ? FROM broker_messages WHERE id = ?`, now(), m.id);
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** A scope's window starts after `marks`: a new start replaces the last, since the mode went on again. */
|
|
56
|
+
start(tenantId, scopeId, marks, now) {
|
|
57
|
+
this.sql.transaction(() => {
|
|
58
|
+
for (const kind of ['event', 'intent']) {
|
|
59
|
+
this.sql.run(`INSERT INTO broker_shadow_starts (tenant_id, scope_id, kind, start_after, started_at) VALUES (?, ?, ?, ?, ?)
|
|
60
|
+
ON CONFLICT (tenant_id, scope_id, kind) DO UPDATE SET start_after = excluded.start_after, started_at = excluded.started_at`, tenantId, scopeId, kind, marks[kind] ?? '', now);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/** The scopes with a window, in scope id order, after `cursor`. */
|
|
65
|
+
scopes(limit, cursor) {
|
|
66
|
+
const rows = this.sql.all(`SELECT tenant_id, scope_id, kind, start_after, started_at FROM broker_shadow_starts
|
|
67
|
+
WHERE scope_id IN (SELECT DISTINCT scope_id FROM broker_shadow_starts WHERE scope_id > ? ORDER BY scope_id LIMIT ?)
|
|
68
|
+
ORDER BY scope_id, kind`, cursor ?? '', limit);
|
|
69
|
+
const byScope = new Map();
|
|
70
|
+
for (const r of rows) {
|
|
71
|
+
const s = byScope.get(r.scope_id) ?? { tenantId: r.tenant_id, scopeId: r.scope_id, start: {}, startedAt: r.started_at };
|
|
72
|
+
if (r.start_after)
|
|
73
|
+
s.start[r.kind] = r.start_after;
|
|
74
|
+
s.startedAt = Math.max(s.startedAt, r.started_at);
|
|
75
|
+
byScope.set(r.scope_id, s);
|
|
76
|
+
}
|
|
77
|
+
return [...byScope.values()];
|
|
78
|
+
}
|
|
79
|
+
/** One scope's records inside its window: ids past its start, committed before `before`, at most `limit` per kind. */
|
|
80
|
+
records(scope, before, limit) {
|
|
81
|
+
return ['event', 'intent'].flatMap((kind) => this.sql
|
|
82
|
+
.all(`SELECT message_id, kind, tenant_id, scope_id, type, committed_at, received_at, recorded_at
|
|
83
|
+
FROM broker_shadow_records
|
|
84
|
+
WHERE tenant_id = ? AND scope_id = ? AND kind = ? AND message_id > ? AND committed_at < ?
|
|
85
|
+
ORDER BY message_id LIMIT ?`, scope.tenantId, scope.scopeId, kind, scope.start[kind] ?? '', before, limit)
|
|
86
|
+
.map((r) => ({
|
|
87
|
+
id: r.message_id,
|
|
88
|
+
kind: r.kind,
|
|
89
|
+
tenantId: r.tenant_id,
|
|
90
|
+
scopeId: r.scope_id,
|
|
91
|
+
type: r.type,
|
|
92
|
+
committedAt: r.committed_at,
|
|
93
|
+
receivedAt: r.received_at,
|
|
94
|
+
recordedAt: r.recorded_at,
|
|
95
|
+
})));
|
|
96
|
+
}
|
|
97
|
+
/** Drop records past their retention (K-70). Windows stay: one row per scope and kind. */
|
|
98
|
+
prune(now) {
|
|
99
|
+
this.sql.run(`DELETE FROM broker_shadow_records WHERE message_id IN (
|
|
100
|
+
SELECT message_id FROM broker_shadow_records WHERE recorded_at <= ? LIMIT ?)`, now - this.retentionMs, SHADOW_PRUNE_BATCH);
|
|
101
|
+
}
|
|
102
|
+
/** Epoch ms the oldest record's retention runs out, or null when it holds none. */
|
|
103
|
+
nextWakeAt() {
|
|
104
|
+
const row = this.sql.all('SELECT MIN(recorded_at) AS oldest FROM broker_shadow_records')[0];
|
|
105
|
+
return row?.oldest == null ? null : row.oldest + this.retentionMs;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The scope's half of the comparison: its own messages past `after`, committed before `before`,
|
|
110
|
+
* with what the drain did with each. Two reads by primary key range, both `emittedHere`, as the
|
|
111
|
+
* handoff's own reads are, so the two sides count the same rows.
|
|
112
|
+
*/
|
|
113
|
+
export function witnessQueries(after, before, limit) {
|
|
114
|
+
return [
|
|
115
|
+
{
|
|
116
|
+
kind: 'event',
|
|
117
|
+
sql: `SELECT id, occurred_at AS committed_at, drained_at AS delivered_at FROM _substrat_outbox
|
|
118
|
+
WHERE id > ? AND occurred_at < ? AND ${emittedHere()} ORDER BY id LIMIT ?`,
|
|
119
|
+
params: [after.event ?? '', before, limit],
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
kind: 'intent',
|
|
123
|
+
sql: `SELECT id, requested_at AS committed_at, CASE WHEN status = 'pending' THEN NULL ELSE settled_at END AS delivered_at
|
|
124
|
+
FROM _substrat_platform_requests WHERE id > ? AND requested_at < ? AND ${emittedHere()} ORDER BY id LIMIT ?`,
|
|
125
|
+
params: [after.intent ?? '', before, limit],
|
|
126
|
+
},
|
|
127
|
+
];
|
|
128
|
+
}
|
|
129
|
+
/** A witness read's rows, as witnesses. */
|
|
130
|
+
export function witnessesOf(kind, rows) {
|
|
131
|
+
return rows.map((r) => ({
|
|
132
|
+
id: String(r.id),
|
|
133
|
+
kind,
|
|
134
|
+
committedAt: String(r.committed_at),
|
|
135
|
+
deliveredAt: r.delivered_at == null ? null : String(r.delivered_at),
|
|
136
|
+
}));
|
|
137
|
+
}
|
|
138
|
+
/** How many ids of each difference a comparison names. */
|
|
139
|
+
export const COMPARISON_SAMPLE = 20;
|
|
140
|
+
const percentile = (sorted, p) => sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1))];
|
|
141
|
+
function stats(values) {
|
|
142
|
+
if (!values.length)
|
|
143
|
+
return null;
|
|
144
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
145
|
+
return { n: sorted.length, p50: percentile(sorted, 50), p95: percentile(sorted, 95), max: sorted[sorted.length - 1] };
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Pair what the recorder got with what the drain did, for one kind. A record and a witness are the
|
|
149
|
+
* same message by id. Latency is from the message's commit: to the drain's delivery, and to the
|
|
150
|
+
* recorder's (which is the broker's whole path: handoff, store, pass).
|
|
151
|
+
*/
|
|
152
|
+
export function compareKind(records, witnesses) {
|
|
153
|
+
const recorded = new Map(records.map((r) => [r.id, r]));
|
|
154
|
+
const witnessed = new Map(witnesses.map((w) => [w.id, w]));
|
|
155
|
+
const ids = [...new Set([...recorded.keys(), ...witnessed.keys()])].sort();
|
|
156
|
+
const out = {
|
|
157
|
+
compared: ids.length,
|
|
158
|
+
both: 0,
|
|
159
|
+
drainOnly: 0,
|
|
160
|
+
brokerOnly: 0,
|
|
161
|
+
neither: 0,
|
|
162
|
+
drainOnlyIds: [],
|
|
163
|
+
brokerOnlyIds: [],
|
|
164
|
+
latencyMs: { drain: null, broker: null },
|
|
165
|
+
};
|
|
166
|
+
const drain = [];
|
|
167
|
+
const broker = [];
|
|
168
|
+
for (const id of ids) {
|
|
169
|
+
const r = recorded.get(id);
|
|
170
|
+
const w = witnessed.get(id);
|
|
171
|
+
const drained = w?.deliveredAt != null;
|
|
172
|
+
const committedMs = Date.parse(r?.committedAt ?? w.committedAt);
|
|
173
|
+
if (drained)
|
|
174
|
+
drain.push(Math.max(0, Date.parse(w.deliveredAt) - committedMs));
|
|
175
|
+
if (r)
|
|
176
|
+
broker.push(Math.max(0, r.recordedAt - committedMs));
|
|
177
|
+
if (r && drained)
|
|
178
|
+
out.both++;
|
|
179
|
+
else if (drained) {
|
|
180
|
+
out.drainOnly++;
|
|
181
|
+
if (out.drainOnlyIds.length < COMPARISON_SAMPLE)
|
|
182
|
+
out.drainOnlyIds.push(id);
|
|
183
|
+
}
|
|
184
|
+
else if (r) {
|
|
185
|
+
out.brokerOnly++;
|
|
186
|
+
if (out.brokerOnlyIds.length < COMPARISON_SAMPLE)
|
|
187
|
+
out.brokerOnlyIds.push(id);
|
|
188
|
+
}
|
|
189
|
+
else
|
|
190
|
+
out.neither++;
|
|
191
|
+
}
|
|
192
|
+
out.latencyMs = { drain: stats(drain), broker: stats(broker) };
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
/** How many messages of each kind one scope contributes to one read. */
|
|
196
|
+
export const COMPARISON_PER_SCOPE = 1_000;
|
|
197
|
+
/** How many scopes one comparison read covers; `nextCursor` names the rest. */
|
|
198
|
+
export const COMPARISON_SCOPES = 50;
|
|
199
|
+
/**
|
|
200
|
+
* The comparison, both adapters' brokers: each scope with a window, its records against its
|
|
201
|
+
* witness. A scope whose witness throws is named in `unread`, never counted as all broker-only.
|
|
202
|
+
*/
|
|
203
|
+
export async function compareDeliveries(recorder, witness, ids, opts) {
|
|
204
|
+
const before = new Date(opts.now - (opts.graceMs ?? SHADOW_GRACE_MS)).toISOString();
|
|
205
|
+
const limit = opts.perScope ?? COMPARISON_PER_SCOPE;
|
|
206
|
+
const pageSize = opts.scopes ?? COMPARISON_SCOPES;
|
|
207
|
+
const scopes = recorder.scopes(pageSize + 1, opts.cursor);
|
|
208
|
+
const page = scopes.slice(0, pageSize);
|
|
209
|
+
const records = [];
|
|
210
|
+
const witnesses = [];
|
|
211
|
+
const unread = [];
|
|
212
|
+
let truncated = false;
|
|
213
|
+
for (const scope of page) {
|
|
214
|
+
let seen;
|
|
215
|
+
try {
|
|
216
|
+
seen = await witness(scope, before, limit);
|
|
217
|
+
}
|
|
218
|
+
catch (err) {
|
|
219
|
+
unread.push({ scopeId: scope.scopeId, error: err instanceof Error ? err.message : String(err) });
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
const mine = recorder.records(scope, before, limit);
|
|
223
|
+
for (const kind of ['event', 'intent']) {
|
|
224
|
+
let w = seen.filter((x) => x.kind === kind);
|
|
225
|
+
let r = mine.filter((x) => x.kind === kind);
|
|
226
|
+
// A side that filled its read stops at its last id; past it, the other side's ids are unknown
|
|
227
|
+
// to it rather than missing. Compare only up to the lower of the two stops.
|
|
228
|
+
const through = [w.length >= limit ? w.at(-1).id : null, r.length >= limit ? r.at(-1).id : null]
|
|
229
|
+
.filter((x) => x !== null)
|
|
230
|
+
.sort()[0];
|
|
231
|
+
if (through !== undefined) {
|
|
232
|
+
truncated = true;
|
|
233
|
+
w = w.filter((x) => x.id <= through);
|
|
234
|
+
r = r.filter((x) => x.id <= through);
|
|
235
|
+
}
|
|
236
|
+
witnesses.push(...w);
|
|
237
|
+
records.push(...r);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return {
|
|
241
|
+
tenantId: ids.tenantId,
|
|
242
|
+
app: ids.app,
|
|
243
|
+
at: opts.now,
|
|
244
|
+
before,
|
|
245
|
+
scopes: page.length - unread.length,
|
|
246
|
+
unread,
|
|
247
|
+
truncated,
|
|
248
|
+
nextCursor: scopes.length > pageSize ? page.at(-1).scopeId : null,
|
|
249
|
+
event: compareKind(records.filter((r) => r.kind === 'event'), witnesses.filter((w) => w.kind === 'event')),
|
|
250
|
+
intent: compareKind(records.filter((r) => r.kind === 'intent'), witnesses.filter((w) => w.kind === 'intent')),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
/** The reads `intentStateQuery` makes: one primary-key read. */
|
|
254
|
+
export const intentStateQuery = (id) => ({
|
|
255
|
+
sql: 'SELECT status FROM _substrat_platform_requests WHERE id = ?',
|
|
256
|
+
params: [id],
|
|
257
|
+
});
|
|
258
|
+
/** An intent's state from `intentStateQuery`'s rows. */
|
|
259
|
+
export const intentStateOf = (rows) => rows.length === 0 ? 'absent' : rows[0].status === 'pending' ? 'pending' : 'settled';
|
|
260
|
+
/** The live receiver's default looks after an ask: half a second, then one, two and four. */
|
|
261
|
+
export const LIVE_SETTLE_WAITS_MS = [500, 1_000, 2_000, 4_000];
|
|
262
|
+
/**
|
|
263
|
+
* The real receiver (`LIVE_RECEIVER`): an intent is delivered once it is no longer pending in its
|
|
264
|
+
* scope. The broker does not run the intent itself; the drain engine does, as it always has, so an
|
|
265
|
+
* intent is executed by one engine whichever path asked, and the ask is idempotent on the intent's
|
|
266
|
+
* own state. A settled or absent intent is delivered at once (another driver took it). A pending
|
|
267
|
+
* one is asked for and looked at again; still pending, the attempt fails and the broker retries it
|
|
268
|
+
* under its policy. An event is never owed here (`receiversFor`), and is delivered as a no-op if one
|
|
269
|
+
* ever is.
|
|
270
|
+
*
|
|
271
|
+
* `not-live`: the platform says this tenant is not live (a cut-back). The intent is the drain's
|
|
272
|
+
* again, and the delivery settles here, so the broker never asks twice for what it no longer owns.
|
|
273
|
+
*/
|
|
274
|
+
export function liveIntentReceiver(deps) {
|
|
275
|
+
const waits = deps.settleWaitsMs ?? LIVE_SETTLE_WAITS_MS;
|
|
276
|
+
const timers = globalThis;
|
|
277
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((r) => void timers.setTimeout(r, ms)));
|
|
278
|
+
return {
|
|
279
|
+
deliver: async (m) => {
|
|
280
|
+
if (m.kind !== 'intent')
|
|
281
|
+
return;
|
|
282
|
+
if ((await deps.state(m)) !== 'pending')
|
|
283
|
+
return;
|
|
284
|
+
if ((await deps.drive(m)) === 'not-live')
|
|
285
|
+
return;
|
|
286
|
+
for (const ms of waits) {
|
|
287
|
+
await sleep(ms);
|
|
288
|
+
if ((await deps.state(m)) !== 'pending')
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
throw new DeliveryFailure(`intent ${m.id} is still pending after the drain was asked to run it`, { status: 503 });
|
|
292
|
+
},
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
//# sourceMappingURL=broker-shadow.js.map
|