@rebasepro/server-postgres 0.10.0 → 0.10.1-canary.14e53ae
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/PostgresBootstrapper.d.ts +7 -3
- package/dist/auth/services.d.ts +43 -4
- package/dist/backup/backup-logic.d.ts +23 -0
- package/dist/backup/backup-service.d.ts +44 -2
- package/dist/backup/pg-tools.d.ts +41 -1
- package/dist/chunk-DSJWtz9O.js +40 -0
- package/dist/cli-helpers.d.ts +33 -1
- package/dist/ensure-collection-tables-CNlIONzj.js +304 -0
- package/dist/ensure-collection-tables-CNlIONzj.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.es.js +1472 -4640
- package/dist/index.es.js.map +1 -1
- package/dist/schema/auth-schema.d.ts +170 -0
- package/dist/schema/destructive-sql.d.ts +49 -0
- package/dist/schema/ensure-collection-tables.d.ts +79 -0
- package/dist/schema/generate-postgres-ddl-logic.d.ts +4 -1
- package/dist/services/cdc/CdcListener.d.ts +7 -14
- package/dist/services/channel-bus/ChannelBus.d.ts +29 -0
- package/dist/services/channel-bus/PostgresChannelBus.d.ts +111 -0
- package/dist/services/channel-bus/index.d.ts +55 -0
- package/dist/services/channel-history.d.ts +11 -0
- package/dist/services/channel-presence.d.ts +66 -0
- package/dist/services/pg-notify-listener.d.ts +47 -0
- package/dist/services/realtimeService.d.ts +114 -6
- package/dist/src-B0v4IKaI.js +329 -0
- package/dist/src-B0v4IKaI.js.map +1 -0
- package/dist/src-DmsRg8MR.js +4056 -0
- package/dist/src-DmsRg8MR.js.map +1 -0
- package/package.json +6 -6
- package/src/PostgresBootstrapper.ts +72 -3
- package/src/auth/ensure-tables.ts +91 -3
- package/src/auth/services.ts +186 -48
- package/src/backup/backup-cli.ts +60 -1
- package/src/backup/backup-cron.ts +24 -1
- package/src/backup/backup-logic.ts +62 -0
- package/src/backup/backup-service.ts +132 -13
- package/src/backup/pg-tools.ts +70 -2
- package/src/cli-helpers.ts +82 -27
- package/src/cli.ts +152 -6
- package/src/index.ts +4 -0
- package/src/schema/auth-schema.ts +41 -3
- package/src/schema/destructive-sql.ts +94 -0
- package/src/schema/ensure-collection-tables.test.ts +156 -0
- package/src/schema/ensure-collection-tables.ts +297 -0
- package/src/schema/generate-postgres-ddl-logic.ts +3 -3
- package/src/services/cdc/CdcListener.ts +27 -91
- package/src/services/channel-bus/ChannelBus.ts +44 -0
- package/src/services/channel-bus/PostgresChannelBus.ts +299 -0
- package/src/services/channel-bus/index.ts +123 -0
- package/src/services/channel-history.ts +35 -0
- package/src/services/channel-presence.ts +148 -0
- package/src/services/pg-notify-listener.ts +137 -0
- package/src/services/realtimeService.ts +383 -14
|
@@ -232,6 +232,23 @@ export declare function createAuthSchema(usersSchemaName?: string): {
|
|
|
232
232
|
}, {}, {
|
|
233
233
|
$type: Record<string, unknown>;
|
|
234
234
|
}>;
|
|
235
|
+
tokensValidAfter: import("drizzle-orm/pg-core").PgColumn<{
|
|
236
|
+
name: "tokens_valid_after";
|
|
237
|
+
tableName: "users";
|
|
238
|
+
dataType: "date";
|
|
239
|
+
columnType: "PgTimestamp";
|
|
240
|
+
data: Date;
|
|
241
|
+
driverParam: string;
|
|
242
|
+
notNull: false;
|
|
243
|
+
hasDefault: false;
|
|
244
|
+
isPrimaryKey: false;
|
|
245
|
+
isAutoincrement: false;
|
|
246
|
+
hasRuntimeDefault: false;
|
|
247
|
+
enumValues: undefined;
|
|
248
|
+
baseColumn: never;
|
|
249
|
+
identity: undefined;
|
|
250
|
+
generated: undefined;
|
|
251
|
+
}, {}, {}>;
|
|
235
252
|
createdAt: import("drizzle-orm/pg-core").PgColumn<{
|
|
236
253
|
name: "created_at";
|
|
237
254
|
tableName: "users";
|
|
@@ -307,6 +324,23 @@ export declare function createAuthSchema(usersSchemaName?: string): {
|
|
|
307
324
|
identity: undefined;
|
|
308
325
|
generated: undefined;
|
|
309
326
|
}, {}, {}>;
|
|
327
|
+
sessionId: import("drizzle-orm/pg-core").PgColumn<{
|
|
328
|
+
name: "session_id";
|
|
329
|
+
tableName: "refresh_tokens";
|
|
330
|
+
dataType: "string";
|
|
331
|
+
columnType: "PgUUID";
|
|
332
|
+
data: string;
|
|
333
|
+
driverParam: string;
|
|
334
|
+
notNull: true;
|
|
335
|
+
hasDefault: true;
|
|
336
|
+
isPrimaryKey: false;
|
|
337
|
+
isAutoincrement: false;
|
|
338
|
+
hasRuntimeDefault: false;
|
|
339
|
+
enumValues: undefined;
|
|
340
|
+
baseColumn: never;
|
|
341
|
+
identity: undefined;
|
|
342
|
+
generated: undefined;
|
|
343
|
+
}, {}, {}>;
|
|
310
344
|
tokenHash: import("drizzle-orm/pg-core").PgColumn<{
|
|
311
345
|
name: "token_hash";
|
|
312
346
|
tableName: "refresh_tokens";
|
|
@@ -343,6 +377,57 @@ export declare function createAuthSchema(usersSchemaName?: string): {
|
|
|
343
377
|
identity: undefined;
|
|
344
378
|
generated: undefined;
|
|
345
379
|
}, {}, {}>;
|
|
380
|
+
revoked: import("drizzle-orm/pg-core").PgColumn<{
|
|
381
|
+
name: "revoked";
|
|
382
|
+
tableName: "refresh_tokens";
|
|
383
|
+
dataType: "boolean";
|
|
384
|
+
columnType: "PgBoolean";
|
|
385
|
+
data: boolean;
|
|
386
|
+
driverParam: boolean;
|
|
387
|
+
notNull: true;
|
|
388
|
+
hasDefault: true;
|
|
389
|
+
isPrimaryKey: false;
|
|
390
|
+
isAutoincrement: false;
|
|
391
|
+
hasRuntimeDefault: false;
|
|
392
|
+
enumValues: undefined;
|
|
393
|
+
baseColumn: never;
|
|
394
|
+
identity: undefined;
|
|
395
|
+
generated: undefined;
|
|
396
|
+
}, {}, {}>;
|
|
397
|
+
rotatedAt: import("drizzle-orm/pg-core").PgColumn<{
|
|
398
|
+
name: "rotated_at";
|
|
399
|
+
tableName: "refresh_tokens";
|
|
400
|
+
dataType: "date";
|
|
401
|
+
columnType: "PgTimestamp";
|
|
402
|
+
data: Date;
|
|
403
|
+
driverParam: string;
|
|
404
|
+
notNull: false;
|
|
405
|
+
hasDefault: false;
|
|
406
|
+
isPrimaryKey: false;
|
|
407
|
+
isAutoincrement: false;
|
|
408
|
+
hasRuntimeDefault: false;
|
|
409
|
+
enumValues: undefined;
|
|
410
|
+
baseColumn: never;
|
|
411
|
+
identity: undefined;
|
|
412
|
+
generated: undefined;
|
|
413
|
+
}, {}, {}>;
|
|
414
|
+
sessionStartedAt: import("drizzle-orm/pg-core").PgColumn<{
|
|
415
|
+
name: "session_started_at";
|
|
416
|
+
tableName: "refresh_tokens";
|
|
417
|
+
dataType: "date";
|
|
418
|
+
columnType: "PgTimestamp";
|
|
419
|
+
data: Date;
|
|
420
|
+
driverParam: string;
|
|
421
|
+
notNull: true;
|
|
422
|
+
hasDefault: true;
|
|
423
|
+
isPrimaryKey: false;
|
|
424
|
+
isAutoincrement: false;
|
|
425
|
+
hasRuntimeDefault: false;
|
|
426
|
+
enumValues: undefined;
|
|
427
|
+
baseColumn: never;
|
|
428
|
+
identity: undefined;
|
|
429
|
+
generated: undefined;
|
|
430
|
+
}, {}, {}>;
|
|
346
431
|
userAgent: import("drizzle-orm/pg-core").PgColumn<{
|
|
347
432
|
name: "user_agent";
|
|
348
433
|
tableName: "refresh_tokens";
|
|
@@ -1398,6 +1483,23 @@ export declare const users: import("drizzle-orm/pg-core").PgTableWithColumns<{
|
|
|
1398
1483
|
}, {}, {
|
|
1399
1484
|
$type: Record<string, unknown>;
|
|
1400
1485
|
}>;
|
|
1486
|
+
tokensValidAfter: import("drizzle-orm/pg-core").PgColumn<{
|
|
1487
|
+
name: "tokens_valid_after";
|
|
1488
|
+
tableName: "users";
|
|
1489
|
+
dataType: "date";
|
|
1490
|
+
columnType: "PgTimestamp";
|
|
1491
|
+
data: Date;
|
|
1492
|
+
driverParam: string;
|
|
1493
|
+
notNull: false;
|
|
1494
|
+
hasDefault: false;
|
|
1495
|
+
isPrimaryKey: false;
|
|
1496
|
+
isAutoincrement: false;
|
|
1497
|
+
hasRuntimeDefault: false;
|
|
1498
|
+
enumValues: undefined;
|
|
1499
|
+
baseColumn: never;
|
|
1500
|
+
identity: undefined;
|
|
1501
|
+
generated: undefined;
|
|
1502
|
+
}, {}, {}>;
|
|
1401
1503
|
createdAt: import("drizzle-orm/pg-core").PgColumn<{
|
|
1402
1504
|
name: "created_at";
|
|
1403
1505
|
tableName: "users";
|
|
@@ -1473,6 +1575,23 @@ export declare const refreshTokens: import("drizzle-orm/pg-core").PgTableWithCol
|
|
|
1473
1575
|
identity: undefined;
|
|
1474
1576
|
generated: undefined;
|
|
1475
1577
|
}, {}, {}>;
|
|
1578
|
+
sessionId: import("drizzle-orm/pg-core").PgColumn<{
|
|
1579
|
+
name: "session_id";
|
|
1580
|
+
tableName: "refresh_tokens";
|
|
1581
|
+
dataType: "string";
|
|
1582
|
+
columnType: "PgUUID";
|
|
1583
|
+
data: string;
|
|
1584
|
+
driverParam: string;
|
|
1585
|
+
notNull: true;
|
|
1586
|
+
hasDefault: true;
|
|
1587
|
+
isPrimaryKey: false;
|
|
1588
|
+
isAutoincrement: false;
|
|
1589
|
+
hasRuntimeDefault: false;
|
|
1590
|
+
enumValues: undefined;
|
|
1591
|
+
baseColumn: never;
|
|
1592
|
+
identity: undefined;
|
|
1593
|
+
generated: undefined;
|
|
1594
|
+
}, {}, {}>;
|
|
1476
1595
|
tokenHash: import("drizzle-orm/pg-core").PgColumn<{
|
|
1477
1596
|
name: "token_hash";
|
|
1478
1597
|
tableName: "refresh_tokens";
|
|
@@ -1509,6 +1628,57 @@ export declare const refreshTokens: import("drizzle-orm/pg-core").PgTableWithCol
|
|
|
1509
1628
|
identity: undefined;
|
|
1510
1629
|
generated: undefined;
|
|
1511
1630
|
}, {}, {}>;
|
|
1631
|
+
revoked: import("drizzle-orm/pg-core").PgColumn<{
|
|
1632
|
+
name: "revoked";
|
|
1633
|
+
tableName: "refresh_tokens";
|
|
1634
|
+
dataType: "boolean";
|
|
1635
|
+
columnType: "PgBoolean";
|
|
1636
|
+
data: boolean;
|
|
1637
|
+
driverParam: boolean;
|
|
1638
|
+
notNull: true;
|
|
1639
|
+
hasDefault: true;
|
|
1640
|
+
isPrimaryKey: false;
|
|
1641
|
+
isAutoincrement: false;
|
|
1642
|
+
hasRuntimeDefault: false;
|
|
1643
|
+
enumValues: undefined;
|
|
1644
|
+
baseColumn: never;
|
|
1645
|
+
identity: undefined;
|
|
1646
|
+
generated: undefined;
|
|
1647
|
+
}, {}, {}>;
|
|
1648
|
+
rotatedAt: import("drizzle-orm/pg-core").PgColumn<{
|
|
1649
|
+
name: "rotated_at";
|
|
1650
|
+
tableName: "refresh_tokens";
|
|
1651
|
+
dataType: "date";
|
|
1652
|
+
columnType: "PgTimestamp";
|
|
1653
|
+
data: Date;
|
|
1654
|
+
driverParam: string;
|
|
1655
|
+
notNull: false;
|
|
1656
|
+
hasDefault: false;
|
|
1657
|
+
isPrimaryKey: false;
|
|
1658
|
+
isAutoincrement: false;
|
|
1659
|
+
hasRuntimeDefault: false;
|
|
1660
|
+
enumValues: undefined;
|
|
1661
|
+
baseColumn: never;
|
|
1662
|
+
identity: undefined;
|
|
1663
|
+
generated: undefined;
|
|
1664
|
+
}, {}, {}>;
|
|
1665
|
+
sessionStartedAt: import("drizzle-orm/pg-core").PgColumn<{
|
|
1666
|
+
name: "session_started_at";
|
|
1667
|
+
tableName: "refresh_tokens";
|
|
1668
|
+
dataType: "date";
|
|
1669
|
+
columnType: "PgTimestamp";
|
|
1670
|
+
data: Date;
|
|
1671
|
+
driverParam: string;
|
|
1672
|
+
notNull: true;
|
|
1673
|
+
hasDefault: true;
|
|
1674
|
+
isPrimaryKey: false;
|
|
1675
|
+
isAutoincrement: false;
|
|
1676
|
+
hasRuntimeDefault: false;
|
|
1677
|
+
enumValues: undefined;
|
|
1678
|
+
baseColumn: never;
|
|
1679
|
+
identity: undefined;
|
|
1680
|
+
generated: undefined;
|
|
1681
|
+
}, {}, {}>;
|
|
1512
1682
|
userAgent: import("drizzle-orm/pg-core").PgColumn<{
|
|
1513
1683
|
name: "user_agent";
|
|
1514
1684
|
tableName: "refresh_tokens";
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers that classify an Atlas declarative-apply plan as destructive
|
|
3
|
+
* or not, and decide what `rebase db push` should do about it.
|
|
4
|
+
*
|
|
5
|
+
* `db push` runs `atlas schema apply` to make the live database match the
|
|
6
|
+
* generated `schema.sql`. Removing a collection field compiles to
|
|
7
|
+
* `DROP COLUMN`; renaming compiles to drop-then-add — either destroys data.
|
|
8
|
+
* We first run the apply with `--dry-run` to obtain the planned SQL, scan it
|
|
9
|
+
* here, and refuse to auto-approve anything destructive without an explicit
|
|
10
|
+
* opt-in.
|
|
11
|
+
*
|
|
12
|
+
* Everything in this file is side-effect free so it can be unit-tested
|
|
13
|
+
* without Atlas or a database.
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Split a SQL script into individual statements, dropping blank lines and
|
|
17
|
+
* `--` comment lines. Deliberately simple: Atlas emits one plain statement
|
|
18
|
+
* per `;`, without string literals that contain semicolons in a schema DDL
|
|
19
|
+
* plan, so a naive split is safe and keeps this dependency-free.
|
|
20
|
+
*/
|
|
21
|
+
export declare function splitSqlStatements(sql: string): string[];
|
|
22
|
+
export interface DestructiveStatement {
|
|
23
|
+
/** The offending statement (trimmed, without the trailing `;`). */
|
|
24
|
+
statement: string;
|
|
25
|
+
/** Which destructive operation it was flagged for, e.g. "DROP COLUMN". */
|
|
26
|
+
kind: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Scan an Atlas plan (the SQL printed by `schema apply --dry-run`) and return
|
|
30
|
+
* the statements that would destroy data. An empty array means the plan is
|
|
31
|
+
* safe to auto-approve.
|
|
32
|
+
*/
|
|
33
|
+
export declare function detectDestructiveStatements(planSql: string): DestructiveStatement[];
|
|
34
|
+
export type PushDecision = "apply" | "confirm" | "refuse";
|
|
35
|
+
/**
|
|
36
|
+
* Decide how `db push` should proceed given the plan's destructiveness and
|
|
37
|
+
* the invocation context.
|
|
38
|
+
*
|
|
39
|
+
* - No destructive statements → `apply` (safe to auto-approve).
|
|
40
|
+
* - Destructive + `--allow-destructive` → `apply` (operator opted in).
|
|
41
|
+
* - Destructive + interactive TTY → `confirm` (prompt before applying).
|
|
42
|
+
* - Destructive + non-interactive → `refuse` (never silently drop data in
|
|
43
|
+
* CI / scripts / agents).
|
|
44
|
+
*/
|
|
45
|
+
export declare function decidePushSafety(opts: {
|
|
46
|
+
destructiveCount: number;
|
|
47
|
+
allowDestructive: boolean;
|
|
48
|
+
interactive: boolean;
|
|
49
|
+
}): PushDecision;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bringing a database up to date with a bundle's collections, additively.
|
|
3
|
+
*
|
|
4
|
+
* ## Why this exists
|
|
5
|
+
*
|
|
6
|
+
* A managed runtime boots someone else's compiled project against a database it
|
|
7
|
+
* has never seen. Auth tables are ensured at boot already, but collection tables
|
|
8
|
+
* were not created by anything: the platform ran the app and every `/api/data/*`
|
|
9
|
+
* request answered 500 on a missing relation. `rebase db push` cannot help — it
|
|
10
|
+
* is an Atlas-driven CLI command, and the runtime image ships no CLI.
|
|
11
|
+
*
|
|
12
|
+
* ## Why additive-only, forever
|
|
13
|
+
*
|
|
14
|
+
* This runs unattended, against a database with customers' data in it, with no
|
|
15
|
+
* human reading a diff. So it may only ever do things that cannot lose data:
|
|
16
|
+
* create a missing table, add a missing column, create a missing enum type.
|
|
17
|
+
*
|
|
18
|
+
* It will **never** drop a table or a column, narrow a type, or alter a
|
|
19
|
+
* constraint. A removed field leaves its column behind; a renamed field looks
|
|
20
|
+
* like an addition and the old column stays. That is the correct trade for an
|
|
21
|
+
* automated path — the alternative is an unattended process that can silently
|
|
22
|
+
* destroy a column, which is precisely the failure `db push` was hardened
|
|
23
|
+
* against. Destructive changes stay a deliberate, human-reviewed migration.
|
|
24
|
+
*
|
|
25
|
+
* Because of that, this is safe to run on every boot, and re-running it is a
|
|
26
|
+
* no-op.
|
|
27
|
+
*/
|
|
28
|
+
import { type CollectionConfig } from "@rebasepro/types";
|
|
29
|
+
/**
|
|
30
|
+
* The subset of a database handle this needs: run a statement, get rows back.
|
|
31
|
+
*
|
|
32
|
+
* Deliberately parameterless. Everything here is DDL or catalogue reads keyed by
|
|
33
|
+
* schema name, and schema names are identifiers — they cannot be bound as
|
|
34
|
+
* parameters anyway. They are validated against {@link SAFE_IDENTIFIER} before
|
|
35
|
+
* they reach a statement, so a config that somehow carried a quote is refused
|
|
36
|
+
* rather than concatenated.
|
|
37
|
+
*/
|
|
38
|
+
export interface Queryable {
|
|
39
|
+
query<T = unknown>(sql: string): Promise<{
|
|
40
|
+
rows: T[];
|
|
41
|
+
}>;
|
|
42
|
+
}
|
|
43
|
+
/** What the database currently has, as the planner needs it. */
|
|
44
|
+
export interface ExistingSchema {
|
|
45
|
+
/** `schema.table` → set of column names. */
|
|
46
|
+
tables: Map<string, Set<string>>;
|
|
47
|
+
/** `schema.typename` of every enum type that already exists. */
|
|
48
|
+
enums: Set<string>;
|
|
49
|
+
}
|
|
50
|
+
export interface EnsureAction {
|
|
51
|
+
kind: "create-enum" | "create-table" | "add-column";
|
|
52
|
+
/** Qualified target, for logging: `public.posts` or `public.posts.title`. */
|
|
53
|
+
target: string;
|
|
54
|
+
sql: string;
|
|
55
|
+
}
|
|
56
|
+
export interface EnsurePlan {
|
|
57
|
+
actions: EnsureAction[];
|
|
58
|
+
/** Every statement, in dependency order. Empty when the schema is current. */
|
|
59
|
+
statements: string[];
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Decide what to add. Pure — the caller supplies what exists and runs the result.
|
|
63
|
+
*
|
|
64
|
+
* Ordering matters and is deliberate: enum types before the tables and columns
|
|
65
|
+
* that reference them, tables before the columns added to other tables (a new
|
|
66
|
+
* table may be the target of a relation), and nothing is emitted twice.
|
|
67
|
+
*/
|
|
68
|
+
export declare function planCollectionSchemaEnsure(collections: CollectionConfig[], existing: ExistingSchema): EnsurePlan;
|
|
69
|
+
/** Read what the database has, for the schemas the collections live in. */
|
|
70
|
+
export declare function readExistingSchema(client: Queryable, schemas: string[]): Promise<ExistingSchema>;
|
|
71
|
+
/**
|
|
72
|
+
* Bring the database up to date. Returns what it did.
|
|
73
|
+
*
|
|
74
|
+
* Each statement runs on its own rather than in one transaction: they are all
|
|
75
|
+
* independently safe and idempotent, and a single failure (an enum label that
|
|
76
|
+
* cannot be added, say) should not roll back the tables that were created fine.
|
|
77
|
+
* The error is surfaced with the statement that caused it.
|
|
78
|
+
*/
|
|
79
|
+
export declare function ensureCollectionTables(client: Queryable, collections: CollectionConfig[], log?: (message: string) => void): Promise<EnsurePlan>;
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import { CollectionConfig } from "@rebasepro/types";
|
|
1
|
+
import { CollectionConfig, Property } from "@rebasepro/types";
|
|
2
|
+
export declare const resolveColumnName: (propName: string, prop?: Property | null) => string;
|
|
3
|
+
export declare const isIdProperty: (propName: string, prop: Property, collection: CollectionConfig) => boolean;
|
|
4
|
+
export declare const getSqlColumnType: (propName: string, prop: Property, collection: CollectionConfig, collections: CollectionConfig[]) => string;
|
|
2
5
|
export declare const generatePostgresDdl: (collections: CollectionConfig[], options?: {
|
|
3
6
|
includePolicies?: boolean;
|
|
4
7
|
}) => Promise<string>;
|
|
@@ -23,19 +23,14 @@ export declare function parseCdcPayload(payload: string): CdcChangeEvent | null;
|
|
|
23
23
|
/**
|
|
24
24
|
* Dedicated Postgres LISTEN client for database-level CDC.
|
|
25
25
|
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
26
|
+
* A {@link PgNotifyListener} — a connection outside the Drizzle pool that stays
|
|
27
|
+
* open and repairs itself — plus the parsing that turns a `rebase_cdc` payload
|
|
28
|
+
* into a change event. Each backend instance runs one, so every instance
|
|
29
|
+
* observes every committed change regardless of which instance (or external
|
|
30
|
+
* process) made the write.
|
|
31
31
|
*/
|
|
32
32
|
export declare class CdcListener {
|
|
33
|
-
private readonly
|
|
34
|
-
private readonly onEvent;
|
|
35
|
-
private client?;
|
|
36
|
-
private running;
|
|
37
|
-
private reconnectTimer?;
|
|
38
|
-
private static readonly RECONNECT_DELAY_MS;
|
|
33
|
+
private readonly listener;
|
|
39
34
|
constructor(connectionString: string, onEvent: (event: CdcChangeEvent) => void | Promise<void>);
|
|
40
35
|
/**
|
|
41
36
|
* Connect and begin listening. Idempotent.
|
|
@@ -44,11 +39,9 @@ export declare class CdcListener {
|
|
|
44
39
|
* established (or `LISTEN` is refused), this rejects so callers — notably
|
|
45
40
|
* `REALTIME_CDC=auto` — can detect an unusable connection and fall back to
|
|
46
41
|
* app-level realtime. Once the initial connection succeeds, later drops
|
|
47
|
-
* self-heal
|
|
42
|
+
* self-heal in the background.
|
|
48
43
|
*/
|
|
49
44
|
start(): Promise<void>;
|
|
50
45
|
/** Stop listening and release the connection. */
|
|
51
46
|
stop(): Promise<void>;
|
|
52
|
-
private connect;
|
|
53
|
-
private scheduleReconnect;
|
|
54
47
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime pieces of the channel bus that are not the contract itself.
|
|
3
|
+
*
|
|
4
|
+
* The interface, the frame shape and the implementer's contract live in
|
|
5
|
+
* `@rebasepro/types` (`types/channel_bus.ts`), so a transport shipped as its own
|
|
6
|
+
* package — a Redis one, say — depends on the contract and not on this database
|
|
7
|
+
* adapter. They are re-exported here for convenience: code already importing
|
|
8
|
+
* from the adapter should not have to know where the types are declared.
|
|
9
|
+
*/
|
|
10
|
+
import type { ChannelBusFrame } from "@rebasepro/types";
|
|
11
|
+
export type { ChannelBus, ChannelBusFrame, ChannelBusHandler, ChannelBusConfig, ChannelBusSetting } from "@rebasepro/types";
|
|
12
|
+
export { isChannelBusInstance } from "@rebasepro/types";
|
|
13
|
+
/**
|
|
14
|
+
* The default: no cross-instance delivery at all.
|
|
15
|
+
*
|
|
16
|
+
* This is what every deployment ran before the bus existed, and what a
|
|
17
|
+
* single-instance deployment should keep running — `publish` resolves without
|
|
18
|
+
* touching the network, so the broadcast path is the same handful of `ws.send`
|
|
19
|
+
* calls it always was.
|
|
20
|
+
*/
|
|
21
|
+
export declare class MemoryChannelBus {
|
|
22
|
+
readonly kind: "memory";
|
|
23
|
+
readonly maxFrameBytes: number;
|
|
24
|
+
start(): Promise<void>;
|
|
25
|
+
publish(): Promise<void>;
|
|
26
|
+
stop(): Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
/** Encoded size of a frame, for a transport's size check. */
|
|
29
|
+
export declare function frameByteLength(frame: ChannelBusFrame): number;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Channel bus over Postgres LISTEN/NOTIFY.
|
|
3
|
+
*
|
|
4
|
+
* Chosen because it needs nothing that a Rebase deployment does not already
|
|
5
|
+
* have — the same database, the same direct URL the CDC listener uses. Three
|
|
6
|
+
* properties of `NOTIFY` shape everything below:
|
|
7
|
+
*
|
|
8
|
+
* - **8000 bytes per payload.** Presence and cursors fit with room to spare; a
|
|
9
|
+
* scene snapshot does not. Rather than truncate or drop, an oversized frame
|
|
10
|
+
* on a *retained* channel is published as a pointer — the body is already in
|
|
11
|
+
* `rebase.channel_messages` with a sequence number, so the receiver reads it
|
|
12
|
+
* back. That is the same trick the entity path uses (notify an address,
|
|
13
|
+
* refetch the row), applied to a different table. On an ephemeral channel
|
|
14
|
+
* there is nothing to point at, so the publish is refused loudly instead of
|
|
15
|
+
* reaching some instances and not others.
|
|
16
|
+
*
|
|
17
|
+
* - **A notify is a query on the primary database.** Not a slow one, but it
|
|
18
|
+
* competes with the application's real queries, and that — not throughput —
|
|
19
|
+
* is what actually limits this transport. Measured, it carried ~10k
|
|
20
|
+
* cross-instance messages/second and stayed flat out to eight instances; what
|
|
21
|
+
* it should not do is spend 10k queries/second of the database's budget on
|
|
22
|
+
* cursor movement. Hence the batching below.
|
|
23
|
+
*
|
|
24
|
+
* - **Delivery is best-effort.** Retained channels repair themselves through
|
|
25
|
+
* the client's history replay, so a lost frame costs a live update rather
|
|
26
|
+
* than correctness. That is what makes coalescing safe.
|
|
27
|
+
*/
|
|
28
|
+
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
29
|
+
import { ChannelBus, ChannelBusFrame, ChannelBusHandler } from "./ChannelBus";
|
|
30
|
+
/** NOTIFY channel carrying channel-bus frames. */
|
|
31
|
+
export declare const CHANNEL_BUS_NOTIFY_CHANNEL = "rebase_channel_bus";
|
|
32
|
+
/**
|
|
33
|
+
* Postgres refuses a NOTIFY payload of 8000 bytes or more. The margin below it
|
|
34
|
+
* is for nothing in particular — it is there so that a payload which passes this
|
|
35
|
+
* check cannot fail at the server for being a few bytes over.
|
|
36
|
+
*/
|
|
37
|
+
export declare const PG_NOTIFY_MAX_PAYLOAD_BYTES = 7500;
|
|
38
|
+
/**
|
|
39
|
+
* How long a batching window stays open.
|
|
40
|
+
*
|
|
41
|
+
* Ten milliseconds is below the threshold where a human notices a cursor lag,
|
|
42
|
+
* and it is the difference between one query per message and one query per
|
|
43
|
+
* window under load. Set to 0 to disable coalescing entirely.
|
|
44
|
+
*/
|
|
45
|
+
export declare const DEFAULT_BATCH_WINDOW_MS = 10;
|
|
46
|
+
export declare class PostgresChannelBus implements ChannelBus {
|
|
47
|
+
private readonly db;
|
|
48
|
+
private readonly connectionString;
|
|
49
|
+
readonly kind: "postgres";
|
|
50
|
+
readonly maxFrameBytes = 7500;
|
|
51
|
+
private listener?;
|
|
52
|
+
private readonly batchWindowMs;
|
|
53
|
+
/**
|
|
54
|
+
* Frames waiting for the current window to close.
|
|
55
|
+
*
|
|
56
|
+
* The window is opened by a publish that found none open, and that publish
|
|
57
|
+
* is sent *immediately* rather than joining a batch — see {@link publish}.
|
|
58
|
+
*/
|
|
59
|
+
private pending;
|
|
60
|
+
private pendingBytes;
|
|
61
|
+
private windowTimer?;
|
|
62
|
+
private stopped;
|
|
63
|
+
constructor(db: NodePgDatabase<Record<string, unknown>>, connectionString: string, options?: {
|
|
64
|
+
batchWindowMs?: number;
|
|
65
|
+
});
|
|
66
|
+
start(handler: ChannelBusHandler): Promise<void>;
|
|
67
|
+
/**
|
|
68
|
+
* Publish, coalescing under load.
|
|
69
|
+
*
|
|
70
|
+
* The window is *leading edge*: a publish arriving when no window is open is
|
|
71
|
+
* sent straight away and opens one, so an idle channel pays no added latency
|
|
72
|
+
* at all. Frames arriving while it is open are collected and leave together
|
|
73
|
+
* when it closes. The effect is that cost tracks elapsed time rather than
|
|
74
|
+
* message count — one query per window instead of one per message — which is
|
|
75
|
+
* the same shape as the retention pruning throttle, for the same reason.
|
|
76
|
+
*
|
|
77
|
+
* The returned promise settles when the frame has actually left, not when it
|
|
78
|
+
* was queued, so the contract ("reaches the other instances, or rejects")
|
|
79
|
+
* still holds.
|
|
80
|
+
*/
|
|
81
|
+
publish(frame: ChannelBusFrame): Promise<void>;
|
|
82
|
+
stop(): Promise<void>;
|
|
83
|
+
private openWindow;
|
|
84
|
+
/** Send everything queued and settle the promises waiting on it. */
|
|
85
|
+
private flush;
|
|
86
|
+
/**
|
|
87
|
+
* One NOTIFY.
|
|
88
|
+
*
|
|
89
|
+
* A single frame goes out in the plain, unwrapped shape. That is not just
|
|
90
|
+
* economy: during a rolling deploy an instance running the previous build
|
|
91
|
+
* understands only that shape, and low-rate traffic — presence, the tail of
|
|
92
|
+
* a session — is exactly what is flowing while pods restart. Batching only
|
|
93
|
+
* appears under load, which shrinks the mixed-version window to almost
|
|
94
|
+
* nothing.
|
|
95
|
+
*/
|
|
96
|
+
private send;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Parse a bus payload into the frames it carries.
|
|
100
|
+
*
|
|
101
|
+
* Accepts both wire shapes — a bare frame and a `{ batch: [...] }` envelope —
|
|
102
|
+
* so an instance on the new build understands one on the old. Returns an empty
|
|
103
|
+
* array for anything unrecognisable: a malformed or future-versioned message
|
|
104
|
+
* must never take the listener down.
|
|
105
|
+
*/
|
|
106
|
+
export declare function parseChannelBusPayload(payload: string): ChannelBusFrame[];
|
|
107
|
+
/**
|
|
108
|
+
* Parse a single bus frame, returning null for anything that is not a frame we
|
|
109
|
+
* understand.
|
|
110
|
+
*/
|
|
111
|
+
export declare function parseChannelBusFrame(payload: string): ChannelBusFrame | null;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolution of the channel bus from config, environment, or a supplied instance.
|
|
3
|
+
*
|
|
4
|
+
* Opt-in, like every other cross-cutting realtime switch here: with nothing
|
|
5
|
+
* configured a deployment gets the memory bus and behaves exactly as it did
|
|
6
|
+
* before this existed. Unlike `REALTIME_CDC=auto`, there is no "try it and see"
|
|
7
|
+
* default — a bus changes where messages go, and quietly turning on a Postgres
|
|
8
|
+
* NOTIFY per broadcast because a direct URL happened to be set is not a
|
|
9
|
+
* decision to make on the user's behalf.
|
|
10
|
+
*
|
|
11
|
+
* Two transports ship, and neither adds a service to a deployment. A third is
|
|
12
|
+
* not a code change here: `realtime.bus` also accepts an already-constructed
|
|
13
|
+
* {@link ChannelBus}, so a transport published as its own package plugs in
|
|
14
|
+
* without this file learning about it. See `@rebasepro/types` →
|
|
15
|
+
* `types/channel_bus.ts` for the contract such a package implements.
|
|
16
|
+
*/
|
|
17
|
+
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
18
|
+
import { type ChannelBus, type ChannelBusConfig, type ChannelBusSetting } from "@rebasepro/types";
|
|
19
|
+
export * from "./ChannelBus";
|
|
20
|
+
export { PostgresChannelBus, CHANNEL_BUS_NOTIFY_CHANNEL, PG_NOTIFY_MAX_PAYLOAD_BYTES, DEFAULT_BATCH_WINDOW_MS, parseChannelBusFrame, parseChannelBusPayload } from "./PostgresChannelBus";
|
|
21
|
+
export interface ChannelBusDeps {
|
|
22
|
+
db: NodePgDatabase<Record<string, unknown>>;
|
|
23
|
+
/**
|
|
24
|
+
* Direct (non-pooled) Postgres URL for the LISTEN client. `LISTEN` is
|
|
25
|
+
* session state, so behind PgBouncer in transaction mode this must be the
|
|
26
|
+
* database itself and not the pooler.
|
|
27
|
+
*/
|
|
28
|
+
directUrl?: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Merge `REALTIME_CHANNEL_BUS` into the configured bus.
|
|
32
|
+
*
|
|
33
|
+
* The environment wins over a *named* built-in, so the transport can be changed
|
|
34
|
+
* per deployment without a rebuild — the same reason `REALTIME_CDC` is an env
|
|
35
|
+
* var. It does **not** win over a supplied instance: the env var can only name
|
|
36
|
+
* transports this package knows how to construct, so honouring it there would
|
|
37
|
+
* mean silently discarding the object the application handed us.
|
|
38
|
+
*/
|
|
39
|
+
export declare function resolveChannelBusSetting(configured?: ChannelBusSetting): ChannelBusSetting;
|
|
40
|
+
/**
|
|
41
|
+
* @deprecated Use {@link resolveChannelBusSetting}, which also accepts a
|
|
42
|
+
* supplied {@link ChannelBus} instance. Kept as a narrow alias so existing
|
|
43
|
+
* config-only callers keep their exact types.
|
|
44
|
+
*/
|
|
45
|
+
export declare function resolveChannelBusConfig(configured?: ChannelBusConfig): ChannelBusConfig;
|
|
46
|
+
/**
|
|
47
|
+
* Produce the bus a setting asks for.
|
|
48
|
+
*
|
|
49
|
+
* An instance is handed straight back — constructing it was the application's
|
|
50
|
+
* job, and this function has nothing to add. A named built-in that turns out to
|
|
51
|
+
* be unusable degrades to the memory bus, with the reason logged, rather than
|
|
52
|
+
* throwing: a misconfigured bus should cost a deployment its cross-instance
|
|
53
|
+
* fan-out, not its ability to boot.
|
|
54
|
+
*/
|
|
55
|
+
export declare function createChannelBus(setting: ChannelBusSetting, deps: ChannelBusDeps): ChannelBus;
|
|
@@ -105,6 +105,17 @@ export declare class ChannelHistoryStore {
|
|
|
105
105
|
messages: ChannelHistoryEntry[];
|
|
106
106
|
latestSeq: number;
|
|
107
107
|
}>;
|
|
108
|
+
/**
|
|
109
|
+
* One retained message by its address.
|
|
110
|
+
*
|
|
111
|
+
* This is what makes the cross-instance pointer path work: a broadcast too
|
|
112
|
+
* large to travel inside a `pg_notify` payload is already stored here, so
|
|
113
|
+
* the notification carries `(channel, seq)` and each receiving instance
|
|
114
|
+
* reads the body back. Returns null when the message has since been pruned
|
|
115
|
+
* — a receiver that is that far behind has nothing useful to deliver, and
|
|
116
|
+
* the client's own `channel_history` replay is the repair path.
|
|
117
|
+
*/
|
|
118
|
+
getBySeq(channel: string, seq: number): Promise<ChannelHistoryEntry | null>;
|
|
108
119
|
/**
|
|
109
120
|
* Enforce a channel's retention bounds.
|
|
110
121
|
*
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shared presence roster.
|
|
3
|
+
*
|
|
4
|
+
* Broadcast only ever needed *fan-out* to work across instances — a frame goes
|
|
5
|
+
* out, whoever is connected receives it. Presence needs more than that, because
|
|
6
|
+
* `presence_state` is a question ("who is in this document?") and a per-process
|
|
7
|
+
* `Map` can only answer for the clients that happen to share a replica with the
|
|
8
|
+
* asker. Two people editing the same scene through different pods would each
|
|
9
|
+
* see an empty room while broadcasting cursors at each other perfectly.
|
|
10
|
+
*
|
|
11
|
+
* So presence gets one row per tracked client, in Postgres, readable by every
|
|
12
|
+
* instance. Three consequences worth stating:
|
|
13
|
+
*
|
|
14
|
+
* - **The table is the roster; the in-process map is a cache of our own
|
|
15
|
+
* clients.** Reads answer from the table when this store is active, so the
|
|
16
|
+
* answer is the same whichever instance is asked.
|
|
17
|
+
*
|
|
18
|
+
* - **`last_seen` is the liveness signal, and it is already there.** The client
|
|
19
|
+
* heartbeats presence every ~20 s against a 30 s window; the sweep that has
|
|
20
|
+
* always reaped local stale entries now also reaps rows belonging to
|
|
21
|
+
* instances that stopped writing — which is exactly what a crashed pod looks
|
|
22
|
+
* like. Crash recovery is a property of the TTL, not a separate mechanism.
|
|
23
|
+
*
|
|
24
|
+
* - **The sweep deletes with `RETURNING`.** Whichever instance wins the delete
|
|
25
|
+
* is the one that announces the departures, so a stale client produces one
|
|
26
|
+
* `presence_diff` for the cluster rather than one per replica.
|
|
27
|
+
*/
|
|
28
|
+
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
29
|
+
/** A tracked client, as any instance sees it. */
|
|
30
|
+
export interface PresenceRow {
|
|
31
|
+
channel: string;
|
|
32
|
+
clientId: string;
|
|
33
|
+
state: Record<string, unknown>;
|
|
34
|
+
}
|
|
35
|
+
export declare class ChannelPresenceStore {
|
|
36
|
+
private readonly db;
|
|
37
|
+
private readonly instanceId;
|
|
38
|
+
private tablesReady;
|
|
39
|
+
constructor(db: NodePgDatabase<Record<string, unknown>>, instanceId: string);
|
|
40
|
+
/** Create the roster table. Idempotent. */
|
|
41
|
+
ensureTables(): Promise<void>;
|
|
42
|
+
/** Record (or refresh) a client's presence. */
|
|
43
|
+
track(channel: string, clientId: string, state: Record<string, unknown>): Promise<void>;
|
|
44
|
+
/** Drop one client's presence in one channel. */
|
|
45
|
+
remove(channel: string, clientId: string): Promise<void>;
|
|
46
|
+
/** Drop a client from every channel — used when its socket closes. */
|
|
47
|
+
removeClient(clientId: string): Promise<void>;
|
|
48
|
+
/** The global roster for a channel. */
|
|
49
|
+
roster(channel: string): Promise<Record<string, Record<string, unknown>>>;
|
|
50
|
+
/**
|
|
51
|
+
* Reap rows this instance is not responsible for and that have gone quiet.
|
|
52
|
+
*
|
|
53
|
+
* Own rows are excluded because the in-process sweep already handles them —
|
|
54
|
+
* and handles them better, since it can tell "the socket is gone" from "the
|
|
55
|
+
* heartbeat is late". What is left is precisely the interesting case: rows
|
|
56
|
+
* written by an instance that is no longer writing.
|
|
57
|
+
*
|
|
58
|
+
* Returns what was removed, so the caller can announce it.
|
|
59
|
+
*/
|
|
60
|
+
sweepStale(ttlMs: number): Promise<PresenceRow[]>;
|
|
61
|
+
/**
|
|
62
|
+
* Remove every row this instance owns. Called on graceful shutdown so a
|
|
63
|
+
* rolling deploy does not leave a TTL window of ghosts in every roster.
|
|
64
|
+
*/
|
|
65
|
+
removeInstance(): Promise<void>;
|
|
66
|
+
}
|