Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(control-api): wait for each pooled client's end event at teardown

Alfredo Lopez56672cbb4dd1
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index b8901b3f7..641cde629 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.690",
+ "version": "0.1.691",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.690",
+ "version": "0.1.691",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index 52f72d6a5..392a3831e 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.690",
+ "version": "0.1.691",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/test/helpers/realPostgresTeardown.ts b/control-api/test/helpers/realPostgresTeardown.ts
index 4e71fe6a2..b91dd6f6f 100644
--- a/control-api/test/helpers/realPostgresTeardown.ts
+++ b/control-api/test/helpers/realPostgresTeardown.ts
@@ -1,40 +1,70 @@
+import type { EventEmitter } from 'node:events'
import type { Pool } from 'pg'
+type TrackedClient = EventEmitter & { _ended?: boolean }
+
/**
- * Ends a pg pool and resolves only after every client it held has closed its
- * connection.
+ * Ends a pg pool and resolves only after every client it held at end() has
+ * closed its connection.
*
* pg-pool's end() resolves as soon as its client list is empty, while each
* client.end() it started is still in flight. A real-Postgres teardown that
* then runs pg_terminate_backend can reach a client that is still closing; the
* 57P01 it receives is re-emitted on the pool and, with no pool `error`
- * listener, fails the run as an unhandled error (#946). pg-pool emits `remove`
- * from each client's end callback, so waiting for one `remove` per client open
- * at end() closes that window without listening for errors.
+ * listener, fails the run as an unhandled error (#946).
+ *
+ * The clients are taken from pg-pool's `_clients` at call time and each one is
+ * awaited on its own `end` event. Counting pool `remove` events is not enough:
+ * pg-pool emits none for a client whose connect fails (or whose onConnect
+ * rejects), which hangs the wait, and a `remove` from a client dropped before
+ * this call is counted in place of one still closing, which ends it early.
+ * `_clients` is private to pg-pool 3.x; the helper throws if it is missing.
+ * A client still open after `timeoutMs` rejects with a count, so a teardown
+ * fails with a cause instead of the hook timeout.
*
* A pool that was never created (setup failed first) is left alone, as the
* `pool?.end()` it replaces did.
*/
-export async function endPoolAndWaitForClients(pool: Pool | null | undefined): Promise<void> {
+export async function endPoolAndWaitForClients(
+ pool: Pool | null | undefined,
+ timeoutMs = 10_000
+): Promise<void> {
if (!pool) return
- const open = pool.totalCount
- let removed = 0
- let onRemove: (() => void) | undefined
- const closed = new Promise<void>(resolve => {
- if (open === 0) {
- resolve()
- return
- }
- onRemove = () => {
- removed += 1
- if (removed === open) resolve()
- }
- pool.on('remove', onRemove)
+ const clients = (pool as unknown as { _clients?: unknown })._clients
+ if (!Array.isArray(clients)) {
+ throw new Error(
+ 'endPoolAndWaitForClients: pg-pool no longer exposes _clients; update the helper for this pg-pool version'
+ )
+ }
+ const tracked = clients.slice() as TrackedClient[]
+ const listeners: Array<[TrackedClient, () => void]> = []
+ const ended = tracked.map(
+ client =>
+ new Promise<void>(resolve => {
+ if (client._ended) {
+ resolve()
+ return
+ }
+ const onEnd = (): void => resolve()
+ listeners.push([client, onEnd])
+ client.once('end', onEnd)
+ })
+ )
+ let timer: NodeJS.Timeout | undefined
+ const timeout = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ const open = tracked.filter(client => !client._ended).length
+ reject(
+ new Error(
+ `endPoolAndWaitForClients: ${open} of ${tracked.length} client(s) held at end() still connected after ${timeoutMs} ms (pool.ended=${pool.ended})`
+ )
+ )
+ }, timeoutMs)
})
try {
- await pool.end()
- await closed
+ await Promise.race([Promise.all([pool.end(), ...ended]), timeout])
} finally {
- if (onRemove) pool.off('remove', onRemove)
+ clearTimeout(timer)
+ for (const [client, onEnd] of listeners) client.off('end', onEnd)
}
}