@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
package/dist/workflow.js
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { WorkflowExecutionRound } from "./activity.js";
|
|
2
|
+
import { RunClaimLost } from "./errors.js";
|
|
3
|
+
import { JOB_CONTINUATION } from "./job.js";
|
|
4
|
+
import { JobRuns } from "./ledger.js";
|
|
5
|
+
import { withJobLogging } from "./logging.js";
|
|
6
|
+
import { decodeParams, pickApiParams } from "./params.js";
|
|
7
|
+
import { executeAndEncodeStats, resolveForce, runWithHeartbeat, summarizeEncodedStats } from "./run-support.js";
|
|
8
|
+
import { handleNonAcquiredClaim, registerInterruptFinalizer, runClaimRoundActivity, waitUntilRunAt } from "./workflow-activities.js";
|
|
9
|
+
import { sleepForScheduledRetry } from "./workflow-retry.js";
|
|
10
|
+
import { JobOutcomeSchema, JobWorkflowPayload, MAX_CRASH_ATTEMPTS_TAG, WorkerJobParams, makeJobWorkflow, maxCrashAttemptsMessage } from "./workflow-schema.js";
|
|
11
|
+
import { isReplayedRoundOver, settleCompletedRound, settleCrashCap, settleFailedRound, settleInvalidParams } from "./workflow-settle.js";
|
|
12
|
+
import { dispatchApiJobWorkflow, dispatchJob } from "./dispatch.js";
|
|
13
|
+
import { Cause, Effect, Exit, Layer, Option } from "effect";
|
|
14
|
+
// src/workflow.ts
|
|
15
|
+
/**
|
|
16
|
+
* Resolves effective parameter overrides for a workflow execution, re-enforcing `apiParams` when
|
|
17
|
+
* `trigger === 'api'` so a forged `api` payload cannot set operator-only parameters. A `manual`
|
|
18
|
+
* payload is trusted as it is.
|
|
19
|
+
*/
|
|
20
|
+
const resolveWorkflowParamOverrides = (definition, payload, operatorParams) => {
|
|
21
|
+
const base = operatorParams[definition.name];
|
|
22
|
+
const caller = payload.trigger === "api" ? pickApiParams(definition, payload.params) : payload.params;
|
|
23
|
+
return {
|
|
24
|
+
...base,
|
|
25
|
+
...caller
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Runs a claimed job body with heartbeat fencing and structured job logging.
|
|
30
|
+
*/
|
|
31
|
+
const runTrackedJobBody = (args) => {
|
|
32
|
+
const ctx = {
|
|
33
|
+
params: args.params,
|
|
34
|
+
runKey: args.payload.runKey,
|
|
35
|
+
trigger: args.payload.trigger,
|
|
36
|
+
attempt: args.owned.attempt
|
|
37
|
+
};
|
|
38
|
+
return runWithHeartbeat(args.runs, args.owned, executeAndEncodeStats(args.definition, ctx).pipe(Effect.provideService(WorkflowExecutionRound, { round: args.round }))).pipe(withJobLogging({
|
|
39
|
+
job: args.definition.name,
|
|
40
|
+
jobRunId: `${args.definition.name}:${args.payload.runKey}:${String(args.owned.attempt)}`,
|
|
41
|
+
trigger: args.payload.trigger,
|
|
42
|
+
attempt: args.owned.attempt,
|
|
43
|
+
fields: {
|
|
44
|
+
...args.definition.logFields,
|
|
45
|
+
runKey: args.payload.runKey,
|
|
46
|
+
executionId: args.executionId
|
|
47
|
+
},
|
|
48
|
+
summarizeResult: (output) => summarizeEncodedStats(output.encoded)
|
|
49
|
+
}));
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Settles a round whose body ran (or whose claim was found lost) and returns its terminal outcome,
|
|
53
|
+
* or `undefined` after a durable sleep when the workflow should run the next round. A completion
|
|
54
|
+
* that could not be written counts as a failed round for a scheduled retry.
|
|
55
|
+
*/
|
|
56
|
+
const settleRound = Effect.fnUntraced(function* (args) {
|
|
57
|
+
if (Exit.isSuccess(args.exit)) {
|
|
58
|
+
const completed = yield* settleCompletedRound({
|
|
59
|
+
...args,
|
|
60
|
+
encodedStats: args.exit.value.encoded
|
|
61
|
+
});
|
|
62
|
+
args.state.activeOwned = void 0;
|
|
63
|
+
if (!completed.settled && (yield* sleepForScheduledRetry(args))) return;
|
|
64
|
+
args.state.terminalSettled = true;
|
|
65
|
+
return completed.outcome;
|
|
66
|
+
}
|
|
67
|
+
const failed = yield* settleFailedRound({
|
|
68
|
+
...args,
|
|
69
|
+
cause: args.exit.cause,
|
|
70
|
+
failureCount: args.counters.failureCount
|
|
71
|
+
});
|
|
72
|
+
args.state.activeOwned = void 0;
|
|
73
|
+
args.counters.failureCount = failed.failureCount;
|
|
74
|
+
if (failed.outcome !== void 0) args.state.terminalSettled = true;
|
|
75
|
+
return failed.outcome;
|
|
76
|
+
});
|
|
77
|
+
/**
|
|
78
|
+
* Executes one durable claim-run-settle round of a job workflow, returning either a terminal
|
|
79
|
+
* `WorkflowJobOutcome` or `undefined` when the workflow slept durably and should run the next
|
|
80
|
+
* round.
|
|
81
|
+
*/
|
|
82
|
+
const executeWorkflowRound = Effect.fnUntraced(function* (args) {
|
|
83
|
+
const { claim: claimResult, replayed } = yield* runClaimRoundActivity({
|
|
84
|
+
runs: args.runs,
|
|
85
|
+
definition: args.definition,
|
|
86
|
+
payload: args.payload,
|
|
87
|
+
executionId: args.executionId,
|
|
88
|
+
force: args.force,
|
|
89
|
+
encodedParams: args.encodedParams,
|
|
90
|
+
round: args.round
|
|
91
|
+
});
|
|
92
|
+
if (claimResult._tag !== "Acquired") {
|
|
93
|
+
const skip = yield* handleNonAcquiredClaim({
|
|
94
|
+
job: args.definition.name,
|
|
95
|
+
cadence: args.definition.cadence,
|
|
96
|
+
logFields: args.definition.logFields,
|
|
97
|
+
payload: args.payload,
|
|
98
|
+
claimResult,
|
|
99
|
+
round: args.round,
|
|
100
|
+
busyRetries: args.counters.busyRetries,
|
|
101
|
+
retry: args.runs.policy.retry
|
|
102
|
+
});
|
|
103
|
+
args.counters.busyRetries = skip.busyRetries;
|
|
104
|
+
if (skip.outcome !== void 0) args.state.terminalSettled = true;
|
|
105
|
+
return skip.outcome;
|
|
106
|
+
}
|
|
107
|
+
const owned = {
|
|
108
|
+
job: args.definition.name,
|
|
109
|
+
runKey: args.payload.runKey,
|
|
110
|
+
token: claimResult.token,
|
|
111
|
+
attempt: claimResult.attempt
|
|
112
|
+
};
|
|
113
|
+
const retries = claimResult.resumed ? claimResult.retries ?? 0 : 0;
|
|
114
|
+
const resumes = claimResult.attempt - args.counters.claims - retries;
|
|
115
|
+
args.counters.claims += 1 + retries;
|
|
116
|
+
const roundOver = replayed && (yield* isReplayedRoundOver(args.runs, owned));
|
|
117
|
+
if (roundOver && (yield* sleepForScheduledRetry({
|
|
118
|
+
...args,
|
|
119
|
+
priorFailures: claimResult.failures
|
|
120
|
+
}))) return;
|
|
121
|
+
args.state.activeOwned = owned;
|
|
122
|
+
if (!roundOver && claimResult.resumed && resumes > args.runs.policy.retry.maxCrashAttempts) {
|
|
123
|
+
const crashOutcome = yield* settleCrashCap({
|
|
124
|
+
...args,
|
|
125
|
+
owned
|
|
126
|
+
});
|
|
127
|
+
args.state.activeOwned = void 0;
|
|
128
|
+
args.state.terminalSettled = true;
|
|
129
|
+
return crashOutcome;
|
|
130
|
+
}
|
|
131
|
+
const exit = roundOver ? Exit.fail(new RunClaimLost({
|
|
132
|
+
job: owned.job,
|
|
133
|
+
runKey: owned.runKey
|
|
134
|
+
})) : yield* Effect.exit(runTrackedJobBody({
|
|
135
|
+
...args,
|
|
136
|
+
owned
|
|
137
|
+
}));
|
|
138
|
+
if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.interrupt;
|
|
139
|
+
return yield* settleRound({
|
|
140
|
+
...args,
|
|
141
|
+
owned,
|
|
142
|
+
startedMs: claimResult.startedMs,
|
|
143
|
+
exit,
|
|
144
|
+
priorFailures: claimResult.failures
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
/**
|
|
148
|
+
* Builds the Effect `Layer` registering the durable workflow handler for one `JobDefinition`.
|
|
149
|
+
*/
|
|
150
|
+
const makeJobWorkflowLayer = (definition) => {
|
|
151
|
+
return makeJobWorkflow(definition).toLayer((payload, executionId) => Effect.gen(function* () {
|
|
152
|
+
const runs = yield* JobRuns;
|
|
153
|
+
const maybeOperatorParams = yield* Effect.serviceOption(WorkerJobParams);
|
|
154
|
+
const operatorParams = Option.getOrElse(maybeOperatorParams, () => ({}));
|
|
155
|
+
const mergedOverrides = resolveWorkflowParamOverrides(definition, payload, operatorParams);
|
|
156
|
+
const decodedParamsResult = yield* decodeParams(definition.name, definition.params, mergedOverrides).pipe(Effect.result);
|
|
157
|
+
if (decodedParamsResult._tag === "Failure") return yield* settleInvalidParams(definition.name, payload, decodedParamsResult.failure._tag, decodedParamsResult.failure.message);
|
|
158
|
+
const { params, encoded: encodedParams } = decodedParamsResult.success;
|
|
159
|
+
const force = resolveForce(definition.cadence, payload.trigger, payload.force);
|
|
160
|
+
const state = {
|
|
161
|
+
activeOwned: void 0,
|
|
162
|
+
terminalSettled: false
|
|
163
|
+
};
|
|
164
|
+
const counters = {
|
|
165
|
+
busyRetries: 0,
|
|
166
|
+
failureCount: 0,
|
|
167
|
+
claims: 0
|
|
168
|
+
};
|
|
169
|
+
yield* registerInterruptFinalizer({
|
|
170
|
+
runs,
|
|
171
|
+
definition,
|
|
172
|
+
payload,
|
|
173
|
+
state
|
|
174
|
+
});
|
|
175
|
+
if (payload.runAt !== void 0) yield* waitUntilRunAt(payload.runAt);
|
|
176
|
+
for (let round = 1;; round += 1) {
|
|
177
|
+
const terminal = yield* executeWorkflowRound({
|
|
178
|
+
definition,
|
|
179
|
+
runs,
|
|
180
|
+
payload,
|
|
181
|
+
executionId,
|
|
182
|
+
force,
|
|
183
|
+
params,
|
|
184
|
+
encodedParams,
|
|
185
|
+
round,
|
|
186
|
+
state,
|
|
187
|
+
counters
|
|
188
|
+
});
|
|
189
|
+
if (terminal !== void 0) return terminal;
|
|
190
|
+
}
|
|
191
|
+
}));
|
|
192
|
+
};
|
|
193
|
+
/**
|
|
194
|
+
* Registers the durable workflow handler layer for a type-erased `AnyJobDefinition<R>` through its
|
|
195
|
+
* rank-2 `JOB_CONTINUATION`, avoiding casts.
|
|
196
|
+
*/
|
|
197
|
+
const makeAnyJobWorkflowLayer = (definition) => {
|
|
198
|
+
const continuation = definition[JOB_CONTINUATION];
|
|
199
|
+
if (continuation === void 0) return Layer.effectDiscard(Effect.die(/* @__PURE__ */ new Error(`Job "${definition.name}" must be constructed with defineJob before registering.`)));
|
|
200
|
+
return continuation((concrete) => makeJobWorkflowLayer(concrete));
|
|
201
|
+
};
|
|
202
|
+
export { JobOutcomeSchema, JobWorkflowPayload, MAX_CRASH_ATTEMPTS_TAG, WorkerJobParams, dispatchApiJobWorkflow, dispatchJob, makeAnyJobWorkflowLayer, makeJobWorkflow, makeJobWorkflowLayer, maxCrashAttemptsMessage };
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# Deployment: several workers and high availability
|
|
2
|
+
|
|
3
|
+
Run as many workers as you like against one PostgreSQL database. They form one Effect Cluster: PostgreSQL holds the membership, shard locks and messages, and workers call each other over HTTP only to deliver work sooner. Most of this page is Effect Cluster 4.1.6 behaviour; the library adds the run ledger.
|
|
4
|
+
|
|
5
|
+
## The moving parts
|
|
6
|
+
|
|
7
|
+
| Process | Cluster role | Address | Needs to reach |
|
|
8
|
+
| ------- | ---------------------------------- | --------------------------------------------- | ------------------------------ |
|
|
9
|
+
| Worker | Runner: owns shards, runs jobs | One advertised `host:port`, unique per worker | PostgreSQL, every other worker |
|
|
10
|
+
| API | Client only: stores and dispatches | None (`runnerAddress: Option.none()`) | PostgreSQL, every worker |
|
|
11
|
+
| Deploy | Not part of the Cluster | None | PostgreSQL |
|
|
12
|
+
|
|
13
|
+
- **Membership:** a worker registers its advertised address in `<prefix>_runners` and counts as a member while its heartbeat is newer than `shardLockExpiration` (35 s).
|
|
14
|
+
- **Ownership:** each group's `shardsPerGroup` shards are spread over the workers that claim it, each held by a PostgreSQL advisory lock. Two Clusters in one database need different prefixes.
|
|
15
|
+
- **Delivery:** a dispatched workflow is written to PostgreSQL, then the owner is woken over HTTP; if that fails, it finds the message on its next poll (10 s).
|
|
16
|
+
- **Fencing:** each run also claims its ledger row with a lease, so only one owner can settle it during a handover.
|
|
17
|
+
|
|
18
|
+
## Addresses and ports
|
|
19
|
+
|
|
20
|
+
Every worker has two addresses:
|
|
21
|
+
|
|
22
|
+
| Setting | Meaning | Typical value |
|
|
23
|
+
| --------------------- | ---------------------------------------------------------------- | ----------------------------------------------- |
|
|
24
|
+
| `runnerAddress` | What other workers and API processes dial; the worker's identity | The node's private IP or DNS name, and the port |
|
|
25
|
+
| `runnerListenAddress` | What this worker binds; defaults to `runnerAddress` | `0.0.0.0` and the same port |
|
|
26
|
+
|
|
27
|
+
The rules:
|
|
28
|
+
|
|
29
|
+
- **Advertise an address everyone can reach**: the private IP or a per-instance DNS name, never `0.0.0.0` or `localhost` unless every process shares one host. Listen on `0.0.0.0`.
|
|
30
|
+
- **One port per worker per host.** Containers with their own IP can share a port.
|
|
31
|
+
- **No load balancer** in front of the runner port: messages go to the owner of a specific shard.
|
|
32
|
+
- **Private network only**: see [Security](workers-and-clients.md#security).
|
|
33
|
+
- **The address is the worker's identity.** A restart at a new IP registers a new runner; the old entry goes at once after a clean stop, or after 35 s after a crash.
|
|
34
|
+
|
|
35
|
+
### Do not let `HOST` and `PORT` choose the address
|
|
36
|
+
|
|
37
|
+
`ShardingConfig.layerFromEnv` reads Effect `Config` keys from the environment, upper-cased with underscores: `HOST`, `PORT`, `LISTEN_HOST`, `LISTEN_PORT`, `SHARD_GROUPS`, `AVAILABLE_SHARD_GROUPS`, `SHARDS_PER_GROUP` and so on. Explicit options win over them. `HOST` and `PORT` are generic names that platforms set for your web server, so a worker that does not set `runnerAddress` itself can end up advertising `0.0.0.0:8080`. Always pass `runnerAddress` (and `runnerListenAddress`) explicitly, read from names of your own, as below.
|
|
38
|
+
|
|
39
|
+
## A worker per node
|
|
40
|
+
|
|
41
|
+
Every node runs the same code, configured by its environment:
|
|
42
|
+
|
|
43
|
+
<!-- prettier-ignore -->
|
|
44
|
+
```ts
|
|
45
|
+
import * as NodeClusterHttp from '@effect/platform-node/NodeClusterHttp';
|
|
46
|
+
import { assignedShardGroupsFor, availableShardGroupsFor, JobStorage, makeSchedulerLayer } from '@yieldkit/jobs';
|
|
47
|
+
import { makePgLive } from '@yieldkit/pg';
|
|
48
|
+
import { Config, Effect, Layer, Option } from 'effect';
|
|
49
|
+
import { ClusterWorkflowEngine, RunnerAddress, ShardingConfig, SqlMessageStorage, SqlRunnerStorage } from 'effect/cluster';
|
|
50
|
+
import { Digest, SecureRandom } from 'effect/crypto';
|
|
51
|
+
|
|
52
|
+
import { allJobs } from './jobs.ts';
|
|
53
|
+
|
|
54
|
+
// Per node. Your own names: Effect's `layerFromEnv` would read the generic HOST and PORT.
|
|
55
|
+
const NodeConfig = Config.all({
|
|
56
|
+
host: Config.String('CLUSTER_HOST'), // this node's IP or DNS name, as other nodes reach it
|
|
57
|
+
port: Config.Port('CLUSTER_PORT').pipe(Config.withDefault(34431)),
|
|
58
|
+
listenHost: Config.String('CLUSTER_LISTEN_HOST').pipe(Config.withDefault('0.0.0.0')),
|
|
59
|
+
only: Config.option(Config.String('JOBS_ONLY')), // e.g. "nightly-report,sync-orders"
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const AppPg = makePgLive({ applicationName: 'worker', searchPath: 'app' });
|
|
63
|
+
|
|
64
|
+
export const WorkerLive = Layer.unwrap(
|
|
65
|
+
Effect.gen(function* () {
|
|
66
|
+
const node = yield* NodeConfig;
|
|
67
|
+
const only = Option.getOrUndefined(node.only)?.split(',');
|
|
68
|
+
const shardingConfig = {
|
|
69
|
+
runnerAddress: Option.some(RunnerAddress.make(node.host, node.port)),
|
|
70
|
+
runnerListenAddress: Option.some(RunnerAddress.make(node.listenHost, node.port)),
|
|
71
|
+
// Identical on every node:
|
|
72
|
+
availableShardGroups: [...availableShardGroupsFor(allJobs)],
|
|
73
|
+
shardsPerGroup: 300,
|
|
74
|
+
// Per node:
|
|
75
|
+
assignedShardGroups: [...assignedShardGroupsFor(allJobs, only)],
|
|
76
|
+
};
|
|
77
|
+
const ShardingConfigLive = ShardingConfig.layerFromEnv(shardingConfig);
|
|
78
|
+
const ClusterLive = ClusterWorkflowEngine.layer.pipe(
|
|
79
|
+
Layer.provideMerge(NodeClusterHttp.layer({ transport: 'http', storage: 'byo', shardingConfig })),
|
|
80
|
+
Layer.provideMerge(
|
|
81
|
+
Layer.mergeAll(
|
|
82
|
+
SqlMessageStorage.layerStorage({ prefix: 'app_cluster' }).pipe(Layer.provide(Digest.layerWebCrypto)),
|
|
83
|
+
SqlRunnerStorage.layerStorage({ prefix: 'app_cluster' }),
|
|
84
|
+
).pipe(Layer.provide([AppPg, ShardingConfigLive])),
|
|
85
|
+
),
|
|
86
|
+
Layer.provideMerge(ShardingConfigLive),
|
|
87
|
+
);
|
|
88
|
+
return makeSchedulerLayer(allJobs, { only }).pipe(
|
|
89
|
+
Layer.provide([ClusterLive, JobStorage.layerStorage().pipe(Layer.provide(AppPg)), SecureRandom.layerWebCrypto]),
|
|
90
|
+
);
|
|
91
|
+
}),
|
|
92
|
+
);
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Launch it with `NodeRuntime.runMain(Layer.launch(WorkerLive))`, so `SIGTERM` shuts it down cleanly.
|
|
96
|
+
|
|
97
|
+
### What must match across nodes
|
|
98
|
+
|
|
99
|
+
| Setting | Same everywhere? | Why |
|
|
100
|
+
| ----------------------------------------------------- | ------------------------------- | ------------------------------------------------------------------------------- |
|
|
101
|
+
| `allJobs` passed to the helpers and the scheduler | Yes | Shard groups and maintenance come from it |
|
|
102
|
+
| `availableShardGroups`, `shardsPerGroup` | Yes | Every process must map an entity to the same shard; Cluster does not check this |
|
|
103
|
+
| Cluster table prefix and schema, `JobStorage` options | Yes | One set of tables per Cluster |
|
|
104
|
+
| Serialization (`binary` or `ndjson`) and transport | Yes | Workers decode each other's RPCs |
|
|
105
|
+
| `effect` and `@yieldkit/jobs` versions | Yes, apart from rolling deploys | Persisted message and payload formats |
|
|
106
|
+
| `runnerAddress`, `runnerListenAddress` | No: unique per worker | |
|
|
107
|
+
| `only` and `assignedShardGroups` | No | Lets worker pools specialise; see below |
|
|
108
|
+
| `runnerShardWeight` | No | A worker with weight 2 gets about twice the shards of one with weight 1 |
|
|
109
|
+
|
|
110
|
+
## Many identical workers
|
|
111
|
+
|
|
112
|
+
With no `only`, every worker claims every group and the shards spread evenly. Each run key still runs once: a cron or singleton runs only on its shard's owner, a second dispatch of a key joins the first execution, and the ledger claim fences the rest.
|
|
113
|
+
|
|
114
|
+
## Worker pools with `only`
|
|
115
|
+
|
|
116
|
+
To keep heavy jobs off your general workers, or run a job on dedicated machines, give each pool its own `only`. Then derive its `assignedShardGroups` with `assignedShardGroupsFor(allJobs, only)`, as `JOBS_ONLY` does above.
|
|
117
|
+
|
|
118
|
+
- Every worker still claims Cluster's `default` group and `yieldkit-jobs` (maintenance), so maintenance can run on any pool. A job's durable clocks stay in the job's group.
|
|
119
|
+
- A job's group is claimed only by the pools that run it. Its workflows never land on a worker that has no handler for them, and `makeSchedulerLayer` refuses a config that would allow that.
|
|
120
|
+
- Give each job at least two workers for redundancy. While a job's whole pool is down, its dispatched workflows wait in PostgreSQL and its crons do not fire. When a worker of the pool starts, its start-up singleton dispatches the current run key; earlier buckets that were missed are not run.
|
|
121
|
+
|
|
122
|
+
## API processes
|
|
123
|
+
|
|
124
|
+
API servers run the [README's client](../README.md#start-a-job-from-an-api) with the workers' `availableShardGroups`, `shardsPerGroup`, prefix and serialization. They should reach every worker's address; if not, dispatches arrive by polling, only slower. They hold no shards, so scaling them never rebalances.
|
|
125
|
+
|
|
126
|
+
## Scaling, restarts and failures
|
|
127
|
+
|
|
128
|
+
| Event | What happens | How fast (defaults) |
|
|
129
|
+
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
|
|
130
|
+
| A worker joins | It registers. On their next assignment refresh, all workers recompute the hash ring and hand over the shards that move. | `refreshAssignmentsInterval` (3 s), plus `runnerJoinDebounce` (0) |
|
|
131
|
+
| A worker stops cleanly (`SIGTERM`) | It stops its entities (waiting up to `entityTerminationTimeout`), releases its shard locks and unregisters. The others take its shards on their next refresh. | Seconds |
|
|
132
|
+
| A worker crashes or its machine dies | Its PostgreSQL session ends, so its advisory locks go at once. It leaves membership once its heartbeat is older than `shardLockExpiration`, or sooner if a health check fails. | Up to `shardLockExpiration` (35 s) |
|
|
133
|
+
| A worker freezes or is partitioned | PostgreSQL ends its idle session after `shardLockExpiration` (PostgreSQL 14+), releasing its locks. If it wakes and can't refresh its locks for that long, it unregisters itself and stops its entities. | `shardLockExpiration` (35 s) |
|
|
134
|
+
| A worker restarts on a new IP | A new runner registers; the old entry is handled as a stop or a crash above. | As above |
|
|
135
|
+
| PostgreSQL is unavailable | Nothing can be stored, locked or claimed. Workers retry, and a worker that can't refresh its locks for `shardLockExpiration` gives up its shards until the database is back. | Until it recovers |
|
|
136
|
+
|
|
137
|
+
When shards move, in-flight workflows resume on the new owner from PostgreSQL; finished durable stages are not repeated, and the interrupted body runs again ([at least once](jobs.md#limits)).
|
|
138
|
+
|
|
139
|
+
Health checks: `NodeClusterHttp.layer` pings each runner (`runnerHealth: 'ping'`, every `runnerHealthCheckInterval`, 1 minute). On Kubernetes, `runnerHealth: 'k8s'` uses pod readiness instead, matching the pod by its IP, so advertise the pod IP.
|
|
140
|
+
|
|
141
|
+
## Rolling deploys
|
|
142
|
+
|
|
143
|
+
1. Run the deploy step first: your Cluster's migrations, then `JobStorage.layerMigrations`. Workers of the old version accept a newer library history, so they keep running.
|
|
144
|
+
2. Replace workers one or a few at a time. Each one stopping hands its shards to the others. Set a termination grace period longer than `entityTerminationTimeout` (15 s), or Kubernetes kills workers mid-handover.
|
|
145
|
+
3. Don't rename jobs, stages or other [persisted names](workers-and-clients.md#persisted-names) in the same deploy: in-flight workflows would be orphaned.
|
|
146
|
+
|
|
147
|
+
## Kubernetes
|
|
148
|
+
|
|
149
|
+
- A `Deployment` (or several, one per `only` pool) of workers, each pod with `CLUSTER_HOST` from the pod IP (`valueFrom.fieldRef.fieldPath: status.podIP`), `CLUSTER_PORT` fixed, and `CLUSTER_LISTEN_HOST=0.0.0.0`.
|
|
150
|
+
- A `containerPort` for the runner port. You need no `Service` for it, because nobody load-balances runner traffic; a `NetworkPolicy` should limit it to workers and API pods.
|
|
151
|
+
- `terminationGracePeriodSeconds` above 15, and `runnerHealth: 'k8s'` if you prefer readiness over pings. Its pod list needs RBAC to list pods.
|
|
152
|
+
- The deploy step as a `Job` or a pre-deploy hook, before the rollout.
|
|
153
|
+
|
|
154
|
+
## Tuning
|
|
155
|
+
|
|
156
|
+
These are `ShardingConfig` options from Effect, with Effect's defaults. Lowering them speeds up failover at the cost of more database traffic.
|
|
157
|
+
|
|
158
|
+
| Option | Default | Controls |
|
|
159
|
+
| ---------------------------- | ------- | ------------------------------------------------------------------------- |
|
|
160
|
+
| `shardLockExpiration` | 35 s | How long a crashed or frozen worker can keep its shards and stay a member |
|
|
161
|
+
| `shardLockRefreshInterval` | 10 s | How often a worker renews its locks and heartbeat |
|
|
162
|
+
| `refreshAssignmentsInterval` | 3 s | How often workers re-read membership and rebalance |
|
|
163
|
+
| `entityMessagePollInterval` | 10 s | The longest a stored message waits when its HTTP wake-up did not arrive |
|
|
164
|
+
| `runnerHealthCheckInterval` | 1 min | How often runners are pinged |
|
|
165
|
+
| `entityTerminationTimeout` | 15 s | How long a stopping worker waits for its entities |
|
|
166
|
+
| `runnerJoinDebounce` | 0 | How long joins are held back to rebalance once |
|
|
167
|
+
| `runnerShardWeight` | 1 | This worker's share of shards relative to others |
|
package/docs/jobs.md
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# Jobs
|
|
2
|
+
|
|
3
|
+
A job is a value built with `defineJob`: a name, a cadence, a params schema, a stats schema and the effect that does the work.
|
|
4
|
+
|
|
5
|
+
<!-- prettier-ignore -->
|
|
6
|
+
```ts
|
|
7
|
+
import { defineJob } from '@yieldkit/jobs';
|
|
8
|
+
import { Effect, Schema } from 'effect';
|
|
9
|
+
|
|
10
|
+
export const syncOrders = defineJob({
|
|
11
|
+
name: 'sync-orders', // ledger key, workflow name and shard group
|
|
12
|
+
description: 'Copies new orders from the shop',
|
|
13
|
+
cadence: { _tag: 'Every', interval: '5 minutes' },
|
|
14
|
+
params: {
|
|
15
|
+
schema: Schema.Struct({ limit: Schema.Int, dryRunEmail: Schema.Boolean }),
|
|
16
|
+
defaults: { limit: 100, dryRunEmail: false }, // encoded values, merged under overrides
|
|
17
|
+
apiParams: ['limit'], // keys an API caller may set; default none
|
|
18
|
+
},
|
|
19
|
+
stats: Schema.Struct({ copied: Schema.Int }), // stored in the ledger, logged on completion
|
|
20
|
+
run: ({ params, runKey, trigger, attempt }) => Effect.succeed({ copied: params.limit }),
|
|
21
|
+
});
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Use `defineJob`, not a plain object. Its hidden continuation lets the scheduler, `runAnyJob` and `makeAnyJobWorkflowLayer` run mixed job lists without casts.
|
|
25
|
+
|
|
26
|
+
## Cadences and run keys
|
|
27
|
+
|
|
28
|
+
The run key makes a run idempotent: one ledger row and one scheduled workflow execution per `(job, runKey)`. `runKeyFor(cadence, nowMs)` computes it for every cadence except `OnDemand`, whose caller chooses it.
|
|
29
|
+
|
|
30
|
+
| Cadence | Run key | Scheduled |
|
|
31
|
+
| ---------------------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------- |
|
|
32
|
+
| `{ _tag: 'Every', interval }` | Bucket start, `YYYY-MM-DDTHH:mmZ` (UTC) | A UTC cron every `interval`; it must evenly divide an hour or a day |
|
|
33
|
+
| `{ _tag: 'Daily', checkEvery? }` | `YYYY-MM-DD` (UTC) | A UTC cron every `checkEvery` (default 1 hour), so a missed midnight catches up |
|
|
34
|
+
| `{ _tag: 'Daily', at, until?, timeZone? }` | `YYYY-MM-DD` in `timeZone` | The first check at or after `at`; retried every `checkEvery` until `until` (default `24:00`) |
|
|
35
|
+
| `{ _tag: 'Daily', window, until?, timeZone? }` | `YYYY-MM-DD` in `timeZone` | A time in `[window.from, window.to)` that changes daily; retried until `until` (default `window.to`) |
|
|
36
|
+
| `{ _tag: 'Cron', expression, timeZone? }` | The tick, `YYYY-MM-DDTHH:mmZ` (UTC) | Each tick of a five-field cron expression; a missed tick runs up to `catchUpWithin` (1 hour) late |
|
|
37
|
+
| `{ _tag: 'Once', start: 'automatic' }` | `once` | At worker start-up until it completes; retried with backoff |
|
|
38
|
+
| `{ _tag: 'Once', start: 'manual' }` | `once` | Never; only `runJob` starts it, and `isApiRequestable` returns `false` |
|
|
39
|
+
| `{ _tag: 'OnDemand' }` | The caller's key, such as `welcome:42` | Never; `dispatchJob` starts each run, optionally delayed, and retries it with backoff |
|
|
40
|
+
|
|
41
|
+
For `Daily`, `at`, `window` and `until` are local `HH:MM` times in `timeZone` (IANA, default `UTC`), and `checkEvery` is also the retry wait. [Scheduling recipes](scheduling.md) covers retries, catch-up and daylight saving time for each cadence.
|
|
42
|
+
|
|
43
|
+
`makeSchedulerLayer`, `runJob` and `dispatchApiJobWorkflow` validate cadences and fail with `ClusterConfigError` for a bad interval, time, time zone, window or cron expression, or `at` together with `window`.
|
|
44
|
+
|
|
45
|
+
## Triggers
|
|
46
|
+
|
|
47
|
+
Every run has a trigger, stored in the ledger and the workflow payload:
|
|
48
|
+
|
|
49
|
+
- `schedule`: the scheduler, or `dispatchJob` for an `OnDemand` job. It retries a failed key once `next_attempt_at` has passed and leaves an exhausted `Daily` or `OnDemand` key alone.
|
|
50
|
+
- `manual`: an operator, with trusted params. It may take a failed or exhausted key at any time.
|
|
51
|
+
- `api`: `dispatchApiJobWorkflow`. Params outside `apiParams` are dropped, and dropped again inside the workflow, so a forged payload cannot set them ([what the filter does not cover](workers-and-clients.md#limits)).
|
|
52
|
+
|
|
53
|
+
`force` re-runs a completed key. It defaults to `true` for `manual` and `api` runs of `Every` and `Cron` jobs, else `false`.
|
|
54
|
+
|
|
55
|
+
## Params
|
|
56
|
+
|
|
57
|
+
Overrides are merged over `params.defaults`, decoded with `params.schema` and stored encoded as `jsonb`. Unknown keys are rejected. Every failure is `InvalidJobParams`, raised before anything is claimed.
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { decodeJobParams, findDisallowedApiParams, parseSetFlags } from '@yieldkit/jobs';
|
|
61
|
+
import { Effect } from 'effect';
|
|
62
|
+
|
|
63
|
+
import { syncOrders } from './jobs.ts';
|
|
64
|
+
|
|
65
|
+
const fromFlags = Effect.gen(function* () {
|
|
66
|
+
const overrides = yield* parseSetFlags(['limit=10']); // { limit: 10 }; JSON, else a string
|
|
67
|
+
return yield* decodeJobParams(syncOrders, overrides); // { params, encoded }
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const rejected = findDisallowedApiParams(syncOrders, { dryRunEmail: true }); // ['dryRunEmail']
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Durable stages
|
|
74
|
+
|
|
75
|
+
`durableStage({ name, schema, execute })` runs `execute` as an Effect `Activity` and stores its result, encoded with `schema`.
|
|
76
|
+
|
|
77
|
+
<!-- prettier-ignore -->
|
|
78
|
+
```ts
|
|
79
|
+
import { defineJob, durableStage } from '@yieldkit/jobs';
|
|
80
|
+
import { Effect, Schema } from 'effect';
|
|
81
|
+
|
|
82
|
+
const Rows = Schema.Struct({ count: Schema.Int });
|
|
83
|
+
|
|
84
|
+
export const nightlyReport = defineJob({
|
|
85
|
+
name: 'nightly-report',
|
|
86
|
+
description: 'Builds and mails the daily report',
|
|
87
|
+
cadence: { _tag: 'Daily' },
|
|
88
|
+
params: { schema: Schema.Struct({}), defaults: {} },
|
|
89
|
+
stats: Rows,
|
|
90
|
+
run: () =>
|
|
91
|
+
Effect.gen(function* () {
|
|
92
|
+
const rows = yield* durableStage({ name: 'collect', schema: Rows, execute: Effect.succeed({ count: 42 }) });
|
|
93
|
+
yield* Effect.log('runs again in every retry round'); // outside a stage
|
|
94
|
+
return yield* durableStage({ name: 'mail', schema: Rows, execute: Effect.succeed(rows) });
|
|
95
|
+
}),
|
|
96
|
+
});
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Code outside a stage runs again in each retry round; a stage that succeeded returns its stored result. A failed stage is stored as a `JobStageError` with a redacted message, the error's `_tag` and any `retryAfterSeconds`. Outside a workflow (`runJob`, tests) a stage just runs `execute`.
|
|
100
|
+
|
|
101
|
+
## Running a job directly
|
|
102
|
+
|
|
103
|
+
`runJob(job, { trigger, params?, force?, runKey?, dryRun?, onClaimed? })` claims the key, runs the job with heartbeats and settles the ledger, without Cluster ([README example](../README.md#run-a-job-from-a-script)). `dryRun: true` provides the job's `dryRun` layer instead of your services and claims and writes nothing:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
import { defineJob, runJob } from '@yieldkit/jobs';
|
|
107
|
+
import { Context, Effect, Layer, Schema } from 'effect';
|
|
108
|
+
|
|
109
|
+
class Mailer extends Context.Service<Mailer, { send: (to: string) => Effect.Effect<void> }>()(
|
|
110
|
+
'app/Mailer',
|
|
111
|
+
) {}
|
|
112
|
+
|
|
113
|
+
export const digest = defineJob({
|
|
114
|
+
name: 'digest',
|
|
115
|
+
description: 'Mails the digest',
|
|
116
|
+
cadence: { _tag: 'Daily' },
|
|
117
|
+
params: { schema: Schema.Struct({}), defaults: {} },
|
|
118
|
+
stats: Schema.Struct({ sent: Schema.Int }),
|
|
119
|
+
run: () => Mailer.use((mailer) => mailer.send('ops@example.com')).pipe(Effect.as({ sent: 1 })),
|
|
120
|
+
dryRun: Layer.succeed(Mailer, { send: (to) => Effect.log(`would mail ${to}`) }),
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
export const preview = runJob(digest, { trigger: 'manual', dryRun: true });
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
`runJob` keeps the job's services in its type with `dryRun: true`, so the caller still provides them; the run uses the `dryRun` layer's.
|
|
127
|
+
|
|
128
|
+
Job errors, defects and lost leases become a `failed` outcome. Interrupting the `runJob` fiber itself settles the row as failed, and the fiber exits interrupted instead of returning an outcome. `runJob` itself fails only with `InvalidJobParams`, `InvalidRunKey`, `ClusterConfigError` (an invalid cadence), `DryRunUnsupported` or a ledger `SqlError`.
|
|
129
|
+
|
|
130
|
+
`runKey` is for `OnDemand` jobs, which need one; any other job fails with `InvalidRunKey` when given one. A `manual` run with the key of an `OnDemand` run that gave up runs it again.
|
|
131
|
+
|
|
132
|
+
Without a `dryRun` layer, `dryRun: true` fails with `DryRunUnsupported`. `runAnyJob` does the same for an element of a mixed job list.
|
|
133
|
+
|
|
134
|
+
## Outcomes
|
|
135
|
+
|
|
136
|
+
`runJob` returns a `JobOutcome`. Workflows return the same shape (`JobOutcomeSchema`), stored in Cluster's replies.
|
|
137
|
+
|
|
138
|
+
| `status` | Fields |
|
|
139
|
+
| ----------- | ------------------------------------------------------------------------------------------------ |
|
|
140
|
+
| `completed` | `attempt`, `dryRun`, `stats` |
|
|
141
|
+
| `skipped` | `reason`: `AlreadyCompleted`, `Busy`, `RetryLater` (with `at`) or `Exhausted` |
|
|
142
|
+
| `failed` | `attempt`, `errorMessage` (redacted), `isDefect`, `interrupted`, `errorTag`, `retryAfterSeconds` |
|
|
143
|
+
|
|
144
|
+
All three also carry `job`, `runKey`, `trigger` and `elapsedMs`.
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
import type { JobOutcome } from '@yieldkit/jobs';
|
|
148
|
+
|
|
149
|
+
const describe = (outcome: JobOutcome): string => {
|
|
150
|
+
switch (outcome.status) {
|
|
151
|
+
case 'completed':
|
|
152
|
+
return `attempt ${String(outcome.attempt)} completed`;
|
|
153
|
+
case 'skipped':
|
|
154
|
+
return outcome.reason._tag === 'RetryLater'
|
|
155
|
+
? `retry at ${outcome.reason.at}`
|
|
156
|
+
: outcome.reason._tag;
|
|
157
|
+
case 'failed':
|
|
158
|
+
return `${outcome.errorTag ?? 'untagged'}: ${outcome.errorMessage}`;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
A run that lost its lease is `failed` with `errorTag: 'RunClaimLost'` and `interrupted: true`.
|
|
164
|
+
|
|
165
|
+
## Annotations and log fields
|
|
166
|
+
|
|
167
|
+
Two optional fields carry your own metadata:
|
|
168
|
+
|
|
169
|
+
<!-- prettier-ignore -->
|
|
170
|
+
```ts
|
|
171
|
+
import { defineJob } from '@yieldkit/jobs';
|
|
172
|
+
import { Context, Effect, Schema } from 'effect';
|
|
173
|
+
|
|
174
|
+
class Tenant extends Context.Service<Tenant, string>()('app/Tenant') {}
|
|
175
|
+
|
|
176
|
+
export const tenantSync = defineJob({
|
|
177
|
+
name: 'tenant-sync',
|
|
178
|
+
description: 'Syncs one tenant',
|
|
179
|
+
cadence: { _tag: 'Daily' },
|
|
180
|
+
params: { schema: Schema.Struct({}), defaults: {} },
|
|
181
|
+
stats: Schema.Struct({}),
|
|
182
|
+
annotations: Context.make(Tenant, 'acme'), // handed to the onSettle hook
|
|
183
|
+
logFields: { tenant: 'acme' }, // added to every log line of its runs
|
|
184
|
+
run: () => Effect.succeed({}),
|
|
185
|
+
});
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
The [settle hook](storage.md#the-settle-hook) reads them back with `Context.getOption(event.annotations, Tenant)`.
|
|
189
|
+
|
|
190
|
+
## Limits
|
|
191
|
+
|
|
192
|
+
- Job code runs at least once, not exactly once. A crash repeats the attempt; a stage repeats if its worker dies before its result is stored.
|
|
193
|
+
- Each API dispatch is its own workflow execution, so two forced dispatches of one key can both run.
|
|
194
|
+
- Do not call `runJob` from a job body that runs in a workflow: its stages would share the parent's journal. Dispatch the other job instead.
|
|
195
|
+
- The `name` is persisted as the ledger's `job` column, the workflow name (`Workflow/<name>`) and the shard group. Renaming a job orphans its history and in-flight workflows. Renaming a stage makes in-flight workflows run it again. [Persisted names](workers-and-clients.md#persisted-names) has the full list.
|
|
196
|
+
- Cluster stores shard ids as `<name>:<n>` in 50 characters, so a name is at most `50 - 1 - digits of shardsPerGroup` characters: 47 with 16 to 99 shards, 46 with Effect's default 300. Longer names fail `makeSchedulerLayer` and `checkShardingConfig` with `ClusterConfigError`. A name holds only letters, digits, `.`, `_` and `-`, is unique in the job list, and is not `default` or `yieldkit-jobs`; `makeSchedulerLayer` and `checkShardingConfig` fail with `ClusterConfigError` otherwise.
|
|
197
|
+
- `Every.interval` and `Daily.checkEvery` must be whole minutes that divide an hour, or whole hours that divide a day (one day included). Anything else, an unparseable duration included, fails `makeSchedulerLayer`, `runJob` and `dispatchApiJobWorkflow` with `ClusterConfigError`.
|
|
198
|
+
- Stage names the workflow uses itself (`claim-round-N`, `claim-deadline-N`, `settle-completed-N`, `settle-failed-N`, `settle-skipped-N`, `settle-crash-cap-N`, `settle-invalid-params`, `retry-later-clock-N`, `retry-deadline-N`, `run-at-clock`, anything under `DurableClock/`) are refused with a `JobStageError` before anything runs.
|
|
199
|
+
- Stats must encode to JSON (no `bigint`), and neither stats nor params may contain `\u0000`.
|
|
200
|
+
- `failed` with `RunClaimLost` also covers a settle that could not be written, and a worker restart right at the settle: the ledger row says what happened, whatever the workflow result or request row reads.
|