@workflow/world-postgres 5.0.0-beta.9 → 5.0.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.
Files changed (58) hide show
  1. package/README.md +307 -34
  2. package/bin/setup-deprecated.js +20 -0
  3. package/dist/config.d.ts +16 -0
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/config.js +1 -1
  6. package/dist/drizzle/schema.d.ts +467 -5
  7. package/dist/drizzle/schema.d.ts.map +1 -1
  8. package/dist/drizzle/schema.js +108 -14
  9. package/dist/executor.d.ts +8 -0
  10. package/dist/executor.d.ts.map +1 -0
  11. package/dist/executor.js +79 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +40 -15
  14. package/dist/invocation-notifications.d.ts +23 -0
  15. package/dist/invocation-notifications.d.ts.map +1 -0
  16. package/dist/invocation-notifications.js +156 -0
  17. package/dist/invocation-retention.d.ts +11 -0
  18. package/dist/invocation-retention.d.ts.map +1 -0
  19. package/dist/invocation-retention.js +14 -0
  20. package/dist/invocations.d.ts +24 -0
  21. package/dist/invocations.d.ts.map +1 -0
  22. package/dist/invocations.js +208 -0
  23. package/dist/message.d.ts +1 -0
  24. package/dist/message.d.ts.map +1 -1
  25. package/dist/message.js +5 -3
  26. package/dist/queue.d.ts +32 -8
  27. package/dist/queue.d.ts.map +1 -1
  28. package/dist/queue.js +468 -97
  29. package/dist/retention.d.ts +66 -0
  30. package/dist/retention.d.ts.map +1 -0
  31. package/dist/retention.js +152 -0
  32. package/dist/run-status.d.ts +54 -0
  33. package/dist/run-status.d.ts.map +1 -0
  34. package/dist/run-status.js +138 -0
  35. package/dist/snapshots.d.ts +23 -0
  36. package/dist/snapshots.d.ts.map +1 -0
  37. package/dist/snapshots.js +64 -0
  38. package/dist/storage.d.ts +8 -1
  39. package/dist/storage.d.ts.map +1 -1
  40. package/dist/storage.js +1613 -319
  41. package/dist/streamer.d.ts.map +1 -1
  42. package/dist/streamer.js +109 -41
  43. package/dist/zod.d.ts.map +1 -1
  44. package/dist/zod.js +3 -3
  45. package/package.json +17 -14
  46. package/src/drizzle/migrations/0014_add_attr_set_event_unique_index.sql +5 -0
  47. package/src/drizzle/migrations/0015_move_enums_to_workflow_schema.sql +75 -0
  48. package/src/drizzle/migrations/0016_add_encryption_public_key.sql +1 -0
  49. package/src/drizzle/migrations/0017_add_hook_resume_context.sql +1 -0
  50. package/src/drizzle/migrations/0018_add_hook_token_retention.sql +1 -0
  51. package/src/drizzle/migrations/0019_add_event_slots.sql +74 -0
  52. package/src/drizzle/migrations/0020_add_invocations.sql +13 -0
  53. package/src/drizzle/migrations/0021_invocation_identity_retention.sql +19 -0
  54. package/src/drizzle/migrations/0022_invocation_outcomes.sql +3 -0
  55. package/src/drizzle/migrations/0023_add_hook_claimed_from.sql +1 -0
  56. package/src/drizzle/migrations/0024_add_dynamic_workflow_code.sql +1 -0
  57. package/src/drizzle/migrations/0025_add_snapshots_table.sql +6 -0
  58. package/src/drizzle/migrations/meta/_journal.json +84 -0
package/README.md CHANGED
@@ -1,6 +1,93 @@
1
1
  # @workflow/world-postgres
2
2
 
