@broberg/db-sdk 0.2.0 → 0.3.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/README.md +145 -5
- package/dist/index.d.ts +7 -104
- package/dist/index.js +79 -9
- package/dist/index.js.map +1 -1
- package/dist/switchable/index.d.ts +506 -0
- package/dist/switchable/index.js +965 -0
- package/dist/switchable/index.js.map +1 -0
- package/dist/types-9Y21zZWt.d.ts +114 -0
- package/package.json +17 -3
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
import { Sql } from 'postgres';
|
|
2
|
+
import { Pool } from 'pg';
|
|
3
|
+
import { D as DbClient } from '../types-9Y21zZWt.js';
|
|
4
|
+
import '@libsql/client';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* THE INSTANT SWITCH (components-F085.5, ported from broberg-id F084.149) — a
|
|
8
|
+
* Postgres client that can move to another database while the process runs.
|
|
9
|
+
*
|
|
10
|
+
* The problem it solves: switching a dual-DB app to its reserve by changing a
|
|
11
|
+
* secret and restarting gives a minute where machine A writes to one database
|
|
12
|
+
* and machine B to the other. Here, every query goes through THIS object, which
|
|
13
|
+
* forwards to the active side. A switch is a pointer change:
|
|
14
|
+
*
|
|
15
|
+
* hold(ms) new queries wait; resolves when none are running (or at `ms`)
|
|
16
|
+
* point() points at the new side WITHOUT letting the waiters go — so a
|
|
17
|
+
* switch can be confirmed on every machine before any query
|
|
18
|
+
* reaches the new database
|
|
19
|
+
* switchTo() point() + release()
|
|
20
|
+
* release() lets the waiters go, onto whatever side is pointed at
|
|
21
|
+
*
|
|
22
|
+
* How long a query may wait is the orchestrator's call (whoever holds); this
|
|
23
|
+
* file is only the mechanism.
|
|
24
|
+
*
|
|
25
|
+
* ── `.raw` FOLLOWS THE SWITCH TOO ───────────────────────────────────────
|
|
26
|
+
*
|
|
27
|
+
* Consumers use `db().raw` (postgres.js) as much as `execute()` — vnlekerv2 has
|
|
28
|
+
* ~220 `sql.unsafe` and 19 `sql.begin` calls (counted 27/11 2026). A switch that
|
|
29
|
+
* only moved `execute()` would leave all of those on the old database. So `raw`
|
|
30
|
+
* is a stand-in `Sql`:
|
|
31
|
+
*
|
|
32
|
+
* sql`…`, sql.unsafe(), sql.file() a real postgres.js Query, built lazily as
|
|
33
|
+
* always; it is sent to the side that is
|
|
34
|
+
* active WHEN IT RUNS, after any hold. Its
|
|
35
|
+
* modifiers (.values(), .cursor(), …) and
|
|
36
|
+
* its use as a fragment inside another
|
|
37
|
+
* sql`…` are unchanged.
|
|
38
|
+
* sql.begin(), sql.reserve() wait out a hold, then count as one
|
|
39
|
+
* running query until they finish
|
|
40
|
+
* sql(obj), sql.json(), … helpers — passed to the active side
|
|
41
|
+
* sql.notify(), sql.largeObject() wait out a hold, then run on the active side
|
|
42
|
+
* sql.listen() passed to the side active at the call;
|
|
43
|
+
* a listener does NOT move with a switch
|
|
44
|
+
*
|
|
45
|
+
* A query counts as running until postgres.js settles it through
|
|
46
|
+
* `query.resolve` / `query.reject` — NOT until its promise settles: the
|
|
47
|
+
* iterator form of `.cursor()` swaps those two out, and its promise never
|
|
48
|
+
* settles (bid review #56236; counted on the promise, one cursor made every
|
|
49
|
+
* later hold() fail).
|
|
50
|
+
*
|
|
51
|
+
* Running a Query on another side uses postgres.js internals (3.4.x: the
|
|
52
|
+
* Query's `handler`, `canceller`, `resolve`, `reject`, `executed`), which are
|
|
53
|
+
* not public API. So it FAILS CLOSED: if they are missing, creating the client
|
|
54
|
+
* or building a query throws — it never quietly runs on the build side. The
|
|
55
|
+
* dependency is pinned to ~3.4.9 for the same reason.
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
interface HoldResult {
|
|
59
|
+
/** true = nothing was running when the hold resolved. */
|
|
60
|
+
ok: boolean;
|
|
61
|
+
/** Queries still running (a transaction that did not finish in time). */
|
|
62
|
+
inFlight: number;
|
|
63
|
+
}
|
|
64
|
+
/** A Postgres DbClient that can move to another database while the process runs.
|
|
65
|
+
* `Raw` is the driver behind `.raw`: postgres.js (`Sql`) or node-postgres (`pg.Pool`, components-F085.6). */
|
|
66
|
+
interface SwitchableClient<Raw = Sql> extends DbClient<Raw> {
|
|
67
|
+
/** The name of the side currently pointed at. */
|
|
68
|
+
readonly label: string;
|
|
69
|
+
readonly holding: boolean;
|
|
70
|
+
readonly inFlight: number;
|
|
71
|
+
/** The side currently pointed at — for code that must talk to it directly. */
|
|
72
|
+
readonly current: DbClient<Raw>;
|
|
73
|
+
hold(ms: number): Promise<HoldResult>;
|
|
74
|
+
/** Point at another side without releasing waiters. Returns the old side; it is NOT closed. */
|
|
75
|
+
point(client: DbClient<Raw>, label: string): DbClient<Raw>;
|
|
76
|
+
/** point() + release(). Returns the old side; it is NOT closed. */
|
|
77
|
+
switchTo(client: DbClient<Raw>, label: string): DbClient<Raw>;
|
|
78
|
+
/** Release the waiters onto the side that is pointed at. */
|
|
79
|
+
release(): void;
|
|
80
|
+
}
|
|
81
|
+
declare function createSwitchable(initial: DbClient<Sql>, label: string): SwitchableClient<Sql>;
|
|
82
|
+
declare function createSwitchable(initial: DbClient<Pool>, label: string): SwitchableClient<Pool>;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* THE FENCE IN THE DATABASE (components-F085.5, ported from broberg-id
|
|
86
|
+
* F084.153) — the database the app is NOT running on refuses the app's writes.
|
|
87
|
+
*
|
|
88
|
+
* The switch makes every machine write to one place. But it is the APP that
|
|
89
|
+
* does that. A machine that missed the switch, or a restart on a stale secret,
|
|
90
|
+
* would write to the old database in silence — two databases each believing
|
|
91
|
+
* they are the real one. With the fence that write fails loudly instead
|
|
92
|
+
* (`25006`, read_only_sql_transaction). It covers every path into the
|
|
93
|
+
* database — `execute()`, `.raw`, a migration, a psql session — because it
|
|
94
|
+
* lives in the database, not in the client.
|
|
95
|
+
*
|
|
96
|
+
* ── WHY A TRIGGER AND NOT `default_transaction_read_only` ───────────────
|
|
97
|
+
*
|
|
98
|
+
* Measured by BID 7/10 2026 (Postgres 17, a real publisher → subscriber):
|
|
99
|
+
*
|
|
100
|
+
* default_transaction_read_only on the role the client turns it off with
|
|
101
|
+
* SET TRANSACTION READ WRITE,
|
|
102
|
+
* and it only applies to NEW
|
|
103
|
+
* connections
|
|
104
|
+
* a per-statement trigger (this file) app writes refused, READ
|
|
105
|
+
* WRITE included; the initial
|
|
106
|
+
* copy AND ongoing replication
|
|
107
|
+
* pass
|
|
108
|
+
*
|
|
109
|
+
* Replication passes because subscription workers run with
|
|
110
|
+
* `session_replication_role = replica`, where ordinary triggers do not fire.
|
|
111
|
+
* The app's role cannot set that itself (superuser only), and neither
|
|
112
|
+
* Supabase's `postgres` nor UpCloud's `upadmin` is a superuser.
|
|
113
|
+
*
|
|
114
|
+
* ── WHAT IT IS, AND WHAT IT IS NOT ─────────────────────────────────────
|
|
115
|
+
*
|
|
116
|
+
* A guard against a MISTAKE — a machine standing in the wrong place. Not a
|
|
117
|
+
* guard against an attacker: the role owns the tables and can drop the trigger
|
|
118
|
+
* with DDL. Whoever has the database password already has everything.
|
|
119
|
+
*
|
|
120
|
+
* The state lives in the FUNCTION BODY, not in a table: a table in `public`
|
|
121
|
+
* would be replicated from the primary and overwrite the reserve's fence. DDL
|
|
122
|
+
* is not replicated. Replacing the body takes effect at once, also for
|
|
123
|
+
* connections already open (plpgsql looks the function up on every call).
|
|
124
|
+
*
|
|
125
|
+
* INSERT/UPDATE/DELETE only. TRUNCATE is left to rebuild tooling.
|
|
126
|
+
*/
|
|
127
|
+
|
|
128
|
+
type FenceState = 'open' | 'locked';
|
|
129
|
+
interface FenceOptions {
|
|
130
|
+
/** Name of the trigger function AND of the trigger on every table. Default `dbFence`. BID: `bidFence`. */
|
|
131
|
+
name?: string;
|
|
132
|
+
/**
|
|
133
|
+
* The session setting that lets the switch's own copy-home write through a
|
|
134
|
+
* locked database (see reconcile). A machine that missed the switch never
|
|
135
|
+
* sets it, so the fence still holds against the mistake it exists for.
|
|
136
|
+
* Default `db_sdk.fence_bypass`. BID: `bid.fence_bypass`.
|
|
137
|
+
*/
|
|
138
|
+
bypass?: string;
|
|
139
|
+
}
|
|
140
|
+
declare const FENCE_DEFAULTS: {
|
|
141
|
+
readonly name: "dbFence";
|
|
142
|
+
readonly bypass: "db_sdk.fence_bypass";
|
|
143
|
+
};
|
|
144
|
+
/** read_only_sql_transaction — what a fenced write fails with. */
|
|
145
|
+
declare const FENCE_ERRCODE = "25006";
|
|
146
|
+
type Pg$1 = Pick<DbClient<Sql>, 'execute'>;
|
|
147
|
+
/** Locked or open — or `missing` if the fence was never installed in this database. */
|
|
148
|
+
declare function fenceState(db: Pg$1, o?: FenceOptions): Promise<FenceState | 'missing'>;
|
|
149
|
+
declare function setFence(db: Pg$1, state: FenceState, o?: FenceOptions): Promise<void>;
|
|
150
|
+
/**
|
|
151
|
+
* Install the fence: the function if missing (in `initial`), and the trigger
|
|
152
|
+
* on every table in the schema that lacks it. Idempotent, and it NEVER changes
|
|
153
|
+
* an existing state — only the switch may. The tables are ASKED of the
|
|
154
|
+
* database, so a table an upgrade adds gets fenced too: call it after every
|
|
155
|
+
* migration.
|
|
156
|
+
*/
|
|
157
|
+
declare function installFence(db: Pg$1, initial: FenceState, o?: FenceOptions): Promise<{
|
|
158
|
+
created: boolean;
|
|
159
|
+
triggered: string[];
|
|
160
|
+
}>;
|
|
161
|
+
/** Tables without the trigger — an empty list means the whole schema is covered. */
|
|
162
|
+
declare function unfencedTables(db: Pg$1, o?: FenceOptions): Promise<string[]>;
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* THE WAY BACK WITHOUT LOSS (components-F085.5, ported from broberg-id
|
|
166
|
+
* F084.154) — what was written in the reserve after the switch is brought over
|
|
167
|
+
* to the primary BEFORE switching back.
|
|
168
|
+
*
|
|
169
|
+
* ── THE WALL ─────────────────────────────────────────────────────────────
|
|
170
|
+
*
|
|
171
|
+
* The obvious tool — a reverse subscription, the primary subscribing to the
|
|
172
|
+
* reserve — is not always possible (Supabase cannot subscribe outward). A
|
|
173
|
+
* publication on the reserve plus a WAL player of our own would be a new,
|
|
174
|
+
* heavy component running from the switch onwards. The databases this is for
|
|
175
|
+
* are small (BID 7/10: ~3,000 rows, 28 tables), so COMPARING the rows takes
|
|
176
|
+
* milliseconds and needs nothing running in between.
|
|
177
|
+
*
|
|
178
|
+
* ── THREE STATES PER ROW ─────────────────────────────────────────────────
|
|
179
|
+
*
|
|
180
|
+
* B the baseline at the switch to the reserve — taken while every machine
|
|
181
|
+
* held, just after the subscription was disabled (`captureBaseline`)
|
|
182
|
+
* R the reserve now
|
|
183
|
+
* P the primary now
|
|
184
|
+
*
|
|
185
|
+
* R = P nothing to do
|
|
186
|
+
* P = B only the reserve changed the row → copy (a DELETE too —
|
|
187
|
+
* otherwise a logged-out session wakes up again)
|
|
188
|
+
* otherwise the primary has a change the reserve never saw: CONFLICT.
|
|
189
|
+
* Reported, never overwritten in silence.
|
|
190
|
+
*
|
|
191
|
+
* After a planned switch there can be no conflicts: the primary is fenced and
|
|
192
|
+
* stood still from the baseline. After an EMERGENCY switch the primary may hold
|
|
193
|
+
* the last seconds of writes that never reached the reserve — those are what
|
|
194
|
+
* the conflicts catch.
|
|
195
|
+
*
|
|
196
|
+
* What was copied is written into the baseline, so a run that is interrupted
|
|
197
|
+
* and re-run sees its own copies as "P = B", not as conflicts.
|
|
198
|
+
*
|
|
199
|
+
* A row is compared as `md5(to_jsonb(row))` in UTC: jsonb keys are sorted, so
|
|
200
|
+
* column order in the two databases does not matter.
|
|
201
|
+
*
|
|
202
|
+
* Only the CURRENT schema (search_path) is compared; the baseline lives in a
|
|
203
|
+
* schema of its own, so it is never part of the comparison.
|
|
204
|
+
*/
|
|
205
|
+
|
|
206
|
+
type Pg = Pick<DbClient<Sql>, 'execute' | 'batch'>;
|
|
207
|
+
interface ReconcileOptions {
|
|
208
|
+
/** Schema that holds the baseline. Default `dbSwitch`. BID: `bidSwitch`. */
|
|
209
|
+
schema?: string;
|
|
210
|
+
/** The fence's bypass setting (see FenceOptions.bypass). Default `db_sdk.fence_bypass`. */
|
|
211
|
+
bypass?: string;
|
|
212
|
+
}
|
|
213
|
+
declare const RECONCILE_DEFAULTS: {
|
|
214
|
+
readonly schema: "dbSwitch";
|
|
215
|
+
readonly bypass: "db_sdk.fence_bypass";
|
|
216
|
+
};
|
|
217
|
+
/** Take the baseline B on the reserve. Call it while every machine holds. Returns the row count. */
|
|
218
|
+
declare function captureBaseline(reserve: Pg, o?: ReconcileOptions): Promise<number>;
|
|
219
|
+
/** Is there a baseline — and when was it taken (epoch ms)? */
|
|
220
|
+
declare function baselineAt(reserve: Pg, o?: ReconcileOptions): Promise<number | null>;
|
|
221
|
+
interface Conflict {
|
|
222
|
+
table: string;
|
|
223
|
+
key: string;
|
|
224
|
+
/** What the reserve holds now (null = deleted). */
|
|
225
|
+
reserve: string | null;
|
|
226
|
+
/** What the primary holds now (null = does not exist). */
|
|
227
|
+
primary: string | null;
|
|
228
|
+
/** The baseline at the switch (null = did not exist). */
|
|
229
|
+
baseline: string | null;
|
|
230
|
+
}
|
|
231
|
+
interface Plan {
|
|
232
|
+
upserts: number;
|
|
233
|
+
deletes: number;
|
|
234
|
+
conflicts: Conflict[];
|
|
235
|
+
/** Tables whose columns differ between the two databases — then nothing can be compared. */
|
|
236
|
+
schemaMismatch: string[];
|
|
237
|
+
/** Rows actually written in the primary (0 when only planned). */
|
|
238
|
+
written: number;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Compare, and copy if `apply` and there are neither conflicts nor schema
|
|
242
|
+
* differences — OR `skipConflicts`, in which case the rest is copied and the
|
|
243
|
+
* conflicting rows stay as the primary has them.
|
|
244
|
+
*
|
|
245
|
+
* Everything is written in the primary in ONE transaction through the fence's
|
|
246
|
+
* door (the bypass setting): the primary is fenced while the app runs on the
|
|
247
|
+
* reserve.
|
|
248
|
+
*/
|
|
249
|
+
declare function reconcile(reserve: Pg, primary: Pg, opts: {
|
|
250
|
+
apply: boolean;
|
|
251
|
+
skipConflicts?: boolean;
|
|
252
|
+
} & ReconcileOptions): Promise<Plan>;
|
|
253
|
+
|
|
254
|
+
/** A Postgres client from either driver (postgres.js or pg, components-F085.6). */
|
|
255
|
+
type AnyPg = DbClient<any>;
|
|
256
|
+
type Target = 'primary' | 'reserve';
|
|
257
|
+
interface TargetSpec {
|
|
258
|
+
/** The name the side answers to (BID: "supabase" / "upcloud"). Known without opening. */
|
|
259
|
+
label: string;
|
|
260
|
+
/** Open a client for it. Called once, on the first prepare. */
|
|
261
|
+
open: () => AnyPg;
|
|
262
|
+
}
|
|
263
|
+
interface SwitchControlOptions {
|
|
264
|
+
switchable: SwitchableClient<any>;
|
|
265
|
+
targets: Record<Target, TargetSpec>;
|
|
266
|
+
/** The machines' shared secret; the Bearer is HMAC-SHA256(secret, context). */
|
|
267
|
+
secret: string;
|
|
268
|
+
/** HMAC context. Default "db-switch". BID: "bid-db-switch". */
|
|
269
|
+
context?: string;
|
|
270
|
+
/** Logged on a switch and on the safety net. Default console. */
|
|
271
|
+
log?: {
|
|
272
|
+
info(msg: string): void;
|
|
273
|
+
error(msg: string): void;
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
declare const HOLD_MIN_MS = 100;
|
|
277
|
+
declare const HOLD_MAX_MS = 10000;
|
|
278
|
+
/** The Bearer an orchestrator sends — derived, so it never travels or is stored on its own. */
|
|
279
|
+
declare function switchToken(secret: string, context?: string): string;
|
|
280
|
+
declare function createSwitchControl(o: SwitchControlOptions): (req: Request) => Promise<Response>;
|
|
281
|
+
/**
|
|
282
|
+
* THE EMERGENCY SWITCH'S GUARD (BID F084.152) — may a switch without the primary
|
|
283
|
+
* run? The emergency switch skips the marker, so whatever had not replicated is
|
|
284
|
+
* lost. It may ONLY run when the primary really does not answer — otherwise the
|
|
285
|
+
* planned switch (lossless) is the right one — and whoever presses must have
|
|
286
|
+
* said the loss is accepted. `fault: "primary-down"` is a test's way past the
|
|
287
|
+
* first condition, against a primary that is alive.
|
|
288
|
+
*/
|
|
289
|
+
type EmergencyDecision = 'proceed' | 'need-accept' | 'refuse-primary-alive';
|
|
290
|
+
declare function emergencyGate(o: {
|
|
291
|
+
primaryResponds: boolean;
|
|
292
|
+
acceptDataLoss: boolean;
|
|
293
|
+
fault?: string;
|
|
294
|
+
}): EmergencyDecision;
|
|
295
|
+
|
|
296
|
+
type MachineAnswer = {
|
|
297
|
+
status: number;
|
|
298
|
+
ok?: boolean;
|
|
299
|
+
label?: string;
|
|
300
|
+
error?: string;
|
|
301
|
+
[k: string]: unknown;
|
|
302
|
+
};
|
|
303
|
+
interface Machine {
|
|
304
|
+
id: string;
|
|
305
|
+
call(path: string, body?: unknown, timeoutMs?: number): Promise<MachineAnswer>;
|
|
306
|
+
}
|
|
307
|
+
/** A machine reached over HTTP at `baseUrl` (e.g. "http://<id>.vm.<app>.internal:8081"). */
|
|
308
|
+
declare function httpMachine(id: string, baseUrl: string, token: string): Machine;
|
|
309
|
+
interface OrchestrateOptions {
|
|
310
|
+
to: Target;
|
|
311
|
+
machines: Machine[];
|
|
312
|
+
/** DIRECT clients to both sides (not through a pooler) — only the orchestration uses them. */
|
|
313
|
+
primary: DbClient<any>;
|
|
314
|
+
reserve: DbClient<any>;
|
|
315
|
+
/** The labels the machines report for each side (same as the control's targets). */
|
|
316
|
+
labels: Record<Target, string>;
|
|
317
|
+
/** The reserve's subscription to the primary (to the reserve only). */
|
|
318
|
+
subscription: string;
|
|
319
|
+
/** Hold ceiling per machine, 100–10 000. Default 3000. */
|
|
320
|
+
holdMs?: number;
|
|
321
|
+
/** To the primary: copy home but keep the primary's version of conflicting rows. */
|
|
322
|
+
skipConflicts?: boolean;
|
|
323
|
+
/** To the primary: drop what was written in the reserve (the emergency exit). */
|
|
324
|
+
discardReserveWrites?: boolean;
|
|
325
|
+
/** Emergency switch to the reserve: the primary is down. No probe, no marker —
|
|
326
|
+
* so what had not replicated is LOST. Needs `acceptDataLoss`, and is refused
|
|
327
|
+
* while the primary answers (emergencyGate). */
|
|
328
|
+
primaryDown?: boolean;
|
|
329
|
+
acceptDataLoss?: boolean;
|
|
330
|
+
/** Fault injection for tests in production (BID AC1). "primary-down" treats a
|
|
331
|
+
* live primary as dead, to test the emergency path. */
|
|
332
|
+
fault?: 'replication' | 'point' | 'primary-down';
|
|
333
|
+
/** Marker table (id text pk, at bigint). Default "dbSwitchMarker" (BID's). */
|
|
334
|
+
markerTable?: string;
|
|
335
|
+
fence?: FenceOptions;
|
|
336
|
+
reconcile?: ReconcileOptions;
|
|
337
|
+
log?: (line: string) => void;
|
|
338
|
+
}
|
|
339
|
+
type Outcome = {
|
|
340
|
+
outcome: 'done';
|
|
341
|
+
label: string;
|
|
342
|
+
heldMs: number;
|
|
343
|
+
} | {
|
|
344
|
+
outcome: 'refused';
|
|
345
|
+
reason: string;
|
|
346
|
+
} | {
|
|
347
|
+
outcome: 'aborted';
|
|
348
|
+
reason: string;
|
|
349
|
+
restored: string[];
|
|
350
|
+
} | {
|
|
351
|
+
outcome: 'unconfirmed';
|
|
352
|
+
reason: string;
|
|
353
|
+
label: string;
|
|
354
|
+
};
|
|
355
|
+
declare function orchestrateSwitch(o: OrchestrateOptions): Promise<Outcome>;
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* IS THE RESERVE ALIVE? — and who gets woken when it is not (components-F085.5,
|
|
359
|
+
* ported from broberg-id reserve-health.ts F084.114 + reserve-watch.ts F084.204).
|
|
360
|
+
*
|
|
361
|
+
* A reserve can die without anyone seeing it: a dead reserve is nothing in the
|
|
362
|
+
* app's logs, and a failed reserve migration is one log line. A reserve you
|
|
363
|
+
* believe is alive is MORE dangerous than none, because you count on it the day
|
|
364
|
+
* the primary falls. fd-sundhed 28/10 2026: two new columns in production
|
|
365
|
+
* without the reserve, replication stood still for 5 hours, the slot was 128 MB
|
|
366
|
+
* from being dropped.
|
|
367
|
+
*
|
|
368
|
+
* The reading comes from the PRIMARY (its replication slot and the walsender),
|
|
369
|
+
* not from the reserve: if the reserve is down, that is exactly what the answer
|
|
370
|
+
* must say. Serve it on its own route — BID: /health/reserve, NOT /health/ready:
|
|
371
|
+
* a dead reserve must never take logins down.
|
|
372
|
+
*
|
|
373
|
+
* The alarm half is PURE: the app keeps the episode state where it wants (BID:
|
|
374
|
+
* a table, because it runs on two machines) and sends the incidents its own way.
|
|
375
|
+
*/
|
|
376
|
+
|
|
377
|
+
interface ReserveThresholds {
|
|
378
|
+
/** No reply from the reserve for this long = stale. BID: 300 (it replies every ~10 s). */
|
|
379
|
+
staleSeconds: number;
|
|
380
|
+
/** This far behind = not catching up. BID: 64 MB (Supabase drops the slot at 512 MB). */
|
|
381
|
+
lagBytes: number;
|
|
382
|
+
}
|
|
383
|
+
declare const RESERVE_DEFAULTS: ReserveThresholds;
|
|
384
|
+
interface SlotReading {
|
|
385
|
+
active: boolean;
|
|
386
|
+
walStatus: string | null;
|
|
387
|
+
lagBytes: number | null;
|
|
388
|
+
/** Seconds since the reserve last replied; null = no live connection. */
|
|
389
|
+
replyAgeSeconds: number | null;
|
|
390
|
+
}
|
|
391
|
+
type ReserveReason = 'missing' | 'inactive' | 'lost' | 'stale' | 'lagging' | 'unreadable';
|
|
392
|
+
type ReserveVerdict = {
|
|
393
|
+
ok: true;
|
|
394
|
+
} | {
|
|
395
|
+
ok: false;
|
|
396
|
+
reason: ReserveReason | (string & {});
|
|
397
|
+
};
|
|
398
|
+
declare function judgeReserve(r: SlotReading | null, t?: ReserveThresholds): ReserveVerdict;
|
|
399
|
+
/** Read the reserve's slot ON THE PRIMARY. The slot name is the subscription's (BID: bid_reserve). */
|
|
400
|
+
declare function readReserveSlot(primary: Pick<DbClient<Sql>, 'execute'>, slot: string): Promise<SlotReading | null>;
|
|
401
|
+
/** Read + judge in one call; a reading that fails — or does not answer within
|
|
402
|
+
* `timeoutMs` (default 5 s; a hung primary must not hang the health route) —
|
|
403
|
+
* is `unreadable`, never «ok». */
|
|
404
|
+
declare function reserveHealth(primary: Pick<DbClient<Sql>, 'execute'>, slot: string, t?: ReserveThresholds, timeoutMs?: number): Promise<ReserveVerdict>;
|
|
405
|
+
/** Unhealthy this long in a row → one incident per episode. A blink sends nothing. BID: 10 min. */
|
|
406
|
+
declare const RESERVE_ALARM_AFTER_MS: number;
|
|
407
|
+
declare const MIGRATION_FAILED = "migration_failed";
|
|
408
|
+
/** The app persists this between rounds (BID: rows in its reserveWatch table). */
|
|
409
|
+
interface ReserveWatchState {
|
|
410
|
+
slot?: {
|
|
411
|
+
reason: string;
|
|
412
|
+
firstSeenAt: number;
|
|
413
|
+
};
|
|
414
|
+
migrationFailed?: {
|
|
415
|
+
firstSeenAt: number;
|
|
416
|
+
detail: string;
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
interface ReserveIncident {
|
|
420
|
+
/** Carries the episode's start, so «sent once per id» gives one alarm per episode and a new one for a new episode. */
|
|
421
|
+
id: string;
|
|
422
|
+
reason: string;
|
|
423
|
+
severity: 'critical' | 'high';
|
|
424
|
+
openedAt: string;
|
|
425
|
+
detail: string | null;
|
|
426
|
+
}
|
|
427
|
+
/** The reserve migration's outcome on a deploy → state. Failure alarms at once
|
|
428
|
+
* (it does not fix itself). `skipped` (no reserve configured on this deploy)
|
|
429
|
+
* leaves the state untouched — it must never clear a pending migration_failed. */
|
|
430
|
+
declare function noteReserveMigration(state: ReserveWatchState, outcome: {
|
|
431
|
+
ok: true;
|
|
432
|
+
} | {
|
|
433
|
+
ok: false;
|
|
434
|
+
reason: string;
|
|
435
|
+
} | {
|
|
436
|
+
skipped: true;
|
|
437
|
+
}, now?: number): ReserveWatchState;
|
|
438
|
+
/** One alarm round: the next state from `verdict`, and the incidents to send. */
|
|
439
|
+
declare function watchReserve(state: ReserveWatchState, verdict: ReserveVerdict, now?: number, alarmAfterMs?: number): {
|
|
440
|
+
state: ReserveWatchState;
|
|
441
|
+
incidents: ReserveIncident[];
|
|
442
|
+
};
|
|
443
|
+
|
|
444
|
+
type Restrictions = {
|
|
445
|
+
dbAllowedCidrs: string[];
|
|
446
|
+
dbAllowedCidrsV6: string[];
|
|
447
|
+
};
|
|
448
|
+
interface GuardDeps {
|
|
449
|
+
reserveHealth(): Promise<{
|
|
450
|
+
ok: boolean;
|
|
451
|
+
reason?: string;
|
|
452
|
+
}>;
|
|
453
|
+
upcloudPublicHost(): Promise<string>;
|
|
454
|
+
resolve(host: string): Promise<string>;
|
|
455
|
+
getRestrictions(): Promise<Restrictions & {
|
|
456
|
+
status: string;
|
|
457
|
+
}>;
|
|
458
|
+
applyRestrictions(r: Restrictions): Promise<void>;
|
|
459
|
+
sleep(ms: number): Promise<void>;
|
|
460
|
+
log(line: string): void;
|
|
461
|
+
}
|
|
462
|
+
interface GuardOptions {
|
|
463
|
+
/** Known fixed v4 addresses (e.g. Fly egress, office) — only for the clean-up note. */
|
|
464
|
+
fixedV4: string[];
|
|
465
|
+
/** How long to wait for an active slot after a fix. */
|
|
466
|
+
waitMs: number;
|
|
467
|
+
pollMs: number;
|
|
468
|
+
/** How long to read back before a list that did not take effect is an error (BID F084.174). */
|
|
469
|
+
readBackMs: number;
|
|
470
|
+
/** BID F084.197 — an unhealthy slot is measured again after this long before acting. A blink is not a state. */
|
|
471
|
+
confirmMs: number;
|
|
472
|
+
}
|
|
473
|
+
type GuardResult = {
|
|
474
|
+
outcome: "healthy";
|
|
475
|
+
} | {
|
|
476
|
+
outcome: "not-network";
|
|
477
|
+
reason: string;
|
|
478
|
+
} | {
|
|
479
|
+
outcome: "already-allowed";
|
|
480
|
+
ip: string;
|
|
481
|
+
} | {
|
|
482
|
+
outcome: "fixed";
|
|
483
|
+
ip: string;
|
|
484
|
+
} | {
|
|
485
|
+
outcome: "still-down";
|
|
486
|
+
ip: string;
|
|
487
|
+
reason: string;
|
|
488
|
+
}
|
|
489
|
+
/** BID F084.238 — the slot is lost. The address is fixed (or was fine); the reserve must be rebuilt. */
|
|
490
|
+
| {
|
|
491
|
+
outcome: "needs-rebuild";
|
|
492
|
+
ip: string;
|
|
493
|
+
added: boolean;
|
|
494
|
+
};
|
|
495
|
+
declare function runGuard(d: GuardDeps, o: GuardOptions): Promise<GuardResult>;
|
|
496
|
+
/** The real APIs (UpCloud Managed Postgres as the reserve, Supabase as the primary).
|
|
497
|
+
* The keys come from the environment and are never logged. */
|
|
498
|
+
declare function liveDeps(env: {
|
|
499
|
+
healthUrl: string;
|
|
500
|
+
upcloudToken: string;
|
|
501
|
+
upcloudDbUuid: string;
|
|
502
|
+
supabaseToken: string;
|
|
503
|
+
supabaseRef: string;
|
|
504
|
+
}): GuardDeps;
|
|
505
|
+
|
|
506
|
+
export { type Conflict, type EmergencyDecision, FENCE_DEFAULTS, FENCE_ERRCODE, type FenceOptions, type FenceState, type GuardDeps, type GuardOptions, type GuardResult, HOLD_MAX_MS, HOLD_MIN_MS, type HoldResult, MIGRATION_FAILED, type Machine, type MachineAnswer, type OrchestrateOptions, type Outcome, type Plan, RECONCILE_DEFAULTS, RESERVE_ALARM_AFTER_MS, RESERVE_DEFAULTS, type ReconcileOptions, type ReserveIncident, type ReserveReason, type ReserveThresholds, type ReserveVerdict, type ReserveWatchState, type Restrictions, type SlotReading, type SwitchControlOptions, type SwitchableClient, type Target, type TargetSpec, baselineAt, captureBaseline, createSwitchControl, createSwitchable, emergencyGate, fenceState, httpMachine, installFence, judgeReserve, liveDeps, noteReserveMigration, orchestrateSwitch, readReserveSlot, reconcile, reserveHealth, runGuard, setFence, switchToken, unfencedTables, watchReserve };
|