Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(cron): implement graceful shutdown for cron jobs with drain timeout handling
Victor Hugo dos Santos131f600d1b63
diff --git a/backend/e2e-test/cron-job.spec.ts b/backend/e2e-test/cron-job.spec.tsindex 015726a2b8..fca1c34dc9 100644--- a/backend/e2e-test/cron-job.spec.ts+++ b/backend/e2e-test/cron-job.spec.ts@@ -51,6 +51,10 @@ const makeFactory = (overrides?: Partial<Parameters<typeof cronJobFactory>[0]>)retryBackoffMaxMs: 500,handlerTimeoutMs: 5_000,minProcessAgeMs: 0,+ // Keep test cleanup snappy. Production default is 25s to fit Kubernetes'+ // grace period; in tests we'd rather not stall afterEach if a handler+ // happens to be in flight at shutdown.+ drainTimeoutMs: 1_000,...overrides});};@@ -358,3 +362,85 @@ describe("min-age gate", () => {expect(handler).toHaveBeenCalled();}, 10_000);});++// ── graceful shutdown ──────────────────────────────────────────────────────────++describe("graceful shutdown", () => {+ // End-to-end regression guard for the BullMQ Worker.close() drain semantics:+ // stop() must wait for in-flight handlers to finish before releasing the+ // slot. Without this, redeploys would tear down active handlers mid-flight+ // (risking half-applied destructive operations like rotations) and leave+ // run hashes stuck in `status='running'` until the lease TTL elapses.+ test("stop() waits for in-flight handler to complete before resolving", async () => {+ let releaseHandler: () => void = () => {};+ let handlerStartedAt = 0;+ const handler = vi.fn().mockImplementation(+ () =>+ new Promise<void>((resolve) => {+ handlerStartedAt = Date.now();+ releaseHandler = resolve;+ })+ );++ const f = factory({ handlerTimeoutMs: 30_000, drainTimeoutMs: 5_000 });+ f.register({ name: "drain-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });+ f.start();++ // Wait for the enqueue + process pipeline to dispatch the handler.+ await new Promise((r) => {+ setTimeout(r, 1500);+ });+ expect(handler).toHaveBeenCalled();+ expect(handlerStartedAt).toBeGreaterThan(0);++ // Begin stop() but don't await yet. The drain race must keep it pending+ // until we release the handler.+ let stopResolvedAt = 0;+ const stopPromise = f.stop().then(() => {+ stopResolvedAt = Date.now();+ });++ // Sample the still-pending state. stop() should not have resolved yet+ // because the handler is still in flight.+ await new Promise((r) => {+ setTimeout(r, 200);+ });+ expect(stopResolvedAt).toBe(0);++ // Release the handler and capture the completion timestamp.+ const handlerCompletedAt = Date.now();+ releaseHandler();+ await stopPromise;++ // stop() must resolve at-or-after handler completion, never before.+ expect(stopResolvedAt).toBeGreaterThanOrEqual(handlerCompletedAt);+ }, 10_000);++ // Ensures a hung handler can't block shutdown past the orchestrator's+ // grace window: stop() falls back to lease-TTL crash recovery once the+ // drain timer expires.+ test("stop() releases the slot even when an in-flight handler hangs past drainTimeoutMs", async () => {+ const handler = vi.fn().mockImplementation(() => new Promise<void>(() => {})); // never resolves+ const f = factory({ handlerTimeoutMs: 30_000, drainTimeoutMs: 300 });+ f.register({ name: "hang-drain-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });+ f.start();++ await new Promise((r) => {+ setTimeout(r, 1500);+ });+ expect(handler).toHaveBeenCalled();++ const slotKeysBefore = await testRedis.keys("cron:slot:*");+ expect(slotKeysBefore.length).toBeGreaterThan(0);++ const startedAt = Date.now();+ await f.stop();+ const elapsed = Date.now() - startedAt;++ // 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:*");+ 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.tsindex 438bdf1b10..1e2458150c 100644--- a/backend/src/lib/cron/cron-job.test.ts+++ b/backend/src/lib/cron/cron-job.test.ts@@ -266,7 +266,11 @@ describe("retry backoff and handler timeout", () => {processIntervalMs: 100,slotTtlMs: 200,leaseDurationMs: 1000,- handlerTimeoutMs: 200+ handlerTimeoutMs: 200,+ // Bound the test's stop() drain. The handler hangs forever and new ticks+ // keep dispatching it, so without a short drainTimeoutMs the cleanup+ // would block until the production default (25s) and time the test out.+ drainTimeoutMs: 50});f.register({ name: "x", pattern: "* * * * *", handler, runHashTtlS: 3600, maxAttempts: 3 });f.start();@@ -283,7 +287,10 @@ describe("retry backoff and handler timeout", () => {);expect(wroteTimeoutError).toBe(true);- await f.stop();+ // Advance past drainTimeoutMs so stop() can resolve via the drain timeout.+ const stopPromise = f.stop();+ await vi.advanceTimersByTimeAsync(100);+ await stopPromise;});});@@ -330,6 +337,24 @@ describe("min-age gate", () => {});describe("stop", () => {+ // Locally mirrored from the retry-backoff suite — `setupPendingRun` lives in+ // that describe's scope, but the graceful-shutdown tests below need the same+ // pending-run fixture without coupling the two suites.+ const setupPendingRun = (redis: ReturnType<typeof makeRedis>, runIdScheduledAt: number) => {+ redis.set.mockResolvedValue("OK");+ redis.eval.mockResolvedValue(1);+ redis.zrangebyscore.mockResolvedValue([`x:${runIdScheduledAt}`]);+ redis.hgetall.mockResolvedValue({+ name: "x",+ status: "pending",+ attempts: "0",+ enqueued_at_ms: "0"+ });+ };++ // Identifies the slot-release eval (only Lua script that contains `del`).+ const isSlotReleaseEval = (call: unknown[]): boolean => typeof call[0] === "string" && call[0].includes("del");+test("releases held slot atomically", async () => {const redis = makeRedis();redis.set.mockResolvedValue("OK");@@ -343,4 +368,104 @@ describe("stop", () => {expect(lastEval[0]).toContain("del");expect(String(lastEval[2])).toContain("cron:slot:");});++ // Regression guard for the BullMQ Worker.close() drain semantics: stop()+ // must wait for in-flight handlers to settle before releasing the slot,+ // otherwise destructive handlers (rotations, deletions) get torn down+ // mid-flight and leases linger until their TTL elapses.+ test("drains in-flight handler before releasing the slot", async () => {+ vi.setSystemTime(new Date("2024-01-01T00:00:30Z"));+ const redis = makeRedis();+ setupPendingRun(redis, Date.parse("2024-01-01T00:00:00Z"));++ // Deferred-style handler: the test resolves it manually so we can assert+ // ordering between handler completion and slot release. Multiple ticks+ // can fire while the handler is in-flight (status stays "pending" in the+ // mock), so we collect every resolver to release them all together.+ const pendingResolvers: Array<() => void> = [];+ const handler = vi.fn().mockImplementation(+ () =>+ new Promise<void>((resolve) => {+ pendingResolvers.push(resolve);+ })+ );+ const redlock = makeRedlock();+ const f = cronJobFactory({+ redis: redis as never,+ redlock: redlock as never,+ slotRefreshMs: 50,+ enqueueIntervalMs: 100,+ processIntervalMs: 100,+ slotTtlMs: 200,+ leaseDurationMs: 1000,+ handlerTimeoutMs: 60_000,+ drainTimeoutMs: 5_000+ });+ f.register({ name: "x", pattern: "* * * * *", handler, runHashTtlS: 3600, maxAttempts: 3 });+ f.start();++ // Drive ticks until at least one handler is mid-execution.+ await vi.advanceTimersByTimeAsync(300);+ expect(handler).toHaveBeenCalled();+ expect(pendingResolvers.length).toBeGreaterThan(0);+ expect(redis.eval.mock.calls.some(isSlotReleaseEval)).toBe(false);++ // Begin stop() but don't await yet — the drain race must keep it pending+ // while handlers are still in flight.+ const stopPromise = f.stop();++ // Flush a couple of microtask cycles. clearInterval has fired, but the+ // slot release must not yet have been issued.+ await Promise.resolve();+ await Promise.resolve();+ expect(redis.eval.mock.calls.some(isSlotReleaseEval)).toBe(false);++ // Release every in-flight handler. Once the chain+ // handler.resolve → markCompleted → redlock.using.resolve → inFlight.delete+ // settles for all of them, drain wins the race and stop() proceeds to+ // slot release.+ pendingResolvers.forEach((resolve) => resolve());+ await stopPromise;++ expect(redis.eval.mock.calls.some(isSlotReleaseEval)).toBe(true);+ });++ // The orchestrator's grace period (e.g. Kubernetes' default 30s) caps how+ // long shutdown can block. drainTimeoutMs guards against a single hung+ // handler holding stop() open past that window — anything still in flight+ // after the timeout falls back to lease-TTL crash recovery.+ test("respects drainTimeoutMs when an in-flight handler hangs", async () => {+ vi.setSystemTime(new Date("2024-01-01T00:00:30Z"));+ const redis = makeRedis();+ setupPendingRun(redis, Date.parse("2024-01-01T00:00:00Z"));++ const handler = vi.fn().mockImplementation(() => new Promise<void>(() => {})); // never resolves+ const redlock = makeRedlock();+ const f = cronJobFactory({+ redis: redis as never,+ redlock: redlock as never,+ slotRefreshMs: 50,+ enqueueIntervalMs: 100,+ processIntervalMs: 100,+ slotTtlMs: 200,+ leaseDurationMs: 1000,+ // Long enough that handlerTimeoutMs doesn't naturally drain inFlight.+ handlerTimeoutMs: 60_000,+ drainTimeoutMs: 200+ });+ f.register({ name: "x", pattern: "* * * * *", handler, runHashTtlS: 3600, maxAttempts: 3 });+ f.start();++ await vi.advanceTimersByTimeAsync(300);+ expect(handler).toHaveBeenCalled();++ const stopPromise = f.stop();+ // Advance past drainTimeoutMs so the timeout branch wins the race.+ await vi.advanceTimersByTimeAsync(300);+ await stopPromise;++ // Slot is released even though the handler is still hung — recovery is+ // delegated to the lease TTL on a replacement pod.+ expect(redis.eval.mock.calls.some(isSlotReleaseEval)).toBe(true);+ });});diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.tsindex 6fdb8f6ac2..952ff86afc 100644--- a/backend/src/lib/cron/cron-job.ts+++ b/backend/src/lib/cron/cron-job.ts@@ -25,7 +25,8 @@ const DEFAULTS = {leaseDurationMs: 5 * 60_000,handlerTimeoutMs: 5 * 60_000,retryBackoffBaseMs: 30_000,- retryBackoffMaxMs: 5 * 60_000+ retryBackoffMaxMs: 5 * 60_000,+ drainTimeoutMs: 25_000} as const;// ── redis schema ──────────────────────────────────────────────────────────────@@ -99,7 +100,8 @@ export const cronJobFactory = ({leaseDurationMs = DEFAULTS.leaseDurationMs,handlerTimeoutMs = DEFAULTS.handlerTimeoutMs,retryBackoffBaseMs = DEFAULTS.retryBackoffBaseMs,- retryBackoffMaxMs = DEFAULTS.retryBackoffMaxMs+ retryBackoffMaxMs = DEFAULTS.retryBackoffMaxMs,+ drainTimeoutMs = DEFAULTS.drainTimeoutMs}: {redis: Redis | Cluster;redlock: Redlock;@@ -112,10 +114,12 @@ export const cronJobFactory = ({handlerTimeoutMs?: number;retryBackoffBaseMs?: number;retryBackoffMaxMs?: number;+ drainTimeoutMs?: number;}) => {const workerId = randomUUID();const entries = new Map<string, CronEntry>();const lastEnqueuedAt = new Map<string, number>();+ const inFlight = new Set<Promise<unknown>>();let slotTimer: ReturnType<typeof setInterval> | null = null;let enqueueTimer: ReturnType<typeof setInterval> | null = null;let processTimer: ReturnType<typeof setInterval> | null = null;@@ -402,14 +406,21 @@ export const cronJobFactory = ({logger.info(`cron[${data.name}]: re-claiming stalled run [id=${id}] [previous_worker=${data.worker_id}]`);}+ // Track the in-flight run so stop() can wait for it to settle before+ // tearing down. Lock-contention rejections settle within a tick, so they+ // don't measurably delay shutdown drain.+ const tracked = redlock.using([LEASE_KEY(id)], leaseDurationMs, (signal) =>+ executeUnderLease(entry, id, attempts + 1, signal as AbortSignal)+ );+ inFlight.add(tracked);try {- await redlock.using([LEASE_KEY(id)], leaseDurationMs, (signal) =>- executeUnderLease(entry, id, attempts + 1, signal as AbortSignal)- );+ await tracked;} catch (err) {// ExecutionError / ResourceLockedError mean another pod owns the lease — expected contention, swallow.if (err instanceof ExecutionError || err instanceof ResourceLockedError) return;logger.error({ err }, `cron[${data.name}]: unexpected error acquiring lease [id=${id}]`);+ } finally {+ inFlight.delete(tracked);}};@@ -451,12 +462,36 @@ export const cronJobFactory = ({safeTick("initial slot claim", claimOrRefreshSlot)();};- // Stops the timers and atomically releases the held slot (only if we still- // own it) so another pod can take over without waiting for the slot TTL.+ // Stops the timers, drains in-flight handlers, and atomically releases the+ // held slot (only if we still own it) so another pod can take over without+ // waiting for the slot TTL.+ //+ // Drain semantics wait for the currently active runs to finish so destructive handlers (rotations, deletions)+ // aren't aborted mid-execution and graceful redeploys don't leave runs+ // stuck in `status='running'` until the lease TTL elapses.const stop = async () => {if (slotTimer) clearInterval(slotTimer);if (enqueueTimer) clearInterval(enqueueTimer);if (processTimer) clearInterval(processTimer);++ if (inFlight.size > 0) {+ logger.info(`cron: draining ${inFlight.size} in-flight run(s) [worker=${workerId}]`);+ const drained = Promise.allSettled(Array.from(inFlight));+ let timeoutHandle: ReturnType<typeof setTimeout> | undefined;+ const timedOut = new Promise<"timeout">((resolve) => {+ timeoutHandle = setTimeout(() => resolve("timeout"), drainTimeoutMs);+ });+ try {+ const result = await Promise.race([drained, timedOut]);+ if (result === "timeout") {+ logger.warn(+ `cron: drain timeout reached after ${drainTimeoutMs}ms with ${inFlight.size} run(s) still active — relying on lease TTL for recovery [worker=${workerId}]`+ );+ }+ } finally {+ if (timeoutHandle) clearTimeout(timeoutHandle);+ }+ }if (currentSlot !== null) {await redis.eval(RELEASE_SLOT_IF_MINE_LUA, 1, SLOT_KEY(currentSlot), workerId);logger.info(`cron: released slot ${currentSlot} [worker=${workerId}]`);