@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,39 @@
1
+ import { JobRunStatus } from "./ledger-types.js";
2
+ import { Effect, Schema } from "effect";
3
+ // src/ledger-sql-deadline.ts
4
+ /**
5
+ * Row schema of the key read by a claim past its deadline.
6
+ */
7
+ const PastDeadlineRow = Schema.Struct({
8
+ /**
9
+ * Current status of the row.
10
+ */
11
+ status: JobRunStatus,
12
+ /**
13
+ * Workflow `execution_id` recorded on the row, or `null`.
14
+ */
15
+ executionId: Schema.NullOr(Schema.String)
16
+ });
17
+ /**
18
+ * Answers a claim of a run past its deadline without taking the row or creating one: marks a
19
+ * `failed` row exhausted, then returns `Completed` (`AlreadySettled` for its own execution) for a
20
+ * `completed` row and `Exhausted` otherwise.
21
+ */
22
+ const refusePastDeadlineSql = ({ sql, runsTable }, request) => sql`
23
+ WITH exhausted AS (
24
+ UPDATE ${sql(runsTable)}
25
+ SET next_attempt_at = NULL
26
+ WHERE job = ${request.job}
27
+ AND run_key = ${request.runKey}
28
+ AND status = 'failed'
29
+ RETURNING 1
30
+ )
31
+ SELECT status, execution_id AS "executionId"
32
+ FROM ${sql(runsTable)}
33
+ WHERE job = ${request.job}
34
+ AND run_key = ${request.runKey}
35
+ `.pipe(Effect.flatMap((rows) => Schema.decodeUnknownEffect(Schema.Array(PastDeadlineRow))(rows).pipe(Effect.orDie)), Effect.map(([row]) => {
36
+ if (row?.status !== "completed") return { _tag: "Exhausted" };
37
+ return request.executionId !== void 0 && request.executionId !== null && row.executionId === request.executionId ? { _tag: "AlreadySettled" } : { _tag: "Completed" };
38
+ }));
39
+ export { refusePastDeadlineSql };
@@ -0,0 +1,5 @@
1
+ import "./ledger-types.js";
2
+ import "./policy.js";
3
+ import "./settle-hook.js";
4
+ import { Effect } from "effect";
5
+ import { SqlClient, SqlError } from "effect/sql";
@@ -0,0 +1,332 @@
1
+ import { failedNextAttemptAt } from "./ledger-retry.js";
2
+ import { refusePastDeadlineSql } from "./ledger-sql-deadline.js";
3
+ import { JobRunRecord, JobRunStatus } from "./ledger-types.js";
4
+ import { decideClaim } from "./policy.js";
5
+ import { runSettleHook } from "./settle-hook.js";
6
+ import { Effect, Schema } from "effect";
7
+ // src/ledger-sql.ts
8
+ /**
9
+ * Row schema for `INSERT ... ON CONFLICT DO NOTHING RETURNING attempt`.
10
+ */
11
+ const ClaimAttemptRow = Schema.Struct({
12
+ /**
13
+ * Assigned 1-based attempt number.
14
+ */
15
+ attempt: Schema.Int,
16
+ /**
17
+ * Failures the key already had.
18
+ */
19
+ failures: Schema.Int
20
+ });
21
+ /**
22
+ * Locked existing ledger row inspected inside `claimRunSql` when the key already exists.
23
+ */
24
+ const ExistingRunRow = Schema.Struct({
25
+ /**
26
+ * Current status on the existing row.
27
+ */
28
+ status: JobRunStatus,
29
+ /**
30
+ * Workflow `execution_id` recorded on the existing row, or `null`.
31
+ */
32
+ executionId: Schema.NullOr(Schema.String),
33
+ /**
34
+ * Current 1-based attempt counter.
35
+ */
36
+ attempt: Schema.Int,
37
+ /**
38
+ * `true` when `lease_expires_at < NOW()` on the database clock.
39
+ */
40
+ leaseExpired: Schema.Boolean,
41
+ /**
42
+ * Scheduled retry timestamp, or `null`.
43
+ */
44
+ nextAttemptAt: Schema.NullOr(Schema.Date),
45
+ /**
46
+ * Current database transaction timestamp `NOW()`.
47
+ */
48
+ now: Schema.Date
49
+ });
50
+ /**
51
+ * Row schema returned by the first phase of a failed settle update.
52
+ */
53
+ const FailedSettleRow = Schema.Struct({
54
+ /**
55
+ * Post-increment non-interrupted failure count.
56
+ */
57
+ failures: Schema.Int,
58
+ /**
59
+ * Database transaction `NOW()` timestamp used to compute `nextAttemptAt`.
60
+ */
61
+ now: Schema.Date
62
+ });
63
+ /**
64
+ * Serializes an optional JSON-safe payload into JSON text for a `::jsonb` cast. Returns `null` for
65
+ * `undefined` and for values `JSON.stringify` cannot represent (functions, symbols).
66
+ */
67
+ const serializeJsonb = (value) => {
68
+ if (value === void 0) return null;
69
+ const encoded = JSON.stringify(value);
70
+ return typeof encoded === "string" ? encoded : null;
71
+ };
72
+ /**
73
+ * Locks the existing `(request.job, request.runKey)` row `FOR UPDATE` inside the caller's
74
+ * transaction and reads it with lease expiry and `NOW()` evaluated on the database clock. Returns
75
+ * `undefined` when the row vanished between the conflicting insert and the lock.
76
+ */
77
+ const lockExistingRunSql = ({ sql, runsTable }, request) => sql`
78
+ SELECT
79
+ status,
80
+ execution_id AS "executionId",
81
+ attempt,
82
+ (lease_expires_at < NOW()) AS "leaseExpired",
83
+ next_attempt_at AS "nextAttemptAt",
84
+ NOW() AS now
85
+ FROM ${sql(runsTable)}
86
+ WHERE job = ${request.job}
87
+ AND run_key = ${request.runKey}
88
+ FOR UPDATE
89
+ `.pipe(Effect.flatMap((rows) => Schema.decodeUnknownEffect(Schema.Array(ExistingRunRow))(rows).pipe(Effect.orDie)), Effect.map((rows) => rows[0]));
90
+ /**
91
+ * Atomically claims or resumes `(request.job, request.runKey)` or classifies why the row could not
92
+ * be claimed. Resuming a `running` row with the same `executionId` rotates `claim_token`, extends
93
+ * the lease, increments `attempt`, and returns `resumed: true`. Finding a `completed` row with the
94
+ * same `executionId` returns `AlreadySettled`. `newToken` mints the fence UUID written to
95
+ * `claim_token`. A row that fails to decode is a bug in the SQL or the row schemas, so it dies
96
+ * (rolling the transaction back) instead of failing with `SchemaError`.
97
+ */
98
+ const claimRunSql = (context, request, leaseMs, newToken) => {
99
+ const { sql, runsTable } = context;
100
+ if (request.pastDeadline === true) return refusePastDeadlineSql(context, request);
101
+ return sql.withTransaction(Effect.gen(function* () {
102
+ const token = yield* newToken;
103
+ const executionId = request.executionId ?? null;
104
+ const paramsJson = serializeJsonb(request.params) ?? "{}";
105
+ const inserted = yield* sql`
106
+ INSERT INTO ${sql(runsTable)} (
107
+ job,
108
+ run_key,
109
+ execution_id,
110
+ status,
111
+ claim_token,
112
+ lease_expires_at,
113
+ trigger,
114
+ params
115
+ )
116
+ VALUES (
117
+ ${request.job},
118
+ ${request.runKey},
119
+ ${executionId},
120
+ 'running',
121
+ ${token}::uuid,
122
+ NOW() + (${leaseMs}::double precision * INTERVAL '1 millisecond'),
123
+ ${request.trigger},
124
+ ${paramsJson}::jsonb
125
+ )
126
+ ON CONFLICT (job, run_key) DO NOTHING
127
+ RETURNING attempt, failures
128
+ `;
129
+ const created = (yield* Schema.decodeUnknownEffect(Schema.Array(ClaimAttemptRow))(inserted).pipe(Effect.orDie))[0];
130
+ if (created !== void 0) return {
131
+ _tag: "Acquired",
132
+ token,
133
+ attempt: created.attempt,
134
+ resumed: false,
135
+ failures: created.failures
136
+ };
137
+ const existing = yield* lockExistingRunSql(context, request);
138
+ if (existing === void 0) return { _tag: "Busy" };
139
+ const decision = decideClaim({
140
+ ...existing,
141
+ nowMs: existing.now.getTime()
142
+ }, {
143
+ trigger: request.trigger,
144
+ force: request.force,
145
+ executionId
146
+ });
147
+ if (decision._tag === "Refuse") return decision.claim;
148
+ const resumingSameExecution = decision.resumed;
149
+ const updated = yield* sql`
150
+ UPDATE ${sql(runsTable)}
151
+ SET
152
+ status = 'running',
153
+ execution_id = ${executionId},
154
+ claim_token = ${token}::uuid,
155
+ lease_expires_at = NOW() + (${leaseMs}::double precision * INTERVAL '1 millisecond'),
156
+ attempt = attempt + 1,
157
+ next_attempt_at = NULL,
158
+ trigger = ${request.trigger},
159
+ params = ${paramsJson}::jsonb,
160
+ stats = NULL,
161
+ error_message = NULL,
162
+ started_at = CASE WHEN ${resumingSameExecution} THEN started_at ELSE NOW() END,
163
+ finished_at = NULL
164
+ WHERE job = ${request.job}
165
+ AND run_key = ${request.runKey}
166
+ RETURNING attempt, failures
167
+ `;
168
+ const claimed = (yield* Schema.decodeUnknownEffect(Schema.Array(ClaimAttemptRow))(updated).pipe(Effect.orDie))[0];
169
+ if (claimed === void 0) return { _tag: "Busy" };
170
+ return {
171
+ _tag: "Acquired",
172
+ token,
173
+ attempt: claimed.attempt,
174
+ resumed: resumingSameExecution,
175
+ failures: claimed.failures
176
+ };
177
+ }));
178
+ };
179
+ /**
180
+ * Extends the lease on an active run when its claim token still matches.
181
+ */
182
+ const heartbeatRunSql = ({ sql, runsTable }, run, leaseMs) => sql`
183
+ UPDATE ${sql(runsTable)}
184
+ SET lease_expires_at = NOW() + (${leaseMs}::double precision * INTERVAL '1 millisecond')
185
+ WHERE job = ${run.job}
186
+ AND run_key = ${run.runKey}
187
+ AND status = 'running'
188
+ AND claim_token = ${run.token}::uuid
189
+ RETURNING 1
190
+ `.pipe(Effect.map((rows) => rows.length > 0));
191
+ /**
192
+ * Token-fenced completion update and the settle hook in one transaction.
193
+ */
194
+ const settleCompletedSql = ({ sql, runsTable, onSettle }, run, result) => sql.withTransaction(Effect.gen(function* () {
195
+ const statsJson = serializeJsonb(result.stats);
196
+ if ((yield* sql`
197
+ UPDATE ${sql(runsTable)}
198
+ SET
199
+ status = 'completed',
200
+ stats = ${statsJson}::jsonb,
201
+ error_message = NULL,
202
+ next_attempt_at = NULL,
203
+ finished_at = NOW()
204
+ WHERE job = ${run.job}
205
+ AND run_key = ${run.runKey}
206
+ AND status = 'running'
207
+ AND claim_token = ${run.token}::uuid
208
+ RETURNING 1
209
+ `).length === 0) return false;
210
+ yield* runSettleHook(sql, onSettle, {
211
+ job: run.job,
212
+ runKey: run.runKey,
213
+ attempt: run.attempt,
214
+ trigger: result.trigger,
215
+ annotations: result.annotations,
216
+ outcome: {
217
+ _tag: "Completed",
218
+ stats: result.stats
219
+ }
220
+ });
221
+ return true;
222
+ }));
223
+ /**
224
+ * Token-fenced failure update, `next_attempt_at` computation and the settle hook in one
225
+ * transaction.
226
+ */
227
+ const settleFailedSql = ({ sql, runsTable, retry, onSettle }, run, result) => sql.withTransaction(Effect.gen(function* () {
228
+ const failureIncrement = result.reason === "interrupted" ? 0 : 1;
229
+ const updated = yield* sql`
230
+ UPDATE ${sql(runsTable)}
231
+ SET
232
+ status = 'failed',
233
+ error_message = ${result.errorMessage},
234
+ failures = failures + ${failureIncrement},
235
+ finished_at = NOW()
236
+ WHERE job = ${run.job}
237
+ AND run_key = ${run.runKey}
238
+ AND status = 'running'
239
+ AND claim_token = ${run.token}::uuid
240
+ RETURNING failures, NOW() AS now
241
+ `;
242
+ if (updated.length === 0) return false;
243
+ const row = (yield* Schema.decodeUnknownEffect(Schema.Array(FailedSettleRow))(updated).pipe(Effect.orDie))[0];
244
+ if (row === void 0) return false;
245
+ const retryAt = failedNextAttemptAt(retry, result, {
246
+ runKey: run.runKey,
247
+ failures: row.failures,
248
+ now: row.now
249
+ });
250
+ yield* sql`
251
+ UPDATE ${sql(runsTable)}
252
+ SET next_attempt_at = ${retryAt}::timestamptz
253
+ WHERE job = ${run.job}
254
+ AND run_key = ${run.runKey}
255
+ AND claim_token = ${run.token}::uuid
256
+ `;
257
+ yield* runSettleHook(sql, onSettle, {
258
+ job: run.job,
259
+ runKey: run.runKey,
260
+ attempt: run.attempt,
261
+ trigger: result.trigger,
262
+ annotations: result.annotations,
263
+ outcome: {
264
+ _tag: "Failed",
265
+ errorMessage: result.errorMessage,
266
+ reason: result.reason,
267
+ failures: row.failures,
268
+ nextAttemptAt: retryAt
269
+ }
270
+ });
271
+ return true;
272
+ }));
273
+ /**
274
+ * Dispatches `JobRuns.settle` based on the terminal `RunResult` variant. A settle that matched no
275
+ * running row still returns `true` when `run`'s own claim already settled it the same way: a repeat
276
+ * of a committed settle (retried after its connection dropped, say), not applied twice.
277
+ */
278
+ const settleRunSql = (context, run, result) => {
279
+ const { sql, runsTable } = context;
280
+ const status = result._tag === "Completed" ? "completed" : "failed";
281
+ const settle = result._tag === "Completed" ? settleCompletedSql(context, run, result) : settleFailedSql(context, run, result);
282
+ const settledByClaim = sql`
283
+ SELECT 1 FROM ${sql(runsTable)}
284
+ WHERE job = ${run.job} AND run_key = ${run.runKey}
285
+ AND status = ${status} AND claim_token = ${run.token}::uuid
286
+ `.pipe(Effect.map((rows) => rows.length > 0));
287
+ return Effect.flatMap(settle, (settled) => settled ? Effect.succeed(true) : settledByClaim);
288
+ };
289
+ /**
290
+ * Checks whether `(job, runKey)` currently has `status = 'completed'`.
291
+ */
292
+ const isRunCompletedSql = ({ sql, runsTable }, job, runKey) => sql`
293
+ SELECT 1
294
+ FROM ${sql(runsTable)}
295
+ WHERE job = ${job}
296
+ AND run_key = ${runKey}
297
+ AND status = 'completed'
298
+ `.pipe(Effect.map((rows) => rows.length > 0));
299
+ /**
300
+ * Queries recent run ledger rows ordered newest first, optionally filtered to one job. A row that
301
+ * fails to decode as `JobRunRecord` dies: it means the table and the schema disagree, a bug rather
302
+ * than a failure the caller can handle.
303
+ */
304
+ const queryRecentRunsSql = ({ sql, runsTable }, query) => {
305
+ const limit = Math.max(0, Math.trunc(query.limit));
306
+ if (limit === 0) return Effect.succeed([]);
307
+ const jobFilter = query.job === void 0 ? sql`` : sql`WHERE job = ${query.job}`;
308
+ return Effect.gen(function* () {
309
+ const rows = yield* sql`
310
+ SELECT
311
+ job,
312
+ run_key AS "runKey",
313
+ execution_id AS "executionId",
314
+ status,
315
+ attempt,
316
+ failures,
317
+ next_attempt_at AS "nextAttemptAt",
318
+ trigger,
319
+ params,
320
+ stats,
321
+ error_message AS "errorMessage",
322
+ started_at AS "startedAt",
323
+ finished_at AS "finishedAt"
324
+ FROM ${sql(runsTable)}
325
+ ${jobFilter}
326
+ ORDER BY started_at DESC, run_key DESC
327
+ LIMIT ${limit}
328
+ `;
329
+ return yield* Schema.decodeUnknownEffect(Schema.Array(JobRunRecord))(rows).pipe(Effect.orDie);
330
+ });
331
+ };
332
+ export { claimRunSql, heartbeatRunSql, isRunCompletedSql, queryRecentRunsSql, serializeJsonb, settleRunSql };