@rebasepro/server-postgres 0.9.1-canary.73476f2 → 0.9.1-canary.74adfbe
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 +43 -2
- package/dist/PostgresBootstrapper.d.ts +17 -1
- package/dist/auth/services.d.ts +68 -52
- package/dist/collections/buildRegistry.d.ts +27 -0
- package/dist/connection.d.ts +21 -0
- package/dist/data-transformer.d.ts +9 -2
- package/dist/index.es.js +2185 -775
- package/dist/index.es.js.map +1 -1
- package/dist/schema/auth-bootstrap-sql.d.ts +1 -1
- package/dist/schema/auth-schema.d.ts +24 -24
- 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 +2 -2
- package/dist/services/FetchService.d.ts +4 -24
- package/dist/services/PersistService.d.ts +27 -1
- package/dist/services/RelationService.d.ts +34 -1
- package/dist/services/channel-history.d.ts +118 -0
- package/dist/services/collection-helpers.d.ts +79 -14
- package/dist/services/dataService.d.ts +3 -1
- package/dist/services/index.d.ts +1 -1
- package/dist/services/realtimeService.d.ts +76 -2
- package/dist/services/row-pipeline.d.ts +63 -0
- package/package.json +13 -34
- package/src/PostgresBackendDriver.ts +183 -18
- package/src/PostgresBootstrapper.ts +80 -26
- package/src/auth/ensure-tables.ts +170 -28
- package/src/auth/services.ts +181 -150
- package/src/cli.ts +60 -0
- package/src/collections/buildRegistry.ts +59 -0
- package/src/connection.ts +61 -1
- package/src/data-transformer.ts +11 -9
- package/src/databasePoolManager.ts +2 -0
- package/src/schema/auth-bootstrap-sql.ts +7 -1
- package/src/schema/auth-schema.ts +13 -13
- package/src/schema/doctor.ts +45 -20
- package/src/schema/generate-drizzle-schema-logic.ts +24 -29
- package/src/schema/generate-postgres-ddl-logic.ts +76 -28
- 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-db.ts +19 -2
- 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 +11 -5
- package/src/services/BranchService.ts +42 -10
- package/src/services/FetchService.ts +65 -270
- package/src/services/PersistService.ts +130 -14
- package/src/services/RelationService.ts +153 -94
- package/src/services/channel-history.ts +343 -0
- package/src/services/collection-helpers.ts +164 -47
- package/src/services/dataService.ts +3 -2
- package/src/services/index.ts +1 -0
- package/src/services/realtimeService.ts +238 -29
- package/src/services/row-pipeline.ts +239 -0
- package/src/utils/drizzle-conditions.ts +13 -0
- package/src/websocket.ts +34 -12
- package/dist/schema/auth-default-policies.d.ts +0 -10
- package/src/schema/auth-default-policies.ts +0 -132
|
@@ -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
|
+
}
|
|
@@ -2,6 +2,15 @@ import { PgTable, AnyPgColumn } from "drizzle-orm/pg-core";
|
|
|
2
2
|
import { CollectionConfig, Property } from "@rebasepro/types";
|
|
3
3
|
import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
|
|
4
4
|
import { getTableName } from "@rebasepro/common";
|
|
5
|
+
import { logger } from "@rebasepro/server";
|
|
6
|
+
|
|
7
|
+
// Row identity is derived on both sides of the wire — the driver parses an
|
|
8
|
+
// incoming address into key columns, the admin derives one from a served row —
|
|
9
|
+
// so the implementation lives in `common` and both agree by construction.
|
|
10
|
+
export { buildCompositeId, parseIdValues, COMPOSITE_ID_SEPARATOR } from "@rebasepro/common";
|
|
11
|
+
export type { PrimaryKeyInfo } from "@rebasepro/common";
|
|
12
|
+
import { buildCompositeId, COMPOSITE_ID_SEPARATOR, getDeclaredPrimaryKeys } from "@rebasepro/common";
|
|
13
|
+
import type { PrimaryKeyInfo } from "@rebasepro/common";
|
|
5
14
|
|
|
6
15
|
/**
|
|
7
16
|
* Shared helper functions for row operations.
|
|
@@ -49,10 +58,27 @@ export function getTableForCollection(collection: CollectionConfig, registry: Po
|
|
|
49
58
|
return table;
|
|
50
59
|
}
|
|
51
60
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
61
|
+
/**
|
|
62
|
+
* The key columns a collection's rows are addressed by.
|
|
63
|
+
*
|
|
64
|
+
* Three tiers, in order: properties marked `isId`, the primary keys of the
|
|
65
|
+
* drizzle schema, and finally a column literally named `id`. Only the first is
|
|
66
|
+
* visible to the browser, which is why a key known only to drizzle is reported
|
|
67
|
+
* at boot — see {@link warnOnKeysTheAdminCannotResolve}.
|
|
68
|
+
*
|
|
69
|
+
* Returns `[]` when nothing resolves, rather than throwing. It used to open by
|
|
70
|
+
* resolving the table, which throws when there is none — so the `isId` tier,
|
|
71
|
+
* which needs no table at all, was unreachable for exactly the collections
|
|
72
|
+
* most likely to have no table registered. Every caller that wanted "no keys"
|
|
73
|
+
* to mean "no keys" had to spell that out in a try/catch.
|
|
74
|
+
*
|
|
75
|
+
* Callers that cannot proceed without a key must say so themselves, naming the
|
|
76
|
+
* collection: an empty array here means "this collection has no address", which
|
|
77
|
+
* is a different answer in a notification (broadcast a wildcard) than in a save
|
|
78
|
+
* (fail).
|
|
79
|
+
*/
|
|
80
|
+
export function getPrimaryKeys(collection: CollectionConfig, registry: PostgresCollectionRegistry): PrimaryKeyInfo[] {
|
|
81
|
+
// Explicitly declared `isId` properties win, and need no table.
|
|
56
82
|
if (collection.properties) {
|
|
57
83
|
const idProps = Object.entries(collection.properties)
|
|
58
84
|
.filter(([_, prop]) => "isId" in (prop as object) && Boolean((prop as { isId?: unknown }).isId))
|
|
@@ -67,8 +93,14 @@ export function getPrimaryKeys(collection: CollectionConfig, registry: PostgresC
|
|
|
67
93
|
}
|
|
68
94
|
}
|
|
69
95
|
|
|
96
|
+
// The remaining tiers read the drizzle schema, so they need the table. A
|
|
97
|
+
// collection without one — another engine's, or simply unregistered — has
|
|
98
|
+
// nothing more to offer.
|
|
99
|
+
const table = registry.getTable(getTableName(collection));
|
|
100
|
+
if (!table) return [];
|
|
101
|
+
|
|
70
102
|
// Otherwise infer from Drizzle schema
|
|
71
|
-
const keys:
|
|
103
|
+
const keys: PrimaryKeyInfo[] = [];
|
|
72
104
|
for (const [key, colRaw] of Object.entries(table)) {
|
|
73
105
|
const col = colRaw as AnyPgColumn;
|
|
74
106
|
if (col && typeof col === "object" && "primary" in col && col.primary) {
|
|
@@ -96,56 +128,141 @@ isUUID });
|
|
|
96
128
|
return keys;
|
|
97
129
|
}
|
|
98
130
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
131
|
+
/**
|
|
132
|
+
* The key columns, for callers that cannot do their job without one.
|
|
133
|
+
*
|
|
134
|
+
* {@link getPrimaryKeys} answers "what keys, if any" and returns `[]` for a
|
|
135
|
+
* collection with no address. Most of this driver, though, is building a WHERE
|
|
136
|
+
* clause and has no meaning without a key — for those, an empty array is not an
|
|
137
|
+
* answer, and indexing `[0]` into it produces `Cannot read properties of
|
|
138
|
+
* undefined` three frames from where the real problem is. This says what is
|
|
139
|
+
* wrong and which collection it is wrong about.
|
|
140
|
+
*/
|
|
141
|
+
export function requirePrimaryKeys(collection: CollectionConfig, registry: PostgresCollectionRegistry): PrimaryKeyInfo[] {
|
|
142
|
+
const keys = getPrimaryKeys(collection, registry);
|
|
143
|
+
if (keys.length === 0) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
`Collection '${collection.slug}' has no primary key, so its rows cannot be addressed. ` +
|
|
146
|
+
`Mark the key property with \`isId\` in its config, or register a table whose schema declares one.`
|
|
147
|
+
);
|
|
104
148
|
}
|
|
149
|
+
return keys;
|
|
150
|
+
}
|
|
105
151
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
152
|
+
/**
|
|
153
|
+
* Collections whose key the *browser* cannot resolve, and what it will do
|
|
154
|
+
* instead.
|
|
155
|
+
*
|
|
156
|
+
* The two sides resolve keys from different evidence. This driver reads, in
|
|
157
|
+
* order: properties marked `isId`, the primary keys of the Drizzle schema, then
|
|
158
|
+
* a column literally named `id`. The admin shares the `CollectionConfig` — it
|
|
159
|
+
* compiles the same collection files into its bundle — but never the Drizzle
|
|
160
|
+
* schema, so the middle tier is invisible to it.
|
|
161
|
+
*
|
|
162
|
+
* Nothing can normalize this at runtime: the server does not serve the admin
|
|
163
|
+
* its collections, so a key resolved here cannot be handed over there. The
|
|
164
|
+
* config files are the only thing both sides read, so the fix is an edit to
|
|
165
|
+
* them, and the most this can do is say exactly which edit.
|
|
166
|
+
*
|
|
167
|
+
* Two shapes, and the second is the dangerous one:
|
|
168
|
+
*
|
|
169
|
+
* - No `isId`, no `id` property → the admin resolves no address, warns in the
|
|
170
|
+
* console, and rows cannot be opened or linked.
|
|
171
|
+
* - No `isId`, but an `id` property that is *not* the key → the admin addresses
|
|
172
|
+
* rows by `id` while this driver reads the address as the real key. Nothing
|
|
173
|
+
* errors: the addresses look right and route wrong.
|
|
174
|
+
*/
|
|
175
|
+
export function findUnresolvableKeyCollections(
|
|
176
|
+
collections: CollectionConfig[],
|
|
177
|
+
registry: PostgresCollectionRegistry
|
|
178
|
+
): { collection: CollectionConfig; keys: PrimaryKeyInfo[]; shadowedByIdProperty: boolean }[] {
|
|
179
|
+
const findings: { collection: CollectionConfig; keys: PrimaryKeyInfo[]; shadowedByIdProperty: boolean }[] = [];
|
|
119
180
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
throw new Error(`Composite ID parts mismatch. Expected ${primaryKeys.length}, got ${parts.length} for ID: ${idValue}`);
|
|
124
|
-
}
|
|
181
|
+
for (const collection of collections) {
|
|
182
|
+
// Declared `isId` is the tier both sides share: if it is there, they agree.
|
|
183
|
+
if (getDeclaredPrimaryKeys(collection).length > 0) continue;
|
|
125
184
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
const
|
|
129
|
-
if (
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
185
|
+
// No registered table resolves to no keys, and a collection this cannot
|
|
186
|
+
// resolve a key for is one it has nothing to say about.
|
|
187
|
+
const keys = getPrimaryKeys(collection, registry);
|
|
188
|
+
if (keys.length === 0) continue;
|
|
189
|
+
|
|
190
|
+
// A single key named `id` is the last tier on both sides: they agree
|
|
191
|
+
// without anything being declared.
|
|
192
|
+
if (keys.length === 1 && keys[0].fieldName === "id") continue;
|
|
193
|
+
|
|
194
|
+
findings.push({
|
|
195
|
+
collection,
|
|
196
|
+
keys,
|
|
197
|
+
shadowedByIdProperty: Boolean(collection.properties?.id)
|
|
198
|
+
});
|
|
138
199
|
}
|
|
139
200
|
|
|
140
|
-
return
|
|
201
|
+
return findings;
|
|
141
202
|
}
|
|
142
203
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
204
|
+
/**
|
|
205
|
+
* Report the collections from {@link findUnresolvableKeyCollections} at boot,
|
|
206
|
+
* with the edit that fixes each one.
|
|
207
|
+
*
|
|
208
|
+
* Grouped by failure, not by collection: the shadowed case is a routing bug and
|
|
209
|
+
* the silent case is a missing feature, and they deserve different urgency.
|
|
210
|
+
*/
|
|
211
|
+
export function warnOnKeysTheAdminCannotResolve(
|
|
212
|
+
collections: CollectionConfig[],
|
|
213
|
+
registry: PostgresCollectionRegistry
|
|
214
|
+
): void {
|
|
215
|
+
const findings = findUnresolvableKeyCollections(collections, registry);
|
|
216
|
+
if (findings.length === 0) return;
|
|
217
|
+
|
|
218
|
+
const edit = (f: { collection: CollectionConfig; keys: PrimaryKeyInfo[] }) =>
|
|
219
|
+
`${f.collection.slug}: mark ${f.keys.map(k => `\`${k.fieldName}\``).join(" and ")} with ` +
|
|
220
|
+
`\`isId: ${f.keys[0].isUUID ? "\"uuid\"" : f.keys[0].type === "number" ? "\"increment\"" : "true"}\``;
|
|
221
|
+
|
|
222
|
+
const shadowed = findings.filter(f => f.shadowedByIdProperty);
|
|
223
|
+
const silent = findings.filter(f => !f.shadowedByIdProperty);
|
|
224
|
+
|
|
225
|
+
if (shadowed.length > 0) {
|
|
226
|
+
logger.warn(
|
|
227
|
+
`⚠️ These collections declare no \`isId\`, and their key is only in the drizzle schema — but they ` +
|
|
228
|
+
`do have a property called \`id\`. The admin has no way to know \`id\` is not the key, so it will ` +
|
|
229
|
+
`address rows by it while this server reads the address as the real key: the links look right and ` +
|
|
230
|
+
`route wrong. Nothing will error.\n\n` +
|
|
231
|
+
shadowed.map(f => ` • ${edit(f)}`).join("\n") + "\n"
|
|
232
|
+
);
|
|
146
233
|
}
|
|
147
|
-
|
|
148
|
-
|
|
234
|
+
|
|
235
|
+
if (silent.length > 0) {
|
|
236
|
+
logger.warn(
|
|
237
|
+
`⚠️ These collections declare no \`isId\`, and their key is only in the drizzle schema, which the ` +
|
|
238
|
+
`admin never sees. It will resolve no address for their rows, so detail links, caching and ` +
|
|
239
|
+
`relations will not work for them:\n\n` +
|
|
240
|
+
silent.map(f => ` • ${edit(f)}`).join("\n") + "\n"
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* The address of a row: derived from the collection's primary keys, because a
|
|
247
|
+
* row does not carry one — it is exactly its columns.
|
|
248
|
+
*
|
|
249
|
+
* Falls back to a literal `id` column, for a row that reached us from somewhere
|
|
250
|
+
* other than this driver. Returns `""` when there is no key and no `id` —
|
|
251
|
+
* callers decide what that means, since "unaddressable" is a different answer
|
|
252
|
+
* in a notification (broadcast a wildcard) than in a save (fail).
|
|
253
|
+
*/
|
|
254
|
+
export function deriveRowAddress(
|
|
255
|
+
row: Record<string, unknown>,
|
|
256
|
+
collection: CollectionConfig,
|
|
257
|
+
registry: PostgresCollectionRegistry
|
|
258
|
+
): string {
|
|
259
|
+
const composite = buildCompositeId(row, getPrimaryKeys(collection, registry));
|
|
260
|
+
// An all-empty composite is indistinguishable from a missing key, and
|
|
261
|
+
// `buildCompositeId` returns "" for no keys at all.
|
|
262
|
+
if (composite && composite.split(COMPOSITE_ID_SEPARATOR).some(part => part !== "")) {
|
|
263
|
+
return composite;
|
|
149
264
|
}
|
|
150
|
-
|
|
265
|
+
if (row.id !== undefined && row.id !== null) return String(row.id);
|
|
266
|
+
return "";
|
|
151
267
|
}
|
|
268
|
+
|
|
@@ -154,9 +154,10 @@ export class DataService implements DataRepository {
|
|
|
154
154
|
collectionPath: string,
|
|
155
155
|
values: Partial<M>,
|
|
156
156
|
id?: string | number,
|
|
157
|
-
databaseId?: string
|
|
157
|
+
databaseId?: string,
|
|
158
|
+
options?: { upsert?: boolean }
|
|
158
159
|
): Promise<Record<string, unknown>> {
|
|
159
|
-
return this.persistService.save<M>(collectionPath, values, id, databaseId);
|
|
160
|
+
return this.persistService.save<M>(collectionPath, values, id, databaseId, options);
|
|
160
161
|
}
|
|
161
162
|
|
|
162
163
|
/**
|