@workflow/world-postgres 5.0.4 → 5.0.5

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
@@ -151,9 +151,17 @@ const world = createWorld({
151
151
  // Or pass an existing pg.Pool (shared with your app Drizzle, etc.); `world.close()` will not end it.
152
152
  import { Pool } from "pg";
153
153
  const pool = new Pool({ connectionString: process.env.DATABASE_URL });
154
+ // The World leaves a pool you pass to you: listen for errors, or a connection
155
+ // the server ends (a restart, a failover, an idle timeout) ends the process.
156
+ pool.on("connect", (client) =>
157
+ client.on("error", (error) => console.error(error.message))
158
+ );
159
+ pool.on("error", () => {}); // An idle client's error, logged just above
154
160
  const worldFromPool = createWorld({ pool });
155
161
  ```
156
162
 
163
+ A connection the server ends emits an `'error'` event, and an `'error'` event with no listener ends the process. When `createWorld()` creates the pool, it listens on the pool and on every client it connects, and logs one `[world-postgres] Pooled PostgreSQL connection lost` line per lost connection. It doesn't add listeners to a pool you pass, so add both yourself, as above: pg-pool listens only on idle clients, and the World holds a checked-out client across a transaction's statements.
164
+
157
165
  ### Application-managed shutdown
158
166
 
159
167
  By default, Graphile Worker responds automatically when the application is asked to shut down. If your application already coordinates shutdown, set `WORKFLOW_POSTGRES_APPLICATION_MANAGED_SHUTDOWN=1` when selecting the package with `WORKFLOW_TARGET_WORLD`, or set `applicationManagedShutdown: true` when calling `createWorld()` directly. Await `world.close()` from your shutdown path so Graphile Worker cannot terminate the process as soon as its queue stops, before your application finishes closing dependent resources:
@@ -181,7 +189,7 @@ An aborted HTTP request does not guarantee that its server-side handler stopped,
181
189
  | ------------------ | --------- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
182
190
  | `connectionString` | `string` | `process.env.WORKFLOW_POSTGRES_URL`, `process.env.DATABASE_URL`, or `'postgres://world:world@localhost:5432/world'` | Used only when `pool` is omitted, to construct an internal pool |
183
191
  | `maxPoolSize` | `number` | `process.env.WORKFLOW_POSTGRES_MAX_POOL_SIZE` or `pg.Pool` default (`10`) | Optional. Sets the internal `pg.Pool` max size when `createWorld()` creates the pool |
184
- | `pool` | `pg.Pool` | Not applicable | Optional. When set, used for Drizzle, Graphile Worker, and stream writes. `world.close()` does not end it. |
192
+ | `pool` | `pg.Pool` | Not applicable | Optional. When set, used for Drizzle, Graphile Worker, and stream writes. `world.close()` does not end it, and the World adds no `'error'` listeners to it (see above). |
185
193
  | `jobPrefix` | `string` | `process.env.WORKFLOW_POSTGRES_JOB_PREFIX` | Optional prefix for queue job names |
186
194
  | `queueConcurrency` | `number` | `50` | Number of concurrent active step executions per process. Must be high enough to cover any parent→child workflow polling in flight because each `Run#returnValue` await holds a worker slot until the child run terminates. |
187
195
  | `pollInterval` | `number` | `500` | Milliseconds between idle job fetches per worker. |
@@ -255,6 +263,45 @@ import * as schema from '@workflow/world-postgres/schema';
255
263
 
256
264
  Make sure your PostgreSQL database is accessible and the user has sufficient permissions to create tables and manage jobs.
257
265
 
266
+ ### Timestamps and time zones
267
+
268
+ Every timestamp column is `timestamp with time zone`, so values are correct
269
+ whatever time zone the server or session runs in. Earlier versions used
270
+ `timestamp without time zone`: on a server outside UTC, `createdAt` came back
271
+ off by the server's UTC offset (for example 7 hours early on
272
+ `America/Los_Angeles`).
273
+
274
+ Migration 0027 converts the columns. On a server in UTC it only changes the
275
+ catalog and rebuilds one small partial index, `workflow_invocations_pending`;
276
+ no table is rewritten. On a server in another time zone it also moves the
277
+ values that came from `now()` (every `created_at`, `updated_at` on rows never
278
+ updated, and `workflow_invocations.responded_at`) from the server's local time
279
+ to the instant they recorded. That costs about one rewrite of each table (new
280
+ row versions, WAL, and bloat until vacuum), with the tables' locks held until
281
+ it finishes, so plan a maintenance window for a large database.
282
+
283
+ The migration waits at most 10 seconds for its locks (unless the session sets
284
+ its own `lock_timeout`), so a long-running transaction makes `bootstrap` fail
285
+ instead of queueing every query behind it. Run `bootstrap` again once that
286
+ transaction ends.
287
+
288
+ It assumes the `now()` values were written in the time zone of the session
289
+ that runs the migration. If your application's pool set a different session
290
+ time zone, set `workflow.legacy_timezone` to that zone for the migration. Use
291
+ `?options=-c%20workflow.legacy_timezone%3DEurope%2FBerlin` in the connection
292
+ string, or, where a pooler drops startup `options` (PgBouncer and several
293
+ hosted poolers), `ALTER DATABASE mydb SET workflow.legacy_timezone =
294
+ 'Europe/Berlin'` or `ALTER ROLE myuser SET ...` before running `bootstrap`.
295
+
296
+ On a server in UTC the upgrade order does not matter: the upgraded World reads
297
+ unconverted columns correctly in any Node.js time zone, and older versions read
298
+ converted ones correctly. On a server outside UTC, stop the previous version's
299
+ workers, run the migration, then start the upgraded app. Older versions read
300
+ the converted columns shifted by the server's UTC offset, which can skip or
301
+ stretch step retry backoffs. For the same reason there is no rolling back past
302
+ 0027 on such a server: the migration has no down step, and an older version
303
+ would read every converted value shifted.
304
+
258
305
  ### Data retention
259
306
 
260
307
  Postgres World does not yet perform general workflow-run cleanup. After a
@@ -418,6 +465,32 @@ The experimental implementation has these remaining limitations:
418
465
  The database integration tests use the built core runtime. Build core before
419
466
  running `pnpm exec vitest run test/invoke.test.ts` from `packages/world-postgres`.
420
467
 
468
+ ## Troubleshooting
469
+
470
+ ### A run stays `running` after a crash
471
+
472
+ Earlier versions wrote a step's `step_completed` or `step_failed` event
473
+ separately from the step row. A process that died between the two left the step
474
+ finished with no matching event, and the run never advanced. This query lists
475
+ those steps for runs still `running`:
476
+
477
+ ```sql
478
+ select s.run_id, s.step_id, s.step_name, s.status
479
+ from workflow.workflow_steps s
480
+ join workflow.workflow_runs r on r.id = s.run_id
481
+ where r.status = 'running'
482
+ and s.status in ('completed', 'failed')
483
+ and not exists (
484
+ select 1 from workflow.workflow_events e
485
+ where e.run_id = s.run_id
486
+ and e.correlation_id = s.step_id
487
+ and e.type = 'step_' || s.status
488
+ );
489
+ ```
490
+
491
+ Upgrading does not recover these runs. Cancel each one with
492
+ `workflow cancel <run-id>`.
493
+
421
494
  ## Development
422
495
 
423
496
  For local development, you can use the included Docker Compose configuration:
@@ -0,0 +1,23 @@
1
+ import type { Pool } from 'pg';
2
+ /**
3
+ * Keep a connection the server drops from ending the process.
4
+ *
5
+ * A restart or failover, `idle_session_timeout`, `pg_terminate_backend`, or a
6
+ * proxy closing idle sockets can end a connection at any time, and `pg`
7
+ * reports it as an `'error'` event on the client. pg-pool forwards an idle
8
+ * client's error to the pool, but detaches its own listener while a client is
9
+ * checked out, and Drizzle transactions and the invocation mailbox hold
10
+ * clients across statements. An `EventEmitter` with no `'error'` listener
11
+ * throws, so either case is an uncaught exception. Graphile Worker attaches
12
+ * listeners like these only while its runner is up, and a World that is only
13
+ * read from never starts one.
14
+ *
15
+ * Logging is all that is left to do: pg-pool discards a failed client when it
16
+ * is released, and a checked-out client's next query rejects, so its caller
17
+ * still sees the error.
18
+ *
19
+ * Only for a pool the World creates. A pool the caller passes in is theirs to
20
+ * listen on.
21
+ */
22
+ export declare function handleConnectionErrors(pool: Pool, isClosing: () => boolean): void;
23
+ //# sourceMappingURL=connection-errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection-errors.d.ts","sourceRoot":"","sources":["../src/connection-errors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAc,MAAM,IAAI,CAAC;AAE3C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,IAAI,EACV,SAAS,EAAE,MAAM,OAAO,GACvB,IAAI,CAuBN"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Keep a connection the server drops from ending the process.
3
+ *
4
+ * A restart or failover, `idle_session_timeout`, `pg_terminate_backend`, or a
5
+ * proxy closing idle sockets can end a connection at any time, and `pg`
6
+ * reports it as an `'error'` event on the client. pg-pool forwards an idle
7
+ * client's error to the pool, but detaches its own listener while a client is
8
+ * checked out, and Drizzle transactions and the invocation mailbox hold
9
+ * clients across statements. An `EventEmitter` with no `'error'` listener
10
+ * throws, so either case is an uncaught exception. Graphile Worker attaches
11
+ * listeners like these only while its runner is up, and a World that is only
12
+ * read from never starts one.
13
+ *
14
+ * Logging is all that is left to do: pg-pool discards a failed client when it
15
+ * is released, and a checked-out client's next query rejects, so its caller
16
+ * still sees the error.
17
+ *
18
+ * Only for a pool the World creates. A pool the caller passes in is theirs to
19
+ * listen on.
20
+ */
21
+ export function handleConnectionErrors(pool, isClosing) {
22
+ const log = (error) => {
23
+ // Expected while the World shuts its pool down.
24
+ if (isClosing())
25
+ return;
26
+ // Never the error itself: pg-pool sets `error.client`, whose connection
27
+ // parameters include the password.
28
+ console.warn(`[world-postgres] Pooled PostgreSQL connection lost${error.code ? ` (${error.code})` : ''}: ${error.message}`);
29
+ };
30
+ pool.on('connect', (client) => {
31
+ let lost = false;
32
+ client.on('error', (error) => {
33
+ // A client nobody has ended reports one drop twice: the server's error,
34
+ // then "Connection terminated unexpectedly" as the socket closes.
35
+ if (lost)
36
+ return;
37
+ lost = true;
38
+ log(error);
39
+ });
40
+ });
41
+ // pg-pool re-emits an idle client's error here after the listener above has
42
+ // logged it, so this one only keeps the pool from throwing.
43
+ pool.on('error', () => { });
44
+ }
45
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29ubmVjdGlvbi1lcnJvcnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvY29ubmVjdGlvbi1lcnJvcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBRUE7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7R0FtQkc7QUFDSCxNQUFNLFVBQVUsc0JBQXNCLENBQ3BDLElBQVUsRUFDVixTQUF3QjtJQUV4QixNQUFNLEdBQUcsR0FBRyxDQUFDLEtBQWdDLEVBQUUsRUFBRTtRQUMvQyxnREFBZ0Q7UUFDaEQsSUFBSSxTQUFTLEVBQUU7WUFBRSxPQUFPO1FBQ3hCLHdFQUF3RTtRQUN4RSxtQ0FBbUM7UUFDbk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