Files
Kelx/tests/scheduler-timezone.test.js
2026-11-30 16:32:37 +00:00

334 lines
15 KiB
JavaScript

"use strict";
// Regression tests for the scheduler timezone fix.
//
// Bug: POST /api/scheduler/:server/tasks added cron repeatables with
// `repeat: { pattern }` and no `tz` option, so daily/weekly (and the
// minute-granularity cron forms) fired in the PANEL HOST's timezone — a
// "daily 09:00" task set by a user in Europe/Bucharest fired at the panel's
// local 09:00, hours off the user's wall clock.
//
// Fix: the browser now sends its IANA zone (`timezone`) in the POST body;
// the create route validates it with Intl.DateTimeFormat (throws on unknown
// zones) and threads it into BullMQ's `tz` repeat option for the CRON branch
// only — the interval branch (`repeat: { every: ms }`) and the one-time
// branch are timezone-independent. The validated zone is also stored on
// jobData (`timezone`) so recurring jobs are self-describing. Absent or
// invalid values fall back SILENTLY to the previous panel-local behavior
// (old clients do not send the field; a bad value must not block creation).
//
// index.js boots servers on require and cannot be loaded in-process, so —
// same technique as scheduler-interval-floor / scheduler-hardening — the
// REAL validation block and the REAL jobData/add block are sliced from
// source and evaluated with injected fakes (a stub schedulerQueue captures
// the exact options handed to BullMQ).
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const crypto = require("node:crypto");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
// Strip full-line comments so prose mentioning the markers cannot satisfy
// the source-level assertions.
function stripFullLineComments(src) {
return src
.split("\n")
.filter((line) => !/^\s*\/\//.test(line))
.join("\n");
}
const indexCode = stripFullLineComments(indexSource);
function sliceFrom(source, startMarker, endMarker, label) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `${label}: start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start);
assert.ok(end > start, `${label}: end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
function createRouteSlice(source) {
return sliceFrom(
source,
'app.post("/api/scheduler/:serverName/tasks"',
'app.delete("/api/scheduler/:serverName/tasks/:taskId"',
"scheduler create route"
);
}
// The REAL scheduleToCron (plus the floor constant and parseCronTimeFields
// it closes over), sliced exactly like scheduler-interval-floor.test.js so
// the harness converts schedule shapes with the shipped code, not a copy.
const { scheduleToCron } = new Function(
sliceFrom(indexSource, "const SCHEDULER_MIN_INTERVAL_SECONDS", "\nasync function shutdownScheduler(", "scheduleToCron") +
"\nreturn { scheduleToCron };"
)();
// The REAL timezone validation block, evaluated with an injected req.
const validateTimezone = new Function(
"req",
sliceFrom(
indexSource,
"const rawTimezone = typeof req.body?.timezone",
'if (actionType === "backup") {',
"timezone validation block"
) + "\nreturn timezone;"
);
// The REAL jobData construction + queue.add branches (once / interval /
// cron), evaluated with the route's in-scope bindings injected. A stub
// schedulerQueue captures the exact (name, data, opts) handed to BullMQ.
// adpanel:scheduler-canonical-name - the create route stores/compares the
// canonical DB name, so the sliced block now references canonicalServer; it
// is injected alongside serverName (equal here: these tests only pin tz).
const makeTaskCreator = new Function(
"taskName", "serverName", "canonicalServer", "actionType", "payload", "scheduleType",
"scheduleValue", "scheduleTime", "timezone", "scheduledTimestamp",
"user", "serverEntry", "email", "schedulerQueue", "crypto", "scheduleToCron", "res", "console",
"runCreateRedisStep", "preAddRepeatableKeys", "autoApproveFileEdits", "serverRepeatables", "isAgentSchedule", "onceRequestId",
`"use strict";
return async () => {
${sliceFrom(
indexSource,
"const jobData = {",
"const userIp = getRequestIp(req);",
"jobData + add branches"
)}
return { job, jobData };
};`
);
// adpanel:scheduler-create-deadline — the add branches are now deadline-raced
// through the route's shared helper, so the harness binds the REAL sliced
// helper (with the real raceWithDeadline). These tests resolve the add
// immediately, so the production deadline (15s) never fires here.
const { awaitSchedulerCreateRedisStep: deadlineStepForTimezone } = new Function(
"raceWithDeadline", "schedulerQueue", "console",
sliceFrom(
indexSource,
"const SCHEDULER_CREATE_REDIS_DEADLINE_MS = 15000;",
"\n// Server-side twin of the scheduler UI's interval floor",
"create-deadline helpers"
) + "\nreturn { awaitSchedulerCreateRedisStep };"
)(
require("../utils/scheduler-failure-streak").raceWithDeadline,
{ removeRepeatableByKey: async () => 0 }, // never reached: no abandonment in these tests
{ warn() {}, error() {}, log() {} }
);
// Runs validation + task creation end-to-end (sans HTTP) for a body-shaped
// input and returns the captured BullMQ add call plus the built jobData.
async function runCreate({ body = {}, scheduleType = "daily", scheduleValue, scheduleTime }) {
const timezone = validateTimezone({ body });
const adds = [];
const schedulerQueue = {
add: async (name, data, opts) => {
adds.push({ name, data, opts });
return { id: `job-${adds.length}` };
}
};
const responses = [];
const res = {
status: (code) => ({ json: (payload) => responses.push({ code, payload }) })
};
const { jobData } = await makeTaskCreator(
"Timezone probe", "srv01", "srv01", "console_command", { command: "say hi" },
scheduleType, scheduleValue, scheduleTime, timezone, undefined,
{ id: 42 }, { id: 7, name: "srv01" }, "creator@example.com", schedulerQueue, crypto, scheduleToCron,
res, { log() {} }, (operation, ...options) => deadlineStepForTimezone(operation(), ...options),
null, false, [], require("../AgentWorker/feature-http").isAgentSchedule, null
)();
assert.strictEqual(adds.length, 1, "exactly one queue.add call expected");
assert.strictEqual(responses.length, 0, "no error response may be produced for these inputs");
return { add: adds[0], jobData };
}
// ---------------------------------------------------------------------------
// The validation block itself
// ---------------------------------------------------------------------------
test("a valid IANA zone is kept verbatim (not canonicalized away)", () => {
assert.strictEqual(validateTimezone({ body: { timezone: "Europe/Bucharest" } }), "Europe/Bucharest");
assert.strictEqual(validateTimezone({ body: { timezone: "America/New_York" } }), "America/New_York");
});
test("an unknown zone string silently degrades to null, never throws", () => {
for (const bad of ["Not/AZone", "garbage", "Europe/Bucharest ", "Mars/Olympus_Mons"]) {
assert.strictEqual(validateTimezone({ body: { timezone: bad } }), null, JSON.stringify(bad));
}
});
test("absent, empty, or non-string timezone values degrade to null (old clients)", () => {
assert.strictEqual(validateTimezone({ body: {} }), null);
assert.strictEqual(validateTimezone({ body: { timezone: "" } }), null);
assert.strictEqual(validateTimezone({ body: { timezone: null } }), null);
assert.strictEqual(validateTimezone({ body: { timezone: 5 } }), null);
assert.strictEqual(validateTimezone({ body: { timezone: { zone: "UTC" } } }), null);
assert.strictEqual(validateTimezone({}), null);
});
test("the validation block rejects nothing (silent fallback, no 4xx on bad zones)", () => {
const block = sliceFrom(
indexSource,
"const rawTimezone = typeof req.body?.timezone",
'if (actionType === "backup") {',
"timezone validation block"
);
assert.ok(!block.includes("res.status"), "an invalid timezone must not turn into a rejected request");
assert.ok(block.includes('new Intl.DateTimeFormat("en-US", { timeZone: rawTimezone })'), "validation must go through Intl (throws on unknown zones)");
});
// ---------------------------------------------------------------------------
// Wiring: the cron repeatable gets tz, and only the cron repeatable
// ---------------------------------------------------------------------------
test("a valid timezone reaches the cron repeat options and jobData", async () => {
const { add, jobData } = await runCreate({
body: { timezone: "Europe/Bucharest" },
scheduleType: "daily",
scheduleTime: "09:00"
});
const { key, ...repeat } = add.opts.repeat;
assert.match(key, /^[a-f0-9-]{36}$/);
assert.deepStrictEqual(repeat, { pattern: "0 9 * * *", tz: "Europe/Bucharest" });
assert.strictEqual(add.data.timezone, "Europe/Bucharest");
assert.strictEqual(jobData.timezone, "Europe/Bucharest");
});
test("weekly cron forms carry tz too (same branch, wall-clock fields)", async () => {
const { add } = await runCreate({
body: { timezone: "America/New_York" },
scheduleType: "weekly",
scheduleValue: "1",
scheduleTime: "23:45"
});
const { key, ...repeat } = add.opts.repeat;
assert.match(key, /^[a-f0-9-]{36}$/);
assert.deepStrictEqual(repeat, { pattern: "45 23 * * 1", tz: "America/New_York" });
});
test("no timezone sent: cron repeat stays tz-free and jobData.timezone is null (old-client behavior)", async () => {
const { add, jobData } = await runCreate({
body: {},
scheduleType: "daily",
scheduleTime: "09:00"
});
const { key, ...repeat } = add.opts.repeat;
assert.match(key, /^[a-f0-9-]{36}$/);
assert.deepStrictEqual(repeat, { pattern: "0 9 * * *" });
assert.ok(!("tz" in add.opts.repeat), "tz key must be absent, not null");
assert.strictEqual(jobData.timezone, null);
});
test("an invalid timezone string behaves exactly like an absent one", async () => {
const { add, jobData } = await runCreate({
body: { timezone: "Not/AZone" },
scheduleType: "daily",
scheduleTime: "09:00"
});
const { key, ...repeat } = add.opts.repeat;
assert.match(key, /^[a-f0-9-]{36}$/);
assert.deepStrictEqual(repeat, { pattern: "0 9 * * *" });
assert.ok(!("tz" in add.opts.repeat));
assert.strictEqual(jobData.timezone, null);
});
test("the interval branch (repeat: { every }) stays timezone-free even with a valid zone", async () => {
const { add, jobData } = await runCreate({
body: { timezone: "Europe/Bucharest" },
scheduleType: "seconds",
scheduleValue: "30"
});
const { key, ...repeat } = add.opts.repeat;
assert.match(key, /^[a-f0-9-]{36}$/);
assert.deepStrictEqual(repeat, { every: 30000 });
assert.ok(!("tz" in add.opts.repeat), "intervals are tz-independent; adding tz would be dead weight");
// jobData still carries the (valid) zone so the job is self-describing.
assert.strictEqual(jobData.timezone, "Europe/Bucharest");
});
test("jobData always carries the timezone field (null when absent), no key drift", async () => {
const { jobData } = await runCreate({ body: {}, scheduleType: "daily" });
assert.ok("timezone" in jobData, "the field must exist so consumers can rely on the shape");
assert.deepStrictEqual(
Object.keys(jobData).sort(),
// adpanel:scheduler-server-identity-bind added serverId (the resolved row's
// id, bound at fire time) — additive, listed consciously.
["actionType", "name", "payload", "scheduleType", "scheduleTime", "scheduleValue", "serverId", "serverName", "timezone", "userId", "userName"].sort()
);
});
test("jobData binds the resolved server row's id as serverId (adpanel:scheduler-server-identity-bind)", async () => {
const { jobData } = await runCreate({ body: {}, scheduleType: "daily" });
assert.strictEqual(jobData.serverId, 7, "the create must store the findServer row's id so a same-name recreate is detectable at fire time");
});
// ---------------------------------------------------------------------------
// Source-level: the exact wiring cannot drift
// ---------------------------------------------------------------------------
test("the cron branch threads tz through the repeat spread exactly as specified", () => {
const route = createRouteSlice(indexCode);
assert.ok(
route.includes("repeat: { pattern: schedule, ...(timezone ? { tz: timezone } : {}), key: repeatKey }"),
"the cron repeatable must spread tz in only when a validated timezone exists"
);
assert.ok(
route.includes("repeat: { every: schedule.ms, key: repeatKey }"),
"the interval branch must set an instance key without adding a timezone"
);
});
test("the one-time branch never gained a tz/repeat option", () => {
const onceBranch = sliceFrom(
createRouteSlice(indexCode),
'if (scheduleType === "once") {',
"} else {",
"once branch"
);
assert.ok(!onceBranch.includes("tz"), "one-time delays are absolute timestamps — no timezone applies");
assert.ok(!onceBranch.includes("repeat:"), "one-time jobs are not repeatables");
});
test("jobData literal includes the timezone field in the shipped style", () => {
const jobDataLiteral = sliceFrom(indexCode, "const jobData = {", "let job;", "jobData literal");
assert.ok(jobDataLiteral.includes("timezone,"), "the timezone field must live on the jobData literal");
});
test("timezone validation runs after the scheduleType whitelist", () => {
const route = createRouteSlice(indexCode);
const tzPos = route.indexOf("const rawTimezone = typeof req.body?.timezone");
const whitelistPos = route.indexOf("if (!validScheduleTypes.includes(scheduleType))");
assert.ok(tzPos > whitelistPos, "request-shape validation stays first; timezone handling follows it");
});
// ---------------------------------------------------------------------------
// Dependency contract: the installed bullmq must actually support tz
// ---------------------------------------------------------------------------
test("installed bullmq accepts tz in repeat options and feeds cron-parser (stop-condition guard)", () => {
const bullmqRoot = path.join(ROOT, "node_modules", "bullmq");
const repeatableOptions = fs.readFileSync(
path.join(bullmqRoot, "dist", "esm", "interfaces", "repeatable-options.d.ts"), "utf8"
);
assert.ok(repeatableOptions.includes("tz?: string"), "RepeatableOptions must declare tz (bullmq upgrade regression guard)");
const repeatClass = fs.readFileSync(path.join(bullmqRoot, "dist", "cjs", "classes", "repeat.js"), "utf8");
assert.ok(
repeatClass.includes("tz: repeatOpts.tz"),
"the Repeat class must persist repeatOpts.tz into the repeatable job metadata"
);
assert.ok(
repeatClass.includes('cron_parser_1.parseExpression)(pattern, Object.assign(Object.assign({}, opts), { currentDate }))'),
"getNextMillis must spread the repeat options (incl. tz) into cron-parser"
);
const cronParserTypes = fs.readFileSync(
path.join(ROOT, "node_modules", "cron-parser", "types", "common.d.ts"), "utf8"
);
assert.ok(cronParserTypes.includes("tz?: string"), "cron-parser ParserOptions must declare tz");
});