@workflow/world-postgres 5.3.0 → 5.4.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 (54) hide show
  1. package/README.md +10 -2
  2. package/bin/prune.js +12 -0
  3. package/chart/.helmignore +1 -0
  4. package/chart/Chart.yaml +5 -0
  5. package/chart/README.md +218 -0
  6. package/chart/templates/_helpers.tpl +125 -0
  7. package/chart/templates/deployment.yaml +40 -0
  8. package/chart/templates/prune.yaml +85 -0
  9. package/chart/templates/service.yaml +14 -0
  10. package/chart/templates/serviceaccount.yaml +9 -0
  11. package/chart/templates/unpinned-worker.yaml +42 -0
  12. package/chart/templates/workers.yaml +67 -0
  13. package/chart/values.yaml +94 -0
  14. package/dist/config.d.ts +13 -0
  15. package/dist/config.js +1 -1
  16. package/dist/drizzle/schema.d.ts +17 -0
  17. package/dist/drizzle/schema.js +10 -1
  18. package/dist/index.js +35 -9
  19. package/dist/job-lease.js +3 -8
  20. package/dist/kubernetes/backlog-handler.d.ts +53 -0
  21. package/dist/kubernetes/backlog-handler.js +71 -0
  22. package/dist/kubernetes/backlog.d.ts +64 -0
  23. package/dist/kubernetes/backlog.js +98 -0
  24. package/dist/kubernetes/index.d.ts +15 -0
  25. package/dist/kubernetes/index.js +15 -0
  26. package/dist/kubernetes/lifecycle.d.ts +58 -0
  27. package/dist/kubernetes/lifecycle.js +62 -0
  28. package/dist/kubernetes/prune/cli.d.ts +2 -0
  29. package/dist/kubernetes/prune/cli.js +126 -0
  30. package/dist/kubernetes/prune/in-cluster.d.ts +25 -0
  31. package/dist/kubernetes/prune/in-cluster.js +75 -0
  32. package/dist/kubernetes/prune/kube.d.ts +17 -0
  33. package/dist/kubernetes/prune/kube.js +115 -0
  34. package/dist/kubernetes/prune/labels.d.ts +20 -0
  35. package/dist/kubernetes/prune/labels.js +20 -0
  36. package/dist/kubernetes/prune/plan.d.ts +64 -0
  37. package/dist/kubernetes/prune/plan.js +69 -0
  38. package/dist/kubernetes/prune/prune.d.ts +61 -0
  39. package/dist/kubernetes/prune/prune.js +240 -0
  40. package/dist/message.d.ts +1 -0
  41. package/dist/message.js +11 -1
  42. package/dist/queue.d.ts +19 -2
  43. package/dist/queue.js +86 -14
  44. package/dist/retention.d.ts +76 -8
  45. package/dist/retention.js +188 -14
  46. package/dist/run-lease.d.ts +10 -0
  47. package/dist/run-lease.js +13 -3
  48. package/dist/storage.d.ts +22 -1
  49. package/dist/storage.js +264 -60
  50. package/dist/streamer.d.ts +1 -1
  51. package/dist/streamer.js +80 -16
  52. package/package.json +15 -8
  53. package/src/drizzle/migrations/0032_add_run_wake_pending.sql +7 -0
  54. package/src/drizzle/migrations/meta/_journal.json +7 -0
package/README.md CHANGED
@@ -204,6 +204,7 @@ An aborted HTTP request does not guarantee that its server-side handler stopped,
204
204
  | `queueConcurrency` | `number` | `50` | Number of concurrent active step executions per process. A parent workflow awaiting `returnValue` of a child it started suspends on a system hook and holds no slot, but a `returnValue` polled inside a step holds one until the child run terminates, so cover the peak number of those in flight. |
205
205
  | `pollInterval` | `number` | `500` | Milliseconds between idle job fetches per worker. |
