@yieldkit/jobs 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +307 -2
  3. package/dist/_virtual/_rolldown/runtime.js +12 -0
  4. package/dist/activity.d.ts +81 -0
  5. package/dist/activity.js +151 -0
  6. package/dist/calendar.d.ts +33 -0
  7. package/dist/calendar.js +205 -0
  8. package/dist/cluster.d.ts +54 -0
  9. package/dist/cluster.js +115 -0
  10. package/dist/cron.d.ts +21 -0
  11. package/dist/cron.js +80 -0
  12. package/dist/dispatch.d.ts +97 -0
  13. package/dist/dispatch.js +140 -0
  14. package/dist/errors.d.ts +194 -0
  15. package/dist/errors.js +132 -0
  16. package/dist/index.d.ts +22 -0
  17. package/dist/index.js +22 -0
  18. package/dist/job.d.ts +306 -0
  19. package/dist/job.js +45 -0
  20. package/dist/ledger-memory.d.ts +64 -0
  21. package/dist/ledger-memory.js +246 -0
  22. package/dist/ledger-retry.js +21 -0
  23. package/dist/ledger-sql-deadline.js +39 -0
  24. package/dist/ledger-sql.d.ts +5 -0
  25. package/dist/ledger-sql.js +332 -0
  26. package/dist/ledger-types.d.ts +340 -0
  27. package/dist/ledger-types.js +71 -0
  28. package/dist/ledger.d.ts +51 -0
  29. package/dist/ledger.js +66 -0
  30. package/dist/logging.d.ts +83 -0
  31. package/dist/logging.js +117 -0
  32. package/dist/maintenance.d.ts +6 -0
  33. package/dist/maintenance.js +115 -0
  34. package/dist/metrics.d.ts +14 -0
  35. package/dist/metrics.js +35 -0
  36. package/dist/migrations.d.ts +21 -0
  37. package/dist/migrations.js +194 -0
  38. package/dist/omit-undefined.js +10 -0
  39. package/dist/params.d.ts +58 -0
  40. package/dist/params.js +97 -0
  41. package/dist/policy.d.ts +225 -0
  42. package/dist/policy.js +247 -0
  43. package/dist/probe.js +67 -0
  44. package/dist/requests-memory.d.ts +36 -0
  45. package/dist/requests-memory.js +142 -0
  46. package/dist/requests.d.ts +195 -0
  47. package/dist/requests.js +242 -0
  48. package/dist/run-key.d.ts +25 -0
  49. package/dist/run-key.js +85 -0
  50. package/dist/run-support.js +212 -0
  51. package/dist/run.d.ts +163 -0
  52. package/dist/run.js +258 -0
  53. package/dist/scheduler.d.ts +56 -0
  54. package/dist/scheduler.js +227 -0
  55. package/dist/settle-hook.d.ts +3 -0
  56. package/dist/settle-hook.js +33 -0
  57. package/dist/storage-options.d.ts +25 -0
  58. package/dist/storage-options.js +60 -0
  59. package/dist/storage.d.ts +53 -0
  60. package/dist/storage.js +75 -0
  61. package/dist/testing/index.d.ts +4 -0
  62. package/dist/testing/index.js +4 -0
  63. package/dist/time-zone.js +83 -0
  64. package/dist/workflow-activities.js +227 -0
  65. package/dist/workflow-retry.js +80 -0
  66. package/dist/workflow-schema.d.ts +207 -0
  67. package/dist/workflow-schema.js +360 -0
  68. package/dist/workflow-settle.js +234 -0
  69. package/dist/workflow.d.ts +17 -0
  70. package/dist/workflow.js +202 -0
  71. package/docs/deployment.md +167 -0
  72. package/docs/jobs.md +200 -0
  73. package/docs/logs-and-metrics.md +129 -0
  74. package/docs/migrations.md +66 -0
  75. package/docs/policy.md +75 -0
  76. package/docs/scheduling.md +149 -0
  77. package/docs/storage.md +138 -0
  78. package/docs/testing.md +144 -0
  79. package/docs/workers-and-clients.md +100 -0
  80. package/package.json +82 -3
