@yieldkit/jobs 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +307 -2
- package/dist/_virtual/_rolldown/runtime.js +12 -0
- package/dist/activity.d.ts +81 -0
- package/dist/activity.js +151 -0
- package/dist/calendar.d.ts +33 -0
- package/dist/calendar.js +205 -0
- package/dist/cluster.d.ts +54 -0
- package/dist/cluster.js +115 -0
- package/dist/cron.d.ts +21 -0
- package/dist/cron.js +80 -0
- package/dist/dispatch.d.ts +97 -0
- package/dist/dispatch.js +140 -0
- package/dist/errors.d.ts +194 -0
- package/dist/errors.js +132 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +22 -0
- package/dist/job.d.ts +306 -0
- package/dist/job.js +45 -0
- package/dist/ledger-memory.d.ts +64 -0
- package/dist/ledger-memory.js +246 -0
- package/dist/ledger-retry.js +21 -0
- package/dist/ledger-sql-deadline.js +39 -0
- package/dist/ledger-sql.d.ts +5 -0
- package/dist/ledger-sql.js +332 -0
- package/dist/ledger-types.d.ts +340 -0
- package/dist/ledger-types.js +71 -0
- package/dist/ledger.d.ts +51 -0
- package/dist/ledger.js +66 -0
- package/dist/logging.d.ts +83 -0
- package/dist/logging.js +117 -0
- package/dist/maintenance.d.ts +6 -0
- package/dist/maintenance.js +115 -0
- package/dist/metrics.d.ts +14 -0
- package/dist/metrics.js +35 -0
- package/dist/migrations.d.ts +21 -0
- package/dist/migrations.js +194 -0
- package/dist/omit-undefined.js +10 -0
- package/dist/params.d.ts +58 -0
- package/dist/params.js +97 -0
- package/dist/policy.d.ts +225 -0
- package/dist/policy.js +247 -0
- package/dist/probe.js +67 -0
- package/dist/requests-memory.d.ts +36 -0
- package/dist/requests-memory.js +142 -0
- package/dist/requests.d.ts +195 -0
- package/dist/requests.js +242 -0
- package/dist/run-key.d.ts +25 -0
- package/dist/run-key.js +85 -0
- package/dist/run-support.js +212 -0
- package/dist/run.d.ts +163 -0
- package/dist/run.js +258 -0
- package/dist/scheduler.d.ts +56 -0
- package/dist/scheduler.js +227 -0
- package/dist/settle-hook.d.ts +3 -0
- package/dist/settle-hook.js +33 -0
- package/dist/storage-options.d.ts +25 -0
- package/dist/storage-options.js +60 -0
- package/dist/storage.d.ts +53 -0
- package/dist/storage.js +75 -0
- package/dist/testing/index.d.ts +4 -0
- package/dist/testing/index.js +4 -0
- package/dist/time-zone.js +83 -0
- package/dist/workflow-activities.js +227 -0
- package/dist/workflow-retry.js +80 -0
- package/dist/workflow-schema.d.ts +207 -0
- package/dist/workflow-schema.js +360 -0
- package/dist/workflow-settle.js +234 -0
- package/dist/workflow.d.ts +17 -0
- package/dist/workflow.js +202 -0
- package/docs/deployment.md +167 -0
- package/docs/jobs.md +200 -0
- package/docs/logs-and-metrics.md +129 -0
- package/docs/migrations.md +66 -0
- package/docs/policy.md +75 -0
- package/docs/scheduling.md +149 -0
- package/docs/storage.md +138 -0
- package/docs/testing.md +144 -0
- package/docs/workers-and-clients.md +100 -0
- package/package.json +82 -3
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# Logs and metrics
|
|
2
|
+
|
|
3
|
+
Logs go through `@yieldkit/logger` and share its formatting and redaction. With its `LoggerLive` (add `@yieldkit/logger` to your own dependencies to import it), every run logs a line when it ends:
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { defineJob, runJob } from '@yieldkit/jobs';
|
|
7
|
+
import { makeJobRunsMemory } from '@yieldkit/jobs/testing';
|
|
8
|
+
import { LoggerLive } from '@yieldkit/logger';
|
|
9
|
+
import { Effect, Schema } from 'effect';
|
|
10
|
+
|
|
11
|
+
const greet = defineJob({
|
|
12
|
+
name: 'greet',
|
|
13
|
+
description: 'Says hello once',
|
|
14
|
+
cadence: { _tag: 'Once', start: 'manual' },
|
|
15
|
+
params: { schema: Schema.Struct({ name: Schema.String }), defaults: { name: 'world' } },
|
|
16
|
+
stats: Schema.Struct({ greeted: Schema.String }),
|
|
17
|
+
logFields: { tenant: 'acme' },
|
|
18
|
+
run: ({ params }) => Effect.succeed({ greeted: params.name }),
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const logged = Effect.gen(function* () {
|
|
22
|
+
const ledger = yield* makeJobRunsMemory();
|
|
23
|
+
return yield* runJob(greet, { trigger: 'manual' }).pipe(Effect.provide(ledger.layer));
|
|
24
|
+
}).pipe(Effect.provide(LoggerLive({ service: 'worker', format: 'json' })));
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The `job.completed` line, without `timestamp`, `traceId` and the other standard fields:
|
|
28
|
+
|
|
29
|
+
```json
|
|
30
|
+
{
|
|
31
|
+
"level": "INFO",
|
|
32
|
+
"message": "job.completed",
|
|
33
|
+
"annotations": {
|
|
34
|
+
"tenant": "acme",
|
|
35
|
+
"runKey": "once",
|
|
36
|
+
"job": "greet",
|
|
37
|
+
"jobRunId": "greet:once:1",
|
|
38
|
+
"trigger": "manual",
|
|
39
|
+
"attempt": 1,
|
|
40
|
+
"greeted": "world",
|
|
41
|
+
"status": "completed",
|
|
42
|
+
"durationMs": 0
|
|
43
|
+
},
|
|
44
|
+
"spans": { "job.run": 0 }
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Every line of a run carries `job`, `jobRunId` (`<job>:<runKey>:<attempt>`), `runKey`, `trigger`, `attempt`, the job's `logFields` and, in a workflow, `executionId`. Runs are traced as `job.<name>`, stages as `job.stage.<stage>`.
|
|
49
|
+
|
|
50
|
+
## Events
|
|
51
|
+
|
|
52
|
+
| Event | Level | When |
|
|
53
|
+
| ----------------------------------------------------------------------------------------------------------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
54
|
+
| `job.started` | Debug | A claimed run starts |
|
|
55
|
+
| `job.completed` | Info | It completed; the encoded stats are added as fields, with `durationMs` |
|
|
56
|
+
| `job.skipped` | Info | The claim was refused; `skipReason`, `retryAt` |
|
|
57
|
+
| `job.failed` | Error | It failed or died; `errorTag`, `errorMessage`, `stage`, `isDefect` |
|
|
58
|
+
| `job.interrupted` | Warn | It was interrupted |
|
|
59
|
+
| `job.claim.failed` | Warn | A claim failed after retries; the round reports `RetryLater` in `busyDelay` |
|
|
60
|
+
| `job.heartbeat.failed` | Warn | A SQL heartbeat failed or timed out; the run ends after a full lease of them. Also logged, with `errorMessage`, when a replayed claim cannot reach the ledger; that round ends without running the body |
|
|
61
|
+
| `job.settle.lost` | Warn | A settle did not write the row: another run holds the key, or the write still failed after retries (then with `errorMessage`). The outcome is `RunClaimLost`. Also logged when the settle of an interrupted or crash-capped workflow run fails |
|
|
62
|
+
| `job.settle_hook_failed` | Warn | The `onSettle` hook failed; the settle still committed |
|
|
63
|
+
| `worker.supervisor.starting`, `.running`, `.stopped`, `.job_filtered` | Info | Scheduler lifecycle; `starting` lists each job's cadence and `logFields` |
|
|
64
|
+
| `worker.scheduler.dispatch_failed` | Warn | A cron or start-up dispatch failed; start-up dispatches retry each minute, `Every` and `Cron` ticks every 30 s |
|
|
65
|
+
| `worker.scheduler.dispatch_abandoned` | Warn | An `Every` or `Cron` tick whose dispatch kept failing until its catch-up window or next tick |
|
|
66
|
+
| `worker.supervisor.pruned`, `worker.maintenance.cluster_pruned`, `worker.maintenance.requests_pruned` | Info | Rows deleted by a maintenance sweep |
|
|
67
|
+
| `worker.supervisor.prune_failed`, `worker.maintenance.cluster_prune_failed`, `worker.maintenance.requests_prune_failed` | Warn | A sweep's delete failed; the next sweep tries again |
|
|
68
|
+
| `worker.request.finish_failed` | Warn | A request row could not be marked finished |
|
|
69
|
+
| `worker.request.start_failed` | Warn | A request row could not be marked started; the run still goes ahead |
|
|
70
|
+
| `job.dispatch.record_failed` | Warn | `dispatchApiJobWorkflow` could not mark its request row as failed after the dispatch failed; the dispatch error still reaches the caller |
|
|
71
|
+
| `jobs.migrate.completed` | Info | `JobStorage.layerMigrations` finished; `applied` is the step count |
|
|
72
|
+
|
|
73
|
+
`withJobLogging`, `withJobContext` and `withJobStage` give your own code the same lines and spans:
|
|
74
|
+
|
|
75
|
+
<!-- prettier-ignore -->
|
|
76
|
+
```ts
|
|
77
|
+
import { withJobLogging, withJobStage } from '@yieldkit/jobs';
|
|
78
|
+
import { Effect } from 'effect';
|
|
79
|
+
|
|
80
|
+
export const backfill = Effect.succeed({ rows: 120 }).pipe(
|
|
81
|
+
withJobStage('copy'), // stage annotation, log and trace span
|
|
82
|
+
withJobLogging({ job: 'backfill', trigger: 'manual' }), // job.started, then job.completed or job.failed
|
|
83
|
+
);
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Metrics
|
|
87
|
+
|
|
88
|
+
| Metric | Type | Attributes |
|
|
89
|
+
| ---------------------- | --------- | ------------------------------------------------------------- |
|
|
90
|
+
| `job_runs_total` | Counter | `job`, `status` (`completed`, `skipped`, `failed`), `trigger` |
|
|
91
|
+
| `job_duration_ms` | Histogram | `job` |
|
|
92
|
+
| `job_lease_lost_total` | Counter | `job` |
|
|
93
|
+
|
|
94
|
+
Scope them per service with your exporter's resource attributes.
|
|
95
|
+
|
|
96
|
+
## Errors
|
|
97
|
+
|
|
98
|
+
| Error | Raised by |
|
|
99
|
+
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
100
|
+
| `InvalidJobParams` | Params that fail the job's schema, or a malformed `parseSetFlags` flag |
|
|
101
|
+
| `InvalidRunKey` | A missing or malformed `OnDemand` run key, or a run key given for a job of another cadence |
|
|
102
|
+
| `InvalidDispatch` | `dispatchJob` with a negative, non-finite or unparseable `delay`, or an invalid `runAt` |
|
|
103
|
+
| `DryRunUnsupported` | `runJob` with `dryRun: true` for a job without a `dryRun` layer |
|
|
104
|
+
| `UnknownJobError` | The scheduler's `only` naming a job that is not in its list |
|
|
105
|
+
| `ClusterConfigError` | A bad cadence (interval, time, time zone, window or cron expression) or policy value, or a `ShardingConfig` missing or misassigning a jobs group |
|
|
106
|
+
| `JobsNotMigratedError` | Runtime layers started against missing or older tables; `component`, `table`, `found`, `expected` |
|
|
107
|
+
| `JobStageError` | A failed durable stage, stored in Cluster's replies with a redacted message |
|
|
108
|
+
| `RunClaimLost` | A run whose heartbeat found another owner; it ends as a `failed` outcome |
|
|
109
|
+
| `MigrationError`, `PgConfigError` | `JobStorage.layerMigrations` and invalid storage options (from `@yieldkit/pg`) |
|
|
110
|
+
|
|
111
|
+
They are tagged errors, so `Effect.catchTag` picks one out:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import { JobRuns, JobStorage } from '@yieldkit/jobs';
|
|
115
|
+
import { makePgLive } from '@yieldkit/pg';
|
|
116
|
+
import { Effect, Layer } from 'effect';
|
|
117
|
+
|
|
118
|
+
export const latest = Effect.gen(function* () {
|
|
119
|
+
const runs = yield* JobRuns;
|
|
120
|
+
return yield* runs.recent({ limit: 10 });
|
|
121
|
+
}).pipe(
|
|
122
|
+
Effect.provide(JobStorage.layerStorage().pipe(Layer.provide(makePgLive()))),
|
|
123
|
+
Effect.catchTag('JobsNotMigratedError', (error) =>
|
|
124
|
+
Effect.die(
|
|
125
|
+
`run JobStorage.layerMigrations first: ${error.table} is at ${String(error.found)}, needs ${String(error.expected)}`,
|
|
126
|
+
),
|
|
127
|
+
),
|
|
128
|
+
);
|
|
129
|
+
```
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# Migrations
|
|
2
|
+
|
|
3
|
+
The library migrates its own tables only: the run ledger `<prefix>_runs`, the request table `<prefix>_requests` and their history `<prefix>_migrations`. Your Cluster's tables are yours to migrate, with Effect's own loaders. The runtime layers create nothing.
|
|
4
|
+
|
|
5
|
+
`JobStorage.migrations` and `JobStorage.layerMigrations` mirror `SqlMessageStorage.migrations` and `.layerMigrations`; the runtime layers are in [Storage](storage.md#layers). Options are `{ prefix?, schema? }` ([table options](storage.md#table-options)).
|
|
6
|
+
|
|
7
|
+
## The deploy step
|
|
8
|
+
|
|
9
|
+
Run your Cluster's migrations and the library's on an owner connection, once per release, before workers and clients start:
|
|
10
|
+
|
|
11
|
+
<!-- prettier-ignore -->
|
|
12
|
+
```ts
|
|
13
|
+
import { JobStorage } from '@yieldkit/jobs';
|
|
14
|
+
import { makePgLive } from '@yieldkit/pg';
|
|
15
|
+
import { Layer } from 'effect';
|
|
16
|
+
import { SqlMessageStorage, SqlRunnerStorage } from 'effect/cluster';
|
|
17
|
+
|
|
18
|
+
const OwnerPg = makePgLive({ applicationName: 'deploy', searchPath: 'app' });
|
|
19
|
+
|
|
20
|
+
export const DeployLive = Layer.mergeAll(
|
|
21
|
+
SqlMessageStorage.layerMigrations({ prefix: 'app_cluster' }), // your Cluster, your prefix
|
|
22
|
+
SqlRunnerStorage.layerMigrations({ prefix: 'app_cluster' }),
|
|
23
|
+
JobStorage.layerMigrations(), // job_runs, job_requests, job_migrations
|
|
24
|
+
).pipe(Layer.provide(OwnerPg));
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`JobStorage.layerMigrations` fails with `MigrationError` (from `@yieldkit/pg`), or `PgConfigError` for invalid options, rather than dying as Effect's does. It logs `jobs.migrate.completed` with the number of applied steps.
|
|
28
|
+
|
|
29
|
+
## How a run works
|
|
30
|
+
|
|
31
|
+
1. Check that the target schema exists (`schema`, or the first existing schema of `search_path`) and that the role may create tables in it, so a missing schema or grant reads as such. Schemas are never created.
|
|
32
|
+
2. Refuse to share a history: if `<prefix>_migrations` has rows but `<prefix>_runs` does not exist, fail without creating anything. Effect's message storage uses the same history table and step names, so a prefix shared with your Cluster would skip steps. The prefix `cluster` is refused outright.
|
|
33
|
+
3. Run Effect's `Migrator` with the library's loader. It creates the history table when missing, locks it (`ACCESS EXCLUSIVE`), and applies the pending steps in one transaction, so concurrent deploys apply each step once. A failed step records nothing, though the empty history table stays.
|
|
34
|
+
|
|
35
|
+
`JobStorage.layerStorage` checks at start-up that the history is current and that `<prefix>_runs` and `<prefix>_requests` exist, and fails with `JobsNotMigratedError` otherwise.
|
|
36
|
+
|
|
37
|
+
## Grants
|
|
38
|
+
|
|
39
|
+
| Role | Needs |
|
|
40
|
+
| ------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
|
41
|
+
| Migration | `USAGE` and `CREATE` on the schema; ownership of existing tables |
|
|
42
|
+
| Workers and clients | `USAGE` on the schema; `SELECT` on `<prefix>_migrations`; `SELECT, INSERT, UPDATE, DELETE` on the ledger and request tables |
|
|
43
|
+
|
|
44
|
+
Your Cluster's grants are yours; Effect's storage needs DML on its tables. The package does not create roles or grant anything.
|
|
45
|
+
|
|
46
|
+
## Adopting existing tables
|
|
47
|
+
|
|
48
|
+
`layerMigrations` adopts tables your own migrations created. Step 0001 uses `CREATE TABLE IF NOT EXISTS` and `ADD COLUMN IF NOT EXISTS`, so existing tables, rows, extra columns and indexes stay, and the step is recorded.
|
|
49
|
+
|
|
50
|
+
The ledger may have a `<prefix>_runs_trigger_check` constraint, PostgreSQL's name for an inline `CHECK` on `trigger`. If it does not allow `'schedule'`, `'manual'` and `'api'`, the migration fails with a message pointing here and records nothing. Otherwise the first manual run would hit a constraint violation. Rewrite the constraint in your own migration first, for example for a table that used `'cli'`:
|
|
51
|
+
|
|
52
|
+
```sql
|
|
53
|
+
ALTER TABLE job_runs DROP CONSTRAINT IF EXISTS job_runs_trigger_check;
|
|
54
|
+
UPDATE job_runs SET trigger = 'manual' WHERE trigger = 'cli';
|
|
55
|
+
ALTER TABLE job_runs ADD CONSTRAINT job_runs_trigger_check
|
|
56
|
+
CHECK (trigger IN ('schedule', 'manual', 'api'));
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Code that still writes the old value fails afterwards, so ship this migration with the code that adopts the library.
|
|
60
|
+
|
|
61
|
+
## Limits
|
|
62
|
+
|
|
63
|
+
- Lock and statement timeouts are your pool's: configure `lockTimeout` and `statementTimeout` on the deploy pool if you want the DDL to give up rather than wait.
|
|
64
|
+
- To adopt existing tables, the migration role must own them or be a member of the owning role, since step 0001 alters them.
|
|
65
|
+
- From PostgreSQL 15, only the database owner may create tables in `public` by default. Use a schema the migration role owns, or grant it `CREATE`.
|
|
66
|
+
- A future step that rewrites a large table should be its own deploy step.
|
package/docs/policy.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Policy
|
|
2
|
+
|
|
3
|
+
Every timing and limit lives in one `JobsPolicy`, given to the storage layer. Workflows, the scheduler and `runJob` read it from `JobRuns.policy`, so the ledger's retry arithmetic and the durable sleeps agree.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { JobStorage } from '@yieldkit/jobs';
|
|
7
|
+
|
|
8
|
+
const StorageLive = JobStorage.layerStorage({
|
|
9
|
+
policy: { retry: { maxCrashAttempts: 5 }, retention: { requests: '7 days' } },
|
|
10
|
+
});
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Overrides merge group by group over `defaultJobsPolicy`. Durations take any `Duration.Input` above zero and at most 3650 days; counts are integers of at least 1. Anything else fails the layer with `ClusterConfigError` naming the field. `makeJobRunsMemory({ policy })` takes the same overrides.
|
|
14
|
+
|
|
15
|
+
| Field | Default | Meaning |
|
|
16
|
+
| --------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
|
|
17
|
+
| `lease.duration` | 2 minutes | Lease written on claim and heartbeat; an expired lease may be taken over |
|
|
18
|
+
| `lease.heartbeatsPerLease` | 4 | Heartbeat every `duration / heartbeatsPerLease` (30 seconds); at least 2 |
|
|
19
|
+
| `retry.dailyMaxFailures` | 6 | Failures of one `Daily` key after which scheduled runs stop (`Exhausted`); not used when the cadence has `at`, `window` or `until` |
|
|
20
|
+
| `retry.onceBase` | 1 hour | First backoff of an automatic `Once` job, doubled per failure |
|
|
21
|
+
| `retry.onceCap` | 24 hours | Longest `Once` backoff |
|
|
22
|
+
| `retry.onDemandBase` | 1 minute | First backoff of a dispatched `OnDemand` run, doubled per failure |
|
|
23
|
+
| `retry.onDemandCap` | 1 hour | Longest `OnDemand` backoff |
|
|
24
|
+
| `retry.onDemandMaxFailures` | 5 | Failures of one `OnDemand` key after which its workflow gives up (`Exhausted`) |
|
|
25
|
+
| `retry.busyDelay` | 1 minute | Durable wait of a scheduled `Daily`, `Once` or `OnDemand` workflow that found its key `Busy` |
|
|
26
|
+
| `retry.busyMaxRetries` | 15 | `Busy` waits of a `Daily` or `OnDemand` workflow before it settles as skipped (`Once` waits forever) |
|
|
27
|
+
| `retry.maxCrashAttempts` | 3 | Claims of the key by one execution, the first included, before it fails with `MaxAttemptsExceeded` |
|
|
28
|
+
| `retention.everyRuns` | 14 days | Ledger rows of `Every` and `Cron` jobs; `Daily` and `Once` rows are kept |
|
|
29
|
+
| `retention.everyCluster` | 14 days | Processed Cluster messages of `Every` and `Cron` workflows, their crons and durable clocks (`retention.onDemand` if shorter) |
|
|
30
|
+
| `retention.dailyCluster` | 30 days | Processed Cluster messages of `Daily` workflows and crons; `Once` workflows are kept |
|
|
31
|
+
| `retention.onDemand` | 30 days | Ledger rows and processed Cluster messages of `OnDemand` jobs; a key deduplicates this long |
|
|
32
|
+
| `retention.requests` | 30 days | Finished request rows; unfinished rows are kept |
|
|
33
|
+
| `maintenance.interval` | 1 day | Time between maintenance sweeps; the first runs when the maintenance singleton starts |
|
|
34
|
+
| `maintenance.batchSize` | 1000 | Rows per delete statement when pruning ledger rows, Cluster messages and requests |
|
|
35
|
+
|
|
36
|
+
## Retry rules
|
|
37
|
+
|
|
38
|
+
A failed run sets the ledger's `failures` (interruptions and lost leases don't count) and `next_attempt_at`:
|
|
39
|
+
|
|
40
|
+
- Interrupted or lost lease: now, without using up the budget. An exhausted `Daily` or `OnDemand` key stays exhausted.
|
|
41
|
+
- `Daily`: now while `failures < dailyMaxFailures`, then never (`Exhausted`) until a `manual` or `api` run takes the key. A scheduled workflow sleeps `checkEvery` between attempts.
|
|
42
|
+
- `Daily` with `at`, `window` or `until`: retried every `checkEvery` while the retry would start on the run's date at or before `until`, then exhausted. `dailyMaxFailures` does not apply.
|
|
43
|
+
- `Every` and `Cron`: now; the next bucket or tick has a new key anyway. Scheduled runs are not retried.
|
|
44
|
+
- `Once`: `min(onceBase * 2^(failures - 1), onceCap)` from now. It never exhausts.
|
|
45
|
+
- `OnDemand`: `min(onDemandBase * 2^(failures - 1), onDemandCap)` from now while `failures < onDemandMaxFailures`, then never (`Exhausted`). `failures` is the key's count, `manual` failures included. The dispatched workflow sleeps until that instant between attempts.
|
|
46
|
+
|
|
47
|
+
`manual` and `api` runs ignore `next_attempt_at`. `nextAttemptAt`, `onceRetryDelay` and `heartbeatIntervalFor` expose the arithmetic:
|
|
48
|
+
|
|
49
|
+
<!-- prettier-ignore -->
|
|
50
|
+
```ts
|
|
51
|
+
import { defaultJobsPolicy, heartbeatIntervalFor, nextAttemptAt, onceRetryDelay } from '@yieldkit/jobs';
|
|
52
|
+
|
|
53
|
+
const now = new Date('2026-11-25T00:00:00Z');
|
|
54
|
+
const { retry, lease } = defaultJobsPolicy;
|
|
55
|
+
|
|
56
|
+
nextAttemptAt(retry, { cadence: 'Once', failures: 3, interrupted: false, now }); // 2026-11-25T04:00:00.000Z
|
|
57
|
+
nextAttemptAt(retry, { cadence: 'Daily', failures: 6, interrupted: false, now }); // null: exhausted
|
|
58
|
+
nextAttemptAt(retry, { cadence: 'OnDemand', failures: 2, interrupted: false, now }); // 2026-11-25T00:02:00.000Z
|
|
59
|
+
onceRetryDelay(retry, 10); // 1 day (onceCap)
|
|
60
|
+
heartbeatIntervalFor(lease); // 30 seconds
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Maintenance
|
|
64
|
+
|
|
65
|
+
One maintenance singleton applies the `retention.*` and `maintenance.*` rows above, and [logs](logs-and-metrics.md) what each sweep deleted. It runs in the library's own shard group, `yieldkit-jobs`, so only workers that run `makeSchedulerLayer` claim it.
|
|
66
|
+
|
|
67
|
+
Durable clocks are not per job: `ClusterWorkflowEngine` keeps every workflow's clock wake-ups under one entity type, `Workflow/-/DurableClock`. On a Cluster that also runs your own workflows, the sweep deletes their processed clock messages after the shorter of `retention.everyCluster` and `retention.onDemand` too. Keep that retention longer than any workflow of yours that sleeps.
|
|
68
|
+
|
|
69
|
+
## Limits
|
|
70
|
+
|
|
71
|
+
- The retry rules apply whatever the trigger: a failed `manual` or `api` run of a `Daily` key uses one failure of the budget and leaves the key to its scheduled workflow.
|
|
72
|
+
- The ledger decides exhaustion. Once `manual` or `api` failures use up a key's budget, its scheduled workflow ends `skipped` (`Exhausted`) at its next claim instead of running the body.
|
|
73
|
+
- A settle never moves an exhausted key's `next_attempt_at` off `null`.
|
|
74
|
+
- Pruning deletes by age, whatever the status. Keep `retention.everyRuns` longer than your longest `Every` run.
|
|
75
|
+
- Keep `retention.everyCluster` and `retention.dailyCluster` longer than your longest workflow, retries included, or it loses its stored stage results and runs those stages again.
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
# Scheduling recipes
|
|
2
|
+
|
|
3
|
+
| Schedule | Cadence | Section |
|
|
4
|
+
| ----------------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------- |
|
|
5
|
+
| Every 5 minutes | `{ _tag: 'Every', interval: '5 minutes' }` | [Every N minutes](#every-n-minutes) |
|
|
6
|
+
| Once a day, any time | `{ _tag: 'Daily' }` | [Once a day](#once-a-day) |
|
|
7
|
+
| Daily at 9 am, retried until noon | `{ _tag: 'Daily', at: '09:00', until: '12:00' }` | [Daily at a fixed time](#daily-at-a-fixed-time) |
|
|
8
|
+
| Daily at a random time between 8 am and 2 pm | `{ _tag: 'Daily', window: { from: '08:00', to: '14:00' } }` | [Daily in a random window](#daily-in-a-random-window) |
|
|
9
|
+
| Cron expression (`0 9 * * 1-5`) | `{ _tag: 'Cron', expression: '0 9 * * 1-5' }` | [Cron](#cron) |
|
|
10
|
+
| Once ever (a backfill, an import) | `{ _tag: 'Once', start: 'automatic' }` | [Once ever](#once-ever) |
|
|
11
|
+
| One-off per item (send this email, maybe later) | `{ _tag: 'OnDemand' }` and `dispatchJob` | [One-off work per item](#one-off-work-per-item) |
|
|
12
|
+
|
|
13
|
+
`Daily` and `Cron` take a `timeZone` (an IANA name such as `Europe/Brussels`, default `UTC`).
|
|
14
|
+
|
|
15
|
+
## Every N minutes
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { defineJob } from '@yieldkit/jobs';
|
|
19
|
+
import { Effect, Schema } from 'effect';
|
|
20
|
+
|
|
21
|
+
export const syncOrders = defineJob({
|
|
22
|
+
name: 'sync-orders',
|
|
23
|
+
description: 'Copies new orders from the shop',
|
|
24
|
+
cadence: { _tag: 'Every', interval: '5 minutes' },
|
|
25
|
+
params: { schema: Schema.Struct({}), defaults: {} },
|
|
26
|
+
stats: Schema.Struct({ copied: Schema.Int }),
|
|
27
|
+
run: () => Effect.succeed({ copied: 0 }),
|
|
28
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The scheduler runs a UTC cron (`*/5 * * * *`) and the run key is the bucket start, such as `2026-11-26T09:05Z`. The interval must be a whole number of minutes that evenly divides an hour (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30 minutes) or a day (1, 2, 3, 4, 6, 8, 12, 24 hours). A failed run is not retried, and a bucket missed while every worker was down is skipped: the next bucket is a new key.
|
|
32
|
+
|
|
33
|
+
## Once a day
|
|
34
|
+
|
|
35
|
+
<!-- prettier-ignore -->
|
|
36
|
+
```ts
|
|
37
|
+
cadence: { _tag: 'Daily' } // or { _tag: 'Daily', checkEvery: '15 minutes' }
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
The run key is the UTC date (`2026-11-26`). The scheduler checks every `checkEvery` (default 1 hour), and the first check of the day starts the run, so it runs just after midnight UTC. A failed run is retried at each check, up to `retry.dailyMaxFailures` (6) failures. A day missed while the workers were down is caught up by the first check after they start.
|
|
41
|
+
|
|
42
|
+
## Daily at a fixed time
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { defineJob } from '@yieldkit/jobs';
|
|
46
|
+
import { Effect, Schema } from 'effect';
|
|
47
|
+
|
|
48
|
+
export const morningDigest = defineJob({
|
|
49
|
+
name: 'morning-digest',
|
|
50
|
+
description: 'Mails the morning digest',
|
|
51
|
+
cadence: {
|
|
52
|
+
_tag: 'Daily',
|
|
53
|
+
at: '09:00',
|
|
54
|
+
until: '12:00',
|
|
55
|
+
timeZone: 'Europe/Brussels',
|
|
56
|
+
checkEvery: '15 minutes',
|
|
57
|
+
},
|
|
58
|
+
params: { schema: Schema.Struct({}), defaults: {} },
|
|
59
|
+
stats: Schema.Struct({ sent: Schema.Int }),
|
|
60
|
+
run: () => Effect.succeed({ sent: 1 }),
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
- **When it starts.** The run key is the local date in `timeZone`. The scheduler still checks every `checkEvery`, but a check before 09:00 local time does nothing. The first check at or after 09:00 starts the day's run, and later checks deduplicate on the date.
|
|
65
|
+
- **Retries.** A failed run is retried every `checkEvery` (09:15, 09:30, ...) as long as the retry would start at or before `until`. `retry.dailyMaxFailures` does not apply. A failure at 11:50 is the last attempt here, since the next one would start at 12:05; the key is then exhausted, and only a `manual` or `api` run takes it that day.
|
|
66
|
+
- **Catch-up.** If no worker is up at 09:00, the first check after one starts runs the job, as long as that is before `until`. A worker that starts at 12:30 does not run it that day.
|
|
67
|
+
- **`until`.** It defaults to `24:00` (end of the local day). It must leave at least one `checkEvery` after `at`, or no check could start the run.
|
|
68
|
+
- **Daylight saving time.** A time skipped in spring runs at the first check after the gap; a repeated autumn time runs once. An `until` inside the gap moves forward by its length.
|
|
69
|
+
- **Precision.** The run starts at the first check at or after `at`: with the default hourly `checkEvery`, `at: '09:20'` runs at 10:00.
|
|
70
|
+
|
|
71
|
+
## Daily in a random window
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
cadence: {
|
|
75
|
+
_tag: 'Daily',
|
|
76
|
+
window: { from: '08:00', to: '14:00' },
|
|
77
|
+
timeZone: 'Europe/Brussels',
|
|
78
|
+
checkEvery: '5 minutes',
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Each day's run is due at one slot of the window, `from` plus a multiple of `checkEvery`, picked from a hash of the job name and the date, so every worker agrees without sharing state. The first attempt starts before `to`. Retries, catch-up and daylight saving time work as for `at`; `until` defaults to `window.to`. The window must be at least one `checkEvery` long, and renaming the job changes its slots.
|
|
83
|
+
|
|
84
|
+
## Cron
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
cadence: { _tag: 'Cron', expression: '0 9 * * 1-5', timeZone: 'Europe/Brussels' }
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
- **Expression.** Five fields: minute, hour, day of month, month, day of week. A seconds field is rejected, since run keys have minute precision, and so is an expression that never matches a date (`0 0 31 2 *`).
|
|
91
|
+
- **Run key.** The tick in UTC, `YYYY-MM-DDTHH:mmZ`, the same format as `Every`. A `manual` or `api` run uses the latest tick at or before now.
|
|
92
|
+
- **Failures.** Like `Every`: a failed run is not retried, and the next tick is a new key. A failed dispatch is retried every 30 seconds within `catchUpWithin`.
|
|
93
|
+
- **Catch-up.** Cluster keeps one pending message, for the next tick. If the workers were down at that tick, it still runs when one starts, as long as it is at most `catchUpWithin` old (default 1 hour; it must be a finite duration above zero). Later ticks missed during the same outage are skipped, and there is no start-up run.
|
|
94
|
+
- **Daylight saving time.** Ticks follow local time in `timeZone`. A local time repeated by the autumn change runs once, at its first occurrence. A local time skipped by the spring change runs at the same offset after the change (02:30 runs at 03:30). When an expression has several ticks inside the skipped hour (`0,30 2 * * *`), only the first runs that day.
|
|
95
|
+
|
|
96
|
+
Use `Cron` for what `Every` and `Daily` can't express: weekdays only, several fixed times a day, the first of the month.
|
|
97
|
+
|
|
98
|
+
## Once ever
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
cadence: { _tag: 'Once', start: 'automatic' } // scheduler runs it at worker start-up until it completes
|
|
102
|
+
cadence: { _tag: 'Once', start: 'manual' } // only runJob starts it
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
The run key is the constant `'once'`, so the job completes once per job name, for the life of the database. Use it for backfills and imports. It is not a way to send one email: a `Once` job named `send-email` sends one email, ever. For that, use `OnDemand`.
|
|
106
|
+
|
|
107
|
+
## One-off work per item
|
|
108
|
+
|
|
109
|
+
An `OnDemand` job is never scheduled. Your code starts each run with `dispatchJob` under a run key it chooses, one per email, webhook or export:
|
|
110
|
+
|
|
111
|
+
<!-- prettier-ignore -->
|
|
112
|
+
```ts
|
|
113
|
+
import { defineJob, dispatchJob } from '@yieldkit/jobs';
|
|
114
|
+
import { Effect, Schema } from 'effect';
|
|
115
|
+
|
|
116
|
+
export const sendEmail = defineJob({
|
|
117
|
+
name: 'send-email',
|
|
118
|
+
description: 'Sends one email',
|
|
119
|
+
cadence: { _tag: 'OnDemand' },
|
|
120
|
+
params: {
|
|
121
|
+
schema: Schema.Struct({ to: Schema.String, template: Schema.String }),
|
|
122
|
+
defaults: {},
|
|
123
|
+
},
|
|
124
|
+
stats: Schema.Struct({ providerId: Schema.String }),
|
|
125
|
+
run: ({ params, runKey }) =>
|
|
126
|
+
Effect.succeed({ providerId: `${runKey}:${params.template}` }), // call your provider here
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// In your API, after you authenticated the caller. Needs WorkflowEngine (a client-only Cluster).
|
|
130
|
+
export const sendWelcome = (userId: string, to: string) =>
|
|
131
|
+
dispatchJob(sendEmail, {
|
|
132
|
+
runKey: `welcome:${userId}`, // 1 to 200 printable ASCII characters, no spaces
|
|
133
|
+
params: { to, template: 'welcome' },
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
export const sendReminder = (userId: string, to: string) =>
|
|
137
|
+
dispatchJob(sendEmail, {
|
|
138
|
+
runKey: `reminder:${userId}`,
|
|
139
|
+
params: { to, template: 'reminder' },
|
|
140
|
+
delay: '24 hours', // or runAt: a DateTime
|
|
141
|
+
});
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
- **One run per key.** The workflow's execution id is derived from the job name and the run key. Dispatching a key again, with any params, joins the run already started under it, so a retried API request sends one email. `dispatchJob` returns `{ runKey, executionId }` without waiting.
|
|
145
|
+
- **Validation.** Params are decoded before dispatch (`InvalidJobParams`); a bad key or a non-`OnDemand` job fails with `InvalidRunKey`, a bad `delay` or `runAt` with `InvalidDispatch`. `apiParams` does not apply.
|
|
146
|
+
- **Retries.** A failed run is retried after 1, 2, 4 and 8 minutes, then the key is exhausted ([policy](policy.md#retry-rules)). `runJob(sendEmail, { trigger: 'manual', runKey })` runs it again.
|
|
147
|
+
- **Delays.** The workflow waits durably before it claims the key. Keep every delay shorter than `retention.onDemand` (30 days), or the sweep deletes the waiting workflow.
|
|
148
|
+
- **Ledger.** One row per key, `trigger: 'schedule'`, pruned after `retention.onDemand`; after that the key runs again.
|
|
149
|
+
- `dispatchApiJobWorkflow` rejects `OnDemand` jobs; call `dispatchJob` from your API. Pass the run key to your provider as its idempotency key, since a crash can repeat the run.
|
package/docs/storage.md
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# Storage and the settle hook
|
|
2
|
+
|
|
3
|
+
The run ledger (`JobRuns`) and the request store (`JobRequests`) run on your application's `SqlClient`, so a settle hook can write your rows in the settle transaction. It can be the same pool your Cluster's storage uses.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { JobStorage } from '@yieldkit/jobs';
|
|
7
|
+
import { makePgLive } from '@yieldkit/pg';
|
|
8
|
+
import { Layer } from 'effect';
|
|
9
|
+
|
|
10
|
+
export const StorageLive = JobStorage.layerStorage().pipe(
|
|
11
|
+
Layer.provide(makePgLive({ applicationName: 'worker' })),
|
|
12
|
+
);
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Layers
|
|
16
|
+
|
|
17
|
+
| Constructor | Does |
|
|
18
|
+
| ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
|
|
19
|
+
| `JobStorage.layerStorage(options?)` | Provides `JobRuns` and `JobRequests` without DDL; checks the migration history at start-up |
|
|
20
|
+
| `JobStorage.layerWith(options?)` | `layerMigrations` then `layerStorage` on the same client, for tests and single-process tools |
|
|
21
|
+
| `JobStorage.layer` | `layerWith()` with default options |
|
|
22
|
+
| `JobStorage.layerMigrations(options?)` and `JobStorage.migrations(options?)` | See [Migrations](migrations.md) |
|
|
23
|
+
|
|
24
|
+
`layerStorage` fails with:
|
|
25
|
+
|
|
26
|
+
- `JobsNotMigratedError`: `<prefix>_migrations` is missing or behind the code, or the ledger or request table is missing;
|
|
27
|
+
- `ClusterConfigError`: an invalid `policy`;
|
|
28
|
+
- `PgConfigError`: invalid table options or a non-PostgreSQL client.
|
|
29
|
+
|
|
30
|
+
A newer history is accepted, so older workers keep running during a rolling deploy.
|
|
31
|
+
|
|
32
|
+
## Options
|
|
33
|
+
|
|
34
|
+
<!-- prettier-ignore -->
|
|
35
|
+
```ts
|
|
36
|
+
import { JobStorage } from '@yieldkit/jobs';
|
|
37
|
+
import { Effect } from 'effect';
|
|
38
|
+
|
|
39
|
+
const StorageLive = JobStorage.layerStorage({
|
|
40
|
+
prefix: 'job', // job_runs, job_requests, job_migrations
|
|
41
|
+
schema: undefined, // default: the client's search_path, like Cluster's tables
|
|
42
|
+
onSettle: () => Effect.void, // see below
|
|
43
|
+
policy: { lease: { duration: '5 minutes' } }, // see Policy
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Table options
|
|
48
|
+
|
|
49
|
+
`prefix` and `schema` mirror the options of Effect Cluster's SQL storage. Pass the same values to `layerMigrations` and `layerStorage`.
|
|
50
|
+
|
|
51
|
+
- Without `schema`, table names are unqualified and resolve through the client's `search_path`, exactly like Cluster's tables, so one pool with one `search_path` serves both.
|
|
52
|
+
- With `schema`, every statement names it, whatever the `search_path`.
|
|
53
|
+
- If your Cluster's tables share the schema, give them a different prefix: both keep their history in `<prefix>_migrations`. The library refuses `cluster`, Effect's default, and [checks for a shared history](migrations.md#how-a-run-works).
|
|
54
|
+
|
|
55
|
+
Statements ignore the client's name transforms.
|
|
56
|
+
|
|
57
|
+
## The settle hook
|
|
58
|
+
|
|
59
|
+
`onSettle` runs once for every settle that still held its claim, inside the settle transaction:
|
|
60
|
+
|
|
61
|
+
<!-- prettier-ignore -->
|
|
62
|
+
```ts
|
|
63
|
+
import { JobStorage, type JobSettled } from '@yieldkit/jobs';
|
|
64
|
+
import { Context, Effect, Option } from 'effect';
|
|
65
|
+
import { SqlClient } from 'effect/sql';
|
|
66
|
+
|
|
67
|
+
class Tenant extends Context.Service<Tenant, string>()('app/Tenant') {}
|
|
68
|
+
|
|
69
|
+
const recordHealth = (event: JobSettled) =>
|
|
70
|
+
Effect.gen(function* () {
|
|
71
|
+
const tenant = Context.getOption(event.annotations, Tenant);
|
|
72
|
+
if (Option.isNone(tenant) || event.trigger === 'manual') {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const sql = yield* SqlClient.SqlClient;
|
|
77
|
+
const healthy = event.outcome._tag === 'Completed';
|
|
78
|
+
yield* sql`UPDATE tenant SET healthy = ${healthy} WHERE id = ${tenant.value}`;
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
export const StorageLive = JobStorage.layerStorage({ onSettle: recordHealth });
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`JobSettled` carries `job`, `runKey`, `attempt`, `trigger`, the job's `annotations` and an `outcome`: `{ _tag: 'Completed', stats }` or `{ _tag: 'Failed', errorMessage, reason, failures, nextAttemptAt }`, where `reason` is `error`, `interrupted` (also a lost lease) or `crash-cap`.
|
|
85
|
+
|
|
86
|
+
- Writes through the layer's own `SqlClient` commit or roll back with the settle.
|
|
87
|
+
- The hook runs in a savepoint: if it fails, its writes roll back, `job.settle_hook_failed` is logged and the settle still commits.
|
|
88
|
+
- A settle that lost its claim skips the hook; a repeated settle does not call it twice.
|
|
89
|
+
- The hook's services become requirements of the layer.
|
|
90
|
+
|
|
91
|
+
## JobRuns
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { JobRuns } from '@yieldkit/jobs';
|
|
95
|
+
import { Effect } from 'effect';
|
|
96
|
+
|
|
97
|
+
export const latestRuns = Effect.gen(function* () {
|
|
98
|
+
const runs = yield* JobRuns;
|
|
99
|
+
return yield* runs.recent({ job: 'sync-orders', limit: 20 }); // newest first, as JobRunRecord
|
|
100
|
+
});
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
| Member | Does |
|
|
104
|
+
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
105
|
+
| `claim(request)` | Takes `(job, runKey)` and returns `Acquired` with a fence token, or why not: `Busy`, `Completed`, `AlreadySettled`, `RetryLater`, `Exhausted` |
|
|
106
|
+
| `heartbeat(run)` | Extends the lease; `false` when another attempt owns the key |
|
|
107
|
+
| `settle(run, result)` | Fenced update plus the hook; `false` when the claim was lost |
|
|
108
|
+
| `isCompleted(job, runKey)` | Whether the key is completed |
|
|
109
|
+
| `recent({ job?, limit })` | Newest rows first, as `JobRunRecord` |
|
|
110
|
+
| `prune(jobs, olderThan)` | Deletes rows of `jobs` that started before the cutoff, `maintenance.batchSize` rows per statement |
|
|
111
|
+
| `leaseDuration`, `policy` | The lease and the resolved [policy](policy.md) |
|
|
112
|
+
|
|
113
|
+
A claim with the same workflow `executionId` resumes its own `running` row after a crash, with a fresh token. Heartbeats and settles match the token, so a stale process never overwrites a newer owner.
|
|
114
|
+
|
|
115
|
+
## JobRequests
|
|
116
|
+
|
|
117
|
+
Records the requests `dispatchApiJobWorkflow` starts: `create`, `upsertStarted`, `markFinished`, `markDispatchFailed`, `getStatus` and `prune(olderThan, limit)`, which deletes finished rows only.
|
|
118
|
+
|
|
119
|
+
`getStatus(job, requestId)` returns the request row with its ledger row, or `undefined` for an unknown or malformed id. Its `run` is the ledger row of the request's own execution, or `null`:
|
|
120
|
+
|
|
121
|
+
- while the request is pending;
|
|
122
|
+
- when another execution holds the key: the request was skipped as `Busy` or `AlreadyCompleted`, or a later run took the key over.
|
|
123
|
+
|
|
124
|
+
## Tables
|
|
125
|
+
|
|
126
|
+
| Table | Columns |
|
|
127
|
+
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
128
|
+
| `<schema>.<prefix>_runs` | Primary key `(job, run_key)`; `status` (`running`, `completed`, `failed`), `claim_token`, `lease_expires_at`, `attempt`, `failures`, `next_attempt_at`, `trigger` (`schedule`, `manual`, `api`), `params`, `stats`, `error_message`, `started_at`, `finished_at`, `execution_id` |
|
|
129
|
+
| `<schema>.<prefix>_requests` | `id` (UUID), `job`, `params`, `force`, `requested_at`, `picked_at`, `finished_at`, `run_key`, `outcome`, `execution_id` |
|
|
130
|
+
|
|
131
|
+
Query them directly if you like; write only through the services.
|
|
132
|
+
|
|
133
|
+
## Limits
|
|
134
|
+
|
|
135
|
+
- A workflow tries each ledger and request call six times (6.2 s of backoff), then a claim reports `RetryLater` and a settle `RunClaimLost`. With a database down, one call can hold a worker's shutdown for about 36 s; give the jobs pool a `statementTimeout` so a hung server is bounded too.
|
|
136
|
+
- The ledger row, not the request row, is the source of truth when the two disagree.
|
|
137
|
+
- Names must be lowercase identifiers (`^[a-z_][a-z0-9_]*$`). `prefix` is at most 37 characters, so derived index names fit PostgreSQL's 63-byte limit.
|
|
138
|
+
- Without `schema`, the tables follow the `search_path`: point the deploy pool and the runtime pools at the same one.
|