3
- An embedded worker/workflow system backed by PostgreSQL for multi-host self-hosted solutions. This is a reference implementation - a production-ready solution might run workers in separate processes with a more robust queuing system.
3
+ An embedded worker and workflow system backed by PostgreSQL for multi-host self-hosted solutions.
4
+
5
+ > **This is a reference implementation.** It shows how to implement the World
6
+ > interface on top of a database and a queue, and it is a reasonable starting
7
+ > point for self-hosting. It is not a managed backend: it ships **without
8
+ > authentication**, and it is not tuned for the performance or scale properties
9
+ > of one. A production deployment typically runs workers in separate processes
10
+ > with a more robust queuing system, and **must** put its own authentication in
11
+ > front of the workflow HTTP routes. Read [Security](#security) before you
12
+ > deploy it.
13
+ >
14
+ > While some customers have been successful in deploying the Postgres World as
15
+ > is, for production use-cases, we highly recommend cloning this reference
16
+ > implementation and adapting it to your persistence, network stack, scale and
17
+ > security requirements.
18
+
19
+ ## Security
20
+
21
+ The Postgres World does **not** automatically authenticate the requests that
22
+ drive workflow execution. Adding that is your responsibility, and it should be
23
+ in place before an app using this World is reachable by untrusted clients.
24
+
25
+ ### Protect the queue route
26
+
27
+ `POST /.well-known/workflow/v1/flow` is where the worker delivers workflow
28
+ orchestration and queued step invocations. It is mounted in your application
29
+ like any other route, so it is publicly reachable by default, and the queue
30
+ handler, inherited from
31
+ [`@workflow/world-local`](https://github.com/vercel/workflow/tree/main/packages/world-local),
32
+ accepts any request whose `x-vqs-*` headers and queue-name prefix are
33
+ well-formed, leaving the payload itself to be validated later by the runtime
34
+ that consumes the message. There is no signature, shared secret, or caller check,
35
+ so anyone who can reach the route can forge or replay a workflow or step
36
+ invocation, including steps your application would only reach after its own
37
+ gating. Restrict it before you expose the app.
38
+
39
+ The other routes under `/.well-known/workflow/v1/` differ:
40
+
41
+ - `webhook/:token`, created by
42
+ [`createWebhook()`](https://workflow-sdk.dev/docs/api-reference/workflow/create-webhook),
43
+ is authorized by the token in the URL and nothing else. Use
44
+ [`createHook()`](https://workflow-sdk.dev/docs/api-reference/workflow/create-hook)
45
+ behind your own authenticated route and
46
+ [`resumeHook()`](https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook)
47
+ when you need more than that.
48
+ - `manifest.json` responds with `404` unless the app was built with
49
+ `WORKFLOW_PUBLIC_MANIFEST=1`. That variable is read at build time, so
50
+ unsetting it in the runtime environment of an already-built deployment does
51
+ not withdraw the manifest. Leave it unset outside of testing, because the
52
+ manifest lists your workflow and step names.
53
+
54
+ ### Bringing your own auth
55
+
56
+ Workflow does not prescribe an auth mechanism, so gate the flow route at the
57
+ network edge rather than inside the application:
58
+
59
+ - **Keep the flow route unreachable from outside.** By default the worker
60
+ delivers to a loopback address (`http://localhost:{PORT}`, or
61
+ `WORKFLOW_LOCAL_BASE_URL` when set), so in the common single-process topology
62
+ nothing outside the container needs to reach it. Blocking external requests to
63
+ `/.well-known/workflow/v1/flow` at your ingress, reverse proxy, or firewall
64
+ costs you nothing, because loopback delivery never traverses that layer. Do
65
+ not block the whole `/.well-known/workflow/` prefix if you use
66
+ `createWebhook()`: its `webhook/:token` route sits under the same prefix and
67
+ has to stay reachable by whoever calls it.
68
+ - **Authenticate at the proxy when the routes must cross hosts.** If your web
69
+ tier and workers are separate deployments, require mTLS or a shared-secret
70
+ header at the proxy in front of the application, and strip any client-supplied
71
+ copy of that header at the edge.
72
+ - **Do not gate these paths in framework middleware.** The setup guides tell you
73
+ to exclude `/.well-known/workflow/*` from your Next.js proxy matcher, because a
74
+ handler that consumes the internal request body breaks execution. Adding the
75
+ paths back in order to gate them reintroduces that failure mode.
76
+ - **Do not expect the World to present a credential.** It does not sign its
77
+ delivery requests or attach a secret to them, so an in-application check that
78
+ requires one will reject the World's own deliveries.
79
+
80
+ ### Data at rest
81
+
82
+ This World does not currently implement `getEncryptionKeyForRun()`, so it does
83
+ not participate in Workflow's
84
+ [end-to-end encryption](https://workflow-sdk.dev/docs/how-it-works/encryption):
85
+ workflow and step inputs and return values, hook payloads and metadata, and
86
+ stream chunks are all stored in your database in readable form. A World derived
87
+ from this one can opt in by implementing that single method (see
88
+ [Custom World implementations](https://workflow-sdk.dev/docs/how-it-works/encryption#custom-world-implementations)),
89
+ which is the recommended route if your workflows carry sensitive data. Until
90
+ then, protect the database, its credentials, and its backups accordingly.
4
91
 
5
92
  ## Installation
6
93
 
@@ -14,9 +101,9 @@ yarn add @workflow/world-postgres
14
101
 
15
102
  ## Usage
16
103
 
17
- ### Basic Setup
104
+ ### Basic setup
18
105
 
19
- The postgres world can be configured by setting the `WORKFLOW_TARGET_WORLD` environment variable to the package name:
106
+ The PostgreSQL World can be configured by setting the `WORKFLOW_TARGET_WORLD` environment variable to the package name:
20
107
 
21
108
  ```bash
22
109
  export WORKFLOW_TARGET_WORLD="@workflow/world-postgres"
@@ -38,9 +125,15 @@ export WORKFLOW_POSTGRES_WORKER_CONCURRENCY="10"
38
125
 
39
126
  # Optional: Internal pg.Pool max size (default: 10)
40
127
  export WORKFLOW_POSTGRES_MAX_POOL_SIZE="10"
128
+
129
+ # Optional: Let the application coordinate shutdown (default: false)
130
+ export WORKFLOW_POSTGRES_APPLICATION_MANAGED_SHUTDOWN="1"
131
+
132
+ # Optional: Maximum Hook minimum retention in days (default: 30)
133
+ export WORKFLOW_POSTGRES_HOOK_RETENTION_LIMIT_DAYS="30"
41
134
  ```
42
135
 
43
- ### Programmatic Usage
136
+ ### Programmatic usage
44
137
 
45
138
  You can also create a PostgreSQL world directly in your code:
46
139
 
@@ -61,62 +154,96 @@ const pool = new Pool({ connectionString: process.env.DATABASE_URL });
61
154
  const worldFromPool = createWorld({ pool });
62
155
  ```
63
156
 
64
- ## Configuration Options
157
+ ### Application-managed shutdown
158
+
159
+ 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:
160
+
161
+ ```typescript
162
+ import { createWorld } from '@workflow/world-postgres';
163
+
164
+ const world = createWorld({
165
+ connectionString: process.env.DATABASE_URL!,
166
+ applicationManagedShutdown: true,
167
+ });
168
+
169
+ await world.start();
170
+ ```
171
+
172
+ Use this option only when your application or framework has its own shutdown hook. Handle cleanup errors there and await `world.close()` first, then close the workflow HTTP server and any caller-owned `pg.Pool`.
173
+
174
+ Closing the world stops the queue from accepting new jobs and waits for active jobs. After Graphile Worker's graceful-shutdown timeout (5s by default), it aborts any workflow HTTP request that is still pending. Graphile Worker then unlocks the same row through its normal failure handling. Graphile counts a delivery attempt when it claims the row, so the aborted delivery consumes that attempt and is retried only if its Graphile attempt budget remains. A one-attempt or final-attempt job is unlocked but not retried. The shutdown handler does not create a replacement row.
175
+
176
+ An aborted HTTP request does not guarantee that its server-side handler stopped, so workflow and step handlers must continue to tolerate at-least-once execution. Keep the workflow HTTP routes and any caller-owned pool available until `world.close()` resolves.
177
+
178
+ ## Configuration options
65
179
 
66
180
  | Option | Type | Default | Description |
67
181
  | ------------------ | --------- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
68
- | `connectionString` | `string` | `process.env.WORKFLOW_POSTGRES_URL` or `'postgres://world:world@localhost:5432/world'` | Used only when `pool` is omitted, to construct an internal pool |
182
+ | `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 |
69
183
  | `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 |
70
- | `pool` | `pg.Pool` | — | Optional. When set, used for Drizzle, Graphile Worker, and stream writes. `world.close()` does not end it. |
184
+ | `pool` | `pg.Pool` | Not applicable | Optional. When set, used for Drizzle, Graphile Worker, and stream writes. `world.close()` does not end it. |
71
185
  | `jobPrefix` | `string` | `process.env.WORKFLOW_POSTGRES_JOB_PREFIX` | Optional prefix for queue job names |
72
- | `queueConcurrency` | `number` | `50` | Number of concurrent active step executions per process. Must be high enough to cover any parent→child workflow polling in flight — each `Run#returnValue` await holds a worker slot until the child run terminates. |
186
+ | `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
+ | `pollInterval` | `number` | `500` | Milliseconds between idle job fetches per worker. |
188
+ | `applicationManagedShutdown` | `boolean` | `false`; `WORKFLOW_POSTGRES_APPLICATION_MANAGED_SHUTDOWN=1` enables it for the default package configuration | Whether the application coordinates shutdown and awaits `world.close()` instead of Graphile Worker responding automatically. |
73
189
 
74
- ## Environment Variables
190
+ ## Environment variables
75
191
 
76
192
  | Variable | Description | Default |
77
193
  | -------------------------------------- | ------------------------------------------------------------ | ----------------------------------------------- |
78
194
  | `WORKFLOW_TARGET_WORLD` | Set to `"@workflow/world-postgres"` to use this world | - |
79
- | `WORKFLOW_POSTGRES_URL` | PostgreSQL connection string | `'postgres://world:world@localhost:5432/world'` |
195
+ | `WORKFLOW_POSTGRES_URL` | PostgreSQL connection string | `DATABASE_URL` or `'postgres://world:world@localhost:5432/world'` |
80
196
  | `WORKFLOW_POSTGRES_JOB_PREFIX` | Prefix for queue job names | - |
81
197
  | `WORKFLOW_POSTGRES_WORKER_CONCURRENCY` | Number of concurrent workers | `50` |
198
+ | `WORKFLOW_POSTGRES_POLL_INTERVAL_MS` | Milliseconds between idle job fetches per worker | `500` |
82
199
  | `WORKFLOW_POSTGRES_MAX_POOL_SIZE` | Internal `pg.Pool` max size | `10` |
200
+ | `WORKFLOW_POSTGRES_APPLICATION_MANAGED_SHUTDOWN` | Set to `1` when the application coordinates shutdown and awaits `world.close()` | unset (`false`) |
201
+ | `WORKFLOW_POSTGRES_HOOK_RETENTION_LIMIT_DAYS` | Maximum Hook minimum retention in days | `30` |
83
202
 
84
203
  When `pool` is omitted, `maxPoolSize` precedence is: `createWorld({ maxPoolSize })`, then `WORKFLOW_POSTGRES_MAX_POOL_SIZE`, then the `pg.Pool` default.
85
204
 
86
205
  For higher worker concurrency, Graphile Worker recommends setting `maxPoolSize` to `10` or `queueConcurrency + 2`, whichever is larger.
87
206
 
88
- ## Database Setup
207
+ ## Database setup
89
208
 
90
209
  This package uses PostgreSQL with the following components:
91
210
 
92
- - **graphile-worker**: For queue processing and job management
211
+ - **Graphile Worker**: For queue processing and job management
93
212
  - **Drizzle ORM**: For database operations and schema management
94
213
  - **pg** (node-postgres): For PostgreSQL client connections. Drizzle and Graphile Worker share a `pg.Pool`, while LISTEN uses a dedicated `pg.Client` created from the same connection options.
95
214
 
96
- ### Quick Setup with CLI
215
+ ### Quick setup with CLI
97
216
 
98
- The easiest way to set up your database is using the included CLI tool:
217
+ Set up your database with the included CLI tool:
99
218
 
100
219
  ```bash
101
- pnpm exec workflow-postgres-setup
102
- # or
103
- npm exec workflow-postgres-setup
220
+ # npm
221
+ npx --package=@workflow/world-postgres bootstrap
222
+
223
+ # pnpm
224
+ pnpm dlx --package @workflow/world-postgres bootstrap
225
+
226
+ # Yarn
227
+ yarn dlx --package @workflow/world-postgres bootstrap
228
+
229
+ # Bun
230
+ bunx --package @workflow/world-postgres bootstrap
104
231
  ```
105
232
 
106
- The CLI automatically loads `.env` files and will use the connection string from:
233
+ The CLI and runtime World automatically load the connection string from:
107
234
  1. `WORKFLOW_POSTGRES_URL` environment variable
108
235
  2. `DATABASE_URL` environment variable
109
236
  3. Default: `postgres://world:world@localhost:5432/world`
110
237
 
111
- ### Database Schema
238
+ ### Database schema
112
239
 
113
240
  The setup creates the following tables:
114
241
 
115
- - `workflow_runs` - Stores workflow execution runs
116
- - `workflow_events` - Stores workflow events
117
- - `workflow_steps` - Stores individual workflow steps
118
- - `workflow_hooks` - Stores webhook hooks
119
- - `workflow_stream_chunks` - Stores streaming data chunks
242
+ - `workflow_runs`: Stores workflow execution runs
243
+ - `workflow_events`: Stores workflow events
244
+ - `workflow_steps`: Stores individual workflow steps
245
+ - `workflow_hooks`: Stores webhook hooks
246
+ - `workflow_stream_chunks`: Stores streaming data chunks
120
247
 
121
248
  You can also access the schema programmatically:
122
249
 
@@ -128,22 +255,168 @@ import * as schema from '@workflow/world-postgres/schema';
128
255
 
129
256
  Make sure your PostgreSQL database is accessible and the user has sufficient permissions to create tables and manage jobs.
130
257
 
258
+ ### Data retention
259
+
260
+ Postgres World does not yet perform general workflow-run cleanup. After a
261
+ retained Hook's run ends and its deadline passes, reads treat the Hook as absent
262
+ and its token can be reused. If the token is never reused, the expired
263
+ `workflow_hooks` row remains.
264
+
131
265
  ## Features
132
266
 
133
- - **Durable Storage**: Stores workflow runs, events, steps, hooks, and webhooks in PostgreSQL
134
- - **Queue Processing**: Uses graphile-worker as the durable queue and executes jobs over the workflow HTTP routes
135
- - **Durable Delays**: Re-schedules waits and retries in PostgreSQL
267
+ - **Durable storage**: Stores workflow runs, events, steps, hooks, and webhooks in PostgreSQL
268
+ - **Queue processing**: Uses Graphile Worker as the durable queue and executes jobs over the workflow HTTP routes
269
+ - **Durable delays**: Reschedules waits and retries in PostgreSQL
136
270
  - **Streaming**: Real-time event streaming capabilities
137
- - **Health Checks**: Built-in connection health monitoring
138
- - **Configurable Concurrency**: Adjustable worker concurrency for queue processing
139
-
140
- ## Queue Behavior
271
+ - **Health checks**: Built-in connection health monitoring
272
+ - **Configurable concurrency**: Adjustable worker concurrency for queue processing
141
273
 
274
+ ## Queue behavior
142
275
 
143
- - Graphile jobs are acknowledged only after the workflow or step execution finishes, or after the worker durably schedules a delayed follow-up job
276
+ - Graphile jobs are acknowledged only after execution finishes, or after the worker durably schedules a delayed follow-up job
144
277
  - Backlog stays in PostgreSQL when all execution slots are busy
145
278
  - Retry and sleep-style delays use Graphile `runAt` scheduling
146
- - Workflow and step execution is sent through `/.well-known/workflow/v1/flow` and `/.well-known/workflow/v1/step`
279
+ - Workflow orchestration and queued step execution are both sent through `/.well-known/workflow/v1/flow`
280
+
281
+ ### Experimental synchronous invocation
282
+
283
+ Enable synchronous hook-input delivery with `WORKFLOW_POSTGRES_INVOKE=1` when
284
+ using `WORKFLOW_TARGET_WORLD`, or pass `enableInvoke: true` to `createWorld()`.
285
+ Invocation is off by default.
286
+
287
+ Apply the database migrations before running the upgraded World, including when
288
+ invocation is disabled, because hook deduplication and data purging use new
289
+ columns. Upgrade producers and workers together, using matching versions and the
290
+ same job prefix and namespace. Migration 0022 versions stored responses so values
291
+ from earlier previews keep their original meaning.
292
+
293
+ With invocation enabled, the World advertises `capabilities.invoke`.
294
+ `resumeHook()` sends the hook input to the run's executor, which validates the
295
+ input, writes the hook event, and responds. The response confirms that processing
296
+ has finished; workflow user code may consume the event later.
297
+
298
+ The World calls the SDK handler with `{ runId, invoke: true, requestId, input }`
299
+ and stores its response as an `InvocationOutcome`. `invoke()` returns the value
300
+ or throws the restored Workflow error with its diagnostic fields. Invocation
301
+ results are response data, including any `timeoutSeconds` property.
302
+
303
+ A terminal error, such as a missing hook or an input-identity conflict, is stored
304
+ as the request's outcome. Retrying that identity returns the stored error while
305
+ the result is retained. Transient or unrecognized failures leave the input pending
306
+ and cause Graphile to retry the workflow execution job. Failure to store or read
307
+ a response leaves the caller's outcome unknown. Earlier event writes may have
308
+ committed in either case.
309
+
310
+ Postgres stores inputs and responses in `workflow.workflow_invocations`. The
311
+ input is inserted into `workflow_invocations` and a request is enqueued in
312
+ Graphile in the same transaction. Retrying a retained input also enqueues a
313
+ workflow execution request, even when its response is already stored. This lets
314
+ the runner check committed events if a previous runner stopped after responding
315
+ but before replaying them.
316
+
317
+ Reuse an `idempotencyKey` with the same payload when retrying an invocation.
318
+ Without a key, each call creates a new input.
319
+
320
+ With invocation disabled (the default), deliveries for the same run may execute
321
+ concurrently. A workflow request can execute a step inline and wait for a hook
322
+ wake to abort that step, so the queue cannot hold a per-run lock for the entire
323
+ request. Each queue instance coalesces in-flight and recently completed deliveries
324
+ with the same idempotency key. Handlers must still tolerate at-least-once delivery
325
+ across worker processes, restarts, or completed-message cache eviction.
326
+
327
+ With invocation enabled, each Graphile worker pool registers two task
328
+ identifiers. A task identifier selects a handler. A named queue controls which
329
+ jobs can execute concurrently. The default job prefix produces these names:
330
+
331
+ | Task identifier | Work | Named queue |
332
+ | --- | --- | --- |
333
+ | `workflow_flows_executor` | Start or resume workflow execution | `workflow_flows:<runId>:executor`, one queue per run |
334
+ | `workflow_flows` | Step execution and health checks | No run-scoped named queue |
335
+
336
+ Graphile permits one active job per run's named queue across worker processes.
337
+ Different runs, step jobs, and health checks can execute concurrently.
338
+ `queueConcurrency` limits the total active Graphile jobs per worker process
339
+ across both task identifiers and defaults to **50**.
340
+
341
+ While a workflow execution job is active, the World passes pending invocation
342
+ inputs to the SDK handler, including while inline steps wait. After an execution
343
+ returns, the World checks for idle time or an expired 120s input-intake budget.
344
+ Before acknowledging the job, the World stops reading new inputs, finishes any
345
+ input already being processed, and replays events committed since the previous
346
+ replay began. A later job can resume the run in another process.
347
+
348
+ A workflow execution request is the HTTP request sent by a Graphile
349
+ `workflow_flows_executor` job to start or resume a run. An invocation is an input
350
+ submitted through `world.invoke()` and stored in `workflow_invocations`. One
351
+ workflow execution request can process several invocations.
352
+
353
+ Before processing pending inputs, the HTTP receiver verifies the execution
354
+ request against Graphile's `jobs` view. The worker supplies the job ID, worker ID,
355
+ and attempt through private HTTP headers. The receiver requires a locked job
356
+ with matching metadata, the executor task identifier, and the run's named queue.
357
+ Application-supplied headers cannot replace this metadata. Step jobs and health
358
+ checks process their own work without reading pending invocation rows.
359
+
360
+ Updated workers move legacy orchestration jobs to the executor task before
361
+ acknowledging them, preserving message identity and the remaining attempt budget.
362
+ Updated HTTP receivers also reroute unmarked legacy requests. Older workers
363
+ cannot enforce these checks, so upgrade participating workers together.
364
+
365
+ Verification happens when the request enters the receiver. A handler that keeps
366
+ running after Graphile reclaims its job can still write events; this
367
+ implementation does not fence those writes.
368
+
369
+ The Postgres World reads pending inputs in pages of 32. One dedicated
370
+ `LISTEN/NOTIFY` connection per World instance signals new inputs and responses.
371
+ The connection opens when needed. Notifications contain hashed identifiers;
372
+ readers fetch payloads and results from the table.
373
+
374
+ Notifications commit with their associated writes. Readers track changes across
375
+ each query and reread after subscribing or reconnecting, covering writes that
376
+ arrived before the subscription became active.
377
+
378
+ Use a database connection that supports sessions for `LISTEN`. Transaction
379
+ pooling alone cannot maintain that subscription. When notifications are
380
+ unavailable, readers poll at 1s intervals and connection retries use a 1s backoff.
381
+ The World logs notification failure and recovery once per transition, excluding
382
+ payloads and connection details.
383
+
384
+ | Setting or limit | Value |
385
+ | --- | --- |
386
+ | Default response-wait timeout | 30s, configurable with `timeoutMs` |
387
+ | Maximum encoded input size | 1 MiB |
388
+ | Maximum encoded outcome size | 1 MiB |
389
+ | Pending-input page size | 32 rows |
390
+
391
+ A timeout ends the caller's wait without canceling processing or establishing
392
+ its outcome. Closing the World aborts local response waits and closes input
393
+ readers and the notification connection.
394
+
395
+ Postgres implements `hookResumeDedup` with a durable resume ID and payload digest.
396
+ Retrying the same identity reuses the committed hook event, including after hook
397
+ disposal or run completion. Reusing the identity with a different payload is
398
+ rejected.
399
+
400
+ The hook event and response are written in separate operations. If storing the
401
+ response fails, deduplication lets a retry recover the event's result. Step code
402
+ remains responsible for making its external side effects safe to retry.
403
+
404
+ `$retention: 0` purges invocation inputs, results, and fingerprints with the run's
405
+ other user data. An expiry marker lets waiting callers and retries receive a 410
406
+ error with code `INVOCATION_DATA_EXPIRED`. Writers lock and recheck the run so
407
+ late writes cannot restore purged data. A caller can receive this expiry error
408
+ after its hook event committed if the result expires before the caller reads it.
409
+ The migration also clears invocation data for runs that already expired or ended
410
+ with zero retention.
411
+
412
+ The experimental implementation has these remaining limitations:
413
+
414
+ - Results outside zero-retention purging have no automatic cleanup.
415
+ - A handler can continue writing after Graphile aborts or reclaims its job.
416
+ - Requests are not routed to a compatible deployment when workers run different code versions.
417
+
418
+ The database integration tests use the built core runtime. Build core before
419
+ running `pnpm exec vitest run test/invoke.test.ts` from `packages/world-postgres`.
147
420
 
148
421
  ## Development
149
422
 
@@ -176,7 +449,7 @@ pnpm build
176
449
  pnpm test
177
450
  ```
178
451
 
179
- ## World Selection
452
+ ## World selection
180
453
 
181
454
  To use the PostgreSQL world, set the `WORKFLOW_TARGET_WORLD` environment variable to the package name:
182
455
 
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+
3
+ console.error(`The workflow-postgres-setup command has moved.
4
+
5
+ Use one of these commands instead:
6
+
7
+ # npm
8
+ npx --package=@workflow/world-postgres bootstrap
9
+
10
+ # pnpm
11
+ pnpm dlx --package @workflow/world-postgres bootstrap
12
+
13
+ # Yarn
14
+ yarn dlx --package @workflow/world-postgres bootstrap
15
+
16
+ # Bun
17
+ bunx --package @workflow/world-postgres bootstrap
18
+ `);
19
+
20
+ process.exit(1);
package/dist/config.d.ts CHANGED
@@ -10,7 +10,23 @@ type PgConnectionConfig = {
10
10
  };
11
11
  export type PostgresWorldConfig = PgConnectionConfig & {
12
12
  jobPrefix?: string;
13
+ /**
14
+ * namespace for queue topic prefixes (e.g. 'custom' → '__custom_wkf_workflow_').
15
+ * defaults to WORKFLOW_QUEUE_NAMESPACE env var if not provided.
16
+ */
17
+ namespace?: string;
13
18
  queueConcurrency?: number;
19
+ /** Milliseconds between idle job fetches per worker. Defaults to 500. */
20
+ pollInterval?: number;
21
+ /** Enable experimental invoke() delivery with one Graphile execution queue per run. */
22
+ enableInvoke?: boolean;
23
+ /**
24
+ * Whether the application coordinates shutdown instead of Graphile Worker
25
+ * responding automatically. The application must await world.close().
26
+ * Defaults to false. The package's default createWorld() configuration
27
+ * enables it when WORKFLOW_POSTGRES_APPLICATION_MANAGED_SHUTDOWN is `1`.
28
+ */
29
+ applicationManagedShutdown?: boolean;
14
30
  /**
15
31
  * Override the flush interval (in ms) for buffered stream writes.
16
32
  * Default is 10ms. Set to 0 for immediate flushing.
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAE/B,KAAK,kBAAkB,GACnB;IAAE,gBAAgB,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,SAAS,CAAA;CAAE,GACpE;IAAE,IAAI,EAAE,IAAI,CAAC;IAAC,gBAAgB,CAAC,EAAE,SAAS,CAAC;IAAC,WAAW,CAAC,EAAE,SAAS,CAAA;CAAE,CAAC;AAE1E,MAAM,MAAM,mBAAmB,GAAG,kBAAkB,GAAG;IACrD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC,CAAC"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAE/B,KAAK,kBAAkB,GACnB;IAAE,gBAAgB,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,SAAS,CAAA;CAAE,GACpE;IAAE,IAAI,EAAE,IAAI,CAAC;IAAC,gBAAgB,CAAC,EAAE,SAAS,CAAC;IAAC,WAAW,CAAC,EAAE,SAAS,CAAA;CAAE,CAAC;AAE1E,MAAM,MAAM,mBAAmB,GAAG,kBAAkB,GAAG;IACrD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,yEAAyE;IACzE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,uFAAuF;IACvF,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;;;;OAKG;IACH,0BAA0B,CAAC,EAAE,OAAO,CAAC;IACrC;;;OAGG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC,CAAC"}
package/dist/config.js CHANGED
@@ -1,2 +1,2 @@
1
1
  export {};
2
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlnLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2NvbmZpZy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHR5cGUgeyBQb29sIH0gZnJvbSAncGcnO1xuXG50eXBlIFBnQ29ubmVjdGlvbkNvbmZpZyA9XG4gIHwgeyBjb25uZWN0aW9uU3RyaW5nOiBzdHJpbmc7IG1heFBvb2xTaXplPzogbnVtYmVyOyBwb29sPzogdW5kZWZpbmVkIH1cbiAg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