@lunora/scheduler 1.0.0-alpha.8 → 1.0.0-alpha.80
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/README.md +4 -3
- package/dist/index.d.mts +1007 -424
- package/dist/index.d.ts +1007 -424
- package/dist/index.mjs +1 -8
- package/dist/packem_shared/CRON_SCHEDULE_KINDS-xyFk800s.mjs +1 -0
- package/dist/packem_shared/MAX_RETRY_ATTEMPTS-DiT3r4jp.mjs +1 -0
- package/dist/packem_shared/assertScheduleDelay-BgA4K1WB.mjs +1 -0
- package/dist/packem_shared/assertScheduleInstant-BzESPqyw.mjs +1 -0
- package/dist/packem_shared/assertValidCronExpression-DnBtukpq.mjs +1 -0
- package/dist/packem_shared/base64-BFBvYeZM.mjs +1 -0
- package/dist/packem_shared/createCronTrigger-DSuDZtqj.mjs +1 -0
- package/dist/packem_shared/createQueueConsumer-DWWfGYKN.mjs +1 -0
- package/dist/packem_shared/createScheduler-BW6wVD57.mjs +1 -0
- package/dist/packem_shared/createSchedulerHost-CO6BlgVY.mjs +1 -0
- package/dist/packem_shared/createWorkpool-CQs6z3Y0.mjs +1 -0
- package/dist/packem_shared/do-client-XQayNStI.mjs +1 -0
- package/dist/packem_shared/isWorkflowReference-CT3tdefh.mjs +1 -0
- package/dist/packem_shared/resolveScheduleId-DgysKSrN.mjs +1 -0
- package/dist/packem_shared/wire-codec-TIVAE0Ds.mjs +1 -0
- package/package.json +4 -3
- package/dist/packem_shared/CRON_SCHEDULE_KINDS-C2FflEnq.mjs +0 -140
- package/dist/packem_shared/SchedulerDO-DbXUK1Qa.mjs +0 -681
- package/dist/packem_shared/assertValidCronExpression-B9m75qU0.mjs +0 -24
- package/dist/packem_shared/createCronTrigger-Dh4VLxD9.mjs +0 -28
- package/dist/packem_shared/createQueueConsumer-Cy-Mp-El.mjs +0 -61
- package/dist/packem_shared/createScheduler-DGVqs2Ft.mjs +0 -44
- package/dist/packem_shared/createWorkpool-Ce0kNM2p.mjs +0 -37
- package/dist/packem_shared/do-client-CMJtLoHO.mjs +0 -42
- package/dist/packem_shared/isWorkflowReference-C9mQkMXt.mjs +0 -3
package/dist/index.d.mts
CHANGED
|
@@ -1,82 +1,162 @@
|
|
|
1
|
+
import { SchedulerHost } from '@lunora/platform';
|
|
1
2
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
|
|
10
|
-
|
|
3
|
+
* The generated function-reference type, shared by every package that needs to
|
|
4
|
+
* infer a call's args or return from `api.<file>.<fn>`.
|
|
5
|
+
*
|
|
6
|
+
* This lives in `shared/` rather than in one package because the consumers span
|
|
7
|
+
* a dependency boundary they must not cross: `@lunora/scheduler` and
|
|
8
|
+
* `@lunora/workflow` accept a reference in `runAfter`/`runAt`/`step.run*` but
|
|
9
|
+
* cannot depend on `@lunora/client`, which is a browser package. Each of them
|
|
10
|
+
* previously hand-copied this declaration, and both copies silently rotted when
|
|
11
|
+
* the phantom carrier was renamed — the conditional matched an OPTIONAL property
|
|
12
|
+
* that no longer existed, so `ArgsOf<F>` quietly resolved to `unknown` and every
|
|
13
|
+
* `step.run(ref, args)` in the repo lost its arg checking without a single error.
|
|
14
|
+
*
|
|
15
|
+
* `shared/` is the repo's answer to exactly that shape: bundler-inlined,
|
|
16
|
+
* zero-dependency source imported by relative path, so it creates no runtime
|
|
17
|
+
* edge between the packages that inline it. Being ONE declaration, there is
|
|
18
|
+
* nothing to keep in lockstep and no drift test to write.
|
|
19
|
+
*/
|
|
20
|
+
/** The registered function kinds a {@link FunctionReference} can describe. `stream` is a query that yields multiple frames over the WS. */
|
|
21
|
+
type FunctionKind = "action" | "mutation" | "query" | "stream";
|
|
22
|
+
/**
|
|
23
|
+
* Opaque reference to a registered function emitted by `@lunora/codegen`.
|
|
24
|
+
*
|
|
25
|
+
* At runtime it carries the `<file>:<function>` identifier in `__lunoraRef`.
|
|
26
|
+
* Generated declarations decorate this with phantom type parameters so callers
|
|
27
|
+
* can infer args / return values per call site.
|
|
28
|
+
*/
|
|
29
|
+
interface FunctionReference<Kind extends FunctionKind = FunctionKind, Args = unknown, Return = unknown> {
|
|
30
|
+
/**
|
|
31
|
+
* Phantom marker carrying the `Kind`/`Args`/`Return` type parameters for
|
|
32
|
+
* inference. Never present at runtime; declared as a covariant (output)
|
|
33
|
+
* position so a concrete reference stays assignable to a widened one.
|
|
34
|
+
*/
|
|
35
|
+
readonly __lunoraPhantom?: {
|
|
36
|
+
args: Args;
|
|
37
|
+
kind: Kind;
|
|
38
|
+
returns: Return;
|
|
39
|
+
};
|
|
11
40
|
readonly __lunoraRef: string;
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
*
|
|
20
|
-
* `
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
|
|
32
|
-
* concrete `lunora/workflows.ts` export statically; the runtime brand here is
|
|
33
|
-
* the authoring-time guard.
|
|
34
|
-
*/
|
|
41
|
+
}
|
|
42
|
+
/** Extract the args type from a {@link FunctionReference}. */
|
|
43
|
+
type ArgsOf<F> = F extends FunctionReference<infer _K, infer A, infer _R> ? A : never;
|
|
44
|
+
/**
|
|
45
|
+
* Typed reference to a Lunora durable workflow — either the generated
|
|
46
|
+
* `workflows.<name>` reference object (`_generated/api.ts`, which carries the
|
|
47
|
+
* `WORKFLOW_*` binding + export name) or, structurally, a `defineWorkflow()`
|
|
48
|
+
* result imported directly. Both are matched by the `isLunoraWorkflow` brand and
|
|
49
|
+
* carry the workflow's `params` in the phantom `__params`, so a `cronJobs()`
|
|
50
|
+
* registration infers them.
|
|
51
|
+
*
|
|
52
|
+
* Declared structurally here so `@lunora/scheduler` can let a `cronJobs()`
|
|
53
|
+
* builder target a workflow without depending on `@lunora/workflow` (and so the
|
|
54
|
+
* generated `workflows.*` object needs no `@lunora/scheduler` import — it
|
|
55
|
+
* matches structurally). A cron whose target is a {@link WorkflowReference}
|
|
56
|
+
* starts a new workflow INSTANCE on each fire (the args become its `params`)
|
|
57
|
+
* instead of dispatching a one-shot function. `@lunora/codegen` resolves the
|
|
58
|
+
* concrete `lunora/workflows.ts` export statically; the runtime brand here is
|
|
59
|
+
* the authoring-time guard.
|
|
60
|
+
*/
|
|
35
61
|
interface WorkflowReference<Params = Record<string, unknown>> {
|
|
36
62
|
/** Phantom carrier for the workflow's `params` type — drives `cronJobs()` arg inference. Never read at runtime. */
|
|
37
63
|
readonly __params?: Params;
|
|
38
|
-
/** The `WORKFLOW_*` binding name (present on a generated `workflows
|
|
64
|
+
/** The `WORKFLOW_*` binding name (present on a generated `workflows.<name>` ref). */
|
|
39
65
|
readonly binding?: string;
|
|
40
66
|
readonly isLunoraWorkflow: true;
|
|
41
67
|
/** The workflow's export/stable name (present on a generated ref; a `defineWorkflow({ name })` override otherwise). */
|
|
42
68
|
readonly name?: string;
|
|
43
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* A function reference a scheduler or workpool may target.
|
|
72
|
+
*
|
|
73
|
+
* `stream` is excluded deliberately, and the exclusion is load-bearing rather
|
|
74
|
+
* than tidiness: a scheduled job is dispatched as an ordinary `/rpc` call, and
|
|
75
|
+
* the function runner cannot execute a stream function (see
|
|
76
|
+
* `create-worker.ts`'s registry note). Accepting one compiles a job that is
|
|
77
|
+
* guaranteed to fail when its alarm fires, long after the call site that
|
|
78
|
+
* scheduled it.
|
|
79
|
+
*/
|
|
80
|
+
type SchedulableReference<Args = unknown, Return = unknown> = FunctionReference<Exclude<FunctionKind, "stream">, Args, Return>;
|
|
44
81
|
/** A cron job's target: either a one-shot function dispatch or a durable workflow start. */
|
|
45
|
-
type CronTarget =
|
|
82
|
+
type CronTarget = SchedulableReference | WorkflowReference;
|
|
46
83
|
/** The arguments a cron's target accepts: a workflow's inferred `params`, else an open record (function args aren't inferred). */
|
|
47
84
|
type CronTargetArgs<T extends CronTarget> = T extends WorkflowReference<infer Params> ? Params : Record<string, unknown>;
|
|
85
|
+
/**
|
|
86
|
+
* The arguments a one-shot schedule target ({@link Scheduler.runAfter} /
|
|
87
|
+
* {@link Scheduler.runAt}) accepts. Unlike {@link CronTargetArgs} it resolves a
|
|
88
|
+
* {@link FunctionReference}'s `args` through {@link ArgsOf} as well as a
|
|
89
|
+
* {@link WorkflowReference}'s `params`, so scheduling a generated function
|
|
90
|
+
* reference is arg-checked against that function's validator while scheduling a
|
|
91
|
+
* workflow/agent is checked against its `params`.
|
|
92
|
+
*/
|
|
93
|
+
type ScheduleTargetArgs<T extends CronTarget> = T extends WorkflowReference<infer Params> ? Params : T extends SchedulableReference ? ArgsOf<T> : Record<string, unknown>;
|
|
48
94
|
/** Narrow a {@link CronTarget} to a {@link WorkflowReference} by its runtime brand. */
|
|
49
95
|
declare const isWorkflowReference: (target: unknown) => target is WorkflowReference;
|
|
50
96
|
/**
|
|
51
|
-
* Per-job retry policy. Wired into the SchedulerDO's existing attempts/backoff
|
|
52
|
-
* machinery. When omitted, the DO falls back to its built-in defaults
|
|
53
|
-
* (`maxAttempts: 5`, `backoff: "exponential"`, `baseMs: 30_000`) so existing
|
|
54
|
-
* `runAfter`/`runAt` callers keep today's behaviour unchanged.
|
|
55
|
-
*
|
|
56
|
-
* On exhaustion (attempts > `maxAttempts`) the record is parked under the
|
|
57
|
-
* `dead:` dead-letter key for inspection — never silently dropped.
|
|
58
|
-
*/
|
|
97
|
+
* Per-job retry policy. Wired into the SchedulerDO's existing attempts/backoff
|
|
98
|
+
* machinery. When omitted, the DO falls back to its built-in defaults
|
|
99
|
+
* (`maxAttempts: 5`, `backoff: "exponential"`, `baseMs: 30_000`) so existing
|
|
100
|
+
* `runAfter`/`runAt` callers keep today's behaviour unchanged.
|
|
101
|
+
*
|
|
102
|
+
* On exhaustion (attempts > `maxAttempts`) the record is parked under the
|
|
103
|
+
* `dead:` dead-letter key for inspection — never silently dropped.
|
|
104
|
+
*/
|
|
59
105
|
interface RetryPolicy {
|
|
60
106
|
/**
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
107
|
+
* Backoff growth across attempts. `"exponential"` doubles the delay each
|
|
108
|
+
* attempt (`baseMs * 2 ** (attempt - 1)`); `"linear"` grows it linearly
|
|
109
|
+
* (`baseMs * attempt`). Default `"exponential"`.
|
|
110
|
+
*/
|
|
65
111
|
backoff?: "exponential" | "linear";
|
|
66
112
|
/** Base delay in milliseconds for the first retry. Default `30_000`. */
|
|
67
113
|
baseMs?: number;
|
|
68
|
-
/**
|
|
114
|
+
/**
|
|
115
|
+
* Maximum number of **retries** after the initial dispatch. Default `5`, so
|
|
116
|
+
* a job that keeps failing is dispatched 6 times in total before it is
|
|
117
|
+
* dead-lettered (the park happens once `attempts > maxAttempts`).
|
|
118
|
+
*/
|
|
69
119
|
maxAttempts?: number;
|
|
70
120
|
/** Optional ceiling clamping the computed backoff delay. */
|
|
71
121
|
maxMs?: number;
|
|
72
122
|
}
|
|
73
123
|
interface RunOptions {
|
|
74
124
|
/**
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
125
|
+
* Job id to store the record under, instead of one the SchedulerDO mints.
|
|
126
|
+
*
|
|
127
|
+
* Exists for `@lunora/server`'s deferred-schedule facade: inside a mutation a
|
|
128
|
+
* `runAfter`/`runAt` is buffered until the transaction commits, but the
|
|
129
|
+
* handler is handed the id synchronously, so the id has to be decided before
|
|
130
|
+
* the call is made. Callers that are not deferring should leave it unset and
|
|
131
|
+
* take the minted id from the return value. Anything that is not a plain
|
|
132
|
+
* `[A-Za-z0-9_-]` id of at most 64 characters, or that LEADS with `-`, is
|
|
133
|
+
* REFUSED (`400 INVALID_SCHEDULE_ID`) rather than replaced: the id is handed
|
|
134
|
+
* to `WorkflowBinding.create({ id })` verbatim for a workflow target, and the
|
|
135
|
+
* engine's instance-id grammar (`^[a-zA-Z0-9_][a-zA-Z0-9-_]*$`) refuses that
|
|
136
|
+
* first character. Minting over it would mean two calls naming the same bad
|
|
137
|
+
* id ran the job twice instead of the second answering `409`.
|
|
138
|
+
*
|
|
139
|
+
* **Not an idempotency key.** An id that is already scheduled is REFUSED
|
|
140
|
+
* (`409 DUPLICATE_SCHEDULE_ID`), not replaced or de-duplicated: the time
|
|
141
|
+
* index is keyed by time as well as id, so an overwrite would fire the new
|
|
142
|
+
* job at the old job's instant and drop the slot it was actually scheduled
|
|
143
|
+
* for. Cancel the existing job first if you mean to reschedule it. The id
|
|
144
|
+
* is free again once the job has fired or been cancelled.
|
|
145
|
+
*/
|
|
146
|
+
id?: string;
|
|
147
|
+
/**
|
|
148
|
+
* Cap for the {@link RunOptions.pool} this job joins, applied when the pool
|
|
149
|
+
* is first created and refreshed on every enqueue that carries one. Ignored
|
|
150
|
+
* without `pool`. A pool created by a `runAfter`/`runAt` that omits it caps
|
|
151
|
+
* at 1 — {@link Workpool} is the usual way to set it.
|
|
152
|
+
*/
|
|
153
|
+
maxConcurrency?: number;
|
|
154
|
+
/**
|
|
155
|
+
* Logical workpool this job belongs to. When set, the SchedulerDO gates the
|
|
156
|
+
* job behind the pool's `maxConcurrency` (see {@link WorkpoolOptions}).
|
|
157
|
+
* Usually populated by {@link Workpool.enqueue}; callers rarely set it on a
|
|
158
|
+
* bare `runAfter`/`runAt`.
|
|
159
|
+
*/
|
|
80
160
|
pool?: string;
|
|
81
161
|
/** Per-job retry policy. Falls back to the DO's built-in defaults when omitted. */
|
|
82
162
|
retry?: RetryPolicy;
|
|
@@ -86,65 +166,108 @@ interface RunOptions {
|
|
|
86
166
|
interface ScheduleRecord {
|
|
87
167
|
args: Record<string, unknown>;
|
|
88
168
|
/**
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
169
|
+
* Number of dispatch attempts already made. Absent (treated as 0) until the
|
|
170
|
+
* first failure, after which `recordRetry()` persists it on both the
|
|
171
|
+
* `retry:` row and the `id:` header. Surfaced here so `/list` consumers and
|
|
172
|
+
* the studio see the field the storage layer actually writes.
|
|
173
|
+
*/
|
|
94
174
|
attempts?: number;
|
|
95
175
|
enqueuedAt: number;
|
|
96
|
-
|
|
176
|
+
/**
|
|
177
|
+
* The `ns:fn` path of the function to dispatch on fire. Absent when the job
|
|
178
|
+
* targets a durable workflow/agent instead — see {@link ScheduleRecord.workflow}.
|
|
179
|
+
* Exactly one of `functionPath` / `workflow` is set.
|
|
180
|
+
*/
|
|
181
|
+
functionPath?: string;
|
|
97
182
|
id: string;
|
|
98
183
|
/**
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
184
|
+
* Scheduler/workpool instance name the job was enqueued through. Echoed in
|
|
185
|
+
* the dispatch payload so the runtime can call back the SAME DO instance's
|
|
186
|
+
* `/complete` to release a pooled slot. Absent for the default instance.
|
|
187
|
+
*/
|
|
103
188
|
instanceName?: string;
|
|
104
189
|
/**
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
190
|
+
* Logical workpool this job belongs to (set by {@link Workpool.enqueue}).
|
|
191
|
+
* When present, the SchedulerDO only dispatches the job while the pool's
|
|
192
|
+
* in-flight count is below its `maxConcurrency`; otherwise it stays queued
|
|
193
|
+
* and drains as slots free. Absent for plain `runAfter`/`runAt` jobs, which
|
|
194
|
+
* are never concurrency-gated.
|
|
195
|
+
*/
|
|
111
196
|
pool?: string;
|
|
112
197
|
/** Per-job retry policy (see {@link RetryPolicy}); absent means DO defaults. */
|
|
113
198
|
retry?: RetryPolicy;
|
|
114
199
|
scheduledFor: number;
|
|
115
200
|
shardKey?: string;
|
|
201
|
+
/**
|
|
202
|
+
* The `WORKFLOW_*`/`AGENT_*` binding name to start a fresh durable instance
|
|
203
|
+
* of on fire (the {@link ScheduleRecord.args} become its `params`). Set
|
|
204
|
+
* instead of {@link ScheduleRecord.functionPath} when the job targets a
|
|
205
|
+
* workflow/agent {@link WorkflowReference}. The runtime — not the DO — owns
|
|
206
|
+
* the binding, so the dispatch payload carries this through to the Worker.
|
|
207
|
+
*/
|
|
208
|
+
workflow?: string;
|
|
116
209
|
}
|
|
117
210
|
interface Scheduler {
|
|
118
211
|
cancel: (id: string) => Promise<{
|
|
119
212
|
cancelled: boolean;
|
|
120
213
|
}>;
|
|
214
|
+
/**
|
|
215
|
+
* Jobs that exhausted their retry budget and were parked under `dead:`
|
|
216
|
+
* (the DO's `/dead` view). Deliberately absent from {@link Scheduler.list} —
|
|
217
|
+
* the park deletes the `id:` header — so this is the only view of a job
|
|
218
|
+
* that failed permanently rather than being silently dropped.
|
|
219
|
+
*/
|
|
220
|
+
dead: () => Promise<ScheduleRecord[]>;
|
|
221
|
+
/**
|
|
222
|
+
* Resurrect a parked job with a fresh attempt budget (the DO's
|
|
223
|
+
* `POST /dead/retry`). `false` when the id is not parked; a racing double
|
|
224
|
+
* recover is a no-op rather than an error.
|
|
225
|
+
*/
|
|
226
|
+
deadRetry: (id: string) => Promise<boolean>;
|
|
121
227
|
/** Resolve a single pending job by id, or `null` when absent (derived from {@link Scheduler.list}). */
|
|
122
228
|
get: (id: string) => Promise<ScheduleRecord | null>;
|
|
123
229
|
/** All pending scheduled jobs (the DO's `/list` view). */
|
|
124
230
|
list: () => Promise<ScheduleRecord[]>;
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
231
|
+
/**
|
|
232
|
+
* Schedule `target` to run once, `delayMs` from now. `target` is a function
|
|
233
|
+
* {@link FunctionReference} (dispatched as a one-shot) or a durable
|
|
234
|
+
* {@link WorkflowReference} — the generated `workflows.<name>` /
|
|
235
|
+
* `agents.<name>` ref — which starts a fresh instance on fire (args become
|
|
236
|
+
* its `params`). {@link ScheduleTargetArgs} infers the accepted args from
|
|
237
|
+
* whichever target was passed.
|
|
238
|
+
*
|
|
239
|
+
* **Resolves the job id, a bare string** — the same value `cancel`/`get`
|
|
240
|
+
* take, and the same value the `ctx.scheduler` surface promises. This object
|
|
241
|
+
* IS `ctx.scheduler` on the shard side (codegen installs it behind
|
|
242
|
+
* `SchedulerLike`, whose `runAfter`/`runAt` are declared `Promise<string>`),
|
|
243
|
+
* so resolving a `{ id, scheduledFor }` record here handed mutations an
|
|
244
|
+
* object where every other gate — `@lunora/server`'s `Scheduler`,
|
|
245
|
+
* `@lunora/shard-engine`'s `SchedulerLike`, `@lunora/runtime`'s httpAction
|
|
246
|
+
* ctx, and the docs — said string. Nothing caught it, because the install is
|
|
247
|
+
* a cast: apps wrote the object into a string column and `cancel(id)`
|
|
248
|
+
* answered `{ cancelled: false }` with no error anywhere.
|
|
249
|
+
*
|
|
250
|
+
* The fire instant is not lost: `runAt` was handed it, and a caller that
|
|
251
|
+
* needs it back reads `scheduledFor` off {@link Scheduler.get}.
|
|
252
|
+
*/
|
|
253
|
+
runAfter: <T extends CronTarget>(delayMs: number, target: T, args: ScheduleTargetArgs<T>, options?: RunOptions) => Promise<string>;
|
|
254
|
+
/** Like {@link Scheduler.runAfter} but fires at an absolute `date`/timestamp. Resolves the job id. */
|
|
255
|
+
runAt: <T extends CronTarget>(date: Date | number, target: T, args: ScheduleTargetArgs<T>, options?: RunOptions) => Promise<string>;
|
|
133
256
|
}
|
|
134
257
|
/**
|
|
135
|
-
* Cloudflare Durable Object data-residency jurisdiction. Widening union —
|
|
136
|
-
* Cloudflare adds values over time.
|
|
137
|
-
* @see https://developers.cloudflare.com/durable-objects/reference/data-location/
|
|
138
|
-
*/
|
|
258
|
+
* Cloudflare Durable Object data-residency jurisdiction. Widening union —
|
|
259
|
+
* Cloudflare adds values over time.
|
|
260
|
+
* @see https://developers.cloudflare.com/durable-objects/reference/data-location/
|
|
261
|
+
*/
|
|
139
262
|
type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
|
|
140
263
|
/** Subset of `DurableObjectNamespace` the package consumes. */
|
|
141
264
|
interface DurableObjectNamespaceLike {
|
|
142
265
|
get: (id: DurableObjectIdLike) => DurableObjectStubLike;
|
|
143
266
|
idFromName: (name: string) => DurableObjectIdLike;
|
|
144
267
|
/**
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
268
|
+
* Derive a jurisdiction-restricted subnamespace. Optional because older
|
|
269
|
+
* workers-types releases (and test doubles) may not expose it.
|
|
270
|
+
*/
|
|
148
271
|
jurisdiction?: (jurisdiction: DurableObjectJurisdiction) => DurableObjectNamespaceLike;
|
|
149
272
|
}
|
|
150
273
|
interface DurableObjectIdLike {
|
|
@@ -157,19 +280,20 @@ interface LunoraSchedulerOptions {
|
|
|
157
280
|
/** Optional named instance — useful for tenant isolation. Default `default`. */
|
|
158
281
|
instanceName?: string;
|
|
159
282
|
/**
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
283
|
+
* Pin the SchedulerDO (durable timers + cron state) to a Cloudflare
|
|
284
|
+
* data-residency jurisdiction. Pass the same value as the worker's
|
|
285
|
+
* `jurisdiction` so scheduled state co-resides with app data. Omit for the
|
|
286
|
+
* un-pinned global namespace.
|
|
287
|
+
*/
|
|
165
288
|
jurisdiction?: DurableObjectJurisdiction;
|
|
166
|
-
/** Binding to the `SchedulerDO` durable object namespace. */
|
|
167
|
-
namespace: DurableObjectNamespaceLike;
|
|
168
289
|
/**
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
290
|
+
* Binding to the `SchedulerDO` durable object namespace.
|
|
291
|
+
*
|
|
292
|
+
* The origin the DO dispatches back to is NOT passed here: it reads
|
|
293
|
+
* `env.LUNORA_ORIGIN_URL` off its own binding at fire time, because a
|
|
294
|
+
* caller-supplied dispatch target would be an SSRF vector.
|
|
295
|
+
*/
|
|
296
|
+
namespace: DurableObjectNamespaceLike;
|
|
173
297
|
}
|
|
174
298
|
/** Per-enqueue options for a {@link Workpool}. Extends {@link RunOptions} minus the implicit `pool` (the pool sets that). */
|
|
175
299
|
interface EnqueueOptions {
|
|
@@ -181,46 +305,46 @@ interface EnqueueOptions {
|
|
|
181
305
|
shardKey?: string;
|
|
182
306
|
}
|
|
183
307
|
/**
|
|
184
|
-
* Options for `createWorkpool`. Mirrors {@link LunoraSchedulerOptions}
|
|
185
|
-
* (same `namespace` / `
|
|
186
|
-
* controls. A workpool is a NAMED logical pool inside the existing SchedulerDO —
|
|
187
|
-
* it needs no extra Durable Object or wrangler binding beyond the SchedulerDO
|
|
188
|
-
* the scheduler already uses.
|
|
189
|
-
*/
|
|
308
|
+
* Options for `createWorkpool`. Mirrors {@link LunoraSchedulerOptions}
|
|
309
|
+
* (same `namespace` / `instanceName`) plus the bounded-concurrency
|
|
310
|
+
* controls. A workpool is a NAMED logical pool inside the existing SchedulerDO —
|
|
311
|
+
* it needs no extra Durable Object or wrangler binding beyond the SchedulerDO
|
|
312
|
+
* the scheduler already uses.
|
|
313
|
+
*/
|
|
190
314
|
interface WorkpoolOptions extends LunoraSchedulerOptions {
|
|
191
315
|
/**
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
316
|
+
* Maximum number of jobs from this pool that may be in flight at once.
|
|
317
|
+
* Excess enqueues are persisted and drain as slots free. Must be a positive
|
|
318
|
+
* integer.
|
|
319
|
+
*/
|
|
196
320
|
maxConcurrency: number;
|
|
197
321
|
/**
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
322
|
+
* Pool name — the concurrency counter is keyed by this inside the
|
|
323
|
+
* SchedulerDO storage (`pool:<name>`). Default `default`.
|
|
324
|
+
*/
|
|
201
325
|
name?: string;
|
|
202
326
|
}
|
|
203
327
|
/**
|
|
204
|
-
* Bounded-concurrency action queue (Lunora equivalent of `@convex-dev/workpool`).
|
|
205
|
-
* Built on the existing SchedulerDO: `enqueue` schedules a job tagged with this
|
|
206
|
-
* pool's name; the DO caps simultaneous dispatch at `maxConcurrency` and queues
|
|
207
|
-
* the rest durably.
|
|
208
|
-
*/
|
|
328
|
+
* Bounded-concurrency action queue (Lunora equivalent of `@convex-dev/workpool`).
|
|
329
|
+
* Built on the existing SchedulerDO: `enqueue` schedules a job tagged with this
|
|
330
|
+
* pool's name; the DO caps simultaneous dispatch at `maxConcurrency` and queues
|
|
331
|
+
* the rest durably.
|
|
332
|
+
*/
|
|
209
333
|
interface Workpool {
|
|
210
334
|
/** Cancel a queued/in-flight pool job by id. */
|
|
211
335
|
cancel: (id: string) => Promise<{
|
|
212
336
|
cancelled: boolean;
|
|
213
337
|
}>;
|
|
214
338
|
/**
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
enqueue: <F extends
|
|
339
|
+
* Enqueue `function_(args)` into the pool. Resolves with the durable job id
|
|
340
|
+
* and the time it was scheduled for (it may not run immediately if the pool
|
|
341
|
+
* is at capacity).
|
|
342
|
+
*/
|
|
343
|
+
enqueue: <F extends SchedulableReference>(function_: F, args: ArgsOf<F>, options?: EnqueueOptions) => Promise<{
|
|
220
344
|
id: string;
|
|
221
345
|
scheduledFor: number;
|
|
222
346
|
}>;
|
|
223
|
-
/** The pool's name (the `pool
|
|
347
|
+
/** The pool's name (the `pool:<name>` storage key suffix). */
|
|
224
348
|
readonly name: string;
|
|
225
349
|
/** Inspect the pool's current state — `inFlight` slots used and the configured `maxConcurrency`. */
|
|
226
350
|
status: () => Promise<{
|
|
@@ -271,6 +395,13 @@ interface MessageBatchLike<Body = unknown> {
|
|
|
271
395
|
}
|
|
272
396
|
/** The wire payload Lunora puts on the queue: a function dispatch. */
|
|
273
397
|
interface QueueJob {
|
|
398
|
+
/**
|
|
399
|
+
* The call's arguments in WIRE form (`shared/wire-codec`), so a `bigint`,
|
|
400
|
+
* `Date` or bytes survives the queue's own JSON serialisation. The producers
|
|
401
|
+
* encode; the shard's dispatch loop is the single decoder. A custom
|
|
402
|
+
* {@link QueueDispatch} must forward this untouched — decoding it here and
|
|
403
|
+
* letting the shard decode again flattens a `Date` to `{}`.
|
|
404
|
+
*/
|
|
274
405
|
args?: Record<string, unknown>;
|
|
275
406
|
functionPath: string;
|
|
276
407
|
/** Routing hint forwarded to the Worker so the call lands on the right shard. */
|
|
@@ -289,14 +420,14 @@ interface QueueWorkpoolOptions {
|
|
|
289
420
|
queue: QueueLike<QueueJob>;
|
|
290
421
|
}
|
|
291
422
|
/**
|
|
292
|
-
* Queues-backed producer: enqueue function dispatches onto a Cloudflare Queue.
|
|
293
|
-
* Concurrency, retries, and dead-lettering are configured on the queue consumer
|
|
294
|
-
* in `wrangler.jsonc` (`max_concurrency` / `max_retries` / `dead_letter_queue`),
|
|
295
|
-
* not here — that's the whole point of using Queues over the DO workpool.
|
|
296
|
-
*/
|
|
423
|
+
* Queues-backed producer: enqueue function dispatches onto a Cloudflare Queue.
|
|
424
|
+
* Concurrency, retries, and dead-lettering are configured on the queue consumer
|
|
425
|
+
* in `wrangler.jsonc` (`max_concurrency` / `max_retries` / `dead_letter_queue`),
|
|
426
|
+
* not here — that's the whole point of using Queues over the DO workpool.
|
|
427
|
+
*/
|
|
297
428
|
interface QueueWorkpool {
|
|
298
429
|
/** Enqueue a single `fn(args)` dispatch. */
|
|
299
|
-
enqueue: <F extends
|
|
430
|
+
enqueue: <F extends SchedulableReference>(function_: F, args: ArgsOf<F>, options?: QueueEnqueueOptions) => Promise<void>;
|
|
300
431
|
/** Enqueue many dispatches in one `sendBatch`. Each job names its function `ref`. */
|
|
301
432
|
enqueueBatch: (jobs: ReadonlyArray<{
|
|
302
433
|
args?: Record<string, unknown>;
|
|
@@ -304,8 +435,12 @@ interface QueueWorkpool {
|
|
|
304
435
|
shardKey?: string;
|
|
305
436
|
}>, options?: QueueSendOptionsLike) => Promise<void>;
|
|
306
437
|
}
|
|
307
|
-
/**
|
|
308
|
-
|
|
438
|
+
/**
|
|
439
|
+
* Dispatches a single {@link QueueJob} — the consumer's per-message worker.
|
|
440
|
+
* `messageId` is the queue message's native id, threaded through so the
|
|
441
|
+
* dispatcher can attribute a failure to the exact message that caused it.
|
|
442
|
+
*/
|
|
443
|
+
type QueueDispatch = (job: QueueJob, messageId?: string) => Promise<void>;
|
|
309
444
|
/** Options for `createQueueConsumer`. */
|
|
310
445
|
interface QueueConsumerOptions {
|
|
311
446
|
/** How each job is executed; e.g. the `httpDispatcher`. */
|
|
@@ -319,43 +454,66 @@ interface HttpDispatcherOptions {
|
|
|
319
454
|
fetchImpl?: typeof fetch;
|
|
320
455
|
/** Origin where the Worker is mounted (the `/_lunora/scheduler/dispatch` endpoint). */
|
|
321
456
|
originUrl: string;
|
|
457
|
+
/**
|
|
458
|
+
* Abort a job's dispatch after this many ms; the abort is retryable, so the
|
|
459
|
+
* consumer retries the message. Defaults to 5 minutes — raise it for a
|
|
460
|
+
* workpool running jobs that legitimately run longer, lower it to fail a
|
|
461
|
+
* stuck origin faster.
|
|
462
|
+
*/
|
|
463
|
+
timeoutMs?: number;
|
|
322
464
|
}
|
|
323
465
|
/**
|
|
324
|
-
* Client-side scheduler — forwards `runAfter` / `runAt` / `cancel` calls to a
|
|
325
|
-
* `SchedulerDO` over HTTP. The DO owns the alarm and the storage; this is a
|
|
326
|
-
* thin RPC wrapper.
|
|
327
|
-
*/
|
|
466
|
+
* Client-side scheduler — forwards `runAfter` / `runAt` / `cancel` calls to a
|
|
467
|
+
* `SchedulerDO` over HTTP. The DO owns the alarm and the storage; this is a
|
|
468
|
+
* thin RPC wrapper.
|
|
469
|
+
*/
|
|
328
470
|
declare const createScheduler: (options: LunoraSchedulerOptions) => Scheduler;
|
|
329
471
|
/**
|
|
330
|
-
* Bounded-concurrency action queue — the Lunora equivalent of
|
|
331
|
-
* `@convex-dev/workpool`. Mirrors `createScheduler`'s `namespace` /
|
|
332
|
-
* `
|
|
333
|
-
* a workpool is just a NAMED logical pool inside that DO (concurrency counter
|
|
334
|
-
* keyed by {@link WorkpoolOptions.name} under the `pool
|
|
335
|
-
* It needs no extra Durable Object or wrangler binding beyond the SchedulerDO
|
|
336
|
-
* the scheduler already uses.
|
|
337
|
-
*
|
|
338
|
-
* `enqueue` schedules a job tagged with this pool; the DO dispatches at most
|
|
339
|
-
* `maxConcurrency` of the pool's jobs at once and queues the rest durably,
|
|
340
|
-
* draining them as the runtime reports completions (`POST /complete`).
|
|
341
|
-
*
|
|
342
|
-
*
|
|
343
|
-
*
|
|
344
|
-
*
|
|
345
|
-
*
|
|
346
|
-
*
|
|
347
|
-
*
|
|
348
|
-
*
|
|
349
|
-
*
|
|
350
|
-
*
|
|
351
|
-
*
|
|
352
|
-
*
|
|
353
|
-
*
|
|
354
|
-
*
|
|
355
|
-
*
|
|
356
|
-
*
|
|
357
|
-
*
|
|
358
|
-
|
|
472
|
+
* Bounded-concurrency action queue — the Lunora equivalent of
|
|
473
|
+
* `@convex-dev/workpool`. Mirrors `createScheduler`'s `namespace` /
|
|
474
|
+
* `instanceName` options and is built on the SAME `SchedulerDO`:
|
|
475
|
+
* a workpool is just a NAMED logical pool inside that DO (concurrency counter
|
|
476
|
+
* keyed by {@link WorkpoolOptions.name} under the `pool:<name>` storage key).
|
|
477
|
+
* It needs no extra Durable Object or wrangler binding beyond the SchedulerDO
|
|
478
|
+
* the scheduler already uses.
|
|
479
|
+
*
|
|
480
|
+
* `enqueue` schedules a job tagged with this pool; the DO dispatches at most
|
|
481
|
+
* `maxConcurrency` of the pool's jobs at once and queues the rest durably,
|
|
482
|
+
* draining them as the runtime reports completions (`POST /complete`).
|
|
483
|
+
*
|
|
484
|
+
* The ceiling the platform adds: one alarm drain keeps at most SIX dispatches in
|
|
485
|
+
* flight, because a Durable Object may have only six connections simultaneously
|
|
486
|
+
* waiting for response headers. A `maxConcurrency` above six is therefore not
|
|
487
|
+
* wrong, just not reachable within a single drain — the surplus drains on the
|
|
488
|
+
* following alarms. The same invocation is bounded by the 15-minute alarm wall
|
|
489
|
+
* clock, which covers the WHOLE drain rather than one job; work that does not
|
|
490
|
+
* fit is deferred to the next alarm, never dropped.
|
|
491
|
+
*
|
|
492
|
+
* For jobs that are individually long — an LLM call, an export, a payment
|
|
493
|
+
* round-trip — prefer `createQueueWorkpool`: the dispatch this DO awaits
|
|
494
|
+
* only returns once the function has finished running, so a long job occupies
|
|
495
|
+
* one of those six slots and one slice of that 15-minute budget for its whole
|
|
496
|
+
* duration. A Queues consumer gets a fresh Worker invocation per batch, with its
|
|
497
|
+
* own connection budget and its own clock, and its `max_concurrency` is not
|
|
498
|
+
* capped at six. You give up the hard cap, per-job cancel, and per-job status.
|
|
499
|
+
*
|
|
500
|
+
* ```ts
|
|
501
|
+
* const pool = createWorkpool({ namespace: env.SCHEDULER, maxConcurrency: 5 });
|
|
502
|
+
* await pool.enqueue(internal.stripe.sync, { invoiceId }, { retry: { maxAttempts: 3 } });
|
|
503
|
+
* ```
|
|
504
|
+
*
|
|
505
|
+
* Why not Cloudflare Queues? Queues natively cover concurrency-capped, retried,
|
|
506
|
+
* dead-lettered, delayed dispatch (`max_concurrency`, `max_retries`,
|
|
507
|
+
* `retry({ delaySeconds })`, `dead_letter_queue`), and are the right tool when
|
|
508
|
+
* you just want to rate-limit fire-and-forget background work. This workpool
|
|
509
|
+
* deliberately stays on `SchedulerDO` because it offers what a queue can't: a
|
|
510
|
+
* hard concurrency cap (the DO is the single serialization point — no
|
|
511
|
+
* cross-consumer overshoot), per-job cancellation, and per-job status
|
|
512
|
+
* introspection, all keyed by a stable job id. Reach for Queues when you don't
|
|
513
|
+
* need those; reach for this when you do. Either way, do NOT grow multi-step
|
|
514
|
+
* orchestration on top of this — that's Cloudflare **Workflows** (`step.do` /
|
|
515
|
+
* `step.sleep` / `step.waitForEvent`).
|
|
516
|
+
*/
|
|
359
517
|
declare const createWorkpool: (options: WorkpoolOptions) => Workpool;
|
|
360
518
|
interface CronTriggerOptions {
|
|
361
519
|
/** Args passed to the function. */
|
|
@@ -377,15 +535,25 @@ interface CronTriggerSnippet {
|
|
|
377
535
|
wranglerJsonc: string;
|
|
378
536
|
}
|
|
379
537
|
/**
|
|
380
|
-
* Produces the wrangler.jsonc fragment + dispatcher metadata for a recurring
|
|
381
|
-
* function. The actual cron handler is mounted by `@lunora/runtime` — we only
|
|
382
|
-
* emit the configuration here.
|
|
383
|
-
*/
|
|
538
|
+
* Produces the wrangler.jsonc fragment + dispatcher metadata for a recurring
|
|
539
|
+
* function. The actual cron handler is mounted by `@lunora/runtime` — we only
|
|
540
|
+
* emit the configuration here.
|
|
541
|
+
*/
|
|
384
542
|
declare const createCronTrigger: (options: CronTriggerOptions) => CronTriggerSnippet;
|
|
385
543
|
/** Sub-day recurrence. Exactly one unit must be provided. */
|
|
386
544
|
interface IntervalSchedule {
|
|
545
|
+
/** 1–23, and must divide 24 (an interval repeats *within* a day). */
|
|
387
546
|
hours?: number;
|
|
547
|
+
/** 1–59, and must divide 60. */
|
|
388
548
|
minutes?: number;
|
|
549
|
+
/**
|
|
550
|
+
* Accepted by the type, **rejected at definition time**: Cloudflare Cron
|
|
551
|
+
* Triggers have a one-minute floor, so the 6-field expression this compiles
|
|
552
|
+
* to would survive codegen and land in the committed `wrangler.jsonc`, then
|
|
553
|
+
* fail at `wrangler deploy` naming neither the job nor the file. Declared so
|
|
554
|
+
* the rejection can name the job instead. Use `ctx.scheduler.runAfter`/
|
|
555
|
+
* `runAt` for sub-minute recurrence, or `{ minutes: 1 }`.
|
|
556
|
+
*/
|
|
389
557
|
seconds?: number;
|
|
390
558
|
}
|
|
391
559
|
/** Daily recurrence at a fixed UTC wall-clock time. */
|
|
@@ -395,6 +563,19 @@ interface DailySchedule {
|
|
|
395
563
|
/** 0–59. */
|
|
396
564
|
minuteUTC: number;
|
|
397
565
|
}
|
|
566
|
+
/**
|
|
567
|
+
* Hourly recurrence at a fixed minute past the hour.
|
|
568
|
+
*
|
|
569
|
+
* `crons.interval({ hours: 1 })` compiles to the same expression, but the
|
|
570
|
+
* asymmetry of having `daily`/`weekly`/`monthly` and no `hourly` is its own
|
|
571
|
+
* papercut — and unlike the interval form this one lets
|
|
572
|
+
* the caller place the job off the hour boundary, which is how you stop a
|
|
573
|
+
* dozen hourly jobs from stampeding at `:00`.
|
|
574
|
+
*/
|
|
575
|
+
interface HourlySchedule {
|
|
576
|
+
/** 0–59. */
|
|
577
|
+
minuteUTC: number;
|
|
578
|
+
}
|
|
398
579
|
/** Weekly recurrence at a fixed UTC time on a given weekday. */
|
|
399
580
|
interface WeeklySchedule extends DailySchedule {
|
|
400
581
|
/** Long weekday name, case-insensitive (e.g. `"monday"`). */
|
|
@@ -406,106 +587,156 @@ interface MonthlySchedule extends DailySchedule {
|
|
|
406
587
|
day: number;
|
|
407
588
|
}
|
|
408
589
|
/**
|
|
409
|
-
* One registered cron job, normalized to a compiled cron expression. Shared
|
|
410
|
-
* verbatim with `@lunora/codegen` (which lifts the same fields out of the AST)
|
|
411
|
-
* and the runtime dispatcher — keep the shape stable across all three.
|
|
412
|
-
*/
|
|
590
|
+
* One registered cron job, normalized to a compiled cron expression. Shared
|
|
591
|
+
* verbatim with `@lunora/codegen` (which lifts the same fields out of the AST)
|
|
592
|
+
* and the runtime dispatcher — keep the shape stable across all three.
|
|
593
|
+
*/
|
|
413
594
|
interface CronJob {
|
|
414
595
|
/** Args forwarded to the function (or, for a workflow target, used as its `params`) on each fire. */
|
|
415
596
|
args: Record<string, unknown>;
|
|
416
597
|
/** Compiled standard cron expression, e.g. `"0 9 * * *"`. */
|
|
417
598
|
cron: string;
|
|
418
599
|
/**
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
600
|
+
* `__lunoraRef` of the target function. Present for a function target;
|
|
601
|
+
* absent when the job targets a workflow ({@link CronJob.workflow} instead).
|
|
602
|
+
*/
|
|
422
603
|
functionPath?: string;
|
|
423
604
|
/** Human-readable identifier — must be unique within one `cronJobs()`. */
|
|
424
605
|
name: string;
|
|
425
606
|
/**
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
607
|
+
* Set when the job targets a durable workflow rather than a function: the
|
|
608
|
+
* workflow's stable name (`defineWorkflow({ name })`) when one was declared,
|
|
609
|
+
* otherwise `""`. `@lunora/codegen` statically resolves the concrete
|
|
610
|
+
* `lunora/workflows.ts` export + its `WORKFLOW_*` binding for the emitted
|
|
611
|
+
* dispatch map, so this authoring-time value is informational only.
|
|
612
|
+
*/
|
|
432
613
|
workflow?: string;
|
|
433
614
|
}
|
|
434
615
|
/** The ergonomic builder methods, excluding the raw `.cron` escape hatch. */
|
|
435
|
-
type CronScheduleKind = "daily" | "interval" | "monthly" | "weekly";
|
|
616
|
+
type CronScheduleKind = "daily" | "hourly" | "interval" | "monthly" | "weekly";
|
|
436
617
|
/** The ergonomic schedule kinds as a runtime set (codegen reads this to detect cron builder methods). */
|
|
437
618
|
declare const CRON_SCHEDULE_KINDS: ReadonlySet<CronScheduleKind>;
|
|
438
619
|
/**
|
|
439
|
-
* Compile one of the ergonomic schedule forms into a standard cron expression.
|
|
440
|
-
* Exposed as a pure function so `@lunora/codegen` can reuse the exact same
|
|
441
|
-
* compilation when it statically lifts a `crons.{kind}(...)` call out of the
|
|
442
|
-
* AST — codegen imports this directly (no duplicated mirror).
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
*
|
|
449
|
-
|
|
620
|
+
* Compile one of the ergonomic schedule forms into a standard cron expression.
|
|
621
|
+
* Exposed as a pure function so `@lunora/codegen` can reuse the exact same
|
|
622
|
+
* compilation when it statically lifts a `crons.{kind}(...)` call out of the
|
|
623
|
+
* AST — codegen imports this directly (no duplicated mirror). `jobName` is
|
|
624
|
+
* optional (see {@link compileInterval}) so codegen's existing 2-arg call site
|
|
625
|
+
* keeps working unchanged.
|
|
626
|
+
*/
|
|
627
|
+
declare const compileCronSchedule: (kind: CronScheduleKind, schedule: DailySchedule | HourlySchedule | IntervalSchedule | MonthlySchedule | WeeklySchedule, jobName?: string) => string;
|
|
628
|
+
/**
|
|
629
|
+
* Builder returned by {@link cronJobs}. Each method registers one recurring
|
|
630
|
+
* job; the compiled expression is validated immediately so authoring mistakes
|
|
631
|
+
* surface at definition time rather than at codegen.
|
|
632
|
+
*/
|
|
450
633
|
interface CronJobsBuilder {
|
|
451
634
|
/**
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
635
|
+
* Raw cron expression escape hatch (5- or 6-field, full cron-parser grammar).
|
|
636
|
+
* The target may be a function (`internal.file.fn`) or a durable workflow
|
|
637
|
+
* (`workflows.<name>`); a workflow's `args` are inferred from its `params`.
|
|
638
|
+
*/
|
|
456
639
|
cron: <T extends CronTarget>(name: string, cronExpr: string, target: T, args?: CronTargetArgs<T>) => CronJobsBuilder;
|
|
457
|
-
/** Daily at `hourUTC:minuteUTC` (UTC). The target may be a function or a durable workflow (`workflows
|
|
640
|
+
/** Daily at `hourUTC:minuteUTC` (UTC). The target may be a function or a durable workflow (`workflows.<name>`). */
|
|
458
641
|
daily: <T extends CronTarget>(name: string, schedule: DailySchedule, target: T, args?: CronTargetArgs<T>) => CronJobsBuilder;
|
|
459
|
-
/**
|
|
642
|
+
/** Hourly at `minuteUTC` past the hour. The target may be a function or a durable workflow (`workflows.<name>`). */
|
|
643
|
+
hourly: <T extends CronTarget>(name: string, schedule: HourlySchedule, target: T, args?: CronTargetArgs<T>) => CronJobsBuilder;
|
|
644
|
+
/** Every `{ minutes | hours }` — `{ seconds }` throws (Cron Triggers have a one-minute floor). The target may be a function or a durable workflow (`workflows.<name>`). */
|
|
460
645
|
interval: <T extends CronTarget>(name: string, schedule: IntervalSchedule, target: T, args?: CronTargetArgs<T>) => CronJobsBuilder;
|
|
461
646
|
/** Snapshot of the registered jobs, in declaration order. */
|
|
462
647
|
jobs: () => ReadonlyArray<CronJob>;
|
|
463
|
-
/** Monthly on `day` at `hourUTC:minuteUTC` (UTC). The target may be a function or a durable workflow (`workflows
|
|
648
|
+
/** Monthly on `day` at `hourUTC:minuteUTC` (UTC). The target may be a function or a durable workflow (`workflows.<name>`). */
|
|
464
649
|
monthly: <T extends CronTarget>(name: string, schedule: MonthlySchedule, target: T, args?: CronTargetArgs<T>) => CronJobsBuilder;
|
|
465
|
-
/** Weekly on `dayOfWeek` at `hourUTC:minuteUTC` (UTC). The target may be a function or a durable workflow (`workflows
|
|
650
|
+
/** Weekly on `dayOfWeek` at `hourUTC:minuteUTC` (UTC). The target may be a function or a durable workflow (`workflows.<name>`). */
|
|
466
651
|
weekly: <T extends CronTarget>(name: string, schedule: WeeklySchedule, target: T, args?: CronTargetArgs<T>) => CronJobsBuilder;
|
|
467
652
|
}
|
|
468
653
|
/**
|
|
469
|
-
* Create a code-first cron registry. The returned builder is chainable;
|
|
470
|
-
* codegen discovers a `lunora/crons.ts` default export by AST, not a runtime
|
|
471
|
-
* brand.
|
|
472
|
-
*/
|
|
654
|
+
* Create a code-first cron registry. The returned builder is chainable;
|
|
655
|
+
* codegen discovers a `lunora/crons.ts` default export by AST, not a runtime
|
|
656
|
+
* brand.
|
|
657
|
+
*/
|
|
473
658
|
declare const cronJobs: () => CronJobsBuilder;
|
|
474
659
|
/**
|
|
475
|
-
* Build a Queues producer that enqueues Lunora function dispatches. Concurrency
|
|
476
|
-
* and retry policy live on the consumer's `wrangler.jsonc` config, not here.
|
|
477
|
-
*/
|
|
660
|
+
* Build a Queues producer that enqueues Lunora function dispatches. Concurrency
|
|
661
|
+
* and retry policy live on the consumer's `wrangler.jsonc` config, not here.
|
|
662
|
+
*/
|
|
478
663
|
declare const createQueueWorkpool: (options: QueueWorkpoolOptions) => QueueWorkpool;
|
|
479
664
|
/**
|
|
480
|
-
* Wrap a {@link QueueDispatch} into a Cloudflare `queue()` consumer handler.
|
|
481
|
-
*
|
|
482
|
-
* Each message is dispatched independently (concurrently across the batch). On
|
|
483
|
-
* success the message is `ack()`-ed; on any failure — a thrown dispatcher or a
|
|
484
|
-
* structurally-invalid body — it is `retry()`-ed, so Queues' own `max_retries`
|
|
485
|
-
* + `dead_letter_queue` settings decide when to give up. Nothing is silently
|
|
486
|
-
* dropped: a permanently-bad message rides retries into the dead-letter queue
|
|
487
|
-
* where you can inspect it.
|
|
488
|
-
*/
|
|
665
|
+
* Wrap a {@link QueueDispatch} into a Cloudflare `queue()` consumer handler.
|
|
666
|
+
*
|
|
667
|
+
* Each message is dispatched independently (concurrently across the batch). On
|
|
668
|
+
* success the message is `ack()`-ed; on any failure — a thrown dispatcher or a
|
|
669
|
+
* structurally-invalid body — it is `retry()`-ed, so Queues' own `max_retries`
|
|
670
|
+
* + `dead_letter_queue` settings decide when to give up. Nothing is silently
|
|
671
|
+
* dropped: a permanently-bad message rides retries into the dead-letter queue
|
|
672
|
+
* where you can inspect it.
|
|
673
|
+
*/
|
|
489
674
|
declare const createQueueConsumer: (options: QueueConsumerOptions) => ((batch: MessageBatchLike) => Promise<void>);
|
|
490
675
|
/**
|
|
491
|
-
* Default {@link QueueDispatch}:
|
|
492
|
-
* `/_lunora/scheduler/dispatch` endpoint (the same path SchedulerDO dispatches
|
|
493
|
-
* through)
|
|
494
|
-
*
|
|
495
|
-
|
|
676
|
+
* Default {@link QueueDispatch}: dispatch each job to the Worker's
|
|
677
|
+
* `/_lunora/scheduler/dispatch` endpoint (the same path SchedulerDO dispatches
|
|
678
|
+
* through) via `@lunora/dispatch`'s `createDispatchRunner` — which bounds each
|
|
679
|
+
* job with {@link HttpDispatcherOptions.timeoutMs} (default
|
|
680
|
+
* {@link DEFAULT_JOB_TIMEOUT_MS}), so a hung origin no longer holds the whole
|
|
681
|
+
* `queue()` invocation open, and threads the queue message id through for
|
|
682
|
+
* failure attribution. Any dispatch failure throws so the consumer retries the
|
|
683
|
+
* message — including a 2xx carrying a non-empty non-JSON body, which is an
|
|
684
|
+
* intermediary's page rather than a function's return value and therefore no
|
|
685
|
+
* evidence the job ran. An empty 2xx is a normal success (a `void` function).
|
|
686
|
+
*
|
|
687
|
+
* `job.args` is forwarded VERBATIM: {@link encodeJobArgs} already put it in wire
|
|
688
|
+
* form at the producer, and the shard's dispatch loop is the single decoder.
|
|
689
|
+
* Encoding again here would leave the handler a tagged array.
|
|
690
|
+
*/
|
|
496
691
|
declare const httpDispatcher: (options: HttpDispatcherOptions) => QueueDispatch;
|
|
497
692
|
/**
|
|
498
|
-
*
|
|
499
|
-
*
|
|
500
|
-
*
|
|
501
|
-
*
|
|
502
|
-
*
|
|
503
|
-
|
|
693
|
+
* The id a new record is stored under: the caller's, or a freshly minted one when
|
|
694
|
+
* they did not name it.
|
|
695
|
+
*
|
|
696
|
+
* A caller id that is not a safe key segment is REFUSED, not replaced.
|
|
697
|
+
* `RunOptions.id` is not an idempotency key — an id already scheduled answers
|
|
698
|
+
* `409 DUPLICATE_SCHEDULE_ID` — so quietly swapping an invalid one for a random
|
|
699
|
+
* id made `runAt(ts, ref, args, { id: "-daily-2026-09-06" })` mint a fresh id on
|
|
700
|
+
* every call and run the job once per call, where naming it was the caller's way
|
|
701
|
+
* of saying "at most once".
|
|
702
|
+
*
|
|
703
|
+
* Minting swaps a leading `-` for `_` rather than re-rolling: 1 in 64 minted ids
|
|
704
|
+
* led with one and was refused by the workflow engine on dispatch. `_` is in the
|
|
705
|
+
* engine's leading class, the swap is a single pass, and 96 random bits stay 96
|
|
706
|
+
* random bits everywhere but that first character.
|
|
707
|
+
*
|
|
708
|
+
* Exported because two surfaces have to agree on it. The SchedulerDO applies it
|
|
709
|
+
* when the record is written (turning the refusal into a `400`);
|
|
710
|
+
* `@lunora/server`'s deferred-schedule facade applies it when the call is
|
|
711
|
+
* BUFFERED, because it answers the handler with the id synchronously — long
|
|
712
|
+
* before the DO sees the request. Restating the rule in the facade is how the two
|
|
713
|
+
* drift: an id the facade accepted and the DO replaced leaves the handler holding
|
|
714
|
+
* an id no job was ever stored under, so its later `cancel` silently misses.
|
|
715
|
+
* @param requested the caller's `RunOptions.id`, if any
|
|
716
|
+
* @throws LunoraError `INVALID_SCHEDULE_ID` when `requested` is supplied and is not a safe key segment
|
|
717
|
+
*/
|
|
718
|
+
declare const resolveScheduleId: (requested: unknown) => string;
|
|
719
|
+
/**
|
|
720
|
+
* Minimal projection of `DurableObjectState` for the SchedulerDO. Declared
|
|
721
|
+
* structurally so unit tests can pass a fake state without booting the
|
|
722
|
+
* workers runtime. The WebSocket methods are optional: they back the live
|
|
723
|
+
* `/ws` subscription (push the job list on every change) and are absent in the
|
|
724
|
+
* storage-only fakes, in which case the DO simply serves no live sockets.
|
|
725
|
+
*/
|
|
504
726
|
interface SchedulerDOState {
|
|
505
727
|
/** Accept a hibernatable server WebSocket (workers `state.acceptWebSocket`). */
|
|
506
728
|
acceptWebSocket?: (ws: WebSocket) => void;
|
|
507
729
|
/** Every accepted server WebSocket (workers `state.getWebSockets`). */
|
|
508
730
|
getWebSockets?: () => WebSocket[];
|
|
731
|
+
/**
|
|
732
|
+
* Register a constant ping/pong auto-response so the runtime answers a
|
|
733
|
+
* known keepalive frame on a hibernated socket WITHOUT waking this DO (no
|
|
734
|
+
* billable request, no dispatch). Optional: absent in the unit harness and
|
|
735
|
+
* older runtimes, present on the real `DurableObjectState`. Mirrors
|
|
736
|
+
* `@lunora/do`'s `ShardDOState.setWebSocketAutoResponse` — see
|
|
737
|
+
* {@link SchedulerDO.armWebSocketKeepalive}.
|
|
738
|
+
*/
|
|
739
|
+
setWebSocketAutoResponse?: (pair: WebSocketRequestResponsePair) => void;
|
|
509
740
|
storage: {
|
|
510
741
|
delete: (key: string | string[]) => Promise<number | boolean>;
|
|
511
742
|
deleteAlarm: () => Promise<void> | void;
|
|
@@ -515,6 +746,7 @@ interface SchedulerDOState {
|
|
|
515
746
|
end?: string;
|
|
516
747
|
limit?: number;
|
|
517
748
|
prefix?: string;
|
|
749
|
+
startAfter?: string;
|
|
518
750
|
}) => Promise<Map<string, T>>;
|
|
519
751
|
put: <T = unknown>(entries: Record<string, T> | string, value?: T) => Promise<void>;
|
|
520
752
|
setAlarm: (scheduledTime: number | Date) => Promise<void> | void;
|
|
@@ -523,293 +755,644 @@ interface SchedulerDOState {
|
|
|
523
755
|
interface SchedulerEnv {
|
|
524
756
|
[key: string]: unknown;
|
|
525
757
|
/**
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
758
|
+
* Fallback bearer token attached to the dispatch when
|
|
759
|
+
* {@link SchedulerEnv.LUNORA_SCHEDULER_SECRET} is not configured. Sent as
|
|
760
|
+
* `authorization: Bearer <token>`.
|
|
761
|
+
*/
|
|
530
762
|
LUNORA_ADMIN_TOKEN?: string;
|
|
531
763
|
/**
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
764
|
+
* Base URL where the Worker is mounted. SchedulerDO uses this at dispatch
|
|
765
|
+
* time to call back into the Worker. Read at fire time (NOT taken from the
|
|
766
|
+
* request body, which carries no dispatch target at all) to prevent SSRF.
|
|
767
|
+
*/
|
|
536
768
|
LUNORA_ORIGIN_URL?: string;
|
|
537
769
|
/**
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
770
|
+
* Shared secret used to HMAC-sign the dispatch body so the runtime receiver
|
|
771
|
+
* can authenticate the call (header `x-lunora-scheduler-signature`). Without
|
|
772
|
+
* it the dispatch is sent unsigned (optionally bearer-authenticated via
|
|
773
|
+
* {@link SchedulerEnv.LUNORA_ADMIN_TOKEN}).
|
|
774
|
+
*/
|
|
543
775
|
LUNORA_SCHEDULER_SECRET?: string;
|
|
544
776
|
}
|
|
545
777
|
/**
|
|
546
|
-
*
|
|
547
|
-
*
|
|
548
|
-
*
|
|
549
|
-
|
|
778
|
+
* Retries allowed after the original attempt before {@link SchedulerDO.recordRetry}
|
|
779
|
+
* parks a record in the dead-letter (`dead:`) prefix. Overridable per job via
|
|
780
|
+
* {@link RetryPolicy.maxAttempts}. Exported so test doubles of the scheduler
|
|
781
|
+
* (`@lunora/testing`'s fake scheduler) model the same budget instead of
|
|
782
|
+
* duplicating the number.
|
|
783
|
+
*/
|
|
784
|
+
declare const MAX_RETRY_ATTEMPTS = 5;
|
|
785
|
+
/**
|
|
786
|
+
* Backoff before the first retry, in milliseconds; doubles on each subsequent
|
|
787
|
+
* retry under the default `"exponential"` backoff (`baseMs * 2 ** (attempts - 1)`).
|
|
788
|
+
* Overridable per job via {@link RetryPolicy.baseMs}. Exported alongside
|
|
789
|
+
* {@link MAX_RETRY_ATTEMPTS} for the same reason.
|
|
790
|
+
*/
|
|
791
|
+
declare const RETRY_BASE_DELAY_MS = 3e4;
|
|
792
|
+
/**
|
|
793
|
+
* One pool's live backlog, as surfaced by `GET /status`. `inFlight`/
|
|
794
|
+
* `maxConcurrency` mirror the durable {@link PoolState} semaphore; `queued`
|
|
795
|
+
* is the number of pending (not-yet-dispatched) jobs routed to this pool.
|
|
796
|
+
*/
|
|
550
797
|
interface SchedulerPoolStatus {
|
|
551
798
|
/** Jobs currently dispatched-but-not-yet-completed (the held slots). */
|
|
552
799
|
inFlight: number;
|
|
553
800
|
/** The pool's concurrency cap. */
|
|
554
801
|
maxConcurrency: number;
|
|
555
|
-
/** The logical workpool name (the `pool
|
|
802
|
+
/** The logical workpool name (the `pool:<name>` suffix). */
|
|
556
803
|
name: string;
|
|
557
804
|
/** Pending jobs routed to this pool but not yet dispatched. */
|
|
558
805
|
queued: number;
|
|
559
806
|
}
|
|
560
807
|
/**
|
|
561
|
-
* App-level scheduler backlog, as returned by `GET /status`. `pools` carries
|
|
562
|
-
* the per-pool breakdown; `backlog` and `inFlight` are the app-wide sums of
|
|
563
|
-
* `queued` and `inFlight` across every pool — the SLO view's headline numbers.
|
|
564
|
-
*/
|
|
808
|
+
* App-level scheduler backlog, as returned by `GET /status`. `pools` carries
|
|
809
|
+
* the per-pool breakdown; `backlog` and `inFlight` are the app-wide sums of
|
|
810
|
+
* `queued` and `inFlight` across every pool — the SLO view's headline numbers.
|
|
811
|
+
*/
|
|
565
812
|
interface SchedulerStatus {
|
|
566
813
|
/** Sum of every pool's `queued` count — the total pending backlog. */
|
|
567
814
|
backlog: number;
|
|
568
815
|
/** Sum of every pool's `inFlight` count — the total held concurrency slots. */
|
|
569
816
|
inFlight: number;
|
|
570
|
-
/** Per-pool backlog breakdown, one entry per `pool
|
|
817
|
+
/** Per-pool backlog breakdown, one entry per `pool:<name>` record. */
|
|
571
818
|
pools: SchedulerPoolStatus[];
|
|
572
819
|
}
|
|
573
820
|
/**
|
|
574
|
-
* Durable Object that stores pending scheduled invocations sorted by their
|
|
575
|
-
* `scheduledFor` time and fires them via HTTP on alarm. Storage layout:
|
|
576
|
-
* `id
|
|
577
|
-
* id (used as a sorted index).
|
|
578
|
-
*
|
|
579
|
-
* On every mutation the DO recomputes the earliest pending task and updates
|
|
580
|
-
* the alarm via `state.storage.setAlarm(time)`.
|
|
581
|
-
*/
|
|
821
|
+
* Durable Object that stores pending scheduled invocations sorted by their
|
|
822
|
+
* `scheduledFor` time and fires them via HTTP on alarm. Storage layout:
|
|
823
|
+
* `id:<id>` maps to {@link ScheduleRecord}; `t:<paddedTime>:<id>` maps to the
|
|
824
|
+
* id (used as a sorted index).
|
|
825
|
+
*
|
|
826
|
+
* On every mutation the DO recomputes the earliest pending task and updates
|
|
827
|
+
* the alarm via `state.storage.setAlarm(time)`.
|
|
828
|
+
*/
|
|
582
829
|
declare class SchedulerDO {
|
|
583
830
|
private static indexKey;
|
|
584
831
|
private static json;
|
|
585
832
|
private static error;
|
|
586
833
|
/**
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
834
|
+
* Resolve the effective retry parameters for a record: its per-job
|
|
835
|
+
* {@link RetryPolicy} merged over the DO's built-in defaults. Callers that
|
|
836
|
+
* never set `record.retry` get today's behaviour verbatim
|
|
837
|
+
* (`maxAttempts: 5`, exponential, `baseMs: 30_000`, no ceiling).
|
|
838
|
+
*/
|
|
592
839
|
private static resolveRetry;
|
|
593
840
|
/** Clamp an untrusted `maxConcurrency` to a positive integer, else fall back. */
|
|
594
841
|
private static normalizeConcurrency;
|
|
595
842
|
/**
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
843
|
+
* Sanitize an untrusted retry policy from the wire into a `RetryPolicy` (or
|
|
844
|
+
* `undefined` when nothing valid was provided). Keeps obviously-bad values
|
|
845
|
+
* out of storage so {@link SchedulerDO.resolveRetry} never has to re-guard.
|
|
846
|
+
* @returns The normalized policy, or `undefined` if no valid policy was found.
|
|
847
|
+
*/
|
|
601
848
|
private static normalizeRetry;
|
|
602
849
|
/**
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
850
|
+
* Idempotently release the slot held by `jobId`, returning the updated
|
|
851
|
+
* {@link PoolState} (pure — the caller persists it). A duplicate release for
|
|
852
|
+
* an id that no longer holds a slot is a no-op, so an at-least-once
|
|
853
|
+
* `/complete` (or a complete racing a failed-kick release) can never push
|
|
854
|
+
* `inFlight` below the true number of running jobs and oversubscribe the
|
|
855
|
+
* pool. Pools persisted before `inFlightIds` existed fall back to a clamped
|
|
856
|
+
* counter decrement.
|
|
857
|
+
*/
|
|
611
858
|
private static releaseSlot;
|
|
612
859
|
/**
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
860
|
+
* Best-effort release with no job id (legacy `/complete` payloads). Drops one
|
|
861
|
+
* tracked id if the set exists, else clamps the counter. Less precise than
|
|
862
|
+
* {@link SchedulerDO.releaseSlot} — a duplicate id-less complete CAN
|
|
863
|
+
* over-release — but every current client sends the id, so this is the
|
|
864
|
+
* compatibility shim, not the hot path.
|
|
865
|
+
*/
|
|
619
866
|
private static releaseFirstSlot;
|
|
867
|
+
/**
|
|
868
|
+
* Normalize the mutually-exclusive dispatch target off an untrusted body: a
|
|
869
|
+
* one-shot function path (`functionPath`) or a durable workflow/agent
|
|
870
|
+
* instance (`workflow`, a `WORKFLOW_*`/`AGENT_*` binding). Returns `undefined`
|
|
871
|
+
* when neither is present so the caller can reject the schedule.
|
|
872
|
+
*/
|
|
873
|
+
private static resolveScheduleTarget;
|
|
620
874
|
protected readonly state: SchedulerDOState;
|
|
621
875
|
protected readonly env: SchedulerEnv;
|
|
876
|
+
/**
|
|
877
|
+
* Whether {@link SchedulerDO.reindexOrphanedRecords} has already run in THIS
|
|
878
|
+
* instance. Once is enough: an orphan can only be minted by an eviction, and
|
|
879
|
+
* an eviction ends the instance that minted it.
|
|
880
|
+
*/
|
|
881
|
+
private reindexed;
|
|
882
|
+
/**
|
|
883
|
+
* Tail of the serialized `pool:<name>` critical section — see
|
|
884
|
+
* the pool lock (`withPoolLock`). Per-instance, which is the right scope: the pool rows
|
|
885
|
+
* live in this Durable Object's own storage and only this instance writes
|
|
886
|
+
* them.
|
|
887
|
+
*/
|
|
888
|
+
private poolLock;
|
|
889
|
+
/**
|
|
890
|
+
* Record id → the `t:` index key its in-flight claim currently holds, for
|
|
891
|
+
* every dispatch this instance has open. See `drainRecordGuarded()`.
|
|
892
|
+
*
|
|
893
|
+
* A lease moves a record's index entry without rewriting its `scheduledFor`,
|
|
894
|
+
* so while a claim is held the live key is NOT the one derivable from the
|
|
895
|
+
* record. Anything that has to remove such a record — `removeRecord()`, on
|
|
896
|
+
* the `/cancel` path — would otherwise delete a key that no longer exists
|
|
897
|
+
* and strand the real one.
|
|
898
|
+
*
|
|
899
|
+
* In-memory and per-instance on purpose: it answers "is THIS instance
|
|
900
|
+
* dispatching that record right now", which is exactly when the divergence
|
|
901
|
+
* can be observed by another request. A lease left behind by an instance that
|
|
902
|
+
* died has no live dispatch to protect and is reconciled from storage
|
|
903
|
+
* instead — `alarm()` drops it as a dangling entry once the header is gone.
|
|
904
|
+
*/
|
|
905
|
+
private readonly activeLeases;
|
|
622
906
|
constructor(state: SchedulerDOState, env: SchedulerEnv);
|
|
623
907
|
fetch(request: Request): Promise<Response>;
|
|
624
|
-
/** Called by the Workers runtime when the alarm previously set by `
|
|
908
|
+
/** Called by the Workers runtime when the alarm previously set by `rescheduleAlarm()` fires. */
|
|
625
909
|
alarm(): Promise<void>;
|
|
626
910
|
/**
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
911
|
+
* Internal dispatch hook; overridden in unit tests to capture the outgoing
|
|
912
|
+
* request. Returns `true` ONLY on an explicit 2xx response (`response.ok`).
|
|
913
|
+
* Anything else — a network failure, a 5xx, OR a non-2xx such as 404
|
|
914
|
+
* (receiver route not mounted) / 401 / 403 / 4xx — returns `false` and
|
|
915
|
+
* enters the retry pipeline via {@link recordRetry}. Treating 4xx as
|
|
916
|
+
* success used to permanently delete the job; since the receiver may simply
|
|
917
|
+
* be missing (404) or transiently failing, we retry rather than silently
|
|
918
|
+
* drop. After {@link MAX_RETRY_ATTEMPTS} the record is parked under a
|
|
919
|
+
* `dead:` key for inspection — never silently deleted.
|
|
920
|
+
*
|
|
921
|
+
* The dispatch target is taken from `env.LUNORA_ORIGIN_URL` (NOT from the
|
|
922
|
+
* stored record) so a schedule request can never name where the DO calls
|
|
923
|
+
* back — that would be SSRF. If that env var is missing at fire time (a deploy/binding
|
|
924
|
+
* regression — schedule time already enforced its presence) we return
|
|
925
|
+
* `false` so the record is retried rather than silently dropped.
|
|
926
|
+
*/
|
|
643
927
|
protected dispatch(record: ScheduleRecord): Promise<boolean>;
|
|
644
928
|
/**
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
929
|
+
* Register the hibernation-safe ping/pong keepalive. The runtime answers a
|
|
930
|
+
* {@link WS_KEEPALIVE_PING} text frame with {@link WS_KEEPALIVE_PONG}
|
|
931
|
+
* WITHOUT waking this Durable Object, keeping an idle `/ws` subscription
|
|
932
|
+
* alive across hibernation with no billable wakeup and no dispatch. Without
|
|
933
|
+
* this, a client's heartbeat ping goes unanswered and its watchdog force-
|
|
934
|
+
* closes the socket every ~90s, defeating hibernation (each unanswered ping
|
|
935
|
+
* wakes the DO to reconnect) — mirrors `@lunora/do`'s
|
|
936
|
+
* `ShardDO.armWebSocketKeepalive`. The auto-response is per-instance, so
|
|
937
|
+
* this re-runs on every construction (including a post-hibernation wake).
|
|
938
|
+
* Guarded: the API and the `WebSocketRequestResponsePair` global are absent
|
|
939
|
+
* in the unit harness and on older runtimes, where it degrades to a no-op.
|
|
940
|
+
*/
|
|
941
|
+
private armWebSocketKeepalive;
|
|
942
|
+
/**
|
|
943
|
+
* Drain the due slice with up to {@link MAX_CONCURRENT_DISPATCHES} records in
|
|
944
|
+
* flight at once, so a slow job delays only its own lane instead of every
|
|
945
|
+
* other due job in the app (see the constant for why the drain used to
|
|
946
|
+
* serialise whole jobs, not just their kicks).
|
|
947
|
+
*
|
|
948
|
+
* Lanes pull from the head of the slice, so records still ENTER dispatch in
|
|
949
|
+
* the slice's order — the same `t:<paddedTime>:<id>` order the sequential
|
|
950
|
+
* drain used. What is no longer implied is that they FINISH in that order,
|
|
951
|
+
* which was never a guarantee worth relying on anyway: two jobs due at the
|
|
952
|
+
* same instant already ran in storage-key (id) order rather than arrival
|
|
953
|
+
* order, a saturated pooled job is pushed {@link POOL_BACKPRESSURE_DELAY_MS}
|
|
954
|
+
* into the future ahead of its queue-mates, and a failed job re-enters at the
|
|
955
|
+
* end of a backoff. Nothing in the public surface documents an ordering
|
|
956
|
+
* guarantee; jobs that must be ordered must chain themselves.
|
|
957
|
+
*
|
|
958
|
+
* {@link drainRecordGuarded} swallows every throw, so no lane can reject and
|
|
959
|
+
* abandon its siblings.
|
|
960
|
+
*/
|
|
961
|
+
private drainDue;
|
|
962
|
+
/**
|
|
963
|
+
* Run `critical` with exclusive access to the `pool:<name>` rows.
|
|
964
|
+
*
|
|
965
|
+
* Every pool mutation is a read-modify-write (`loadPool` → mutate →
|
|
966
|
+
* `savePool`), and the two halves are separated by an `await`. That was safe
|
|
967
|
+
* while the drain ran one record at a time — the Durable Object input gate
|
|
968
|
+
* keeps a foreign event (a concurrent `/complete`) out while a storage
|
|
969
|
+
* operation is in flight, and nothing else in this instance could interleave.
|
|
970
|
+
* Concurrent lanes break exactly that assumption: lane A and lane B can both
|
|
971
|
+
* issue their `get` before either `put` lands, both observe `inFlight: 0`,
|
|
972
|
+
* and the second `put` then erases the first lane's reservation — the pool
|
|
973
|
+
* oversubscribes and one holder's id is lost, so its slot is never released.
|
|
974
|
+
*
|
|
975
|
+
* The lock is a promise chain rather than anything cleverer because the
|
|
976
|
+
* critical section is two local storage ops with no I/O in it. It is held
|
|
977
|
+
* across NO outbound fetch: `dispatch()` runs outside it, which is the whole
|
|
978
|
+
* point of draining concurrently.
|
|
979
|
+
*
|
|
980
|
+
* The chain is rebuilt from a swallowed copy so one rejecting section can
|
|
981
|
+
* never wedge every later one.
|
|
982
|
+
*/
|
|
983
|
+
private withPoolLock;
|
|
984
|
+
/**
|
|
985
|
+
* Claim + drain one due record with per-record fault isolation, so a storage
|
|
986
|
+
* throw can never abort the whole alarm pass (which would skip the remaining
|
|
987
|
+
* due records and the `rescheduleAlarm()` that re-arms the clock).
|
|
988
|
+
*
|
|
989
|
+
* The claim is a LEASE, not a deletion. The record's `t:` entry is moved
|
|
990
|
+
* from its due time to `now + DISPATCH_LEASE_MS` before
|
|
991
|
+
* {@link SchedulerDO.dispatch} is called, so this alarm pass (and the next)
|
|
992
|
+
* will not pick it up again, while the record is never left WITHOUT an index
|
|
993
|
+
* entry. That distinction is the whole point: deleting the entry outright
|
|
994
|
+
* made an instance evicted mid-dispatch leave an `id:` header with no index,
|
|
995
|
+
* which {@link SchedulerDO.reindexOrphanedRecords} re-armed and the
|
|
996
|
+
* successor fired AGAIN on sight — concurrently with an attempt that could
|
|
997
|
+
* still be running at the origin. A leased record is not an orphan, so the
|
|
998
|
+
* successor leaves it alone until the lease lapses; see
|
|
999
|
+
* {@link DISPATCH_LEASE_MS} for why that horizon is fifteen minutes and what
|
|
1000
|
+
* it does and does not bound.
|
|
1001
|
+
*
|
|
1002
|
+
* The lease is released as soon as this instance knows the attempt settled —
|
|
1003
|
+
* dispatched, re-armed for retry, backpressured, or dead-lettered — so the
|
|
1004
|
+
* horizon only ever governs the one case nobody is left to report: a lost
|
|
1005
|
+
* instance.
|
|
1006
|
+
*
|
|
1007
|
+
* A throw reaching here always means the job was NOT dispatched:
|
|
1008
|
+
* {@link drainRecord} swallows its own post-dispatch cleanup errors and
|
|
1009
|
+
* returns instead of throwing once a kick succeeds, so every escaping throw
|
|
1010
|
+
* comes from the pre-dispatch or failed-dispatch paths. Nothing is in flight,
|
|
1011
|
+
* so the lease is dropped and the due-time claim re-asserted — keeping the
|
|
1012
|
+
* job re-fireable on the very next alarm (at-least-once) rather than letting
|
|
1013
|
+
* a transient storage blip cost it a whole lease.
|
|
1014
|
+
*
|
|
1015
|
+
* With one exception, checked first: a record that already has a durable
|
|
1016
|
+
* `dead:` row is TERMINAL, and re-claiming it would re-dispatch a job the
|
|
1017
|
+
* dead-letter says is finished. See the comment on that branch.
|
|
1018
|
+
*
|
|
1019
|
+
* `claimKey` is the index key `alarm()` SELECTED this record under, passed
|
|
1020
|
+
* down rather than recomputed. That is load-bearing, not tidiness: a lease
|
|
1021
|
+
* moves the record's index entry and deliberately does NOT rewrite its
|
|
1022
|
+
* `scheduledFor` (that field is the job's real due time, which `/list`,
|
|
1023
|
+
* `/get`, `/dead` and the studio all show, and which `parkDead` preserves).
|
|
1024
|
+
* So from the moment a lease is taken the live key and the key derivable
|
|
1025
|
+
* from the record disagree — and a claim that recomputed it would delete a
|
|
1026
|
+
* key that no longer exists while adding a second one, leaving the record
|
|
1027
|
+
* indexed twice and dispatched twice. That is the same double-run the lease
|
|
1028
|
+
* exists to close, re-entering through the expiry path.
|
|
1029
|
+
*/
|
|
663
1030
|
private drainRecordGuarded;
|
|
664
1031
|
/**
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
1032
|
+
* Process one due (already index-claimed) record within an alarm drain:
|
|
1033
|
+
* apply the workpool concurrency gate, dispatch, and settle the result.
|
|
1034
|
+
* A saturated pool re-arms the job (backpressure, no attempt charged); a
|
|
1035
|
+
* free slot is reserved durably before dispatch and released immediately if
|
|
1036
|
+
* the kick fails (success holds it until the runtime reports completion).
|
|
1037
|
+
* Success clears the `id:`/`retry:` rows; failure routes to
|
|
1038
|
+
* {@link recordRetry}. Pool state is read FRESH from storage per record (see
|
|
1039
|
+
* {@link reservePoolSlot}) and never held across the dispatch() await, so a
|
|
1040
|
+
* concurrent /complete landing mid-dispatch can't be clobbered.
|
|
1041
|
+
* Once a kick succeeds, post-dispatch cleanup (clearing the `id:`/`retry:`
|
|
1042
|
+
* rows) is swallowed rather than allowed to throw, so a successful dispatch
|
|
1043
|
+
* NEVER propagates an error to {@link drainRecordGuarded}: every throw that
|
|
1044
|
+
* escapes comes from the pre-dispatch or failed-dispatch paths, where the job
|
|
1045
|
+
* is still re-fireable and the guard safely re-claims the time index.
|
|
1046
|
+
* @returns `true` only when the record was successfully dispatched (a 2xx
|
|
1047
|
+
* kick); `false` on pool backpressure or a failed dispatch (the job is still
|
|
1048
|
+
* re-fireable — already re-armed here). The value is informational (the guard
|
|
1049
|
+
* branches on throw/no-throw, not on this boolean).
|
|
1050
|
+
*/
|
|
684
1051
|
private drainRecord;
|
|
685
1052
|
/**
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
1053
|
+
* Concurrency gate for a pooled record. Returns `false` (and re-arms the
|
|
1054
|
+
* job via {@link requeuePooled}) when the pool is at `maxConcurrency`;
|
|
1055
|
+
* otherwise reserves a slot durably and returns `true`. Non-pooled records
|
|
1056
|
+
* always return `true` without touching any pool state.
|
|
1057
|
+
*
|
|
1058
|
+
* The pool row is read FRESH from storage on every call — never cached
|
|
1059
|
+
* across the drain — and the read-modify-write runs under
|
|
1060
|
+
* the pool lock (`withPoolLock`). Both halves are load-bearing. Freshness is what
|
|
1061
|
+
* keeps a concurrent `/complete` landing during a dispatch from being
|
|
1062
|
+
* clobbered by a stale in-memory copy (which would leak a slot permanently: a
|
|
1063
|
+
* POOL SLOT has no expiry, unlike the dispatch claim's). The lock is what
|
|
1064
|
+
* keeps two drain lanes from both reading the same pre-reservation row and
|
|
1065
|
+
* both believing a slot was free — without it the pool oversubscribes past
|
|
1066
|
+
* `maxConcurrency` and one holder's id is dropped from `inFlightIds`, so its
|
|
1067
|
+
* slot is never released.
|
|
1068
|
+
*/
|
|
699
1069
|
private reservePoolSlot;
|
|
700
1070
|
/**
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
1071
|
+
* Accept a hibernatable live subscription to the job list. The scheduler has
|
|
1072
|
+
* exactly one subscription shape (the whole list), so there's no per-socket
|
|
1073
|
+
* registry or dependency tracking — every accepted socket gets the full list
|
|
1074
|
+
* on connect and on every change. The worker is responsible for gating the
|
|
1075
|
+
* upgrade behind the admin token before it reaches here.
|
|
1076
|
+
*/
|
|
707
1077
|
private handleWebSocketUpgrade;
|
|
708
1078
|
/**
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
1079
|
+
* Re-list the jobs (bounded — see {@link listPage}) and push them to
|
|
1080
|
+
* every connected subscriber. Called after any change (schedule / cancel /
|
|
1081
|
+
* alarm-fire) so live studios reflect it immediately. A no-op when the
|
|
1082
|
+
* runtime doesn't support hibernated sockets.
|
|
1083
|
+
*/
|
|
713
1084
|
private broadcastChange;
|
|
714
|
-
/**
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
1085
|
+
/**
|
|
1086
|
+
* One bounded page of the rows under `prefix`, in key order, plus the
|
|
1087
|
+
* `cursor` a caller resumes from (the last key of the page) when `truncated`.
|
|
1088
|
+
* Lists `limit + 1` and slices back down so both facts are known without a
|
|
1089
|
+
* second round-trip.
|
|
1090
|
+
*
|
|
1091
|
+
* Shared by `/list` (pending headers) and `/dead` (dead-letter records) so
|
|
1092
|
+
* NEITHER can materialize an unbounded set into one JSON response: nothing
|
|
1093
|
+
* prunes `dead:`, so a workpool with a broken origin parks thousands of rows
|
|
1094
|
+
* and the studio's only view of them — and only way to requeue them — would
|
|
1095
|
+
* fail exactly when it is needed.
|
|
1096
|
+
*/
|
|
1097
|
+
private listPage;
|
|
1098
|
+
/**
|
|
1099
|
+
* Page through every row under `prefix` exactly once with bounded per-page
|
|
1100
|
+
* memory (a `limit`+`startAfter` cursor loop), invoking `visit` for each.
|
|
1101
|
+
* Unlike {@link listPage}, which intentionally truncates for the studio's
|
|
1102
|
+
* live view, `/status` and `/pool` need EXACT counts — this walks the full
|
|
1103
|
+
* set, but never materializes more than one page at a time.
|
|
1104
|
+
*/
|
|
1105
|
+
private forEachPage;
|
|
1106
|
+
/**
|
|
1107
|
+
* HMAC-SHA-256 sign the dispatch body with `env.LUNORA_SCHEDULER_SECRET`,
|
|
1108
|
+
* returning a base64url signature, or `undefined` when no secret is
|
|
1109
|
+
* configured. Mirrors `@lunora/storage`'s signed-URL HMAC pattern (WebCrypto
|
|
1110
|
+
* `crypto.subtle`, available in workerd).
|
|
1111
|
+
*/
|
|
722
1112
|
private signDispatch;
|
|
723
1113
|
/**
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
1114
|
+
* Move a failed record into the retry pipeline with configurable backoff.
|
|
1115
|
+
* The retry budget/backoff comes from the record's {@link RetryPolicy}
|
|
1116
|
+
* (falling back to the DO defaults); on exhaustion the record is parked
|
|
1117
|
+
* under a `dead:` key for manual inspection.
|
|
1118
|
+
*/
|
|
729
1119
|
private recordRetry;
|
|
730
|
-
/**
|
|
1120
|
+
/**
|
|
1121
|
+
* Terminal park into the dead-letter (`dead:`) prefix, with `reason` naming
|
|
1122
|
+
* why in the emitted warning. Shared by the two ways a retry ends for good:
|
|
1123
|
+
* an exhausted attempt budget, and a backoff that ran past the largest
|
|
1124
|
+
* schedulable time (see {@link isIndexableTime}).
|
|
1125
|
+
*/
|
|
1126
|
+
private parkDead;
|
|
1127
|
+
/** Read the durable `pool:<name>` row, defaulting to a fresh `inFlight: 0` pool. */
|
|
731
1128
|
private loadPool;
|
|
732
1129
|
private savePool;
|
|
733
1130
|
/**
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
1131
|
+
* Re-arm a pooled job that couldn't run because its pool was at capacity.
|
|
1132
|
+
* No attempt is charged (this is backpressure, not a failure): the job is
|
|
1133
|
+
* pushed `POOL_BACKPRESSURE_DELAY_MS` into the future so a later alarm
|
|
1134
|
+
* drains it once a slot frees, keeping its `id:` header and retry policy.
|
|
1135
|
+
*/
|
|
739
1136
|
private requeuePooled;
|
|
740
1137
|
/**
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
1138
|
+
* Release a pool slot when the runtime reports an action finished. This is
|
|
1139
|
+
* the durable-semaphore decrement: dispatch() only KICKS the action and
|
|
1140
|
+
* holds the slot; the runtime calls back here (`POST /complete { id }`) once
|
|
1141
|
+
* the action settles, freeing the slot for the next queued job. Idempotent
|
|
1142
|
+
* and safe if the job/pool is already gone.
|
|
1143
|
+
*/
|
|
747
1144
|
private handleComplete;
|
|
748
1145
|
/** `GET /pool?name=` — inspect a pool's slot usage + queued count. */
|
|
749
1146
|
private handlePoolStatus;
|
|
750
1147
|
/**
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
1148
|
+
* `GET /status` — the app-level backlog signal that powers the studio's
|
|
1149
|
+
* SLO view. Enumerates every durable `pool:<name>` row for its `inFlight`/
|
|
1150
|
+
* `maxConcurrency` semaphore, counts the pending (not-yet-dispatched) jobs
|
|
1151
|
+
* routed to each pool with the same single-pass scan {@link handlePoolStatus}
|
|
1152
|
+
* uses, and rolls those up into app-wide `backlog` (sum of `queued`) and
|
|
1153
|
+
* `inFlight` (sum of held slots) totals.
|
|
1154
|
+
*
|
|
1155
|
+
* Pools that have rows but no queued jobs still appear (with `queued: 0`) so
|
|
1156
|
+
* a saturated-but-idle pool stays visible; a pool that only ever existed as
|
|
1157
|
+
* queued jobs without a persisted row is unreachable here (the schedule path
|
|
1158
|
+
* always writes a `pool:<name>` row before the job's header), so a single
|
|
1159
|
+
* scan over `pool:` plus a cursor loop over `id:` is sufficient.
|
|
1160
|
+
*/
|
|
764
1161
|
private handleStatus;
|
|
1162
|
+
/**
|
|
1163
|
+
* Persist (or refresh) a pool's concurrency cap, so the alarm-time gate has
|
|
1164
|
+
* a durable `maxConcurrency` even after the enqueuing client is gone.
|
|
1165
|
+
*/
|
|
1166
|
+
private persistPoolCap;
|
|
1167
|
+
/**
|
|
1168
|
+
* The `409` a caller-supplied id earns when something durable already holds
|
|
1169
|
+
* it, or `undefined` when the id is free.
|
|
1170
|
+
*
|
|
1171
|
+
* A pending header is the obvious half: `put` on `id:<id>` overwrites, but
|
|
1172
|
+
* the `t:` index is keyed by TIME as well as id, so the OLD entry survives.
|
|
1173
|
+
* The drain then dispatches the NEW record at the OLD time and deletes the
|
|
1174
|
+
* entry it should have fired at — the job runs early and never runs again.
|
|
1175
|
+
* Refused rather than made a replace: `RunOptions.id` exists so a deferred
|
|
1176
|
+
* schedule can name its own job, and silently retiming someone else's is the
|
|
1177
|
+
* worse failure.
|
|
1178
|
+
*
|
|
1179
|
+
* The `dead:` row holds the id too, and for a worse reason. A dead record
|
|
1180
|
+
* keeps NO `id:` header, so a pending-only check leaves the id apparently
|
|
1181
|
+
* free — and a later `/dead/retry` writes the revived corpse straight over
|
|
1182
|
+
* the new job's header and adds a SECOND time index under the same id. The
|
|
1183
|
+
* new job is gone and the dead one fires in its place. Recovering a dead job
|
|
1184
|
+
* is an operator action taken minutes or days after the schedule, so nothing
|
|
1185
|
+
* at schedule time would ever have surfaced the collision.
|
|
1186
|
+
*/
|
|
1187
|
+
private idConflict;
|
|
1188
|
+
/**
|
|
1189
|
+
* The id the record is stored under, or the `Response` refusing it.
|
|
1190
|
+
*
|
|
1191
|
+
* A caller id that is not a safe key segment is refused with a `400` rather
|
|
1192
|
+
* than minted over: `RunOptions.id` is not an idempotency key, so swapping an
|
|
1193
|
+
* invalid one for a random id made two calls naming it schedule two jobs
|
|
1194
|
+
* where the second should have answered `409`.
|
|
1195
|
+
*
|
|
1196
|
+
* Only an id the CALLER chose can collide — a minted one is 96 random bits —
|
|
1197
|
+
* so {@link idConflict} costs two `get`s on the deferred path and nothing on
|
|
1198
|
+
* the ordinary one.
|
|
1199
|
+
*/
|
|
1200
|
+
private resolveId;
|
|
765
1201
|
private handleSchedule;
|
|
766
1202
|
private handleCancel;
|
|
1203
|
+
/**
|
|
1204
|
+
* `GET /list[?cursor=]` — one bounded page of pending jobs. `truncated` says
|
|
1205
|
+
* whether more rows follow and `cursor` is what a caller passes back to get
|
|
1206
|
+
* them (`createScheduler.list()` walks every page; the studio shows one).
|
|
1207
|
+
*/
|
|
767
1208
|
private handleList;
|
|
768
1209
|
/**
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
1210
|
+
* `GET /dead` — list the dead-letter records: jobs that exhausted their
|
|
1211
|
+
* retry budget ({@link recordRetry}) and were parked under `dead:<id>`
|
|
1212
|
+
* instead of being silently dropped. These never appear in `/list` (their
|
|
1213
|
+
* `id:` header is deleted on park), so this is the ONLY way the studio can
|
|
1214
|
+
* surface — and recover — a permanently-failed job. Bounded and cursored
|
|
1215
|
+
* like `/list`: nothing prunes `dead:`, so this set grows without limit.
|
|
1216
|
+
*/
|
|
775
1217
|
private handleDeadList;
|
|
776
1218
|
/**
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
1219
|
+
* `POST /dead/retry { id }` — resurrect a dead-letter record: reset its
|
|
1220
|
+
* exhausted attempt count to 0 (a fresh retry budget), re-arm it for
|
|
1221
|
+
* immediate dispatch via the standard time index, and drop the `dead:` row.
|
|
1222
|
+
* The new `id:` header makes it visible to `/list` and the live `/ws`
|
|
1223
|
+
* subscription again. A miss is a no-op (`{ retried: false }`).
|
|
1224
|
+
*/
|
|
783
1225
|
private handleDeadRetry;
|
|
784
1226
|
/**
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
1227
|
+
* `POST /dead/cancel { id }` — permanently drop a dead-letter record the
|
|
1228
|
+
* operator has decided not to recover. Returns `{ removed }` (false when
|
|
1229
|
+
* nothing matched). Idempotent: a repeated purge is a harmless no-op.
|
|
1230
|
+
*/
|
|
789
1231
|
private handleDeadCancel;
|
|
790
1232
|
/**
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
1233
|
+
* Resolve a single pending job by id via a direct `id:<id>` storage read —
|
|
1234
|
+
* O(1), versus scanning the whole `/list` view. Responds `{ record }` on a
|
|
1235
|
+
* hit and `{}` on a miss (an absent `record` field — JSON has no `undefined`
|
|
1236
|
+
* — which the client reads back as `null`).
|
|
1237
|
+
*/
|
|
796
1238
|
private handleGet;
|
|
797
1239
|
private removeRecord;
|
|
798
1240
|
/**
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
1241
|
+
* Arm the alarm for `scheduledFor` only if it is sooner than the currently
|
|
1242
|
+
* set alarm (or none is set). Used on the schedule path: inserting a job
|
|
1243
|
+
* can only ever pull the earliest-pending time *earlier*, never later, so a
|
|
1244
|
+
* full `t:` rescan is unnecessary unless the new job is the new earliest.
|
|
1245
|
+
*/
|
|
804
1246
|
private armAlarmIfEarlier;
|
|
1247
|
+
/**
|
|
1248
|
+
* Re-index every pending job whose time-index entry is gone, and fire it now.
|
|
1249
|
+
*
|
|
1250
|
+
* A record with an `id:` header but no `t:` entry is invisible to every
|
|
1251
|
+
* clock in this class: {@link SchedulerDO.rescheduleAlarm} derives the alarm
|
|
1252
|
+
* from `t:` alone, and `alarm()`'s inline reconciliation only handles the
|
|
1253
|
+
* INVERSE orphan (a `t:` entry whose header is gone). Left alone such a job
|
|
1254
|
+
* sits in `/list` and `/status.backlog` forever — never fires, never reaches
|
|
1255
|
+
* `/dead`.
|
|
1256
|
+
*
|
|
1257
|
+
* **This is no longer how a lost dispatch looks.**
|
|
1258
|
+
* {@link SchedulerDO.drainRecordGuarded} used to claim a record by deleting
|
|
1259
|
+
* its `t:` entry outright, so an instance evicted mid-dispatch minted an
|
|
1260
|
+
* orphan on every claimed record and this method re-fired each of them ON
|
|
1261
|
+
* SIGHT — concurrently with attempts that could still have been running at
|
|
1262
|
+
* the origin. The claim is a lease now (see {@link DISPATCH_LEASE_MS}): a
|
|
1263
|
+
* claimed record keeps a `t:` entry at the lease horizon, so it is not an
|
|
1264
|
+
* orphan, is not recovered here, and is re-fired by the ordinary alarm drain
|
|
1265
|
+
* only once the lease lapses.
|
|
1266
|
+
*
|
|
1267
|
+
* What still reaches this method is the residue of a storage failure — a
|
|
1268
|
+
* claim released with no lease written, or a pre-lease record written by an
|
|
1269
|
+
* older build — where nothing was dispatched and firing immediately is
|
|
1270
|
+
* exactly right.
|
|
1271
|
+
*
|
|
1272
|
+
* The dispatch is deduplicated by the record id, which the receiver spends
|
|
1273
|
+
* as `x-lunora-mutation-id` for a function target and as the workflow
|
|
1274
|
+
* INSTANCE id for a `workflow` target. A mutation's dedup read runs inside
|
|
1275
|
+
* the shard's single-writer gate, so a mutation is exactly-once even under a
|
|
1276
|
+
* genuinely concurrent re-fire; a workflow re-attaches to the running
|
|
1277
|
+
* instance rather than starting a second one. An ACTION is weaker:
|
|
1278
|
+
* `@lunora/do` deliberately does NOT take the gate for a non-mutation —
|
|
1279
|
+
* gating one would let any caller freeze a whole shard for the length of an
|
|
1280
|
+
* action's outbound I/O — and its dedup row is written only after the
|
|
1281
|
+
* handler returns, so two dispatches genuinely overlapping in time can both
|
|
1282
|
+
* miss the cache. The lease exists to keep them from overlapping; an action
|
|
1283
|
+
* that can outlive it must still be idempotent.
|
|
1284
|
+
*
|
|
1285
|
+
* Two bounded walks (all `t:` values, then all `id:` headers) rather than a
|
|
1286
|
+
* per-header `get`, so the cost is one pass over each prefix.
|
|
1287
|
+
*/
|
|
1288
|
+
private reindexOrphanedRecords;
|
|
1289
|
+
/**
|
|
1290
|
+
* The time component of the earliest pending `t:` entry, or `undefined` when
|
|
1291
|
+
* there is no pending entry at all. Reads exactly one row — the index's
|
|
1292
|
+
* lexical order is its numeric order. A present-but-unreadable key yields
|
|
1293
|
+
* `NaN`, which callers must distinguish from "nothing pending": the two
|
|
1294
|
+
* answers mean opposite things for the alarm.
|
|
1295
|
+
*/
|
|
1296
|
+
private earliestPendingTime;
|
|
805
1297
|
private rescheduleAlarm;
|
|
806
1298
|
}
|
|
1299
|
+
/** What the Cloudflare scheduler host needs from the Worker's environment. */
|
|
1300
|
+
interface SchedulerHostOptions {
|
|
1301
|
+
/**
|
|
1302
|
+
* Named scheduler instance — one `SchedulerDO` per name, useful for tenant
|
|
1303
|
+
* isolation. Defaults to `"default"`.
|
|
1304
|
+
*/
|
|
1305
|
+
instanceName?: string;
|
|
1306
|
+
/**
|
|
1307
|
+
* Data-residency jurisdiction for the `SchedulerDO`. Pass the same value as
|
|
1308
|
+
* the worker's own jurisdiction so scheduled state co-resides with app data.
|
|
1309
|
+
*/
|
|
1310
|
+
jurisdiction?: "eu" | "fedramp" | "us";
|
|
1311
|
+
/**
|
|
1312
|
+
* The `SchedulerDO` namespace binding.
|
|
1313
|
+
*
|
|
1314
|
+
* The origin the DO dispatches back to is not configured here — it reads
|
|
1315
|
+
* `env.LUNORA_ORIGIN_URL` off its own binding at fire time, so a wrong value
|
|
1316
|
+
* there (or none) is what makes jobs fire into nothing.
|
|
1317
|
+
*/
|
|
1318
|
+
namespace: Parameters<typeof createScheduler>[0]["namespace"];
|
|
1319
|
+
}
|
|
1320
|
+
/**
|
|
1321
|
+
* Build the Cloudflare {@link SchedulerHost}.
|
|
1322
|
+
*
|
|
1323
|
+
* The returned host has no `cron` member — see the module docstring.
|
|
1324
|
+
*/
|
|
1325
|
+
declare const createSchedulerHost: (options: SchedulerHostOptions) => SchedulerHost;
|
|
807
1326
|
/** Standard cron expression (5- or 6-field) or a supported `@macro`, per `cron-parser`. */
|
|
808
1327
|
declare const isValidCronExpression: (schedule: string) => boolean;
|
|
809
1328
|
/**
|
|
810
|
-
*
|
|
811
|
-
*
|
|
812
|
-
*
|
|
813
|
-
|
|
1329
|
+
* A 6-field (seconds-leading) cron expression is legal generic cron grammar
|
|
1330
|
+
* but not a Cloudflare Cron Trigger — the platform only understands the
|
|
1331
|
+
* 5-field, minute-granularity form and rejects the rest at `wrangler deploy`
|
|
1332
|
+
* with a message naming neither the job nor the file. Warn here instead of
|
|
1333
|
+
* staying silent, without throwing: unlike the ergonomic `.interval()` form,
|
|
1334
|
+
* the raw `.cron()` escape hatch is meant to accept cron grammar this module
|
|
1335
|
+
* doesn't otherwise second-guess.
|
|
1336
|
+
*
|
|
1337
|
+
* Exported (not module-private) because it is the ONE place this advisory is
|
|
1338
|
+
* written: the runtime `cronJobs()` builder reaches it via
|
|
1339
|
+
* {@link assertValidCronExpression}, and `@lunora/codegen`'s static
|
|
1340
|
+
* `discover/crons.ts` calls it directly after its own `isValidCronExpression`
|
|
1341
|
+
* check — so a hand-authored 6-field `.cron()` warns whether it's discovered
|
|
1342
|
+
* from source at build time or registered at runtime, with one shared message.
|
|
1343
|
+
*/
|
|
1344
|
+
declare const warnIfSecondsLeading: (schedule: string, context: string) => void;
|
|
1345
|
+
/**
|
|
1346
|
+
* Assert a raw cron expression is well-formed, throwing the same shaped error
|
|
1347
|
+
* both cron surfaces use. The `context` prefix lets callers name the offending
|
|
1348
|
+
* job (`cron job "send digest"`) vs. the bare trigger. Well-formed but
|
|
1349
|
+
* Cloudflare-incompatible (6-field) expressions pass but log a warning — see
|
|
1350
|
+
* {@link warnIfSecondsLeading}.
|
|
1351
|
+
*/
|
|
814
1352
|
declare const assertValidCronExpression: (schedule: string, context?: string) => void;
|
|
815
|
-
|
|
1353
|
+
/**
|
|
1354
|
+
* Reject a `delayMs` a scheduler cannot act on, before it reaches the
|
|
1355
|
+
* SchedulerDO.
|
|
1356
|
+
*
|
|
1357
|
+
* A `NaN`/`Infinity` delay serializes to `null` through JSON and lands as a
|
|
1358
|
+
* malformed `scheduledFor`; a negative one schedules into the past. Both are the
|
|
1359
|
+
* caller's argument, so the answer has to name the argument — which is why the
|
|
1360
|
+
* code is `INVALID_INPUT` (400) and not `INTERNAL`: `toErrorBody` replaces an
|
|
1361
|
+
* internal-coded message with "Internal error", redacting the one sentence that
|
|
1362
|
+
* says what to fix.
|
|
1363
|
+
*
|
|
1364
|
+
* Exported because four surfaces enforce it — `createScheduler().runAfter`,
|
|
1365
|
+
* `createWorkpool().enqueue`, `@lunora/server`'s deferred-schedule facade (which
|
|
1366
|
+
* must reject BEFORE the transaction commits, not at flush time) and
|
|
1367
|
+
* `@lunora/testing`'s fake scheduler. They used to restate it and threw three
|
|
1368
|
+
* different codes between them, so a test written against the harness caught one
|
|
1369
|
+
* code while production threw another.
|
|
1370
|
+
* @param delayMs the delay to validate
|
|
1371
|
+
* @param surface what to name in the message — the call the delay was passed to (e.g. `"ctx.scheduler.runAfter"`)
|
|
1372
|
+
* @param argument the caller's argument to name in the message; `runAt` converts its absolute `date` to a delay and passes that name through so the answer points at what was actually written
|
|
1373
|
+
*/
|
|
1374
|
+
declare const assertScheduleDelay: (delayMs: number, surface: string, argument?: string) => void;
|
|
1375
|
+
/**
|
|
1376
|
+
* Reject a `runAt` instant a scheduler cannot act on — {@link assertScheduleDelay}'s
|
|
1377
|
+
* bound, restated for the absolute form by converting the instant to the delay it
|
|
1378
|
+
* implies.
|
|
1379
|
+
*
|
|
1380
|
+
* `runAfter` has refused a `NaN`/`Infinity` argument since the guard was written;
|
|
1381
|
+
* `runAt` took the same value through a different door and let it reach the DO,
|
|
1382
|
+
* where it serializes to `null` through JSON and lands as a `scheduledFor` no
|
|
1383
|
+
* alarm can ever fire. `new Date("2026-13-01")`, `runAt(row.dueAt + delay)` on a
|
|
1384
|
+
* row whose `dueAt` is absent — both arrive here as a number that is not one.
|
|
1385
|
+
*
|
|
1386
|
+
* An instant already in the PAST is not refused. It is an overdue job
|
|
1387
|
+
* (`runAt(row.dueAt)` on a row that came due while the request was in flight),
|
|
1388
|
+
* and `runAfter` itself reaches `runAt` a fraction of a millisecond after
|
|
1389
|
+
* capturing its own clock reading — so a strict sign check would fail the
|
|
1390
|
+
* documented `runAfter(0, …)` call at random. The delay is therefore clamped at
|
|
1391
|
+
* zero while it is still a finite number, which leaves the half that matters:
|
|
1392
|
+
* a value that is not a number at all.
|
|
1393
|
+
* @param timestampMs the absolute instant (epoch ms) the caller passed
|
|
1394
|
+
* @param nowMs the clock to measure it against — the wall clock in production, the harness's virtual clock in a test
|
|
1395
|
+
* @param surface what to name in the message — the call the instant was passed to (e.g. `"ctx.scheduler.runAt"`)
|
|
1396
|
+
*/
|
|
1397
|
+
declare const assertScheduleInstant: (timestampMs: number, nowMs: number, surface: string) => void;
|
|
1398
|
+
export { type ArgsOf, CRON_SCHEDULE_KINDS, type CronJob, type CronJobsBuilder, type CronScheduleKind, type CronTarget, type CronTriggerOptions, type CronTriggerSnippet, type DailySchedule, type DurableObjectIdLike, type DurableObjectJurisdiction, type DurableObjectNamespaceLike, type DurableObjectStubLike, type EnqueueOptions, type FunctionKind, type FunctionReference, type HourlySchedule, type HttpDispatcherOptions, type IntervalSchedule, type LunoraSchedulerOptions, MAX_RETRY_ATTEMPTS, type MessageBatchLike, type MonthlySchedule, type QueueConsumerOptions, type QueueDispatch, type QueueEnqueueOptions, type QueueJob, type QueueLike, type QueueMessageLike, type QueueSendOptionsLike, type QueueSendRequestLike, type QueueWorkpool, type QueueWorkpoolOptions, RETRY_BASE_DELAY_MS, type RetryPolicy, type RunOptions, type ScheduleRecord, type Scheduler, SchedulerDO, type SchedulerDOState, type SchedulerEnv, type SchedulerHostOptions, type SchedulerPoolStatus, type SchedulerStatus, type WeeklySchedule, type WorkflowReference, type Workpool, type WorkpoolOptions, assertScheduleDelay, assertScheduleInstant, assertValidCronExpression, compileCronSchedule, createCronTrigger, createQueueConsumer, createQueueWorkpool, createScheduler, createSchedulerHost, createWorkpool, cronJobs, httpDispatcher, isValidCronExpression, isWorkflowReference, resolveScheduleId, warnIfSecondsLeading };
|