@cubicecho/server-kit 0.8.1 → 0.9.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.
@@ -27,5 +27,6 @@ stopOnSignals(server, { before: () => scheduler.stop(), after: closeDatabase });
27
27
  - `checkHealth` logs why Postgres did not answer and never says it: anyone may ask, and a driver's error names hosts.
28
28
  - `createStaticHandler` keeps `/assets/` and `/_expo/` files for a year, and answers 404 for one that is gone. Anything else that is not a file is `index.html`.
29
29
  - `stopOnSignals` drains, runs `after`, and exits within `shutdownDeadlineSeconds`, under Docker's 10. A second signal exits at once.
30
+ - `cutOff` runs at the drain deadline and is awaited before the open connections are cut: end SSE streams there, so a client reads a clean end instead of a reset.
30
31
  - `oidcSignInUrl` and `oidcRedirectUri` name the two OIDC routes for a provider.
31
32
  - `toHeaders` copies Node's headers into fetch `Headers`, for a door that reads its own caller.
@@ -0,0 +1,47 @@
1
+ # Database lock
2
+
3
+ `@cubicecho/server-kit/lock` makes one process the only one that uses a database, for an app that keeps what it serves in memory. It is a Postgres advisory lock held on a connection of its own. It needs no peer: the connection is a `pg.Client` the app makes.
4
+
5
+ ```ts
6
+ import { DatabaseLockError, holdPostgresLock } from '@cubicecho/server-kit/lock';
7
+ import pg from 'pg';
8
+
9
+ const connectionString = process.env.DATABASE_URL ?? '';
10
+ const pool = new pg.Pool({ connectionString });
11
+ pool.on('error', (error) => console.warn(`[db] an idle connection dropped: ${error.message}`));
12
+
13
+ const session = new pg.Client({ connectionString, keepAlive: true, keepAliveInitialDelayMillis: 10_000 });
14
+
15
+ let release: () => Promise<void>;
16
+ try {
17
+ release = await holdPostgresLock(session, {
18
+ app: 'my-app',
19
+ key: 'my-app',
20
+ advice: 'Stop the other one first.',
21
+ onLost: (error) => {
22
+ console.error(`[db] ${error.message}`);
23
+ process.exit(1);
24
+ },
25
+ });
26
+ } catch (error) {
27
+ if (error instanceof DatabaseLockError) {
28
+ console.error(`[db] ${error.message}`);
29
+ process.exit(1);
30
+ }
31
+ throw error;
32
+ }
33
+
34
+ export async function close(): Promise<void> {
35
+ await pool.end();
36
+ await release();
37
+ }
38
+ ```
39
+
40
+ - Take it after the database answers and before migrating.
41
+ - **`onLost` has to end the process**, at once and without writing: another process may hold the lock by then. Run the app under something that restarts it.
42
+ - Turn on `keepAlive`, or a connection that dies in silence goes unnoticed.
43
+ - End the pool before `release()`, so the last write is in before another process may start.
44
+ - `key` is a name, which Postgres hashes, or a `bigint`. It has to stay the same in every version of the app, or two versions run side by side.
45
+ - `waitMs` (15 s) is how long to wait for a holder to stop, and `retryDelayMs` (1 s) how often to look. They override `LOCK_DEFAULTS`.
46
+ - Any error but a `DatabaseLockError` is the driver's own. The connection is closed either way.
47
+ - After a silent network loss, Postgres holds the old connection's lock until it notices, so a restarted process is refused until then.
@@ -21,3 +21,15 @@ Each insert has a new id, so it never conflicts on it, and the unique index refu
21
21
  ## Importing the testing entry in a server
22
22
 
23
23
  `@cubicecho/server-kit/testing` imports Vitest and PGlite, which are dev dependencies. Import it only from tests.
