@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,227 @@
|
|
|
1
|
+
import { recordJobRunMetrics } from "./metrics.js";
|
|
2
|
+
import { omitUndefined } from "./omit-undefined.js";
|
|
3
|
+
import { JobRequests } from "./requests.js";
|
|
4
|
+
import { annotationsOf, retryTransientSql, settleBudgetFor, settleOrLogLost } from "./run-support.js";
|
|
5
|
+
import { isRetryBeforeDeadline } from "./workflow-retry.js";
|
|
6
|
+
import { ClaimActivityResult, INTERRUPTED_WORKFLOW_MESSAGE, buildFailedOutcome, claimToSkipReason, encodeRunClaim } from "./workflow-schema.js";
|
|
7
|
+
import { Cause, Clock, DateTime, Duration, Effect, Exit, Option, Schema } from "effect";
|
|
8
|
+
import { describeError, logInfo, logWarning } from "@yieldkit/logger";
|
|
9
|
+
import { Activity, DurableClock, Workflow } from "effect/workflow";
|
|
10
|
+
// src/workflow-activities.ts
|
|
11
|
+
/**
|
|
12
|
+
* Shortest durable sleep before reclaiming a `RetryLater` key, so a retry instant that is already
|
|
13
|
+
* due (or skewed into the past) still yields one second instead of spinning.
|
|
14
|
+
*/
|
|
15
|
+
const MIN_RETRY_LATER_WAIT_MS = 1e3;
|
|
16
|
+
/**
|
|
17
|
+
* Returns `true` when scheduled runs of `cadence` wait durably across `Busy`/`RetryLater` claims:
|
|
18
|
+
* `Daily`, automatic `Once` and dispatched `OnDemand` runs.
|
|
19
|
+
*/
|
|
20
|
+
const isScheduledDurableCadence = (cadence, trigger) => trigger === "schedule" && (cadence._tag === "Daily" || cadence._tag === "OnDemand" || cadence._tag === "Once" && cadence.start === "automatic");
|
|
21
|
+
/**
|
|
22
|
+
* Records the request's terminal outcome with `JobRequests.markFinished` when `requestId` is set.
|
|
23
|
+
* Skipped when no `JobRequests` is provided.
|
|
24
|
+
*/
|
|
25
|
+
const finishRequestIfPresent = Effect.fnUntraced(function* (requestId, runKey, outcome) {
|
|
26
|
+
if (requestId === null) return;
|
|
27
|
+
const maybeRequests = yield* Effect.serviceOption(JobRequests);
|
|
28
|
+
if (Option.isNone(maybeRequests)) return;
|
|
29
|
+
yield* maybeRequests.value.markFinished({
|
|
30
|
+
id: requestId,
|
|
31
|
+
runKey,
|
|
32
|
+
outcome
|
|
33
|
+
}).pipe(retryTransientSql, Effect.catch((error) => logWarning("worker.request.finish_failed", {
|
|
34
|
+
requestId,
|
|
35
|
+
runKey,
|
|
36
|
+
errorMessage: describeError(error)
|
|
37
|
+
})));
|
|
38
|
+
});
|
|
39
|
+
/**
|
|
40
|
+
* Runs the `claim-round-N` durable activity: marks the request as started and claims `(job,
|
|
41
|
+
* runKey)` in the ledger with our `executionId`. A scheduled run of a `Daily` job past its `until`
|
|
42
|
+
* claims with `pastDeadline`, so it never takes the key and a failed row reads exhausted; each
|
|
43
|
+
* claim attempt reads the clock again to decide it, and the claim reply that results is journaled.
|
|
44
|
+
* A claim that still fails after the short retry is logged as `job.claim.failed` and reported as
|
|
45
|
+
* `RetryLater` in `busyDelay`, never stored as a defect. `replayed` is `true` when the claim reply
|
|
46
|
+
* came from the workflow's journal instead of a claim made now.
|
|
47
|
+
*/
|
|
48
|
+
const runClaimRoundActivity = (params) => {
|
|
49
|
+
let executed = false;
|
|
50
|
+
return Activity.make({
|
|
51
|
+
name: `claim-round-${String(params.round)}`,
|
|
52
|
+
success: ClaimActivityResult,
|
|
53
|
+
execute: Effect.gen(function* () {
|
|
54
|
+
executed = true;
|
|
55
|
+
const startedMs = yield* Clock.currentTimeMillis;
|
|
56
|
+
const job = params.definition.name;
|
|
57
|
+
if (params.payload.requestId !== null) {
|
|
58
|
+
const maybeRequests = yield* Effect.serviceOption(JobRequests);
|
|
59
|
+
if (Option.isSome(maybeRequests)) yield* maybeRequests.value.upsertStarted({
|
|
60
|
+
id: params.payload.requestId,
|
|
61
|
+
job,
|
|
62
|
+
params: params.payload.params,
|
|
63
|
+
force: params.payload.force,
|
|
64
|
+
executionId: params.executionId,
|
|
65
|
+
runKey: params.payload.runKey
|
|
66
|
+
}).pipe(retryTransientSql, Effect.catch((error) => logWarning("worker.request.start_failed", {
|
|
67
|
+
requestId: params.payload.requestId,
|
|
68
|
+
runKey: params.payload.runKey,
|
|
69
|
+
errorMessage: describeError(error)
|
|
70
|
+
})));
|
|
71
|
+
}
|
|
72
|
+
let claimCalls = 0;
|
|
73
|
+
const claim = yield* Effect.gen(function* () {
|
|
74
|
+
claimCalls += 1;
|
|
75
|
+
const claimMs = yield* Clock.currentTimeMillis;
|
|
76
|
+
const pastDeadline = params.payload.trigger === "schedule" && !isRetryBeforeDeadline(params.definition, params.payload.runKey, claimMs);
|
|
77
|
+
return yield* params.runs.claim({
|
|
78
|
+
job,
|
|
79
|
+
runKey: params.payload.runKey,
|
|
80
|
+
trigger: params.payload.trigger,
|
|
81
|
+
force: params.force,
|
|
82
|
+
params: params.encodedParams,
|
|
83
|
+
executionId: params.executionId,
|
|
84
|
+
...omitUndefined({ pastDeadline: pastDeadline ? true : void 0 })
|
|
85
|
+
});
|
|
86
|
+
}).pipe(retryTransientSql, Effect.catch((error) => logWarning("job.claim.failed", {
|
|
87
|
+
job,
|
|
88
|
+
runKey: params.payload.runKey,
|
|
89
|
+
errorMessage: describeError(error)
|
|
90
|
+
}).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map((failedMs) => ({
|
|
91
|
+
_tag: "RetryLater",
|
|
92
|
+
at: new Date(failedMs + Duration.toMillis(params.runs.policy.retry.busyDelay))
|
|
93
|
+
})))));
|
|
94
|
+
return encodeRunClaim(claim, startedMs, claimCalls - 1);
|
|
95
|
+
})
|
|
96
|
+
}).pipe(Effect.map((claim) => ({
|
|
97
|
+
claim,
|
|
98
|
+
replayed: !executed
|
|
99
|
+
})));
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Handles a non-acquired claim: either sleeps durably via `DurableClock.sleep` and signals the
|
|
103
|
+
* caller to retry (`undefined`), or settles the workflow as `skipped`. The `job.skipped` line
|
|
104
|
+
* carries the job's `logFields`, which never override its own fields.
|
|
105
|
+
*/
|
|
106
|
+
const handleNonAcquiredClaim = Effect.fnUntraced(function* (params) {
|
|
107
|
+
const durableSchedule = isScheduledDurableCadence(params.cadence, params.payload.trigger);
|
|
108
|
+
if (durableSchedule && params.claimResult._tag === "Busy") {
|
|
109
|
+
const nextBusyRetries = params.busyRetries + 1;
|
|
110
|
+
if (params.cadence._tag === "Once" || nextBusyRetries <= params.retry.busyMaxRetries) {
|
|
111
|
+
yield* DurableClock.sleep({
|
|
112
|
+
name: `busy-backoff-${String(params.round)}`,
|
|
113
|
+
duration: params.retry.busyDelay
|
|
114
|
+
});
|
|
115
|
+
return {
|
|
116
|
+
outcome: void 0,
|
|
117
|
+
busyRetries: nextBusyRetries
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (durableSchedule && params.claimResult._tag === "RetryLater") {
|
|
122
|
+
const nowMs = yield* Activity.make({
|
|
123
|
+
name: `retry-later-clock-${String(params.round)}`,
|
|
124
|
+
success: Schema.Finite,
|
|
125
|
+
execute: Clock.currentTimeMillis
|
|
126
|
+
});
|
|
127
|
+
const waitMs = Math.max(MIN_RETRY_LATER_WAIT_MS, DateTime.toEpochMillis(DateTime.makeUnsafe(params.claimResult.at)) - nowMs);
|
|
128
|
+
yield* DurableClock.sleep({
|
|
129
|
+
name: `retry-later-wait-${String(params.round)}`,
|
|
130
|
+
duration: Duration.millis(waitMs)
|
|
131
|
+
});
|
|
132
|
+
return {
|
|
133
|
+
outcome: void 0,
|
|
134
|
+
busyRetries: params.busyRetries
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
const reason = claimToSkipReason(params.claimResult);
|
|
138
|
+
const skippedOutcome = {
|
|
139
|
+
job: params.job,
|
|
140
|
+
runKey: params.payload.runKey,
|
|
141
|
+
trigger: params.payload.trigger,
|
|
142
|
+
elapsedMs: params.claimResult.elapsedMs,
|
|
143
|
+
status: "skipped",
|
|
144
|
+
reason
|
|
145
|
+
};
|
|
146
|
+
yield* Activity.make({
|
|
147
|
+
name: `settle-skipped-${String(params.round)}`,
|
|
148
|
+
execute: Effect.gen(function* () {
|
|
149
|
+
yield* logInfo("job.skipped", {
|
|
150
|
+
...params.logFields,
|
|
151
|
+
job: params.job,
|
|
152
|
+
runKey: params.payload.runKey,
|
|
153
|
+
trigger: params.payload.trigger,
|
|
154
|
+
status: "skipped",
|
|
155
|
+
skipReason: reason._tag,
|
|
156
|
+
retryAt: reason._tag === "RetryLater" ? reason.at : void 0
|
|
157
|
+
});
|
|
158
|
+
yield* recordJobRunMetrics({
|
|
159
|
+
job: params.job,
|
|
160
|
+
status: "skipped",
|
|
161
|
+
trigger: params.payload.trigger,
|
|
162
|
+
elapsedMs: params.claimResult.elapsedMs,
|
|
163
|
+
leaseLost: false
|
|
164
|
+
});
|
|
165
|
+
yield* finishRequestIfPresent(params.payload.requestId, params.payload.runKey, skippedOutcome);
|
|
166
|
+
})
|
|
167
|
+
});
|
|
168
|
+
return {
|
|
169
|
+
outcome: skippedOutcome,
|
|
170
|
+
busyRetries: params.busyRetries
|
|
171
|
+
};
|
|
172
|
+
});
|
|
173
|
+
/**
|
|
174
|
+
* Registers the explicit-interrupt workflow finalizer. Ignores terminal completions and superseded
|
|
175
|
+
* `Exit.void` exits so abandoned runs never change the ledger.
|
|
176
|
+
*/
|
|
177
|
+
const registerInterruptFinalizer = (params) => Workflow.addFinalizer((exit) => Effect.gen(function* () {
|
|
178
|
+
if (params.state.terminalSettled || Exit.isSuccess(exit) || !Cause.hasInterruptsOnly(exit.cause)) return;
|
|
179
|
+
const owned = params.state.activeOwned;
|
|
180
|
+
if (owned !== void 0) yield* settleOrLogLost(params.runs, owned, {
|
|
181
|
+
_tag: "Failed",
|
|
182
|
+
errorMessage: INTERRUPTED_WORKFLOW_MESSAGE,
|
|
183
|
+
reason: "interrupted",
|
|
184
|
+
cadence: params.definition.cadence._tag,
|
|
185
|
+
...settleBudgetFor(params.definition.cadence),
|
|
186
|
+
trigger: params.payload.trigger,
|
|
187
|
+
annotations: annotationsOf(params.definition)
|
|
188
|
+
});
|
|
189
|
+
const interruptedOutcome = buildFailedOutcome({
|
|
190
|
+
job: params.definition.name,
|
|
191
|
+
runKey: params.payload.runKey,
|
|
192
|
+
trigger: params.payload.trigger,
|
|
193
|
+
elapsedMs: 0,
|
|
194
|
+
attempt: owned?.attempt ?? 0,
|
|
195
|
+
errorMessage: INTERRUPTED_WORKFLOW_MESSAGE,
|
|
196
|
+
isDefect: false,
|
|
197
|
+
interrupted: true,
|
|
198
|
+
errorTag: "Interrupted",
|
|
199
|
+
retryAfterSeconds: void 0
|
|
200
|
+
});
|
|
201
|
+
yield* finishRequestIfPresent(params.payload.requestId, params.payload.runKey, interruptedOutcome);
|
|
202
|
+
}));
|
|
203
|
+
/**
|
|
204
|
+
* Sleeps durably on the clock `name` until the epoch millisecond `atMs`, at once when it has
|
|
205
|
+
* passed. The time left is read from the clock, not journaled, so a replay waits only for what is
|
|
206
|
+
* left (the engine keeps the first wake-up of a clock it already scheduled) and skips the wait once
|
|
207
|
+
* `atMs` is past; either way the workflow goes on to the same next step.
|
|
208
|
+
*/
|
|
209
|
+
const sleepUntilInstant = Effect.fnUntraced(function* (name, atMs) {
|
|
210
|
+
const waitMs = atMs - (yield* Clock.currentTimeMillis);
|
|
211
|
+
if (waitMs > 0) yield* DurableClock.sleep({
|
|
212
|
+
name,
|
|
213
|
+
duration: Duration.millis(waitMs)
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
/**
|
|
217
|
+
* Waits durably until `runAt` (ISO-8601) before the first claim of a delayed `dispatchJob` run, on
|
|
218
|
+
* the clock `run-at-<epoch ms of runAt>`. The name changes with every dispatch, so the processed
|
|
219
|
+
* clock of an earlier run of the same key, which Cluster may keep longer than the workflow, cannot
|
|
220
|
+
* swallow the wake-up. A crash during the wait resumes it for the time left only.
|
|
221
|
+
*/
|
|
222
|
+
const waitUntilRunAt = Effect.fnUntraced(function* (runAt) {
|
|
223
|
+
const runAtMs = Date.parse(runAt);
|
|
224
|
+
if (!Number.isFinite(runAtMs)) return yield* Effect.die(/* @__PURE__ */ new Error(`runAt "${runAt}" is not an ISO-8601 instant.`));
|
|
225
|
+
return yield* sleepUntilInstant(`run-at-${String(runAtMs)}`, runAtMs);
|
|
226
|
+
});
|
|
227
|
+
export { finishRequestIfPresent, handleNonAcquiredClaim, registerInterruptFinalizer, runClaimRoundActivity, sleepUntilInstant, waitUntilRunAt };
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { dailyScheduleFor, failureBudgetFor, isWithinDailyDeadline } from "./calendar.js";
|
|
2
|
+
import { onDemandRetryDelay, onceRetryDelay } from "./policy.js";
|
|
3
|
+
import { Clock, Duration, Effect, Result, Schema } from "effect";
|
|
4
|
+
import { Activity, DurableClock } from "effect/workflow";
|
|
5
|
+
// src/workflow-retry.ts
|
|
6
|
+
/**
|
|
7
|
+
* Computes the durable sleep duration before the next scheduled retry round, or `undefined` when
|
|
8
|
+
* the failure is terminal. `failureCount` counts failed rounds of this execution, lost leases
|
|
9
|
+
* included.
|
|
10
|
+
*/
|
|
11
|
+
const scheduledRetrySleepFor = (retry, failure) => {
|
|
12
|
+
const { cadence, trigger, failureCount } = failure;
|
|
13
|
+
if (trigger !== "schedule") return;
|
|
14
|
+
switch (cadence._tag) {
|
|
15
|
+
case "Daily": return failureCount < (failureBudgetFor(cadence) ?? retry.dailyMaxFailures) ? Duration.fromInputUnsafe(cadence.checkEvery ?? "1 hour") : void 0;
|
|
16
|
+
case "Once": return cadence.start === "automatic" ? onceRetryDelay(retry, failureCount) : void 0;
|
|
17
|
+
case "OnDemand": return failureCount < retry.onDemandMaxFailures ? onDemandRetryDelay(retry, failureCount) : void 0;
|
|
18
|
+
case "Every":
|
|
19
|
+
case "Cron": return;
|
|
20
|
+
default: return cadence;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Failure count of the round that just failed, which sizes its retry: one more than the workflow's
|
|
25
|
+
* own count, or for `OnDemand` the key's count in the ledger when that is higher (failures of
|
|
26
|
+
* `manual` runs included), so the workflow sleeps exactly until the `next_attempt_at` the ledger
|
|
27
|
+
* stores. `failureCount` is the workflow's count before this round, `priorFailures` the key's count
|
|
28
|
+
* at claim time (missing from older journals).
|
|
29
|
+
*/
|
|
30
|
+
const failureCountAfter = (round, interrupted) => {
|
|
31
|
+
const local = round.failureCount + 1;
|
|
32
|
+
if (round.definition.cadence._tag !== "OnDemand" || round.priorFailures === void 0) return local;
|
|
33
|
+
return Math.max(local, round.priorFailures + (interrupted ? 0 : 1));
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Whether a retry of `runKey` starting at `startMs` is still allowed: always, except for a `Daily`
|
|
37
|
+
* job with a deadline, whose retries must start on the run's local date at or before `until`.
|
|
38
|
+
*/
|
|
39
|
+
const isRetryBeforeDeadline = (definition, runKey, startMs) => {
|
|
40
|
+
const { cadence } = definition;
|
|
41
|
+
if (cadence._tag !== "Daily") return true;
|
|
42
|
+
const schedule = dailyScheduleFor(definition.name, cadence);
|
|
43
|
+
return Result.isFailure(schedule) || isWithinDailyDeadline(schedule.success, runKey, startMs);
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Whether `definition` has a retry deadline (a `Daily` cadence with `at`, `window` or `until`).
|
|
47
|
+
*/
|
|
48
|
+
const hasRetryDeadline = (definition) => failureBudgetFor(definition.cadence) !== void 0;
|
|
49
|
+
/**
|
|
50
|
+
* For a round that ended without a settle of its own (its claim was lost, or its completion could
|
|
51
|
+
* not be written): when a scheduled retry applies, counts the round as failed, sleeps
|
|
52
|
+
* `retry-backoff-N` (at once when the journal holds that sleep) and returns `true`, so the caller
|
|
53
|
+
* goes on to the next round. Returns `false` when no retry applies.
|
|
54
|
+
*/
|
|
55
|
+
const sleepForScheduledRetry = Effect.fnUntraced(function* (args) {
|
|
56
|
+
const failureCount = failureCountAfter({
|
|
57
|
+
...args,
|
|
58
|
+
failureCount: args.counters.failureCount
|
|
59
|
+
}, false);
|
|
60
|
+
const retrySleep = scheduledRetrySleepFor(args.runs.policy.retry, {
|
|
61
|
+
cadence: args.definition.cadence,
|
|
62
|
+
trigger: args.payload.trigger,
|
|
63
|
+
failureCount
|
|
64
|
+
});
|
|
65
|
+
if (retrySleep === void 0) return false;
|
|
66
|
+
if (hasRetryDeadline(args.definition)) {
|
|
67
|
+
if (!(yield* Activity.make({
|
|
68
|
+
name: `retry-deadline-${String(args.round)}`,
|
|
69
|
+
success: Schema.Boolean,
|
|
70
|
+
execute: Clock.currentTimeMillis.pipe(Effect.map((nowMs) => isRetryBeforeDeadline(args.definition, args.payload.runKey, nowMs + Duration.toMillis(retrySleep))))
|
|
71
|
+
}))) return false;
|
|
72
|
+
}
|
|
73
|
+
args.counters.failureCount = failureCount;
|
|
74
|
+
yield* DurableClock.sleep({
|
|
75
|
+
name: `retry-backoff-${String(args.round)}`,
|
|
76
|
+
duration: retrySleep
|
|
77
|
+
});
|
|
78
|
+
return true;
|
|
79
|
+
});
|
|
80
|
+
export { failureCountAfter, isRetryBeforeDeadline, scheduledRetrySleepFor, sleepForScheduledRetry };
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { AnyJobDefinition } from "./job.js";
|
|
2
|
+
import "./ledger-types.js";
|
|
3
|
+
import "./run.js";
|
|
4
|
+
import { Context, Layer, Schema } from "effect";
|
|
5
|
+
import { Workflow } from "effect/workflow";
|
|
6
|
+
/**
|
|
7
|
+
* Parameter overrides passed to a single job workflow. Values are JSON because they travel inside
|
|
8
|
+
* the persisted workflow payload; each job's `params.schema` validates them before claiming.
|
|
9
|
+
*/
|
|
10
|
+
export type WorkflowParamOverrides = {
|
|
11
|
+
readonly [key: string]: Schema.Json;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Operator param overrides configured on the worker (the scheduler's `params`), keyed by job name.
|
|
15
|
+
*/
|
|
16
|
+
export type OperatorJobParams = Readonly<Record<string, WorkflowParamOverrides>>;
|
|
17
|
+
declare const WorkerJobParams_base: Context.ServiceClass<WorkerJobParams, "@yieldkit/jobs/WorkerJobParams", Readonly<Record<string, WorkflowParamOverrides>>>;
|
|
18
|
+
/**
|
|
19
|
+
* Context service carrying the worker's operator params into durable workflow handlers. Defaults to
|
|
20
|
+
* an empty map when not provided.
|
|
21
|
+
*/
|
|
22
|
+
export declare class WorkerJobParams extends WorkerJobParams_base {
|
|
23
|
+
/**
|
|
24
|
+
* Layer supplying `params` to workflow handlers.
|
|
25
|
+
*/
|
|
26
|
+
static readonly layer: (params?: OperatorJobParams) => Layer.Layer<WorkerJobParams>;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Serializable payload of every job `Workflow`. Its field names are persisted in Cluster messages.
|
|
30
|
+
*/
|
|
31
|
+
export declare const JobWorkflowPayload: Schema.Struct<{
|
|
32
|
+
/**
|
|
33
|
+
* Ledger run key (`YYYY-MM-DD`, `YYYY-MM-DDTHH:MMZ`, `'once'`, or an `OnDemand` caller's key).
|
|
34
|
+
*/
|
|
35
|
+
readonly runKey: Schema.String;
|
|
36
|
+
/**
|
|
37
|
+
* How this execution was started.
|
|
38
|
+
*/
|
|
39
|
+
readonly trigger: Schema.Literals<readonly ["schedule", "manual", "api"]>;
|
|
40
|
+
/**
|
|
41
|
+
* Caller parameter overrides (re-filtered through `apiParams` when `trigger === 'api'`).
|
|
42
|
+
*/
|
|
43
|
+
readonly params: Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>;
|
|
44
|
+
/**
|
|
45
|
+
* Whether a completed `(job, runKey)` row may be re-run.
|
|
46
|
+
*/
|
|
47
|
+
readonly force: Schema.Boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Linked request id when `trigger === 'api'`, else `null`.
|
|
50
|
+
*/
|
|
51
|
+
readonly requestId: Schema.NullOr<Schema.String>;
|
|
52
|
+
/**
|
|
53
|
+
* Optional uniqueness nonce (`requestId` for API runs, a fresh UUID for other forced runs, `null`
|
|
54
|
+
* for idempotent scheduled runs).
|
|
55
|
+
*/
|
|
56
|
+
readonly attemptNonce: Schema.NullOr<Schema.String>;
|
|
57
|
+
/**
|
|
58
|
+
* ISO-8601 UTC instant the run must not start before; the workflow waits durably until then. Set
|
|
59
|
+
* by `dispatchJob` for a delayed run, missing otherwise. Any other string fails decoding, so the
|
|
60
|
+
* job never runs without its wait.
|
|
61
|
+
*/
|
|
62
|
+
readonly runAt: Schema.optional<Schema.String>;
|
|
63
|
+
}>;
|
|
64
|
+
/**
|
|
65
|
+
* Decoded `JobWorkflowPayload` type.
|
|
66
|
+
*/
|
|
67
|
+
export type JobWorkflowPayload = typeof JobWorkflowPayload.Type;
|
|
68
|
+
/**
|
|
69
|
+
* Serializable `JobOutcome` schema returned by every job `Workflow`.
|
|
70
|
+
*/
|
|
71
|
+
export declare const JobOutcomeSchema: Schema.Union<readonly [Schema.Struct<{
|
|
72
|
+
/**
|
|
73
|
+
* Registered job name.
|
|
74
|
+
*/
|
|
75
|
+
readonly job: Schema.String;
|
|
76
|
+
/**
|
|
77
|
+
* Deterministic cadence key executed by this workflow.
|
|
78
|
+
*/
|
|
79
|
+
readonly runKey: Schema.String;
|
|
80
|
+
/**
|
|
81
|
+
* How the run was started.
|
|
82
|
+
*/
|
|
83
|
+
readonly trigger: Schema.Literals<readonly ["schedule", "manual", "api"]>;
|
|
84
|
+
/**
|
|
85
|
+
* Elapsed duration in milliseconds measured via the Effect clock.
|
|
86
|
+
*/
|
|
87
|
+
readonly elapsedMs: Schema.Finite;
|
|
88
|
+
/**
|
|
89
|
+
* Terminal status discriminant for completed runs.
|
|
90
|
+
*/
|
|
91
|
+
readonly status: Schema.Literal<"completed">;
|
|
92
|
+
/**
|
|
93
|
+
* 1-based attempt number recorded in the ledger.
|
|
94
|
+
*/
|
|
95
|
+
readonly attempt: Schema.Int;
|
|
96
|
+
/**
|
|
97
|
+
* Whether the run executed in dry-run mode (always `false` in cluster workflows).
|
|
98
|
+
*/
|
|
99
|
+
readonly dryRun: Schema.Boolean;
|
|
100
|
+
/**
|
|
101
|
+
* Schema-encoded completion stats returned by the job.
|
|
102
|
+
*/
|
|
103
|
+
readonly stats: Schema.Unknown;
|
|
104
|
+
}>, Schema.Struct<{
|
|
105
|
+
/**
|
|
106
|
+
* Registered job name.
|
|
107
|
+
*/
|
|
108
|
+
readonly job: Schema.String;
|
|
109
|
+
/**
|
|
110
|
+
* Deterministic cadence key skipped by this workflow.
|
|
111
|
+
*/
|
|
112
|
+
readonly runKey: Schema.String;
|
|
113
|
+
/**
|
|
114
|
+
* How the run was started.
|
|
115
|
+
*/
|
|
116
|
+
readonly trigger: Schema.Literals<readonly ["schedule", "manual", "api"]>;
|
|
117
|
+
/**
|
|
118
|
+
* Elapsed duration in milliseconds measured via the Effect clock.
|
|
119
|
+
*/
|
|
120
|
+
readonly elapsedMs: Schema.Finite;
|
|
121
|
+
/**
|
|
122
|
+
* Terminal status discriminant for skipped runs.
|
|
123
|
+
*/
|
|
124
|
+
readonly status: Schema.Literal<"skipped">;
|
|
125
|
+
/**
|
|
126
|
+
* Structured reason explaining why the run was skipped.
|
|
127
|
+
*/
|
|
128
|
+
readonly reason: Schema.Union<readonly [Schema.TaggedStruct<"AlreadyCompleted", {}>, Schema.TaggedStruct<"Busy", {}>, Schema.TaggedStruct<"RetryLater", {
|
|
129
|
+
/**
|
|
130
|
+
* ISO-8601 UTC timestamp when the key becomes eligible for retry.
|
|
131
|
+
*/
|
|
132
|
+
readonly at: Schema.String;
|
|
133
|
+
}>, Schema.TaggedStruct<"Exhausted", {}>]>;
|
|
134
|
+
}>, Schema.Struct<{
|
|
135
|
+
/**
|
|
136
|
+
* Registered job name.
|
|
137
|
+
*/
|
|
138
|
+
readonly job: Schema.String;
|
|
139
|
+
/**
|
|
140
|
+
* Deterministic cadence key that failed.
|
|
141
|
+
*/
|
|
142
|
+
readonly runKey: Schema.String;
|
|
143
|
+
/**
|
|
144
|
+
* How the run was started.
|
|
145
|
+
*/
|
|
146
|
+
readonly trigger: Schema.Literals<readonly ["schedule", "manual", "api"]>;
|
|
147
|
+
/**
|
|
148
|
+
* Elapsed duration in milliseconds measured via the Effect clock.
|
|
149
|
+
*/
|
|
150
|
+
readonly elapsedMs: Schema.Finite;
|
|
151
|
+
/**
|
|
152
|
+
* Terminal status discriminant for failed runs.
|
|
153
|
+
*/
|
|
154
|
+
readonly status: Schema.Literal<"failed">;
|
|
155
|
+
/**
|
|
156
|
+
* 1-based attempt number recorded in the ledger (`0` for pre-claim failures).
|
|
157
|
+
*/
|
|
158
|
+
readonly attempt: Schema.Int;
|
|
159
|
+
/**
|
|
160
|
+
* Redacted failure summary safe for logs, API responses and Cluster replies.
|
|
161
|
+
*/
|
|
162
|
+
readonly errorMessage: Schema.String;
|
|
163
|
+
/**
|
|
164
|
+
* Whether the failure originated as an unhandled defect.
|
|
165
|
+
*/
|
|
166
|
+
readonly isDefect: Schema.Boolean;
|
|
167
|
+
/**
|
|
168
|
+
* Whether the failure resulted from an interruption or lost lease claim.
|
|
169
|
+
*/
|
|
170
|
+
readonly interrupted: Schema.Boolean;
|
|
171
|
+
/**
|
|
172
|
+
* Optional original `_tag` of the typed domain error.
|
|
173
|
+
*/
|
|
174
|
+
readonly errorTag: Schema.optional<Schema.String>;
|
|
175
|
+
/**
|
|
176
|
+
* Optional `retryAfterSeconds` hint copied from the typed error.
|
|
177
|
+
*/
|
|
178
|
+
readonly retryAfterSeconds: Schema.optional<Schema.Finite>;
|
|
179
|
+
}>]>;
|
|
180
|
+
/**
|
|
181
|
+
* Decoded workflow outcome matching `JobOutcomeSchema`.
|
|
182
|
+
*/
|
|
183
|
+
export type WorkflowJobOutcome = typeof JobOutcomeSchema.Type;
|
|
184
|
+
/**
|
|
185
|
+
* Error tag recorded when the same workflow execution crashes and resumes more than
|
|
186
|
+
* `policy.retry.maxCrashAttempts` times.
|
|
187
|
+
*/
|
|
188
|
+
export declare const MAX_CRASH_ATTEMPTS_TAG = "MaxAttemptsExceeded";
|
|
189
|
+
/**
|
|
190
|
+
* Error message recorded when the same workflow execution crashed and resumed more than
|
|
191
|
+
* `maxCrashAttempts` times.
|
|
192
|
+
*/
|
|
193
|
+
export declare const maxCrashAttemptsMessage: (maxCrashAttempts: number) => string;
|
|
194
|
+
/**
|
|
195
|
+
* Type of the durable Effect `Workflow` constructed for one job.
|
|
196
|
+
*/
|
|
197
|
+
export type JobWorkflow<Name extends string = string> = Workflow.Workflow<Name, typeof JobWorkflowPayload, typeof JobOutcomeSchema, typeof Schema.Never>;
|
|
198
|
+
/**
|
|
199
|
+
* Builds the Effect `Workflow` declaration for `definition`, annotated with its own
|
|
200
|
+
* `ClusterSchema.ShardGroup` (`definition.name`) so workers assigned a subset of the jobs never
|
|
201
|
+
* claim messages of the others. The workflow name and the idempotency key (`runKey`, or
|
|
202
|
+
* `runKey:attemptNonce`) are persisted; changing them orphans in-flight executions.
|
|
203
|
+
*/
|
|
204
|
+
export declare const makeJobWorkflow: <Name extends string>(definition: Pick<AnyJobDefinition, 'name'> & {
|
|
205
|
+
readonly name: Name;
|
|
206
|
+
}) => JobWorkflow<Name>;
|
|
207
|
+
export {};
|