@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,360 @@
|
|
|
1
|
+
import { JobTrigger } from "./job.js";
|
|
2
|
+
import { omitUndefined } from "./omit-undefined.js";
|
|
3
|
+
import { Context, Layer, Schema } from "effect";
|
|
4
|
+
import { redactLogString } from "@yieldkit/logger";
|
|
5
|
+
import { Workflow } from "effect/workflow";
|
|
6
|
+
import { ClusterSchema } from "effect/cluster";
|
|
7
|
+
// src/workflow-schema.ts
|
|
8
|
+
/**
|
|
9
|
+
* Context service carrying the worker's operator params into durable workflow handlers. Defaults to
|
|
10
|
+
* an empty map when not provided.
|
|
11
|
+
*/
|
|
12
|
+
var WorkerJobParams = class extends Context.Service()("@yieldkit/jobs/WorkerJobParams") {
|
|
13
|
+
/**
|
|
14
|
+
* Layer supplying `params` to workflow handlers.
|
|
15
|
+
*/
|
|
16
|
+
static layer = (params = {}) => Layer.succeed(this, params);
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* ISO-8601 UTC instant such as `2026-11-26T09:30:00.000Z`, the `runAt` format `dispatchJob` writes.
|
|
20
|
+
*/
|
|
21
|
+
const IsoInstant = Schema.String.check(Schema.makeFilter((value) => /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?Z$/u.test(value) && Number.isFinite(Date.parse(value)), { expected: "an ISO-8601 UTC instant" }));
|
|
22
|
+
/**
|
|
23
|
+
* Serializable payload of every job `Workflow`. Its field names are persisted in Cluster messages.
|
|
24
|
+
*/
|
|
25
|
+
const JobWorkflowPayload = Schema.Struct({
|
|
26
|
+
/**
|
|
27
|
+
* Ledger run key (`YYYY-MM-DD`, `YYYY-MM-DDTHH:MMZ`, `'once'`, or an `OnDemand` caller's key).
|
|
28
|
+
*/
|
|
29
|
+
runKey: Schema.String,
|
|
30
|
+
/**
|
|
31
|
+
* How this execution was started.
|
|
32
|
+
*/
|
|
33
|
+
trigger: JobTrigger,
|
|
34
|
+
/**
|
|
35
|
+
* Caller parameter overrides (re-filtered through `apiParams` when `trigger === 'api'`).
|
|
36
|
+
*/
|
|
37
|
+
params: Schema.JsonObject,
|
|
38
|
+
/**
|
|
39
|
+
* Whether a completed `(job, runKey)` row may be re-run.
|
|
40
|
+
*/
|
|
41
|
+
force: Schema.Boolean,
|
|
42
|
+
/**
|
|
43
|
+
* Linked request id when `trigger === 'api'`, else `null`.
|
|
44
|
+
*/
|
|
45
|
+
requestId: Schema.NullOr(Schema.String),
|
|
46
|
+
/**
|
|
47
|
+
* Optional uniqueness nonce (`requestId` for API runs, a fresh UUID for other forced runs, `null`
|
|
48
|
+
* for idempotent scheduled runs).
|
|
49
|
+
*/
|
|
50
|
+
attemptNonce: Schema.NullOr(Schema.String),
|
|
51
|
+
/**
|
|
52
|
+
* ISO-8601 UTC instant the run must not start before; the workflow waits durably until then. Set
|
|
53
|
+
* by `dispatchJob` for a delayed run, missing otherwise. Any other string fails decoding, so the
|
|
54
|
+
* job never runs without its wait.
|
|
55
|
+
*/
|
|
56
|
+
runAt: Schema.optional(IsoInstant)
|
|
57
|
+
});
|
|
58
|
+
/**
|
|
59
|
+
* Serializable `SkipReason` schema persisted in Cluster replies.
|
|
60
|
+
*/
|
|
61
|
+
const SkipReasonSchema = Schema.Union([
|
|
62
|
+
Schema.TaggedStruct("AlreadyCompleted", {}),
|
|
63
|
+
Schema.TaggedStruct("Busy", {}),
|
|
64
|
+
Schema.TaggedStruct("RetryLater", {
|
|
65
|
+
/**
|
|
66
|
+
* ISO-8601 UTC timestamp when the key becomes eligible for retry.
|
|
67
|
+
*/
|
|
68
|
+
at: Schema.String }),
|
|
69
|
+
Schema.TaggedStruct("Exhausted", {})
|
|
70
|
+
]);
|
|
71
|
+
/**
|
|
72
|
+
* Serializable `JobOutcome` schema returned by every job `Workflow`.
|
|
73
|
+
*/
|
|
74
|
+
const JobOutcomeSchema = Schema.Union([
|
|
75
|
+
Schema.Struct({
|
|
76
|
+
/**
|
|
77
|
+
* Registered job name.
|
|
78
|
+
*/
|
|
79
|
+
job: Schema.String,
|
|
80
|
+
/**
|
|
81
|
+
* Deterministic cadence key executed by this workflow.
|
|
82
|
+
*/
|
|
83
|
+
runKey: Schema.String,
|
|
84
|
+
/**
|
|
85
|
+
* How the run was started.
|
|
86
|
+
*/
|
|
87
|
+
trigger: JobTrigger,
|
|
88
|
+
/**
|
|
89
|
+
* Elapsed duration in milliseconds measured via the Effect clock.
|
|
90
|
+
*/
|
|
91
|
+
elapsedMs: Schema.Finite,
|
|
92
|
+
/**
|
|
93
|
+
* Terminal status discriminant for completed runs.
|
|
94
|
+
*/
|
|
95
|
+
status: Schema.Literal("completed"),
|
|
96
|
+
/**
|
|
97
|
+
* 1-based attempt number recorded in the ledger.
|
|
98
|
+
*/
|
|
99
|
+
attempt: Schema.Int,
|
|
100
|
+
/**
|
|
101
|
+
* Whether the run executed in dry-run mode (always `false` in cluster workflows).
|
|
102
|
+
*/
|
|
103
|
+
dryRun: Schema.Boolean,
|
|
104
|
+
/**
|
|
105
|
+
* Schema-encoded completion stats returned by the job.
|
|
106
|
+
*/
|
|
107
|
+
stats: Schema.Unknown
|
|
108
|
+
}),
|
|
109
|
+
Schema.Struct({
|
|
110
|
+
/**
|
|
111
|
+
* Registered job name.
|
|
112
|
+
*/
|
|
113
|
+
job: Schema.String,
|
|
114
|
+
/**
|
|
115
|
+
* Deterministic cadence key skipped by this workflow.
|
|
116
|
+
*/
|
|
117
|
+
runKey: Schema.String,
|
|
118
|
+
/**
|
|
119
|
+
* How the run was started.
|
|
120
|
+
*/
|
|
121
|
+
trigger: JobTrigger,
|
|
122
|
+
/**
|
|
123
|
+
* Elapsed duration in milliseconds measured via the Effect clock.
|
|
124
|
+
*/
|
|
125
|
+
elapsedMs: Schema.Finite,
|
|
126
|
+
/**
|
|
127
|
+
* Terminal status discriminant for skipped runs.
|
|
128
|
+
*/
|
|
129
|
+
status: Schema.Literal("skipped"),
|
|
130
|
+
/**
|
|
131
|
+
* Structured reason explaining why the run was skipped.
|
|
132
|
+
*/
|
|
133
|
+
reason: SkipReasonSchema
|
|
134
|
+
}),
|
|
135
|
+
Schema.Struct({
|
|
136
|
+
/**
|
|
137
|
+
* Registered job name.
|
|
138
|
+
*/
|
|
139
|
+
job: Schema.String,
|
|
140
|
+
/**
|
|
141
|
+
* Deterministic cadence key that failed.
|
|
142
|
+
*/
|
|
143
|
+
runKey: Schema.String,
|
|
144
|
+
/**
|
|
145
|
+
* How the run was started.
|
|
146
|
+
*/
|
|
147
|
+
trigger: JobTrigger,
|
|
148
|
+
/**
|
|
149
|
+
* Elapsed duration in milliseconds measured via the Effect clock.
|
|
150
|
+
*/
|
|
151
|
+
elapsedMs: Schema.Finite,
|
|
152
|
+
/**
|
|
153
|
+
* Terminal status discriminant for failed runs.
|
|
154
|
+
*/
|
|
155
|
+
status: Schema.Literal("failed"),
|
|
156
|
+
/**
|
|
157
|
+
* 1-based attempt number recorded in the ledger (`0` for pre-claim failures).
|
|
158
|
+
*/
|
|
159
|
+
attempt: Schema.Int,
|
|
160
|
+
/**
|
|
161
|
+
* Redacted failure summary safe for logs, API responses and Cluster replies.
|
|
162
|
+
*/
|
|
163
|
+
errorMessage: Schema.String,
|
|
164
|
+
/**
|
|
165
|
+
* Whether the failure originated as an unhandled defect.
|
|
166
|
+
*/
|
|
167
|
+
isDefect: Schema.Boolean,
|
|
168
|
+
/**
|
|
169
|
+
* Whether the failure resulted from an interruption or lost lease claim.
|
|
170
|
+
*/
|
|
171
|
+
interrupted: Schema.Boolean,
|
|
172
|
+
/**
|
|
173
|
+
* Optional original `_tag` of the typed domain error.
|
|
174
|
+
*/
|
|
175
|
+
errorTag: Schema.optional(Schema.String),
|
|
176
|
+
/**
|
|
177
|
+
* Optional `retryAfterSeconds` hint copied from the typed error.
|
|
178
|
+
*/
|
|
179
|
+
retryAfterSeconds: Schema.optional(Schema.Finite)
|
|
180
|
+
})
|
|
181
|
+
]);
|
|
182
|
+
/**
|
|
183
|
+
* Serializable result of the `claim-round` activity.
|
|
184
|
+
*/
|
|
185
|
+
const ClaimActivityResult = Schema.Union([
|
|
186
|
+
Schema.TaggedStruct("Acquired", {
|
|
187
|
+
/**
|
|
188
|
+
* Fencing claim token persisted in the ledger.
|
|
189
|
+
*/
|
|
190
|
+
token: Schema.String,
|
|
191
|
+
/**
|
|
192
|
+
* 1-based attempt number recorded in the ledger.
|
|
193
|
+
*/
|
|
194
|
+
attempt: Schema.Int,
|
|
195
|
+
/**
|
|
196
|
+
* `true` when resuming a prior crashed execution with the same `executionId`.
|
|
197
|
+
*/
|
|
198
|
+
resumed: Schema.Boolean,
|
|
199
|
+
/**
|
|
200
|
+
* Epoch millisecond timestamp captured when the claim activity started.
|
|
201
|
+
*/
|
|
202
|
+
startedMs: Schema.Finite,
|
|
203
|
+
/**
|
|
204
|
+
* Retries within this activity whose earlier claims may have committed.
|
|
205
|
+
*/
|
|
206
|
+
retries: Schema.optional(Schema.Int),
|
|
207
|
+
/**
|
|
208
|
+
* Failures the key already had when claimed; missing from replies of earlier releases.
|
|
209
|
+
*/
|
|
210
|
+
failures: Schema.optional(Schema.Int)
|
|
211
|
+
}),
|
|
212
|
+
Schema.TaggedStruct("Busy", {
|
|
213
|
+
/**
|
|
214
|
+
* Elapsed milliseconds for the skipped claim check.
|
|
215
|
+
*/
|
|
216
|
+
elapsedMs: Schema.Finite }),
|
|
217
|
+
Schema.TaggedStruct("Completed", {
|
|
218
|
+
/**
|
|
219
|
+
* Elapsed milliseconds for the skipped claim check.
|
|
220
|
+
*/
|
|
221
|
+
elapsedMs: Schema.Finite }),
|
|
222
|
+
Schema.TaggedStruct("AlreadySettled", {
|
|
223
|
+
/**
|
|
224
|
+
* Elapsed milliseconds for the skipped claim check.
|
|
225
|
+
*/
|
|
226
|
+
elapsedMs: Schema.Finite }),
|
|
227
|
+
Schema.TaggedStruct("RetryLater", {
|
|
228
|
+
/**
|
|
229
|
+
* ISO-8601 UTC timestamp when the backoff window expires.
|
|
230
|
+
*/
|
|
231
|
+
at: Schema.String,
|
|
232
|
+
/**
|
|
233
|
+
* Elapsed milliseconds for the skipped claim check.
|
|
234
|
+
*/
|
|
235
|
+
elapsedMs: Schema.Finite
|
|
236
|
+
}),
|
|
237
|
+
Schema.TaggedStruct("Exhausted", {
|
|
238
|
+
/**
|
|
239
|
+
* Elapsed milliseconds for the skipped claim check.
|
|
240
|
+
*/
|
|
241
|
+
elapsedMs: Schema.Finite })
|
|
242
|
+
]);
|
|
243
|
+
/**
|
|
244
|
+
* Serializable result of a `settle` activity.
|
|
245
|
+
*/
|
|
246
|
+
const SettleActivityResult = Schema.Struct({
|
|
247
|
+
/**
|
|
248
|
+
* `true` when `JobRuns.settle` matched our fencing claim token.
|
|
249
|
+
*/
|
|
250
|
+
settled: Schema.Boolean,
|
|
251
|
+
/**
|
|
252
|
+
* Elapsed run duration in milliseconds.
|
|
253
|
+
*/
|
|
254
|
+
elapsedMs: Schema.Finite,
|
|
255
|
+
/**
|
|
256
|
+
* Whether a failed round goes on to a durable retry, decided at settle time so a `Daily` deadline
|
|
257
|
+
* is checked once. Missing in replies stored by earlier releases.
|
|
258
|
+
*/
|
|
259
|
+
retries: Schema.optional(Schema.Boolean)
|
|
260
|
+
});
|
|
261
|
+
/**
|
|
262
|
+
* Error tag recorded when the same workflow execution crashes and resumes more than
|
|
263
|
+
* `policy.retry.maxCrashAttempts` times.
|
|
264
|
+
*/
|
|
265
|
+
const MAX_CRASH_ATTEMPTS_TAG = "MaxAttemptsExceeded";
|
|
266
|
+
/**
|
|
267
|
+
* Error message recorded when the same workflow execution crashed and resumed more than
|
|
268
|
+
* `maxCrashAttempts` times.
|
|
269
|
+
*/
|
|
270
|
+
const maxCrashAttemptsMessage = (maxCrashAttempts) => `The run crashed and resumed more than ${String(maxCrashAttempts)} times without finishing.`;
|
|
271
|
+
/**
|
|
272
|
+
* Error message recorded when a workflow is explicitly interrupted via `Workflow.interrupt`.
|
|
273
|
+
*/
|
|
274
|
+
const INTERRUPTED_WORKFLOW_MESSAGE = "The workflow was interrupted before the run finished.";
|
|
275
|
+
/**
|
|
276
|
+
* Builds the Effect `Workflow` declaration for `definition`, annotated with its own
|
|
277
|
+
* `ClusterSchema.ShardGroup` (`definition.name`) so workers assigned a subset of the jobs never
|
|
278
|
+
* claim messages of the others. The workflow name and the idempotency key (`runKey`, or
|
|
279
|
+
* `runKey:attemptNonce`) are persisted; changing them orphans in-flight executions.
|
|
280
|
+
*/
|
|
281
|
+
const makeJobWorkflow = (definition) => Workflow.make(definition.name, {
|
|
282
|
+
payload: JobWorkflowPayload,
|
|
283
|
+
success: JobOutcomeSchema,
|
|
284
|
+
error: Schema.Never,
|
|
285
|
+
idempotencyKey: (payload) => payload.attemptNonce === null ? payload.runKey : `${payload.runKey}:${payload.attemptNonce}`
|
|
286
|
+
}).annotate(ClusterSchema.ShardGroup, () => definition.name);
|
|
287
|
+
/**
|
|
288
|
+
* Converts a non-acquired `ClaimActivityResult` into its public `SkipReason`.
|
|
289
|
+
*/
|
|
290
|
+
const claimToSkipReason = (claim) => {
|
|
291
|
+
switch (claim._tag) {
|
|
292
|
+
case "Completed":
|
|
293
|
+
case "AlreadySettled": return { _tag: "AlreadyCompleted" };
|
|
294
|
+
case "Busy": return { _tag: "Busy" };
|
|
295
|
+
case "RetryLater": return {
|
|
296
|
+
_tag: "RetryLater",
|
|
297
|
+
at: claim.at
|
|
298
|
+
};
|
|
299
|
+
case "Exhausted": return { _tag: "Exhausted" };
|
|
300
|
+
default: return claim;
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
/**
|
|
304
|
+
* Encodes a ledger claim for the activity journal. An acquired claim records how many times the
|
|
305
|
+
* activity retried it, defaulting to zero.
|
|
306
|
+
*/
|
|
307
|
+
const encodeRunClaim = (claim, startedMs, retries = 0) => {
|
|
308
|
+
switch (claim._tag) {
|
|
309
|
+
case "Acquired": return {
|
|
310
|
+
_tag: "Acquired",
|
|
311
|
+
token: claim.token,
|
|
312
|
+
attempt: claim.attempt,
|
|
313
|
+
resumed: claim.resumed,
|
|
314
|
+
startedMs,
|
|
315
|
+
retries,
|
|
316
|
+
...omitUndefined({ failures: claim.failures })
|
|
317
|
+
};
|
|
318
|
+
case "Busy": return {
|
|
319
|
+
_tag: "Busy",
|
|
320
|
+
elapsedMs: 0
|
|
321
|
+
};
|
|
322
|
+
case "Completed": return {
|
|
323
|
+
_tag: "Completed",
|
|
324
|
+
elapsedMs: 0
|
|
325
|
+
};
|
|
326
|
+
case "AlreadySettled": return {
|
|
327
|
+
_tag: "AlreadySettled",
|
|
328
|
+
elapsedMs: 0
|
|
329
|
+
};
|
|
330
|
+
case "RetryLater": return {
|
|
331
|
+
_tag: "RetryLater",
|
|
332
|
+
at: claim.at.toISOString(),
|
|
333
|
+
elapsedMs: 0
|
|
334
|
+
};
|
|
335
|
+
case "Exhausted": return {
|
|
336
|
+
_tag: "Exhausted",
|
|
337
|
+
elapsedMs: 0
|
|
338
|
+
};
|
|
339
|
+
default: return claim;
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
/**
|
|
343
|
+
* Builds a `failed` `WorkflowJobOutcome` matching `JobOutcomeSchema`.
|
|
344
|
+
*/
|
|
345
|
+
const buildFailedOutcome = (args) => ({
|
|
346
|
+
job: args.job,
|
|
347
|
+
runKey: args.runKey,
|
|
348
|
+
trigger: args.trigger,
|
|
349
|
+
elapsedMs: args.elapsedMs,
|
|
350
|
+
status: "failed",
|
|
351
|
+
attempt: args.attempt,
|
|
352
|
+
errorMessage: redactLogString(args.errorMessage),
|
|
353
|
+
isDefect: args.isDefect,
|
|
354
|
+
interrupted: args.interrupted,
|
|
355
|
+
...omitUndefined({
|
|
356
|
+
errorTag: args.errorTag,
|
|
357
|
+
retryAfterSeconds: args.retryAfterSeconds
|
|
358
|
+
})
|
|
359
|
+
});
|
|
360
|
+
export { ClaimActivityResult, INTERRUPTED_WORKFLOW_MESSAGE, JobOutcomeSchema, JobWorkflowPayload, MAX_CRASH_ATTEMPTS_TAG, SettleActivityResult, WorkerJobParams, buildFailedOutcome, claimToSkipReason, encodeRunClaim, makeJobWorkflow, maxCrashAttemptsMessage };
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { RUN_CLAIM_LOST_MESSAGE, RUN_CLAIM_LOST_TAG } from "./errors.js";
|
|
2
|
+
import { recordJobRunMetrics } from "./metrics.js";
|
|
3
|
+
import { analyzeFailureExit, annotationsOf, elapsedMillisSince, retryTransientSql, settleOrLogLost } from "./run-support.js";
|
|
4
|
+
import { finishRequestIfPresent, sleepUntilInstant } from "./workflow-activities.js";
|
|
5
|
+
import { failureCountAfter, isRetryBeforeDeadline, scheduledRetrySleepFor } from "./workflow-retry.js";
|
|
6
|
+
import { MAX_CRASH_ATTEMPTS_TAG, SettleActivityResult, buildFailedOutcome, maxCrashAttemptsMessage } from "./workflow-schema.js";
|
|
7
|
+
import { DateTime, Duration, Effect } from "effect";
|
|
8
|
+
import { describeError, logWarning } from "@yieldkit/logger";
|
|
9
|
+
import { Activity } from "effect/workflow";
|
|
10
|
+
// src/workflow-settle.ts
|
|
11
|
+
/**
|
|
12
|
+
* Checks a claim reply replayed from the journal. A token that still holds the row renews its lease
|
|
13
|
+
* and returns `false`, so the round goes on. A token that lost the row, or a ledger that cannot be
|
|
14
|
+
* reached after the short retry (logged as `job.heartbeat.failed`), returns `true`: the round is
|
|
15
|
+
* over (it settled before the workflow suspended, or another run took the key) and its body must
|
|
16
|
+
* not run again.
|
|
17
|
+
*/
|
|
18
|
+
const isReplayedRoundOver = (runs, owned) => runs.heartbeat(owned).pipe(retryTransientSql, Effect.catch((error) => logWarning("job.heartbeat.failed", {
|
|
19
|
+
job: owned.job,
|
|
20
|
+
runKey: owned.runKey,
|
|
21
|
+
attempt: owned.attempt,
|
|
22
|
+
errorMessage: describeError(error)
|
|
23
|
+
}).pipe(Effect.as(false))), Effect.map((stillOwned) => !stillOwned));
|
|
24
|
+
/**
|
|
25
|
+
* Builds the `RunClaimLost` failed outcome when a settle call fails its fencing check.
|
|
26
|
+
*/
|
|
27
|
+
const buildClaimLostOutcome = (job, payload, elapsedMs, attempt) => buildFailedOutcome({
|
|
28
|
+
job,
|
|
29
|
+
runKey: payload.runKey,
|
|
30
|
+
trigger: payload.trigger,
|
|
31
|
+
elapsedMs,
|
|
32
|
+
attempt,
|
|
33
|
+
errorMessage: RUN_CLAIM_LOST_MESSAGE,
|
|
34
|
+
isDefect: false,
|
|
35
|
+
interrupted: true,
|
|
36
|
+
errorTag: RUN_CLAIM_LOST_TAG,
|
|
37
|
+
retryAfterSeconds: void 0
|
|
38
|
+
});
|
|
39
|
+
/**
|
|
40
|
+
* Records metrics and the request's terminal status when workflow param decoding fails.
|
|
41
|
+
*/
|
|
42
|
+
const settleInvalidParams = (job, payload, errorTag, errorMessage) => {
|
|
43
|
+
const outcome = buildFailedOutcome({
|
|
44
|
+
job,
|
|
45
|
+
runKey: payload.runKey,
|
|
46
|
+
trigger: payload.trigger,
|
|
47
|
+
elapsedMs: 0,
|
|
48
|
+
attempt: 0,
|
|
49
|
+
errorMessage,
|
|
50
|
+
isDefect: false,
|
|
51
|
+
interrupted: false,
|
|
52
|
+
errorTag,
|
|
53
|
+
retryAfterSeconds: void 0
|
|
54
|
+
});
|
|
55
|
+
return Activity.make({
|
|
56
|
+
name: "settle-invalid-params",
|
|
57
|
+
execute: finishRequestIfPresent(payload.requestId, payload.runKey, outcome).pipe(Effect.andThen(recordJobRunMetrics({
|
|
58
|
+
job,
|
|
59
|
+
status: "failed",
|
|
60
|
+
trigger: payload.trigger,
|
|
61
|
+
elapsedMs: 0,
|
|
62
|
+
leaseLost: false
|
|
63
|
+
})))
|
|
64
|
+
}).pipe(Effect.as(outcome));
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Settles a crash-looping workflow once its same-`executionId` resume count exceeds
|
|
68
|
+
* `policy.retry.maxCrashAttempts`.
|
|
69
|
+
*/
|
|
70
|
+
const settleCrashCap = (params) => {
|
|
71
|
+
const crashMessage = maxCrashAttemptsMessage(params.runs.policy.retry.maxCrashAttempts);
|
|
72
|
+
const crashOutcome = buildFailedOutcome({
|
|
73
|
+
job: params.definition.name,
|
|
74
|
+
runKey: params.payload.runKey,
|
|
75
|
+
trigger: params.payload.trigger,
|
|
76
|
+
elapsedMs: 0,
|
|
77
|
+
attempt: params.owned.attempt,
|
|
78
|
+
errorMessage: crashMessage,
|
|
79
|
+
isDefect: true,
|
|
80
|
+
interrupted: false,
|
|
81
|
+
errorTag: MAX_CRASH_ATTEMPTS_TAG,
|
|
82
|
+
retryAfterSeconds: void 0
|
|
83
|
+
});
|
|
84
|
+
return Activity.make({
|
|
85
|
+
name: `settle-crash-cap-${String(params.round)}`,
|
|
86
|
+
execute: Effect.gen(function* () {
|
|
87
|
+
yield* settleOrLogLost(params.runs, params.owned, {
|
|
88
|
+
_tag: "Failed",
|
|
89
|
+
errorMessage: crashMessage,
|
|
90
|
+
reason: "crash-cap",
|
|
91
|
+
cadence: params.definition.cadence._tag,
|
|
92
|
+
trigger: params.payload.trigger,
|
|
93
|
+
annotations: annotationsOf(params.definition),
|
|
94
|
+
nextAttemptAtOverride: null
|
|
95
|
+
});
|
|
96
|
+
yield* recordJobRunMetrics({
|
|
97
|
+
job: params.definition.name,
|
|
98
|
+
status: "failed",
|
|
99
|
+
trigger: params.payload.trigger,
|
|
100
|
+
elapsedMs: 0,
|
|
101
|
+
leaseLost: false
|
|
102
|
+
});
|
|
103
|
+
yield* finishRequestIfPresent(params.payload.requestId, params.payload.runKey, crashOutcome);
|
|
104
|
+
})
|
|
105
|
+
}).pipe(Effect.as(crashOutcome));
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* Runs the `settle-completed-N` durable activity after a job body finishes successfully. A settle
|
|
109
|
+
* that still fails after the short retry counts as not settled (`RunClaimLost`); `settled` tells
|
|
110
|
+
* the caller whether the completion was written.
|
|
111
|
+
*/
|
|
112
|
+
const settleCompletedRound = Effect.fnUntraced(function* (params) {
|
|
113
|
+
/**
|
|
114
|
+
* Converts a `settle` result into the matching completed or claim-lost `WorkflowJobOutcome`.
|
|
115
|
+
*/
|
|
116
|
+
const outcomeFor = (settled, elapsedMs) => settled ? {
|
|
117
|
+
job: params.definition.name,
|
|
118
|
+
runKey: params.payload.runKey,
|
|
119
|
+
trigger: params.payload.trigger,
|
|
120
|
+
elapsedMs,
|
|
121
|
+
status: "completed",
|
|
122
|
+
attempt: params.owned.attempt,
|
|
123
|
+
dryRun: false,
|
|
124
|
+
stats: params.encodedStats
|
|
125
|
+
} : buildClaimLostOutcome(params.definition.name, params.payload, elapsedMs, params.owned.attempt);
|
|
126
|
+
const settledInfo = yield* Activity.make({
|
|
127
|
+
name: `settle-completed-${String(params.round)}`,
|
|
128
|
+
success: SettleActivityResult,
|
|
129
|
+
execute: Effect.gen(function* () {
|
|
130
|
+
const settled = yield* settleOrLogLost(params.runs, params.owned, {
|
|
131
|
+
_tag: "Completed",
|
|
132
|
+
stats: params.encodedStats,
|
|
133
|
+
trigger: params.payload.trigger,
|
|
134
|
+
annotations: annotationsOf(params.definition)
|
|
135
|
+
});
|
|
136
|
+
const elapsedMs = yield* elapsedMillisSince(params.startedMs);
|
|
137
|
+
const outcome = outcomeFor(settled, elapsedMs);
|
|
138
|
+
yield* recordJobRunMetrics({
|
|
139
|
+
job: params.definition.name,
|
|
140
|
+
status: outcome.status,
|
|
141
|
+
trigger: params.payload.trigger,
|
|
142
|
+
elapsedMs,
|
|
143
|
+
leaseLost: !settled
|
|
144
|
+
});
|
|
145
|
+
yield* finishRequestIfPresent(params.payload.requestId, params.payload.runKey, outcome);
|
|
146
|
+
return {
|
|
147
|
+
settled,
|
|
148
|
+
elapsedMs
|
|
149
|
+
};
|
|
150
|
+
})
|
|
151
|
+
});
|
|
152
|
+
return {
|
|
153
|
+
settled: settledInfo.settled,
|
|
154
|
+
outcome: outcomeFor(settledInfo.settled, settledInfo.elapsedMs)
|
|
155
|
+
};
|
|
156
|
+
});
|
|
157
|
+
/**
|
|
158
|
+
* `next_attempt_at` a failed round writes: the wake-up of its durable retry; `null` when a
|
|
159
|
+
* scheduled `Daily` or `OnDemand` workflow gives the key up, so the row reads exhausted too;
|
|
160
|
+
* otherwise `undefined`, leaving the ledger's own retry rules. The ledger keeps `null` whenever its
|
|
161
|
+
* rules say exhausted.
|
|
162
|
+
*/
|
|
163
|
+
const nextAttemptOverrideFor = (retrySleep, now, params) => {
|
|
164
|
+
if (retrySleep !== void 0) return DateTime.toDateUtc(DateTime.addDuration(now, retrySleep));
|
|
165
|
+
return params.payload.trigger === "schedule" && (params.definition.cadence._tag === "Daily" || params.definition.cadence._tag === "OnDemand") ? null : void 0;
|
|
166
|
+
};
|
|
167
|
+
/**
|
|
168
|
+
* Runs the `settle-failed-N` durable activity after a failed round and returns either `undefined`
|
|
169
|
+
* (after durably sleeping for the next retry) or the terminal `failed` outcome.
|
|
170
|
+
*/
|
|
171
|
+
const settleFailedRound = Effect.fnUntraced(function* (params) {
|
|
172
|
+
const failure = analyzeFailureExit(params.definition, params.payload.trigger, params.cause);
|
|
173
|
+
const nextFailureCount = failureCountAfter(params, failure.interrupted);
|
|
174
|
+
const retrySleep = scheduledRetrySleepFor(params.runs.policy.retry, {
|
|
175
|
+
cadence: params.definition.cadence,
|
|
176
|
+
trigger: params.payload.trigger,
|
|
177
|
+
failureCount: nextFailureCount
|
|
178
|
+
});
|
|
179
|
+
/**
|
|
180
|
+
* Converts a `settle` result into the matching failed or claim-lost `WorkflowJobOutcome`.
|
|
181
|
+
*/
|
|
182
|
+
const outcomeFor = (settled, elapsedMs) => settled ? buildFailedOutcome({
|
|
183
|
+
job: params.definition.name,
|
|
184
|
+
runKey: params.payload.runKey,
|
|
185
|
+
trigger: params.payload.trigger,
|
|
186
|
+
elapsedMs,
|
|
187
|
+
attempt: params.owned.attempt,
|
|
188
|
+
errorMessage: failure.errorMessage,
|
|
189
|
+
isDefect: failure.isDefect,
|
|
190
|
+
interrupted: failure.interrupted,
|
|
191
|
+
errorTag: failure.errorTag,
|
|
192
|
+
retryAfterSeconds: failure.retryAfterSeconds
|
|
193
|
+
}) : buildClaimLostOutcome(params.definition.name, params.payload, elapsedMs, params.owned.attempt);
|
|
194
|
+
const settledInfo = yield* Activity.make({
|
|
195
|
+
name: `settle-failed-${String(params.round)}`,
|
|
196
|
+
success: SettleActivityResult,
|
|
197
|
+
execute: Effect.gen(function* () {
|
|
198
|
+
const now = yield* DateTime.now;
|
|
199
|
+
const nowMs = DateTime.toEpochMillis(now);
|
|
200
|
+
const elapsedMs = Math.max(0, nowMs - params.startedMs);
|
|
201
|
+
const retries = retrySleep !== void 0 && isRetryBeforeDeadline(params.definition, params.payload.runKey, nowMs + Duration.toMillis(retrySleep));
|
|
202
|
+
const result = {
|
|
203
|
+
...failure.runResult,
|
|
204
|
+
nextAttemptAtOverride: nextAttemptOverrideFor(retries ? retrySleep : void 0, now, params)
|
|
205
|
+
};
|
|
206
|
+
const settled = yield* settleOrLogLost(params.runs, params.owned, result);
|
|
207
|
+
yield* recordJobRunMetrics({
|
|
208
|
+
job: params.definition.name,
|
|
209
|
+
status: "failed",
|
|
210
|
+
trigger: params.payload.trigger,
|
|
211
|
+
elapsedMs,
|
|
212
|
+
leaseLost: !settled || failure.isRunClaimLost
|
|
213
|
+
});
|
|
214
|
+
if (!retries) yield* finishRequestIfPresent(params.payload.requestId, params.payload.runKey, outcomeFor(settled, elapsedMs));
|
|
215
|
+
return {
|
|
216
|
+
settled,
|
|
217
|
+
elapsedMs,
|
|
218
|
+
retries
|
|
219
|
+
};
|
|
220
|
+
})
|
|
221
|
+
});
|
|
222
|
+
if (retrySleep !== void 0 && (settledInfo.retries ?? true)) {
|
|
223
|
+
yield* sleepUntilInstant(`retry-backoff-${String(params.round)}`, params.startedMs + settledInfo.elapsedMs + Duration.toMillis(retrySleep));
|
|
224
|
+
return {
|
|
225
|
+
outcome: void 0,
|
|
226
|
+
failureCount: nextFailureCount
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
return {
|
|
230
|
+
outcome: outcomeFor(settledInfo.settled, settledInfo.elapsedMs),
|
|
231
|
+
failureCount: nextFailureCount
|
|
232
|
+
};
|
|
233
|
+
});
|
|
234
|
+
export { isReplayedRoundOver, settleCompletedRound, settleCrashCap, settleFailedRound, settleInvalidParams };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { AnyJobDefinition, JobDefinition } from "./job.js";
|
|
2
|
+
import { JobRuns } from "./ledger.js";
|
|
3
|
+
import { JobOutcomeSchema, JobWorkflow, JobWorkflowPayload, MAX_CRASH_ATTEMPTS_TAG, OperatorJobParams, WorkerJobParams, WorkflowJobOutcome, WorkflowParamOverrides, makeJobWorkflow, maxCrashAttemptsMessage } from "./workflow-schema.js";
|
|
4
|
+
import { DispatchApiJobWorkflowOptions, DispatchJobOptions, DispatchedApiJobWorkflow, DispatchedJob, dispatchApiJobWorkflow, dispatchJob } from "./dispatch.js";
|
|
5
|
+
import { Layer } from "effect";
|
|
6
|
+
import { SecureRandom } from "effect/crypto";
|
|
7
|
+
import { WorkflowEngine } from "effect/workflow";
|
|
8
|
+
/**
|
|
9
|
+
* Builds the Effect `Layer` registering the durable workflow handler for one `JobDefinition`.
|
|
10
|
+
*/
|
|
11
|
+
export declare const makeJobWorkflowLayer: <Name extends string, P, S, E, R, PE>(definition: JobDefinition<Name, P, S, E, R, PE>) => Layer.Layer<never, never, R | JobRuns | WorkflowEngine.WorkflowEngine | SecureRandom.SecureRandom>;
|
|
12
|
+
/**
|
|
13
|
+
* Registers the durable workflow handler layer for a type-erased `AnyJobDefinition<R>` through its
|
|
14
|
+
* rank-2 `JOB_CONTINUATION`, avoiding casts.
|
|
15
|
+
*/
|
|
16
|
+
export declare const makeAnyJobWorkflowLayer: <R>(definition: AnyJobDefinition<R>) => Layer.Layer<never, never, R | JobRuns | WorkflowEngine.WorkflowEngine | SecureRandom.SecureRandom>;
|
|
17
|
+
export { type DispatchApiJobWorkflowOptions, type DispatchJobOptions, type DispatchedApiJobWorkflow, type DispatchedJob, JobOutcomeSchema, type JobWorkflow, JobWorkflowPayload, MAX_CRASH_ATTEMPTS_TAG, type OperatorJobParams, WorkerJobParams, type WorkflowJobOutcome, type WorkflowParamOverrides, dispatchApiJobWorkflow, dispatchJob, makeJobWorkflow, maxCrashAttemptsMessage };
|