@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,227 @@
1
+ import { cronCatchUpFor, dailyScheduleOrThrow, isDailyRunDue, validateCadence } from "./calendar.js";
2
+ import { checkShardingConfig, checkWorkerAssignment } from "./cluster.js";
3
+ import { cronForCadence, validateJobCadence } from "./cron.js";
4
+ import { ClusterConfigError, UnknownJobError } from "./errors.js";
5
+ import { isManualOnceJob } from "./job.js";
6
+ import { makeMaintenanceLayer } from "./maintenance.js";
7
+ import { decodeJobParams } from "./params.js";
8
+ import { WorkerJobParams, makeJobWorkflow } from "./workflow-schema.js";
9
+ import "./policy.js";
10
+ import { runKeyFor } from "./run-key.js";
11
+ import { makeAnyJobWorkflowLayer } from "./workflow.js";
12
+ import { Clock, Cron, DateTime, Duration, Effect, Layer } from "effect";
13
+ import { describeError, logInfo, logWarning } from "@yieldkit/logger";
14
+ import { ClusterCron, Singleton } from "effect/cluster";
15
+ // src/scheduler.ts
16
+ /**
17
+ * Name of the Singleton that dispatches a job's run at start-up.
18
+ */
19
+ const startupSingletonName = (job) => `@yieldkit/jobs/startup/${job}`;
20
+ /**
21
+ * Validates `only` against `jobs` and returns the non-manual jobs enabled for this worker.
22
+ */
23
+ const selectWorkerJobs = (jobs, only) => {
24
+ if (only === void 0) return Effect.succeed({
25
+ enabledJobs: jobs.filter((job) => !isManualOnceJob(job)),
26
+ filteredOutJobs: []
27
+ });
28
+ const knownNames = new Set(jobs.map((job) => job.name));
29
+ const unknown = only.filter((name) => !knownNames.has(name));
30
+ if (unknown.length > 0) return Effect.fail(new UnknownJobError({ names: unknown }));
31
+ const selected = new Set(only);
32
+ const enabledJobs = jobs.filter((job) => selected.has(job.name) && !isManualOnceJob(job));
33
+ const filteredOutJobs = jobs.flatMap((job) => selected.has(job.name) ? [] : [job.name]);
34
+ return Effect.succeed({
35
+ enabledJobs,
36
+ filteredOutJobs
37
+ });
38
+ };
39
+ /**
40
+ * Formats a job's cadence into a short human-readable string for startup logs.
41
+ */
42
+ const formatCadence = (job) => {
43
+ switch (job.cadence._tag) {
44
+ case "Daily": {
45
+ const { at, window, until, timeZone } = job.cadence;
46
+ const checkEvery = job.cadence.checkEvery ?? "1 hour";
47
+ return `daily(${[
48
+ `every ${Duration.format(Duration.fromInputUnsafe(checkEvery))}`,
49
+ at === void 0 ? void 0 : `at ${at}`,
50
+ window === void 0 ? void 0 : `window ${window.from}-${window.to}`,
51
+ until === void 0 ? void 0 : `until ${until}`,
52
+ timeZone === void 0 ? void 0 : timeZone
53
+ ].filter((detail) => detail !== void 0).join(", ")})`;
54
+ }
55
+ case "Every": return `every(${Duration.format(Duration.fromInputUnsafe(job.cadence.interval))})`;
56
+ case "Cron": return `cron(${job.cadence.expression}${job.cadence.timeZone === void 0 ? "" : `, ${job.cadence.timeZone}`})`;
57
+ case "Once": return `once(${job.cadence.start})`;
58
+ case "OnDemand": return "on-demand";
59
+ default: return job.cadence;
60
+ }
61
+ };
62
+ /**
63
+ * Wait between start-up dispatch attempts of a job whose last attempt failed.
64
+ */
65
+ const STARTUP_DISPATCH_RETRY = Duration.minutes(1);
66
+ /**
67
+ * Dispatches one idempotent scheduled workflow run of `job` under `runKey`. A failure is logged as
68
+ * `worker.scheduler.dispatch_failed`; the result says whether the run reached Cluster.
69
+ */
70
+ const dispatchScheduledRun = (job, runKey) => {
71
+ return makeJobWorkflow(job).execute({
72
+ runKey,
73
+ trigger: "schedule",
74
+ params: {},
75
+ force: false,
76
+ requestId: null,
77
+ attemptNonce: null
78
+ }, { discard: true }).pipe(Effect.as(true), Effect.catchCause((cause) => logWarning("worker.scheduler.dispatch_failed", {
79
+ job: job.name,
80
+ runKey,
81
+ errorMessage: describeError(cause)
82
+ }).pipe(Effect.as(false))));
83
+ };
84
+ /**
85
+ * Wait between dispatch attempts of a `Cron` or `Every` tick whose last attempt failed.
86
+ */
87
+ const CRON_DISPATCH_RETRY = Duration.seconds(30);
88
+ /**
89
+ * Dispatches the run `runKey` of the `Cron` or `Every` tick at `scheduledMs`, from a `ClusterCron`
90
+ * handler. A failed dispatch is tried again under the same run key every 30 seconds while the retry
91
+ * starts within `skipIfOlderThan` (`catchUpWithin` for `Cron`, one interval for `Every`) of the
92
+ * tick and before the next tick, since `ClusterCron` only schedules the next tick, from the time
93
+ * this handler returns, and would otherwise drop the run.
94
+ */
95
+ const dispatchCronTick = Effect.fnUntraced(function* (job, runKey, cron, scheduledMs) {
96
+ const { skipIfOlderThan } = yield* ClusterCron.CronSchedule;
97
+ const deadlineMs = Math.min(scheduledMs + Duration.toMillis(skipIfOlderThan), Cron.next(cron, scheduledMs).getTime());
98
+ while (!(yield* dispatchScheduledRun(job, runKey))) {
99
+ if ((yield* Clock.currentTimeMillis) + Duration.toMillis(CRON_DISPATCH_RETRY) >= deadlineMs) {
100
+ yield* logWarning("worker.scheduler.dispatch_abandoned", {
101
+ job: job.name,
102
+ runKey
103
+ });
104
+ return;
105
+ }
106
+ yield* Effect.sleep(CRON_DISPATCH_RETRY);
107
+ }
108
+ });
109
+ /**
110
+ * Builds the start-up `Singleton` of a scheduled job: it dispatches the run due now, when `isDue`
111
+ * says one is, and tries again every minute until the dispatch reaches Cluster, since an automatic
112
+ * `Once` job has no cron to make up for it.
113
+ */
114
+ const makeStartupTrigger = (job, cadence, isDue) => Singleton.make(startupSingletonName(job.name), Effect.gen(function* () {
115
+ for (;;) {
116
+ const nowMs = yield* Clock.currentTimeMillis;
117
+ if (!isDue(nowMs, nowMs)) return;
118
+ if (yield* dispatchScheduledRun(job, runKeyFor(cadence, nowMs))) return;
119
+ yield* Effect.sleep(STARTUP_DISPATCH_RETRY);
120
+ }
121
+ }), { shardGroup: job.name });
122
+ /**
123
+ * Builds the schedule of one job, scoped to its dedicated shard group (`job.name`):
124
+ *
125
+ * - `Every` and `Daily`: a `ClusterCron` and a start-up `Singleton` that dispatches the current run.
126
+ * A failed dispatch of an `Every` tick is retried (see `dispatchCronTick`). A `Daily` check
127
+ * dispatches only once the day's `at` or window time is reached and while `until` has not passed;
128
+ * a check whose dispatch fails is made up for by the next one, under the same run key.
129
+ * - `Cron`: a `ClusterCron` on the expression; a tick missed by up to `catchUpWithin` still runs, and
130
+ * a failed dispatch of a tick is retried (see `dispatchCronTick`).
131
+ * - Automatic `Once`: the start-up `Singleton` only.
132
+ * - `OnDemand`: nothing; `dispatchJob` starts its runs.
133
+ *
134
+ * Fails with `ClusterConfigError` for an invalid interval, time, time zone or expression.
135
+ */
136
+ const makeJobScheduleLayer = Effect.fnUntraced(function* (job) {
137
+ const { cadence } = job;
138
+ yield* validateCadence(job.name, cadence);
139
+ if (cadence._tag === "OnDemand") return Layer.empty;
140
+ if (cadence._tag === "Once") return makeStartupTrigger(job, cadence, () => true);
141
+ const daily = cadence._tag === "Daily" ? dailyScheduleOrThrow(job.name, cadence) : void 0;
142
+ /**
143
+ * Whether a check scheduled at `scheduledMs`, handled at `nowMs`, starts the run: always, except
144
+ * before a `Daily` job's due time or after its `until`.
145
+ */
146
+ const isDue = (scheduledMs, nowMs) => daily === void 0 || isDailyRunDue(daily, scheduledMs, nowMs);
147
+ const cron = yield* cronForCadence(cadence);
148
+ const cronLayer = ClusterCron.make({
149
+ name: job.name,
150
+ cron,
151
+ shardGroup: job.name,
152
+ calculateNextRunFromPrevious: false,
153
+ skipIfOlderThan: skipIfOlderThanFor(cadence),
154
+ execute: Effect.gen(function* () {
155
+ const scheduledMs = DateTime.toEpochMillis(yield* ClusterCron.CurrentScheduledTime);
156
+ const nowMs = yield* Clock.currentTimeMillis;
157
+ const runKey = runKeyFor(cadence, scheduledMs);
158
+ if (cadence._tag !== "Daily") yield* dispatchCronTick(job, runKey, cron, scheduledMs);
159
+ else if (isDue(scheduledMs, nowMs)) yield* dispatchScheduledRun(job, runKey);
160
+ })
161
+ });
162
+ if (cadence._tag === "Cron") return cronLayer;
163
+ return Layer.mergeAll(makeStartupTrigger(job, cadence, isDue), cronLayer);
164
+ });
165
+ /**
166
+ * How old a `ClusterCron` tick of `cadence` may be and still run: one interval for `Every`, a day
167
+ * for `Daily` (its own checks bound it further) and `catchUpWithin` for `Cron`.
168
+ */
169
+ const skipIfOlderThanFor = (cadence) => {
170
+ switch (cadence._tag) {
171
+ case "Every": return cadence.interval;
172
+ case "Daily": return Duration.days(1);
173
+ case "Cron": return cronCatchUpFor(cadence);
174
+ default: return cadence;
175
+ }
176
+ };
177
+ /**
178
+ * Decodes the operator params of `job` over its defaults when the scheduler starts its runs itself,
179
+ * with no caller params, so a bad value fails at start-up instead of failing every scheduled run
180
+ * (and for an automatic `Once` job, storing a failure its later dispatches join). `OnDemand` jobs
181
+ * are skipped, since their required params come with each dispatch.
182
+ */
183
+ const checkOperatorParams = (job, params) => {
184
+ if (job.cadence._tag === "OnDemand") return Effect.void;
185
+ return decodeJobParams(job, params?.[job.name]).pipe(Effect.asVoid, Effect.mapError((error) => new ClusterConfigError({ message: `Job "${job.name}": ${error.message}` })));
186
+ };
187
+ /**
188
+ * Everything a worker runs for `jobs`: a durable `Workflow` handler per job, `ClusterCron`
189
+ * schedules, a start-up `Singleton` per `Every`, `Daily` and automatic `Once` job that dispatches
190
+ * the current run, and the maintenance `Singleton`. `OnDemand` jobs get a handler but no schedule.
191
+ * Manual `Once` jobs are never registered. Provide it with your own Cluster (built with
192
+ * `ClusterWorkflowEngine.layer`) and its `ShardingConfig`, `JobStorage.layerStorage`, the services
193
+ * the jobs need and `SecureRandom` for job logging. At start-up it checks the `ShardingConfig` with
194
+ * `checkShardingConfig` and `checkWorkerAssignment`, and fails with `ClusterConfigError` when a
195
+ * shard group the jobs need is missing or misassigned, when the cadence of any job in `jobs`,
196
+ * including one `only` leaves out, is invalid, or when `params` for a job this worker schedules
197
+ * itself (any but `OnDemand`) do not decode over its defaults.
198
+ */
199
+ const makeSchedulerLayer = (jobs, options = {}) => Layer.unwrap(Effect.gen(function* () {
200
+ yield* Effect.forEach(jobs, validateJobCadence, { discard: true });
201
+ const { enabledJobs, filteredOutJobs } = yield* selectWorkerJobs(jobs, options.only);
202
+ yield* Effect.forEach(enabledJobs, (job) => checkOperatorParams(job, options.params), { discard: true });
203
+ yield* checkShardingConfig(jobs);
204
+ yield* checkWorkerAssignment(jobs, enabledJobs.map((job) => job.name));
205
+ yield* logInfo("worker.supervisor.starting", {
206
+ jobCount: enabledJobs.length,
207
+ jobs: enabledJobs.map((job) => ({
208
+ ...job.logFields,
209
+ name: job.name,
210
+ cadence: formatCadence(job)
211
+ })),
212
+ filteredOutJobs: filteredOutJobs.length > 0 ? filteredOutJobs : void 0
213
+ });
214
+ for (const jobName of filteredOutJobs) yield* logInfo("worker.supervisor.job_filtered", { job: jobName });
215
+ const workflowLayers = enabledJobs.map((job) => makeAnyJobWorkflowLayer(job));
216
+ const scheduleLayers = yield* Effect.forEach(enabledJobs, makeJobScheduleLayer);
217
+ const maintenanceLayer = makeMaintenanceLayer(jobs);
218
+ const lifecycleLayer = Layer.effectDiscard(Effect.gen(function* () {
219
+ yield* Effect.addFinalizer(() => logInfo("worker.supervisor.stopped", { jobCount: enabledJobs.length }));
220
+ yield* logInfo("worker.supervisor.running", {
221
+ jobCount: enabledJobs.length,
222
+ jobNames: enabledJobs.map((job) => job.name)
223
+ });
224
+ }));
225
+ return Layer.mergeAll(maintenanceLayer, lifecycleLayer, ...workflowLayers, ...scheduleLayers).pipe(Layer.provide(WorkerJobParams.layer(options.params ?? {})));
226
+ }));
227
+ export { makeSchedulerLayer, selectWorkerJobs };
@@ -0,0 +1,3 @@
1
+ import "./ledger-types.js";
2
+ import { Cause, Context, Effect } from "effect";
3
+ import { SqlClient, SqlError } from "effect/sql";
@@ -0,0 +1,33 @@
1
+ import { Cause, Data, Effect } from "effect";
2
+ import { describeError, logWarning } from "@yieldkit/logger";
3
+ // src/settle-hook.ts
4
+ /**
5
+ * A settle hook failed or died. Carries the hook's cause for the warning log line.
6
+ */
7
+ var SettleHookFailed = class extends Data.TaggedError("SettleHookFailed") {};
8
+ /**
9
+ * Binds `hook` to the services captured in `context` and maps any failure or defect to
10
+ * `SettleHookFailed`. Interruptions are kept as interruptions. Returns `undefined` without a hook.
11
+ */
12
+ const bindSettleHook = (hook, context) => {
13
+ if (hook === void 0) return;
14
+ return (event) => Effect.suspend(() => hook(event)).pipe(Effect.provideContext(context), Effect.catchCause((cause) => Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.fail(new SettleHookFailed({ cause }))));
15
+ };
16
+ /**
17
+ * Runs the settle hook for `event` in a nested transaction level (a savepoint) of the settle
18
+ * transaction. A failure or defect rolls back only the hook's writes and drops its `afterCommit`
19
+ * callbacks, is logged as `job.settle_hook_failed`, and the settle still commits. A `SELECT 1` ends
20
+ * the level, so a hook that succeeded after catching one of its own SQL errors (which leaves the
21
+ * level aborted) is rolled back the same way. An interruption is not swallowed.
22
+ */
23
+ const runSettleHook = (sql, hook, event) => {
24
+ if (hook === void 0) return Effect.void;
25
+ return sql.withTransaction(hook(event).pipe(Effect.andThen(sql`SELECT 1`))).pipe(Effect.asVoid, Effect.catch((error) => logWarning("job.settle_hook_failed", {
26
+ job: event.job,
27
+ runKey: event.runKey,
28
+ attempt: event.attempt,
29
+ outcome: event.outcome._tag,
30
+ errorMessage: describeError(error._tag === "SettleHookFailed" ? Cause.squash(error.cause) : error)
31
+ })));
32
+ };
33
+ export { SettleHookFailed, bindSettleHook, runSettleHook };
@@ -0,0 +1,25 @@
1
+ import { PgConfigError } from "@yieldkit/pg";
2
+ import { Effect } from "effect";
3
+ /**
4
+ * Where the library's tables live, in the shape of Effect Cluster's `SqlMessageStorage` options.
5
+ * Shared by `JobStorage.migrations`, `layerMigrations`, `layerStorage`, `layerWith` and `layer`;
6
+ * pass the same value to all of them.
7
+ */
8
+ export type JobsStorageOptions = {
9
+ /**
10
+ * Prefix of the library's tables: `<prefix>_runs`, `<prefix>_requests` and the history
11
+ * `<prefix>_migrations`. Default `job`. It must differ from your Cluster storage's prefix when
12
+ * both share a schema, since both keep their history in `<prefix>_migrations`.
13
+ */
14
+ readonly prefix?: string | undefined;
15
+ /**
16
+ * Schema of the library's tables. When omitted, table names are unqualified and resolve through
17
+ * the connection's `search_path`, as Effect Cluster's tables do. When set, every statement names
18
+ * it explicitly.
19
+ */
20
+ readonly schema?: string | undefined;
21
+ };
22
+ /**
23
+ * Default prefix of the library's tables.
24
+ */
25
+ export declare const DEFAULT_PREFIX = "job";
@@ -0,0 +1,60 @@
1
+ import { PgConfigError } from "@yieldkit/pg";
2
+ import { Effect } from "effect";
3
+ // src/storage-options.ts
4
+ /**
5
+ * Default prefix of the library's tables.
6
+ */
7
+ const DEFAULT_PREFIX = "job";
8
+ /**
9
+ * Effect Cluster's default table prefix. The library refuses it: its `<prefix>_migrations` would
10
+ * share a history with Cluster's message storage, and each would skip the other's steps.
11
+ */
12
+ const CLUSTER_DEFAULT_PREFIX = "cluster";
13
+ /**
14
+ * Accepted identifiers: lowercase letters, digits and underscores, not starting with a digit. No
15
+ * quoting rules or case folding apply to them, so quoting is exact and name transforms are no-ops.
16
+ */
17
+ const IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_]*$/;
18
+ /**
19
+ * Longest identifier PostgreSQL keeps without truncating it.
20
+ */
21
+ const MAX_IDENTIFIER_LENGTH = 63;
22
+ /**
23
+ * Longest `prefix`: leaves room under 63 bytes for `<prefix>_runs_trigger_check` and names of
24
+ * future steps.
25
+ */
26
+ const MAX_PREFIX_LENGTH = 37;
27
+ /**
28
+ * Checks one identifier against `IDENTIFIER_PATTERN` and `maxLength`, failing with `PgConfigError`
29
+ * that names the option.
30
+ */
31
+ const validateIdentifier = (option, value, maxLength) => {
32
+ if (!IDENTIFIER_PATTERN.test(value) || value.length > maxLength) return Effect.fail(new PgConfigError({ message: `Invalid ${option} "${value}": expected lowercase letters, digits and underscores, starting with a letter or underscore, at most ${String(maxLength)} characters.` }));
33
+ return Effect.succeed(value);
34
+ };
35
+ /**
36
+ * `name` qualified with `schema` when one is set.
37
+ */
38
+ const qualify = (schema, name) => schema === void 0 ? name : `${schema}.${name}`;
39
+ /**
40
+ * Validates `options` and derives every table, index and constraint name. Fails with
41
+ * `PgConfigError` when a name is not a plain lowercase identifier, the prefix is too long, or the
42
+ * prefix is Effect Cluster's default `cluster`.
43
+ */
44
+ const resolveStorage = Effect.fnUntraced(function* (options) {
45
+ const schema = options?.schema === void 0 ? void 0 : yield* validateIdentifier("schema", options.schema, MAX_IDENTIFIER_LENGTH);
46
+ const prefix = yield* validateIdentifier("prefix", options?.prefix ?? "job", MAX_PREFIX_LENGTH);
47
+ if (prefix === CLUSTER_DEFAULT_PREFIX) return yield* new PgConfigError({ message: `prefix "${CLUSTER_DEFAULT_PREFIX}" is Effect Cluster's default: both would keep their history in ${CLUSTER_DEFAULT_PREFIX}_migrations. Choose a different prefix.` });
48
+ return {
49
+ schema,
50
+ prefix,
51
+ runsTable: qualify(schema, `${prefix}_runs`),
52
+ requestsTable: qualify(schema, `${prefix}_requests`),
53
+ migrationsTable: qualify(schema, `${prefix}_migrations`),
54
+ migrationsTableName: `${prefix}_migrations`,
55
+ runsRecentIndex: `idx_${prefix}_runs_recent`,
56
+ runsStatusCheck: `${prefix}_runs_status_check`,
57
+ runsTriggerCheck: `${prefix}_runs_trigger_check`
58
+ };
59
+ });
60
+ export { DEFAULT_PREFIX, resolveStorage };
@@ -0,0 +1,53 @@
1
+ import { ClusterConfigError, JobsNotMigratedError } from "./errors.js";
2
+ import { JobSettleHook } from "./ledger-types.js";
3
+ import { JobsPolicyOverrides } from "./policy.js";
4
+ import { JobsStorageOptions } from "./storage-options.js";
5
+ import { JobRuns } from "./ledger.js";
6
+ import { JobRequests } from "./requests.js";
7
+ import { layerMigrations, migrations } from "./migrations.js";
8
+ import { MigrationError, PgConfigError } from "@yieldkit/pg";
9
+ import { Layer } from "effect";
10
+ import { SqlClient, SqlError } from "effect/sql";
11
+ declare namespace storage_d_exports {
12
+ export { JobStorageLayerOptions, layer, layerMigrations, layerStorage, layerWith, migrations };
13
+ }
14
+ /**
15
+ * Options of `layerStorage` and `layerWith`: where the tables are, the settle hook and policy
16
+ * overrides.
17
+ */
18
+ export type JobStorageLayerOptions<R = never> = JobsStorageOptions & {
19
+ /**
20
+ * Called once per successful fenced settle, inside the settle transaction and in a savepoint of
21
+ * it. Writes through the same `SqlClient` commit with the settle; a failure or defect rolls back
22
+ * only the hook's writes, is logged as `job.settle_hook_failed`, and the settle still commits. A
23
+ * settle that lost its claim never calls it.
24
+ */
25
+ readonly onSettle?: JobSettleHook<R> | undefined;
26
+ /**
27
+ * Policy overrides merged over `defaultJobsPolicy`. Invalid values fail the layer with
28
+ * `ClusterConfigError`.
29
+ */
30
+ readonly policy?: JobsPolicyOverrides | undefined;
31
+ };
32
+ /**
33
+ * Run ledger and request store on the provided `SqlClient`, without DDL, like Effect Cluster's
34
+ * `SqlMessageStorage.layerStorage`. Run `layerMigrations` with the same options first. On build it
35
+ * checks that `<prefix>_migrations` is at least at the installed code's version and that the ledger
36
+ * and request tables exist, and fails with `JobsNotMigratedError` otherwise; the role needs
37
+ * `SELECT` on the history plus DML on the ledger and request tables. Without `schema`, tables
38
+ * resolve through the client's `search_path`.
39
+ */
40
+ export declare const layerStorage: <R = never>(options?: JobStorageLayerOptions<R>) => Layer.Layer<JobRuns | JobRequests, JobsNotMigratedError | PgConfigError | ClusterConfigError | SqlError.SqlError, SqlClient.SqlClient | R>;
41
+ /**
42
+ * `layerStorage` that first runs `layerMigrations` on the same client, like Effect Cluster's
43
+ * `SqlMessageStorage.layerWith`, for tests and single-process tools. The role needs DDL rights;
44
+ * production deployments should run `layerMigrations` as a separate deploy step instead.
45
+ */
46
+ export declare const layerWith: <R = never>(options?: JobStorageLayerOptions<R>) => Layer.Layer<JobRuns | JobRequests, MigrationError | JobsNotMigratedError | PgConfigError | ClusterConfigError | SqlError.SqlError, SqlClient.SqlClient | R>;
47
+ /**
48
+ * `layerWith()` with default options, like Effect Cluster's `SqlMessageStorage.layer`: tables
49
+ * `job_runs` and `job_requests` on the client's `search_path`, the default policy and no settle
50
+ * hook.
51
+ */
52
+ export declare const layer: Layer.Layer<JobRuns | JobRequests, MigrationError | JobsNotMigratedError | PgConfigError | ClusterConfigError | SqlError.SqlError, SqlClient.SqlClient>;
53
+ export { layerMigrations, migrations, storage_d_exports };
@@ -0,0 +1,75 @@
1
+ import { __exportAll } from "./_virtual/_rolldown/runtime.js";
2
+ import { JobRuns, makeSqlJobRuns } from "./ledger.js";
3
+ import { jobsMigrationLoader, layerMigrations, migrations } from "./migrations.js";
4
+ import { resolveJobsPolicy } from "./policy.js";
5
+ import { probeHistory } from "./probe.js";
6
+ import { JobRequests, makeSqlJobRequests } from "./requests.js";
7
+ import { bindSettleHook } from "./settle-hook.js";
8
+ import { resolveStorage } from "./storage-options.js";
9
+ import { PgConfigError } from "@yieldkit/pg";
10
+ import { Context, Effect, Layer } from "effect";
11
+ import { SecureRandom } from "effect/crypto";
12
+ import { SqlClient } from "effect/sql";
13
+ // src/storage.ts
14
+ var storage_exports = /* @__PURE__ */ __exportAll({
15
+ layer: () => layer,
16
+ layerMigrations: () => layerMigrations,
17
+ layerStorage: () => layerStorage,
18
+ layerWith: () => layerWith,
19
+ migrations: () => migrations
20
+ });
21
+ /**
22
+ * Fails with `PgConfigError` unless `sql` talks to PostgreSQL: the ledger relies on `FOR UPDATE`,
23
+ * `ON CONFLICT`, `jsonb` and advisory locks.
24
+ */
25
+ const assertPostgres = (sql) => sql.onDialectOrElse({
26
+ pg: () => Effect.void,
27
+ orElse: () => Effect.fail(new PgConfigError({ message: "@yieldkit/jobs requires a PostgreSQL SqlClient." }))
28
+ });
29
+ /**
30
+ * Run ledger and request store on the provided `SqlClient`, without DDL, like Effect Cluster's
31
+ * `SqlMessageStorage.layerStorage`. Run `layerMigrations` with the same options first. On build it
32
+ * checks that `<prefix>_migrations` is at least at the installed code's version and that the ledger
33
+ * and request tables exist, and fails with `JobsNotMigratedError` otherwise; the role needs
34
+ * `SELECT` on the history plus DML on the ledger and request tables. Without `schema`, tables
35
+ * resolve through the client's `search_path`.
36
+ */
37
+ const layerStorage = (options) => Layer.effectContext(Effect.gen(function* () {
38
+ const storage = yield* resolveStorage(options);
39
+ const policy = yield* resolveJobsPolicy(options?.policy);
40
+ const sql = (yield* SqlClient.SqlClient).withoutTransforms();
41
+ yield* assertPostgres(sql);
42
+ yield* probeHistory({
43
+ component: "jobs",
44
+ history: storage.migrationsTable,
45
+ tables: [storage.runsTable, storage.requestsTable],
46
+ loader: jobsMigrationLoader(storage)
47
+ });
48
+ const random = yield* SecureRandom.SecureRandom;
49
+ const hookContext = yield* Effect.context();
50
+ const runs = makeSqlJobRuns({
51
+ sql,
52
+ runsTable: storage.runsTable,
53
+ retry: policy.retry,
54
+ onSettle: bindSettleHook(options?.onSettle, hookContext)
55
+ }, policy, random.uuidV4());
56
+ const requests = makeSqlJobRequests({
57
+ sql,
58
+ requestsTable: storage.requestsTable,
59
+ runsTable: storage.runsTable
60
+ });
61
+ return Context.make(JobRuns, runs).pipe(Context.add(JobRequests, requests));
62
+ })).pipe(Layer.provide(SecureRandom.layerWebCrypto));
63
+ /**
64
+ * `layerStorage` that first runs `layerMigrations` on the same client, like Effect Cluster's
65
+ * `SqlMessageStorage.layerWith`, for tests and single-process tools. The role needs DDL rights;
66
+ * production deployments should run `layerMigrations` as a separate deploy step instead.
67
+ */
68
+ const layerWith = (options) => layerStorage(options).pipe(Layer.provide(layerMigrations(options)));
69
+ /**
70
+ * `layerWith()` with default options, like Effect Cluster's `SqlMessageStorage.layer`: tables
71
+ * `job_runs` and `job_requests` on the client's `search_path`, the default policy and no settle
72
+ * hook.
73
+ */
74
+ const layer = layerWith();
75
+ export { layer, layerMigrations, layerStorage, layerWith, migrations, storage_exports };
@@ -0,0 +1,4 @@
1
+ import { makeTestClusterLayer } from "../cluster.js";
2
+ import { JobRunsMemoryHarness, JobRunsMemoryOptions, MemorySettleEntry, makeJobRunsMemory } from "../ledger-memory.js";
3
+ import { JobRequestsMemoryHarness, JobRequestsMemoryOptions, makeJobRequestsMemory } from "../requests-memory.js";
4
+ export { type JobRequestsMemoryHarness, type JobRequestsMemoryOptions, type JobRunsMemoryHarness, type JobRunsMemoryOptions, type MemorySettleEntry, makeJobRequestsMemory, makeJobRunsMemory, makeTestClusterLayer };
@@ -0,0 +1,4 @@
1
+ import { makeTestClusterLayer } from "../cluster.js";
2
+ import { makeJobRunsMemory } from "../ledger-memory.js";
3
+ import { makeJobRequestsMemory } from "../requests-memory.js";
4
+ export { makeJobRequestsMemory, makeJobRunsMemory, makeTestClusterLayer };
@@ -0,0 +1,83 @@
1
+ // src/time-zone.ts
2
+ /**
3
+ * Number of milliseconds in one minute.
4
+ */
5
+ const MILLIS_PER_MINUTE = 6e4;
6
+ /**
7
+ * Number of milliseconds in one day.
8
+ */
9
+ const MILLIS_PER_DAY = 864e5;
10
+ /**
11
+ * Cached `Intl.DateTimeFormat` per time zone.
12
+ */
13
+ const formatters = /* @__PURE__ */ new Map();
14
+ /**
15
+ * Returns the cached formatter giving numeric date and 24-hour time parts in `timeZone`. Throws a
16
+ * `RangeError` for an unknown time zone.
17
+ */
18
+ const formatterFor = (timeZone) => {
19
+ const cached = formatters.get(timeZone);
20
+ if (cached !== void 0) return cached;
21
+ const created = new Intl.DateTimeFormat("en-US", {
22
+ timeZone,
23
+ year: "numeric",
24
+ month: "2-digit",
25
+ day: "2-digit",
26
+ hour: "2-digit",
27
+ minute: "2-digit",
28
+ hourCycle: "h23"
29
+ });
30
+ formatters.set(timeZone, created);
31
+ return created;
32
+ };
33
+ /**
34
+ * Returns `true` when `timeZone` is an IANA time zone this runtime knows.
35
+ */
36
+ const isValidTimeZone = (timeZone) => {
37
+ try {
38
+ formatterFor(timeZone);
39
+ return true;
40
+ } catch {
41
+ return false;
42
+ }
43
+ };
44
+ /**
45
+ * Local date and minute of the day of `ms` (epoch milliseconds) in `timeZone`.
46
+ */
47
+ const localTimeOf = (timeZone, ms) => {
48
+ const parts = {};
49
+ for (const part of formatterFor(timeZone).formatToParts(new Date(ms))) parts[part.type] = part.value;
50
+ return {
51
+ date: `${(parts.year ?? "0").padStart(4, "0")}-${parts.month ?? "01"}-${parts.day ?? "01"}`,
52
+ minute: Number(parts.hour ?? 0) * 60 + Number(parts.minute ?? 0)
53
+ };
54
+ };
55
+ /**
56
+ * Epoch milliseconds of local midnight of `date` (`YYYY-MM-DD`) read as if it were UTC.
57
+ */
58
+ const naiveMidnightOf = (date) => Date.parse(`${date}T00:00:00Z`);
59
+ /**
60
+ * Offset of `timeZone` from UTC at `ms`, in whole minutes as milliseconds: the local wall time read
61
+ * as UTC minus the instant, both truncated to the minute.
62
+ */
63
+ const offsetAt = (timeZone, ms) => {
64
+ const flooredMs = Math.floor(ms / MILLIS_PER_MINUTE) * MILLIS_PER_MINUTE;
65
+ const local = localTimeOf(timeZone, flooredMs);
66
+ return naiveMidnightOf(local.date) + local.minute * MILLIS_PER_MINUTE - flooredMs;
67
+ };
68
+ /**
69
+ * Epoch milliseconds of the local time `minute` minutes after midnight of `date` in `timeZone`
70
+ * (`1440` is the next local midnight). A time repeated by a daylight saving change resolves to its
71
+ * later occurrence. A time skipped by one resolves as if the clock had not changed, which lands the
72
+ * length of the gap after it (02:30 in a one-hour gap from 02:00 to 03:00 is 03:30 after it).
73
+ * Returns `NaN` when `date` is not a `YYYY-MM-DD` date.
74
+ */
75
+ const latestInstantOf = (timeZone, date, minute) => {
76
+ const naiveMs = naiveMidnightOf(date) + minute * MILLIS_PER_MINUTE;
77
+ if (Number.isNaN(naiveMs)) return NaN;
78
+ const offsetBefore = offsetAt(timeZone, naiveMs - MILLIS_PER_DAY);
79
+ const offsetAfter = offsetAt(timeZone, naiveMs + MILLIS_PER_DAY);
80
+ const candidates = [naiveMs - offsetBefore, naiveMs - offsetAfter].filter((candidateMs) => candidateMs + offsetAt(timeZone, candidateMs) === naiveMs);
81
+ return candidates.length === 0 ? naiveMs - offsetBefore : Math.max(...candidates);
82
+ };
83
+ export { isValidTimeZone, latestInstantOf, localTimeOf };