@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sandrino Di Mattia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,308 @@
1
- # Temporary Holding Version
1
+ # @yieldkit/jobs
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@yieldkit/jobs)](https://www.npmjs.com/package/@yieldkit/jobs)
4
+ [![CI](https://github.com/yieldkit/jobs/actions/workflows/ci.yml/badge.svg)](https://github.com/yieldkit/jobs/actions/workflows/ci.yml)
5
+ [![license](https://img.shields.io/npm/l/@yieldkit/jobs)](LICENSE)
6
+
7
+ Scheduled and on-demand jobs for Effect on PostgreSQL, on the Effect Cluster you already run. Each job runs as a durable Cluster workflow, and a run ledger table fences its runs: one ledger row and one scheduled workflow execution per job and run key.
8
+
9
+ Define a job once with `defineJob`, then run it on a schedule (`Every`, `Daily` at a time or in a window, `Cron` or `Once`), once per item under your own key (`OnDemand` with `dispatchJob`, optionally delayed), from an API (`dispatchApiJobWorkflow`) or from a script (`runJob`). Failed stages retry durably without repeating the ones that succeeded. Job code runs [at least once](docs/jobs.md#limits), not exactly once.
10
+
11
+ You own the Cluster: its tables, schema, prefix, transport, serialization and migrations. The library owns only its two tables, and its storage API has the same shape as Cluster's `SqlMessageStorage`: `JobStorage.migrations`, `layerMigrations`, `layerStorage`, `layerWith` and `layer`. Nothing creates tables at start-up.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ pnpm add @yieldkit/jobs @yieldkit/pg @effect/sql-pg effect
17
+ ```
18
+
19
+ `effect` and `@effect/sql-pg` 4.1.6 or a later 4.1 patch are peer dependencies; a new Effect minor needs a new release, since the package builds on Effect's unstable Cluster, Workflow and SQL modules. Your runner also needs a platform package such as `@effect/platform-node`. Runs on Node.js 22.18+, 24.11+ and 26+, and on Bun, against PostgreSQL 15 to 19.
20
+
21
+ | Import | Contents |
22
+ | ------------------------ | ------------------------------------------------------------------------------------------ |
23
+ | `@yieldkit/jobs` | Job definitions, `runJob`, workflows, the scheduler, `JobStorage`, the shard-group helpers |
24
+ | `@yieldkit/jobs/testing` | In-memory ledger, request store and Cluster for unit tests |
25
+
26
+ ## Quick start
27
+
28
+ The four steps: set up your Cluster, run its migrations, run the library's migrations, then start the jobs engine on your Cluster.
29
+
30
+ <!-- prettier-ignore -->
31
+ ```ts
32
+ import * as NodeClusterHttp from '@effect/platform-node/NodeClusterHttp';
33
+ import {
34
+ assignedShardGroupsFor,
35
+ availableShardGroupsFor,
36
+ defineJob,
37
+ JobStorage,
38
+ makeSchedulerLayer,
39
+ } from '@yieldkit/jobs';
40
+ import { makePgLive } from '@yieldkit/pg';
41
+ import { Effect, Layer, Option, Schema } from 'effect';
42
+ import {
43
+ ClusterWorkflowEngine,
44
+ RunnerAddress,
45
+ ShardingConfig,
46
+ SqlMessageStorage,
47
+ SqlRunnerStorage,
48
+ } from 'effect/cluster';
49
+ import { Digest, SecureRandom } from 'effect/crypto';
50
+
51
+ const syncOrders = defineJob({
52
+ name: 'sync-orders',
53
+ description: 'Copies new orders from the shop',
54
+ cadence: { _tag: 'Every', interval: '5 minutes' },
55
+ params: { schema: Schema.Struct({ limit: Schema.Int }), defaults: { limit: 100 }, apiParams: ['limit'] },
56
+ stats: Schema.Struct({ copied: Schema.Int }),
57
+ run: ({ params }) => Effect.succeed({ copied: params.limit }),
58
+ });
59
+
60
+ const jobs = [syncOrders] as const;
61
+
62
+ // One pool whose search_path holds your Cluster's tables and the library's.
63
+ const AppPg = makePgLive({ applicationName: 'worker', searchPath: 'app' });
64
+
65
+ // 1. Your Cluster: your table prefix, your shard groups plus the ones the jobs need.
66
+ const CLUSTER_PREFIX = 'app_cluster';
67
+ const shardingConfig = {
68
+ // Where other nodes reach this worker. Set it explicitly: Effect would otherwise read the generic
69
+ // HOST and PORT. One address per worker; see docs/deployment.md for several nodes.
70
+ runnerAddress: Option.some(RunnerAddress.make('127.0.0.1', 34431)),
71
+ availableShardGroups: [...availableShardGroupsFor(jobs)],
72
+ assignedShardGroups: [...assignedShardGroupsFor(jobs, undefined)],
73
+ };
74
+ const ShardingConfigLive = ShardingConfig.layerFromEnv(shardingConfig);
75
+ const ClusterStorageLive = Layer.mergeAll(
76
+ SqlMessageStorage.layerStorage({ prefix: CLUSTER_PREFIX }).pipe(
77
+ Layer.provide(Digest.layerWebCrypto),
78
+ ),
79
+ SqlRunnerStorage.layerStorage({ prefix: CLUSTER_PREFIX }),
80
+ ).pipe(Layer.provide([AppPg, ShardingConfigLive]));
81
+ const ClusterLive = ClusterWorkflowEngine.layer.pipe(
82
+ Layer.provideMerge(NodeClusterHttp.layer({ transport: 'http', storage: 'byo', shardingConfig })),
83
+ Layer.provideMerge(ClusterStorageLive),
84
+ Layer.provideMerge(ShardingConfigLive),
85
+ );
86
+
87
+ // 2 and 4. Deploy step: your Cluster's migrations and the library's, each into its own history.
88
+ // Nothing else creates tables.
89
+ export const DeployLive = Layer.mergeAll(
90
+ SqlMessageStorage.layerMigrations({ prefix: CLUSTER_PREFIX }),
91
+ SqlRunnerStorage.layerMigrations({ prefix: CLUSTER_PREFIX }),
92
+ JobStorage.layerMigrations(),
93
+ ).pipe(Layer.provide(AppPg));
94
+
95
+ // 3. Worker process: the jobs engine on your Cluster.
96
+ export const WorkerLive = makeSchedulerLayer(jobs).pipe(
97
+ Layer.provide([
98
+ ClusterLive,
99
+ JobStorage.layerStorage().pipe(Layer.provide(AppPg)),
100
+ SecureRandom.layerWebCrypto,
101
+ ]),
102
+ );
103
+ ```
104
+
105
+ Run `DeployLive` once per release, then `WorkerLive` in as many processes as you like, each with its own reachable `runnerAddress`. Each 5-minute bucket runs once across all of them.
106
+
107
+ ```ts
108
+ import * as NodeRuntime from '@effect/platform-node/NodeRuntime';
109
+
110
+ // deploy.ts: builds the layer, then exits
111
+ NodeRuntime.runMain(Layer.build(DeployLive).pipe(Effect.scoped));
112
+ // worker.ts: runs until SIGTERM
113
+ NodeRuntime.runMain(Layer.launch(WorkerLive));
114
+ ```
115
+
116
+ [Deployment](docs/deployment.md) covers several nodes, addresses and failover.
117
+
118
+ `makeSchedulerLayer` fails at start-up with `ClusterConfigError` when your `ShardingConfig` lacks or misassigns a jobs group, and with `JobsNotMigratedError` before `JobStorage.layerMigrations` has run. See [Workers and clients](docs/workers-and-clients.md).
119
+
120
+ ## Common tasks
121
+
122
+ The samples import `syncOrders` and `allJobs`, the list of every job, from your own `./jobs.ts`.
123
+
124
+ ### Split work into durable stages
125
+
126
+ `durableStage` checkpoints a stage's result. When a later stage fails, the retry reads finished stages from storage and runs only the failed one. Code outside a stage runs again on each retry.
127
+
128
+ ```ts
129
+ import { defineJob, durableStage } from '@yieldkit/jobs';
130
+ import { Effect, Schema } from 'effect';
131
+
132
+ const Count = Schema.Struct({ count: Schema.Int });
133
+
134
+ export const nightlyReport = defineJob({
135
+ name: 'nightly-report',
136
+ description: 'Builds and mails the daily report',
137
+ cadence: { _tag: 'Daily' }, // checked hourly; run key YYYY-MM-DD (UTC)
138
+ params: { schema: Schema.Struct({}), defaults: {} },
139
+ stats: Count,
140
+ run: () =>
141
+ Effect.gen(function* () {
142
+ const rows = yield* durableStage({
143
+ name: 'collect',
144
+ schema: Count,
145
+ execute: Effect.succeed({ count: 42 }),
146
+ });
147
+ return yield* durableStage({ name: 'mail', schema: Count, execute: Effect.succeed(rows) });
148
+ }),
149
+ });
150
+ ```
151
+
152
+ ### Start a job from an API
153
+
154
+ `dispatchApiJobWorkflow` records a request row and hands the workflow to your Cluster, which runs it on a worker even if the API process exits. The API runs a client-only Cluster: no runner address, so it claims no shards.
155
+
156
+ <!-- prettier-ignore -->
157
+ ```ts
158
+ import * as NodeClusterHttp from '@effect/platform-node/NodeClusterHttp';
159
+ import { availableShardGroupsFor, checkShardingConfig, dispatchApiJobWorkflow, JobStorage } from '@yieldkit/jobs';
160
+ import { makePgLive } from '@yieldkit/pg';
161
+ import { Effect, Layer, Option } from 'effect';
162
+ import { ClusterWorkflowEngine, ShardingConfig, SqlMessageStorage, SqlRunnerStorage } from 'effect/cluster';
163
+ import { Digest, SecureRandom } from 'effect/crypto';
164
+
165
+ import { allJobs, syncOrders } from './jobs.ts';
166
+
167
+ const AppPg = makePgLive({ applicationName: 'api', searchPath: 'app' });
168
+ const shardingConfig = {
169
+ runnerAddress: Option.none(), // not a runner: claims no shards
170
+ availableShardGroups: [...availableShardGroupsFor(allJobs)],
171
+ assignedShardGroups: [],
172
+ shardLockDisableAdvisory: true,
173
+ };
174
+ const ShardingConfigLive = ShardingConfig.layerFromEnv(shardingConfig);
175
+
176
+ const ApiLive = Layer.mergeAll(
177
+ ClusterWorkflowEngine.layer.pipe(
178
+ Layer.provideMerge(
179
+ NodeClusterHttp.layer({ transport: 'http', clientOnly: true, storage: 'byo', shardingConfig }),
180
+ ),
181
+ Layer.provideMerge(
182
+ Layer.mergeAll(
183
+ SqlMessageStorage.layerStorage({ prefix: 'app_cluster' }).pipe(Layer.provide(Digest.layerWebCrypto)),
184
+ SqlRunnerStorage.layerStorage({ prefix: 'app_cluster' }),
185
+ ).pipe(Layer.provide([AppPg, ShardingConfigLive])),
186
+ ),
187
+ ),
188
+ Layer.effectDiscard(checkShardingConfig(allJobs)).pipe(Layer.provide(ShardingConfigLive)),
189
+ JobStorage.layerStorage().pipe(Layer.provide(AppPg)),
190
+ SecureRandom.layerWebCrypto,
191
+ );
192
+
193
+ export const startSync = dispatchApiJobWorkflow(syncOrders, {
194
+ params: { limit: 10 },
195
+ force: false,
196
+ }).pipe(
197
+ Effect.provide(ApiLive), // { requestId, executionId }
198
+ );
199
+ ```
200
+
201
+ Only params listed in the job's `apiParams` are kept. The rest are decoded before anything is recorded; a value that does not decode fails with `InvalidJobParams`. Your API still has to [authenticate callers and decide `force`](docs/workers-and-clients.md#limits).
202
+
203
+ ### Run a job once per item
204
+
205
+ An `OnDemand` job runs once per key your code chooses, such as one email per user. Dispatching a key again joins the run already started under it, and a failed run retries with backoff.
206
+
207
+ <!-- prettier-ignore -->
208
+ ```ts
209
+ import { defineJob, dispatchJob } from '@yieldkit/jobs';
210
+ import { Effect, Schema } from 'effect';
211
+
212
+ export const sendEmail = defineJob({
213
+ name: 'send-email',
214
+ description: 'Sends one email',
215
+ cadence: { _tag: 'OnDemand' },
216
+ params: { schema: Schema.Struct({ to: Schema.String }), defaults: {} },
217
+ stats: Schema.Struct({ sent: Schema.Boolean }),
218
+ run: () => Effect.succeed({ sent: true }),
219
+ });
220
+
221
+ // From your API, on the same client-only Cluster as above.
222
+ export const sendWelcome = (userId: string, to: string) =>
223
+ dispatchJob(sendEmail, { runKey: `welcome:${userId}`, params: { to }, delay: '10 minutes' });
224
+ ```
225
+
226
+ [Scheduling recipes](docs/scheduling.md) covers `OnDemand`, `Daily` with `at`, `window` and `until`, and `Cron`.
227
+
228
+ ### Run a job from a script
229
+
230
+ `runJob` claims the run key, runs the job and settles the ledger without Cluster. A failing job yields a `failed` outcome, not an error.
231
+
232
+ ```ts
233
+ import { JobStorage, runJob } from '@yieldkit/jobs';
234
+ import { makePgLive } from '@yieldkit/pg';
235
+ import { Effect, Layer } from 'effect';
236
+ import { SecureRandom } from 'effect/crypto';
237
+
238
+ import { syncOrders } from './jobs.ts';
239
+
240
+ export const backfill = runJob(syncOrders, { trigger: 'manual', params: { limit: 5000 } }).pipe(
241
+ Effect.provide([
242
+ JobStorage.layerStorage().pipe(Layer.provide(makePgLive())),
243
+ SecureRandom.layerWebCrypto,
244
+ ]),
245
+ );
246
+ ```
247
+
248
+ ### Record something in the same transaction as the settle
249
+
250
+ <!-- prettier-ignore -->
251
+ ```ts
252
+ import { JobStorage } from '@yieldkit/jobs';
253
+ import { SqlClient } from 'effect/sql';
254
+
255
+ const StorageLive = JobStorage.layerStorage({
256
+ onSettle: (event) =>
257
+ SqlClient.SqlClient.use(
258
+ (sql) => sql`INSERT INTO job_audit (job, outcome) VALUES (${event.job}, ${event.outcome._tag})`,
259
+ ),
260
+ });
261
+ ```
262
+
263
+ The [hook](docs/storage.md#the-settle-hook) runs once per successful settle, in a savepoint of the settle transaction. If it fails, its writes roll back, `job.settle_hook_failed` is logged, and the settle still commits.
264
+
265
+ ### Test a job without a database
266
+
267
+ ```ts
268
+ import { defineJob, runJob } from '@yieldkit/jobs';
269
+ import { makeJobRunsMemory } from '@yieldkit/jobs/testing';
270
+ import { Effect, Schema } from 'effect';
271
+
272
+ const greet = defineJob({
273
+ name: 'greet',
274
+ description: 'Says hello once',
275
+ cadence: { _tag: 'Once', start: 'manual' },
276
+ params: { schema: Schema.Struct({ name: Schema.String }), defaults: { name: 'world' } },
277
+ stats: Schema.Struct({ greeted: Schema.String }),
278
+ run: ({ params }) => Effect.succeed({ greeted: params.name }),
279
+ });
280
+
281
+ const outcome = Effect.gen(function* () {
282
+ const ledger = yield* makeJobRunsMemory();
283
+ return yield* runJob(greet, { trigger: 'manual' }).pipe(Effect.provide(ledger.layer));
284
+ });
285
+ // { job: 'greet', runKey: 'once', trigger: 'manual', status: 'completed', attempt: 1, ... }
286
+ ```
287
+
288
+ ## Documentation
289
+
290
+ | Page | Covers |
291
+ | -------------------------------------------------- | ---------------------------------------------------------------------------- |
292
+ | [Jobs](docs/jobs.md) | `defineJob`, cadences and run keys, params, stages, `runJob`, outcomes |
293
+ | [Scheduling recipes](docs/scheduling.md) | Every N minutes, daily at a time or in a window, cron, one-off jobs per item |
294
+ | [Workers and clients](docs/workers-and-clients.md) | Your Cluster, shard groups, the scheduler, API dispatch |
295
+ | [Storage and the settle hook](docs/storage.md) | `JobStorage` layers, table options, `onSettle`, the ledger |
296
+ | [Migrations](docs/migrations.md) | `JobStorage.layerMigrations` and `migrations`, grants, adoption |
297
+ | [Policy](docs/policy.md) | Leases, retries, retention and maintenance, with defaults |
298
+ | [Logs and metrics](docs/logs-and-metrics.md) | Log events, metric names, error types |
299
+ | [Deployment](docs/deployment.md) | Several workers, addresses and ports, failover, Kubernetes |
300
+ | [Testing](docs/testing.md) | The in-memory ledger, request store and Cluster |
301
+
302
+ ## Development
303
+
304
+ See [CONTRIBUTING.md](https://github.com/yieldkit/jobs/blob/main/CONTRIBUTING.md). `pnpm test` runs the unit tests. `pnpm test:integration` starts PostgreSQL with Testcontainers, so it needs Docker.
305
+
306
+ ## License
307
+
308
+ [MIT](LICENSE)
@@ -0,0 +1,12 @@
1
+ // \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __exportAll = (all, no_symbols) => {
4
+ let target = {};
5
+ for (var name in all) __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true
8
+ });
9
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
+ return target;
11
+ };
12
+ export { __exportAll };
@@ -0,0 +1,81 @@
1
+ import { Cause, Context, Effect, Schema } from "effect";
2
+ import { LogFields } from "@yieldkit/logger";
3
+ declare const JobStageError_base: Schema.Class<JobStageError, Schema.TaggedStruct<"JobStageError", {
4
+ /**
5
+ * Name of the durable stage that failed.
6
+ */
7
+ readonly stage: Schema.String;
8
+ /**
9
+ * Redacted human-readable failure message.
10
+ */
11
+ readonly message: Schema.String;
12
+ /**
13
+ * Original `_tag` of the typed error (for example `RateLimitedError`), or `null` when untagged.
14
+ */
15
+ readonly errorTag: Schema.NullOr<Schema.String>;
16
+ /**
17
+ * `true` when the failure originated from an unhandled defect (`Cause.Die`).
18
+ */
19
+ readonly isDefect: Schema.Boolean;
20
+ /**
21
+ * Finite `retryAfterSeconds` field of the original error, whatever its tag, or `null`.
22
+ */
23
+ readonly retryAfterSeconds: Schema.NullOr<Schema.Finite>;
24
+ }>, Cause.YieldableError & {
25
+ /**
26
+ * Nominal marker: only values built by this class's constructor satisfy the type, never a
27
+ * structurally similar object.
28
+ */
29
+ readonly brand: unique symbol;
30
+ }>;
31
+ /**
32
+ * Serializable, redacted error persisted in Effect Cluster's replies when a durable job stage fails
33
+ * or dies. Keeps the error tag and a `retryAfterSeconds` hint across replays without letting raw
34
+ * secrets into storage.
35
+ */
36
+ export declare class JobStageError extends JobStageError_base {}
37
+ /**
38
+ * Converts a non-interrupt failure or defect cause into a redacted `JobStageError` safe to persist
39
+ * in Effect Cluster's replies.
40
+ */
41
+ export declare const toJobStageError: (stage: string, cause: Cause.Cause<unknown>) => JobStageError;
42
+ /**
43
+ * Options for `durableStage`.
44
+ */
45
+ export type DurableStageOptions<A, Encoded, E, R> = {
46
+ /**
47
+ * Stable stage name within the job (used as both the `Activity` name and `withJobStage` label).
48
+ */
49
+ readonly name: string;
50
+ /**
51
+ * Schema encoding and decoding the stage's return value for durable checkpointing in Effect
52
+ * Cluster's replies.
53
+ */
54
+ readonly schema: Schema.Codec<A, Encoded>;
55
+ /**
56
+ * Stage work effect.
57
+ */
58
+ readonly execute: Effect.Effect<A, E, R>;
59
+ /**
60
+ * Optional structured log fields attached to `withJobStage`.
61
+ */
62
+ readonly fields?: LogFields | undefined;
63
+ };
64
+ /**
65
+ * Runs a named job stage as a durable Effect `Activity` when executing inside a `Workflow`, or as a
66
+ * plain logged stage (`withJobStage`) when the job runs outside a workflow (`runJob`, unit tests).
67
+ *
68
+ * Inside a workflow, in durable retry round `round`:
69
+ *
70
+ * - The stage first reads its replies for attempts `1` to `round - 1`. A stored success is returned
71
+ * without running anything. An attempt the stage never reached stores a placeholder failure,
72
+ * once, so later rounds skip it the same way.
73
+ * - Otherwise the stage runs under `Activity.CurrentAttempt = round`, so a durable retry genuinely
74
+ * re-runs a failed stage instead of replaying its stored failure.
75
+ * - Typed errors and defects (excluding interrupts) are redacted and serialized as `JobStageError`.
76
+ *
77
+ * A stage named like one of the workflow's own activities (see `isReservedStageName`) fails at
78
+ * once, inside or outside a workflow, with a `JobStageError` marked as a defect.
79
+ */
80
+ export declare const durableStage: <A, Encoded, E, R>(options: DurableStageOptions<A, Encoded, E, R>) => Effect.Effect<A, E | JobStageError, R>;
81
+ export {};
@@ -0,0 +1,151 @@
1
+ import { withJobStage } from "./logging.js";
2
+ import { Cause, Context, Effect, Exit, Option, Schema } from "effect";
3
+ import { describeError, extractCauseSummary, redactLogString } from "@yieldkit/logger";
4
+ import { Activity, WorkflowEngine } from "effect/workflow";
5
+ // src/activity.ts
6
+ /**
7
+ * Serializable, redacted error persisted in Effect Cluster's replies when a durable job stage fails
8
+ * or dies. Keeps the error tag and a `retryAfterSeconds` hint across replays without letting raw
9
+ * secrets into storage.
10
+ */
11
+ var JobStageError = class extends Schema.TaggedError()("JobStageError", {
12
+ /**
13
+ * Name of the durable stage that failed.
14
+ */
15
+ stage: Schema.String,
16
+ /**
17
+ * Redacted human-readable failure message.
18
+ */
19
+ message: Schema.String,
20
+ /**
21
+ * Original `_tag` of the typed error (for example `RateLimitedError`), or `null` when untagged.
22
+ */
23
+ errorTag: Schema.NullOr(Schema.String),
24
+ /**
25
+ * `true` when the failure originated from an unhandled defect (`Cause.Die`).
26
+ */
27
+ isDefect: Schema.Boolean,
28
+ /**
29
+ * Finite `retryAfterSeconds` field of the original error, whatever its tag, or `null`.
30
+ */
31
+ retryAfterSeconds: Schema.NullOr(Schema.Finite)
32
+ }) {};
33
+ /**
34
+ * Structural shape of any error carrying a finite `retryAfterSeconds` field, such as a rate-limit
35
+ * error from an HTTP client.
36
+ */
37
+ const RetryAfterShape = Schema.Struct({
38
+ /**
39
+ * Finite retry delay in seconds.
40
+ */
41
+ retryAfterSeconds: Schema.Finite });
42
+ /**
43
+ * Context service carrying `WorkflowRoundState` into durable job stages. Optional so jobs can also
44
+ * execute directly inside unit tests outside a workflow engine.
45
+ */
46
+ var WorkflowExecutionRound = class extends Context.Service()("@yieldkit/jobs/WorkflowExecutionRound") {};
47
+ /**
48
+ * Returns the first typed failure in `cause` when it is a `JobStageError`, or `undefined` when the
49
+ * cause holds no typed failure or its first one is another error.
50
+ */
51
+ const findJobStageError = (cause) => Cause.findErrorOption(cause).pipe(Option.filter(Schema.is(JobStageError)), Option.getOrUndefined);
52
+ /**
53
+ * Returns the finite `retryAfterSeconds` field of the first typed failure in `cause`, whatever its
54
+ * tag, or `undefined` when it has none.
55
+ */
56
+ const findRetryAfterSeconds = (cause) => Cause.findErrorOption(cause).pipe(Option.filter(Schema.is(RetryAfterShape)), Option.map((error) => error.retryAfterSeconds), Option.getOrUndefined);
57
+ /**
58
+ * Converts a non-interrupt failure or defect cause into a redacted `JobStageError` safe to persist
59
+ * in Effect Cluster's replies.
60
+ */
61
+ const toJobStageError = (stage, cause) => {
62
+ const stageError = findJobStageError(cause);
63
+ if (stageError !== void 0) return stageError;
64
+ const summary = extractCauseSummary(cause);
65
+ const rawMessage = summary?.message ?? describeError(Cause.squash(cause));
66
+ return new JobStageError({
67
+ stage,
68
+ message: redactLogString(rawMessage),
69
+ errorTag: summary?.tag ?? null,
70
+ isDefect: summary?.kind === "die",
71
+ retryAfterSeconds: findRetryAfterSeconds(cause) ?? null
72
+ });
73
+ };
74
+ /**
75
+ * Maps typed errors and unhandled defects on `effect` into `JobStageError` while letting
76
+ * interruptions propagate untouched.
77
+ */
78
+ const mapStageFailures = (stage, effect) => effect.pipe(Effect.mapError((error) => toJobStageError(stage, Cause.fail(error))), Effect.catchDefect((defect) => Effect.fail(toJobStageError(stage, Cause.die(defect)))));
79
+ /**
80
+ * The stored reply of a stage attempt that never ran because its round failed before reaching it.
81
+ */
82
+ const notRunInRound = (stage) => new JobStageError({
83
+ stage,
84
+ message: "The stage did not run in this round.",
85
+ errorTag: null,
86
+ isDefect: false,
87
+ retryAfterSeconds: null
88
+ });
89
+ /**
90
+ * Activity names the job workflow uses itself (`N` is a round number), and old journals may still
91
+ * hold. A stage under one of these names would read the workflow's journaled replies.
92
+ */
93
+ const RESERVED_STAGE_NAME = /^(?:(?:claim-round|claim-deadline|settle-completed|settle-failed|settle-skipped|settle-crash-cap|retry-later-clock|retry-deadline)-\d+|settle-invalid-params|run-at-clock|DurableClock\/.*)$/u;
94
+ /**
95
+ * Whether `name` is reserved for the job workflow's own activities and clocks: `claim-round-N`,
96
+ * `claim-deadline-N`, `settle-completed-N`, `settle-failed-N`, `settle-skipped-N`,
97
+ * `settle-crash-cap-N`, `retry-later-clock-N`, `retry-deadline-N`, `settle-invalid-params`,
98
+ * `run-at-clock`, and anything starting with `DurableClock/`.
99
+ */
100
+ const isReservedStageName = (name) => RESERVED_STAGE_NAME.test(name);
101
+ /**
102
+ * The defect a stage under a reserved name fails with, before anything runs.
103
+ */
104
+ const reservedStageName = (stage) => new JobStageError({
105
+ stage,
106
+ message: `Stage name "${stage}" is reserved for the job workflow; rename the stage.`,
107
+ errorTag: null,
108
+ isDefect: true,
109
+ retryAfterSeconds: null
110
+ });
111
+ /**
112
+ * Runs a named job stage as a durable Effect `Activity` when executing inside a `Workflow`, or as a
113
+ * plain logged stage (`withJobStage`) when the job runs outside a workflow (`runJob`, unit tests).
114
+ *
115
+ * Inside a workflow, in durable retry round `round`:
116
+ *
117
+ * - The stage first reads its replies for attempts `1` to `round - 1`. A stored success is returned
118
+ * without running anything. An attempt the stage never reached stores a placeholder failure,
119
+ * once, so later rounds skip it the same way.
120
+ * - Otherwise the stage runs under `Activity.CurrentAttempt = round`, so a durable retry genuinely
121
+ * re-runs a failed stage instead of replaying its stored failure.
122
+ * - Typed errors and defects (excluding interrupts) are redacted and serialized as `JobStageError`.
123
+ *
124
+ * A stage named like one of the workflow's own activities (see `isReservedStageName`) fails at
125
+ * once, inside or outside a workflow, with a `JobStageError` marked as a defect.
126
+ */
127
+ const durableStage = Effect.fnUntraced(function* (options) {
128
+ if (isReservedStageName(options.name)) return yield* reservedStageName(options.name);
129
+ const engine = yield* Effect.serviceOption(WorkflowEngine.WorkflowEngine);
130
+ const instance = yield* Effect.serviceOption(WorkflowEngine.WorkflowInstance);
131
+ const roundState = yield* Effect.serviceOption(WorkflowExecutionRound);
132
+ const logged = options.execute.pipe(withJobStage(options.name, options.fields));
133
+ if (Option.isNone(engine) || Option.isNone(instance)) return yield* logged;
134
+ const round = Option.isSome(roundState) ? roundState.value.round : 1;
135
+ /**
136
+ * The stage's activity for `attempt`, running `execute` unless the journal holds its reply.
137
+ */
138
+ const runAttempt = (execute, attempt) => Activity.make({
139
+ name: options.name,
140
+ success: options.schema,
141
+ error: JobStageError,
142
+ execute: mapStageFailures(options.name, execute)
143
+ }).pipe(Effect.provideService(Activity.CurrentAttempt, attempt), Effect.provideService(WorkflowEngine.WorkflowEngine, engine.value), Effect.provideService(WorkflowEngine.WorkflowInstance, instance.value));
144
+ for (let attempt = 1; attempt < round; attempt += 1) {
145
+ const earlier = yield* Effect.exit(runAttempt(Effect.fail(notRunInRound(options.name)), attempt));
146
+ if (Exit.isSuccess(earlier)) return earlier.value;
147
+ if (Cause.hasInterrupts(earlier.cause) || Cause.hasDies(earlier.cause)) return yield* Effect.failCause(earlier.cause);
148
+ }
149
+ return yield* runAttempt(logged, round);
150
+ });
151
+ export { JobStageError, WorkflowExecutionRound, durableStage, findJobStageError, findRetryAfterSeconds, isReservedStageName, toJobStageError };
@@ -0,0 +1,33 @@
1
+ import "./job.js";
2
+ import "./errors.js";
3
+ import { Cron, Duration, Effect, Result } from "effect";
4
+ /**
5
+ * A validated `Daily` cadence: when each day's run is due and the latest time it may start.
6
+ */
7
+ export type DailySchedule = {
8
+ /**
9
+ * IANA time zone of the run key and the times below.
10
+ */
11
+ readonly timeZone: string;
12
+ /**
13
+ * Scheduler check interval in minutes; also the retry wait.
14
+ */
15
+ readonly checkEveryMinutes: number;
16
+ /**
17
+ * Local minute of the day the run is due on `date`: `at`, a slot of the window, or `0`.
18
+ */
19
+ readonly dueMinuteOn: (date: string) => number;
20
+ /**
21
+ * Latest local minute a run may start, or `undefined` for no limit.
22
+ */
23
+ readonly untilMinute: number | undefined;
24
+ /**
25
+ * Local minute the day's first start must come strictly before, or `undefined` when only
26
+ * `untilMinute` bounds it: `window.to`, unless an explicit `until` is later.
27
+ */
28
+ readonly firstStartBeforeMinute: number | undefined;
29
+ };
30
+ /**
31
+ * Longest run key an `OnDemand` caller may choose.
32
+ */
33
+ export declare const MAX_RUN_KEY_LENGTH = 200;