@aria-framework/db-worker 0.26.0 → 0.27.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.
package/README.md CHANGED
@@ -437,6 +437,22 @@ Against 0.25.0's code, 6 of its 10 checks fail.
437
437
 
438
438
  ## Changelog
439
439
 
440
+ - **0.27.0** — "Time is UTC" (repo README): a Postgres session and a Date on the wire no longer
441
+ depend on the server's, the role's, the connection string's or the process's timezone.
442
+ - **Every connection the driver opens runs `SET TIME ZONE 'UTC'` first** — the app pool and the
443
+ short-lived migration connection. `'now'::timestamp`, `CURRENT_DATE`, `date_trunc` on a
444
+ timestamptz and a `timestamp` compared with a timestamptz all resolve in the session zone;
445
+ it is now always UTC. SET rather than `options=-c TimeZone=UTC` because a connection
446
+ string's own `options=` silently overrides one passed beside it.
447
+ - **`pinPoolUtc(pool)` is exported** for a pg Pool the app builds itself.
448
+ - **PROCESS-WIDE node-postgres changes** (one parser table per process, like the int8 parser):
449
+ a Date PARAMETER is sent as UTC (`parseInputDatesAsUTC`) where it was sent with the process's
450
+ local offset — which a `timestamp` column discards, storing the host's wall clock; a
451
+ `timestamp` column is READ as UTC where it was read as local; a `date` column is read as the
452
+ string `'YYYY-MM-DD'` where it was a Date at local midnight. An app that relied on a `date`
453
+ arriving as a Date must parse it.
454
+ - `test/timezone.pg.js`: four process zones, against a connection string that asks for
455
+ America/Chicago, temp tables only. 26 of its 37 checks fail on 0.26.0.
440
456
  - **0.26.0** — composite keys into the principal table (and any in `NO_CASCADE`) no longer
441
457
  cascade; `generateCompositeOnUpdateAdoption` converges both ways and repairs a 0.25.0 install.
442
458
  `stats.attributionKeys` (generator) and `stats.noCascade` (adoption). PGlite devDependency;
@@ -0,0 +1,86 @@
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. pg-pool emits 'connect' synchronously, BEFORE handing the new client to
25
+ * whoever asked for it, and a client runs its queries in the order they were queued. The SET is
26
+ * therefore the first statement on every connection, ahead of the caller's first query.
27
+ * test/timezone.pg.js proves it against a pool whose connection string asks for another zone.
28
+ *
29
+ * LIMIT, stated: only connections opened AFTER the call are pinned. Call it on a pool before
30
+ * its first query — which is what the driver and the session-store factory both do.
31
+ */
32
+
33
+ 'use strict';
34
+
35
+ const PINNED = new WeakSet();
36
+
37
+ /**
38
+ * @param {object} pool a node-postgres Pool
39
+ * @param {{logger?: object}} [opts]
40
+ * @returns {object} the same pool
41
+ */
42
+ function pinPoolUtc(pool, opts = {}) {
43
+ if (!pool || typeof pool.on !== 'function') throw new Error('pinPoolUtc(pool): a pg Pool is required');
44
+ if (PINNED.has(pool)) return pool;
45
+ PINNED.add(pool);
46
+ pool.on('connect', (client) => {
47
+ client.query("SET TIME ZONE 'UTC'").catch((err) => {
48
+ // Loud, because an unpinned session is exactly the silent failure this exists to prevent.
49
+ try { (opts.logger || console).error(`postgres: could not pin a session to UTC (${err.message})`); }
50
+ catch (_) { /* a logging failure must not become an unhandled rejection */ }
51
+ });
52
+ });
53
+ return pool;
54
+ }
55
+
56
+ /**
57
+ * Process-wide node-postgres settings, so a Date crosses the wire as the instant it is.
58
+ *
59
+ * A Date PARAMETER is serialised with the process's local offset by default. Postgres discards
60
+ * the offset when the target is a `timestamp` (no zone) column, so the column receives the
61
+ * HOST's wall clock. `parseInputDatesAsUTC` sends UTC wall clock instead — the same instant for
62
+ * a timestamptz, and the right digits for a timestamp.
63
+ *
64
+ * A `timestamp` (OID 1114) is parsed as LOCAL time by default — the same misreading on the way
65
+ * out. Here its digits are UTC, because that is the only thing this framework ever writes.
66
+ *
67
+ * A `date` (OID 1082) becomes a Date at LOCAL midnight by default: a calendar day turned into
68
+ * an instant, which then prints as the day before anywhere west of UTC. It stays the string
69
+ * 'YYYY-MM-DD' — a date has no zone, and kit's dbTime renders a bare date literally.
70
+ *
71
+ * Array columns of these types (1115, 1182) are left at pg's defaults; nothing here uses one.
72
+ * pg keeps ONE parser table per process, which is why this sits beside the int8 parser in the
73
+ * driver rather than with each consumer.
74
+ */
75
+ function configurePgTypes(pg) {
76
+ pg.defaults.parseInputDatesAsUTC = true;
77
+ pg.types.setTypeParser(1114, (v) => {
78
+ if (v === null) return null;
79
+ if (v === 'infinity') return Infinity;
80
+ if (v === '-infinity') return -Infinity;
81
+ return new Date(v.replace(' ', 'T') + 'Z');
82
+ });
83
+ pg.types.setTypeParser(1082, (v) => v);
84
+ }
85
+
86
+ 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.0",
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",
44
44
  "prepublishOnly": "node ../../test/packaging.js db-worker"
45
45
  }
46
46
  }