@gnldev/scheduler 0.1.0

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,201 @@
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
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Karaca Yılmaz (https://gnl.dev)
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,110 @@
1
+ # @gnldev/scheduler
2
+
3
+ Cron, interval and one-shot triggers for durable workflows. Several workers can poll the same
4
+ schedule: a run-lock picks one winner per fire and every write to the trigger's state is CAS-fenced,
5
+ so a slot is never double-advanced or rolled back — see [the lock section](#lock-ttl-and-what-once-covers)
6
+ for what that does and does not promise about the workflow body.
7
+
8
+ ## Install
9
+
10
+ > Install: `pnpm add @gnldev/scheduler` — or use it from a [repo clone](https://github.com/Karaca7/gnldev): `pnpm install && pnpm -r build`.
11
+
12
+ ```bash
13
+ npm i @gnldev/scheduler
14
+ ```
15
+
16
+ ## Schedule something
17
+
18
+ ```ts
19
+ import { scheduleWorkflow, createScheduler, pollScheduler } from '@gnldev/scheduler';
20
+
21
+ await scheduleWorkflow(journal, {
22
+ id: 'nightly-invoices',
23
+ cron: '0 3 * * *',
24
+ name: 'invoices', // the workflow name handed to runner.runWorkflow
25
+ });
26
+
27
+ // in your worker loop. The runner is an object with runWorkflow — createGnl() is one.
28
+ setInterval(() => pollScheduler(journal, gnl), 30_000);
29
+ ```
30
+
31
+ ## Lock TTL and what "once" covers
32
+
33
+ Two workers polling at the same moment do not both fire the trigger: `acquireRunLock` picks one
34
+ winner on `<runId>:fire`, and every write to the trigger's state is a CAS against the record that
35
+ winner read when the fire began. `fireCount`, `nextRunAt` and `attempts` can therefore only be advanced by the poller that
36
+ actually owns the fire — a poller that lost the lock cannot roll them back or resurrect a stale
37
+ attempt count. The property comes from the journal rather than from careful timing.
38
+
39
+ `lockTtlMs` (default **60 s**, on both `pollScheduler` and `createScheduler`) is how long that lock is
40
+ held. It is renewed every `lockTtlMs / 3` for as long as the workflow is in flight, so a run that
41
+ takes longer than the TTL keeps its lock. That renewal is not cosmetic: the TTL used to be fixed and
42
+ never renewed, so *any* workflow running longer than 60 s let its lock expire and a second poller
43
+ re-fired the same trigger. Raise `lockTtlMs` if your triggers are long and your journal is slow;
44
+ lowering it makes a genuinely dead worker's fire reclaimable sooner.
45
+
46
+ **Known limit — the fencing covers the state write, not the execution.** A `renew` that fails is
47
+ logged and nothing else; `pollScheduler` does not abort the workflow it already started. So if the
48
+ lock does expire anyway — a stalled or paused process, a clock jump, a journal outage that outlasts
49
+ the TTL — a second poller can take the fire over and call `runner.runWorkflow` with the **same**
50
+ `runId` while the first is still inside it. The CAS then discards the loser's state write, so the
51
+ schedule stays correct; it does not undo what the loser's workflow did. This is measured, not
52
+ theoretical: in `test/scheduler-lock-fence.test.ts` both pollers run `sched:<id>:<fireCount>`.
53
+
54
+ What keeps that from becoming a duplicated side effect is the run, not the scheduler. Because both
55
+ attempts share one `runId`, each workflow step reads its output from the journal first and only the
56
+ first writer's result is kept (`claim`), so the two attempts converge on one recorded result — and a
57
+ step built on `runDurable`/`durableTool` gets the real [at-most-once guarantee](../durable/README.md#what-never-charged-twice-actually-means). A plain step's body, however, still
58
+ executes in both pollers. Read the guarantee as *"the schedule advances once and the journal records
59
+ one result"*, not as *"two workers can never run the same job at the same time"*, and write steps that
60
+ touch the outside world to be idempotent — the same rule `@gnldev/queue` and `@gnldev/events` state.
61
+
62
+ ### The fire lock is not the run's lock
63
+
64
+ `<runId>:fire`, not `<runId>`, and the distinction is load-bearing. The two locks answer different
65
+ questions — *"is another poller firing this occurrence?"* versus *"is this run executing anywhere?"* —
66
+ and for a while they were the same key. That was invisible until a run started taking its own lock:
67
+ under `preset: 'critical'`, `runWorkflow` locks `<runId>` too, so the poller was refusing its own run.
68
+ Measured in production on a five-minute health trigger — five polls, five `RunBusyError`s, `status:
69
+ 'failed'`, and not one step ever executed. Nothing raced; it simply could not work. The two locks now
70
+ nest instead of competing.
71
+
72
+ One upgrade note: during a rolling deploy across this change, an old poller and a new one hold
73
+ *different* fire-lock keys for the same occurrence, so both can start the fire. Under the `critical`
74
+ preset the run's own lock refuses the second executor; without it, a side-effecting workflow can run
75
+ once per poller in that window. If that matters to the workflow, drain the pollers over the upgrade.
76
+
77
+ ### A busy run is a deferral, not an attempt
78
+
79
+ If `runWorkflow` refuses at lock acquisition (`RunBusyError` with `atLockAcquisition` — somebody else
80
+ is already running this exact `runId`), the trigger is **deferred by `retryMs`**: `attempts` is not
81
+ incremented, `status` stays `'pending'`, nothing is written to `sched:fail:<id>`, and `PollResult.skipped`
82
+ counts it. Nothing was tried and nothing went wrong, so spending retry budget on it is how a busy
83
+ minute turns into a permanently dead trigger.
84
+
85
+ Deferrals are counted in `sched:busy-skip:<id>` and surfaced on `listTriggers()` as `deferrals` /
86
+ `lastDeferralAt`, because a deferred trigger otherwise reads exactly like a healthy one. If that
87
+ number climbs while `fireCount` does not, the trigger is being refused, not waiting. A **mid-flight**
88
+ `RunBusyError` (this poller got in and was fenced out later) is still an ordinary failure — something
89
+ did happen there.
90
+
91
+ ## Time is data
92
+
93
+ A trigger's next fire time is **resolved and then frozen** into the journal, not recomputed on each
94
+ poll. A worker that wakes up late fires the run it owed rather than silently skipping it, and a
95
+ replay sees the same schedule the original run saw.
96
+
97
+ ## Exports
98
+
99
+ | Export | What it is |
100
+ |---|---|
101
+ | `scheduleWorkflow` | Registers a cron / interval / `at` trigger |
102
+ | `pollScheduler` | Fires whatever is due; call it from a loop or a cron container |
103
+ | `listTriggers` | Everything currently registered |
104
+ | `createScheduler` | The stateful wrapper, if you would rather hold an object than call functions |
105
+ | `nextCronTime`, `parseField` | The cron arithmetic, exported for testing and for building your own UI |
106
+ | `createWorkflowWaker` | Wakes a suspended workflow when its sleep or wait elapses |
107
+
108
+ ## License
109
+
110
+ Apache-2.0 — see [LICENSE](./LICENSE).
package/dist/cron.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /** Converts a cron field into the set of allowed values within [min,max]. */
2
+ export declare function parseField(field: string, min: number, max: number): Set<number>;
3
+ /**
4
+ * Returns the first cron match (epoch ms, minute boundary) AFTER the `after` (epoch ms) time.
5
+ * 5 fields: minute hour day-of-month month day-of-week (0=Sunday). UTC. Minute-by-minute scan, 366-day cap.
6
+ */
7
+ export declare function nextCronTime(expr: string, after: number): number;
package/dist/cron.js ADDED
@@ -0,0 +1,66 @@
1
+ // Minimal 5-field cron (minute resolution, UTC). Supports '*', list ',', range '-', step '/'.
2
+ // dom/dow POSIX OR semantics: if both are restricted, "day-of-month OR day-of-week"; if one is '*', the other decides.
3
+ /** Converts a cron field into the set of allowed values within [min,max]. */
4
+ export function parseField(field, min, max) {
5
+ const out = new Set();
6
+ for (const part of field.split(',')) {
7
+ const [rangeRaw, stepRaw] = part.split('/');
8
+ const step = stepRaw !== undefined ? parseInt(stepRaw, 10) : 1;
9
+ if (!Number.isFinite(step) || step < 1)
10
+ throw new Error(`cron: invalid step '${part}'`);
11
+ let lo;
12
+ let hi;
13
+ if (rangeRaw === '*' || rangeRaw === '') {
14
+ lo = min;
15
+ hi = max;
16
+ }
17
+ else if (rangeRaw.includes('-')) {
18
+ const [a, b] = rangeRaw.split('-').map((x) => parseInt(x, 10));
19
+ lo = a;
20
+ hi = b;
21
+ }
22
+ else {
23
+ lo = hi = parseInt(rangeRaw, 10);
24
+ }
25
+ if (!Number.isFinite(lo) || !Number.isFinite(hi) || lo < min || hi > max || lo > hi) {
26
+ throw new Error(`cron: invalid range '${part}' (expected ${min}-${max})`);
27
+ }
28
+ for (let v = lo; v <= hi; v += step)
29
+ out.add(v);
30
+ }
31
+ return out;
32
+ }
33
+ /**
34
+ * Returns the first cron match (epoch ms, minute boundary) AFTER the `after` (epoch ms) time.
35
+ * 5 fields: minute hour day-of-month month day-of-week (0=Sunday). UTC. Minute-by-minute scan, 366-day cap.
36
+ */
37
+ export function nextCronTime(expr, after) {
38
+ const fields = expr.trim().split(/\s+/);
39
+ if (fields.length !== 5)
40
+ throw new Error(`cron expects 5 fields (min hour day month weekday): '${expr}'`);
41
+ const min = parseField(fields[0], 0, 59);
42
+ const hour = parseField(fields[1], 0, 23);
43
+ const dom = parseField(fields[2], 1, 31);
44
+ const mon = parseField(fields[3], 1, 12);
45
+ const dow = parseField(fields[4], 0, 6);
46
+ const domRestricted = fields[2] !== '*';
47
+ const dowRestricted = fields[4] !== '*';
48
+ let t = Math.ceil((after + 1) / 60000) * 60000; // next minute boundary
49
+ const limit = 366 * 24 * 60;
50
+ for (let i = 0; i < limit; i++, t += 60000) {
51
+ const d = new Date(t);
52
+ if (!min.has(d.getUTCMinutes()))
53
+ continue;
54
+ if (!hour.has(d.getUTCHours()))
55
+ continue;
56
+ if (!mon.has(d.getUTCMonth() + 1))
57
+ continue;
58
+ const domOk = dom.has(d.getUTCDate());
59
+ const dowOk = dow.has(d.getUTCDay());
60
+ const dayOk = domRestricted && dowRestricted ? domOk || dowOk : domOk && dowOk;
61
+ if (dayOk)
62
+ return t;
63
+ }
64
+ throw new Error(`cron: no match within 1 year: '${expr}'`);
65
+ }
66
+ //# sourceMappingURL=cron.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cron.js","sourceRoot":"","sources":["../src/cron.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,uHAAuH;AAEvH,6EAA6E;AAC7E,MAAM,UAAU,UAAU,CAAC,KAAa,EAAE,GAAW,EAAE,GAAW;IAChE,MAAM,GAAG,GAAG,IAAI,GAAG,EAAU,CAAC;IAC9B,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACpC,MAAM,CAAC,QAAQ,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC5C,MAAM,IAAI,GAAG,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC/D,IAAI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CAAC,CAAC,CAAC,aAAa,EAAE,CAAC;YAAE,SAAS;QAC1C,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;YAAE,SAAS;QACzC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC;YAAE,SAAS;QAC5C,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC;QACtC,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC;QACrC,MAAM,KAAK,GAAG,aAAa,IAAI,aAAa,CAAC,CAAC,CAAC,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,KAAK,CAAC;QAC/E,IAAI,KAAK;YAAE,OAAO,CAAC,CAAC;IACtB,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,kCAAkC,IAAI,GAAG,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["// Minimal 5-field cron (minute resolution, UTC). Supports '*', list ',', range '-', step '/'.\n// dom/dow POSIX OR semantics: if both are restricted, \"day-of-month OR day-of-week\"; if one is '*', the other decides.\n\n/** Converts a cron field into the set of allowed values within [min,max]. */\nexport function parseField(field: string, min: number, max: number): Set<number> {\n const out = new Set<number>();\n for (const part of field.split(',')) {\n const [rangeRaw, stepRaw] = part.split('/');\n const step = stepRaw !== undefined ? parseInt(stepRaw, 10) : 1;\n if (!Number.isFinite(step) || step < 1) throw new Error(`cron: invalid step '${part}'`);\n let lo: number;\n let hi: number;\n if (rangeRaw === '*' || rangeRaw === '') {\n lo = min;\n hi = max;\n } else if (rangeRaw.includes('-')) {\n const [a, b] = rangeRaw.split('-').map((x) => parseInt(x, 10));\n lo = a!;\n hi = b!;\n } else {\n lo = hi = parseInt(rangeRaw, 10);\n }\n if (!Number.isFinite(lo) || !Number.isFinite(hi) || lo < min || hi > max || lo > hi) {\n throw new Error(`cron: invalid range '${part}' (expected ${min}-${max})`);\n }\n for (let v = lo; v <= hi; v += step) out.add(v);\n }\n return out;\n}\n\n/**\n * Returns the first cron match (epoch ms, minute boundary) AFTER the `after` (epoch ms) time.\n * 5 fields: minute hour day-of-month month day-of-week (0=Sunday). UTC. Minute-by-minute scan, 366-day cap.\n */\nexport function nextCronTime(expr: string, after: number): number {\n const fields = expr.trim().split(/\\s+/);\n if (fields.length !== 5) throw new Error(`cron expects 5 fields (min hour day month weekday): '${expr}'`);\n const min = parseField(fields[0]!, 0, 59);\n const hour = parseField(fields[1]!, 0, 23);\n const dom = parseField(fields[2]!, 1, 31);\n const mon = parseField(fields[3]!, 1, 12);\n const dow = parseField(fields[4]!, 0, 6);\n const domRestricted = fields[2] !== '*';\n const dowRestricted = fields[4] !== '*';\n\n let t = Math.ceil((after + 1) / 60000) * 60000; // next minute boundary\n const limit = 366 * 24 * 60;\n for (let i = 0; i < limit; i++, t += 60000) {\n const d = new Date(t);\n if (!min.has(d.getUTCMinutes())) continue;\n if (!hour.has(d.getUTCHours())) continue;\n if (!mon.has(d.getUTCMonth() + 1)) continue;\n const domOk = dom.has(d.getUTCDate());\n const dowOk = dow.has(d.getUTCDay());\n const dayOk = domRestricted && dowRestricted ? domOk || dowOk : domOk && dowOk;\n if (dayOk) return t;\n }\n throw new Error(`cron: no match within 1 year: '${expr}'`);\n}\n"]}
@@ -0,0 +1,147 @@
1
+ import type { Journal } from '@gnldev/durable';
2
+ export { nextCronTime, parseField } from './cron.js';
3
+ export { createWorkflowWaker } from './workflow-waker.js';
4
+ export type { WorkflowWaker, WorkflowWakerOptions, WorkflowWakerTickResult } from './workflow-waker.js';
5
+ /** Structurally compatible with what createGnl returns — no hard dependency. */
6
+ export interface WorkflowRunner {
7
+ runWorkflow(name: string, input: unknown, opts?: {
8
+ runId?: string;
9
+ }): Promise<{
10
+ runId: string;
11
+ suspended?: boolean;
12
+ output?: unknown;
13
+ }>;
14
+ }
15
+ export interface ScheduleSpec {
16
+ /** Trigger id (idempotent record; `name` is used if not given). */
17
+ id?: string;
18
+ /** Workflow name to run (passed to runner.runWorkflow). */
19
+ name: string;
20
+ input?: unknown;
21
+ /** Absolute time (epoch ms) — one-shot. */
22
+ at?: number;
23
+ /** Period (ms) — repeats every interval. */
24
+ every?: number;
25
+ /** 5-field cron (UTC, minute resolution) — repeats on every match. */
26
+ cron?: string;
27
+ /** Max attempts on failure (default 5). */
28
+ maxAttempts?: number;
29
+ /**
30
+ * Policy for missed (misfire) fires — only meaningful for every/cron:
31
+ * 'skip' (default) — skip missed fires, jump to the next slot aligned to the planned grid (no drift accumulates).
32
+ * 'catchup' — fire each missed occurrence in sequence (one per poll), none are skipped.
33
+ */
34
+ misfire?: MisfirePolicy;
35
+ }
36
+ export type Kind = 'at' | 'every' | 'cron';
37
+ export type MisfirePolicy = 'skip' | 'catchup';
38
+ /**
39
+ * 1.4: optional budget/quota hook — called BEFORE the trigger starts (before runner.runWorkflow is
40
+ * CALLED). Throws on overage (typically `@gnldev/durable`'s `assertBudget` — `BudgetExceededError`);
41
+ * `pollScheduler` does NOT RUN this trigger (skip + records/logs to `sched:budget-skip:<id>`,
42
+ * `out.skipped` increments), state is DEFERRED to retry after `retryMs` but `attempts` DOES NOT
43
+ * increase (a budget overage isn't the workflow's fault → doesn't count toward maxAttempts, `status`
44
+ * stays 'pending'). IF NOT GIVEN (default) behavior is UNCHANGED — no quota check (backward compat).
45
+ * Typical host usage:
46
+ * budgetGuard: () => assertBudget(journal, { orgId, fallback })
47
+ * Kept simple: the scheduler does NOT EMBED quota logic itself, the host injects it (same pattern as limits/guard).
48
+ */
49
+ export type BudgetGuard = (ctx: {
50
+ triggerId: string;
51
+ workflowName: string;
52
+ input: unknown;
53
+ now: number;
54
+ }) => Promise<unknown> | unknown;
55
+ /** Schedules a workflow (at | every | cron). Idempotent: repeating with the same id = no-op. Returns the id. */
56
+ export declare function scheduleWorkflow(journal: Journal, spec: ScheduleSpec, now?: number): Promise<string>;
57
+ export interface PollResult {
58
+ fired: number;
59
+ rescheduled: number;
60
+ failed: number;
61
+ /**
62
+ * Triggers that were NOT RUN and are NOT a failure — the three deferral reasons, counted together
63
+ * because they mean the same thing to a caller ("nothing happened, come back later"):
64
+ * - another poller holds the fire lock for this occurrence (no record; the lock IS the record),
65
+ * - `budgetGuard` was given and threw on overage (`sched:budget-skip:<id>`),
66
+ * - the run is already in flight elsewhere (`sched:busy-skip:<id>`).
67
+ * None of them consume an attempt. Without a guard and without contention this stays 0.
68
+ */
69
+ skipped: number;
70
+ }
71
+ /**
72
+ * Fires triggers that are due ('pending' && now≥nextRunAt). Double-firing is prevented via the run-lock;
73
+ * the real exactly-once guarantee comes from the durable workflow run (per-fireCount runId).
74
+ *
75
+ * Y2: the lock is kept alive by a heartbeat while the workflow runs (`lockTtlMs`, default 60s, renewed
76
+ * every ttl/3) — a long workflow no longer lets a second poller take the fire over. And EVERY state
77
+ * write is a CAS (`putIfMatch`) against the state read at the start of the fire, so even if a takeover
78
+ * does happen the late poller cannot write its stale result back.
79
+ */
80
+ export declare function pollScheduler(journal: Journal, runner: WorkflowRunner, now?: number, opts?: {
81
+ owner?: string;
82
+ retryMs?: number;
83
+ budgetGuard?: BudgetGuard;
84
+ lockTtlMs?: number;
85
+ }): Promise<PollResult>;
86
+ /** Introspection view of a single trigger (for the Studio Scheduler view). */
87
+ export interface TriggerInfo {
88
+ id: string;
89
+ name: string;
90
+ kind: Kind;
91
+ /** kind='at' → absolute time (epoch ms); kind='every' → period (ms); kind='cron' → 5-field cron expression. */
92
+ value: number | string;
93
+ input?: unknown;
94
+ /** Next (planned) fire time, epoch ms — if in the past, the trigger is due/overdue. */
95
+ nextRunAt: number;
96
+ attempts: number;
97
+ maxAttempts: number;
98
+ fireCount: number;
99
+ status: 'pending' | 'done' | 'failed';
100
+ misfire: MisfirePolicy;
101
+ /** Last error if status='failed' (if any, from `sched:fail:<id>`). */
102
+ lastError?: string;
103
+ lastErrorAt?: number;
104
+ /**
105
+ * How many times this trigger was DEFERRED because the run was already in flight elsewhere
106
+ * (`sched:busy-skip:<id>`, lifetime total). Absent when it has never happened.
107
+ *
108
+ * On this list a deferred trigger is otherwise indistinguishable from a healthy one — 'pending',
109
+ * with a nextRunAt in the near future, forever. That is the shape of a trigger that has not run in
110
+ * a week and looks fine, so the count is here rather than only in the journal. Compare it against
111
+ * `fireCount`: a number that keeps climbing while fireCount does not is a trigger that is being
112
+ * refused, not one that is waiting.
113
+ */
114
+ deferrals?: number;
115
+ lastDeferralAt?: number;
116
+ }
117
+ /**
118
+ * READ-ONLY trigger listing from the journal, WITHOUT needing a scheduler INSTANCE or a runner (for
119
+ * Studio introspection). Reads the SAME `sched:def:`/`sched:state:` keys (+ `sched:fail:` for 'failed')
120
+ * as `pollScheduler`; does NOT change any state, does not take a lock, does not run a workflow. Returns
121
+ * results sorted alphabetically by id (stable list order).
122
+ */
123
+ export declare function listTriggers(journal: Journal): Promise<TriggerInfo[]>;
124
+ export interface Scheduler {
125
+ poll(now?: number): Promise<PollResult>;
126
+ start(): void;
127
+ stop(): void;
128
+ }
129
+ /**
130
+ * Scheduler that manages the poll loop (a self-rescheduling setTimeout chain) — the same pattern as
131
+ * @gnldev/queue's createWorker. `backoff` (default OFF — timing is the scheduler's core contract, see the
132
+ * trade-off below): IF ENABLED, when a poll fires NO triggers at all (`fired === 0`) the next poll
133
+ * interval grows ×2 (cap: `maxPollMs ?? pollMs*32`) → prevents tens of thousands of empty queries per
134
+ * second (poll storm) on an empty schedule table; the interval resets to `pollMs` once a trigger fires.
135
+ * Trade-off: `backoff: true` cuts idle poll load by ~32x but can delay a trigger that becomes due after
136
+ * a quiet period by up to `maxPollMs` — for timing-critical use (e.g. minute-level cron) the default
137
+ * should stay OFF; only enable it for deployments with many idle-poller instances that can tolerate delay.
138
+ */
139
+ export declare function createScheduler(journal: Journal, runner: WorkflowRunner, opts?: {
140
+ pollMs?: number;
141
+ owner?: string;
142
+ retryMs?: number;
143
+ backoff?: boolean;
144
+ maxPollMs?: number;
145
+ budgetGuard?: BudgetGuard;
146
+ lockTtlMs?: number;
147
+ }): Scheduler;