@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.
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,142 @@
1
+ import { JobRequests, isUuidString } from "./requests.js";
2
+ import { Clock, DateTime, Duration, Effect, Layer } from "effect";
3
+ // src/requests-memory.ts
4
+ /**
5
+ * Inserts or updates a pending request row in the in-memory store.
6
+ */
7
+ const createInMemory = Effect.fnUntraced(function* (store, input) {
8
+ const existingIndex = store.findIndex((row) => row.id === input.id);
9
+ const existing = existingIndex >= 0 ? store[existingIndex] : void 0;
10
+ if (existing !== void 0) {
11
+ const updated = {
12
+ ...existing,
13
+ executionId: existing.executionId ?? input.executionId
14
+ };
15
+ store[existingIndex] = updated;
16
+ return updated;
17
+ }
18
+ const row = {
19
+ id: input.id,
20
+ job: input.job,
21
+ params: input.params ?? {},
22
+ force: input.force,
23
+ executionId: input.executionId,
24
+ requestedAt: yield* DateTime.nowAsDate,
25
+ pickedAt: null,
26
+ finishedAt: null,
27
+ runKey: null,
28
+ outcome: null
29
+ };
30
+ store.push(row);
31
+ return row;
32
+ });
33
+ /**
34
+ * Marks a request row started in the in-memory store, inserting one if absent.
35
+ */
36
+ const upsertStartedInMemory = Effect.fnUntraced(function* (store, input) {
37
+ const now = yield* DateTime.nowAsDate;
38
+ const existingIndex = store.findIndex((row) => row.id === input.id);
39
+ const existing = existingIndex >= 0 ? store[existingIndex] : void 0;
40
+ if (existing !== void 0) {
41
+ store[existingIndex] = {
42
+ ...existing,
43
+ executionId: existing.executionId ?? input.executionId,
44
+ finishedAt: existing.pickedAt === null ? null : existing.finishedAt,
45
+ outcome: existing.pickedAt === null ? null : existing.outcome,
46
+ pickedAt: existing.pickedAt ?? now,
47
+ runKey: input.runKey ?? existing.runKey
48
+ };
49
+ return;
50
+ }
51
+ store.push({
52
+ id: input.id,
53
+ job: input.job,
54
+ params: input.params ?? {},
55
+ force: input.force,
56
+ executionId: input.executionId,
57
+ requestedAt: now,
58
+ pickedAt: now,
59
+ finishedAt: null,
60
+ runKey: input.runKey,
61
+ outcome: null
62
+ });
63
+ });
64
+ /**
65
+ * Marks a request row finished in the in-memory store unless it already finished after a pickup.
66
+ */
67
+ const markFinishedInMemory = Effect.fnUntraced(function* (store, input) {
68
+ const existingIndex = store.findIndex((row) => row.id === input.id);
69
+ const existing = existingIndex >= 0 ? store[existingIndex] : void 0;
70
+ if (existing === void 0 || existing.finishedAt !== null && existing.pickedAt !== null) return false;
71
+ const now = yield* DateTime.nowAsDate;
72
+ store[existingIndex] = {
73
+ ...existing,
74
+ pickedAt: existing.pickedAt ?? now,
75
+ runKey: input.runKey ?? existing.runKey,
76
+ outcome: input.outcome ?? null,
77
+ finishedAt: now
78
+ };
79
+ return true;
80
+ });
81
+ /**
82
+ * Marks an unpicked request row failed on dispatch error in the in-memory store.
83
+ */
84
+ const markDispatchFailedInMemory = Effect.fnUntraced(function* (store, input) {
85
+ const existingIndex = store.findIndex((row) => row.id === input.id);
86
+ const existing = existingIndex >= 0 ? store[existingIndex] : void 0;
87
+ if (existing === void 0 || existing.pickedAt !== null || existing.finishedAt !== null) return;
88
+ store[existingIndex] = {
89
+ ...existing,
90
+ finishedAt: yield* DateTime.nowAsDate,
91
+ outcome: {
92
+ job: input.job,
93
+ trigger: "api",
94
+ status: "failed",
95
+ errorTag: "WorkflowDispatchError",
96
+ errorMessage: input.errorMessage
97
+ }
98
+ };
99
+ });
100
+ /**
101
+ * Builds an in-memory `JobRequests` that reads time through the Effect `Clock`, so `TestClock`
102
+ * controls every timestamp.
103
+ */
104
+ const makeJobRequestsMemory = (options) => Effect.sync(() => {
105
+ const store = [];
106
+ const service = JobRequests.of({
107
+ create: (input) => createInMemory(store, input),
108
+ upsertStarted: (input) => upsertStartedInMemory(store, input),
109
+ markFinished: (input) => markFinishedInMemory(store, input),
110
+ markDispatchFailed: (input) => markDispatchFailedInMemory(store, input),
111
+ getStatus: (job, requestId) => Effect.sync(() => {
112
+ if (!isUuidString(requestId)) return;
113
+ const request = store.find((row) => row.id === requestId && row.job === job);
114
+ if (request === void 0) return;
115
+ const found = request.runKey === null ? void 0 : options?.findRun?.(request.job, request.runKey);
116
+ return {
117
+ request,
118
+ run: found !== void 0 && request.executionId !== null && found.executionId === request.executionId ? found : null
119
+ };
120
+ }),
121
+ prune: (olderThan, limit) => Effect.gen(function* () {
122
+ const cutoffMs = (yield* Clock.currentTimeMillis) - Math.max(0, Duration.toMillis(Duration.fromInputUnsafe(olderThan)));
123
+ let remaining = Math.max(1, Math.trunc(limit));
124
+ let deleted = 0;
125
+ for (let index = store.length - 1; index >= 0 && remaining > 0; index -= 1) {
126
+ const finishedAt = store[index]?.finishedAt;
127
+ if (finishedAt !== void 0 && finishedAt !== null && finishedAt.getTime() < cutoffMs) {
128
+ store.splice(index, 1);
129
+ deleted += 1;
130
+ remaining -= 1;
131
+ }
132
+ }
133
+ return deleted;
134
+ })
135
+ });
136
+ return {
137
+ layer: Layer.succeed(JobRequests, service),
138
+ service,
139
+ rows: () => [...store]
140
+ };
141
+ });
142
+ export { makeJobRequestsMemory };
@@ -0,0 +1,195 @@
1
+ import { JobRunRecord } from "./ledger-types.js";
2
+ import { Context, Duration, Effect, Schema } from "effect";
3
+ import { SqlClient, SqlError } from "effect/sql";
4
+ /**
5
+ * Schema of a request row. Effect Cluster owns queueing, delivery and crash recovery; the request
6
+ * table records which workflow execution an API request started and how it ended.
7
+ */
8
+ export declare const JobRequestRecord: Schema.Struct<{
9
+ /**
10
+ * Unique UUID assigned to this API request.
11
+ */
12
+ readonly id: Schema.String;
13
+ /**
14
+ * Registered job name targeted by this request.
15
+ */
16
+ readonly job: Schema.String;
17
+ /**
18
+ * JSON-encoded parameter overrides validated by the API.
19
+ */
20
+ readonly params: Schema.Unknown;
21
+ /**
22
+ * Whether the workflow should pass `force: true` when claiming `(job, runKey)`.
23
+ */
24
+ readonly force: Schema.Boolean;
25
+ /**
26
+ * Effect Workflow `executionId` linked to this request, or `null` when none was recorded.
27
+ */
28
+ readonly executionId: Schema.NullOr<Schema.String>;
29
+ /**
30
+ * Timestamp when the API recorded the request row.
31
+ */
32
+ readonly requestedAt: Schema.Date;
33
+ /**
34
+ * Timestamp when the workflow started processing the request, or `null` while pending.
35
+ */
36
+ readonly pickedAt: Schema.NullOr<Schema.Date>;
37
+ /**
38
+ * Timestamp when the workflow recorded the terminal outcome, or `null` until finished.
39
+ */
40
+ readonly finishedAt: Schema.NullOr<Schema.Date>;
41
+ /**
42
+ * Ledger run key executed for this request, or `null` until it started.
43
+ */
44
+ readonly runKey: Schema.NullOr<Schema.String>;
45
+ /**
46
+ * Serialized terminal `JobOutcome` (or failure summary) written on finish, or `null`.
47
+ */
48
+ readonly outcome: Schema.Unknown;
49
+ }>;
50
+ /**
51
+ * Decoded request row.
52
+ */
53
+ export type JobRequestRecord = typeof JobRequestRecord.Type;
54
+ /**
55
+ * Input passed to `JobRequests.create`.
56
+ */
57
+ export type CreateJobRequest = {
58
+ /**
59
+ * Pre-generated UUID for the request row (also used as the workflow's `attemptNonce`).
60
+ */
61
+ readonly id: string;
62
+ /**
63
+ * Registered job name.
64
+ */
65
+ readonly job: string;
66
+ /**
67
+ * JSON-safe encoded param overrides persisted in the request row.
68
+ */
69
+ readonly params: unknown;
70
+ /**
71
+ * Whether the worker should re-run an already completed key.
72
+ */
73
+ readonly force: boolean;
74
+ /**
75
+ * Deterministic Effect Workflow `executionId` dispatched for this request.
76
+ */
77
+ readonly executionId: string;
78
+ };
79
+ /**
80
+ * Input passed to `JobRequests.upsertStarted` from the workflow's first activity.
81
+ */
82
+ export type UpsertStartedJobRequest = {
83
+ /**
84
+ * Request UUID.
85
+ */
86
+ readonly id: string;
87
+ /**
88
+ * Registered job name.
89
+ */
90
+ readonly job: string;
91
+ /**
92
+ * Encoded parameter overrides (used only if the API crashed before inserting the row).
93
+ */
94
+ readonly params: unknown;
95
+ /**
96
+ * Force flag (used only if the API crashed before inserting the row).
97
+ */
98
+ readonly force: boolean;
99
+ /**
100
+ * Effect Workflow `executionId`.
101
+ */
102
+ readonly executionId: string;
103
+ /**
104
+ * Ledger run key claimed or targeted by the workflow.
105
+ */
106
+ readonly runKey: string | null;
107
+ };
108
+ /**
109
+ * Input passed to `JobRequests.markFinished`.
110
+ */
111
+ export type FinishJobRequest = {
112
+ /**
113
+ * Request UUID.
114
+ */
115
+ readonly id: string;
116
+ /**
117
+ * Ledger run key executed by the workflow, or `null` if stopped before claiming.
118
+ */
119
+ readonly runKey: string | null;
120
+ /**
121
+ * JSON-safe terminal outcome or error summary stored in the request row.
122
+ */
123
+ readonly outcome: unknown;
124
+ };
125
+ /**
126
+ * Input passed to `JobRequests.markDispatchFailed` when workflow enqueue fails after inserting the
127
+ * metadata row.
128
+ */
129
+ export type DispatchFailedJobRequest = {
130
+ /**
131
+ * Request UUID.
132
+ */
133
+ readonly id: string;
134
+ /**
135
+ * Registered job name.
136
+ */
137
+ readonly job: string;
138
+ /**
139
+ * Redacted dispatch failure message.
140
+ */
141
+ readonly errorMessage: string;
142
+ };
143
+ /**
144
+ * Combined status returned by `JobRequests.getStatus`: the request row paired with its matching run
145
+ * ledger row when there is one.
146
+ */
147
+ export type JobRequestStatus = {
148
+ /**
149
+ * Persisted request row.
150
+ */
151
+ readonly request: JobRequestRecord;
152
+ /**
153
+ * Ledger row of `(request.job, request.runKey)` while it belongs to the request's workflow
154
+ * execution, or `null` while pending, absent, or held by another execution (a run that took the
155
+ * key from it, or one that ran before it).
156
+ */
157
+ readonly run: JobRunRecord | null;
158
+ };
159
+ declare const JobRequests_base: Context.ServiceClass<JobRequests, "@yieldkit/jobs/JobRequests", {
160
+ /**
161
+ * Persists a pending request row linked to `executionId`.
162
+ */
163
+ readonly create: (input: CreateJobRequest) => Effect.Effect<JobRequestRecord, SqlError.SqlError | Schema.SchemaError>;
164
+ /**
165
+ * Idempotently marks the request as picked up and linked to `runKey`, creating the row if the
166
+ * dispatching process crashed before persisting it.
167
+ */
168
+ readonly upsertStarted: (input: UpsertStartedJobRequest) => Effect.Effect<void, SqlError.SqlError>;
169
+ /**
170
+ * Records the terminal `runKey`, `outcome` and `finishedAt` of a request. Returns `false` when
171
+ * it had already finished.
172
+ */
173
+ readonly markFinished: (input: FinishJobRequest) => Effect.Effect<boolean, SqlError.SqlError>;
174
+ /**
175
+ * Marks a never-picked request row as failed after dispatching its workflow failed.
176
+ */
177
+ readonly markDispatchFailed: (input: DispatchFailedJobRequest) => Effect.Effect<void, SqlError.SqlError>;
178
+ /**
179
+ * Looks up a request by `(job, requestId)` together with its ledger row, when that row belongs
180
+ * to the request's execution. Returns `undefined` when it is missing or `requestId` is not a
181
+ * valid UUID.
182
+ */
183
+ readonly getStatus: (job: string, requestId: string) => Effect.Effect<JobRequestStatus | undefined, SqlError.SqlError | Schema.SchemaError>;
184
+ /**
185
+ * Deletes up to `limit` rows that finished more than `olderThan` ago and returns how many it
186
+ * deleted. Unfinished rows are kept.
187
+ */
188
+ readonly prune: (olderThan: Duration.Input, limit: number) => Effect.Effect<number, SqlError.SqlError>;
189
+ }>;
190
+ /**
191
+ * Request store: links each API request to its Effect Workflow `executionId` and ledger row.
192
+ * Queueing, delivery, retries and crash recovery are Effect Cluster's job.
193
+ */
194
+ export declare class JobRequests extends JobRequests_base {}
195
+ export {};
@@ -0,0 +1,242 @@
1
+ import { serializeJsonb } from "./ledger-sql.js";
2
+ import { JobRunRecord } from "./ledger-types.js";
3
+ import { Context, Duration, Effect, Schema } from "effect";
4
+ // src/requests.ts
5
+ /**
6
+ * Strict canonical UUID pattern checked before casting a caller-supplied `requestId` to PostgreSQL
7
+ * `uuid`, so malformed IDs return `undefined` instead of raising a SQL syntax error.
8
+ */
9
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
+ /**
11
+ * Schema of a request row. Effect Cluster owns queueing, delivery and crash recovery; the request
12
+ * table records which workflow execution an API request started and how it ended.
13
+ */
14
+ const JobRequestRecord = Schema.Struct({
15
+ /**
16
+ * Unique UUID assigned to this API request.
17
+ */
18
+ id: Schema.String,
19
+ /**
20
+ * Registered job name targeted by this request.
21
+ */
22
+ job: Schema.String,
23
+ /**
24
+ * JSON-encoded parameter overrides validated by the API.
25
+ */
26
+ params: Schema.Unknown,
27
+ /**
28
+ * Whether the workflow should pass `force: true` when claiming `(job, runKey)`.
29
+ */
30
+ force: Schema.Boolean,
31
+ /**
32
+ * Effect Workflow `executionId` linked to this request, or `null` when none was recorded.
33
+ */
34
+ executionId: Schema.NullOr(Schema.String),
35
+ /**
36
+ * Timestamp when the API recorded the request row.
37
+ */
38
+ requestedAt: Schema.Date,
39
+ /**
40
+ * Timestamp when the workflow started processing the request, or `null` while pending.
41
+ */
42
+ pickedAt: Schema.NullOr(Schema.Date),
43
+ /**
44
+ * Timestamp when the workflow recorded the terminal outcome, or `null` until finished.
45
+ */
46
+ finishedAt: Schema.NullOr(Schema.Date),
47
+ /**
48
+ * Ledger run key executed for this request, or `null` until it started.
49
+ */
50
+ runKey: Schema.NullOr(Schema.String),
51
+ /**
52
+ * Serialized terminal `JobOutcome` (or failure summary) written on finish, or `null`.
53
+ */
54
+ outcome: Schema.Unknown
55
+ });
56
+ /**
57
+ * Returns `true` when `value` matches the canonical 36-character UUID syntax accepted by
58
+ * PostgreSQL's `uuid` type.
59
+ */
60
+ const isUuidString = (value) => UUID_PATTERN.test(value);
61
+ /**
62
+ * Inserts a pending request row linked to `input.executionId`.
63
+ */
64
+ const createRequestSql = Effect.fnUntraced(function* ({ sql, requestsTable }, input) {
65
+ const paramsJson = serializeJsonb(input.params) ?? "{}";
66
+ const rows = yield* sql`
67
+ INSERT INTO ${sql(requestsTable)} AS existing (id, job, params, force, execution_id)
68
+ VALUES (${input.id}::uuid, ${input.job}, ${paramsJson}::jsonb, ${input.force}, ${input.executionId})
69
+ ON CONFLICT (id) DO UPDATE SET
70
+ execution_id = COALESCE(existing.execution_id, EXCLUDED.execution_id)
71
+ RETURNING
72
+ id::text AS id,
73
+ job,
74
+ params,
75
+ force,
76
+ execution_id AS "executionId",
77
+ requested_at AS "requestedAt",
78
+ picked_at AS "pickedAt",
79
+ finished_at AS "finishedAt",
80
+ run_key AS "runKey",
81
+ outcome
82
+ `;
83
+ const row = (yield* Schema.decodeUnknownEffect(Schema.Array(JobRequestRecord))(rows))[0];
84
+ if (row === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("The request insert returned no row."));
85
+ return row;
86
+ });
87
+ /**
88
+ * Idempotently upserts the request row when the durable workflow begins executing, so it exists
89
+ * with `picked_at` and `run_key` even if the dispatching process crashed right after dispatch. A
90
+ * row that finished without ever being picked up holds a provisional `markDispatchFailed` outcome
91
+ * (the dispatch reached Cluster after all), so pickup clears it.
92
+ */
93
+ const upsertStartedSql = ({ sql, requestsTable }, input) => {
94
+ const paramsJson = serializeJsonb(input.params) ?? "{}";
95
+ return sql`
96
+ INSERT INTO ${sql(requestsTable)} AS existing (id, job, params, force, execution_id, picked_at, run_key)
97
+ VALUES (
98
+ ${input.id}::uuid,
99
+ ${input.job},
100
+ ${paramsJson}::jsonb,
101
+ ${input.force},
102
+ ${input.executionId},
103
+ NOW(),
104
+ ${input.runKey}
105
+ )
106
+ ON CONFLICT (id) DO UPDATE SET
107
+ execution_id = COALESCE(existing.execution_id, EXCLUDED.execution_id),
108
+ picked_at = COALESCE(existing.picked_at, NOW()),
109
+ run_key = COALESCE(EXCLUDED.run_key, existing.run_key),
110
+ finished_at = CASE WHEN existing.picked_at IS NULL THEN NULL ELSE existing.finished_at END,
111
+ outcome = CASE WHEN existing.picked_at IS NULL THEN NULL ELSE existing.outcome END
112
+ `.pipe(Effect.asVoid);
113
+ };
114
+ /**
115
+ * Records the terminal `run_key`, `outcome` and `finished_at` of a request that has not finished,
116
+ * or whose only outcome is a provisional `markDispatchFailed` one (it was never picked up).
117
+ */
118
+ const markFinishedSql = ({ sql, requestsTable }, input) => {
119
+ const outcomeJson = serializeJsonb(input.outcome);
120
+ return sql`
121
+ UPDATE ${sql(requestsTable)}
122
+ SET
123
+ run_key = COALESCE(${input.runKey}, run_key),
124
+ outcome = ${outcomeJson}::jsonb,
125
+ picked_at = COALESCE(picked_at, NOW()),
126
+ finished_at = NOW()
127
+ WHERE id = ${input.id}::uuid
128
+ AND (finished_at IS NULL OR picked_at IS NULL)
129
+ RETURNING 1
130
+ `.pipe(Effect.map((rows) => rows.length > 0));
131
+ };
132
+ /**
133
+ * Marks a never-picked request row as failed when workflow dispatch throws. Leaves rows already
134
+ * picked up by a worker untouched so a post-commit network error never erases an active run.
135
+ */
136
+ const markDispatchFailedSql = ({ sql, requestsTable }, input) => {
137
+ const outcomeJson = serializeJsonb({
138
+ job: input.job,
139
+ trigger: "api",
140
+ status: "failed",
141
+ errorTag: "WorkflowDispatchError",
142
+ errorMessage: input.errorMessage
143
+ });
144
+ return sql`
145
+ UPDATE ${sql(requestsTable)}
146
+ SET
147
+ finished_at = NOW(),
148
+ outcome = ${outcomeJson}::jsonb
149
+ WHERE id = ${input.id}::uuid
150
+ AND picked_at IS NULL
151
+ AND finished_at IS NULL
152
+ `.pipe(Effect.asVoid);
153
+ };
154
+ /**
155
+ * Fetches `(job, requestId)` together with its ledger row when `run_key` is set and the row belongs
156
+ * to the request's execution. Returns `undefined` for missing rows and malformed UUIDs.
157
+ */
158
+ const getRequestStatusSql = Effect.fnUntraced(function* ({ sql, requestsTable, runsTable }, job, requestId) {
159
+ if (!isUuidString(requestId)) return;
160
+ const requestRows = yield* sql`
161
+ SELECT
162
+ id::text AS id,
163
+ job,
164
+ params,
165
+ force,
166
+ execution_id AS "executionId",
167
+ requested_at AS "requestedAt",
168
+ picked_at AS "pickedAt",
169
+ finished_at AS "finishedAt",
170
+ run_key AS "runKey",
171
+ outcome
172
+ FROM ${sql(requestsTable)}
173
+ WHERE id = ${requestId}::uuid
174
+ AND job = ${job}
175
+ `;
176
+ const request = (yield* Schema.decodeUnknownEffect(Schema.Array(JobRequestRecord))(requestRows))[0];
177
+ if (request === void 0) return;
178
+ if (request.runKey === null) return {
179
+ request,
180
+ run: null
181
+ };
182
+ const runRows = yield* sql`
183
+ SELECT
184
+ job,
185
+ run_key AS "runKey",
186
+ execution_id AS "executionId",
187
+ status,
188
+ attempt,
189
+ failures,
190
+ next_attempt_at AS "nextAttemptAt",
191
+ trigger,
192
+ params,
193
+ stats,
194
+ error_message AS "errorMessage",
195
+ started_at AS "startedAt",
196
+ finished_at AS "finishedAt"
197
+ FROM ${sql(runsTable)}
198
+ WHERE job = ${request.job}
199
+ AND run_key = ${request.runKey}
200
+ AND execution_id = ${request.executionId}
201
+ `;
202
+ return {
203
+ request,
204
+ run: (yield* Schema.decodeUnknownEffect(Schema.Array(JobRunRecord))(runRows))[0] ?? null
205
+ };
206
+ });
207
+ /**
208
+ * Deletes up to `limit` request rows that finished more than `olderThan` ago. Unfinished rows are
209
+ * kept. Returns the deleted row count.
210
+ */
211
+ const pruneRequestsSql = ({ sql, requestsTable }, olderThan, limit) => {
212
+ const cutoffMs = Math.max(0, Duration.toMillis(Duration.fromInputUnsafe(olderThan)));
213
+ const batch = Math.max(1, Math.trunc(limit));
214
+ return sql`
215
+ DELETE FROM ${sql(requestsTable)}
216
+ WHERE id IN (
217
+ SELECT id
218
+ FROM ${sql(requestsTable)}
219
+ WHERE finished_at IS NOT NULL
220
+ AND finished_at < NOW() - (${cutoffMs}::double precision * INTERVAL '1 millisecond')
221
+ LIMIT ${batch}
222
+ )
223
+ RETURNING 1
224
+ `.pipe(Effect.map((rows) => rows.length));
225
+ };
226
+ /**
227
+ * Request store: links each API request to its Effect Workflow `executionId` and ledger row.
228
+ * Queueing, delivery, retries and crash recovery are Effect Cluster's job.
229
+ */
230
+ var JobRequests = class extends Context.Service()("@yieldkit/jobs/JobRequests") {};
231
+ /**
232
+ * Builds the SQL `JobRequests` service over `context`.
233
+ */
234
+ const makeSqlJobRequests = (context) => JobRequests.of({
235
+ create: (input) => createRequestSql(context, input),
236
+ upsertStarted: (input) => upsertStartedSql(context, input),
237
+ markFinished: (input) => markFinishedSql(context, input),
238
+ markDispatchFailed: (input) => markDispatchFailedSql(context, input),
239
+ getStatus: (job, requestId) => getRequestStatusSql(context, job, requestId),
240
+ prune: (olderThan, limit) => pruneRequestsSql(context, olderThan, limit)
241
+ });
242
+ export { JobRequestRecord, JobRequests, isUuidString, makeSqlJobRequests };
@@ -0,0 +1,25 @@
1
+ import "./errors.js";
2
+ import { JobCadence } from "./job.js";
3
+ import { Effect } from "effect";
4
+ /**
5
+ * Constant `run_key` used by all `Once` jobs.
6
+ */
7
+ export declare const ONCE_RUN_KEY = "once";
8
+ /**
9
+ * A cadence whose run keys come from the clock: every cadence except `OnDemand`, whose keys the
10
+ * caller chooses.
11
+ */
12
+ export type ClockCadence = Exclude<JobCadence, {
13
+ readonly _tag: 'OnDemand';
14
+ }>;
15
+ /**
16
+ * Computes the deterministic ledger key of the run due at `nowMs` (epoch milliseconds):
17
+ *
18
+ * - `Daily`: the local date `YYYY-MM-DD` in the cadence's time zone (UTC by default)
19
+ * - `Every`: bucket start `floor(nowMs / intervalMs) * intervalMs` as `YYYY-MM-DDTHH:MMZ`
20
+ * - `Cron`: the latest tick at or before `nowMs`, in UTC, as `YYYY-MM-DDTHH:MMZ`
21
+ * - `Once`: `'once'`
22
+ *
23
+ * Throws for a `Daily` time zone or `Cron` expression that `makeSchedulerLayer` would reject.
24
+ */
25
+ export declare const runKeyFor: (cadence: ClockCadence, nowMs: number) => string;
@@ -0,0 +1,85 @@
1
+ import { latestCronTick, parseCronCadence, runKeyProblem } from "./calendar.js";
2
+ import { validateJobCadence } from "./cron.js";
3
+ import { InvalidRunKey } from "./errors.js";
4
+ import { localTimeOf } from "./time-zone.js";
5
+ import { Duration, Effect, Result } from "effect";
6
+ // src/run-key.ts
7
+ /**
8
+ * Constant `run_key` used by all `Once` jobs.
9
+ */
10
+ const ONCE_RUN_KEY = "once";
11
+ /**
12
+ * Zero-pads a non-negative integer to at least `width` digits.
13
+ */
14
+ const pad = (value, width) => String(value).padStart(width, "0");
15
+ /**
16
+ * Formats a UTC millisecond timestamp as `YYYY-MM-DD`.
17
+ */
18
+ const formatUtcDay = (ms) => {
19
+ const date = new Date(ms);
20
+ return `${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1, 2)}-${pad(date.getUTCDate(), 2)}`;
21
+ };
22
+ /**
23
+ * Formats a UTC millisecond timestamp as `YYYY-MM-DDTHH:MMZ` for `Every` bucket keys.
24
+ */
25
+ const formatUtcBucket = (ms) => {
26
+ const date = new Date(ms);
27
+ return `${formatUtcDay(ms)}T${pad(date.getUTCHours(), 2)}:${pad(date.getUTCMinutes(), 2)}Z`;
28
+ };
29
+ /**
30
+ * Computes the deterministic ledger key of the run due at `nowMs` (epoch milliseconds):
31
+ *
32
+ * - `Daily`: the local date `YYYY-MM-DD` in the cadence's time zone (UTC by default)
33
+ * - `Every`: bucket start `floor(nowMs / intervalMs) * intervalMs` as `YYYY-MM-DDTHH:MMZ`
34
+ * - `Cron`: the latest tick at or before `nowMs`, in UTC, as `YYYY-MM-DDTHH:MMZ`
35
+ * - `Once`: `'once'`
36
+ *
37
+ * Throws for a `Daily` time zone or `Cron` expression that `makeSchedulerLayer` would reject.
38
+ */
39
+ const runKeyFor = (cadence, nowMs) => {
40
+ switch (cadence._tag) {
41
+ case "Daily": return localTimeOf(cadence.timeZone ?? "UTC", nowMs).date;
42
+ case "Every": {
43
+ const intervalMs = Math.max(1, Duration.toMillis(Duration.fromInputUnsafe(cadence.interval)));
44
+ const bucketStartMs = Math.floor(nowMs / intervalMs) * intervalMs;
45
+ return formatUtcBucket(bucketStartMs);
46
+ }
47
+ case "Cron": {
48
+ const cron = Result.getOrThrowWith(parseCronCadence(cadence), (message) => new Error(message));
49
+ return formatUtcBucket(latestCronTick(cron, nowMs));
50
+ }
51
+ case "Once": return ONCE_RUN_KEY;
52
+ default: return cadence;
53
+ }
54
+ };
55
+ /**
56
+ * Resolves the run key of a run of `job` starting at `nowMs`: the caller's `runKey` for an
57
+ * `OnDemand` job, which needs one, else `runKeyFor` of the cadence, which takes none. Fails with
58
+ * `InvalidRunKey` otherwise or when the caller's key is malformed, and with `ClusterConfigError`
59
+ * when the cadence is invalid (an unknown time zone, an expression that never matches, an interval
60
+ * the scheduler would reject).
61
+ */
62
+ const resolveRunKey = (job, nowMs, runKey) => {
63
+ const { cadence } = job;
64
+ if (cadence._tag !== "OnDemand") return runKey === void 0 ? validateJobCadence(job).pipe(Effect.map(() => runKeyFor(cadence, nowMs))) : Effect.fail(new InvalidRunKey({
65
+ job: job.name,
66
+ message: `Job "${job.name}" has a ${cadence._tag} cadence: its run keys come from the clock. Only OnDemand jobs take a run key.`
67
+ }));
68
+ return resolveCallerRunKey(job.name, runKey);
69
+ };
70
+ /**
71
+ * Checks the caller-chosen `runKey` of a run of the `OnDemand` job `job`. Fails with
72
+ * `InvalidRunKey` when it is missing or malformed.
73
+ */
74
+ const resolveCallerRunKey = (job, runKey) => {
75
+ if (runKey === void 0) return Effect.fail(new InvalidRunKey({
76
+ job,
77
+ message: `OnDemand job "${job}" needs a run key.`
78
+ }));
79
+ const problem = runKeyProblem(runKey);
80
+ return problem === void 0 ? Effect.succeed(runKey) : Effect.fail(new InvalidRunKey({
81
+ job,
82
+ message: problem
83
+ }));
84
+ };
85
+ export { ONCE_RUN_KEY, resolveCallerRunKey, resolveRunKey, runKeyFor };