@lunora/scheduler 1.0.0-alpha.160 → 1.0.0-alpha.162
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/dist/index.d.mts +228 -7
- package/dist/index.d.ts +228 -7
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{CRON_SCHEDULE_KINDS-v0tEYoxJ.mjs → CRON_SCHEDULE_KINDS-AS5GtmnL.mjs} +1 -1
- package/dist/packem_shared/MAX_RETRY_ATTEMPTS-B0v-qzSa.mjs +1 -0
- package/dist/packem_shared/{assertScheduleDelay-DiyM8a3y.mjs → assertScheduleDelay-CH6-R3I0.mjs} +1 -1
- package/dist/packem_shared/{assertScheduleInstant-DlXlSbXn.mjs → assertScheduleInstant-BRQWdkcF.mjs} +1 -1
- package/dist/packem_shared/{createScheduler-BhkNvLvi.mjs → createScheduler-gJy27c_Q.mjs} +1 -1
- package/dist/packem_shared/createSchedulerHost-Dicjj_iQ.mjs +1 -0
- package/dist/packem_shared/{createWorkpool-C9Qf2k6N.mjs → createWorkpool-CdedzPRj.mjs} +1 -1
- package/dist/packem_shared/do-client-DnJqrsmj.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/MAX_RETRY_ATTEMPTS-oLI_d_xX.mjs +0 -1
- package/dist/packem_shared/createSchedulerHost-CyQLO3fi.mjs +0 -1
- package/dist/packem_shared/do-client-XQayNStI.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -174,6 +174,8 @@ interface ScheduleRecord {
|
|
|
174
174
|
*/
|
|
175
175
|
attempts?: number;
|
|
176
176
|
enqueuedAt: number;
|
|
177
|
+
/** Why the job was dead-lettered. Set only on a parked (`/dead`) record. */
|
|
178
|
+
error?: string;
|
|
177
179
|
/**
|
|
178
180
|
* The `ns:fn` path of the function to dispatch on fire. Absent when the job
|
|
179
181
|
* targets a durable workflow/agent instead — see {@link ScheduleRecord.workflow}.
|
|
@@ -208,6 +210,65 @@ interface ScheduleRecord {
|
|
|
208
210
|
*/
|
|
209
211
|
workflow?: string;
|
|
210
212
|
}
|
|
213
|
+
/**
|
|
214
|
+
* Where a job is in its life, as {@link Scheduler.get} reports it.
|
|
215
|
+
*
|
|
216
|
+
* - `pending` — waiting for its fire time, a pool slot, or a retry backoff.
|
|
217
|
+
* - `running` — its dispatch is in flight right now.
|
|
218
|
+
* - `succeeded` — the dispatch answered 2xx. For a function target the receiver
|
|
219
|
+
* answers only after the function returned, so this is the function's success;
|
|
220
|
+
* for a workflow/agent target it means the instance was STARTED, not finished —
|
|
221
|
+
* follow the instance (same id) for its outcome.
|
|
222
|
+
* - `failed` — the retry budget ran out and the job was dead-lettered
|
|
223
|
+
* ({@link Scheduler.dead}); `deadRetry` returns it to `pending`.
|
|
224
|
+
* - `canceled` — removed by {@link Scheduler.cancel}.
|
|
225
|
+
*/
|
|
226
|
+
type ScheduledJobState = "canceled" | "failed" | "pending" | "running" | "succeeded";
|
|
227
|
+
/**
|
|
228
|
+
* A job as {@link Scheduler.get} sees it: the record plus its lifecycle state.
|
|
229
|
+
* Terminal states (`succeeded`, `canceled`, and a purged `failed`) are kept for
|
|
230
|
+
* a bounded retention window after `completedAt`, then answer `null`.
|
|
231
|
+
*/
|
|
232
|
+
interface ScheduledJobView extends ScheduleRecord {
|
|
233
|
+
/** When the job reached its terminal state (epoch ms). Absent while `pending`/`running`. */
|
|
234
|
+
completedAt?: number;
|
|
235
|
+
state: ScheduledJobState;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* How one cron fire ended. `skipped` is a tick that did not run: the previous
|
|
239
|
+
* run of the same cron was still in flight (`reason: "in-flight"`), or the
|
|
240
|
+
* deployment was paused (`reason: "paused"`).
|
|
241
|
+
*/
|
|
242
|
+
type CronRunStatus = "failed" | "skipped" | "succeeded";
|
|
243
|
+
/** One recorded fire of a code-defined cron job (`cronJobs()`), as the SchedulerDO's `/cron/runs` reports it. */
|
|
244
|
+
interface CronRunRecord {
|
|
245
|
+
/** Run time in ms; `0` for a skipped tick. */
|
|
246
|
+
durationMs: number;
|
|
247
|
+
/** When the run finished, or when the tick was skipped (epoch ms). */
|
|
248
|
+
endedAt: number;
|
|
249
|
+
/** The thrown message of a `failed` run. */
|
|
250
|
+
error?: string;
|
|
251
|
+
/** The `cronJobs()` name. */
|
|
252
|
+
name: string;
|
|
253
|
+
/** Why a tick was `skipped`: the previous run still held the lease, or the deployment was paused. */
|
|
254
|
+
reason?: "in-flight" | "paused";
|
|
255
|
+
runId: string;
|
|
256
|
+
/** Ticks of the same cron skipped while this run held the lease; on a `skipped` row, the consecutive ticks it stands for. */
|
|
257
|
+
skipped: number;
|
|
258
|
+
/** When the run began, or the first tick of a `skipped` row's streak (epoch ms). */
|
|
259
|
+
startedAt: number;
|
|
260
|
+
status: CronRunStatus;
|
|
261
|
+
}
|
|
262
|
+
/** A cron run that holds its lease right now. */
|
|
263
|
+
interface CronRunInFlight {
|
|
264
|
+
name: string;
|
|
265
|
+
/** When the run last said it was still alive; the lease lapses fifteen minutes after this, or after `startedAt` when it never did. */
|
|
266
|
+
renewedAt?: number;
|
|
267
|
+
runId: string;
|
|
268
|
+
/** Ticks skipped so far because this run was still going. */
|
|
269
|
+
skipped: number;
|
|
270
|
+
startedAt: number;
|
|
271
|
+
}
|
|
211
272
|
interface Scheduler {
|
|
212
273
|
cancel: (id: string) => Promise<{
|
|
213
274
|
cancelled: boolean;
|
|
@@ -225,8 +286,12 @@ interface Scheduler {
|
|
|
225
286
|
* recover is a no-op rather than an error.
|
|
226
287
|
*/
|
|
227
288
|
deadRetry: (id: string) => Promise<boolean>;
|
|
228
|
-
/**
|
|
229
|
-
|
|
289
|
+
/**
|
|
290
|
+
* Resolve a job by id with its lifecycle {@link ScheduledJobView.state} —
|
|
291
|
+
* pending, running, or (for a bounded retention window) its terminal outcome.
|
|
292
|
+
* `null` when the id was never scheduled or its terminal record has expired.
|
|
293
|
+
*/
|
|
294
|
+
get: (id: string) => Promise<ScheduledJobView | null>;
|
|
230
295
|
/** All pending scheduled jobs (the DO's `/list` view). */
|
|
231
296
|
list: () => Promise<ScheduleRecord[]>;
|
|
232
297
|
/**
|
|
@@ -295,6 +360,13 @@ interface LunoraSchedulerOptions {
|
|
|
295
360
|
* caller-supplied dispatch target would be an SSRF vector.
|
|
296
361
|
*/
|
|
297
362
|
namespace: DurableObjectNamespaceLike;
|
|
363
|
+
/**
|
|
364
|
+
* The instance that holds the deployment's pause flag and the registry of
|
|
365
|
+
* named instances: the worker's `schedulerInstanceName`. Default `default`.
|
|
366
|
+
* A named instance registers there the first time it is addressed, so a
|
|
367
|
+
* pause reaches it and an instance created during a pause starts paused.
|
|
368
|
+
*/
|
|
369
|
+
primaryInstanceName?: string;
|
|
298
370
|
}
|
|
299
371
|
/** Per-enqueue options for a {@link Workpool}. Extends {@link RunOptions} minus the implicit `pool` (the pool sets that). */
|
|
300
372
|
interface EnqueueOptions {
|
|
@@ -814,6 +886,13 @@ declare const MAX_RETRY_ATTEMPTS = 5;
|
|
|
814
886
|
* {@link MAX_RETRY_ATTEMPTS} for the same reason.
|
|
815
887
|
*/
|
|
816
888
|
declare const RETRY_BASE_DELAY_MS = 3e4;
|
|
889
|
+
/**
|
|
890
|
+
* How long a terminal (`succeeded` / `canceled` / purged `failed`) record keeps
|
|
891
|
+
* answering `/get` and `/history` after it settled. Expiry is enforced on read,
|
|
892
|
+
* so the window holds even when no alarm runs to sweep; the sweep only reclaims
|
|
893
|
+
* the storage.
|
|
894
|
+
*/
|
|
895
|
+
declare const TERMINAL_RETENTION_MS = 6048e5;
|
|
817
896
|
/**
|
|
818
897
|
* One pool's live backlog, as surfaced by `GET /status`. `inFlight`/
|
|
819
898
|
* `maxConcurrency` mirror the durable {@link PoolState} semaphore; `queued`
|
|
@@ -842,6 +921,14 @@ interface SchedulerStatus {
|
|
|
842
921
|
/** Per-pool backlog breakdown, one entry per `pool:<name>` record. */
|
|
843
922
|
pools: SchedulerPoolStatus[];
|
|
844
923
|
}
|
|
924
|
+
/** Whether the deployment is paused, as `GET /pause` answers it. */
|
|
925
|
+
interface DeploymentPauseState {
|
|
926
|
+
paused: boolean;
|
|
927
|
+
/** When the pause began (epoch ms). */
|
|
928
|
+
pausedAt?: number;
|
|
929
|
+
/** The operator's note, shown wherever the pause is. */
|
|
930
|
+
reason?: string;
|
|
931
|
+
}
|
|
845
932
|
/**
|
|
846
933
|
* Durable Object that stores pending scheduled invocations sorted by their
|
|
847
934
|
* `scheduledFor` time and fires them via HTTP on alarm. Storage layout:
|
|
@@ -853,6 +940,13 @@ interface SchedulerStatus {
|
|
|
853
940
|
*/
|
|
854
941
|
declare class SchedulerDO {
|
|
855
942
|
private static indexKey;
|
|
943
|
+
private static terminalIndexKey;
|
|
944
|
+
/** A cron run row's key: newest end first under its job's prefix. */
|
|
945
|
+
private static cronRunKey;
|
|
946
|
+
/** Whether `lease` still holds: its newest sign of life is within {@link DISPATCH_LEASE_MS}. */
|
|
947
|
+
private static leaseIsLive;
|
|
948
|
+
/** A cron job name off an untrusted body, or `undefined` when absent or implausible. */
|
|
949
|
+
private static cronName;
|
|
856
950
|
/** The record's `pq:` row key, or `undefined` for a job outside any pool. */
|
|
857
951
|
private static poolQueueKey;
|
|
858
952
|
/**
|
|
@@ -1305,12 +1399,133 @@ declare class SchedulerDO {
|
|
|
1305
1399
|
*/
|
|
1306
1400
|
private handleDeadCancel;
|
|
1307
1401
|
/**
|
|
1308
|
-
*
|
|
1309
|
-
*
|
|
1310
|
-
*
|
|
1311
|
-
*
|
|
1402
|
+
* `GET /get?id=` — one job with its lifecycle state, in O(1) reads. Responds
|
|
1403
|
+
* `{ record }` on a hit and `{}` on a miss (JSON has no `undefined`; the
|
|
1404
|
+
* client reads it back as `null`).
|
|
1405
|
+
*
|
|
1406
|
+
* The terminal row is read FIRST: a successful dispatch writes it before
|
|
1407
|
+
* clearing the header, so a header that outlived a swallowed cleanup still
|
|
1408
|
+
* reads as `succeeded`. A reused id cannot hit a stale terminal row, because
|
|
1409
|
+
* `/schedule` deletes it. `running` is this instance's own lease set — the
|
|
1410
|
+
* only instance that can be dispatching — so a lease orphaned by an eviction
|
|
1411
|
+
* reads as `pending`, which is what it is until the lease lapses.
|
|
1312
1412
|
*/
|
|
1313
1413
|
private handleGet;
|
|
1414
|
+
/**
|
|
1415
|
+
* `GET /history[?cursor=]` — one bounded page of finished jobs, newest first,
|
|
1416
|
+
* within the retention window. Paged off the `dt:` index, then each page's
|
|
1417
|
+
* rows are read; an index entry whose row was replaced (id reuse) or has
|
|
1418
|
+
* expired is skipped rather than shown.
|
|
1419
|
+
*/
|
|
1420
|
+
private handleHistory;
|
|
1421
|
+
/**
|
|
1422
|
+
* The unexpired terminal row for `id`, or `undefined`. With `indexKey`, only
|
|
1423
|
+
* the row that index entry was written for — a newer outcome under the same
|
|
1424
|
+
* id has its own entry.
|
|
1425
|
+
*/
|
|
1426
|
+
private readTerminal;
|
|
1427
|
+
/** A parked job as an outcome row, when it was parked with its failure time. */
|
|
1428
|
+
private readParked;
|
|
1429
|
+
/**
|
|
1430
|
+
* Rewrite the `canceled` outcome `/cancel` wrote for `record` to `succeeded`,
|
|
1431
|
+
* because the dispatch it raced went through. Only while that row is still
|
|
1432
|
+
* this record's and no new job has reused the id; the reads and the write
|
|
1433
|
+
* await no I/O in between, so the input gate keeps `/schedule` out.
|
|
1434
|
+
*/
|
|
1435
|
+
private correctCanceledToSucceeded;
|
|
1436
|
+
/** Record how `record` ended: its `done:` row and `dt:` index entry, in one put. */
|
|
1437
|
+
private writeTerminal;
|
|
1438
|
+
/**
|
|
1439
|
+
* Reclaim terminal rows past {@link TERMINAL_RETENTION_MS}, in up to
|
|
1440
|
+
* {@link TERMINAL_SWEEP_PASSES} batches — enough to outpace one full drain's
|
|
1441
|
+
* worth of new outcomes, so a steady load cannot outgrow the sweep. Runs on
|
|
1442
|
+
* every alarm and after a cancel or purge, the paths that write outcomes.
|
|
1443
|
+
*/
|
|
1444
|
+
private sweepTerminal;
|
|
1445
|
+
/**
|
|
1446
|
+
* Reclaim one batch and answer how many index entries it held. The index is
|
|
1447
|
+
* newest-first, so every expired entry sorts after the horizon key. A `done:`
|
|
1448
|
+
* row is deleted only when THIS entry is its index — an id reused since owns
|
|
1449
|
+
* a newer row with its own entry.
|
|
1450
|
+
*/
|
|
1451
|
+
private sweepTerminalBatch;
|
|
1452
|
+
private pauseState;
|
|
1453
|
+
private isPaused;
|
|
1454
|
+
/**
|
|
1455
|
+
* `POST /instances/register { name }` — record a named scheduler instance, on
|
|
1456
|
+
* the instance that holds the pause flag, and answer the pause state it was
|
|
1457
|
+
* recorded under. The write and the read sit in one handler, so a pause
|
|
1458
|
+
* either lands first (and the new instance is told) or after (and its
|
|
1459
|
+
* fan-out lists the new instance). Idempotent.
|
|
1460
|
+
*/
|
|
1461
|
+
private handleRegisterInstance;
|
|
1462
|
+
/** `GET /instances` — every registered instance name, for the pause fan-out. */
|
|
1463
|
+
private handleListInstances;
|
|
1464
|
+
/**
|
|
1465
|
+
* `POST /pause { paused, reason? }` — pause or resume the deployment.
|
|
1466
|
+
* Pausing stops the alarm (see `alarm()`); resuming re-derives it from the
|
|
1467
|
+
* time index, so every job held while paused fires on the next alarm, late
|
|
1468
|
+
* but with its attempt budget intact. Idempotent both ways; re-pausing keeps
|
|
1469
|
+
* the original `pausedAt`.
|
|
1470
|
+
*/
|
|
1471
|
+
private handleSetPause;
|
|
1472
|
+
/**
|
|
1473
|
+
* `POST /cron/begin { name }` — take the in-flight lease for one cron job, or
|
|
1474
|
+
* answer `{ acquired: false }` and record the tick as skipped when a run of
|
|
1475
|
+
* the same job still holds it.
|
|
1476
|
+
*
|
|
1477
|
+
* The lease lives here rather than in the worker because Cloudflare delivers
|
|
1478
|
+
* cron triggers to whichever isolate it likes: module state cannot see a run
|
|
1479
|
+
* in another isolate, and this Durable Object is the one place every fire of
|
|
1480
|
+
* an app passes through. The check and the write are atomic for the same
|
|
1481
|
+
* reason every read-modify-write in this class is: the input gate keeps any
|
|
1482
|
+
* other request out while a storage operation is pending, and nothing between
|
|
1483
|
+
* them awaits I/O.
|
|
1484
|
+
*
|
|
1485
|
+
* A lease with no sign of life (its start, or its last `/cron/renew`) within
|
|
1486
|
+
* {@link DISPATCH_LEASE_MS} is treated as lost: the run was torn down or its
|
|
1487
|
+
* worker died. The lost run is recorded as failed rather than vanishing.
|
|
1488
|
+
*/
|
|
1489
|
+
private handleCronBegin;
|
|
1490
|
+
/**
|
|
1491
|
+
* `POST /cron/renew { name, runId }` — a running cron job says it is still
|
|
1492
|
+
* alive, which restarts the {@link DISPATCH_LEASE_MS} window. The ceiling
|
|
1493
|
+
* assumes a `scheduled()` invocation is torn down at fifteen minutes; a run
|
|
1494
|
+
* with no such bound (a manual run from Studio, a host that does not enforce
|
|
1495
|
+
* it) renews instead of being declared lost while it works.
|
|
1496
|
+
*
|
|
1497
|
+
* Only the run that holds the lease, and only while it is still live, can
|
|
1498
|
+
* extend it. A lapsed lease may already have been recorded as lost or taken
|
|
1499
|
+
* over, and reviving it would give two runs the lease.
|
|
1500
|
+
*/
|
|
1501
|
+
private handleCronRenew;
|
|
1502
|
+
/**
|
|
1503
|
+
* `POST /cron/end { name, runId, status, error? }` — release the lease and
|
|
1504
|
+
* record the run. A `runId` that no longer holds the lease (its lease expired
|
|
1505
|
+
* and was already recorded as lost) is ignored, so a late report cannot
|
|
1506
|
+
* record the same run twice or free a successor's lease.
|
|
1507
|
+
*/
|
|
1508
|
+
private handleCronEnd;
|
|
1509
|
+
/**
|
|
1510
|
+
* `GET /cron/runs` — every cron job's in-flight lease and recorded runs,
|
|
1511
|
+
* newest end first per job. Bounded by {@link CRON_HISTORY_LIMIT} rows per job
|
|
1512
|
+
* and by the app's own `cronJobs()` declarations.
|
|
1513
|
+
*/
|
|
1514
|
+
private handleCronRuns;
|
|
1515
|
+
/** Record a run whose lease lapsed without a `/cron/end`. */
|
|
1516
|
+
private recordLostCronRun;
|
|
1517
|
+
/**
|
|
1518
|
+
* Record a skipped tick, folded into the newest row when that row is a skip
|
|
1519
|
+
* for the same reason. Otherwise a long run or a long pause would write one
|
|
1520
|
+
* row per tick and push every real run out of the {@link CRON_HISTORY_LIMIT}.
|
|
1521
|
+
*/
|
|
1522
|
+
private recordCronSkip;
|
|
1523
|
+
/**
|
|
1524
|
+
* Write one run row and drop that job's rows past {@link CRON_HISTORY_LIMIT}.
|
|
1525
|
+
* Keyed newest END first, so a run is the newest row the moment it is
|
|
1526
|
+
* recorded, however many ticks were skipped while it held the lease.
|
|
1527
|
+
*/
|
|
1528
|
+
private recordCronRun;
|
|
1314
1529
|
private removeRecord;
|
|
1315
1530
|
/**
|
|
1316
1531
|
* Arm the alarm for `scheduledFor` only if it is sooner than the currently
|
|
@@ -1377,6 +1592,12 @@ declare class SchedulerDO {
|
|
|
1377
1592
|
private reindexOrphanedRecords;
|
|
1378
1593
|
/** One run of {@link reindexOrphanedRecords}. */
|
|
1379
1594
|
private recoverStore;
|
|
1595
|
+
/**
|
|
1596
|
+
* Write back the outcome a failed write lost, then drop the marker and any
|
|
1597
|
+
* header the job left behind. Skipped when a newer outcome already exists
|
|
1598
|
+
* (the id was reused and finished again); the marker goes either way.
|
|
1599
|
+
*/
|
|
1600
|
+
private restoreOutcome;
|
|
1380
1601
|
/** The full orphan walk — see {@link reindexOrphanedRecords}. */
|
|
1381
1602
|
private reindexWalk;
|
|
1382
1603
|
/**
|
|
@@ -1461,4 +1682,4 @@ declare const assertScheduleDelay: (delayMs: number, surface: string, argument?:
|
|
|
1461
1682
|
* @param surface what to name in the message — the call the instant was passed to (e.g. `"ctx.scheduler.runAt"`)
|
|
1462
1683
|
*/
|
|
1463
1684
|
declare const assertScheduleInstant: (timestampMs: number, nowMs: number, surface: string) => void;
|
|
1464
|
-
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, compileCronSchedule, createCronTrigger, createQueueConsumer, createQueueWorkpool, createScheduler, createSchedulerHost, createWorkpool, cronJobs, httpDispatcher, isWorkflowReference, resolveScheduleId };
|
|
1685
|
+
export { type ArgsOf, CRON_SCHEDULE_KINDS, type CronJob, type CronJobsBuilder, type CronRunInFlight, type CronRunRecord, type CronRunStatus, type CronScheduleKind, type CronTarget, type CronTriggerOptions, type CronTriggerSnippet, type DailySchedule, type DeploymentPauseState, 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 ScheduledJobState, type ScheduledJobView, type Scheduler, SchedulerDO, type SchedulerDOState, type SchedulerEnv, type SchedulerHostOptions, type SchedulerPoolStatus, type SchedulerStatus, TERMINAL_RETENTION_MS, type WeeklySchedule, type WorkflowReference, type Workpool, type WorkpoolOptions, assertScheduleDelay, assertScheduleInstant, compileCronSchedule, createCronTrigger, createQueueConsumer, createQueueWorkpool, createScheduler, createSchedulerHost, createWorkpool, cronJobs, httpDispatcher, isWorkflowReference, resolveScheduleId };
|
package/dist/index.d.ts
CHANGED
|
@@ -174,6 +174,8 @@ interface ScheduleRecord {
|
|
|
174
174
|
*/
|
|
175
175
|
attempts?: number;
|
|
176
176
|
enqueuedAt: number;
|
|
177
|
+
/** Why the job was dead-lettered. Set only on a parked (`/dead`) record. */
|
|
178
|
+
error?: string;
|
|
177
179
|
/**
|
|
178
180
|
* The `ns:fn` path of the function to dispatch on fire. Absent when the job
|
|
179
181
|
* targets a durable workflow/agent instead — see {@link ScheduleRecord.workflow}.
|
|
@@ -208,6 +210,65 @@ interface ScheduleRecord {
|
|
|
208
210
|
*/
|
|
209
211
|
workflow?: string;
|
|
210
212
|
}
|
|
213
|
+
/**
|
|
214
|
+
* Where a job is in its life, as {@link Scheduler.get} reports it.
|
|
215
|
+
*
|
|
216
|
+
* - `pending` — waiting for its fire time, a pool slot, or a retry backoff.
|
|
217
|
+
* - `running` — its dispatch is in flight right now.
|
|
218
|
+
* - `succeeded` — the dispatch answered 2xx. For a function target the receiver
|
|
219
|
+
* answers only after the function returned, so this is the function's success;
|
|
220
|
+
* for a workflow/agent target it means the instance was STARTED, not finished —
|
|
221
|
+
* follow the instance (same id) for its outcome.
|
|
222
|
+
* - `failed` — the retry budget ran out and the job was dead-lettered
|
|
223
|
+
* ({@link Scheduler.dead}); `deadRetry` returns it to `pending`.
|
|
224
|
+
* - `canceled` — removed by {@link Scheduler.cancel}.
|
|
225
|
+
*/
|
|
226
|
+
type ScheduledJobState = "canceled" | "failed" | "pending" | "running" | "succeeded";
|
|
227
|
+
/**
|
|
228
|
+
* A job as {@link Scheduler.get} sees it: the record plus its lifecycle state.
|
|
229
|
+
* Terminal states (`succeeded`, `canceled`, and a purged `failed`) are kept for
|
|
230
|
+
* a bounded retention window after `completedAt`, then answer `null`.
|
|
231
|
+
*/
|
|
232
|
+
interface ScheduledJobView extends ScheduleRecord {
|
|
233
|
+
/** When the job reached its terminal state (epoch ms). Absent while `pending`/`running`. */
|
|
234
|
+
completedAt?: number;
|
|
235
|
+
state: ScheduledJobState;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* How one cron fire ended. `skipped` is a tick that did not run: the previous
|
|
239
|
+
* run of the same cron was still in flight (`reason: "in-flight"`), or the
|
|
240
|
+
* deployment was paused (`reason: "paused"`).
|
|
241
|
+
*/
|
|
242
|
+
type CronRunStatus = "failed" | "skipped" | "succeeded";
|
|
243
|
+
/** One recorded fire of a code-defined cron job (`cronJobs()`), as the SchedulerDO's `/cron/runs` reports it. */
|
|
244
|
+
interface CronRunRecord {
|
|
245
|
+
/** Run time in ms; `0` for a skipped tick. */
|
|
246
|
+
durationMs: number;
|
|
247
|
+
/** When the run finished, or when the tick was skipped (epoch ms). */
|
|
248
|
+
endedAt: number;
|
|
249
|
+
/** The thrown message of a `failed` run. */
|
|
250
|
+
error?: string;
|
|
251
|
+
/** The `cronJobs()` name. */
|
|
252
|
+
name: string;
|
|
253
|
+
/** Why a tick was `skipped`: the previous run still held the lease, or the deployment was paused. */
|
|
254
|
+
reason?: "in-flight" | "paused";
|
|
255
|
+
runId: string;
|
|
256
|
+
/** Ticks of the same cron skipped while this run held the lease; on a `skipped` row, the consecutive ticks it stands for. */
|
|
257
|
+
skipped: number;
|
|
258
|
+
/** When the run began, or the first tick of a `skipped` row's streak (epoch ms). */
|
|
259
|
+
startedAt: number;
|
|
260
|
+
status: CronRunStatus;
|
|
261
|
+
}
|
|
262
|
+
/** A cron run that holds its lease right now. */
|
|
263
|
+
interface CronRunInFlight {
|
|
264
|
+
name: string;
|
|
265
|
+
/** When the run last said it was still alive; the lease lapses fifteen minutes after this, or after `startedAt` when it never did. */
|
|
266
|
+
renewedAt?: number;
|
|
267
|
+
runId: string;
|
|
268
|
+
/** Ticks skipped so far because this run was still going. */
|
|
269
|
+
skipped: number;
|
|
270
|
+
startedAt: number;
|
|
271
|
+
}
|
|
211
272
|
interface Scheduler {
|
|
212
273
|
cancel: (id: string) => Promise<{
|
|
213
274
|
cancelled: boolean;
|
|
@@ -225,8 +286,12 @@ interface Scheduler {
|
|
|
225
286
|
* recover is a no-op rather than an error.
|
|
226
287
|
*/
|
|
227
288
|
deadRetry: (id: string) => Promise<boolean>;
|
|
228
|
-
/**
|
|
229
|
-
|
|
289
|
+
/**
|
|
290
|
+
* Resolve a job by id with its lifecycle {@link ScheduledJobView.state} —
|
|
291
|
+
* pending, running, or (for a bounded retention window) its terminal outcome.
|
|
292
|
+
* `null` when the id was never scheduled or its terminal record has expired.
|
|
293
|
+
*/
|
|
294
|
+
get: (id: string) => Promise<ScheduledJobView | null>;
|
|
230
295
|
/** All pending scheduled jobs (the DO's `/list` view). */
|
|
231
296
|
list: () => Promise<ScheduleRecord[]>;
|
|
232
297
|
/**
|
|
@@ -295,6 +360,13 @@ interface LunoraSchedulerOptions {
|
|
|
295
360
|
* caller-supplied dispatch target would be an SSRF vector.
|
|
296
361
|
*/
|
|
297
362
|
namespace: DurableObjectNamespaceLike;
|
|
363
|
+
/**
|
|
364
|
+
* The instance that holds the deployment's pause flag and the registry of
|
|
365
|
+
* named instances: the worker's `schedulerInstanceName`. Default `default`.
|
|
366
|
+
* A named instance registers there the first time it is addressed, so a
|
|
367
|
+
* pause reaches it and an instance created during a pause starts paused.
|
|
368
|
+
*/
|
|
369
|
+
primaryInstanceName?: string;
|
|
298
370
|
}
|
|
299
371
|
/** Per-enqueue options for a {@link Workpool}. Extends {@link RunOptions} minus the implicit `pool` (the pool sets that). */
|
|
300
372
|
interface EnqueueOptions {
|
|
@@ -814,6 +886,13 @@ declare const MAX_RETRY_ATTEMPTS = 5;
|
|
|
814
886
|
* {@link MAX_RETRY_ATTEMPTS} for the same reason.
|
|
815
887
|
*/
|
|
816
888
|
declare const RETRY_BASE_DELAY_MS = 3e4;
|
|
889
|
+
/**
|
|
890
|
+
* How long a terminal (`succeeded` / `canceled` / purged `failed`) record keeps
|
|
891
|
+
* answering `/get` and `/history` after it settled. Expiry is enforced on read,
|
|
892
|
+
* so the window holds even when no alarm runs to sweep; the sweep only reclaims
|
|
893
|
+
* the storage.
|
|
894
|
+
*/
|
|
895
|
+
declare const TERMINAL_RETENTION_MS = 6048e5;
|
|
817
896
|
/**
|
|
818
897
|
* One pool's live backlog, as surfaced by `GET /status`. `inFlight`/
|
|
819
898
|
* `maxConcurrency` mirror the durable {@link PoolState} semaphore; `queued`
|
|
@@ -842,6 +921,14 @@ interface SchedulerStatus {
|
|
|
842
921
|
/** Per-pool backlog breakdown, one entry per `pool:<name>` record. */
|
|
843
922
|
pools: SchedulerPoolStatus[];
|
|
844
923
|
}
|
|
924
|
+
/** Whether the deployment is paused, as `GET /pause` answers it. */
|
|
925
|
+
interface DeploymentPauseState {
|
|
926
|
+
paused: boolean;
|
|
927
|
+
/** When the pause began (epoch ms). */
|
|
928
|
+
pausedAt?: number;
|
|
929
|
+
/** The operator's note, shown wherever the pause is. */
|
|
930
|
+
reason?: string;
|
|
931
|
+
}
|
|
845
932
|
/**
|
|
846
933
|
* Durable Object that stores pending scheduled invocations sorted by their
|
|
847
934
|
* `scheduledFor` time and fires them via HTTP on alarm. Storage layout:
|
|
@@ -853,6 +940,13 @@ interface SchedulerStatus {
|
|
|
853
940
|
*/
|
|
854
941
|
declare class SchedulerDO {
|
|
855
942
|
private static indexKey;
|
|
943
|
+
private static terminalIndexKey;
|
|
944
|
+
/** A cron run row's key: newest end first under its job's prefix. */
|
|
945
|
+
private static cronRunKey;
|
|
946
|
+
/** Whether `lease` still holds: its newest sign of life is within {@link DISPATCH_LEASE_MS}. */
|
|
947
|
+
private static leaseIsLive;
|
|
948
|
+
/** A cron job name off an untrusted body, or `undefined` when absent or implausible. */
|
|
949
|
+
private static cronName;
|
|
856
950
|
/** The record's `pq:` row key, or `undefined` for a job outside any pool. */
|
|
857
951
|
private static poolQueueKey;
|
|
858
952
|
/**
|
|
@@ -1305,12 +1399,133 @@ declare class SchedulerDO {
|
|
|
1305
1399
|
*/
|
|
1306
1400
|
private handleDeadCancel;
|
|
1307
1401
|
/**
|
|
1308
|
-
*
|
|
1309
|
-
*
|
|
1310
|
-
*
|
|
1311
|
-
*
|
|
1402
|
+
* `GET /get?id=` — one job with its lifecycle state, in O(1) reads. Responds
|
|
1403
|
+
* `{ record }` on a hit and `{}` on a miss (JSON has no `undefined`; the
|
|
1404
|
+
* client reads it back as `null`).
|
|
1405
|
+
*
|
|
1406
|
+
* The terminal row is read FIRST: a successful dispatch writes it before
|
|
1407
|
+
* clearing the header, so a header that outlived a swallowed cleanup still
|
|
1408
|
+
* reads as `succeeded`. A reused id cannot hit a stale terminal row, because
|
|
1409
|
+
* `/schedule` deletes it. `running` is this instance's own lease set — the
|
|
1410
|
+
* only instance that can be dispatching — so a lease orphaned by an eviction
|
|
1411
|
+
* reads as `pending`, which is what it is until the lease lapses.
|
|
1312
1412
|
*/
|
|
1313
1413
|
private handleGet;
|
|
1414
|
+
/**
|
|
1415
|
+
* `GET /history[?cursor=]` — one bounded page of finished jobs, newest first,
|
|
1416
|
+
* within the retention window. Paged off the `dt:` index, then each page's
|
|
1417
|
+
* rows are read; an index entry whose row was replaced (id reuse) or has
|
|
1418
|
+
* expired is skipped rather than shown.
|
|
1419
|
+
*/
|
|
1420
|
+
private handleHistory;
|
|
1421
|
+
/**
|
|
1422
|
+
* The unexpired terminal row for `id`, or `undefined`. With `indexKey`, only
|
|
1423
|
+
* the row that index entry was written for — a newer outcome under the same
|
|
1424
|
+
* id has its own entry.
|
|
1425
|
+
*/
|
|
1426
|
+
private readTerminal;
|
|
1427
|
+
/** A parked job as an outcome row, when it was parked with its failure time. */
|
|
1428
|
+
private readParked;
|
|
1429
|
+
/**
|
|
1430
|
+
* Rewrite the `canceled` outcome `/cancel` wrote for `record` to `succeeded`,
|
|
1431
|
+
* because the dispatch it raced went through. Only while that row is still
|
|
1432
|
+
* this record's and no new job has reused the id; the reads and the write
|
|
1433
|
+
* await no I/O in between, so the input gate keeps `/schedule` out.
|
|
1434
|
+
*/
|
|
1435
|
+
private correctCanceledToSucceeded;
|
|
1436
|
+
/** Record how `record` ended: its `done:` row and `dt:` index entry, in one put. */
|
|
1437
|
+
private writeTerminal;
|
|
1438
|
+
/**
|
|
1439
|
+
* Reclaim terminal rows past {@link TERMINAL_RETENTION_MS}, in up to
|
|
1440
|
+
* {@link TERMINAL_SWEEP_PASSES} batches — enough to outpace one full drain's
|
|
1441
|
+
* worth of new outcomes, so a steady load cannot outgrow the sweep. Runs on
|
|
1442
|
+
* every alarm and after a cancel or purge, the paths that write outcomes.
|
|
1443
|
+
*/
|
|
1444
|
+
private sweepTerminal;
|
|
1445
|
+
/**
|
|
1446
|
+
* Reclaim one batch and answer how many index entries it held. The index is
|
|
1447
|
+
* newest-first, so every expired entry sorts after the horizon key. A `done:`
|
|
1448
|
+
* row is deleted only when THIS entry is its index — an id reused since owns
|
|
1449
|
+
* a newer row with its own entry.
|
|
1450
|
+
*/
|
|
1451
|
+
private sweepTerminalBatch;
|
|
1452
|
+
private pauseState;
|
|
1453
|
+
private isPaused;
|
|
1454
|
+
/**
|
|
1455
|
+
* `POST /instances/register { name }` — record a named scheduler instance, on
|
|
1456
|
+
* the instance that holds the pause flag, and answer the pause state it was
|
|
1457
|
+
* recorded under. The write and the read sit in one handler, so a pause
|
|
1458
|
+
* either lands first (and the new instance is told) or after (and its
|
|
1459
|
+
* fan-out lists the new instance). Idempotent.
|
|
1460
|
+
*/
|
|
1461
|
+
private handleRegisterInstance;
|
|
1462
|
+
/** `GET /instances` — every registered instance name, for the pause fan-out. */
|
|
1463
|
+
private handleListInstances;
|
|
1464
|
+
/**
|
|
1465
|
+
* `POST /pause { paused, reason? }` — pause or resume the deployment.
|
|
1466
|
+
* Pausing stops the alarm (see `alarm()`); resuming re-derives it from the
|
|
1467
|
+
* time index, so every job held while paused fires on the next alarm, late
|
|
1468
|
+
* but with its attempt budget intact. Idempotent both ways; re-pausing keeps
|
|
1469
|
+
* the original `pausedAt`.
|
|
1470
|
+
*/
|
|
1471
|
+
private handleSetPause;
|
|
1472
|
+
/**
|
|
1473
|
+
* `POST /cron/begin { name }` — take the in-flight lease for one cron job, or
|
|
1474
|
+
* answer `{ acquired: false }` and record the tick as skipped when a run of
|
|
1475
|
+
* the same job still holds it.
|
|
1476
|
+
*
|
|
1477
|
+
* The lease lives here rather than in the worker because Cloudflare delivers
|
|
1478
|
+
* cron triggers to whichever isolate it likes: module state cannot see a run
|
|
1479
|
+
* in another isolate, and this Durable Object is the one place every fire of
|
|
1480
|
+
* an app passes through. The check and the write are atomic for the same
|
|
1481
|
+
* reason every read-modify-write in this class is: the input gate keeps any
|
|
1482
|
+
* other request out while a storage operation is pending, and nothing between
|
|
1483
|
+
* them awaits I/O.
|
|
1484
|
+
*
|
|
1485
|
+
* A lease with no sign of life (its start, or its last `/cron/renew`) within
|
|
1486
|
+
* {@link DISPATCH_LEASE_MS} is treated as lost: the run was torn down or its
|
|
1487
|
+
* worker died. The lost run is recorded as failed rather than vanishing.
|
|
1488
|
+
*/
|
|
1489
|
+
private handleCronBegin;
|
|
1490
|
+
/**
|
|
1491
|
+
* `POST /cron/renew { name, runId }` — a running cron job says it is still
|
|
1492
|
+
* alive, which restarts the {@link DISPATCH_LEASE_MS} window. The ceiling
|
|
1493
|
+
* assumes a `scheduled()` invocation is torn down at fifteen minutes; a run
|
|
1494
|
+
* with no such bound (a manual run from Studio, a host that does not enforce
|
|
1495
|
+
* it) renews instead of being declared lost while it works.
|
|
1496
|
+
*
|
|
1497
|
+
* Only the run that holds the lease, and only while it is still live, can
|
|
1498
|
+
* extend it. A lapsed lease may already have been recorded as lost or taken
|
|
1499
|
+
* over, and reviving it would give two runs the lease.
|
|
1500
|
+
*/
|
|
1501
|
+
private handleCronRenew;
|
|
1502
|
+
/**
|
|
1503
|
+
* `POST /cron/end { name, runId, status, error? }` — release the lease and
|
|
1504
|
+
* record the run. A `runId` that no longer holds the lease (its lease expired
|
|
1505
|
+
* and was already recorded as lost) is ignored, so a late report cannot
|
|
1506
|
+
* record the same run twice or free a successor's lease.
|
|
1507
|
+
*/
|
|
1508
|
+
private handleCronEnd;
|
|
1509
|
+
/**
|
|
1510
|
+
* `GET /cron/runs` — every cron job's in-flight lease and recorded runs,
|
|
1511
|
+
* newest end first per job. Bounded by {@link CRON_HISTORY_LIMIT} rows per job
|
|
1512
|
+
* and by the app's own `cronJobs()` declarations.
|
|
1513
|
+
*/
|
|
1514
|
+
private handleCronRuns;
|
|
1515
|
+
/** Record a run whose lease lapsed without a `/cron/end`. */
|
|
1516
|
+
private recordLostCronRun;
|
|
1517
|
+
/**
|
|
1518
|
+
* Record a skipped tick, folded into the newest row when that row is a skip
|
|
1519
|
+
* for the same reason. Otherwise a long run or a long pause would write one
|
|
1520
|
+
* row per tick and push every real run out of the {@link CRON_HISTORY_LIMIT}.
|
|
1521
|
+
*/
|
|
1522
|
+
private recordCronSkip;
|
|
1523
|
+
/**
|
|
1524
|
+
* Write one run row and drop that job's rows past {@link CRON_HISTORY_LIMIT}.
|
|
1525
|
+
* Keyed newest END first, so a run is the newest row the moment it is
|
|
1526
|
+
* recorded, however many ticks were skipped while it held the lease.
|
|
1527
|
+
*/
|
|
1528
|
+
private recordCronRun;
|
|
1314
1529
|
private removeRecord;
|
|
1315
1530
|
/**
|
|
1316
1531
|
* Arm the alarm for `scheduledFor` only if it is sooner than the currently
|
|
@@ -1377,6 +1592,12 @@ declare class SchedulerDO {
|
|
|
1377
1592
|
private reindexOrphanedRecords;
|
|
1378
1593
|
/** One run of {@link reindexOrphanedRecords}. */
|
|
1379
1594
|
private recoverStore;
|
|
1595
|
+
/**
|
|
1596
|
+
* Write back the outcome a failed write lost, then drop the marker and any
|
|
1597
|
+
* header the job left behind. Skipped when a newer outcome already exists
|
|
1598
|
+
* (the id was reused and finished again); the marker goes either way.
|
|
1599
|
+
*/
|
|
1600
|
+
private restoreOutcome;
|
|
1380
1601
|
/** The full orphan walk — see {@link reindexOrphanedRecords}. */
|
|
1381
1602
|
private reindexWalk;
|
|
1382
1603
|
/**
|
|
@@ -1461,4 +1682,4 @@ declare const assertScheduleDelay: (delayMs: number, surface: string, argument?:
|
|
|
1461
1682
|
* @param surface what to name in the message — the call the instant was passed to (e.g. `"ctx.scheduler.runAt"`)
|
|
1462
1683
|
*/
|
|
1463
1684
|
declare const assertScheduleInstant: (timestampMs: number, nowMs: number, surface: string) => void;
|
|
1464
|
-
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, compileCronSchedule, createCronTrigger, createQueueConsumer, createQueueWorkpool, createScheduler, createSchedulerHost, createWorkpool, cronJobs, httpDispatcher, isWorkflowReference, resolveScheduleId };
|
|
1685
|
+
export { type ArgsOf, CRON_SCHEDULE_KINDS, type CronJob, type CronJobsBuilder, type CronRunInFlight, type CronRunRecord, type CronRunStatus, type CronScheduleKind, type CronTarget, type CronTriggerOptions, type CronTriggerSnippet, type DailySchedule, type DeploymentPauseState, 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 ScheduledJobState, type ScheduledJobView, type Scheduler, SchedulerDO, type SchedulerDOState, type SchedulerEnv, type SchedulerHostOptions, type SchedulerPoolStatus, type SchedulerStatus, TERMINAL_RETENTION_MS, type WeeklySchedule, type WorkflowReference, type Workpool, type WorkpoolOptions, assertScheduleDelay, assertScheduleInstant, compileCronSchedule, createCronTrigger, createQueueConsumer, createQueueWorkpool, createScheduler, createSchedulerHost, createWorkpool, cronJobs, httpDispatcher, isWorkflowReference, resolveScheduleId };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{default as o}from"./packem_shared/createScheduler-
|
|
1
|
+
import{default as o}from"./packem_shared/createScheduler-gJy27c_Q.mjs";import{default as a}from"./packem_shared/createWorkpool-CdedzPRj.mjs";import{createCronTrigger as f}from"./packem_shared/createCronTrigger-cg32QNgj.mjs";import{CRON_SCHEDULE_KINDS as p,compileCronSchedule as c,cronJobs as d}from"./packem_shared/CRON_SCHEDULE_KINDS-AS5GtmnL.mjs";import{createQueueConsumer as m,createQueueWorkpool as n,httpDispatcher as x}from"./packem_shared/createQueueConsumer-CYwmsmvq.mjs";import{r as E}from"./packem_shared/resolve-schedule-id-B2ghxgFm.mjs";import{MAX_RETRY_ATTEMPTS as h,RETRY_BASE_DELAY_MS as T,SchedulerDO as _,TERMINAL_RETENTION_MS as R}from"./packem_shared/MAX_RETRY_ATTEMPTS-B0v-qzSa.mjs";import{createSchedulerHost as D}from"./packem_shared/createSchedulerHost-Dicjj_iQ.mjs";import{isWorkflowReference as A}from"./packem_shared/isWorkflowReference-CT3tdefh.mjs";import{assertValidCronExpression as N,isValidCronExpression as L,warnIfSecondsLeading as g}from"./packem_shared/assertValidCronExpression-fiNfNiWf.mjs";import{default as O}from"./packem_shared/assertScheduleDelay-CH6-R3I0.mjs";import{default as Y}from"./packem_shared/assertScheduleInstant-BRQWdkcF.mjs";export{p as CRON_SCHEDULE_KINDS,h as MAX_RETRY_ATTEMPTS,T as RETRY_BASE_DELAY_MS,_ as SchedulerDO,R as TERMINAL_RETENTION_MS,O as assertScheduleDelay,Y as assertScheduleInstant,N as assertValidCronExpression,c as compileCronSchedule,f as createCronTrigger,m as createQueueConsumer,n as createQueueWorkpool,o as createScheduler,D as createSchedulerHost,a as createWorkpool,d as cronJobs,x as httpDispatcher,L as isValidCronExpression,A as isWorkflowReference,E as resolveScheduleId,g as warnIfSecondsLeading};
|
package/dist/packem_shared/{CRON_SCHEDULE_KINDS-v0tEYoxJ.mjs → CRON_SCHEDULE_KINDS-AS5GtmnL.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as l}from"@lunora/errors";import{isWorkflowReference as
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{isWorkflowReference as f}from"./isWorkflowReference-CT3tdefh.mjs";import{assertValidCronExpression as m}from"./assertValidCronExpression-fiNfNiWf.mjs";const w={friday:6,monday:2,saturday:7,sunday:1,thursday:5,tuesday:3,wednesday:4},T=24,h=" For a daily or longer schedule use crons.daily(name, { hourUTC, minuteUTC }, …), crons.weekly(name, { dayOfWeek, hourUTC, minuteUTC }, …) or crons.monthly(name, { day, hourUTC, minuteUTC }, …).",c=(e,o,r,i)=>{if(!Number.isInteger(e)||e<r||e>i)throw new l("INTERNAL",`@lunora/scheduler: cronJobs ${o} must be an integer in [${r.toFixed(0)}, ${i.toFixed(0)}], got ${String(e)}`);return e.toFixed(0)},y=(e,o,r)=>{const i=c(e,o,1,r-1);if(r%e!==0)throw new l("INTERNAL",`@lunora/scheduler: ${o} must evenly divide ${r.toFixed(0)} for a fixed "every ${e.toFixed(0)}" interval — cron "*/${e.toFixed(0)}" means "at values divisible by ${e.toFixed(0)}", which wraps unevenly; pick a divisor of ${r.toFixed(0)}`);return i},$=(e,o)=>{const r=["seconds","minutes","hours"].filter(s=>e[s]!==void 0);if(r.length!==1){const s=Object.entries(e).filter(([,t])=>t!==void 0).map(([t])=>t);throw new l("INTERNAL",`@lunora/scheduler: interval schedule must specify exactly one of { seconds, minutes, hours }, got { ${s.join(", ")} }.${h}`)}const i=r[0],n=e[i];if(i==="hours"&&n>=T)throw new l("INTERNAL",`@lunora/scheduler: interval.hours is capped at 23, got ${String(n)} — an interval repeats WITHIN a day rather than spanning one.${h}`);if(i==="seconds")throw new l("INTERNAL",`@lunora/scheduler: cron job${o?` "${o}"`:""} uses interval.seconds (${String(n)}) — Cloudflare Cron Triggers have a one-minute floor and cannot run sub-minute schedules; \`wrangler deploy\` would reject the resulting 6-field cron expression. Use ctx.scheduler.runAfter/runAt (optionally via a workpool for bounded concurrency) for sub-minute recurrence, or crons.interval(name, { minutes: 1 }, …) for the fastest cron-native cadence.`);return i==="minutes"?`*/${y(n,"interval.minutes",60)} * * * *`:`0 */${y(n,"interval.hours",24)} * * *`},p=e=>`${c(e.minuteUTC,"hourly.minuteUTC",0,59)} * * * *`,C=e=>{const o=c(e.minuteUTC,"daily.minuteUTC",0,59),r=c(e.hourUTC,"daily.hourUTC",0,23);return`${o} ${r} * * *`},N=e=>{const o=w[e.dayOfWeek];if(o===void 0)throw new l("INTERNAL",`@lunora/scheduler: weekly schedule has invalid dayOfWeek "${e.dayOfWeek}"`);const r=c(e.minuteUTC,"weekly.minuteUTC",0,59),i=c(e.hourUTC,"weekly.hourUTC",0,23);return`${r} ${i} * * ${o.toFixed(0)}`},U=e=>{const o=c(e.day,"monthly.day",1,31),r=c(e.minuteUTC,"monthly.minuteUTC",0,59),i=c(e.hourUTC,"monthly.hourUTC",0,23);return`${r} ${i} ${o} * *`},v=new Set(["daily","hourly","interval","monthly","weekly"]),a=(e,o,r)=>{switch(e){case"daily":return C(o);case"hourly":return p(o);case"interval":return $(o,r);case"monthly":return U(o);case"weekly":return N(o);default:throw new l("INTERNAL",`@lunora/scheduler: unknown cron schedule kind "${String(e)}"`)}},k=()=>{const e=[],o=new Set,r=(n,s,t,u)=>{if(typeof n!="string"||n.trim()==="")throw new l("INTERNAL","@lunora/scheduler: cron job name must be a non-empty string");if(n.length>256)throw new l("INTERNAL",`@lunora/scheduler: cron job name "${n.slice(0,40)}…" is longer than 256 characters`);if(o.has(n))throw new l("INTERNAL",`@lunora/scheduler: duplicate cron job name "${n}" — names must be unique within one cronJobs()`);let d;if(f(t))d={workflow:typeof t.name=="string"?t.name:""};else if(t&&typeof t.__lunoraRef=="string")d={functionPath:t.__lunoraRef};else throw new l("INTERNAL",`@lunora/scheduler: cron job "${n}" requires a function reference (e.g. internal.email.digest) or a workflow reference`);m(s,`cron expression for job "${n}"`),o.add(n),e.push({args:u??{},cron:s,name:n,...d})},i={cron(n,s,t,u){return r(n,s,t,u),i},daily(n,s,t,u){return r(n,a("daily",s),t,u),i},hourly(n,s,t,u){return r(n,a("hourly",s),t,u),i},interval(n,s,t,u){return r(n,a("interval",s,n),t,u),i},jobs:()=>[...e],monthly(n,s,t,u){return r(n,a("monthly",s),t,u),i},weekly(n,s,t,u){return r(n,a("weekly",s),t,u),i}};return i};export{v as CRON_SCHEDULE_KINDS,a as compileCronSchedule,k as cronJobs};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as q,r as b}from"./resolve-schedule-id-B2ghxgFm.mjs";const X="DISPATCH_IN_PROGRESS",V="x-lunora-dispatch-declined",z=(c,t)=>{if(c.size<t)return;const e=c.keys().next().value;e!==void 0&&c.delete(e)},B=(c,t,e,s)=>{const a=c.get(t);if(a!==void 0)return a;z(c,s);const n=e().catch(r=>{throw c.get(t)===n&&c.delete(t),r});return c.set(t,n),n},Y=new TextEncoder,J=64,Q=new Map,Z=async c=>B(Q,c,async()=>crypto.subtle.importKey("raw",Y.encode(c),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),J),D=new TextEncoder,O=Array.from({length:32},(c,t)=>t);new RegExp(`[${O.map(c=>String.fromCodePoint(c)).join("")}]`,"u");const tt=async(c,t)=>{const e=await Z(c),s=await crypto.subtle.sign("HMAC",e,D.encode(t));return q(new Uint8Array(s))},M=(c,t=200,e)=>{const s=new Headers({"content-type":"application/json"});for(const[a,n]of Object.entries({}))s.set(a,n);return Response.json(c,{headers:s,status:t})},et="lunora-ping",st="lunora-pong",g="id:",I="retry:",f="dead:",$="pool:",A="pq:",p="done:",C="dt:",P="repair:",U="inst:",N="cl:",R="cr:",L=50,y=128,K=c=>typeof c=="string"&&c.length>0?c:void 0,m=c=>Array.from({length:c.length},(t,e)=>c.charCodeAt(e).toString(16).padStart(4,"0")).join(""),at=c=>{let t="";for(let e=0;e<c.length;e+=4)t+=String.fromCharCode(Number.parseInt(c.slice(e,e+4),16));return t},S=c=>`${A}${m(c)}:`,T="meta:clean",F="meta:paused",v=100,it=10,nt=5,G=3e4,rt=1e3,ot=6,H=9e5,W=6048e5,_=64,dt=4,j=999999999999999,ct=15,x=c=>String(c).padStart(ct,"0"),k=c=>Number.isInteger(c)&&c>0&&c<=j;class i{static indexKey(t,e){return`t:${x(t)}:${e}`}static terminalIndexKey(t,e){return`${C}${x(j-t)}:${e}`}static cronRunKey(t){return`${R}${m(t.name)}:${x(j-t.endedAt)}:${t.runId}`}static leaseIsLive(t,e){return(t.renewedAt??t.startedAt)>e-H}static cronName(t){const e=t?.name;return typeof e=="string"&&e.length>0&&e.length<=256?e:void 0}static poolQueueKey(t){return t.pool===void 0?void 0:`${S(t.pool)}${t.id}`}static pendingRows(t){const e=i.poolQueueKey(t);return{[`${g}${t.id}`]:t,...e===void 0?{}:{[e]:t.id}}}static pendingKeys(t){return Object.keys(i.pendingRows(t))}static json(t,e=200){return M(t,e)}static error(t,e,s){return i.json({error:{code:e,message:s}},t)}static resolveRetry(t){const e=t.retry,s=typeof e?.maxAttempts=="number"&&Number.isInteger(e.maxAttempts)&&e.maxAttempts>0?e.maxAttempts:nt,a=typeof e?.baseMs=="number"&&Number.isFinite(e.baseMs)&&e.baseMs>=0?e.baseMs:G,n=e?.backoff==="linear"?"linear":"exponential",r=typeof e?.maxMs=="number"&&Number.isFinite(e.maxMs)&&e.maxMs>=0?e.maxMs:void 0;return{backoff:n,baseMs:a,maxAttempts:s,maxMs:r}}static normalizeConcurrency(t,e){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:e}static normalizeRetry(t){if(typeof t!="object"||t===null)return;const e=t,s={};return typeof e.maxAttempts=="number"&&Number.isInteger(e.maxAttempts)&&e.maxAttempts>0&&(s.maxAttempts=e.maxAttempts),typeof e.baseMs=="number"&&Number.isFinite(e.baseMs)&&e.baseMs>=0&&(s.baseMs=e.baseMs),(e.backoff==="exponential"||e.backoff==="linear")&&(s.backoff=e.backoff),typeof e.maxMs=="number"&&Number.isFinite(e.maxMs)&&e.maxMs>=0&&(s.maxMs=e.maxMs),Object.keys(s).length===0?void 0:s}static releaseSlot(t,e){if(t.inFlightIds===void 0)return{...t,inFlight:Math.max(0,t.inFlight-1)};const s=t.inFlightIds.filter(a=>a!==e);return{...t,inFlight:s.length,inFlightIds:s}}static releaseFirstSlot(t){if(t.inFlightIds===void 0)return{...t,inFlight:Math.max(0,t.inFlight-1)};const e=t.inFlightIds.slice(0,Math.max(0,t.inFlightIds.length-1));return{...t,inFlight:e.length,inFlightIds:e}}static resolveScheduleTarget(t){const e=typeof t?.functionPath=="string"&&t.functionPath.length>0?t.functionPath:void 0,s=typeof t?.workflow=="string"&&t.workflow.length>0?t.workflow:void 0;if(!(e===void 0&&s===void 0))return{functionPath:e,workflow:s}}state;env;recovery;recovered=!1;dirty=!1;poolLock=Promise.resolve();activeLeases=new Map;cancelledLeases=new Set;constructor(t,e){this.state=t,this.env=e,this.armWebSocketKeepalive()}async fetch(t){await this.reindexOrphanedRecords();const e=new URL(t.url);if(e.pathname==="/ws"&&t.headers.get("Upgrade")==="websocket")return this.handleWebSocketUpgrade();switch(`${t.method} ${e.pathname}`){case"GET /cron/runs":return this.handleCronRuns();case"GET /dead":return this.handleDeadList(e);case"GET /get":return this.handleGet(e);case"GET /history":return this.handleHistory(e);case"GET /instances":return this.handleListInstances();case"GET /list":return this.handleList(e);case"GET /pause":return i.json(await this.pauseState());case"GET /pool":return this.handlePoolStatus(e);case"GET /status":return this.handleStatus();case"POST /cancel":return this.handleCancel(t);case"POST /complete":return this.handleComplete(t);case"POST /cron/begin":return this.handleCronBegin(t);case"POST /cron/end":return this.handleCronEnd(t);case"POST /cron/renew":return this.handleCronRenew(t);case"POST /dead/cancel":return this.handleDeadCancel(t);case"POST /dead/retry":return this.handleDeadRetry(t);case"POST /instances/register":return this.handleRegisterInstance(t);case"POST /pause":return this.handleSetPause(t);case"POST /schedule":return this.handleSchedule(t)}return M({error:{code:"NOT_FOUND"}},404)}async alarm(){if(await this.reindexOrphanedRecords(),(await this.pauseState()).paused){await this.state.storage.deleteAlarm();return}const e=Date.now(),s=[],a=new Set,n=await this.state.storage.list({end:`t:${x(e)}:~`,limit:100,prefix:"t:"}),r=[];for(const[l,h]of n.entries()){const w=Number.parseInt(l.slice(2,l.indexOf(":",2)),10);Number.isFinite(w)&&w<=e&&r.push({indexKey:l,recordId:h})}const d=await Promise.all(r.map(l=>this.state.storage.get(`${g}${l.recordId}`)));for(const[l,{indexKey:h,recordId:w}]of r.entries()){const u=d[l];u&&a.has(w)?await this.state.storage.delete(h):u?(a.add(w),s.push({claimKey:h,record:u})):await this.state.storage.delete(h)}let o=!1;try{s.length>0&&(await this.state.storage.delete(T),o=!0),await this.drainDue(s)}finally{await this.rescheduleAlarm(),o&&this.recovered&&!this.dirty&&await this.state.storage.put(T,!0)}await this.sweepTerminal().catch(()=>{}),s.length>0&&await this.broadcastChange()}async dispatch(t){const e=typeof this.env.LUNORA_ORIGIN_URL=="string"&&this.env.LUNORA_ORIGIN_URL.length>0?this.env.LUNORA_ORIGIN_URL:void 0;if(!e)return!1;const s=JSON.stringify({args:t.args,functionPath:t.functionPath,id:t.id,instanceName:t.instanceName,pool:t.pool,scheduledFor:t.scheduledFor,shardKey:t.shardKey,workflow:t.workflow});try{const a={"content-type":"application/json"},n=await this.signDispatch(s);n!==void 0?a["x-lunora-scheduler-signature"]=n:typeof this.env.LUNORA_ADMIN_TOKEN=="string"&&this.env.LUNORA_ADMIN_TOKEN.length>0&&(a.authorization=`Bearer ${this.env.LUNORA_ADMIN_TOKEN}`);const r=await fetch(`${e}/_lunora/scheduler/dispatch`,{body:s,headers:a,method:"POST"});return r.status===409&&r.headers.get(V)==="1"&&await r.json().then(o=>o?.error?.code===X,()=>!1)?"in-progress":r.ok}catch{return!1}}armWebSocketKeepalive(){const t=this.state.setWebSocketAutoResponse;typeof t!="function"||typeof WebSocketRequestResponsePair>"u"||t.call(this.state,new WebSocketRequestResponsePair(et,st))}async drainDue(t){const e=[...t],s=[],a=Math.min(ot,e.length);for(let n=0;n<a;n+=1)s.push((async()=>{for(let r=e.shift();r!==void 0;r=e.shift())await this.drainRecordGuarded(r.record,r.claimKey)})());await Promise.all(s)}async withPoolLock(t){const e=this.poolLock.then(t,t);return this.poolLock=e.then(()=>{},()=>{}),e}async drainRecordGuarded(t,e){const s=i.indexKey(Date.now()+H,t.id);try{const a=await this.state.storage.get(`${g}${t.id}`);if(a===void 0){await this.state.storage.delete(e);return}if(JSON.stringify(a)!==JSON.stringify(t)||await this.isPaused())return;await this.state.storage.delete(e),await this.state.storage.put(s,t.id),this.activeLeases.set(t.id,s),await this.drainRecord(t)}catch{try{if(this.cancelledLeases.has(t.id)){await this.state.storage.delete(s);return}if(await this.state.storage.get(`${f}${t.id}`)!==void 0){await this.state.storage.delete(s),await this.state.storage.delete([`${I}${t.id}`,...i.pendingKeys(t)]);return}await this.state.storage.put(e,t.id),await this.state.storage.delete(s)}catch{this.dirty=!0}return}finally{this.activeLeases.delete(t.id),this.cancelledLeases.delete(t.id)}try{await this.state.storage.delete(s)}catch{}}async drainRecord(t){if(!await this.reservePoolSlot(t))return!1;const s=await this.dispatch(t),a=s===!0,n=t.pool;if(!a&&n!==void 0&&await this.withPoolLock(async()=>{const r=await this.loadPool(n);await this.savePool(n,i.releaseSlot(r,t.id))}),this.cancelledLeases.has(t.id))return a&&await this.correctCanceledToSucceeded(t).catch(()=>{}),a;if(a){const r=Date.now();try{await this.writeTerminal(t,"succeeded",r)}catch{this.dirty=!0,await this.state.storage.put(`${P}${t.id}`,{...t,completedAt:r,state:"succeeded"}).catch(()=>{})}try{await this.state.storage.delete([...i.pendingKeys(t),`${I}${t.id}`])}catch{this.dirty=!0}return!0}return await this.recordRetry(t,s==="in-progress"),!1}async reservePoolSlot(t){const e=t.pool;if(e===void 0)return!0;const s=await this.withPoolLock(async()=>{const a=await this.loadPool(e);if(a.inFlight>=a.maxConcurrency)return!1;const n=a.inFlightIds??[];return n.includes(t.id)||n.push(t.id),a.inFlightIds=n,a.inFlight=n.length,await this.savePool(e,a),!0});return s||await this.requeuePooled(t),s}async handleWebSocketUpgrade(){if(this.state.acceptWebSocket===void 0)return i.error(501,"WS_UNSUPPORTED","WebSocket subscriptions are not supported in this runtime");const t=new WebSocketPair,e=t[0],s=t[1];this.state.acceptWebSocket(s);const a=await this.listPage(g,v);return s.send(JSON.stringify({records:a.records,truncated:a.truncated,type:"jobs"})),new Response(null,{status:101,webSocket:e})}async broadcastChange(){const t=this.state.getWebSockets?.();if(t===void 0||t.length===0)return;const{records:e,truncated:s}=await this.listPage(g,v),a=JSON.stringify({records:e,truncated:s,type:"jobs"});for(const n of t)try{n.send(a)}catch{}}async listPage(t,e,s){const a=await this.state.storage.list({limit:e+1,prefix:t,...s===void 0?{}:{startAfter:s}}),n=[...a.keys()],r=[...a.values()],d=r.length>e;return d?{cursor:n[e-1],records:r.slice(0,e),truncated:d}:{records:r,truncated:d}}async forEachPage(t,e,s=v){let a;for(;;){const n=await this.state.storage.list(a===void 0?{limit:s,prefix:t}:{limit:s,prefix:t,startAfter:a});if(n.size===0)break;for(const[d,o]of n.entries())e(o,d);if(a=[...n.keys()].at(-1),n.size<s)break}}async signDispatch(t){const e=typeof this.env.LUNORA_SCHEDULER_SECRET=="string"?this.env.LUNORA_SCHEDULER_SECRET:void 0;if(!(!e||e.length===0))return tt(e,t)}async recordRetry(t,e=!1){if(this.cancelledLeases.has(t.id))return;const s=(t.attempts??0)+(e?0:1),a=(t.attempts??0)+1,{backoff:n,baseMs:r,maxAttempts:d,maxMs:o}=i.resolveRetry(t),l=n==="linear"?r*a:r*2**(a-1),h=o===void 0?l:Math.min(l,o),w=e?Math.max(h,G):h,u=Math.round(Date.now()+w);if(s>d){await this.parkDead(t,s,`after ${String(s)} attempts`);return}if(!k(u)){await this.parkDead(t,s,`at attempt ${String(s)}: the retry backoff exceeded the largest schedulable time`);return}const E={...t,attempts:s,scheduledFor:u};await this.state.storage.put({...i.pendingRows(E),[`${I}${t.id}`]:E,[i.indexKey(u,t.id)]:t.id})}async parkDead(t,e,s){const a=Date.now();await this.state.storage.put({[`${f}${t.id}`]:{...t,attempts:e,completedAt:a,error:`dead-lettered ${s}`},[i.terminalIndexKey(a,t.id)]:t.id}),await this.state.storage.delete([`${I}${t.id}`,...i.pendingKeys(t)]),console.warn(`@lunora/scheduler: job "${t.id}" (${t.functionPath??t.workflow??"unknown"}) parked in dead-letter ${s}`)}async loadPool(t,e){const s=await this.state.storage.get(`${$}${t}`);return s!==void 0?Array.isArray(s.inFlightIds)?{inFlight:s.inFlightIds.length,inFlightIds:[...s.inFlightIds],maxConcurrency:s.maxConcurrency}:{inFlight:Math.max(0,s.inFlight),maxConcurrency:s.maxConcurrency}:{inFlight:0,inFlightIds:[],maxConcurrency:i.normalizeConcurrency(e,1)}}async savePool(t,e){await this.state.storage.put(`${$}${t}`,e)}async requeuePooled(t){if(this.cancelledLeases.has(t.id))return;const e=Date.now()+rt,s={...t,scheduledFor:e};await this.state.storage.put({...i.pendingRows(s),[i.indexKey(e,t.id)]:t.id})}async handleComplete(t){const e=await t.json().catch(()=>{}),s=typeof e?.pool=="string"&&e.pool.length>0?e.pool:void 0,a=typeof e?.id=="string"&&e.id.length>0?e.id:void 0;if(s===void 0)return i.error(400,"INVALID_INPUT","pool is required");const n=await this.withPoolLock(async()=>{const r=await this.loadPool(s),d=a===void 0?i.releaseFirstSlot(r):i.releaseSlot(r,a);return await this.savePool(s,d),d});return await this.armAlarmIfEarlier(Date.now()),i.json({inFlight:n.inFlight})}async handlePoolStatus(t){const e=t.searchParams.get("name");if(e===null||e.length===0)return i.error(400,"INVALID_INPUT","name is required");const s=await this.loadPool(e);let a=0;return await this.forEachPage(S(e),()=>{a+=1}),i.json({inFlight:s.inFlight,maxConcurrency:s.maxConcurrency,queued:a})}async handleStatus(){const t=new Map;await this.forEachPage(A,(r,d)=>{const o=at(d.slice(A.length,d.indexOf(":",A.length)));t.set(o,(t.get(o)??0)+1)});const e=[];let s=0,a=0;await this.forEachPage($,(r,d)=>{const o=d.slice($.length),l=Math.max(0,r.inFlight),h=t.get(o)??0;e.push({inFlight:l,maxConcurrency:r.maxConcurrency,name:o,queued:h}),s+=h,a+=l});const n={backlog:s,inFlight:a,pools:e};return i.json(n)}async persistPoolCap(t,e){const s=await this.loadPool(t,e);await this.savePool(t,{inFlight:s.inFlight,...s.inFlightIds===void 0?{}:{inFlightIds:s.inFlightIds},maxConcurrency:i.normalizeConcurrency(e,s.maxConcurrency)})}async idConflict(t){if(await this.state.storage.get(`${g}${t}`)!==void 0)return i.error(409,"DUPLICATE_SCHEDULE_ID",`a job with id "${t}" is already scheduled — cancel it first, or schedule under a different id`);if(await this.state.storage.get(`${f}${t}`)!==void 0)return i.error(409,"DUPLICATE_SCHEDULE_ID",`id "${t}" is held by a dead-letter record — retry or cancel it (POST /dead/retry, POST /dead/cancel) first, or schedule under a different id`)}async resolveId(t){let e;try{e=b(t)}catch(s){return i.error(400,"INVALID_SCHEDULE_ID",s instanceof Error?s.message:"invalid `id`")}return t===void 0?e:await this.idConflict(e)??e}async handleSchedule(t){const e=await t.json().catch(()=>{}),s=i.resolveScheduleTarget(e);if(!e||s===void 0)return i.error(400,"INVALID_INPUT","functionPath or workflow is required");const{functionPath:a,workflow:n}=s;if(typeof e.scheduledFor!="number"||!k(e.scheduledFor))return i.error(400,"INVALID_INPUT","scheduledFor must be a positive integer epoch-millisecond number no greater than 999999999999999");if(typeof this.env.LUNORA_ORIGIN_URL!="string"||this.env.LUNORA_ORIGIN_URL.length===0)return i.error(500,"ORIGIN_NOT_CONFIGURED","LUNORA_ORIGIN_URL env binding must be set on the SchedulerDO");const r=K(e.pool),d=K(e.instanceName),o=i.normalizeRetry(e.retry),l=await this.resolveId(e.id);if(l instanceof Response)return l;const h=l;r!==void 0&&await this.persistPoolCap(r,e.maxConcurrency);const w=e.id===void 0?void 0:this.state.storage.delete([`${p}${h}`,`${P}${h}`]),u={args:e.args??{},enqueuedAt:Date.now(),id:h,...a===void 0?{}:{functionPath:a},...d===void 0?{}:{instanceName:d},...r===void 0?{}:{pool:r},...o===void 0?{}:{retry:o},scheduledFor:e.scheduledFor,shardKey:e.shardKey,...n===void 0?{}:{workflow:n}},E=this.state.storage.put({...i.pendingRows(u),[i.indexKey(u.scheduledFor,h)]:h});return await Promise.all([w,E]),await this.armAlarmIfEarlier(u.scheduledFor),await this.broadcastChange(),i.json({id:h,scheduledFor:u.scheduledFor})}async handleCancel(t){const e=await t.json().catch(()=>{});if(!e?.id)return i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${g}${e.id}`);return s?await this.state.storage.get(`${p}${e.id}`)!==void 0?(await this.removeRecord(s),await this.rescheduleAlarm(),i.json({cancelled:!1})):(await this.removeRecord(s),await this.writeTerminal(s,"canceled").catch(()=>{}),await this.sweepTerminal().catch(()=>{}),await this.rescheduleAlarm(),await this.broadcastChange(),i.json({cancelled:!0})):i.json({cancelled:!1})}async handleList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(g,v,t.searchParams.get("cursor")??void 0);return i.json({cursor:e,records:s,truncated:a})}async handleDeadList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(f,v,t.searchParams.get("cursor")??void 0);return i.json({cursor:e,records:s,truncated:a})}async handleDeadRetry(t){const e=await t.json().catch(()=>{});if(typeof e?.id!="string"||e.id.length===0)return i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${f}${e.id}`);if(s===void 0)return i.json({retried:!1});const a=Date.now(),n={...s,attempts:0,scheduledFor:a};delete n.error,delete n.completedAt,await this.state.storage.delete(`${p}${s.id}`);const r=this.state.storage.put({...i.pendingRows(n),[i.indexKey(a,s.id)]:s.id}),d=this.state.storage.delete(s.completedAt===void 0?[`${f}${s.id}`]:[`${f}${s.id}`,i.terminalIndexKey(s.completedAt,s.id)]);return await Promise.all([r,d]),await this.armAlarmIfEarlier(a),await this.broadcastChange(),i.json({id:s.id,retried:!0,scheduledFor:a})}async handleDeadCancel(t){const e=await t.json().catch(()=>{});if(typeof e?.id!="string"||e.id.length===0)return i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${f}${e.id}`);return s===void 0?i.json({removed:!1}):(await this.writeTerminal(s,"failed",s.completedAt),await this.state.storage.delete(`${f}${e.id}`),await this.sweepTerminal().catch(()=>{}),i.json({removed:!0}))}async handleGet(t){const e=t.searchParams.get("id");if(e===null||e.length===0)return i.error(400,"INVALID_INPUT","id is required");const s=await this.readTerminal(e);if(s!==void 0)return i.json({record:s});const a=await this.state.storage.get(`${g}${e}`);if(a!==void 0){const r={...a,state:this.activeLeases.has(e)?"running":"pending"};return i.json({record:r})}const n=await this.state.storage.get(`${f}${e}`);return i.json(n===void 0?{}:{record:{...n,state:"failed"}})}async handleHistory(t){let e=t.searchParams.get("cursor")??void 0;const s=[];for(let a=0;a<it;a+=1){const r=[...(await this.state.storage.list({limit:v+1,prefix:C,...e===void 0?{}:{startAfter:e}})).entries()],d=r.slice(0,v),o=await Promise.all(d.map(async([l,h])=>this.readTerminal(h,l)));if(s.push(...o.filter(l=>l!==void 0)),e=d.at(-1)?.[0],r.length<=v)return i.json({records:s,truncated:!1});if(s.length>0)break}return i.json({cursor:e,records:s,truncated:!0})}async readTerminal(t,e){const s=await this.state.storage.get(`${p}${t}`)??await this.readParked(t);if(!(s===void 0||s.completedAt<=Date.now()-W)&&!(e!==void 0&&i.terminalIndexKey(s.completedAt,t)!==e))return s}async readParked(t){const e=await this.state.storage.get(`${f}${t}`);return e?.completedAt===void 0?void 0:{...e,completedAt:e.completedAt,state:"failed"}}async correctCanceledToSucceeded(t){const e=await this.state.storage.get(`${p}${t.id}`);e?.state!=="canceled"||await this.state.storage.get(`${g}${t.id}`)!==void 0||JSON.stringify(e)===JSON.stringify({...t,completedAt:e.completedAt,state:e.state})&&await Promise.all([this.state.storage.delete(i.terminalIndexKey(e.completedAt,t.id)),this.writeTerminal(t,"succeeded")])}async writeTerminal(t,e,s=Date.now()){const a={...t,completedAt:s,state:e};await this.state.storage.put({[`${p}${t.id}`]:a,[i.terminalIndexKey(s,t.id)]:t.id})}async sweepTerminal(){for(let t=0;t<dt;t+=1)if(await this.sweepTerminalBatch()<_)return}async sweepTerminalBatch(){const t=i.terminalIndexKey(Date.now()-W+1,"~"),e=await this.state.storage.list({limit:_,prefix:C,startAfter:t});if(e.size===0)return 0;const s=await Promise.all([...e.entries()].map(async([a,n])=>{const r=await this.state.storage.get(`${p}${n}`);return r!==void 0&&i.terminalIndexKey(r.completedAt,n)===a?[a,`${p}${n}`]:[a]}));return await this.state.storage.delete(s.flat()),e.size}async pauseState(){return await this.state.storage.get(F)??{paused:!1}}async isPaused(){return(await this.pauseState()).paused}async handleRegisterInstance(t){const e=i.cronName(await t.json().catch(()=>{}));return e===void 0?i.error(400,"INVALID_INPUT","name is required"):(await this.state.storage.put(`${U}${m(e)}`,e),i.json(await this.pauseState()))}async handleListInstances(){const t=[];return await this.forEachPage(U,e=>{t.push(e)}),i.json({instances:t})}async handleSetPause(t){const e=await t.json().catch(()=>{});if(typeof e?.paused!="boolean")return i.error(400,"INVALID_INPUT","paused (boolean) is required");if(!e.paused){const n=await this.earliestPendingTime();return n!==void 0&&Number.isFinite(n)&&await this.state.storage.setAlarm(n),await this.state.storage.delete(F),i.json({paused:!1})}const a={paused:!0,pausedAt:(await this.pauseState()).pausedAt??Date.now(),...typeof e.reason=="string"&&e.reason.length>0?{reason:e.reason.slice(0,500)}:{}};return await this.state.storage.put(F,a),await this.state.storage.deleteAlarm(),i.json(a)}async handleCronBegin(t){const e=i.cronName(await t.json().catch(()=>{}));if(e===void 0)return i.error(400,"INVALID_INPUT","name is required");const s=`${N}${m(e)}`,a=Date.now();if((await this.pauseState()).paused)return await this.recordCronSkip(e,"paused",a).catch(()=>{}),i.json({acquired:!1,reason:"paused"});const r=await this.state.storage.get(s);if(r!==void 0&&i.leaseIsLive(r,a))return await this.state.storage.put(s,{...r,skipped:r.skipped+1}).catch(()=>{}),await this.recordCronSkip(e,"in-flight",a).catch(()=>{}),i.json({acquired:!1,reason:"in-flight",runningSince:r.startedAt});r!==void 0&&await this.recordLostCronRun(r,a);const d=b(void 0);return await this.state.storage.put(s,{name:e,runId:d,skipped:0,startedAt:a}),i.json({acquired:!0,runId:d})}async handleCronRenew(t){const e=await t.json().catch(()=>{}),s=i.cronName(e);if(s===void 0||typeof e?.runId!="string")return i.error(400,"INVALID_INPUT","name and runId are required");const a=`${N}${m(s)}`,n=await this.state.storage.get(a),r=Date.now();return n?.runId!==e.runId||!i.leaseIsLive(n,r)?i.json({renewed:!1}):(await this.state.storage.put(a,{...n,renewedAt:r}),i.json({renewed:!0}))}async handleCronEnd(t){const e=await t.json().catch(()=>{}),s=i.cronName(e);if(s===void 0||typeof e?.runId!="string"||e.status!=="succeeded"&&e.status!=="failed")return i.error(400,"INVALID_INPUT","name, runId and status (succeeded | failed) are required");const a=`${N}${m(s)}`,n=await this.state.storage.get(a);if(n?.runId!==e.runId)return i.json({recorded:!1});const r=Date.now();return await this.recordCronRun({durationMs:r-n.startedAt,endedAt:r,...e.status==="failed"&&typeof e.error=="string"?{error:e.error.slice(0,2e3)}:{},name:s,runId:n.runId,skipped:n.skipped,startedAt:n.startedAt,status:e.status}),await this.state.storage.delete(a),i.json({recorded:!0})}async handleCronRuns(){const t=[],e=[],s=[],a=Date.now();await this.forEachPage(N,(n,r)=>{i.leaseIsLive(n,a)?t.push(n):e.push([r,n])});for(const[n,r]of e)await this.recordLostCronRun(r,a),await this.state.storage.delete(n);return await this.forEachPage(R,n=>{s.push(n)}),i.json({inFlight:t,runs:s})}async recordLostCronRun(t,e){[...(await this.state.storage.list({limit:L+y,prefix:`${R}${m(t.name)}:`})).keys()].some(a=>a.endsWith(`:${t.runId}`))||await this.recordCronRun({durationMs:e-t.startedAt,endedAt:e,error:"the run never reported completion; its lease expired",name:t.name,runId:t.runId,skipped:t.skipped,startedAt:t.startedAt,status:"failed"})}async recordCronSkip(t,e,s){const a=`${R}${m(t)}:`,n=await this.state.storage.list({limit:1,prefix:a}),[r]=n.entries();if(r?.[1].status==="skipped"&&r[1].reason===e){const[d,o]=r,l={...o,endedAt:s,skipped:o.skipped+1};await this.recordCronRun(l,i.cronRunKey(l)===d?void 0:d);return}await this.recordCronRun({durationMs:0,endedAt:s,name:t,reason:e,runId:b(void 0),skipped:1,startedAt:s,status:"skipped"})}async recordCronRun(t,e){const s=`${R}${m(t.name)}:`,a=this.state.storage.put(i.cronRunKey(t),t);await Promise.all([a,e===void 0?void 0:this.state.storage.delete(e)]);const r=[...(await this.state.storage.list({limit:L+y+1,prefix:s})).keys()].filter(d=>d!==e).slice(L);for(let d=0;d<r.length;d+=y)await this.state.storage.delete(r.slice(d,d+y))}async removeRecord(t){const e=[...i.pendingKeys(t),i.indexKey(t.scheduledFor,t.id),`${I}${t.id}`],s=this.activeLeases.get(t.id);s!==void 0&&(e.push(s),this.cancelledLeases.add(t.id)),await this.state.storage.delete(e)}async armAlarmIfEarlier(t){const e=await this.state.storage.getAlarm();(e===null||t<e)&&await this.state.storage.setAlarm(t)}async reindexOrphanedRecords(){if(this.recovery!==void 0)return this.recovery;const t=this.recoverStore();return this.recovery=t,t.catch(()=>{this.recovery=void 0}),t}async recoverStore(){if(await this.state.storage.get(T)===void 0&&(await this.reindexWalk(),await this.state.storage.put(T,!0)),await this.state.storage.getAlarm()===null){const t=await this.earliestPendingTime();t!==void 0&&Number.isFinite(t)&&await this.state.storage.setAlarm(t)}this.recovered=!0}async restoreOutcome(t){const e=await this.state.storage.get(`${g}${t.id}`);if(e!==void 0&&e.enqueuedAt!==t.enqueuedAt){await this.state.storage.delete(`${P}${t.id}`);return}await this.state.storage.get(`${p}${t.id}`)===void 0&&await this.writeTerminal(t,"succeeded",t.completedAt),await this.state.storage.delete([`${P}${t.id}`,...i.pendingKeys(t),`${I}${t.id}`])}async reindexWalk(){const t=new Set,e=new Set;await this.forEachPage("t:",o=>{t.add(o)}),await this.forEachPage(A,(o,l)=>{e.add(l)});const s=new Map;await this.forEachPage(P,o=>{s.set(o.id,o)});const a=new Set,n=[],r=[];await this.forEachPage(g,o=>{!t.has(o.id)&&k(o.scheduledFor)&&n.push(o),a.add(o.id);const l=i.poolQueueKey(o);l!==void 0&&!e.has(l)&&r.push([l,o.id])});const d=[...e].filter(o=>!a.has(o.slice(o.indexOf(":",A.length)+1)));for(let o=0;o<d.length;o+=y)await this.state.storage.delete(d.slice(o,o+y));for(let o=0;o<r.length;o+=y)await this.state.storage.put(Object.fromEntries(r.slice(o,o+y)));for(const o of s.values())await this.restoreOutcome(o);for(const o of n)await this.state.storage.put(i.indexKey(o.scheduledFor,o.id),o.id),await this.armAlarmIfEarlier(o.scheduledFor)}async earliestPendingTime(){const e=(await this.state.storage.list({limit:1,prefix:"t:"})).entries().next();if(e.done)return;const[s]=e.value;return Number.parseInt(s.slice(2,s.indexOf(":",2)),10)}async rescheduleAlarm(){if(await this.isPaused()){await this.state.storage.deleteAlarm();return}const t=await this.earliestPendingTime();if(t===void 0){await this.state.storage.deleteAlarm();return}Number.isFinite(t)&&await this.state.storage.setAlarm(t)}}export{H as DISPATCH_LEASE_MS,ot as MAX_CONCURRENT_DISPATCHES,nt as MAX_RETRY_ATTEMPTS,j as MAX_SCHEDULED_FOR_MS,G as RETRY_BASE_DELAY_MS,i as SchedulerDO,W as TERMINAL_RETENTION_MS};
|
package/dist/packem_shared/{assertScheduleDelay-DiyM8a3y.mjs → assertScheduleDelay-CH6-R3I0.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as r}from"@lunora/errors";import{MAX_SCHEDULED_FOR_MS as i}from"./MAX_RETRY_ATTEMPTS-
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{MAX_SCHEDULED_FOR_MS as i}from"./MAX_RETRY_ATTEMPTS-B0v-qzSa.mjs";const s=(t,e,n="delayMs")=>{if(!Number.isFinite(t)||t<0)throw new r("INVALID_INPUT",`${e}: \`${n}\` must be a non-negative finite number`);if(Date.now()+t>i)throw new r("INVALID_INPUT",`${e}: \`${n}\` is later than the latest schedulable instant (${String(i)} ms)`)};export{s as default};
|
package/dist/packem_shared/{assertScheduleInstant-DlXlSbXn.mjs → assertScheduleInstant-BRQWdkcF.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import r from"./assertScheduleDelay-
|
|
1
|
+
import r from"./assertScheduleDelay-CH6-R3I0.mjs";const l=(t,s,a)=>{const e=t-s;r(Number.isFinite(e)&&e<0?0:e,a,"date")};export{l as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as w}from"@lunora/errors";import{encodeArgsOrThrow as g,decodeWire as A}from"@lunora/wire";import{a as p,c as d,g as f}from"./do-client-
|
|
1
|
+
import{LunoraError as w}from"@lunora/errors";import{encodeArgsOrThrow as g,decodeWire as A}from"@lunora/wire";import{a as p,c as d,g as f}from"./do-client-DnJqrsmj.mjs";import{isWorkflowReference as h}from"./isWorkflowReference-CT3tdefh.mjs";import N from"./assertScheduleDelay-CH6-R3I0.mjs";import R from"./assertScheduleInstant-BRQWdkcF.mjs";const v=async e=>{const a=[];let o;for(;;){const c=await e(o);if(a.push(...Array.isArray(c.records)?c.records:[]),c.truncated!==!0||typeof c.cursor!="string"||c.cursor.length===0)return a;if(c.cursor===o)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");o=c.cursor}},x=e=>typeof e=="string"?e:(h(e)?e.className:e.__lunoraRef)??"<unknown>",m=e=>({...e,args:A(e.args)}),K=e=>{p(e);const a=async(s,r,n,t={})=>{const u=Math.ceil(s instanceof Date?s.getTime():s);R(u,Date.now(),"ctx.scheduler.runAt");const i={args:g("ctx.scheduler.runAt",x(r),n),id:t.id,instanceName:e.instanceName??"default",maxConcurrency:t.pool===void 0?void 0:t.maxConcurrency,pool:t.pool,retry:t.retry,scheduledFor:u,shardKey:t.shardKey};if(h(r)){if(typeof r.className!="string"||r.className.length===0)throw new w("INTERNAL","@lunora/scheduler: workflow/agent schedule target is missing its `className` — pass the generated `workflows.<name>` / `agents.<name>` reference");return(await d(e,"/schedule",{...i,workflow:r.className})).id}const y=typeof r=="string"?r:r.__lunoraRef;return(await d(e,"/schedule",{...i,functionPath:y})).id},o=async(s,r,n,t={})=>(N(s,"ctx.scheduler.runAfter"),a(Date.now()+s,r,n,t)),c=async s=>d(e,"/cancel",{id:s}),l=async s=>(await v(async n=>f(e,n===void 0?s:`${s}?cursor=${encodeURIComponent(n)}`))).map(n=>m(n));return{cancel:c,dead:async()=>l("/dead"),deadRetry:async s=>{const{retried:r}=await d(e,"/dead/retry",{id:s});return r===!0},get:async s=>{const r=await f(e,`/get?id=${encodeURIComponent(s)}`);return r.record===void 0?null:m(r.record)},list:async()=>l("/list"),runAfter:o,runAt:a}};export{K as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import u from"./createScheduler-gJy27c_Q.mjs";const l=a=>a?.at!==void 0?typeof a.at=="number"?a.at:a.at.getTime():Date.now()+(a?.delayMs??0),m=a=>{const r=u({instanceName:a.instanceName,jurisdiction:a.jurisdiction,namespace:a.namespace}),c=e=>({attempts:e.attempts??0,functionPath:e.functionPath??e.workflow??"",id:e.id,scheduledFor:e.scheduledFor});return{cancel:async e=>{const{cancelled:t}=await r.cancel(e);return t},deadLetter:{list:async()=>(await r.dead()).map(t=>c(t)),requeue:async e=>r.deadRetry(e)},get:async e=>{const t=await r.get(e);return t===null?null:{...c(t),state:t.state,...t.completedAt===void 0?{}:{completedAt:t.completedAt}}},list:async()=>(await r.list()).map(t=>c(t)),schedule:async(e,t,n)=>{const d=r.runAt,s=l(n);return{id:await d(s,e,t,{retry:n?.retry,shardKey:n?.shardKey}),scheduledFor:s}}}};export{m as createSchedulerHost};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as l}from"@lunora/errors";import{encodeArgsOrThrow as o}from"@lunora/wire";import{a as s,g as m,c as u}from"./do-client-
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{encodeArgsOrThrow as o}from"@lunora/wire";import{a as s,g as m,c as u}from"./do-client-DnJqrsmj.mjs";import y from"./assertScheduleDelay-CH6-R3I0.mjs";const N=e=>{if(s(e),!Number.isInteger(e.maxConcurrency)||e.maxConcurrency<=0)throw new l("INTERNAL","@lunora/scheduler: `maxConcurrency` must be a positive integer");const a=typeof e.name=="string"&&e.name.length>0?e.name:"default";return{cancel:async r=>u(e,"/cancel",{id:r}),enqueue:async(r,t,n={})=>{const c=n.delayMs??0;return y(c,"workpool.enqueue"),u(e,"/schedule",{args:o("workpool.enqueue",r.__lunoraRef,t),functionPath:r.__lunoraRef,instanceName:e.instanceName??"default",maxConcurrency:e.maxConcurrency,pool:a,retry:n.retry,scheduledFor:Math.ceil(Date.now()+c),shardKey:n.shardKey})},name:a,status:async()=>m(e,`/pool?name=${encodeURIComponent(a)}`)}};export{N as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as o}from"@lunora/errors";const p=(e,t)=>{if(t===void 0)return e;if(typeof e.jurisdiction!="function")throw new TypeError(`@lunora/scheduler: Durable Object namespace does not support jurisdiction("${t}") — update @cloudflare/workers-types or remove the jurisdiction option`);return e.jurisdiction(t)},O=e=>{if(!e.namespace)throw new o("INTERNAL","@lunora/scheduler: `namespace` (SchedulerDO binding) is required")},y=e=>{const t=p(e.namespace,e.jurisdiction);return t.get(t.idFromName(e.instanceName??"default"))},h=(e,t,n)=>{let s,r;try{({code:s,message:r}=JSON.parse(n).error??{})}catch{}throw typeof s=="string"&&s.length>0?new o(s,typeof r=="string"&&r.length>0?r:`@lunora/scheduler: SchedulerDO ${e} failed`,{status:t}):new o("INTERNAL",`@lunora/scheduler: SchedulerDO ${e} failed (${String(t)}): ${n}`)},d="default",l=new WeakMap,g=async e=>{const t=e.instanceName??d,n=e.primaryInstanceName??d;if(t===n)return;const s=l.get(e.namespace)??new Set;if(l.set(e.namespace,s),s.has(t))return;const r=p(e.namespace,e.jurisdiction),i=async(f,u,w)=>{const a=await r.get(r.idFromName(f)).fetch(`https://scheduler.internal${u}`,{body:JSON.stringify(w),headers:{"content-type":"application/json"},method:"POST"});return a.ok||h(u,a.status,await a.text()),await a.json()},c=await i(n,"/instances/register",{name:t});c.paused===!0&&await i(t,"/pause",{paused:!0,...c.reason===void 0?{}:{reason:c.reason}}),s.add(t)},m=async(e,t,n)=>{await g(e);const r=await y(e).fetch(`https://scheduler.internal${t}`,n);return r.ok||h(t,r.status,await r.text()),await r.json()},S=async(e,t,n)=>m(e,t,{body:JSON.stringify(n),headers:{"content-type":"application/json"},method:"POST"}),j=async(e,t)=>m(e,t,{method:"GET"});export{O as a,S as c,j as g};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/scheduler",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.162",
|
|
4
4
|
"description": "Scheduling for Lunora: runAfter / runAt and Cron Triggers via SchedulerDO",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
53
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
54
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
54
|
+
"@lunora/platform": "1.0.0-alpha.77",
|
|
55
55
|
"@lunora/wire": "1.0.0-alpha.6",
|
|
56
56
|
"@visulima/cron-parser": "2.0.0"
|
|
57
57
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as L,r as C}from"./resolve-schedule-id-B2ghxgFm.mjs";const T="DISPATCH_IN_PROGRESS",k="x-lunora-dispatch-declined",$=(c,t)=>{if(c.size<t)return;const e=c.keys().next().value;e!==void 0&&c.delete(e)},M=(c,t,e,s)=>{const a=c.get(t);if(a!==void 0)return a;$(c,s);const n=e().catch(r=>{throw c.get(t)===n&&c.delete(t),r});return c.set(t,n),n},U=new TextEncoder,S=64,K=new Map,j=async c=>M(K,c,async()=>crypto.subtle.importKey("raw",U.encode(c),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),S),_=new TextEncoder,G=Array.from({length:32},(c,t)=>t);new RegExp(`[${G.map(c=>String.fromCodePoint(c)).join("")}]`,"u");const H=async(c,t)=>{const e=await j(c),s=await crypto.subtle.sign("HMAC",e,_.encode(t));return L(new Uint8Array(s))},A=(c,t=200,e)=>{const s=new Headers({"content-type":"application/json"});for(const[a,n]of Object.entries({}))s.set(a,n);return Response.json(c,{headers:s,status:t})},W="lunora-ping",O="lunora-pong",g="id:",w="retry:",f="dead:",p="pool:",y="pq:",v=128,b=c=>typeof c=="string"&&c.length>0?c:void 0,D=c=>Array.from({length:c.length},(t,e)=>c.charCodeAt(e).toString(16).padStart(4,"0")).join(""),q=c=>{let t="";for(let e=0;e<c.length;e+=4)t+=String.fromCharCode(Number.parseInt(c.slice(e,e+4),16));return t},x=c=>`${y}${D(c)}:`,I="meta:clean",m=100,V=5,N=3e4,X=1e3,z=6,B=9e5,Q=999999999999999,Y=15,F=c=>String(c).padStart(Y,"0"),R=c=>Number.isInteger(c)&&c>0&&c<=Q;class i{static indexKey(t,e){return`t:${F(t)}:${e}`}static poolQueueKey(t){return t.pool===void 0?void 0:`${x(t.pool)}${t.id}`}static pendingRows(t){const e=i.poolQueueKey(t);return{[`${g}${t.id}`]:t,...e===void 0?{}:{[e]:t.id}}}static pendingKeys(t){return Object.keys(i.pendingRows(t))}static json(t,e=200){return A(t,e)}static error(t,e,s){return i.json({error:{code:e,message:s}},t)}static resolveRetry(t){const e=t.retry,s=typeof e?.maxAttempts=="number"&&Number.isInteger(e.maxAttempts)&&e.maxAttempts>0?e.maxAttempts:V,a=typeof e?.baseMs=="number"&&Number.isFinite(e.baseMs)&&e.baseMs>=0?e.baseMs:N,n=e?.backoff==="linear"?"linear":"exponential",r=typeof e?.maxMs=="number"&&Number.isFinite(e.maxMs)&&e.maxMs>=0?e.maxMs:void 0;return{backoff:n,baseMs:a,maxAttempts:s,maxMs:r}}static normalizeConcurrency(t,e){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:e}static normalizeRetry(t){if(typeof t!="object"||t===null)return;const e=t,s={};return typeof e.maxAttempts=="number"&&Number.isInteger(e.maxAttempts)&&e.maxAttempts>0&&(s.maxAttempts=e.maxAttempts),typeof e.baseMs=="number"&&Number.isFinite(e.baseMs)&&e.baseMs>=0&&(s.baseMs=e.baseMs),(e.backoff==="exponential"||e.backoff==="linear")&&(s.backoff=e.backoff),typeof e.maxMs=="number"&&Number.isFinite(e.maxMs)&&e.maxMs>=0&&(s.maxMs=e.maxMs),Object.keys(s).length===0?void 0:s}static releaseSlot(t,e){if(t.inFlightIds===void 0)return{...t,inFlight:Math.max(0,t.inFlight-1)};const s=t.inFlightIds.filter(a=>a!==e);return{...t,inFlight:s.length,inFlightIds:s}}static releaseFirstSlot(t){if(t.inFlightIds===void 0)return{...t,inFlight:Math.max(0,t.inFlight-1)};const e=t.inFlightIds.slice(0,Math.max(0,t.inFlightIds.length-1));return{...t,inFlight:e.length,inFlightIds:e}}static resolveScheduleTarget(t){const e=typeof t?.functionPath=="string"&&t.functionPath.length>0?t.functionPath:void 0,s=typeof t?.workflow=="string"&&t.workflow.length>0?t.workflow:void 0;if(!(e===void 0&&s===void 0))return{functionPath:e,workflow:s}}state;env;recovery;recovered=!1;dirty=!1;poolLock=Promise.resolve();activeLeases=new Map;cancelledLeases=new Set;constructor(t,e){this.state=t,this.env=e,this.armWebSocketKeepalive()}async fetch(t){await this.reindexOrphanedRecords();const e=new URL(t.url);if(e.pathname==="/ws"&&t.headers.get("Upgrade")==="websocket")return this.handleWebSocketUpgrade();switch(`${t.method} ${e.pathname}`){case"GET /dead":return this.handleDeadList(e);case"GET /get":return this.handleGet(e);case"GET /list":return this.handleList(e);case"GET /pool":return this.handlePoolStatus(e);case"GET /status":return this.handleStatus();case"POST /cancel":return this.handleCancel(t);case"POST /complete":return this.handleComplete(t);case"POST /dead/cancel":return this.handleDeadCancel(t);case"POST /dead/retry":return this.handleDeadRetry(t);case"POST /schedule":return this.handleSchedule(t)}return A({error:{code:"NOT_FOUND"}},404)}async alarm(){await this.reindexOrphanedRecords();const t=Date.now(),e=[],s=new Set,a=await this.state.storage.list({end:`t:${F(t)}:~`,limit:100,prefix:"t:"}),n=[];for(const[d,h]of a.entries()){const l=Number.parseInt(d.slice(2,d.indexOf(":",2)),10);Number.isFinite(l)&&l<=t&&n.push({indexKey:d,recordId:h})}const r=await Promise.all(n.map(d=>this.state.storage.get(`${g}${d.recordId}`)));for(const[d,{indexKey:h,recordId:l}]of n.entries()){const u=r[d];u&&s.has(l)?await this.state.storage.delete(h):u?(s.add(l),e.push({claimKey:h,record:u})):await this.state.storage.delete(h)}let o=!1;try{e.length>0&&(await this.state.storage.delete(I),o=!0),await this.drainDue(e)}finally{await this.rescheduleAlarm(),o&&this.recovered&&!this.dirty&&await this.state.storage.put(I,!0)}e.length>0&&await this.broadcastChange()}async dispatch(t){const e=typeof this.env.LUNORA_ORIGIN_URL=="string"&&this.env.LUNORA_ORIGIN_URL.length>0?this.env.LUNORA_ORIGIN_URL:void 0;if(!e)return!1;const s=JSON.stringify({args:t.args,functionPath:t.functionPath,id:t.id,instanceName:t.instanceName,pool:t.pool,scheduledFor:t.scheduledFor,shardKey:t.shardKey,workflow:t.workflow});try{const a={"content-type":"application/json"},n=await this.signDispatch(s);n!==void 0?a["x-lunora-scheduler-signature"]=n:typeof this.env.LUNORA_ADMIN_TOKEN=="string"&&this.env.LUNORA_ADMIN_TOKEN.length>0&&(a.authorization=`Bearer ${this.env.LUNORA_ADMIN_TOKEN}`);const r=await fetch(`${e}/_lunora/scheduler/dispatch`,{body:s,headers:a,method:"POST"});return r.status===409&&r.headers.get(k)==="1"&&await r.json().then(d=>d?.error?.code===T,()=>!1)?"in-progress":r.ok}catch{return!1}}armWebSocketKeepalive(){const t=this.state.setWebSocketAutoResponse;typeof t!="function"||typeof WebSocketRequestResponsePair>"u"||t.call(this.state,new WebSocketRequestResponsePair(W,O))}async drainDue(t){const e=[...t],s=[],a=Math.min(z,e.length);for(let n=0;n<a;n+=1)s.push((async()=>{for(let r=e.shift();r!==void 0;r=e.shift())await this.drainRecordGuarded(r.record,r.claimKey)})());await Promise.all(s)}async withPoolLock(t){const e=this.poolLock.then(t,t);return this.poolLock=e.then(()=>{},()=>{}),e}async drainRecordGuarded(t,e){const s=i.indexKey(Date.now()+B,t.id);try{const a=await this.state.storage.get(`${g}${t.id}`);if(a===void 0){await this.state.storage.delete(e);return}if(JSON.stringify(a)!==JSON.stringify(t))return;await this.state.storage.delete(e),await this.state.storage.put(s,t.id),this.activeLeases.set(t.id,s),await this.drainRecord(t)}catch{try{if(this.cancelledLeases.has(t.id)){await this.state.storage.delete(s);return}if(await this.state.storage.get(`${f}${t.id}`)!==void 0){await this.state.storage.delete(s),await this.state.storage.delete([`${w}${t.id}`,...i.pendingKeys(t)]);return}await this.state.storage.put(e,t.id),await this.state.storage.delete(s)}catch{this.dirty=!0}return}finally{this.activeLeases.delete(t.id),this.cancelledLeases.delete(t.id)}try{await this.state.storage.delete(s)}catch{}}async drainRecord(t){if(!await this.reservePoolSlot(t))return!1;const s=await this.dispatch(t),a=s===!0,n=t.pool;if(!a&&n!==void 0&&await this.withPoolLock(async()=>{const r=await this.loadPool(n);await this.savePool(n,i.releaseSlot(r,t.id))}),this.cancelledLeases.has(t.id))return a;if(a){try{await this.state.storage.delete([...i.pendingKeys(t),`${w}${t.id}`])}catch{this.dirty=!0}return!0}return await this.recordRetry(t,s==="in-progress"),!1}async reservePoolSlot(t){const e=t.pool;if(e===void 0)return!0;const s=await this.withPoolLock(async()=>{const a=await this.loadPool(e);if(a.inFlight>=a.maxConcurrency)return!1;const n=a.inFlightIds??[];return n.includes(t.id)||n.push(t.id),a.inFlightIds=n,a.inFlight=n.length,await this.savePool(e,a),!0});return s||await this.requeuePooled(t),s}async handleWebSocketUpgrade(){if(this.state.acceptWebSocket===void 0)return i.error(501,"WS_UNSUPPORTED","WebSocket subscriptions are not supported in this runtime");const t=new WebSocketPair,e=t[0],s=t[1];this.state.acceptWebSocket(s);const a=await this.listPage(g,m);return s.send(JSON.stringify({records:a.records,truncated:a.truncated,type:"jobs"})),new Response(null,{status:101,webSocket:e})}async broadcastChange(){const t=this.state.getWebSockets?.();if(t===void 0||t.length===0)return;const{records:e,truncated:s}=await this.listPage(g,m),a=JSON.stringify({records:e,truncated:s,type:"jobs"});for(const n of t)try{n.send(a)}catch{}}async listPage(t,e,s){const a=await this.state.storage.list({limit:e+1,prefix:t,...s===void 0?{}:{startAfter:s}}),n=[...a.keys()],r=[...a.values()],o=r.length>e;return o?{cursor:n[e-1],records:r.slice(0,e),truncated:o}:{records:r,truncated:o}}async forEachPage(t,e,s=m){let a;for(;;){const n=await this.state.storage.list(a===void 0?{limit:s,prefix:t}:{limit:s,prefix:t,startAfter:a});if(n.size===0)break;for(const[o,d]of n.entries())e(d,o);if(a=[...n.keys()].at(-1),n.size<s)break}}async signDispatch(t){const e=typeof this.env.LUNORA_SCHEDULER_SECRET=="string"?this.env.LUNORA_SCHEDULER_SECRET:void 0;if(!(!e||e.length===0))return H(e,t)}async recordRetry(t,e=!1){if(this.cancelledLeases.has(t.id))return;const s=(t.attempts??0)+(e?0:1),a=(t.attempts??0)+1,{backoff:n,baseMs:r,maxAttempts:o,maxMs:d}=i.resolveRetry(t),h=n==="linear"?r*a:r*2**(a-1),l=d===void 0?h:Math.min(h,d),u=e?Math.max(l,N):l,P=Math.round(Date.now()+u);if(s>o){await this.parkDead(t,s,`after ${String(s)} attempts`);return}if(!R(P)){await this.parkDead(t,s,`at attempt ${String(s)}: the retry backoff exceeded the largest schedulable time`);return}const E={...t,attempts:s,scheduledFor:P};await this.state.storage.put({...i.pendingRows(E),[`${w}${t.id}`]:E,[i.indexKey(P,t.id)]:t.id})}async parkDead(t,e,s){await this.state.storage.put(`${f}${t.id}`,{...t,attempts:e}),await this.state.storage.delete([`${w}${t.id}`,...i.pendingKeys(t)]),console.warn(`@lunora/scheduler: job "${t.id}" (${t.functionPath??t.workflow??"unknown"}) parked in dead-letter ${s}`)}async loadPool(t,e){const s=await this.state.storage.get(`${p}${t}`);return s!==void 0?Array.isArray(s.inFlightIds)?{inFlight:s.inFlightIds.length,inFlightIds:[...s.inFlightIds],maxConcurrency:s.maxConcurrency}:{inFlight:Math.max(0,s.inFlight),maxConcurrency:s.maxConcurrency}:{inFlight:0,inFlightIds:[],maxConcurrency:i.normalizeConcurrency(e,1)}}async savePool(t,e){await this.state.storage.put(`${p}${t}`,e)}async requeuePooled(t){if(this.cancelledLeases.has(t.id))return;const e=Date.now()+X,s={...t,scheduledFor:e};await this.state.storage.put({...i.pendingRows(s),[i.indexKey(e,t.id)]:t.id})}async handleComplete(t){const e=await t.json().catch(()=>{}),s=typeof e?.pool=="string"&&e.pool.length>0?e.pool:void 0,a=typeof e?.id=="string"&&e.id.length>0?e.id:void 0;if(s===void 0)return i.error(400,"INVALID_INPUT","pool is required");const n=await this.withPoolLock(async()=>{const r=await this.loadPool(s),o=a===void 0?i.releaseFirstSlot(r):i.releaseSlot(r,a);return await this.savePool(s,o),o});return await this.armAlarmIfEarlier(Date.now()),i.json({inFlight:n.inFlight})}async handlePoolStatus(t){const e=t.searchParams.get("name");if(e===null||e.length===0)return i.error(400,"INVALID_INPUT","name is required");const s=await this.loadPool(e);let a=0;return await this.forEachPage(x(e),()=>{a+=1}),i.json({inFlight:s.inFlight,maxConcurrency:s.maxConcurrency,queued:a})}async handleStatus(){const t=new Map;await this.forEachPage(y,(r,o)=>{const d=q(o.slice(y.length,o.indexOf(":",y.length)));t.set(d,(t.get(d)??0)+1)});const e=[];let s=0,a=0;await this.forEachPage(p,(r,o)=>{const d=o.slice(p.length),h=Math.max(0,r.inFlight),l=t.get(d)??0;e.push({inFlight:h,maxConcurrency:r.maxConcurrency,name:d,queued:l}),s+=l,a+=h});const n={backlog:s,inFlight:a,pools:e};return i.json(n)}async persistPoolCap(t,e){const s=await this.loadPool(t,e);await this.savePool(t,{inFlight:s.inFlight,...s.inFlightIds===void 0?{}:{inFlightIds:s.inFlightIds},maxConcurrency:i.normalizeConcurrency(e,s.maxConcurrency)})}async idConflict(t){if(await this.state.storage.get(`${g}${t}`)!==void 0)return i.error(409,"DUPLICATE_SCHEDULE_ID",`a job with id "${t}" is already scheduled — cancel it first, or schedule under a different id`);if(await this.state.storage.get(`${f}${t}`)!==void 0)return i.error(409,"DUPLICATE_SCHEDULE_ID",`id "${t}" is held by a dead-letter record — retry or cancel it (POST /dead/retry, POST /dead/cancel) first, or schedule under a different id`)}async resolveId(t){let e;try{e=C(t)}catch(s){return i.error(400,"INVALID_SCHEDULE_ID",s instanceof Error?s.message:"invalid `id`")}return t===void 0?e:await this.idConflict(e)??e}async handleSchedule(t){const e=await t.json().catch(()=>{}),s=i.resolveScheduleTarget(e);if(!e||s===void 0)return i.error(400,"INVALID_INPUT","functionPath or workflow is required");const{functionPath:a,workflow:n}=s;if(typeof e.scheduledFor!="number"||!R(e.scheduledFor))return i.error(400,"INVALID_INPUT","scheduledFor must be a positive integer epoch-millisecond number no greater than 999999999999999");if(typeof this.env.LUNORA_ORIGIN_URL!="string"||this.env.LUNORA_ORIGIN_URL.length===0)return i.error(500,"ORIGIN_NOT_CONFIGURED","LUNORA_ORIGIN_URL env binding must be set on the SchedulerDO");const r=b(e.pool),o=b(e.instanceName),d=i.normalizeRetry(e.retry),h=await this.resolveId(e.id);if(h instanceof Response)return h;const l=h,u={args:e.args??{},enqueuedAt:Date.now(),id:l,...a===void 0?{}:{functionPath:a},...o===void 0?{}:{instanceName:o},...r===void 0?{}:{pool:r},...d===void 0?{}:{retry:d},scheduledFor:e.scheduledFor,shardKey:e.shardKey,...n===void 0?{}:{workflow:n}};return r!==void 0&&await this.persistPoolCap(r,e.maxConcurrency),await this.state.storage.put({...i.pendingRows(u),[i.indexKey(u.scheduledFor,l)]:l}),await this.armAlarmIfEarlier(u.scheduledFor),await this.broadcastChange(),i.json({id:l,scheduledFor:u.scheduledFor})}async handleCancel(t){const e=await t.json().catch(()=>{});if(!e?.id)return i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${g}${e.id}`);return s?(await this.removeRecord(s),await this.rescheduleAlarm(),await this.broadcastChange(),i.json({cancelled:!0})):i.json({cancelled:!1})}async handleList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(g,m,t.searchParams.get("cursor")??void 0);return i.json({cursor:e,records:s,truncated:a})}async handleDeadList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(f,m,t.searchParams.get("cursor")??void 0);return i.json({cursor:e,records:s,truncated:a})}async handleDeadRetry(t){const e=await t.json().catch(()=>{});if(typeof e?.id!="string"||e.id.length===0)return i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${f}${e.id}`);if(s===void 0)return i.json({retried:!1});const a=Date.now(),n={...s,attempts:0,scheduledFor:a};return await this.state.storage.put({...i.pendingRows(n),[i.indexKey(a,s.id)]:s.id}),await this.state.storage.delete(`${f}${s.id}`),await this.armAlarmIfEarlier(a),await this.broadcastChange(),i.json({id:s.id,retried:!0,scheduledFor:a})}async handleDeadCancel(t){const e=await t.json().catch(()=>{});if(typeof e?.id!="string"||e.id.length===0)return i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.delete(`${f}${e.id}`);return i.json({removed:!!s})}async handleGet(t){const e=t.searchParams.get("id");if(e===null||e.length===0)return i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${g}${e}`);return i.json(s===void 0?{}:{record:s})}async removeRecord(t){const e=[...i.pendingKeys(t),i.indexKey(t.scheduledFor,t.id),`${w}${t.id}`],s=this.activeLeases.get(t.id);s!==void 0&&(e.push(s),this.cancelledLeases.add(t.id)),await this.state.storage.delete(e)}async armAlarmIfEarlier(t){const e=await this.state.storage.getAlarm();(e===null||t<e)&&await this.state.storage.setAlarm(t)}async reindexOrphanedRecords(){if(this.recovery!==void 0)return this.recovery;const t=this.recoverStore();return this.recovery=t,t.catch(()=>{this.recovery=void 0}),t}async recoverStore(){if(await this.state.storage.get(I)===void 0&&(await this.reindexWalk(),await this.state.storage.put(I,!0)),await this.state.storage.getAlarm()===null){const t=await this.earliestPendingTime();t!==void 0&&Number.isFinite(t)&&await this.state.storage.setAlarm(t)}this.recovered=!0}async reindexWalk(){const t=new Set,e=new Set;await this.forEachPage("t:",o=>{t.add(o)}),await this.forEachPage(y,(o,d)=>{e.add(d)});const s=new Set,a=[],n=[];await this.forEachPage(g,o=>{!t.has(o.id)&&R(o.scheduledFor)&&a.push(o),s.add(o.id);const d=i.poolQueueKey(o);d!==void 0&&!e.has(d)&&n.push([d,o.id])});const r=[...e].filter(o=>!s.has(o.slice(o.indexOf(":",y.length)+1)));for(let o=0;o<r.length;o+=v)await this.state.storage.delete(r.slice(o,o+v));for(let o=0;o<n.length;o+=v)await this.state.storage.put(Object.fromEntries(n.slice(o,o+v)));for(const o of a)await this.state.storage.put(i.indexKey(o.scheduledFor,o.id),o.id),await this.armAlarmIfEarlier(o.scheduledFor)}async earliestPendingTime(){const e=(await this.state.storage.list({limit:1,prefix:"t:"})).entries().next();if(e.done)return;const[s]=e.value;return Number.parseInt(s.slice(2,s.indexOf(":",2)),10)}async rescheduleAlarm(){const t=await this.earliestPendingTime();if(t===void 0){await this.state.storage.deleteAlarm();return}Number.isFinite(t)&&await this.state.storage.setAlarm(t)}}export{B as DISPATCH_LEASE_MS,z as MAX_CONCURRENT_DISPATCHES,V as MAX_RETRY_ATTEMPTS,Q as MAX_SCHEDULED_FOR_MS,N as RETRY_BASE_DELAY_MS,i as SchedulerDO};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import u from"./createScheduler-BhkNvLvi.mjs";const i=t=>t?.at!==void 0?typeof t.at=="number"?t.at:t.at.getTime():Date.now()+(t?.delayMs??0),m=t=>{const r=u({instanceName:t.instanceName,jurisdiction:t.jurisdiction,namespace:t.namespace}),n=e=>({attempts:e.attempts??0,functionPath:e.functionPath??e.workflow??"",id:e.id,scheduledFor:e.scheduledFor});return{cancel:async e=>{const{cancelled:a}=await r.cancel(e);return a},deadLetter:{list:async()=>(await r.dead()).map(a=>n(a)),requeue:async e=>r.deadRetry(e)},list:async()=>(await r.list()).map(a=>n(a)),schedule:async(e,a,c)=>{const d=r.runAt,s=i(c);return{id:await d(s,e,a,{retry:c?.retry,shardKey:c?.shardKey}),scheduledFor:s}}}};export{m as createSchedulerHost};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as o}from"@lunora/errors";const c=(e,r)=>{if(r===void 0)return e;if(typeof e.jurisdiction!="function")throw new TypeError(`@lunora/scheduler: Durable Object namespace does not support jurisdiction("${r}") — update @cloudflare/workers-types or remove the jurisdiction option`);return e.jurisdiction(r)},d=e=>{if(!e.namespace)throw new o("INTERNAL","@lunora/scheduler: `namespace` (SchedulerDO binding) is required")},i=e=>{const r=c(e.namespace,e.jurisdiction);return r.get(r.idFromName(e.instanceName??"default"))},u=(e,r,n)=>{let s,t;try{({code:s,message:t}=JSON.parse(n).error??{})}catch{}throw typeof s=="string"&&s.length>0?new o(s,typeof t=="string"&&t.length>0?t:`@lunora/scheduler: SchedulerDO ${e} failed`,{status:r}):new o("INTERNAL",`@lunora/scheduler: SchedulerDO ${e} failed (${String(r)}): ${n}`)},a=async(e,r,n)=>{const t=await i(e).fetch(`https://scheduler.internal${r}`,n);return t.ok||u(r,t.status,await t.text()),await t.json()},h=async(e,r,n)=>a(e,r,{body:JSON.stringify(n),headers:{"content-type":"application/json"},method:"POST"}),p=async(e,r)=>a(e,r,{method:"GET"});export{d as a,h as c,p as g};
|