@stonyx/cron 0.2.1-beta.32 → 0.2.1-beta.34

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.
@@ -0,0 +1,271 @@
1
+ /**
2
+ * CronService - the main API for advanced job scheduling.
3
+ *
4
+ * Manages jobs in memory with a min-heap for efficient next-job lookup.
5
+ * All state mutations are serialized via async locking.
6
+ */
7
+ import config from 'stonyx/config';
8
+ import log from 'stonyx/log';
9
+ import MinHeap from './min-heap.js';
10
+ import { createJob, updateJob, markRunning, applyResult, isDue } from './job.js';
11
+ import { locked } from './locked.js';
12
+ import { normalizeJobInput, recoverFlatParams } from './normalize.js';
13
+ import RunLog from './run-log.js';
14
+ const MAX_TIMER_DELAY_MS = 60_000;
15
+ export default class CronService {
16
+ jobs;
17
+ heap;
18
+ timer;
19
+ running;
20
+ runLog;
21
+ started;
22
+ // Pluggable callbacks for consumers
23
+ onJobDue;
24
+ constructor() {
25
+ this.jobs = new Map();
26
+ this.heap = new MinHeap();
27
+ this.timer = null;
28
+ this.running = false;
29
+ this.runLog = new RunLog();
30
+ this.started = false;
31
+ this.onJobDue = null;
32
+ }
33
+ // -- Lifecycle -------------------------------------------------------
34
+ /**
35
+ * Start the service. Loads jobs from store (if any), arms timer.
36
+ */
37
+ async start(initialJobs) {
38
+ if (this.started)
39
+ return;
40
+ this.started = true;
41
+ if (initialJobs) {
42
+ for (const job of initialJobs) {
43
+ this.jobs.set(job.id, job);
44
+ if (job.enabled && job.state.nextRunAtMs) {
45
+ this.heap.push({ key: job.id, nextTrigger: job.state.nextRunAtMs });
46
+ }
47
+ }
48
+ }
49
+ this.armTimer();
50
+ }
51
+ /**
52
+ * Stop the service. Clears timer.
53
+ */
54
+ stop() {
55
+ this.started = false;
56
+ if (this.timer)
57
+ clearTimeout(this.timer);
58
+ this.timer = null;
59
+ }
60
+ // -- CRUD ------------------------------------------------------------
61
+ /**
62
+ * Get service status.
63
+ */
64
+ status() {
65
+ const peek = this.heap.peek();
66
+ return {
67
+ started: this.started,
68
+ jobCount: this.jobs.size,
69
+ nextWakeAtMs: peek ? peek.nextTrigger : undefined,
70
+ };
71
+ }
72
+ /**
73
+ * List jobs, optionally including disabled ones.
74
+ */
75
+ list(opts) {
76
+ const includeDisabled = opts?.includeDisabled ?? false;
77
+ const jobs = [...this.jobs.values()];
78
+ const filtered = includeDisabled ? jobs : jobs.filter(j => j.enabled);
79
+ return filtered.sort((a, b) => (a.state.nextRunAtMs ?? Infinity) - (b.state.nextRunAtMs ?? Infinity));
80
+ }
81
+ /**
82
+ * Get a single job by ID.
83
+ */
84
+ get(id) {
85
+ return this.jobs.get(id) || null;
86
+ }
87
+ /**
88
+ * Add a new job. Input is normalized for AI compatibility.
89
+ */
90
+ async add(rawInput) {
91
+ return locked(() => {
92
+ const input = normalizeJobInput(recoverFlatParams(rawInput));
93
+ const job = createJob(input);
94
+ this.jobs.set(job.id, job);
95
+ if (job.enabled && job.state.nextRunAtMs) {
96
+ this.heap.push({ key: job.id, nextTrigger: job.state.nextRunAtMs });
97
+ this.armTimer();
98
+ }
99
+ return job;
100
+ });
101
+ }
102
+ /**
103
+ * Update an existing job.
104
+ */
105
+ async update(id, patch) {
106
+ return locked(() => {
107
+ const job = this.jobs.get(id);
108
+ if (!job)
109
+ throw new Error(`Job not found: ${id}`);
110
+ const oldNextRun = job.state.nextRunAtMs;
111
+ updateJob(job, patch);
112
+ // Update heap entry
113
+ this.removeFromHeap(id);
114
+ if (job.enabled && job.state.nextRunAtMs) {
115
+ this.heap.push({ key: id, nextTrigger: job.state.nextRunAtMs });
116
+ }
117
+ if (job.state.nextRunAtMs !== oldNextRun) {
118
+ this.armTimer();
119
+ }
120
+ return job;
121
+ });
122
+ }
123
+ /**
124
+ * Remove a job.
125
+ */
126
+ async remove(id) {
127
+ return locked(() => {
128
+ const job = this.jobs.get(id);
129
+ if (!job)
130
+ throw new Error(`Job not found: ${id}`);
131
+ this.jobs.delete(id);
132
+ this.removeFromHeap(id);
133
+ this.runLog.removeJob(id);
134
+ this.armTimer();
135
+ });
136
+ }
137
+ /**
138
+ * Manually trigger a job.
139
+ */
140
+ async run(id, mode = 'force') {
141
+ const job = this.jobs.get(id);
142
+ if (!job)
143
+ throw new Error(`Job not found: ${id}`);
144
+ if (mode === 'due' && !isDue(job, Date.now())) {
145
+ return { status: 'skipped', reason: 'not due' };
146
+ }
147
+ return this.executeJob(job);
148
+ }
149
+ /**
150
+ * Get run history for a job.
151
+ */
152
+ runs(id, limit) {
153
+ return this.runLog.get(id, limit);
154
+ }
155
+ // -- Timer Engine ----------------------------------------------------
156
+ armTimer() {
157
+ if (this.timer)
158
+ clearTimeout(this.timer);
159
+ if (!this.started)
160
+ return;
161
+ const peek = this.heap.peek();
162
+ if (!peek)
163
+ return;
164
+ const delay = Math.min(Math.max(peek.nextTrigger - Date.now(), 0), MAX_TIMER_DELAY_MS);
165
+ this.timer = setTimeout(() => this.onTimer(), delay);
166
+ }
167
+ async onTimer() {
168
+ if (this.running) {
169
+ // Already processing - re-arm at max delay to prevent scheduler death
170
+ this.timer = setTimeout(() => this.onTimer(), MAX_TIMER_DELAY_MS);
171
+ return;
172
+ }
173
+ this.running = true;
174
+ try {
175
+ await locked(async () => {
176
+ const nowMs = Date.now();
177
+ const dueJobs = this.findDueJobs(nowMs);
178
+ for (const job of dueJobs) {
179
+ markRunning(job);
180
+ }
181
+ for (const job of dueJobs) {
182
+ await this.executeJob(job);
183
+ }
184
+ });
185
+ }
186
+ finally {
187
+ this.running = false;
188
+ this.armTimer();
189
+ }
190
+ }
191
+ findDueJobs(nowMs) {
192
+ const due = [];
193
+ while (!this.heap.isEmpty()) {
194
+ const peek = this.heap.peek();
195
+ if (!peek || peek.nextTrigger > nowMs)
196
+ break;
197
+ this.heap.pop();
198
+ const job = this.jobs.get(peek.key);
199
+ if (job && isDue(job, nowMs)) {
200
+ due.push(job);
201
+ }
202
+ }
203
+ return due;
204
+ }
205
+ async executeJob(job) {
206
+ const startMs = Date.now();
207
+ let status = 'ok';
208
+ let error;
209
+ let summary;
210
+ try {
211
+ if (this.onJobDue) {
212
+ const result = await this.onJobDue(job);
213
+ if (result) {
214
+ status = result.status || 'ok';
215
+ error = result.error;
216
+ summary = result.summary;
217
+ }
218
+ }
219
+ }
220
+ catch (err) {
221
+ status = 'error';
222
+ error = err instanceof Error ? err.message : String(err);
223
+ this.log(`Job "${job.name}" (${job.id}) failed: ${error}`);
224
+ }
225
+ const durationMs = Date.now() - startMs;
226
+ const validStatus = (status === 'ok' || status === 'error' || status === 'skipped') ? status : 'error';
227
+ applyResult(job, validStatus, error, durationMs);
228
+ // Log the run
229
+ this.runLog.record({
230
+ jobId: job.id,
231
+ status,
232
+ error,
233
+ summary,
234
+ runAtMs: startMs,
235
+ durationMs,
236
+ nextRunAtMs: job.state.nextRunAtMs,
237
+ });
238
+ // Handle one-shot auto-delete
239
+ if (job.deleteAfterRun && status === 'ok' && !job.enabled) {
240
+ this.jobs.delete(job.id);
241
+ this.runLog.removeJob(job.id);
242
+ return { status, summary, deleted: true };
243
+ }
244
+ // Re-insert into heap if still active
245
+ if (job.enabled && job.state.nextRunAtMs) {
246
+ this.heap.push({ key: job.id, nextTrigger: job.state.nextRunAtMs });
247
+ }
248
+ return { status, error, summary, durationMs };
249
+ }
250
+ // -- Helpers ---------------------------------------------------------
251
+ removeFromHeap(id) {
252
+ // MinHeap doesn't support remove-by-key efficiently,
253
+ // so we rebuild. Fine for typical job counts (< 1000).
254
+ const remaining = [];
255
+ while (!this.heap.isEmpty()) {
256
+ const item = this.heap.pop();
257
+ if (!item)
258
+ break;
259
+ if (item.key !== id)
260
+ remaining.push(item);
261
+ }
262
+ for (const item of remaining) {
263
+ this.heap.push(item);
264
+ }
265
+ }
266
+ log(message) {
267
+ if (!config.cron?.log)
268
+ return;
269
+ log.cron(`Cron — ${message}`);
270
+ }
271
+ }
package/package.json CHANGED
@@ -3,25 +3,53 @@
3
3
  "keywords": [
4
4
  "stonyx-module"
5
5
  ],
