@aria-framework/db-worker 0.26.0 → 0.27.1

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.
package/README.md CHANGED
@@ -437,6 +437,33 @@ Against 0.25.0's code, 6 of its 10 checks fail.
437
437
 
438
438
  ## Changelog
439
439
 
440
+ - **0.27.1** — the UTC pin is WAITED FOR. 0.27.0 fired `SET TIME ZONE 'UTC'` from the pool's
441
+ `connect` event without awaiting it, so the first query on every new connection was issued
442
+ while the SET was still running: pg 8 prints "Calling client.query() when the client is already
443
+ executing a query is deprecated" (seen on an app at startup), and pg 9 makes it a failed query.
444
+ The SET now runs in pg-pool's awaited `onConnect` hook — installed on the pool's options, so
445
+ `pinPoolUtc` covers a pool the app built too; an `onConnect` already there still runs, after the
446
+ pin. A pg-pool without the hook falls back to the old `connect` path. **Behaviour change:** a SET
447
+ that fails now fails that checkout (the query rejects, the client is discarded, the error is
448
+ logged) instead of handing out an unpinned session. `test/pinAwaited.pg.js` (N concurrent
449
+ queries on N fresh connections: no overlap, every connection UTC) and `test/pinPoolUtc.js`
450
+ (wiring) — against 0.27.0, 4 of 15 and 5 of 6 fail.
451
+ - **0.27.0** — "Time is UTC" (repo README): a Postgres session and a Date on the wire no longer
452
+ depend on the server's, the role's, the connection string's or the process's timezone.
453
+ - **Every connection the driver opens runs `SET TIME ZONE 'UTC'` first** — the app pool and the
454
+ short-lived migration connection. `'now'::timestamp`, `CURRENT_DATE`, `date_trunc` on a
455
+ timestamptz and a `timestamp` compared with a timestamptz all resolve in the session zone;
456
+ it is now always UTC. SET rather than `options=-c TimeZone=UTC` because a connection
457
+ string's own `options=` silently overrides one passed beside it.
458
+ - **`pinPoolUtc(pool)` is exported** for a pg Pool the app builds itself.
459
+ - **PROCESS-WIDE node-postgres changes** (one parser table per process, like the int8 parser):
460
+ a Date PARAMETER is sent as UTC (`parseInputDatesAsUTC`) where it was sent with the process's
461
+ local offset — which a `timestamp` column discards, storing the host's wall clock; a
462
+ `timestamp` column is READ as UTC where it was read as local; a `date` column is read as the
463
+ string `'YYYY-MM-DD'` where it was a Date at local midnight. An app that relied on a `date`
464
+ arriving as a Date must parse it.
465
+ - `test/timezone.pg.js`: four process zones, against a connection string that asks for
466
+ America/Chicago, temp tables only. 26 of its 37 checks fail on 0.26.0.
440
467
  - **0.26.0** — composite keys into the principal table (and any in `NO_CASCADE`) no longer
441
468
  cascade; `generateCompositeOnUpdateAdoption` converges both ways and repairs a 0.25.0 install.
442
469
  `stats.attributionKeys` (generator) and `stats.noCascade` (adoption). PGlite devDependency;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Every Postgres session this framework opens runs in UTC, whatever the server, the database,
