@molecule/api-scheduler-cloudflare 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,115 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,169 @@
1
+ <!--
2
+ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
+ Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
+ Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
+ To change this document, edit the module-level JSDoc in src/index.ts.
6
+ Generated: 2026-08-06T03:42:48.089Z
7
+ -->
8
+
9
+ # @molecule/api-scheduler-cloudflare
10
+
11
+ > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
12
+ > It is written to be read by coding agents as much as by people, and is generated from this
13
+ > package's source — edit `src/index.ts` JSDoc, not this file.
14
+
15
+ `@molecule/api-scheduler-cloudflare` — a `@molecule/api-scheduler` provider
16
+ for Cloudflare Workers, where **the platform owns the clock**.
17
+
18
+ `@molecule/api-scheduler-default` keeps tasks running with `setInterval`,
19
+ which needs a long-lived process. A Worker has none: it is an isolate that
20
+ exists for one invocation. So this provider registers tasks and runs them
21
+ when a **Cron Trigger** fires, via `runDueTasks()` from the Worker's
22
+ `scheduled()` handler. The application code that calls `schedule()` does not
23
+ change — only the bond wired in `bonds/`.
24
+
25
+ ## Quick Start
26
+
27
+ ```typescript
28
+ import { schedule, setProvider, start } from '@molecule/api-scheduler'
29
+ import { createProvider } from '@molecule/api-scheduler-cloudflare'
30
+
31
+ const scheduler = createProvider()
32
+ setProvider(scheduler)
33
+
34
+ schedule({
35
+ name: 'monitor-sweep',
36
+ intervalMs: 60000,
37
+ async handler() {
38
+ // ...
39
+ },
40
+ })
41
+
42
+ // REQUIRED, same as the default provider: nothing runs until start().
43
+ // Unlike it, start() begins no timers — a Worker has no process to hold one.
44
+ start()
45
+
46
+ // Then, from the Worker's scheduled() handler, wrapped in ctx.waitUntil():
47
+ // export default { async scheduled(event, env, ctx) {
48
+ // ctx.waitUntil(scheduler.runDueTasks())
49
+ // } }
50
+ // and in wrangler.toml: [triggers] crons = ["* * * * *"]
51
+ void scheduler.runDueTasks()
52
+ ```
53
+
54
+ ## Type
55
+
56
+ `provider`
57
+
58
+ ## Installation
59
+
60
+ ```bash
61
+ npm install @molecule/api-scheduler-cloudflare @molecule/api-bond @molecule/api-scheduler
62
+ ```
63
+
64
+ ## API
65
+
66
+ ### Interfaces
67
+
68
+ #### `CloudflareScheduler`
69
+
70
+ A scheduler provider whose tasks are driven by Cloudflare Cron Triggers
71
+ rather than by an in-process timer.
72
+
73
+ `start()` and `stop()` gate whether {@link CloudflareScheduler.runDueTasks}
74
+ will execute anything; they start no timers, because a Worker has no
75
+ long-lived process to hold one. Nothing runs until the Worker's `scheduled()`
76
+ handler calls `runDueTasks()`.
77
+
78
+ ```typescript
79
+ interface CloudflareScheduler extends SchedulerProvider {
80
+ /**
81
+ * Run the scheduled tasks. Call this from the Worker's `scheduled()` handler.
82
+ *
83
+ * Tasks run SEQUENTIALLY and every rejection is captured, so one failing task
84
+ * can neither abort the sweep nor reject the caller's promise — a Cron
85
+ * Trigger invocation that throws is retried by the platform, which would
86
+ * re-run the tasks that had already succeeded.
87
+ *
88
+ * @returns The status of every task after the run.
89
+ */
90
+ runDueTasks(): Promise<TaskStatus[]>
91
+ }
92
+ ```
93
+
94
+ #### `CloudflareSchedulerOptions`
95
+
96
+ Options for the Cloudflare Workers scheduler provider.
97
+
98
+ ```typescript
99
+ interface CloudflareSchedulerOptions {
100
+ /**
101
+ * Honour each task's `intervalMs` as a floor, using an in-isolate record of
102
+ * when it last ran.
103
+ *
104
+ * Defaults to `false`, and false is almost always what you want. A Worker
105
+ * isolate is short-lived and there may be many of them, so "when did this last
106
+ * run" is NOT reliably known — a task skipped on that basis may simply never
107
+ * run. With the default, every Cron Trigger runs every enabled task and the
108
+ * trigger schedule IS the schedule, which is the only interpretation the
109
+ * platform can actually guarantee.
110
+ *
111
+ * Set this to `true` only when a duplicate run is more expensive than a missed
112
+ * one, and even then treat it as best-effort.
113
+ */
114
+ respectIntervalWithinIsolate?: boolean
115
+ }
116
+ ```
117
+
118
+ ### Functions
119
+
120
+ #### `createProvider(options)`
121
+
122
+ Creates a Cloudflare Workers scheduler provider.
123
+
124
+ ```typescript
125
+ function createProvider(options?: CloudflareSchedulerOptions): CloudflareScheduler
126
+ ```
127
+
128
+ - `options` — Configuration options.
129
+
130
+ **Returns:** A SchedulerProvider driven by Cron Triggers.
131
+
132
+ ## Core Interface
133
+
134
+ Implements `@molecule/api-scheduler` interface.
135
+
136
+ ## Injection Notes
137
+
138
+ ### Requirements
139
+
140
+ Peer dependencies:
141
+
142
+ - `@molecule/api-scheduler` ^1.0.1
143
+ - `@molecule/api-bond` ^1.0.1
144
+
145
+ ### Runtime Dependencies
146
+
147
+ - `@molecule/api-bond`
148
+ - `@molecule/api-scheduler`
149
+
150
+ - **`intervalMs` is not honoured by default, and that is deliberate.** The
151
+ Cron Trigger cadence is the real schedule. A Worker isolate is short-lived
152
+ and there may be many, so "when did this task last run" is not reliably
153
+ known in-process; skipping a task on that basis can mean it never runs.
154
+ Set the interval you want in `wrangler.toml`, not in `intervalMs`. The
155
+ `respectIntervalWithinIsolate` option exists for the case where a duplicate
156
+ run costs more than a missed one, and even then it is best-effort.
157
+ - **Nothing runs until `start()` is called**, exactly as with the default
158
+ provider. `runDueTasks()` on a stopped scheduler logs a warning and returns
159
+ an empty array rather than silently doing nothing — a Cron Trigger firing
160
+ into a stopped scheduler otherwise looks identical to having no work.
161
+ - **`TaskStatus.nextRunAt` is always `null`.** Only the platform knows when
162
+ the next trigger fires, and this code cannot read the cron expression.
163
+ Computing a plausible-looking time would be a guess presented as a fact.
164
+ - **Status counters live in the isolate and do not persist.** They are useful
165
+ for the current invocation, not as a run history — persist to D1/KV if you
166
+ need that.
167
+ - **Wrap `runDueTasks()` in `ctx.waitUntil()`** so the invocation is not
168
+ cut short. The scheduled handler has a 15-minute budget; a sweep that
169
+ exceeds it is killed mid-task.
@@ -0,0 +1,69 @@
1
+ /**
2
+ * `@molecule/api-scheduler-cloudflare` — a `@molecule/api-scheduler` provider
3
+ * for Cloudflare Workers, where **the platform owns the clock**.
4
+ *
5
+ * `@molecule/api-scheduler-default` keeps tasks running with `setInterval`,
6
+ * which needs a long-lived process. A Worker has none: it is an isolate that
7
+ * exists for one invocation. So this provider registers tasks and runs them
8
+ * when a **Cron Trigger** fires, via `runDueTasks()` from the Worker's
9
+ * `scheduled()` handler. The application code that calls `schedule()` does not
10
+ * change — only the bond wired in `bonds/`.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * // bonds/scheduler-cloudflare.ts
15
+ * import { bond } from '@molecule/api-bond'
16
+ * import { createProvider } from '@molecule/api-scheduler-cloudflare'
17
+ *
18
+ * export const scheduler = createProvider()
19
+ * export function setupSchedulerCloudflare(): void {
20
+ * bond('scheduler', scheduler)
21
+ * }
22
+ * ```
23
+ *
24
+ * ```ts
25
+ * // worker.ts — the Cron Trigger entry point
26
+ * import { scheduler } from './bonds/scheduler-cloudflare.js'
27
+ * import { setupBonds } from './bonds/index.js'
28
+ *
29
+ * export default {
30
+ * async scheduled(_event, _env, ctx) {
31
+ * await setupBonds() // registers tasks via schedule() + start()
32
+ * ctx.waitUntil(scheduler.runDueTasks())
33
+ * },
34
+ * }
35
+ * ```
36
+ *
37
+ * ```toml
38
+ * # wrangler.toml
39
+ * [triggers]
40
+ * crons = ["*&#47;1 * * * *"] # the trigger schedule IS the schedule
41
+ * ```
42
+ *
43
+ * @remarks
44
+ * - **`intervalMs` is not honoured by default, and that is deliberate.** The
45
+ * Cron Trigger cadence is the real schedule. A Worker isolate is short-lived
46
+ * and there may be many, so "when did this task last run" is not reliably
47
+ * known in-process; skipping a task on that basis can mean it never runs.
48
+ * Set the interval you want in `wrangler.toml`, not in `intervalMs`. The
49
+ * `respectIntervalWithinIsolate` option exists for the case where a duplicate
50
+ * run costs more than a missed one, and even then it is best-effort.
51
+ * - **Nothing runs until `start()` is called**, exactly as with the default
52
+ * provider. `runDueTasks()` on a stopped scheduler logs a warning and returns
53
+ * an empty array rather than silently doing nothing — a Cron Trigger firing
54
+ * into a stopped scheduler otherwise looks identical to having no work.
55
+ * - **`TaskStatus.nextRunAt` is always `null`.** Only the platform knows when
56
+ * the next trigger fires, and this code cannot read the cron expression.
57
+ * Computing a plausible-looking time would be a guess presented as a fact.
58
+ * - **Status counters live in the isolate and do not persist.** They are useful
59
+ * for the current invocation, not as a run history — persist to D1/KV if you
60
+ * need that.
61
+ * - **Wrap `runDueTasks()` in `ctx.waitUntil()`** so the invocation is not
62
+ * cut short. The scheduled handler has a 15-minute budget; a sweep that
63
+ * exceeds it is killed mid-task.
64
+ *
65
+ * @module
66
+ */
67
+ export * from './provider.js';
68
+ export * from './types.js';
69
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiEG;AAEH,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * `@molecule/api-scheduler-cloudflare` — a `@molecule/api-scheduler` provider
3
+ * for Cloudflare Workers, where **the platform owns the clock**.
4
+ *
5
+ * `@molecule/api-scheduler-default` keeps tasks running with `setInterval`,
6
+ * which needs a long-lived process. A Worker has none: it is an isolate that
7
+ * exists for one invocation. So this provider registers tasks and runs them
8
+ * when a **Cron Trigger** fires, via `runDueTasks()` from the Worker's
9
+ * `scheduled()` handler. The application code that calls `schedule()` does not
10
+ * change — only the bond wired in `bonds/`.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * // bonds/scheduler-cloudflare.ts
15
+ * import { bond } from '@molecule/api-bond'
16
+ * import { createProvider } from '@molecule/api-scheduler-cloudflare'
17
+ *
18
+ * export const scheduler = createProvider()
19
+ * export function setupSchedulerCloudflare(): void {
20
+ * bond('scheduler', scheduler)
21
+ * }
22
+ * ```
23
+ *
24
+ * ```ts
25
+ * // worker.ts — the Cron Trigger entry point
26
+ * import { scheduler } from './bonds/scheduler-cloudflare.js'
27
+ * import { setupBonds } from './bonds/index.js'
28
+ *
29
+ * export default {
30
+ * async scheduled(_event, _env, ctx) {
31
+ * await setupBonds() // registers tasks via schedule() + start()
32
+ * ctx.waitUntil(scheduler.runDueTasks())
33
+ * },
34
+ * }
35
+ * ```
36
+ *
37
+ * ```toml
38
+ * # wrangler.toml
39
+ * [triggers]
40
+ * crons = ["*&#47;1 * * * *"] # the trigger schedule IS the schedule
41
+ * ```
42
+ *
43
+ * @remarks
44
+ * - **`intervalMs` is not honoured by default, and that is deliberate.** The
45
+ * Cron Trigger cadence is the real schedule. A Worker isolate is short-lived
46
+ * and there may be many, so "when did this task last run" is not reliably
47
+ * known in-process; skipping a task on that basis can mean it never runs.
48
+ * Set the interval you want in `wrangler.toml`, not in `intervalMs`. The
49
+ * `respectIntervalWithinIsolate` option exists for the case where a duplicate
50
+ * run costs more than a missed one, and even then it is best-effort.
51
+ * - **Nothing runs until `start()` is called**, exactly as with the default
52
+ * provider. `runDueTasks()` on a stopped scheduler logs a warning and returns
53
+ * an empty array rather than silently doing nothing — a Cron Trigger firing
54
+ * into a stopped scheduler otherwise looks identical to having no work.
55
+ * - **`TaskStatus.nextRunAt` is always `null`.** Only the platform knows when
56
+ * the next trigger fires, and this code cannot read the cron expression.
57
+ * Computing a plausible-looking time would be a guess presented as a fact.
58
+ * - **Status counters live in the isolate and do not persist.** They are useful
59
+ * for the current invocation, not as a run history — persist to D1/KV if you
60
+ * need that.
61
+ * - **Wrap `runDueTasks()` in `ctx.waitUntil()`** so the invocation is not
62
+ * cut short. The scheduled handler has a 15-minute budget; a sweep that
63
+ * exceeds it is killed mid-task.
64
+ *
65
+ * @module
66
+ */
67
+ export * from './provider.js';
68
+ export * from './types.js';
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Cloudflare Workers scheduler provider — the platform owns the clock.
3
+ *
4
+ * @module
5
+ */
6
+ import type { SchedulerProvider, TaskStatus } from '@molecule/api-scheduler';
7
+ import type { CloudflareSchedulerOptions } from './types.js';
8
+ /**
9
+ * A scheduler provider whose tasks are driven by Cloudflare Cron Triggers
10
+ * rather than by an in-process timer.
11
+ *
12
+ * `start()` and `stop()` gate whether {@link CloudflareScheduler.runDueTasks}
13
+ * will execute anything; they start no timers, because a Worker has no
14
+ * long-lived process to hold one. Nothing runs until the Worker's `scheduled()`
15
+ * handler calls `runDueTasks()`.
16
+ */
17
+ export interface CloudflareScheduler extends SchedulerProvider {
18
+ /**
19
+ * Run the scheduled tasks. Call this from the Worker's `scheduled()` handler.
20
+ *
21
+ * Tasks run SEQUENTIALLY and every rejection is captured, so one failing task
22
+ * can neither abort the sweep nor reject the caller's promise — a Cron
23
+ * Trigger invocation that throws is retried by the platform, which would
24
+ * re-run the tasks that had already succeeded.
25
+ *
26
+ * @returns The status of every task after the run.
27
+ */
28
+ runDueTasks(): Promise<TaskStatus[]>;
29
+ }
30
+ /**
31
+ * Creates a Cloudflare Workers scheduler provider.
32
+ *
33
+ * @param options - Configuration options.
34
+ * @returns A SchedulerProvider driven by Cron Triggers.
35
+ */
36
+ export declare const createProvider: (options?: CloudflareSchedulerOptions) => CloudflareScheduler;
37
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAiB,iBAAiB,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAA;AAE3F,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAA;AAa5D;;;;;;;;GAQG;AACH,MAAM,WAAW,mBAAoB,SAAQ,iBAAiB;IAC5D;;;;;;;;;OASG;IACH,WAAW,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC,CAAA;CACrC;AAED;;;;;GAKG;AACH,eAAO,MAAM,cAAc,GAAI,UAAU,0BAA0B,KAAG,mBAkGrE,CAAA"}
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Cloudflare Workers scheduler provider — the platform owns the clock.
3
+ *
4
+ * @module
5
+ */
6
+ import { getLogger } from '@molecule/api-bond';
7
+ /**
8
+ * Creates a Cloudflare Workers scheduler provider.
9
+ *
10
+ * @param options - Configuration options.
11
+ * @returns A SchedulerProvider driven by Cron Triggers.
12
+ */
13
+ export const createProvider = (options) => {
14
+ const respectInterval = options?.respectIntervalWithinIsolate ?? false;
15
+ const tasks = new Map();
16
+ const logger = getLogger();
17
+ let started = false;
18
+ const toStatus = (entry) => ({
19
+ name: entry.task.name,
20
+ lastRunAt: entry.lastRunAt,
21
+ // The platform decides when the next run happens, and this code cannot read
22
+ // the Worker's cron expression. Reporting a computed time would be a guess
23
+ // presented as fact, so this is null by design.
24
+ nextRunAt: null,
25
+ isRunning: entry.isRunning,
26
+ lastError: entry.lastError,
27
+ durationMs: entry.durationMs,
28
+ totalRuns: entry.totalRuns,
29
+ totalFailures: entry.totalFailures,
30
+ lastSuccessAt: entry.lastSuccessAt,
31
+ enabled: entry.task.enabled !== false,
32
+ });
33
+ const runTask = async (entry) => {
34
+ if (entry.isRunning) {
35
+ logger.warn(`Scheduler task '${entry.task.name}' skipped: previous execution still running`);
36
+ return;
37
+ }
38
+ entry.isRunning = true;
39
+ const startTime = Date.now();
40
+ try {
41
+ await entry.task.handler();
42
+ entry.lastError = null;
43
+ entry.lastSuccessAt = new Date().toISOString();
44
+ }
45
+ catch (error) {
46
+ entry.lastError = error instanceof Error ? error.message : String(error);
47
+ logger.error(`Scheduler task '${entry.task.name}' failed: ${entry.lastError}`);
48
+ entry.totalFailures++;
49
+ }
50
+ finally {
51
+ entry.isRunning = false;
52
+ entry.durationMs = Date.now() - startTime;
53
+ entry.totalRuns++;
54
+ entry.lastRunAt = new Date().toISOString();
55
+ }
56
+ };
57
+ return {
58
+ schedule(task) {
59
+ tasks.set(task.name, {
60
+ task,
61
+ lastRunAt: null,
62
+ isRunning: false,
63
+ lastError: null,
64
+ durationMs: null,
65
+ totalRuns: 0,
66
+ totalFailures: 0,
67
+ lastSuccessAt: null,
68
+ });
69
+ },
70
+ unschedule(name) {
71
+ return tasks.delete(name);
72
+ },
73
+ getStatus(name) {
74
+ const entry = tasks.get(name);
75
+ return entry ? toStatus(entry) : null;
76
+ },
77
+ getAllStatuses() {
78
+ return [...tasks.values()].map(toStatus);
79
+ },
80
+ start() {
81
+ started = true;
82
+ },
83
+ stop() {
84
+ started = false;
85
+ },
86
+ async runDueTasks() {
87
+ if (!started) {
88
+ // Loud: a Cron Trigger that fires into a stopped scheduler does nothing,
89
+ // and silence here looks identical to "there was no work to do".
90
+ logger.warn('Cloudflare scheduler: runDueTasks() called before start(); nothing ran');
91
+ return [];
92
+ }
93
+ const now = Date.now();
94
+ for (const entry of tasks.values()) {
95
+ if (entry.task.enabled === false)
96
+ continue;
97
+ if (respectInterval && entry.lastRunAt) {
98
+ if (now - new Date(entry.lastRunAt).getTime() < entry.task.intervalMs)
99
+ continue;
100
+ }
101
+ await runTask(entry);
102
+ }
103
+ return [...tasks.values()].map(toStatus);
104
+ },
105
+ };
106
+ };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Type definitions for the Cloudflare Workers scheduler provider.
3
+ *
4
+ * @module
5
+ */
6
+ /**
7
+ * Options for the Cloudflare Workers scheduler provider.
8
+ */
9
+ export interface CloudflareSchedulerOptions {
10
+ /**
11
+ * Honour each task's `intervalMs` as a floor, using an in-isolate record of
12
+ * when it last ran.
13
+ *
14
+ * Defaults to `false`, and false is almost always what you want. A Worker
15
+ * isolate is short-lived and there may be many of them, so "when did this last
16
+ * run" is NOT reliably known — a task skipped on that basis may simply never
17
+ * run. With the default, every Cron Trigger runs every enabled task and the
18
+ * trigger schedule IS the schedule, which is the only interpretation the
19
+ * platform can actually guarantee.
20
+ *
21
+ * Set this to `true` only when a duplicate run is more expensive than a missed
22
+ * one, and even then treat it as best-effort.
23
+ */
24
+ respectIntervalWithinIsolate?: boolean;
25
+ }
26
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;GAEG;AACH,MAAM,WAAW,0BAA0B;IACzC;;;;;;;;;;;;;OAaG;IACH,4BAA4B,CAAC,EAAE,OAAO,CAAA;CACvC"}
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Type definitions for the Cloudflare Workers scheduler provider.
3
+ *
4
+ * @module
5
+ */
6
+ export {};
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@molecule/api-scheduler-cloudflare",
3
+ "version": "1.0.2",
4
+ "description": "Scheduler provider for Cloudflare Workers Cron Triggers — the platform owns the clock, so tasks run from the scheduled() handler instead of an in-process timer.",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md"
22
+ ],
23
+ "keywords": [
24
+ "molecule",
25
+ "scheduler",
26
+ "cloudflare"
27
+ ],
28
+ "license": "Apache-2.0",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/molecule-dev/molecule.git",
32
+ "directory": "packages/api/bonds/scheduler/cloudflare"
33
+ },
34
+ "devDependencies": {
35
+ "@molecule/api-bond": "1.0.1",
36
+ "@molecule/api-scheduler": "1.0.1",
37
+ "@types/node": "26.1.2",
38
+ "typescript": "6.0.3",
39
+ "vitest": "4.1.10"
40
+ },
41
+ "peerDependencies": {
42
+ "@molecule/api-scheduler": "^1.0.1",
43
+ "@molecule/api-bond": "^1.0.1"
44
+ }
45
+ }