@@ -0,0 +1,212 @@
1
+ import { findJobStageError, findRetryAfterSeconds } from "./activity.js";
2
+ import { dailyScheduleFor, failureBudgetFor } from "./calendar.js";
3
+ import { RUN_CLAIM_LOST_MESSAGE, RUN_CLAIM_LOST_TAG, RunClaimLost } from "./errors.js";
4
+ import { heartbeatIntervalFor } from "./policy.js";
5
+ import { Cause, Clock, Context, Duration, Effect, Result, Schedule, Schema } from "effect";
6
+ import { describeError, extractCauseSummary, logWarning, redactLogString } from "@yieldkit/logger";
7
+ // src/run-support.ts
8
+ /**
9
+ * Resolves the effective `force` flag: implied `true` only for `Every` and `Cron` jobs with
10
+ * non-`schedule` triggers unless explicitly passed by the caller.
11
+ */
12
+ const resolveForce = (cadence, trigger, explicit) => {
13
+ if (explicit !== void 0) return explicit;
14
+ return (cadence._tag === "Every" || cadence._tag === "Cron") && trigger !== "schedule";
15
+ };
16
+ /**
17
+ * Milliseconds elapsed on the Effect `Clock` since `startedMs`, never negative.
18
+ */
19
+ const elapsedMillisSince = (startedMs) => Clock.currentTimeMillis.pipe(Effect.map((nowMs) => Math.max(0, nowMs - startedMs)));
20
+ /**
21
+ * Runs the job body for `ctx` and encodes its stats through `definition.stats`. Callers wrap the
22
+ * result in their logging scope, so an encoding failure settles as a `failed` run like any other.
23
+ */
24
+ const executeAndEncodeStats = (definition, ctx) => Effect.suspend(() => definition.run(ctx)).pipe(Effect.flatMap((stats) => Schema.encodeUnknownEffect(definition.stats)(stats).pipe(Effect.map((encoded) => ({
25
+ stats,
26
+ encoded
27
+ })))));
28
+ /**
29
+ * Stats keys the `job.completed` summary leaves out, because the line already carries them as the
30
+ * run's own status, duration and identity.
31
+ */
32
+ const RESERVED_SUMMARY_KEYS = /* @__PURE__ */ new Set([
33
+ "status",
34
+ "durationMs",
35
+ "job",
36
+ "jobRunId",
37
+ "runKey",
38
+ "attempt",
39
+ "trigger"
40
+ ]);
41
+ /**
42
+ * Converts encoded completion stats into flat log fields for `job.completed`. An object's keys
43
+ * become fields, except `status`, `durationMs`, `job`, `jobRunId`, `runKey`, `attempt` and
44
+ * `trigger`, which are dropped so they cannot overwrite the run's own fields. Any other non-object
45
+ * value is logged as `stats`, and `undefined` adds nothing.
46
+ */
47
+ const summarizeEncodedStats = (encoded) => {
48
+ if (typeof encoded === "object" && encoded !== null && !Array.isArray(encoded)) {
49
+ const entries = [];
50
+ for (const [key, value] of Object.entries(encoded)) if (!RESERVED_SUMMARY_KEYS.has(key)) entries.push([key, value]);
51
+ return Object.fromEntries(entries);
52
+ }
53
+ return encoded === void 0 ? {} : { stats: encoded };
54
+ };
55
+ /**
56
+ * Races `work` against a renewal loop that calls `options.renew` every
57
+ * `heartbeatIntervalFor(lease)`. Fails with `options.lost()`, interrupting `work`, as soon as a
58
+ * renewal returns `false`, or once renewals have failed for a full lease. A renewal fails with a
59
+ * `SqlError` or by taking longer than one interval. Each failed renewal is logged as
60
+ * `options.failureEvent`.
61
+ */
62
+ const raceWithLeaseRenewal = (work, options) => {
63
+ const leaseMs = Math.max(1, Duration.toMillis(options.lease.duration));
64
+ const interval = heartbeatIntervalFor(options.lease);
65
+ const renewLoop = Effect.gen(function* () {
66
+ let lastSuccessMs = yield* Clock.currentTimeMillis;
67
+ return yield* Effect.forever(Effect.gen(function* () {
68
+ const untilDeadline = Effect.map(Clock.currentTimeMillis, (nowMs) => Duration.min(interval, Duration.millis(Math.max(0, lastSuccessMs + leaseMs - nowMs))));
69
+ yield* Effect.sleep(yield* untilDeadline);
70
+ const requestMs = yield* Clock.currentTimeMillis;
71
+ const result = yield* options.renew.pipe(Effect.timeout(yield* untilDeadline), Effect.result);
72
+ const nowMs = yield* Clock.currentTimeMillis;
73
+ if (result._tag === "Success") {
74
+ if (result.success) lastSuccessMs = requestMs;
75
+ return result.success;
76
+ }
77
+ const elapsedWithoutSuccessMs = nowMs - lastSuccessMs;
78
+ yield* logWarning(options.failureEvent, {
79
+ ...options.fields,
80
+ errorMessage: describeError(result.failure),
81
+ elapsedSinceSuccessMs: elapsedWithoutSuccessMs
82
+ });
83
+ return elapsedWithoutSuccessMs < leaseMs;
84
+ }).pipe(Effect.filterOrFail((stillOwned) => stillOwned, () => options.lost())));
85
+ });
86
+ return Effect.raceFirst(work, renewLoop);
87
+ };
88
+ /**
89
+ * Heartbeat loop racing against the job body. Extends the lease every `heartbeatIntervalFor` of the
90
+ * ledger's lease policy and tolerates transient `SqlError`s and renewals slower than one interval
91
+ * for up to a full lease before failing with `RunClaimLost`. Fails with `RunClaimLost` at once if
92
+ * `heartbeat` returns `false`.
93
+ */
94
+ const runWithHeartbeat = (runs, owned, work) => raceWithLeaseRenewal(work, {
95
+ renew: runs.heartbeat(owned),
96
+ lease: runs.policy.lease,
97
+ lost: () => new RunClaimLost({
98
+ job: owned.job,
99
+ runKey: owned.runKey
100
+ }),
101
+ failureEvent: "job.heartbeat.failed",
102
+ fields: {
103
+ job: owned.job,
104
+ runKey: owned.runKey,
105
+ attempt: owned.attempt
106
+ }
107
+ });
108
+ /**
109
+ * Annotations of `definition`, or an empty context.
110
+ */
111
+ const annotationsOf = (definition) => definition.annotations ?? Context.empty();
112
+ /**
113
+ * Replaces NUL characters, which PostgreSQL `text` columns reject, with U+FFFD.
114
+ */
115
+ const withoutNul = (text) => text.includes("\0") ? text.replaceAll("\0", "�") : text;
116
+ /**
117
+ * The budget a failed settle of `cadence` passes to the ledger: `maxFailures` from
118
+ * `failureBudgetFor`, and for a `Daily` cadence with a deadline its schedule, so a failure after
119
+ * `until` leaves the key exhausted whatever the trigger.
120
+ */
121
+ const settleBudgetFor = (cadence) => {
122
+ const maxFailures = failureBudgetFor(cadence);
123
+ if (cadence._tag !== "Daily" || maxFailures === void 0) return { maxFailures };
124
+ const schedule = dailyScheduleFor("", cadence);
125
+ return Result.isSuccess(schedule) ? {
126
+ maxFailures,
127
+ deadline: schedule.success
128
+ } : { maxFailures };
129
+ };
130
+ /**
131
+ * Analyzes a failed `Exit` cause into failure metadata and the matching ledger `RunResult`. The
132
+ * error message is redacted and has NUL characters replaced, so the ledger can always store it.
133
+ */
134
+ const analyzeFailureExit = (definition, trigger, cause) => {
135
+ const stageError = findJobStageError(cause);
136
+ if (stageError !== void 0) {
137
+ const isRunClaimLost = stageError.errorTag === RUN_CLAIM_LOST_TAG;
138
+ const interrupted = isRunClaimLost;
139
+ const errorMessage = withoutNul(redactLogString(stageError.message));
140
+ return {
141
+ isRunClaimLost,
142
+ isDefect: stageError.isDefect,
143
+ interrupted,
144
+ errorMessage,
145
+ errorTag: stageError.errorTag ?? void 0,
146
+ retryAfterSeconds: stageError.retryAfterSeconds ?? void 0,
147
+ runResult: {
148
+ _tag: "Failed",
149
+ errorMessage,
150
+ reason: interrupted ? "interrupted" : "error",
151
+ cadence: definition.cadence._tag,
152
+ ...settleBudgetFor(definition.cadence),
153
+ trigger,
154
+ annotations: annotationsOf(definition)
155
+ }
156
+ };
157
+ }
158
+ const summary = extractCauseSummary(cause);
159
+ const isRunClaimLost = summary?.tag === RUN_CLAIM_LOST_TAG;
160
+ const interrupted = Cause.hasInterruptsOnly(cause) || isRunClaimLost;
161
+ const isDefect = summary?.kind === "die";
162
+ const errorMessage = isRunClaimLost ? RUN_CLAIM_LOST_MESSAGE : withoutNul(redactLogString(summary?.message ?? Cause.pretty(cause)));
163
+ return {
164
+ isRunClaimLost,
165
+ isDefect,
166
+ interrupted,
167
+ errorMessage,
168
+ errorTag: summary?.tag,
169
+ retryAfterSeconds: findRetryAfterSeconds(cause),
170
+ runResult: {
171
+ _tag: "Failed",
172
+ errorMessage,
173
+ reason: interrupted ? "interrupted" : "error",
174
+ cadence: definition.cadence._tag,
175
+ ...settleBudgetFor(definition.cadence),
176
+ trigger,
177
+ annotations: annotationsOf(definition)
178
+ }
179
+ };
180
+ };
181
+ /**
182
+ * Retries `effect` five times with backoff (6.2 seconds of waiting), whatever the `SqlError`.
183
+ * Enough for a reset connection; a longer outage is left to the caller's durable path. Each try's
184
+ * own duration comes on top: a try that waits for a pool connection adds the acquire or connect
185
+ * timeout each time (about 36 s in all with 5-second timeouts), and a hung server is bounded only
186
+ * by the pool's statement timeout. That is also how long it can hold up a worker's shutdown.
187
+ */
188
+ const retryTransientSql = (effect) => Effect.retry(effect, {
189
+ schedule: Schedule.exponential("200 millis", 2),
190
+ times: 5
191
+ });
192
+ /**
193
+ * Settles `owned` with `result`, retrying transient SQL errors, and returns whether the row was
194
+ * written. A settle that is rejected (another run holds the key) or still fails after the retry
195
+ * returns `false` and logs `job.settle.lost`, with the error's message when there was one.
196
+ */
197
+ const settleOrLogLost = (runs, owned, result) => {
198
+ /**
199
+ * Logs the lost settle, with the error's message when the ledger could not be reached.
200
+ */
201
+ const logLost = (error) => logWarning("job.settle.lost", {
202
+ job: owned.job,
203
+ runKey: owned.runKey,
204
+ attempt: owned.attempt,
205
+ errorMessage: error === void 0 ? void 0 : describeError(error)
206
+ }).pipe(Effect.as(false));
207
+ return runs.settle(owned, result).pipe(retryTransientSql, Effect.matchEffect({
208
+ onFailure: logLost,
209
+ onSuccess: (settled) => settled ? Effect.succeed(true) : logLost(void 0)
210
+ }));
211
+ };
212
+ export { analyzeFailureExit, annotationsOf, elapsedMillisSince, executeAndEncodeStats, raceWithLeaseRenewal, resolveForce, retryTransientSql, runWithHeartbeat, settleBudgetFor, settleOrLogLost, summarizeEncodedStats };
package/dist/run.d.ts ADDED
@@ -0,0 +1,163 @@
1
+ import { ClusterConfigError, DryRunUnsupported, InvalidJobParams, InvalidRunKey } from "./errors.js";
2
+ import { AnyJobDefinition, JobDefinition, JobTrigger } from "./job.js";
3
+ import { JobRuns } from "./ledger.js";
4
+ import { Effect, Schema } from "effect";
5
+ import { SecureRandom } from "effect/crypto";
6
+ import { SqlError } from "effect/sql";
7
+ /**
8
+ * Why a claimed run did not execute.
9
+ */
10
+ export type SkipReason = {
11
+ /**
12
+ * The `(job, runKey)` row is already `completed` and `force` was `false`.
13
+ */
14
+ readonly _tag: 'AlreadyCompleted';
15
+ } | {
16
+ /**
17
+ * Another replica currently holds a live lease on `(job, runKey)`.
18
+ */
19
+ readonly _tag: 'Busy';
20
+ } | {
21
+ /**
22
+ * A scheduled run encountered a `failed` key whose retry backoff expires at ISO timestamp
23
+ * `at`.
24
+ */
25
+ readonly _tag: 'RetryLater';
26
+ /**
27
+ * ISO-8601 UTC timestamp when the key becomes eligible for scheduled retry.
28
+ */
29
+ readonly at: string;
30
+ } | {
31
+ /**
32
+ * A scheduled run encountered a `failed` key whose `next_attempt_at` is `NULL`.
33
+ */
34
+ readonly _tag: 'Exhausted';
35
+ };
36
+ /**
37
+ * Non-failing outcome returned by `runJob`. Typed errors, defects, interruptions, and lost claims
38
+ * inside the job body all settle into the `failed` variant.
39
+ */
40
+ export type JobOutcome<Name extends string = string, Stats = unknown> = {
41
+ /**
42
+ * Job name.
43
+ */
44
+ readonly job: Name;
45
+ /**
46
+ * Cadence ledger key for this execution.
47
+ */
48
+ readonly runKey: string;
49
+ /**
50
+ * Trigger that started the run.
51
+ */
52
+ readonly trigger: JobTrigger;
53
+ /**
54
+ * Wall/clock elapsed duration in milliseconds measured via Effect `Clock`.
55
+ */
56
+ readonly elapsedMs: number;
57
+ } & ({
58
+ /**
59
+ * Run finished successfully.
60
+ */
61
+ readonly status: 'completed';
62
+ /**
63
+ * 1-based attempt number (`0` for a dry run).
64
+ */
65
+ readonly attempt: number;
66
+ /**
67
+ * `true` when executed with `dryRun: true` (no claim and no ledger write).
68
+ */
69
+ readonly dryRun: boolean;
70
+ /**
71
+ * Decoded completion stats returned by the job.
72
+ */
73
+ readonly stats: Stats;
74
+ } | {
75
+ /**
76
+ * Run skipped because `JobRuns.claim` did not acquire the key.
77
+ */
78
+ readonly status: 'skipped';
79
+ /**
80
+ * Structured reason explaining why the claim was skipped.
81
+ */
82
+ readonly reason: SkipReason;
83
+ } | {
84
+ /**
85
+ * Run failed, died, was interrupted, or lost its lease claim.
86
+ */
87
+ readonly status: 'failed';
88
+ /**
89
+ * 1-based attempt number (`0` for a dry run).
90
+ */
91
+ readonly attempt: number;
92
+ /**
93
+ * Redacted failure summary (or `'lost its run claim'` when fence check fails).
94
+ */
95
+ readonly errorMessage: string;
96
+ /**
97
+ * `true` when the failure was an unmasked defect.
98
+ */
99
+ readonly isDefect: boolean;
100
+ /**
101
+ * `true` when interrupted or when the run lost its claim.
102
+ */
103
+ readonly interrupted: boolean;
104
+ /**
105
+ * `_tag` of the typed error, if any.
106
+ */
107
+ readonly errorTag: string | undefined;
108
+ /**
109
+ * Finite `retryAfterSeconds` field of the typed error, or `undefined`.
110
+ */
111
+ readonly retryAfterSeconds: number | undefined;
112
+ });
113
+ /**
114
+ * Options controlling one `runJob` execution.
115
+ */
116
+ export type RunJobOptions = {
117
+ /**
118
+ * How this run was started.
119
+ */
120
+ readonly trigger: JobTrigger;
121
+ /**
122
+ * Re-runs a `completed` key. Defaults to `true` only for `Every` and `Cron` jobs with
123
+ * non-`schedule` triggers unless explicitly passed.
124
+ */
125
+ readonly force?: boolean | undefined;
126
+ /**
127
+ * Run key of an `OnDemand` job, which needs one. Other jobs take their key from the clock and
128
+ * fail with `InvalidRunKey` when given one.
129
+ */
130
+ readonly runKey?: string | undefined;
131
+ /**
132
+ * Partial param overrides merged over `definition.params.defaults` and validated before claim.
133
+ */
134
+ readonly params?: Schema.JsonObject | undefined;
135
+ /**
136
+ * Executes `definition.run` with `definition.dryRun` provided, without claiming or writing the
137
+ * ledger. Fails with `DryRunUnsupported` if the job defines no `dryRun` layer.
138
+ */
139
+ readonly dryRun?: boolean | undefined;
140
+ /**
141
+ * Called with the run key once the `(job, runKey)` claim is acquired, before the job body runs.
142
+ * Lets a caller link the ledger row even when the run is interrupted before `runJob` returns. Not
143
+ * called for skipped claims or dry runs. It runs as part of the job body: if it throws, the run
144
+ * settles `failed` as a defect and `runJob` returns that outcome.
145
+ */
146
+ readonly onClaimed?: ((runKey: string) => void) | undefined;
147
+ };
148
+ /**
149
+ * Runs a `JobDefinition` once, outside a workflow: validates params, derives the run key, handles
150
+ * `dryRun`, claims in `JobRuns`, races the job against heartbeats under `withJobLogging`, settles
151
+ * (calling the storage layer's `onSettle` hook) and records metrics. Errors and defects inside
152
+ * `definition.run` become a `failed` `JobOutcome`. Requires `SecureRandom` for job logging: provide
153
+ * `SecureRandom.layerWebCrypto` with `JobStorage.layerStorage`; `makeJobRunsMemory`'s layer already
154
+ * includes it. Fails with `ClusterConfigError` when the job's cadence is invalid, before anything
155
+ * is claimed.
156
+ */
157
+ export declare const runJob: <Name extends string, P, S, E, R, PE = P>(definition: JobDefinition<Name, P, S, E, R, PE>, options: RunJobOptions) => Effect.Effect<JobOutcome<Name, S>, ClusterConfigError | DryRunUnsupported | InvalidJobParams | InvalidRunKey | SqlError.SqlError, R | JobRuns | SecureRandom.SecureRandom>;
158
+ /**
159
+ * Runs a job drawn from a heterogeneous `ReadonlyArray<AnyJobDefinition<R>>` through its rank-2
160
+ * `JOB_CONTINUATION` attached by `defineJob`, avoiding any `any` or unsafe type assertions.
161
+ * Requires `SecureRandom` like `runJob`.
162
+ */
163
+ export declare const runAnyJob: <R>(definition: AnyJobDefinition<R>, options: RunJobOptions) => Effect.Effect<JobOutcome, InvalidJobParams | InvalidRunKey | ClusterConfigError | DryRunUnsupported | SqlError.SqlError, R | JobRuns | SecureRandom.SecureRandom>;
package/dist/run.js ADDED
@@ -0,0 +1,258 @@
1
+ import { DryRunUnsupported, RUN_CLAIM_LOST_MESSAGE, RUN_CLAIM_LOST_TAG } from "./errors.js";
2
+ import { JOB_CONTINUATION } from "./job.js";
3
+ import { JobRuns } from "./ledger.js";
4
+ import { withJobLogging } from "./logging.js";
5
+ import { recordJobRunMetrics } from "./metrics.js";
6
+ import { decodeParams } from "./params.js";
7
+ import { resolveRunKey } from "./run-key.js";
8
+ import { analyzeFailureExit, annotationsOf, elapsedMillisSince, executeAndEncodeStats, resolveForce, retryTransientSql, runWithHeartbeat, summarizeEncodedStats } from "./run-support.js";
9
+ import { Clock, Effect, Exit, Layer } from "effect";
10
+ import { logInfo, logWarning } from "@yieldkit/logger";
11
+ // src/run.ts
12
+ /**
13
+ * Converts a non-`Acquired` `RunClaim` into its public `SkipReason`.
14
+ */
15
+ const toSkipReason = (claim) => {
16
+ switch (claim._tag) {
17
+ case "Completed":
18
+ case "AlreadySettled": return { _tag: "AlreadyCompleted" };
19
+ case "Busy": return { _tag: "Busy" };
20
+ case "RetryLater": return {
21
+ _tag: "RetryLater",
22
+ at: claim.at.toISOString()
23
+ };
24
+ case "Exhausted": return { _tag: "Exhausted" };
25
+ default: return claim;
26
+ }
27
+ };
28
+ /**
29
+ * The `failed`-variant fields of a `JobOutcome` for an analyzed failure at `attempt`, without the
30
+ * run identity and timing that every variant shares.
31
+ */
32
+ const failedOutcomeFields = (failure, attempt) => ({
33
+ status: "failed",
34
+ attempt,
35
+ errorMessage: failure.errorMessage,
36
+ isDefect: failure.isDefect,
37
+ interrupted: failure.interrupted,
38
+ errorTag: failure.errorTag,
39
+ retryAfterSeconds: failure.retryAfterSeconds
40
+ });
41
+ /**
42
+ * Runs a dry run with `definition.dryRun` provided, without claiming or writing the ledger.
43
+ */
44
+ const executeDryRun = Effect.fnUntraced(function* (definition, ctx, startedMs) {
45
+ const dryRunLayer = definition.dryRun;
46
+ if (dryRunLayer === void 0) return yield* new DryRunUnsupported({ job: definition.name });
47
+ const work = executeAndEncodeStats(definition, ctx).pipe((effect) => Effect.scoped(Layer.build(dryRunLayer).pipe(Effect.flatMap((context) => effect.pipe(Effect.provideContext(context))))), withJobLogging({
48
+ job: definition.name,
49
+ jobRunId: `${definition.name}:${ctx.runKey}:0`,
50
+ trigger: ctx.trigger,
51
+ attempt: 0,
52
+ fields: {
53
+ ...definition.logFields,
54
+ runKey: ctx.runKey,
55
+ dryRun: true
56
+ },
57
+ summarizeResult: (output) => summarizeEncodedStats(output.encoded)
58
+ }));
59
+ const exit = yield* Effect.exit(work);
60
+ const base = {
61
+ job: definition.name,
62
+ runKey: ctx.runKey,
63
+ trigger: ctx.trigger,
64
+ elapsedMs: yield* elapsedMillisSince(startedMs)
65
+ };
66
+ const outcome = Exit.isSuccess(exit) ? {
67
+ ...base,
68
+ status: "completed",
69
+ attempt: 0,
70
+ dryRun: true,
71
+ stats: exit.value.stats
72
+ } : {
73
+ ...base,
74
+ ...failedOutcomeFields(analyzeFailureExit(definition, ctx.trigger, exit.cause), 0)
75
+ };
76
+ yield* recordJobRunMetrics({
77
+ ...outcome,
78
+ leaseLost: false
79
+ });
80
+ return outcome;
81
+ });
82
+ /**
83
+ * Builds the `JobOutcome` for an `Exit` after settling (or failing to settle) in the ledger.
84
+ */
85
+ const buildClaimedOutcome = (args) => {
86
+ const { definition, ctx, exit, settled, elapsedMs } = args;
87
+ const base = {
88
+ job: definition.name,
89
+ runKey: ctx.runKey,
90
+ trigger: ctx.trigger,
91
+ elapsedMs,
92
+ attempt: ctx.attempt
93
+ };
94
+ if (!settled) return {
95
+ leaseLost: true,
96
+ outcome: {
97
+ ...base,
98
+ status: "failed",
99
+ errorMessage: RUN_CLAIM_LOST_MESSAGE,
100
+ isDefect: false,
101
+ interrupted: true,
102
+ errorTag: RUN_CLAIM_LOST_TAG,
103
+ retryAfterSeconds: void 0
104
+ }
105
+ };
106
+ if (Exit.isSuccess(exit)) return {
107
+ leaseLost: false,
108
+ outcome: {
109
+ ...base,
110
+ status: "completed",
111
+ dryRun: false,
112
+ stats: exit.value.stats
113
+ }
114
+ };
115
+ const failure = analyzeFailureExit(definition, ctx.trigger, exit.cause);
116
+ return {
117
+ leaseLost: failure.isRunClaimLost,
118
+ outcome: {
119
+ ...base,
120
+ ...failedOutcomeFields(failure, ctx.attempt)
121
+ }
122
+ };
123
+ };
124
+ /**
125
+ * Claims `(definition.name, runKey)`, runs `definition.run` raced with heartbeats inside
126
+ * `uninterruptibleMask`, settles the ledger atomically, and records metrics before leaving the
127
+ * uninterruptible region.
128
+ */
129
+ const executeClaimed = (args) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
130
+ const { definition, ctxBase, encodedParams, force, startedMs, onClaimed } = args;
131
+ const runs = yield* JobRuns;
132
+ const claim = yield* runs.claim({
133
+ job: definition.name,
134
+ runKey: ctxBase.runKey,
135
+ trigger: ctxBase.trigger,
136
+ force,
137
+ params: encodedParams
138
+ });
139
+ if (claim._tag !== "Acquired") {
140
+ const reason = toSkipReason(claim);
141
+ yield* logInfo("job.skipped", {
142
+ ...definition.logFields,
143
+ job: definition.name,
144
+ runKey: ctxBase.runKey,
145
+ trigger: ctxBase.trigger,
146
+ status: "skipped",
147
+ skipReason: reason._tag,
148
+ retryAt: reason._tag === "RetryLater" ? reason.at : void 0
149
+ });
150
+ const elapsedMs = yield* elapsedMillisSince(startedMs);
151
+ const outcome = {
152
+ job: definition.name,
153
+ runKey: ctxBase.runKey,
154
+ trigger: ctxBase.trigger,
155
+ elapsedMs,
156
+ status: "skipped",
157
+ reason
158
+ };
159
+ yield* recordJobRunMetrics({
160
+ ...outcome,
161
+ leaseLost: false
162
+ });
163
+ return outcome;
164
+ }
165
+ const owned = {
166
+ job: definition.name,
167
+ runKey: ctxBase.runKey,
168
+ token: claim.token,
169
+ attempt: claim.attempt
170
+ };
171
+ const ctx = {
172
+ params: ctxBase.params,
173
+ runKey: ctxBase.runKey,
174
+ trigger: ctxBase.trigger,
175
+ attempt: claim.attempt
176
+ };
177
+ const work = Effect.sync(() => onClaimed?.(ctxBase.runKey)).pipe(Effect.andThen(executeAndEncodeStats(definition, ctx)));
178
+ const tracked = runWithHeartbeat(runs, owned, work).pipe(withJobLogging({
179
+ job: definition.name,
180
+ jobRunId: `${definition.name}:${ctx.runKey}:${String(claim.attempt)}`,
181
+ trigger: ctx.trigger,
182
+ attempt: claim.attempt,
183
+ fields: {
184
+ ...definition.logFields,
185
+ runKey: ctx.runKey
186
+ },
187
+ summarizeResult: (output) => summarizeEncodedStats(output.encoded)
188
+ }));
189
+ const exit = yield* Effect.exit(restore(tracked));
190
+ const runResult = Exit.isSuccess(exit) ? {
191
+ _tag: "Completed",
192
+ stats: exit.value.encoded,
193
+ trigger: ctx.trigger,
194
+ annotations: annotationsOf(definition)
195
+ } : analyzeFailureExit(definition, ctx.trigger, exit.cause).runResult;
196
+ const settled = yield* runs.settle(owned, runResult).pipe(retryTransientSql);
197
+ if (!settled) yield* logWarning("job.settle.lost", {
198
+ job: owned.job,
199
+ runKey: owned.runKey,
200
+ attempt: owned.attempt
201
+ });
202
+ const elapsedMs = yield* elapsedMillisSince(startedMs);
203
+ const { outcome, leaseLost } = buildClaimedOutcome({
204
+ definition,
205
+ ctx,
206
+ exit,
207
+ settled,
208
+ elapsedMs
209
+ });
210
+ yield* recordJobRunMetrics({
211
+ ...outcome,
212
+ leaseLost
213
+ });
214
+ return outcome;
215
+ }));
216
+ /**
217
+ * Runs a `JobDefinition` once, outside a workflow: validates params, derives the run key, handles
218
+ * `dryRun`, claims in `JobRuns`, races the job against heartbeats under `withJobLogging`, settles
219
+ * (calling the storage layer's `onSettle` hook) and records metrics. Errors and defects inside
220
+ * `definition.run` become a `failed` `JobOutcome`. Requires `SecureRandom` for job logging: provide
221
+ * `SecureRandom.layerWebCrypto` with `JobStorage.layerStorage`; `makeJobRunsMemory`'s layer already
222
+ * includes it. Fails with `ClusterConfigError` when the job's cadence is invalid, before anything
223
+ * is claimed.
224
+ */
225
+ const runJob = Effect.fnUntraced(function* (definition, options) {
226
+ const startedMs = yield* Clock.currentTimeMillis;
227
+ const runKey = yield* resolveRunKey(definition, startedMs, options.runKey);
228
+ const { params, encoded } = yield* decodeParams(definition.name, definition.params, options.params);
229
+ const ctxBase = {
230
+ params,
231
+ runKey,
232
+ trigger: options.trigger
233
+ };
234
+ if (options.dryRun === true) return yield* executeDryRun(definition, {
235
+ ...ctxBase,
236
+ attempt: 0
237
+ }, startedMs);
238
+ const force = resolveForce(definition.cadence, options.trigger, options.force);
239
+ return yield* executeClaimed({
240
+ definition,
241
+ ctxBase,
242
+ encodedParams: encoded,
243
+ force,
244
+ startedMs,
245
+ onClaimed: options.onClaimed
246
+ });
247
+ });
248
+ /**
249
+ * Runs a job drawn from a heterogeneous `ReadonlyArray<AnyJobDefinition<R>>` through its rank-2
250
+ * `JOB_CONTINUATION` attached by `defineJob`, avoiding any `any` or unsafe type assertions.
251
+ * Requires `SecureRandom` like `runJob`.
252
+ */
253
+ const runAnyJob = (definition, options) => {
254
+ const continuation = definition[JOB_CONTINUATION];
255
+ if (continuation === void 0) return Effect.die(/* @__PURE__ */ new Error(`Job "${definition.name}" must be constructed with defineJob before supervising.`));
256
+ return continuation((concrete) => runJob(concrete, options));
257
+ };
258
+ export { runAnyJob, runJob };
@@ -0,0 +1,56 @@
1
+ import { AnyJobDefinition, JobServices } from "./job.js";
2
+ import { JobRuns } from "./ledger.js";
3
+ import { JobRequests } from "./requests.js";
4
+ import "./workflow.js";
5
+ import { OperatorJobParams } from "./workflow-schema.js";
6
+ import { ClusterConfigError, UnknownJobError } from "./errors.js";
7
+ import "./maintenance.js";
8
+ import { Effect, Layer } from "effect";
9
+ import { SecureRandom } from "effect/crypto";
10
+ import { WorkflowEngine } from "effect/workflow";
11
+ import { MessageStorage, Sharding, ShardingConfig } from "effect/cluster";
12
+ /**
13
+ * Options for `makeSchedulerLayer`.
14
+ */
15
+ export type SchedulerOptions = {
16
+ /**
17
+ * Job names to run on this worker; defaults to every job that is not a manual `Once` job. Unknown
18
+ * names fail at start-up with `UnknownJobError`.
19
+ */
20
+ readonly only?: ReadonlyArray<string> | undefined;
21
+ /**
22
+ * Operator param overrides per job name, merged under API params and over each job's defaults.
23
+ */
24
+ readonly params?: OperatorJobParams | undefined;
25
+ };
26
+ /**
27
+ * Resolved non-manual jobs selected for registration on this worker.
28
+ */
29
+ type SelectedWorkerJobs<R> = {
30
+ /**
31
+ * Non-manual jobs enabled on this worker (manual `Once` jobs are never registered on workers).
32
+ */
33
+ readonly enabledJobs: ReadonlyArray<AnyJobDefinition<R>>;
34
+ /**
35
+ * Names of jobs excluded by `options.only`.
36
+ */
37
+ readonly filteredOutJobs: ReadonlyArray<string>;
38
+ };
39
+ /**
40
+ * Validates `only` against `jobs` and returns the non-manual jobs enabled for this worker.
41
+ */
42
+ export declare const selectWorkerJobs: <R>(jobs: ReadonlyArray<AnyJobDefinition<R>>, only: ReadonlyArray<string> | undefined) => Effect.Effect<SelectedWorkerJobs<R>, UnknownJobError>;
43
+ /**
44
+ * Everything a worker runs for `jobs`: a durable `Workflow` handler per job, `ClusterCron`
45
+ * schedules, a start-up `Singleton` per `Every`, `Daily` and automatic `Once` job that dispatches
46
+ * the current run, and the maintenance `Singleton`. `OnDemand` jobs get a handler but no schedule.
47
+ * Manual `Once` jobs are never registered. Provide it with your own Cluster (built with
48
+ * `ClusterWorkflowEngine.layer`) and its `ShardingConfig`, `JobStorage.layerStorage`, the services
49
+ * the jobs need and `SecureRandom` for job logging. At start-up it checks the `ShardingConfig` with
50
+ * `checkShardingConfig` and `checkWorkerAssignment`, and fails with `ClusterConfigError` when a
51
+ * shard group the jobs need is missing or misassigned, when the cadence of any job in `jobs`,
52
+ * including one `only` leaves out, is invalid, or when `params` for a job this worker schedules
53
+ * itself (any but `OnDemand`) do not decode over its defaults.
54
+ */
55
+ export declare const makeSchedulerLayer: <Jobs extends ReadonlyArray<AnyJobDefinition<JobServices<Jobs>>>>(jobs: Jobs, options?: SchedulerOptions) => Layer.Layer<never, UnknownJobError | ClusterConfigError, JobServices<Jobs> | JobRuns | JobRequests | Sharding.Sharding | ShardingConfig.ShardingConfig | MessageStorage.MessageStorage | WorkflowEngine.WorkflowEngine | SecureRandom.SecureRandom>;
56
+ export {};