3
+ * the role or the connection string says.
4
+ *
5
+ * WHY A SESSION HAS A ZONE AT ALL. Postgres resolves a zoneless value in the SESSION's `TimeZone`:
6
+ * `'now'::timestamp`, `to_timestamp(n)` assigned to a `timestamp` column, `date_trunc` on a
7
+ * timestamptz, `CURRENT_DATE`, a `timestamp` compared with a timestamptz. That setting defaults
8
+ * from postgresql.conf, can be overridden per database and per role, and can be set by the client
9
+ * — so it is not the application's unless the application takes it.
10
+ *
11
+ * WHAT IT COST. connect-pg-simple stores a session's expiry as `to_timestamp(n)` in a
12
+ * `timestamp` (no zone) column and compares it the same way: correct while the zone never
13
+ * changes, and off by the whole offset the moment it does. Measured against a real server — a
14
+ * one-hour session written under UTC and read under America/Chicago lived six hours; written
15
+ * under Chicago and read under UTC, or written under UTC and read under Asia/Kolkata, it was
16
+ * dead on arrival. No error either way.
17
+ *
18
+ * WHY `SET` ON CONNECT, NOT `options=-c TimeZone=UTC`. The startup option is the obvious spelling
19
+ * and it has a hole: in node-postgres a connection STRING's own `options=` silently wins over an
20
+ * `options` passed beside it, so a URL carrying one un-pins the pool with nothing to say so. A
21
+ * SET issued after the session starts overrides the server default, the database default, the
22
+ * role default and the startup packet alike.
23
+ *
24
+ * WHY IT IS IN TIME — AND WAITED FOR. pg-pool awaits its `onConnect(client)` option after a
25
+ * connection opens and BEFORE the client is handed to whoever asked for it, so the SET has
26
+ * COMPLETED before the caller's first query is issued. Until 0.27.1 the SET was fired from the
27
+ * 'connect' event and not awaited: still first in the client's queue, but the caller's query was
28
+ * then issued while it ran — pg 8 prints "Calling client.query() when the client is already
29
+ * executing a query is deprecated", and pg 9 removes that queue, which makes it a failed query
30
+ * on a fresh connection. The hook is installed on the pool's own options, so it covers a pool
31
+ * the CALLER built too; a hook already there still runs, after the pin.
32
+ * test/timezone.pg.js proves the zone against a pool whose connection string asks for another;
33
+ * test/pinAwaited.pg.js proves that no query overlaps the SET.
34
+ *
35
+ * A pg-pool too old to know `onConnect` ignores it, and the 'connect' listener below then sees
36
+ * a client the hook never pinned and issues the SET the old way: pinned, with the warning.
37
+ *
38
+ * A SET THAT FAILS FAILS THE CHECKOUT: pg-pool ends that client and the caller's query rejects
39
+ * with the error (logged here too). An unpinned session is exactly the silent failure this
40
+ * exists to prevent, so it is no longer handed out.
41
+ *
42
+ * LIMIT, stated: only connections opened AFTER the call are pinned. Call it on a pool before
43
+ * its first query — which is what the driver and the session-store factory both do.
44
+ */
45
+
46
+ 'use strict';
47
+
48
+ const PIN_SQL = "SET TIME ZONE 'UTC'";
49
+ const PINNED = new WeakSet();
50
+ const PINNED_CLIENTS = new WeakSet();
51
+
52
+ /**
53
+ * @param {object} pool a node-postgres Pool
54
+ * @param {{logger?: object}} [opts]
55
+ * @returns {object} the same pool
56
+ */
57
+ function pinPoolUtc(pool, opts = {}) {
58
+ if (!pool || typeof pool.on !== 'function') throw new Error('pinPoolUtc(pool): a pg Pool is required');
59
+ if (PINNED.has(pool)) return pool;
60
+ PINNED.add(pool);
61
+ const say = (err) => {
62
+ // Loud, because an unpinned session is exactly the silent failure this exists to prevent.
63
+ try { (opts.logger || console).error(`postgres: could not pin a session to UTC (${err.message})`); }
64
+ catch (_) { /* a logging failure must not become an unhandled rejection */ }
65
+ };
66
+ if (!pool.options) pool.options = {};
67
+ const prior = pool.options.onConnect;
68
+ pool.options.onConnect = async (client) => {
69
+ try { await client.query(PIN_SQL); } catch (err) { say(err); throw err; }
70
+ PINNED_CLIENTS.add(client);
71
+ if (typeof prior === 'function') await prior(client);
72
+ };
73
+ // Fallback for a pg-pool without the hook; a no-op for every client the hook pinned.
74
+ pool.on('connect', (client) => {
75
+ if (PINNED_CLIENTS.has(client)) return;
76
+ client.query(PIN_SQL).catch(say);
77
+ });
78
+ return pool;
79
+ }
80
+
81
+ /**
82
+ * Process-wide node-postgres settings, so a Date crosses the wire as the instant it is.
83
+ *
84
+ * A Date PARAMETER is serialised with the process's local offset by default. Postgres discards
85
+ * the offset when the target is a `timestamp` (no zone) column, so the column receives the
86
+ * HOST's wall clock. `parseInputDatesAsUTC` sends UTC wall clock instead — the same instant for
87
+ * a timestamptz, and the right digits for a timestamp.
88
+ *
89
+ * A `timestamp` (OID 1114) is parsed as LOCAL time by default — the same misreading on the way
90
+ * out. Here its digits are UTC, because that is the only thing this framework ever writes.
91
+ *
92
+ * A `date` (OID 1082) becomes a Date at LOCAL midnight by default: a calendar day turned into
93
+ * an instant, which then prints as the day before anywhere west of UTC. It stays the string
94
+ * 'YYYY-MM-DD' — a date has no zone, and kit's dbTime renders a bare date literally.
95
+ *
96
+ * Array columns of these types (1115, 1182) are left at pg's defaults; nothing here uses one.
97
+ * pg keeps ONE parser table per process, which is why this sits beside the int8 parser in the
98
+ * driver rather than with each consumer.
99
+ */
100
+ function configurePgTypes(pg) {
101
+ pg.defaults.parseInputDatesAsUTC = true;
102
+ pg.types.setTypeParser(1114, (v) => {
103
+ if (v === null) return null;
104
+ if (v === 'infinity') return Infinity;
105
+ if (v === '-infinity') return -Infinity;
106
+ return new Date(v.replace(' ', 'T') + 'Z');
107
+ });
108
+ pg.types.setTypeParser(1082, (v) => v);
109
+ }
110
+
111
+ module.exports = { pinPoolUtc, configurePgTypes };
@@ -30,6 +30,7 @@ const txContext = new AsyncLocalStorage();
30
30
 
