Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

test: enhance local-refresh tests and improve interval validation

Victor Hugo dos Santos3f193189cbd4
diff --git a/backend/src/lib/cron/local-refresh.test.ts b/backend/src/lib/cron/local-refresh.test.ts
index 52108bc86f..f905c9114d 100644
--- a/backend/src/lib/cron/local-refresh.test.ts
+++ b/backend/src/lib/cron/local-refresh.test.ts
@@ -9,6 +9,9 @@ vi.mock("@app/lib/logger", () => ({
}));
const INTERVAL_MS = 5 * 60 * 1000;
+const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
+
+const mockRandom = (value: number) => vi.spyOn(Math, "random").mockReturnValue(value);
describe("startLocalRefresh", () => {
let handle: TLocalRefreshHandle | undefined;
@@ -21,12 +24,14 @@ describe("startLocalRefresh", () => {
afterEach(() => {
handle?.stop();
handle = undefined;
+ vi.restoreAllMocks();
vi.useRealTimers();
});
test("first run lands at the random offset, within [0, interval)", async () => {
+ mockRandom(0.4);
const task = vi.fn().mockResolvedValue(undefined);
- handle = startLocalRefresh({ name: "t", intervalMs: INTERVAL_MS, task, random: () => 0.4 });
+ handle = startLocalRefresh({ name: "t", intervalMs: INTERVAL_MS, task });
await vi.advanceTimersByTimeAsync(0.4 * INTERVAL_MS - 1);
expect(task).not.toHaveBeenCalled();
@@ -37,12 +42,11 @@ describe("startLocalRefresh", () => {
test.each([
[0, 0],
- [0.999999999, INTERVAL_MS - 1],
- [1, INTERVAL_MS - 1],
- [-1, 0]
- ])("clamps offset for random()=%s to %sms", async (randomValue, expectedDelay) => {
+ [0.999999999, INTERVAL_MS - 1]
+ ])("offset for Math.random()=%s is %sms", async (randomValue, expectedDelay) => {
+ mockRandom(randomValue);
const task = vi.fn().mockResolvedValue(undefined);
- handle = startLocalRefresh({ name: "t", intervalMs: INTERVAL_MS, task, random: () => randomValue });
+ handle = startLocalRefresh({ name: "t", intervalMs: INTERVAL_MS, task });
if (expectedDelay > 0) {
await vi.advanceTimersByTimeAsync(expectedDelay - 1);
@@ -52,7 +56,7 @@ describe("startLocalRefresh", () => {
expect(task).toHaveBeenCalledTimes(1);
});
- test("default random source keeps the offset inside the interval", async () => {
+ test("real random source keeps the offset inside the interval", async () => {
for (let i = 0; i < 20; i += 1) {
const task = vi.fn().mockResolvedValue(undefined);
const h = startLocalRefresh({ name: "t", intervalMs: INTERVAL_MS, task });
@@ -64,8 +68,9 @@ describe("startLocalRefresh", () => {
});
test("runs every interval after the first run", async () => {
+ mockRandom(0);
const task = vi.fn().mockResolvedValue(undefined);
- handle = startLocalRefresh({ name: "t", intervalMs: INTERVAL_MS, task, random: () => 0 });
+ handle = startLocalRefresh({ name: "t", intervalMs: INTERVAL_MS, task });
await vi.advanceTimersByTimeAsync(0);
expect(task).toHaveBeenCalledTimes(1);
@@ -81,6 +86,7 @@ describe("startLocalRefresh", () => {
});
test("skips ticks while a previous run is still in flight", async () => {
+ mockRandom(0);
let release: () => void = () => {};
let active = 0;
let maxActive = 0;
@@ -93,7 +99,7 @@ describe("startLocalRefresh", () => {
active -= 1;
});
- handle = startLocalRefresh({ name: "slow", intervalMs: INTERVAL_MS, task, random: () => 0 });
+ handle = startLocalRefresh({ name: "slow", intervalMs: INTERVAL_MS, task });
await vi.advanceTimersByTimeAsync(0);
expect(task).toHaveBeenCalledTimes(1);
@@ -115,6 +121,7 @@ describe("startLocalRefresh", () => {
});
test("an error in one run does not stop later runs", async () => {
+ mockRandom(0);
const task = vi
.fn()
.mockRejectedValueOnce(new Error("boom"))
@@ -123,7 +130,7 @@ describe("startLocalRefresh", () => {
})
.mockResolvedValue(undefined);
- handle = startLocalRefresh({ name: "flaky", intervalMs: INTERVAL_MS, task, random: () => 0 });
+ handle = startLocalRefresh({ name: "flaky", intervalMs: INTERVAL_MS, task });
await vi.advanceTimersByTimeAsync(0);
await vi.advanceTimersByTimeAsync(INTERVAL_MS);
await vi.advanceTimersByTimeAsync(INTERVAL_MS);
@@ -134,19 +141,14 @@ describe("startLocalRefresh", () => {
});
test("logs duration at debug and warns only above the threshold", async () => {
+ mockRandom(0);
const task = vi.fn(async () => {
await new Promise((resolve) => {
setTimeout(resolve, 200);
});
});
- handle = startLocalRefresh({
- name: "timed",
- intervalMs: INTERVAL_MS,
- task,
- random: () => 0,
- slowRunThresholdMs: 500
- });
+ handle = startLocalRefresh({ name: "timed", intervalMs: INTERVAL_MS, task, slowRunThresholdMs: 500 });
await vi.advanceTimersByTimeAsync(200);
expect(logger.debug).toHaveBeenCalledWith(
@@ -157,8 +159,9 @@ describe("startLocalRefresh", () => {
});
test("stop() before the first run cancels it", async () => {
+ mockRandom(0.5);
const task = vi.fn().mockResolvedValue(undefined);
- handle = startLocalRefresh({ name: "t", intervalMs: INTERVAL_MS, task, random: () => 0.5 });
+ handle = startLocalRefresh({ name: "t", intervalMs: INTERVAL_MS, task });
handle.stop();
await vi.advanceTimersByTimeAsync(INTERVAL_MS * 5);
@@ -167,8 +170,9 @@ describe("startLocalRefresh", () => {
});
test("stop() after runs have started cancels future runs", async () => {
+ mockRandom(0);
const task = vi.fn().mockResolvedValue(undefined);
- handle = startLocalRefresh({ name: "t", intervalMs: INTERVAL_MS, task, random: () => 0 });
+ handle = startLocalRefresh({ name: "t", intervalMs: INTERVAL_MS, task });
await vi.advanceTimersByTimeAsync(INTERVAL_MS);
expect(task).toHaveBeenCalledTimes(2);
@@ -187,28 +191,32 @@ describe("startLocalRefresh", () => {
test("offset and interval timers are unref'd so they never hold the process open", async () => {
vi.useRealTimers();
+ mockRandom(0);
const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
const setIntervalSpy = vi.spyOn(globalThis, "setInterval");
const task = vi.fn();
- try {
- handle = startLocalRefresh({ name: "t", intervalMs: INTERVAL_MS, task, random: () => 0 });
- const offsetTimer = setTimeoutSpy.mock.results[0]?.value as NodeJS.Timeout;
- expect(offsetTimer.hasRef()).toBe(false);
+ handle = startLocalRefresh({ name: "t", intervalMs: INTERVAL_MS, task });
+ const offsetTimer = setTimeoutSpy.mock.results[0]?.value as NodeJS.Timeout;
+ expect(offsetTimer.hasRef()).toBe(false);
- await new Promise<void>((resolve) => {
- setTimeout(resolve, 20);
- });
- expect(task).toHaveBeenCalledTimes(1);
- const intervalTimer = setIntervalSpy.mock.results[0]?.value as NodeJS.Timeout;
- expect(intervalTimer.hasRef()).toBe(false);
- } finally {
- setTimeoutSpy.mockRestore();
- setIntervalSpy.mockRestore();
- }
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, 20);
+ });
+ expect(task).toHaveBeenCalledTimes(1);
+ const intervalTimer = setIntervalSpy.mock.results[0]?.value as NodeJS.Timeout;
+ expect(intervalTimer.hasRef()).toBe(false);
});
- test.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])("rejects invalid interval %s", (intervalMs) => {
- expect(() => startLocalRefresh({ name: "bad", intervalMs, task: vi.fn() })).toThrow(/positive number/);
+ test("accepts the largest interval Node can schedule", () => {
+ handle = startLocalRefresh({ name: "max", intervalMs: MAX_TIMER_DELAY_MS, task: vi.fn() });
+ expect(vi.getTimerCount()).toBe(1);
});
+
+ test.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY, MAX_TIMER_DELAY_MS + 1, 30 * 24 * 60 * 60 * 1000])(
+ "rejects invalid interval %s",
+ (intervalMs) => {
+ expect(() => startLocalRefresh({ name: "bad", intervalMs, task: vi.fn() })).toThrow(/positive number/);
+ }
+ );
});
diff --git a/backend/src/lib/cron/local-refresh.ts b/backend/src/lib/cron/local-refresh.ts
index 0dd8eb0b2f..8bd7583eec 100644
--- a/backend/src/lib/cron/local-refresh.ts
+++ b/backend/src/lib/cron/local-refresh.ts
@@ -9,11 +9,13 @@ type TStartLocalRefreshDTO = {
intervalMs: number;
task: () => Promise<void> | void;
slowRunThresholdMs?: number;
- random?: () => number;
};
const DEFAULT_SLOW_RUN_THRESHOLD_MS = 1000;
+// Node clamps any timer delay above this to 1ms, which would turn a long interval into a hot loop.
+const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
+
// Refreshes state held in this process's memory, so it has to run on every pod; fleet-wide
// scheduled work belongs on the cron manager in ./cron-job instead. The offset is random per
// process on purpose: the point is that pods disagree, so they don't all hit the DB in the same second.
@@ -21,11 +23,12 @@ export const startLocalRefresh = ({
name,
intervalMs,
task,
- slowRunThresholdMs = DEFAULT_SLOW_RUN_THRESHOLD_MS,
- random = Math.random
+ slowRunThresholdMs = DEFAULT_SLOW_RUN_THRESHOLD_MS
}: TStartLocalRefreshDTO): TLocalRefreshHandle => {
- if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
- throw new Error(`Local refresh interval must be a positive number of milliseconds [name=${name}]`);
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0 || intervalMs > MAX_TIMER_DELAY_MS) {
+ throw new Error(
+ `Local refresh interval must be a positive number of milliseconds no greater than ${MAX_TIMER_DELAY_MS} [name=${name}]`
+ );
}
let stopped = false;
@@ -61,7 +64,7 @@ export const startLocalRefresh = ({
}
};
- const initialDelayMs = Math.max(0, Math.min(intervalMs - 1, Math.floor(random() * intervalMs)));
+ const initialDelayMs = Math.floor(Math.random() * intervalMs);
timer = setTimeout(() => {
if (stopped) return;