@stonyx/cron 0.2.1-beta.12 → 0.2.1-beta.121

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js ADDED
@@ -0,0 +1,276 @@
1
+ /*
2
+ * Copyright 2025 Stone Costa
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the 'License');
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import config from 'stonyx/config';
17
+ import log from 'stonyx/log';
18
+ import { getTimestamp } from '@stonyx/utils/date';
19
+ import MinHeap from './min-heap.js';
20
+ /** Longest error text that may reach a log line. Anything past this is truncated. */
21
+ const MAX_LOGGED_ERROR_LENGTH = 512;
22
+ /**
23
+ * Flatten a value for interpolation into a single log line.
24
+ *
25
+ * `@stonyx/logs` writes `${timestamp} ${content}\n` to a newline-delimited
26
+ * file, so any `\r` or `\n` inside `content` ends the record early and
27
+ * everything after it is read back as a separate entry — including a forged
28
+ * `[timestamp] ...` prefix that is indistinguishable from a real one. Newlines
29
+ * become the literal two characters so the content survives for a reader, and
30
+ * the length cap keeps one pathological value from swamping the file.
31
+ *
32
+ * Kept byte-identical to the `forLog` landing in `src/service.ts` on #34: the
33
+ * two tiers render the same untrusted values into the same log file, and a
34
+ * reader diagnosing a forged record should not have to know which tier wrote
35
+ * it. Duplicated rather than shared because the two land on separate branches;
36
+ * folding them into one helper is a follow-up once both are on `dev`, not a
37
+ * cross-PR dependency that would make either unmergeable alone.
38
+ */
39
+ function forLog(value, maxLength) {
40
+ const flattened = value.replace(/\r\n|[\r\n\u2028\u2029]/g, '\\n');
41
+ return flattened.length > maxLength ? `${flattened.slice(0, maxLength)}...` : flattened;
42
+ }
43
+ /**
44
+ * Render an unknown thrown value as log text. Total by construction.
45
+ *
46
+ * `@stonyx/logs` reads a second argument as `logToFile`, not as a format
47
+ * argument, so `log.error(message, err)` discards the error entirely *and*
48
+ * forces a disk write on every failure. The error has to be interpolated into
49
+ * the message instead — the shape `CronService.executeJob` already uses.
50
+ *
51
+ * Every read below touches a consumer-controlled value and can therefore throw:
52
+ * `instanceof` runs a proxy's `getPrototypeOf` trap, `stack`/`name`/`message`
53
+ * can be accessor properties, and `String(Object.create(null))` throws outright.
54
+ * This function runs *inside* `invokeJob`'s catch — the one place whose job is
55
+ * to stop a callback failure from reaching the scheduler — so a throw here
56
+ * escapes that catch and skips `scheduleNextRun()`, which is defect #36.
57
+ */
58
+ function describeError(err) {
59
+ try {
60
+ if (err instanceof Error) {
61
+ return forLog(err.stack ?? `${err.name}: ${err.message}`, MAX_LOGGED_ERROR_LENGTH);
62
+ }
63
+ return forLog(String(err), MAX_LOGGED_ERROR_LENGTH);
64
+ }
65
+ catch {
66
+ // Deliberately not re-entrant: describing the failure to describe the error
67
+ // would be the same read that just threw.
68
+ return '<thrown value could not be rendered>';
69
+ }
70
+ }
71
+ /**
72
+ * Render a consumer-supplied job key safely for log output.
73
+ *
74
+ * Keys reach the log verbatim, so a key containing a newline can forge a
75
+ * complete, well-formed log line (`'a:\n[FORGED] Cron::admin - all jobs
76
+ * healthy'`). `JSON.stringify` quotes the value and escapes the control
77
+ * characters, which is also how the key is rendered one tier up.
78
+ */
79
+ function describeKey(key) {
80
+ return JSON.stringify(key);
81
+ }
82
+ export default class Cron {
83
+ static instance;
84
+ jobs = {};
85
+ heap = new MinHeap();
86
+ timer = null;
87
+ constructor() {
88
+ if (Cron.instance)
89
+ return Cron.instance;
90
+ Cron.instance = this;
91
+ }
92
+ async init() {
93
+ // Self-register so log.cron works even when @stonyx/cron is in the
94
+ // consumer's `dependencies` (stonyx loader only merges devDependencies).
95
+ const { logColor = '#888', logMethod = 'cron' } = config.cron ?? {};
96
+ log.defineType(logMethod, logColor);
97
+ }
98
+ scheduleNextRun() {
99
+ if (this.timer)
100
+ clearTimeout(this.timer);
101
+ const { heap } = this;
102
+ if (heap.isEmpty())
103
+ return;
104
+ const nextJob = heap.peek();
105
+ if (!nextJob)
106
+ return;
107
+ const delay = Math.max(0, nextJob.nextTrigger - getTimestamp()) * 1000;
108
+ // Terminal catch: `runDueJobs` is async, so anything that escapes it would
109
+ // otherwise become an unhandled rejection raised from a bare timer callback
110
+ // — the very failure mode this class was fixed for.
111
+ this.timer = setTimeout(() => {
112
+ this.runDueJobs().catch((err) => {
113
+ this.report('error', `Cron scheduler tick failed: ${describeError(err)}`);
114
+ });
115
+ }, delay);
116
+ }
117
+ async runDueJobs() {
118
+ const now = getTimestamp();
119
+ const { heap } = this;
120
+ // `finally`, not a trailing statement: `scheduleNextRun()` running on every
121
+ // exit from the drain loop is the invariant this whole fix is about. If
122
+ // anything in the loop body ever throws, the scheduler must still re-arm
123
+ // rather than stopping silently while `timer` still holds a fired handle.
124
+ try {
125
+ while (!heap.isEmpty()) {
126
+ const next = heap.peek();
127
+ if (!next || next.nextTrigger > now)
128
+ break;
129
+ const job = heap.pop();
130
+ if (config.debug)
131
+ this.log('job has been triggered', job.key);
132
+ // Reschedule before invoking: a consumer callback is never awaited here,
133
+ // so a callback that hangs or rejects can no longer starve the drain loop
134
+ // or leave the job orphaned outside the heap.
135
+ this.setNextTrigger(job);
136
+ heap.push(job);
137
+ this.invokeJob(job);
138
+ }
139
+ }
140
+ finally {
141
+ this.scheduleNextRun();
142
+ }
143
+ }
144
+ register(key, callback, interval, runOnInit = false) {
145
+ const job = { callback, interval, key, nextTrigger: 0 };
146
+ this.jobs[key] = job;
147
+ this.setNextTrigger(job);
148
+ this.heap.push(job);
149
+ if (config.debug) {
150
+ this.log(`job has been registered with interval: ${interval}`, key);
151
+ }
152
+ // `finally`, not a trailing statement, for the same reason as `runDueJobs`:
153
+ // a job that is registered but never scheduled is defect #36's terminal
154
+ // state reached through the other entry point. `invokeJob` is total, so
155
+ // this guard should be unreachable — which is exactly why it is a guard and
156
+ // not an assumption.
157
+ try {
158
+ if (runOnInit)
159
+ this.invokeJob(job, true);
160
+ }
161
+ finally {
162
+ this.scheduleNextRun();
163
+ }
164
+ }
165
+ unregister(key) {
166
+ const { heap, jobs } = this;
167
+ const job = jobs[key];
168
+ if (!job)
169
+ return;
170
+ delete jobs[key];
171
+ heap.remove(job);
172
+ if (config.debug)
173
+ this.log('job has been unregistered', key);
174
+ this.scheduleNextRun();
175
+ }
176
+ /**
177
+ * The one place this class invokes a consumer callback.
178
+ *
179
+ * Never blocks the caller, catches synchronous throws and asynchronous
180
+ * rejections identically, and skips the invocation entirely while the job's
181
+ * previous invocation has not settled (fire-and-forget would otherwise let a
182
+ * slow job stack invocations on itself).
183
+ *
184
+ * Everything that touches the callback — including the thenable probe and the
185
+ * handler attachment — is inside the `try`. A callback may return an object
186
+ * whose `then` is a throwing getter, and reading it outside the guard would
187
+ * abort the drain loop before `scheduleNextRun()`, which is defect #36 again.
188
+ */
189
+ invokeJob(job, runOnInit = false) {
190
+ const { key } = job;
191
+ const context = runOnInit ? 'failed on init:' : 'failed:';
192
+ // The in-flight guard lives on the job object, not in a module-level set
193
+ // keyed by string. Object identity is invocation identity: the only thing
194
+ // that clears the guard is the settle handler of the invocation that set it,
195
+ // and that handler closes over this exact job object, so a stale handler can
196
+ // never release a later invocation's guard.
197
+ if (job.runningAtMs !== undefined) {
198
+ // Bounded to one line per stuck run, not one per tick. A permanently hung
199
+ // job is re-pushed and re-skipped every interval forever; at the 1s
200
+ // interval this class's own tests use that measures 43,200 lines/day per
201
+ // job — a disk-fill and ingest-cost vector whose natural operator response
202
+ // is to silence the only signal that the job is dead.
203
+ if (!job.skipReported) {
204
+ job.skipReported = true;
205
+ const runningForSeconds = Math.max(0, Math.round((Date.now() - job.runningAtMs) / 1000));
206
+ // Ungated, deliberately, matching the sibling `CronService` handler. A
207
+ // skipped run is a *lost* execution, and `runDueJobs`/`register` both
208
+ // return `void`, so this is the legacy class's only wedged-job channel.
209
+ // Routing it through `this.log` would put it behind `config.cron.log`,
210
+ // where a permanently dead job is indistinguishable from a healthy one.
211
+ this.report('warn', `Cron job ${describeKey(key)} is still running after ${runningForSeconds}s; skipping this `
212
+ + 'tick and any further ticks until it settles (this warning is not repeated for this run)');
213
+ }
214
+ return;
215
+ }
216
+ job.runningAtMs = Date.now();
217
+ job.skipReported = false;
218
+ try {
219
+ const result = job.callback();
220
+ if (result && typeof result.then === 'function') {
221
+ Promise.resolve(result)
222
+ .catch((err) => {
223
+ // Braces matter: returning `report`'s value would put it back into
224
+ // the chain, and `.finally` passes a rejection straight through.
225
+ this.report('error', `Cron job ${describeKey(key)} ${context} ${describeError(err)}`);
226
+ })
227
+ .finally(() => { this.release(job); })
228
+ // Backstop: a throw inside the error handler or the release must not
229
+ // re-create the unhandled rejection this helper exists to prevent.
230
+ .catch(() => { });
231
+ return;
232
+ }
233
+ this.release(job);
234
+ }
235
+ catch (err) {
236
+ this.release(job);
237
+ this.report('error', `Cron job ${describeKey(key)} ${context} ${describeError(err)}`);
238
+ }
239
+ }
240
+ /**
241
+ * Report a scheduler-level message without ever letting the logger's own
242
+ * failure reach the caller.
243
+ *
244
+ * `@stonyx/logs` convenience methods return a promise and write to disk
245
+ * through an unguarded `mkdirSync` + `fsp.appendFile`. On a read-only or full
246
+ * log volume that promise rejects; an unobserved rejection raised from inside
247
+ * the handler that exists to prevent unhandled rejections would re-create
248
+ * exactly the defect this class was fixed for.
249
+ */
250
+ report(level, message) {
251
+ try {
252
+ const result = level === 'error' ? log.error(message) : log.warn(message);
253
+ void Promise.resolve(result).catch(() => { });
254
+ }
255
+ catch {
256
+ // Nowhere left to report to; the logger must never stop the scheduler.
257
+ }
258
+ }
259
+ /** Release a job's in-flight guard. Only ever called for the job it belongs to. */
260
+ release(job) {
261
+ job.runningAtMs = undefined;
262
+ job.skipReported = false;
263
+ }
264
+ setNextTrigger(job) {
265
+ job.nextTrigger = getTimestamp() + parseInt(job.interval, 10);
266
+ }
267
+ log(text, key = null) {
268
+ if (!config.cron?.log)
269
+ return;
270
+ // The key is consumer-controlled and reaches the log verbatim. Strip the
271
+ // line terminators so a key cannot forge a second, well-formed log line;
272
+ // the surrounding format is unchanged.
273
+ const tag = key ? `Cron::${key.replace(/[\r\n]+/g, ' ')}` : `Cron`;
274
+ log.cron(`${tag} - ${text}:`);
275
+ }
276
+ }
@@ -0,0 +1,13 @@
1
+ export interface HeapItem {
2
+ nextTrigger: number;
3
+ }
4
+ export default class MinHeap<T extends HeapItem> {
5
+ items: T[];
6
+ push(job: T): void;
7
+ pop(): T | undefined;
8
+ peek(): T | undefined;
9
+ bubbleUp(): void;
10
+ bubbleDown(): void;
11
+ remove(job: T): void;
12
+ isEmpty(): boolean;
13
+ }
@@ -0,0 +1,67 @@
1
+ export default class MinHeap {
2
+ items = [];
3
+ push(job) {
4
+ this.items.push(job);
5
+ this.bubbleUp();
6
+ }
7
+ pop() {
8
+ if (this.items.length <= 1)
9
+ return this.items.pop();
10
+ const top = this.items[0];
11
+ const last = this.items.pop();
12
+ if (last === undefined)
13
+ return top;
14
+ this.items[0] = last;
15
+ this.bubbleDown();
16
+ return top;
17
+ }
18
+ peek() {
19
+ return this.items[0];
20
+ }
21
+ bubbleUp() {
22
+ let idx = this.items.length - 1;
23
+ while (idx > 0) {
24
+ const parentIdx = Math.floor((idx - 1) / 2);
25
+ if (this.items[idx].nextTrigger >= this.items[parentIdx].nextTrigger)
26
+ break;
27
+ [this.items[idx], this.items[parentIdx]] = [this.items[parentIdx], this.items[idx]];
28
+ idx = parentIdx;
29
+ }
30
+ }
31
+ bubbleDown() {
32
+ let idx = 0;
33
+ const length = this.items.length;
34
+ while (true) {
35
+ const leftIdx = 2 * idx + 1;
36
+ const rightIdx = 2 * idx + 2;
37
+ let swapIdx = null;
38
+ if (leftIdx < length && this.items[leftIdx].nextTrigger < this.items[idx].nextTrigger) {
39
+ swapIdx = leftIdx;
40
+ }
41
+ if (rightIdx < length &&
42
+ this.items[rightIdx].nextTrigger < (swapIdx === null ? this.items[idx].nextTrigger : this.items[leftIdx].nextTrigger)) {
43
+ swapIdx = rightIdx;
44
+ }
45
+ if (swapIdx === null)
46
+ break;
47
+ [this.items[idx], this.items[swapIdx]] = [this.items[swapIdx], this.items[idx]];
48
+ idx = swapIdx;
49
+ }
50
+ }
51
+ remove(job) {
52
+ const idx = this.items.indexOf(job);
53
+ if (idx === -1)
54
+ return;
55
+ const end = this.items.pop();
56
+ if (end === undefined)
57
+ return;
58
+ if (idx < this.items.length) {
59
+ this.items[idx] = end;
60
+ this.bubbleUp();
61
+ this.bubbleDown();
62
+ }
63
+ }
64
+ isEmpty() {
65
+ return this.items.length === 0;
66
+ }
67
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Input normalization for AI-generated job definitions.
3
+ * Handles imperfect JSON from AI models: wrong casing, missing fields,
4
+ * flat-param recovery, type coercion.
5
+ */
6
+ interface RawSchedule {
7
+ kind?: string;
8
+ at?: string | number;
9
+ atMs?: number;
10
+ everyMs?: string | number;
11
+ expr?: string;
12
+ tz?: string;
13
+ }
14
+ interface RawPayload {
15
+ kind?: string;
16
+ message?: string;
17
+ text?: string;
18
+ [key: string]: unknown;
19
+ }
20
+ interface RawJobInput {
21
+ name?: string;
22
+ description?: string;
23
+ schedule?: RawSchedule;
24
+ payload?: RawPayload;
25
+ delivery?: Record<string, unknown>;
26
+ sessionTarget?: string;
27
+ wakeMode?: string;
28
+ enabled?: boolean;
29
+ deleteAfterRun?: boolean;
30
+ job?: RawJobInput;
31
+ message?: string;
32
+ text?: string;
33
+ [key: string]: unknown;
34
+ }
35
+ /**
36
+ * Normalize a schedule object. Infers kind from fields if missing.
37
+ */
38
+ export declare function normalizeSchedule(raw: unknown): RawSchedule;
39
+ /**
40
+ * Normalize a payload object. Infers kind from fields if missing.
41
+ */
42
+ export declare function normalizePayload(raw: unknown): RawPayload;
43
+ export declare function recoverFlatParams(params: RawJobInput): RawJobInput;
44
+ /**
45
+ * Normalize a complete job input for creation.
46
+ * Applies all normalization: schedule, payload, defaults.
47
+ */
48
+ export declare function normalizeJobInput(raw: RawJobInput): RawJobInput;
49
+ export {};
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Input normalization for AI-generated job definitions.
3
+ * Handles imperfect JSON from AI models: wrong casing, missing fields,
4
+ * flat-param recovery, type coercion.
5
+ */
6
+ /**
7
+ * Normalize a schedule object. Infers kind from fields if missing.
8
+ */
9
+ export function normalizeSchedule(raw) {
10
+ if (!raw || typeof raw !== 'object')
11
+ return raw;
12
+ const schedule = { ...raw };
13
+ // Infer kind from fields if missing
14
+ if (!schedule.kind) {
15
+ if (schedule.at || schedule.atMs)
16
+ schedule.kind = 'at';
17
+ else if (schedule.everyMs)
18
+ schedule.kind = 'every';
19
+ else if (schedule.expr)
20
+ schedule.kind = 'cron';
21
+ }
22
+ // Case normalization
23
+ if (typeof schedule.kind === 'string') {
24
+ schedule.kind = schedule.kind.toLowerCase();
25
+ }
26
+ // Legacy: atMs (number) -> at (ISO string)
27
+ if (schedule.atMs && !schedule.at) {
28
+ schedule.at = new Date(schedule.atMs).toISOString();
29
+ delete schedule.atMs;
30
+ }
31
+ // Coerce string everyMs to number
32
+ if (typeof schedule.everyMs === 'string') {
33
+ schedule.everyMs = Number(schedule.everyMs);
34
+ }
35
+ return schedule;
36
+ }
37
+ /**
38
+ * Normalize a payload object. Infers kind from fields if missing.
39
+ */
40
+ export function normalizePayload(raw) {
41
+ if (!raw || typeof raw !== 'object')
42
+ return raw;
43
+ const payload = { ...raw };
44
+ // Infer kind from fields
45
+ if (!payload.kind) {
46
+ if (payload.message)
47
+ payload.kind = 'agentTurn';
48
+ else if (payload.text)
49
+ payload.kind = 'systemEvent';
50
+ }
51
+ // Case normalization
52
+ if (typeof payload.kind === 'string') {
53
+ const lower = payload.kind.toLowerCase();
54
+ if (lower === 'agentturn')
55
+ payload.kind = 'agentTurn';
56
+ else if (lower === 'systemevent')
57
+ payload.kind = 'systemEvent';
58
+ }
59
+ return payload;
60
+ }
61
+ /**
62
+ * Recover a job object from flat parameters.
63
+ * AI models sometimes flatten nested fields to the top level.
64
+ */
65
+ const JOB_KEYS = new Set([
66
+ 'name', 'description', 'schedule', 'sessionTarget', 'payload',
67
+ 'delivery', 'enabled', 'deleteAfterRun', 'wakeMode',
68
+ ]);
69
+ export function recoverFlatParams(params) {
70
+ if (params.job && typeof params.job === 'object' && Object.keys(params.job).length > 0) {
71
+ return params.job;
72
+ }
73
+ const synthetic = {};
74
+ for (const key of Object.keys(params)) {
75
+ if (JOB_KEYS.has(key)) {
76
+ synthetic[key] = params[key];
77
+ }
78
+ }
79
+ // message/text are not JOB_KEYS but need to be recovered for payload wrapping
80
+ const message = params.message;
81
+ const text = params.text;
82
+ if (synthetic.schedule || synthetic.payload || message || text) {
83
+ // If message/text are at top level, wrap into payload
84
+ if (!synthetic.payload) {
85
+ if (message) {
86
+ synthetic.payload = { kind: 'agentTurn', message };
87
+ }
88
+ else if (text) {
89
+ synthetic.payload = { kind: 'systemEvent', text };
90
+ }
91
+ }
92
+ return synthetic;
93
+ }
94
+ return params;
95
+ }
96
+ /**
97
+ * Normalize a complete job input for creation.
98
+ * Applies all normalization: schedule, payload, defaults.
99
+ */
100
+ export function normalizeJobInput(raw) {
101
+ const job = { ...raw };
102
+ if (job.schedule) {
103
+ job.schedule = normalizeSchedule(job.schedule);
104
+ }
105
+ if (job.payload) {
106
+ job.payload = normalizePayload(job.payload);
107
+ }
108
+ // Default: enabled
109
+ if (job.enabled === undefined)
110
+ job.enabled = true;
111
+ // Default: wakeMode
112
+ if (!job.wakeMode)
113
+ job.wakeMode = 'now';
114
+ // Default: sessionTarget inferred from payload
115
+ if (!job.sessionTarget && job.payload) {
116
+ job.sessionTarget = job.payload.kind === 'systemEvent' ? 'main' : 'isolated';
117
+ }
118
+ // Default: deleteAfterRun for one-shot
119
+ if (job.deleteAfterRun === undefined && job.schedule?.kind === 'at') {
120
+ job.deleteAfterRun = true;
121
+ }
122
+ // Default: delivery for isolated agentTurn
123
+ if (!job.delivery && job.sessionTarget === 'isolated' && job.payload?.kind === 'agentTurn') {
124
+ job.delivery = { mode: 'announce' };
125
+ }
126
+ // Auto-generate name if missing
127
+ if (!job.name) {
128
+ job.name = inferName(job);
129
+ }
130
+ return job;
131
+ }
132
+ /**
133
+ * Infer a job name from schedule and payload.
134
+ */
135
+ function inferName(job) {
136
+ const parts = [];
137
+ if (job.schedule?.kind === 'at')
138
+ parts.push('One-shot');
139
+ else if (job.schedule?.kind === 'every')
140
+ parts.push('Recurring');
141
+ else if (job.schedule?.kind === 'cron')
142
+ parts.push('Scheduled');
143
+ if (job.payload?.kind === 'agentTurn')
144
+ parts.push('agent task');
145
+ else if (job.payload?.kind === 'systemEvent')
146
+ parts.push('system event');
147
+ return parts.join(' ') || 'Unnamed job';
148
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * In-memory run log for job execution history.
3
+ * Stores recent execution results per job with auto-pruning.
4
+ */
5
+ export interface RunLogEntry {
6
+ ts: number;
7
+ jobId: string;
8
+ status: string;
9
+ error?: string;
10
+ summary?: string;
11
+ runAtMs?: number;
12
+ durationMs?: number;
13
+ nextRunAtMs?: number;
14
+ }
15
+ export interface RunLogInput {
16
+ jobId: string;
17
+ status: string;
18
+ error?: string;
19
+ summary?: string;
20
+ runAtMs?: number;
21
+ durationMs?: number;
22
+ nextRunAtMs?: number;
23
+ }
24
+ export default class RunLog {
25
+ maxEntries: number;
26
+ entries: Map<string, RunLogEntry[]>;
27
+ constructor(maxEntriesPerJob?: number);
28
+ /**
29
+ * Record a job execution result.
30
+ */
31
+ record(entry: RunLogInput): void;
32
+ /**
33
+ * Get run history for a job.
34
+ */
35
+ get(jobId: string, limit?: number): RunLogEntry[];
36
+ /**
37
+ * Remove all entries for a job.
38
+ */
39
+ removeJob(jobId: string): void;
40
+ /**
41
+ * Clear all entries.
42
+ */
43
+ clear(): void;
44
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * In-memory run log for job execution history.
3
+ * Stores recent execution results per job with auto-pruning.
4
+ */
5
+ const DEFAULT_MAX_ENTRIES_PER_JOB = 100;
6
+ export default class RunLog {
7
+ maxEntries;
8
+ entries;
9
+ constructor(maxEntriesPerJob = DEFAULT_MAX_ENTRIES_PER_JOB) {
10
+ this.maxEntries = maxEntriesPerJob;
11
+ this.entries = new Map();
12
+ }
13
+ /**
14
+ * Record a job execution result.
15
+ */
16
+ record(entry) {
17
+ const log = {
18
+ ts: Date.now(),
19
+ jobId: entry.jobId,
20
+ status: entry.status,
21
+ error: entry.error,
22
+ summary: entry.summary,
23
+ runAtMs: entry.runAtMs,
24
+ durationMs: entry.durationMs,
25
+ nextRunAtMs: entry.nextRunAtMs,
26
+ };
27
+ if (!this.entries.has(entry.jobId)) {
28
+ this.entries.set(entry.jobId, []);
29
+ }
30
+ const logs = this.entries.get(entry.jobId);
31
+ if (!logs)
32
+ return;
33
+ logs.push(log);
34
+ // Auto-prune
35
+ if (logs.length > this.maxEntries) {
36
+ logs.splice(0, logs.length - this.maxEntries);
37
+ }
38
+ }
39
+ /**
40
+ * Get run history for a job.
41
+ */
42
+ get(jobId, limit = 20) {
43
+ const logs = this.entries.get(jobId);
44
+ if (!logs)
45
+ return [];
46
+ return logs.slice(-limit).reverse();
47
+ }
48
+ /**
49
+ * Remove all entries for a job.
50
+ */
51
+ removeJob(jobId) {
52
+ this.entries.delete(jobId);
53
+ }
54
+ /**
55
+ * Clear all entries.
56
+ */
57
+ clear() {
58
+ this.entries.clear();
59
+ }
60
+ }
@@ -0,0 +1,23 @@
1
+ export interface AtSchedule {
2
+ kind: 'at';
3
+ at: string | number;
4
+ }
5
+ export interface EverySchedule {
6
+ kind: 'every';
7
+ everyMs: number;
8
+ anchorMs?: number;
9
+ }
10
+ export interface CronSchedule {
11
+ kind: 'cron';
12
+ expr: string;
13
+ tz?: string;
14
+ }
15
+ export type Schedule = AtSchedule | EverySchedule | CronSchedule;
16
+ /**
17
+ * Compute the next run time for a schedule.
18
+ */
19
+ export declare function computeNextRunAtMs(schedule: Schedule, nowMs: number): number | undefined;
20
+ /**
21
+ * Validate a schedule definition.
22
+ */
23
+ export declare function validateSchedule(schedule: Schedule): void;