@rebasepro/server-postgres 0.10.1-canary.6f89f77 → 0.10.1-canary.7801eed
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/schema-version.d.ts +106 -0
- package/dist/chunk-DSJWtz9O.js +40 -0
- package/dist/collections/validate-relations.d.ts +53 -0
- package/dist/data-transformer.d.ts +3 -3
- package/dist/ensure-collection-tables-DGMYK0fr.js +304 -0
- package/dist/ensure-collection-tables-DGMYK0fr.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.es.js +1853 -4900
- package/dist/index.es.js.map +1 -1
- package/dist/schema/ensure-collection-tables.d.ts +79 -0
- package/dist/schema/generate-postgres-ddl-logic.d.ts +4 -1
- package/dist/services/FetchService.d.ts +21 -8
- package/dist/services/PersistService.d.ts +12 -0
- package/dist/services/RelationService.d.ts +39 -8
- package/dist/services/cdc/CdcListener.d.ts +7 -14
- package/dist/services/cdc/junction-tables.d.ts +38 -0
- 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/nested-path.d.ts +59 -0
- package/dist/services/pg-notify-listener.d.ts +47 -0
- package/dist/services/realtimeService.d.ts +133 -6
- package/dist/services/row-pipeline.d.ts +2 -2
- package/dist/src-3VmUJ8Xn.js +3994 -0
- package/dist/src-3VmUJ8Xn.js.map +1 -0
- package/dist/src-D5xBTl32.js +346 -0
- package/dist/src-D5xBTl32.js.map +1 -0
- package/dist/utils/drizzle-conditions.d.ts +71 -18
- package/package.json +8 -9
- package/src/PostgresBootstrapper.ts +87 -5
- package/src/auth/ensure-tables.ts +23 -0
- package/src/auth/schema-version.ts +260 -0
- package/src/cli-errors.ts +1 -1
- package/src/cli-helpers.ts +4 -3
- package/src/collections/PostgresCollectionRegistry.ts +9 -4
- package/src/collections/buildRegistry.ts +7 -0
- package/src/collections/validate-relations.ts +280 -0
- package/src/data-transformer.ts +28 -38
- package/src/index.ts +4 -0
- package/src/schema/doctor.ts +14 -14
- package/src/schema/ensure-collection-tables.test.ts +156 -0
- package/src/schema/ensure-collection-tables.ts +297 -0
- package/src/schema/generate-drizzle-schema-logic.ts +62 -110
- package/src/schema/generate-postgres-ddl-logic.ts +31 -24
- package/src/schema/introspect-db-inference.ts +13 -13
- package/src/schema/introspect-db-logic.ts +25 -29
- package/src/services/FetchService.ts +116 -126
- package/src/services/PersistService.ts +126 -88
- package/src/services/RelationService.ts +157 -86
- package/src/services/cdc/CdcListener.ts +27 -91
- package/src/services/cdc/junction-tables.ts +91 -0
- 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/nested-path.ts +145 -0
- package/src/services/pg-notify-listener.ts +137 -0
- package/src/services/realtimeService.ts +430 -11
- package/src/services/row-pipeline.ts +5 -6
- package/src/utils/drizzle-conditions.ts +268 -330
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { CollectionConfig, ResolvedRelation, isManyToMany } from "@rebasepro/types";
|
|
2
|
+
import { resolveCollectionRelations } from "@rebasepro/common";
|
|
3
|
+
|
|
4
|
+
import { PostgresCollectionRegistry } from "../../collections/PostgresCollectionRegistry";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* One end of a many-to-many, as seen from the junction table.
|
|
8
|
+
*
|
|
9
|
+
* A junction table is not a collection, so nothing in the registry maps it to
|
|
10
|
+
* one — which is why a change to it was invisible to change capture. But its
|
|
11
|
+
* rows are exactly the contents of a parent's child list, so a write to it is a
|
|
12
|
+
* change to `<parentSlug>/<sourceId>/<relationKey>` and to nothing else.
|
|
13
|
+
*/
|
|
14
|
+
export interface JunctionLink {
|
|
15
|
+
schema: string;
|
|
16
|
+
/** The junction table itself, e.g. `posts_tags`. */
|
|
17
|
+
table: string;
|
|
18
|
+
/** The collection whose relation this is, e.g. `posts`. */
|
|
19
|
+
parentCollection: CollectionConfig;
|
|
20
|
+
/** The relation's key — the path segment a child list is addressed by. */
|
|
21
|
+
relationKey: string;
|
|
22
|
+
/** Junction column holding the parent's id. */
|
|
23
|
+
sourceColumn: string;
|
|
24
|
+
/** Junction column holding the target's id. */
|
|
25
|
+
targetColumn: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Every junction table reachable from a registered collection, once per
|
|
30
|
+
* relation that uses it.
|
|
31
|
+
*
|
|
32
|
+
* A junction is listed once per *direction* when both sides declare it, because
|
|
33
|
+
* each direction addresses a different child list: `posts/1/tags` and
|
|
34
|
+
* `tags/t/posts` both change when one link is written.
|
|
35
|
+
*/
|
|
36
|
+
export function collectJunctionLinks(registry: PostgresCollectionRegistry): JunctionLink[] {
|
|
37
|
+
const links: JunctionLink[] = [];
|
|
38
|
+
const seen = new Set<string>();
|
|
39
|
+
|
|
40
|
+
for (const collection of registry.getCollections()) {
|
|
41
|
+
let relations: Record<string, ResolvedRelation>;
|
|
42
|
+
try {
|
|
43
|
+
relations = resolveCollectionRelations(collection);
|
|
44
|
+
} catch {
|
|
45
|
+
// A collection whose relations cannot be resolved (an unresolvable
|
|
46
|
+
// target, typically mid-migration) simply contributes none.
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
for (const [relationKey, relation] of Object.entries(relations)) {
|
|
51
|
+
if (!isManyToMany(relation)) continue;
|
|
52
|
+
const through = relation.through;
|
|
53
|
+
|
|
54
|
+
// Same relation registered under both its canonical name and the
|
|
55
|
+
// declaring property key would otherwise notify the same path twice.
|
|
56
|
+
const key = `${collection.slug}::${relationKey}::${through.table}`;
|
|
57
|
+
if (seen.has(key)) continue;
|
|
58
|
+
seen.add(key);
|
|
59
|
+
|
|
60
|
+
links.push({
|
|
61
|
+
schema: (collection as { schema?: string }).schema ?? "public",
|
|
62
|
+
table: through.table,
|
|
63
|
+
parentCollection: collection,
|
|
64
|
+
relationKey,
|
|
65
|
+
sourceColumn: through.sourceColumn,
|
|
66
|
+
targetColumn: through.targetColumn
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return links;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Index {@link collectJunctionLinks} by table, under both the qualified and the
|
|
76
|
+
* bare name — a change event carries whatever the trigger reports, and a
|
|
77
|
+
* collection need not declare a schema.
|
|
78
|
+
*/
|
|
79
|
+
export function buildJunctionLinkMap(registry: PostgresCollectionRegistry): Map<string, JunctionLink[]> {
|
|
80
|
+
const map = new Map<string, JunctionLink[]>();
|
|
81
|
+
|
|
82
|
+
for (const link of collectJunctionLinks(registry)) {
|
|
83
|
+
for (const key of [`${link.schema}.${link.table}`, link.table]) {
|
|
84
|
+
const existing = map.get(key);
|
|
85
|
+
if (existing) existing.push(link);
|
|
86
|
+
else map.set(key, [link]);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return map;
|
|
91
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
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
|
+
|
|
11
|
+
import type { ChannelBusFrame } from "@rebasepro/types";
|
|
12
|
+
|
|
13
|
+
export type {
|
|
14
|
+
ChannelBus,
|
|
15
|
+
ChannelBusFrame,
|
|
16
|
+
ChannelBusHandler,
|
|
17
|
+
ChannelBusConfig,
|
|
18
|
+
ChannelBusSetting
|
|
19
|
+
} from "@rebasepro/types";
|
|
20
|
+
export { isChannelBusInstance } from "@rebasepro/types";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The default: no cross-instance delivery at all.
|
|
24
|
+
*
|
|
25
|
+
* This is what every deployment ran before the bus existed, and what a
|
|
26
|
+
* single-instance deployment should keep running — `publish` resolves without
|
|
27
|
+
* touching the network, so the broadcast path is the same handful of `ws.send`
|
|
28
|
+
* calls it always was.
|
|
29
|
+
*/
|
|
30
|
+
export class MemoryChannelBus {
|
|
31
|
+
readonly kind = "memory" as const;
|
|
32
|
+
readonly maxFrameBytes = Infinity;
|
|
33
|
+
|
|
34
|
+
async start(): Promise<void> { /* nothing to connect */ }
|
|
35
|
+
|
|
36
|
+
async publish(): Promise<void> { /* nowhere to publish to */ }
|
|
37
|
+
|
|
38
|
+
async stop(): Promise<void> { /* nothing to release */ }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Encoded size of a frame, for a transport's size check. */
|
|
42
|
+
export function frameByteLength(frame: ChannelBusFrame): number {
|
|
43
|
+
return Buffer.byteLength(JSON.stringify(frame), "utf8");
|
|
44
|
+
}
|
|
@@ -0,0 +1,299 @@
|
|
|
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
|
+
|
|
29
|
+
import { sql } from "drizzle-orm";
|
|
30
|
+
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
31
|
+
import { logger } from "@rebasepro/server";
|
|
32
|
+
import { PgNotifyListener } from "../pg-notify-listener";
|
|
33
|
+
import { ChannelBus, ChannelBusFrame, ChannelBusHandler, frameByteLength } from "./ChannelBus";
|
|
34
|
+
|
|
35
|
+
/** NOTIFY channel carrying channel-bus frames. */
|
|
36
|
+
export const CHANNEL_BUS_NOTIFY_CHANNEL = "rebase_channel_bus";
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Postgres refuses a NOTIFY payload of 8000 bytes or more. The margin below it
|
|
40
|
+
* is for nothing in particular — it is there so that a payload which passes this
|
|
41
|
+
* check cannot fail at the server for being a few bytes over.
|
|
42
|
+
*/
|
|
43
|
+
export const PG_NOTIFY_MAX_PAYLOAD_BYTES = 7500;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* How long a batching window stays open.
|
|
47
|
+
*
|
|
48
|
+
* Ten milliseconds is below the threshold where a human notices a cursor lag,
|
|
49
|
+
* and it is the difference between one query per message and one query per
|
|
50
|
+
* window under load. Set to 0 to disable coalescing entirely.
|
|
51
|
+
*/
|
|
52
|
+
export const DEFAULT_BATCH_WINDOW_MS = 10;
|
|
53
|
+
|
|
54
|
+
/** JSON overhead per frame inside a batch: the wrapping array's comma. */
|
|
55
|
+
const BATCH_SEPARATOR_BYTES = 1;
|
|
56
|
+
/** JSON overhead of the batch envelope itself: `{"batch":[]}`. */
|
|
57
|
+
const BATCH_ENVELOPE_BYTES = 12;
|
|
58
|
+
|
|
59
|
+
interface PendingFrame {
|
|
60
|
+
frame: ChannelBusFrame;
|
|
61
|
+
bytes: number;
|
|
62
|
+
resolve: () => void;
|
|
63
|
+
reject: (error: unknown) => void;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export class PostgresChannelBus implements ChannelBus {
|
|
67
|
+
readonly kind = "postgres" as const;
|
|
68
|
+
readonly maxFrameBytes = PG_NOTIFY_MAX_PAYLOAD_BYTES;
|
|
69
|
+
|
|
70
|
+
private listener?: PgNotifyListener;
|
|
71
|
+
private readonly batchWindowMs: number;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Frames waiting for the current window to close.
|
|
75
|
+
*
|
|
76
|
+
* The window is opened by a publish that found none open, and that publish
|
|
77
|
+
* is sent *immediately* rather than joining a batch — see {@link publish}.
|
|
78
|
+
*/
|
|
79
|
+
private pending: PendingFrame[] = [];
|
|
80
|
+
private pendingBytes = BATCH_ENVELOPE_BYTES;
|
|
81
|
+
private windowTimer?: ReturnType<typeof setTimeout>;
|
|
82
|
+
private stopped = false;
|
|
83
|
+
|
|
84
|
+
constructor(
|
|
85
|
+
private readonly db: NodePgDatabase<Record<string, unknown>>,
|
|
86
|
+
private readonly connectionString: string,
|
|
87
|
+
options: { batchWindowMs?: number } = {}
|
|
88
|
+
) {
|
|
89
|
+
const configured = options.batchWindowMs;
|
|
90
|
+
this.batchWindowMs = typeof configured === "number" && configured >= 0
|
|
91
|
+
? configured
|
|
92
|
+
: DEFAULT_BATCH_WINDOW_MS;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async start(handler: ChannelBusHandler): Promise<void> {
|
|
96
|
+
this.stopped = false;
|
|
97
|
+
this.listener = new PgNotifyListener({
|
|
98
|
+
connectionString: this.connectionString,
|
|
99
|
+
channel: CHANNEL_BUS_NOTIFY_CHANNEL,
|
|
100
|
+
logLabel: "[ChannelBus]",
|
|
101
|
+
onPayload: async (payload) => {
|
|
102
|
+
const frames = parseChannelBusPayload(payload);
|
|
103
|
+
if (!frames.length) {
|
|
104
|
+
logger.warn("⚠️ [ChannelBus] Dropping unparseable payload.");
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
// In order: a batch preserves the sender's publish order, and a
|
|
108
|
+
// retained channel's consumers rely on it.
|
|
109
|
+
for (const frame of frames) await handler(frame);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
await this.listener.start();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Publish, coalescing under load.
|
|
117
|
+
*
|
|
118
|
+
* The window is *leading edge*: a publish arriving when no window is open is
|
|
119
|
+
* sent straight away and opens one, so an idle channel pays no added latency
|
|
120
|
+
* at all. Frames arriving while it is open are collected and leave together
|
|
121
|
+
* when it closes. The effect is that cost tracks elapsed time rather than
|
|
122
|
+
* message count — one query per window instead of one per message — which is
|
|
123
|
+
* the same shape as the retention pruning throttle, for the same reason.
|
|
124
|
+
*
|
|
125
|
+
* The returned promise settles when the frame has actually left, not when it
|
|
126
|
+
* was queued, so the contract ("reaches the other instances, or rejects")
|
|
127
|
+
* still holds.
|
|
128
|
+
*/
|
|
129
|
+
async publish(frame: ChannelBusFrame): Promise<void> {
|
|
130
|
+
if (this.batchWindowMs === 0 || this.stopped) {
|
|
131
|
+
await this.send([frame]);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (!this.windowTimer) {
|
|
136
|
+
this.openWindow();
|
|
137
|
+
await this.send([frame]);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const bytes = frameByteLength(frame) + BATCH_SEPARATOR_BYTES;
|
|
142
|
+
|
|
143
|
+
// A batch is one NOTIFY payload, so the 8 KB ceiling applies to the
|
|
144
|
+
// whole batch. Send what we have rather than let the frame push it over.
|
|
145
|
+
if (this.pending.length && this.pendingBytes + bytes > this.maxFrameBytes) {
|
|
146
|
+
this.flush();
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return new Promise<void>((resolve, reject) => {
|
|
150
|
+
this.pending.push({ frame, bytes, resolve, reject });
|
|
151
|
+
this.pendingBytes += bytes;
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async stop(): Promise<void> {
|
|
156
|
+
this.stopped = true;
|
|
157
|
+
if (this.windowTimer) {
|
|
158
|
+
clearTimeout(this.windowTimer);
|
|
159
|
+
this.windowTimer = undefined;
|
|
160
|
+
}
|
|
161
|
+
// Anything still queued belongs to clients that are already waiting on
|
|
162
|
+
// it; dropping it on shutdown would be a silent loss where a flush costs
|
|
163
|
+
// one more query.
|
|
164
|
+
this.flush();
|
|
165
|
+
await this.listener?.stop();
|
|
166
|
+
this.listener = undefined;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
private openWindow(): void {
|
|
170
|
+
this.windowTimer = setTimeout(() => {
|
|
171
|
+
this.windowTimer = undefined;
|
|
172
|
+
if (this.pending.length) {
|
|
173
|
+
// Still busy: send this window's frames and open the next one,
|
|
174
|
+
// so a sustained stream keeps costing one query per window.
|
|
175
|
+
this.flush();
|
|
176
|
+
this.openWindow();
|
|
177
|
+
}
|
|
178
|
+
// Otherwise leave it closed, so the next publish after a quiet
|
|
179
|
+
// moment goes out immediately.
|
|
180
|
+
}, this.batchWindowMs);
|
|
181
|
+
|
|
182
|
+
// Housekeeping must never hold the process open.
|
|
183
|
+
(this.windowTimer as unknown as { unref?: () => void }).unref?.();
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Send everything queued and settle the promises waiting on it. */
|
|
187
|
+
private flush(): void {
|
|
188
|
+
if (!this.pending.length) return;
|
|
189
|
+
|
|
190
|
+
const batch = this.pending;
|
|
191
|
+
this.pending = [];
|
|
192
|
+
this.pendingBytes = BATCH_ENVELOPE_BYTES;
|
|
193
|
+
|
|
194
|
+
this.send(batch.map(p => p.frame))
|
|
195
|
+
.then(() => { for (const p of batch) p.resolve(); })
|
|
196
|
+
.catch((error) => { for (const p of batch) p.reject(error); });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* One NOTIFY.
|
|
201
|
+
*
|
|
202
|
+
* A single frame goes out in the plain, unwrapped shape. That is not just
|
|
203
|
+
* economy: during a rolling deploy an instance running the previous build
|
|
204
|
+
* understands only that shape, and low-rate traffic — presence, the tail of
|
|
205
|
+
* a session — is exactly what is flowing while pods restart. Batching only
|
|
206
|
+
* appears under load, which shrinks the mixed-version window to almost
|
|
207
|
+
* nothing.
|
|
208
|
+
*/
|
|
209
|
+
private async send(frames: ChannelBusFrame[]): Promise<void> {
|
|
210
|
+
if (!frames.length) return;
|
|
211
|
+
const payload = frames.length === 1
|
|
212
|
+
? JSON.stringify(frames[0])
|
|
213
|
+
: JSON.stringify({ batch: frames });
|
|
214
|
+
|
|
215
|
+
await this.db.execute(sql`SELECT pg_notify(${CHANNEL_BUS_NOTIFY_CHANNEL}, ${payload})`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Parse a bus payload into the frames it carries.
|
|
221
|
+
*
|
|
222
|
+
* Accepts both wire shapes — a bare frame and a `{ batch: [...] }` envelope —
|
|
223
|
+
* so an instance on the new build understands one on the old. Returns an empty
|
|
224
|
+
* array for anything unrecognisable: a malformed or future-versioned message
|
|
225
|
+
* must never take the listener down.
|
|
226
|
+
*/
|
|
227
|
+
export function parseChannelBusPayload(payload: string): ChannelBusFrame[] {
|
|
228
|
+
let parsed: unknown;
|
|
229
|
+
try {
|
|
230
|
+
parsed = JSON.parse(payload);
|
|
231
|
+
} catch {
|
|
232
|
+
return [];
|
|
233
|
+
}
|
|
234
|
+
if (!parsed || typeof parsed !== "object") return [];
|
|
235
|
+
|
|
236
|
+
const batch = (parsed as { batch?: unknown }).batch;
|
|
237
|
+
if (Array.isArray(batch)) {
|
|
238
|
+
return batch
|
|
239
|
+
.map(entry => coerceFrame(entry))
|
|
240
|
+
.filter((frame): frame is ChannelBusFrame => frame !== null);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const single = coerceFrame(parsed);
|
|
244
|
+
return single ? [single] : [];
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Parse a single bus frame, returning null for anything that is not a frame we
|
|
249
|
+
* understand.
|
|
250
|
+
*/
|
|
251
|
+
export function parseChannelBusFrame(payload: string): ChannelBusFrame | null {
|
|
252
|
+
try {
|
|
253
|
+
return coerceFrame(JSON.parse(payload));
|
|
254
|
+
} catch {
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function coerceFrame(value: unknown): ChannelBusFrame | null {
|
|
260
|
+
if (!value || typeof value !== "object") return null;
|
|
261
|
+
|
|
262
|
+
const obj = value as Record<string, unknown>;
|
|
263
|
+
const sid = typeof obj.sid === "string" ? obj.sid : undefined;
|
|
264
|
+
const channel = typeof obj.channel === "string" ? obj.channel : undefined;
|
|
265
|
+
if (!sid || !channel) return null;
|
|
266
|
+
|
|
267
|
+
switch (obj.kind) {
|
|
268
|
+
case "broadcast":
|
|
269
|
+
if (typeof obj.event !== "string") return null;
|
|
270
|
+
return {
|
|
271
|
+
kind: "broadcast",
|
|
272
|
+
sid,
|
|
273
|
+
channel,
|
|
274
|
+
event: obj.event,
|
|
275
|
+
from: typeof obj.from === "string" ? obj.from : undefined,
|
|
276
|
+
seq: typeof obj.seq === "number" ? obj.seq : undefined,
|
|
277
|
+
payload: obj.payload
|
|
278
|
+
};
|
|
279
|
+
case "broadcast_ref":
|
|
280
|
+
if (typeof obj.seq !== "number") return null;
|
|
281
|
+
return {
|
|
282
|
+
kind: "broadcast_ref",
|
|
283
|
+
sid,
|
|
284
|
+
channel,
|
|
285
|
+
from: typeof obj.from === "string" ? obj.from : undefined,
|
|
286
|
+
seq: obj.seq
|
|
287
|
+
};
|
|
288
|
+
case "presence_diff":
|
|
289
|
+
return {
|
|
290
|
+
kind: "presence_diff",
|
|
291
|
+
sid,
|
|
292
|
+
channel,
|
|
293
|
+
joins: (obj.joins ?? {}) as Record<string, Record<string, unknown>>,
|
|
294
|
+
leaves: (obj.leaves ?? {}) as Record<string, Record<string, unknown>>
|
|
295
|
+
};
|
|
296
|
+
default:
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
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
|
+
|
|
18
|
+
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
19
|
+
import { isChannelBusInstance, type ChannelBus, type ChannelBusConfig, type ChannelBusSetting } from "@rebasepro/types";
|
|
20
|
+
import { logger } from "@rebasepro/server";
|
|
21
|
+
import { MemoryChannelBus } from "./ChannelBus";
|
|
22
|
+
import { PostgresChannelBus } from "./PostgresChannelBus";
|
|
23
|
+
|
|
24
|
+
export * from "./ChannelBus";
|
|
25
|
+
export {
|
|
26
|
+
PostgresChannelBus,
|
|
27
|
+
CHANNEL_BUS_NOTIFY_CHANNEL,
|
|
28
|
+
PG_NOTIFY_MAX_PAYLOAD_BYTES,
|
|
29
|
+
DEFAULT_BATCH_WINDOW_MS,
|
|
30
|
+
parseChannelBusFrame,
|
|
31
|
+
parseChannelBusPayload
|
|
32
|
+
} from "./PostgresChannelBus";
|
|
33
|
+
|
|
34
|
+
export interface ChannelBusDeps {
|
|
35
|
+
db: NodePgDatabase<Record<string, unknown>>;
|
|
36
|
+
/**
|
|
37
|
+
* Direct (non-pooled) Postgres URL for the LISTEN client. `LISTEN` is
|
|
38
|
+
* session state, so behind PgBouncer in transaction mode this must be the
|
|
39
|
+
* database itself and not the pooler.
|
|
40
|
+
*/
|
|
41
|
+
directUrl?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Merge `REALTIME_CHANNEL_BUS` into the configured bus.
|
|
46
|
+
*
|
|
47
|
+
* The environment wins over a *named* built-in, so the transport can be changed
|
|
48
|
+
* per deployment without a rebuild — the same reason `REALTIME_CDC` is an env
|
|
49
|
+
* var. It does **not** win over a supplied instance: the env var can only name
|
|
50
|
+
* transports this package knows how to construct, so honouring it there would
|
|
51
|
+
* mean silently discarding the object the application handed us.
|
|
52
|
+
*/
|
|
53
|
+
export function resolveChannelBusSetting(configured?: ChannelBusSetting): ChannelBusSetting {
|
|
54
|
+
const raw = (process.env.REALTIME_CHANNEL_BUS || "").trim().toLowerCase();
|
|
55
|
+
|
|
56
|
+
if (isChannelBusInstance(configured)) {
|
|
57
|
+
if (raw && raw !== configured.kind) {
|
|
58
|
+
logger.warn(
|
|
59
|
+
`⚠️ [ChannelBus] REALTIME_CHANNEL_BUS="${raw}" is ignored because realtime.bus was given a ` +
|
|
60
|
+
`"${configured.kind}" transport instance directly. Remove one of the two to make the intent clear.`
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
return configured;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (!raw) return configured ?? { type: "memory" };
|
|
67
|
+
|
|
68
|
+
if (raw !== "memory" && raw !== "postgres") {
|
|
69
|
+
logger.warn(
|
|
70
|
+
`⚠️ [ChannelBus] Unknown REALTIME_CHANNEL_BUS value "${raw}" — expected memory|postgres, or pass a ` +
|
|
71
|
+
"ChannelBus instance as realtime.bus for a transport that ships separately. Falling back to the " +
|
|
72
|
+
"configured bus."
|
|
73
|
+
);
|
|
74
|
+
return configured ?? { type: "memory" };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Keep the configured options (an explicit connection string) when the env
|
|
78
|
+
// var only restates the type it was already set to.
|
|
79
|
+
if (configured?.type === raw) return configured;
|
|
80
|
+
return raw === "memory" ? { type: "memory" } : { type: "postgres" };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* @deprecated Use {@link resolveChannelBusSetting}, which also accepts a
|
|
85
|
+
* supplied {@link ChannelBus} instance. Kept as a narrow alias so existing
|
|
86
|
+
* config-only callers keep their exact types.
|
|
87
|
+
*/
|
|
88
|
+
export function resolveChannelBusConfig(configured?: ChannelBusConfig): ChannelBusConfig {
|
|
89
|
+
return resolveChannelBusSetting(configured) as ChannelBusConfig;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Produce the bus a setting asks for.
|
|
94
|
+
*
|
|
95
|
+
* An instance is handed straight back — constructing it was the application's
|
|
96
|
+
* job, and this function has nothing to add. A named built-in that turns out to
|
|
97
|
+
* be unusable degrades to the memory bus, with the reason logged, rather than
|
|
98
|
+
* throwing: a misconfigured bus should cost a deployment its cross-instance
|
|
99
|
+
* fan-out, not its ability to boot.
|
|
100
|
+
*/
|
|
101
|
+
export function createChannelBus(setting: ChannelBusSetting, deps: ChannelBusDeps): ChannelBus {
|
|
102
|
+
if (isChannelBusInstance(setting)) return setting;
|
|
103
|
+
|
|
104
|
+
switch (setting.type) {
|
|
105
|
+
case "postgres": {
|
|
106
|
+
const connectionString = setting.connectionString || deps.directUrl;
|
|
107
|
+
if (!connectionString) {
|
|
108
|
+
logger.warn(
|
|
109
|
+
"⚠️ [ChannelBus] realtime.bus is \"postgres\" but no direct database URL is available " +
|
|
110
|
+
"(set DATABASE_DIRECT_URL or realtime.bus.connectionString) — channel broadcast and presence " +
|
|
111
|
+
"stay per-instance."
|
|
112
|
+
);
|
|
113
|
+
return new MemoryChannelBus();
|
|
114
|
+
}
|
|
115
|
+
return new PostgresChannelBus(deps.db, connectionString, {
|
|
116
|
+
batchWindowMs: setting.batchWindowMs
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
case "memory":
|
|
120
|
+
default:
|
|
121
|
+
return new MemoryChannelBus();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -290,6 +290,41 @@ export class ChannelHistoryStore {
|
|
|
290
290
|
return { messages, latestSeq };
|
|
291
291
|
}
|
|
292
292
|
|
|
293
|
+
/**
|
|
294
|
+
* One retained message by its address.
|
|
295
|
+
*
|
|
296
|
+
* This is what makes the cross-instance pointer path work: a broadcast too
|
|
297
|
+
* large to travel inside a `pg_notify` payload is already stored here, so
|
|
298
|
+
* the notification carries `(channel, seq)` and each receiving instance
|
|
299
|
+
* reads the body back. Returns null when the message has since been pruned
|
|
300
|
+
* — a receiver that is that far behind has nothing useful to deliver, and
|
|
301
|
+
* the client's own `channel_history` replay is the repair path.
|
|
302
|
+
*/
|
|
303
|
+
async getBySeq(channel: string, seq: number): Promise<ChannelHistoryEntry | null> {
|
|
304
|
+
const result = await this.db.execute(sql`
|
|
305
|
+
SELECT seq, event, payload, sender_id, created_at
|
|
306
|
+
FROM rebase.channel_messages
|
|
307
|
+
WHERE channel = ${channel} AND seq = ${seq}
|
|
308
|
+
`);
|
|
309
|
+
|
|
310
|
+
const row = result.rows[0] as {
|
|
311
|
+
seq: string | number;
|
|
312
|
+
event: string;
|
|
313
|
+
payload: unknown;
|
|
314
|
+
sender_id: string | null;
|
|
315
|
+
created_at: Date | string;
|
|
316
|
+
} | undefined;
|
|
317
|
+
if (!row) return null;
|
|
318
|
+
|
|
319
|
+
return {
|
|
320
|
+
seq: Number(row.seq),
|
|
321
|
+
event: row.event,
|
|
322
|
+
payload: row.payload,
|
|
323
|
+
senderId: row.sender_id ?? undefined,
|
|
324
|
+
at: row.created_at instanceof Date ? row.created_at.toISOString() : String(row.created_at)
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
293
328
|
/**
|
|
294
329
|
* Enforce a channel's retention bounds.
|
|
295
330
|
*
|