@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,340 @@
|
|
|
1
|
+
import { DailySchedule } from "./calendar.js";
|
|
2
|
+
import { JobCadence, JobTrigger } from "./job.js";
|
|
3
|
+
import { Context, Effect, Schema } from "effect";
|
|
4
|
+
/**
|
|
5
|
+
* Schema of the run ledger's persisted `status` values.
|
|
6
|
+
*/
|
|
7
|
+
export declare const JobRunStatus: Schema.Literals<readonly ["running", "completed", "failed"]>;
|
|
8
|
+
/**
|
|
9
|
+
* Persisted status of a run ledger row.
|
|
10
|
+
*/
|
|
11
|
+
export type JobRunStatus = typeof JobRunStatus.Type;
|
|
12
|
+
/**
|
|
13
|
+
* Result of attempting to acquire or resume a `(job, runKey)` row in the ledger.
|
|
14
|
+
*/
|
|
15
|
+
export type RunClaim = {
|
|
16
|
+
/**
|
|
17
|
+
* Ownership acquired (or resumed for the same `executionId`) with a fresh fence `token` and
|
|
18
|
+
* 1-based `attempt`.
|
|
19
|
+
*/
|
|
20
|
+
readonly _tag: 'Acquired';
|
|
21
|
+
/**
|
|
22
|
+
* Fence UUID required by `heartbeat` and `settle`. Rotated on every claim/resume so a zombie
|
|
23
|
+
* process sharing `executionId` cannot overwrite a newer owner. A claim reply the workflow
|
|
24
|
+
* replays from its journal keeps its token: the workflow only renews that token's lease.
|
|
25
|
+
*/
|
|
26
|
+
readonly token: string;
|
|
27
|
+
/**
|
|
28
|
+
* 1-based attempt number for this `(job, runKey)`.
|
|
29
|
+
*/
|
|
30
|
+
readonly attempt: number;
|
|
31
|
+
/**
|
|
32
|
+
* `true` when this call resumed an unfinished `running` row carrying the same `executionId`
|
|
33
|
+
* after a worker crash or shard move.
|
|
34
|
+
*/
|
|
35
|
+
readonly resumed: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Failures the key already had (the ledger's `failures`), so a workflow can back off from the
|
|
38
|
+
* key's count. Missing from replies journaled by earlier releases.
|
|
39
|
+
*/
|
|
40
|
+
readonly failures?: number | undefined;
|
|
41
|
+
} | {
|
|
42
|
+
/**
|
|
43
|
+
* Another worker or process currently holds a live lease on `(job, runKey)`.
|
|
44
|
+
*/
|
|
45
|
+
readonly _tag: 'Busy';
|
|
46
|
+
} | {
|
|
47
|
+
/**
|
|
48
|
+
* The key is already `completed` and `force` was `false`.
|
|
49
|
+
*/
|
|
50
|
+
readonly _tag: 'Completed';
|
|
51
|
+
} | {
|
|
52
|
+
/**
|
|
53
|
+
* The key was already settled as `completed` by this exact `executionId` (idempotent replay).
|
|
54
|
+
*/
|
|
55
|
+
readonly _tag: 'AlreadySettled';
|
|
56
|
+
} | {
|
|
57
|
+
/**
|
|
58
|
+
* The key is `failed` and scheduled retry backoff has not elapsed yet.
|
|
59
|
+
*/
|
|
60
|
+
readonly _tag: 'RetryLater';
|
|
61
|
+
/**
|
|
62
|
+
* Earliest timestamp at which a scheduled run may reclaim this key.
|
|
63
|
+
*/
|
|
64
|
+
readonly at: Date;
|
|
65
|
+
} | {
|
|
66
|
+
/**
|
|
67
|
+
* The key is `failed` with `next_attempt_at IS NULL` and needs a `manual` or `api` run to
|
|
68
|
+
* retry it.
|
|
69
|
+
*/
|
|
70
|
+
readonly _tag: 'Exhausted';
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Input passed to `JobRuns.claim`.
|
|
74
|
+
*/
|
|
75
|
+
export type ClaimRequest = {
|
|
76
|
+
/**
|
|
77
|
+
* Job name (the ledger's `job` column).
|
|
78
|
+
*/
|
|
79
|
+
readonly job: string;
|
|
80
|
+
/**
|
|
81
|
+
* Deterministic cadence key (the ledger's `run_key` column).
|
|
82
|
+
*/
|
|
83
|
+
readonly runKey: string;
|
|
84
|
+
/**
|
|
85
|
+
* How the run was started.
|
|
86
|
+
*/
|
|
87
|
+
readonly trigger: JobTrigger;
|
|
88
|
+
/**
|
|
89
|
+
* When `true`, allows reclaiming a `completed` row owned by a different execution.
|
|
90
|
+
*/
|
|
91
|
+
readonly force: boolean;
|
|
92
|
+
/**
|
|
93
|
+
* JSON-safe encoded params persisted in the ledger's `params` column.
|
|
94
|
+
*/
|
|
95
|
+
readonly params: unknown;
|
|
96
|
+
/**
|
|
97
|
+
* Optional Effect Workflow `executionId` associated with this claim. When supplied, resuming an
|
|
98
|
+
* active `running` row with the same `executionId` rotates `claim_token` and extends the lease
|
|
99
|
+
* without failing as `Busy`, and a `completed` row with the same `executionId` returns
|
|
100
|
+
* `AlreadySettled`.
|
|
101
|
+
*/
|
|
102
|
+
readonly executionId?: string | null | undefined;
|
|
103
|
+
/**
|
|
104
|
+
* `true` when the run must not start, because it is a scheduled run of a `Daily` key past its
|
|
105
|
+
* `until`. The ledger then takes nothing and creates no row: it marks a `failed` row exhausted
|
|
106
|
+
* (`next_attempt_at = NULL`) and returns `Exhausted`, or `Completed` or `AlreadySettled` for a
|
|
107
|
+
* completed row.
|
|
108
|
+
*/
|
|
109
|
+
readonly pastDeadline?: boolean | undefined;
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* Fenced ownership handle for an active run attempt.
|
|
113
|
+
*/
|
|
114
|
+
export type OwnedRun = {
|
|
115
|
+
/**
|
|
116
|
+
* Claimed job name.
|
|
117
|
+
*/
|
|
118
|
+
readonly job: string;
|
|
119
|
+
/**
|
|
120
|
+
* Claimed ledger run key.
|
|
121
|
+
*/
|
|
122
|
+
readonly runKey: string;
|
|
123
|
+
/**
|
|
124
|
+
* Fence UUID generated on claim.
|
|
125
|
+
*/
|
|
126
|
+
readonly token: string;
|
|
127
|
+
/**
|
|
128
|
+
* 1-based attempt number assigned when claimed.
|
|
129
|
+
*/
|
|
130
|
+
readonly attempt: number;
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* Why a run settled as failed: the job failed or died (`error`), it was interrupted or lost its
|
|
134
|
+
* claim (`interrupted`, which does not count as a failure), or one workflow execution crashed and
|
|
135
|
+
* resumed more often than `policy.retry.maxCrashAttempts` (`crash-cap`).
|
|
136
|
+
*/
|
|
137
|
+
export type JobFailureReason = 'error' | 'interrupted' | 'crash-cap';
|
|
138
|
+
/**
|
|
139
|
+
* Terminal or per-attempt outcome written by `JobRuns.settle`.
|
|
140
|
+
*/
|
|
141
|
+
export type RunResult = {
|
|
142
|
+
/**
|
|
143
|
+
* Run succeeded and produced JSON-safe `stats`.
|
|
144
|
+
*/
|
|
145
|
+
readonly _tag: 'Completed';
|
|
146
|
+
/**
|
|
147
|
+
* Encoded completion stats stored in the ledger's `stats` column.
|
|
148
|
+
*/
|
|
149
|
+
readonly stats: unknown;
|
|
150
|
+
/**
|
|
151
|
+
* Trigger of the run, passed on to the `onSettle` hook.
|
|
152
|
+
*/
|
|
153
|
+
readonly trigger: JobTrigger;
|
|
154
|
+
/**
|
|
155
|
+
* The job definition's annotations, passed on to the `onSettle` hook.
|
|
156
|
+
*/
|
|
157
|
+
readonly annotations: Context.Context<never>;
|
|
158
|
+
} | {
|
|
159
|
+
/**
|
|
160
|
+
* Run failed, died, was interrupted, or lost its lease.
|
|
161
|
+
*/
|
|
162
|
+
readonly _tag: 'Failed';
|
|
163
|
+
/**
|
|
164
|
+
* Redacted failure summary stored in the ledger's `error_message` column.
|
|
165
|
+
*/
|
|
166
|
+
readonly errorMessage: string;
|
|
167
|
+
/**
|
|
168
|
+
* Why the run failed. `interrupted` does not increment `failures`.
|
|
169
|
+
*/
|
|
170
|
+
readonly reason: JobFailureReason;
|
|
171
|
+
/**
|
|
172
|
+
* Cadence tag used by `nextAttemptAt` to compute backoff or exhaustion.
|
|
173
|
+
*/
|
|
174
|
+
readonly cadence: JobCadence['_tag'];
|
|
175
|
+
/**
|
|
176
|
+
* Failures after which `nextAttemptAt` exhausts the key, in place of the policy's budget for
|
|
177
|
+
* the cadence. `Infinity` for a `Daily` job with a deadline.
|
|
178
|
+
*/
|
|
179
|
+
readonly maxFailures?: number | undefined;
|
|
180
|
+
/**
|
|
181
|
+
* Deadline of a `Daily` job with `at`, `window` or `until`: a failure settled after `until`
|
|
182
|
+
* on the run key's local date leaves the key exhausted, whatever the trigger.
|
|
183
|
+
*/
|
|
184
|
+
readonly deadline?: DailySchedule | undefined;
|
|
185
|
+
/**
|
|
186
|
+
* Trigger of the run, passed on to the `onSettle` hook.
|
|
187
|
+
*/
|
|
188
|
+
readonly trigger: JobTrigger;
|
|
189
|
+
/**
|
|
190
|
+
* The job definition's annotations, passed on to the `onSettle` hook.
|
|
191
|
+
*/
|
|
192
|
+
readonly annotations: Context.Context<never>;
|
|
193
|
+
/**
|
|
194
|
+
* Explicit `next_attempt_at`, for example when a workflow schedules a durable retry or forces
|
|
195
|
+
* exhaustion. Omit to compute it with `nextAttemptAt`. Ignored when `nextAttemptAt` says the
|
|
196
|
+
* key is exhausted or `deadline` has passed, which always stores `null`.
|
|
197
|
+
*/
|
|
198
|
+
readonly nextAttemptAtOverride?: Date | null | undefined;
|
|
199
|
+
};
|
|
200
|
+
/**
|
|
201
|
+
* Facts about one run that just settled, handed to the storage layer's `onSettle` hook.
|
|
202
|
+
*/
|
|
203
|
+
export type JobSettled = {
|
|
204
|
+
/**
|
|
205
|
+
* Job name.
|
|
206
|
+
*/
|
|
207
|
+
readonly job: string;
|
|
208
|
+
/**
|
|
209
|
+
* Ledger run key.
|
|
210
|
+
*/
|
|
211
|
+
readonly runKey: string;
|
|
212
|
+
/**
|
|
213
|
+
* 1-based attempt number of the settled run.
|
|
214
|
+
*/
|
|
215
|
+
readonly attempt: number;
|
|
216
|
+
/**
|
|
217
|
+
* How the run was started.
|
|
218
|
+
*/
|
|
219
|
+
readonly trigger: JobTrigger;
|
|
220
|
+
/**
|
|
221
|
+
* The job definition's `annotations`; read them with `Context.getOption`.
|
|
222
|
+
*/
|
|
223
|
+
readonly annotations: Context.Context<never>;
|
|
224
|
+
/**
|
|
225
|
+
* What the run produced.
|
|
226
|
+
*/
|
|
227
|
+
readonly outcome: {
|
|
228
|
+
/**
|
|
229
|
+
* The run completed.
|
|
230
|
+
*/
|
|
231
|
+
readonly _tag: 'Completed';
|
|
232
|
+
/**
|
|
233
|
+
* Encoded completion stats, as stored in the ledger.
|
|
234
|
+
*/
|
|
235
|
+
readonly stats: unknown;
|
|
236
|
+
} | {
|
|
237
|
+
/**
|
|
238
|
+
* The run failed.
|
|
239
|
+
*/
|
|
240
|
+
readonly _tag: 'Failed';
|
|
241
|
+
/**
|
|
242
|
+
* Redacted failure summary, as stored in the ledger.
|
|
243
|
+
*/
|
|
244
|
+
readonly errorMessage: string;
|
|
245
|
+
/**
|
|
246
|
+
* Why the run failed.
|
|
247
|
+
*/
|
|
248
|
+
readonly reason: JobFailureReason;
|
|
249
|
+
/**
|
|
250
|
+
* Failures of this run key after the settle; interruptions do not count.
|
|
251
|
+
*/
|
|
252
|
+
readonly failures: number;
|
|
253
|
+
/**
|
|
254
|
+
* When a scheduled run may retry the key, or `null` when it is exhausted.
|
|
255
|
+
*/
|
|
256
|
+
readonly nextAttemptAt: Date | null;
|
|
257
|
+
};
|
|
258
|
+
};
|
|
259
|
+
/**
|
|
260
|
+
* Hook called once per successful fenced settle, inside the settle transaction. Its writes through
|
|
261
|
+
* the same `SqlClient` commit or roll back with the settle; a failure is rolled back on its own and
|
|
262
|
+
* logged, and the settle still commits.
|
|
263
|
+
*/
|
|
264
|
+
export type JobSettleHook<R = never> = (event: JobSettled) => Effect.Effect<void, unknown, R>;
|
|
265
|
+
/**
|
|
266
|
+
* Schema of a run ledger row.
|
|
267
|
+
*/
|
|
268
|
+
export declare const JobRunRecord: Schema.Struct<{
|
|
269
|
+
/**
|
|
270
|
+
* Job identifier.
|
|
271
|
+
*/
|
|
272
|
+
readonly job: Schema.String;
|
|
273
|
+
/**
|
|
274
|
+
* Cadence ledger key (`YYYY-MM-DD`, `YYYY-MM-DDTHH:MMZ`, or `'once'`).
|
|
275
|
+
*/
|
|
276
|
+
readonly runKey: Schema.String;
|
|
277
|
+
/**
|
|
278
|
+
* Effect Workflow `executionId` linked to the latest claim, or `null` for runs outside a
|
|
279
|
+
* workflow.
|
|
280
|
+
*/
|
|
281
|
+
readonly executionId: Schema.NullOr<Schema.String>;
|
|
282
|
+
/**
|
|
283
|
+
* Current ledger status (`'running'`, `'completed'`, or `'failed'`).
|
|
284
|
+
*/
|
|
285
|
+
readonly status: Schema.Literals<readonly ["running", "completed", "failed"]>;
|
|
286
|
+
/**
|
|
287
|
+
* 1-based attempt number for this `(job, runKey)`.
|
|
288
|
+
*/
|
|
289
|
+
readonly attempt: Schema.Int;
|
|
290
|
+
/**
|
|
291
|
+
* Count of non-interrupted failures accumulated on this key.
|
|
292
|
+
*/
|
|
293
|
+
readonly failures: Schema.Int;
|
|
294
|
+
/**
|
|
295
|
+
* Earliest scheduled retry timestamp, or `null` when completed, running, or exhausted.
|
|
296
|
+
*/
|
|
297
|
+
readonly nextAttemptAt: Schema.NullOr<Schema.Date>;
|
|
298
|
+
/**
|
|
299
|
+
* Trigger of the most recent claim attempt.
|
|
300
|
+
*/
|
|
301
|
+
readonly trigger: Schema.Literals<readonly ["schedule", "manual", "api"]>;
|
|
302
|
+
/**
|
|
303
|
+
* Encoded JSON parameter payload from the most recent claim.
|
|
304
|
+
*/
|
|
305
|
+
readonly params: Schema.Unknown;
|
|
306
|
+
/**
|
|
307
|
+
* Encoded JSON stats payload from the last completion, or `null`.
|
|
308
|
+
*/
|
|
309
|
+
readonly stats: Schema.Unknown;
|
|
310
|
+
/**
|
|
311
|
+
* Last recorded failure message, or `null`.
|
|
312
|
+
*/
|
|
313
|
+
readonly errorMessage: Schema.NullOr<Schema.String>;
|
|
314
|
+
/**
|
|
315
|
+
* When the execution holding the key first claimed it. A claim by the same workflow execution
|
|
316
|
+
* resuming the key keeps this value; a claim by any other run sets it to the claim time.
|
|
317
|
+
*/
|
|
318
|
+
readonly startedAt: Schema.Date;
|
|
319
|
+
/**
|
|
320
|
+
* Completion or failure timestamp of the latest attempt, or `null` while running.
|
|
321
|
+
*/
|
|
322
|
+
readonly finishedAt: Schema.NullOr<Schema.Date>;
|
|
323
|
+
}>;
|
|
324
|
+
/**
|
|
325
|
+
* Decoded run ledger row.
|
|
326
|
+
*/
|
|
327
|
+
export type JobRunRecord = typeof JobRunRecord.Type;
|
|
328
|
+
/**
|
|
329
|
+
* Query filter for `JobRuns.recent`.
|
|
330
|
+
*/
|
|
331
|
+
export type RecentRunsQuery = {
|
|
332
|
+
/**
|
|
333
|
+
* Optional job name filter; omit to query across all jobs.
|
|
334
|
+
*/
|
|
335
|
+
readonly job?: string | undefined;
|
|
336
|
+
/**
|
|
337
|
+
* Maximum number of rows returned, ordered newest first.
|
|
338
|
+
*/
|
|
339
|
+
readonly limit: number;
|
|
340
|
+
};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { JobTrigger } from "./job.js";
|
|
2
|
+
import { Schema } from "effect";
|
|
3
|
+
// src/ledger-types.ts
|
|
4
|
+
/**
|
|
5
|
+
* Schema of the run ledger's persisted `status` values.
|
|
6
|
+
*/
|
|
7
|
+
const JobRunStatus = Schema.Literals([
|
|
8
|
+
"running",
|
|
9
|
+
"completed",
|
|
10
|
+
"failed"
|
|
11
|
+
]);
|
|
12
|
+
/**
|
|
13
|
+
* Schema of a run ledger row.
|
|
14
|
+
*/
|
|
15
|
+
const JobRunRecord = Schema.Struct({
|
|
16
|
+
/**
|
|
17
|
+
* Job identifier.
|
|
18
|
+
*/
|
|
19
|
+
job: Schema.String,
|
|
20
|
+
/**
|
|
21
|
+
* Cadence ledger key (`YYYY-MM-DD`, `YYYY-MM-DDTHH:MMZ`, or `'once'`).
|
|
22
|
+
*/
|
|
23
|
+
runKey: Schema.String,
|
|
24
|
+
/**
|
|
25
|
+
* Effect Workflow `executionId` linked to the latest claim, or `null` for runs outside a
|
|
26
|
+
* workflow.
|
|
27
|
+
*/
|
|
28
|
+
executionId: Schema.NullOr(Schema.String),
|
|
29
|
+
/**
|
|
30
|
+
* Current ledger status (`'running'`, `'completed'`, or `'failed'`).
|
|
31
|
+
*/
|
|
32
|
+
status: JobRunStatus,
|
|
33
|
+
/**
|
|
34
|
+
* 1-based attempt number for this `(job, runKey)`.
|
|
35
|
+
*/
|
|
36
|
+
attempt: Schema.Int,
|
|
37
|
+
/**
|
|
38
|
+
* Count of non-interrupted failures accumulated on this key.
|
|
39
|
+
*/
|
|
40
|
+
failures: Schema.Int,
|
|
41
|
+
/**
|
|
42
|
+
* Earliest scheduled retry timestamp, or `null` when completed, running, or exhausted.
|
|
43
|
+
*/
|
|
44
|
+
nextAttemptAt: Schema.NullOr(Schema.Date),
|
|
45
|
+
/**
|
|
46
|
+
* Trigger of the most recent claim attempt.
|
|
47
|
+
*/
|
|
48
|
+
trigger: JobTrigger,
|
|
49
|
+
/**
|
|
50
|
+
* Encoded JSON parameter payload from the most recent claim.
|
|
51
|
+
*/
|
|
52
|
+
params: Schema.Unknown,
|
|
53
|
+
/**
|
|
54
|
+
* Encoded JSON stats payload from the last completion, or `null`.
|
|
55
|
+
*/
|
|
56
|
+
stats: Schema.Unknown,
|
|
57
|
+
/**
|
|
58
|
+
* Last recorded failure message, or `null`.
|
|
59
|
+
*/
|
|
60
|
+
errorMessage: Schema.NullOr(Schema.String),
|
|
61
|
+
/**
|
|
62
|
+
* When the execution holding the key first claimed it. A claim by the same workflow execution
|
|
63
|
+
* resuming the key keeps this value; a claim by any other run sets it to the claim time.
|
|
64
|
+
*/
|
|
65
|
+
startedAt: Schema.Date,
|
|
66
|
+
/**
|
|
67
|
+
* Completion or failure timestamp of the latest attempt, or `null` while running.
|
|
68
|
+
*/
|
|
69
|
+
finishedAt: Schema.NullOr(Schema.Date)
|
|
70
|
+
});
|
|
71
|
+
export { JobRunRecord, JobRunStatus };
|
package/dist/ledger.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import "./ledger-sql.js";
|
|
2
|
+
import { ClaimRequest, JobRunRecord, OwnedRun, RecentRunsQuery, RunClaim, RunResult } from "./ledger-types.js";
|
|
3
|
+
import { JobsPolicy } from "./policy.js";
|
|
4
|
+
import { Context, Duration, Effect } from "effect";
|
|
5
|
+
import { SqlError } from "effect/sql";
|
|
6
|
+
declare const JobRuns_base: Context.ServiceClass<JobRuns, "@yieldkit/jobs/JobRuns", {
|
|
7
|
+
/**
|
|
8
|
+
* Claims `(request.job, request.runKey)` or returns why an existing row blocked it. A ledger
|
|
9
|
+
* row that fails to decode is a defect, not a typed failure.
|
|
10
|
+
*/
|
|
11
|
+
readonly claim: (request: ClaimRequest) => Effect.Effect<RunClaim, SqlError.SqlError>;
|
|
12
|
+
/**
|
|
13
|
+
* Extends the lease. Returns `false` when another attempt owns the key now.
|
|
14
|
+
*/
|
|
15
|
+
readonly heartbeat: (run: OwnedRun) => Effect.Effect<boolean, SqlError.SqlError>;
|
|
16
|
+
/**
|
|
17
|
+
* Fenced settle plus the `onSettle` hook in one transaction. Returns `false`, without calling
|
|
18
|
+
* the hook, when the claim was lost. Repeating a settle that already committed under the same
|
|
19
|
+
* token returns `true` again without applying it or calling the hook twice.
|
|
20
|
+
*/
|
|
21
|
+
readonly settle: (run: OwnedRun, result: RunResult) => Effect.Effect<boolean, SqlError.SqlError>;
|
|
22
|
+
/**
|
|
23
|
+
* Returns `true` when `(job, runKey)` is stored with `status = 'completed'`.
|
|
24
|
+
*/
|
|
25
|
+
readonly isCompleted: (job: string, runKey: string) => Effect.Effect<boolean, SqlError.SqlError>;
|
|
26
|
+
/**
|
|
27
|
+
* Returns recent ledger rows ordered newest first. A row that fails to decode as `JobRunRecord`
|
|
28
|
+
* is a defect, not a typed failure.
|
|
29
|
+
*/
|
|
30
|
+
readonly recent: (query: RecentRunsQuery) => Effect.Effect<ReadonlyArray<JobRunRecord>, SqlError.SqlError>;
|
|
31
|
+
/**
|
|
32
|
+
* Deletes rows of `jobs` that started more than `olderThan` ago, whatever their status, in
|
|
33
|
+
* batches of `policy.maintenance.batchSize`. Returns the deleted row count.
|
|
34
|
+
*/
|
|
35
|
+
readonly prune: (jobs: ReadonlyArray<string>, olderThan: Duration.Input) => Effect.Effect<number, SqlError.SqlError>;
|
|
36
|
+
/**
|
|
37
|
+
* Lease written on claim and heartbeat (`policy.lease.duration`).
|
|
38
|
+
*/
|
|
39
|
+
readonly leaseDuration: Duration.Duration;
|
|
40
|
+
/**
|
|
41
|
+
* The resolved policy this ledger was built with. Workflows, the scheduler and `runJob` read
|
|
42
|
+
* their retry, lease and maintenance settings from here.
|
|
43
|
+
*/
|
|
44
|
+
readonly policy: JobsPolicy;
|
|
45
|
+
}>;
|
|
46
|
+
/**
|
|
47
|
+
* Run ledger: `(job, run_key)` leases, fenced settles with the `onSettle` hook, history queries and
|
|
48
|
+
* pruning. Built by `JobStorage.layerStorage` on PostgreSQL or by `makeJobRunsMemory` in tests.
|
|
49
|
+
*/
|
|
50
|
+
export declare class JobRuns extends JobRuns_base {}
|
|
51
|
+
export {};
|
package/dist/ledger.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { claimRunSql, heartbeatRunSql, isRunCompletedSql, queryRecentRunsSql, settleRunSql } from "./ledger-sql.js";
|
|
2
|
+
import { Context, Duration, Effect, Schema } from "effect";
|
|
3
|
+
// src/ledger.ts
|
|
4
|
+
/**
|
|
5
|
+
* Run ledger: `(job, run_key)` leases, fenced settles with the `onSettle` hook, history queries and
|
|
6
|
+
* pruning. Built by `JobStorage.layerStorage` on PostgreSQL or by `makeJobRunsMemory` in tests.
|
|
7
|
+
*/
|
|
8
|
+
var JobRuns = class extends Context.Service()("@yieldkit/jobs/JobRuns") {};
|
|
9
|
+
/**
|
|
10
|
+
* Row returned by one batch of `pruneRunsSql`.
|
|
11
|
+
*/
|
|
12
|
+
const PrunedBatchRow = Schema.Struct({
|
|
13
|
+
/**
|
|
14
|
+
* Rows the batch deleted, counted by the database.
|
|
15
|
+
*/
|
|
16
|
+
deleted: Schema.Int });
|
|
17
|
+
/**
|
|
18
|
+
* Deletes rows belonging to `jobs` whose `started_at` is older than `olderThan`, whatever their
|
|
19
|
+
* status, `batchSize` rows per statement until a batch deletes fewer, so no single statement holds
|
|
20
|
+
* locks on or returns every old row. Returns the total count.
|
|
21
|
+
*/
|
|
22
|
+
const pruneRunsSql = ({ sql, runsTable }, jobs, olderThan, batchSize) => Effect.gen(function* () {
|
|
23
|
+
const cutoffMs = Math.max(0, Duration.toMillis(Duration.fromInputUnsafe(olderThan)));
|
|
24
|
+
const batch = Math.max(1, Math.trunc(batchSize));
|
|
25
|
+
const jobNames = [...jobs];
|
|
26
|
+
const eligible = sql`job = ANY(${jobNames}::text[])
|
|
27
|
+
AND started_at < NOW() - (${cutoffMs}::double precision * INTERVAL '1 millisecond')`;
|
|
28
|
+
let total = 0;
|
|
29
|
+
while (jobNames.length > 0) {
|
|
30
|
+
const rows = yield* sql`
|
|
31
|
+
WITH pruned AS (
|
|
32
|
+
DELETE FROM ${sql(runsTable)}
|
|
33
|
+
WHERE ${eligible}
|
|
34
|
+
AND (job, run_key) IN (
|
|
35
|
+
SELECT job, run_key FROM ${sql(runsTable)}
|
|
36
|
+
WHERE ${eligible}
|
|
37
|
+
LIMIT ${batch}
|
|
38
|
+
)
|
|
39
|
+
RETURNING 1
|
|
40
|
+
)
|
|
41
|
+
SELECT count(*)::int AS deleted FROM pruned
|
|
42
|
+
`;
|
|
43
|
+
const [row] = yield* Schema.decodeUnknownEffect(Schema.Array(PrunedBatchRow))(rows).pipe(Effect.orDie);
|
|
44
|
+
const deleted = row?.deleted ?? 0;
|
|
45
|
+
total += deleted;
|
|
46
|
+
if (deleted < batch) break;
|
|
47
|
+
}
|
|
48
|
+
return total;
|
|
49
|
+
});
|
|
50
|
+
/**
|
|
51
|
+
* Builds the SQL `JobRuns` service over `context`, minting claim tokens with `newToken`.
|
|
52
|
+
*/
|
|
53
|
+
const makeSqlJobRuns = (context, policy, newToken) => {
|
|
54
|
+
const leaseMs = Math.max(1, Duration.toMillis(policy.lease.duration));
|
|
55
|
+
return JobRuns.of({
|
|
56
|
+
claim: (request) => claimRunSql(context, request, leaseMs, newToken),
|
|
57
|
+
heartbeat: (run) => heartbeatRunSql(context, run, leaseMs),
|
|
58
|
+
settle: (run, result) => settleRunSql(context, run, result),
|
|
59
|
+
isCompleted: (job, runKey) => isRunCompletedSql(context, job, runKey),
|
|
60
|
+
recent: (query) => queryRecentRunsSql(context, query),
|
|
61
|
+
prune: (jobs, olderThan) => pruneRunsSql(context, jobs, olderThan, policy.maintenance.batchSize),
|
|
62
|
+
leaseDuration: policy.lease.duration,
|
|
63
|
+
policy
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
export { JobRuns, makeSqlJobRuns };
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { JobTrigger } from "./job.js";
|
|
2
|
+
import { Effect, LogLevel } from "effect";
|
|
3
|
+
import { SecureRandom } from "effect/crypto";
|
|
4
|
+
import { LogFields } from "@yieldkit/logger";
|
|
5
|
+
/**
|
|
6
|
+
* Fields attached to every log line inside one job run.
|
|
7
|
+
*/
|
|
8
|
+
export type JobLogContext = {
|
|
9
|
+
/**
|
|
10
|
+
* Stable job name, such as `sync-orders`.
|
|
11
|
+
*/
|
|
12
|
+
readonly job: string;
|
|
13
|
+
/**
|
|
14
|
+
* Correlation id for this run. Generated when omitted.
|
|
15
|
+
*/
|
|
16
|
+
readonly jobRunId?: string | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* What started the run.
|
|
19
|
+
*/
|
|
20
|
+
readonly trigger?: JobTrigger | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* 1-based attempt counter for a scheduled loop.
|
|
23
|
+
*/
|
|
24
|
+
readonly attempt?: number | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Extra annotations copied onto every line in the run.
|
|
27
|
+
*/
|
|
28
|
+
readonly fields?: LogFields | undefined;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Options for wrapping one job execution with start, completion, and failure logs.
|
|
32
|
+
*/
|
|
33
|
+
export type JobLoggingOptions<A = unknown> = JobLogContext & {
|
|
34
|
+
/**
|
|
35
|
+
* Severity of `job.started`. Defaults to `Debug`, so the default minimum hides it.
|
|
36
|
+
*/
|
|
37
|
+
readonly startLevel?: LogLevel.Severity | undefined;
|
|
38
|
+
/**
|
|
39
|
+
* Severity of `job.completed`. Defaults to `Info`.
|
|
40
|
+
*/
|
|
41
|
+
readonly completeLevel?: LogLevel.Severity | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* Severity of `job.skipped`. Defaults to `Info`.
|
|
44
|
+
*/
|
|
45
|
+
readonly skipLevel?: LogLevel.Severity | undefined;
|
|
46
|
+
/**
|
|
47
|
+
* Trace span name. Defaults to `job.${job}`.
|
|
48
|
+
*/
|
|
49
|
+
readonly spanName?: string | undefined;
|
|
50
|
+
/**
|
|
51
|
+
* Log span name. Defaults to `job.run`.
|
|
52
|
+
*/
|
|
53
|
+
readonly logSpanName?: string | undefined;
|
|
54
|
+
/**
|
|
55
|
+
* When this returns true, a successful result is logged as `job.skipped` instead of completed.
|
|
56
|
+
*/
|
|
57
|
+
readonly isSkipped?: ((result: A) => boolean) | undefined;
|
|
58
|
+
/**
|
|
59
|
+
* Extra fields copied onto the completion or skip line.
|
|
60
|
+
*/
|
|
61
|
+
readonly summarizeResult?: ((result: A) => LogFields) | undefined;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Allocates a new random UUIDv4 run id from `SecureRandom`. Callers that already have one should
|
|
65
|
+
* pass it instead.
|
|
66
|
+
*/
|
|
67
|
+
export declare const generateJobRunId: Effect.Effect<string, never, SecureRandom.SecureRandom>;
|
|
68
|
+
/**
|
|
69
|
+
* Annotates logs inside `effect` with the job name, run id, trigger, attempt and `fields`. Does not
|
|
70
|
+
* emit start or completion events. Requires `SecureRandom` to generate a run id when `jobRunId` is
|
|
71
|
+
* omitted.
|
|
72
|
+
*/
|
|
73
|
+
export declare const withJobContext: (context: JobLogContext) => (<A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R | SecureRandom.SecureRandom>);
|
|
74
|
+
/**
|
|
75
|
+
* Names one step inside a job. Adds a `stage` annotation, a log span, and a trace span.
|
|
76
|
+
*/
|
|
77
|
+
export declare const withJobStage: (stage: string, fields?: LogFields) => (<A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>);
|
|
78
|
+
/**
|
|
79
|
+
* Logs `job.started`, then `job.completed`, `job.skipped`, `job.interrupted`, or `job.failed`.
|
|
80
|
+
* Duration comes from the Effect clock. A missing `jobRunId` is generated from `SecureRandom`,
|
|
81
|
+
* which the returned effect therefore requires.
|
|
82
|
+
*/
|
|
83
|
+
export declare const withJobLogging: <A>(options: JobLoggingOptions<A>) => (<E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R | SecureRandom.SecureRandom>);
|