@aria-framework/db-worker 0.21.0 → 0.23.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.
@@ -223,6 +223,30 @@ function createPostgresDriver(opts = {}) {
223
223
  if (parent && parent.pool === pool) return parent.nest(fn);
224
224
 
225
225
  const client = await pool.connect();
226
+
227
+ // ── A CHECKED-OUT CLIENT EMITS ON ITSELF, NOT ON THE POOL ────────────────────────────────
228
+ //
229
+ // The `pool.on('error')` above covers clients sitting IDLE in the pool. Once `connect()` has
230
+ // handed one over, node-postgres emits connection errors on the CLIENT — and with nothing
231
+ // listening, Node turns an unhandled 'error' event into an uncaught exception and the process
232
+ // exits. So a Postgres restart, a failover or a stray pg_terminate_backend during any
233
+ // transaction took the whole app down, including every unrelated request in flight, at
234
+ // precisely the moment it should have been riding out a short outage.
235
+ //
236
+ // ONLY THIS PATH NEEDED IT. `pool.query()` — everything outside a transaction — already
237
+ // rejects cleanly, because pg's own pool machinery owns the client for the length of that
238
+ // call. Verified both ways rather than assumed; test/clientError.pg.js keeps the distinction.
239
+ //
240
+ // The query still rejects exactly as before. This changes only whether the process survives
241
+ // to see the rejection.
242
+ let connError = null;
243
+ const onClientError = (err) => {
244
+ connError = err;
245
+ try { (opts.logger || console).warn(`postgres: connection lost mid-transaction (${err.message})`); }
246
+ catch (_) { /* a logger that throws must not become the crash it replaced */ }
247
+ };
248
+ client.on('error', onClientError);
249
+
226
250
  const q = (sql, params) => client.query(sql, params);
227
251
 
228
252
  /**
@@ -287,7 +311,14 @@ function createPostgresDriver(opts = {}) {
287
311
  try { await client.query('ROLLBACK'); } catch (_) { /* the original error is what matters */ }
288
312
  throw e;
289
313
  } finally {
290
- client.release();
314
+ // REMOVE THE LISTENER, because the pool reuses client objects across checkouts: one added
315
+ // per transaction and never removed accumulates, and an old handler fires for a later
316
+ // transaction's error.
317
+ client.removeListener('error', onClientError);
318
+ // RELEASE WITH THE ERROR, which destroys the connection instead of returning it to the
319
+ // pool. A client whose connection died must not be handed to the next caller — that is how
320
+ // a dead connection gets reused and fails somebody else's request for no reason of its own.
321
+ client.release(connError || undefined);
291
322
  }
292
323
  },
293
324
  async close() { await pool.end(); },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.21.0",
4
- "description": "Aria App Framework \u2014 db-worker module. Async RPC bridge over synchronous better-sqlite3: a worker-thread dispatcher (runWorker), a main-thread client with per-call timeouts and crash handling (DbClient), and a SQLite layer with WAL pragmas + a numbered-migration runner (database).",
3
+ "version": "0.23.0",
4
+ "description": "Aria App Framework — db-worker module. Async RPC bridge over synchronous better-sqlite3: a worker-thread dispatcher (runWorker), a main-thread client with per-call timeouts and crash handling (DbClient), and a SQLite layer with WAL pragmas + a numbered-migration runner (database).",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
7
7
  "publishConfig": {
@@ -39,7 +39,7 @@
39
39
  "pg": "^8.23.0"
40
40
  },
41
41
  "scripts": {
42
- "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/tenancyNullable.pg.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js",
42
+ "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/tenancyNullable.pg.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/clientError.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js",
43
43
  "prepublishOnly": "node ../../test/packaging.js db-worker"
44
44
  }
45
45
  }
@@ -280,6 +280,41 @@ function generateTenancyMigration(opts = {}) {
280
280
  `ALTER TABLE ${table} ADD CONSTRAINT fk_${table}_${fk.from}_partner`
281
281
  + ` FOREIGN KEY (${fk.from}, partner_id)`
282
282
  + ` REFERENCES ${fk.table} (${fk.to}, partner_id)${del};`);
283
+ // ── AND DROP THE ONE IT SUPERSEDES ──────────────────────────────────────────────────
284
+ //
285
+ // The composite key is strictly stronger: it enforces everything the single-column key
286
+ // did AND that the child agrees with its parent about the tenant. Leaving the original
287
+ // in place is therefore not WRONG, which is exactly why it went unnoticed — a consuming
288
+ // app measured 49 duplicated pairs across 28 tables, every one of them redundant and
289
+ // none of them broken. What they cost is writes: every INSERT and UPDATE of the child
290
+ // takes two lookups on the parent instead of one, and every DELETE of a parent row
291
+ // checks both, on the hot path, for ever.
292
+ //
293
+ // BY SHAPE, NOT BY NAME. `<table>_<column>_fkey` is only Postgres's default; a schema
294
+ // that named its constraint would keep its duplicate while the generator reported
295
+ // success. This drops any FK on this table whose key is EXACTLY this one column and
296
+ // which points at the same parent — the precise set the line above supersedes, and
297
+ // nothing else. It runs after the ADD, so a failure leaves the stronger key in place
298
+ // rather than no key at all.
299
+ //
300
+ // GUARDED ON partner_id BEING NOT NULL, which is the condition that makes "supersedes"
301
+ // true at all. Foreign keys are MATCH SIMPLE: if ANY column of a composite key is NULL
302
+ // the constraint is satisfied trivially, so on a table whose partner_id is NULLABLE — a
303
+ // PARTNER_NULLABLE table, where NULL means "the installation" — a row could carry a
304
+ // dangling reference with partner_id NULL and pass the composite while failing the
305
+ // single. There the single key is NOT redundant and must stay. Checked here rather than
306
+ // asserted in a comment, because the manifest can move a table between those lists.
307
+ out.push(
308
+ `DO $$ DECLARE c record; BEGIN`
309
+ + ` IF (SELECT attnotnull FROM pg_attribute`
310
+ + ` WHERE attrelid = '${table}'::regclass AND attname = 'partner_id') THEN`
311
+ + ` FOR c IN SELECT conname FROM pg_constraint`
312
+ + ` WHERE conrelid = '${table}'::regclass AND contype = 'f'`
313
+ + ` AND confrelid = '${fk.table}'::regclass`
314
+ + ` AND conkey = ARRAY[(SELECT attnum FROM pg_attribute`
315
+ + ` WHERE attrelid = '${table}'::regclass AND attname = '${fk.from}' AND NOT attisdropped)]`
316
+ + ` LOOP EXECUTE format('ALTER TABLE ${table} DROP CONSTRAINT %I', c.conname);`
317
+ + ` END LOOP; END IF; END $$;`);
283
318
  n++;
284
319
  }
285
320
  }