fix(db): give each database address time for a retransmitted SYN (#23784)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server reads and writes all state through one postgres.js pool
in `packages/db`.
> - Sentry recorded a production query failure. Every address of the
database host failed to connect: `connect ETIMEDOUT` on three IPv4
addresses and `ENETUNREACH` on three IPv6 addresses.
> - Node tries the addresses of a host name in turn ("happy eyeballs").
It gives each address except the last only 250 ms. The last address was
IPv6 and this host has no IPv6 route, so it failed at once.
> - Thus the connection failed after about 750 ms. One dropped SYN was
sufficient, because Linux sends the first SYN again only after 1 s. The
30 s `connect_timeout` of postgres.js did not apply.
> - This pull request gives each address 2 s by default, so a
retransmitted SYN can get an answer.
> - The benefit is that a short network stall to the database no longer
fails queries.

## Linked Issues or Issue Description

No public GitHub issue exists. This is a bug report.

**What happened?**

A server query failed with `Failed query: select ... from "companies"
...`. The cause was an `AggregateError` with code `ETIMEDOUT`. Its
errors were `ETIMEDOUT`, `ENETUNREACH`, `ETIMEDOUT`, `ENETUNREACH`,
`ETIMEDOUT`, `ENETUNREACH`. Each `ETIMEDOUT` came from Node's
per-address attempt timer (`internalConnectMultipleTimeout`), not from
postgres.js.

**Steps to reproduce**

1. Use a database host name that resolves to IPv4 addresses and IPv6
addresses, on a machine without an IPv6 route.
2. Make the IPv4 addresses drop SYN packets for less than one second.
3. Run a query that opens a new pooled connection.

**Expected behavior**

The connection waits for a retransmitted SYN. It fails only after
`connect_timeout`.

**Actual behavior**

The connection fails after about 750 ms with `AggregateError`
`ETIMEDOUT`.

## What Changed

- `patches/postgres@3.4.9.patch`: postgres.js now calls
`socket.connect({ port, host, autoSelectFamilyAttemptTimeout })` when
the new `auto_select_family_attempt_timeout` option is set. Without the
option, the call is the same as before. The change is in both the ESM
and CJS builds.
- `packages/db/src/client.ts`: new `connectAttemptTimeoutMs` client
option and `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS` variable.
`resolveDatabaseClientOptions` sets a default of 2000 ms, so all pools
from `createDb` use it. `client.ts` was already longer than 1,000 lines.
This change adds the option next to the other driver options in that
file, because they share one parser and one mapping.
- `packages/db/src/postgres-connect-attempt-timeout.test.ts`: new
regression test. It examines the arguments that the patched driver gives
to `net.Socket.prototype.connect`.
- `packages/db/src/client-options.test.ts`: tests for the new variable,
its validation, the mapping and the default.
- `docs/deploy/database.md` and `doc/DATABASE.md`: document the new
variable.
- I did not commit `pnpm-lock.yaml`. The patch hash changes, and the
lockfile policy in `doc/ci-workflows.md` lets CI and the refresh
workflow update it.

## Verification

- Red, then green: `cd packages/db && npx vitest run
src/postgres-connect-attempt-timeout.test.ts`. Before the fix, both
tests failed. The driver called `connect(1, "127.0.0.1")` with no
options. After the fix, both tests pass.
- Focused: `npx vitest run src/postgres-connect-attempt-timeout.test.ts
src/client-options.test.ts src/postgres-connection-recovery.test.ts
src/client-disconnect-replay.test.ts src/client.test.ts
src/postgres-receive-buffer.test.ts`. Result: 6 files, 48 tests pass.
Some of these tests open real connections through the patched driver.
- `pnpm exec tsc --noEmit -p packages/db` passes.
- `pnpm verify` exits 2, because the postgres patch is a global CI
input. Required CI supplies the broad coverage.
- Manual reproduction on Node v24.23.0. A script overrides `dns.lookup`
to give the production address shape: three loopback IPv4 listeners with
full accept queues, which drop SYNs, and three unroutable IPv6
addresses. The listeners start to accept after 600 ms.
- Before: `AggregateError code=ETIMEDOUT after 764ms
inner=ETIMEDOUT,ENETUNREACH,ETIMEDOUT,ENETUNREACH,ETIMEDOUT,ENETUNREACH`.
This is the same as the production error.
- After, with the 2000 ms default: the listener accepted the client's
retransmitted SYN at 1.035 s, and the TCP connection opened. The stub
was not a Postgres server, so the query then stopped at the test's 3 s
`connect_timeout`.

## Risks

- Low risk. The option changes only how long Node waits for one address
before it tries the next one. `connect_timeout` still bounds the whole
attempt.
- If an IPv6 address comes first and drops packets without an error,
each new connection can wait up to 2 s before it tries IPv4, not 250 ms.
Operators can set `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS` lower.
- Unix-socket connections (`path`) and custom `socket` factories do not
change.
- The patch hash of `postgres@3.4.9` changes. CI resolves the lockfile
for this run, and the refresh workflow commits the new lockfile after
merge.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edit and test execution).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-04 16:08:46 -08:00
1 parent bbb226dcbe
commit 627e1be76d
6 files changed
+146 -14

No files matched your search

+1
View File
@@ -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:<boot id>
```
+2 -1
View File
@@ -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:<boot id>` (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:<boot id>` (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:<boot id>` (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. |
+13 -2
View File
@@ -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,
});
+28 -3
View File
@@ -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<string
if (options.maxConnections !== undefined) driverOptions.max = options.maxConnections;
if (options.idleTimeoutSeconds !== undefined) driverOptions.idle_timeout = options.idleTimeoutSeconds;
if (options.connectTimeoutSeconds !== undefined) driverOptions.connect_timeout = options.connectTimeoutSeconds;
// Read by the patched postgres.js connect (patches/postgres@3.4.9.patch).
if (options.connectAttemptTimeoutMs !== undefined) {
driverOptions.auto_select_family_attempt_timeout = options.connectAttemptTimeoutMs;
}
if (options.maxLifetimeSeconds !== undefined) driverOptions.max_lifetime = options.maxLifetimeSeconds;
const connection: Record<string, string> = {};
if (options.applicationName !== undefined) connection.application_name = options.applicationName;
@@ -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,
});
});
});
+54 -8
View File
@@ -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