@alma-harness/schedule 0.3.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # @alma-harness/schedule
2
+
3
+ The clock of [Alma](https://github.com/FabioFernandesCarneiro/alma), as a
4
+ tick: what is due, and the call an external scheduler makes to run it. No
5
+ process is kept alive (spec: clock-tick).
6
+
7
+ > **Status: 0.2.0 on npm, pre-1.0.** The API is still moving; see the
8
+ > [roadmap](../../docs/architecture.md#12-adoption-roadmap) for where it stands.
9
+
10
+ ## What it owns
11
+
12
+ - `createSchedule({ routines, runs, runner })` — `tick({ now? })` reads
13
+ the routine store, decides what is due, runs it through the routine
14
+ runner with the FIRE's instant as the run id, and reports `{ at, due,
15
+ runs, errors }`. `plan(now?)` answers without running. `runner` may be a
16
+ resolver, `(routine) => RoutineRunner`, for a deployment with an agent
17
+ per tenant — `list` crosses every scope. A routine that cannot be
18
+ planned (a zone typo, a bad cron) is one entry in `errors`; the others
19
+ run.
20
+ - `register` / `cancel` — register THROUGH the schedule: it asks the runner
21
+ to validate and reads the schedule once, so what the tick could not run
22
+ is refused at registration, not at 8h with nobody watching.
23
+ - What is due: the latest fire at or before now — a cron's previous
24
+ occurrence in its `tz` (UTC when absent), `every` anchored on the
25
+ routine's registration, `at` once — when it is later than the routine's
26
+ last run. A job routine whose submission is still open is collected on
27
+ every tick. Missed fires are not replayed: after downtime a daily routine
28
+ runs once.
29
+ - `latestFire`, `validateSchedule` — the pure halves, exported.
30
+
31
+ ## Wiring
32
+
33
+ One endpoint the scheduler calls on a cadence. Cloud Scheduler every
34
+ minute against a Cloud Run service at zero minimum instances is the shape
35
+ it was written for; anything that can call a URL on a cron is the clock.
36
+
37
+ ```ts
38
+ import { createSchedule } from "@alma-harness/schedule";
39
+
40
+ const schedule = createSchedule({ routines, runs, runner: (routine) => runnerFor(routine.scope) });
41
+ await schedule.register(briefing);
42
+
43
+ // Node's http, Hono, Express — the product's choice. A shared secret, or
44
+ // the platform's OIDC, decides who may tick.
45
+ app.post("/tick", async (req, res) => {
46
+ if (req.headers["x-tick-secret"] !== process.env.TICK_SECRET) return res.status(401).end();
47
+ res.json(await schedule.tick());
48
+ });
49
+ ```
50
+
51
+ A tick retried by the scheduler runs nothing twice: the runner treats the
52
+ same run id as one run (spec: routine-runner), and the run store is in
53
+ Postgres (spec: postgres-routine-runs), so a fresh container reads the same
54
+ state the last one wrote. A turn may take tens of seconds: the host's
55
+ request timeout must allow it (Cloud Run does). A container killed
56
+ mid-turn leaves a lease that expires on its own and a claim the next fire
57
+ re-runs (spec 030).
58
+
59
+ ## What it must never do
60
+
61
+ - Keep a timer. The clock is outside; this package only answers it.
62
+ - Replay missed fires, or run routines in parallel.
63
+ - Hold a vendor scheduler's SDK. The tick IS the adapter.
64
+
65
+ ## Documentation
66
+
67
+ [Docs index](../../docs/README.md) · [Architecture §8](../../docs/architecture.md#8-triggered-turns-and-routines)
68
+ · [Routine runner spec](../../docs/specs/047-routine-runner.md)
69
+
70
+ Apache-2.0
@@ -0,0 +1,74 @@
1
+ import { StoredRoutine, Routine, Scope, RoutineRun, RoutineStore, RoutineRunStore, Schedule } from '@alma-harness/core';
2
+ import { RoutineRunner } from '@alma-harness/loop';
3
+
4
+ /**
5
+ * What is due, and the tick that runs it — spec: clock-tick, hardened by
6
+ * spec: close-060-064-findings.
7
+ *
8
+ * The scheduler knows one thing: call `tick` every minute or five. The tick
9
+ * knows everything else from the stores, so a tick retried, doubled or
10
+ * missed does no harm: the FIRE's instant is the run id, and the runner
11
+ * treats the same id twice as one run (spec: routine-runner).
12
+ */
13
+ interface ScheduleConfig {
14
+ routines: RoutineStore;
15
+ runs: RoutineRunStore;
16
+ /**
17
+ * One runner, or one per routine: a deployment with an agent per tenant
18
+ * resolves it from the routine's scope, since `list` crosses every scope.
19
+ */
20
+ runner: RoutineRunner | ((routine: Routine) => RoutineRunner);
21
+ /** Injected clock (ISO 8601) — tests stay deterministic. */
22
+ now?: () => string;
23
+ /** Per-routine store reads in flight at once. Default 8. */
24
+ concurrency?: number;
25
+ }
26
+ interface DueFire {
27
+ routine: StoredRoutine;
28
+ /** The instant the run is named by: the fire, or the tick's own instant for a pending collection. */
29
+ at: string;
30
+ /** `fire`: the schedule came due. `pending`: a job routine's submission is still open and is collected now. */
31
+ reason: "fire" | "pending";
32
+ }
33
+ interface ScheduleError {
34
+ routineId: string;
35
+ scope: Scope;
36
+ message: string;
37
+ /** `plan`: the routine's schedule could not be read. `run`: the runner threw. The others were not affected. */
38
+ stage: "plan" | "run";
39
+ }
40
+ interface TickPlan {
41
+ at: string;
42
+ due: DueFire[];
43
+ errors: ScheduleError[];
44
+ }
45
+ interface TickReport extends TickPlan {
46
+ runs: RoutineRun[];
47
+ }
48
+ interface RoutineSchedule {
49
+ /**
50
+ * Registers with the store AFTER the runner and the schedule have refused
51
+ * what they cannot run — at registration, not at 8h with nobody watching.
52
+ */
53
+ register(routine: Routine & {
54
+ registeredAt?: string;
55
+ }): Promise<void>;
56
+ cancel(scope: Scope, routineId: string): Promise<void>;
57
+ /** What would run at `now`, without running it, and which routines could not even be planned. */
58
+ plan(now?: string): Promise<TickPlan>;
59
+ /** Runs what is due, one routine after another, and reports. Never throws for a routine's sake. */
60
+ tick(opts?: {
61
+ now?: string;
62
+ }): Promise<TickReport>;
63
+ }
64
+ /** Refuses a schedule the tick could not read — the same errors croner or the parser would raise mid-tick. */
65
+ declare function validateSchedule(schedule: Schedule): void;
66
+ /**
67
+ * The latest fire of a schedule at or before `now`, as an ISO instant — or
68
+ * nothing: before the first fire, or a fire the routine never saw (earlier
69
+ * than its registration). `{ every }` anchors on the registration stamp.
70
+ */
71
+ declare function latestFire(schedule: Schedule, registeredAt: string, nowIso: string): string | undefined;
72
+ declare function createSchedule(config: ScheduleConfig): RoutineSchedule;
73
+
74
+ export { type DueFire, type RoutineSchedule, type ScheduleConfig, type ScheduleError, type TickPlan, type TickReport, createSchedule, latestFire, validateSchedule };
package/dist/index.js ADDED
@@ -0,0 +1,143 @@
1
+ // src/schedule.ts
2
+ import {
3
+ assertIso8601,
4
+ parseIso8601
5
+ } from "@alma-harness/core";
6
+ import { Cron } from "croner";
7
+ var UNITS = { s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
8
+ function durationMs(duration) {
9
+ const match = /^(\d+)([smhd])$/.exec(duration);
10
+ const ms = match === null ? 0 : Number(match[1]) * UNITS[match[2]];
11
+ if (ms <= 0) throw new Error(`malformed duration: ${JSON.stringify(duration)}`);
12
+ return ms;
13
+ }
14
+ function cronOf(expression, tz) {
15
+ return new Cron(expression, { timezone: tz ?? "UTC" });
16
+ }
17
+ function validateSchedule(schedule) {
18
+ if ("at" in schedule) {
19
+ assertIso8601(schedule.at, "schedule.at");
20
+ } else if ("every" in schedule) {
21
+ durationMs(schedule.every);
22
+ } else {
23
+ cronOf(schedule.cron, schedule.tz).nextRun(/* @__PURE__ */ new Date());
24
+ }
25
+ }
26
+ function nextFire(schedule, registered, afterMs) {
27
+ if ("at" in schedule) {
28
+ const at = parseIso8601(schedule.at, "schedule.at");
29
+ return at > afterMs ? at : void 0;
30
+ }
31
+ if ("every" in schedule) {
32
+ const step = durationMs(schedule.every);
33
+ const k = Math.max(1, Math.floor((afterMs - registered) / step) + 1);
34
+ return registered + k * step;
35
+ }
36
+ const next = cronOf(schedule.cron, schedule.tz).nextRun(new Date(afterMs));
37
+ return next === null ? void 0 : next.getTime();
38
+ }
39
+ function latestCron(expression, tz, now) {
40
+ const cron = cronOf(expression, tz);
41
+ for (const window of [2 * UNITS.m, 2 * UNITS.h, 2 * UNITS.d, 40 * UNITS.d, 400 * UNITS.d]) {
42
+ let at = cron.nextRun(new Date(now - window));
43
+ if (at === null || at.getTime() > now) continue;
44
+ for (; ; ) {
45
+ const next = cron.nextRun(at);
46
+ if (next === null || next.getTime() > now) return at.getTime();
47
+ at = next;
48
+ }
49
+ }
50
+ return void 0;
51
+ }
52
+ function latestFire(schedule, registeredAt, nowIso) {
53
+ const now = parseIso8601(nowIso, "now");
54
+ const registered = parseIso8601(registeredAt, "registeredAt");
55
+ let fire;
56
+ if ("at" in schedule) {
57
+ const at = parseIso8601(schedule.at, "schedule.at");
58
+ fire = at <= now ? at : void 0;
59
+ } else if ("every" in schedule) {
60
+ const step = durationMs(schedule.every);
61
+ fire = now - registered >= step ? registered + Math.floor((now - registered) / step) * step : void 0;
62
+ } else {
63
+ fire = latestCron(schedule.cron, schedule.tz, now);
64
+ }
65
+ if (fire === void 0 || fire < registered) return void 0;
66
+ return new Date(fire).toISOString();
67
+ }
68
+ async function mapConcurrent(items, limit, fn) {
69
+ const out = new Array(items.length);
70
+ let next = 0;
71
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
72
+ for (; ; ) {
73
+ const i = next++;
74
+ if (i >= items.length) return;
75
+ out[i] = await fn(items[i]);
76
+ }
77
+ });
78
+ await Promise.all(workers);
79
+ return out;
80
+ }
81
+ function createSchedule(config) {
82
+ const { routines, runs } = config;
83
+ const runnerFor = typeof config.runner === "function" ? config.runner : () => config.runner;
84
+ const clock = config.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
85
+ const concurrency = config.concurrency ?? 8;
86
+ const message = (err) => err instanceof Error ? err.message : String(err);
87
+ async function planOne(routine, nowIso, now) {
88
+ try {
89
+ const [pending] = await runs.list(routine.scope, routine.id, { outcome: "submitted", limit: 1 });
90
+ if (pending !== void 0) return { fire: { routine, at: nowIso, reason: "pending" } };
91
+ const [last] = await runs.list(routine.scope, routine.id, { limit: 1 });
92
+ const registered = parseIso8601(routine.registeredAt, "registeredAt");
93
+ const after = last === void 0 ? registered - 1 : Math.max(registered - 1, parseIso8601(last.startedAt, "startedAt"));
94
+ const next = nextFire(routine.schedule, registered, after);
95
+ if (next === void 0 || next > now) return {};
96
+ const fire = latestFire(routine.schedule, routine.registeredAt, nowIso);
97
+ if (fire === void 0 || last !== void 0 && parseIso8601(fire) <= parseIso8601(last.startedAt)) return {};
98
+ return { fire: { routine, at: fire, reason: "fire" } };
99
+ } catch (err) {
100
+ return { error: { routineId: routine.id, scope: routine.scope, message: message(err), stage: "plan" } };
101
+ }
102
+ }
103
+ async function plan(nowIso = clock()) {
104
+ const now = parseIso8601(nowIso, "now");
105
+ const plans = await mapConcurrent(await routines.list(), concurrency, (routine) => planOne(routine, nowIso, now));
106
+ return {
107
+ at: nowIso,
108
+ due: plans.flatMap((p) => p.fire === void 0 ? [] : [p.fire]),
109
+ errors: plans.flatMap((p) => p.error === void 0 ? [] : [p.error])
110
+ };
111
+ }
112
+ return {
113
+ async register(routine) {
114
+ runnerFor(routine).validate(routine);
115
+ try {
116
+ validateSchedule(routine.schedule);
117
+ } catch (err) {
118
+ throw new Error(`routine ${JSON.stringify(routine.id)} has a schedule the tick cannot read: ${message(err)}`);
119
+ }
120
+ await routines.register(routine);
121
+ },
122
+ cancel: (scope, routineId) => routines.cancel(scope, routineId),
123
+ plan,
124
+ async tick(opts = {}) {
125
+ const planned = await plan(opts.now ?? clock());
126
+ const report = { ...planned, runs: [] };
127
+ for (const fire of planned.due) {
128
+ try {
129
+ report.runs.push(await runnerFor(fire.routine).run(fire.routine, { runId: fire.at, at: fire.at }));
130
+ } catch (err) {
131
+ report.errors.push({ routineId: fire.routine.id, scope: fire.routine.scope, message: message(err), stage: "run" });
132
+ }
133
+ }
134
+ return report;
135
+ }
136
+ };
137
+ }
138
+ export {
139
+ createSchedule,
140
+ latestFire,
141
+ validateSchedule
142
+ };
143
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schedule.ts"],"sourcesContent":["import {\n assertIso8601,\n parseIso8601,\n type Duration,\n type Routine,\n type RoutineRun,\n type RoutineRunStore,\n type RoutineStore,\n type Schedule as ScheduleSpec,\n type Scope,\n type StoredRoutine,\n} from \"@alma-harness/core\";\nimport type { RoutineRunner } from \"@alma-harness/loop\";\nimport { Cron } from \"croner\";\n\n/**\n * What is due, and the tick that runs it — spec: clock-tick, hardened by\n * spec: close-060-064-findings.\n *\n * The scheduler knows one thing: call `tick` every minute or five. The tick\n * knows everything else from the stores, so a tick retried, doubled or\n * missed does no harm: the FIRE's instant is the run id, and the runner\n * treats the same id twice as one run (spec: routine-runner).\n */\n\nexport interface ScheduleConfig {\n routines: RoutineStore;\n runs: RoutineRunStore;\n /**\n * One runner, or one per routine: a deployment with an agent per tenant\n * resolves it from the routine's scope, since `list` crosses every scope.\n */\n runner: RoutineRunner | ((routine: Routine) => RoutineRunner);\n /** Injected clock (ISO 8601) — tests stay deterministic. */\n now?: () => string;\n /** Per-routine store reads in flight at once. Default 8. */\n concurrency?: number;\n}\n\nexport interface DueFire {\n routine: StoredRoutine;\n /** The instant the run is named by: the fire, or the tick's own instant for a pending collection. */\n at: string;\n /** `fire`: the schedule came due. `pending`: a job routine's submission is still open and is collected now. */\n reason: \"fire\" | \"pending\";\n}\n\nexport interface ScheduleError {\n routineId: string;\n scope: Scope;\n message: string;\n /** `plan`: the routine's schedule could not be read. `run`: the runner threw. The others were not affected. */\n stage: \"plan\" | \"run\";\n}\n\nexport interface TickPlan {\n at: string;\n due: DueFire[];\n errors: ScheduleError[];\n}\n\nexport interface TickReport extends TickPlan {\n runs: RoutineRun[];\n}\n\nexport interface RoutineSchedule {\n /**\n * Registers with the store AFTER the runner and the schedule have refused\n * what they cannot run — at registration, not at 8h with nobody watching.\n */\n register(routine: Routine & { registeredAt?: string }): Promise<void>;\n cancel(scope: Scope, routineId: string): Promise<void>;\n /** What would run at `now`, without running it, and which routines could not even be planned. */\n plan(now?: string): Promise<TickPlan>;\n /** Runs what is due, one routine after another, and reports. Never throws for a routine's sake. */\n tick(opts?: { now?: string }): Promise<TickReport>;\n}\n\nconst UNITS: Record<\"s\" | \"m\" | \"h\" | \"d\", number> = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 };\n\n/** A compact duration (\"90s\", \"15m\", \"2h\", \"1d\") in milliseconds; zero is refused — it would fire NaN. */\nexport function durationMs(duration: Duration): number {\n const match = /^(\\d+)([smhd])$/.exec(duration);\n const ms = match === null ? 0 : Number(match[1]) * UNITS[match[2] as keyof typeof UNITS];\n if (ms <= 0) throw new Error(`malformed duration: ${JSON.stringify(duration)}`);\n return ms;\n}\n\n/**\n * UTC unless the routine says where it lives: croner would otherwise read\n * the cron in the PROCESS's zone, and a fire would move with the deployment.\n * Constructed without a callback, so nothing is scheduled.\n */\nfunction cronOf(expression: string, tz: string | undefined): Cron {\n return new Cron(expression, { timezone: tz ?? \"UTC\" });\n}\n\n/** Refuses a schedule the tick could not read — the same errors croner or the parser would raise mid-tick. */\nexport function validateSchedule(schedule: ScheduleSpec): void {\n if (\"at\" in schedule) {\n assertIso8601(schedule.at, \"schedule.at\");\n } else if (\"every\" in schedule) {\n durationMs(schedule.every);\n } else {\n // A bad zone surfaces only on the first computation, not at construction.\n cronOf(schedule.cron, schedule.tz).nextRun(new Date());\n }\n}\n\n/** The first fire strictly after `afterMs`, or nothing. */\nfunction nextFire(schedule: ScheduleSpec, registered: number, afterMs: number): number | undefined {\n if (\"at\" in schedule) {\n const at = parseIso8601(schedule.at, \"schedule.at\");\n return at > afterMs ? at : undefined;\n }\n if (\"every\" in schedule) {\n const step = durationMs(schedule.every);\n const k = Math.max(1, Math.floor((afterMs - registered) / step) + 1);\n return registered + k * step;\n }\n const next = cronOf(schedule.cron, schedule.tz).nextRun(new Date(afterMs));\n return next === null ? undefined : next.getTime();\n}\n\n/**\n * The latest occurrence of a cron at or before `now`. Windows widen until\n * one holds an occurrence, then the window is walked forward to the last\n * one — bounded, because a window is only walked when the cron fits it,\n * and only reached once `nextFire` said something may be due.\n */\nfunction latestCron(expression: string, tz: string | undefined, now: number): number | undefined {\n const cron = cronOf(expression, tz);\n for (const window of [2 * UNITS.m, 2 * UNITS.h, 2 * UNITS.d, 40 * UNITS.d, 400 * UNITS.d]) {\n let at = cron.nextRun(new Date(now - window));\n if (at === null || at.getTime() > now) continue;\n for (;;) {\n const next = cron.nextRun(at);\n if (next === null || next.getTime() > now) return at.getTime();\n at = next;\n }\n }\n return undefined;\n}\n\n/**\n * The latest fire of a schedule at or before `now`, as an ISO instant — or\n * nothing: before the first fire, or a fire the routine never saw (earlier\n * than its registration). `{ every }` anchors on the registration stamp.\n */\nexport function latestFire(schedule: ScheduleSpec, registeredAt: string, nowIso: string): string | undefined {\n const now = parseIso8601(nowIso, \"now\");\n const registered = parseIso8601(registeredAt, \"registeredAt\");\n let fire: number | undefined;\n if (\"at\" in schedule) {\n const at = parseIso8601(schedule.at, \"schedule.at\");\n fire = at <= now ? at : undefined;\n } else if (\"every\" in schedule) {\n const step = durationMs(schedule.every);\n fire = now - registered >= step ? registered + Math.floor((now - registered) / step) * step : undefined;\n } else {\n fire = latestCron(schedule.cron, schedule.tz, now);\n }\n if (fire === undefined || fire < registered) return undefined;\n return new Date(fire).toISOString();\n}\n\n/** `fn` over `items`, at most `limit` in flight — the per-routine reads of a tick (spec: close-060-064-findings). */\nasync function mapConcurrent<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {\n const out: R[] = new Array<R>(items.length);\n let next = 0;\n const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {\n for (;;) {\n const i = next++;\n if (i >= items.length) return;\n out[i] = await fn(items[i]!);\n }\n });\n await Promise.all(workers);\n return out;\n}\n\nexport function createSchedule(config: ScheduleConfig): RoutineSchedule {\n const { routines, runs } = config;\n const runnerFor = typeof config.runner === \"function\" ? config.runner : () => config.runner as RoutineRunner;\n const clock = config.now ?? (() => new Date().toISOString());\n const concurrency = config.concurrency ?? 8;\n const message = (err: unknown): string => (err instanceof Error ? err.message : String(err));\n\n /** One routine's share of a tick: a fire, nothing, or the error that kept it from being planned. */\n async function planOne(routine: StoredRoutine, nowIso: string, now: number): Promise<{ fire?: DueFire; error?: ScheduleError }> {\n try {\n // A submission still open is collected on EVERY tick, not on the next\n // cron occurrence (spec: model-jobs) — asked the way the runner asks it.\n const [pending] = await runs.list(routine.scope, routine.id, { outcome: \"submitted\", limit: 1 });\n if (pending !== undefined) return { fire: { routine, at: nowIso, reason: \"pending\" } };\n const [last] = await runs.list(routine.scope, routine.id, { limit: 1 });\n const registered = parseIso8601(routine.registeredAt, \"registeredAt\");\n // The common case answered in one step: is there any fire after the\n // later of the registration and the last run, at or before now?\n const after = last === undefined ? registered - 1 : Math.max(registered - 1, parseIso8601(last.startedAt, \"startedAt\"));\n const next = nextFire(routine.schedule, registered, after);\n if (next === undefined || next > now) return {};\n const fire = latestFire(routine.schedule, routine.registeredAt, nowIso);\n // Refusals are runs too: a routine past its ceiling is not re-fired every minute.\n if (fire === undefined || (last !== undefined && parseIso8601(fire) <= parseIso8601(last.startedAt))) return {};\n return { fire: { routine, at: fire, reason: \"fire\" } };\n } catch (err) {\n return { error: { routineId: routine.id, scope: routine.scope, message: message(err), stage: \"plan\" } };\n }\n }\n\n async function plan(nowIso: string = clock()): Promise<TickPlan> {\n const now = parseIso8601(nowIso, \"now\");\n const plans = await mapConcurrent(await routines.list(), concurrency, (routine) => planOne(routine, nowIso, now));\n return {\n at: nowIso,\n due: plans.flatMap((p) => (p.fire === undefined ? [] : [p.fire])),\n errors: plans.flatMap((p) => (p.error === undefined ? [] : [p.error])),\n };\n }\n\n return {\n async register(routine) {\n runnerFor(routine).validate(routine);\n try {\n validateSchedule(routine.schedule);\n } catch (err) {\n throw new Error(`routine ${JSON.stringify(routine.id)} has a schedule the tick cannot read: ${message(err)}`);\n }\n await routines.register(routine);\n },\n cancel: (scope, routineId) => routines.cancel(scope, routineId),\n plan,\n async tick(opts = {}) {\n const planned = await plan(opts.now ?? clock());\n const report: TickReport = { ...planned, runs: [] };\n for (const fire of planned.due) {\n try {\n report.runs.push(await runnerFor(fire.routine).run(fire.routine, { runId: fire.at, at: fire.at }));\n } catch (err) {\n report.errors.push({ routineId: fire.rout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ACF,iBAAO,KAAK,KAAK,MAAM,UAAU,KAAK,OAAO,EAAE,IAAI,KAAK,SAAS,EAAE,OAAO,KAAK,IAAI,IAAI,KAAK,GAAG,CAAC,CAAC;AAAA,QACnG,SAAS,KAAK;AACZ,iBAAO,OAAO,KAAK,EAAE,WAAW,KAAK,QAAQ,IAAI,OAAO,KAAK,QAAQ,OAAO,SAAS,QAAQ,GAAG,GAAG,OAAO,MAAM,CAAC;AAAA,QACnH;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@alma-harness/schedule",
3
+ "version": "0.3.0",
4
+ "description": "Alma's clock: what is due, and the tick an external scheduler calls to run it — no process kept alive.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/FabioFernandesCarneiro/alma.git",
19
+ "directory": "packages/schedule"
20
+ },
21
+ "dependencies": {
22
+ "croner": "^10.0.1"
23
+ },
24
+ "peerDependencies": {
25
+ "@alma-harness/core": "^0.3.0",
26
+ "@alma-harness/loop": "^0.3.0"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^24.1.0",
30
+ "typescript": "^5.9.2",
31
+ "vitest": "^3.2.4"
32
+ },
33
+ "files": [
34
+ "dist"
35
+ ],
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "scripts": {
40
+ "typecheck": "tsc --noEmit",
41
+ "test": "vitest run",
42
+ "build": "tsup"
43
+ },
44
+ "main": "./dist/index.js",
45
+ "types": "./dist/index.d.ts"
46
+ }