206
206
  | `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. |
207
+ | `skipWorkers` | `boolean` | `false`; `WORKFLOW_POSTGRES_SKIP_WORKERS=1` enables it for the default package configuration | Run no workers in this process: it can start, resume, cancel and read runs, but claims no jobs and doesn't recover interrupted runs at startup. Its runs execute on processes with workers on the same database, `jobPrefix` and `deploymentId` (when one is set); a run this process created but didn't enqueue is recovered the next time one of them starts. |
207
208
  | `jobLockStaleSeconds` | `number` | `process.env.WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`, or unset: renew every delivery and release only spec 9 run-lease jobs of renewing holders after 300 s | Seconds a running delivery's job lock may go unrenewed before another process redelivers any of this World's jobs. `0` turns renewal and the release of stale locks off. `30` is a good value when more than one process shares the database. See [Crash recovery](#crash-recovery). |
208
209
 
209
210
  ## Environment variables
@@ -218,6 +219,7 @@ An aborted HTTP request does not guarantee that its server-side handler stopped,
218
219
  | `WORKFLOW_POSTGRES_POLL_INTERVAL_MS` | Milliseconds between idle job fetches per worker | `500` |
219
220
  | `WORKFLOW_POSTGRES_MAX_POOL_SIZE` | Internal `pg.Pool` max size | `10` |
220
221
  | `WORKFLOW_POSTGRES_APPLICATION_MANAGED_SHUTDOWN` | Set to `1` when the application coordinates shutdown and awaits `world.close()` | unset (`false`) |
222
+ | `WORKFLOW_POSTGRES_SKIP_WORKERS` | Set to `1` to run no workers in this process: it sends work, which processes with workers on the same database, job prefix and deployment ID execute | unset (`false`) |
221
223
  | `WORKFLOW_POSTGRES_HOOK_RETENTION_LIMIT_DAYS` | Maximum Hook minimum retention in days | `30` |
222
224
  | `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS` | Seconds a running delivery's job lock may go unrenewed before another process redelivers the job; `0` disables | unset: 300 s, spec 9 run-lease jobs only |
223
225
 
@@ -322,6 +324,12 @@ retained Hook's run ends and its deadline passes, reads treat the Hook as absent
322
324
  and its token can be reused. If the token is never reused, the expired
323
325
  `workflow_hooks` row remains.
324
326
 
327
+ ## Kubernetes
328
+
329
+ The package includes a Helm chart for Kubernetes in its `chart` directory, as an optional way for production deployments into Kubernetes clusters. It works by pinning each run to its image tag, and by keeping around older releases' worker pods until their runs finish. It's scale-to-zero and supports pruning.
330
+
331
+ World postgres comes with optional Kubernetes support. See [`chart/README.md`](./chart/README.md) for more information.
332
+
325
333
  ## Features
326
334
 
327
335
  - **Durable storage**: Stores workflow runs, events, steps, hooks, and webhooks in PostgreSQL
@@ -343,7 +351,7 @@ and its token can be reused. If the token is never reused, the expired
343
351
 
344
352
  Graphile Worker on its own keeps a dead worker's job locked for 4 hours. A running delivery therefore renews its Graphile job lock every quarter of the stale window, and at least every 10 seconds, and every process that runs workers releases jobs whose locks have gone unrenewed for that window.
345
353
 
346
- By default (`jobLockStaleSeconds` unset), the window is 300 seconds and the release covers only the jobs that own a spec 9 run's delivery lease (its orchestrator deliveries, and invoke mode's executor lane) whose holder registered as renewing. A worker registers in `workflow.workflow_job_lock_holders` (migration 0030, applied by `bootstrap`) before its delivery runs. A spec 9 run whose worker was killed mid-delivery thus continues within about 8 minutes (one and a half windows). A job held by a process on an earlier version is never released this way, so the default is safe during a rolling upgrade, and other jobs are recovered by the next `start()`, which re-enqueues active runs, or after Graphile Worker's 4 hours. Without migrations 0030 and 0031, deliveries still run and renew, but nothing is released; a warning names the migration.
354
+ By default (`jobLockStaleSeconds` unset), the window is 300 seconds and the release covers only the jobs that own a spec 9 run's delivery lease (its orchestrator deliveries, and invoke mode's executor lane) whose holder registered as renewing. A worker registers in `workflow.workflow_job_lock_holders` (migration 0030, applied by `bootstrap`) before its delivery runs. A spec 9 run whose worker was killed mid-delivery thus continues within about 8 minutes (one and a half windows). A job held by a process on an earlier version is never released this way, so the default is safe during a rolling upgrade, and other jobs are recovered by the next `start()`, which re-enqueues active runs other than ones parked on a hook or a wait, or after Graphile Worker's 4 hours. A run that looks parked is still re-enqueued while a worker holds one of its orchestrator jobs locked: on a spec 8 run, whose deliveries are not serialized, a delivery that completes clears the run's owed wake even while a newer delivery of the run is still running, so the locked job is what shows that delivery may have been cut off. Without migrations 0030 and 0031, deliveries still run and renew, but nothing is released; a warning names the migration.
347
355
 
348
356
  Set `jobLockStaleSeconds` (or `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`) to release every job of this World, whoever holds it, after that many seconds. When a process dies mid-delivery, another process redelivers its jobs within about one and a half windows: about 45 seconds at 30. `30` is a good value when more than one process shares the database. The redelivery counts the attempt the dead process used. In invoke mode, the release covers the run's executor jobs too.
349
357
 
@@ -565,7 +573,7 @@ export WORKFLOW_TARGET_WORLD="@workflow/world-postgres"
565
573
 
566
574
  Runs of the experimental spec 9 runtime (`WORKFLOW_SPEC_VERSION=9`) run their orchestrator deliveries one at a time under the run's delivery lease (`workflow.workflow_run_delivery_leases`, migration 0031), with or without invocation, and publish their keyed messages with the `unsafe_dedupe` job key mode. A worker killed mid-job keeps the lease, through its locked job, until another process releases the job, by default after 300 seconds unrenewed (see [Crash recovery](#crash-recovery)); the job's redelivery takes the lease back. Earlier versions used a Graphile named queue per run, whose rows Graphile never deletes and locks on every poll, so throughput fell as runs accumulated. See [world-postgres on spec 9 runs](https://github.com/vercel/workflow/blob/main/packages/core/src/runtime/spec9/README.md#first-party-worlds).
567
575
 
568
- - **Live event feed.** Every committed event write of a spec 9 run sends a `NOTIFY` on `workflow_run_events` after its transaction commits, and `events.subscribe` delivers the run's new events to a running orchestrator from one shared `LISTEN` connection per process, read from the table in slot order. A delivery with nothing left to run then lingers on the feed while it waits on a background step (30 seconds, `WORKFLOW_ORCHESTRATOR_LINGER_MS`) or an open hook (5 seconds), so a burst of step outcomes or hook resumes is handled by one warm delivery. The feed does not deliver a `resumeHook()` resume (a `hook_received` with a `resumeId`): it ends there, so a delivery that is only waiting stops lingering, and the resume's wake, which carries its timing, consumes and measures it. A lingering delivery holds a worker slot, so at most half of a process's `queueConcurrency` slots keep a live feed at once (none at `queueConcurrency: 1`); past that, a delivery polls the log instead of lingering. The `LISTEN` connection needs a database connection that supports sessions, as for streams.
576
+ - **Live event feed.** Every committed event write of a spec 9 run sends a `NOTIFY` on `workflow_run_events` after its transaction commits, and `events.subscribe` delivers the run's new events to a running orchestrator from one shared `LISTEN` connection per process, read from the table in slot order. A delivery with nothing left to run then lingers on the feed while it waits on a background step (`WORKFLOW_ORCHESTRATOR_LINGER_MS`) or an open hook (`WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS`), 5 seconds each by default, or until a sleep due within that window (`WORKFLOW_ORCHESTRATOR_WAIT_LINGER_MS`) ends, so a burst of step outcomes or hook resumes, or a loop of short sleeps, is handled by one warm delivery. The feed does not deliver a `resumeHook()` resume (a `hook_received` with a `resumeId`): it ends there, so a delivery that is only waiting stops lingering, and the resume's wake, which carries its timing, consumes and measures it. A lingering delivery holds a worker slot, so at most half of a process's `queueConcurrency` slots keep a live feed at once (none at `queueConcurrency: 1`); past that, a delivery polls the log instead of lingering. The `LISTEN` connection needs a database connection that supports sessions, as for streams.
569
577
  - **Coalescing.** An orchestrator delivery that finds the run's lease held leaves its message on the lease and completes. When the holder finishes, it runs the handler again in the same worker for a wake left there (neither a start message nor a legacy `hookInput` resume, which are re-added as jobs instead), up to 32 times, instead of delivering each one. A re-run reports the next `deliveryCount`, the same `attempt` and the same `invocationStartedAt`, and carries the `hookResumeTiming` of a hook wake it absorbed, so the resume it consumes is measured (`workflow.resume.total_ms`). A handoff (`{ timeoutSeconds: 0 }`) passes the lease to its continuation, in the same transaction that adds it.
570
578
  - **Delivery cap.** A spec 9 orchestrator's `{ timeoutSeconds: n > 0 }` (a redelivery after the in-band fence refused its write) carries `attempt` over, so a run refused on every pass fails with `MAX_DELIVERIES_EXCEEDED` instead of looping. A step's retry in place still starts `attempt` over.
571
579
  - **Unstamped messages.** An orchestrator message without a spec stamp (an older SDK's `resumeHook()` or `cancel()` during a rolling upgrade) is checked against the run's stored `spec_version` when a worker takes it. For a spec 9 run, it is stamped with that version and re-added, so it takes the run's lease and waits for the run's live delivery instead of running beside it.
package/bin/prune.js ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../dist/kubernetes/prune/cli.js';
3
+
4
+ main().then(
5
+ (code) => {
6
+ process.exitCode = code;
7
+ },
8
+ (error) => {
9
+ console.error(error);
10
+ process.exitCode = 1;
11
+ }
12
+ );
@@ -0,0 +1 @@
1
+ tests/
@@ -0,0 +1,5 @@
1
+ apiVersion: v2
2
+ name: workflow-postgres
3
+ description: Runs a Workflow SDK application on @workflow/world-postgres in Kubernetes, with every run pinned to the image version that started it.
4
+ type: application
5
+ version: 0.1.0
@@ -0,0 +1,218 @@
1
+ # `workflow-postgres` Helm chart
2
+
3
+ Deploys an application that runs Workflow SDK workflows on `@workflow/world-postgres` in Kubernetes. Every run is pinned to the image version that started it, the way Vercel deployments pin runs on the Vercel World: a rollout never continues an in-flight run on new code.
4
+
5
+ The chart ships in the npm package, so an application that depends on `@workflow/world-postgres` can install it from `node_modules`:
6
+
7
+ ```sh
8
+ helm upgrade --install billing node_modules/@workflow/world-postgres/chart \
9
+ --set serviceName=billing \
10
+ --set image.repository=registry.example.com/billing \
11
+ --set image.tag="$(git rev-parse HEAD)" \
12
+ --set env.WORKFLOW_POSTGRES_URL="postgres://…"
13
+ ```
14
+
15
+ It needs [KEDA](https://keda.sh) in the cluster.
16
+
17
+ ## What it installs
18
+
19
+ | Resource | Per | Purpose |
20
+ | --- | --- | --- |
21
+ | Deployment `<serviceName>` and Service | release | Serves the application, the probes and the backlog endpoints, and runs this release's workflows. |
22
+ | Deployment `<serviceName>-wf-<tag>` | version | Runs only the workflows that version started. No Service traffic. |
23
+ | ScaledObject `<serviceName>-wf-<tag>` | version | KEDA scales that version's workers between 0 and `versionPinning.workers.maxReplicas` on its due deliveries (`<backlogPath>/backlog/<tag>`, field `wanted`). |
24
+ | CronJob `<serviceName>-workflow-prune`, with its ServiceAccount, Role and RoleBinding | release | Deletes the workers of versions whose runs have all finished, and recreates those of versions that have unfinished runs but no workers. |
25
+
26
+ The worker Deployment and ScaledObject carry `helm.sh/resource-policy: keep`. Without it, `helm upgrade` to a new tag would delete the previous version's workers while its runs still need them. With it, Helm stops tracking them on upgrade, and only the prune job deletes them.
27
+
28
+ Every container gets the configuration `createWorld()` reads:
29
+ - `WORKFLOW_POSTGRES_JOB_PREFIX`: `jobPrefix`, by default derived from `serviceName`;
30
+ - `WORKFLOW_POSTGRES_DEPLOYMENT_ID`: the image tag, which pins runs;
31
+ - `WORKFLOW_ROLE`: `service`, `worker` or `prune`;
32
+ - `PORT`, and everything in `env` and `envFrom`.
33
+
34
+ ## The application image
35
+
36
+ One image serves all three roles. Its entrypoint reads `WORKFLOW_ROLE`:
37
+
38
+ ```ts
39
+ import { createServer } from 'node:http';
40
+ import { createWorld } from '@workflow/world-postgres';
41
+ import {
42
+ createBacklogEndpoints,
43
+ createLifecycle,
44
+ pruneWorkersInCluster,
45
+ resolveWorkflowRole,
46
+ } from '@workflow/world-postgres/kubernetes';
47
+ import pg from 'pg';
48
+ import { setWorld } from 'workflow/runtime';
49
+
50
+ const role = resolveWorkflowRole();
51
+ if (role === 'prune') {
52
+ const result = await pruneWorkersInCluster();
53
+ process.exit(result.errors.length > 0 ? 1 : 0);
54
+ }
55
+
56
+ const pool = new pg.Pool({ connectionString: process.env.WORKFLOW_POSTGRES_URL });
57
+ const config = {
58
+ pool,
59
+ jobPrefix: process.env.WORKFLOW_POSTGRES_JOB_PREFIX,
60
+ // Pins every run this process starts to its image tag.
61
+ deploymentId: process.env.WORKFLOW_POSTGRES_DEPLOYMENT_ID || undefined,
62
+ // `createLifecycle` below drains on SIGTERM.
63
+ applicationManagedShutdown: true,
64
+ };
65
+ const world = createWorld(config);
66
+ setWorld(world);
67
+ await world.start();
68
+
69
+ const backlog = createBacklogEndpoints({ pool, config });
70
+ const server = createServer(async (req, res) => {
71
+ const { pathname } = new URL(req.url ?? '/', 'http://localhost');
72
+ const reply =
73
+ lifecycle.probe(pathname) ??
74
+ (role === 'service' ? await backlog.respond(req.method ?? 'GET', pathname) : undefined);
75
+ if (reply) {
76
+ res.writeHead(reply.status, { 'content-type': 'application/json' });
77
+ return res.end(JSON.stringify(reply.body));
78
+ }
79
+ // A worker serves only the Workflow SDK's routes: the queue delivers each
80
+ // job to this pod's own flow route.
81
+ if (role === 'worker' && !pathname.startsWith('/.well-known/workflow/')) {
82
+ return res.writeHead(404).end();
83
+ }
84
+ // …the application's own routes, including the Workflow SDK's.
85
+ });
86
+ server.listen(Number(process.env.PORT));
87
+
88
+ const lifecycle = createLifecycle({
89
+ close: async () => {
90
+ // The World first: it stops claiming jobs and waits for running
91
+ // deliveries, which reach this server's flow route.
92
+ await world.close?.();
93
+ await new Promise((resolve) => server.close(resolve));
94
+ await pool.end();
95
+ },
96
+ });
97
+ ```
98
+
99
+ The backlog endpoints disclose run counts: serve them only inside the cluster, or behind your own authentication.
100
+
101
+ A Dockerfile needs nothing specific to this chart, beyond an immutable tag per build:
102
+
103
+ ```dockerfile
104
+ FROM node:24-slim
105
+ WORKDIR /app
106
+ COPY package.json pnpm-lock.yaml ./
107
+ RUN corepack enable && pnpm install --frozen-lockfile --prod
108
+ COPY . .
109
+ RUN pnpm build
110
+ CMD ["node", "dist/server.js"]
111
+ ```
112
+
113
+ To run the prune job without your entrypoint, set `versionPinning.prune.command` to the bundled CLI:
114
+
115
+ ```yaml
116
+ versionPinning:
117
+ prune:
118
+ command: [node, node_modules/@workflow/world-postgres/bin/prune.js, --in-cluster]
119
+ ```
120
+
121
+ ## Migrations
122
+
123
+ Run `bootstrap` before a new version's pods start, or let the chart do it in an init container of every pod:
124
+
125
+ ```yaml
126
+ migrations:
127
+ enabled: true
128
+ command: [node, node_modules/@workflow/world-postgres/bin/setup.js]
129
+ ```
130
+
131
+ `bootstrap` is idempotent and safe to run from several pods at once. Old versions keep using the database until their last run finishes, so every migration must stay compatible with the oldest version that still has workers.
132
+
133
+ ## Use one immutable tag per build
134
+
135
+ The commit SHA is the right choice:
136
+ - the tag is the deployment ID runs are pinned to;
137
+ - it names that version's workers;
138
+ - restoring a version's lost workers swaps it into a copy of another version's manifests, which is why restoring needs a SHA.
139
+
140
+ The chart refuses tags it can't use: longer than 40 characters, with characters a deployment ID can't hold, `postgres` (reserved for unpinned runs), or too long together with `jobPrefix` for Graphile Worker's 128 character names.
141
+
142
+ ## How long old versions run
143
+
144
+ An old version keeps its workers until its last run finishes, with no time limit. A run started with `experimental_retention: 0` counts as unfinished until the check that its data was deleted has run, about a minute after it ends. Its pods scale to zero while nothing is due, including while its runs sleep or wait on a hook, and back up when a timer fires or a hook is resumed, even from a newer version.
145
+
146
+ The prune job never deletes a version's workers unless all of these hold:
147
+ - the version isn't the release's current version, and isn't the version of any of the main Deployment's ReplicaSets that still has pods (a rollout in progress, or a rollback);
148
+ - the workers are older than `versionPinning.prune.minAgeMinutes`;
149
+ - its backlog was read, and it reports no unfinished runs;
150
+ - the list of versions with unfinished runs was read, and the version isn't in it.
151
+
152
+ If any of these can't be checked, the workers are kept.
153
+
154
+ Things to plan for:
155
+ - **Runs that never finish** keep their version forever. Give hooks a timeout.
156
+ - **Child runs** inherit their parent's version.
157
+ - **Runs started without a deployment ID** are unpinned, and every pod this chart renders is pinned, so nothing claims them by default. See [Unpinned runs](#unpinned-runs).
158
+ - **A delivery still running when its pod stops** is redelivered from the start once its job lock goes stale. Keep `terminationGracePeriodSeconds` above your longest delivery.
159
+
160
+ ## Unpinned runs
161
+
162
+ A run started without a deployment ID waits for a process without one. Two kinds exist:
163
+ - the in-flight runs of an application that adopts this chart, started before its runs were pinned;
164
+ - runs created by a tool that doesn't set `WORKFLOW_POSTGRES_DEPLOYMENT_ID`, such as a re-run from a CLI or dashboard.
165
+
166
+ Enable `unpinnedWorker` to run them on the current release's image, with a fixed number of pods:
167
+
168
+ ```yaml
169
+ unpinnedWorker:
170
+ enabled: true
171
+ replicas: 1
172
+ ```
173
+
174
+ The backlog endpoints report how many there are (`unpinnedRuns` in `<backlogPath>/versions`), and the prune job logs a warning while there are any and no unpinned worker is deployed.
175
+
176
+ When adopting the chart, either let the previous deployment finish its in-flight runs before you switch, or enable `unpinnedWorker` until `unpinnedRuns` reaches zero. Leave it on if tools outside the release start runs. Give those tools `WORKFLOW_POSTGRES_DEPLOYMENT_ID` instead to pin their runs to a version.
177
+
178
+ ## Uninstalling
179
+
180
+ The per-version worker Deployments and ScaledObjects carry `helm.sh/resource-policy: keep`, so `helm uninstall` leaves them behind. It still deletes:
181
+ - the ServiceAccount they run as;
182
+ - the Service KEDA reads their backlog from;
183
+ - the prune job, which would otherwise delete them.
184
+
185
+ Their pods can't start again, and a reinstall under another release name conflicts with them. Once their runs have finished, delete them:
186
+
187
+ ```sh
188
+ kubectl delete deployment,scaledobject \
189
+ -l workflow.vercel.com/service=<serviceName>,workflow.vercel.com/role=worker
190
+ ```
191
+
192
+ To keep their runs going instead, uninstall only after every version but the current one has been pruned.
193
+
194
+ ## Images
195
+
196
+ The image of every version with workers must stay pullable until those workers are deleted. A KEDA scale-up from zero, or a restore, pulls it again. If your registry expires images, exclude tags that still have a `<serviceName>-wf-<tag>` Deployment, or keep images for longer than your longest-running workflow.
197
+
198
+ ## Permissions
199
+
200
+ - The prune job runs as its own ServiceAccount, with no database access: it reads backlogs from the service over HTTP.
201
+ - Its Role allows reading the main Deployment and listing its ReplicaSets, plus listing, creating and deleting Deployments and ScaledObjects. Kubernetes RBAC can't scope that by label, so install the chart in a namespace of its own.
202
+ - The application and its workers run as `serviceAccount`.
203
+
204
+ ## Deploying workers another way
205
+
206
+ To render a version's workers with your own tooling instead, keep the labels pruning lists them by (`WORKER_LABELS`) and run `workflow-postgres-prune` after each deploy, with your deploy pipeline's `kubectl` credentials:
207
+
208
+ ```sh
209
+ npx workflow-postgres-prune --context prod --namespace billing --service billing --version "$TAG"
210
+ ```
211
+
212
+ ## Test
213
+
214
+ `tests/kwok-e2e.sh` runs against any API server with RBAC and the KEDA CRDs, such as [kwok](https://kwok.sigs.k8s.io) started with `--secure-port --kube-authorization`. It:
215
+ - installs the chart, then upgrades it to a new tag;
216
+ - runs pruning as the chart's prune ServiceAccount, so the API server enforces its RBAC;
217
+ - reads backlogs from `createBacklogEndpoints` against a real Postgres;
218
+ - checks that a version is kept while it has an unfinished run, deleted once it finishes, and restored when it has runs but no workers.
@@ -0,0 +1,125 @@
1
+ {{- define "workflow-postgres.name" -}}
2
+ {{- $name := required "serviceName is required" .Values.serviceName -}}
3
+ {{- if not (regexMatch "^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$" $name) -}}{{- fail "serviceName must be a DNS label: at most 63 lowercase letters, digits and '-'" -}}{{- end -}}
4
+ {{- $name -}}
5
+ {{- end -}}
6
+
7
+ {{- define "workflow-postgres.jobPrefix" -}}
8
+ {{- if .Values.jobPrefix -}}
9
+ {{- .Values.jobPrefix -}}
10
+ {{- else -}}
11
+ {{- printf "%s_" (regexReplaceAll "[^a-z0-9]+" (lower .Values.serviceName) "_") -}}
12
+ {{- end -}}
13
+ {{- end -}}
14
+
15
+ {{/* The image tag, which is the deployment ID runs are pinned to. */}}
16
+ {{- define "workflow-postgres.tag" -}}
17
+ {{- if not (kindIs "string" (required "image.tag is required: one immutable tag per build, such as the commit SHA" .Values.image.tag)) -}}{{- fail "image.tag must be a string: quote it, or use --set-string (an all-digit SHA is read as a number)" -}}{{- end -}}
18
+ {{- $tag := .Values.image.tag -}}
19
+ {{- if gt (len $tag) 40 -}}{{- fail "image.tag must be at most 40 characters (a commit SHA)" -}}{{- end -}}
20
+ {{- /* It names the version's worker Deployment and ScaledObject and labels them, so it must suit both. */}}
21
+ {{- if not (regexMatch "^[a-z0-9]([a-z0-9._-]*[a-z0-9])?$" $tag) -}}{{- fail "image.tag may use only lowercase letters, digits, '.', '-' and '_', and must start and end with a letter or digit (it names Kubernetes objects)" -}}{{- end -}}
22
+ {{- if eq $tag "postgres" -}}{{- fail "image.tag must not be 'postgres': it is reserved for unpinned runs" -}}{{- end -}}
23
+ {{- if gt (add (len (include "workflow-postgres.jobPrefix" .)) (len $tag) 1) 82 -}}{{- fail "jobPrefix and image.tag together must be at most 81 characters (Graphile Worker's 128 character names)" -}}{{- end -}}
24
+ {{- $tag -}}
25
+ {{- end -}}
26
+
27
+ {{/* <name>-wf-<tag>, within the 63 characters KEDA needs for the HPA label it derives. */}}
28
+ {{- define "workflow-postgres.workerName" -}}
29
+ {{- $name := include "workflow-postgres.name" . -}}
30
+ {{- $tag := include "workflow-postgres.tag" . -}}
31
+ {{- $budget := sub 59 (len $tag) | int -}}
32
+ {{- if le (len $name) $budget -}}
33
+ {{- printf "%s-wf-%s" $name $tag -}}
34
+ {{- else -}}
35
+ {{- printf "%s-%s-wf-%s" (trunc (sub $budget 7 | int) $name | trimSuffix "-") (sha256sum $name | trunc 6) $tag -}}
36
+ {{- end -}}
37
+ {{- end -}}
38
+
39
+ {{- define "workflow-postgres.serviceAccountName" -}}
40
+ {{- if .Values.serviceAccount.create -}}
41
+ {{- default (include "workflow-postgres.name" .) .Values.serviceAccount.name -}}
42
+ {{- else -}}
43
+ {{- required "serviceAccount.name is required when serviceAccount.create is false" .Values.serviceAccount.name -}}
44
+ {{- end -}}
45
+ {{- end -}}
46
+
47
+ {{/* Read by `pruneWorkers`: keep in sync with WORKER_LABELS. */}}
48
+ {{- define "workflow-postgres.workerLabels" -}}
49
+ workflow.vercel.com/service: {{ include "workflow-postgres.name" . }}
50
+ workflow.vercel.com/role: worker
51
+ workflow.vercel.com/version: {{ include "workflow-postgres.tag" . | quote }}
52
+ {{- end -}}
53
+
54
+ {{- define "workflow-postgres.image" -}}
55
+ "{{ required "image.repository is required" .Values.image.repository }}:{{ include "workflow-postgres.tag" . }}"
56
+ {{- end -}}
57
+
58
+ {{/* The application container, less its name and env. */}}
59
+ {{- define "workflow-postgres.container" -}}
60
+ image: {{ include "workflow-postgres.image" . }}
61
+ imagePullPolicy: {{ .Values.image.pullPolicy }}
62
+ {{- with .Values.command }}
63
+ command: {{- toYaml . | nindent 2 }}
64
+ {{- end }}
65
+ {{- with .Values.args }}
66
+ args: {{- toYaml . | nindent 2 }}
67
+ {{- end }}
68
+ ports:
69
+ - name: http
70
+ containerPort: {{ .Values.port }}
71
+ livenessProbe:
72
+ httpGet: { path: {{ .Values.probes.livenessPath }}, port: http }
73
+ readinessProbe:
74
+ httpGet: { path: {{ .Values.probes.readinessPath }}, port: http }
75
+ {{- with .Values.resources }}
76
+ resources: {{- toYaml . | nindent 2 }}
77
+ {{- end }}
78
+ {{- with .Values.envFrom }}
79
+ envFrom: {{- toYaml . | nindent 2 }}
80
+ {{- end }}
81
+ {{- end -}}
82
+
83
+ {{/* Env of every container: how @workflow/world-postgres's createWorld() reads its configuration. */}}
84
+ {{- define "workflow-postgres.baseEnv" -}}
85
+ - name: PORT
86
+ value: {{ .Values.port | quote }}
87
+ - name: WORKFLOW_POSTGRES_JOB_PREFIX
88
+ value: {{ include "workflow-postgres.jobPrefix" . | quote }}
89
+ {{- if .Values.versionPinning.enabled }}
90
+ - name: WORKFLOW_POSTGRES_DEPLOYMENT_ID
91
+ value: {{ include "workflow-postgres.tag" . | quote }}
92
+ {{- end }}
93
+ {{- range $name, $value := .Values.env }}
94
+ - name: {{ $name }}
95
+ value: {{ $value | quote }}
96
+ {{- end }}
97
+ {{- end -}}
98
+
99
+ {{/* baseEnv without WORKFLOW_POSTGRES_DEPLOYMENT_ID: the unpinned worker's. */}}
100
+ {{- define "workflow-postgres.unpinnedEnv" -}}
101
+ - name: PORT
102
+ value: {{ .Values.port | quote }}
103
+ - name: WORKFLOW_POSTGRES_JOB_PREFIX
104
+ value: {{ include "workflow-postgres.jobPrefix" . | quote }}
105
+ {{- range $name, $value := .Values.env }}
106
+ - name: {{ $name }}
107
+ value: {{ $value | quote }}
108
+ {{- end }}
109
+ {{- end -}}
110
+
111
+ {{- define "workflow-postgres.initContainers" -}}
112
+ {{- if .Values.migrations.enabled }}
113
+ {{- if not .Values.migrations.command }}{{- fail "migrations.command is required when migrations.enabled is true" }}{{- end }}
114
+ initContainers:
115
+ - name: migrate
116
+ image: {{ include "workflow-postgres.image" . }}
117
+ imagePullPolicy: {{ .Values.image.pullPolicy }}
118
+ command: {{- toYaml .Values.migrations.command | nindent 6 }}
119
+ env:
120
+ {{- include "workflow-postgres.baseEnv" . | nindent 6 }}
121
+ {{- with .Values.envFrom }}
122
+ envFrom: {{- toYaml . | nindent 6 }}
123
+ {{- end }}
124
+ {{- end }}
125
+ {{- end -}}
@@ -0,0 +1,40 @@
1
+ # The main Deployment: serves the application, the probes and the backlog
2
+ # endpoints, and runs this release's workflows.
3
+ apiVersion: apps/v1
4
+ kind: Deployment
5
+ metadata:
6
+ name: {{ include "workflow-postgres.name" . }}
7
+ labels:
8
+ app.kubernetes.io/name: {{ include "workflow-postgres.name" . }}
9
+ app.kubernetes.io/component: service
10
+ app.kubernetes.io/version: {{ include "workflow-postgres.tag" . | quote }}
11
+ spec:
12
+ replicas: {{ .Values.replicas }}
13
+ selector:
14
+ matchLabels:
15
+ app.kubernetes.io/name: {{ include "workflow-postgres.name" . }}
16
+ app.kubernetes.io/component: service
17
+ template:
18
+ metadata:
19
+ labels:
20
+ app.kubernetes.io/name: {{ include "workflow-postgres.name" . }}
21
+ app.kubernetes.io/component: service
22
+ # Read by pruning: the versions of live pods can still start runs.
23
+ app.kubernetes.io/version: {{ include "workflow-postgres.tag" . | quote }}
24
+ spec:
25
+ serviceAccountName: {{ include "workflow-postgres.serviceAccountName" . }}
26
+ terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
27
+ {{- with .Values.nodeSelector }}
28
+ nodeSelector: {{- toYaml . | nindent 8 }}
29
+ {{- end }}
30
+ {{- with .Values.tolerations }}
31
+ tolerations: {{- toYaml . | nindent 8 }}
32
+ {{- end }}
33
+ {{- include "workflow-postgres.initContainers" . | nindent 6 }}
34
+ containers:
35
+ - name: {{ include "workflow-postgres.name" . }}
36
+ {{- include "workflow-postgres.container" . | nindent 10 }}
37
+ env:
38
+ - name: WORKFLOW_ROLE
39
+ value: service
40
+ {{- include "workflow-postgres.baseEnv" . | nindent 12 }}
@@ -0,0 +1,85 @@
1
+ {{- if .Values.versionPinning.enabled }}
2
+ {{- /* CronJob names are capped at 52 characters (Jobs get an 11-character suffix). */}}
3
+ {{- $name := printf "%s-workflow-prune" (include "workflow-postgres.name" . | trunc 37 | trimSuffix "-") }}
4
+ apiVersion: v1
5
+ kind: ServiceAccount
6
+ metadata:
7
+ name: {{ $name }}
8
+ ---
9
+ # Only what pruning does: read the main Deployment and its ReplicaSets, and
10
+ # list, create and delete version workers and their ScaledObjects. Kubernetes
11
+ # RBAC cannot scope by label, so this covers every Deployment in the
12
+ # namespace; install the chart in a namespace of its own.
13
+ apiVersion: rbac.authorization.k8s.io/v1
14
+ kind: Role
15
+ metadata:
16
+ name: {{ $name }}
17
+ rules:
18
+ - apiGroups: ["apps"]
19
+ resources: ["deployments"]
20
+ verbs: ["get", "list", "create", "delete"]
21
+ - apiGroups: ["apps"]
22
+ resources: ["replicasets"]
23
+ verbs: ["list"]
24
+ - apiGroups: ["keda.sh"]
25
+ resources: ["scaledobjects"]
26
+ verbs: ["get", "list", "create", "delete"]
27
+ ---
28
+ apiVersion: rbac.authorization.k8s.io/v1
29
+ kind: RoleBinding
30
+ metadata:
31
+ name: {{ $name }}
32
+ roleRef:
33
+ apiGroup: rbac.authorization.k8s.io
34
+ kind: Role
35
+ name: {{ $name }}
36
+ subjects:
37
+ - kind: ServiceAccount
38
+ name: {{ $name }}
39
+ namespace: {{ .Release.Namespace }}
40
+ ---
41
+ apiVersion: batch/v1
42
+ kind: CronJob
43
+ metadata:
44
+ name: {{ $name }}
45
+ spec:
46
+ schedule: {{ .Values.versionPinning.prune.schedule | quote }}
47
+ concurrencyPolicy: Forbid
48
+ jobTemplate:
49
+ spec:
50
+ backoffLimit: 0
51
+ template:
52
+ spec:
53
+ restartPolicy: Never
54
+ # Its own account for the Kubernetes API; it reads backlogs from the
55
+ # service over HTTP, so it has no database access.
56
+ serviceAccountName: {{ $name }}
57
+ {{- with .Values.nodeSelector }}
58
+ nodeSelector: {{- toYaml . | nindent 12 }}
59
+ {{- end }}
60
+ {{- with .Values.tolerations }}
61
+ tolerations: {{- toYaml . | nindent 12 }}
62
+ {{- end }}
63
+ containers:
64
+ - name: prune
65
+ image: {{ include "workflow-postgres.image" . }}
66
+ imagePullPolicy: {{ .Values.image.pullPolicy }}
67
+ {{- with .Values.versionPinning.prune.command }}
68
+ command: {{- toYaml . | nindent 16 }}
69
+ {{- end }}
70
+ # `pruneWorkersInCluster()` reads these. No database settings:
71
+ # it reads backlogs from the service.
72
+ env:
73
+ - name: WORKFLOW_ROLE
74
+ value: prune
75
+ - name: WORKFLOW_PRUNE_SERVICE
76
+ value: {{ include "workflow-postgres.name" . | quote }}
77
+ - name: WORKFLOW_PRUNE_MAIN_DEPLOYMENT
78
+ value: {{ include "workflow-postgres.name" . | quote }}
79
+ - name: WORKFLOW_PRUNE_BACKLOG_URL
80
+ value: "http://{{ include "workflow-postgres.name" . }}.{{ .Release.Namespace }}.svc.cluster.local{{ .Values.backlogPath }}"
81
+ - name: WORKFLOW_PRUNE_MIN_AGE_MINUTES
82
+ value: {{ .Values.versionPinning.prune.minAgeMinutes | quote }}
83
+ - name: WORKFLOW_PRUNE_DRY_RUN
84
+ value: {{ ternary "1" "0" .Values.versionPinning.prune.dryRun | quote }}
85
+ {{- end }}
@@ -0,0 +1,14 @@
1
+ apiVersion: v1
2
+ kind: Service
3
+ metadata:
4
+ name: {{ include "workflow-postgres.name" . }}
5
+ labels:
6
+ app.kubernetes.io/name: {{ include "workflow-postgres.name" . }}
7
+ spec:
8
+ selector:
9
+ app.kubernetes.io/name: {{ include "workflow-postgres.name" . }}
10
+ app.kubernetes.io/component: service
11
+ ports:
12
+ - name: http
13
+ port: 80
14
+ targetPort: http
@@ -0,0 +1,9 @@
1
+ {{- if .Values.serviceAccount.create }}
2
+ apiVersion: v1
3
+ kind: ServiceAccount
4
+ metadata:
5
+ name: {{ include "workflow-postgres.serviceAccountName" . }}
6
+ {{- with .Values.serviceAccount.annotations }}
7
+ annotations: {{- toYaml . | nindent 4 }}
8
+ {{- end }}
9
+ {{- end }}
@@ -0,0 +1,42 @@
1
+ {{- if .Values.unpinnedWorker.enabled }}
2
+ {{- $name := printf "%s-wf-unpinned" (include "workflow-postgres.name" . | trunc 51 | trimSuffix "-") }}
3
+ # Runs the runs no version claims: those started without a deployment ID. Its
4
+ # role label keeps it out of pruning, which reports such runs while this
5
+ # Deployment doesn't exist.
6
+ apiVersion: apps/v1
7
+ kind: Deployment
8
+ metadata:
9
+ name: {{ $name }}
10
+ labels:
11
+ workflow.vercel.com/service: {{ include "workflow-postgres.name" . }}
12
+ workflow.vercel.com/role: unpinned-worker
13
+ spec:
14
+ replicas: {{ .Values.unpinnedWorker.replicas }}
15
+ selector:
16
+ matchLabels:
17
+ app.kubernetes.io/name: {{ $name }}
18
+ template:
19
+ metadata:
20
+ labels:
21
+ app.kubernetes.io/name: {{ $name }}
22
+ app.kubernetes.io/component: unpinned-worker
23
+ workflow.vercel.com/service: {{ include "workflow-postgres.name" . }}
24
+ workflow.vercel.com/role: unpinned-worker
25
+ spec:
26
+ serviceAccountName: {{ include "workflow-postgres.serviceAccountName" . }}
27
+ terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
28
+ {{- with .Values.nodeSelector }}
29
+ nodeSelector: {{- toYaml . | nindent 8 }}
30
+ {{- end }}
31
+ {{- with .Values.tolerations }}
32
+ tolerations: {{- toYaml . | nindent 8 }}
33
+ {{- end }}
34
+ {{- include "workflow-postgres.initContainers" . | nindent 6 }}
35
+ containers:
36
+ - name: worker
37
+ {{- include "workflow-postgres.container" . | nindent 10 }}
38
+ env:
39
+ - name: WORKFLOW_ROLE
40
+ value: worker
41
+ {{- include "workflow-postgres.unpinnedEnv" . | nindent 12 }}
42
+ {{- end }}