Skip to content

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

fix(cron): enhance error handling in cron job execution and improve logging for resource cleanup tasks

Victor Hugo dos Santos17f9be12ab7c
diff --git a/backend/e2e-test/cron-job.spec.ts b/backend/e2e-test/cron-job.spec.ts
index c02ae4742c..015726a2b8 100644
--- a/backend/e2e-test/cron-job.spec.ts
+++ b/backend/e2e-test/cron-job.spec.ts
@@ -323,7 +323,7 @@ describe("ZSET cleanup", () => {
});
const pending = await testRedis.zrange("cron:pending", 0, -1);
- expect(pending).not.toContain(expect.stringContaining("clean-job"));
+ expect(pending.filter((s) => s.startsWith("clean-job:"))).toEqual([]);
}, 10_000);
});
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index 0e134a0078..6fdb8f6ac2 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -4,7 +4,7 @@ import { CronExpressionParser } from "cron-parser";
import { Cluster, Redis } from "ioredis";
import { logger } from "@app/lib/logger";
-import { Redlock } from "@app/lib/red-lock";
+import { ExecutionError, Redlock, ResourceLockedError } from "@app/lib/red-lock";
// ── tuning constants ──────────────────────────────────────────────────────────
@@ -322,7 +322,13 @@ export const cronJobFactory = ({
const ac = new AbortController();
leaseSignal.addEventListener?.("abort", () => ac.abort());
- await markRunning(id, attempt);
+ try {
+ await markRunning(id, attempt);
+ } catch (err) {
+ logger.error({ err }, `cron[${entry.name}]: failed to mark run as running [id=${id}]`);
+ return;
+ }
+
const startMs = Date.now();
logger.info(`cron[${entry.name}]: start (attempt ${attempt}/${entry.maxAttempts}) [id=${id}]`);
@@ -341,8 +347,15 @@ export const cronJobFactory = ({
const fitsBeforeNextFire = nextAttemptAt + NEXT_FIRE_BUFFER_MS < nextFireMs(entry.pattern);
const final = attempt >= entry.maxAttempts || !fitsBeforeNextFire;
- if (final) await markFailedFinal(id, err);
- else await markPendingRetry(id, err, nextAttemptAt);
+ try {
+ if (final) await markFailedFinal(id, err);
+ else await markPendingRetry(id, err, nextAttemptAt);
+ } catch (stateErr) {
+ logger.error(
+ { err: stateErr, originalErr: err },
+ `cron[${entry.name}]: failed to mark run state after attempt ${attempt} [id=${id}]`
+ );
+ }
logger.error(
{ err },
@@ -393,8 +406,10 @@ export const cronJobFactory = ({
await redlock.using([LEASE_KEY(id)], leaseDurationMs, (signal) =>
executeUnderLease(entry, id, attempts + 1, signal as AbortSignal)
);
- } catch {
- // Lock contention — another pod is executing this run; move on.
+ } 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}]`);
}
};
@@ -411,27 +426,29 @@ export const cronJobFactory = ({
shuffleInPlace(ids);
for (const id of ids) {
- // eslint-disable-next-line no-await-in-loop
- await processCandidate(id);
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ await processCandidate(id);
+ } catch (err) {
+ logger.error({ err, id }, "cron: processCandidate failed");
+ }
}
};
// ── lifecycle ───────────────────────────────────────────────────────────────
+ const safeTick = (label: string, fn: () => Promise<void>) => () => {
+ fn().catch((err: unknown) => logger.error({ err }, `cron: ${label} failed`));
+ };
+
// Starts the slot-refresh, enqueue, and process timers, and claims a slot
// immediately so the pod doesn't wait a full `slotRefreshMs` before
// participating.
const start = () => {
- slotTimer = setInterval(() => {
- void claimOrRefreshSlot();
- }, slotRefreshMs);
- enqueueTimer = setInterval(() => {
- void enqueueTick();
- }, enqueueIntervalMs);
- processTimer = setInterval(() => {
- void processTick();
- }, processIntervalMs);
- void claimOrRefreshSlot();
+ slotTimer = setInterval(safeTick("slot refresh", claimOrRefreshSlot), slotRefreshMs);
+ enqueueTimer = setInterval(safeTick("enqueue tick", enqueueTick), enqueueIntervalMs);
+ processTimer = setInterval(safeTick("process tick", processTick), processIntervalMs);
+ safeTick("initial slot claim", claimOrRefreshSlot)();
};
// Stops the timers and atomically releases the held slot (only if we still
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 317fafeed3..767b73d745 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -525,7 +525,7 @@ export const registerRoutes = async (
) => {
const appCfg = getConfig();
- const redlock = new Redlock([redis as Redis], { retryCount: 0 });
+ const redlock = new Redlock([redis], { retryCount: 0 });
const cronJob = cronJobFactory({ redis, redlock });
cronJob.start();
diff --git a/backend/src/services/identity-ua/identity-ua-client-secret-dal.ts b/backend/src/services/identity-ua/identity-ua-client-secret-dal.ts
index dd025857fa..c02b245397 100644
--- a/backend/src/services/identity-ua/identity-ua-client-secret-dal.ts
+++ b/backend/src/services/identity-ua/identity-ua-client-secret-dal.ts
@@ -33,7 +33,7 @@ export const identityUaClientSecretDALFactory = (db: TDbClient) => {
let numberOfRetryOnFailure = 0;
let isRetrying = false;
- logger.info(`daily-resource-cleanup: remove expired univesal auth client secret started`);
+ logger.info(`daily-resource-cleanup: remove expired universal auth client secret started`);
do {
try {
const findExpiredClientSecretQuery = (tx || db)(TableName.IdentityUaClientSecret)
@@ -77,7 +77,7 @@ export const identityUaClientSecretDALFactory = (db: TDbClient) => {
}
isRetrying = numberOfRetryOnFailure > 0;
} while (deletedClientSecret.length > 0 || (isRetrying && numberOfRetryOnFailure < MAX_RETRY_ON_FAILURE));
- logger.info(`daily-resource-cleanup: remove expired univesal auth client secret completed`);
+ logger.info(`daily-resource-cleanup: remove expired universal auth client secret completed`);
};
return { ...uaClientSecretOrm, incrementUsage, removeExpiredClientSecrets };
diff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
index 61458e8e25..a0b86594f7 100644
--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
@@ -21,6 +21,9 @@ import { TSecretSharingDALFactory } from "../secret-sharing/secret-sharing-dal";
import { TSecretVersionV2DALFactory } from "../secret-v2-bridge/secret-version-dal";
import { TServiceTokenServiceFactory } from "../service-token/service-token-service";
+const CRON_NAME_DAILY_CLEANUP = "daily-resource-cleanup";
+const CRON_NAME_FREQUENT_CLEANUP = "frequent-resource-cleanup";
+
type TDailyResourceCleanUpQueueServiceFactoryDep = {
auditLogDAL: Pick<TAuditLogDALFactory, "pruneAuditLog">;
auditLogService: Pick<TAuditLogServiceFactory, "checkPostgresAuditLogVolumeMigrationAlert">;
@@ -76,12 +79,12 @@ export const dailyResourceCleanUpQueueServiceFactory = ({
const init = () => {
cronJob.register({
- name: "daily-resource-cleanup",
+ name: CRON_NAME_DAILY_CLEANUP,
pattern: appCfg.isDailyResourceCleanUpDevelopmentMode ? "*/5 * * * *" : "0 0 * * *",
runHashTtlS: 3 * 24 * 60 * 60,
enabled: !appCfg.isSecondaryInstance,
handler: async () => {
- logger.info("cron[daily-resource-cleanup]: task started");
+ logger.info(`cron[${CRON_NAME_DAILY_CLEANUP}]: task started`);
await identityUniversalAuthClientSecretDAL.removeExpiredClientSecrets();
await secretSharingDAL.pruneExpiredSharedSecrets();
await secretSharingDAL.pruneExpiredSecretRequests();
@@ -107,12 +110,12 @@ export const dailyResourceCleanUpQueueServiceFactory = ({
});
cronJob.register({
- name: "frequent-resource-cleanup",
+ name: CRON_NAME_FREQUENT_CLEANUP,
pattern: appCfg.isDailyResourceCleanUpDevelopmentMode ? "*/5 * * * *" : "0 * * * *",
runHashTtlS: 2 * 24 * 60 * 60,
enabled: !appCfg.isSecondaryInstance,
handler: async () => {
- logger.info("cron[frequent-resource-cleanup]: task started");
+ logger.info(`cron[${CRON_NAME_FREQUENT_CLEANUP}]: task started`);
await identityAccessTokenDAL.removeExpiredTokens();
}
});
diff --git a/backend/src/services/telemetry/telemetry-queue.ts b/backend/src/services/telemetry/telemetry-queue.ts
index 8ab64da4b4..b49cda867a 100644
--- a/backend/src/services/telemetry/telemetry-queue.ts
+++ b/backend/src/services/telemetry/telemetry-queue.ts
@@ -46,13 +46,13 @@ export const telemetryQueueServiceFactory = ({
runHashTtlS: 3 * 24 * 60 * 60,
handler: async () => {
const { instanceId } = await getServerCfg();
- const telemtryStats = await telemetryDAL.getTelemetryInstanceStats();
+ const telemetryStats = await telemetryDAL.getTelemetryInstanceStats();
const numberOfSecretOperationsMade = parseInt(
(await keyStore.getItem(TELEMETRY_SECRET_OPERATIONS_KEY)) || "0",
10
);
const numberOfSecretProcessed = parseInt((await keyStore.getItem(TELEMETRY_SECRET_PROCESSED_KEY)) || "0", 10);
- const stats = { ...telemtryStats, numberOfSecretProcessed, numberOfSecretOperationsMade };
+ const stats = { ...telemetryStats, numberOfSecretProcessed, numberOfSecretOperationsMade };
postHog.capture({
event: PostHogEventTypes.TelemetryInstanceStats,