@rebasepro/server-postgres 0.9.1-canary.09aaf62 → 0.9.1-canary.0de22e0

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/index.es.js CHANGED
@@ -8190,14 +8190,14 @@ async function ensureAppRole(run, schemas) {
8190
8190
  * semantics: it is why `auth.uid() IS NOT NULL` is true for anonymous requests.
8191
8191
  */
8192
8192
  async function applyAuthContext(tx, auth, userRole) {
8193
- const userId = typeof auth.userId === "string" && auth.userId.trim() !== "" ? auth.userId : ANONYMOUS_USER_ID;
8193
+ const uid = typeof auth.uid === "string" && auth.uid.trim() !== "" ? auth.uid : ANONYMOUS_USER_ID;
8194
8194
  const normalizedRoles = auth.roles.map((r) => typeof r === "string" ? r : r?.id ?? String(r));
8195
8195
  await tx.execute(sql`
8196
8196
  SELECT
8197
- set_config('app.user_id', ${userId}, true),
8197
+ set_config('app.user_id', ${uid}, true),
8198
8198
  set_config('app.user_roles', ${normalizedRoles.join(",")}, true),
8199
8199
  set_config('app.jwt', ${JSON.stringify({
8200
- sub: userId,
8200
+ sub: uid,
8201
8201
  roles: auth.roles
8202
8202
  })}, true)
8203
8203
  `);
@@ -8343,6 +8343,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
8343
8343
  executeSql: (...args) => this.executeSql(...args),
8344
8344
  fetchAvailableDatabases: () => this.fetchAvailableDatabases(),
8345
8345
  fetchAvailableRoles: () => this.fetchAvailableRoles(),
8346
+ fetchApplicationRoles: () => this.fetchApplicationRoles(),
8346
8347
  fetchCurrentDatabase: () => this.fetchCurrentDatabase(),
8347
8348
  fetchUnmappedTables: (...args) => this.fetchUnmappedTables(...args),
8348
8349
  fetchTableMetadata: (...args) => this.fetchTableMetadata(...args),
@@ -8996,6 +8997,45 @@ var PostgresBackendDriver = class PostgresBackendDriver {
8996
8997
  async fetchAvailableRoles() {
8997
8998
  return (await this.executeSql("SELECT rolname FROM pg_roles WHERE pg_has_role(current_user, rolname, 'member') ORDER BY rolname;")).map((r) => r.rolname);
8998
8999
  }
9000
+ /**
9001
+ * Application-level roles actually in use in this project.
9002
+ *
9003
+ * Distinct from {@link fetchAvailableRoles}, which returns native
9004
+ * PostgreSQL roles from `pg_roles` (`postgres`, `rebase_user`, …). Those
9005
+ * are the roles the SQL editor can `SET ROLE` to. *These* are the strings
9006
+ * held in the users table's `roles` column, injected per-transaction as
9007
+ * `auth.roles()` and matched by `SecurityRule.roles`. Feeding the pg roles
9008
+ * into a `SecurityRule.roles` field produces a condition no user can ever
9009
+ * satisfy, so the two must not be conflated.
9010
+ *
9011
+ * Roles have no registry table — they were migrated out of
9012
+ * `rebase.user_roles` onto an inline `roles TEXT[]` column — so the live
9013
+ * set is derived from what is assigned. A role that is declared in a policy
9014
+ * but held by nobody yet cannot be discovered here; callers that need it
9015
+ * should union in the roles they already know about.
9016
+ */
9017
+ async fetchApplicationRoles() {
9018
+ const located = await this.executeSql(`
9019
+ SELECT table_schema, table_name
9020
+ FROM information_schema.columns
9021
+ WHERE column_name = 'roles'
9022
+ AND data_type = 'ARRAY'
9023
+ AND table_name = 'users'
9024
+ AND table_schema NOT IN ('information_schema', 'pg_catalog')
9025
+ ORDER BY (table_schema = 'rebase') DESC, table_schema
9026
+ LIMIT 1;
9027
+ `);
9028
+ if (located.length === 0) return [];
9029
+ const schema = located[0].table_schema;
9030
+ const table = located[0].table_name;
9031
+ const qualified = `"${schema.replace(/"/g, "\"\"")}"."${table.replace(/"/g, "\"\"")}"`;
9032
+ return (await this.executeSql(`
9033
+ SELECT DISTINCT unnest(roles) AS role
9034
+ FROM ${qualified}
9035
+ WHERE roles IS NOT NULL
9036
+ ORDER BY role;
9037
+ `)).map((r) => r.role).filter((r) => typeof r === "string" && r.length > 0);
9038
+ }
8999
9039
  async fetchCurrentDatabase() {
9000
9040
  return this.poolManager?.defaultDatabaseName;
9001
9041
  }
@@ -9137,15 +9177,15 @@ var AuthenticatedPostgresBackendDriver = class {
9137
9177
  async withTransaction(operation, options) {
9138
9178
  const pendingNotifications = [];
9139
9179
  const result = await this.delegate.db.transaction(async (tx) => {
9140
- let userId = this.user?.uid;
9141
- if (!userId) {
9180
+ let uid = this.user?.uid;
9181
+ if (!uid) {
9142
9182
  logger.warn("[DataDriver] User ID (uid) is missing for authenticated delegate. Using 'anonymous'. User object", { detail: this.user });
9143
- userId = "anonymous";
9183
+ uid = "anonymous";
9144
9184
  }
9145
9185
  const userRoles = this.user?.roles ?? [];
9146
9186
  if (!this.user?.roles) logger.warn("[DataDriver] User roles are missing for authenticated delegate. Using empty array. User object", { detail: this.user });
9147
9187
  await applyAuthContext(tx, {
9148
- userId,
9188
+ uid,
9149
9189
  roles: userRoles
9150
9190
  }, this.delegate.rlsUserRole);
9151
9191
  const txEntityService = new DataService(tx, this.delegate.registry);
@@ -9172,7 +9212,7 @@ var AuthenticatedPostgresBackendDriver = class {
9172
9212
  */
9173
9213
  injectAuthContext(unsubscribe) {
9174
9214
  const authContext = {
9175
- userId: this.user?.uid || "anonymous",
9215
+ uid: this.user?.uid || "anonymous",
9176
9216
  roles: this.user?.roles ?? []
9177
9217
  };
9178
9218
  const entries = Array.from(this.delegate.realtimeService.subscriptions.entries());
@@ -10280,6 +10320,267 @@ var CdcListener = class CdcListener {
10280
10320
  }
10281
10321
  };
10282
10322
  //#endregion
10323
+ //#region src/services/channel-history.ts
10324
+ /**
10325
+ * Ordered, replayable per-channel message history.
10326
+ *
10327
+ * Broadcast on its own is fire-and-forget to whoever is connected at the
10328
+ * instant it is sent: fine for presence and for "someone saved" notifications,
10329
+ * not enough for op-based collaborative editing, where a client that blinks
10330
+ * out for two seconds has to resync a whole document rather than catch up on
10331
+ * the four operations it missed. This adds the missing half — every retained
10332
+ * broadcast gets a per-channel sequence number, and a client can ask for
10333
+ * everything after the last one it saw.
10334
+ *
10335
+ * Three decisions worth stating, because each rules out a simpler-looking one:
10336
+ *
10337
+ * - **Retention is server-side and opt-in.** A channel is created by whoever
10338
+ * names it, so a client-supplied history depth would let any visitor commit
10339
+ * the backend to unbounded storage. And presence channels — the common case
10340
+ * — must not pay for this: with no rules configured nothing is written, no
10341
+ * table is created, and `broadcast` runs exactly the code it ran before.
10342
+ *
10343
+ * - **Sequence numbers come from the database, not from a counter in this
10344
+ * process.** They have to survive a restart and be shared across instances;
10345
+ * an in-memory counter would restart at 1 after a deploy and hand a
10346
+ * reconnecting client a replay from the wrong era, silently.
10347
+ *
10348
+ * - **The cursor row outlives the messages it numbered.** Pruning is what
10349
+ * makes retention affordable, but pruning the cursor along with the messages
10350
+ * would restart the sequence and make `sinceSeq` mean something different
10351
+ * before and after — the worst kind of bug, because replay would still
10352
+ * return rows and they would look plausible. Cursors are tiny and are kept
10353
+ * forever; see {@link prune}, which touches only `channel_messages`.
10354
+ */
10355
+ /** How many messages a replay returns when the caller does not say. */
10356
+ var DEFAULT_REPLAY_LIMIT = 200;
10357
+ /**
10358
+ * Hard ceiling on one replay, whatever the caller asks for.
10359
+ *
10360
+ * A reconnecting client names its own `limit`, so this is the only thing
10361
+ * standing between a stale `sinceSeq` and a single frame carrying a channel's
10362
+ * entire retained history. A client that is further behind than this is told so
10363
+ * via `latestSeq` and can decide to resync wholesale instead of paging.
10364
+ */
10365
+ var MAX_REPLAY_LIMIT = 1e3;
10366
+ /** Minimum gap between two prunes of the same channel. */
10367
+ var PRUNE_THROTTLE_MS = 3e4;
10368
+ /**
10369
+ * Parse a retention TTL into milliseconds.
10370
+ *
10371
+ * Accepts a raw millisecond count or a short duration string (`"30s"`, `"15m"`,
10372
+ * `"24h"`, `"7d"`). Returns undefined for anything unparseable, which the
10373
+ * caller treats as "no TTL" — a misspelt duration must not silently become an
10374
+ * aggressive one.
10375
+ */
10376
+ function parseTtlMs(ttl) {
10377
+ if (ttl === void 0 || ttl === null) return void 0;
10378
+ if (typeof ttl === "number") return Number.isFinite(ttl) && ttl > 0 ? ttl : void 0;
10379
+ const match = /^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.exec(ttl);
10380
+ if (!match) {
10381
+ logger.warn(`⚠️ [ChannelHistory] Ignoring unparseable retention ttl "${ttl}" — expected e.g. "30s", "15m", "24h", "7d".`);
10382
+ return;
10383
+ }
10384
+ const value = parseFloat(match[1]);
10385
+ const unit = match[2].toLowerCase();
10386
+ const ms = value * (unit === "ms" ? 1 : unit === "s" ? 1e3 : unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5);
10387
+ return ms > 0 ? ms : void 0;
10388
+ }
10389
+ /**
10390
+ * Whether `channel` is covered by `rule`.
10391
+ *
10392
+ * Exact match, or a trailing `*` acting as a prefix. Not a general glob: this
10393
+ * decides what reaches disk, and a pattern language whose reach is not obvious
10394
+ * at a glance is the wrong tool for that job.
10395
+ */
10396
+ function channelMatchesRule(channel, rule) {
10397
+ const pattern = rule.match;
10398
+ if (pattern === "*") return true;
10399
+ if (pattern.endsWith("*")) return channel.startsWith(pattern.slice(0, -1));
10400
+ return channel === pattern;
10401
+ }
10402
+ /**
10403
+ * Persistence and replay for retained channels.
10404
+ *
10405
+ * Inert unless constructed with at least one rule: {@link enabled} is false,
10406
+ * {@link ensureTables} does nothing, and {@link retentionFor} answers undefined
10407
+ * for every channel, so the realtime service never reaches the SQL below.
10408
+ */
10409
+ var ChannelHistoryStore = class {
10410
+ db;
10411
+ rules;
10412
+ /** Resolved rule per channel name, so the match runs once per channel. */
10413
+ resolved = /* @__PURE__ */ new Map();
10414
+ /** Channel → timestamp of its last prune, for {@link PRUNE_THROTTLE_MS}. */
10415
+ lastPruned = /* @__PURE__ */ new Map();
10416
+ tablesReady = false;
10417
+ constructor(db, rules = []) {
10418
+ this.db = db;
10419
+ this.rules = rules.filter((rule) => {
10420
+ if (!rule?.match) {
10421
+ logger.warn("⚠️ [ChannelHistory] Ignoring a retention rule with no `match`.");
10422
+ return false;
10423
+ }
10424
+ if (!(rule.limit !== void 0 || rule.ttl !== void 0)) {
10425
+ logger.warn(`⚠️ [ChannelHistory] Retention rule "${rule.match}" sets neither \`limit\` nor \`ttl\` — ignoring it, as it would retain forever.`);
10426
+ return false;
10427
+ }
10428
+ return true;
10429
+ });
10430
+ }
10431
+ /** Whether any channel retains anything at all. */
10432
+ get enabled() {
10433
+ return this.rules.length > 0;
10434
+ }
10435
+ /**
10436
+ * The retention that applies to `channel`, or undefined when none does.
10437
+ *
10438
+ * First matching rule wins, so callers order them most-specific first.
10439
+ */
10440
+ retentionFor(channel) {
10441
+ if (!this.enabled || !channel) return void 0;
10442
+ const cached = this.resolved.get(channel);
10443
+ if (cached !== void 0) return cached ?? void 0;
10444
+ const rule = this.rules.find((r) => channelMatchesRule(channel, r));
10445
+ const resolved = rule ? {
10446
+ limit: rule.limit,
10447
+ ttlMs: parseTtlMs(rule.ttl)
10448
+ } : null;
10449
+ this.resolved.set(channel, resolved);
10450
+ return resolved ?? void 0;
10451
+ }
10452
+ /**
10453
+ * Create the history tables. Idempotent, and a no-op when no rule is set —
10454
+ * a deployment that never retains anything gets no schema for it.
10455
+ */
10456
+ async ensureTables() {
10457
+ if (!this.enabled || this.tablesReady) return;
10458
+ await this.db.execute(sql`CREATE SCHEMA IF NOT EXISTS rebase`);
10459
+ await this.db.execute(sql`
10460
+ CREATE TABLE IF NOT EXISTS rebase.channel_messages (
10461
+ channel TEXT NOT NULL,
10462
+ seq BIGINT NOT NULL,
10463
+ event TEXT NOT NULL,
10464
+ payload JSONB,
10465
+ sender_id TEXT,
10466
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
10467
+ PRIMARY KEY (channel, seq)
10468
+ )
10469
+ `);
10470
+ await this.db.execute(sql`
10471
+ CREATE INDEX IF NOT EXISTS idx_channel_messages_created
10472
+ ON rebase.channel_messages (created_at)
10473
+ `);
10474
+ await this.db.execute(sql`
10475
+ CREATE TABLE IF NOT EXISTS rebase.channel_cursors (
10476
+ channel TEXT PRIMARY KEY,
10477
+ last_seq BIGINT NOT NULL
10478
+ )
10479
+ `);
10480
+ this.tablesReady = true;
10481
+ logger.info(`✅ [ChannelHistory] Retained channels ready (${this.rules.length} rule(s)).`);
10482
+ }
10483
+ /**
10484
+ * Append a broadcast and return the sequence number it was given.
10485
+ *
10486
+ * The sequence is allocated by the same statement that stores the message,
10487
+ * so a crash between the two is not a possibility. `ON CONFLICT DO UPDATE`
10488
+ * takes a row lock on the channel's cursor, which is what makes concurrent
10489
+ * broadcasts to one channel line up in a single order — and what keeps
10490
+ * different channels from contending with each other at all.
10491
+ */
10492
+ async append(channel, event, payload, senderId) {
10493
+ const row = (await this.db.execute(sql`
10494
+ WITH next AS (
10495
+ INSERT INTO rebase.channel_cursors (channel, last_seq)
10496
+ VALUES (${channel}, 1)
10497
+ ON CONFLICT (channel)
10498
+ DO UPDATE SET last_seq = rebase.channel_cursors.last_seq + 1
10499
+ RETURNING last_seq
10500
+ )
10501
+ INSERT INTO rebase.channel_messages (channel, seq, event, payload, sender_id)
10502
+ SELECT ${channel}, next.last_seq, ${event}, ${JSON.stringify(payload ?? null)}::jsonb, ${senderId ?? null}
10503
+ FROM next
10504
+ RETURNING seq, created_at
10505
+ `)).rows[0];
10506
+ if (!row) throw new Error(`Failed to append to channel history for "${channel}"`);
10507
+ return {
10508
+ seq: Number(row.seq),
10509
+ at: row.created_at instanceof Date ? row.created_at.toISOString() : String(row.created_at)
10510
+ };
10511
+ }
10512
+ /**
10513
+ * Everything retained for `channel` after `sinceSeq`, oldest first.
10514
+ *
10515
+ * `latestSeq` is reported whether or not the messages were capped, so a
10516
+ * client that is further behind than one page can tell.
10517
+ */
10518
+ async replay(channel, sinceSeq = 0, limit = DEFAULT_REPLAY_LIMIT) {
10519
+ const capped = Math.max(1, Math.min(Math.floor(limit) || DEFAULT_REPLAY_LIMIT, MAX_REPLAY_LIMIT));
10520
+ const after = Number.isFinite(sinceSeq) && sinceSeq > 0 ? Math.floor(sinceSeq) : 0;
10521
+ const messages = (await this.db.execute(sql`
10522
+ SELECT seq, event, payload, sender_id, created_at
10523
+ FROM rebase.channel_messages
10524
+ WHERE channel = ${channel} AND seq > ${after}
10525
+ ORDER BY seq ASC
10526
+ LIMIT ${capped}
10527
+ `)).rows.map((row) => ({
10528
+ seq: Number(row.seq),
10529
+ event: row.event,
10530
+ payload: row.payload,
10531
+ senderId: row.sender_id ?? void 0,
10532
+ at: row.created_at instanceof Date ? row.created_at.toISOString() : String(row.created_at)
10533
+ }));
10534
+ const cursorRow = (await this.db.execute(sql`
10535
+ SELECT last_seq FROM rebase.channel_cursors WHERE channel = ${channel}
10536
+ `)).rows[0];
10537
+ return {
10538
+ messages,
10539
+ latestSeq: cursorRow ? Number(cursorRow.last_seq) : 0
10540
+ };
10541
+ }
10542
+ /**
10543
+ * Enforce a channel's retention bounds.
10544
+ *
10545
+ * Throttled per channel, so a burst of operations prunes once rather than
10546
+ * once per message — the cost then tracks elapsed time instead of write
10547
+ * volume, which is what makes retention affordable on a hot channel.
10548
+ */
10549
+ async prune(channel, retention) {
10550
+ const now = Date.now();
10551
+ if (now - (this.lastPruned.get(channel) ?? 0) < PRUNE_THROTTLE_MS) return 0;
10552
+ this.lastPruned.set(channel, now);
10553
+ let deleted = 0;
10554
+ if (retention.ttlMs !== void 0) {
10555
+ const result = await this.db.execute(sql`
10556
+ DELETE FROM rebase.channel_messages
10557
+ WHERE channel = ${channel}
10558
+ AND created_at < NOW() - MAKE_INTERVAL(secs => ${retention.ttlMs / 1e3})
10559
+ `);
10560
+ deleted += result.rowCount ?? 0;
10561
+ }
10562
+ if (retention.limit !== void 0 && retention.limit > 0) {
10563
+ const result = await this.db.execute(sql`
10564
+ DELETE FROM rebase.channel_messages
10565
+ WHERE channel = ${channel}
10566
+ AND seq <= (
10567
+ SELECT seq FROM rebase.channel_messages
10568
+ WHERE channel = ${channel}
10569
+ ORDER BY seq DESC
10570
+ OFFSET ${Math.floor(retention.limit)} LIMIT 1
10571
+ )
10572
+ `);
10573
+ deleted += result.rowCount ?? 0;
10574
+ }
10575
+ return deleted;
10576
+ }
10577
+ /** Forget throttle and match caches. Called on shutdown. */
10578
+ clear() {
10579
+ this.resolved.clear();
10580
+ this.lastPruned.clear();
10581
+ }
10582
+ };
10583
+ //#endregion
10283
10584
  //#region src/services/realtimeService.ts
10284
10585
  /** Channel name used for Postgres LISTEN/NOTIFY cross-instance realtime. */
10285
10586
  var PG_NOTIFY_CHANNEL = "rebase_entity_changes";
@@ -10295,6 +10596,26 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10295
10596
  clients = /* @__PURE__ */ new Map();
10296
10597
  channels = /* @__PURE__ */ new Map();
10297
10598
  presence = /* @__PURE__ */ new Map();
10599
+ /**
10600
+ * Ordered, replayable history for channels that opt into it.
10601
+ *
10602
+ * Undefined until {@link configureChannelHistory} is called, and inert even
10603
+ * then unless retention rules were supplied — so presence and ephemeral
10604
+ * notification channels never touch it. See `channel-history.ts`.
10605
+ */
10606
+ channelHistory;
10607
+ /**
10608
+ * One promise chain per retained channel, so that assigning a sequence
10609
+ * number and fanning the message out happen in the same order for every
10610
+ * message on that channel.
10611
+ *
10612
+ * Without it, two concurrent broadcasts can be numbered 4 and 5 by the
10613
+ * database and still reach subscribers as 5 then 4 — live order and replay
10614
+ * order would disagree, which is exactly the divergence sequence numbers
10615
+ * are supposed to rule out. Keyed by channel, so unrelated channels never
10616
+ * wait on each other.
10617
+ */
10618
+ channelSendQueues = /* @__PURE__ */ new Map();
10298
10619
  presenceInterval;
10299
10620
  static PRESENCE_TIMEOUT_MS = 3e4;
10300
10621
  dataService;
@@ -10471,6 +10792,9 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10471
10792
  case "broadcast":
10472
10793
  this.broadcastToChannel(clientId, payload?.channel, payload?.event, payload?.payload);
10473
10794
  break;
10795
+ case "channel_history":
10796
+ await this.handleChannelHistoryRequest(clientId, payload?.channel, payload?.sinceSeq, payload?.limit);
10797
+ break;
10474
10798
  case "presence_track":
10475
10799
  this.joinChannel(clientId, payload?.channel);
10476
10800
  this.trackPresence(clientId, payload?.channel, payload?.state ?? {});
@@ -10681,12 +11005,12 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10681
11005
  if (this.driver) {
10682
11006
  const collection = this.registry.getCollectionByPath(notifyPath);
10683
11007
  const activeAuth = authContext || {
10684
- userId: "anon",
11008
+ uid: "anon",
10685
11009
  roles: ["anon"]
10686
11010
  };
10687
11011
  return await this.db.transaction(async (tx) => {
10688
11012
  await applyAuthContext(tx, {
10689
- userId: activeAuth.userId,
11013
+ uid: activeAuth.uid,
10690
11014
  roles: activeAuth.roles
10691
11015
  }, this.rlsUserRole);
10692
11016
  const txEntityService = new DataService(tx, this.registry);
@@ -10718,7 +11042,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10718
11042
  if (globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead) {
10719
11043
  const contextForCallback = {
10720
11044
  user: {
10721
- uid: activeAuth.userId,
11045
+ uid: activeAuth.uid,
10722
11046
  roles: activeAuth.roles
10723
11047
  },
10724
11048
  driver: this.driver,
@@ -10810,12 +11134,12 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10810
11134
  if (this.driver) {
10811
11135
  const collection = this.registry.getCollectionByPath(notifyPath);
10812
11136
  const activeAuth = authContext || {
10813
- userId: "anon",
11137
+ uid: "anon",
10814
11138
  roles: ["anon"]
10815
11139
  };
10816
11140
  return await this.db.transaction(async (tx) => {
10817
11141
  await applyAuthContext(tx, {
10818
- userId: activeAuth.userId,
11142
+ uid: activeAuth.uid,
10819
11143
  roles: activeAuth.roles
10820
11144
  }, this.rlsUserRole);
10821
11145
  let processedEntity = await new DataService(tx, this.registry).fetchOne(notifyPath, id, collection?.databaseId);
@@ -10831,7 +11155,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10831
11155
  if (globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead) {
10832
11156
  const contextForCallback = {
10833
11157
  user: {
10834
- uid: activeAuth.userId,
11158
+ uid: activeAuth.uid,
10835
11159
  roles: activeAuth.roles
10836
11160
  },
10837
11161
  driver: this.driver,
@@ -10957,15 +11281,67 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10957
11281
  }
10958
11282
  this.removePresence(clientId, channel);
10959
11283
  }
10960
- /** Broadcast a message to all clients in a channel except sender */
11284
+ /**
11285
+ * Broadcast a message to all clients in a channel except the sender.
11286
+ *
11287
+ * On a channel with no retention rule this is what it always was: a
11288
+ * synchronous fan-out to whoever is connected, with no sequence number, no
11289
+ * SQL and no await — the body below runs to completion before returning.
11290
+ *
11291
+ * On a retained channel the message is durably numbered first and only then
11292
+ * delivered, through a per-channel queue so that delivery order matches
11293
+ * sequence order. That ordering is the whole point: a client that catches up
11294
+ * with `sinceSeq` has to arrive at the same state as one that never
11295
+ * disconnected.
11296
+ */
10961
11297
  broadcastToChannel(clientId, channel, event, payload) {
11298
+ const retention = this.channelHistory?.retentionFor(channel);
11299
+ if (!retention) {
11300
+ this.fanOutBroadcast(clientId, channel, event, payload);
11301
+ return;
11302
+ }
11303
+ const next = (this.channelSendQueues.get(channel) ?? Promise.resolve()).catch(() => {}).then(() => this.persistAndFanOut(clientId, channel, event, payload, retention));
11304
+ this.channelSendQueues.set(channel, next);
11305
+ next.finally(() => {
11306
+ if (this.channelSendQueues.get(channel) === next) this.channelSendQueues.delete(channel);
11307
+ });
11308
+ }
11309
+ /**
11310
+ * Number a broadcast, store it, then deliver it.
11311
+ *
11312
+ * A message that cannot be stored is **not** delivered. Delivering it would
11313
+ * put it in front of live subscribers while leaving it absent from every
11314
+ * future replay — the two views of the channel would disagree permanently,
11315
+ * and no later message could repair the gap. Failing loudly to the sender
11316
+ * instead lets it retry, which for an operation stream is the only outcome
11317
+ * that keeps clients convergent.
11318
+ */
11319
+ async persistAndFanOut(clientId, channel, event, payload, retention) {
11320
+ let seq;
11321
+ try {
11322
+ ({seq} = await this.channelHistory.append(channel, event, payload, clientId));
11323
+ } catch (error) {
11324
+ logger.error(`❌ [ChannelHistory] Could not persist broadcast on "${channel}" — message dropped`, { error });
11325
+ this.sendError(clientId, `Could not persist broadcast on retained channel "${channel}"`, void 0, "CHANNEL_HISTORY_WRITE_FAILED");
11326
+ return;
11327
+ }
11328
+ this.fanOutBroadcast(clientId, channel, event, payload, seq);
11329
+ try {
11330
+ await this.channelHistory.prune(channel, retention);
11331
+ } catch (error) {
11332
+ logger.warn(`⚠️ [ChannelHistory] Prune failed for "${channel}"`, { error });
11333
+ }
11334
+ }
11335
+ /** Deliver a broadcast frame to every member of a channel but the sender. */
11336
+ fanOutBroadcast(clientId, channel, event, payload, seq) {
10962
11337
  const members = this.channels.get(channel);
10963
11338
  if (!members) return;
10964
11339
  const message = JSON.stringify({
10965
11340
  type: "broadcast",
10966
11341
  channel,
10967
11342
  event,
10968
- payload
11343
+ payload,
11344
+ ...seq !== void 0 ? { seq } : {}
10969
11345
  });
10970
11346
  for (const memberId of members) {
10971
11347
  if (memberId === clientId) continue;
@@ -10973,6 +11349,55 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10973
11349
  if (ws && ws.readyState === WebSocket.OPEN) ws.send(message);
10974
11350
  }
10975
11351
  }
11352
+ /**
11353
+ * Install retention rules and create the tables they need.
11354
+ *
11355
+ * Safe to call with no rules (and safe not to call at all): the store stays
11356
+ * inert, no schema is created, and broadcast keeps its original
11357
+ * fire-and-forget path.
11358
+ */
11359
+ async configureChannelHistory(rules) {
11360
+ this.channelHistory = new ChannelHistoryStore(this.db, rules ?? []);
11361
+ if (!this.channelHistory.enabled) return;
11362
+ await this.channelHistory.ensureTables();
11363
+ }
11364
+ /** Whether any channel is configured to retain messages. */
11365
+ isChannelHistoryEnabled() {
11366
+ return this.channelHistory?.enabled ?? false;
11367
+ }
11368
+ /**
11369
+ * Answer a client's catch-up request.
11370
+ *
11371
+ * A channel with no retention rule is answered with `retained: false`
11372
+ * rather than an empty list, so the client can tell "you missed nothing"
11373
+ * apart from "this channel never keeps anything" — the second means its
11374
+ * reconnect strategy has to be a full resync, and silence would leave it
11375
+ * guessing.
11376
+ */
11377
+ async handleChannelHistoryRequest(clientId, channel, sinceSeq, limit) {
11378
+ if (!channel) return;
11379
+ if (!this.channelHistory?.retentionFor(channel)) {
11380
+ this.sendChannelHistory(clientId, channel, [], false);
11381
+ return;
11382
+ }
11383
+ try {
11384
+ const { messages, latestSeq } = await this.channelHistory.replay(channel, sinceSeq, limit);
11385
+ this.sendChannelHistory(clientId, channel, messages, true, latestSeq);
11386
+ } catch (error) {
11387
+ logger.error(`❌ [ChannelHistory] Replay failed for "${channel}"`, { error });
11388
+ this.sendError(clientId, `Could not replay history for channel "${channel}"`, void 0, "CHANNEL_HISTORY_READ_FAILED");
11389
+ }
11390
+ }
11391
+ sendChannelHistory(clientId, channel, messages, retained, latestSeq) {
11392
+ const ws = this.clients.get(clientId);
11393
+ if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({
11394
+ type: "channel_history",
11395
+ channel,
11396
+ messages,
11397
+ retained,
11398
+ ...latestSeq !== void 0 ? { latestSeq } : {}
11399
+ }));
11400
+ }
10976
11401
  /** Track presence in a channel */
10977
11402
  trackPresence(clientId, channel, state) {
10978
11403
  if (!this.presence.has(channel)) this.presence.set(channel, /* @__PURE__ */ new Map());
@@ -11053,6 +11478,9 @@ var RealtimeService = class RealtimeService extends EventEmitter {
11053
11478
  this.subscriptionCallbacks.clear();
11054
11479
  this.channels.clear();
11055
11480
  this.presence.clear();
11481
+ await Promise.allSettled([...this.channelSendQueues.values()]);
11482
+ this.channelSendQueues.clear();
11483
+ this.channelHistory?.clear();
11056
11484
  if (this.presenceInterval) {
11057
11485
  clearInterval(this.presenceInterval);
11058
11486
  this.presenceInterval = void 0;
@@ -11394,20 +11822,20 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
11394
11822
  if (authAdapter) try {
11395
11823
  const adapterUser = authAdapter.verifyToken ? await authAdapter.verifyToken(token) : await authAdapter.verifyRequest(new Request("http://localhost/_ws_auth", { headers: { Authorization: `Bearer ${token}` } }));
11396
11824
  if (adapterUser) verifiedUser = {
11397
- userId: adapterUser.uid,
11825
+ uid: adapterUser.uid,
11398
11826
  roles: adapterUser.roles,
11399
11827
  isAdmin: adapterUser.isAdmin
11400
11828
  };
11401
11829
  } catch {}
11402
11830
  else if (authConfig?.serviceKey && safeCompare(token, authConfig.serviceKey)) verifiedUser = {
11403
- userId: "service",
11831
+ uid: "service",
11404
11832
  roles: ["admin"],
11405
11833
  isAdmin: true
11406
11834
  };
11407
11835
  else {
11408
11836
  const jwtPayload = extractUserFromToken(token);
11409
11837
  if (jwtPayload) verifiedUser = {
11410
- userId: jwtPayload.userId,
11838
+ uid: jwtPayload.uid,
11411
11839
  roles: jwtPayload.roles ?? [],
11412
11840
  isAdmin: (jwtPayload.roles ?? []).some((r) => r === "admin")
11413
11841
  };
@@ -11423,11 +11851,11 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
11423
11851
  type: "AUTH_SUCCESS",
11424
11852
  requestId,
11425
11853
  payload: {
11426
- userId: verifiedUser.userId,
11854
+ uid: verifiedUser.uid,
11427
11855
  roles: verifiedUser.roles
11428
11856
  }
11429
11857
  }));
11430
- wsDebug(`🔐 [WebSocket Server] Client ${clientId} authenticated as ${verifiedUser.userId}`);
11858
+ wsDebug(`🔐 [WebSocket Server] Client ${clientId} authenticated as ${verifiedUser.uid}`);
11431
11859
  } else {
11432
11860
  wsDebug(`[WS] replying AUTH_ERROR for requestId ${requestId} (invalid token)`);
11433
11861
  sendError("AUTH_ERROR", "INVALID_TOKEN", "Invalid or expired token");
@@ -11465,7 +11893,7 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
11465
11893
  const session = clientSessions.get(clientId);
11466
11894
  if (typeof driver.withAuth === "function") try {
11467
11895
  const userForAuth = session?.user ? {
11468
- uid: session.user.userId,
11896
+ uid: session.user.uid,
11469
11897
  displayName: null,
11470
11898
  email: null,
11471
11899
  photoURL: null,
@@ -11599,7 +12027,7 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
11599
12027
  sql: typeof sql === "string" ? sql.substring(0, 500) : sql,
11600
12028
  options,
11601
12029
  resultRows: Array.isArray(result) ? result.length : "unknown",
11602
- userId: auditSession?.user?.userId ?? "unknown",
12030
+ uid: auditSession?.user?.uid ?? "unknown",
11603
12031
  roles: auditSession?.user?.roles ?? [],
11604
12032
  isAdmin: auditSession?.user?.isAdmin ?? false
11605
12033
  }));
@@ -11644,6 +12072,21 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
11644
12072
  ws.send(JSON.stringify(response));
11645
12073
  }
11646
12074
  break;
12075
+ case "FETCH_APPLICATION_ROLES":
12076
+ {
12077
+ wsDebug("👤 [WebSocket Server] Processing FETCH_APPLICATION_ROLES request");
12078
+ const admin = (await getScopedDelegate()).admin;
12079
+ let roles = [];
12080
+ if (isSQLAdmin(admin) && admin.fetchApplicationRoles) roles = await admin.fetchApplicationRoles();
12081
+ wsDebug(`👤 [WebSocket Server] Fetched ${roles.length} application roles.`);
12082
+ const response = {
12083
+ type: "FETCH_APPLICATION_ROLES_SUCCESS",
12084
+ payload: { roles },
12085
+ requestId
12086
+ };
12087
+ ws.send(JSON.stringify(response));
12088
+ }
12089
+ break;
11647
12090
  case "FETCH_CURRENT_DATABASE":
11648
12091
  {
11649
12092
  wsDebug("📚 [WebSocket Server] Processing FETCH_CURRENT_DATABASE request");
@@ -11750,14 +12193,15 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
11750
12193
  case "broadcast":
11751
12194
  case "presence_track":
11752
12195
  case "presence_untrack":
11753
- case "presence_state": {
12196
+ case "presence_state":
12197
+ case "channel_history": {
11754
12198
  wsDebug("🔄 [WebSocket Server] Routing realtime message to RealtimeService:", type);
11755
12199
  const session = clientSessions.get(clientId);
11756
12200
  const authContext = session?.user ? {
11757
- userId: session.user.userId,
12201
+ uid: session.user.uid,
11758
12202
  roles: session.user.roles ?? []
11759
12203
  } : {
11760
- userId: "anon",
12204
+ uid: "anon",
11761
12205
  roles: ["anon"]
11762
12206
  };
11763
12207
  await realtimeService.handleClientMessage(clientId, {
@@ -22171,6 +22615,20 @@ function patchPgArrayNullSafety(tables) {
22171
22615
  if (patchedCount > 0) logger.debug(`[PgArray] Patched ${patchedCount} array column(s) for null-safety`);
22172
22616
  }
22173
22617
  //#endregion
22618
+ //#region src/schema/introspect-db-naming.ts
22619
+ /**
22620
+ * Naming helpers shared by the introspection modules. These live apart from
22621
+ * `introspect-db-logic.ts` because the inference pass needs them too, and
22622
+ * importing them from there would close a cycle back through this module.
22623
+ */
22624
+ /**
22625
+ * Convert a snake_case name to a human-readable Title Case label.
22626
+ * e.g. "created_at" -> "Created At", "customer_id" -> "Customer Id"
22627
+ */
22628
+ function humanize(snakeName) {
22629
+ return snakeName.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
22630
+ }
22631
+ //#endregion
22174
22632
  //#region src/schema/introspect-db-logic.ts
22175
22633
  var IRREGULAR_SINGULARS = {
22176
22634
  people: "person",
@@ -22230,13 +22688,6 @@ function singularize(word) {
22230
22688
  if (lower.endsWith("s") && !lower.endsWith("ss") && !lower.endsWith("us") && !lower.endsWith("is")) return word.slice(0, -1);
22231
22689
  return word;
22232
22690
  }
22233
- /**
22234
- * Convert a snake_case name to a human-readable Title Case label.
22235
- * e.g. "created_at" -> "Created At", "customer_id" -> "Customer Id"
22236
- */
22237
- function humanize(snakeName) {
22238
- return snakeName.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
22239
- }
22240
22691
  function getIconForTable(tableName) {
22241
22692
  const table = tableName.toLowerCase();
22242
22693
  if (table.includes("user") || table.includes("account") || table.includes("member") || table.includes("customer") || table.includes("client") || table.includes("patient")) return "Users";
@@ -22757,6 +23208,11 @@ function createPostgresBootstrapper(pgConfig) {
22757
23208
  } catch (err) {
22758
23209
  logger.warn("⚠️ Could not initialize branch metadata table", { error: err });
22759
23210
  }
23211
+ try {
23212
+ await realtimeService.configureChannelHistory(pgConfig.realtime?.channels);
23213
+ } catch (err) {
23214
+ logger.warn("⚠️ Could not initialize channel history tables — retained channels will not replay", { error: err });
23215
+ }
22760
23216
  const directUrl = process.env.DATABASE_DIRECT_URL || pgConfig.connectionString;
22761
23217
  const validModes = new Set([
22762
23218
  "auto",