@makaio/storage-pg 1.0.0-dev-1795476104890 → 1.0.0-dev-1795548607801
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts
CHANGED
|
@@ -1,14 +1,6 @@
|
|
|
1
1
|
import type { DatabaseClient, PostgresClientOptions } from '@makaio/framework/storage/drizzle/client';
|
|
2
2
|
import { type PostgresPoolLike } from './raw-sql.js';
|
|
3
|
-
|
|
4
|
-
interface PgModule {
|
|
5
|
-
default: {
|
|
6
|
-
Pool: new (config: {
|
|
7
|
-
connectionString: string;
|
|
8
|
-
max: number;
|
|
9
|
-
}) => PostgresPoolLike;
|
|
10
|
-
};
|
|
11
|
-
}
|
|
3
|
+
import type { PostgresDriverModule } from './pg-signal-client.js';
|
|
12
4
|
/** Structural surface of the `drizzle-orm/node-postgres` module used by {@link createNodePgClient}. */
|
|
13
5
|
interface NodePgDrizzleModule {
|
|
14
6
|
drizzle: (pool: PostgresPoolLike) => object;
|
|
@@ -21,8 +13,10 @@ interface NodePgDrizzleModule {
|
|
|
21
13
|
* path without mocking the module system.
|
|
22
14
|
*/
|
|
23
15
|
export interface NodePgDriverLoaders {
|
|
24
|
-
/** Loads the `pg` module. */
|
|
25
|
-
readonly loadPg: () => Promise<
|
|
16
|
+
/** Loads the `pg` module. Typed via the shared {@link PostgresDriverModule}, which covers both the writing pool and the dedicated signal-listener connection constructed from it. */
|
|
17
|
+
readonly loadPg: () => Promise<{
|
|
18
|
+
default: PostgresDriverModule;
|
|
19
|
+
}>;
|
|
26
20
|
/** Loads the `drizzle-orm/node-postgres` module. */
|
|
27
21
|
readonly loadDrizzlePg: () => Promise<NodePgDrizzleModule>;
|
|
28
22
|
}
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
2
|
import { and, asc, count, eq, getTableColumns, sql } from "drizzle-orm";
|
|
3
|
-
import { brandDatabase, buildFirstUserMessagePreviewQuery, getRawSqlExecutor, quoteSqlIdentifier, readErrorCode, someInCauseChain } from "@makaio/framework/storage/drizzle";
|
|
3
|
+
import { bindDatabaseSignals, brandDatabase, buildFirstUserMessagePreviewQuery, createRegistrationSet, getRawSqlExecutor, invokeListenersSafely, quoteSqlIdentifier, readErrorCode, releaseHostDatabaseWake, someInCauseChain } from "@makaio/framework/storage/drizzle";
|
|
4
4
|
import { PgDialect } from "drizzle-orm/pg-core";
|
|
5
5
|
import { createHash } from "node:crypto";
|
|
6
6
|
|
|
@@ -71,6 +71,343 @@ function createPostgresRawSqlExecutor(pool) {
|
|
|
71
71
|
};
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
//#endregion
|
|
75
|
+
//#region src/signal-listener.ts
|
|
76
|
+
/**
|
|
77
|
+
* Postgres implementation of the database signal capability.
|
|
78
|
+
*
|
|
79
|
+
* Postgres can wake readers in other processes at commit time through
|
|
80
|
+
* `pg_notify`/`LISTEN`: a writer notifies a fixed channel inside its
|
|
81
|
+
* committing transaction, and every connection that issued `LISTEN` on that
|
|
82
|
+
* channel receives the notification once the transaction commits (never on
|
|
83
|
+
* rollback). This module builds the `database-notify` branch of
|
|
84
|
+
* `DatabaseSignals` over one dedicated `pg.Client` per database client,
|
|
85
|
+
* opened lazily on the first subscription — never one of the writing pool's
|
|
86
|
+
* connections, which would otherwise stay checked out indefinitely just to
|
|
87
|
+
* remain subscribed.
|
|
88
|
+
*
|
|
89
|
+
* Lifecycle invariants:
|
|
90
|
+
* - Direct subscribers live in one {@link RegistrationSet}: registering the
|
|
91
|
+
* same listener function twice yields two independent entries, each
|
|
92
|
+
* removed independently.
|
|
93
|
+
* - `ready()` never owns a long-lived promise. Closed: a fresh, caller-owned
|
|
94
|
+
* rejection. Already listening: a resolved promise. Otherwise: a waiter is
|
|
95
|
+
* enqueued and a connection attempt is ensured. A confirmed `LISTEN`
|
|
96
|
+
* resolves and clears every waiter; a failed attempt leaves them waiting;
|
|
97
|
+
* `close()` rejects and clears them — no promise this module creates for
|
|
98
|
+
* itself is ever left unobserved.
|
|
99
|
+
* - At most one connection is owned at a time. Each connection has one
|
|
100
|
+
* memoized `release()`: end it, wait for that to settle, only then detach
|
|
101
|
+
* its handlers (node-postgres can re-emit `'error'` on the very same
|
|
102
|
+
* client once the underlying socket finally closes, and an unlistened
|
|
103
|
+
* `'error'` crashes the process). A connection whose release started
|
|
104
|
+
* outside `close()` — a failed attempt — is tracked until that release
|
|
105
|
+
* settles, so `close()` can still wait for it.
|
|
106
|
+
* - The first `'error'`/`'end'` (or a failed `connect()`/`LISTEN`) of a
|
|
107
|
+
* connection concludes it exactly once, merged by connection identity;
|
|
108
|
+
* later events of the same connection are swallowed by its still-attached
|
|
109
|
+
* handlers until release has completed.
|
|
110
|
+
* - A concluded connection schedules at most one retry timer with bounded
|
|
111
|
+
* exponential backoff, unless closed; retries continue until success or
|
|
112
|
+
* close, and success resets the backoff. A confirmed `LISTEN` that follows
|
|
113
|
+
* an earlier confirmed `LISTEN` of this capability emits a `resynced`
|
|
114
|
+
* event; the very first confirmed `LISTEN` does not.
|
|
115
|
+
* - `close()` is idempotent and memoized: mark closed, clear a pending retry
|
|
116
|
+
* timer, reject and clear waiters, clear the subscriber set, release every
|
|
117
|
+
* owned connection (current and still-releasing) and await them. After
|
|
118
|
+
* close, `subscribe()` throws and `ready()` rejects.
|
|
119
|
+
* - No connection is opened before the first `subscribe()`/`ready()` call.
|
|
120
|
+
* - No internal path (attempts, releases, retry timers, notification
|
|
121
|
+
* handling) produces an unhandled rejection; subscriber delivery goes
|
|
122
|
+
* through `invokeListenersSafely`.
|
|
123
|
+
* @packageDocumentation
|
|
124
|
+
*/
|
|
125
|
+
/**
|
|
126
|
+
* Fixed channel every client of this capability listens on and notifies.
|
|
127
|
+
*
|
|
128
|
+
* One well-known channel per deployment (not one channel per topic or per
|
|
129
|
+
* table) keeps the listener side to a single `LISTEN` statement; topics are
|
|
130
|
+
* carried in the notification payload instead, validated by
|
|
131
|
+
* {@link validateNotifyTopic}.
|
|
132
|
+
*/
|
|
133
|
+
const POSTGRES_WAKE_CHANNEL = "makaio_storage_wake_v1";
|
|
134
|
+
/**
|
|
135
|
+
* Postgres truncates a `NOTIFY` payload silently once it approaches 8000
|
|
136
|
+
* bytes, so this capability rejects a topic that would be truncated instead
|
|
137
|
+
* of delivering a silently-shortened one. Kept one byte under the documented
|
|
138
|
+
* ~8000-byte limit.
|
|
139
|
+
*/
|
|
140
|
+
const MAX_TOPIC_UTF8_BYTES = 7999;
|
|
141
|
+
const topicEncoder = new TextEncoder();
|
|
142
|
+
/**
|
|
143
|
+
* Validate a notify topic against the constraints `pg_notify` imposes on its
|
|
144
|
+
* payload: non-empty, no embedded NUL (Postgres text values cannot carry
|
|
145
|
+
* one), and short enough that the server never truncates it.
|
|
146
|
+
* @param topic - Application-defined topic about to be notified.
|
|
147
|
+
* @throws Error when the topic is empty, contains a NUL byte, or its UTF-8
|
|
148
|
+
* encoding exceeds {@link MAX_TOPIC_UTF8_BYTES}.
|
|
149
|
+
*/
|
|
150
|
+
function validateNotifyTopic(topic) {
|
|
151
|
+
if (topic.length === 0) throw new Error("createPostgresDatabaseSignals: a notify topic must be a non-empty string.");
|
|
152
|
+
if (topic.includes("\0")) throw new Error("createPostgresDatabaseSignals: a notify topic must not contain a NUL byte.");
|
|
153
|
+
const byteLength = topicEncoder.encode(topic).length;
|
|
154
|
+
if (byteLength > MAX_TOPIC_UTF8_BYTES) throw new Error(`createPostgresDatabaseSignals: a notify topic's UTF-8 encoding must be at most ${MAX_TOPIC_UTF8_BYTES} bytes (got ${byteLength} bytes). Postgres truncates an oversized NOTIFY payload silently, so this capability rejects it instead of delivering a truncated topic.`);
|
|
155
|
+
}
|
|
156
|
+
/** Initial reconnect delay; doubled per attempt up to {@link MAX_RECONNECT_DELAY_MS}. */
|
|
157
|
+
const BASE_RECONNECT_DELAY_MS = 250;
|
|
158
|
+
/** Upper bound on the reconnect backoff delay. */
|
|
159
|
+
const MAX_RECONNECT_DELAY_MS = 3e4;
|
|
160
|
+
/** Caps the exponent so the backoff computation never overflows. */
|
|
161
|
+
const MAX_BACKOFF_EXPONENT = 10;
|
|
162
|
+
/** Rejection reason used by every pending or future `ready()`/`subscribe()` call once `close()` was called. */
|
|
163
|
+
const CLOSED_REASON = "createPostgresDatabaseSignals: ready() rejects because close() was called.";
|
|
164
|
+
/**
|
|
165
|
+
* Create a fresh, not-yet-connecting lifecycle state.
|
|
166
|
+
* @param options - Connection configuration and client constructor.
|
|
167
|
+
* @returns A new {@link ListenerState}.
|
|
168
|
+
*/
|
|
169
|
+
function createListenerState(options) {
|
|
170
|
+
return {
|
|
171
|
+
options,
|
|
172
|
+
subscribers: createRegistrationSet(),
|
|
173
|
+
closed: false,
|
|
174
|
+
listening: false,
|
|
175
|
+
everListened: false,
|
|
176
|
+
current: void 0,
|
|
177
|
+
releasing: /* @__PURE__ */ new Set(),
|
|
178
|
+
waiters: /* @__PURE__ */ new Set(),
|
|
179
|
+
retryTimer: void 0,
|
|
180
|
+
retryAttempt: 0,
|
|
181
|
+
closePromise: void 0
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Deliver a notification on the dedicated connection to every direct
|
|
186
|
+
* subscriber. Notifications on any channel but the fixed wake channel are
|
|
187
|
+
* ignored — the connection never issues `LISTEN` for anything else, but a
|
|
188
|
+
* defensive channel check keeps that invariant explicit.
|
|
189
|
+
* @param state - Lifecycle state whose subscribers to deliver to.
|
|
190
|
+
* @param notification - The delivered notification.
|
|
191
|
+
*/
|
|
192
|
+
function deliverNotification(state, notification) {
|
|
193
|
+
if (notification.channel !== "makaio_storage_wake_v1") return;
|
|
194
|
+
invokeListenersSafely(state.subscribers.snapshot(), {
|
|
195
|
+
kind: "topic",
|
|
196
|
+
topic: notification.payload ?? ""
|
|
197
|
+
}, "database signal topic");
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Deliver a `resynced` event to every direct subscriber, isolating each from
|
|
201
|
+
* the others.
|
|
202
|
+
* @param state - Lifecycle state whose subscribers to deliver to.
|
|
203
|
+
*/
|
|
204
|
+
function deliverResynced(state) {
|
|
205
|
+
invokeListenersSafely(state.subscribers.snapshot(), { kind: "resynced" }, "database signal resynced");
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Open one dedicated connection and confirm `LISTEN`. The first `'error'`,
|
|
209
|
+
* `'end'`, or failed `connect()`/`LISTEN` of this connection concludes it
|
|
210
|
+
* exactly once: ownership is cleared, its release is tracked until settled,
|
|
211
|
+
* and — unless closed — the next attempt is scheduled with backoff. A
|
|
212
|
+
* success resolves every pending waiter, resets the backoff, and emits
|
|
213
|
+
* `resynced` once this is not the capability's first confirmed `LISTEN`.
|
|
214
|
+
* @param state - Lifecycle state this attempt belongs to.
|
|
215
|
+
*/
|
|
216
|
+
async function attemptConnection(state) {
|
|
217
|
+
const client = state.options.createClient({ connectionString: state.options.connectionString });
|
|
218
|
+
let concluded = false;
|
|
219
|
+
let releasePromise;
|
|
220
|
+
const isCurrent = () => state.current?.client === client;
|
|
221
|
+
/**
|
|
222
|
+
* End `client`, then detach this attempt's handlers from it. Memoized:
|
|
223
|
+
* every call returns the same promise.
|
|
224
|
+
* @returns Promise that resolves once `client` has fully ended and its
|
|
225
|
+
* handlers are detached.
|
|
226
|
+
*/
|
|
227
|
+
function release() {
|
|
228
|
+
releasePromise ??= (async () => {
|
|
229
|
+
await client.end().catch(() => void 0);
|
|
230
|
+
client.off("notification", onNotification);
|
|
231
|
+
client.off("error", onError);
|
|
232
|
+
client.off("end", onEnd);
|
|
233
|
+
})();
|
|
234
|
+
return releasePromise;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Conclude this attempt exactly once: release ownership, track the release
|
|
238
|
+
* until settled, and schedule a retry unless the capability is closed.
|
|
239
|
+
* @param error - The triggering failure, or `undefined` for a bare `'end'` event.
|
|
240
|
+
*/
|
|
241
|
+
function conclude(error) {
|
|
242
|
+
if (concluded) return;
|
|
243
|
+
concluded = true;
|
|
244
|
+
if (isCurrent()) {
|
|
245
|
+
state.current = void 0;
|
|
246
|
+
state.listening = false;
|
|
247
|
+
}
|
|
248
|
+
const pending = release();
|
|
249
|
+
state.releasing.add(pending);
|
|
250
|
+
pending.finally(() => state.releasing.delete(pending));
|
|
251
|
+
if (error !== void 0) console.error("[makaio:storage-pg] database signal listener connection failed; reconnecting with backoff.", error);
|
|
252
|
+
if (!state.closed) scheduleRetry(state);
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* `'notification'` handler: delivers only while `client` is still current.
|
|
256
|
+
* @param notification - The delivered notification.
|
|
257
|
+
*/
|
|
258
|
+
function onNotification(notification) {
|
|
259
|
+
if (isCurrent()) deliverNotification(state, notification);
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* `'error'` handler. Required: node-postgres escalates an unlistened
|
|
263
|
+
* `'error'` on a `Client` to an uncaught exception.
|
|
264
|
+
* @param error - The connection failure.
|
|
265
|
+
*/
|
|
266
|
+
function onError(error) {
|
|
267
|
+
conclude(error);
|
|
268
|
+
}
|
|
269
|
+
/** `'end'` handler: the connection closed, whether via {@link release} or an upstream failure. */
|
|
270
|
+
function onEnd() {
|
|
271
|
+
conclude(void 0);
|
|
272
|
+
}
|
|
273
|
+
client.on("notification", onNotification);
|
|
274
|
+
client.on("error", onError);
|
|
275
|
+
client.on("end", onEnd);
|
|
276
|
+
state.current = {
|
|
277
|
+
client,
|
|
278
|
+
release
|
|
279
|
+
};
|
|
280
|
+
try {
|
|
281
|
+
await client.connect();
|
|
282
|
+
await client.query(`LISTEN ${POSTGRES_WAKE_CHANNEL}`);
|
|
283
|
+
} catch (error) {
|
|
284
|
+
console.error("[makaio:storage-pg] database signal listener failed to connect or LISTEN; retrying.", error);
|
|
285
|
+
conclude(error instanceof Error ? error : new Error(String(error)));
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (concluded || state.closed) {
|
|
289
|
+
conclude(void 0);
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
state.listening = true;
|
|
293
|
+
state.retryAttempt = 0;
|
|
294
|
+
for (const waiter of state.waiters) waiter.resolve();
|
|
295
|
+
state.waiters.clear();
|
|
296
|
+
if (state.everListened) deliverResynced(state);
|
|
297
|
+
state.everListened = true;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Start a connection attempt unless one is already owned or a retry is
|
|
301
|
+
* already scheduled. The only entry point into {@link attemptConnection}, so
|
|
302
|
+
* "at most one current connection" and "no connection before the first
|
|
303
|
+
* `subscribe()`/`ready()`" both hold by construction; also the landing spot a
|
|
304
|
+
* retry timer calls back into.
|
|
305
|
+
* @param state - Lifecycle state to start connecting.
|
|
306
|
+
*/
|
|
307
|
+
function ensureConnectionAttempt(state) {
|
|
308
|
+
if (state.closed || state.current !== void 0 || state.retryTimer !== void 0) return;
|
|
309
|
+
attemptConnection(state).catch((error) => {
|
|
310
|
+
console.error("[makaio:storage-pg] database signal listener attempt failed unexpectedly.", error);
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Schedule the single next connection attempt after a failure, with a delay
|
|
315
|
+
* that doubles per attempt up to {@link MAX_RECONNECT_DELAY_MS}. A no-op
|
|
316
|
+
* while a retry is already scheduled.
|
|
317
|
+
* @param state - Lifecycle state to schedule the retry on.
|
|
318
|
+
*/
|
|
319
|
+
function scheduleRetry(state) {
|
|
320
|
+
if (state.retryTimer !== void 0) return;
|
|
321
|
+
const exponent = Math.min(state.retryAttempt, MAX_BACKOFF_EXPONENT);
|
|
322
|
+
state.retryAttempt += 1;
|
|
323
|
+
const delay = Math.min(BASE_RECONNECT_DELAY_MS * 2 ** exponent, MAX_RECONNECT_DELAY_MS);
|
|
324
|
+
state.retryTimer = setTimeout(() => {
|
|
325
|
+
state.retryTimer = void 0;
|
|
326
|
+
ensureConnectionAttempt(state);
|
|
327
|
+
}, delay);
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Resolve once the dedicated connection confirms `LISTEN`.
|
|
331
|
+
* @param state - Lifecycle state to read and wait on.
|
|
332
|
+
* @returns A promise owned solely by the caller: rejected immediately once
|
|
333
|
+
* closed, resolved immediately once already listening, otherwise a fresh
|
|
334
|
+
* promise resolved or rejected once {@link attemptConnection} or
|
|
335
|
+
* {@link closeListener} settles it.
|
|
336
|
+
*/
|
|
337
|
+
function ready(state) {
|
|
338
|
+
if (state.closed) return Promise.reject(new Error(CLOSED_REASON));
|
|
339
|
+
if (state.listening) return Promise.resolve();
|
|
340
|
+
return new Promise((resolve, reject) => {
|
|
341
|
+
state.waiters.add({
|
|
342
|
+
resolve,
|
|
343
|
+
reject
|
|
344
|
+
});
|
|
345
|
+
ensureConnectionAttempt(state);
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Tear down a lifecycle: mark it closed, cancel a pending retry, reject and
|
|
350
|
+
* clear every waiting `ready()` call, clear the subscriber set, and release
|
|
351
|
+
* every owned connection — the current one and any still settling from an
|
|
352
|
+
* earlier failure — before resolving. Idempotent and memoized.
|
|
353
|
+
* @param state - Lifecycle state to close.
|
|
354
|
+
* @returns The memoized close promise, resolved once every owned connection
|
|
355
|
+
* has fully ended.
|
|
356
|
+
*/
|
|
357
|
+
function closeListener(state) {
|
|
358
|
+
if (state.closePromise !== void 0) return state.closePromise;
|
|
359
|
+
state.closed = true;
|
|
360
|
+
if (state.retryTimer !== void 0) {
|
|
361
|
+
clearTimeout(state.retryTimer);
|
|
362
|
+
state.retryTimer = void 0;
|
|
363
|
+
}
|
|
364
|
+
const closedError = new Error(CLOSED_REASON);
|
|
365
|
+
for (const waiter of state.waiters) waiter.reject(closedError);
|
|
366
|
+
state.waiters.clear();
|
|
367
|
+
state.subscribers.clear();
|
|
368
|
+
state.closePromise = (async () => {
|
|
369
|
+
const pending = [...state.releasing];
|
|
370
|
+
const current = state.current;
|
|
371
|
+
state.current = void 0;
|
|
372
|
+
if (current !== void 0) pending.push(current.release());
|
|
373
|
+
await Promise.all(pending);
|
|
374
|
+
})();
|
|
375
|
+
return state.closePromise;
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Create the Postgres `database-notify` signal capability for one database
|
|
379
|
+
* client.
|
|
380
|
+
*
|
|
381
|
+
* Owns exactly one dedicated `pg.Client`, outside the writing pool, opened
|
|
382
|
+
* lazily on the first {@link PostgresDatabaseSignals.subscribe} or
|
|
383
|
+
* {@link PostgresDatabaseSignals.ready} call. Once a reconnect re-confirms
|
|
384
|
+
* `LISTEN`, subscribers receive a `{ kind: 'resynced' }` event: notifications
|
|
385
|
+
* are not queued while the connection is down, so a subscriber must treat
|
|
386
|
+
* `resynced` as "replay what you may have missed" rather than rely on
|
|
387
|
+
* buffered topics. The connection string is never logged.
|
|
388
|
+
* @param options - Connection configuration and client constructor for the
|
|
389
|
+
* dedicated listener connection.
|
|
390
|
+
* @returns The `database-notify` branch of `DatabaseSignals`.
|
|
391
|
+
*/
|
|
392
|
+
function createPostgresDatabaseSignals(options) {
|
|
393
|
+
const state = createListenerState(options);
|
|
394
|
+
return {
|
|
395
|
+
kind: "database-notify",
|
|
396
|
+
notifyExpression(topic) {
|
|
397
|
+
validateNotifyTopic(topic);
|
|
398
|
+
return sql`pg_notify(${POSTGRES_WAKE_CHANNEL}, ${topic})`;
|
|
399
|
+
},
|
|
400
|
+
subscribe(listener) {
|
|
401
|
+
if (state.closed) throw new Error("createPostgresDatabaseSignals: subscribe() was called after close().");
|
|
402
|
+
const remove = state.subscribers.add(listener);
|
|
403
|
+
ensureConnectionAttempt(state);
|
|
404
|
+
return remove;
|
|
405
|
+
},
|
|
406
|
+
ready: () => ready(state),
|
|
407
|
+
close: () => closeListener(state)
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
74
411
|
//#endregion
|
|
75
412
|
//#region src/client.ts
|
|
76
413
|
/**
|
|
@@ -137,14 +474,27 @@ async function createNodePgClient(url, options, loaders = defaultDriverLoaders)
|
|
|
137
474
|
attachPgPoolErrorLogger(pool);
|
|
138
475
|
const db = drizzlePg(pool);
|
|
139
476
|
brandDatabase(db, "postgres", createPostgresRawSqlExecutor(pool));
|
|
140
|
-
|
|
477
|
+
const signals = createPostgresDatabaseSignals({
|
|
478
|
+
connectionString: url,
|
|
479
|
+
createClient: (config) => new pg.Client(config)
|
|
480
|
+
});
|
|
481
|
+
bindDatabaseSignals(db, signals);
|
|
482
|
+
let closePromise;
|
|
141
483
|
return {
|
|
142
484
|
db,
|
|
143
485
|
dialect: "postgres",
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
486
|
+
signals,
|
|
487
|
+
close: () => {
|
|
488
|
+
if (closePromise !== void 0) return closePromise;
|
|
489
|
+
closePromise = (async () => {
|
|
490
|
+
releaseHostDatabaseWake(db);
|
|
491
|
+
try {
|
|
492
|
+
await signals.close();
|
|
493
|
+
} finally {
|
|
494
|
+
await pool.end();
|
|
495
|
+
}
|
|
496
|
+
})();
|
|
497
|
+
return closePromise;
|
|
148
498
|
}
|
|
149
499
|
};
|
|
150
500
|
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-owned structural types for the dedicated `pg` listener connection and
|
|
3
|
+
* the shared driver-module shape it is constructed through.
|
|
4
|
+
*
|
|
5
|
+
* The signal capability of a Postgres client (`pg_notify`/`LISTEN`) needs a
|
|
6
|
+
* `pg.Client` outside the writing pool — a pool connection cannot stay
|
|
7
|
+
* subscribed to `LISTEN` between checkouts. This module types only that
|
|
8
|
+
* dedicated-connection surface plus the driver-module shape shared with the
|
|
9
|
+
* pool constructor so both can be built from one place. It intentionally
|
|
10
|
+
* declares no runtime behavior: constructing or wiring the listener
|
|
11
|
+
* connection is the capability implementation's job.
|
|
12
|
+
*
|
|
13
|
+
* Self-owned so the published declaration file never references
|
|
14
|
+
* `import('pg')`, mirroring `PostgresPoolLike` in `raw-sql.ts`. Shapes
|
|
15
|
+
* verified against `pg`'s `Client` implementation (`node_modules/pg/lib/client.js`)
|
|
16
|
+
* and the wire message it re-emits (`node_modules/pg-protocol/dist/messages.d.ts`).
|
|
17
|
+
* @packageDocumentation
|
|
18
|
+
*/
|
|
19
|
+
import type { PostgresPoolLike } from './raw-sql.js';
|
|
20
|
+
/**
|
|
21
|
+
* A `NOTIFY` delivered to a `pg.Client` subscribed via `LISTEN`.
|
|
22
|
+
*
|
|
23
|
+
* Mirrors `NotificationResponseMessage` in
|
|
24
|
+
* `pg-protocol/dist/messages.d.ts`: `processId` identifies the notifying
|
|
25
|
+
* backend, `channel` is the notified channel name, and `payload` is the
|
|
26
|
+
* notification payload. Declared optional here because this structural type
|
|
27
|
+
* also describes what a listener callback may be handed; the wire message
|
|
28
|
+
* itself always carries a `payload` string (empty when `NOTIFY` supplied
|
|
29
|
+
* none).
|
|
30
|
+
*/
|
|
31
|
+
export interface PostgresNotificationLike {
|
|
32
|
+
/** Backend process ID of the connection that issued `NOTIFY`. */
|
|
33
|
+
processId: number;
|
|
34
|
+
/** Channel name the notification was sent on. */
|
|
35
|
+
channel: string;
|
|
36
|
+
/** Notification payload, or absent/empty when `NOTIFY` supplied none. */
|
|
37
|
+
payload?: string;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Structural surface of a dedicated `pg.Client` used only for `LISTEN` —
|
|
41
|
+
* never for query execution outside listener setup. Self-owned so the
|
|
42
|
+
* published declaration file never references `import('pg')`.
|
|
43
|
+
*/
|
|
44
|
+
export interface PostgresSignalClientLike {
|
|
45
|
+
/**
|
|
46
|
+
* Open the connection. Resolves once the connection handshake completes;
|
|
47
|
+
* rejects on connection failure.
|
|
48
|
+
*/
|
|
49
|
+
connect(): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Execute a statement on this connection — used to issue `LISTEN <channel>`
|
|
52
|
+
* once connected. `LISTEN` takes no bind parameters (the channel is a
|
|
53
|
+
* literal in the statement text, not a placeholder), so `params` is
|
|
54
|
+
* optional here, unlike the mandatory parameter list on
|
|
55
|
+
* `PostgresQueryableLike.query` in `raw-sql.ts`.
|
|
56
|
+
* @param text - SQL text to execute.
|
|
57
|
+
* @param params - Positional parameter values, when the statement has any.
|
|
58
|
+
*/
|
|
59
|
+
query(text: string, params?: unknown[]): Promise<unknown>;
|
|
60
|
+
/**
|
|
61
|
+
* Close the connection. Resolves once the connection has fully closed.
|
|
62
|
+
*/
|
|
63
|
+
end(): Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* Subscribe to an event on this connection.
|
|
66
|
+
* - `'notification'` — a `NOTIFY` delivered on a channel this connection is
|
|
67
|
+
* listening on.
|
|
68
|
+
* - `'error'` — the connection failed (e.g. backend restart, network
|
|
69
|
+
* partition). Required listener: node-postgres escalates an unlistened
|
|
70
|
+
* `'error'` on a `Client` to an uncaught exception.
|
|
71
|
+
* - `'end'` — the connection closed, whether via `end()` or a failure.
|
|
72
|
+
* @param event - Event name to subscribe to.
|
|
73
|
+
* @param listener - Listener invoked with the event's payload, if any.
|
|
74
|
+
*/
|
|
75
|
+
on(event: 'notification', listener: (notification: PostgresNotificationLike) => void): void;
|
|
76
|
+
on(event: 'error', listener: (error: Error) => void): void;
|
|
77
|
+
on(event: 'end', listener: () => void): void;
|
|
78
|
+
/**
|
|
79
|
+
* Unsubscribe a listener previously registered with {@link on}.
|
|
80
|
+
* @param event - Event name the listener was registered for.
|
|
81
|
+
* @param listener - The exact listener function to remove.
|
|
82
|
+
*/
|
|
83
|
+
off(event: 'notification', listener: (notification: PostgresNotificationLike) => void): void;
|
|
84
|
+
off(event: 'error', listener: (error: Error) => void): void;
|
|
85
|
+
off(event: 'end', listener: () => void): void;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Structural surface of the `pg` module's CJS default export, covering both
|
|
89
|
+
* driver entry points this package constructs: the writing pool
|
|
90
|
+
* (`PostgresPoolLike`, used by `client.ts`) and the dedicated listener
|
|
91
|
+
* connection (`PostgresSignalClientLike`, used by the signal capability).
|
|
92
|
+
*
|
|
93
|
+
* Replaces the pool-only constructor shape previously duplicated between
|
|
94
|
+
* `client.ts`'s local `PgModule` interface and the ambient `pg` module
|
|
95
|
+
* declaration in `pg-module.d.ts` — both import this type instead of
|
|
96
|
+
* restating the constructor shapes.
|
|
97
|
+
*/
|
|
98
|
+
export interface PostgresDriverModule {
|
|
99
|
+
/** node-postgres connection pool constructor. */
|
|
100
|
+
Pool: new (config: {
|
|
101
|
+
connectionString: string;
|
|
102
|
+
max: number;
|
|
103
|
+
}) => PostgresPoolLike;
|
|
104
|
+
/** node-postgres dedicated single-connection client constructor. */
|
|
105
|
+
Client: new (config: {
|
|
106
|
+
connectionString: string;
|
|
107
|
+
}) => PostgresSignalClientLike;
|
|
108
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type DatabaseSignals } from '@makaio/framework/storage/drizzle';
|
|
2
|
+
import type { PostgresSignalClientLike } from './pg-signal-client.js';
|
|
3
|
+
/**
|
|
4
|
+
* The `database-notify` branch of {@link DatabaseSignals}, as produced by
|
|
5
|
+
* {@link createPostgresDatabaseSignals}.
|
|
6
|
+
*/
|
|
7
|
+
export type PostgresDatabaseSignals = Extract<DatabaseSignals, {
|
|
8
|
+
kind: 'database-notify';
|
|
9
|
+
}>;
|
|
10
|
+
/**
|
|
11
|
+
* Fixed channel every client of this capability listens on and notifies.
|
|
12
|
+
*
|
|
13
|
+
* One well-known channel per deployment (not one channel per topic or per
|
|
14
|
+
* table) keeps the listener side to a single `LISTEN` statement; topics are
|
|
15
|
+
* carried in the notification payload instead, validated by
|
|
16
|
+
* {@link validateNotifyTopic}.
|
|
17
|
+
*/
|
|
18
|
+
export declare const POSTGRES_WAKE_CHANNEL = "makaio_storage_wake_v1";
|
|
19
|
+
/**
|
|
20
|
+
* Connection configuration {@link createPostgresDatabaseSignals} needs to
|
|
21
|
+
* open its dedicated listener connection.
|
|
22
|
+
*/
|
|
23
|
+
export interface PostgresDatabaseSignalsOptions {
|
|
24
|
+
/**
|
|
25
|
+
* Connection string for the dedicated listener connection — the same
|
|
26
|
+
* configuration the writing pool was created from, so the listener
|
|
27
|
+
* authenticates against the same database and role.
|
|
28
|
+
*/
|
|
29
|
+
connectionString: string;
|
|
30
|
+
/**
|
|
31
|
+
* Constructs the dedicated, listener-only connection. Injected rather than
|
|
32
|
+
* imported directly so this module stays independent of how the caller
|
|
33
|
+
* loaded the `pg` driver module.
|
|
34
|
+
* @param config - Connection configuration for the new client.
|
|
35
|
+
* @returns A not-yet-connected listener-only client.
|
|
36
|
+
*/
|
|
37
|
+
createClient: (config: {
|
|
38
|
+
connectionString: string;
|
|
39
|
+
}) => PostgresSignalClientLike;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Create the Postgres `database-notify` signal capability for one database
|
|
43
|
+
* client.
|
|
44
|
+
*
|
|
45
|
+
* Owns exactly one dedicated `pg.Client`, outside the writing pool, opened
|
|
46
|
+
* lazily on the first {@link PostgresDatabaseSignals.subscribe} or
|
|
47
|
+
* {@link PostgresDatabaseSignals.ready} call. Once a reconnect re-confirms
|
|
48
|
+
* `LISTEN`, subscribers receive a `{ kind: 'resynced' }` event: notifications
|
|
49
|
+
* are not queued while the connection is down, so a subscriber must treat
|
|
50
|
+
* `resynced` as "replay what you may have missed" rather than rely on
|
|
51
|
+
* buffered topics. The connection string is never logged.
|
|
52
|
+
* @param options - Connection configuration and client constructor for the
|
|
53
|
+
* dedicated listener connection.
|
|
54
|
+
* @returns The `database-notify` branch of `DatabaseSignals`.
|
|
55
|
+
*/
|
|
56
|
+
export declare function createPostgresDatabaseSignals(options: PostgresDatabaseSignalsOptions): PostgresDatabaseSignals;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
CREATE TABLE "journal_edge_cursors" (
|
|
2
|
+
"edge" text NOT NULL,
|
|
3
|
+
"partition" text NOT NULL,
|
|
4
|
+
"value" text,
|
|
5
|
+
CONSTRAINT "journal_edge_cursors_pk" PRIMARY KEY("edge","partition")
|
|
6
|
+
);
|
|
7
|
+
--> statement-breakpoint
|
|
8
|
+
CREATE TABLE "journal_entries" (
|
|
9
|
+
"entry_id" text PRIMARY KEY NOT NULL,
|
|
10
|
+
"position" bigint NOT NULL,
|
|
11
|
+
"extension" text NOT NULL,
|
|
12
|
+
"subject" text NOT NULL,
|
|
13
|
+
"payload" jsonb NOT NULL,
|
|
14
|
+
"schema_version" text NOT NULL,
|
|
15
|
+
"key" text NOT NULL,
|
|
16
|
+
"order_key" text,
|
|
17
|
+
"origin" jsonb NOT NULL,
|
|
18
|
+
"recorded_at" bigint NOT NULL
|
|
19
|
+
);
|
|
20
|
+
--> statement-breakpoint
|
|
21
|
+
CREATE TABLE "journal_position_counter" (
|
|
22
|
+
"id" text PRIMARY KEY NOT NULL,
|
|
23
|
+
"value" bigint DEFAULT 0 NOT NULL,
|
|
24
|
+
CONSTRAINT "journal_position_counter_singleton_ck" CHECK ("journal_position_counter"."id" = 'journal')
|
|
25
|
+
);
|
|
26
|
+
--> statement-breakpoint
|
|
27
|
+
CREATE TABLE "journal_reader_cursors" (
|
|
28
|
+
"reader" text PRIMARY KEY NOT NULL,
|
|
29
|
+
"position" bigint NOT NULL
|
|
30
|
+
);
|
|
31
|
+
--> statement-breakpoint
|
|
32
|
+
CREATE TABLE "journal_reader_states" (
|
|
33
|
+
"reader" text NOT NULL,
|
|
34
|
+
"entry_id" text NOT NULL,
|
|
35
|
+
"position" bigint NOT NULL,
|
|
36
|
+
"order_key" text,
|
|
37
|
+
"state" text NOT NULL,
|
|
38
|
+
"retries" integer DEFAULT 0 NOT NULL,
|
|
39
|
+
"reason" text,
|
|
40
|
+
"not_before" bigint,
|
|
41
|
+
"claim_token" text,
|
|
42
|
+
"claim_expires_at" bigint,
|
|
43
|
+
CONSTRAINT "journal_reader_states_pk" PRIMARY KEY("reader","entry_id"),
|
|
44
|
+
CONSTRAINT "journal_reader_states_state_ck" CHECK ("journal_reader_states"."state" IN ('open', 'done', 'failed'))
|
|
45
|
+
);
|
|
46
|
+
--> statement-breakpoint
|
|
47
|
+
CREATE UNIQUE INDEX "journal_entries_position_uq" ON "journal_entries" USING btree ("position");--> statement-breakpoint
|
|
48
|
+
CREATE UNIQUE INDEX "journal_entries_extension_key_uq" ON "journal_entries" USING btree ("extension","key");--> statement-breakpoint
|
|
49
|
+
CREATE INDEX "journal_entries_subject_position_idx" ON "journal_entries" USING btree ("subject","position");--> statement-breakpoint
|
|
50
|
+
CREATE INDEX "journal_reader_states_claim_idx" ON "journal_reader_states" USING btree ("reader","state","position");--> statement-breakpoint
|
|
51
|
+
CREATE INDEX "journal_reader_states_order_idx" ON "journal_reader_states" USING btree ("reader","order_key","position");
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@makaio/storage-pg",
|
|
3
3
|
"description": "Postgres storage engine for the Makaio framework: driver glue, error classification, and migration behavior registered through the storage engine seam.",
|
|
4
|
-
"version": "1.0.0-dev-
|
|
4
|
+
"version": "1.0.0-dev-1795548607801",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|