6
- "version": "0.2.1-beta.32",
6
+ "version": "0.2.1-beta.34",
7
7
  "description": "Cron/job scheduler for Stonyx framework",
8
- "main": "src/main.js",
8
+ "main": "dist/main.js",
9
+ "types": "dist/main.d.ts",
9
10
  "type": "module",
10
11
  "files": [
11
- "src",
12
+ "dist",
12
13
  "config",
13
14
  "README.md"
14
15
  ],
15
16
  "exports": {
16
- ".": "./src/main.js",
17
- "./service": "./src/service.js",
18
- "./cron-parser": "./src/cron-parser.js",
19
- "./schedule": "./src/schedule.js",
20
- "./job": "./src/job.js",
21
- "./normalize": "./src/normalize.js",
22
- "./locked": "./src/locked.js",
23
- "./run-log": "./src/run-log.js",
24
- "./min-heap": "./src/min-heap.js"
17
+ ".": {
18
+ "types": "./dist/main.d.ts",
19
+ "default": "./dist/main.js"
20
+ },
21
+ "./service": {
22
+ "types": "./dist/service.d.ts",
23
+ "default": "./dist/service.js"
24
+ },
25
+ "./cron-parser": {
26
+ "types": "./dist/cron-parser.d.ts",
27
+ "default": "./dist/cron-parser.js"
28
+ },
29
+ "./schedule": {
30
+ "types": "./dist/schedule.d.ts",
31
+ "default": "./dist/schedule.js"
32
+ },
33
+ "./job": {
34
+ "types": "./dist/job.d.ts",
35
+ "default": "./dist/job.js"
36
+ },
37
+ "./normalize": {
38
+ "types": "./dist/normalize.d.ts",
39
+ "default": "./dist/normalize.js"
40
+ },
41
+ "./locked": {
42
+ "types": "./dist/locked.d.ts",
43
+ "default": "./dist/locked.js"
44
+ },
45
+ "./run-log": {
46
+ "types": "./dist/run-log.d.ts",
47
+ "default": "./dist/run-log.js"
48
+ },
49
+ "./min-heap": {
50
+ "types": "./dist/min-heap.d.ts",
51
+ "default": "./dist/min-heap.js"
52
+ }
25
53
  },
