Fix annoying negative timeout warnings.
I went and asked copilot to fix these annoying warnings #1061 it implemented the suggested fix from the issue.
Here are its remarks:
---
Fixes the `TimeoutNegativeWarning` that occurs when the postgres library attempts to reconnect to the database after the intended reconnection time has already passed.
## Problem
The postgres library occasionally throws a `TimeoutNegativeWarning` error when attempting to reconnect:
```
(node:8951) TimeoutNegativeWarning: -235416.31458278198 is a negative number.
Timeout duration was set to 1.
at new Timeout (node:internal/timers:195:17)
at setTimeout (node:timers:138:19)
at reconnect (/path/to/connection.js:355:9)
```
This occurs when the calculated delay value `closedDate + delay - performance.now()` becomes negative, meaning the intended reconnection time has already passed.
## Root Cause
In the `reconnect()` function, the current code calculates the timeout delay as:
```javascript
setTimeout(connect, closedDate ? closedDate + delay - performance.now() : 0)
```
When `closedDate + delay - performance.now()` results in a negative value, Node.js emits a `TimeoutNegativeWarning` and sets the timeout to 1ms.
## Solution
Wrapped the delay calculation in `Math.max()` to ensure the timeout value is never negative:
```javascript
// Before
setTimeout(connect, closedDate ? closedDate + delay - performance.now() : 0)
// After
setTimeout(connect, Math.max(closedDate ? closedDate + delay - performance.now() : 0, 0))
```
This ensures:
- If the calculated delay is positive, it uses that delay (normal case)
- If the calculated delay is negative (reconnection time has passed), it uses 0 for immediate reconnection
- Maintains the existing behavior while preventing the Node.js warning
## Files Changed
- `src/connection.js` (line 353) - Main source
- `cf/src/connection.js` (line 355) - Cloudflare version
- `cjs/src/connection.js` (line 353) - CommonJS version
- `deno/src/connection.js` (line 356) - Deno version
All transpiled versions are automatically updated via the build process to ensure consistency across environments.
## Testing
Created comprehensive tests to verify:
- The fix prevents `TimeoutNegativeWarning` in negative timeout scenarios
- All existing reconnection behaviors work correctly (initial connections, future reconnections, past reconnections)
- The change maintains backward compatibility
This is a minimal, safe fix that preserves the existing reconnection logic while eliminating the Node.js warning.
---
Hope this helps
合并状态:未合并 关闭于 2025-11-12 3 条评论