31
31
  const { dialectFor } = require('../dialect');
32
32
  const { bindNamed } = require('./params');
33
+ const { pinPoolUtc, configurePgTypes } = require('./pgUtc');
33
34
 
34
35
  /**
35
36
  * Rewrite `?` placeholders to `$1..$n`, leaving any `?` inside a literal alone.
@@ -132,6 +133,8 @@ function createPostgresDriver(opts = {}) {
132
133
  * point the driver is built, rather than by each consumer remembering to.
133
134
  */
134
135
  pg.types.setTypeParser(20, (v) => (v === null ? null : Number(v)));
136
+ // Dates cross the wire as the instants they are, not as the host's wall clock. See pgUtc.js.
137
+ configurePgTypes(pg);
135
138
 
136
139
  // Pass the CONNECTION OPTIONS THROUGH. The guard above accepts host/user/database as an
137
140
  // alternative to a connection string and the JSDoc documents it, but only connectionString was
@@ -144,6 +147,9 @@ function createPostgresDriver(opts = {}) {
144
147
  if (v !== undefined) poolCfg[k] = v;
145
148
  }
146
149
  const pool = new pg.Pool(poolCfg);
150
+ // Every session in UTC, before the first query on it — the app pool AND the short-lived
151
+ // migration connection, since both are built here. See pgUtc.js for why SET and not `options`.
152
+ pinPoolUtc(pool, { logger: opts.logger });
147
153
 
148
154
  // An unhandled 'error' on a Pool CRASHES THE PROCESS, and this is not hypothetical: the restore
149
155
  // path issues pg_terminate_backend and DROP DATABASE ... WITH (FORCE), which kill this pool's
package/index.js CHANGED
@@ -20,6 +20,9 @@ const { dialectFor } = require('./dialect');
20
20
  module.exports = {
21
21
  createSqliteDriver,
22
22
  createPostgresDriver,
23
+ // 0.27.0 — for a pg Pool the app builds ITSELF (a session store's, a reporting pool). The
24
+ // driver pins its own. Does not load `pg`.
25
+ pinPoolUtc: require('./driver/pgUtc').pinPoolUtc,
23
26
  dialectFor,
24
27
  DbClient: require('./client').DbClient,
25
28
  runWorker: require('./worker').runWorker,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.26.0",
3
+ "version": "0.27.1",
4
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,
@@ -40,7 +40,7 @@
40
40
  "pg": "^8.23.0"
41
41
  },
42
42
  "scripts": {
43
- "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/tenancyAttribution.pglite.js && node test/tenancyNullable.pg.js && node test/tenancyPartnerFk.pg.js && node test/tenancyOnUpdate.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
+ "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/tenancyAttribution.pglite.js && node test/tenancyNullable.pg.js && node test/tenancyPartnerFk.pg.js && node test/tenancyOnUpdate.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 && node test/timezone.pg.js && node test/pinPoolUtc.js && node test/pinAwaited.pg.js",
44
44
  "prepublishOnly": "node ../../test/packaging.js db-worker"
45
45
  }
46
46
  }