@cronvello/sdk 0.1.4 → 0.2.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/CHANGELOG.md +45 -0
- package/README.md +135 -2
- package/dist/cli.cjs +1092 -8
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +1088 -8
- package/dist/cli.js.map +1 -1
- package/dist/dev.cjs +1186 -0
- package/dist/dev.cjs.map +1 -0
- package/dist/dev.d.cts +318 -0
- package/dist/dev.d.ts +318 -0
- package/dist/dev.js +1173 -0
- package/dist/dev.js.map +1 -0
- package/dist/index.cjs +645 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +23 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +644 -7
- package/dist/index.js.map +1 -1
- package/docs/dashboard.png +0 -0
- package/package.json +12 -1
package/dist/index.cjs
CHANGED
|
@@ -528,7 +528,7 @@ function createDispatcher(state) {
|
|
|
528
528
|
throw error;
|
|
529
529
|
}
|
|
530
530
|
}
|
|
531
|
-
function buildContext(key, job, req, body, isAsync, source) {
|
|
531
|
+
function buildContext(key, job, req, body, isAsync, source, signal) {
|
|
532
532
|
return {
|
|
533
533
|
key,
|
|
534
534
|
schedule: typeof body["schedule"] === "string" ? body["schedule"] : job.config.schedule ?? "",
|
|
@@ -538,7 +538,7 @@ function createDispatcher(state) {
|
|
|
538
538
|
isAsync,
|
|
539
539
|
source,
|
|
540
540
|
logger: log,
|
|
541
|
-
signal: req?.signal
|
|
541
|
+
signal: req?.signal ?? signal
|
|
542
542
|
};
|
|
543
543
|
}
|
|
544
544
|
async function handle(req) {
|
|
@@ -588,11 +588,11 @@ function createDispatcher(state) {
|
|
|
588
588
|
return resp(500, { ok: false, job: key, error: err instanceof Error ? err.message : String(err) });
|
|
589
589
|
}
|
|
590
590
|
}
|
|
591
|
-
async function runLocal(key, payload) {
|
|
591
|
+
async function runLocal(key, payload, opts) {
|
|
592
592
|
const job = state.jobs.get(key);
|
|
593
593
|
if (!job) throw new Error(`Unknown job '${key}'. Known: ${[...state.jobs.keys()].join(", ") || "(none)"}`);
|
|
594
594
|
const body = { job: key, schedule: job.config.schedule, ...payload ?? {} };
|
|
595
|
-
const ctx = buildContext(key, job, null, body, false, "local");
|
|
595
|
+
const ctx = buildContext(key, job, null, body, false, "local", opts?.signal);
|
|
596
596
|
const { result } = await invokeHandler(job, ctx);
|
|
597
597
|
return result;
|
|
598
598
|
}
|
|
@@ -879,6 +879,610 @@ function nextHandler(app) {
|
|
|
879
879
|
};
|
|
880
880
|
}
|
|
881
881
|
|
|
882
|
+
// src/internal/cron-schedule.ts
|
|
883
|
+
var MACRO_EXPANSIONS = {
|
|
884
|
+
"@yearly": "0 0 1 1 *",
|
|
885
|
+
"@annually": "0 0 1 1 *",
|
|
886
|
+
"@monthly": "0 0 1 * *",
|
|
887
|
+
"@weekly": "0 0 * * 0",
|
|
888
|
+
"@daily": "0 0 * * *",
|
|
889
|
+
"@midnight": "0 0 * * *",
|
|
890
|
+
"@hourly": "0 * * * *"
|
|
891
|
+
};
|
|
892
|
+
var MONTH_NAMES = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
|
|
893
|
+
var DOW_NAMES = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
894
|
+
var SECOND_SPEC = { min: 0, max: 59, nameOffset: 0, label: "second" };
|
|
895
|
+
var MINUTE_SPEC = { min: 0, max: 59, nameOffset: 0, label: "minute" };
|
|
896
|
+
var HOUR_SPEC = { min: 0, max: 23, nameOffset: 0, label: "hour" };
|
|
897
|
+
var DOM_SPEC = { min: 1, max: 31, nameOffset: 0, label: "day-of-month" };
|
|
898
|
+
var MONTH_SPEC = { min: 1, max: 12, names: MONTH_NAMES, nameOffset: 1, label: "month" };
|
|
899
|
+
var DOW_SPEC = { min: 0, max: 7, names: DOW_NAMES, nameOffset: 0, fold: (v) => v % 7, label: "day-of-week" };
|
|
900
|
+
function parseCron(expr) {
|
|
901
|
+
if (typeof expr !== "string" || !expr.trim()) throw new Error("cron expression is empty");
|
|
902
|
+
let trimmed = expr.trim();
|
|
903
|
+
if (trimmed.startsWith("@")) {
|
|
904
|
+
const macro = trimmed.toLowerCase();
|
|
905
|
+
if (macro === "@reboot") {
|
|
906
|
+
return {
|
|
907
|
+
seconds: /* @__PURE__ */ new Set([0]),
|
|
908
|
+
minutes: /* @__PURE__ */ new Set(),
|
|
909
|
+
hours: /* @__PURE__ */ new Set(),
|
|
910
|
+
daysOfMonth: /* @__PURE__ */ new Set(),
|
|
911
|
+
months: /* @__PURE__ */ new Set(),
|
|
912
|
+
daysOfWeek: /* @__PURE__ */ new Set(),
|
|
913
|
+
domRestricted: false,
|
|
914
|
+
dowRestricted: false,
|
|
915
|
+
reboot: true
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
const expanded = MACRO_EXPANSIONS[macro];
|
|
919
|
+
if (!expanded) throw new Error(`unknown cron macro "${trimmed}" (try @daily, @hourly, \u2026)`);
|
|
920
|
+
trimmed = expanded;
|
|
921
|
+
}
|
|
922
|
+
const parts = trimmed.split(/\s+/);
|
|
923
|
+
if (parts.length !== 5 && parts.length !== 6) {
|
|
924
|
+
throw new Error(`expected 5 fields (min hour dom month dow) or 6 with seconds, got ${parts.length}: "${trimmed}"`);
|
|
925
|
+
}
|
|
926
|
+
const hasSeconds = parts.length === 6;
|
|
927
|
+
const [secRaw, minRaw, hourRaw, domRaw, monthRaw, dowRaw] = hasSeconds ? parts : ["0", ...parts];
|
|
928
|
+
return {
|
|
929
|
+
seconds: expandField(secRaw, SECOND_SPEC),
|
|
930
|
+
minutes: expandField(minRaw, MINUTE_SPEC),
|
|
931
|
+
hours: expandField(hourRaw, HOUR_SPEC),
|
|
932
|
+
daysOfMonth: expandField(domRaw, DOM_SPEC),
|
|
933
|
+
months: expandField(monthRaw, MONTH_SPEC),
|
|
934
|
+
daysOfWeek: expandField(dowRaw, DOW_SPEC),
|
|
935
|
+
domRestricted: isRestricted(domRaw),
|
|
936
|
+
dowRestricted: isRestricted(dowRaw),
|
|
937
|
+
reboot: false
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
function isRestricted(field2) {
|
|
941
|
+
const f = field2.trim();
|
|
942
|
+
return f !== "*" && f !== "?";
|
|
943
|
+
}
|
|
944
|
+
function expandField(raw, spec) {
|
|
945
|
+
const set = /* @__PURE__ */ new Set();
|
|
946
|
+
for (const term of raw.split(",")) {
|
|
947
|
+
if (term === "") throw new Error(`empty term in ${spec.label} field "${raw}"`);
|
|
948
|
+
let base = term;
|
|
949
|
+
let step = 1;
|
|
950
|
+
const slash = term.indexOf("/");
|
|
951
|
+
if (slash >= 0) {
|
|
952
|
+
base = term.slice(0, slash);
|
|
953
|
+
const stepStr = term.slice(slash + 1);
|
|
954
|
+
if (!/^\d+$/.test(stepStr) || Number(stepStr) === 0) {
|
|
955
|
+
throw new Error(`invalid step "${stepStr}" in ${spec.label} field "${raw}"`);
|
|
956
|
+
}
|
|
957
|
+
step = Number(stepStr);
|
|
958
|
+
}
|
|
959
|
+
let lo;
|
|
960
|
+
let hi;
|
|
961
|
+
if (base === "*" || base === "?") {
|
|
962
|
+
lo = spec.min;
|
|
963
|
+
hi = spec.max;
|
|
964
|
+
} else {
|
|
965
|
+
const dash = base.indexOf("-");
|
|
966
|
+
if (dash > 0) {
|
|
967
|
+
lo = resolveValue2(base.slice(0, dash), spec);
|
|
968
|
+
hi = resolveValue2(base.slice(dash + 1), spec);
|
|
969
|
+
} else {
|
|
970
|
+
lo = resolveValue2(base, spec);
|
|
971
|
+
hi = step > 1 ? spec.max : lo;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
if (lo === null || hi === null) {
|
|
975
|
+
throw new Error(`value out of range in ${spec.label} field "${raw}" (${spec.min}-${spec.max})`);
|
|
976
|
+
}
|
|
977
|
+
if (lo > hi) throw new Error(`range start ${lo} is greater than end ${hi} in ${spec.label} field "${raw}"`);
|
|
978
|
+
for (let v = lo; v <= hi; v += step) set.add(spec.fold ? spec.fold(v) : v);
|
|
979
|
+
}
|
|
980
|
+
return set;
|
|
981
|
+
}
|
|
982
|
+
function resolveValue2(token, spec) {
|
|
983
|
+
const t = token.trim();
|
|
984
|
+
if (/^\d+$/.test(t)) {
|
|
985
|
+
const n = Number(t);
|
|
986
|
+
return n >= spec.min && n <= spec.max ? n : null;
|
|
987
|
+
}
|
|
988
|
+
if (spec.names) {
|
|
989
|
+
const idx = spec.names.indexOf(t.toLowerCase());
|
|
990
|
+
if (idx >= 0) return idx + spec.nameOffset;
|
|
991
|
+
}
|
|
992
|
+
return null;
|
|
993
|
+
}
|
|
994
|
+
var SEARCH_HORIZON_YEARS = 5;
|
|
995
|
+
function nextOccurrence(expr, opts = {}) {
|
|
996
|
+
const parsed = typeof expr === "string" ? parseCron(expr) : expr;
|
|
997
|
+
if (parsed.reboot) throw new Error("@reboot has no scheduled next occurrence (the engine fires it once at start)");
|
|
998
|
+
const tz = opts.timeZone ?? "UTC";
|
|
999
|
+
const fromMs = opts.from === void 0 ? Date.now() : typeof opts.from === "number" ? opts.from : opts.from.getTime();
|
|
1000
|
+
const cursor = Math.floor(fromMs / 1e3) * 1e3 + 1e3;
|
|
1001
|
+
const p = getZonedParts(cursor, tz);
|
|
1002
|
+
const startYear = p.y;
|
|
1003
|
+
const hourArr = sorted(parsed.hours);
|
|
1004
|
+
const minuteArr = sorted(parsed.minutes);
|
|
1005
|
+
const secondArr = sorted(parsed.seconds);
|
|
1006
|
+
let guard = 0;
|
|
1007
|
+
while (guard++ < 1e6) {
|
|
1008
|
+
if (p.y > startYear + SEARCH_HORIZON_YEARS) return null;
|
|
1009
|
+
if (!parsed.months.has(p.mo)) {
|
|
1010
|
+
bumpMonth(p);
|
|
1011
|
+
continue;
|
|
1012
|
+
}
|
|
1013
|
+
if (p.d > daysInMonth(p.y, p.mo)) {
|
|
1014
|
+
bumpMonth(p);
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
if (!dayMatches(parsed, p.y, p.mo, p.d)) {
|
|
1018
|
+
bumpDay(p);
|
|
1019
|
+
continue;
|
|
1020
|
+
}
|
|
1021
|
+
const nh = firstAtLeast(hourArr, p.h);
|
|
1022
|
+
if (nh === null) {
|
|
1023
|
+
bumpDay(p);
|
|
1024
|
+
continue;
|
|
1025
|
+
}
|
|
1026
|
+
if (nh !== p.h) {
|
|
1027
|
+
p.h = nh;
|
|
1028
|
+
p.mi = 0;
|
|
1029
|
+
p.s = 0;
|
|
1030
|
+
}
|
|
1031
|
+
const nmi = firstAtLeast(minuteArr, p.mi);
|
|
1032
|
+
if (nmi === null) {
|
|
1033
|
+
p.h += 1;
|
|
1034
|
+
p.mi = 0;
|
|
1035
|
+
p.s = 0;
|
|
1036
|
+
continue;
|
|
1037
|
+
}
|
|
1038
|
+
if (nmi !== p.mi) {
|
|
1039
|
+
p.mi = nmi;
|
|
1040
|
+
p.s = 0;
|
|
1041
|
+
}
|
|
1042
|
+
const ns = firstAtLeast(secondArr, p.s);
|
|
1043
|
+
if (ns === null) {
|
|
1044
|
+
p.mi += 1;
|
|
1045
|
+
p.s = 0;
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
p.s = ns;
|
|
1049
|
+
const epoch = zonedWallToEpoch(p, tz);
|
|
1050
|
+
if (epoch <= fromMs) {
|
|
1051
|
+
p.s += 1;
|
|
1052
|
+
continue;
|
|
1053
|
+
}
|
|
1054
|
+
return new Date(epoch);
|
|
1055
|
+
}
|
|
1056
|
+
throw new Error(`nextOccurrence: search exceeded its iteration bound for "${typeof expr === "string" ? expr : "(parsed)"}"`);
|
|
1057
|
+
}
|
|
1058
|
+
function dayMatches(parsed, y, mo, d) {
|
|
1059
|
+
const domOk = parsed.daysOfMonth.has(d);
|
|
1060
|
+
const dowOk = parsed.daysOfWeek.has(weekdayOf(y, mo, d));
|
|
1061
|
+
if (parsed.domRestricted && parsed.dowRestricted) return domOk || dowOk;
|
|
1062
|
+
if (parsed.domRestricted) return domOk;
|
|
1063
|
+
if (parsed.dowRestricted) return dowOk;
|
|
1064
|
+
return true;
|
|
1065
|
+
}
|
|
1066
|
+
function bumpMonth(p) {
|
|
1067
|
+
p.mo += 1;
|
|
1068
|
+
if (p.mo > 12) {
|
|
1069
|
+
p.mo = 1;
|
|
1070
|
+
p.y += 1;
|
|
1071
|
+
}
|
|
1072
|
+
p.d = 1;
|
|
1073
|
+
p.h = 0;
|
|
1074
|
+
p.mi = 0;
|
|
1075
|
+
p.s = 0;
|
|
1076
|
+
}
|
|
1077
|
+
function bumpDay(p) {
|
|
1078
|
+
p.d += 1;
|
|
1079
|
+
p.h = 0;
|
|
1080
|
+
p.mi = 0;
|
|
1081
|
+
p.s = 0;
|
|
1082
|
+
}
|
|
1083
|
+
function sorted(set) {
|
|
1084
|
+
return [...set].sort((a, b) => a - b);
|
|
1085
|
+
}
|
|
1086
|
+
function firstAtLeast(arr, v) {
|
|
1087
|
+
for (const x of arr) if (x >= v) return x;
|
|
1088
|
+
return null;
|
|
1089
|
+
}
|
|
1090
|
+
function daysInMonth(year, month) {
|
|
1091
|
+
return new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
1092
|
+
}
|
|
1093
|
+
function weekdayOf(year, month, day) {
|
|
1094
|
+
return new Date(Date.UTC(year, month - 1, day)).getUTCDay();
|
|
1095
|
+
}
|
|
1096
|
+
var FORMATTER_CACHE = /* @__PURE__ */ new Map();
|
|
1097
|
+
function formatterFor(timeZone) {
|
|
1098
|
+
let fmt = FORMATTER_CACHE.get(timeZone);
|
|
1099
|
+
if (!fmt) {
|
|
1100
|
+
fmt = new Intl.DateTimeFormat("en-US", {
|
|
1101
|
+
timeZone,
|
|
1102
|
+
year: "numeric",
|
|
1103
|
+
month: "2-digit",
|
|
1104
|
+
day: "2-digit",
|
|
1105
|
+
hour: "2-digit",
|
|
1106
|
+
minute: "2-digit",
|
|
1107
|
+
second: "2-digit",
|
|
1108
|
+
hour12: false
|
|
1109
|
+
});
|
|
1110
|
+
FORMATTER_CACHE.set(timeZone, fmt);
|
|
1111
|
+
}
|
|
1112
|
+
return fmt;
|
|
1113
|
+
}
|
|
1114
|
+
function getZonedParts(epochMs, timeZone) {
|
|
1115
|
+
const parts = formatterFor(timeZone).formatToParts(new Date(epochMs));
|
|
1116
|
+
const m = {};
|
|
1117
|
+
for (const part of parts) if (part.type !== "literal") m[part.type] = part.value;
|
|
1118
|
+
let h = Number(m["hour"]);
|
|
1119
|
+
if (h === 24) h = 0;
|
|
1120
|
+
return { y: Number(m["year"]), mo: Number(m["month"]), d: Number(m["day"]), h, mi: Number(m["minute"]), s: Number(m["second"]) };
|
|
1121
|
+
}
|
|
1122
|
+
function offsetAt(epochMs, timeZone) {
|
|
1123
|
+
const p = getZonedParts(epochMs, timeZone);
|
|
1124
|
+
const asNaive = Date.UTC(p.y, p.mo - 1, p.d, p.h, p.mi, p.s);
|
|
1125
|
+
return asNaive - epochMs;
|
|
1126
|
+
}
|
|
1127
|
+
function zonedWallToEpoch(p, timeZone) {
|
|
1128
|
+
const asUTC = Date.UTC(p.y, p.mo - 1, p.d, p.h, p.mi, p.s);
|
|
1129
|
+
const o1 = offsetAt(asUTC, timeZone);
|
|
1130
|
+
let epoch = asUTC - o1;
|
|
1131
|
+
const o2 = offsetAt(epoch, timeZone);
|
|
1132
|
+
if (o2 !== o1) epoch = asUTC - o2;
|
|
1133
|
+
return epoch;
|
|
1134
|
+
}
|
|
1135
|
+
function previewSchedule(expr, opts = {}) {
|
|
1136
|
+
const parsed = parseCron(expr);
|
|
1137
|
+
const timeZone = opts.timeZone ?? localTimeZone();
|
|
1138
|
+
const count = Math.min(Math.max(Math.trunc(opts.count ?? 5), 1), 100);
|
|
1139
|
+
const out = [];
|
|
1140
|
+
let from = opts.from === void 0 ? Date.now() : typeof opts.from === "number" ? opts.from : opts.from.getTime();
|
|
1141
|
+
for (let i = 0; i < count; i++) {
|
|
1142
|
+
const next = nextOccurrence(parsed, { from, timeZone });
|
|
1143
|
+
if (!next) break;
|
|
1144
|
+
out.push(next);
|
|
1145
|
+
from = next.getTime();
|
|
1146
|
+
}
|
|
1147
|
+
return out;
|
|
1148
|
+
}
|
|
1149
|
+
function localTimeZone() {
|
|
1150
|
+
try {
|
|
1151
|
+
return new Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
1152
|
+
} catch {
|
|
1153
|
+
return "UTC";
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
// src/dev/engine.ts
|
|
1158
|
+
var DEFAULT_HISTORY_LIMIT = 100;
|
|
1159
|
+
var MAX_TIMER_MS = 2 ** 31 - 1;
|
|
1160
|
+
function defaultBackoff(attempt) {
|
|
1161
|
+
return Math.min(3e4, 500 * 2 ** (attempt - 1));
|
|
1162
|
+
}
|
|
1163
|
+
var realClock = {
|
|
1164
|
+
now: () => Date.now(),
|
|
1165
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
1166
|
+
clearTimeout: (handle) => clearTimeout(handle)
|
|
1167
|
+
};
|
|
1168
|
+
var RunTimeoutError = class extends Error {
|
|
1169
|
+
constructor(key, ms) {
|
|
1170
|
+
super(`job '${key}' timed out after ${ms}ms`);
|
|
1171
|
+
this.name = "RunTimeoutError";
|
|
1172
|
+
}
|
|
1173
|
+
};
|
|
1174
|
+
function createLocalEngine(jobs, runner, options = {}) {
|
|
1175
|
+
return new LocalEngine(jobs, runner, options);
|
|
1176
|
+
}
|
|
1177
|
+
var LocalEngine = class {
|
|
1178
|
+
clock;
|
|
1179
|
+
/** Every event listener. The constructor's `onEvent` is registered as one of them. */
|
|
1180
|
+
listeners = /* @__PURE__ */ new Set();
|
|
1181
|
+
/** Run after the engine has drained, e.g. to close a dashboard server. */
|
|
1182
|
+
closeHooks = [];
|
|
1183
|
+
historyLimit;
|
|
1184
|
+
backoff;
|
|
1185
|
+
runner;
|
|
1186
|
+
states;
|
|
1187
|
+
history = [];
|
|
1188
|
+
inFlight = /* @__PURE__ */ new Set();
|
|
1189
|
+
started = false;
|
|
1190
|
+
stopped = false;
|
|
1191
|
+
signalCleanup = null;
|
|
1192
|
+
constructor(jobs, runner, options = {}) {
|
|
1193
|
+
this.clock = options.clock ?? realClock;
|
|
1194
|
+
if (options.onEvent) this.listeners.add(options.onEvent);
|
|
1195
|
+
this.historyLimit = Math.max(1, options.historyLimit ?? DEFAULT_HISTORY_LIMIT);
|
|
1196
|
+
this.backoff = options.backoff ?? defaultBackoff;
|
|
1197
|
+
this.runner = runner;
|
|
1198
|
+
this.states = jobs.map((job) => ({
|
|
1199
|
+
job,
|
|
1200
|
+
nextFire: null,
|
|
1201
|
+
timer: null,
|
|
1202
|
+
running: false,
|
|
1203
|
+
isReboot: job.schedule.trim().toLowerCase() === "@reboot"
|
|
1204
|
+
}));
|
|
1205
|
+
if (options.installSignalHandlers) this.installSignalHandlers();
|
|
1206
|
+
}
|
|
1207
|
+
/**
|
|
1208
|
+
* Subscribe to every lifecycle event (in addition to the constructor's `onEvent`). Returns an
|
|
1209
|
+
* unsubscribe function. Used by the local dashboard to fan events out to many SSE clients without
|
|
1210
|
+
* disturbing the scheduler. A listener that throws is isolated — it can't break the loop.
|
|
1211
|
+
*/
|
|
1212
|
+
subscribe(listener) {
|
|
1213
|
+
this.listeners.add(listener);
|
|
1214
|
+
return () => {
|
|
1215
|
+
this.listeners.delete(listener);
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
/**
|
|
1219
|
+
* Register a hook to run once, after {@link stop} has drained in-flight runs — e.g. to close a
|
|
1220
|
+
* dashboard server so `engine.stop()` tears everything down together. Hooks are awaited.
|
|
1221
|
+
*/
|
|
1222
|
+
onStop(hook) {
|
|
1223
|
+
this.closeHooks.push(hook);
|
|
1224
|
+
return this;
|
|
1225
|
+
}
|
|
1226
|
+
/** Deliver an event to every listener, isolating each so one bad listener can't stall the loop. */
|
|
1227
|
+
emit(event) {
|
|
1228
|
+
for (const listener of this.listeners) {
|
|
1229
|
+
try {
|
|
1230
|
+
listener(event);
|
|
1231
|
+
} catch {
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
/** Begin scheduling. Idempotent — a second call is a no-op. */
|
|
1236
|
+
start() {
|
|
1237
|
+
if (this.started) return this;
|
|
1238
|
+
this.started = true;
|
|
1239
|
+
this.stopped = false;
|
|
1240
|
+
this.emit({ type: "engine-start", jobs: this.states.length, at: this.clock.now() });
|
|
1241
|
+
for (const state of this.states) {
|
|
1242
|
+
if (state.isReboot) {
|
|
1243
|
+
this.launch(state);
|
|
1244
|
+
} else {
|
|
1245
|
+
this.scheduleNext(state);
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
return this;
|
|
1249
|
+
}
|
|
1250
|
+
/**
|
|
1251
|
+
* Stop scheduling and wait for in-flight runs to settle. After this resolves no further handlers
|
|
1252
|
+
* will start. Safe to call from a signal handler.
|
|
1253
|
+
*/
|
|
1254
|
+
async stop() {
|
|
1255
|
+
if (this.stopped) {
|
|
1256
|
+
await Promise.allSettled([...this.inFlight]);
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
this.stopped = true;
|
|
1260
|
+
for (const state of this.states) {
|
|
1261
|
+
if (state.timer !== null) {
|
|
1262
|
+
this.clock.clearTimeout(state.timer);
|
|
1263
|
+
state.timer = null;
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
this.signalCleanup?.();
|
|
1267
|
+
this.signalCleanup = null;
|
|
1268
|
+
await Promise.allSettled([...this.inFlight]);
|
|
1269
|
+
this.emit({ type: "engine-stop", at: this.clock.now() });
|
|
1270
|
+
for (const hook of this.closeHooks.splice(0)) {
|
|
1271
|
+
try {
|
|
1272
|
+
await hook();
|
|
1273
|
+
} catch {
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
/** The run history, newest first (a copy — safe to keep). */
|
|
1278
|
+
runs() {
|
|
1279
|
+
return [...this.history].reverse();
|
|
1280
|
+
}
|
|
1281
|
+
/** History entries for one job, newest first. */
|
|
1282
|
+
runsFor(key) {
|
|
1283
|
+
return this.runs().filter((r) => r.key === key);
|
|
1284
|
+
}
|
|
1285
|
+
/** Current scheduling state of every job, for the dev table. */
|
|
1286
|
+
snapshot() {
|
|
1287
|
+
return this.states.map((s) => ({
|
|
1288
|
+
key: s.job.key,
|
|
1289
|
+
schedule: s.job.schedule,
|
|
1290
|
+
timeZone: s.job.timeZone,
|
|
1291
|
+
...s.job.description !== void 0 ? { description: s.job.description } : {},
|
|
1292
|
+
nextFire: s.nextFire !== null ? new Date(s.nextFire) : null,
|
|
1293
|
+
running: s.running
|
|
1294
|
+
}));
|
|
1295
|
+
}
|
|
1296
|
+
/** The jobs this engine manages (read-only view). */
|
|
1297
|
+
jobs() {
|
|
1298
|
+
return this.states.map((s) => s.job);
|
|
1299
|
+
}
|
|
1300
|
+
/** Number of runs currently in flight. */
|
|
1301
|
+
get activeRuns() {
|
|
1302
|
+
return this.inFlight.size;
|
|
1303
|
+
}
|
|
1304
|
+
// ── Scheduling ─────────────────────────────────────────────────────────────
|
|
1305
|
+
scheduleNext(state) {
|
|
1306
|
+
if (this.stopped) return;
|
|
1307
|
+
const now = this.clock.now();
|
|
1308
|
+
let next;
|
|
1309
|
+
try {
|
|
1310
|
+
next = nextOccurrence(state.job.schedule, { from: now, timeZone: state.job.timeZone });
|
|
1311
|
+
} catch {
|
|
1312
|
+
state.nextFire = null;
|
|
1313
|
+
return;
|
|
1314
|
+
}
|
|
1315
|
+
if (!next) {
|
|
1316
|
+
state.nextFire = null;
|
|
1317
|
+
return;
|
|
1318
|
+
}
|
|
1319
|
+
state.nextFire = next.getTime();
|
|
1320
|
+
const delay = Math.max(0, Math.min(state.nextFire - now, MAX_TIMER_MS));
|
|
1321
|
+
state.timer = this.clock.setTimeout(() => this.onDue(state), delay);
|
|
1322
|
+
this.emit({ type: "scheduled", key: state.job.key, at: state.nextFire });
|
|
1323
|
+
}
|
|
1324
|
+
onDue(state) {
|
|
1325
|
+
state.timer = null;
|
|
1326
|
+
if (this.stopped) return;
|
|
1327
|
+
const now = this.clock.now();
|
|
1328
|
+
if (state.nextFire !== null && now < state.nextFire) {
|
|
1329
|
+
const delay = Math.max(0, Math.min(state.nextFire - now, MAX_TIMER_MS));
|
|
1330
|
+
state.timer = this.clock.setTimeout(() => this.onDue(state), delay);
|
|
1331
|
+
return;
|
|
1332
|
+
}
|
|
1333
|
+
if (state.running && !state.job.allowConcurrentRuns) {
|
|
1334
|
+
this.emit({ type: "skipped", key: state.job.key, reason: "overlap", at: now });
|
|
1335
|
+
this.record({
|
|
1336
|
+
key: state.job.key,
|
|
1337
|
+
source: "local",
|
|
1338
|
+
startedAt: now,
|
|
1339
|
+
finishedAt: now,
|
|
1340
|
+
durationMs: 0,
|
|
1341
|
+
status: "skipped",
|
|
1342
|
+
attempts: 0
|
|
1343
|
+
});
|
|
1344
|
+
} else {
|
|
1345
|
+
this.launch(state);
|
|
1346
|
+
}
|
|
1347
|
+
this.scheduleNext(state);
|
|
1348
|
+
}
|
|
1349
|
+
/**
|
|
1350
|
+
* Run a job once, right now, by key — the local equivalent of "run now" in the cloud. Goes through
|
|
1351
|
+
* the exact same execution path as a scheduled fire (overlap protection, timeout, retry/backoff,
|
|
1352
|
+
* history + events), so a manual run shows up in the feed just like any other. Resolves with the
|
|
1353
|
+
* resulting {@link RunRecord}. Throws for an unknown key or after the engine has stopped.
|
|
1354
|
+
*/
|
|
1355
|
+
async trigger(key) {
|
|
1356
|
+
if (this.stopped) throw new Error("cannot trigger a job on a stopped engine");
|
|
1357
|
+
const state = this.states.find((s) => s.job.key === key);
|
|
1358
|
+
if (!state) throw new Error(`unknown job '${key}'`);
|
|
1359
|
+
if (state.running && !state.job.allowConcurrentRuns) {
|
|
1360
|
+
const now = this.clock.now();
|
|
1361
|
+
const skipped = { key, source: "local", startedAt: now, finishedAt: now, durationMs: 0, status: "skipped", attempts: 0 };
|
|
1362
|
+
this.emit({ type: "skipped", key, reason: "overlap", at: now });
|
|
1363
|
+
this.record(skipped);
|
|
1364
|
+
return skipped;
|
|
1365
|
+
}
|
|
1366
|
+
return this.launch(state);
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* The run history as newline-delimited JSON (NDJSON), oldest run first — one record per line, the
|
|
1370
|
+
* natural shape for piping to a file or another tool. No trailing newline.
|
|
1371
|
+
*/
|
|
1372
|
+
toNdjson() {
|
|
1373
|
+
return this.history.map((r) => JSON.stringify(r)).join("\n");
|
|
1374
|
+
}
|
|
1375
|
+
/** Start an execution and track it so {@link stop} can await it. Resolves with the run's record. */
|
|
1376
|
+
launch(state) {
|
|
1377
|
+
const promise = this.execute(state);
|
|
1378
|
+
const tracked = promise.finally(() => {
|
|
1379
|
+
this.inFlight.delete(tracked);
|
|
1380
|
+
});
|
|
1381
|
+
this.inFlight.add(tracked);
|
|
1382
|
+
return tracked;
|
|
1383
|
+
}
|
|
1384
|
+
// ── Execution with timeout + retry/backoff ──────────────────────────────────
|
|
1385
|
+
async execute(state) {
|
|
1386
|
+
const job = state.job;
|
|
1387
|
+
state.running = true;
|
|
1388
|
+
const startedAt = this.clock.now();
|
|
1389
|
+
const maxRetries = Math.max(0, job.maxRetries ?? 0);
|
|
1390
|
+
let attempt = 0;
|
|
1391
|
+
let status = "error";
|
|
1392
|
+
let error;
|
|
1393
|
+
let result;
|
|
1394
|
+
while (!this.stopped) {
|
|
1395
|
+
attempt++;
|
|
1396
|
+
this.emit({ type: "fire", key: job.key, attempt, at: this.clock.now() });
|
|
1397
|
+
try {
|
|
1398
|
+
result = await this.runOnce(job);
|
|
1399
|
+
status = "success";
|
|
1400
|
+
this.emit({ type: "success", key: job.key, durationMs: this.clock.now() - startedAt, attempts: attempt, result, at: this.clock.now() });
|
|
1401
|
+
error = void 0;
|
|
1402
|
+
break;
|
|
1403
|
+
} catch (err) {
|
|
1404
|
+
const timedOut = err instanceof RunTimeoutError;
|
|
1405
|
+
status = timedOut ? "timed_out" : "error";
|
|
1406
|
+
error = err instanceof Error ? err.message : String(err);
|
|
1407
|
+
const willRetry = attempt <= maxRetries && !this.stopped;
|
|
1408
|
+
const at = this.clock.now();
|
|
1409
|
+
if (timedOut) {
|
|
1410
|
+
this.emit({ type: "timeout", key: job.key, durationMs: at - startedAt, attempt, willRetry, at });
|
|
1411
|
+
} else {
|
|
1412
|
+
this.emit({ type: "error", key: job.key, durationMs: at - startedAt, attempt, willRetry, error, at });
|
|
1413
|
+
}
|
|
1414
|
+
if (!willRetry) break;
|
|
1415
|
+
const delayMs = this.backoff(attempt);
|
|
1416
|
+
this.emit({ type: "retry", key: job.key, attempt: attempt + 1, delayMs, at });
|
|
1417
|
+
await this.sleep(delayMs);
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
const finishedAt = this.clock.now();
|
|
1421
|
+
const record = {
|
|
1422
|
+
key: job.key,
|
|
1423
|
+
source: "local",
|
|
1424
|
+
startedAt,
|
|
1425
|
+
finishedAt,
|
|
1426
|
+
durationMs: finishedAt - startedAt,
|
|
1427
|
+
status,
|
|
1428
|
+
attempts: attempt,
|
|
1429
|
+
...error !== void 0 ? { error } : {},
|
|
1430
|
+
...status === "success" ? { result } : {}
|
|
1431
|
+
};
|
|
1432
|
+
this.record(record);
|
|
1433
|
+
state.running = false;
|
|
1434
|
+
return record;
|
|
1435
|
+
}
|
|
1436
|
+
/** A single attempt: run the handler, racing it against the per-job timeout. */
|
|
1437
|
+
runOnce(job) {
|
|
1438
|
+
const controller = new AbortController();
|
|
1439
|
+
const handlerPromise = this.runner(job.key, controller.signal);
|
|
1440
|
+
const timeoutMs = job.timeoutMs;
|
|
1441
|
+
if (!timeoutMs || timeoutMs <= 0) return handlerPromise;
|
|
1442
|
+
return new Promise((resolve, reject) => {
|
|
1443
|
+
let settled = false;
|
|
1444
|
+
const timer = this.clock.setTimeout(() => {
|
|
1445
|
+
if (settled) return;
|
|
1446
|
+
settled = true;
|
|
1447
|
+
controller.abort();
|
|
1448
|
+
reject(new RunTimeoutError(job.key, timeoutMs));
|
|
1449
|
+
}, timeoutMs);
|
|
1450
|
+
handlerPromise.then(
|
|
1451
|
+
(value) => {
|
|
1452
|
+
if (settled) return;
|
|
1453
|
+
settled = true;
|
|
1454
|
+
this.clock.clearTimeout(timer);
|
|
1455
|
+
resolve(value);
|
|
1456
|
+
},
|
|
1457
|
+
(err) => {
|
|
1458
|
+
if (settled) return;
|
|
1459
|
+
settled = true;
|
|
1460
|
+
this.clock.clearTimeout(timer);
|
|
1461
|
+
reject(err);
|
|
1462
|
+
}
|
|
1463
|
+
);
|
|
1464
|
+
});
|
|
1465
|
+
}
|
|
1466
|
+
sleep(ms) {
|
|
1467
|
+
return new Promise((resolve) => this.clock.setTimeout(resolve, ms));
|
|
1468
|
+
}
|
|
1469
|
+
record(record) {
|
|
1470
|
+
this.history.push(record);
|
|
1471
|
+
if (this.history.length > this.historyLimit) this.history.shift();
|
|
1472
|
+
}
|
|
1473
|
+
installSignalHandlers() {
|
|
1474
|
+
const handler = () => {
|
|
1475
|
+
void this.stop().then(() => process.exit(0));
|
|
1476
|
+
};
|
|
1477
|
+
process.once("SIGINT", handler);
|
|
1478
|
+
process.once("SIGTERM", handler);
|
|
1479
|
+
this.signalCleanup = () => {
|
|
1480
|
+
process.removeListener("SIGINT", handler);
|
|
1481
|
+
process.removeListener("SIGTERM", handler);
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
};
|
|
1485
|
+
|
|
882
1486
|
// src/registry/define.ts
|
|
883
1487
|
var DEFAULT_DISPATCH_PATH = "/cronvello/dispatch";
|
|
884
1488
|
var DEFAULT_TIME_ZONE = "Europe/Berlin";
|
|
@@ -972,10 +1576,43 @@ function defineCronvello(config) {
|
|
|
972
1576
|
handle: dispatcher.handle,
|
|
973
1577
|
expressHandler: () => expressHandler(app),
|
|
974
1578
|
nextHandler: () => nextHandler(app),
|
|
1579
|
+
dev(options) {
|
|
1580
|
+
const { autoStart = true, dashboard, ...engineOptions } = options ?? {};
|
|
1581
|
+
const engineJobs = buildEngineJobs([...jobs.values()], defaultTimeZone);
|
|
1582
|
+
const runner = (key, signal) => dispatcher.runLocal(key, void 0, { signal });
|
|
1583
|
+
const engine = createLocalEngine(engineJobs, runner, engineOptions);
|
|
1584
|
+
if (autoStart) engine.start();
|
|
1585
|
+
if (dashboard) {
|
|
1586
|
+
const dashboardOptions = dashboard === true ? {} : dashboard;
|
|
1587
|
+
const devSubpath = "@cronvello/sdk/dev";
|
|
1588
|
+
void import(devSubpath).then(({ startDashboard }) => startDashboard(engine, dashboardOptions)).then((handle) => {
|
|
1589
|
+
engine.onStop(() => handle.close());
|
|
1590
|
+
console.log(`Cronvello dashboard \u2192 ${handle.url}`);
|
|
1591
|
+
}).catch((err) => console.error(`Cronvello dashboard failed to start: ${err.message}`));
|
|
1592
|
+
}
|
|
1593
|
+
return engine;
|
|
1594
|
+
},
|
|
975
1595
|
keys: () => [...jobs.keys()]
|
|
976
1596
|
};
|
|
977
1597
|
return app;
|
|
978
1598
|
}
|
|
1599
|
+
function buildEngineJobs(jobs, defaultTimeZone) {
|
|
1600
|
+
const engineJobs = [];
|
|
1601
|
+
for (const { key, config } of jobs) {
|
|
1602
|
+
if (config.enabled === false) continue;
|
|
1603
|
+
const job = {
|
|
1604
|
+
key,
|
|
1605
|
+
schedule: config.schedule,
|
|
1606
|
+
timeZone: config.timeZone ?? defaultTimeZone,
|
|
1607
|
+
allowConcurrentRuns: config.allowConcurrentRuns ?? false,
|
|
1608
|
+
maxRetries: config.maxRetries ?? 0
|
|
1609
|
+
};
|
|
1610
|
+
if (config.callbackTimeoutMs !== void 0) job.timeoutMs = config.callbackTimeoutMs;
|
|
1611
|
+
if (config.description !== void 0) job.description = config.description;
|
|
1612
|
+
engineJobs.push(job);
|
|
1613
|
+
}
|
|
1614
|
+
return engineJobs;
|
|
1615
|
+
}
|
|
979
1616
|
((defineCronvello2) => {
|
|
980
1617
|
function fromEnv(config, env = typeof process !== "undefined" ? process.env : {}) {
|
|
981
1618
|
const apiKey = config.apiKey ?? env["CRONVELLO_API_KEY"];
|
|
@@ -1104,8 +1741,8 @@ function formatSyncResult(result, options = {}) {
|
|
|
1104
1741
|
`${paint("Cronvello", "cyan")} ${verb} ${paint(`"${result.jobName}"`, "bold")} ${paint(`(${result.jobId})`, "gray")}`
|
|
1105
1742
|
);
|
|
1106
1743
|
const order = ["created", "updated", "deleted", "skipped", "unchanged"];
|
|
1107
|
-
const
|
|
1108
|
-
for (const c of
|
|
1744
|
+
const sorted2 = [...result.changes].sort((a, b) => order.indexOf(a.action) - order.indexOf(b.action));
|
|
1745
|
+
for (const c of sorted2) {
|
|
1109
1746
|
const g = GLYPH[c.action];
|
|
1110
1747
|
const detail = c.changedFields && c.changedFields.length ? paint(` (${c.changedFields.join(", ")})`, "gray") : c.reason ? paint(` (${c.reason})`, "gray") : "";
|
|
1111
1748
|
lines.push(` ${paint(g.sign, g.color)} ${paint(c.action.padEnd(9), g.color)} ${c.key}${detail}`);
|
|
@@ -1244,6 +1881,8 @@ exports.generateDispatchSecret = generateDispatchSecret;
|
|
|
1244
1881
|
exports.hourly = hourly;
|
|
1245
1882
|
exports.isValidTimeZone = isValidTimeZone;
|
|
1246
1883
|
exports.monthly = monthly;
|
|
1884
|
+
exports.nextOccurrence = nextOccurrence;
|
|
1885
|
+
exports.previewSchedule = previewSchedule;
|
|
1247
1886
|
exports.schedule = schedule;
|
|
1248
1887
|
exports.validateCron = validateCron;
|
|
1249
1888
|
exports.weekdays = weekdays;
|