24
+
25
+ ## Taking the lock on a pool connection
26
+
27
+ The pool lends a connection out with no `error` listener, so losing it crashes the process with no word of the lock. Give `holdPostgresLock` a `pg.Client` of its own.
28
+
29
+ ## A `pg.Pool` with no `error` listener
30
+
31
+ `pg` emits an idle connection's error on the pool, and Node ends a process that doesn't listen. A Postgres restart is enough. The pool has already let go of that connection, so log it and carry on.
32
+
33
+ ```ts
34
+ pool.on('error', (error) => console.warn(`[db] an idle connection dropped: ${error.message}`));
35
+ ```
@@ -4,6 +4,8 @@ import { type HttpSettings } from './defaults.ts';
4
4
  export interface ShutdownSteps {
5
5
  /** Stops starting new work (timers, queue pollers). Runs as soon as the signal arrives. */
6
6
  before?: () => unknown;
7
+ /** Ends what never finishes on its own (SSE streams) cleanly. Runs at the drain deadline, before connections are cut. */
8
+ cutOff?: () => unknown;
7
9
  /** Closes what requests were using (MCP sessions, the pool). Runs once the server has drained. */
8
10
  after?: () => unknown;
9
11
  }
@@ -12,14 +14,16 @@ export interface ShutdownSteps {
12
14
  *
13
15
  * @param server - The HTTP server.
14
16
  * @param drainSeconds - How long requests in flight get before their sockets are closed.
17
+ * @param [cutOff] - Awaited at that deadline, before the sockets are closed.
15
18
  * @returns Resolves once the server has closed.
19
+ * @throws What `cutOff` threw, once the server has closed anyway.
16
20
  */
17
- export declare function drain(server: Server, drainSeconds: number): Promise<void>;
21
+ export declare function drain(server: Server, drainSeconds: number, cutOff?: () => unknown): Promise<void>;
18
22
  /**
19
23
  * On SIGTERM or SIGINT: stops accepting, lets in-flight requests finish, closes, exits. A second signal exits at once.
20
24
  *
21
25
  * @param server - The listening server.
22
- * @param [steps] - Work to stop before the drain, and resources to close after it.
26
+ * @param [steps] - Work to stop before the drain, streams to end at its deadline, and resources to close after it.
23
27
  * @param [overrides] - Settings that differ from `HTTP_DEFAULTS`.
24
28
  */
25
- export declare function stopOnSignals(server: Server, { before, after }?: ShutdownSteps, overrides?: Partial<Pick<HttpSettings, 'drainSeconds' | 'shutdownDeadlineSeconds'>>): void;
29
+ export declare function stopOnSignals(server: Server, { before, cutOff, after }?: ShutdownSteps, overrides?: Partial<Pick<HttpSettings, 'drainSeconds' | 'shutdownDeadlineSeconds'>>): void;
@@ -7,15 +7,30 @@ const STOP_SIGNALS = ['SIGTERM', 'SIGINT'];
7
7
  *
8
8
  * @param server - The HTTP server.
9
9
  * @param drainSeconds - How long requests in flight get before their sockets are closed.
10
+ * @param [cutOff] - Awaited at that deadline, before the sockets are closed.
10
11
  * @returns Resolves once the server has closed.
12
+ * @throws What `cutOff` threw, once the server has closed anyway.
11
13
  */
12
- export function drain(server, drainSeconds) {
13
- return new Promise((resolve) => {
14
+ export function drain(server, drainSeconds, cutOff) {
15
+ return new Promise((resolve, reject) => {
16
+ let failure = null;
14
17
  // Subscriptions never finish on their own.
15
- const cutOff = setTimeout(() => server.closeAllConnections(), drainSeconds * MS_PER_SECOND);
18
+ const deadline = setTimeout(async () => {
19
+ try {
20
+ await cutOff?.();
21
+ }
22
+ catch (error) {
23
+ failure = { error };
24
+ }
25
+ server.closeAllConnections();
26
+ }, drainSeconds * MS_PER_SECOND);
16
27
  server.close(() => {
17
- clearTimeout(cutOff);
18
- resolve();
28
+ clearTimeout(deadline);
29
+ if (failure === null) {
30
+ resolve();
31
+ return;
32
+ }
33
+ reject(failure.error);
19
34
  });
20
35
  server.closeIdleConnections();
21
36
  });
@@ -24,10 +39,10 @@ export function drain(server, drainSeconds) {
24
39
  * On SIGTERM or SIGINT: stops accepting, lets in-flight requests finish, closes, exits. A second signal exits at once.
25
40
  *
26
41
  * @param server - The listening server.
27
- * @param [steps] - Work to stop before the drain, and resources to close after it.
42
+ * @param [steps] - Work to stop before the drain, streams to end at its deadline, and resources to close after it.
28
43
  * @param [overrides] - Settings that differ from `HTTP_DEFAULTS`.
29
44
  */
30
- export function stopOnSignals(server, { before, after } = {}, overrides = {}) {
45
+ export function stopOnSignals(server, { before, cutOff, after } = {}, overrides = {}) {
31
46
  const { drainSeconds, shutdownDeadlineSeconds } = { ...HTTP_DEFAULTS, ...overrides };
32
47
  let isStopping = false;
33
48
  const stop = async (signal) => {
@@ -42,7 +57,7 @@ export function stopOnSignals(server, { before, after } = {}, overrides = {}) {
42
57
  }, shutdownDeadlineSeconds * MS_PER_SECOND).unref();
43
58
  try {
44
59
  await before?.();
45
- await drain(server, drainSeconds);
60
+ await drain(server, drainSeconds, cutOff);
46
61
  await after?.();
47
62
  }
48
63
  catch (error) {
@@ -0,0 +1,9 @@
1
+ /** Settings for taking the lock. */
2
+ export interface LockSettings {
3
+ /** How long to wait for another process to let go: a restarted container can start before the old one has stopped. */
4
+ waitMs: number;
5
+ /** How long to wait between two tries. */
6
+ retryDelayMs: number;
7
+ }
8
+ /** What taking the lock uses when the app overrides nothing. */
9
+ export declare const LOCK_DEFAULTS: Readonly<LockSettings>;
@@ -0,0 +1,6 @@
1
+ // Every value someone might tune, as plain data. Nothing here computes, reads the environment or imports.
2
+ /** What taking the lock uses when the app overrides nothing. */
3
+ export const LOCK_DEFAULTS = Object.freeze({
4
+ waitMs: 15_000,
5
+ retryDelayMs: 1_000,
6
+ });
@@ -0,0 +1,23 @@
1
+ import { DatabaseBootError } from '../db/errors.ts';
2
+ /** Why a process can't use the database. */
3
+ export declare const DatabaseLockErrorCode: {
4
+ /** Another process holds the lock. */
5
+ readonly InUse: 'DATABASE_IN_USE';
6
+ /** The connection that held the lock dropped, so the lock is gone. */
7
+ readonly Lost: 'DATABASE_LOCK_LOST';
8
+ };
9
+ /** One of the values in `DatabaseLockErrorCode`. */
10
+ export type DatabaseLockErrorCode = (typeof DatabaseLockErrorCode)[keyof typeof DatabaseLockErrorCode];
11
+ /** A database lock that was refused or lost. Its message is written for whoever runs the server. */
12
+ export declare class DatabaseLockError extends DatabaseBootError {
13
+ name: string;
14
+ /** What went wrong. */
15
+ readonly code: DatabaseLockErrorCode;
16
+ /**
17
+ * Makes the error.
18
+ *
19
+ * @param code - What went wrong.
20
+ * @param message - What to do about it.
21
+ */
22
+ constructor(code: DatabaseLockErrorCode, message: string);
23
+ }
@@ -0,0 +1,24 @@
1
+ import { DatabaseBootError } from '../db/errors.js';
2
+ /** Why a process can't use the database. */
3
+ export const DatabaseLockErrorCode = {
4
+ /** Another process holds the lock. */
5
+ InUse: 'DATABASE_IN_USE',
6
+ /** The connection that held the lock dropped, so the lock is gone. */
7
+ Lost: 'DATABASE_LOCK_LOST',
8
+ };
9
+ /** A database lock that was refused or lost. Its message is written for whoever runs the server. */
10
+ export class DatabaseLockError extends DatabaseBootError {
11
+ name = 'DatabaseLockError';
12
+ /** What went wrong. */
13
+ code;
14
+ /**
15
+ * Makes the error.
16
+ *
17
+ * @param code - What went wrong.
18
+ * @param message - What to do about it.
19
+ */
20
+ constructor(code, message) {
21
+ super(message);
22
+ this.code = code;
23
+ }
24
+ }
@@ -0,0 +1,49 @@
1
+ import { type LockSettings } from './defaults.ts';
2
+ import { DatabaseLockError } from './errors.ts';
3
+ /** The connection that holds the lock: a `pg.Client` of its own, not yet open, and never one from a pool. */
4
+ export interface LockSession {
5
+ connect: () => Promise<unknown>;
6
+ query: (text: string, values: unknown[]) => Promise<{
7
+ rows: Record<string, unknown>[];
8
+ }>;
9
+ on(event: 'error', listener: (error: Error) => void): unknown;
10
+ on(event: 'end', listener: () => void): unknown;
11
+ end: () => Promise<void>;
12
+ }
13
+ /** Lets the lock go. Safe to call twice. */
14
+ export type ReleaseLock = () => Promise<void>;
15
+ /** How the lock is taken. */
16
+ export interface LockOptions extends Partial<LockSettings> {
17
+ /** What the app is called, for the messages. */
18
+ app: string;
19
+ /** What the lock is on: a name, which Postgres hashes, or a number of the app's own. The same in every version. */
20
+ key: string | bigint;
21
+ /**
22
+ * Called once if the connection drops while the lock is held. From then on another process may take it, so the app
23
+ * has to stop without writing anything more.
24
+ */
25
+ onLost: (error: DatabaseLockError) => void;
26
+ /**
27
+ * What to do about a lock that another process holds, added to the refusal.
28
+ *
29
+ * @defaultValue none
30
+ */
31
+ advice?: string;
32
+ /**
33
+ * Told once, when the first try finds the lock held.
34
+ *
35
+ * @defaultValue `console.warn`
36
+ */
37
+ log?: (message: string) => void;
38
+ }
39
+ /**
40
+ * Makes this process the only one that uses a database, with an advisory lock on a connection of its own. Nothing else
41
+ * runs on that connection, so a pool's connections come and go without letting the lock go.
42
+ *
43
+ * @param session - A connection not yet open.
44
+ * @param options - What to lock, and what to do when the lock is lost.
45
+ * @returns What ends the connection, letting the lock go.
46
+ * @throws {@link DatabaseLockError} `DATABASE_IN_USE` when another process keeps the lock, or `DATABASE_LOCK_LOST` when
47
+ * the connection drops as it is taken. The driver's own error when the connection fails. It is closed either way.
48
+ */
49
+ export declare function holdPostgresLock(session: LockSession, options: LockOptions): Promise<ReleaseLock>;
@@ -0,0 +1,117 @@
1
+ import { setTimeout as sleep } from 'node:timers/promises';
2
+ import { LOCK_DEFAULTS } from './defaults.js';
3
+ import { DatabaseLockError, DatabaseLockErrorCode } from './errors.js';
4
+ const MS_PER_SECOND = 1000;
5
+ /**
6
+ * Writes the key as Postgres takes it.
7
+ *
8
+ * @param key - The key.
9
+ * @returns The expression, whose `$1` is `value`.
10
+ */
11
+ function keyParameter(key) {
12
+ return typeof key === 'bigint'
13
+ ? { expression: '$1::bigint', value: String(key) }
14
+ : { expression: 'hashtext($1)::bigint', value: key };
15
+ }
16
+ /**
17
+ * Says who holds the lock. Best effort: the holder may let go in between, and a role without `pg_read_all_stats` sees
18
+ * no other role's address.
19
+ *
20
+ * @param session - The lock's connection.
21
+ * @param key - The key, as `keyParameter` writes it.
22
+ * @returns The holder's Postgres process and the address it connects from.
23
+ *
24
+ * @remarks
25
+ * Postgres files a bigint key as its high 32 bits in `classid`, its low 32 bits in `objid` and 1 in `objsubid`.
26
+ */
27
+ async function describeHolder(session, key) {
28
+ const findHolder = `select l.pid, host(a.client_addr) as address
29
+ from pg_locks l left join pg_stat_activity a on a.pid = l.pid
30
+ where l.locktype = 'advisory' and l.granted and l.objsubid = 1
31
+ and l.database = (select oid from pg_database where datname = current_database())
32
+ and l.classid = ((${key.expression} >> 32) & 4294967295)::oid
33
+ and l.objid = (${key.expression} & 4294967295)::oid`;
34
+ try {
35
+ const { rows } = await session.query(findHolder, [key.value]);
36
+ const [row] = rows;
37
+ if (row === undefined) {
38
+ return 'it has just let go';
39
+ }
40
+ const from = typeof row.address === 'string' ? `from ${row.address}` : 'on a local socket';
41
+ return `Postgres process ${String(row.pid)}, connected ${from}`;
42
+ }
43
+ catch {
44
+ return 'its holder could not be read';
45
+ }
46
+ }
47
+ /**
48
+ * Makes this process the only one that uses a database, with an advisory lock on a connection of its own. Nothing else
49
+ * runs on that connection, so a pool's connections come and go without letting the lock go.
50
+ *
51
+ * @param session - A connection not yet open.
52
+ * @param options - What to lock, and what to do when the lock is lost.
53
+ * @returns What ends the connection, letting the lock go.
54
+ * @throws {@link DatabaseLockError} `DATABASE_IN_USE` when another process keeps the lock, or `DATABASE_LOCK_LOST` when
55
+ * the connection drops as it is taken. The driver's own error when the connection fails. It is closed either way.
56
+ */
57
+ export async function holdPostgresLock(session, options) {
58
+ const { app, onLost, advice, log = console.warn } = options;
59
+ const { waitMs = LOCK_DEFAULTS.waitMs, retryDelayMs = LOCK_DEFAULTS.retryDelayMs } = options;
60
+ const key = keyParameter(options.key);
61
+ let isHeld = false;
62
+ let isReleasing = false;
63
+ let dropped = null;
64
+ const lost = (reason) => new DatabaseLockError(DatabaseLockErrorCode.Lost, `The database lock was lost (its connection dropped: ${reason}), so another ${app} could now use this database. Stopping rather than go on without it; starting again takes the lock again.`);
65
+ const drop = (reason) => {
66
+ const isNews = dropped === null && isReleasing === false;
67
+ if (isNews === false) {
68
+ return;
69
+ }
70
+ dropped = reason;
71
+ if (isHeld) {
72
+ onLost(lost(reason));
73
+ }
74
+ };
75
+ // Before the lock is held, a failing query rejects on its own; this listener also stops an unhandled 'error'.
76
+ session.on('error', (error) => drop(error.message));
77
+ session.on('end', () => drop('the connection ended'));
78
+ const release = async () => {
79
+ if (isReleasing) {
80
+ return;
81
+ }
82
+ isReleasing = true;
83
+ await session.end();
84
+ };
85
+ const takeLock = async () => {
86
+ const deadline = Date.now() + waitMs;
87
+ for (let tries = 1;; tries += 1) {
88
+ const { rows } = await session.query(`select pg_try_advisory_lock(${key.expression}) as locked`, [key.value]);
89
+ if (rows[0]?.locked === true) {
90
+ return;
91
+ }
92
+ const holder = await describeHolder(session, key);
93
+ const isOutOfTime = Date.now() + retryDelayMs > deadline;
94
+ if (isOutOfTime) {
95
+ const refusal = `Another ${app} is already using this database (${holder}), and only one may.`;
96
+ throw new DatabaseLockError(DatabaseLockErrorCode.InUse, advice ? `${refusal} ${advice}` : refusal);
97
+ }
98
+ if (tries === 1) {
99
+ log(`[db] the database is in use (${holder}); waiting up to ${waitMs / MS_PER_SECOND} s for it to stop`);
100
+ }
101
+ await sleep(retryDelayMs);
102
+ }
103
+ };
104
+ try {
105
+ await session.connect();
106
+ await takeLock();
107
+ if (dropped !== null) {
108
+ throw lost(dropped);
109
+ }
110
+ }
111
+ catch (error) {
112
+ await release().catch(() => { });
113
+ throw error;
114
+ }
115
+ isHeld = true;
116
+ return release;
117
+ }
@@ -0,0 +1,3 @@
1
+ export { LOCK_DEFAULTS, type LockSettings } from './defaults.ts';
2
+ export { DatabaseLockError, DatabaseLockErrorCode } from './errors.ts';
3
+ export { holdPostgresLock, type LockOptions, type LockSession, type ReleaseLock } from './hold.ts';
@@ -0,0 +1,3 @@
1
+ export { LOCK_DEFAULTS } from './defaults.js';
2
+ export { DatabaseLockError, DatabaseLockErrorCode } from './errors.js';
3
+ export { holdPostgresLock } from './hold.js';
package/llms.txt CHANGED
@@ -15,6 +15,7 @@ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0 (optio
15
15
  - [GraphQL](_agents/docs/05-graphql.md): `@cubicecho/server-kit/graphql` has what every Yoga 6 server shares: operation limits, coded errors, input validation and a logger that never prints a request's variables.
16
16
  - [HTTP](_agents/docs/06-http.md): `@cubicecho/server-kit/http` has what surrounds an Express app: a clean stop, the health check, serving the built app, and the two OIDC redirects.
17
17
  - [MCP](_agents/docs/07-mcp.md): `@cubicecho/server-kit/mcp` has what every MCP door over a drizzle-graphql schema shares: how the caller is read, and the options that keep the listing small. It needs `@cubicecho/graphql-mcp`, an optional peer.
18
+ - [Database lock](_agents/docs/08-lock.md): `@cubicecho/server-kit/lock` makes one process the only one that uses a database, for an app that keeps what it serves in memory. It is a Postgres advisory lock held on a connection of its own. It needs no peer: the connection is a `pg.Client` the app makes.
18
19
  - [Common mistakes](_agents/docs/common-mistakes.md): What goes wrong when the kit is wired up slightly differently, and the fix for each.
19
20
 
20
21
  ## Exports: @cubicecho/server-kit/auth
@@ -127,6 +128,17 @@ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0 (optio
127
128
  - `StaticHandler` (type): A request handler, for Express or plain `node:http`.
128
129
  - `HttpStatus`: The HTTP statuses a server sends, and its tests expect.
129
130
 
131
+ ## Exports: @cubicecho/server-kit/lock
132
+
133
+ - `LOCK_DEFAULTS`: What taking the lock uses when the app overrides nothing.
134
+ - `LockSettings` (type): Settings for taking the lock.
135
+ - `DatabaseLockError`: A database lock that was refused or lost.
136
+ - `DatabaseLockErrorCode`: Why a process can't use the database.
137
+ - `holdPostgresLock`: Makes this process the only one that uses a database, with an advisory lock on a connection of its own.
138
+ - `LockOptions` (type): How the lock is taken.
139
+ - `LockSession` (type): The connection that holds the lock: a `pg.Client` of its own, not yet open, and never one from a pool.
140
+ - `ReleaseLock` (type): Lets the lock go.
141
+
130
142
  ## Exports: @cubicecho/server-kit/mcp
131
143
 
132
144
  - `MCP_DEFAULTS`: What the MCP helpers and `checkMcpBudget` use when the app overrides nothing.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cubicecho/server-kit",
3
- "version": "0.8.1",
3
+ "version": "0.9.0",
4
4
  "description": "The server code every cubicecho GraphQL backend shares: database boot, id columns and the checks that keep a schema to the standard.",
5
5
  "license": "MIT",
6
6
  "author": "Benjamin Van Treese",
@@ -43,6 +43,10 @@
43
43
  "types": "./dist/http/index.d.ts",
44
44
  "import": "./dist/http/index.js"
45
45
  },
46
+ "./lock": {
47
+ "types": "./dist/lock/index.d.ts",
48
+ "import": "./dist/lock/index.js"
49
+ },
46
50
  "./mcp": {
47
51
  "types": "./dist/mcp/index.d.ts",
48
52
  "import": "./dist/mcp/index.js"