Skip to content

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

refactor(cron): standardize Redis key formatting with hash tags for cluster compatibility and enhance test coverage

Victor Hugo dos Santosb01e4f98cfe0
diff --git a/backend/e2e-test/cron-job.spec.ts b/backend/e2e-test/cron-job.spec.ts
index b0de6dd25e..19cb9e8627 100644
--- a/backend/e2e-test/cron-job.spec.ts
+++ b/backend/e2e-test/cron-job.spec.ts
@@ -68,6 +68,20 @@ const factory = (overrides?: Partial<Parameters<typeof cronJobFactory>[0]>) => {
return f;
};
+// FAST_PATTERN fires every minute, so a test that waits ~5s and asserts
+// "exactly one fire happened" will spuriously see two when the wait crosses a
+// minute boundary. This helper pads beforeEach to start the test at least
+// MIN_HEADROOM_MS away from the next boundary, so no test wait can straddle it.
+const MIN_HEADROOM_MS = 10_000;
+const waitForFreshMinute = async () => {
+ const msUntilNext = 60_000 - (Date.now() % 60_000);
+ if (msUntilNext < MIN_HEADROOM_MS) {
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, msUntilNext + 200);
+ });
+ }
+};
+
beforeAll(() => {
initLogger();
});
@@ -76,6 +90,7 @@ beforeEach(async () => {
await testRedis.flushdb();
allFactories.length = 0;
lockManager.clear();
+ await waitForFreshMinute();
});
afterEach(async () => {
@@ -99,7 +114,7 @@ describe("single pod", () => {
});
expect(handler).toHaveBeenCalled();
- const keys = await testRedis.keys("cron:run:test-job:*");
+ const keys = await testRedis.keys("{cron}:run:test-job:*");
expect(keys.length).toBe(1);
const run = await testRedis.hgetall(keys[0]);
expect(run.status).toBe("completed");
@@ -122,7 +137,7 @@ describe("multi-pod single fire", () => {
setTimeout(r, 4000);
});
- const keys = await testRedis.keys("cron:run:shared-job:*");
+ const keys = await testRedis.keys("{cron}:run:shared-job:*");
expect(keys.length).toBe(1);
const run = await testRedis.hgetall(keys[0]);
expect(run.status).toBe("completed");
@@ -144,7 +159,7 @@ describe("slot exhaustion", () => {
setTimeout(r, 2000);
});
- const slotKeys = await testRedis.keys("cron:slot:*");
+ const slotKeys = await testRedis.keys("{cron}:slot:*");
expect(slotKeys.length).toBeLessThanOrEqual(5);
}, 8_000);
});
@@ -160,12 +175,12 @@ describe("slot handover", () => {
await new Promise((r) => {
setTimeout(r, 2000);
});
- const slotsBefore = await testRedis.keys("cron:slot:*");
+ const slotsBefore = await testRedis.keys("{cron}:slot:*");
expect(slotsBefore.length).toBeLessThanOrEqual(5);
// Stop all — this releases slots
await Promise.all(factories.map((f) => f.stop()));
- const slotsAfter = await testRedis.keys("cron:slot:*");
+ const slotsAfter = await testRedis.keys("{cron}:slot:*");
expect(slotsAfter.length).toBe(0);
}, 8_000);
});
@@ -187,7 +202,7 @@ describe("retry", () => {
setTimeout(r, 4000);
});
- const keys = await testRedis.keys("cron:run:retry-job:*");
+ const keys = await testRedis.keys("{cron}:run:retry-job:*");
expect(keys.length).toBe(1);
const run = await testRedis.hgetall(keys[0]);
// After first failure + retry success, should be completed
@@ -205,7 +220,7 @@ describe("retry", () => {
setTimeout(r, 5000);
});
- const keys = await testRedis.keys("cron:run:fail-job:*");
+ const keys = await testRedis.keys("{cron}:run:fail-job:*");
expect(keys.length).toBe(1);
const run = await testRedis.hgetall(keys[0]);
expect(run.status).toBe("failed");
@@ -242,14 +257,14 @@ describe("handler timeout", () => {
// no retry can be scheduled for this id.
expect(handler).toHaveBeenCalledTimes(1);
- const keys = await testRedis.keys("cron:run:hang-job:*");
+ const keys = await testRedis.keys("{cron}:run:hang-job:*");
expect(keys.length).toBe(1);
const run = await testRedis.hgetall(keys[0]);
expect(run.status).toBe("failed");
expect(run.last_error).toContain("exceeded");
// The id is removed from the pending zset so no further tick can re-process it.
- const pending = await testRedis.zrange("cron:pending", 0, -1);
+ const pending = await testRedis.zrange("{cron}:pending", 0, -1);
expect(pending.filter((s) => s.startsWith("hang-job:"))).toEqual([]);
}, 10_000);
});
@@ -290,10 +305,10 @@ describe("retry backoff", () => {
setTimeout(r, 2_000);
});
- const keys = await testRedis.keys("cron:run:score-job:*");
+ const keys = await testRedis.keys("{cron}:run:score-job:*");
expect(keys.length).toBe(1);
- const id = keys[0].replace("cron:run:", "");
- const score = await testRedis.zscore("cron:pending", id);
+ const id = keys[0].replace("{cron}:run:", "");
+ const score = await testRedis.zscore("{cron}:pending", id);
expect(score).not.toBeNull();
expect(Number(score)).toBeGreaterThan(Date.now());
expect(handler).toHaveBeenCalledTimes(1);
@@ -316,7 +331,7 @@ describe("next-fire guard", () => {
});
expect(handler).toHaveBeenCalledTimes(1);
- const keys = await testRedis.keys("cron:run:guard-job:*");
+ const keys = await testRedis.keys("{cron}:run:guard-job:*");
expect(keys.length).toBe(1);
const run = await testRedis.hgetall(keys[0]);
expect(run.status).toBe("failed");
@@ -327,7 +342,7 @@ describe("next-fire guard", () => {
// ── ZSET cleared on success ────────────────────────────────────────────────────
describe("ZSET cleanup", () => {
- test("cron:pending ZSET is empty after successful execution", async () => {
+ test("{cron}:pending ZSET is empty after successful execution", async () => {
const handler = vi.fn().mockResolvedValue(undefined);
const f = factory();
f.register({ name: "clean-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
@@ -337,7 +352,7 @@ describe("ZSET cleanup", () => {
setTimeout(r, 3000);
});
- const pending = await testRedis.zrange("cron:pending", 0, -1);
+ const pending = await testRedis.zrange("{cron}:pending", 0, -1);
expect(pending.filter((s) => s.startsWith("clean-job:"))).toEqual([]);
}, 10_000);
});
@@ -360,7 +375,7 @@ describe("min-age gate", () => {
setTimeout(r, 700);
});
- const keys = await testRedis.keys("cron:run:age-gate-job:*");
+ const keys = await testRedis.keys("{cron}:run:age-gate-job:*");
expect(keys.length).toBe(1); // run is in Redis
expect(handler).not.toHaveBeenCalled(); // but age gate is holding it back
@@ -441,7 +456,7 @@ describe("graceful shutdown", () => {
});
expect(handler).toHaveBeenCalled();
- const slotKeysBefore = await testRedis.keys("cron:slot:*");
+ const slotKeysBefore = await testRedis.keys("{cron}:slot:*");
expect(slotKeysBefore.length).toBeGreaterThan(0);
const startedAt = Date.now();
@@ -451,7 +466,7 @@ describe("graceful shutdown", () => {
// Drain timed out; stop() returned within drainTimeoutMs + buffer rather
// than blocking on the hung handler. The slot was released atomically.
expect(elapsed).toBeLessThan(2_000);
- const slotKeysAfter = await testRedis.keys("cron:slot:*");
+ const slotKeysAfter = await testRedis.keys("{cron}:slot:*");
expect(slotKeysAfter.length).toBe(0);
}, 10_000);
});
diff --git a/backend/src/lib/cron/cron-job.test.ts b/backend/src/lib/cron/cron-job.test.ts
index 975dac4eea..1fb3101610 100644
--- a/backend/src/lib/cron/cron-job.test.ts
+++ b/backend/src/lib/cron/cron-job.test.ts
@@ -95,7 +95,7 @@ describe("slot election", () => {
start();
// Let the immediate claimOrRefreshSlot call in start() complete
await Promise.resolve();
- expect(redis.set).toHaveBeenCalledWith("cron:slot:0", expect.any(String), "PX", expect.any(Number), "NX");
+ expect(redis.set).toHaveBeenCalledWith("{cron}:slot:0", expect.any(String), "PX", expect.any(Number), "NX");
await stop();
});
@@ -105,8 +105,8 @@ describe("slot election", () => {
const { start, stop } = makeFactory({ redis });
start();
await Promise.resolve();
- expect(redis.set).toHaveBeenNthCalledWith(1, "cron:slot:0", expect.any(String), "PX", expect.any(Number), "NX");
- expect(redis.set).toHaveBeenNthCalledWith(2, "cron:slot:1", expect.any(String), "PX", expect.any(Number), "NX");
+ expect(redis.set).toHaveBeenNthCalledWith(1, "{cron}:slot:0", expect.any(String), "PX", expect.any(Number), "NX");
+ expect(redis.set).toHaveBeenNthCalledWith(2, "{cron}:slot:1", expect.any(String), "PX", expect.any(Number), "NX");
await stop();
});
@@ -181,6 +181,57 @@ describe("claim and execute", () => {
});
});
+// Multi-key Lua scripts (currently just ENQUEUE_RUN_LUA) must pass keys that
+// hash to the same Redis Cluster slot, otherwise the server returns CROSSSLOT
+// in cluster mode and every enqueue tick fails silently. This invariant test
+// guards the {cron} hash-tag convention against future regressions, mirroring
+// the per-queue {<name>} pattern that queue-service.ts already uses for BullMQ.
+describe("redis cluster compatibility", () => {
+ // Extracts the Redis Cluster hash tag (text between the first `{` and `}`)
+ // from a key, or undefined if the key isn't tagged. Two keys hash to the
+ // same slot iff this returns a non-empty equal value for both.
+ const hashTagOf = (key: unknown): string | undefined => {
+ const s = String(key);
+ const start = s.indexOf("{");
+ if (start < 0) return undefined;
+ const end = s.indexOf("}", start + 1);
+ if (end <= start + 1) return undefined;
+ return s.slice(start + 1, end);
+ };
+
+ test("multi-key Lua EVAL passes keys that share a Cluster hash tag", async () => {
+ vi.setSystemTime(new Date("2024-01-01T00:00:30Z"));
+ const redis = makeRedis();
+ redis.set.mockResolvedValue("OK");
+ redis.eval.mockResolvedValue(1);
+
+ const { register, start, stop } = makeFactory({ redis });
+ register({ name: "x", pattern: "* * * * *", handler: vi.fn(), runHashTtlS: 3600 });
+ start();
+
+ // Drive at least one enqueue tick (enqueueIntervalMs=100 in makeFactory).
+ await vi.advanceTimersByTimeAsync(150);
+
+ // ENQUEUE_RUN_LUA is the only multi-key script (KEYS[1]=run, KEYS[2]=pending).
+ // Identify its eval call by numKeys === 2 (RELEASE_SLOT_IF_MINE_LUA uses 1).
+ const multiKeyEvalCalls = redis.eval.mock.calls.filter((c) => c[1] === 2);
+ expect(multiKeyEvalCalls.length).toBeGreaterThan(0);
+
+ for (const call of multiKeyEvalCalls) {
+ const numKeys = Number(call[1]);
+ const keys = (call as unknown[]).slice(2, 2 + numKeys);
+ const tags = keys.map(hashTagOf);
+ // Every key in a multi-key EVAL must carry a non-empty hash tag and
+ // every tag must match — that's the precondition for Redis Cluster to
+ // accept the command without returning CROSSSLOT.
+ expect(tags.every((t) => t && t.length > 0)).toBe(true);
+ expect(new Set(tags).size).toBe(1);
+ }
+
+ await stop();
+ });
+});
+
describe("retry backoff and handler timeout", () => {
// Helper: wires up the mock chain so the factory will pick up a single
// pending run for cron name "x" and invoke the registered handler.
@@ -376,7 +427,7 @@ describe("stop", () => {
await stop();
const lastEval = redis.eval.mock.calls.at(-1) as unknown[];
expect(lastEval[0]).toContain("del");
- expect(String(lastEval[2])).toContain("cron:slot:");
+ expect(String(lastEval[2])).toContain("{cron}:slot:");
});
// Regression guard for the BullMQ Worker.close() drain semantics: stop()
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index 34412d3f64..02151c3649 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -31,10 +31,11 @@ const DEFAULTS = {
// ── redis schema ──────────────────────────────────────────────────────────────
-const SLOT_KEY = (i: number) => `cron:slot:${i}`;
-const RUN_KEY = (id: string) => `cron:run:${id}`;
-const LEASE_KEY = (id: string) => `cron:lease:${id}`;
-const PENDING_ZSET = "cron:pending";
+const KEY_HASH_TAG = "{cron}";
+const SLOT_KEY = (i: number) => `${KEY_HASH_TAG}:slot:${i}`;
+const RUN_KEY = (id: string) => `${KEY_HASH_TAG}:run:${id}`;
+const LEASE_KEY = (id: string) => `${KEY_HASH_TAG}:lease:${id}`;
+const PENDING_ZSET = `${KEY_HASH_TAG}:pending`;
// Run-hash status values. Stored as plain strings in the hash so we don't
// break Redis tooling, but referenced through this object to avoid drift.