@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.
- package/LICENSE +21 -0
- package/README.md +307 -2
- package/dist/_virtual/_rolldown/runtime.js +12 -0
- package/dist/activity.d.ts +81 -0
- package/dist/activity.js +151 -0
- package/dist/calendar.d.ts +33 -0
- package/dist/calendar.js +205 -0
- package/dist/cluster.d.ts +54 -0
- package/dist/cluster.js +115 -0
- package/dist/cron.d.ts +21 -0
- package/dist/cron.js +80 -0
- package/dist/dispatch.d.ts +97 -0
- package/dist/dispatch.js +140 -0
- package/dist/errors.d.ts +194 -0
- package/dist/errors.js +132 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +22 -0
- package/dist/job.d.ts +306 -0
- package/dist/job.js +45 -0
- package/dist/ledger-memory.d.ts +64 -0
- package/dist/ledger-memory.js +246 -0
- package/dist/ledger-retry.js +21 -0
- package/dist/ledger-sql-deadline.js +39 -0
- package/dist/ledger-sql.d.ts +5 -0
- package/dist/ledger-sql.js +332 -0
- package/dist/ledger-types.d.ts +340 -0
- package/dist/ledger-types.js +71 -0
- package/dist/ledger.d.ts +51 -0
- package/dist/ledger.js +66 -0
- package/dist/logging.d.ts +83 -0
- package/dist/logging.js +117 -0
- package/dist/maintenance.d.ts +6 -0
- package/dist/maintenance.js +115 -0
- package/dist/metrics.d.ts +14 -0
- package/dist/metrics.js +35 -0
- package/dist/migrations.d.ts +21 -0
- package/dist/migrations.js +194 -0
- package/dist/omit-undefined.js +10 -0
- package/dist/params.d.ts +58 -0
- package/dist/params.js +97 -0
- package/dist/policy.d.ts +225 -0
- package/dist/policy.js +247 -0
- package/dist/probe.js +67 -0
- package/dist/requests-memory.d.ts +36 -0
- package/dist/requests-memory.js +142 -0
- package/dist/requests.d.ts +195 -0
- package/dist/requests.js +242 -0
- package/dist/run-key.d.ts +25 -0
- package/dist/run-key.js +85 -0
- package/dist/run-support.js +212 -0
- package/dist/run.d.ts +163 -0
- package/dist/run.js +258 -0
- package/dist/scheduler.d.ts +56 -0
- package/dist/scheduler.js +227 -0
- package/dist/settle-hook.d.ts +3 -0
- package/dist/settle-hook.js +33 -0
- package/dist/storage-options.d.ts +25 -0
- package/dist/storage-options.js +60 -0
- package/dist/storage.d.ts +53 -0
- package/dist/storage.js +75 -0
- package/dist/testing/index.d.ts +4 -0
- package/dist/testing/index.js +4 -0
- package/dist/time-zone.js +83 -0
- package/dist/workflow-activities.js +227 -0
- package/dist/workflow-retry.js +80 -0
- package/dist/workflow-schema.d.ts +207 -0
- package/dist/workflow-schema.js +360 -0
- package/dist/workflow-settle.js +234 -0
- package/dist/workflow.d.ts +17 -0
- package/dist/workflow.js +202 -0
- package/docs/deployment.md +167 -0
- package/docs/jobs.md +200 -0
- package/docs/logs-and-metrics.md +129 -0
- package/docs/migrations.md +66 -0
- package/docs/policy.md +75 -0
- package/docs/scheduling.md +149 -0
- package/docs/storage.md +138 -0
- package/docs/testing.md +144 -0
- package/docs/workers-and-clients.md +100 -0
- package/package.json +82 -3
package/dist/params.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { InvalidJobParams } from "./errors.js";
|
|
2
|
+
import { JOB_CONTINUATION } from "./job.js";
|
|
3
|
+
import { Effect, Option, Schema } from "effect";
|
|
4
|
+
// src/params.ts
|
|
5
|
+
/**
|
|
6
|
+
* JSON-value decoder used for CLI `--set key=value` flag parsing.
|
|
7
|
+
*/
|
|
8
|
+
const decodeJsonValue = Schema.decodeOption(Schema.fromJsonString(Schema.Json));
|
|
9
|
+
/**
|
|
10
|
+
* Strict decode options reporting every schema issue and rejecting unknown override keys.
|
|
11
|
+
*/
|
|
12
|
+
const PARAMS_PARSE_OPTIONS = {
|
|
13
|
+
/**
|
|
14
|
+
* Collect all schema validation errors instead of stopping at the first issue.
|
|
15
|
+
*/
|
|
16
|
+
errors: "all",
|
|
17
|
+
/**
|
|
18
|
+
* Reject unrecognized override keys so flag typos fail loudly before claiming.
|
|
19
|
+
*/
|
|
20
|
+
onExcessProperty: "error"
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Merges `spec.defaults` with `overrides` (overrides win per key), validates through `spec.schema`,
|
|
24
|
+
* and encodes the validated parameters back into `ParamsEncoded` for ledger storage. Maps schema
|
|
25
|
+
* issues into `InvalidJobParams`.
|
|
26
|
+
*/
|
|
27
|
+
const decodeParams = (job, spec, overrides) => Effect.gen(function* () {
|
|
28
|
+
const mergedInput = {
|
|
29
|
+
...spec.defaults,
|
|
30
|
+
...overrides
|
|
31
|
+
};
|
|
32
|
+
const params = yield* Schema.decodeUnknownEffect(spec.schema, PARAMS_PARSE_OPTIONS)(mergedInput);
|
|
33
|
+
return {
|
|
34
|
+
params,
|
|
35
|
+
encoded: yield* Schema.encodeUnknownEffect(spec.schema)(params)
|
|
36
|
+
};
|
|
37
|
+
}).pipe(Effect.mapError((error) => new InvalidJobParams({
|
|
38
|
+
job,
|
|
39
|
+
message: error.message
|
|
40
|
+
})));
|
|
41
|
+
/**
|
|
42
|
+
* Validates and encodes parameter overrides for any `JobDefinition` (including unions drawn from
|
|
43
|
+
* `ALL_JOBS`) without executing the job, using its rank-2 `JOB_CONTINUATION` when present.
|
|
44
|
+
*/
|
|
45
|
+
const decodeJobParams = (definition, overrides) => {
|
|
46
|
+
const continuation = definition[JOB_CONTINUATION];
|
|
47
|
+
if (continuation !== void 0) return continuation((concrete) => decodeParams(concrete.name, concrete.params, overrides));
|
|
48
|
+
return decodeParams(definition.name, definition.params, overrides);
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Lists the keys of `overrides` that `definition.params.apiParams` does not allow an API caller to
|
|
52
|
+
* set, in their original order. Every key counts, whatever its value. Returns an empty array when
|
|
53
|
+
* `overrides` is missing or sets only allowed keys.
|
|
54
|
+
*/
|
|
55
|
+
const findDisallowedApiParams = (definition, overrides) => {
|
|
56
|
+
const allowed = new Set(definition.params.apiParams ?? []);
|
|
57
|
+
return Object.keys(overrides ?? {}).filter((key) => !allowed.has(key));
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Narrows an override value to a JSON value; `undefined`, functions, and other non-JSON values
|
|
61
|
+
* fail.
|
|
62
|
+
*/
|
|
63
|
+
const isJsonValue = Schema.is(Schema.Json);
|
|
64
|
+
/**
|
|
65
|
+
* Returns a copy of `params` holding only the keys `definition.params.apiParams` allows an API
|
|
66
|
+
* caller to set, so every other param comes from the worker. Entries whose value is not JSON are
|
|
67
|
+
* dropped too, since overrides travel through the JSON workflow payload. Returns an empty record
|
|
68
|
+
* when `params` is not an object.
|
|
69
|
+
*/
|
|
70
|
+
const pickApiParams = (definition, params) => {
|
|
71
|
+
if (typeof params !== "object" || params === null || Array.isArray(params)) return {};
|
|
72
|
+
const allowed = new Set(definition.params.apiParams ?? []);
|
|
73
|
+
return Object.fromEntries(Object.entries(params).flatMap(([key, value]) => allowed.has(key) && isJsonValue(value) ? [[key, value]] : []));
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Parses one `--set key=value` flag into a key and value. The value is decoded via
|
|
77
|
+
* `Schema.fromJsonString(Schema.Json)`, falling back to the raw string when JSON decoding fails.
|
|
78
|
+
* Fails with `InvalidJobParams` when the flag lacks `=` or has an empty key.
|
|
79
|
+
*/
|
|
80
|
+
const parseSetFlag = (flag) => {
|
|
81
|
+
const equalsIndex = flag.indexOf("=");
|
|
82
|
+
if (equalsIndex <= 0) return Effect.fail(new InvalidJobParams({
|
|
83
|
+
job: "--set",
|
|
84
|
+
message: `Invalid --set value "${flag}". Expected key=value with a non-empty key.`
|
|
85
|
+
}));
|
|
86
|
+
const rawValue = flag.slice(equalsIndex + 1);
|
|
87
|
+
const parsed = decodeJsonValue(rawValue);
|
|
88
|
+
return Effect.succeed([flag.slice(0, equalsIndex), Option.getOrElse(parsed, () => rawValue)]);
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Parses repeated `--set key=value` CLI flags into an override record, later flags overriding
|
|
92
|
+
* earlier ones for the same key. Each value is decoded via `Schema.fromJsonString(Schema.Json)`,
|
|
93
|
+
* falling back to the raw string when JSON decoding fails. Fails with `InvalidJobParams` (job
|
|
94
|
+
* `--set`) on the first entry lacking `=` or using an empty key.
|
|
95
|
+
*/
|
|
96
|
+
const parseSetFlags = (flags) => Effect.forEach(flags, parseSetFlag).pipe(Effect.map((entries) => Object.fromEntries(entries)));
|
|
97
|
+
export { decodeJobParams, decodeParams, findDisallowedApiParams, parseSetFlags, pickApiParams };
|
package/dist/policy.d.ts
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { JobCadence } from "./job.js";
|
|
2
|
+
import "./ledger-types.js";
|
|
3
|
+
import { ClusterConfigError } from "./errors.js";
|
|
4
|
+
import { Duration, Effect } from "effect";
|
|
5
|
+
/**
|
|
6
|
+
* Lease and heartbeat timing of a claimed run.
|
|
7
|
+
*/
|
|
8
|
+
export type LeasePolicy = {
|
|
9
|
+
/**
|
|
10
|
+
* Lease written on claim and extended by every heartbeat. A run whose lease expires may be taken
|
|
11
|
+
* over by another worker. Default 2 minutes.
|
|
12
|
+
*/
|
|
13
|
+
readonly duration: Duration.Duration;
|
|
14
|
+
/**
|
|
15
|
+
* Heartbeats per lease: the heartbeat interval is `duration / heartbeatsPerLease`. Default 4
|
|
16
|
+
* (every 30 seconds). Must be an integer of at least 2, so a renewal has time to complete before
|
|
17
|
+
* the lease it extends runs out; a smaller value fails policy resolution with
|
|
18
|
+
* `ClusterConfigError`.
|
|
19
|
+
*/
|
|
20
|
+
readonly heartbeatsPerLease: number;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Retry and backoff rules for failed and blocked runs.
|
|
24
|
+
*/
|
|
25
|
+
export type RetryPolicy = {
|
|
26
|
+
/**
|
|
27
|
+
* Failures (interruptions excluded) of one `Daily` run key after which scheduled runs stop
|
|
28
|
+
* retrying it (`Exhausted`) until a `manual` or `api` run takes it. Default 6.
|
|
29
|
+
*/
|
|
30
|
+
readonly dailyMaxFailures: number;
|
|
31
|
+
/**
|
|
32
|
+
* Backoff after the first failure of an automatic `Once` job, doubled per further failure.
|
|
33
|
+
* Default 1 hour.
|
|
34
|
+
*/
|
|
35
|
+
readonly onceBase: Duration.Duration;
|
|
36
|
+
/**
|
|
37
|
+
* Longest backoff between `Once` attempts. Default 24 hours.
|
|
38
|
+
*/
|
|
39
|
+
readonly onceCap: Duration.Duration;
|
|
40
|
+
/**
|
|
41
|
+
* Backoff after the first failure of an `OnDemand` run, doubled per further failure. Default 1
|
|
42
|
+
* minute.
|
|
43
|
+
*/
|
|
44
|
+
readonly onDemandBase: Duration.Duration;
|
|
45
|
+
/**
|
|
46
|
+
* Longest backoff between `OnDemand` attempts. Default 1 hour.
|
|
47
|
+
*/
|
|
48
|
+
readonly onDemandCap: Duration.Duration;
|
|
49
|
+
/**
|
|
50
|
+
* Failures of one `OnDemand` run key after which its dispatched workflow gives up (`Exhausted`).
|
|
51
|
+
* Default 5.
|
|
52
|
+
*/
|
|
53
|
+
readonly onDemandMaxFailures: number;
|
|
54
|
+
/**
|
|
55
|
+
* Durable wait before a scheduled `Daily`, automatic `Once` or dispatched `OnDemand` workflow
|
|
56
|
+
* tries again after finding the key `Busy`. Default 1 minute.
|
|
57
|
+
*/
|
|
58
|
+
readonly busyDelay: Duration.Duration;
|
|
59
|
+
/**
|
|
60
|
+
* `Busy` waits a scheduled `Daily` or dispatched `OnDemand` workflow makes before it settles as
|
|
61
|
+
* skipped. Automatic `Once` workflows wait without limit. Default 15.
|
|
62
|
+
*/
|
|
63
|
+
readonly busyMaxRetries: number;
|
|
64
|
+
/**
|
|
65
|
+
* Times one workflow execution may claim its own `running` row again after a crash before it
|
|
66
|
+
* settles as failed with `MaxAttemptsExceeded`. A run whose claim reply is already stored resumes
|
|
67
|
+
* without a limit. Default 3.
|
|
68
|
+
*/
|
|
69
|
+
readonly maxCrashAttempts: number;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* How long the maintenance loop keeps finished data.
|
|
73
|
+
*/
|
|
74
|
+
export type RetentionPolicy = {
|
|
75
|
+
/**
|
|
76
|
+
* Ledger rows of `Every` and `Cron` jobs. `Daily` and `Once` rows are kept. Default 14 days.
|
|
77
|
+
*/
|
|
78
|
+
readonly everyRuns: Duration.Duration;
|
|
79
|
+
/**
|
|
80
|
+
* Processed Cluster messages of `Every` and `Cron` workflows, their crons and durable clocks.
|
|
81
|
+
* Default 14 days.
|
|
82
|
+
*/
|
|
83
|
+
readonly everyCluster: Duration.Duration;
|
|
84
|
+
/**
|
|
85
|
+
* Processed Cluster messages of `Daily` workflows and their crons. `Once` workflows are never
|
|
86
|
+
* pruned, so a completed `Once` job stays deduplicated. Default 30 days.
|
|
87
|
+
*/
|
|
88
|
+
readonly dailyCluster: Duration.Duration;
|
|
89
|
+
/**
|
|
90
|
+
* Ledger rows and processed Cluster messages of `OnDemand` jobs. A run key deduplicates for this
|
|
91
|
+
* long after its run started. Default 30 days.
|
|
92
|
+
*/
|
|
93
|
+
readonly onDemand: Duration.Duration;
|
|
94
|
+
/**
|
|
95
|
+
* Finished request rows (`JobRequests`). Unfinished rows are kept. Default 30 days.
|
|
96
|
+
*/
|
|
97
|
+
readonly requests: Duration.Duration;
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* When the maintenance loop runs and how much it deletes per statement.
|
|
101
|
+
*/
|
|
102
|
+
export type MaintenancePolicy = {
|
|
103
|
+
/**
|
|
104
|
+
* Time between maintenance sweeps; the first one runs when the maintenance singleton starts.
|
|
105
|
+
* Default 1 day.
|
|
106
|
+
*/
|
|
107
|
+
readonly interval: Duration.Duration;
|
|
108
|
+
/**
|
|
109
|
+
* Rows deleted per statement when pruning ledger rows, Cluster messages and request rows. Default 1000.
|
|
110
|
+
*/
|
|
111
|
+
readonly batchSize: number;
|
|
112
|
+
};
|
|
113
|
+
/**
|
|
114
|
+
* Every tunable timing and limit of the run ledger, the workflows and the maintenance loop. Given
|
|
115
|
+
* once to the storage layer and read by everything else from `JobRuns.policy`, so the ledger's
|
|
116
|
+
* retry arithmetic and the workflows' durable sleeps always agree.
|
|
117
|
+
*/
|
|
118
|
+
export type JobsPolicy = {
|
|
119
|
+
/**
|
|
120
|
+
* Lease and heartbeat timing.
|
|
121
|
+
*/
|
|
122
|
+
readonly lease: LeasePolicy;
|
|
123
|
+
/**
|
|
124
|
+
* Retry and backoff rules.
|
|
125
|
+
*/
|
|
126
|
+
readonly retry: RetryPolicy;
|
|
127
|
+
/**
|
|
128
|
+
* Data retention of the maintenance loop.
|
|
129
|
+
*/
|
|
130
|
+
readonly retention: RetentionPolicy;
|
|
131
|
+
/**
|
|
132
|
+
* Schedule and batch size of the maintenance loop.
|
|
133
|
+
*/
|
|
134
|
+
readonly maintenance: MaintenancePolicy;
|
|
135
|
+
};
|
|
136
|
+
/**
|
|
137
|
+
* Overrides of one policy group: durations accept any `Duration.Input`.
|
|
138
|
+
*/
|
|
139
|
+
type GroupOverrides<Group> = { readonly [Key in keyof Group]?: Group[Key] extends Duration.Duration ? Duration.Input | undefined : Group[Key] | undefined; };
|
|
140
|
+
/**
|
|
141
|
+
* Partial policy merged over `defaultJobsPolicy` group by group: an omitted group or field keeps
|
|
142
|
+
* its default.
|
|
143
|
+
*/
|
|
144
|
+
export type JobsPolicyOverrides = { readonly [Group in keyof JobsPolicy]?: GroupOverrides<JobsPolicy[Group]> | undefined; };
|
|
145
|
+
/**
|
|
146
|
+
* The defaults: a 2-minute lease with 4 heartbeats, 6 `Daily` failures, `Once` backoff from 1 to 24
|
|
147
|
+
* hours, `OnDemand` backoff from 1 minute to 1 hour over 5 failures, 1-minute `Busy` waits (15 for
|
|
148
|
+
* `Daily` and `OnDemand`), 3 crash resumes, 14/14/30/30/30 days of retention and a daily
|
|
149
|
+
* maintenance sweep deleting 1000 rows per statement.
|
|
150
|
+
*/
|
|
151
|
+
export declare const defaultJobsPolicy: JobsPolicy;
|
|
152
|
+
/**
|
|
153
|
+
* Default `checkEvery` of a `Daily` cadence.
|
|
154
|
+
*/
|
|
155
|
+
export declare const DEFAULT_DAILY_CHECK_EVERY: Duration.Input;
|
|
156
|
+
/**
|
|
157
|
+
* Default `catchUpWithin` of a `Cron` cadence.
|
|
158
|
+
*/
|
|
159
|
+
export declare const DEFAULT_CRON_CATCH_UP: Duration.Input;
|
|
160
|
+
/**
|
|
161
|
+
* Shards per shard group of `makeTestClusterLayer`. Your own Cluster sets its own `shardsPerGroup`.
|
|
162
|
+
*/
|
|
163
|
+
export declare const DEFAULT_SHARDS_PER_GROUP = 16;
|
|
164
|
+
/**
|
|
165
|
+
* Merges `overrides` over `defaultJobsPolicy` group by group and validates every value: durations
|
|
166
|
+
* must be above zero and at most ten years (3650 days), counts integers of at least 1. Fails with
|
|
167
|
+
* `ClusterConfigError` naming the first invalid field.
|
|
168
|
+
*/
|
|
169
|
+
export declare const resolveJobsPolicy: (overrides: JobsPolicyOverrides | undefined) => Effect.Effect<JobsPolicy, ClusterConfigError, never>;
|
|
170
|
+
/**
|
|
171
|
+
* Heartbeat interval for `lease`: `duration / heartbeatsPerLease`, at least 1 millisecond. 30
|
|
172
|
+
* seconds with the defaults.
|
|
173
|
+
*/
|
|
174
|
+
export declare const heartbeatIntervalFor: (lease: LeasePolicy) => Duration.Duration;
|
|
175
|
+
/**
|
|
176
|
+
* Backoff of an automatic `Once` job after its `failures`-th failure (1-based): `min(onceBase *
|
|
177
|
+
* 2^(failures - 1), onceCap)`.
|
|
178
|
+
*/
|
|
179
|
+
export declare const onceRetryDelay: (retry: RetryPolicy, failures: number) => Duration.Duration;
|
|
180
|
+
/**
|
|
181
|
+
* Backoff of an `OnDemand` run after its `failures`-th failure (1-based): `min(onDemandBase *
|
|
182
|
+
* 2^(failures - 1), onDemandCap)`.
|
|
183
|
+
*/
|
|
184
|
+
export declare const onDemandRetryDelay: (retry: RetryPolicy, failures: number) => Duration.Duration;
|
|
185
|
+
/**
|
|
186
|
+
* Facts `nextAttemptAt` decides from.
|
|
187
|
+
*/
|
|
188
|
+
export type NextAttemptInput = {
|
|
189
|
+
/**
|
|
190
|
+
* Cadence of the job.
|
|
191
|
+
*/
|
|
192
|
+
readonly cadence: JobCadence['_tag'];
|
|
193
|
+
/**
|
|
194
|
+
* Failures of the run key after the settle (incremented for real failures, unchanged for
|
|
195
|
+
* interruptions).
|
|
196
|
+
*/
|
|
197
|
+
readonly failures: number;
|
|
198
|
+
/**
|
|
199
|
+
* Whether the run was interrupted or lost its claim.
|
|
200
|
+
*/
|
|
201
|
+
readonly interrupted: boolean;
|
|
202
|
+
/**
|
|
203
|
+
* Settle time.
|
|
204
|
+
*/
|
|
205
|
+
readonly now: Date;
|
|
206
|
+
/**
|
|
207
|
+
* Failures after which the key is exhausted, in place of the policy's budget for the cadence.
|
|
208
|
+
* `Infinity` for a `Daily` job with a deadline, whose workflow stops retrying at `until`.
|
|
209
|
+
*/
|
|
210
|
+
readonly maxFailures?: number | undefined;
|
|
211
|
+
};
|
|
212
|
+
/**
|
|
213
|
+
* Computes the ledger's `next_attempt_at` after a failed run settles:
|
|
214
|
+
*
|
|
215
|
+
* - `Daily` and `OnDemand`: `null` (exhausted) once `failures` reaches the budget
|
|
216
|
+
* (`retry.dailyMaxFailures`, `retry.onDemandMaxFailures` or `maxFailures`), also after an
|
|
217
|
+
* interruption, so an interrupted run that took an exhausted key leaves it exhausted
|
|
218
|
+
* - Other interrupted (or lost-claim) runs: `now`, without backoff and without using up the budget
|
|
219
|
+
* - `Every` and `Cron`: `now` (the next tick uses a new run key anyway)
|
|
220
|
+
* - `Once`: `now + onceRetryDelay(retry, failures)` (never exhausts)
|
|
221
|
+
* - `OnDemand`: `now + onDemandRetryDelay(retry, failures)` while `failures <
|
|
222
|
+
* retry.onDemandMaxFailures`, otherwise `null`
|
|
223
|
+
*/
|
|
224
|
+
export declare const nextAttemptAt: (retry: RetryPolicy, { cadence, failures, interrupted, now, maxFailures }: NextAttemptInput) => Date | null;
|
|
225
|
+
export {};
|
package/dist/policy.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { ClusterConfigError } from "./errors.js";
|
|
2
|
+
import { Duration, Effect } from "effect";
|
|
3
|
+
// src/policy.ts
|
|
4
|
+
/**
|
|
5
|
+
* The defaults: a 2-minute lease with 4 heartbeats, 6 `Daily` failures, `Once` backoff from 1 to 24
|
|
6
|
+
* hours, `OnDemand` backoff from 1 minute to 1 hour over 5 failures, 1-minute `Busy` waits (15 for
|
|
7
|
+
* `Daily` and `OnDemand`), 3 crash resumes, 14/14/30/30/30 days of retention and a daily
|
|
8
|
+
* maintenance sweep deleting 1000 rows per statement.
|
|
9
|
+
*/
|
|
10
|
+
const defaultJobsPolicy = {
|
|
11
|
+
/**
|
|
12
|
+
* 2-minute lease renewed four times per lease.
|
|
13
|
+
*/
|
|
14
|
+
lease: {
|
|
15
|
+
duration: Duration.minutes(2),
|
|
16
|
+
heartbeatsPerLease: 4
|
|
17
|
+
},
|
|
18
|
+
/**
|
|
19
|
+
* Retry limits and backoff.
|
|
20
|
+
*/
|
|
21
|
+
retry: {
|
|
22
|
+
dailyMaxFailures: 6,
|
|
23
|
+
onceBase: Duration.hours(1),
|
|
24
|
+
onceCap: Duration.hours(24),
|
|
25
|
+
onDemandBase: Duration.minutes(1),
|
|
26
|
+
onDemandCap: Duration.hours(1),
|
|
27
|
+
onDemandMaxFailures: 5,
|
|
28
|
+
busyDelay: Duration.minutes(1),
|
|
29
|
+
busyMaxRetries: 15,
|
|
30
|
+
maxCrashAttempts: 3
|
|
31
|
+
},
|
|
32
|
+
/**
|
|
33
|
+
* Retention windows of the maintenance loop.
|
|
34
|
+
*/
|
|
35
|
+
retention: {
|
|
36
|
+
everyRuns: Duration.days(14),
|
|
37
|
+
everyCluster: Duration.days(14),
|
|
38
|
+
dailyCluster: Duration.days(30),
|
|
39
|
+
onDemand: Duration.days(30),
|
|
40
|
+
requests: Duration.days(30)
|
|
41
|
+
},
|
|
42
|
+
/**
|
|
43
|
+
* Daily sweep, 1000 rows per delete.
|
|
44
|
+
*/
|
|
45
|
+
maintenance: {
|
|
46
|
+
interval: Duration.days(1),
|
|
47
|
+
batchSize: 1e3
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Default `checkEvery` of a `Daily` cadence.
|
|
52
|
+
*/
|
|
53
|
+
const DEFAULT_DAILY_CHECK_EVERY = "1 hour";
|
|
54
|
+
/**
|
|
55
|
+
* Default `catchUpWithin` of a `Cron` cadence.
|
|
56
|
+
*/
|
|
57
|
+
const DEFAULT_CRON_CATCH_UP = "1 hour";
|
|
58
|
+
/**
|
|
59
|
+
* Shards per shard group of `makeTestClusterLayer`. Your own Cluster sets its own `shardsPerGroup`.
|
|
60
|
+
*/
|
|
61
|
+
const DEFAULT_SHARDS_PER_GROUP = 16;
|
|
62
|
+
/**
|
|
63
|
+
* Longest duration any policy field accepts: ten years, so every retry instant, lease and cutoff
|
|
64
|
+
* computed from one stays a valid date.
|
|
65
|
+
*/
|
|
66
|
+
const MAX_POLICY_DURATION = Duration.days(3650);
|
|
67
|
+
/**
|
|
68
|
+
* Fewest heartbeats per lease: with one, the renew loop sleeps the whole lease and has no time left
|
|
69
|
+
* to renew it before it runs out.
|
|
70
|
+
*/
|
|
71
|
+
const MIN_HEARTBEATS_PER_LEASE = 2;
|
|
72
|
+
/**
|
|
73
|
+
* Resolves a duration override, failing with `ClusterConfigError` unless it is above zero and at
|
|
74
|
+
* most ten years.
|
|
75
|
+
*/
|
|
76
|
+
const positiveDuration = (name, input, fallback) => {
|
|
77
|
+
if (input === void 0) return Effect.succeed(fallback);
|
|
78
|
+
const decoded = Duration.fromInput(input);
|
|
79
|
+
if (decoded._tag === "None" || !Duration.isFinite(decoded.value) || Duration.toMillis(decoded.value) <= 0 || Duration.isGreaterThan(decoded.value, MAX_POLICY_DURATION)) return Effect.fail(new ClusterConfigError({ message: `policy.${name} must be a duration above zero and at most 3650 days.` }));
|
|
80
|
+
return Effect.succeed(decoded.value);
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Resolves a count override, failing with `ClusterConfigError` unless it is an integer of at least
|
|
84
|
+
* `minimum` (1 when omitted).
|
|
85
|
+
*/
|
|
86
|
+
const positiveInteger = (name, input, fallback, minimum = 1) => {
|
|
87
|
+
if (input === void 0) return Effect.succeed(fallback);
|
|
88
|
+
if (!Number.isSafeInteger(input) || input < minimum) return Effect.fail(new ClusterConfigError({ message: `policy.${name} must be an integer of at least ${minimum}.` }));
|
|
89
|
+
return Effect.succeed(input);
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* Resolves the `lease` group over its defaults.
|
|
93
|
+
*/
|
|
94
|
+
const resolveLease = Effect.fnUntraced(function* (overrides) {
|
|
95
|
+
const defaults = defaultJobsPolicy.lease;
|
|
96
|
+
return {
|
|
97
|
+
duration: yield* positiveDuration("lease.duration", overrides?.duration, defaults.duration),
|
|
98
|
+
heartbeatsPerLease: yield* positiveInteger("lease.heartbeatsPerLease", overrides?.heartbeatsPerLease, defaults.heartbeatsPerLease, MIN_HEARTBEATS_PER_LEASE)
|
|
99
|
+
};
|
|
100
|
+
});
|
|
101
|
+
/**
|
|
102
|
+
* Resolves the `retry` group over its defaults.
|
|
103
|
+
*/
|
|
104
|
+
const resolveRetry = Effect.fnUntraced(function* (overrides) {
|
|
105
|
+
const defaults = defaultJobsPolicy.retry;
|
|
106
|
+
return {
|
|
107
|
+
dailyMaxFailures: yield* positiveInteger("retry.dailyMaxFailures", overrides?.dailyMaxFailures, defaults.dailyMaxFailures),
|
|
108
|
+
onceBase: yield* positiveDuration("retry.onceBase", overrides?.onceBase, defaults.onceBase),
|
|
109
|
+
onceCap: yield* positiveDuration("retry.onceCap", overrides?.onceCap, defaults.onceCap),
|
|
110
|
+
onDemandBase: yield* positiveDuration("retry.onDemandBase", overrides?.onDemandBase, defaults.onDemandBase),
|
|
111
|
+
onDemandCap: yield* positiveDuration("retry.onDemandCap", overrides?.onDemandCap, defaults.onDemandCap),
|
|
112
|
+
onDemandMaxFailures: yield* positiveInteger("retry.onDemandMaxFailures", overrides?.onDemandMaxFailures, defaults.onDemandMaxFailures),
|
|
113
|
+
busyDelay: yield* positiveDuration("retry.busyDelay", overrides?.busyDelay, defaults.busyDelay),
|
|
114
|
+
busyMaxRetries: yield* positiveInteger("retry.busyMaxRetries", overrides?.busyMaxRetries, defaults.busyMaxRetries),
|
|
115
|
+
maxCrashAttempts: yield* positiveInteger("retry.maxCrashAttempts", overrides?.maxCrashAttempts, defaults.maxCrashAttempts)
|
|
116
|
+
};
|
|
117
|
+
});
|
|
118
|
+
/**
|
|
119
|
+
* Resolves the `retention` group over its defaults.
|
|
120
|
+
*/
|
|
121
|
+
const resolveRetention = Effect.fnUntraced(function* (overrides) {
|
|
122
|
+
const defaults = defaultJobsPolicy.retention;
|
|
123
|
+
return {
|
|
124
|
+
everyRuns: yield* positiveDuration("retention.everyRuns", overrides?.everyRuns, defaults.everyRuns),
|
|
125
|
+
everyCluster: yield* positiveDuration("retention.everyCluster", overrides?.everyCluster, defaults.everyCluster),
|
|
126
|
+
dailyCluster: yield* positiveDuration("retention.dailyCluster", overrides?.dailyCluster, defaults.dailyCluster),
|
|
127
|
+
onDemand: yield* positiveDuration("retention.onDemand", overrides?.onDemand, defaults.onDemand),
|
|
128
|
+
requests: yield* positiveDuration("retention.requests", overrides?.requests, defaults.requests)
|
|
129
|
+
};
|
|
130
|
+
});
|
|
131
|
+
/**
|
|
132
|
+
* Resolves the `maintenance` group over its defaults.
|
|
133
|
+
*/
|
|
134
|
+
const resolveMaintenance = Effect.fnUntraced(function* (overrides) {
|
|
135
|
+
const defaults = defaultJobsPolicy.maintenance;
|
|
136
|
+
return {
|
|
137
|
+
interval: yield* positiveDuration("maintenance.interval", overrides?.interval, defaults.interval),
|
|
138
|
+
batchSize: yield* positiveInteger("maintenance.batchSize", overrides?.batchSize, defaults.batchSize)
|
|
139
|
+
};
|
|
140
|
+
});
|
|
141
|
+
/**
|
|
142
|
+
* Merges `overrides` over `defaultJobsPolicy` group by group and validates every value: durations
|
|
143
|
+
* must be above zero and at most ten years (3650 days), counts integers of at least 1. Fails with
|
|
144
|
+
* `ClusterConfigError` naming the first invalid field.
|
|
145
|
+
*/
|
|
146
|
+
const resolveJobsPolicy = Effect.fnUntraced(function* (overrides) {
|
|
147
|
+
return {
|
|
148
|
+
lease: yield* resolveLease(overrides?.lease),
|
|
149
|
+
retry: yield* resolveRetry(overrides?.retry),
|
|
150
|
+
retention: yield* resolveRetention(overrides?.retention),
|
|
151
|
+
maintenance: yield* resolveMaintenance(overrides?.maintenance)
|
|
152
|
+
};
|
|
153
|
+
});
|
|
154
|
+
/**
|
|
155
|
+
* Heartbeat interval for `lease`: `duration / heartbeatsPerLease`, at least 1 millisecond. 30
|
|
156
|
+
* seconds with the defaults.
|
|
157
|
+
*/
|
|
158
|
+
const heartbeatIntervalFor = (lease) => {
|
|
159
|
+
const leaseMs = Math.max(1, Duration.toMillis(lease.duration));
|
|
160
|
+
return Duration.millis(Math.max(1, Math.floor(leaseMs / lease.heartbeatsPerLease)));
|
|
161
|
+
};
|
|
162
|
+
/**
|
|
163
|
+
* Backoff of an automatic `Once` job after its `failures`-th failure (1-based): `min(onceBase *
|
|
164
|
+
* 2^(failures - 1), onceCap)`.
|
|
165
|
+
*/
|
|
166
|
+
const onceRetryDelay = (retry, failures) => {
|
|
167
|
+
const exponent = Math.max(0, failures - 1);
|
|
168
|
+
const delayMs = Math.min(Duration.toMillis(retry.onceBase) * 2 ** exponent, Duration.toMillis(retry.onceCap));
|
|
169
|
+
return Duration.millis(delayMs);
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* Backoff of an `OnDemand` run after its `failures`-th failure (1-based): `min(onDemandBase *
|
|
173
|
+
* 2^(failures - 1), onDemandCap)`.
|
|
174
|
+
*/
|
|
175
|
+
const onDemandRetryDelay = (retry, failures) => {
|
|
176
|
+
const exponent = Math.max(0, failures - 1);
|
|
177
|
+
const delayMs = Math.min(Duration.toMillis(retry.onDemandBase) * 2 ** exponent, Duration.toMillis(retry.onDemandCap));
|
|
178
|
+
return Duration.millis(delayMs);
|
|
179
|
+
};
|
|
180
|
+
/**
|
|
181
|
+
* Computes the ledger's `next_attempt_at` after a failed run settles:
|
|
182
|
+
*
|
|
183
|
+
* - `Daily` and `OnDemand`: `null` (exhausted) once `failures` reaches the budget
|
|
184
|
+
* (`retry.dailyMaxFailures`, `retry.onDemandMaxFailures` or `maxFailures`), also after an
|
|
185
|
+
* interruption, so an interrupted run that took an exhausted key leaves it exhausted
|
|
186
|
+
* - Other interrupted (or lost-claim) runs: `now`, without backoff and without using up the budget
|
|
187
|
+
* - `Every` and `Cron`: `now` (the next tick uses a new run key anyway)
|
|
188
|
+
* - `Once`: `now + onceRetryDelay(retry, failures)` (never exhausts)
|
|
189
|
+
* - `OnDemand`: `now + onDemandRetryDelay(retry, failures)` while `failures <
|
|
190
|
+
* retry.onDemandMaxFailures`, otherwise `null`
|
|
191
|
+
*/
|
|
192
|
+
const nextAttemptAt = (retry, { cadence, failures, interrupted, now, maxFailures }) => {
|
|
193
|
+
if (cadence === "OnDemand" && failures >= (maxFailures ?? retry.onDemandMaxFailures)) return null;
|
|
194
|
+
if (interrupted && cadence !== "Daily") return new Date(now.getTime());
|
|
195
|
+
switch (cadence) {
|
|
196
|
+
case "Daily": return failures < (maxFailures ?? retry.dailyMaxFailures) ? new Date(now.getTime()) : null;
|
|
197
|
+
case "Every":
|
|
198
|
+
case "Cron": return new Date(now.getTime());
|
|
199
|
+
case "OnDemand": return new Date(now.getTime() + Duration.toMillis(onDemandRetryDelay(retry, failures)));
|
|
200
|
+
case "Once": {
|
|
201
|
+
const delayMs = Duration.toMillis(onceRetryDelay(retry, failures));
|
|
202
|
+
return new Date(now.getTime() + delayMs);
|
|
203
|
+
}
|
|
204
|
+
default: return cadence;
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
/**
|
|
208
|
+
* Classifies why `existing` cannot be claimed, from its status alone.
|
|
209
|
+
*/
|
|
210
|
+
const classifyRefusal = (existing) => {
|
|
211
|
+
switch (existing.status) {
|
|
212
|
+
case "completed": return { _tag: "Completed" };
|
|
213
|
+
case "running": return { _tag: "Busy" };
|
|
214
|
+
case "failed": return existing.nextAttemptAt === null ? { _tag: "Exhausted" } : {
|
|
215
|
+
_tag: "RetryLater",
|
|
216
|
+
at: existing.nextAttemptAt
|
|
217
|
+
};
|
|
218
|
+
default: return existing.status;
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
/**
|
|
222
|
+
* Shared claim rule for every `JobRuns` implementation. A `completed` row settled by the same
|
|
223
|
+
* execution is `AlreadySettled`. Otherwise the row is taken when the same execution resumes its own
|
|
224
|
+
* `running` row, when a `failed` row is retried manually or its backoff elapsed, when `force`
|
|
225
|
+
* re-runs a `completed` row, or when a `running` row's lease expired; every other case is refused
|
|
226
|
+
* with the reason from the row's status.
|
|
227
|
+
*/
|
|
228
|
+
const decideClaim = (existing, request) => {
|
|
229
|
+
const sameExecution = request.executionId !== null && existing.executionId === request.executionId;
|
|
230
|
+
if (existing.status === "completed" && sameExecution) return {
|
|
231
|
+
_tag: "Refuse",
|
|
232
|
+
claim: { _tag: "AlreadySettled" }
|
|
233
|
+
};
|
|
234
|
+
const resumed = existing.status === "running" && sameExecution;
|
|
235
|
+
const canTakeFailed = existing.status === "failed" && (request.trigger !== "schedule" || existing.nextAttemptAt !== null && existing.nextAttemptAt.getTime() <= existing.nowMs);
|
|
236
|
+
const canTakeCompleted = request.force && existing.status === "completed";
|
|
237
|
+
const canTakeExpired = existing.status === "running" && existing.leaseExpired;
|
|
238
|
+
if (resumed || canTakeFailed || canTakeCompleted || canTakeExpired) return {
|
|
239
|
+
_tag: "Take",
|
|
240
|
+
resumed
|
|
241
|
+
};
|
|
242
|
+
return {
|
|
243
|
+
_tag: "Refuse",
|
|
244
|
+
claim: classifyRefusal(existing)
|
|
245
|
+
};
|
|
246
|
+
};
|
|
247
|
+
export { DEFAULT_CRON_CATCH_UP, DEFAULT_DAILY_CHECK_EVERY, DEFAULT_SHARDS_PER_GROUP, decideClaim, defaultJobsPolicy, heartbeatIntervalFor, nextAttemptAt, onDemandRetryDelay, onceRetryDelay, resolveJobsPolicy };
|
package/dist/probe.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { JobsNotMigratedError } from "./errors.js";
|
|
2
|
+
import { Effect, Schema } from "effect";
|
|
3
|
+
import { SqlClient } from "effect/sql";
|
|
4
|
+
// src/probe.ts
|
|
5
|
+
/**
|
|
6
|
+
* Highest migration id recorded in a history, `0` when it has no rows.
|
|
7
|
+
*/
|
|
8
|
+
const MaxIdRow = Schema.Struct({
|
|
9
|
+
/**
|
|
10
|
+
* `COALESCE(MAX(migration_id), 0)`.
|
|
11
|
+
*/
|
|
12
|
+
found: Schema.Int });
|
|
13
|
+
/**
|
|
14
|
+
* Row of the existence check: whether `to_regclass` found the table.
|
|
15
|
+
*/
|
|
16
|
+
const ExistsRow = Schema.Struct({
|
|
17
|
+
/**
|
|
18
|
+
* `to_regclass(...) IS NOT NULL`.
|
|
19
|
+
*/
|
|
20
|
+
present: Schema.Boolean });
|
|
21
|
+
/**
|
|
22
|
+
* Whether `table` (`schema.table` or a bare name, both plain lowercase identifiers) exists, as the
|
|
23
|
+
* session's `search_path` resolves it.
|
|
24
|
+
*/
|
|
25
|
+
const tableExists = Effect.fnUntraced(function* (sql, table) {
|
|
26
|
+
const rows = yield* sql`SELECT to_regclass(${table}) IS NOT NULL AS present`;
|
|
27
|
+
return (yield* Schema.decodeUnknownEffect(Schema.Array(ExistsRow))(rows).pipe(Effect.orDie))[0]?.present === true;
|
|
28
|
+
});
|
|
29
|
+
/**
|
|
30
|
+
* Highest migration id recorded in `history`, `0` when the table is missing or empty.
|
|
31
|
+
*/
|
|
32
|
+
const recordedMigrationId = Effect.fnUntraced(function* (sql, history) {
|
|
33
|
+
if (!(yield* tableExists(sql, history))) return 0;
|
|
34
|
+
const rows = yield* sql`SELECT COALESCE(MAX(migration_id), 0)::int AS found FROM ${sql(history)}`;
|
|
35
|
+
return (yield* Schema.decodeUnknownEffect(Schema.Array(MaxIdRow))(rows).pipe(Effect.orDie))[0]?.found ?? 0;
|
|
36
|
+
});
|
|
37
|
+
/**
|
|
38
|
+
* Highest id in the installed loader. A loader that cannot be read is a bug in this package.
|
|
39
|
+
*/
|
|
40
|
+
const expectedMigrationId = (loader) => loader.pipe(Effect.orDie, Effect.map((steps) => steps.reduce((highest, [id]) => Math.max(highest, id), 0)));
|
|
41
|
+
/**
|
|
42
|
+
* Compares the history in `probe` with its loader. Fails with `JobsNotMigratedError` when the table
|
|
43
|
+
* is missing, its highest id is lower than the installed code ships, or it is current while one of
|
|
44
|
+
* `probe.tables` is missing; a higher id (newer code ran the migration) is accepted. Connection and
|
|
45
|
+
* permission failures stay `SqlError`.
|
|
46
|
+
*/
|
|
47
|
+
const probeHistory = Effect.fnUntraced(function* (probe) {
|
|
48
|
+
const sql = (yield* SqlClient.SqlClient).withoutTransforms();
|
|
49
|
+
const found = yield* recordedMigrationId(sql, probe.history);
|
|
50
|
+
const expected = yield* expectedMigrationId(probe.loader);
|
|
51
|
+
if (found < expected) return yield* new JobsNotMigratedError({
|
|
52
|
+
component: probe.component,
|
|
53
|
+
table: probe.history,
|
|
54
|
+
found,
|
|
55
|
+
expected,
|
|
56
|
+
message: `${probe.history} is not migrated (found ${String(found)}, needs ${String(expected)}). Run JobStorage.layerMigrations first.`
|
|
57
|
+
});
|
|
58
|
+
for (const table of probe.tables) if (!(yield* tableExists(sql, table))) return yield* new JobsNotMigratedError({
|
|
59
|
+
component: probe.component,
|
|
60
|
+
table: probe.history,
|
|
61
|
+
found,
|
|
62
|
+
expected,
|
|
63
|
+
message: `${probe.history} is current but ${table} does not exist. Another component, such as Cluster storage with the same prefix, may share that history; give the library its own prefix.`
|
|
64
|
+
});
|
|
65
|
+
return yield* Effect.void;
|
|
66
|
+
});
|
|
67
|
+
export { probeHistory, recordedMigrationId, tableExists };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { JobRunRecord } from "./ledger-types.js";
|
|
2
|
+
import { JobRequestRecord, JobRequests } from "./requests.js";
|
|
3
|
+
import { Effect, Layer } from "effect";
|
|
4
|
+
/**
|
|
5
|
+
* Options for `makeJobRequestsMemory`.
|
|
6
|
+
*/
|
|
7
|
+
export type JobRequestsMemoryOptions = {
|
|
8
|
+
/**
|
|
9
|
+
* Optional lookup resolving `(job, runKey)` to a `JobRunRecord` (for example from
|
|
10
|
+
* `makeJobRunsMemory().rows()`) so `getStatus` joins the ledger like the SQL store.
|
|
11
|
+
*/
|
|
12
|
+
readonly findRun?: ((job: string, runKey: string) => JobRunRecord | undefined) | undefined;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* In-memory `JobRequests` test harness exposing its Effect `layer`, direct `service` handle, and
|
|
16
|
+
* current `rows` snapshot.
|
|
17
|
+
*/
|
|
18
|
+
export type JobRequestsMemoryHarness = {
|
|
19
|
+
/**
|
|
20
|
+
* Standalone `Layer<JobRequests>` requiring no database.
|
|
21
|
+
*/
|
|
22
|
+
readonly layer: Layer.Layer<JobRequests>;
|
|
23
|
+
/**
|
|
24
|
+
* Direct `JobRequests` service handle for test assertions without `Effect.provide`.
|
|
25
|
+
*/
|
|
26
|
+
readonly service: JobRequests['Service'];
|
|
27
|
+
/**
|
|
28
|
+
* Current request rows in insertion order.
|
|
29
|
+
*/
|
|
30
|
+
readonly rows: () => ReadonlyArray<JobRequestRecord>;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Builds an in-memory `JobRequests` that reads time through the Effect `Clock`, so `TestClock`
|
|
34
|
+
* controls every timestamp.
|
|
35
|
+
*/
|
|
36
|
+
export declare const makeJobRequestsMemory: (options?: JobRequestsMemoryOptions) => Effect.Effect<JobRequestsMemoryHarness>;
|