@ingram-tech/nk-db 2.1.3 → 2.3.0
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 +42 -4
- package/dist/fingerprint-bin.d.ts +3 -0
- package/dist/fingerprint-bin.d.ts.map +1 -0
- package/dist/fingerprint-bin.js +86 -0
- package/dist/fingerprint-bin.js.map +1 -0
- package/dist/fingerprint.d.ts +61 -0
- package/dist/fingerprint.d.ts.map +1 -0
- package/dist/fingerprint.js +201 -0
- package/dist/fingerprint.js.map +1 -0
- package/dist/pglite/index.d.ts +12 -2
- package/dist/pglite/index.d.ts.map +1 -1
- package/dist/pglite/index.js +11 -3
- package/dist/pglite/index.js.map +1 -1
- package/dist/pglite/socket-fix.d.ts +8 -0
- package/dist/pglite/socket-fix.d.ts.map +1 -0
- package/dist/pglite/socket-fix.js +177 -0
- package/dist/pglite/socket-fix.js.map +1 -0
- package/dist/pool.d.ts +2 -2
- package/dist/pool.js +4 -4
- package/dist/pool.js.map +1 -1
- package/package.json +9 -4
- package/src/fingerprint-bin.ts +100 -0
- package/src/fingerprint.ts +291 -0
- package/src/pglite/index.ts +20 -3
- package/src/pglite/socket-fix.ts +204 -0
- package/src/pool.ts +4 -4
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
// Catalog-level schema fingerprint: the squash / baseline equivalence gate.
|
|
2
|
+
//
|
|
3
|
+
// A normalized JSON view of everything a schema is made of, including what
|
|
4
|
+
// drizzle's snapshot cannot model (functions, triggers, grants, policies,
|
|
5
|
+
// ownership, DEFERRABLE clauses, roles), so two databases can be diffed
|
|
6
|
+
// structurally. Two sources: a fresh in-memory PGlite booted from a migration
|
|
7
|
+
// chain, or a live database. Diff set-wise per key, never positionally:
|
|
8
|
+
// identifier collation differs between PGlite and a server, so a textual diff
|
|
9
|
+
// is sort noise.
|
|
10
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
11
|
+
import { createRequire } from "node:module";
|
|
12
|
+
import { join, resolve } from "node:path";
|
|
13
|
+
import type { Pool } from "pg";
|
|
14
|
+
import { createPool, type CreatePoolConfig } from "./pool.js";
|
|
15
|
+
|
|
16
|
+
export interface FingerprintScope {
|
|
17
|
+
/** Schemas to cover. Default `["public"]`. */
|
|
18
|
+
schemas?: string[];
|
|
19
|
+
/**
|
|
20
|
+
* Roles whose ownership and grants matter (the app's RLS roles, a view
|
|
21
|
+
* owner). Ownership and ACL entries of other roles are ignored, because the
|
|
22
|
+
* migration role differs per environment.
|
|
23
|
+
*/
|
|
24
|
+
roles?: string[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type Fingerprint = Record<string, unknown[]>;
|
|
28
|
+
|
|
29
|
+
const DEFAULT_SCHEMAS = ["public"];
|
|
30
|
+
const DEFAULT_ROLES = ["anon", "authenticated", "service_role", "authenticator"];
|
|
31
|
+
|
|
32
|
+
const quoteList = (values: string[]): string =>
|
|
33
|
+
`in (${values.map((v) => `'${v.replace(/'/g, "''")}'`).join(",")})`;
|
|
34
|
+
|
|
35
|
+
/** The catalog queries, each returning one json value via json_agg with explicit ordering. */
|
|
36
|
+
export const fingerprintQueries = (
|
|
37
|
+
scope: FingerprintScope = {},
|
|
38
|
+
): Record<string, string> => {
|
|
39
|
+
const inSchemas = quoteList(scope.schemas ?? DEFAULT_SCHEMAS);
|
|
40
|
+
const inRoles = quoteList(scope.roles ?? DEFAULT_ROLES);
|
|
41
|
+
return {
|
|
42
|
+
schemas: `select coalesce(json_agg(s order by s.nspname), '[]') from (
|
|
43
|
+
select n.nspname, pg_get_userbyid(n.nspowner) as owner,
|
|
44
|
+
coalesce((select json_agg(x order by x) from unnest(n.nspacl::text[]) x), '[]'::json) as acl
|
|
45
|
+
from pg_namespace n where n.nspname ${inSchemas}) s`,
|
|
46
|
+
relowners: `select coalesce(json_agg(o order by o.rel), '[]') from (
|
|
47
|
+
select n.nspname || '.' || cl.relname as rel, cl.relkind::text as kind,
|
|
48
|
+
pg_get_userbyid(cl.relowner) as owner, coalesce(cl.reloptions::text, '') as options
|
|
49
|
+
from pg_class cl join pg_namespace n on n.oid = cl.relnamespace
|
|
50
|
+
where n.nspname ${inSchemas} and cl.relkind in ('r','p','v','m')
|
|
51
|
+
and pg_get_userbyid(cl.relowner) ${inRoles}) o`,
|
|
52
|
+
roles: `select coalesce(json_agg(r order by r.rolname), '[]') from (
|
|
53
|
+
select rolname, rolsuper, rolinherit, rolcanlogin, rolbypassrls from pg_roles where rolname ${inRoles}) r`,
|
|
54
|
+
enums: `select coalesce(json_agg(e order by e.typname, e.sort), '[]') from (
|
|
55
|
+
select t.typname, en.enumsortorder as sort, en.enumlabel
|
|
56
|
+
from pg_type t join pg_namespace n on n.oid = t.typnamespace join pg_enum en on en.enumtypid = t.oid
|
|
57
|
+
where n.nspname ${inSchemas}) e`,
|
|
58
|
+
columns: `select coalesce(json_agg(c order by c.rel, c.col), '[]') from (
|
|
59
|
+
select n.nspname || '.' || cl.relname as rel, a.attname as col,
|
|
60
|
+
format_type(a.atttypid, a.atttypmod) as type, a.attnotnull as notnull,
|
|
61
|
+
pg_get_expr(d.adbin, d.adrelid) as default, a.attidentity as identity, a.attgenerated as generated
|
|
62
|
+
from pg_attribute a join pg_class cl on cl.oid = a.attrelid join pg_namespace n on n.oid = cl.relnamespace
|
|
63
|
+
left join pg_attrdef d on d.adrelid = a.attrelid and d.adnum = a.attnum
|
|
64
|
+
where n.nspname ${inSchemas} and cl.relkind in ('r','p') and a.attnum > 0 and not a.attisdropped) c`,
|
|
65
|
+
constraints: `select coalesce(json_agg(c order by c.rel, c.name), '[]') from (
|
|
66
|
+
select co.conrelid::regclass::text as rel, co.conname as name, pg_get_constraintdef(co.oid) as def
|
|
67
|
+
from pg_constraint co join pg_namespace n on n.oid = co.connamespace where n.nspname ${inSchemas}) c`,
|
|
68
|
+
indexes: `select coalesce(json_agg(i order by i.indexname), '[]') from (
|
|
69
|
+
select schemaname, tablename, indexname, indexdef from pg_indexes where schemaname ${inSchemas}) i`,
|
|
70
|
+
triggers: `select coalesce(json_agg(t order by t.rel, t.name), '[]') from (
|
|
71
|
+
select tg.tgrelid::regclass::text as rel, tg.tgname as name, pg_get_triggerdef(tg.oid) as def
|
|
72
|
+
from pg_trigger tg join pg_class cl on cl.oid = tg.tgrelid join pg_namespace n on n.oid = cl.relnamespace
|
|
73
|
+
where n.nspname ${inSchemas} and not tg.tgisinternal) t`,
|
|
74
|
+
functions: `select coalesce(json_agg(f order by f.schema, f.name, f.args), '[]') from (
|
|
75
|
+
select n.nspname as schema, p.proname as name, pg_get_function_identity_arguments(p.oid) as args,
|
|
76
|
+
pg_get_functiondef(p.oid) as def
|
|
77
|
+
from pg_proc p join pg_namespace n on n.oid = p.pronamespace
|
|
78
|
+
where n.nspname ${inSchemas} and p.prokind in ('f','p')
|
|
79
|
+
and not exists (select 1 from pg_depend dep where dep.objid = p.oid and dep.deptype = 'e')) f`,
|
|
80
|
+
policies: `select coalesce(json_agg(p order by p.tablename, p.policyname), '[]') from (
|
|
81
|
+
select schemaname, tablename, policyname, permissive, roles::text[] as roles, cmd, qual, with_check
|
|
82
|
+
from pg_policies where schemaname ${inSchemas}) p`,
|
|
83
|
+
rls: `select coalesce(json_agg(r order by r.rel), '[]') from (
|
|
84
|
+
select n.nspname || '.' || cl.relname as rel, cl.relrowsecurity as enabled, cl.relforcerowsecurity as forced
|
|
85
|
+
from pg_class cl join pg_namespace n on n.oid = cl.relnamespace where n.nspname ${inSchemas} and cl.relkind = 'r') r`,
|
|
86
|
+
views: `select coalesce(json_agg(v order by v.schemaname, v.viewname), '[]') from (
|
|
87
|
+
select vw.schemaname, vw.viewname, vw.definition
|
|
88
|
+
from pg_views vw join pg_class cl on cl.relname = vw.viewname
|
|
89
|
+
join pg_namespace n on n.oid = cl.relnamespace and n.nspname = vw.schemaname
|
|
90
|
+
where vw.schemaname ${inSchemas}
|
|
91
|
+
and not exists (select 1 from pg_depend dep where dep.objid = cl.oid and dep.deptype = 'e')) v`,
|
|
92
|
+
sequences: `select coalesce(json_agg(s order by s.sequencename), '[]') from (
|
|
93
|
+
select schemaname, sequencename, data_type::text, start_value, min_value, max_value, increment_by, cycle
|
|
94
|
+
from pg_sequences where schemaname ${inSchemas}) s`,
|
|
95
|
+
// ACLs from pg_class / pg_proc via aclexplode, not information_schema,
|
|
96
|
+
// whose role_*_grants views hide rows whose grantor is not an enabled
|
|
97
|
+
// role for the connecting user. The grantor is environment-specific and
|
|
98
|
+
// omitted.
|
|
99
|
+
table_grants: `select coalesce(json_agg(g order by g.table_schema, g.table_name, g.grantee, g.privilege_type), '[]') from (
|
|
100
|
+
select distinct n.nspname as table_schema, cl.relname as table_name,
|
|
101
|
+
acl.grantee::regrole::text as grantee, acl.privilege_type
|
|
102
|
+
from pg_class cl join pg_namespace n on n.oid = cl.relnamespace, lateral aclexplode(cl.relacl) acl
|
|
103
|
+
where n.nspname ${inSchemas} and cl.relkind in ('r','p','v','m')
|
|
104
|
+
and acl.grantee::regrole::text ${inRoles}) g`,
|
|
105
|
+
routine_grants: `select coalesce(json_agg(g order by g.routine, g.grantee), '[]') from (
|
|
106
|
+
select distinct n.nspname || '.' || p.proname as routine, acl.grantee::regrole::text as grantee, acl.privilege_type
|
|
107
|
+
from pg_proc p join pg_namespace n on n.oid = p.pronamespace, lateral aclexplode(p.proacl) acl
|
|
108
|
+
where n.nspname ${inSchemas} and acl.grantee::regrole::text ${inRoles}) g`,
|
|
109
|
+
default_acls: `select coalesce(json_agg(d order by d.role, d.schema, d.objtype), '[]') from (
|
|
110
|
+
select defaclrole::regrole::text as role, coalesce(defaclnamespace::regnamespace::text, '') as schema,
|
|
111
|
+
defaclobjtype as objtype, defaclacl::text as acl from pg_default_acl) d`,
|
|
112
|
+
};
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
type Queryable = Pick<Pool, "query">;
|
|
116
|
+
|
|
117
|
+
const collect = async (
|
|
118
|
+
run: (sql: string) => Promise<unknown>,
|
|
119
|
+
scope: FingerprintScope,
|
|
120
|
+
): Promise<Fingerprint> => {
|
|
121
|
+
const out: Fingerprint = {};
|
|
122
|
+
for (const [name, sql] of Object.entries(fingerprintQueries(scope))) {
|
|
123
|
+
const value = await run(sql);
|
|
124
|
+
out[name] = Array.isArray(value) ? value : [];
|
|
125
|
+
}
|
|
126
|
+
return out;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const firstColumn = async (db: Queryable, sql: string): Promise<unknown> => {
|
|
130
|
+
const { rows } = await db.query<Record<string, unknown>>(sql);
|
|
131
|
+
return Object.values(rows[0] ?? {})[0];
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
export type FingerprintDatabaseOptions = FingerprintScope &
|
|
135
|
+
CreatePoolConfig & {
|
|
136
|
+
/** Reuse a pool instead of creating one from the connection string. Not ended here. */
|
|
137
|
+
pool?: Pool;
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
/** Fingerprint a live database (connection from the env contract, a URL, or a pool). */
|
|
141
|
+
export const fingerprintDatabase = async (
|
|
142
|
+
options: FingerprintDatabaseOptions = {},
|
|
143
|
+
): Promise<Fingerprint> => {
|
|
144
|
+
const pool = options.pool ?? createPool(options);
|
|
145
|
+
try {
|
|
146
|
+
return await collect((sql) => firstColumn(pool, sql), options);
|
|
147
|
+
} finally {
|
|
148
|
+
if (!options.pool) await pool.end();
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
export interface FingerprintChainOptions extends FingerprintScope {
|
|
153
|
+
/** The chain to apply. Default `drizzle`. */
|
|
154
|
+
migrationsFolder?: string;
|
|
155
|
+
/** Chains applied before it (nk-auth's `migrations/`), in order. */
|
|
156
|
+
dependencyMigrations?: string[];
|
|
157
|
+
/** Install nk-db's id codec functions first, as `createTestDb` does. Default false. */
|
|
158
|
+
id758?: boolean;
|
|
159
|
+
/** PGlite extensions to load (`{ vector }` from `@electric-sql/pglite-pgvector`). */
|
|
160
|
+
extensions?: Record<string, unknown>;
|
|
161
|
+
/** SQL the server had before the chain ran (`create extension if not exists vector`). */
|
|
162
|
+
pre?: string[];
|
|
163
|
+
/**
|
|
164
|
+
* Directory whose `package.json` anchors the `@electric-sql/pglite` import
|
|
165
|
+
* (a site workspace that depends on it). Without it the peer resolves from
|
|
166
|
+
* nk-db's own install, which an isolated linker only satisfies when the
|
|
167
|
+
* depending workspace also lists the peer.
|
|
168
|
+
*/
|
|
169
|
+
resolveFrom?: string;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const loadPglite = async (
|
|
173
|
+
from?: string,
|
|
174
|
+
): Promise<typeof import("@electric-sql/pglite")> => {
|
|
175
|
+
if (from !== undefined) {
|
|
176
|
+
const req = createRequire(join(resolve(from), "package.json"));
|
|
177
|
+
return (await import(
|
|
178
|
+
req.resolve("@electric-sql/pglite")
|
|
179
|
+
)) as typeof import("@electric-sql/pglite");
|
|
180
|
+
}
|
|
181
|
+
return import("@electric-sql/pglite");
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
/** The `.sql` files of a chain folder in journal order (sorted names without a journal). */
|
|
185
|
+
export const chainFiles = (folder: string): string[] => {
|
|
186
|
+
try {
|
|
187
|
+
const journal = JSON.parse(
|
|
188
|
+
readFileSync(join(folder, "meta", "_journal.json"), "utf8"),
|
|
189
|
+
) as { entries: Array<{ tag: string }> };
|
|
190
|
+
return journal.entries.map((e) => join(folder, `${e.tag}.sql`));
|
|
191
|
+
} catch {
|
|
192
|
+
return readdirSync(folder)
|
|
193
|
+
.filter((f) => f.endsWith(".sql"))
|
|
194
|
+
.sort()
|
|
195
|
+
.map((f) => join(folder, f));
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Fingerprint a fresh in-memory PGlite booted from a chain. Every file is
|
|
201
|
+
* exec'd whole, in journal order: drizzle's migrator sends a file as one
|
|
202
|
+
* query, which a pg_dump-derived baseline (no breakpoints, `DO $$` blocks,
|
|
203
|
+
* `SET LOCAL ROLE`) is not. `@electric-sql/pglite` is the optional peer.
|
|
204
|
+
*/
|
|
205
|
+
export const fingerprintChain = async (
|
|
206
|
+
options: FingerprintChainOptions = {},
|
|
207
|
+
): Promise<Fingerprint> => {
|
|
208
|
+
const { PGlite } = await loadPglite(options.resolveFrom);
|
|
209
|
+
const db = new PGlite({ extensions: (options.extensions ?? {}) as never });
|
|
210
|
+
try {
|
|
211
|
+
if (options.id758) {
|
|
212
|
+
const { ID758_SQL } = await import("id758/sql");
|
|
213
|
+
await db.exec(ID758_SQL);
|
|
214
|
+
}
|
|
215
|
+
for (const sql of options.pre ?? []) await db.exec(sql);
|
|
216
|
+
const folders = [
|
|
217
|
+
...(options.dependencyMigrations ?? []),
|
|
218
|
+
options.migrationsFolder ?? "drizzle",
|
|
219
|
+
].map((f) => resolve(f));
|
|
220
|
+
for (const folder of folders) {
|
|
221
|
+
for (const file of chainFiles(folder)) {
|
|
222
|
+
// PGlite does not persist a session SET across exec calls.
|
|
223
|
+
await db.exec(
|
|
224
|
+
`set search_path to public;\n${readFileSync(file, "utf8")}`,
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return await collect(
|
|
229
|
+
(sql) => firstColumn(db as unknown as Queryable, sql),
|
|
230
|
+
options,
|
|
231
|
+
);
|
|
232
|
+
} finally {
|
|
233
|
+
await db.close();
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
export interface FingerprintDifference {
|
|
238
|
+
key: string;
|
|
239
|
+
/** Entries only the first fingerprint has, as canonical JSON. */
|
|
240
|
+
onlyA: string[];
|
|
241
|
+
/** Entries only the second fingerprint has, as canonical JSON. */
|
|
242
|
+
onlyB: string[];
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const canonical = (value: unknown): string =>
|
|
246
|
+
JSON.stringify(value, (_key, v: unknown) =>
|
|
247
|
+
v !== null && typeof v === "object" && !Array.isArray(v)
|
|
248
|
+
? Object.fromEntries(
|
|
249
|
+
Object.entries(v as Record<string, unknown>).sort(([a], [b]) =>
|
|
250
|
+
a.localeCompare(b),
|
|
251
|
+
),
|
|
252
|
+
)
|
|
253
|
+
: v,
|
|
254
|
+
);
|
|
255
|
+
|
|
256
|
+
/** Set-wise, per-key difference between two fingerprints; empty when equivalent. */
|
|
257
|
+
export const diffFingerprints = (
|
|
258
|
+
a: Fingerprint,
|
|
259
|
+
b: Fingerprint,
|
|
260
|
+
): FingerprintDifference[] => {
|
|
261
|
+
const keys = [...new Set([...Object.keys(a), ...Object.keys(b)])].sort();
|
|
262
|
+
const out: FingerprintDifference[] = [];
|
|
263
|
+
for (const key of keys) {
|
|
264
|
+
const sa = new Set((a[key] ?? []).map(canonical));
|
|
265
|
+
const sb = new Set((b[key] ?? []).map(canonical));
|
|
266
|
+
const onlyA = [...sa].filter((x) => !sb.has(x)).sort();
|
|
267
|
+
const onlyB = [...sb].filter((x) => !sa.has(x)).sort();
|
|
268
|
+
if (onlyA.length > 0 || onlyB.length > 0) out.push({ key, onlyA, onlyB });
|
|
269
|
+
}
|
|
270
|
+
return out;
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
/** Human-readable rendering of a diff, `limit` entries per side per key. */
|
|
274
|
+
export const formatFingerprintDiff = (
|
|
275
|
+
differences: FingerprintDifference[],
|
|
276
|
+
labels: [string, string] = ["a", "b"],
|
|
277
|
+
limit = 12,
|
|
278
|
+
): string => {
|
|
279
|
+
const lines: string[] = [];
|
|
280
|
+
let total = 0;
|
|
281
|
+
for (const d of differences) {
|
|
282
|
+
total += d.onlyA.length + d.onlyB.length;
|
|
283
|
+
lines.push(
|
|
284
|
+
`## ${d.key}: only in ${labels[0]}: ${d.onlyA.length}, only in ${labels[1]}: ${d.onlyB.length}`,
|
|
285
|
+
);
|
|
286
|
+
for (const x of d.onlyA.slice(0, limit)) lines.push(` - ${x}`);
|
|
287
|
+
for (const x of d.onlyB.slice(0, limit)) lines.push(` + ${x}`);
|
|
288
|
+
}
|
|
289
|
+
lines.push(`TOTAL DIFFS ${total}`);
|
|
290
|
+
return lines.join("\n");
|
|
291
|
+
};
|
package/src/pglite/index.ts
CHANGED
|
@@ -16,6 +16,7 @@ import { PGLiteSocketServer } from "@electric-sql/pglite-socket";
|
|
|
16
16
|
import { ID758_SQL } from "id758/sql";
|
|
17
17
|
import type { Pool } from "pg";
|
|
18
18
|
import { resetPublicTables } from "./reset.js";
|
|
19
|
+
import { isolateConnections } from "./socket-fix.js";
|
|
19
20
|
|
|
20
21
|
export interface PgliteServerOptions {
|
|
21
22
|
/** Persisted data dir; omit for an in-memory database (tests). */
|
|
@@ -65,6 +66,15 @@ export interface PgliteServerOptions {
|
|
|
65
66
|
* `CREATE EXTENSION` them: PGlite only knows the extensions passed here.
|
|
66
67
|
*/
|
|
67
68
|
extensions?: Extensions;
|
|
69
|
+
/**
|
|
70
|
+
* How many TCP connections the socket accepts. Default `20`. They share
|
|
71
|
+
* PGlite's one session, one message batch at a time (see `socket-fix.ts`),
|
|
72
|
+
* so this buys no parallelism: it is room for every pool `next dev` creates
|
|
73
|
+
* (one per module graph and process) and for a `psql` alongside. At `1`,
|
|
74
|
+
* pglite-socket's own default, the second pool is refused and its query
|
|
75
|
+
* fails with "Connection terminated unexpectedly".
|
|
76
|
+
*/
|
|
77
|
+
maxConnections?: number;
|
|
68
78
|
}
|
|
69
79
|
|
|
70
80
|
export interface PgliteServer {
|
|
@@ -120,8 +130,9 @@ const applyDependencyMigrations = async (
|
|
|
120
130
|
* Boot PGlite, apply migrations (on a fresh/in-memory db), and expose it over a
|
|
121
131
|
* TCP socket so a normal `pg.Pool` connects via `DATABASE_URL` with no app code
|
|
122
132
|
* changes. Reused by both `startPgliteDev` (persisted) and `createTestDb`
|
|
123
|
-
* (in-memory). The socket
|
|
124
|
-
* at `max: 1`
|
|
133
|
+
* (in-memory). The socket accepts several connections but serves them from one
|
|
134
|
+
* session, one batch at a time, so a pool above `max: 1` gains nothing
|
|
135
|
+
* (createPool caps local hosts at 1).
|
|
125
136
|
*/
|
|
126
137
|
export const createPgliteServer = async (
|
|
127
138
|
options: PgliteServerOptions = {},
|
|
@@ -153,7 +164,13 @@ export const createPgliteServer = async (
|
|
|
153
164
|
await applyDependencyMigrations(db, options.dependencyMigrations ?? []);
|
|
154
165
|
await (options.migrate ?? defaultMigrate(migrationsFolder))(db);
|
|
155
166
|
|
|
156
|
-
const server = new PGLiteSocketServer({
|
|
167
|
+
const server = new PGLiteSocketServer({
|
|
168
|
+
db,
|
|
169
|
+
host,
|
|
170
|
+
port,
|
|
171
|
+
maxConnections: options.maxConnections ?? 20,
|
|
172
|
+
});
|
|
173
|
+
isolateConnections(server, db);
|
|
157
174
|
await server.start();
|
|
158
175
|
const databaseUrl = `postgresql://postgres:postgres@${host}:${port}/postgres`;
|
|
159
176
|
const stop = async (): Promise<void> => {
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// Makes pglite-socket safe for more than one connection. PGlite is a single
|
|
2
|
+
// Postgres session, and pglite-socket 0.2.x shares it between connections by
|
|
3
|
+
// queueing their protocol messages one at a time, with connection affinity only
|
|
4
|
+
// inside a transaction. Two bugs follow once a second connection exists:
|
|
5
|
+
//
|
|
6
|
+
// - Two connections' Parse/Bind/Execute/Sync batches interleave and clobber
|
|
7
|
+
// each other's unnamed statement ("unexpected commandComplete"), and one
|
|
8
|
+
// failed message returns without clearing the queue's `processing` flag, so
|
|
9
|
+
// the queue stops for good (electric-sql/pglite#1046; upstream fixes are
|
|
10
|
+
// open as #977 and #1094).
|
|
11
|
+
// - PGlite answers an error inside an extended-protocol batch with
|
|
12
|
+
// ErrorResponse plus an early ReadyForQuery, then a second one on Sync
|
|
13
|
+
// (electric-sql/pglite#958). `pg` takes the early one as its next query's
|
|
14
|
+
// completion, and every later result is shifted by one.
|
|
15
|
+
//
|
|
16
|
+
// This replaces the queue loop: a connection that sends an extended-protocol
|
|
17
|
+
// message owns the session until its Sync, a transaction owns it until it
|
|
18
|
+
// ends, and an error rejects only its own message. It also drops the early
|
|
19
|
+
// ReadyForQuery.
|
|
20
|
+
//
|
|
21
|
+
// Delete once pglite-socket ships #977/#1094 and PGlite fixes #958. It patches
|
|
22
|
+
// a private field, so it checks the field's shape first and leaves the server
|
|
23
|
+
// untouched (with a warning) if a pglite-socket release has changed it.
|
|
24
|
+
|
|
25
|
+
import type { PGlite } from "@electric-sql/pglite";
|
|
26
|
+
import type { PGLiteSocketServer } from "@electric-sql/pglite-socket";
|
|
27
|
+
|
|
28
|
+
interface QueueItem {
|
|
29
|
+
handlerId: number;
|
|
30
|
+
message: Uint8Array;
|
|
31
|
+
resolve: (bytes: number) => void;
|
|
32
|
+
reject: (error: unknown) => void;
|
|
33
|
+
onData: (data: Uint8Array) => void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface QueryQueue {
|
|
37
|
+
queue: QueueItem[];
|
|
38
|
+
processing: boolean;
|
|
39
|
+
lastHandlerId: number | null;
|
|
40
|
+
processQueue: () => Promise<void>;
|
|
41
|
+
clearQueueForHandler: (handlerId: number) => void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const isQueryQueue = (value: unknown): value is QueryQueue =>
|
|
45
|
+
typeof value === "object" &&
|
|
46
|
+
value !== null &&
|
|
47
|
+
Array.isArray(Reflect.get(value, "queue")) &&
|
|
48
|
+
typeof Reflect.get(value, "processing") === "boolean" &&
|
|
49
|
+
typeof Reflect.get(value, "processQueue") === "function" &&
|
|
50
|
+
typeof Reflect.get(value, "clearQueueForHandler") === "function";
|
|
51
|
+
|
|
52
|
+
const code = (c: string): number => c.charCodeAt(0);
|
|
53
|
+
// Parse, Bind, Describe, Execute, Flush, Close: a batch stays open until Sync.
|
|
54
|
+
const EXTENDED = new Set([..."PBDEHC"].map(code));
|
|
55
|
+
const SYNC = code("S");
|
|
56
|
+
const ERROR_RESPONSE = code("E");
|
|
57
|
+
const READY_FOR_QUERY = code("Z");
|
|
58
|
+
|
|
59
|
+
/** Drop ReadyForQuery from a reply that carries an ErrorResponse; the batch's
|
|
60
|
+
* Sync sends the one Postgres would have sent. */
|
|
61
|
+
const dropEarlyReadyForQuery = (reply: Buffer): Buffer => {
|
|
62
|
+
const messages: Buffer[] = [];
|
|
63
|
+
for (let o = 0; o + 5 <= reply.length; o += 1 + reply.readInt32BE(o + 1)) {
|
|
64
|
+
messages.push(reply.subarray(o, o + 1 + reply.readInt32BE(o + 1)));
|
|
65
|
+
}
|
|
66
|
+
if (!messages.some((m) => m[0] === ERROR_RESPONSE)) return reply;
|
|
67
|
+
return Buffer.concat(messages.filter((m) => m[0] !== READY_FOR_QUERY));
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** First line of the SQL in a Query (`sql\0`) or Parse (`name\0sql\0…`). */
|
|
71
|
+
const sqlOf = (message: Uint8Array): string => {
|
|
72
|
+
const parts = Buffer.from(message).toString("utf8", 5).split("\0");
|
|
73
|
+
const sql = message[0] === code("Q") ? parts[0] : parts[1];
|
|
74
|
+
return (sql ?? "").replace(/\s+/g, " ").slice(0, 160);
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Patch `server`'s query queue so several connections can share `db` safely.
|
|
79
|
+
* Call before `server.start()`. Returns whether the patch was applied.
|
|
80
|
+
*/
|
|
81
|
+
export const isolateConnections = (server: PGLiteSocketServer, db: PGlite): boolean => {
|
|
82
|
+
const q: unknown = Reflect.get(server, "queryQueue");
|
|
83
|
+
if (!isQueryQueue(q)) {
|
|
84
|
+
console.warn(
|
|
85
|
+
"nk(pglite): pglite-socket's query queue has an unexpected shape; " +
|
|
86
|
+
"running it unpatched, so concurrent connections may interleave.",
|
|
87
|
+
);
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
let batchOwner: number | null = null;
|
|
91
|
+
|
|
92
|
+
// One session means a connection holding a transaction blocks every other
|
|
93
|
+
// connection until it commits. If app code awaits a second connection from
|
|
94
|
+
// inside that transaction, nothing moves again; say so instead of hanging
|
|
95
|
+
// silently.
|
|
96
|
+
const lastSql = new Map<number, string>();
|
|
97
|
+
let stalledSince: number | null = null;
|
|
98
|
+
let stalledOwner: number | null = null;
|
|
99
|
+
// A deadlock never clears itself, so the warning backs off (5s, 10s, 20s…
|
|
100
|
+
// capped at a minute) instead of repeating every 5s for the rest of the run.
|
|
101
|
+
let warnGap = 5000;
|
|
102
|
+
let warnAt = 0;
|
|
103
|
+
let stallTimer: ReturnType<typeof setTimeout> | undefined;
|
|
104
|
+
const armStallCheck = (): void => {
|
|
105
|
+
stallTimer = setTimeout(checkStall, Math.max(0, warnAt - Date.now()));
|
|
106
|
+
stallTimer.unref?.();
|
|
107
|
+
};
|
|
108
|
+
const checkStall = (): void => {
|
|
109
|
+
stallTimer = undefined;
|
|
110
|
+
if (stalledSince === null || q.queue.length === 0) {
|
|
111
|
+
stalledSince = null;
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
// The stall that armed this timer may have ended and a newer one begun;
|
|
115
|
+
// then it is not yet due.
|
|
116
|
+
if (Date.now() >= warnAt) {
|
|
117
|
+
const seconds = Math.round((Date.now() - stalledSince) / 1000);
|
|
118
|
+
const waiting = q.queue
|
|
119
|
+
.map(
|
|
120
|
+
(i) => `#${i.handlerId}:${String.fromCharCode(i.message[0] ?? 63)}`,
|
|
121
|
+
)
|
|
122
|
+
.join(" ");
|
|
123
|
+
const holding = db.isInTransaction() ? "open transaction" : "open batch";
|
|
124
|
+
console.warn(
|
|
125
|
+
`nk(pglite): queue stalled ${seconds}s on connection #${stalledOwner} ` +
|
|
126
|
+
`(${holding}); its last SQL: ${lastSql.get(stalledOwner ?? -1) ?? "?"}; ` +
|
|
127
|
+
`waiting: ${waiting}. PGlite is one session: code that awaits ` +
|
|
128
|
+
"a second connection inside a transaction never finishes here.",
|
|
129
|
+
);
|
|
130
|
+
warnGap = Math.min(warnGap * 2, 60_000);
|
|
131
|
+
warnAt = Date.now() + warnGap;
|
|
132
|
+
}
|
|
133
|
+
armStallCheck();
|
|
134
|
+
};
|
|
135
|
+
const reportStall = (owner: number | null): void => {
|
|
136
|
+
stalledOwner = owner;
|
|
137
|
+
if (stalledSince === null) {
|
|
138
|
+
stalledSince = Date.now();
|
|
139
|
+
warnGap = 5000;
|
|
140
|
+
warnAt = stalledSince + warnGap;
|
|
141
|
+
}
|
|
142
|
+
// Arm once per stall: re-arming on every arrival would let steady traffic
|
|
143
|
+
// from the waiting connections postpone the warning forever.
|
|
144
|
+
if (stallTimer === undefined) armStallCheck();
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
q.processQueue = async (): Promise<void> => {
|
|
148
|
+
if (q.processing) return;
|
|
149
|
+
q.processing = true;
|
|
150
|
+
try {
|
|
151
|
+
while (q.queue.length > 0) {
|
|
152
|
+
const owner = db.isInTransaction() ? q.lastHandlerId : batchOwner;
|
|
153
|
+
const index =
|
|
154
|
+
owner === null
|
|
155
|
+
? 0
|
|
156
|
+
: q.queue.findIndex((i) => i.handlerId === owner);
|
|
157
|
+
// The owner's next message has not arrived; its arrival re-runs this.
|
|
158
|
+
if (index === -1) {
|
|
159
|
+
reportStall(owner);
|
|
160
|
+
break;
|
|
161
|
+
}
|
|
162
|
+
stalledSince = null;
|
|
163
|
+
const [item] = q.queue.splice(index, 1);
|
|
164
|
+
if (!item) break;
|
|
165
|
+
const type = item.message[0] ?? 0;
|
|
166
|
+
if (type === code("P") || type === code("Q")) {
|
|
167
|
+
lastSql.set(item.handlerId, sqlOf(item.message));
|
|
168
|
+
}
|
|
169
|
+
const chunks: Uint8Array[] = [];
|
|
170
|
+
try {
|
|
171
|
+
await db.runExclusive(() =>
|
|
172
|
+
db.execProtocolRawStream(item.message, {
|
|
173
|
+
onRawData: (data) => chunks.push(data.slice()),
|
|
174
|
+
}),
|
|
175
|
+
);
|
|
176
|
+
const raw = Buffer.concat(chunks);
|
|
177
|
+
const reply = EXTENDED.has(type)
|
|
178
|
+
? dropEarlyReadyForQuery(raw)
|
|
179
|
+
: raw;
|
|
180
|
+
if (reply.length > 0) item.onData(reply);
|
|
181
|
+
item.resolve(reply.length);
|
|
182
|
+
} catch (error) {
|
|
183
|
+
item.reject(error);
|
|
184
|
+
}
|
|
185
|
+
q.lastHandlerId = item.handlerId;
|
|
186
|
+
if (EXTENDED.has(type)) batchOwner = item.handlerId;
|
|
187
|
+
else if (type === SYNC) batchOwner = null;
|
|
188
|
+
}
|
|
189
|
+
} finally {
|
|
190
|
+
q.processing = false;
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
const clear = q.clearQueueForHandler.bind(q);
|
|
195
|
+
q.clearQueueForHandler = (handlerId: number): void => {
|
|
196
|
+
clear(handlerId);
|
|
197
|
+
lastSql.delete(handlerId);
|
|
198
|
+
if (batchOwner === handlerId) {
|
|
199
|
+
batchOwner = null;
|
|
200
|
+
void q.processQueue();
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
return true;
|
|
204
|
+
};
|
package/src/pool.ts
CHANGED
|
@@ -48,8 +48,8 @@ export const normalizeCaCert = (caCert: string | undefined): string | undefined
|
|
|
48
48
|
* `createAuthPool`):
|
|
49
49
|
*
|
|
50
50
|
* - `caCert` set -> verify the server cert + hostname (`sslmode=verify-full`).
|
|
51
|
-
* - local host -> no TLS, and cap at `max: 1` (the PGlite socket
|
|
52
|
-
*
|
|
51
|
+
* - local host -> no TLS, and cap at `max: 1` (the PGlite socket serves
|
|
52
|
+
* every connection from one session; more buys nothing).
|
|
53
53
|
* - otherwise -> TLS **without** chain verification. Managed certs (e.g.
|
|
54
54
|
* DigitalOcean) aren't in Node's trust store, so full
|
|
55
55
|
* verification fails with "self-signed certificate in
|
|
@@ -82,8 +82,8 @@ export const createPool = (config: CreatePoolConfig = {}): Pool => {
|
|
|
82
82
|
const caCert = normalizeCaCert(config.caCert ?? env?.caCert);
|
|
83
83
|
const local = isLocal(connectionString);
|
|
84
84
|
// Local wins over the env: a pulled .env (e.g. `vercel env pull`) carries the
|
|
85
|
-
// production DATABASE_POOL_MAX/DATABASE_CA_CERT, but the PGlite socket
|
|
86
|
-
//
|
|
85
|
+
// production DATABASE_POOL_MAX/DATABASE_CA_CERT, but the PGlite socket
|
|
86
|
+
// serves one session and speaks no TLS — honoring them breaks dev. An explicit
|
|
87
87
|
// `config.max` in code still applies.
|
|
88
88
|
const max = config.max ?? (local ? 1 : env?.poolMax);
|
|
89
89
|
|