@rebasepro/server-postgres 0.9.1-canary.f0ac103 → 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 +511 -36
- package/dist/index.es.js.map +1 -1
- package/dist/schema/doctor.d.ts +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/doctor.ts +45 -20
- 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/services/row-pipeline.ts +27 -3
- package/src/websocket.ts +30 -11
package/dist/index.es.js
CHANGED
|
@@ -6524,8 +6524,27 @@ function coerceDeclaredNumbers(row, collection) {
|
|
|
6524
6524
|
return out;
|
|
6525
6525
|
}
|
|
6526
6526
|
/** Render one target row in the requested style. */
|
|
6527
|
+
/**
|
|
6528
|
+
* Drop every column the collection marked `excludeFromApi`.
|
|
6529
|
+
*
|
|
6530
|
+
* Password hashes and verification tokens have to be readable server-side but
|
|
6531
|
+
* must never reach a client — and "never" has to mean every exit from this
|
|
6532
|
+
* pipeline, including relation targets, or a secret leaks through whichever
|
|
6533
|
+
* path was overlooked. Keyed by both the property name and its column name,
|
|
6534
|
+
* since a row can arrive keyed either way depending on the caller.
|
|
6535
|
+
*/
|
|
6536
|
+
function stripExcluded(row, collection) {
|
|
6537
|
+
const properties = collection.properties;
|
|
6538
|
+
if (!properties) return row;
|
|
6539
|
+
for (const [key, property] of Object.entries(properties)) {
|
|
6540
|
+
if (!property?.excludeFromApi) continue;
|
|
6541
|
+
delete row[key];
|
|
6542
|
+
if (property.columnName) delete row[property.columnName];
|
|
6543
|
+
}
|
|
6544
|
+
return row;
|
|
6545
|
+
}
|
|
6527
6546
|
function renderTarget(targetRow, targetCollection, style, registry) {
|
|
6528
|
-
if (style === "inline") return coerceDeclaredNumbers({ ...targetRow }, targetCollection);
|
|
6547
|
+
if (style === "inline") return stripExcluded(coerceDeclaredNumbers({ ...targetRow }, targetCollection), targetCollection);
|
|
6529
6548
|
const address = relationTargetAddress(targetRow, targetCollection, registry);
|
|
6530
6549
|
const path = targetCollection.slug;
|
|
6531
6550
|
return createRelationRefWithData(address, path, {
|
|
@@ -6567,7 +6586,7 @@ function toCmsRow(row, collection, registry) {
|
|
|
6567
6586
|
normalized[key] = relData.map((item) => renderTarget(isJunctionRelation(relation) ? unwrapJunctionRow(item) : item, targetCollection, "ref", registry));
|
|
6568
6587
|
} else if (relation.cardinality === "one" && typeof relData === "object" && !Array.isArray(relData)) normalized[key] = renderTarget(relData, relation.target(), "ref", registry);
|
|
6569
6588
|
}
|
|
6570
|
-
return normalized;
|
|
6589
|
+
return stripExcluded(normalized, collection);
|
|
6571
6590
|
}
|
|
6572
6591
|
/**
|
|
6573
6592
|
* The row REST serves: every column under its own name, with the value Postgres
|
|
@@ -6592,7 +6611,7 @@ function toRestRow(row, collection, registry) {
|
|
|
6592
6611
|
else if (relation && typeof value === "object" && value !== null) flat[key] = renderTarget(value, relation.target(), "inline", registry);
|
|
6593
6612
|
else flat[key] = coerceDeclaredNumber(value, collection.properties?.[key]);
|
|
6594
6613
|
}
|
|
6595
|
-
return flat;
|
|
6614
|
+
return stripExcluded(flat, collection);
|
|
6596
6615
|
}
|
|
6597
6616
|
//#endregion
|
|
6598
6617
|
//#region src/services/FetchService.ts
|
|
@@ -8171,14 +8190,14 @@ async function ensureAppRole(run, schemas) {
|
|
|
8171
8190
|
* semantics: it is why `auth.uid() IS NOT NULL` is true for anonymous requests.
|
|
8172
8191
|
*/
|
|
8173
8192
|
async function applyAuthContext(tx, auth, userRole) {
|
|
8174
|
-
const
|
|
8193
|
+
const uid = typeof auth.uid === "string" && auth.uid.trim() !== "" ? auth.uid : ANONYMOUS_USER_ID;
|
|
8175
8194
|
const normalizedRoles = auth.roles.map((r) => typeof r === "string" ? r : r?.id ?? String(r));
|
|
8176
8195
|
await tx.execute(sql`
|
|
8177
8196
|
SELECT
|
|
8178
|
-
set_config('app.user_id', ${
|
|
8197
|
+
set_config('app.user_id', ${uid}, true),
|
|
8179
8198
|
set_config('app.user_roles', ${normalizedRoles.join(",")}, true),
|
|
8180
8199
|
set_config('app.jwt', ${JSON.stringify({
|
|
8181
|
-
sub:
|
|
8200
|
+
sub: uid,
|
|
8182
8201
|
roles: auth.roles
|
|
8183
8202
|
})}, true)
|
|
8184
8203
|
`);
|
|
@@ -8324,6 +8343,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
8324
8343
|
executeSql: (...args) => this.executeSql(...args),
|
|
8325
8344
|
fetchAvailableDatabases: () => this.fetchAvailableDatabases(),
|
|
8326
8345
|
fetchAvailableRoles: () => this.fetchAvailableRoles(),
|
|
8346
|
+
fetchApplicationRoles: () => this.fetchApplicationRoles(),
|
|
8327
8347
|
fetchCurrentDatabase: () => this.fetchCurrentDatabase(),
|
|
8328
8348
|
fetchUnmappedTables: (...args) => this.fetchUnmappedTables(...args),
|
|
8329
8349
|
fetchTableMetadata: (...args) => this.fetchTableMetadata(...args),
|
|
@@ -8977,6 +8997,45 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
8977
8997
|
async fetchAvailableRoles() {
|
|
8978
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);
|
|
8979
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
|
+
}
|
|
8980
9039
|
async fetchCurrentDatabase() {
|
|
8981
9040
|
return this.poolManager?.defaultDatabaseName;
|
|
8982
9041
|
}
|
|
@@ -9118,15 +9177,15 @@ var AuthenticatedPostgresBackendDriver = class {
|
|
|
9118
9177
|
async withTransaction(operation, options) {
|
|
9119
9178
|
const pendingNotifications = [];
|
|
9120
9179
|
const result = await this.delegate.db.transaction(async (tx) => {
|
|
9121
|
-
let
|
|
9122
|
-
if (!
|
|
9180
|
+
let uid = this.user?.uid;
|
|
9181
|
+
if (!uid) {
|
|
9123
9182
|
logger.warn("[DataDriver] User ID (uid) is missing for authenticated delegate. Using 'anonymous'. User object", { detail: this.user });
|
|
9124
|
-
|
|
9183
|
+
uid = "anonymous";
|
|
9125
9184
|
}
|
|
9126
9185
|
const userRoles = this.user?.roles ?? [];
|
|
9127
9186
|
if (!this.user?.roles) logger.warn("[DataDriver] User roles are missing for authenticated delegate. Using empty array. User object", { detail: this.user });
|
|
9128
9187
|
await applyAuthContext(tx, {
|
|
9129
|
-
|
|
9188
|
+
uid,
|
|
9130
9189
|
roles: userRoles
|
|
9131
9190
|
}, this.delegate.rlsUserRole);
|
|
9132
9191
|
const txEntityService = new DataService(tx, this.delegate.registry);
|
|
@@ -9153,7 +9212,7 @@ var AuthenticatedPostgresBackendDriver = class {
|
|
|
9153
9212
|
*/
|
|
9154
9213
|
injectAuthContext(unsubscribe) {
|
|
9155
9214
|
const authContext = {
|
|
9156
|
-
|
|
9215
|
+
uid: this.user?.uid || "anonymous",
|
|
9157
9216
|
roles: this.user?.roles ?? []
|
|
9158
9217
|
};
|
|
9159
9218
|
const entries = Array.from(this.delegate.realtimeService.subscriptions.entries());
|
|
@@ -10261,6 +10320,267 @@ var CdcListener = class CdcListener {
|
|
|
10261
10320
|
}
|
|
10262
10321
|
};
|
|
10263
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
|
|
10264
10584
|
//#region src/services/realtimeService.ts
|
|
10265
10585
|
/** Channel name used for Postgres LISTEN/NOTIFY cross-instance realtime. */
|
|
10266
10586
|
var PG_NOTIFY_CHANNEL = "rebase_entity_changes";
|
|
@@ -10276,6 +10596,26 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
10276
10596
|
clients = /* @__PURE__ */ new Map();
|
|
10277
10597
|
channels = /* @__PURE__ */ new Map();
|
|
10278
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();
|
|
10279
10619
|
presenceInterval;
|
|
10280
10620
|
static PRESENCE_TIMEOUT_MS = 3e4;
|
|
10281
10621
|
dataService;
|
|
@@ -10452,6 +10792,9 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
10452
10792
|
case "broadcast":
|
|
10453
10793
|
this.broadcastToChannel(clientId, payload?.channel, payload?.event, payload?.payload);
|
|
10454
10794
|
break;
|
|
10795
|
+
case "channel_history":
|
|
10796
|
+
await this.handleChannelHistoryRequest(clientId, payload?.channel, payload?.sinceSeq, payload?.limit);
|
|
10797
|
+
break;
|
|
10455
10798
|
case "presence_track":
|
|
10456
10799
|
this.joinChannel(clientId, payload?.channel);
|
|
10457
10800
|
this.trackPresence(clientId, payload?.channel, payload?.state ?? {});
|
|
@@ -10662,12 +11005,12 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
10662
11005
|
if (this.driver) {
|
|
10663
11006
|
const collection = this.registry.getCollectionByPath(notifyPath);
|
|
10664
11007
|
const activeAuth = authContext || {
|
|
10665
|
-
|
|
11008
|
+
uid: "anon",
|
|
10666
11009
|
roles: ["anon"]
|
|
10667
11010
|
};
|
|
10668
11011
|
return await this.db.transaction(async (tx) => {
|
|
10669
11012
|
await applyAuthContext(tx, {
|
|
10670
|
-
|
|
11013
|
+
uid: activeAuth.uid,
|
|
10671
11014
|
roles: activeAuth.roles
|
|
10672
11015
|
}, this.rlsUserRole);
|
|
10673
11016
|
const txEntityService = new DataService(tx, this.registry);
|
|
@@ -10699,7 +11042,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
10699
11042
|
if (globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead) {
|
|
10700
11043
|
const contextForCallback = {
|
|
10701
11044
|
user: {
|
|
10702
|
-
uid: activeAuth.
|
|
11045
|
+
uid: activeAuth.uid,
|
|
10703
11046
|
roles: activeAuth.roles
|
|
10704
11047
|
},
|
|
10705
11048
|
driver: this.driver,
|
|
@@ -10791,12 +11134,12 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
10791
11134
|
if (this.driver) {
|
|
10792
11135
|
const collection = this.registry.getCollectionByPath(notifyPath);
|
|
10793
11136
|
const activeAuth = authContext || {
|
|
10794
|
-
|
|
11137
|
+
uid: "anon",
|
|
10795
11138
|
roles: ["anon"]
|
|
10796
11139
|
};
|
|
10797
11140
|
return await this.db.transaction(async (tx) => {
|
|
10798
11141
|
await applyAuthContext(tx, {
|
|
10799
|
-
|
|
11142
|
+
uid: activeAuth.uid,
|
|
10800
11143
|
roles: activeAuth.roles
|
|
10801
11144
|
}, this.rlsUserRole);
|
|
10802
11145
|
let processedEntity = await new DataService(tx, this.registry).fetchOne(notifyPath, id, collection?.databaseId);
|
|
@@ -10812,7 +11155,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
10812
11155
|
if (globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead) {
|
|
10813
11156
|
const contextForCallback = {
|
|
10814
11157
|
user: {
|
|
10815
|
-
uid: activeAuth.
|
|
11158
|
+
uid: activeAuth.uid,
|
|
10816
11159
|
roles: activeAuth.roles
|
|
10817
11160
|
},
|
|
10818
11161
|
driver: this.driver,
|
|
@@ -10938,15 +11281,67 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
10938
11281
|
}
|
|
10939
11282
|
this.removePresence(clientId, channel);
|
|
10940
11283
|
}
|
|
10941
|
-
/**
|
|
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
|
+
*/
|
|
10942
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) {
|
|
10943
11337
|
const members = this.channels.get(channel);
|
|
10944
11338
|
if (!members) return;
|
|
10945
11339
|
const message = JSON.stringify({
|
|
10946
11340
|
type: "broadcast",
|
|
10947
11341
|
channel,
|
|
10948
11342
|
event,
|
|
10949
|
-
payload
|
|
11343
|
+
payload,
|
|
11344
|
+
...seq !== void 0 ? { seq } : {}
|
|
10950
11345
|
});
|
|
10951
11346
|
for (const memberId of members) {
|
|
10952
11347
|
if (memberId === clientId) continue;
|
|
@@ -10954,6 +11349,55 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
10954
11349
|
if (ws && ws.readyState === WebSocket.OPEN) ws.send(message);
|
|
10955
11350
|
}
|
|
10956
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
|
+
}
|
|
10957
11401
|
/** Track presence in a channel */
|
|
10958
11402
|
trackPresence(clientId, channel, state) {
|
|
10959
11403
|
if (!this.presence.has(channel)) this.presence.set(channel, /* @__PURE__ */ new Map());
|
|
@@ -11034,6 +11478,9 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
11034
11478
|
this.subscriptionCallbacks.clear();
|
|
11035
11479
|
this.channels.clear();
|
|
11036
11480
|
this.presence.clear();
|
|
11481
|
+
await Promise.allSettled([...this.channelSendQueues.values()]);
|
|
11482
|
+
this.channelSendQueues.clear();
|
|
11483
|
+
this.channelHistory?.clear();
|
|
11037
11484
|
if (this.presenceInterval) {
|
|
11038
11485
|
clearInterval(this.presenceInterval);
|
|
11039
11486
|
this.presenceInterval = void 0;
|
|
@@ -11375,20 +11822,20 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
11375
11822
|
if (authAdapter) try {
|
|
11376
11823
|
const adapterUser = authAdapter.verifyToken ? await authAdapter.verifyToken(token) : await authAdapter.verifyRequest(new Request("http://localhost/_ws_auth", { headers: { Authorization: `Bearer ${token}` } }));
|
|
11377
11824
|
if (adapterUser) verifiedUser = {
|
|
11378
|
-
|
|
11825
|
+
uid: adapterUser.uid,
|
|
11379
11826
|
roles: adapterUser.roles,
|
|
11380
11827
|
isAdmin: adapterUser.isAdmin
|
|
11381
11828
|
};
|
|
11382
11829
|
} catch {}
|
|
11383
11830
|
else if (authConfig?.serviceKey && safeCompare(token, authConfig.serviceKey)) verifiedUser = {
|
|
11384
|
-
|
|
11831
|
+
uid: "service",
|
|
11385
11832
|
roles: ["admin"],
|
|
11386
11833
|
isAdmin: true
|
|
11387
11834
|
};
|
|
11388
11835
|
else {
|
|
11389
11836
|
const jwtPayload = extractUserFromToken(token);
|
|
11390
11837
|
if (jwtPayload) verifiedUser = {
|
|
11391
|
-
|
|
11838
|
+
uid: jwtPayload.uid,
|
|
11392
11839
|
roles: jwtPayload.roles ?? [],
|
|
11393
11840
|
isAdmin: (jwtPayload.roles ?? []).some((r) => r === "admin")
|
|
11394
11841
|
};
|
|
@@ -11404,11 +11851,11 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
11404
11851
|
type: "AUTH_SUCCESS",
|
|
11405
11852
|
requestId,
|
|
11406
11853
|
payload: {
|
|
11407
|
-
|
|
11854
|
+
uid: verifiedUser.uid,
|
|
11408
11855
|
roles: verifiedUser.roles
|
|
11409
11856
|
}
|
|
11410
11857
|
}));
|
|
11411
|
-
wsDebug(`🔐 [WebSocket Server] Client ${clientId} authenticated as ${verifiedUser.
|
|
11858
|
+
wsDebug(`🔐 [WebSocket Server] Client ${clientId} authenticated as ${verifiedUser.uid}`);
|
|
11412
11859
|
} else {
|
|
11413
11860
|
wsDebug(`[WS] replying AUTH_ERROR for requestId ${requestId} (invalid token)`);
|
|
11414
11861
|
sendError("AUTH_ERROR", "INVALID_TOKEN", "Invalid or expired token");
|
|
@@ -11446,7 +11893,7 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
11446
11893
|
const session = clientSessions.get(clientId);
|
|
11447
11894
|
if (typeof driver.withAuth === "function") try {
|
|
11448
11895
|
const userForAuth = session?.user ? {
|
|
11449
|
-
uid: session.user.
|
|
11896
|
+
uid: session.user.uid,
|
|
11450
11897
|
displayName: null,
|
|
11451
11898
|
email: null,
|
|
11452
11899
|
photoURL: null,
|
|
@@ -11580,7 +12027,7 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
11580
12027
|
sql: typeof sql === "string" ? sql.substring(0, 500) : sql,
|
|
11581
12028
|
options,
|
|
11582
12029
|
resultRows: Array.isArray(result) ? result.length : "unknown",
|
|
11583
|
-
|
|
12030
|
+
uid: auditSession?.user?.uid ?? "unknown",
|
|
11584
12031
|
roles: auditSession?.user?.roles ?? [],
|
|
11585
12032
|
isAdmin: auditSession?.user?.isAdmin ?? false
|
|
11586
12033
|
}));
|
|
@@ -11625,6 +12072,21 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
11625
12072
|
ws.send(JSON.stringify(response));
|
|
11626
12073
|
}
|
|
11627
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;
|
|
11628
12090
|
case "FETCH_CURRENT_DATABASE":
|
|
11629
12091
|
{
|
|
11630
12092
|
wsDebug("📚 [WebSocket Server] Processing FETCH_CURRENT_DATABASE request");
|
|
@@ -11731,14 +12193,15 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
11731
12193
|
case "broadcast":
|
|
11732
12194
|
case "presence_track":
|
|
11733
12195
|
case "presence_untrack":
|
|
11734
|
-
case "presence_state":
|
|
12196
|
+
case "presence_state":
|
|
12197
|
+
case "channel_history": {
|
|
11735
12198
|
wsDebug("🔄 [WebSocket Server] Routing realtime message to RealtimeService:", type);
|
|
11736
12199
|
const session = clientSessions.get(clientId);
|
|
11737
12200
|
const authContext = session?.user ? {
|
|
11738
|
-
|
|
12201
|
+
uid: session.user.uid,
|
|
11739
12202
|
roles: session.user.roles ?? []
|
|
11740
12203
|
} : {
|
|
11741
|
-
|
|
12204
|
+
uid: "anon",
|
|
11742
12205
|
roles: ["anon"]
|
|
11743
12206
|
};
|
|
11744
12207
|
await realtimeService.handleClientMessage(clientId, {
|
|
@@ -22152,6 +22615,20 @@ function patchPgArrayNullSafety(tables) {
|
|
|
22152
22615
|
if (patchedCount > 0) logger.debug(`[PgArray] Patched ${patchedCount} array column(s) for null-safety`);
|
|
22153
22616
|
}
|
|
22154
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
|
|
22155
22632
|
//#region src/schema/introspect-db-logic.ts
|
|
22156
22633
|
var IRREGULAR_SINGULARS = {
|
|
22157
22634
|
people: "person",
|
|
@@ -22211,13 +22688,6 @@ function singularize(word) {
|
|
|
22211
22688
|
if (lower.endsWith("s") && !lower.endsWith("ss") && !lower.endsWith("us") && !lower.endsWith("is")) return word.slice(0, -1);
|
|
22212
22689
|
return word;
|
|
22213
22690
|
}
|
|
22214
|
-
/**
|
|
22215
|
-
* Convert a snake_case name to a human-readable Title Case label.
|
|
22216
|
-
* e.g. "created_at" -> "Created At", "customer_id" -> "Customer Id"
|
|
22217
|
-
*/
|
|
22218
|
-
function humanize(snakeName) {
|
|
22219
|
-
return snakeName.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
22220
|
-
}
|
|
22221
22691
|
function getIconForTable(tableName) {
|
|
22222
22692
|
const table = tableName.toLowerCase();
|
|
22223
22693
|
if (table.includes("user") || table.includes("account") || table.includes("member") || table.includes("customer") || table.includes("client") || table.includes("patient")) return "Users";
|
|
@@ -22738,6 +23208,11 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
22738
23208
|
} catch (err) {
|
|
22739
23209
|
logger.warn("⚠️ Could not initialize branch metadata table", { error: err });
|
|
22740
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
|
+
}
|
|
22741
23216
|
const directUrl = process.env.DATABASE_DIRECT_URL || pgConfig.connectionString;
|
|
22742
23217
|
const validModes = new Set([
|
|
22743
23218
|
"auto",
|