@rebasepro/server-postgres 0.9.1-canary.f2f61da → 0.9.1-canary.faee831
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 +21 -0
- package/dist/PostgresBackendDriver.d.ts +18 -0
- package/dist/PostgresBootstrapper.d.ts +7 -1
- package/dist/index.es.js +489 -33
- package/dist/index.es.js.map +1 -1
- package/dist/schema/introspect-db-logic.d.ts +0 -5
- package/dist/schema/introspect-db-naming.d.ts +10 -0
- package/dist/security/policy-drift.d.ts +30 -0
- package/dist/security/rls-enforcement.d.ts +1 -1
- package/dist/services/channel-history.d.ts +118 -0
- package/dist/services/realtimeService.d.ts +69 -2
- package/package.json +8 -31
- package/src/PostgresBackendDriver.ts +56 -5
- package/src/PostgresBootstrapper.ts +18 -1
- package/src/cli.ts +60 -0
- package/src/schema/introspect-db-inference.ts +1 -1
- package/src/schema/introspect-db-logic.ts +1 -10
- package/src/schema/introspect-db-naming.ts +15 -0
- package/src/schema/introspect-runtime.ts +1 -1
- package/src/security/policy-drift.test.ts +106 -1
- package/src/security/policy-drift.ts +56 -0
- package/src/security/rls-enforcement.ts +4 -4
- package/src/services/channel-history.ts +343 -0
- package/src/services/realtimeService.ts +197 -9
- package/src/websocket.ts +30 -11
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { describe, expect, it } from "@jest/globals";
|
|
2
2
|
import type { CollectionConfig } from "@rebasepro/types";
|
|
3
3
|
|
|
4
|
-
import { checkPolicyDrift, parseExpectedPolicies, formatPolicyDrift, hasDrift, type PolicyRef, type Queryable } from "./policy-drift";
|
|
4
|
+
import { checkPolicyDrift, parseExpectedPolicies, formatPolicyDrift, hasDrift, dropOrphanedPolicies, isGeneratedPolicyName, type PolicyRef, type Queryable } from "./policy-drift";
|
|
5
5
|
import { generatePostgresPoliciesDdl } from "../schema/generate-postgres-ddl-logic";
|
|
6
6
|
|
|
7
7
|
function collection(slug: string): CollectionConfig {
|
|
@@ -154,3 +154,108 @@ describe("checkPolicyDrift", () => {
|
|
|
154
154
|
expect(drift.missing.length).toBeGreaterThan(0);
|
|
155
155
|
});
|
|
156
156
|
});
|
|
157
|
+
|
|
158
|
+
describe("isGeneratedPolicyName", () => {
|
|
159
|
+
it("recognises the generator's own shape", () => {
|
|
160
|
+
expect(isGeneratedPolicyName("documents_insert_a1b2c3d", "documents")).toBe(true);
|
|
161
|
+
// One rule spanning several operations appends the operation index.
|
|
162
|
+
expect(isGeneratedPolicyName("documents_update_a1b2c3d_1", "documents")).toBe(true);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it("does not claim names a human could have written", () => {
|
|
166
|
+
expect(isGeneratedPolicyName("owner_access", "documents")).toBe(false);
|
|
167
|
+
expect(isGeneratedPolicyName("documents_default_admin_read", "documents")).toBe(false);
|
|
168
|
+
// Right shape, wrong table — belongs to something else.
|
|
169
|
+
expect(isGeneratedPolicyName("teams_insert_a1b2c3d", "documents")).toBe(false);
|
|
170
|
+
// A digest is 7 lowercase hex characters, nothing else.
|
|
171
|
+
expect(isGeneratedPolicyName("documents_insert_notahex", "documents")).toBe(false);
|
|
172
|
+
expect(isGeneratedPolicyName("documents_grant_a1b2c3d", "documents")).toBe(false);
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
describe("dropOrphanedPolicies", () => {
|
|
177
|
+
/** Records the DDL issued so the test can assert on what was dropped. */
|
|
178
|
+
function recordingDb(rows: Record<string, unknown>[]) {
|
|
179
|
+
const executed: string[] = [];
|
|
180
|
+
const db: Queryable = {
|
|
181
|
+
query: async (text: string) => {
|
|
182
|
+
if (!/^SELECT/i.test(text)) executed.push(text);
|
|
183
|
+
return { rows: rows as never[] };
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
return { db, executed };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
it("drops the policy a rule edit superseded", async () => {
|
|
190
|
+
// The reported failure: tightening a rule renames its policy, and the
|
|
191
|
+
// permissive original stays live and keeps ORing itself back in.
|
|
192
|
+
const cols = [collection("documents")];
|
|
193
|
+
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
|
|
194
|
+
const stale = {
|
|
195
|
+
schemaname: "public", tablename: "documents", policyname: "documents_insert_dead1ee",
|
|
196
|
+
roles: ["public"], cmd: "INSERT", qual: null, with_check: "true"
|
|
197
|
+
};
|
|
198
|
+
const live = [...expected.map((p) => liveRow(p)), stale];
|
|
199
|
+
|
|
200
|
+
const drift = await checkPolicyDrift(dbWith(live), cols);
|
|
201
|
+
const { db, executed } = recordingDb(live);
|
|
202
|
+
const { dropped, kept } = await dropOrphanedPolicies(db, drift, cols);
|
|
203
|
+
|
|
204
|
+
expect(dropped).toHaveLength(1);
|
|
205
|
+
expect(dropped[0].name).toBe("documents_insert_dead1ee");
|
|
206
|
+
expect(kept).toHaveLength(0);
|
|
207
|
+
expect(executed).toEqual([
|
|
208
|
+
'DROP POLICY IF EXISTS "documents_insert_dead1ee" ON "public"."documents"'
|
|
209
|
+
]);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it("leaves a hand-written policy alone and reports it instead", async () => {
|
|
213
|
+
const cols = [collection("documents")];
|
|
214
|
+
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
|
|
215
|
+
const live = [
|
|
216
|
+
...expected.map((p) => liveRow(p)),
|
|
217
|
+
{ schemaname: "public", tablename: "documents", policyname: "ops_break_glass", roles: ["public"], cmd: "ALL", qual: "true", with_check: null }
|
|
218
|
+
];
|
|
219
|
+
|
|
220
|
+
const drift = await checkPolicyDrift(dbWith(live), cols);
|
|
221
|
+
const { db, executed } = recordingDb(live);
|
|
222
|
+
const { dropped, kept } = await dropOrphanedPolicies(db, drift, cols);
|
|
223
|
+
|
|
224
|
+
expect(dropped).toHaveLength(0);
|
|
225
|
+
expect(kept.map((p) => p.name)).toEqual(["ops_break_glass"]);
|
|
226
|
+
expect(executed).toEqual([]);
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it("never touches a table the collections do not describe", async () => {
|
|
230
|
+
// Another application sharing the schema owns this table; a
|
|
231
|
+
// generator-shaped name there is coincidence, not our leftover.
|
|
232
|
+
const cols = [collection("documents")];
|
|
233
|
+
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
|
|
234
|
+
const live = [
|
|
235
|
+
...expected.map((p) => liveRow(p)),
|
|
236
|
+
{ schemaname: "public", tablename: "legacy", policyname: "legacy_select_a1b2c3d", roles: ["public"], cmd: "SELECT", qual: "true", with_check: null }
|
|
237
|
+
];
|
|
238
|
+
|
|
239
|
+
const drift = await checkPolicyDrift(dbWith(live), cols);
|
|
240
|
+
const { db, executed } = recordingDb(live);
|
|
241
|
+
const { dropped, kept } = await dropOrphanedPolicies(db, drift, cols);
|
|
242
|
+
|
|
243
|
+
expect(dropped).toHaveLength(0);
|
|
244
|
+
expect(kept.map((p) => p.name)).toEqual(["legacy_select_a1b2c3d"]);
|
|
245
|
+
expect(executed).toEqual([]);
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it("does nothing when the database already matches", async () => {
|
|
249
|
+
const cols = [collection("documents")];
|
|
250
|
+
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
|
|
251
|
+
const live = expected.map((p) => liveRow(p));
|
|
252
|
+
|
|
253
|
+
const drift = await checkPolicyDrift(dbWith(live), cols);
|
|
254
|
+
const { db, executed } = recordingDb(live);
|
|
255
|
+
const { dropped, kept } = await dropOrphanedPolicies(db, drift, cols);
|
|
256
|
+
|
|
257
|
+
expect(dropped).toHaveLength(0);
|
|
258
|
+
expect(kept).toHaveLength(0);
|
|
259
|
+
expect(executed).toEqual([]);
|
|
260
|
+
});
|
|
261
|
+
});
|
|
@@ -192,6 +192,62 @@ export async function checkPolicyDrift(
|
|
|
192
192
|
return drift;
|
|
193
193
|
}
|
|
194
194
|
|
|
195
|
+
/**
|
|
196
|
+
* Does this name look like one the generator produced for this table?
|
|
197
|
+
*
|
|
198
|
+
* Unnamed rules compile to `<table>_<op>_<sha1[0:7]>` (plus `_<idx>` when one
|
|
199
|
+
* rule spans several operations), and the hash covers the rule's semantics — so
|
|
200
|
+
* *editing* a rule renames its policy. The policy under the old name is left
|
|
201
|
+
* behind by `db push`, which only DROPs the names it is about to CREATE, and
|
|
202
|
+
* Postgres ORs PERMISSIVE policies together: a superseded `USING (true)` keeps
|
|
203
|
+
* granting everything no matter how tight its replacement is.
|
|
204
|
+
*
|
|
205
|
+
* Matching the shape is what makes dropping them safe. A hand-written policy
|
|
206
|
+
* would have to collide with a 7-hex digest to be mistaken for generated one;
|
|
207
|
+
* a policy named anything else is left alone and merely reported, because a
|
|
208
|
+
* custom name is indistinguishable from one someone wrote in SQL on purpose.
|
|
209
|
+
*/
|
|
210
|
+
export function isGeneratedPolicyName(name: string, table: string): boolean {
|
|
211
|
+
return new RegExp(`^${table.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}_(select|insert|update|delete|all)_[0-9a-f]{7}(_\\d+)?$`)
|
|
212
|
+
.test(name);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export interface OrphanCleanup {
|
|
216
|
+
/** Superseded generated policies that were dropped. */
|
|
217
|
+
dropped: PolicyRef[];
|
|
218
|
+
/** Orphans left in place because their names are not generator-shaped. */
|
|
219
|
+
kept: PolicyRef[];
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Drop the policies an earlier push superseded but never removed.
|
|
224
|
+
*
|
|
225
|
+
* Only touches tables the collections describe — a table with no expected
|
|
226
|
+
* policy is not ours to reconcile, and scanning by schema alone would sweep up
|
|
227
|
+
* policies belonging to something else sharing the database.
|
|
228
|
+
*/
|
|
229
|
+
export async function dropOrphanedPolicies(
|
|
230
|
+
client: Queryable,
|
|
231
|
+
drift: PolicyDrift,
|
|
232
|
+
collections: CollectionConfig[]
|
|
233
|
+
): Promise<OrphanCleanup> {
|
|
234
|
+
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(collections));
|
|
235
|
+
const managed = new Set(expected.map((p) => `${p.schema}.${p.table}`));
|
|
236
|
+
|
|
237
|
+
const cleanup: OrphanCleanup = { dropped: [], kept: [] };
|
|
238
|
+
for (const p of drift.orphaned) {
|
|
239
|
+
if (!managed.has(`${p.schema}.${p.table}`) || !isGeneratedPolicyName(p.name, p.table)) {
|
|
240
|
+
cleanup.kept.push(p);
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
// Identifiers are quoted, and the name came from pg_policies rather than
|
|
244
|
+
// from user input, so it is already a valid identifier.
|
|
245
|
+
await client.query(`DROP POLICY IF EXISTS "${p.name}" ON "${p.schema}"."${p.table}"`);
|
|
246
|
+
cleanup.dropped.push(p);
|
|
247
|
+
}
|
|
248
|
+
return cleanup;
|
|
249
|
+
}
|
|
250
|
+
|
|
195
251
|
export const hasDrift = (d: PolicyDrift): boolean =>
|
|
196
252
|
d.missing.length > 0 || d.orphaned.length > 0 || d.diverged.length > 0;
|
|
197
253
|
|
|
@@ -59,7 +59,7 @@ export interface ConnectionPosture {
|
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
export interface AuthContext {
|
|
62
|
-
|
|
62
|
+
uid: string;
|
|
63
63
|
/** Raw roles as carried on the user (strings or `{ id }` objects). */
|
|
64
64
|
roles: unknown[];
|
|
65
65
|
}
|
|
@@ -208,15 +208,15 @@ export async function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promi
|
|
|
208
208
|
* semantics: it is why `auth.uid() IS NOT NULL` is true for anonymous requests.
|
|
209
209
|
*/
|
|
210
210
|
export async function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string): Promise<void> {
|
|
211
|
-
const
|
|
211
|
+
const uid = typeof auth.uid === "string" && auth.uid.trim() !== "" ? auth.uid : ANONYMOUS_USER_ID;
|
|
212
212
|
const normalizedRoles = auth.roles.map((r: unknown) =>
|
|
213
213
|
typeof r === "string" ? r : (r as Record<string, unknown>)?.id ?? String(r)
|
|
214
214
|
);
|
|
215
215
|
await tx.execute(drizzleSql`
|
|
216
216
|
SELECT
|
|
217
|
-
set_config('app.user_id', ${
|
|
217
|
+
set_config('app.user_id', ${uid}, true),
|
|
218
218
|
set_config('app.user_roles', ${normalizedRoles.join(",")}, true),
|
|
219
|
-
set_config('app.jwt', ${JSON.stringify({ sub:
|
|
219
|
+
set_config('app.jwt', ${JSON.stringify({ sub: uid, roles: auth.roles })}, true)
|
|
220
220
|
`);
|
|
221
221
|
if (userRole) {
|
|
222
222
|
await tx.execute(drizzleSql.raw(`SET LOCAL ROLE ${quoteIdent(userRole)}`));
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ordered, replayable per-channel message history.
|
|
3
|
+
*
|
|
4
|
+
* Broadcast on its own is fire-and-forget to whoever is connected at the
|
|
5
|
+
* instant it is sent: fine for presence and for "someone saved" notifications,
|
|
6
|
+
* not enough for op-based collaborative editing, where a client that blinks
|
|
7
|
+
* out for two seconds has to resync a whole document rather than catch up on
|
|
8
|
+
* the four operations it missed. This adds the missing half — every retained
|
|
9
|
+
* broadcast gets a per-channel sequence number, and a client can ask for
|
|
10
|
+
* everything after the last one it saw.
|
|
11
|
+
*
|
|
12
|
+
* Three decisions worth stating, because each rules out a simpler-looking one:
|
|
13
|
+
*
|
|
14
|
+
* - **Retention is server-side and opt-in.** A channel is created by whoever
|
|
15
|
+
* names it, so a client-supplied history depth would let any visitor commit
|
|
16
|
+
* the backend to unbounded storage. And presence channels — the common case
|
|
17
|
+
* — must not pay for this: with no rules configured nothing is written, no
|
|
18
|
+
* table is created, and `broadcast` runs exactly the code it ran before.
|
|
19
|
+
*
|
|
20
|
+
* - **Sequence numbers come from the database, not from a counter in this
|
|
21
|
+
* process.** They have to survive a restart and be shared across instances;
|
|
22
|
+
* an in-memory counter would restart at 1 after a deploy and hand a
|
|
23
|
+
* reconnecting client a replay from the wrong era, silently.
|
|
24
|
+
*
|
|
25
|
+
* - **The cursor row outlives the messages it numbered.** Pruning is what
|
|
26
|
+
* makes retention affordable, but pruning the cursor along with the messages
|
|
27
|
+
* would restart the sequence and make `sinceSeq` mean something different
|
|
28
|
+
* before and after — the worst kind of bug, because replay would still
|
|
29
|
+
* return rows and they would look plausible. Cursors are tiny and are kept
|
|
30
|
+
* forever; see {@link prune}, which touches only `channel_messages`.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import { sql } from "drizzle-orm";
|
|
34
|
+
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
35
|
+
import type { ChannelHistoryEntry, ChannelRetentionRule } from "@rebasepro/types";
|
|
36
|
+
import { logger } from "@rebasepro/server";
|
|
37
|
+
|
|
38
|
+
/** How many messages a replay returns when the caller does not say. */
|
|
39
|
+
const DEFAULT_REPLAY_LIMIT = 200;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Hard ceiling on one replay, whatever the caller asks for.
|
|
43
|
+
*
|
|
44
|
+
* A reconnecting client names its own `limit`, so this is the only thing
|
|
45
|
+
* standing between a stale `sinceSeq` and a single frame carrying a channel's
|
|
46
|
+
* entire retained history. A client that is further behind than this is told so
|
|
47
|
+
* via `latestSeq` and can decide to resync wholesale instead of paging.
|
|
48
|
+
*/
|
|
49
|
+
const MAX_REPLAY_LIMIT = 1000;
|
|
50
|
+
|
|
51
|
+
/** Minimum gap between two prunes of the same channel. */
|
|
52
|
+
const PRUNE_THROTTLE_MS = 30_000;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Parse a retention TTL into milliseconds.
|
|
56
|
+
*
|
|
57
|
+
* Accepts a raw millisecond count or a short duration string (`"30s"`, `"15m"`,
|
|
58
|
+
* `"24h"`, `"7d"`). Returns undefined for anything unparseable, which the
|
|
59
|
+
* caller treats as "no TTL" — a misspelt duration must not silently become an
|
|
60
|
+
* aggressive one.
|
|
61
|
+
*/
|
|
62
|
+
export function parseTtlMs(ttl: number | string | undefined): number | undefined {
|
|
63
|
+
if (ttl === undefined || ttl === null) return undefined;
|
|
64
|
+
if (typeof ttl === "number") return Number.isFinite(ttl) && ttl > 0 ? ttl : undefined;
|
|
65
|
+
|
|
66
|
+
const match = /^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.exec(ttl);
|
|
67
|
+
if (!match) {
|
|
68
|
+
logger.warn(`⚠️ [ChannelHistory] Ignoring unparseable retention ttl "${ttl}" — expected e.g. "30s", "15m", "24h", "7d".`);
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
const value = parseFloat(match[1]);
|
|
72
|
+
const unit = match[2].toLowerCase();
|
|
73
|
+
const multiplier = unit === "ms" ? 1
|
|
74
|
+
: unit === "s" ? 1_000
|
|
75
|
+
: unit === "m" ? 60_000
|
|
76
|
+
: unit === "h" ? 3_600_000
|
|
77
|
+
: 86_400_000;
|
|
78
|
+
const ms = value * multiplier;
|
|
79
|
+
return ms > 0 ? ms : undefined;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Whether `channel` is covered by `rule`.
|
|
84
|
+
*
|
|
85
|
+
* Exact match, or a trailing `*` acting as a prefix. Not a general glob: this
|
|
86
|
+
* decides what reaches disk, and a pattern language whose reach is not obvious
|
|
87
|
+
* at a glance is the wrong tool for that job.
|
|
88
|
+
*/
|
|
89
|
+
export function channelMatchesRule(channel: string, rule: ChannelRetentionRule): boolean {
|
|
90
|
+
const pattern = rule.match;
|
|
91
|
+
if (pattern === "*") return true;
|
|
92
|
+
if (pattern.endsWith("*")) return channel.startsWith(pattern.slice(0, -1));
|
|
93
|
+
return channel === pattern;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** A rule with its TTL already resolved to milliseconds. */
|
|
97
|
+
export interface ResolvedRetention {
|
|
98
|
+
limit?: number;
|
|
99
|
+
ttlMs?: number;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Persistence and replay for retained channels.
|
|
104
|
+
*
|
|
105
|
+
* Inert unless constructed with at least one rule: {@link enabled} is false,
|
|
106
|
+
* {@link ensureTables} does nothing, and {@link retentionFor} answers undefined
|
|
107
|
+
* for every channel, so the realtime service never reaches the SQL below.
|
|
108
|
+
*/
|
|
109
|
+
export class ChannelHistoryStore {
|
|
110
|
+
private rules: ChannelRetentionRule[];
|
|
111
|
+
/** Resolved rule per channel name, so the match runs once per channel. */
|
|
112
|
+
private resolved = new Map<string, ResolvedRetention | null>();
|
|
113
|
+
/** Channel → timestamp of its last prune, for {@link PRUNE_THROTTLE_MS}. */
|
|
114
|
+
private lastPruned = new Map<string, number>();
|
|
115
|
+
private tablesReady = false;
|
|
116
|
+
|
|
117
|
+
constructor(private db: NodePgDatabase<Record<string, unknown>>, rules: ChannelRetentionRule[] = []) {
|
|
118
|
+
this.rules = rules.filter(rule => {
|
|
119
|
+
if (!rule?.match) {
|
|
120
|
+
logger.warn("⚠️ [ChannelHistory] Ignoring a retention rule with no `match`.");
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
const hasBound = rule.limit !== undefined || rule.ttl !== undefined;
|
|
124
|
+
if (!hasBound) {
|
|
125
|
+
// Unbounded retention is almost never intended and cannot be
|
|
126
|
+
// walked back once the table has grown, so it is refused rather
|
|
127
|
+
// than honoured.
|
|
128
|
+
logger.warn(`⚠️ [ChannelHistory] Retention rule "${rule.match}" sets neither \`limit\` nor \`ttl\` — ignoring it, as it would retain forever.`);
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
return true;
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Whether any channel retains anything at all. */
|
|
136
|
+
get enabled(): boolean {
|
|
137
|
+
return this.rules.length > 0;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The retention that applies to `channel`, or undefined when none does.
|
|
142
|
+
*
|
|
143
|
+
* First matching rule wins, so callers order them most-specific first.
|
|
144
|
+
*/
|
|
145
|
+
retentionFor(channel: string): ResolvedRetention | undefined {
|
|
146
|
+
if (!this.enabled || !channel) return undefined;
|
|
147
|
+
|
|
148
|
+
const cached = this.resolved.get(channel);
|
|
149
|
+
if (cached !== undefined) return cached ?? undefined;
|
|
150
|
+
|
|
151
|
+
const rule = this.rules.find(r => channelMatchesRule(channel, r));
|
|
152
|
+
const resolved: ResolvedRetention | null = rule
|
|
153
|
+
? { limit: rule.limit, ttlMs: parseTtlMs(rule.ttl) }
|
|
154
|
+
: null;
|
|
155
|
+
|
|
156
|
+
// Bounded by the number of distinct channel names seen, which is the
|
|
157
|
+
// same thing the in-memory channel and presence maps are bounded by.
|
|
158
|
+
this.resolved.set(channel, resolved);
|
|
159
|
+
return resolved ?? undefined;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Create the history tables. Idempotent, and a no-op when no rule is set —
|
|
164
|
+
* a deployment that never retains anything gets no schema for it.
|
|
165
|
+
*/
|
|
166
|
+
async ensureTables(): Promise<void> {
|
|
167
|
+
if (!this.enabled || this.tablesReady) return;
|
|
168
|
+
|
|
169
|
+
await this.db.execute(sql`CREATE SCHEMA IF NOT EXISTS rebase`);
|
|
170
|
+
|
|
171
|
+
// The primary key is exactly the replay query's access path
|
|
172
|
+
// (`channel = $1 AND seq > $2 ORDER BY seq`), so it needs no further
|
|
173
|
+
// index of its own.
|
|
174
|
+
await this.db.execute(sql`
|
|
175
|
+
CREATE TABLE IF NOT EXISTS rebase.channel_messages (
|
|
176
|
+
channel TEXT NOT NULL,
|
|
177
|
+
seq BIGINT NOT NULL,
|
|
178
|
+
event TEXT NOT NULL,
|
|
179
|
+
payload JSONB,
|
|
180
|
+
sender_id TEXT,
|
|
181
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
182
|
+
PRIMARY KEY (channel, seq)
|
|
183
|
+
)
|
|
184
|
+
`);
|
|
185
|
+
|
|
186
|
+
// Only for the TTL arm of pruning; the limit arm rides the primary key.
|
|
187
|
+
await this.db.execute(sql`
|
|
188
|
+
CREATE INDEX IF NOT EXISTS idx_channel_messages_created
|
|
189
|
+
ON rebase.channel_messages (created_at)
|
|
190
|
+
`);
|
|
191
|
+
|
|
192
|
+
// Never pruned — see the note at the top of this file. One row per
|
|
193
|
+
// channel that has ever retained a message.
|
|
194
|
+
await this.db.execute(sql`
|
|
195
|
+
CREATE TABLE IF NOT EXISTS rebase.channel_cursors (
|
|
196
|
+
channel TEXT PRIMARY KEY,
|
|
197
|
+
last_seq BIGINT NOT NULL
|
|
198
|
+
)
|
|
199
|
+
`);
|
|
200
|
+
|
|
201
|
+
this.tablesReady = true;
|
|
202
|
+
logger.info(`✅ [ChannelHistory] Retained channels ready (${this.rules.length} rule(s)).`);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Append a broadcast and return the sequence number it was given.
|
|
207
|
+
*
|
|
208
|
+
* The sequence is allocated by the same statement that stores the message,
|
|
209
|
+
* so a crash between the two is not a possibility. `ON CONFLICT DO UPDATE`
|
|
210
|
+
* takes a row lock on the channel's cursor, which is what makes concurrent
|
|
211
|
+
* broadcasts to one channel line up in a single order — and what keeps
|
|
212
|
+
* different channels from contending with each other at all.
|
|
213
|
+
*/
|
|
214
|
+
async append(
|
|
215
|
+
channel: string,
|
|
216
|
+
event: string,
|
|
217
|
+
payload: unknown,
|
|
218
|
+
senderId?: string
|
|
219
|
+
): Promise<{ seq: number; at: string }> {
|
|
220
|
+
const result = await this.db.execute(sql`
|
|
221
|
+
WITH next AS (
|
|
222
|
+
INSERT INTO rebase.channel_cursors (channel, last_seq)
|
|
223
|
+
VALUES (${channel}, 1)
|
|
224
|
+
ON CONFLICT (channel)
|
|
225
|
+
DO UPDATE SET last_seq = rebase.channel_cursors.last_seq + 1
|
|
226
|
+
RETURNING last_seq
|
|
227
|
+
)
|
|
228
|
+
INSERT INTO rebase.channel_messages (channel, seq, event, payload, sender_id)
|
|
229
|
+
SELECT ${channel}, next.last_seq, ${event}, ${JSON.stringify(payload ?? null)}::jsonb, ${senderId ?? null}
|
|
230
|
+
FROM next
|
|
231
|
+
RETURNING seq, created_at
|
|
232
|
+
`);
|
|
233
|
+
|
|
234
|
+
const row = result.rows[0] as { seq: string | number; created_at: Date | string } | undefined;
|
|
235
|
+
if (!row) throw new Error(`Failed to append to channel history for "${channel}"`);
|
|
236
|
+
|
|
237
|
+
return {
|
|
238
|
+
// BIGINT comes back as a string from node-postgres; the wire type is
|
|
239
|
+
// a number, and a channel would need 2^53 messages to notice.
|
|
240
|
+
seq: Number(row.seq),
|
|
241
|
+
at: row.created_at instanceof Date ? row.created_at.toISOString() : String(row.created_at)
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Everything retained for `channel` after `sinceSeq`, oldest first.
|
|
247
|
+
*
|
|
248
|
+
* `latestSeq` is reported whether or not the messages were capped, so a
|
|
249
|
+
* client that is further behind than one page can tell.
|
|
250
|
+
*/
|
|
251
|
+
async replay(
|
|
252
|
+
channel: string,
|
|
253
|
+
sinceSeq = 0,
|
|
254
|
+
limit = DEFAULT_REPLAY_LIMIT
|
|
255
|
+
): Promise<{ messages: ChannelHistoryEntry[]; latestSeq: number }> {
|
|
256
|
+
const capped = Math.max(1, Math.min(Math.floor(limit) || DEFAULT_REPLAY_LIMIT, MAX_REPLAY_LIMIT));
|
|
257
|
+
const after = Number.isFinite(sinceSeq) && sinceSeq > 0 ? Math.floor(sinceSeq) : 0;
|
|
258
|
+
|
|
259
|
+
const result = await this.db.execute(sql`
|
|
260
|
+
SELECT seq, event, payload, sender_id, created_at
|
|
261
|
+
FROM rebase.channel_messages
|
|
262
|
+
WHERE channel = ${channel} AND seq > ${after}
|
|
263
|
+
ORDER BY seq ASC
|
|
264
|
+
LIMIT ${capped}
|
|
265
|
+
`);
|
|
266
|
+
|
|
267
|
+
const messages = (result.rows as Array<{
|
|
268
|
+
seq: string | number;
|
|
269
|
+
event: string;
|
|
270
|
+
payload: unknown;
|
|
271
|
+
sender_id: string | null;
|
|
272
|
+
created_at: Date | string;
|
|
273
|
+
}>).map(row => ({
|
|
274
|
+
seq: Number(row.seq),
|
|
275
|
+
event: row.event,
|
|
276
|
+
payload: row.payload,
|
|
277
|
+
senderId: row.sender_id ?? undefined,
|
|
278
|
+
at: row.created_at instanceof Date ? row.created_at.toISOString() : String(row.created_at)
|
|
279
|
+
}));
|
|
280
|
+
|
|
281
|
+
// Read from the cursor rather than from the messages: the cursor is the
|
|
282
|
+
// authority on how far the channel has got, and still says so after
|
|
283
|
+
// pruning has removed the messages it counted.
|
|
284
|
+
const cursor = await this.db.execute(sql`
|
|
285
|
+
SELECT last_seq FROM rebase.channel_cursors WHERE channel = ${channel}
|
|
286
|
+
`);
|
|
287
|
+
const cursorRow = cursor.rows[0] as { last_seq: string | number } | undefined;
|
|
288
|
+
const latestSeq = cursorRow ? Number(cursorRow.last_seq) : 0;
|
|
289
|
+
|
|
290
|
+
return { messages, latestSeq };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Enforce a channel's retention bounds.
|
|
295
|
+
*
|
|
296
|
+
* Throttled per channel, so a burst of operations prunes once rather than
|
|
297
|
+
* once per message — the cost then tracks elapsed time instead of write
|
|
298
|
+
* volume, which is what makes retention affordable on a hot channel.
|
|
299
|
+
*/
|
|
300
|
+
async prune(channel: string, retention: ResolvedRetention): Promise<number> {
|
|
301
|
+
const now = Date.now();
|
|
302
|
+
const last = this.lastPruned.get(channel) ?? 0;
|
|
303
|
+
if (now - last < PRUNE_THROTTLE_MS) return 0;
|
|
304
|
+
this.lastPruned.set(channel, now);
|
|
305
|
+
|
|
306
|
+
let deleted = 0;
|
|
307
|
+
|
|
308
|
+
if (retention.ttlMs !== undefined) {
|
|
309
|
+
const result = await this.db.execute(sql`
|
|
310
|
+
DELETE FROM rebase.channel_messages
|
|
311
|
+
WHERE channel = ${channel}
|
|
312
|
+
AND created_at < NOW() - MAKE_INTERVAL(secs => ${retention.ttlMs / 1000})
|
|
313
|
+
`);
|
|
314
|
+
deleted += result.rowCount ?? 0;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (retention.limit !== undefined && retention.limit > 0) {
|
|
318
|
+
// OFFSET past the newest `limit` rows to find the highest seq that
|
|
319
|
+
// is no longer wanted, then delete everything at or below it. Fewer
|
|
320
|
+
// rows than the limit leaves the subquery empty, and the comparison
|
|
321
|
+
// with NULL deletes nothing.
|
|
322
|
+
const result = await this.db.execute(sql`
|
|
323
|
+
DELETE FROM rebase.channel_messages
|
|
324
|
+
WHERE channel = ${channel}
|
|
325
|
+
AND seq <= (
|
|
326
|
+
SELECT seq FROM rebase.channel_messages
|
|
327
|
+
WHERE channel = ${channel}
|
|
328
|
+
ORDER BY seq DESC
|
|
329
|
+
OFFSET ${Math.floor(retention.limit)} LIMIT 1
|
|
330
|
+
)
|
|
331
|
+
`);
|
|
332
|
+
deleted += result.rowCount ?? 0;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return deleted;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Forget throttle and match caches. Called on shutdown. */
|
|
339
|
+
clear(): void {
|
|
340
|
+
this.resolved.clear();
|
|
341
|
+
this.lastPruned.clear();
|
|
342
|
+
}
|
|
343
|
+
}
|