26
54
  "publishConfig": {
27
55
  "access": "public",
@@ -42,13 +70,17 @@
42
70
  "homepage": "https://github.com/abofs/stonyx-cron#readme",
43
71
  "devDependencies": {
44
72
  "@stonyx/utils": "0.2.3-beta.7",
73
+ "@types/node": "^25.5.2",
45
74
  "qunit": "^2.24.1",
46
- "sinon": "^21.0.0"
75
+ "sinon": "^21.0.0",
76
+ "typescript": "^5.8.3"
47
77
  },
48
78
  "dependencies": {
49
79
  "stonyx": "0.2.3-beta.12"
50
80
  },
51
81
  "scripts": {
52
- "test": "stonyx test"
82
+ "build": "tsc",
83
+ "build:test": "tsc -p tsconfig.test.json",
84
+ "test": "pnpm build && pnpm build:test && stonyx test 'dist-test/test/**/*-test.js'"
53
85
  }
54
86
  }
@@ -1,246 +0,0 @@
1
- /**
2
- * 5-field cron expression parser with next-occurrence computation.
3
- * No external dependencies — built for stonyx-cron.
4
- *
5
- * Fields: minute(0-59) hour(0-23) day-of-month(1-31) month(1-12) day-of-week(0-6)
6
- * Supports: wildcards(*), ranges(1-5), steps(* /5), lists(1,3,5), names(jan-dec, sun-sat)
7
- */
8
-
9
- const MONTH_NAMES = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 };
10
- const DAY_NAMES = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 };
11
-
12
- const FIELD_RANGES = [
13
- { min: 0, max: 59 }, // minute
14
- { min: 0, max: 23 }, // hour
15
- { min: 1, max: 31 }, // day of month
16
- { min: 1, max: 12 }, // month
17
- { min: 0, max: 6 }, // day of week
18
- ];
19
-
20
- /**
21
- * Parse a single cron field into a sorted array of allowed values.
22
- * @param {string} field - The field string (e.g., "1-5", "* /15", "mon,wed,fri")
23
- * @param {number} fieldIndex - Index (0=minute, 1=hour, 2=dom, 3=month, 4=dow)
24
- * @returns {number[]} Sorted array of allowed integer values
25
- */
26
- export function parseField(field, fieldIndex) {
27
- const { min, max } = FIELD_RANGES[fieldIndex];
28
- const names = fieldIndex === 3 ? MONTH_NAMES : fieldIndex === 4 ? DAY_NAMES : null;
29
-
30
- const resolveToken = (token) => {
31
- if (names) {
32
- const lower = token.toLowerCase();
33
- if (lower in names) return names[lower];
34
- }
35
- const n = Number(token);
36
- if (!Number.isInteger(n)) throw new Error(`Invalid cron value: "${token}" in field ${fieldIndex}`);
37
- // Normalize day-of-week 7 → 0 (both mean Sunday)
38
- if (fieldIndex === 4 && n === 7) return 0;
39
- return n;
40
- };
41
-
42
- const results = new Set();
43
-
44
- for (const part of field.split(',')) {
45
- const trimmed = part.trim();
46
- const [rangeStr, stepStr] = trimmed.split('/');
47
- const step = stepStr !== undefined ? Number(stepStr) : 1;
48
-
49
- if (!Number.isInteger(step) || step < 1) {
50
- throw new Error(`Invalid step "${stepStr}" in cron field ${fieldIndex}`);
51
- }
52
-
53
- let start, end;
54
-
55
- if (rangeStr === '*') {
56
- start = min;
57
- end = max;
58
- } else if (rangeStr.includes('-')) {
59
- const [lo, hi] = rangeStr.split('-');
60
- start = resolveToken(lo);
61
- end = resolveToken(hi);
62
- } else {
63
- start = resolveToken(rangeStr);
64
- end = stepStr !== undefined ? max : start;
65
- }
66
-
67
- if (start < min || start > max || end < min || end > max) {
68
- throw new Error(`Value out of range [${min}-${max}] in cron field ${fieldIndex}: "${trimmed}"`);
69
- }
70
-
71
- for (let v = start; v <= end; v += step) {
72
- results.add(v);
73
- }
74
- }
75
-
76
- return [...results].sort((a, b) => a - b);
77
- }
78
-
79
- /**
80
- * Parse a 5-field cron expression into field arrays.
81
- * @param {string} expr - Cron expression (e.g., "0 9 * * 1-5")
82
- * @returns {{ minutes: number[], hours: number[], daysOfMonth: number[], months: number[], daysOfWeek: number[] }}
83
- */
84
- export function parseCronExpression(expr) {
85
- const fields = expr.trim().split(/\s+/);
86
- if (fields.length !== 5) {
87
- throw new Error(`Cron expression must have exactly 5 fields, got ${fields.length}: "${expr}"`);
88
- }
89
-
90
- return {
91
- minutes: parseField(fields[0], 0),
92
- hours: parseField(fields[1], 1),
93
- daysOfMonth: parseField(fields[2], 2),
94
- months: parseField(fields[3], 3),
95
- daysOfWeek: parseField(fields[4], 4),
96
- };
97
- }
98
-
99
- /**
100
- * Get the number of days in a given month/year.
101
- */
102
- function daysInMonth(year, month) {
103
- return new Date(year, month, 0).getDate();
104
- }
105
-
106
- /**
107
- * Check if a day-of-month + day-of-week pair matches the parsed expression.
108
- *
109
- * Standard cron behavior: if BOTH dom and dow are restricted (not *),
110
- * then EITHER matching is sufficient (OR logic).
111
- * If only one is restricted, it acts as the sole filter.
112
- */
113
- function dayMatches(parsed, domWild, dowWild, dayOfMonth, dayOfWeek) {
114
- const domMatch = parsed.daysOfMonth.includes(dayOfMonth);
115
- const dowMatch = parsed.daysOfWeek.includes(dayOfWeek);
116
-
117
- if (domWild && dowWild) return true;
118
- if (domWild) return dowMatch;
119
- if (dowWild) return domMatch;
120
- return domMatch || dowMatch; // Both restricted → OR
121
- }
122
-
123
- /**
124
- * Compute the next occurrence of a cron expression after a given timestamp.
125
- *
126
- * @param {string} expr - 5-field cron expression
127
- * @param {number} afterMs - Timestamp in milliseconds (exclusive — finds strictly after this)
128
- * @param {string} [tz] - IANA timezone (defaults to system timezone)
129
- * @returns {number|undefined} Next occurrence in milliseconds, or undefined if none within 4 years
130
- */
131
- export function nextOccurrence(expr, afterMs, tz) {
132
- const parsed = parseCronExpression(expr);
133
- const exprFields = expr.trim().split(/\s+/);
134
- const domWild = exprFields[2] === '*';
135
- const dowWild = exprFields[4] === '*';
136
-
137
- // Start from the next whole minute after afterMs
138
- const startDate = new Date(afterMs);
139
- startDate.setSeconds(0, 0);
140
- startDate.setMinutes(startDate.getMinutes() + 1);
141
-
142
- // Convert to target timezone for field matching
143
- const formatter = new Intl.DateTimeFormat('en-US', {
144
- timeZone: tz || undefined,
145
- year: 'numeric', month: 'numeric', day: 'numeric',
146
- hour: 'numeric', minute: 'numeric', hour12: false,
147
- weekday: 'short',
148
- });
149
-
150
- const dayMap = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
151
-
152
- // Parse formatted date parts in the target timezone
153
- function getLocalParts(date) {
154
- const parts = {};
155
- for (const { type, value } of formatter.formatToParts(date)) {
156
- parts[type] = value;
157
- }
158
- return {
159
- year: Number(parts.year),
160
- month: Number(parts.month),
161
- day: Number(parts.day),
162
- hour: Number(parts.hour === '24' ? 0 : parts.hour),
163
- minute: Number(parts.minute),
164
- weekday: dayMap[parts.weekday] ?? 0,
165
- };
166
- }
167
-
168
- // Search limit: 4 years of minutes (≈ 2.1M iterations max)
169
- const maxMs = afterMs + 4 * 365.25 * 24 * 60 * 60 * 1000;
170
- let candidate = new Date(startDate);
171
-
172
- while (candidate.getTime() <= maxMs) {
173
- const p = getLocalParts(candidate);
174
-
175
- // Check month
176
- if (!parsed.months.includes(p.month)) {
177
- // Advance to next matching month
178
- const nextMonth = parsed.months.find(m => m > p.month);
179
- if (nextMonth) {
180
- // Stay in same year, advance to first day of nextMonth
181
- candidate = advanceToMonth(candidate, p.year, nextMonth, tz, formatter, dayMap);
182
- } else {
183
- // Wrap to next year, first matching month
184
- candidate = advanceToMonth(candidate, p.year + 1, parsed.months[0], tz, formatter, dayMap);
185
- }
186
- continue;
187
- }
188
-
189
- // Check day (dom + dow)
190
- if (!dayMatches(parsed, domWild, dowWild, p.day, p.weekday)) {
191
- candidate.setMinutes(candidate.getMinutes() + (24 * 60 - p.hour * 60 - p.minute));
192
- continue;
193
- }
194
-
195
- // Check hour
196
- if (!parsed.hours.includes(p.hour)) {
197
- const nextHour = parsed.hours.find(h => h > p.hour);
198
- if (nextHour) {
199
- candidate.setMinutes(candidate.getMinutes() + ((nextHour - p.hour) * 60 - p.minute));
200
- } else {
201
- // Advance to next day
202
- candidate.setMinutes(candidate.getMinutes() + ((24 - p.hour) * 60 - p.minute));
203
- }
204
- continue;
205
- }
206
-
207
- // Check minute
208
- if (!parsed.minutes.includes(p.minute)) {
209
- const nextMin = parsed.minutes.find(m => m > p.minute);
210
- if (nextMin) {
211
- candidate.setMinutes(candidate.getMinutes() + (nextMin - p.minute));
212
- } else {
213
- // Advance to next hour
214
- candidate.setMinutes(candidate.getMinutes() + (60 - p.minute));
215
- }
216
- continue;
217
- }
218
-
219
- // All fields match
220
- return candidate.getTime();
221
- }
222
-
223
- return undefined;
224
- }
225
-
226
- /**
227
- * Create a Date advanced to the start of a specific month in a specific year,
228
- * using the target timezone's midnight.
229
- */
230
- function advanceToMonth(current, year, month, tz, formatter, dayMap) {
231
- // Create a new date at ~start of the target month in UTC, then adjust
232
- const d = new Date(current);
233
- // Jump to approximately the right time
234
- d.setFullYear(year, month - 1, 1);
235
- d.setHours(0, 0, 0, 0);
236
- return d;
237
- }
238
-
239
- /**
240
- * Validate a cron expression without computing next occurrence.
241
- * @param {string} expr - 5-field cron expression
242
- * @throws {Error} if the expression is invalid
243
- */
244
- export function validateCronExpression(expr) {
245
- parseCronExpression(expr);
246
- }