diff --git a/doc/DATABASE.md b/doc/DATABASE.md index ecb92a12e1c..d4508f845dd 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -133,6 +133,7 @@ DATABASE_PREPARED_STATEMENTS=false # use false when the pooler does not suppor DATABASE_POOL_MAX=25 # connection pool size; default: 10 DATABASE_IDLE_TIMEOUT_SECONDS=60 # close idle pooled connections; default: 60 (0 = keep open) DATABASE_CONNECT_TIMEOUT_SECONDS=10 # default: 30 +DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS=2000 # time for each address of the host before the next; default: 2000 DATABASE_MAX_LIFETIME_SECONDS=1800 # recycle a pooled connection after this long; default: 30-60 min (random) DATABASE_APPLICATION_NAME=paperclip # application_name in pg_stat_activity; default for the server's main pool: paperclip: ``` diff --git a/docs/deploy/database.md b/docs/deploy/database.md index 57cb92f5c4f..bab93856de4 100644 --- a/docs/deploy/database.md +++ b/docs/deploy/database.md @@ -73,7 +73,7 @@ statements longer than 8 KB. If a prepared statement fails because the pooler's stale after a schema change or was lost, Paperclip stops preparing that statement and retries it once unprepared. -Related optional client tuning: `DATABASE_POOL_MAX`, `DATABASE_IDLE_TIMEOUT_SECONDS`, `DATABASE_CONNECT_TIMEOUT_SECONDS`, `DATABASE_MAX_LIFETIME_SECONDS`, `DATABASE_APPLICATION_NAME`. Driver defaults apply when unset, except that idle pooled connections close after 60 seconds (`DATABASE_IDLE_TIMEOUT_SECONDS=0` keeps them open) and the server's main pool reports `application_name=paperclip:` (other pools use names that start with `paperclip`). See [Connection pool settings](#connection-pool-settings). +Related optional client tuning: `DATABASE_POOL_MAX`, `DATABASE_IDLE_TIMEOUT_SECONDS`, `DATABASE_CONNECT_TIMEOUT_SECONDS`, `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS`, `DATABASE_MAX_LIFETIME_SECONDS`, `DATABASE_APPLICATION_NAME`. Driver defaults apply when unset, except that idle pooled connections close after 60 seconds (`DATABASE_IDLE_TIMEOUT_SECONDS=0` keeps them open), each address of the database host gets 2 seconds to answer a connection attempt, and the server's main pool reports `application_name=paperclip:` (other pools use names that start with `paperclip`). See [Connection pool settings](#connection-pool-settings). ## Connection Pool Settings @@ -84,6 +84,7 @@ The server opens one postgres.js pool for its own queries (and a second one when | `DATABASE_POOL_MAX` | `10` (driver) | Maximum pooled connections. | | `DATABASE_IDLE_TIMEOUT_SECONDS` | `60` | Close a pooled connection after this much idle time. `0` keeps idle connections open forever (the driver default). | | `DATABASE_CONNECT_TIMEOUT_SECONDS` | `30` (driver) | Give up on a connection attempt after this long. | +| `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS` | `2000` | When the database host name resolves to several addresses, wait this long for one address before trying the next. Node's own default (250 ms) is shorter than one TCP retransmission, so a single dropped packet could fail the connection. `DATABASE_CONNECT_TIMEOUT_SECONDS` still bounds the whole attempt. | | `DATABASE_MAX_LIFETIME_SECONDS` | 30–60 min, randomized (driver) | Recycle a pooled connection once it is this old. | | `DATABASE_APPLICATION_NAME` | `paperclip:` (server main pool) | Value of `application_name` in `pg_stat_activity`. The boot id tells the sessions of each server process apart after a restart. Find Paperclip's backends with `SELECT * FROM pg_stat_activity WHERE application_name LIKE 'paperclip%';` | | `DATABASE_DEDICATED_CONNECTION_MAX` | `24` | Dedicated lock connections in use at once per process before new callers wait. Nested callers do not wait. | diff --git a/packages/db/src/client-options.test.ts b/packages/db/src/client-options.test.ts index 3e4836e7ad8..c31a35180a2 100644 --- a/packages/db/src/client-options.test.ts +++ b/packages/db/src/client-options.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { DEFAULT_DATABASE_APPLICATION_NAME, + DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS, DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS, databaseClientOptionsFromEnv, postgresJsOptions, @@ -35,6 +36,7 @@ describe("databaseClientOptionsFromEnv", () => { DATABASE_POOL_MAX: "25", DATABASE_IDLE_TIMEOUT_SECONDS: "60", DATABASE_CONNECT_TIMEOUT_SECONDS: "10", + DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS: "1500", DATABASE_MAX_LIFETIME_SECONDS: "1800", DATABASE_APPLICATION_NAME: " paperclip-web ", }), @@ -42,6 +44,7 @@ describe("databaseClientOptionsFromEnv", () => { maxConnections: 25, idleTimeoutSeconds: 60, connectTimeoutSeconds: 10, + connectAttemptTimeoutMs: 1500, maxLifetimeSeconds: 1800, applicationName: "paperclip-web", }); @@ -60,6 +63,9 @@ describe("databaseClientOptionsFromEnv", () => { expect(() => databaseClientOptionsFromEnv({ DATABASE_CONNECT_TIMEOUT_SECONDS: "1.5" })).toThrow( /DATABASE_CONNECT_TIMEOUT_SECONDS/, ); + expect(() => databaseClientOptionsFromEnv({ DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS: "0" })).toThrow( + /DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS/, + ); expect(() => databaseClientOptionsFromEnv({ DATABASE_IDLE_TIMEOUT_SECONDS: "-1" })).toThrow( /DATABASE_IDLE_TIMEOUT_SECONDS/, ); @@ -81,6 +87,7 @@ describe("databaseClientOptionsFromEnv", () => { maxConnections: 25, idleTimeoutSeconds: 60, connectTimeoutSeconds: 10, + connectAttemptTimeoutMs: 1500, maxLifetimeSeconds: 1800, applicationName: "paperclip-web", }), @@ -89,6 +96,7 @@ describe("databaseClientOptionsFromEnv", () => { max: 25, idle_timeout: 60, connect_timeout: 10, + auto_select_family_attempt_timeout: 1500, max_lifetime: 1800, connection: { application_name: "paperclip-web" }, }); @@ -102,13 +110,15 @@ describe("databaseClientOptionsFromEnv", () => { }); describe("resolveDatabaseClientOptions", () => { - it("reaps idle connections and names the pool when the environment sets nothing", () => { + it("reaps idle connections, bounds each address attempt and names the pool when the environment sets nothing", () => { expect(resolveDatabaseClientOptions({})).toEqual({ idleTimeoutSeconds: DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS, + connectAttemptTimeoutMs: DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS, applicationName: DEFAULT_DATABASE_APPLICATION_NAME, }); expect(postgresJsOptions(resolveDatabaseClientOptions(databaseClientOptionsFromEnv({})))).toEqual({ idle_timeout: DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS, + auto_select_family_attempt_timeout: DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS, connection: { application_name: DEFAULT_DATABASE_APPLICATION_NAME }, }); }); @@ -118,9 +128,10 @@ describe("resolveDatabaseClientOptions", () => { resolveDatabaseClientOptions({ maxConnections: 3, idleTimeoutSeconds: 0, + connectAttemptTimeoutMs: 500, applicationName: "paperclip-cli", }), - ).toEqual({ maxConnections: 3, idleTimeoutSeconds: 0, applicationName: "paperclip-cli" }); + ).toEqual({ maxConnections: 3, idleTimeoutSeconds: 0, connectAttemptTimeoutMs: 500, applicationName: "paperclip-cli" }); expect(postgresJsOptions(resolveDatabaseClientOptions({ idleTimeoutSeconds: 0 }))).toMatchObject({ idle_timeout: 0, }); diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 303d460e803..2045df0fa86 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -151,6 +151,13 @@ export interface DatabaseClientOptions { idleTimeoutSeconds?: number; /** postgres.js `connect_timeout` in seconds (driver default: 30). */ connectTimeoutSeconds?: number; + /** + * Time in milliseconds that one connection attempt gives each address of the + * database host before it tries the next one (Node's + * `autoSelectFamilyAttemptTimeout`, default 250). The whole attempt is still + * bounded by `connectTimeoutSeconds`. + */ + connectAttemptTimeoutMs?: number; /** * postgres.js `max_lifetime` in seconds. Bounds how long one pooled * connection is reused before the client replaces it (driver default: a @@ -183,6 +190,16 @@ export interface DatabaseClientOptions { export const DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS = 60; /** `application_name` reported to PostgreSQL unless `DATABASE_APPLICATION_NAME` overrides it. */ export const DEFAULT_DATABASE_APPLICATION_NAME = "paperclip"; +/** + * Each address of the database host gets this many milliseconds unless + * `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS` says otherwise. Node's own default of + * 250 ms is shorter than the first SYN retransmission (1 s on Linux). When the + * host name also has AAAA records and this machine has no IPv6 route, the last + * address fails at once, so a connection failed after about 750 ms when one + * packet was dropped, long before `connect_timeout`. 2 s lets each address + * answer a retransmitted SYN. + */ +export const DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS = 2_000; function envBoolean(env: NodeJS.ProcessEnv, name: string): boolean | undefined { const value = env[name]?.trim().toLowerCase(); @@ -235,6 +252,8 @@ export function databaseClientOptionsFromEnv(env: NodeJS.ProcessEnv = process.en if (idleTimeoutSeconds !== undefined) options.idleTimeoutSeconds = idleTimeoutSeconds; const connectTimeoutSeconds = envPositiveInteger(env, "DATABASE_CONNECT_TIMEOUT_SECONDS"); if (connectTimeoutSeconds !== undefined) options.connectTimeoutSeconds = connectTimeoutSeconds; + const connectAttemptTimeoutMs = envPositiveInteger(env, "DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS"); + if (connectAttemptTimeoutMs !== undefined) options.connectAttemptTimeoutMs = connectAttemptTimeoutMs; const maxLifetimeSeconds = envPositiveInteger(env, "DATABASE_MAX_LIFETIME_SECONDS"); if (maxLifetimeSeconds !== undefined) options.maxLifetimeSeconds = maxLifetimeSeconds; const applicationName = envNonEmptyString(env, "DATABASE_APPLICATION_NAME"); @@ -248,15 +267,17 @@ export function databaseClientOptionsFromEnv(env: NodeJS.ProcessEnv = process.en /** * Fills in Paperclip's defaults for the options the caller left unset: idle - * connections are reaped after `DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS`, and the - * pool identifies itself as `DEFAULT_DATABASE_APPLICATION_NAME`. Everything - * else stays at the driver default. An explicit value (including + * connections are reaped after `DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS`, each + * address of the database host gets `DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS`, + * and the pool identifies itself as `DEFAULT_DATABASE_APPLICATION_NAME`. + * Everything else stays at the driver default. An explicit value (including * `idleTimeoutSeconds: 0`) always wins over the default. */ export function resolveDatabaseClientOptions(options: DatabaseClientOptions): DatabaseClientOptions { return { ...options, idleTimeoutSeconds: options.idleTimeoutSeconds ?? DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS, + connectAttemptTimeoutMs: options.connectAttemptTimeoutMs ?? DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS, applicationName: options.applicationName ?? DEFAULT_DATABASE_APPLICATION_NAME, }; } @@ -267,6 +288,10 @@ export function postgresJsOptions(options: DatabaseClientOptions): Record = {}; if (options.applicationName !== undefined) connection.application_name = options.applicationName; diff --git a/packages/db/src/postgres-connect-attempt-timeout.test.ts b/packages/db/src/postgres-connect-attempt-timeout.test.ts new file mode 100644 index 00000000000..660b13ed64b --- /dev/null +++ b/packages/db/src/postgres-connect-attempt-timeout.test.ts @@ -0,0 +1,48 @@ +import net from "node:net"; +import postgres from "postgres"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS, + postgresJsOptions, + resolveDatabaseClientOptions, +} from "./client.js"; + +// Node tries each address of a database host name in turn (happy eyeballs) and +// by default gives every address but the last only 250 ms. When the last +// address is IPv6 on a host with no IPv6 route, it fails at once, so a host +// name with three A and three AAAA records fails to connect after about 750 ms +// whatever `connect_timeout` says. A single dropped SYN then fails the query. +describe("database connect attempt timeout", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("gives each address of the database host enough time for a retransmitted SYN by default", () => { + expect(DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS).toBeGreaterThanOrEqual(1_000); + expect(postgresJsOptions(resolveDatabaseClientOptions({}))).toMatchObject({ + auto_select_family_attempt_timeout: DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS, + }); + }); + + it("passes the per-address budget to the socket that postgres.js opens", async () => { + const connect = vi.spyOn(net.Socket.prototype, "connect"); + // Port 1 on loopback refuses at once; only the connect arguments matter. + const sql = postgres("postgres://paperclip:unused@127.0.0.1:1/paperclip", { + ...postgresJsOptions(resolveDatabaseClientOptions({ connectTimeoutSeconds: 5 })), + max: 1, + onnotice: () => {}, + }); + try { + await expect(sql`select 1`).rejects.toMatchObject({ code: "ECONNREFUSED" }); + } finally { + await sql.end({ timeout: 0 }); + } + + expect(connect).toHaveBeenCalled(); + expect(connect.mock.calls[0]?.[0]).toMatchObject({ + host: "127.0.0.1", + port: 1, + autoSelectFamilyAttemptTimeout: DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS, + }); + }); +}); diff --git a/patches/postgres@3.4.9.patch b/patches/postgres@3.4.9.patch index b9cd7a82c8f..598df858e19 100644 --- a/patches/postgres@3.4.9.patch +++ b/patches/postgres@3.4.9.patch @@ -1,5 +1,5 @@ diff --git a/cjs/src/connection.js b/cjs/src/connection.js -index 07f6716702ac888215c86ad6e0071aaf55ae519c..4ee75faa8ae47555576e3b4e0ec6b7c4b140ec2f 100644 +index 07f6716702ac888215c86ad6e0071aaf55ae519c..3ecac096b4d757364d4a9b33add6ded4eecbd80f 100644 --- a/cjs/src/connection.js +++ b/cjs/src/connection.js @@ -173,8 +173,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose @@ -21,7 +21,22 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..4ee75faa8ae47555576e3b4e0ec6b7c4 } async function connect() { -@@ -438,6 +440,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose +@@ -351,7 +353,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose + return socket.connect(options.path) + + socket.ssl = ssl +- socket.connect(port[hostIndex], host[hostIndex]) ++ socket.connect({ ++ port: port[hostIndex], ++ host: host[hostIndex], ++ ...(options.auto_select_family_attempt_timeout ++ ? { autoSelectFamilyAttemptTimeout: options.auto_select_family_attempt_timeout } ++ : {}) ++ }) + socket.host = host[hostIndex] + socket.port = port[hostIndex] + +@@ -438,6 +446,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose remaining = 0 incomings = null clearImmediate(nextWriteTimer) @@ -29,7 +44,7 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..4ee75faa8ae47555576e3b4e0ec6b7c4 socket.removeListener('data', data) socket.removeListener('connect', connected) idleTimer.cancel() -@@ -451,6 +454,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose +@@ -451,6 +460,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose return reconnect() !hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket)) @@ -40,7 +55,7 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..4ee75faa8ae47555576e3b4e0ec6b7c4 hadError && options.shared.retries++ delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000 diff --git a/cjs/src/index.js b/cjs/src/index.js -index f09c61c7e998f411560b95c9a8e1ed6a97972c11..04dded5c7e2cdc34ac01b29a87cc93248ec8c9c6 100644 +index f09c61c7e998f411560b95c9a8e1ed6a97972c11..5ae05848b627d4e7b849eb093a3d9ceb7f922b6d 100644 --- a/cjs/src/index.js +++ b/cjs/src/index.js @@ -216,8 +216,19 @@ function Postgres(a, b) { @@ -102,6 +117,14 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..04dded5c7e2cdc34ac01b29a87cc9324 c.queue === full ? queries.push(q) : c.execute(q) || move(c, full) +@@ -493,6 +514,7 @@ function parseOptions(a, b) { + onclose : o.onclose, + onparameter : o.onparameter, + socket : o.socket, ++ auto_select_family_attempt_timeout: o.auto_select_family_attempt_timeout, + transform : parseTransform(o.transform || { undefined: undefined }), + parameters : {}, + shared : { retries: 0, typeArrayMap: {} }, diff --git a/cjs/src/queue.js b/cjs/src/queue.js index 8438f5da92cf7637d98a33491d75c75b1c817c25..1c9a330fa173ecae84219055368cf630feadbda2 100644 --- a/cjs/src/queue.js @@ -131,7 +154,7 @@ index 8438f5da92cf7637d98a33491d75c75b1c817c25..1c9a330fa173ecae84219055368cf630 xs[index - 1] = undefined } diff --git a/src/connection.js b/src/connection.js -index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..0a4c4cc185f14afa30c7c6a294bafe689e685683 100644 +index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..a5057f0d1b03898b4c22b8711498871f200cce69 100644 --- a/src/connection.js +++ b/src/connection.js @@ -173,8 +173,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose @@ -153,7 +176,22 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..0a4c4cc185f14afa30c7c6a294bafe68 } async function connect() { -@@ -438,6 +440,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose +@@ -351,7 +353,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose + return socket.connect(options.path) + + socket.ssl = ssl +- socket.connect(port[hostIndex], host[hostIndex]) ++ socket.connect({ ++ port: port[hostIndex], ++ host: host[hostIndex], ++ ...(options.auto_select_family_attempt_timeout ++ ? { autoSelectFamilyAttemptTimeout: options.auto_select_family_attempt_timeout } ++ : {}) ++ }) + socket.host = host[hostIndex] + socket.port = port[hostIndex] + +@@ -438,6 +446,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose remaining = 0 incomings = null clearImmediate(nextWriteTimer) @@ -161,7 +199,7 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..0a4c4cc185f14afa30c7c6a294bafe68 socket.removeListener('data', data) socket.removeListener('connect', connected) idleTimer.cancel() -@@ -451,6 +454,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose +@@ -451,6 +460,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose return reconnect() !hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket)) @@ -172,7 +210,7 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..0a4c4cc185f14afa30c7c6a294bafe68 hadError && options.shared.retries++ delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000 diff --git a/src/index.js b/src/index.js -index c7fba3dace20173f4cb13f3f138bb6d213b43683..f0888986add8ba02c8853f792ae42dd1cec88c82 100644 +index c7fba3dace20173f4cb13f3f138bb6d213b43683..59fcbc0d44e709e86abdf34e47ad6bc98a9e6974 100644 --- a/src/index.js +++ b/src/index.js @@ -216,8 +216,19 @@ function Postgres(a, b) { @@ -234,6 +272,14 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..f0888986add8ba02c8853f792ae42dd1 c.queue === full ? queries.push(q) : c.execute(q) || move(c, full) +@@ -493,6 +514,7 @@ function parseOptions(a, b) { + onclose : o.onclose, + onparameter : o.onparameter, + socket : o.socket, ++ auto_select_family_attempt_timeout: o.auto_select_family_attempt_timeout, + transform : parseTransform(o.transform || { undefined: undefined }), + parameters : {}, + shared : { retries: 0, typeArrayMap: {} }, diff --git a/src/queue.js b/src/queue.js index c4ef97164f057db99dce1b9af3401dbb1af37e31..46e7ade55c0a3250137a21117c03ce9166b40bc2 100644 --- a/src/queue.js