@ingram-tech/nk-db 2.2.0 → 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 +11 -4
- 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 +3 -3
- package/src/pglite/index.ts +20 -3
- package/src/pglite/socket-fix.ts +204 -0
- package/src/pool.ts +4 -4
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ DATABASE_POOL_MAX=5 # optional; keep small on serverless
|
|
|
28
28
|
|
|
29
29
|
TLS is determined by the connection string and the CA cert, never by a flag: a
|
|
30
30
|
local host (`127.0.0.1`/`localhost`) gets no TLS and a `max: 1` pool (the
|
|
31
|
-
PGlite socket
|
|
31
|
+
PGlite socket serves one session; local detection also wins over a pulled
|
|
32
32
|
`DATABASE_POOL_MAX`/`DATABASE_CA_CERT`); with `DATABASE_CA_CERT` set the server
|
|
33
33
|
cert + hostname are verified; otherwise TLS runs without chain verification
|
|
34
34
|
(managed-provider certs aren't in Node's trust store).
|
|
@@ -300,15 +300,22 @@ Tests use an in-memory instance:
|
|
|
300
300
|
```ts
|
|
301
301
|
import { createTestDb } from "@ingram-tech/nk-db/pglite";
|
|
302
302
|
|
|
303
|
-
// Vitest: fileParallelism:false (
|
|
303
|
+
// Vitest: fileParallelism:false (PGlite is one session).
|
|
304
304
|
const { pool, db, reset, close } = await createTestDb({ migrationsFolder: "drizzle" });
|
|
305
305
|
// beforeEach(reset); afterAll(close);
|
|
306
306
|
```
|
|
307
307
|
|
|
308
308
|
## Gotchas it bakes in
|
|
309
309
|
|
|
310
|
-
- **Local pool is capped at `max:1`** —
|
|
311
|
-
|
|
310
|
+
- **Local pool is capped at `max:1`** — PGlite is one Postgres session. The
|
|
311
|
+
socket accepts up to `maxConnections` (default 20, room for the several pools
|
|
312
|
+
`next dev` creates) but runs one batch at a time, so a bigger pool gains
|
|
313
|
+
nothing.
|
|
314
|
+
- **Never await a second connection inside a transaction.** On PGlite the
|
|
315
|
+
transaction holds the only session, so the second query waits forever; the
|
|
316
|
+
socket logs `nk(pglite): queue stalled …` with the holder's last SQL. Prod
|
|
317
|
+
survives it but pins two connections per request. Do the extra lookup
|
|
318
|
+
before or after the transaction.
|
|
312
319
|
- **`pg.Pool` destroys a connection on a query *error*.** Don't catch unique
|
|
313
320
|
violations as control flow — use `INSERT … ON CONFLICT DO NOTHING RETURNING …`.
|
|
314
321
|
- **`jsonb` params:** `JSON.stringify()` the value and cast `$n::jsonb` (Drizzle's
|
package/dist/pglite/index.d.ts
CHANGED
|
@@ -49,6 +49,15 @@ export interface PgliteServerOptions {
|
|
|
49
49
|
* `CREATE EXTENSION` them: PGlite only knows the extensions passed here.
|
|
50
50
|
*/
|
|
51
51
|
extensions?: Extensions;
|
|
52
|
+
/**
|
|
53
|
+
* How many TCP connections the socket accepts. Default `20`. They share
|
|
54
|
+
* PGlite's one session, one message batch at a time (see `socket-fix.ts`),
|
|
55
|
+
* so this buys no parallelism: it is room for every pool `next dev` creates
|
|
56
|
+
* (one per module graph and process) and for a `psql` alongside. At `1`,
|
|
57
|
+
* pglite-socket's own default, the second pool is refused and its query
|
|
58
|
+
* fails with "Connection terminated unexpectedly".
|
|
59
|
+
*/
|
|
60
|
+
maxConnections?: number;
|
|
52
61
|
}
|
|
53
62
|
export interface PgliteServer {
|
|
54
63
|
db: PGlite;
|
|
@@ -61,8 +70,9 @@ export interface PgliteServer {
|
|
|
61
70
|
* Boot PGlite, apply migrations (on a fresh/in-memory db), and expose it over a
|
|
62
71
|
* TCP socket so a normal `pg.Pool` connects via `DATABASE_URL` with no app code
|
|
63
72
|
* changes. Reused by both `startPgliteDev` (persisted) and `createTestDb`
|
|
64
|
-
* (in-memory). The socket
|
|
65
|
-
* at `max: 1`
|
|
73
|
+
* (in-memory). The socket accepts several connections but serves them from one
|
|
74
|
+
* session, one batch at a time, so a pool above `max: 1` gains nothing
|
|
75
|
+
* (createPool caps local hosts at 1).
|
|
66
76
|
*/
|
|
67
77
|
export declare const createPgliteServer: (options?: PgliteServerOptions) => Promise<PgliteServer>;
|
|
68
78
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/pglite/index.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,MAAM,EAAE,KAAK,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAEjE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/pglite/index.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,MAAM,EAAE,KAAK,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAEjE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAI/B,MAAM,WAAW,mBAAmB;IACnC,kEAAkE;IAClE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,2DAA2D;IAC3D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,oEAAoE;IACpE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,wEAAwE;IACxE,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,4EAA4E;IAC5E,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;;;;;;;;OASG;IACH,oBAAoB,CAAC,EAAE,KAAK,CAAC;QAC5B,yEAAyE;QACzE,MAAM,EAA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import { PGlite } from "@electric-sql/pglite";
|
|
|
14
14
|
import { PGLiteSocketServer } from "@electric-sql/pglite-socket";
|
|
15
15
|
import { ID758_SQL } from "id758/sql";
|
|
16
16
|
import { resetPublicTables } from "./reset.js";
|
|
17
|
+
import { isolateConnections } from "./socket-fix.js";
|
|
17
18
|
/** Ask the OS for a currently-free TCP port (bind :0, read it back, release).
|
|
18
19
|
* Used so the test harness never collides with a dev Postgres on 5432. */
|
|
19
20
|
const freePort = (host) => new Promise((resolve, reject) => {
|
|
@@ -51,8 +52,9 @@ const applyDependencyMigrations = async (db, chains) => {
|
|
|
51
52
|
* Boot PGlite, apply migrations (on a fresh/in-memory db), and expose it over a
|
|
52
53
|
* TCP socket so a normal `pg.Pool` connects via `DATABASE_URL` with no app code
|
|
53
54
|
* changes. Reused by both `startPgliteDev` (persisted) and `createTestDb`
|
|
54
|
-
* (in-memory). The socket
|
|
55
|
-
* at `max: 1`
|
|
55
|
+
* (in-memory). The socket accepts several connections but serves them from one
|
|
56
|
+
* session, one batch at a time, so a pool above `max: 1` gains nothing
|
|
57
|
+
* (createPool caps local hosts at 1).
|
|
56
58
|
*/
|
|
57
59
|
export const createPgliteServer = async (options = {}) => {
|
|
58
60
|
const host = options.host ?? "127.0.0.1";
|
|
@@ -79,7 +81,13 @@ export const createPgliteServer = async (options = {}) => {
|
|
|
79
81
|
await db.exec(ID758_SQL);
|
|
80
82
|
await applyDependencyMigrations(db, options.dependencyMigrations ?? []);
|
|
81
83
|
await (options.migrate ?? defaultMigrate(migrationsFolder))(db);
|
|
82
|
-
const server = new PGLiteSocketServer({
|
|
84
|
+
const server = new PGLiteSocketServer({
|
|
85
|
+
db,
|
|
86
|
+
host,
|
|
87
|
+
port,
|
|
88
|
+
maxConnections: options.maxConnections ?? 20,
|
|
89
|
+
});
|
|
90
|
+
isolateConnections(server, db);
|
|
83
91
|
await server.start();
|
|
84
92
|
const databaseUrl = `postgresql://postgres:postgres@${host}:${port}/postgres`;
|
|
85
93
|
const stop = async () => {
|
package/dist/pglite/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/pglite/index.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,iFAAiF;AACjF,uEAAuE;AACvE,iFAAiF;AACjF,sBAAsB;AACtB,EAAE;AACF,8EAA8E;AAC9E,8EAA8E;AAC9E,2CAA2C;AAE3C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,MAAM,EAAmB,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/pglite/index.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,iFAAiF;AACjF,uEAAuE;AACvE,iFAAiF;AACjF,sBAAsB;AACtB,EAAE;AACF,8EAA8E;AAC9E,8EAA8E;AAC9E,2CAA2C;AAE3C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,MAAM,EAAmB,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAqErD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MAAM,IAAI,EAAE,CAAC;IACd,CAAC,CAAC;IACF,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AAC5C,CAAC,CAAC"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { PGlite } from "@electric-sql/pglite";
|
|
2
|
+
import type { PGLiteSocketServer } from "@electric-sql/pglite-socket";
|
|
3
|
+
/**
|
|
4
|
+
* Patch `server`'s query queue so several connections can share `db` safely.
|
|
5
|
+
* Call before `server.start()`. Returns whether the patch was applied.
|
|
6
|
+
*/
|
|
7
|
+
export declare const isolateConnections: (server: PGLiteSocketServer, db: PGlite) => boolean;
|
|
8
|
+
//# sourceMappingURL=socket-fix.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket-fix.d.ts","sourceRoot":"","sources":["../../src/pglite/socket-fix.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAmDtE;;;GAGG;AACH,eAAO,MAAM,kBAAkB,WAAY,kBAAkB,MAAM,MAAM,KAAG,OA2H3E,CAAC"}
|
|
@@ -0,0 +1,177 @@
|
|
|
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
|
+
const isQueryQueue = (value) => typeof value === "object" &&
|
|
25
|
+
value !== null &&
|
|
26
|
+
Array.isArray(Reflect.get(value, "queue")) &&
|
|
27
|
+
typeof Reflect.get(value, "processing") === "boolean" &&
|
|
28
|
+
typeof Reflect.get(value, "processQueue") === "function" &&
|
|
29
|
+
typeof Reflect.get(value, "clearQueueForHandler") === "function";
|
|
30
|
+
const code = (c) => c.charCodeAt(0);
|
|
31
|
+
// Parse, Bind, Describe, Execute, Flush, Close: a batch stays open until Sync.
|
|
32
|
+
const EXTENDED = new Set([..."PBDEHC"].map(code));
|
|
33
|
+
const SYNC = code("S");
|
|
34
|
+
const ERROR_RESPONSE = code("E");
|
|
35
|
+
const READY_FOR_QUERY = code("Z");
|
|
36
|
+
/** Drop ReadyForQuery from a reply that carries an ErrorResponse; the batch's
|
|
37
|
+
* Sync sends the one Postgres would have sent. */
|
|
38
|
+
const dropEarlyReadyForQuery = (reply) => {
|
|
39
|
+
const messages = [];
|
|
40
|
+
for (let o = 0; o + 5 <= reply.length; o += 1 + reply.readInt32BE(o + 1)) {
|
|
41
|
+
messages.push(reply.subarray(o, o + 1 + reply.readInt32BE(o + 1)));
|
|
42
|
+
}
|
|
43
|
+
if (!messages.some((m) => m[0] === ERROR_RESPONSE))
|
|
44
|
+
return reply;
|
|
45
|
+
return Buffer.concat(messages.filter((m) => m[0] !== READY_FOR_QUERY));
|
|
46
|
+
};
|
|
47
|
+
/** First line of the SQL in a Query (`sql\0`) or Parse (`name\0sql\0…`). */
|
|
48
|
+
const sqlOf = (message) => {
|
|
49
|
+
const parts = Buffer.from(message).toString("utf8", 5).split("\0");
|
|
50
|
+
const sql = message[0] === code("Q") ? parts[0] : parts[1];
|
|
51
|
+
return (sql ?? "").replace(/\s+/g, " ").slice(0, 160);
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Patch `server`'s query queue so several connections can share `db` safely.
|
|
55
|
+
* Call before `server.start()`. Returns whether the patch was applied.
|
|
56
|
+
*/
|
|
57
|
+
export const isolateConnections = (server, db) => {
|
|
58
|
+
const q = Reflect.get(server, "queryQueue");
|
|
59
|
+
if (!isQueryQueue(q)) {
|
|
60
|
+
console.warn("nk(pglite): pglite-socket's query queue has an unexpected shape; " +
|
|
61
|
+
"running it unpatched, so concurrent connections may interleave.");
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
let batchOwner = null;
|
|
65
|
+
// One session means a connection holding a transaction blocks every other
|
|
66
|
+
// connection until it commits. If app code awaits a second connection from
|
|
67
|
+
// inside that transaction, nothing moves again; say so instead of hanging
|
|
68
|
+
// silently.
|
|
69
|
+
const lastSql = new Map();
|
|
70
|
+
let stalledSince = null;
|
|
71
|
+
let stalledOwner = null;
|
|
72
|
+
// A deadlock never clears itself, so the warning backs off (5s, 10s, 20s…
|
|
73
|
+
// capped at a minute) instead of repeating every 5s for the rest of the run.
|
|
74
|
+
let warnGap = 5000;
|
|
75
|
+
let warnAt = 0;
|
|
76
|
+
let stallTimer;
|
|
77
|
+
const armStallCheck = () => {
|
|
78
|
+
stallTimer = setTimeout(checkStall, Math.max(0, warnAt - Date.now()));
|
|
79
|
+
stallTimer.unref?.();
|
|
80
|
+
};
|
|
81
|
+
const checkStall = () => {
|
|
82
|
+
stallTimer = undefined;
|
|
83
|
+
if (stalledSince === null || q.queue.length === 0) {
|
|
84
|
+
stalledSince = null;
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
// The stall that armed this timer may have ended and a newer one begun;
|
|
88
|
+
// then it is not yet due.
|
|
89
|
+
if (Date.now() >= warnAt) {
|
|
90
|
+
const seconds = Math.round((Date.now() - stalledSince) / 1000);
|
|
91
|
+
const waiting = q.queue
|
|
92
|
+
.map((i) => `#${i.handlerId}:${String.fromCharCode(i.message[0] ?? 63)}`)
|
|
93
|
+
.join(" ");
|
|
94
|
+
const holding = db.isInTransaction() ? "open transaction" : "open batch";
|
|
95
|
+
console.warn(`nk(pglite): queue stalled ${seconds}s on connection #${stalledOwner} ` +
|
|
96
|
+
`(${holding}); its last SQL: ${lastSql.get(stalledOwner ?? -1) ?? "?"}; ` +
|
|
97
|
+
`waiting: ${waiting}. PGlite is one session: code that awaits ` +
|
|
98
|
+
"a second connection inside a transaction never finishes here.");
|
|
99
|
+
warnGap = Math.min(warnGap * 2, 60_000);
|
|
100
|
+
warnAt = Date.now() + warnGap;
|
|
101
|
+
}
|
|
102
|
+
armStallCheck();
|
|
103
|
+
};
|
|
104
|
+
const reportStall = (owner) => {
|
|
105
|
+
stalledOwner = owner;
|
|
106
|
+
if (stalledSince === null) {
|
|
107
|
+
stalledSince = Date.now();
|
|
108
|
+
warnGap = 5000;
|
|
109
|
+
warnAt = stalledSince + warnGap;
|
|
110
|
+
}
|
|
111
|
+
// Arm once per stall: re-arming on every arrival would let steady traffic
|
|
112
|
+
// from the waiting connections postpone the warning forever.
|
|
113
|
+
if (stallTimer === undefined)
|
|
114
|
+
armStallCheck();
|
|
115
|
+
};
|
|
116
|
+
q.processQueue = async () => {
|
|
117
|
+
if (q.processing)
|
|
118
|
+
return;
|
|
119
|
+
q.processing = true;
|
|
120
|
+
try {
|
|
121
|
+
while (q.queue.length > 0) {
|
|
122
|
+
const owner = db.isInTransaction() ? q.lastHandlerId : batchOwner;
|
|
123
|
+
const index = owner === null
|
|
124
|
+
? 0
|
|
125
|
+
: q.queue.findIndex((i) => i.handlerId === owner);
|
|
126
|
+
// The owner's next message has not arrived; its arrival re-runs this.
|
|
127
|
+
if (index === -1) {
|
|
128
|
+
reportStall(owner);
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
stalledSince = null;
|
|
132
|
+
const [item] = q.queue.splice(index, 1);
|
|
133
|
+
if (!item)
|
|
134
|
+
break;
|
|
135
|
+
const type = item.message[0] ?? 0;
|
|
136
|
+
if (type === code("P") || type === code("Q")) {
|
|
137
|
+
lastSql.set(item.handlerId, sqlOf(item.message));
|
|
138
|
+
}
|
|
139
|
+
const chunks = [];
|
|
140
|
+
try {
|
|
141
|
+
await db.runExclusive(() => db.execProtocolRawStream(item.message, {
|
|
142
|
+
onRawData: (data) => chunks.push(data.slice()),
|
|
143
|
+
}));
|
|
144
|
+
const raw = Buffer.concat(chunks);
|
|
145
|
+
const reply = EXTENDED.has(type)
|
|
146
|
+
? dropEarlyReadyForQuery(raw)
|
|
147
|
+
: raw;
|
|
148
|
+
if (reply.length > 0)
|
|
149
|
+
item.onData(reply);
|
|
150
|
+
item.resolve(reply.length);
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
item.reject(error);
|
|
154
|
+
}
|
|
155
|
+
q.lastHandlerId = item.handlerId;
|
|
156
|
+
if (EXTENDED.has(type))
|
|
157
|
+
batchOwner = item.handlerId;
|
|
158
|
+
else if (type === SYNC)
|
|
159
|
+
batchOwner = null;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
finally {
|
|
163
|
+
q.processing = false;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
const clear = q.clearQueueForHandler.bind(q);
|
|
167
|
+
q.clearQueueForHandler = (handlerId) => {
|
|
168
|
+
clear(handlerId);
|
|
169
|
+
lastSql.delete(handlerId);
|
|
170
|
+
if (batchOwner === handlerId) {
|
|
171
|
+
batchOwner = null;
|
|
172
|
+
void q.processQueue();
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
return true;
|
|
176
|
+
};
|
|
177
|
+
//# sourceMappingURL=socket-fix.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket-fix.js","sourceRoot":"","sources":["../../src/pglite/socket-fix.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,6EAA6E;AAC7E,gFAAgF;AAChF,yEAAyE;AACzE,EAAE;AACF,6EAA6E;AAC7E,4EAA4E;AAC5E,+EAA+E;AAC/E,4EAA4E;AAC5E,8BAA8B;AAC9B,oEAAoE;AACpE,0EAA0E;AAC1E,6EAA6E;AAC7E,2DAA2D;AAC3D,EAAE;AACF,6EAA6E;AAC7E,0EAA0E;AAC1E,2EAA2E;AAC3E,iBAAiB;AACjB,EAAE;AACF,+EAA+E;AAC/E,8EAA8E;AAC9E,wEAAwE;AAqBxE,MAAM,YAAY,GAAG,CAAC,KAAc,EAAuB,EAAE,CAC5D,OAAO,KAAK,KAAK,QAAQ;IACzB,KAAK,KAAK,IAAI;IACd,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC1C,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,YAAY,CAAC,KAAK,SAAS;IACrD,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,cAAc,CAAC,KAAK,UAAU;IACxD,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,sBAAsB,CAAC,KAAK,UAAU,CAAC;AAElE,MAAM,IAAI,GAAG,CAAC,CAAS,EAAU,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AACpD,+EAA+E;AAC/E,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;AAClD,MAAM,IAAI,GAAG,IAAI,CAAC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AAoB,GAAG,CAAC,SAAiB,EAAQ,EAAE;QACpD,KAAK,CAAC,SAAS,CAAC,CAAC;QACjB,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QAC1B,IAAI,UAAU,KAAK,SAAS,EAAE,CAAC;YAC9B,UAAU,GAAG,IAAI,CAAC;YAClB,KAAK,CAAC,CAAC,YAAY,EAAE,CAAC;QACvB,CAAC;IACF,CAAC,CAAC;IACF,OAAO,IAAI,CAAC;AACb,CAAC,CAAC"}
|
package/dist/pool.d.ts
CHANGED
|
@@ -31,8 +31,8 @@ export declare const normalizeCaCert: (caCert: string | undefined) => string | u
|
|
|
31
31
|
* `createAuthPool`):
|
|
32
32
|
*
|
|
33
33
|
* - `caCert` set -> verify the server cert + hostname (`sslmode=verify-full`).
|
|
34
|
-
* - local host -> no TLS, and cap at `max: 1` (the PGlite socket
|
|
35
|
-
*
|
|
34
|
+
* - local host -> no TLS, and cap at `max: 1` (the PGlite socket serves
|
|
35
|
+
* every connection from one session; more buys nothing).
|
|
36
36
|
* - otherwise -> TLS **without** chain verification. Managed certs (e.g.
|
|
37
37
|
* DigitalOcean) aren't in Node's trust store, so full
|
|
38
38
|
* verification fails with "self-signed certificate in
|
package/dist/pool.js
CHANGED
|
@@ -35,8 +35,8 @@ export const normalizeCaCert = (caCert) => caCert?.includes("\\n") ? caCert.repl
|
|
|
35
35
|
* `createAuthPool`):
|
|
36
36
|
*
|
|
37
37
|
* - `caCert` set -> verify the server cert + hostname (`sslmode=verify-full`).
|
|
38
|
-
* - local host -> no TLS, and cap at `max: 1` (the PGlite socket
|
|
39
|
-
*
|
|
38
|
+
* - local host -> no TLS, and cap at `max: 1` (the PGlite socket serves
|
|
39
|
+
* every connection from one session; more buys nothing).
|
|
40
40
|
* - otherwise -> TLS **without** chain verification. Managed certs (e.g.
|
|
41
41
|
* DigitalOcean) aren't in Node's trust store, so full
|
|
42
42
|
* verification fails with "self-signed certificate in
|
|
@@ -68,8 +68,8 @@ export const createPool = (config = {}) => {
|
|
|
68
68
|
const caCert = normalizeCaCert(config.caCert ?? env?.caCert);
|
|
69
69
|
const local = isLocal(connectionString);
|
|
70
70
|
// Local wins over the env: a pulled .env (e.g. `vercel env pull`) carries the
|
|
71
|
-
// production DATABASE_POOL_MAX/DATABASE_CA_CERT, but the PGlite socket
|
|
72
|
-
//
|
|
71
|
+
// production DATABASE_POOL_MAX/DATABASE_CA_CERT, but the PGlite socket
|
|
72
|
+
// serves one session and speaks no TLS — honoring them breaks dev. An explicit
|
|
73
73
|
// `config.max` in code still applies.
|
|
74
74
|
const max = config.max ?? (local ? 1 : env?.poolMax);
|
|
75
75
|
const base = max === undefined ? {} : { max };
|
package/dist/pool.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pool.js","sourceRoot":"","sources":["../src/pool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAmB,MAAM,IAAI,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAWlD,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;AAExE,MAAM,OAAO,GAAG,CAAC,gBAAwB,EAAW,EAAE;IACrD,wEAAwE;IACxE,4DAA4D;IAC5D,IAAI,CAAC;QACJ,OAAO,WAAW,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC,QAAQ,CAAC,CAAC;IAC5D,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;AACF,CAAC,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,MAA0B,EAAsB,EAAE,CACjF,MAAM,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,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|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ingram-tech/nk-db",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "The Ingram Postgres data layer: one TLS-aware pg pool, raw-SQL helpers, Drizzle wiring, and a PGlite (no-Docker) dev/test harness for Next.js sites.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|
|
70
70
|
"@electric-sql/pglite": ">=0.5.0",
|
|
71
|
-
"@electric-sql/pglite-socket": ">=0.2.
|
|
71
|
+
"@electric-sql/pglite-socket": ">=0.2.11",
|
|
72
72
|
"drizzle-orm": ">=0.44.0",
|
|
73
73
|
"pg": "^8.13.0"
|
|
74
74
|
},
|
|
@@ -83,7 +83,7 @@
|
|
|
83
83
|
"devDependencies": {
|
|
84
84
|
"@electric-sql/pglite": "^0.5.8",
|
|
85
85
|
"@electric-sql/pglite-socket": "^0.2.11",
|
|
86
|
-
"@ingram-tech/nk-dev": "0.
|
|
86
|
+
"@ingram-tech/nk-dev": "0.18.0",
|
|
87
87
|
"@types/node": "^26.5.1",
|
|
88
88
|
"@types/pg": "^8.23.1",
|
|
89
89
|
"drizzle-orm": "^0.45.2",
|
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
|
|