@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,205 @@
1
+ import { ClusterConfigError } from "./errors.js";
2
+ import "./policy.js";
3
+ import { isValidTimeZone, latestInstantOf, localTimeOf } from "./time-zone.js";
4
+ import { Cron, Duration, Effect, Option, Result } from "effect";
5
+ // src/calendar.ts
6
+ /**
7
+ * Number of minutes in one day; also the `until` value `24:00`.
8
+ */
9
+ const MINUTES_PER_DAY = 1440;
10
+ /**
11
+ * Number of milliseconds in one minute.
12
+ */
13
+ const MILLIS_PER_MINUTE = 6e4;
14
+ /**
15
+ * Parses `HH:MM` into minutes since midnight, `24:00` only when `allowEndOfDay`. Returns
16
+ * `undefined` for anything else.
17
+ */
18
+ const parseTimeOfDay = (value, allowEndOfDay) => {
19
+ const match = /^(\d{2}):(\d{2})$/.exec(value);
20
+ if (match === null) return;
21
+ const minutes = Number(match[1]) * 60 + Number(match[2]);
22
+ if (Number(match[2]) >= 60) return;
23
+ return minutes < MINUTES_PER_DAY || allowEndOfDay && minutes === MINUTES_PER_DAY ? minutes : void 0;
24
+ };
25
+ /**
26
+ * 32-bit FNV-1a hash of `value`, used to pick a window slot that every worker agrees on.
27
+ */
28
+ const fnv1a = (value) => {
29
+ let hash = 2166136261;
30
+ for (let index = 0; index < value.length; index += 1) hash = Math.imul(hash ^ value.charCodeAt(index), 16777619) >>> 0;
31
+ return hash;
32
+ };
33
+ /**
34
+ * The schedule of a `Daily` cadence with `at`: due at `at`, until `until` or `24:00`.
35
+ */
36
+ const atSchedule = (base, at, untilMinute) => {
37
+ const atMinute = parseTimeOfDay(at, false);
38
+ if (atMinute === void 0) return Result.fail(`Daily at "${at}" must be HH:MM between 00:00 and 23:59.`);
39
+ const deadline = untilMinute ?? MINUTES_PER_DAY;
40
+ if (deadline - atMinute < base.checkEveryMinutes) return Result.fail(`Daily until must be at least checkEvery (${String(base.checkEveryMinutes)} minutes) after at.`);
41
+ return Result.succeed({
42
+ ...base,
43
+ dueMinuteOn: () => atMinute,
44
+ untilMinute: deadline,
45
+ firstStartBeforeMinute: void 0
46
+ });
47
+ };
48
+ /**
49
+ * The schedule of a `Daily` cadence with `window`: due at a slot of `checkEvery` steps from
50
+ * `window.from`, picked by hashing the job name and date, until `until` or `window.to`.
51
+ */
52
+ const windowSchedule = (base, job, window, untilMinute) => {
53
+ const from = parseTimeOfDay(window.from, false);
54
+ const to = parseTimeOfDay(window.to, true);
55
+ if (from === void 0 || to === void 0) return Result.fail("Daily window from and to must be HH:MM.");
56
+ const step = base.checkEveryMinutes;
57
+ const slots = Math.floor((to - from) / step);
58
+ if (slots < 1) return Result.fail(`Daily window must be at least checkEvery (${String(step)} minutes) long.`);
59
+ const deadline = untilMinute ?? to;
60
+ if (deadline < to) return Result.fail("Daily until must not be before window.to.");
61
+ return Result.succeed({
62
+ ...base,
63
+ dueMinuteOn: (date) => from + fnv1a(`${job}:${date}`) % slots * step,
64
+ untilMinute: deadline,
65
+ firstStartBeforeMinute: deadline > to ? void 0 : to
66
+ });
67
+ };
68
+ /**
69
+ * Validates a `Daily` cadence of job `job` and resolves its schedule, or returns why it is invalid.
70
+ */
71
+ const dailyScheduleFor = (job, cadence) => {
72
+ const timeZone = cadence.timeZone ?? "UTC";
73
+ if (!isValidTimeZone(timeZone)) return Result.fail(`Daily timeZone "${timeZone}" is not a known IANA time zone.`);
74
+ const checkEvery = Duration.fromInput(cadence.checkEvery ?? "1 hour");
75
+ if (Option.isNone(checkEvery)) return Result.fail("Daily checkEvery must be a duration.");
76
+ const checkEveryMs = Duration.toMillis(checkEvery.value);
77
+ const base = {
78
+ timeZone,
79
+ checkEveryMinutes: Math.max(1, Math.floor(checkEveryMs / MILLIS_PER_MINUTE))
80
+ };
81
+ const untilMinute = cadence.until === void 0 ? void 0 : parseTimeOfDay(cadence.until, true);
82
+ if (cadence.until !== void 0 && untilMinute === void 0) return Result.fail(`Daily until "${cadence.until}" must be HH:MM between 00:00 and 24:00.`);
83
+ if (cadence.at !== void 0 && cadence.window !== void 0) return Result.fail("Daily takes at or window, not both.");
84
+ if (cadence.at !== void 0) return atSchedule(base, cadence.at, untilMinute);
85
+ if (cadence.window !== void 0) return windowSchedule(base, job, cadence.window, untilMinute);
86
+ if (untilMinute !== void 0 && untilMinute < base.checkEveryMinutes) return Result.fail(`Daily until must be at least checkEvery (${String(base.checkEveryMinutes)} minutes) after 00:00.`);
87
+ return Result.succeed({
88
+ ...base,
89
+ dueMinuteOn: () => 0,
90
+ untilMinute,
91
+ firstStartBeforeMinute: void 0
92
+ });
93
+ };
94
+ /**
95
+ * `dailyScheduleFor` for a cadence the scheduler already validated; an invalid one is a defect.
96
+ */
97
+ const dailyScheduleOrThrow = (job, cadence) => {
98
+ const resolved = dailyScheduleFor(job, cadence);
99
+ if (Result.isFailure(resolved)) throw new Error(`Job "${job}": ${resolved.failure}`);
100
+ return resolved.success;
101
+ };
102
+ /**
103
+ * The `maxFailures` a failed settle of `cadence` passes to the ledger: `Infinity` for a `Daily`
104
+ * cadence with a deadline, whose workflow stops at `until` instead of after
105
+ * `retry.dailyMaxFailures` failures; `undefined` (the policy's budget) otherwise.
106
+ */
107
+ const failureBudgetFor = (cadence) => {
108
+ if (cadence._tag !== "Daily") return;
109
+ const resolved = dailyScheduleFor("", cadence);
110
+ return Result.isSuccess(resolved) && resolved.success.untilMinute !== void 0 ? Number.POSITIVE_INFINITY : void 0;
111
+ };
112
+ /**
113
+ * Whether a run of the day `runKey` may still start at `ms`: always without `until`, else when the
114
+ * minute of `ms` is at or before the minute `until` falls on that local date (`24:00` counts as
115
+ * 23:59). Instants are compared, so a deadline in the hour skipped by a daylight saving change
116
+ * lands that long after the change, and one in a repeated hour at its second occurrence.
117
+ */
118
+ const isWithinDailyDeadline = (schedule, runKey, ms) => {
119
+ if (schedule.untilMinute === void 0) return true;
120
+ const deadlineMs = latestInstantOf(schedule.timeZone, runKey, Math.min(schedule.untilMinute, 1439));
121
+ return Math.floor(ms / MILLIS_PER_MINUTE) * MILLIS_PER_MINUTE <= deadlineMs;
122
+ };
123
+ /**
124
+ * Whether the scheduler should start the day's run on a check scheduled at `scheduledMs` and
125
+ * handled at `nowMs`: the check's local time has reached the day's due time, `nowMs` is not past
126
+ * `until` and, for a window, `nowMs` is before `window.to` unless an explicit `until` is later or
127
+ * the spring change skips the day's slot and `window.to` with it.
128
+ */
129
+ const isDailyRunDue = (schedule, scheduledMs, nowMs) => {
130
+ const { date, minute } = localTimeOf(schedule.timeZone, scheduledMs);
131
+ const dueMinute = schedule.dueMinuteOn(date);
132
+ if (minute < dueMinute) return false;
133
+ const startBefore = schedule.firstStartBeforeMinute;
134
+ if (startBefore !== void 0) {
135
+ const endMs = latestInstantOf(schedule.timeZone, date, startBefore);
136
+ if (!(latestInstantOf(schedule.timeZone, date, dueMinute) >= endMs) && nowMs >= endMs) return false;
137
+ }
138
+ return isWithinDailyDeadline(schedule, date, nowMs);
139
+ };
140
+ /**
141
+ * Parses the expression of a `Cron` cadence in its time zone, or returns why it is invalid. Only
142
+ * five fields are accepted, since run keys have minute precision. A local time repeated by a
143
+ * daylight saving change runs once, at its first occurrence.
144
+ */
145
+ const parseCronCadence = (cadence) => {
146
+ if (cadence.expression.trim().split(/\s+/).length !== 5) return Result.fail(`Cron expression "${cadence.expression}" must have five fields (minute hour day month weekday).`);
147
+ return Cron.parse(cadence.expression, cadence.timeZone ?? "UTC", { onDstOverlap: "earlier" }).pipe(Result.mapError((error) => `Cron expression "${cadence.expression}" is invalid: ${error.message}`), Result.flatMap((cron) => hasOccurrences(cron) ? Result.succeed(cron) : Result.fail(`Cron expression "${cadence.expression}" never matches a date.`)));
148
+ };
149
+ /**
150
+ * Reference instant for `hasOccurrences`; five-field expressions repeat every few years at most.
151
+ */
152
+ const OCCURRENCE_REFERENCE = new Date(Date.UTC(2e3, 0, 1));
153
+ /**
154
+ * Whether `cron` has a tick before and after a reference date. An expression such as `0 0 31 2 *`
155
+ * parses but never matches, and `Cron.next` and `Cron.prev` throw for it.
156
+ */
157
+ const hasOccurrences = (cron) => {
158
+ try {
159
+ Cron.next(cron, OCCURRENCE_REFERENCE);
160
+ Cron.prev(cron, OCCURRENCE_REFERENCE);
161
+ return true;
162
+ } catch {
163
+ return false;
164
+ }
165
+ };
166
+ /**
167
+ * Checks that the `catchUpWithin` of a `Cron` cadence is a finite duration above zero.
168
+ */
169
+ const cronCatchUpProblem = (cadence) => {
170
+ const catchUp = Duration.fromInput(cronCatchUpFor(cadence));
171
+ return Option.isSome(catchUp) && Duration.isFinite(catchUp.value) && Duration.toMillis(catchUp.value) > 0 ? Result.void : Result.fail("Cron catchUpWithin must be a finite duration above zero.");
172
+ };
173
+ /**
174
+ * Latest tick of `cron` at or before `nowMs`, in epoch milliseconds.
175
+ */
176
+ const latestCronTick = (cron, nowMs) => Cron.prev(cron, new Date(nowMs + 1)).getTime();
177
+ /**
178
+ * How late a missed tick of a `Cron` cadence may still run.
179
+ */
180
+ const cronCatchUpFor = (cadence) => cadence.catchUpWithin ?? "1 hour";
181
+ /**
182
+ * Validates the parts of `cadence` the scheduler and `runKeyFor` read at run time: the time zone,
183
+ * times and window of a `Daily` cadence, and the expression and `catchUpWithin` of a `Cron`
184
+ * cadence. Fails with `ClusterConfigError` naming `job`.
185
+ */
186
+ const validateCadence = (job, cadence) => {
187
+ let checked = Result.succeed(void 0);
188
+ if (cadence._tag === "Daily") checked = dailyScheduleFor(job, cadence);
189
+ else if (cadence._tag === "Cron") checked = parseCronCadence(cadence).pipe(Result.flatMap(() => cronCatchUpProblem(cadence)));
190
+ return Result.isSuccess(checked) ? Effect.void : Effect.fail(new ClusterConfigError({ message: `Job "${job}": ${checked.failure}` }));
191
+ };
192
+ /**
193
+ * Longest run key an `OnDemand` caller may choose.
194
+ */
195
+ const MAX_RUN_KEY_LENGTH = 200;
196
+ /**
197
+ * Returns why `runKey` is not a valid caller-chosen run key, or `undefined` when it is: 1 to
198
+ * `MAX_RUN_KEY_LENGTH` printable ASCII characters, no spaces.
199
+ */
200
+ const runKeyProblem = (runKey) => {
201
+ if (typeof runKey !== "string") return "Run key must be a string.";
202
+ if (runKey.length === 0 || runKey.length > 200) return `Run key must be 1 to ${String(200)} characters long.`;
203
+ return /^[!-~]+$/.test(runKey) ? void 0 : "Run key may only hold printable ASCII characters without spaces.";
204
+ };
205
+ export { MAX_RUN_KEY_LENGTH, cronCatchUpFor, dailyScheduleFor, dailyScheduleOrThrow, failureBudgetFor, isDailyRunDue, isWithinDailyDeadline, latestCronTick, parseCronCadence, runKeyProblem, validateCadence };
@@ -0,0 +1,54 @@
1
+ import { AnyJobDefinition } from "./job.js";
2
+ import { ClusterConfigError } from "./errors.js";
3
+ import { Effect, Layer } from "effect";
4
+ import { WorkflowEngine } from "effect/workflow";
5
+ import { MessageStorage, Runners, Sharding, ShardingConfig } from "effect/cluster";
6
+ /**
7
+ * Effect Cluster's default shard group, which entities without a group of their own use. A job's
8
+ * durable clocks run in the job's own group, not here.
9
+ */
10
+ export declare const DEFAULT_SHARD_GROUP = "default";
11
+ /**
12
+ * Shard group of the library's maintenance singleton. It is the library's own, so runners of your
13
+ * application that do not run `makeSchedulerLayer` never claim it and keep it from running.
14
+ */
15
+ export declare const MAINTENANCE_SHARD_GROUP = "yieldkit-jobs";
16
+ /**
17
+ * Cluster services the jobs engine uses: a worker needs all of them, a client only
18
+ * `WorkflowEngine`.
19
+ */
20
+ export type ClusterServices = Sharding.Sharding | Runners.Runners | MessageStorage.MessageStorage | WorkflowEngine.WorkflowEngine;
21
+ /**
22
+ * Shard groups the jobs engine needs in `ShardingConfig.availableShardGroups` of every runner and
23
+ * client: `default`, the maintenance group and one group per job that is not a manual `Once` job.
24
+ * Add them to your own groups.
25
+ */
26
+ export declare const availableShardGroupsFor: (allJobs: ReadonlyArray<Pick<AnyJobDefinition, 'name' | 'cadence'>>) => ReadonlyArray<string>;
27
+ /**
28
+ * Shard groups a worker running `makeSchedulerLayer(allJobs, { only })` must claim in
29
+ * `ShardingConfig.assignedShardGroups`: `default`, the maintenance group, and the groups of the
30
+ * jobs `only` selects (every job that is not a manual `Once` job without it). Add them to your
31
+ * own.
32
+ */
33
+ export declare const assignedShardGroupsFor: (allJobs: ReadonlyArray<Pick<AnyJobDefinition, 'name' | 'cadence'>>, only: ReadonlyArray<string> | undefined) => ReadonlyArray<string>;
34
+ /**
35
+ * Checks the `ShardingConfig` of a client or worker against `allJobs`: every job name is unique,
36
+ * holds only `A-Z`, `a-z`, `0-9`, `.`, `_` and `-`, and is not the default or maintenance group,
37
+ * `availableShardGroups` holds every group of `availableShardGroupsFor`, and each job's shard ids
38
+ * fit Effect Cluster's `shard_id` column with the configured `shardsPerGroup`. A missing group
39
+ * would not fail anywhere else: its messages would be stored and never run. Fails with
40
+ * `ClusterConfigError` naming the offending names or groups. `makeSchedulerLayer` runs it; clients
41
+ * can run it at start-up.
42
+ */
43
+ export declare const checkShardingConfig: (allJobs: readonly Pick<AnyJobDefinition, "cadence" | "name">[]) => Effect.Effect<void, ClusterConfigError, ShardingConfig.ShardingConfig>;
44
+ /**
45
+ * Checks a worker's `ShardingConfig.assignedShardGroups` against the jobs it registers: it claims
46
+ * the maintenance group and the group of every enabled job, and no group of a job it does not
47
+ * register (it would own those workflows' shards without a handler, and they would never run).
48
+ */
49
+ export declare const checkWorkerAssignment: (allJobs: readonly Pick<AnyJobDefinition, "cadence" | "name">[], enabledJobNames: readonly string[]) => Effect.Effect<void, ClusterConfigError, ShardingConfig.ShardingConfig>;
50
+ /**
51
+ * In-memory Cluster, `ClusterWorkflowEngine` and its `ShardingConfig` for unit tests of workflows,
52
+ * durable sleeps, crons and singletons, without PostgreSQL or sockets.
53
+ */
54
+ export declare const makeTestClusterLayer: (allJobs: ReadonlyArray<Pick<AnyJobDefinition, 'name' | 'cadence'>>, only?: ReadonlyArray<string>) => Layer.Layer<ClusterServices | ShardingConfig.ShardingConfig | MessageStorage.MemoryDriver>;
@@ -0,0 +1,115 @@
1
+ import { ClusterConfigError } from "./errors.js";
2
+ import { isManualOnceJob } from "./job.js";
3
+ import "./policy.js";
4
+ import { Effect, Layer } from "effect";
5
+ import { ClusterWorkflowEngine, MessageStorage, RunnerHealth, RunnerStorage, Runners, Sharding, ShardingConfig } from "effect/cluster";
6
+ // src/cluster.ts
7
+ /**
8
+ * Effect Cluster's default shard group, which entities without a group of their own use. A job's
9
+ * durable clocks run in the job's own group, not here.
10
+ */
11
+ const DEFAULT_SHARD_GROUP = "default";
12
+ /**
13
+ * Shard group of the library's maintenance singleton. It is the library's own, so runners of your
14
+ * application that do not run `makeSchedulerLayer` never claim it and keep it from running.
15
+ */
16
+ const MAINTENANCE_SHARD_GROUP = "yieldkit-jobs";
17
+ /**
18
+ * Characters a job name may hold. Effect Cluster's SQL runner storage writes shard ids, which hold
19
+ * the name, into its queries without escaping them, PostgreSQL counts the column aliases built from
20
+ * them in bytes, and its own entities use names with `/`, so names keep to this safe set.
21
+ */
22
+ const JOB_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
23
+ /**
24
+ * The sorted shard groups of every job that is not a manual `Once` job: each such job's workflow,
25
+ * cron and start-up singleton live in a group named after it.
26
+ */
27
+ const jobShardGroupsFor = (allJobs) => [...new Set(allJobs.flatMap((job) => isManualOnceJob(job) ? [] : [job.name]).toSorted())];
28
+ /**
29
+ * Shard groups the jobs engine needs in `ShardingConfig.availableShardGroups` of every runner and
30
+ * client: `default`, the maintenance group and one group per job that is not a manual `Once` job.
31
+ * Add them to your own groups.
32
+ */
33
+ const availableShardGroupsFor = (allJobs) => [
34
+ DEFAULT_SHARD_GROUP,
35
+ MAINTENANCE_SHARD_GROUP,
36
+ ...jobShardGroupsFor(allJobs)
37
+ ];
38
+ /**
39
+ * Shard groups a worker running `makeSchedulerLayer(allJobs, { only })` must claim in
40
+ * `ShardingConfig.assignedShardGroups`: `default`, the maintenance group, and the groups of the
41
+ * jobs `only` selects (every job that is not a manual `Once` job without it). Add them to your
42
+ * own.
43
+ */
44
+ const assignedShardGroupsFor = (allJobs, only) => {
45
+ const jobGroups = jobShardGroupsFor(allJobs);
46
+ const selected = only === void 0 ? jobGroups : jobGroups.filter((g) => only.includes(g));
47
+ return [
48
+ DEFAULT_SHARD_GROUP,
49
+ MAINTENANCE_SHARD_GROUP,
50
+ ...selected
51
+ ];
52
+ };
53
+ /**
54
+ * Checks the `ShardingConfig` of a client or worker against `allJobs`: every job name is unique,
55
+ * holds only `A-Z`, `a-z`, `0-9`, `.`, `_` and `-`, and is not the default or maintenance group,
56
+ * `availableShardGroups` holds every group of `availableShardGroupsFor`, and each job's shard ids
57
+ * fit Effect Cluster's `shard_id` column with the configured `shardsPerGroup`. A missing group
58
+ * would not fail anywhere else: its messages would be stored and never run. Fails with
59
+ * `ClusterConfigError` naming the offending names or groups. `makeSchedulerLayer` runs it; clients
60
+ * can run it at start-up.
61
+ */
62
+ const checkShardingConfig = Effect.fnUntraced(function* (allJobs) {
63
+ const config = yield* ShardingConfig.ShardingConfig;
64
+ const nameProblem = jobNamesProblem(allJobs.map((job) => job.name));
65
+ if (nameProblem !== void 0) return yield* new ClusterConfigError({ message: nameProblem });
66
+ const available = new Set(config.availableShardGroups);
67
+ const missing = availableShardGroupsFor(allJobs).filter((group) => !available.has(group));
68
+ if (missing.length > 0) return yield* new ClusterConfigError({ message: `ShardingConfig.availableShardGroups lacks ${missing.join(", ")}. Add availableShardGroupsFor(allJobs) to it on every runner and client.` });
69
+ const maxNameLength = 49 - String(config.shardsPerGroup).length;
70
+ const tooLong = jobShardGroupsFor(allJobs).filter((group) => Array.from(group).length > maxNameLength);
71
+ if (tooLong.length > 0) return yield* new ClusterConfigError({ message: `Job names longer than ${String(maxNameLength)} characters do not fit Effect Cluster's shard ids with shardsPerGroup ${String(config.shardsPerGroup)}: ${tooLong.join(", ")}.` });
72
+ return yield* Effect.void;
73
+ });
74
+ /**
75
+ * Returns why the job names `names` cannot run on Effect Cluster, or `undefined` when they can: one
76
+ * takes the default or maintenance group, holds a character outside `JOB_NAME_PATTERN`, or is used
77
+ * twice.
78
+ */
79
+ const jobNamesProblem = (names) => {
80
+ if (names.includes("yieldkit-jobs")) return `Job name "${MAINTENANCE_SHARD_GROUP}" is reserved for the maintenance shard group.`;
81
+ if (names.includes("default")) return `Job name "${DEFAULT_SHARD_GROUP}" is reserved for the default shard group.`;
82
+ const malformed = names.filter((name) => !JOB_NAME_PATTERN.test(name));
83
+ if (malformed.length > 0) return `Job names may only hold A-Z, a-z, 0-9, ".", "_" and "-": ${malformed.join(", ")}.`;
84
+ const duplicates = new Set(names.filter((name, index) => names.indexOf(name) !== index));
85
+ return duplicates.size > 0 ? `Job names must be unique; more than one job is named ${[...duplicates].join(", ")}.` : void 0;
86
+ };
87
+ /**
88
+ * Checks a worker's `ShardingConfig.assignedShardGroups` against the jobs it registers: it claims
89
+ * the maintenance group and the group of every enabled job, and no group of a job it does not
90
+ * register (it would own those workflows' shards without a handler, and they would never run).
91
+ */
92
+ const checkWorkerAssignment = Effect.fnUntraced(function* (allJobs, enabledJobNames) {
93
+ const config = yield* ShardingConfig.ShardingConfig;
94
+ const assigned = new Set(config.assignedShardGroups);
95
+ const enabled = new Set(enabledJobNames);
96
+ const unclaimed = [MAINTENANCE_SHARD_GROUP, ...enabledJobNames].filter((g) => !assigned.has(g));
97
+ if (unclaimed.length > 0) return yield* new ClusterConfigError({ message: `ShardingConfig.assignedShardGroups lacks ${unclaimed.join(", ")}, which this worker runs. Add assignedShardGroupsFor(allJobs, only) to it.` });
98
+ const unhandled = jobShardGroupsFor(allJobs).filter((g) => assigned.has(g) && !enabled.has(g));
99
+ if (unhandled.length > 0) return yield* new ClusterConfigError({ message: `ShardingConfig.assignedShardGroups claims ${unhandled.join(", ")}, but this worker does not run those jobs. Remove them, or include them in \`only\`.` });
100
+ return yield* Effect.void;
101
+ });
102
+ /**
103
+ * In-memory Cluster, `ClusterWorkflowEngine` and its `ShardingConfig` for unit tests of workflows,
104
+ * durable sleeps, crons and singletons, without PostgreSQL or sockets.
105
+ */
106
+ const makeTestClusterLayer = (allJobs, only) => {
107
+ const shardingConfigLayer = ShardingConfig.layer({
108
+ availableShardGroups: [...availableShardGroupsFor(allJobs)],
109
+ assignedShardGroups: [...assignedShardGroupsFor(allJobs, only)],
110
+ shardsPerGroup: 16
111
+ });
112
+ const runnerLayer = Sharding.layer.pipe(Layer.provideMerge(Runners.layerNoop), Layer.provideMerge(MessageStorage.layerMemory), Layer.provide([RunnerStorage.layerMemory, RunnerHealth.layerNoop]), Layer.provideMerge(shardingConfigLayer));
113
+ return ClusterWorkflowEngine.layer.pipe(Layer.provideMerge(runnerLayer));
114
+ };
115
+ export { DEFAULT_SHARD_GROUP, MAINTENANCE_SHARD_GROUP, assignedShardGroupsFor, availableShardGroupsFor, checkShardingConfig, checkWorkerAssignment, makeTestClusterLayer };
package/dist/cron.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { JobCadence } from "./job.js";
2
+ import { ClusterConfigError } from "./errors.js";
3
+ import { Cron, Effect } from "effect";
4
+ /**
5
+ * Converts a recurring `JobCadence` (`Every`, `Daily` or `Cron`) into the `Cron.Cron` the scheduler
6
+ * runs:
7
+ *
8
+ * - `Daily`: every `checkEvery` in UTC (default 1 hour, `0 * * * *`), with the local date as the
9
+ * workflow idempotency key, so a missed check catches up on the next one while completed or
10
+ * running days deduplicate. The scheduler skips checks before the day's `at` or window time and
11
+ * after `until`.
12
+ * - `Every`: every `interval` in UTC, on minute (`*\/N * * * *`) or hour (`0 *\/H * * *`) boundaries,
13
+ * or at midnight UTC (`0 0 * * *`) for one day.
14
+ * - `Cron`: the expression in its time zone.
15
+ *
16
+ * Fails with `ClusterConfigError` when the interval is not a duration or does not evenly divide an
17
+ * hour or a day, or the expression or time zone is invalid.
18
+ */
19
+ export declare const cronForCadence: (cadence: Extract<JobCadence, {
20
+ readonly _tag: 'Daily' | 'Every' | 'Cron';
21
+ }>) => Effect.Effect<Cron.Cron, ClusterConfigError>;
package/dist/cron.js ADDED
@@ -0,0 +1,80 @@
1
+ import { parseCronCadence, validateCadence } from "./calendar.js";
2
+ import { ClusterConfigError } from "./errors.js";
3
+ import "./policy.js";
4
+ import { Cron, Duration, Effect, Option, Result } from "effect";
5
+ // src/cron.ts
6
+ /**
7
+ * Number of milliseconds in one minute.
8
+ */
9
+ const MILLIS_PER_MINUTE = 6e4;
10
+ /**
11
+ * Number of minutes in one hour.
12
+ */
13
+ const MINUTES_PER_HOUR = 60;
14
+ /**
15
+ * Number of hours in one day.
16
+ */
17
+ const HOURS_PER_DAY = 24;
18
+ /**
19
+ * Cron for a fixed interval: every N minutes when N divides an hour, every H hours when H divides a
20
+ * day, and midnight UTC for a whole day. Fails with `ClusterConfigError` naming `label` for any
21
+ * other interval, or for input that is not a duration.
22
+ */
23
+ const cronForInterval = (label, interval) => {
24
+ const decoded = Duration.fromInput(interval);
25
+ if (Option.isNone(decoded)) return Effect.fail(new ClusterConfigError({ message: `${label} must be a duration.` }));
26
+ const intervalMs = Duration.toMillis(decoded.value);
27
+ if (intervalMs < MILLIS_PER_MINUTE || intervalMs % MILLIS_PER_MINUTE !== 0) return Effect.fail(new ClusterConfigError({ message: `${label} must be a whole number of minutes (got ${String(intervalMs)}ms).` }));
28
+ const minutes = intervalMs / MILLIS_PER_MINUTE;
29
+ if (minutes < MINUTES_PER_HOUR && MINUTES_PER_HOUR % minutes === 0) {
30
+ const expr = minutes === 1 ? "* * * * *" : `*/${String(minutes)} * * * *`;
31
+ return Effect.succeed(Cron.parseUnsafe(expr, "UTC"));
32
+ }
33
+ if (minutes === 1440) return Effect.succeed(Cron.parseUnsafe("0 0 * * *", "UTC"));
34
+ if (minutes % MINUTES_PER_HOUR === 0) {
35
+ const hours = minutes / MINUTES_PER_HOUR;
36
+ if (hours >= 1 && hours < HOURS_PER_DAY && HOURS_PER_DAY % hours === 0) {
37
+ const expr = hours === 1 ? "0 * * * *" : `0 */${String(hours)} * * *`;
38
+ return Effect.succeed(Cron.parseUnsafe(expr, "UTC"));
39
+ }
40
+ }
41
+ return Effect.fail(new ClusterConfigError({ message: `${label} of ${String(minutes)} minutes is not supported; it must evenly divide 60 minutes or 24 hours.` }));
42
+ };
43
+ /**
44
+ * Converts a recurring `JobCadence` (`Every`, `Daily` or `Cron`) into the `Cron.Cron` the scheduler
45
+ * runs:
46
+ *
47
+ * - `Daily`: every `checkEvery` in UTC (default 1 hour, `0 * * * *`), with the local date as the
48
+ * workflow idempotency key, so a missed check catches up on the next one while completed or
49
+ * running days deduplicate. The scheduler skips checks before the day's `at` or window time and
50
+ * after `until`.
51
+ * - `Every`: every `interval` in UTC, on minute (`*\/N * * * *`) or hour (`0 *\/H * * *`) boundaries,
52
+ * or at midnight UTC (`0 0 * * *`) for one day.
53
+ * - `Cron`: the expression in its time zone.
54
+ *
55
+ * Fails with `ClusterConfigError` when the interval is not a duration or does not evenly divide an
56
+ * hour or a day, or the expression or time zone is invalid.
57
+ */
58
+ const cronForCadence = (cadence) => {
59
+ switch (cadence._tag) {
60
+ case "Daily": return cronForInterval("Daily checkEvery", cadence.checkEvery ?? "1 hour");
61
+ case "Every": return cronForInterval("Every interval", cadence.interval);
62
+ case "Cron": return Result.match(parseCronCadence(cadence), {
63
+ onFailure: (message) => Effect.fail(new ClusterConfigError({ message })),
64
+ onSuccess: Effect.succeed
65
+ });
66
+ default: return cadence;
67
+ }
68
+ };
69
+ /**
70
+ * Validates the cadence of `job` as the scheduler would, whether or not this worker runs it:
71
+ * `validateCadence`, and for `Every`, `Daily` and `Cron` the cron the scheduler derives. `runJob`
72
+ * and `dispatchApiJobWorkflow` run it too, so a cadence the scheduler rejects never gets a run key.
73
+ * Fails with `ClusterConfigError`.
74
+ */
75
+ const validateJobCadence = Effect.fnUntraced(function* (job) {
76
+ const { cadence } = job;
77
+ yield* validateCadence(job.name, cadence);
78
+ if (cadence._tag === "Every" || cadence._tag === "Daily" || cadence._tag === "Cron") yield* cronForCadence(cadence);
79
+ });
80
+ export { cronForCadence, validateJobCadence };
@@ -0,0 +1,97 @@
1
+ import { ClusterConfigError, InvalidDispatch, InvalidJobParams, InvalidRunKey } from "./errors.js";
2
+ import { AnyJobDefinition } from "./job.js";
3
+ import { WorkflowParamOverrides } from "./workflow-schema.js";
4
+ import { JobRequests } from "./requests.js";
5
+ import { DateTime, Duration, Effect, Schema } from "effect";
6
+ import { SecureRandom } from "effect/crypto";
7
+ import { SqlError } from "effect/sql";
8
+ import { WorkflowEngine } from "effect/workflow";
9
+ /**
10
+ * Options for `dispatchApiJobWorkflow`.
11
+ */
12
+ export type DispatchApiJobWorkflowOptions = {
13
+ /**
14
+ * API-validated parameter overrides (already checked against `apiParams`).
15
+ */
16
+ readonly params: WorkflowParamOverrides;
17
+ /**
18
+ * Whether the workflow should force re-running an already completed cadence key.
19
+ */
20
+ readonly force: boolean;
21
+ };
22
+ /**
23
+ * Result returned by `dispatchApiJobWorkflow`.
24
+ */
25
+ export type DispatchedApiJobWorkflow = {
26
+ /**
27
+ * Random UUIDv4 from `SecureRandom`, the request row's id.
28
+ */
29
+ readonly requestId: string;
30
+ /**
31
+ * Deterministic Effect Workflow `executionId`, persisted in Cluster's messages.
32
+ */
33
+ readonly executionId: string;
34
+ };
35
+ /**
36
+ * Starts a job for an external caller: keeps only the params `apiParams` allows, records a request
37
+ * row linked to the workflow's deterministic `executionId`, and dispatches the durable workflow
38
+ * with `trigger: 'api'` without waiting for it. If dispatch fails, the row is marked failed unless
39
+ * a worker already picked it up; the worker can still finish it if the workflow did start. An
40
+ * interrupted dispatch leaves the row pending. The request id is a UUIDv4 drawn from
41
+ * `SecureRandom`. Check `isApiRequestable` and `findDisallowedApiParams` before calling it. An
42
+ * `OnDemand` job fails with `InvalidRunKey`: start it with `dispatchJob`. An invalid cadence fails
43
+ * with `ClusterConfigError` before anything is recorded. Params that do not decode over the job's
44
+ * defaults fail with `InvalidJobParams` before anything is recorded.
45
+ */
46
+ export declare const dispatchApiJobWorkflow: (definition: AnyJobDefinition, options: DispatchApiJobWorkflowOptions) => Effect.Effect<DispatchedApiJobWorkflow, ClusterConfigError | InvalidJobParams | InvalidRunKey | Schema.SchemaError | SqlError.SqlError, JobRequests | SecureRandom.SecureRandom | WorkflowEngine.WorkflowEngine>;
47
+ /**
48
+ * Options for `dispatchJob`.
49
+ */
50
+ export type DispatchJobOptions = {
51
+ /**
52
+ * The run's key, chosen by the caller, such as `welcome-email:user-42`: 1 to 200 printable ASCII
53
+ * characters. Dispatching a key again joins the run already started under it.
54
+ */
55
+ readonly runKey: string;
56
+ /**
57
+ * Param overrides merged over the job's defaults. Validated before dispatch; every key is
58
+ * allowed, since the caller is trusted application code.
59
+ */
60
+ readonly params?: Schema.JsonObject | undefined;
61
+ /**
62
+ * Instant the run must not start before. Takes precedence over `delay`.
63
+ */
64
+ readonly runAt?: DateTime.DateTime | undefined;
65
+ /**
66
+ * How long after dispatch the run may start.
67
+ */
68
+ readonly delay?: Duration.Input | undefined;
69
+ };
70
+ /**
71
+ * Result of `dispatchJob`.
72
+ */
73
+ export type DispatchedJob = {
74
+ /**
75
+ * The run key, as given.
76
+ */
77
+ readonly runKey: string;
78
+ /**
79
+ * Deterministic Effect Workflow `executionId`, derived from the job name and run key.
80
+ */
81
+ readonly executionId: string;
82
+ };
83
+ /**
84
+ * Starts a run of an `OnDemand` job under a caller-chosen run key, optionally delayed, and returns
85
+ * without waiting for it. The workflow runs on a worker even if the caller exits. Each key is one
86
+ * execution: dispatching it again, with any params, joins that execution instead of starting
87
+ * another, so a retried request does not run the job twice. A failed run retries with backoff
88
+ * (`retry.onDemandBase` to `retry.onDemandCap`) up to `retry.onDemandMaxFailures` failures; after
89
+ * that, `runJob` with `trigger: 'manual'` and the same key runs it again. Runs carry `trigger:
90
+ * 'schedule'`.
91
+ *
92
+ * Fails with `InvalidRunKey` for a job that is not `OnDemand` or a malformed key, with
93
+ * `InvalidJobParams` when the params do not decode, and with `InvalidDispatch` for a `delay` that
94
+ * is not a finite duration of zero or more or a `runAt` that is not a valid date, all before
95
+ * anything is dispatched.
96
+ */
97
+ export declare const dispatchJob: (definition: AnyJobDefinition, options: DispatchJobOptions) => Effect.Effect<DispatchedJob, InvalidDispatch | InvalidJobParams | InvalidRunKey, WorkflowEngine.WorkflowEngine>;