@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
package/dist/job.d.ts ADDED
@@ -0,0 +1,306 @@
1
+ import { Context, Duration, Effect, Layer, Schema } from "effect";
2
+ import { LogFields } from "@yieldkit/logger";
3
+ /**
4
+ * Schema of how a job run was started. `schedule` runs follow the retry rules for failed keys,
5
+ * `api` runs only accept the job's `apiParams`, and `manual` runs are started by an operator with
6
+ * trusted params. The `apiParams` filter applies to `dispatchApiJobWorkflow` and to `api` workflow
7
+ * payloads only: `runJob` trusts its caller, and anyone who can write Cluster's messages can start
8
+ * a `manual` run. Persisted in the run ledger and in workflow payloads.
9
+ */
10
+ export declare const JobTrigger: Schema.Literals<readonly ["schedule", "manual", "api"]>;
11
+ /**
12
+ * How a job run was started: `'schedule'`, `'manual'` or `'api'`.
13
+ */
14
+ export type JobTrigger = typeof JobTrigger.Type;
15
+ /**
16
+ * Local wall-clock time `HH:MM` (24-hour, `00:00` to `23:59`; `until` also takes `24:00`, the end
17
+ * of the day).
18
+ */
19
+ export type TimeOfDay = `${number}:${number}`;
20
+ /**
21
+ * Local time window of a `Daily` cadence: each day's run starts at a time drawn from `[from, to)`.
22
+ */
23
+ export type DailyWindow = {
24
+ /**
25
+ * Earliest start, inclusive.
26
+ */
27
+ readonly from: TimeOfDay;
28
+ /**
29
+ * Latest start, exclusive.
30
+ */
31
+ readonly to: TimeOfDay;
32
+ };
33
+ /**
34
+ * Once a day, by default just after midnight UTC.
35
+ */
36
+ export type DailyCadence = {
37
+ /**
38
+ * Once per day. The scheduler checks every `checkEvery`; the run key is the local date
39
+ * `YYYY-MM-DD` in `timeZone`.
40
+ */
41
+ readonly _tag: 'Daily';
42
+ /**
43
+ * How often the scheduler checks whether today's run is due, and how long a failed scheduled run
44
+ * waits before its next attempt. Must evenly divide an hour or a day. Defaults to 1 hour.
45
+ */
46
+ readonly checkEvery?: Duration.Input | undefined;
47
+ /**
48
+ * IANA time zone of the run key, `at`, `window` and `until`, such as `Europe/Brussels`. Defaults
49
+ * to `UTC`.
50
+ */
51
+ readonly timeZone?: string | undefined;
52
+ /**
53
+ * Local time the run is due. The first check at or after it starts the run. Not with `window`.
54
+ */
55
+ readonly at?: TimeOfDay | undefined;
56
+ /**
57
+ * Local window the run starts in, at a time that differs per day but is the same on every worker.
58
+ * Not with `at`.
59
+ */
60
+ readonly window?: DailyWindow | undefined;
61
+ /**
62
+ * Latest local time a run may start, first attempt or retry. Defaults to `window.to` with a
63
+ * window, `24:00` with `at`, and no limit otherwise. With a limit, retries go on until it instead
64
+ * of stopping after `retry.dailyMaxFailures` failures.
65
+ */
66
+ readonly until?: TimeOfDay | undefined;
67
+ };
68
+ /**
69
+ * When a job is due and what one idempotent unit of work (`runKey`) represents.
70
+ */
71
+ export type JobCadence = DailyCadence | {
72
+ /**
73
+ * Every tick of a cron expression. The run key is the tick in UTC (`YYYY-MM-DDTHH:MMZ`).
74
+ */
75
+ readonly _tag: 'Cron';
76
+ /**
77
+ * Five-field cron expression (`minute hour day month weekday`), such as `0 9 * * 1-5`.
78
+ */
79
+ readonly expression: string;
80
+ /**
81
+ * IANA time zone the expression is read in. Defaults to `UTC`.
82
+ */
83
+ readonly timeZone?: string | undefined;
84
+ /**
85
+ * How late a missed tick may still run, for example after every worker was down. Defaults to
86
+ * 1 hour.
87
+ */
88
+ readonly catchUpWithin?: Duration.Input | undefined;
89
+ } | {
90
+ /**
91
+ * Never scheduled. Each run is started with `dispatchJob` (or `runJob`) under a run key the
92
+ * caller chooses, such as `welcome-email:user-42`.
93
+ */
94
+ readonly _tag: 'OnDemand';
95
+ } | {
96
+ /**
97
+ * Fixed interval bucket. The run key is the UTC bucket start (`YYYY-MM-DDTHH:MMZ`), so
98
+ * replicas dedupe within each bucket.
99
+ */
100
+ readonly _tag: 'Every';
101
+ /**
102
+ * Duration of each execution bucket.
103
+ */
104
+ readonly interval: Duration.Input;
105
+ } | {
106
+ /**
107
+ * Once ever (for example a full historical import). The run key is `'once'`.
108
+ */
109
+ readonly _tag: 'Once';
110
+ /**
111
+ * `automatic` jobs are run by the scheduler until they complete. `manual` jobs run only when
112
+ * an operator starts them with `runJob`; the scheduler never registers them and
113
+ * `isApiRequestable` rejects them.
114
+ */
115
+ readonly start: 'automatic' | 'manual';
116
+ };
117
+ /**
118
+ * Runtime context passed into `JobDefinition.run` after parameter validation and run claiming.
119
+ */
120
+ export type JobContext<Params> = {
121
+ /**
122
+ * Decoded and validated job parameters merged from `defaults` and caller overrides.
123
+ */
124
+ readonly params: Params;
125
+ /**
126
+ * Ledger key of this run: `YYYY-MM-DD`, `YYYY-MM-DDTHH:MMZ`, `'once'`, or the caller's key for an
127
+ * `OnDemand` job.
128
+ */
129
+ readonly runKey: string;
130
+ /**
131
+ * What triggered this run.
132
+ */
133
+ readonly trigger: JobTrigger;
134
+ /**
135
+ * 1-based attempt number at this `(job, runKey)`. `0` during a dry run.
136
+ */
137
+ readonly attempt: number;
138
+ };
139
+ /**
140
+ * Non-enumerable symbol attaching an existential rank-2 continuation to jobs created with
141
+ * `defineJob`, allowing the scheduler to invoke `runJob` with correlated `Params` without casts.
142
+ */
143
+ export declare const JOB_CONTINUATION: unique symbol;
144
+ /**
145
+ * Existential continuation preserving the invariant relationship between `params.schema`,
146
+ * `params.defaults`, `run`, `stats`, and `dryRun` across heterogeneous job lists.
147
+ */
148
+ export type JobContinuation<R> = <Result>(invoke: <Name extends string, P, S, E, PE>(definition: JobDefinition<Name, P, S, E, R, PE>) => Result) => Result;
149
+ /**
150
+ * Typed specification of one job: identity, cadence, validated params, persisted completion stats,
151
+ * the effect that does the work, and an optional dry-run layer.
152
+ */
153
+ export type JobDefinition<Name extends string, Params, Stats, E, R, ParamsEncoded = Params> = {
154
+ /**
155
+ * Unique job name. It is the ledger's `job` column, the workflow name and the shard group, so
156
+ * renaming a job orphans its history and in-flight executions.
157
+ */
158
+ readonly name: Name;
159
+ /**
160
+ * Short human-readable description for listings and logs.
161
+ */
162
+ readonly description: string;
163
+ /**
164
+ * Schedule and idempotent ledger key cadence.
165
+ */
166
+ readonly cadence: JobCadence;
167
+ /**
168
+ * Validated runtime parameters. `{ ...defaults, ...overrides }` is decoded before claiming.
169
+ */
170
+ readonly params: {
171
+ /**
172
+ * Codec validating caller overrides + defaults and encoding validated params for `job_runs`.
173
+ */
174
+ readonly schema: Schema.Codec<Params, ParamsEncoded>;
175
+ /**
176
+ * Encoded default parameter values merged beneath caller overrides before decoding.
177
+ */
178
+ readonly defaults: Partial<ParamsEncoded>;
179
+ /**
180
+ * Param keys an API caller may set. Every other key stays with the operator (`runJob` params
181
+ * and the scheduler's `params`). Defaults to none, so an API request can only start the job
182
+ * with the worker's params. `findDisallowedApiParams` lists the keys a request must be rejected
183
+ * for, and the workflow drops every other key again before running. Opt in only params that
184
+ * cannot widen what the job reads, deletes or how long it runs.
185
+ */
186
+ readonly apiParams?: ReadonlyArray<Extract<keyof ParamsEncoded, string>> | undefined;
187
+ };
188
+ /**
189
+ * Codec for the finished run's stats, encoded into the ledger's `stats` column and the completion
190
+ * log line.
191
+ */
192
+ readonly stats: Schema.Codec<Stats, unknown>;
193
+ /**
194
+ * Performs one unit of work for `ctx`.
195
+ */
196
+ readonly run: (ctx: JobContext<Params>) => Effect.Effect<Stats, E, R>;
197
+ /**
198
+ * Optional layer that replaces the job's writes (for example with log-only stores) for a dry run.
199
+ */
200
+ readonly dryRun?: Layer.Layer<never, never, R> | undefined;
201
+ /**
202
+ * Typed metadata handed to the storage layer's `onSettle` hook as `JobSettled.annotations`, built
203
+ * with `Context.make`. Defaults to an empty context.
204
+ */
205
+ readonly annotations?: Context.Context<never> | undefined;
206
+ /**
207
+ * Static fields added to every log line of this job's runs and to the scheduler's start-up
208
+ * listing.
209
+ */
210
+ readonly logFields?: LogFields | undefined;
211
+ /**
212
+ * Internal non-enumerable rank-2 continuation attached by `defineJob`.
213
+ */
214
+ readonly [JOB_CONTINUATION]?: JobContinuation<R> | undefined;
215
+ };
216
+ /**
217
+ * Widest `JobDefinition` shape a heterogeneous job registry or scheduler list can hold without
218
+ * using `any`. Parameterized by `R` (default `unknown`) so callers can preserve the union of
219
+ * required services.
220
+ */
221
+ export type AnyJobDefinition<R = unknown> = {
222
+ /**
223
+ * Registered job name.
224
+ */
225
+ readonly name: string;
226
+ /**
227
+ * Human-readable job summary.
228
+ */
229
+ readonly description: string;
230
+ /**
231
+ * Job scheduling cadence.
232
+ */
233
+ readonly cadence: JobCadence;
234
+ /**
235
+ * Type-erased parameter schema and defaults.
236
+ */
237
+ readonly params: {
238
+ /**
239
+ * Parameter codec narrowed covariantly to `unknown`.
240
+ */
241
+ readonly schema: Schema.Codec<unknown, unknown>;
242
+ /**
243
+ * Encoded parameter defaults as a JSON object, merged beneath JSON overrides before decoding.
244
+ */
245
+ readonly defaults: Schema.JsonObject;
246
+ /**
247
+ * Param keys an API caller may set; none when missing.
248
+ */
249
+ readonly apiParams?: ReadonlyArray<string> | undefined;
250
+ };
251
+ /**
252
+ * Stats codec narrowed covariantly to `unknown`.
253
+ */
254
+ readonly stats: Schema.Codec<unknown, unknown>;
255
+ /**
256
+ * Type-erased job runner accepting `JobContext<never>` in contravariant position.
257
+ */
258
+ readonly run: (ctx: JobContext<never>) => Effect.Effect<unknown, unknown, R>;
259
+ /**
260
+ * Optional dry-run layer narrowed to `Layer<never, never, R>`.
261
+ */
262
+ readonly dryRun?: Layer.Layer<never, never, R> | undefined;
263
+ /**
264
+ * Typed metadata handed to the `onSettle` hook.
265
+ */
266
+ readonly annotations?: Context.Context<never> | undefined;
267
+ /**
268
+ * Static fields added to the job's log lines.
269
+ */
270
+ readonly logFields?: LogFields | undefined;
271
+ /**
272
+ * Non-enumerable rank-2 continuation attached by `defineJob` for type-safe scheduler invocation.
273
+ */
274
+ readonly [JOB_CONTINUATION]?: JobContinuation<R> | undefined;
275
+ };
276
+ /**
277
+ * The part of a job definition that decides which params an API caller may set. Any `JobDefinition`
278
+ * satisfies it, whatever its parameter types.
279
+ */
280
+ export type JobApiParamsPolicy = {
281
+ /**
282
+ * Parameter spec holding the `apiParams` allowlist.
283
+ */
284
+ readonly params: Pick<AnyJobDefinition['params'], 'apiParams'>;
285
+ };
286
+ /**
287
+ * Returns `true` when `job` is a manual one-time job that should not start a scheduled loop or be
288
+ * registered on cluster workers.
289
+ */
290
+ export declare const isManualOnceJob: (job: Pick<AnyJobDefinition, 'cadence'>) => boolean;
291
+ /**
292
+ * Returns `true` when `job` may be requested through the API (`dispatchApiJobWorkflow`). Manual
293
+ * `Once` jobs are excluded: they are one-off operator tasks, so only an operator starts them.
294
+ * `OnDemand` jobs are excluded too: they need a run key, so they start with `dispatchJob`.
295
+ */
296
+ export declare const isApiRequestable: (job: Pick<AnyJobDefinition, 'cadence'>) => boolean;
297
+ /**
298
+ * Union of Effect service requirements across all jobs in a tuple/array of `JobDefinition`s.
299
+ */
300
+ export type JobServices<Jobs extends ReadonlyArray<AnyJobDefinition>> = Effect.Services<ReturnType<Jobs[number]['run']>>;
301
+ /**
302
+ * Defines a typed job, preserving the literal name and inferring `Params`, `ParamsEncoded`,
303
+ * `Stats`, `E` and `R`. Attaches a non-enumerable continuation so heterogeneous job lists can still
304
+ * be run and registered without casts; jobs not built with `defineJob` cannot be scheduled.
305
+ */
306
+ export declare const defineJob: <const Name extends string, Params, Stats, E, R, ParamsEncoded = Params>(definition: JobDefinition<Name, Params, Stats, E, R, ParamsEncoded>) => JobDefinition<Name, Params, Stats, E, R, ParamsEncoded>;
package/dist/job.js ADDED
@@ -0,0 +1,45 @@
1
+ import { Schema } from "effect";
2
+ // src/job.ts
3
+ /**
4
+ * Schema of how a job run was started. `schedule` runs follow the retry rules for failed keys,
5
+ * `api` runs only accept the job's `apiParams`, and `manual` runs are started by an operator with
6
+ * trusted params. The `apiParams` filter applies to `dispatchApiJobWorkflow` and to `api` workflow
7
+ * payloads only: `runJob` trusts its caller, and anyone who can write Cluster's messages can start
8
+ * a `manual` run. Persisted in the run ledger and in workflow payloads.
9
+ */
10
+ const JobTrigger = Schema.Literals([
11
+ "schedule",
12
+ "manual",
13
+ "api"
14
+ ]);
15
+ /**
16
+ * Non-enumerable symbol attaching an existential rank-2 continuation to jobs created with
17
+ * `defineJob`, allowing the scheduler to invoke `runJob` with correlated `Params` without casts.
18
+ */
19
+ const JOB_CONTINUATION = Symbol.for("@yieldkit/jobs/JobContinuation");
20
+ /**
21
+ * Returns `true` when `job` is a manual one-time job that should not start a scheduled loop or be
22
+ * registered on cluster workers.
23
+ */
24
+ const isManualOnceJob = (job) => job.cadence._tag === "Once" && job.cadence.start === "manual";
25
+ /**
26
+ * Returns `true` when `job` may be requested through the API (`dispatchApiJobWorkflow`). Manual
27
+ * `Once` jobs are excluded: they are one-off operator tasks, so only an operator starts them.
28
+ * `OnDemand` jobs are excluded too: they need a run key, so they start with `dispatchJob`.
29
+ */
30
+ const isApiRequestable = (job) => !isManualOnceJob(job) && job.cadence._tag !== "OnDemand";
31
+ /**
32
+ * Defines a typed job, preserving the literal name and inferring `Params`, `ParamsEncoded`,
33
+ * `Stats`, `E` and `R`. Attaches a non-enumerable continuation so heterogeneous job lists can still
34
+ * be run and registered without casts; jobs not built with `defineJob` cannot be scheduled.
35
+ */
36
+ const defineJob = (definition) => {
37
+ const defined = { ...definition };
38
+ Object.defineProperty(defined, JOB_CONTINUATION, {
39
+ value: ((invoke) => invoke(definition)),
40
+ enumerable: false,
41
+ configurable: true
42
+ });
43
+ return defined;
44
+ };
45
+ export { JOB_CONTINUATION, JobTrigger, defineJob, isApiRequestable, isManualOnceJob };
@@ -0,0 +1,64 @@
1
+ import { ClusterConfigError } from "./errors.js";
2
+ import { JobRunRecord, JobSettleHook, JobSettled, OwnedRun, RunResult } from "./ledger-types.js";
3
+ import { JobsPolicyOverrides } from "./policy.js";
4
+ import { JobRuns } from "./ledger.js";
5
+ import { Effect, Layer } from "effect";
6
+ import { SecureRandom } from "effect/crypto";
7
+ /**
8
+ * Recorded settle invocation captured by `makeJobRunsMemory` for assertions.
9
+ */
10
+ export type MemorySettleEntry = {
11
+ /**
12
+ * Ownership handle that settled the run.
13
+ */
14
+ readonly run: OwnedRun;
15
+ /**
16
+ * Terminal `RunResult` passed to `settle`.
17
+ */
18
+ readonly result: RunResult;
19
+ /**
20
+ * The event handed to the `onSettle` hook for this settle.
21
+ */
22
+ readonly event: JobSettled;
23
+ };
24
+ /**
25
+ * Options of `makeJobRunsMemory`.
26
+ */
27
+ export type JobRunsMemoryOptions<R = never> = {
28
+ /**
29
+ * Hook called after every successful settle, like the SQL ledger's. A failure is swallowed (and
30
+ * the settle still counts), an interruption is not.
31
+ */
32
+ readonly onSettle?: JobSettleHook<R> | undefined;
33
+ /**
34
+ * Policy overrides merged over `defaultJobsPolicy`.
35
+ */
36
+ readonly policy?: JobsPolicyOverrides | undefined;
37
+ };
38
+ /**
39
+ * In-memory `JobRuns` test harness exposing its Effect `layer` alongside recorded `settles` and
40
+ * current `rows`.
41
+ */
42
+ export type JobRunsMemoryHarness<R = never> = {
43
+ /**
44
+ * Standalone layer requiring no database (only the hook's services). Also provides the WebCrypto
45
+ * `SecureRandom` it mints claim tokens from, so `runJob` and job logging run on this layer
46
+ * alone.
47
+ */
48
+ readonly layer: Layer.Layer<JobRuns | SecureRandom.SecureRandom, never, R>;
49
+ /**
50
+ * Every successful settle in order, with its `RunResult` and the hook event.
51
+ */
52
+ readonly settles: () => ReadonlyArray<MemorySettleEntry>;
53
+ /**
54
+ * Current ledger rows, for assertions on status, attempt, failures, and `nextAttemptAt`.
55
+ */
56
+ readonly rows: () => ReadonlyArray<JobRunRecord>;
57
+ };
58
+ /**
59
+ * Builds an in-memory `JobRuns` with the claim, lease, fence, backoff, query and prune semantics of
60
+ * the SQL ledger, reading time from the Effect `Clock` so `TestClock` controls every timestamp. It
61
+ * calls `onSettle` after each successful settle and records the events. Fails with
62
+ * `ClusterConfigError` for invalid policy overrides.
63
+ */
64
+ export declare const makeJobRunsMemory: <R = never>(options?: JobRunsMemoryOptions<R>) => Effect.Effect<JobRunsMemoryHarness<R>, ClusterConfigError>;
@@ -0,0 +1,246 @@
1
+ import { failedNextAttemptAt } from "./ledger-retry.js";
2
+ import { JobRuns } from "./ledger.js";
3
+ import { decideClaim, resolveJobsPolicy } from "./policy.js";
4
+ import { bindSettleHook } from "./settle-hook.js";
5
+ import { Clock, DateTime, Duration, Effect, Layer } from "effect";
6
+ import { SecureRandom } from "effect/crypto";
7
+ // src/ledger-memory.ts
8
+ /**
9
+ * Formats the composite `Map` key for `(job, runKey)`.
10
+ */
11
+ const rowKey = (job, runKey) => `${job}\0${runKey}`;
12
+ /**
13
+ * Returns the row of `run` while it is still `running` under `run.token`, or `undefined` once it
14
+ * settled, vanished, or another claim rotated the token.
15
+ */
16
+ const findOwnedRow = (store, run) => {
17
+ const existing = store.get(rowKey(run.job, run.runKey));
18
+ return existing !== void 0 && existing.record.status === "running" && existing.claimToken === run.token ? existing : void 0;
19
+ };
20
+ /**
21
+ * Answers a claim of a run past its deadline without taking the row: a `completed` row is
22
+ * `Completed` (`AlreadySettled` for its own execution); any other key is `Exhausted`, and a
23
+ * `failed` row is marked exhausted.
24
+ */
25
+ const refusePastDeadline = (existing, executionId) => {
26
+ if (existing?.record.status === "completed") return executionId !== null && existing.record.executionId === executionId ? { _tag: "AlreadySettled" } : { _tag: "Completed" };
27
+ if (existing?.record.status === "failed") existing.record = {
28
+ ...existing.record,
29
+ nextAttemptAt: null
30
+ };
31
+ return { _tag: "Exhausted" };
32
+ };
33
+ /**
34
+ * Claims or resumes `(request.job, request.runKey)` using Effect `Clock` time so `TestClock` drives
35
+ * lease expiration and retry timestamps deterministically. `newToken` mints the fence UUID.
36
+ */
37
+ const claimMemory = Effect.fnUntraced(function* (store, request, leaseMs, newToken) {
38
+ const now = yield* DateTime.nowAsDate;
39
+ const nowMs = now.getTime();
40
+ const key = rowKey(request.job, request.runKey);
41
+ const executionId = request.executionId ?? null;
42
+ const existing = store.get(key);
43
+ if (request.pastDeadline === true) return refusePastDeadline(existing, executionId);
44
+ let resumed = false;
45
+ if (existing !== void 0) {
46
+ const decision = decideClaim({
47
+ status: existing.record.status,
48
+ executionId: existing.record.executionId,
49
+ nextAttemptAt: existing.record.nextAttemptAt,
50
+ leaseExpired: existing.leaseExpiresAtMs < nowMs,
51
+ nowMs
52
+ }, {
53
+ trigger: request.trigger,
54
+ force: request.force,
55
+ executionId
56
+ });
57
+ if (decision._tag === "Refuse") return decision.claim;
58
+ resumed = decision.resumed;
59
+ }
60
+ const token = yield* newToken;
61
+ const attempt = existing === void 0 ? 1 : existing.record.attempt + 1;
62
+ const failures = existing === void 0 ? 0 : existing.record.failures;
63
+ const startedAt = resumed && existing !== void 0 ? existing.record.startedAt : now;
64
+ store.set(key, {
65
+ record: {
66
+ job: request.job,
67
+ runKey: request.runKey,
68
+ executionId,
69
+ status: "running",
70
+ attempt,
71
+ failures,
72
+ nextAttemptAt: null,
73
+ trigger: request.trigger,
74
+ params: request.params ?? {},
75
+ stats: null,
76
+ errorMessage: null,
77
+ startedAt,
78
+ finishedAt: null
79
+ },
80
+ claimToken: token,
81
+ leaseExpiresAtMs: nowMs + leaseMs
82
+ });
83
+ return {
84
+ _tag: "Acquired",
85
+ token,
86
+ attempt,
87
+ resumed,
88
+ failures
89
+ };
90
+ });
91
+ /**
92
+ * Extends the in-memory lease when `run.token` still owns a running row.
93
+ */
94
+ const heartbeatMemory = Effect.fnUntraced(function* (store, run, leaseMs) {
95
+ const existing = findOwnedRow(store, run);
96
+ if (existing === void 0) return false;
97
+ existing.leaseExpiresAtMs = (yield* Clock.currentTimeMillis) + leaseMs;
98
+ return true;
99
+ });
100
+ /**
101
+ * Whether `run`'s own claim already settled its row the way `result` would, so a repeated settle
102
+ * counts as settled without being applied again, like the SQL ledger.
103
+ */
104
+ const isSettledByClaim = (store, run, result) => {
105
+ const existing = store.get(rowKey(run.job, run.runKey));
106
+ const status = result._tag === "Completed" ? "completed" : "failed";
107
+ return existing?.claimToken === run.token && existing.record.status === status;
108
+ };
109
+ /**
110
+ * Settles an owned in-memory row and records the settle entry when `run.token` still owns it.
111
+ */
112
+ const settleMemory = Effect.fnUntraced(function* (state, run, result) {
113
+ const { store, settleLog, retry } = state;
114
+ const existing = findOwnedRow(store, run);
115
+ if (existing === void 0) return;
116
+ const now = yield* DateTime.nowAsDate;
117
+ const identity = {
118
+ job: run.job,
119
+ runKey: run.runKey,
120
+ attempt: run.attempt,
121
+ trigger: result.trigger,
122
+ annotations: result.annotations
123
+ };
124
+ if (result._tag === "Completed") {
125
+ existing.record = {
126
+ ...existing.record,
127
+ status: "completed",
128
+ stats: result.stats ?? null,
129
+ errorMessage: null,
130
+ nextAttemptAt: null,
131
+ finishedAt: now
132
+ };
133
+ const event = {
134
+ ...identity,
135
+ outcome: {
136
+ _tag: "Completed",
137
+ stats: result.stats
138
+ }
139
+ };
140
+ settleLog.push({
141
+ run,
142
+ result,
143
+ event
144
+ });
145
+ return event;
146
+ }
147
+ const interrupted = result.reason === "interrupted";
148
+ const failures = existing.record.failures + (interrupted ? 0 : 1);
149
+ const retryAt = failedNextAttemptAt(retry, result, {
150
+ runKey: run.runKey,
151
+ failures,
152
+ now
153
+ });
154
+ existing.record = {
155
+ ...existing.record,
156
+ status: "failed",
157
+ errorMessage: result.errorMessage,
158
+ failures,
159
+ nextAttemptAt: retryAt,
160
+ finishedAt: now
161
+ };
162
+ const event = {
163
+ ...identity,
164
+ outcome: {
165
+ _tag: "Failed",
166
+ errorMessage: result.errorMessage,
167
+ reason: result.reason,
168
+ failures,
169
+ nextAttemptAt: retryAt
170
+ }
171
+ };
172
+ settleLog.push({
173
+ run,
174
+ result,
175
+ event
176
+ });
177
+ return event;
178
+ });
179
+ /**
180
+ * Runs `hook` for `event` like the SQL ledger: a failure or defect is dropped, an interruption is
181
+ * not. Resolves to whether the settle matched its claim.
182
+ */
183
+ const runMemoryHook = (hook, event) => {
184
+ if (event === void 0) return Effect.succeed(false);
185
+ if (hook === void 0) return Effect.succeed(true);
186
+ return hook(event).pipe(Effect.catchTag("SettleHookFailed", () => Effect.void), Effect.as(true));
187
+ };
188
+ /**
189
+ * Builds an in-memory `JobRuns` with the claim, lease, fence, backoff, query and prune semantics of
190
+ * the SQL ledger, reading time from the Effect `Clock` so `TestClock` controls every timestamp. It
191
+ * calls `onSettle` after each successful settle and records the events. Fails with
192
+ * `ClusterConfigError` for invalid policy overrides.
193
+ */
194
+ const makeJobRunsMemory = (options) => Effect.gen(function* () {
195
+ const policy = yield* resolveJobsPolicy(options?.policy);
196
+ const leaseDuration = policy.lease.duration;
197
+ const leaseMs = Math.max(1, Duration.toMillis(leaseDuration));
198
+ const store = /* @__PURE__ */ new Map();
199
+ const settleLog = [];
200
+ /**
201
+ * Builds the service over the shared `store` and `settleLog`, minting claim fence tokens from
202
+ * `random` so every layer built from this harness sees the same rows.
203
+ */
204
+ const makeService = (random, hook) => JobRuns.of({
205
+ claim: (request) => claimMemory(store, request, leaseMs, random.uuidV4()),
206
+ heartbeat: (run) => heartbeatMemory(store, run, leaseMs),
207
+ settle: (run, result) => settleMemory({
208
+ store,
209
+ settleLog,
210
+ retry: policy.retry
211
+ }, run, result).pipe(Effect.flatMap((event) => event === void 0 && isSettledByClaim(store, run, result) ? Effect.succeed(true) : runMemoryHook(hook, event))),
212
+ isCompleted: (job, runKey) => Effect.sync(() => store.get(rowKey(job, runKey))?.record.status === "completed"),
213
+ recent: (query) => Effect.sync(() => {
214
+ const limit = Math.max(0, Math.trunc(query.limit));
215
+ if (limit === 0) return [];
216
+ return [...store.values()].flatMap(({ record }) => query.job === void 0 || record.job === query.job ? [record] : []).toSorted((left, right) => {
217
+ const timeDiff = right.startedAt.getTime() - left.startedAt.getTime();
218
+ if (timeDiff !== 0) return timeDiff;
219
+ return right.runKey.localeCompare(left.runKey);
220
+ }).slice(0, limit);
221
+ }),
222
+ prune: (jobs, olderThan) => Effect.gen(function* () {
223
+ if (jobs.length === 0) return 0;
224
+ const cutoffMs = (yield* Clock.currentTimeMillis) - Math.max(0, Duration.toMillis(Duration.fromInputUnsafe(olderThan)));
225
+ const jobSet = new Set(jobs);
226
+ let deleted = 0;
227
+ for (const [key, entry] of store.entries()) if (jobSet.has(entry.record.job) && entry.record.startedAt.getTime() < cutoffMs) {
228
+ store.delete(key);
229
+ deleted += 1;
230
+ }
231
+ return deleted;
232
+ }),
233
+ leaseDuration,
234
+ policy
235
+ });
236
+ return {
237
+ layer: Layer.effect(JobRuns, Effect.gen(function* () {
238
+ const random = yield* SecureRandom.SecureRandom;
239
+ const context = yield* Effect.context();
240
+ return makeService(random, bindSettleHook(options?.onSettle, context));
241
+ })).pipe(Layer.provideMerge(SecureRandom.layerWebCrypto)),
242
+ settles: () => [...settleLog],
243
+ rows: () => [...store.values()].map((entry) => entry.record)
244
+ };
245
+ });
246
+ export { makeJobRunsMemory };
@@ -0,0 +1,21 @@
1
+ import { isWithinDailyDeadline } from "./calendar.js";
2
+ import { nextAttemptAt } from "./policy.js";
3
+ // src/ledger-retry.ts
4
+ /**
5
+ * `next_attempt_at` a failed settle of `runKey` stores, shared by every `JobRuns` implementation:
6
+ * `null` when `nextAttemptAt` exhausts the key or its deadline has passed, else the result's
7
+ * override, else `nextAttemptAt`'s instant. `failures` is the key's count after the settle.
8
+ */
9
+ const failedNextAttemptAt = (retry, result, settled) => {
10
+ const ruled = nextAttemptAt(retry, {
11
+ cadence: result.cadence,
12
+ failures: settled.failures,
13
+ interrupted: result.reason === "interrupted",
14
+ now: settled.now,
15
+ maxFailures: result.maxFailures
16
+ });
17
+ const pastDeadline = result.deadline !== void 0 && !isWithinDailyDeadline(result.deadline, settled.runKey, settled.now.getTime());
18
+ if (ruled === null || pastDeadline) return null;
19
+ return result.nextAttemptAtOverride === void 0 ? ruled : result.nextAttemptAtOverride;
20
+ };
21
+ export { failedNextAttemptAt };