Skip to content

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

feat(cron): implement cron job system with cron-parser integration and add tests

Victor Hugo dos Santosd61202ee02ac
diff --git a/backend/e2e-test/cron-job.spec.ts b/backend/e2e-test/cron-job.spec.ts
new file mode 100644
index 0000000000..c02ae4742c
--- /dev/null
+++ b/backend/e2e-test/cron-job.spec.ts
@@ -0,0 +1,360 @@
+import type { Redis } from "ioredis";
+import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
+
+import { cronJobFactory } from "@app/lib/cron/cron-job";
+import { initLogger } from "@app/lib/logger";
+
+// testRedis is injected by vitest-environment-knex.ts
+declare const testRedis: Redis;
+
+// ── helpers ───────────────────────────────────────────────────────────────────
+
+// Simple in-memory lock manager for test redlock
+const lockManager = new Map<string, { timeout: NodeJS.Timeout; held: boolean }>();
+
+// Mock Redlock for testing
+const createTestRedlock = () => ({
+ async using(keys: string[], duration: number, fn: (signal: AbortSignal) => Promise<void>) {
+ const lockKey = keys[0];
+ const existing = lockManager.get(lockKey);
+ if (existing?.held) {
+ throw new Error("Lock already held");
+ }
+ const timeout = setTimeout(() => lockManager.delete(lockKey), duration);
+ lockManager.set(lockKey, { timeout, held: true });
+
+ try {
+ const controller = new AbortController();
+ await fn(controller.signal);
+ } finally {
+ const lock = lockManager.get(lockKey);
+ if (lock?.timeout) {
+ clearTimeout(lock.timeout);
+ }
+ lockManager.delete(lockKey);
+ }
+ }
+});
+
+const makeFactory = (overrides?: Partial<Parameters<typeof cronJobFactory>[0]>) => {
+ const redis = testRedis;
+ const redlock = createTestRedlock() as unknown as Parameters<typeof cronJobFactory>[0]["redlock"];
+ return cronJobFactory({
+ redis,
+ redlock,
+ slotTtlMs: 500,
+ slotRefreshMs: 100,
+ enqueueIntervalMs: 500,
+ processIntervalMs: 200,
+ leaseDurationMs: 2000,
+ retryBackoffBaseMs: 100,
+ retryBackoffMaxMs: 500,
+ handlerTimeoutMs: 5_000,
+ minProcessAgeMs: 0,
+ ...overrides
+ });
+};
+
+const FAST_PATTERN = "* * * * *"; // fires every minute
+const allFactories: ReturnType<typeof makeFactory>[] = [];
+
+const factory = (overrides?: Partial<Parameters<typeof cronJobFactory>[0]>) => {
+ const f = makeFactory(overrides);
+ allFactories.push(f);
+ return f;
+};
+
+beforeAll(() => {
+ initLogger();
+});
+
+beforeEach(async () => {
+ await testRedis.flushdb();
+ allFactories.length = 0;
+ lockManager.clear();
+});
+
+afterEach(async () => {
+ await Promise.allSettled(allFactories.map((f) => f.stop()));
+ await testRedis.flushdb();
+ vi.useRealTimers();
+});
+
+// ── single-pod: handler runs and completes ─────────────────────────────────────
+
+describe("single pod", () => {
+ test("handler is called and run hash ends up completed", async () => {
+ const handler = vi.fn().mockResolvedValue(undefined);
+ const f = factory();
+ f.register({ name: "test-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
+ f.start();
+
+ // Give the tick time to fire (slot acquisition + enqueue + claim + execute)
+ await new Promise((r) => {
+ setTimeout(r, 3000);
+ });
+
+ expect(handler).toHaveBeenCalled();
+ 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");
+ }, 10_000);
+});
+
+// ── two pods: exactly one handler invocation per fire boundary ─────────────────
+
+describe("multi-pod single fire", () => {
+ test("exactly one handler invocation across two factory instances", async () => {
+ const handler = vi.fn().mockResolvedValue(undefined);
+ const f1 = factory();
+ const f2 = factory();
+ f1.register({ name: "shared-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
+ f2.register({ name: "shared-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
+ f1.start();
+ f2.start();
+
+ await new Promise((r) => {
+ setTimeout(r, 4000);
+ });
+
+ 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");
+ // Handler should have been called exactly once across both pods
+ expect(handler).toHaveBeenCalledTimes(1);
+ }, 12_000);
+});
+
+// ── slot exhaustion: N+1 factories, exactly N participate ─────────────────────
+
+describe("slot exhaustion", () => {
+ test("only PARTICIPANT_SLOTS=5 out of 6 factories claim a slot", async () => {
+ const factories = Array.from({ length: 6 }, () => factory());
+ factories.forEach((f) => f.register({ name: `j`, pattern: FAST_PATTERN, handler: vi.fn(), runHashTtlS: 3600 }));
+ factories.forEach((f) => f.start());
+
+ // Allow slot acquisition to propagate
+ await new Promise((r) => {
+ setTimeout(r, 2000);
+ });
+
+ const slotKeys = await testRedis.keys("cron:slot:*");
+ expect(slotKeys.length).toBeLessThanOrEqual(5);
+ }, 8_000);
+});
+
+// ── slot handover on stop ──────────────────────────────────────────────────────
+
+describe("slot handover", () => {
+ test("stopping a participant frees its slot for another factory", async () => {
+ const factories = Array.from({ length: 6 }, () => factory());
+ factories.forEach((f) => f.register({ name: `h`, pattern: FAST_PATTERN, handler: vi.fn(), runHashTtlS: 3600 }));
+ factories.forEach((f) => f.start());
+
+ await new Promise((r) => {
+ setTimeout(r, 2000);
+ });
+ 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:*");
+ expect(slotsAfter.length).toBe(0);
+ }, 8_000);
+});
+
+// ── retry on failure ──────────────────────────────────────────────────────────
+
+describe("retry", () => {
+ test("failed handler flips status back to pending with last_error populated", async () => {
+ let calls = 0;
+ const handler = vi.fn().mockImplementation(async () => {
+ calls += 1;
+ if (calls === 1) throw new Error("transient failure");
+ });
+ const f = factory();
+ f.register({ name: "retry-job", pattern: FAST_PATTERN, handler, maxAttempts: 3, runHashTtlS: 3600 });
+ f.start();
+
+ await new Promise((r) => {
+ setTimeout(r, 4000);
+ });
+
+ 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
+ expect(run.status).toBe("completed");
+ expect(handler).toHaveBeenCalledTimes(2);
+ }, 12_000);
+
+ test("after maxAttempts failures status becomes failed", async () => {
+ const handler = vi.fn().mockRejectedValue(new Error("always fails"));
+ const f = factory();
+ f.register({ name: "fail-job", pattern: FAST_PATTERN, handler, maxAttempts: 2, runHashTtlS: 3600 });
+ f.start();
+
+ await new Promise((r) => {
+ setTimeout(r, 5000);
+ });
+
+ 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");
+ expect(run.last_error).toContain("always fails");
+ expect(handler).toHaveBeenCalledTimes(2);
+ }, 15_000);
+});
+
+// ── handler timeout ────────────────────────────────────────────────────────────
+
+describe("handler timeout", () => {
+ test("hung handler is aborted after handlerTimeoutMs and run flips to pending with timeout error", async () => {
+ // Handler never resolves — simulates a wedged network call.
+ const handler = vi.fn().mockImplementation(() => new Promise<void>(() => {}));
+ const f = factory({
+ handlerTimeoutMs: 500,
+ retryBackoffBaseMs: 100,
+ retryBackoffMaxMs: 200
+ });
+ f.register({ name: "hang-job", pattern: FAST_PATTERN, handler, maxAttempts: 5, runHashTtlS: 3600 });
+ f.start();
+
+ // Enqueue (~500ms) + first attempt hangs for handlerTimeoutMs (500ms) +
+ // backoff (100ms) + second attempt window. Wait long enough to observe
+ // the timeout-driven retry without burning all attempts.
+ await new Promise((r) => {
+ setTimeout(r, 2500);
+ });
+
+ expect(handler.mock.calls.length).toBeGreaterThanOrEqual(2);
+ const keys = await testRedis.keys("cron:run:hang-job:*");
+ expect(keys.length).toBe(1);
+ const run = await testRedis.hgetall(keys[0]);
+ expect(run.last_error).toContain("exceeded");
+ }, 10_000);
+});
+
+// ── retry backoff spacing ──────────────────────────────────────────────────────
+
+describe("retry backoff", () => {
+ test("retries are spaced out by backoffBase, not back-to-back", async () => {
+ const callTimes: number[] = [];
+ const handler = vi.fn().mockImplementation(async () => {
+ callTimes.push(Date.now());
+ throw new Error("boom");
+ });
+ const f = factory({ retryBackoffBaseMs: 700, retryBackoffMaxMs: 2_000 });
+ f.register({ name: "backoff-job", pattern: FAST_PATTERN, handler, maxAttempts: 4, runHashTtlS: 3600 });
+ f.start();
+
+ // Two failures separated by ~700ms backoff = ~1.4s + enqueue overhead.
+ await new Promise((r) => {
+ setTimeout(r, 3_500);
+ });
+
+ expect(callTimes.length).toBeGreaterThanOrEqual(2);
+ const gap = callTimes[1] - callTimes[0];
+ // Tolerance: backoff is 700ms; allow some scheduling slop on either side.
+ expect(gap).toBeGreaterThanOrEqual(500);
+ }, 10_000);
+
+ test("non-final failure updates zset score to next_attempt_at (future)", async () => {
+ const handler = vi.fn().mockRejectedValue(new Error("boom"));
+ const f = factory({ retryBackoffBaseMs: 5_000, retryBackoffMaxMs: 10_000 });
+ f.register({ name: "score-job", pattern: FAST_PATTERN, handler, maxAttempts: 3, runHashTtlS: 3600 });
+ f.start();
+
+ // Give time for one failure to be processed and re-scored, but not for the
+ // 5s backoff to elapse.
+ await new Promise((r) => {
+ setTimeout(r, 2_000);
+ });
+
+ 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);
+ expect(score).not.toBeNull();
+ expect(Number(score)).toBeGreaterThan(Date.now());
+ expect(handler).toHaveBeenCalledTimes(1);
+ }, 10_000);
+});
+
+// ── next-fire guard ────────────────────────────────────────────────────────────
+
+describe("next-fire guard", () => {
+ test("failure with backoff > cron interval is marked final immediately", async () => {
+ const handler = vi.fn().mockRejectedValue(new Error("boom"));
+ // backoffBase (65s) > 60s cron interval — guard should mark this final on
+ // the very first failure regardless of maxAttempts.
+ const f = factory({ retryBackoffBaseMs: 65_000, retryBackoffMaxMs: 65_000 });
+ f.register({ name: "guard-job", pattern: FAST_PATTERN, handler, maxAttempts: 5, runHashTtlS: 3600 });
+ f.start();
+
+ await new Promise((r) => {
+ setTimeout(r, 2_000);
+ });
+
+ expect(handler).toHaveBeenCalledTimes(1);
+ 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");
+ expect(run.last_error).toContain("boom");
+ }, 10_000);
+});
+
+// ── ZSET cleared on success ────────────────────────────────────────────────────
+
+describe("ZSET cleanup", () => {
+ 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 });
+ f.start();
+
+ await new Promise((r) => {
+ setTimeout(r, 3000);
+ });
+
+ const pending = await testRedis.zrange("cron:pending", 0, -1);
+ expect(pending).not.toContain(expect.stringContaining("clean-job"));
+ }, 10_000);
+});
+
+// ── min-age gate ───────────────────────────────────────────────────────────────
+
+describe("min-age gate", () => {
+ test("run is enqueued but handler is withheld until minProcessAgeMs elapses", async () => {
+ const handler = vi.fn().mockResolvedValue(undefined);
+ // Override only the age gate; all other timings stay at their e2e defaults.
+ const f = factory({ minProcessAgeMs: 500 });
+ f.register({ name: "age-gate-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
+ f.start();
+
+ // Wait for the enqueue tick (enqueueIntervalMs=500ms) + buffer so the run
+ // hash is present in Redis, but NOT long enough for the 500ms age gate to
+ // clear. Enqueue fires at ~500ms; at 700ms the run is only ~200ms old and
+ // the process ticks at 600ms / 800ms both skip it.
+ await new Promise((r) => {
+ setTimeout(r, 700);
+ });
+
+ 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
+
+ // Earliest possible pickup: enqueue at ~500ms + minProcessAgeMs 500ms = ~1000ms.
+ // Allow until 2500ms total to absorb any scheduling jitter.
+ await new Promise((r) => {
+ setTimeout(r, 1800);
+ });
+
+ expect(handler).toHaveBeenCalled();
+ }, 10_000);
+});
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 2ba6b5528d..5c862b2098 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -85,6 +85,7 @@
"cassandra-driver": "^4.7.2",
"connect-redis": "^7.1.1",
"cron": "^3.1.7",
+ "cron-parser": "^5.5.0",
"dd-trace": "^5.40.0",
"dns-packet": "^5.6.1",
"dotenv": "^16.4.1",
@@ -13879,6 +13880,18 @@
"uuid": "11.1.0"
}
},
+ "node_modules/bullmq/node_modules/cron-parser": {
+ "version": "4.9.0",
+ "resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-4.9.0.tgz",
+ "integrity": "sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==",
+ "license": "MIT",
+ "dependencies": {
+ "luxon": "^3.2.1"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
"node_modules/bundle-name": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/bundle-name/-/bundle-name-4.1.0.tgz",
@@ -14687,14 +14700,24 @@
}
},
"node_modules/cron-parser": {
- "version": "4.9.0",
- "resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-4.9.0.tgz",
- "integrity": "sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==",
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-5.5.0.tgz",
+ "integrity": "sha512-oML4lKUXxizYswqmxuOCpgFS8BNUJpIu6k/2HVHyaL8Ynnf3wdf9tkns0yRdJLSIjkJ+b0DXHMZEHGpMwjnPww==",
+ "license": "MIT",
"dependencies": {
- "luxon": "^3.2.1"
+ "luxon": "^3.7.1"
},
"engines": {
- "node": ">=12.0.0"
+ "node": ">=18"
+ }
+ },
+ "node_modules/cron-parser/node_modules/luxon": {
+ "version": "3.7.2",
+ "resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz",
+ "integrity": "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
}
},
"node_modules/cross-fetch": {
diff --git a/backend/package.json b/backend/package.json
index d1c83fd749..1dd21945ff 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -211,6 +211,7 @@
"cassandra-driver": "^4.7.2",
"connect-redis": "^7.1.1",
"cron": "^3.1.7",
+ "cron-parser": "^5.5.0",
"dd-trace": "^5.40.0",
"dns-packet": "^5.6.1",
"dotenv": "^16.4.1",
diff --git a/backend/src/ee/services/audit-log/audit-log-dal.ts b/backend/src/ee/services/audit-log/audit-log-dal.ts
index cf4d8763f9..2d258d5e2d 100644
--- a/backend/src/ee/services/audit-log/audit-log-dal.ts
+++ b/backend/src/ee/services/audit-log/audit-log-dal.ts
@@ -8,7 +8,6 @@ import { getConfig } from "@app/lib/config/env";
import { DatabaseError, GatewayTimeoutError } from "@app/lib/errors";
import { ormify, selectAllTableCols, TOrmify } from "@app/lib/knex";
import { logger } from "@app/lib/logger";
-import { QueueName } from "@app/queue";
import { ActorType } from "@app/services/auth/auth-type";
import { ACTOR_TYPE_TO_METADATA_ID_KEY, EventType, filterableSecretEvents } from "./audit-log-types";
@@ -184,7 +183,7 @@ export const auditLogDALFactory = (db: TDbClient) => {
let numberOfRetryOnFailure = 0;
let isRetrying = false;
- logger.info(`${QueueName.DailyResourceCleanUp}: audit log started`);
+ logger.info(`daily-resource-cleanup: audit log started`);
do {
try {
// eslint-disable-next-line no-await-in-loop
@@ -217,7 +216,7 @@ export const auditLogDALFactory = (db: TDbClient) => {
}
isRetrying = numberOfRetryOnFailure > 0;
} while (deletedAuditLogIds.length > 0 || (isRetrying && numberOfRetryOnFailure < MAX_RETRY_ON_FAILURE));
- logger.info(`${QueueName.DailyResourceCleanUp}: audit log completed`);
+ logger.info(`daily-resource-cleanup: audit log completed`);
};
const getApproximateRowCount: TAuditLogDALFactory["getApproximateRowCount"] = async () => {
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-queue.ts b/backend/src/ee/services/pam-discovery/pam-discovery-queue.ts
index fe6979c2d6..727686352a 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-queue.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-queue.ts
@@ -1,7 +1,8 @@
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue/queue-service";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue/queue-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
@@ -33,6 +34,7 @@ type TPamDiscoveryQueueFactoryDep = {
pamAccountDAL: Pick<TPamAccountDALFactory, "create" | "find" | "updateById" | "transaction">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById">;
};
@@ -51,6 +53,7 @@ export const pamDiscoveryQueueFactory = ({
pamAccountDAL,
kmsService,
queueService,
+ cronJob,
gatewayV2Service,
gatewayV2DAL
}: TPamDiscoveryQueueFactoryDep) => {
@@ -123,14 +126,16 @@ export const pamDiscoveryQueueFactory = ({
});
// runs every day at 3:00 AM
- void queueService
- .upsertJobScheduler(
- QueueName.PamDiscoveryScan,
- `${JOB_SCHEDULER_PREFIX}:pam-discovery-scheduled-scan`,
- { pattern: "0 3 * * *" },
- { name: QueueJobs.PamDiscoveryScheduledScan }
- )
- .catch((err) => logger.error(err, "Failed to schedule PAM Discovery cron"));
+ cronJob.register({
+ name: "pam-discovery-scheduled-scan",
+ pattern: "0 3 * * *",
+ runHashTtlS: 3 * 24 * 60 * 60,
+ handler: async () => {
+ await queueService.queue(QueueName.PamDiscoveryScan, QueueJobs.PamDiscoveryScheduledScan, undefined as never, {
+ jobId: "pam-discovery-scheduled-scan"
+ });
+ }
+ });
};
const queuePamDiscoveryScan = async (discoverySourceId: string) => {
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts b/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts
index c83dc00cf7..b75cfac891 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts
@@ -1,7 +1,8 @@
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue/queue-service";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue/queue-service";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -26,6 +27,7 @@ type TPkiDiscoveryQueueFactoryDep = {
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey">;
queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById">;
};
@@ -43,6 +45,7 @@ export const pkiDiscoveryQueueFactory = ({
projectDAL,
kmsService,
queueService,
+ cronJob,
gatewayV2Service,
gatewayV2DAL
}: TPkiDiscoveryQueueFactoryDep) => {
@@ -100,14 +103,16 @@ export const pkiDiscoveryQueueFactory = ({
}
});
- void queueService
- .upsertJobScheduler(
- QueueName.PkiDiscoveryScan,
- `${JOB_SCHEDULER_PREFIX}:pki-discovery-scheduled-scan`,
- { pattern: "0 2 * * *" },
- { name: QueueJobs.PkiDiscoveryScheduledScan }
- )
- .catch((err) => logger.error(err, "Failed to schedule PKI discovery cron"));
+ cronJob.register({
+ name: "pki-discovery-scheduled-scan",
+ pattern: "0 2 * * *",
+ runHashTtlS: 3 * 24 * 60 * 60,
+ handler: async () => {
+ await queueService.queue(QueueName.PkiDiscoveryScan, QueueJobs.PkiDiscoveryScheduledScan, undefined as never, {
+ jobId: "pki-discovery-scheduled-scan"
+ });
+ }
+ });
};
const queuePkiDiscoveryScan = async (discoveryId: string) => {
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-queue.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-queue.ts
index 2eaec1c3db..b571d6647a 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-queue.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-queue.ts
@@ -15,8 +15,9 @@ import {
TSecretRotationSendNotificationJobPayload
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
import { getConfig } from "@app/lib/config/env";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
import { NotificationType } from "@app/services/notification/notification-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -25,6 +26,7 @@ import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
type TSecretRotationV2QueueServiceFactoryDep = {
queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
secretRotationV2DAL: Pick<TSecretRotationV2DALFactory, "findSecretRotationsToQueue" | "findById">;
secretRotationV2Service: Pick<TSecretRotationV2ServiceFactory, "rotateGeneratedCredentials">;
smtpService: Pick<TSmtpService, "sendMail">;
@@ -35,6 +37,7 @@ type TSecretRotationV2QueueServiceFactoryDep = {
export const secretRotationV2QueueServiceFactory = async ({
queueService,
+ cronJob,
secretRotationV2DAL,
secretRotationV2Service,
projectMembershipDAL,
@@ -180,10 +183,17 @@ export const secretRotationV2QueueServiceFactory = async ({
}
});
- await queueService.upsertJobScheduler(
- QueueName.SecretRotationV2,
- `${JOB_SCHEDULER_PREFIX}:secret-rotation-v2-cron`,
- { pattern: appCfg.isRotationDevelopmentMode ? "* * * * *" : "0 0 * * *" },
- { name: QueueJobs.SecretRotationV2QueueRotations }
- );
+ cronJob.register({
+ name: "secret-rotation-v2-queue-rotations",
+ pattern: appCfg.isRotationDevelopmentMode ? "* * * * *" : "0 0 * * *",
+ runHashTtlS: 3 * 24 * 60 * 60,
+ handler: async () => {
+ await queueService.queue(
+ QueueName.SecretRotationV2,
+ QueueJobs.SecretRotationV2QueueRotations,
+ undefined as never,
+ { jobId: "secret-rotation-v2-queue-rotations" }
+ );
+ }
+ });
};
diff --git a/backend/src/ee/services/secret-snapshot/snapshot-dal.ts b/backend/src/ee/services/secret-snapshot/snapshot-dal.ts
index 17f1fad057..391113eea8 100644
--- a/backend/src/ee/services/secret-snapshot/snapshot-dal.ts
+++ b/backend/src/ee/services/secret-snapshot/snapshot-dal.ts
@@ -16,7 +16,6 @@ import {
import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex";
import { logger } from "@app/lib/logger";
-import { QueueName } from "@app/queue";
export type TSnapshotDALFactory = ReturnType<typeof snapshotDALFactory>;
@@ -621,7 +620,7 @@ export const snapshotDALFactory = (db: TDbClient) => {
const pruneExcessSnapshots = async () => {
const PRUNE_FOLDER_BATCH_SIZE = 10000;
- logger.info(`${QueueName.DailyResourceCleanUp}: pruning secret snapshots started`);
+ logger.info(`daily-resource-cleanup: pruning secret snapshots started`);
try {
let uuidOffset = "00000000-0000-0000-0000-000000000000";
// cleanup snapshots from current folders
@@ -737,7 +736,7 @@ export const snapshotDALFactory = (db: TDbClient) => {
} catch (error) {
throw new DatabaseError({ error, name: "SnapshotPrune" });
}
- logger.info(`${QueueName.DailyResourceCleanUp}: pruning secret snapshots completed`);
+ logger.info(`daily-resource-cleanup: pruning secret snapshots completed`);
};
// special query for migration for secret v2
diff --git a/backend/src/keystore/key-value-store-dal.ts b/backend/src/keystore/key-value-store-dal.ts
index bccedf4ac1..79e42fe9b7 100644
--- a/backend/src/keystore/key-value-store-dal.ts
+++ b/backend/src/keystore/key-value-store-dal.ts
@@ -4,7 +4,6 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
import { ormify, TOrmify } from "@app/lib/knex";
import { logger } from "@app/lib/logger";
-import { QueueName } from "@app/queue";
export interface TKeyValueStoreDALFactory extends TOrmify<TableName.KeyValueStore> {
incrementBy: (key: string, dto: { incr?: number; tx?: Knex; expiresAt?: Date }) => Promise<number>;
@@ -50,7 +49,7 @@ export const keyValueStoreDALFactory = (db: TDbClient): TKeyValueStoreDALFactory
let numberOfRetryOnFailure = 0;
let isRetrying = false;
- logger.info(`${QueueName.DailyResourceCleanUp}: db key value store clean up started`);
+ logger.info(`daily-resource-cleanup: db key value store clean up started`);
do {
try {
// eslint-disable-next-line no-await-in-loop
@@ -84,7 +83,7 @@ export const keyValueStoreDALFactory = (db: TDbClient): TKeyValueStoreDALFactory
}
isRetrying = numberOfRetryOnFailure > 0;
} while (deletedIds.length > 0 || (isRetrying && numberOfRetryOnFailure < MAX_RETRY_ON_FAILURE));
- logger.info(`${QueueName.DailyResourceCleanUp}: db key value store clean up completed`);
+ logger.info(`daily-resource-cleanup: db key value store clean up completed`);
};
return { ...keyValueStoreOrm, incrementBy, findOneInt, pruneExpiredKeys };
diff --git a/backend/src/lib/cron/cron-job.test.ts b/backend/src/lib/cron/cron-job.test.ts
new file mode 100644
index 0000000000..2933f93522
--- /dev/null
+++ b/backend/src/lib/cron/cron-job.test.ts
@@ -0,0 +1,346 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import { cronJobFactory } from "./cron-job";
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }
+}));
+
+// ── helpers ───────────────────────────────────────────────────────────────────
+
+const makeRedis = () => ({
+ set: vi.fn().mockResolvedValue(null),
+ get: vi.fn().mockResolvedValue(null),
+ del: vi.fn().mockResolvedValue(1),
+ exists: vi.fn().mockResolvedValue(0),
+ hset: vi.fn().mockResolvedValue(1),
+ hgetall: vi.fn().mockResolvedValue(null),
+ zrangebyscore: vi.fn().mockResolvedValue([]),
+ zadd: vi.fn().mockResolvedValue(1),
+ zrem: vi.fn().mockResolvedValue(1),
+ eval: vi.fn().mockResolvedValue(0)
+});
+
+const makeRedlock = () => ({
+ using: vi.fn(async (_keys: string[], _duration: number, fn: (signal: AbortSignal) => Promise<void>) => {
+ const controller = new AbortController();
+ return fn(controller.signal);
+ })
+});
+
+// Use a cast via unknown to satisfy the type system for the mocks
+type FakeDeps = {
+ redis: ReturnType<typeof makeRedis>;
+ redlock: ReturnType<typeof makeRedlock>;
+};
+const makeFactory = (deps?: Partial<FakeDeps>) => {
+ const redis = deps?.redis ?? makeRedis();
+ const redlock = deps?.redlock ?? makeRedlock();
+ return {
+ ...cronJobFactory({
+ redis: redis as never,
+ redlock: redlock as never,
+ slotRefreshMs: 50,
+ enqueueIntervalMs: 100,
+ processIntervalMs: 100,
+ slotTtlMs: 200,
+ leaseDurationMs: 1000
+ }),
+ redis,
+ redlock
+ };
+};
+
+// ── lifecycle ─────────────────────────────────────────────────────────────────
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+// ── tests ─────────────────────────────────────────────────────────────────────
+
+describe("register", () => {
+ test("throws on invalid cron pattern", () => {
+ const { register } = makeFactory();
+ expect(() => register({ name: "x", pattern: "not-a-cron", handler: vi.fn(), runHashTtlS: 3600 })).toThrow();
+ });
+
+ test("throws on duplicate name", () => {
+ const { register } = makeFactory();
+ register({ name: "x", pattern: "0 0 * * *", handler: vi.fn(), runHashTtlS: 3600 });
+ expect(() => register({ name: "x", pattern: "0 0 * * *", handler: vi.fn(), runHashTtlS: 3600 })).toThrow(
+ /already registered/
+ );
+ });
+
+ test("disabled entry is skipped", async () => {
+ const { register, start, stop, redis } = makeFactory();
+ register({ name: "x", pattern: "0 0 * * *", handler: vi.fn(), runHashTtlS: 3600, enabled: false });
+ start();
+ expect(redis.eval).not.toHaveBeenCalled();
+ await stop();
+ });
+});
+
+describe("slot election", () => {
+ test("claims slot 0 on boot when free", async () => {
+ const redis = makeRedis();
+ redis.set.mockResolvedValueOnce("OK");
+ const { start, stop } = makeFactory({ redis });
+ 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");
+ await stop();
+ });
+
+ test("falls through to slot 1 when slot 0 is held", async () => {
+ const redis = makeRedis();
+ redis.set.mockResolvedValueOnce(null).mockResolvedValueOnce("OK");
+ 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");
+ await stop();
+ });
+
+ test("sits idle when all slots are held", async () => {
+ const redis = makeRedis();
+ redis.set.mockResolvedValue(null);
+ const { register, start, stop } = makeFactory({ redis });
+ register({ name: "x", pattern: "0 0 * * *", handler: vi.fn(), runHashTtlS: 3600 });
+ start();
+ await Promise.resolve();
+ expect(redis.eval).not.toHaveBeenCalled();
+ await stop();
+ });
+
+ test("refreshes held slot on next interval", async () => {
+ const redis = makeRedis();
+ redis.set.mockResolvedValueOnce("OK").mockResolvedValue("OK");
+ const { start, stop } = makeFactory({ redis });
+ start();
+ await Promise.resolve();
+ vi.advanceTimersByTime(60);
+ await Promise.resolve();
+ const xxCalls = redis.set.mock.calls.filter((c) => (c as string[]).includes("XX"));
+ expect(xxCalls.length).toBeGreaterThan(0);
+ await stop();
+ });
+
+ test("re-attempts NX after slot refresh fails", async () => {
+ const redis = makeRedis();
+ redis.set.mockResolvedValueOnce("OK").mockResolvedValueOnce(null).mockResolvedValueOnce("OK");
+ const { start, stop } = makeFactory({ redis });
+ start();
+ vi.advanceTimersByTime(60);
+ await Promise.resolve();
+ const nxCalls = redis.set.mock.calls.filter((c) => (c as string[]).includes("NX"));
+ expect(nxCalls.length).toBeGreaterThanOrEqual(2);
+ await stop();
+ });
+});
+
+describe("claim and execute", () => {
+ test("boundary cache skips eval when timestamp unchanged", async () => {
+ const redis = makeRedis();
+ redis.set.mockResolvedValue("OK");
+ redis.eval.mockResolvedValue(1);
+ const { register, start, stop } = makeFactory({ redis });
+ register({ name: "x", pattern: "0 0 * * *", handler: vi.fn(), runHashTtlS: 3600 });
+ start();
+ await Promise.resolve();
+ vi.advanceTimersByTime(300);
+ await Promise.resolve();
+ const firstCount = redis.eval.mock.calls.length;
+ vi.advanceTimersByTime(30_000);
+ await Promise.resolve();
+ expect(redis.eval.mock.calls.length).toBe(firstCount);
+ await stop();
+ });
+
+ test("skips row whose name is not in local registry", async () => {
+ const redis = makeRedis();
+ redis.set.mockResolvedValue("OK");
+ redis.zrangebyscore.mockResolvedValue(["unknown:1000000000000"]);
+ redis.hgetall.mockResolvedValue({ name: "unknown", status: "pending", attempts: "0" });
+ const redlock = makeRedlock();
+ const { register, start, stop } = makeFactory({ redis, redlock });
+ register({ name: "x", pattern: "0 0 * * *", handler: vi.fn(), runHashTtlS: 3600 });
+ start();
+ vi.advanceTimersByTime(300);
+ await Promise.resolve();
+ expect(redlock.using).not.toHaveBeenCalled();
+ 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.
+ const setupPendingRun = (redis: ReturnType<typeof makeRedis>, runIdScheduledAt: number) => {
+ redis.set.mockResolvedValue("OK"); // slot claim succeeds
+ redis.eval.mockResolvedValue(1); // enqueue succeeds
+ redis.zrangebyscore.mockResolvedValue([`x:${runIdScheduledAt}`]);
+ redis.hgetall.mockResolvedValue({
+ name: "x",
+ status: "pending",
+ attempts: "0",
+ enqueued_at_ms: "0"
+ });
+ };
+
+ test("non-final failure updates zset score to a future next_attempt_at", async () => {
+ // Early in a minute: default 30s backoff fits comfortably before next fire.
+ vi.setSystemTime(new Date("2024-01-01T00:00:05Z"));
+ const redis = makeRedis();
+ setupPendingRun(redis, Date.parse("2024-01-01T00:00:00Z"));
+
+ const handler = vi.fn().mockRejectedValue(new Error("boom"));
+ const { register, start, stop } = makeFactory({ redis });
+ register({ name: "x", pattern: "* * * * *", handler, runHashTtlS: 3600, maxAttempts: 3 });
+ start();
+
+ // Slot claim + enqueue + process tick + handler reject
+ await vi.advanceTimersByTimeAsync(300);
+
+ expect(handler).toHaveBeenCalled();
+ expect(redis.zadd).toHaveBeenCalled();
+ const zaddArgs = redis.zadd.mock.calls[0] as unknown[];
+ expect(Number(zaddArgs[1])).toBeGreaterThan(Date.now());
+
+ // Status hash was updated to pending with next_attempt_at
+ const wroteNextAttempt = redis.hset.mock.calls.some((c) =>
+ (c as unknown[]).some((arg) => arg === "next_attempt_at")
+ );
+ expect(wroteNextAttempt).toBe(true);
+
+ await stop();
+ });
+
+ test("retry whose backoff overflows next fire is marked failed (zrem, not zadd)", async () => {
+ // 5s before next minute: backoffBase=30s overflows the interval.
+ vi.setSystemTime(new Date("2024-01-01T00:00:55Z"));
+ const redis = makeRedis();
+ setupPendingRun(redis, Date.parse("2024-01-01T00:00:00Z"));
+
+ const handler = vi.fn().mockRejectedValue(new Error("boom"));
+ const { register, start, stop } = makeFactory({ redis });
+ register({ name: "x", pattern: "* * * * *", handler, runHashTtlS: 3600, maxAttempts: 5 });
+ start();
+
+ await vi.advanceTimersByTimeAsync(300);
+
+ expect(handler).toHaveBeenCalled();
+ // Guard short-circuits before zadd
+ expect(redis.zadd).not.toHaveBeenCalled();
+ expect(redis.zrem).toHaveBeenCalled();
+ // Status flipped to failed
+ const wroteFailed = redis.hset.mock.calls.some((c) =>
+ (c as unknown[]).some((arg, i, arr) => arg === "status" && arr[i + 1] === "failed")
+ );
+ expect(wroteFailed).toBe(true);
+
+ await stop();
+ });
+
+ test("hung handler is aborted after handlerTimeoutMs and last_error includes 'exceeded'", 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
+ // Build factory inline because makeFactory doesn't expose handlerTimeoutMs.
+ 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: 200
+ });
+ f.register({ name: "x", pattern: "* * * * *", handler, runHashTtlS: 3600, maxAttempts: 3 });
+ f.start();
+
+ // Slot + enqueue + handler starts hanging, then past handlerTimeoutMs.
+ await vi.advanceTimersByTimeAsync(200);
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(handler).toHaveBeenCalled();
+ // The handler-timeout setTimeout's reject path writes last_error containing
+ // "exceeded" — strongest evidence the timeout fired and the catch ran.
+ const wroteTimeoutError = redis.hset.mock.calls.some((c) =>
+ (c as unknown[]).some((arg) => typeof arg === "string" && arg.includes("exceeded"))
+ );
+ expect(wroteTimeoutError).toBe(true);
+
+ await f.stop();
+ });
+});
+
+describe("min-age gate", () => {
+ test("redlock is skipped while run is fresh, then fires once minProcessAgeMs has elapsed", async () => {
+ vi.setSystemTime(new Date("2024-01-01T00:00:30Z"));
+ const enqueuedAt = Date.now(); // captured at fake-clock baseline
+
+ const redis = makeRedis();
+ redis.set.mockResolvedValue("OK"); // slot claim succeeds
+ redis.zrangebyscore.mockResolvedValue([`x:${enqueuedAt}`]);
+ redis.hgetall.mockResolvedValue({
+ name: "x",
+ status: "pending",
+ attempts: "0",
+ enqueued_at_ms: String(enqueuedAt)
+ });
+
+ const redlock = makeRedlock();
+ const f = cronJobFactory({
+ redis: redis as never,
+ redlock: redlock as never,
+ slotRefreshMs: 50,
+ enqueueIntervalMs: 100,
+ processIntervalMs: 100,
+ slotTtlMs: 200,
+ leaseDurationMs: 1000,
+ minProcessAgeMs: 500
+ });
+ f.register({ name: "x", pattern: "* * * * *", handler: vi.fn(), runHashTtlS: 3600 });
+ f.start();
+
+ // Process ticks at 100 / 200 / 300ms have all seen the run, but age
+ // (300ms) < minProcessAgeMs (500ms) — redlock must remain idle.
+ await vi.advanceTimersByTimeAsync(300);
+ expect(redlock.using).not.toHaveBeenCalled();
+
+ // The tick at ≥500ms sees age ≥ 500ms and clears the gate.
+ await vi.advanceTimersByTimeAsync(300); // total 600ms elapsed
+ expect(redlock.using).toHaveBeenCalled();
+
+ await f.stop();
+ });
+});
+
+describe("stop", () => {
+ test("releases held slot atomically", async () => {
+ const redis = makeRedis();
+ redis.set.mockResolvedValue("OK");
+ redis.eval.mockResolvedValue(1);
+ const { start, stop } = makeFactory({ redis });
+ start();
+ vi.advanceTimersByTime(300);
+ await Promise.resolve();
+ await stop();
+ const lastEval = redis.eval.mock.calls.at(-1) as unknown[];
+ expect(lastEval[0]).toContain("del");
+ expect(String(lastEval[2])).toContain("cron:slot:");
+ });
+});
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
new file mode 100644
index 0000000000..0e134a0078
--- /dev/null
+++ b/backend/src/lib/cron/cron-job.ts
@@ -0,0 +1,450 @@
+import { randomUUID } from "node:crypto";
+
+import { CronExpressionParser } from "cron-parser";
+import { Cluster, Redis } from "ioredis";
+
+import { logger } from "@app/lib/logger";
+import { Redlock } from "@app/lib/red-lock";
+
+// ── tuning constants ──────────────────────────────────────────────────────────
+
+const PARTICIPANT_SLOTS = 5;
+const PROCESS_BATCH_SIZE = 50;
+// Safety buffer in `fitsBeforeNextFire`: if the retry's nextAttemptAt is within
+// this many ms of the next scheduled fire, treat the run as final and let the
+// next fire (separate id) be the natural retry instead.
+const NEXT_FIRE_BUFFER_MS = 1_000;
+const ERROR_MESSAGE_MAX_LEN = 4_000;
+
+const DEFAULTS = {
+ slotTtlMs: 60_000,
+ slotRefreshMs: 30_000,
+ enqueueIntervalMs: 30_000,
+ processIntervalMs: 5_000,
+ minProcessAgeMs: 1_000,
+ leaseDurationMs: 5 * 60_000,
+ handlerTimeoutMs: 5 * 60_000,
+ retryBackoffBaseMs: 30_000,
+ retryBackoffMaxMs: 5 * 60_000
+} as const;
+
+// ── 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";
+
+// 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.
+const RunStatus = {
+ Pending: "pending",
+ Running: "running",
+ Completed: "completed",
+ Failed: "failed"
+} as const;
+
+const F = {
+ Name: "name",
+ Status: "status",
+ Attempts: "attempts",
+ WorkerId: "worker_id",
+ ScheduledAt: "scheduled_at",
+ EnqueuedAtMs: "enqueued_at_ms",
+ StartedAt: "started_at",
+ CompletedAt: "completed_at",
+ LastError: "last_error",
+ NextAttemptAt: "next_attempt_at"
+} as const;
+
+// ── lua scripts ───────────────────────────────────────────────────────────────
+
+// Atomic "enqueue this run hash + zset entry if no other pod beat us to it".
+const ENQUEUE_RUN_LUA = `
+ if redis.call('exists', KEYS[1]) == 0 then
+ redis.call('hset', KEYS[1],
+ 'name', ARGV[1],
+ 'scheduled_at', ARGV[2],
+ 'status', 'pending',
+ 'attempts', 0,
+ 'enqueued_at_ms', ARGV[5])
+ redis.call('expire', KEYS[1], ARGV[3])
+ redis.call('zadd', KEYS[2], ARGV[2], ARGV[4])
+ return 1
+ end
+ return 0
+`;
+
+// "DEL only if I still own this slot". Stops a stale stop() call from
+// accidentally evicting the new owner after our TTL expired.
+const RELEASE_SLOT_IF_MINE_LUA = `if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end`;
+
+// ── types ─────────────────────────────────────────────────────────────────────
+
+type Handler = (signal: AbortSignal) => Promise<void>;
+type CronEntry = { name: string; pattern: string; maxAttempts: number; handler: Handler; runHashTtlS: number };
+
+export type TCronJobFactory = ReturnType<typeof cronJobFactory>;
+
+// ── factory ───────────────────────────────────────────────────────────────────
+
+export const cronJobFactory = ({
+ redis,
+ redlock,
+ slotTtlMs = DEFAULTS.slotTtlMs,
+ slotRefreshMs = DEFAULTS.slotRefreshMs,
+ enqueueIntervalMs = DEFAULTS.enqueueIntervalMs,
+ processIntervalMs = DEFAULTS.processIntervalMs,
+ minProcessAgeMs = DEFAULTS.minProcessAgeMs,
+ leaseDurationMs = DEFAULTS.leaseDurationMs,
+ handlerTimeoutMs = DEFAULTS.handlerTimeoutMs,
+ retryBackoffBaseMs = DEFAULTS.retryBackoffBaseMs,
+ retryBackoffMaxMs = DEFAULTS.retryBackoffMaxMs
+}: {
+ redis: Redis | Cluster;
+ redlock: Redlock;
+ slotTtlMs?: number;
+ slotRefreshMs?: number;
+ enqueueIntervalMs?: number;
+ processIntervalMs?: number;
+ minProcessAgeMs?: number;
+ leaseDurationMs?: number;
+ handlerTimeoutMs?: number;
+ retryBackoffBaseMs?: number;
+ retryBackoffMaxMs?: number;
+}) => {
+ const workerId = randomUUID();
+ const entries = new Map<string, CronEntry>();
+ const lastEnqueuedAt = new Map<string, number>();
+ let slotTimer: ReturnType<typeof setInterval> | null = null;
+ let enqueueTimer: ReturnType<typeof setInterval> | null = null;
+ let processTimer: ReturnType<typeof setInterval> | null = null;
+ let currentSlot: number | null = null;
+
+ // ── helpers ────────────────────────────────────────────────────────────
+
+ const prevFireMs = (pattern: string) => CronExpressionParser.parse(pattern, { tz: "UTC" }).prev().toDate().getTime();
+
+ const nextFireMs = (pattern: string) => CronExpressionParser.parse(pattern, { tz: "UTC" }).next().toDate().getTime();
+
+ const shuffleInPlace = <T>(arr: T[]): void => {
+ for (let i = arr.length - 1; i > 0; i -= 1) {
+ const j = Math.floor(Math.random() * (i + 1));
+ // eslint-disable-next-line no-param-reassign
+ [arr[i], arr[j]] = [arr[j], arr[i]];
+ }
+ };
+
+ // Races `task` against a timeout. If the timeout wins, aborts `ac` (so
+ // well-behaved handlers can short-circuit network calls) and rejects with a
+ // descriptive error. Used for HANG recovery — see executeUnderLease for the
+ // two-knob recovery model that justifies racing on top of redlock.using.
+ const withTimeout = async (task: (signal: AbortSignal) => Promise<void>, ac: AbortController, timeoutMs: number) => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ ac.abort();
+ reject(new Error(`handler exceeded ${timeoutMs}ms`));
+ }, timeoutMs);
+ });
+ try {
+ await Promise.race([task(ac.signal), timeout]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+ };
+
+ // ── run-hash status writes ──────────────────────────────────────────────────
+
+ const markRunning = (id: string, attempt: number) =>
+ redis.hset(
+ RUN_KEY(id),
+ F.Status,
+ RunStatus.Running,
+ F.WorkerId,
+ workerId,
+ F.StartedAt,
+ String(Date.now()),
+ F.Attempts,
+ String(attempt)
+ );
+
+ const markCompleted = async (id: string) => {
+ await redis.hset(RUN_KEY(id), F.Status, RunStatus.Completed, F.CompletedAt, String(Date.now()));
+ await redis.zrem(PENDING_ZSET, id);
+ };
+
+ // `err` is optional: the max-attempts-reached path writes a "failed" status
+ // without a last_error.
+ const markFailedFinal = async (id: string, err?: unknown) => {
+ if (err === undefined) {
+ await redis.hset(RUN_KEY(id), F.Status, RunStatus.Failed, F.CompletedAt, String(Date.now()));
+ } else {
+ await redis.hset(
+ RUN_KEY(id),
+ F.Status,
+ RunStatus.Failed,
+ F.LastError,
+ String(err).slice(0, ERROR_MESSAGE_MAX_LEN),
+ F.CompletedAt,
+ String(Date.now())
+ );
+ }
+ await redis.zrem(PENDING_ZSET, id);
+ };
+
+ const markPendingRetry = async (id: string, err: unknown, nextAttemptAt: number) => {
+ await redis.hset(
+ RUN_KEY(id),
+ F.Status,
+ RunStatus.Pending,
+ F.LastError,
+ String(err).slice(0, ERROR_MESSAGE_MAX_LEN),
+ F.NextAttemptAt,
+ String(nextAttemptAt)
+ );
+ // zset score = next_attempt_at so processTick's zrangebyscore filter skips
+ // this run until its backoff window elapses.
+ await redis.zadd(PENDING_ZSET, nextAttemptAt, id);
+ };
+
+ // ── registration ────────────────────────────────────────────────────────────
+
+ // Registers a cron entry with this pod. `runHashTtlS` controls how long each
+ // run's hash lives in Redis after enqueue.
+ const register = ({
+ name,
+ pattern,
+ handler,
+ runHashTtlS,
+ maxAttempts = 3,
+ enabled = true
+ }: {
+ name: string;
+ pattern: string;
+ handler: Handler;
+ runHashTtlS: number;
+ maxAttempts?: number;
+ enabled?: boolean;
+ }) => {
+ if (!enabled) {
+ logger.info(`cron[${name}]: disabled`);
+ return;
+ }
+ if (entries.has(name)) throw new Error(`cron[${name}] already registered`);
+ CronExpressionParser.parse(pattern, { tz: "UTC" }); // validate at registration
+ entries.set(name, { name, pattern, maxAttempts, handler, runHashTtlS });
+ logger.info(`cron[${name}]: registered (pattern="${pattern}")`);
+ };
+
+ // ── slot election ───────────────────────────────────────────────────────────
+
+ // Caps the number of pods that participate in cron ticking. Each pod holds
+ // one of N slots via SET NX/XX with a short TTL: refreshes its own slot if
+ // it still owns one, otherwise tries to claim a free slot.
+ const claimOrRefreshSlot = async () => {
+ if (currentSlot !== null) {
+ const ok = await redis.set(SLOT_KEY(currentSlot), workerId, "PX", slotTtlMs, "XX");
+ if (ok) return;
+ logger.info(`cron: lost slot ${currentSlot} [worker=${workerId}]`);
+ currentSlot = null;
+ }
+ for (let i = 0; i < PARTICIPANT_SLOTS; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const got = await redis.set(SLOT_KEY(i), workerId, "PX", slotTtlMs, "NX");
+ if (got) {
+ currentSlot = i;
+ logger.info(`cron: claimed slot ${i} [worker=${workerId}]`);
+ return;
+ }
+ }
+ };
+
+ // ── enqueue ─────────────────────────────────────────────────────────────────
+
+ // For each registered entry, computes the most recent scheduled fire time
+ // and atomically inserts a run hash + pending-zset entry if not already
+ // present. The Lua script makes the existence check + write a single op so
+ // multiple pods racing to enqueue the same fire produce exactly one run.
+ const enqueueDueFires = async () => {
+ for (const entry of entries.values()) {
+ const scheduledAt = prevFireMs(entry.pattern);
+ // eslint-disable-next-line no-continue
+ if (lastEnqueuedAt.get(entry.name) === scheduledAt) continue;
+
+ const id = `${entry.name}:${scheduledAt}`;
+ // eslint-disable-next-line no-await-in-loop
+ const initialized = await redis.eval(
+ ENQUEUE_RUN_LUA,
+ 2,
+ RUN_KEY(id),
+ PENDING_ZSET,
+ entry.name,
+ String(scheduledAt),
+ String(entry.runHashTtlS),
+ id,
+ String(Date.now())
+ );
+ if (initialized)
+ logger.info(
+ `cron[${entry.name}]: enqueued run [id=${id}] [scheduled_at=${new Date(scheduledAt).toISOString()}]`
+ );
+ lastEnqueuedAt.set(entry.name, scheduledAt);
+ }
+ };
+
+ // Slow timer (~30s) that only creates run hashes for due fires. Split from
+ // processing so the pod that enqueues doesn't immediately consume everything
+ // it just created — leaves time for other slot-holders' process ticks to race.
+ const enqueueTick = async () => {
+ if (currentSlot === null) return;
+ await enqueueDueFires();
+ };
+
+ // ── process ─────────────────────────────────────────────────────────────────
+
+ // Executes one attempt of `entry` under an already-acquired redlock. Wires
+ // up the AbortController, writes the running state, races the handler
+ // against handlerTimeoutMs, and branches into success / retry / final
+ // failure on completion.
+ //
+ // Two-knob recovery model:
+ // leaseDurationMs → governs CRASH recovery. When the holder pod dies,
+ // its lease key TTLs out and other pods see the run as
+ // stalled via the isStalled path in processCandidate.
+ // handlerTimeoutMs → governs HANG recovery. When a handler wedges in a
+ // live pod, redlock would auto-extend the lease
+ // forever. The withTimeout race fires ac.abort() after
+ // handlerTimeoutMs and rejects, so the catch runs,
+ // status flips back to pending, and redlock.using
+ // releases the lease on return.
+ const executeUnderLease = async (entry: CronEntry, id: string, attempt: number, leaseSignal: AbortSignal) => {
+ const ac = new AbortController();
+ leaseSignal.addEventListener?.("abort", () => ac.abort());
+
+ await markRunning(id, attempt);
+ const startMs = Date.now();
+ logger.info(`cron[${entry.name}]: start (attempt ${attempt}/${entry.maxAttempts}) [id=${id}]`);
+
+ try {
+ await withTimeout((sig) => entry.handler(sig), ac, handlerTimeoutMs);
+ await markCompleted(id);
+ logger.info(`cron[${entry.name}]: complete [id=${id}] [duration_ms=${Date.now() - startMs}]`);
+ } catch (err) {
+ // Exponential backoff: 1×, 2×, 4× ... capped at retryBackoffMaxMs.
+ const backoffMs = Math.min(retryBackoffBaseMs * 2 ** (attempt - 1), retryBackoffMaxMs);
+ const nextAttemptAt = Date.now() + backoffMs;
+ // If the retry wouldn't fit before the next scheduled fire, treat this
+ // run as final — the upcoming fire (separate id) is the natural retry.
+ // Avoids overlapping attempts of the same cron and avoids squashing
+ // backoff to ~0 near the end of an interval.
+ 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);
+
+ logger.error(
+ { err },
+ `cron[${entry.name}]: attempt ${attempt} failed (${final ? "giving up" : "will retry"}) [id=${id}]`
+ );
+ }
+ };
+
+ // Inspects one pending zset id: validates the run hash, applies the
+ // min-age and max-attempts gates, and races for the lease. Anything that
+ // can be decided without taking a lock is decided here so we only ever
+ // hand a "ready, attempt-eligible" run to executeUnderLease.
+ const processCandidate = async (id: string) => {
+ const data = await redis.hgetall(RUN_KEY(id));
+ if (!data?.name) {
+ // Hash expired (TTL) but zset entry lingered; clean up.
+ await redis.zrem(PENDING_ZSET, id);
+ return;
+ }
+
+ const entry = entries.get(data.name);
+ if (!entry) return; // not handled on this pod
+
+ const isPending = data.status === RunStatus.Pending;
+ const isStalled = data.status === RunStatus.Running && (await redis.exists(LEASE_KEY(id))) === 0;
+ if (!isPending && !isStalled) return;
+
+ // Min-age delay on first pickup so the pod that enqueued doesn't
+ // immediately grab everything before other slot-holders' process ticks
+ // fire. Stalled runs bypass this — they're already past first pickup.
+ if (isPending) {
+ const enqueuedAtMs = Number(data[F.EnqueuedAtMs] ?? 0);
+ if (Date.now() - enqueuedAtMs < minProcessAgeMs) return;
+ }
+
+ const attempts = Number(data.attempts ?? 0);
+ if (attempts >= entry.maxAttempts) {
+ await markFailedFinal(id);
+ logger.error(`cron[${data.name}]: max attempts reached [id=${id}]`);
+ return;
+ }
+
+ if (isStalled) {
+ logger.info(`cron[${data.name}]: re-claiming stalled run [id=${id}] [previous_worker=${data.worker_id}]`);
+ }
+
+ try {
+ 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.
+ }
+ };
+
+ // Fast timer (~5s) that scans the pending zset and races for runs to
+ // execute. Ids are shuffled per tick so different slot-holders try
+ // different ids first, spreading lease contention and distributing handler
+ // load across pods.
+ const processTick = async () => {
+ if (currentSlot === null) return;
+
+ // Filter by zset score so backed-off retries (score = next_attempt_at)
+ // are skipped until their backoff window elapses.
+ const ids = await redis.zrangebyscore(PENDING_ZSET, "-inf", Date.now(), "LIMIT", 0, PROCESS_BATCH_SIZE);
+ shuffleInPlace(ids);
+
+ for (const id of ids) {
+ // eslint-disable-next-line no-await-in-loop
+ await processCandidate(id);
+ }
+ };
+
+ // ── lifecycle ───────────────────────────────────────────────────────────────
+
+ // 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();
+ };
+
+ // 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.
+ const stop = async () => {
+ if (slotTimer) clearInterval(slotTimer);
+ if (enqueueTimer) clearInterval(enqueueTimer);
+ if (processTimer) clearInterval(processTimer);
+ if (currentSlot !== null) {
+ await redis.eval(RELEASE_SLOT_IF_MINE_LUA, 1, SLOT_KEY(currentSlot), workerId);
+ logger.info(`cron: released slot ${currentSlot} [worker=${workerId}]`);
+ }
+ };
+
+ return { register, start, stop };
+};
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 784c41f5dc..8820d767d7 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -58,14 +58,8 @@ export enum QueueName {
AuditLog = "audit-log",
// TODO(akhilmhdh): This will get removed later. For now this is kept to stop the repeatable queue
AuditLogPrune = "audit-log-prune",
- DailyResourceCleanUp = "daily-resource-cleanup",
- FrequentResourceCleanUp = "frequent-resource-cleanup",
- DailyExpiringPkiItemAlert = "daily-expiring-pki-item-alert",
- DailyPkiAlertV2Processing = "daily-pki-alert-v2-processing",
PkiAlertV2Event = "pki-alert-v2-event",
- PkiSyncCleanup = "pki-sync-cleanup",
PkiSubscriber = "pki-subscriber",
- TelemetryInstanceStats = "telemtry-self-hosted-stats",
IntegrationSync = "sync-integrations",
SecretWebhook = "secret-webhook",
SecretFullRepoScan = "secret-full-repo-scan",
@@ -88,13 +82,7 @@ export enum QueueName {
FolderTreeCheckpoint = "folder-tree-checkpoint",
InvalidateCache = "invalidate-cache",
SecretScanningV2 = "secret-scanning-v2",
- TelemetryAggregatedEvents = "telemetry-aggregated-events",
- DailyReminders = "daily-reminders",
- SecretReminderMigration = "secret-reminder-migration",
UserNotification = "user-notification",
- HealthAlert = "health-alert",
- CertificateV3AutoRenewal = "certificate-v3-auto-renewal",
- PamAccountRotation = "pam-account-rotation",
PamSessionExpiration = "pam-session-expiration",
PamSessionAiSummary = "pam-session-ai-summary",
PkiAcmeChallengeValidation = "pki-acme-challenge-validation",
@@ -104,7 +92,6 @@ export enum QueueName {
AuditLogClickHouseBatch = "audit-log-clickhouse-batch",
PamDiscoveryScan = "pam-discovery-scan",
CaAutoRenewal = "ca-auto-renewal",
- CertificateCleanup = "certificate-cleanup",
DigiCertOrderPolling = "digicert-order-polling"
}
@@ -215,18 +202,6 @@ export type TQueueJobTypes = {
name: QueueJobs.AuditLog;
payload: TCreateAuditLogDTO;
};
- [QueueName.DailyResourceCleanUp]: {
- name: QueueJobs.DailyResourceCleanUp;
- payload: undefined;
- };
- [QueueName.DailyExpiringPkiItemAlert]: {
- name: QueueJobs.DailyExpiringPkiItemAlert;
- payload: undefined;
- };
- [QueueName.DailyPkiAlertV2Processing]: {
- name: QueueJobs.DailyPkiAlertV2Processing;
- payload: undefined;
- };
[QueueName.PkiAlertV2Event]: {
name: QueueJobs.PkiAlertV2ProcessEvent;
payload: {
@@ -235,10 +210,6 @@ export type TQueueJobTypes = {
eventType: PkiAlertEventType;
};
};
- [QueueName.PkiSyncCleanup]: {
- name: QueueJobs.PkiSyncCleanup;
- payload: undefined;
- };
[QueueName.AuditLogPrune]: {
name: QueueJobs.AuditLogPrune;
payload: undefined;
@@ -285,10 +256,6 @@ export type TQueueJobTypes = {
};
};
};
- [QueueName.TelemetryInstanceStats]: {
- name: QueueJobs.TelemetryInstanceStats;
- payload: undefined;
- };
[QueueName.DynamicSecretLeaseRevocationFailedEmail]: {
name: QueueJobs.DynamicSecretLeaseRevocationFailedEmail;
payload: {
@@ -447,38 +414,14 @@ export type TQueueJobTypes = {
locality?: string;
};
};
- [QueueName.DailyReminders]: {
- name: QueueJobs.DailyReminders;
- payload: undefined;
- };
- [QueueName.SecretReminderMigration]: {
- name: QueueJobs.SecretReminderMigration;
- payload: undefined;
- };
[QueueName.PkiSubscriber]: {
name: QueueJobs.PkiSubscriberDailyAutoRenewal;
payload: undefined;
};
- [QueueName.TelemetryAggregatedEvents]: {
- name: QueueJobs.TelemetryAggregatedEvents;
- payload: undefined;
- };
[QueueName.UserNotification]: {
name: QueueJobs.UserNotification;
payload: { notifications: TCreateUserNotificationDTO[] };
};
- [QueueName.HealthAlert]: {
- name: QueueJobs.HealthAlert;
- payload: undefined;
- };
- [QueueName.CertificateV3AutoRenewal]: {
- name: QueueJobs.CertificateV3DailyAutoRenewal;
- payload: undefined;
- };
- [QueueName.PamAccountRotation]: {
- name: QueueJobs.PamAccountRotation;
- payload: undefined;
- };
[QueueName.PamSessionExpiration]: {
name: QueueJobs.PamSessionExpiration;
payload: { sessionId: string };
@@ -491,10 +434,6 @@ export type TQueueJobTypes = {
name: QueueJobs.PkiAcmeChallengeValidation;
payload: { challengeId: string };
};
- [QueueName.FrequentResourceCleanUp]: {
- name: QueueJobs.FrequentResourceCleanUp;
- payload: undefined;
- };
[QueueName.PkiDiscoveryScan]:
| {
name: QueueJobs.PkiDiscoveryRunScan;
@@ -543,10 +482,6 @@ export type TQueueJobTypes = {
name: QueueJobs.CaAdcsInstall;
payload: { caId: string; maxPathLength?: number };
};
- [QueueName.CertificateCleanup]: {
- name: QueueJobs.CertificateCleanup;
- payload: undefined;
- };
[QueueName.DigiCertOrderPolling]: {
name: QueueJobs.DigiCertOrderPolling;
payload: undefined;
@@ -647,9 +582,29 @@ export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFa
Record<QueueName, Worker<TQueueJobTypes[QueueName]["payload"], void, TQueueJobTypes[QueueName]["name"]>>
> = {};
- // Remove orphaned job schedulers left in Redis by the QueueInternalRecovery/QueueInternalReconciliation deleted queues.
+ // Remove orphaned job schedulers left in Redis by deleted queues.
+ // Queues migrated to the cronJob system (cron-job.ts) are listed here so their
+ // BullMQ schedulers and pending jobs are cleaned up on first boot of the new image.
void (async () => {
- const staleQueueNames = ["queue-internal-recovery", "queue-internal-reconciliation", "secret-rotation"];
+ const staleQueueNames = [
+ "queue-internal-recovery",
+ "queue-internal-reconciliation",
+ "secret-rotation",
+ // Queues replaced by cronJobFactory (src/lib/cron/cron-job.ts)
+ "daily-resource-cleanup",
+ "frequent-resource-cleanup",
+ "daily-reminders",
+ "secret-reminder-migration",
+ "health-alert",
+ "certificate-cleanup",
+ "pki-sync-cleanup",
+ "pam-account-rotation",
+ "daily-pki-alert-v2-processing",
+ "daily-expiring-pki-item-alert",
+ "telemtry-self-hosted-stats", // note: typo from original enum value
+ "telemetry-aggregated-events",
+ "certificate-v3-auto-renewal"
+ ];
await Promise.allSettled(
staleQueueNames.map(async (name) => {
const staleQueue = new Queue(name, {
diff --git a/backend/src/server/app.ts b/backend/src/server/app.ts
index 6ff780af65..322744c907 100644
--- a/backend/src/server/app.ts
+++ b/backend/src/server/app.ts
@@ -183,6 +183,7 @@ export const main = async ({
db,
auditLogDb,
keyStore,
+ redis,
clickhouse,
hsmService,
envConfig,
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index a39b55c7a3..317fafeed3 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1,6 +1,7 @@
import { registerBddNockRouter } from "@bdd_routes/bdd-nock-router";
import type { ClickHouseClient } from "@clickhouse/client";
import { CronJob } from "cron";
+import { Cluster, Redis } from "ioredis";
import { Knex } from "knex";
import { monitorEventLoopDelay } from "perf_hooks";
import { z } from "zod";
@@ -217,9 +218,11 @@ import { trustedIpServiceFactory } from "@app/ee/services/trusted-ip/trusted-ip-
import { keyValueStoreDALFactory } from "@app/keystore/key-value-store-dal";
import { TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig, TEnvConfig } from "@app/lib/config/env";
+import { cronJobFactory } from "@app/lib/cron/cron-job";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
+import { Redlock } from "@app/lib/red-lock";
import { TQueueServiceFactory } from "@app/queue";
import { readLimit } from "@app/server/config/rateLimiter";
import { registerSecretScanningV2Webhooks } from "@app/server/plugins/secret-scanner-v2";
@@ -501,6 +504,7 @@ export const registerRoutes = async (
smtp: smtpService,
queue: queueService,
keyStore,
+ redis,
clickhouse,
envConfig,
hsmService,
@@ -512,6 +516,7 @@ export const registerRoutes = async (
smtp: TSmtpService;
queue: TQueueServiceFactory;
keyStore: TKeyStoreFactory;
+ redis: Redis | Cluster;
clickhouse: ClickHouseClient | null;
envConfig: TEnvConfig;
hsmService: THsmServiceFactory;
@@ -519,6 +524,11 @@ export const registerRoutes = async (
}
) => {
const appCfg = getConfig();
+
+ const redlock = new Redlock([redis as Redis], { retryCount: 0 });
+ const cronJob = cronJobFactory({ redis, redlock });
+ cronJob.start();
+
await server.register(registerSecretScanningV2Webhooks, {
prefix: "/secret-scanning/webhooks"
});
@@ -943,7 +953,7 @@ export const registerRoutes = async (
const telemetryQueue = telemetryQueueServiceFactory({
keyStore,
telemetryDAL,
- queueService,
+ cronJob,
telemetryService
});
@@ -1512,6 +1522,7 @@ export const registerRoutes = async (
const secretSyncQueue = secretSyncQueueFactory({
queueService,
+ cronJob,
secretSyncDAL,
folderDAL,
secretImportDAL,
@@ -2126,6 +2137,7 @@ export const registerRoutes = async (
const pkiAlertV2Queue = pkiAlertV2QueueServiceFactory({
queueService,
+ cronJob,
pkiAlertV2Service,
pkiAlertV2DAL,
pkiAlertHistoryDAL
@@ -2143,7 +2155,7 @@ export const registerRoutes = async (
const certificateCleanupQueue = certificateCleanupQueueFactory({
db,
- queueService,
+ cronJob,
certificateCleanupConfigDAL,
certificateDAL,
certificateRequestDAL,
@@ -2213,7 +2225,7 @@ export const registerRoutes = async (
scimService,
auditLogDAL,
auditLogService,
- queueService,
+ cronJob,
secretVersionDAL,
secretFolderVersionDAL: folderVersionDAL,
snapshotDAL,
@@ -2234,19 +2246,17 @@ export const registerRoutes = async (
const healthAlert = healthAlertServiceFactory({
gatewayV2Service,
- queueService,
+ cronJob,
relayService
});
const dailyReminderQueueService = dailyReminderQueueServiceFactory({
reminderService,
- queueService,
- secretDAL: secretV2BridgeDAL,
- secretReminderRecipientsDAL
+ cronJob
});
const dailyExpiringPkiItemAlert = dailyExpiringPkiItemAlertQueueServiceFactory({
- queueService,
+ cronJob,
pkiAlertService
});
@@ -2475,7 +2485,7 @@ export const registerRoutes = async (
});
const pkiSyncCleanup = pkiSyncCleanupQueueServiceFactory({
- queueService,
+ cronJob,
pkiSyncDAL,
pkiSyncQueue
});
@@ -2535,6 +2545,7 @@ export const registerRoutes = async (
const caAutoRenewalQueue = caAutoRenewalQueueFactory({
queueService,
+ cronJob,
internalCertificateAuthorityDAL,
caSigningConfigDAL,
internalCertificateAuthorityService,
@@ -2584,6 +2595,7 @@ export const registerRoutes = async (
const pkiSubscriberQueue = pkiSubscriberQueueServiceFactory({
queueService,
+ cronJob,
pkiSubscriberDAL,
certificateAuthorityDAL,
certificateAuthorityQueue,
@@ -2720,7 +2732,7 @@ export const registerRoutes = async (
});
const certificateV3Queue = certificateV3QueueServiceFactory({
- queueService,
+ cronJob,
certificateDAL,
certificateV3Service,
auditLogService
@@ -2847,6 +2859,7 @@ export const registerRoutes = async (
projectDAL,
kmsService,
queueService,
+ cronJob,
gatewayV2Service,
gatewayV2DAL
});
@@ -2895,6 +2908,7 @@ export const registerRoutes = async (
secretRotationV2Service,
secretRotationV2DAL,
queueService,
+ cronJob,
projectDAL,
projectMembershipDAL,
smtpService,
@@ -2903,6 +2917,7 @@ export const registerRoutes = async (
await appConnectionCredentialRotationQueueFactory({
queueService,
+ cronJob,
appConnectionCredentialRotationDAL,
appConnectionCredentialRotationService,
smtpService,
@@ -3063,7 +3078,7 @@ export const registerRoutes = async (
});
const pamAccountRotation = pamAccountRotationServiceFactory({
- queueService,
+ cronJob,
pamAccountService
});
@@ -3118,6 +3133,7 @@ export const registerRoutes = async (
pamAccountDAL,
kmsService,
queueService,
+ cronJob,
gatewayV2Service,
gatewayV2DAL
});
@@ -3217,27 +3233,27 @@ export const registerRoutes = async (
}
await kmsService.startService(hsmStatus);
- await telemetryQueue.startTelemetryCheck();
- await telemetryQueue.startAggregatedEventsJob();
- await dailyResourceCleanUp.init();
- await healthAlert.init();
- await pkiSyncCleanup.init();
+ // Register all cron jobs (synchronous registrations) before starting the scheduler
+ telemetryQueue.startTelemetryCheck();
+ telemetryQueue.startAggregatedEventsJob();
+ dailyResourceCleanUp.init();
+ healthAlert.init();
+ pkiSyncCleanup.init();
pkiDiscoveryQueue.startPkiDiscoveryScanQueue();
pamDiscoveryQueue.startPamDiscoveryQueue();
- await pamAccountRotation.init();
+ pamAccountRotation.init();
pamSessionExpirationService.init();
pamSessionAiSummaryService.init();
- await dailyReminderQueueService.startDailyRemindersJob();
- await secretSyncQueue.startDailySecretSyncRetryJob();
- await dailyReminderQueueService.startSecretReminderMigrationJob();
- await dailyExpiringPkiItemAlert.startSendingAlerts();
+ dailyReminderQueueService.startDailyRemindersJob();
+ secretSyncQueue.startDailySecretSyncRetryJob();
+ dailyExpiringPkiItemAlert.startSendingAlerts();
await certificateAuthorityQueue.startCaCrlRebuildJob();
- await pkiSubscriberQueue.startDailyAutoRenewalJob();
- await pkiAlertV2Queue.init();
- await certificateCleanupQueue.init();
- await certificateV3Queue.init();
+ pkiSubscriberQueue.startDailyAutoRenewalJob();
+ pkiAlertV2Queue.init();
+ certificateCleanupQueue.init();
+ certificateV3Queue.init();
await digicertCaQueue.init();
- await caAutoRenewalQueue.startDailyAutoRenewalJob();
+ caAutoRenewalQueue.startDailyAutoRenewalJob();
await microsoftTeamsService.start();
await eventBusService.init();
@@ -3551,6 +3567,7 @@ export const registerRoutes = async (
server.addHook("onClose", async () => {
cronJobs.forEach((job) => job.stop());
+ await cronJob.stop();
await telemetryService.flushAll();
await eventBusService.close();
await projectEventsSSEService.close();
diff --git a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-queue.ts b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-queue.ts
index eccd5510dd..f61868b7ab 100644
--- a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-queue.ts
+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-queue.ts
@@ -2,8 +2,9 @@ import { v4 as uuidv4 } from "uuid";
import { OrgMembershipRole, ProjectMembershipRole } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
import { NotificationType } from "@app/services/notification/notification-types";
import { TOrgDALFactory } from "@app/services/org/org-dal";
@@ -21,6 +22,7 @@ import {
type TAppConnectionCredentialRotationQueueFactoryDep = {
queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
appConnectionCredentialRotationDAL: Pick<
TAppConnectionCredentialRotationDALFactory,
"findRotationsDueForQueue" | "findByIdWithConnection"
@@ -35,6 +37,7 @@ type TAppConnectionCredentialRotationQueueFactoryDep = {
export const appConnectionCredentialRotationQueueFactory = async ({
queueService,
+ cronJob,
appConnectionCredentialRotationDAL,
appConnectionCredentialRotationService,
smtpService,
@@ -209,11 +212,17 @@ export const appConnectionCredentialRotationQueueFactory = async ({
}
});
- // Schedule the cron job
- await queueService.upsertJobScheduler(
- QueueName.AppConnectionCredentialRotation,
- `${JOB_SCHEDULER_PREFIX}:app-connection-credential-rotation-cron`,
- { pattern: appCfg.isRotationDevelopmentMode ? "* * * * *" : "0 0 * * *" },
- { name: QueueJobs.AppConnectionCredentialRotationQueueRotations }
- );
+ cronJob.register({
+ name: "app-connection-credential-rotation-queue-rotations",
+ pattern: appCfg.isRotationDevelopmentMode ? "* * * * *" : "0 0 * * *",
+ runHashTtlS: 3 * 24 * 60 * 60,
+ handler: async () => {
+ await queueService.queue(
+ QueueName.AppConnectionCredentialRotation,
+ QueueJobs.AppConnectionCredentialRotationQueueRotations,
+ undefined as never,
+ { jobId: "app-connection-credential-rotation-queue-rotations" }
+ );
+ }
+ });
};
diff --git a/backend/src/services/certificate-authority/ca-auto-renewal-queue.ts b/backend/src/services/certificate-authority/ca-auto-renewal-queue.ts
index b4c8e41708..994d9ce761 100644
--- a/backend/src/services/certificate-authority/ca-auto-renewal-queue.ts
+++ b/backend/src/services/certificate-authority/ca-auto-renewal-queue.ts
@@ -1,9 +1,10 @@
/* eslint-disable no-continue, no-await-in-loop */
import RE2 from "re2";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";
import { decryptAppConnectionCredentials } from "../app-connection/app-connection-fns";
@@ -29,6 +30,7 @@ import { TInternalCertificateAuthorityServiceFactory } from "./internal/internal
type TCaAutoRenewalQueueFactoryDep = {
queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
internalCertificateAuthorityDAL: Pick<TInternalCertificateAuthorityDALFactory, "find" | "findOne" | "updateById">;
caSigningConfigDAL: Pick<TCaSigningConfigDALFactory, "findByCaId" | "updateById">;
internalCertificateAuthorityService: Pick<
@@ -47,6 +49,7 @@ const PEM_CERT_REGEX = new RE2("-----BEGIN CERTIFICATE-----[\\s\\S]*?-----END CE
export const caAutoRenewalQueueFactory = ({
queueService,
+ cronJob,
internalCertificateAuthorityDAL,
caSigningConfigDAL,
internalCertificateAuthorityService,
@@ -432,13 +435,17 @@ export const caAutoRenewalQueueFactory = ({
);
});
- const startDailyAutoRenewalJob = async () => {
- await queueService.upsertJobScheduler(
- QueueName.CaAutoRenewal,
- `${JOB_SCHEDULER_PREFIX}:${QueueJobs.CaDailyAutoRenewal}`,
- { pattern: "0 0 * * *" },
- { name: QueueJobs.CaDailyAutoRenewal }
- );
+ const startDailyAutoRenewalJob = () => {
+ cronJob.register({
+ name: "ca-daily-auto-renewal",
+ pattern: "0 0 * * *",
+ runHashTtlS: 3 * 24 * 60 * 60,
+ handler: async () => {
+ await queueService.queue(QueueName.CaAutoRenewal, QueueJobs.CaDailyAutoRenewal, undefined as never, {
+ jobId: "ca-daily-auto-renewal"
+ });
+ }
+ });
};
const queueVenafiInstall = async (caId: string, maxPathLength?: number) => {
diff --git a/backend/src/services/certificate-cleanup/certificate-cleanup-queue.ts b/backend/src/services/certificate-cleanup/certificate-cleanup-queue.ts
index 28f782895c..99bc7c4ad3 100644
--- a/backend/src/services/certificate-cleanup/certificate-cleanup-queue.ts
+++ b/backend/src/services/certificate-cleanup/certificate-cleanup-queue.ts
@@ -4,8 +4,9 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { getConfig } from "@app/lib/config/env";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { QueueJobs } from "@app/queue";
import { ActorType } from "@app/services/auth/auth-type";
import { TCertificateDALFactory } from "../certificate/certificate-dal";
@@ -15,7 +16,7 @@ import { CLEANUP_BATCH_SIZE, CleanupRunStatus } from "./certificate-cleanup-type
type TCertificateCleanupQueueFactoryDep = {
db: TDbClient;
- queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
certificateCleanupConfigDAL: TCertificateCleanupConfigDALFactory;
certificateDAL: Pick<TCertificateDALFactory, "delete">;
certificateRequestDAL: Pick<TCertificateRequestDALFactory, "delete">;
@@ -26,7 +27,7 @@ export type TCertificateCleanupQueueFactory = ReturnType<typeof certificateClean
export const certificateCleanupQueueFactory = ({
db,
- queueService,
+ cronJob,
certificateCleanupConfigDAL,
certificateDAL,
certificateRequestDAL,
@@ -150,56 +151,50 @@ export const certificateCleanupQueueFactory = ({
return { deletedCount, errors: errorMessages.length };
};
- const init = async () => {
- if (appCfg.isSecondaryInstance) {
- return;
- }
-
- queueService.start(QueueName.CertificateCleanup, async () => {
- logger.info(`${QueueJobs.CertificateCleanup}: started`);
-
- const configs = await certificateCleanupConfigDAL.find({ isEnabled: true });
-
- logger.info(`${QueueJobs.CertificateCleanup}: found ${configs.length} projects with cleanup enabled`);
-
- let totalDeleted = 0;
- let totalErrors = 0;
-
- for (const config of configs) {
- try {
- const result = await processProjectCleanup(config);
- totalDeleted += result.deletedCount;
- totalErrors += result.errors;
-
- if (result.deletedCount > 0) {
- logger.info(
- `${QueueJobs.CertificateCleanup}: project ${config.projectId} — deleted ${result.deletedCount} certificates`
- );
+ const init = () => {
+ cronJob.register({
+ name: "certificate-cleanup",
+ pattern: "0 2 * * *",
+ runHashTtlS: 3 * 24 * 60 * 60,
+ enabled: !appCfg.isSecondaryInstance,
+ handler: async () => {
+ logger.info(`${QueueJobs.CertificateCleanup}: started`);
+
+ const configs = await certificateCleanupConfigDAL.find({ isEnabled: true });
+
+ logger.info(`${QueueJobs.CertificateCleanup}: found ${configs.length} projects with cleanup enabled`);
+
+ let totalDeleted = 0;
+ let totalErrors = 0;
+
+ for (const config of configs) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ const result = await processProjectCleanup(config);
+ totalDeleted += result.deletedCount;
+ totalErrors += result.errors;
+
+ if (result.deletedCount > 0) {
+ logger.info(
+ `${QueueJobs.CertificateCleanup}: project ${config.projectId} — deleted ${result.deletedCount} certificates`
+ );
+ }
+ } catch (err) {
+ totalErrors += 1;
+ logger.error(err, `${QueueJobs.CertificateCleanup}: failed for project ${config.projectId}`);
+ // eslint-disable-next-line no-await-in-loop
+ await certificateCleanupConfigDAL.updateById(config.id, {
+ lastRunStatus: CleanupRunStatus.Error,
+ lastRunAt: new Date(),
+ lastRunMessage: String((err as Error).message || "Unknown error").slice(0, 500)
+ });
}
- } catch (err) {
- totalErrors += 1;
- logger.error(err, `${QueueJobs.CertificateCleanup}: failed for project ${config.projectId}`);
-
- await certificateCleanupConfigDAL.updateById(config.id, {
- lastRunStatus: CleanupRunStatus.Error,
- lastRunAt: new Date(),
- lastRunMessage: String((err as Error).message || "Unknown error").slice(0, 500)
- });
}
- }
- logger.info(`${QueueJobs.CertificateCleanup}: completed — deleted ${totalDeleted} total, ${totalErrors} errors`);
- });
-
- await queueService.upsertJobScheduler(
- QueueName.CertificateCleanup,
- `${JOB_SCHEDULER_PREFIX}:${QueueJobs.CertificateCleanup}`,
- { pattern: "0 2 * * *" },
- { name: QueueJobs.CertificateCleanup }
- );
-
- queueService.listen(QueueName.CertificateCleanup, "failed", (_, err) => {
- logger.error(err, `${QueueName.CertificateCleanup}: job failed`);
+ logger.info(
+ `${QueueJobs.CertificateCleanup}: completed — deleted ${totalDeleted} total, ${totalErrors} errors`
+ );
+ }
});
};
diff --git a/backend/src/services/certificate-v3/certificate-v3-queue.ts b/backend/src/services/certificate-v3/certificate-v3-queue.ts
index 913f2d0b2a..50f3803819 100644
--- a/backend/src/services/certificate-v3/certificate-v3-queue.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-queue.ts
@@ -1,8 +1,9 @@
/* eslint-disable no-await-in-loop */
import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { getConfig } from "@app/lib/config/env";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { QueueJobs } from "@app/queue";
import { ActorType } from "../auth/auth-type";
import { TCertificateDALFactory } from "../certificate/certificate-dal";
@@ -10,134 +11,129 @@ import { CERTIFICATE_RENEWAL_CONFIG } from "../certificate-common/certificate-co
import { TCertificateV3ServiceFactory } from "./certificate-v3-service";
type TCertificateV3QueueServiceFactoryDep = {
- queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
certificateDAL: Pick<TCertificateDALFactory, "findCertificatesEligibleForRenewal" | "updateById">;
certificateV3Service: TCertificateV3ServiceFactory;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
};
export const certificateV3QueueServiceFactory = ({
- queueService,
+ cronJob,
certificateDAL,
certificateV3Service,
auditLogService
}: TCertificateV3QueueServiceFactoryDep) => {
const appCfg = getConfig();
- const init = async () => {
- if (appCfg.isSecondaryInstance) {
- return;
- }
-
- queueService.start(QueueName.CertificateV3AutoRenewal, async () => {
- try {
- logger.info(`${QueueJobs.CertificateV3DailyAutoRenewal}: queue task started`);
-
- const { QUEUE_BATCH_SIZE } = CERTIFICATE_RENEWAL_CONFIG;
- let offset = 0;
- let hasMore = true;
- let totalCertificatesFound = 0;
- let totalCertificatesRenewed = 0;
-
- while (hasMore) {
- const certificates = await certificateDAL.findCertificatesEligibleForRenewal({
- limit: QUEUE_BATCH_SIZE,
- offset
- });
-
- if (certificates.length === 0) {
- hasMore = false;
- break;
- }
-
- totalCertificatesFound += certificates.length;
- logger.info(
- `${QueueJobs.CertificateV3DailyAutoRenewal}: found ${certificates.length} certificates eligible for renewal (batch ${Math.floor(offset / QUEUE_BATCH_SIZE) + 1}, total found so far: ${totalCertificatesFound})`
- );
+ const init = () => {
+ cronJob.register({
+ name: "certificate-v3-auto-renewal",
+ pattern: CERTIFICATE_RENEWAL_CONFIG.DAILY_CRON_SCHEDULE,
+ runHashTtlS: 3 * 24 * 60 * 60,
+ enabled: !appCfg.isSecondaryInstance,
+ handler: async () => {
+ try {
+ logger.info(`${QueueJobs.CertificateV3DailyAutoRenewal}: queue task started`);
+
+ const { QUEUE_BATCH_SIZE } = CERTIFICATE_RENEWAL_CONFIG;
+ let offset = 0;
+ let hasMore = true;
+ let totalCertificatesFound = 0;
+ let totalCertificatesRenewed = 0;
+
+ while (hasMore) {
+ const certificates = await certificateDAL.findCertificatesEligibleForRenewal({
+ limit: QUEUE_BATCH_SIZE,
+ offset
+ });
+
+ if (certificates.length === 0) {
+ hasMore = false;
+ break;
+ }
- for (const certificate of certificates) {
- try {
- if (certificate.renewBeforeDays) {
- const { MIN_RENEW_BEFORE_DAYS, MAX_RENEW_BEFORE_DAYS } = CERTIFICATE_RENEWAL_CONFIG;
- if (
- certificate.renewBeforeDays < MIN_RENEW_BEFORE_DAYS ||
- certificate.renewBeforeDays > MAX_RENEW_BEFORE_DAYS
- ) {
- // eslint-disable-next-line no-continue
- continue;
+ totalCertificatesFound += certificates.length;
+ logger.info(
+ `${QueueJobs.CertificateV3DailyAutoRenewal}: found ${certificates.length} certificates eligible for renewal (batch ${Math.floor(offset / QUEUE_BATCH_SIZE) + 1}, total found so far: ${totalCertificatesFound})`
+ );
+
+ for (const certificate of certificates) {
+ try {
+ if (certificate.renewBeforeDays) {
+ const { MIN_RENEW_BEFORE_DAYS, MAX_RENEW_BEFORE_DAYS } = CERTIFICATE_RENEWAL_CONFIG;
+ if (
+ certificate.renewBeforeDays < MIN_RENEW_BEFORE_DAYS ||
+ certificate.renewBeforeDays > MAX_RENEW_BEFORE_DAYS
+ ) {
+ // eslint-disable-next-line no-continue
+ continue;
+ }
}
- }
- await certificateV3Service.renewCertificate({
- actor: ActorType.PLATFORM,
- actorId: "",
- actorAuthMethod: null,
- actorOrgId: "",
- certificateId: certificate.id,
- internal: true
- });
-
- totalCertificatesRenewed += 1;
-
- await auditLogService.createAuditLog({
- projectId: certificate.projectId,
- actor: {
- type: ActorType.PLATFORM,
- metadata: {}
- },
- event: {
- type: EventType.AUTOMATED_RENEW_CERTIFICATE,
- metadata: {
- certificateId: certificate.id,
- commonName: certificate.commonName || "",
- profileId: certificate.profileId!,
- renewBeforeDays: certificate.renewBeforeDays?.toString() || "",
- profileName: certificate.profileName || ""
+ await certificateV3Service.renewCertificate({
+ actor: ActorType.PLATFORM,
+ actorId: "",
+ actorAuthMethod: null,
+ actorOrgId: "",
+ certificateId: certificate.id,
+ internal: true
+ });
+
+ totalCertificatesRenewed += 1;
+
+ await auditLogService.createAuditLog({
+ projectId: certificate.projectId,
+ actor: {
+ type: ActorType.PLATFORM,
+ metadata: {}
+ },
+ event: {
+ type: EventType.AUTOMATED_RENEW_CERTIFICATE,
+ metadata: {
+ certificateId: certificate.id,
+ commonName: certificate.commonName || "",
+ profileId: certificate.profileId!,
+ renewBeforeDays: certificate.renewBeforeDays?.toString() || "",
+ profileName: certificate.profileName || ""
+ }
}
- }
- });
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error);
- logger.error(error, `Failed to renew certificate ${certificate.id}: ${errorMessage}`);
- await auditLogService.createAuditLog({
- projectId: certificate.projectId,
- actor: {
- type: ActorType.PLATFORM,
- metadata: {}
- },
- event: {
- type: EventType.AUTOMATED_RENEW_CERTIFICATE_FAILED,
- metadata: {
- certificateId: certificate.id,
- commonName: certificate.commonName || "",
- profileId: certificate.profileId || "",
- renewBeforeDays: certificate.renewBeforeDays?.toString() || "",
- profileName: certificate.profileName || "",
- error: errorMessage
+ });
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ logger.error(error, `Failed to renew certificate ${certificate.id}: ${errorMessage}`);
+ await auditLogService.createAuditLog({
+ projectId: certificate.projectId,
+ actor: {
+ type: ActorType.PLATFORM,
+ metadata: {}
+ },
+ event: {
+ type: EventType.AUTOMATED_RENEW_CERTIFICATE_FAILED,
+ metadata: {
+ certificateId: certificate.id,
+ commonName: certificate.commonName || "",
+ profileId: certificate.profileId || "",
+ renewBeforeDays: certificate.renewBeforeDays?.toString() || "",
+ profileName: certificate.profileName || "",
+ error: errorMessage
+ }
}
- }
- });
+ });
+ }
}
+
+ offset += QUEUE_BATCH_SIZE;
}
- offset += QUEUE_BATCH_SIZE;
+ logger.info(
+ `${QueueJobs.CertificateV3DailyAutoRenewal}: queue task completed. Renewed ${totalCertificatesRenewed} certificates out of ${totalCertificatesFound}`
+ );
+ } catch (error) {
+ logger.error(error, `${QueueJobs.CertificateV3DailyAutoRenewal}: certificate renewal failed`);
+ throw error;
}
-
- logger.info(
- `${QueueJobs.CertificateV3DailyAutoRenewal}: queue task completed. Renewed ${totalCertificatesRenewed} certificates out of ${totalCertificatesFound}`
- );
- } catch (error) {
- logger.error(error, `${QueueJobs.CertificateV3DailyAutoRenewal}: certificate renewal failed`);
- throw error;
}
});
-
- await queueService.upsertJobScheduler(
- QueueName.CertificateV3AutoRenewal,
- `${JOB_SCHEDULER_PREFIX}:${QueueJobs.CertificateV3DailyAutoRenewal}`,
- { pattern: CERTIFICATE_RENEWAL_CONFIG.DAILY_CRON_SCHEDULE },
- { name: QueueJobs.CertificateV3DailyAutoRenewal }
- );
};
return {
diff --git a/backend/src/services/health-alert/health-alert-queue.ts b/backend/src/services/health-alert/health-alert-queue.ts
index e02d57e006..1b0c350924 100644
--- a/backend/src/services/health-alert/health-alert-queue.ts
+++ b/backend/src/services/health-alert/health-alert-queue.ts
@@ -1,11 +1,11 @@
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TRelayServiceFactory } from "@app/ee/services/relay/relay-service";
import { getConfig } from "@app/lib/config/env";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
type THealthAlertServiceFactoryDep = {
- queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "healthcheckNotify">;
relayService: Pick<TRelayServiceFactory, "healthcheckNotify">;
};
@@ -13,35 +13,24 @@ type THealthAlertServiceFactoryDep = {
export type THealthAlertServiceFactory = ReturnType<typeof healthAlertServiceFactory>;
export const healthAlertServiceFactory = ({
- queueService,
+ cronJob,
gatewayV2Service,
relayService
}: THealthAlertServiceFactoryDep) => {
const appCfg = getConfig();
- const init = async () => {
- if (appCfg.isSecondaryInstance) {
- return;
- }
-
- queueService.start(QueueName.HealthAlert, async () => {
- try {
- logger.info(`${QueueName.HealthAlert}: health check alert task started`);
+ const init = () => {
+ cronJob.register({
+ name: "health-alert",
+ pattern: "*/5 * * * *",
+ runHashTtlS: 60 * 60,
+ enabled: !appCfg.isSecondaryInstance,
+ handler: async () => {
+ logger.info("cron[health-alert]: health check task started");
await gatewayV2Service.healthcheckNotify();
await relayService.healthcheckNotify();
- logger.info(`${QueueName.HealthAlert}: health check alert task completed`);
- } catch (error) {
- logger.error(error, `${QueueName.HealthAlert}: health check alert failed`);
- throw error;
}
});
-
- await queueService.upsertJobScheduler(
- QueueName.HealthAlert,
- `${JOB_SCHEDULER_PREFIX}:${QueueJobs.HealthAlert}`,
- { pattern: "*/5 * * * *" },
- { name: QueueJobs.HealthAlert }
- );
};
return {
diff --git a/backend/src/services/identity-access-token/identity-access-token-dal.ts b/backend/src/services/identity-access-token/identity-access-token-dal.ts
index 40a35f60e5..8e9d5b322e 100644
--- a/backend/src/services/identity-access-token/identity-access-token-dal.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-dal.ts
@@ -5,7 +5,6 @@ import { TableName, TIdentityAccessTokens } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex";
import { logger } from "@app/lib/logger";
-import { QueueName } from "@app/queue";
export type TIdentityAccessTokenDALFactory = ReturnType<typeof identityAccessTokenDALFactory>;
@@ -30,7 +29,7 @@ export const identityAccessTokenDALFactory = (db: TDbClient) => {
};
const removeExpiredTokens = async (tx?: Knex) => {
- logger.info(`${QueueName.FrequentResourceCleanUp}: remove expired access token started`);
+ logger.info(`frequent-resource-cleanup: remove expired access token started`);
const BATCH_SIZE = 5000;
const MAX_RETRY_ON_FAILURE = 3;
@@ -138,7 +137,7 @@ export const identityAccessTokenDALFactory = (db: TDbClient) => {
}
logger.info(
- `${QueueName.FrequentResourceCleanUp}: remove expired access token completed. Deleted ${totalDeletedCount} tokens.`
+ `frequent-resource-cleanup: remove expired access token completed. Deleted ${totalDeletedCount} tokens.`
);
};
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 b9a4c678a1..dd025857fa 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
@@ -5,7 +5,6 @@ import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex";
import { logger } from "@app/lib/logger";
-import { QueueName } from "@app/queue";
export type TIdentityUaClientSecretDALFactory = ReturnType<typeof identityUaClientSecretDALFactory>;
@@ -34,7 +33,7 @@ export const identityUaClientSecretDALFactory = (db: TDbClient) => {
let numberOfRetryOnFailure = 0;
let isRetrying = false;
- logger.info(`${QueueName.DailyResourceCleanUp}: remove expired univesal auth client secret started`);
+ logger.info(`daily-resource-cleanup: remove expired univesal auth client secret started`);
do {
try {
const findExpiredClientSecretQuery = (tx || db)(TableName.IdentityUaClientSecret)
@@ -78,7 +77,7 @@ export const identityUaClientSecretDALFactory = (db: TDbClient) => {
}
isRetrying = numberOfRetryOnFailure > 0;
} while (deletedClientSecret.length > 0 || (isRetrying && numberOfRetryOnFailure < MAX_RETRY_ON_FAILURE));
- logger.info(`${QueueName.DailyResourceCleanUp}: remove expired univesal auth client secret completed`);
+ logger.info(`daily-resource-cleanup: remove expired univesal auth client secret completed`);
};
return { ...uaClientSecretOrm, incrementUsage, removeExpiredClientSecrets };
diff --git a/backend/src/services/notification/user-notification-dal.ts b/backend/src/services/notification/user-notification-dal.ts
index 6dcb2e3d06..4a5b2f2419 100644
--- a/backend/src/services/notification/user-notification-dal.ts
+++ b/backend/src/services/notification/user-notification-dal.ts
@@ -5,7 +5,6 @@ import { TableName } from "@app/db/schemas";
import { DatabaseError, GatewayTimeoutError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex";
import { logger } from "@app/lib/logger";
-import { QueueName } from "@app/queue";
export type TUserNotificationDALFactory = ReturnType<typeof userNotificationDALFactory>;
@@ -70,7 +69,7 @@ export const userNotificationDALFactory = (db: TDbClient) => {
let deletedNotificationIds: { id: string }[] = [];
let numberOfRetryOnFailure = 0;
- logger.info(`${QueueName.DailyResourceCleanUp}: prune notifications started`);
+ logger.info(`daily-resource-cleanup: prune notifications started`);
do {
try {
// eslint-disable-next-line no-await-in-loop
@@ -110,10 +109,10 @@ export const userNotificationDALFactory = (db: TDbClient) => {
if (numberOfRetryOnFailure >= MAX_RETRY_ON_FAILURE) {
logger.error(
- `${QueueName.DailyResourceCleanUp}: prune notifications completed with persistent errors after ${MAX_RETRY_ON_FAILURE} retries. Some notifications might not have been pruned.`
+ `daily-resource-cleanup: prune notifications completed with persistent errors after ${MAX_RETRY_ON_FAILURE} retries. Some notifications might not have been pruned.`
);
} else {
- logger.info(`${QueueName.DailyResourceCleanUp}: prune notifications completed`);
+ logger.info(`daily-resource-cleanup: prune notifications completed`);
}
};
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index 77bccafc0c..122ca489b2 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -35,7 +35,6 @@ import { logger } from "@app/lib/logger";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { QueueName } from "@app/queue";
import { getDefaultOrgMembershipRoleForUpdateOrg } from "@app/services/org/org-role-fns";
import { TOrgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";
import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";
@@ -1228,7 +1227,7 @@ export const orgServiceFactory = ({
* Re-send emails to users who haven't accepted an invite yet
*/
const notifyInvitedUsers = async () => {
- logger.info(`${QueueName.DailyResourceCleanUp}: notify invited users started`);
+ logger.info(`daily-resource-cleanup: notify invited users started`);
const invitedUsers = await orgMembershipDAL.findRecentInvitedMemberships();
const appCfg = getConfig();
@@ -1272,7 +1271,7 @@ export const orgServiceFactory = ({
});
notifiedUsers.push(invitedUser.id);
} catch (err) {
- logger.error(err, `${QueueName.DailyResourceCleanUp}: notify invited users failed to send email`);
+ logger.error(err, `daily-resource-cleanup: notify invited users failed to send email`);
}
}
})
@@ -1280,7 +1279,7 @@ export const orgServiceFactory = ({
await orgMembershipDAL.updateLastInvitedAtByIds(notifiedUsers);
- logger.info(`${QueueName.DailyResourceCleanUp}: notify invited users completed`);
+ logger.info(`daily-resource-cleanup: notify invited users completed`);
};
return {
diff --git a/backend/src/services/pam-account-rotation/pam-account-rotation-queue.ts b/backend/src/services/pam-account-rotation/pam-account-rotation-queue.ts
index 9ae28f95af..8263c7f99f 100644
--- a/backend/src/services/pam-account-rotation/pam-account-rotation-queue.ts
+++ b/backend/src/services/pam-account-rotation/pam-account-rotation-queue.ts
@@ -1,43 +1,32 @@
import { TPamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";
import { getConfig } from "@app/lib/config/env";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
type TPamAccountRotationServiceFactoryDep = {
- queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
pamAccountService: Pick<TPamAccountServiceFactory, "rotateAllDueAccounts">;
};
export type TPamAccountRotationServiceFactory = ReturnType<typeof pamAccountRotationServiceFactory>;
export const pamAccountRotationServiceFactory = ({
- queueService,
+ cronJob,
pamAccountService
}: TPamAccountRotationServiceFactoryDep) => {
const appCfg = getConfig();
- const init = async () => {
- if (appCfg.isSecondaryInstance) {
- return;
- }
-
- queueService.start(QueueName.PamAccountRotation, async () => {
- try {
- logger.info(`${QueueName.PamAccountRotation}: pam account rotation task started`);
+ const init = () => {
+ cronJob.register({
+ name: "pam-account-rotation",
+ pattern: "0 * * * *",
+ runHashTtlS: 1 * 24 * 60 * 60,
+ enabled: !appCfg.isSecondaryInstance,
+ handler: async () => {
+ logger.info("cron[pam-account-rotation]: task started");
await pamAccountService.rotateAllDueAccounts();
- logger.info(`${QueueName.PamAccountRotation}: pam account rotation task completed`);
- } catch (error) {
- logger.error(error, `${QueueName.PamAccountRotation}: pam account rotation failed`);
- throw error;
}
});
-
- await queueService.upsertJobScheduler(
- QueueName.PamAccountRotation,
- `${JOB_SCHEDULER_PREFIX}:${QueueJobs.PamAccountRotation}`,
- { pattern: "0 * * * *" },
- { name: QueueJobs.PamAccountRotation }
- );
};
return {
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-queue.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-queue.ts
index 860fb0428c..31d271c03f 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-queue.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-queue.ts
@@ -1,8 +1,9 @@
/* eslint-disable no-await-in-loop */
import { getConfig } from "@app/lib/config/env";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TPkiAlertHistoryDALFactory } from "./pki-alert-history-dal";
import { TPkiAlertV2DALFactory } from "./pki-alert-v2-dal";
@@ -12,6 +13,7 @@ import { CertificateOrigin, PkiAlertEventType, TNotificationConfig, TPkiFilterRu
type TPkiAlertV2QueueServiceFactoryDep = {
queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
pkiAlertV2Service: Pick<TPkiAlertV2ServiceFactory, "sendAlertNotifications" | "sendEventNotifications">;
pkiAlertV2DAL: Pick<TPkiAlertV2DALFactory, "findByProjectId" | "findMatchingCertificates" | "getDistinctProjectIds">;
pkiAlertHistoryDAL: Pick<TPkiAlertHistoryDALFactory, "findRecentlyAlertedCertificates">;
@@ -21,6 +23,7 @@ export type TPkiAlertV2QueueServiceFactory = ReturnType<typeof pkiAlertV2QueueSe
export const pkiAlertV2QueueServiceFactory = ({
queueService,
+ cronJob,
pkiAlertV2Service,
pkiAlertV2DAL,
pkiAlertHistoryDAL
@@ -235,22 +238,8 @@ export const pkiAlertV2QueueServiceFactory = ({
});
};
- const init = async () => {
- if (appCfg.isSecondaryInstance) {
- return;
- }
-
- queueService.start(QueueName.DailyPkiAlertV2Processing, async () => {
- try {
- logger.info(`${QueueJobs.DailyPkiAlertV2Processing}: queue task started`);
- await processDailyAlerts();
- logger.info(`${QueueJobs.DailyPkiAlertV2Processing}: queue task completed successfully`);
- } catch (error) {
- logger.error(error, `${QueueJobs.DailyPkiAlertV2Processing}: queue task failed`);
- throw error;
- }
- });
-
+ const init = () => {
+ // PkiAlertV2Event is event-driven (ad-hoc per certificate event) — stays on BullMQ
queueService.start(QueueName.PkiAlertV2Event, async (job) => {
try {
logger.info(`${QueueJobs.PkiAlertV2ProcessEvent}: processing ${job.data.eventType} event`);
@@ -262,12 +251,16 @@ export const pkiAlertV2QueueServiceFactory = ({
}
});
- await queueService.upsertJobScheduler(
- QueueName.DailyPkiAlertV2Processing,
- `${JOB_SCHEDULER_PREFIX}:${QueueJobs.DailyPkiAlertV2Processing}`,
- { pattern: "0 0 * * *" },
- { name: QueueJobs.DailyPkiAlertV2Processing }
- );
+ cronJob.register({
+ name: "daily-pki-alert-v2-processing",
+ pattern: "0 0 * * *",
+ runHashTtlS: 3 * 24 * 60 * 60,
+ enabled: !appCfg.isSecondaryInstance,
+ handler: async () => {
+ logger.info("cron[daily-pki-alert-v2-processing]: task started");
+ await processDailyAlerts();
+ }
+ });
};
return {
diff --git a/backend/src/services/pki-alert/expiring-pki-item-alert-queue.ts b/backend/src/services/pki-alert/expiring-pki-item-alert-queue.ts
index 524685cc5a..e7c3f105a5 100644
--- a/backend/src/services/pki-alert/expiring-pki-item-alert-queue.ts
+++ b/backend/src/services/pki-alert/expiring-pki-item-alert-queue.ts
@@ -1,9 +1,9 @@
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TPkiAlertServiceFactory } from "@app/services/pki-alert/pki-alert-service";
type TDailyExpiringPkiItemAlertQueueServiceFactoryDep = {
- queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
pkiAlertService: Pick<TPkiAlertServiceFactory, "sendPkiItemExpiryNotices">;
};
@@ -12,29 +12,21 @@ export type TDailyExpiringPkiItemAlertQueueServiceFactory = ReturnType<
>;
export const dailyExpiringPkiItemAlertQueueServiceFactory = ({
- queueService,
+ cronJob,
pkiAlertService
}: TDailyExpiringPkiItemAlertQueueServiceFactoryDep) => {
- queueService.start(QueueName.DailyExpiringPkiItemAlert, async () => {
- logger.info(`${QueueName.DailyExpiringPkiItemAlert}: queue task started`);
- await pkiAlertService.sendPkiItemExpiryNotices();
- logger.info(`${QueueName.DailyExpiringPkiItemAlert}: queue task completed`);
- });
-
- // we do a repeat cron job in utc timezone at 12 Midnight each day
- const startSendingAlerts = async () => {
- await queueService.upsertJobScheduler(
- QueueName.DailyExpiringPkiItemAlert,
- `${JOB_SCHEDULER_PREFIX}:${QueueName.DailyExpiringPkiItemAlert}`,
- { pattern: "0 0 * * *" },
- { name: QueueJobs.DailyExpiringPkiItemAlert, opts: { delay: 5000 } }
- );
+ const startSendingAlerts = () => {
+ cronJob.register({
+ name: "daily-expiring-pki-item-alert",
+ pattern: "0 0 * * *",
+ runHashTtlS: 3 * 24 * 60 * 60,
+ handler: async () => {
+ logger.info("cron[daily-expiring-pki-item-alert]: task started");
+ await pkiAlertService.sendPkiItemExpiryNotices();
+ }
+ });
};
- queueService.listen(QueueName.DailyExpiringPkiItemAlert, "failed", (_, err) => {
- logger.error(err, `${QueueName.DailyExpiringPkiItemAlert}: Expiring PKI item alert failed`);
- });
-
return {
startSendingAlerts
};
diff --git a/backend/src/services/pki-subscriber/pki-subscriber-queue.ts b/backend/src/services/pki-subscriber/pki-subscriber-queue.ts
index 0707b0213e..b3122813a9 100644
--- a/backend/src/services/pki-subscriber/pki-subscriber-queue.ts
+++ b/backend/src/services/pki-subscriber/pki-subscriber-queue.ts
@@ -1,6 +1,7 @@
import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { ActorType } from "../auth/auth-type";
import { TCertificateDALFactory } from "../certificate/certificate-dal";
@@ -13,6 +14,7 @@ import { PkiSubscriberStatus, SubscriberOperationStatus } from "./pki-subscriber
type TPkiSubscriberQueueServiceFactoryDep = {
queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
pkiSubscriberDAL: TPkiSubscriberDALFactory;
certificateAuthorityDAL: TCertificateAuthorityDALFactory;
certificateAuthorityQueue: TCertificateAuthorityQueueFactory;
@@ -23,6 +25,7 @@ type TPkiSubscriberQueueServiceFactoryDep = {
export const pkiSubscriberQueueServiceFactory = ({
queueService,
+ cronJob,
pkiSubscriberDAL,
certificateAuthorityDAL,
certificateAuthorityQueue,
@@ -157,14 +160,17 @@ export const pkiSubscriberQueueServiceFactory = ({
}
});
- // we do a repeat cron job in utc timezone at 12 Midnight each day
- const startDailyAutoRenewalJob = async () => {
- await queueService.upsertJobScheduler(
- QueueName.PkiSubscriber,
- `${JOB_SCHEDULER_PREFIX}:${QueueName.PkiSubscriber}`,
- { pattern: "0 0 * * *" },
- { name: QueueJobs.PkiSubscriberDailyAutoRenewal, opts: { delay: 5000 } }
- );
+ const startDailyAutoRenewalJob = () => {
+ cronJob.register({
+ name: "pki-subscriber-daily-auto-renewal",
+ pattern: "0 0 * * *",
+ runHashTtlS: 3 * 24 * 60 * 60,
+ handler: async () => {
+ await queueService.queue(QueueName.PkiSubscriber, QueueJobs.PkiSubscriberDailyAutoRenewal, undefined as never, {
+ jobId: "pki-subscriber-daily-auto-renewal"
+ });
+ }
+ });
};
queueService.listen(QueueName.PkiSubscriber, "failed", (_, err) => {
diff --git a/backend/src/services/pki-sync/pki-sync-cleanup-queue.ts b/backend/src/services/pki-sync/pki-sync-cleanup-queue.ts
index f00834364e..61f0e8700d 100644
--- a/backend/src/services/pki-sync/pki-sync-cleanup-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-cleanup-queue.ts
@@ -1,12 +1,12 @@
import { getConfig } from "@app/lib/config/env";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TPkiSyncDALFactory } from "./pki-sync-dal";
import { TPkiSyncQueueFactory } from "./pki-sync-queue";
type TPkiSyncCleanupQueueServiceFactoryDep = {
- queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
pkiSyncDAL: Pick<TPkiSyncDALFactory, "findPkiSyncsWithExpiredCertificates">;
pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;
};
@@ -14,7 +14,7 @@ type TPkiSyncCleanupQueueServiceFactoryDep = {
export type TPkiSyncCleanupQueueServiceFactory = ReturnType<typeof pkiSyncCleanupQueueServiceFactory>;
export const pkiSyncCleanupQueueServiceFactory = ({
- queueService,
+ cronJob,
pkiSyncDAL,
pkiSyncQueue
}: TPkiSyncCleanupQueueServiceFactoryDep) => {
@@ -53,28 +53,17 @@ export const pkiSyncCleanupQueueServiceFactory = ({
}
};
- const init = async () => {
- if (appCfg.isSecondaryInstance) {
- return;
- }
-
- queueService.start(QueueName.PkiSyncCleanup, async () => {
- try {
- logger.info(`${QueueName.PkiSyncCleanup}: queue task started`);
+ const init = () => {
+ cronJob.register({
+ name: "pki-sync-cleanup",
+ pattern: "0 0 * * *",
+ runHashTtlS: 3 * 24 * 60 * 60,
+ enabled: !appCfg.isSecondaryInstance,
+ handler: async () => {
+ logger.info("cron[pki-sync-cleanup]: task started");
await syncExpiredCertificatesForPkiSyncs();
- logger.info(`${QueueName.PkiSyncCleanup}: queue task completed`);
- } catch (error) {
- logger.error(error, `${QueueName.PkiSyncCleanup}: PKI sync cleanup failed`);
- throw error;
}
});
-
- await queueService.upsertJobScheduler(
- QueueName.PkiSyncCleanup,
- `${JOB_SCHEDULER_PREFIX}:${QueueJobs.PkiSyncCleanup}`,
- { pattern: "0 0 * * *" },
- { name: QueueJobs.PkiSyncCleanup }
- );
};
return {
diff --git a/backend/src/services/reminder/reminder-queue.ts b/backend/src/services/reminder/reminder-queue.ts
index bdb277cf4a..cd7ce03b99 100644
--- a/backend/src/services/reminder/reminder-queue.ts
+++ b/backend/src/services/reminder/reminder-queue.ts
@@ -1,191 +1,32 @@
-/* eslint-disable no-await-in-loop */
-import RE2 from "re2";
-
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
-import { TSecretReminderRecipientsDALFactory } from "../secret-reminder-recipients/secret-reminder-recipients-dal";
-import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
import { TReminderServiceFactory } from "./reminder-types";
type TDailyReminderQueueServiceFactoryDep = {
reminderService: TReminderServiceFactory;
- queueService: TQueueServiceFactory;
- secretDAL: Pick<TSecretV2BridgeDALFactory, "transaction" | "findSecretsWithReminderRecipientsOld">;
- secretReminderRecipientsDAL: Pick<TSecretReminderRecipientsDALFactory, "delete">;
+ cronJob: TCronJobFactory;
};
export type TDailyReminderQueueServiceFactory = ReturnType<typeof dailyReminderQueueServiceFactory>;
-const uuidRegex = new RE2(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);
-
export const dailyReminderQueueServiceFactory = ({
reminderService,
- queueService,
- secretDAL,
- secretReminderRecipientsDAL
+ cronJob
}: TDailyReminderQueueServiceFactoryDep) => {
- queueService.start(QueueName.DailyReminders, async () => {
- logger.info(`${QueueName.DailyReminders}: queue task started`);
- await reminderService.sendDailyReminders();
- logger.info(`${QueueName.DailyReminders}: queue task completed`);
- });
-
- queueService.start(QueueName.SecretReminderMigration, async () => {
- const REMINDER_PRUNE_BATCH_SIZE = 5_000;
- const MAX_RETRY_ON_FAILURE = 3;
- let numberOfRetryOnFailure = 0;
- let deletedReminderCount = 0;
-
- logger.info(`${QueueName.SecretReminderMigration}: queue task started`);
- try {
- const repeatableJobs = await queueService.getRepeatableJobs(QueueName.SecretReminder);
- const delayedJobs = await queueService.getDelayedJobs(QueueName.SecretReminder);
- logger.info(`${QueueName.SecretReminderMigration}: found ${repeatableJobs.length} secret reminder jobs`);
-
- const reminderJobs = repeatableJobs
- .map((job) => ({ secretId: job.id?.replace("reminder-", "") as string, jobKey: job.key }))
- .filter(Boolean);
- const reminderDelayedJobs = delayedJobs.reduce((map, job) => {
- const match = uuidRegex.exec(job.repeatJobKey || "");
- if (match) {
- map.set(match[0], {
- timestamp: job.timestamp,
- delay: job.delay,
- data: job.data
- });
- }
- return map;
- }, new Map<string, { timestamp: number; delay: number; data: unknown }>());
- if (reminderJobs.length === 0) {
- logger.info(`${QueueName.SecretReminderMigration}: no reminder jobs found`);
- return;
+ const startDailyRemindersJob = () => {
+ cronJob.register({
+ name: "daily-reminders",
+ pattern: "0 0 * * *",
+ runHashTtlS: 3 * 24 * 60 * 60,
+ handler: async () => {
+ logger.info("cron[daily-reminders]: task started");
+ await reminderService.sendDailyReminders();
}
-
- for (let offset = 0; offset < reminderJobs.length; offset += REMINDER_PRUNE_BATCH_SIZE) {
- try {
- const batch = reminderJobs.slice(offset, offset + REMINDER_PRUNE_BATCH_SIZE);
- const batchIds = batch.map((job) => job.secretId);
-
- // Find existing secrets with pagination
- // eslint-disable-next-line no-await-in-loop
- const secrets = await secretDAL.findSecretsWithReminderRecipientsOld(batchIds, REMINDER_PRUNE_BATCH_SIZE);
- const secretsWithReminder = secrets.filter((secret) => secret.reminderRepeatDays);
-
- const foundSecretIds = new Set(secretsWithReminder.map((secret) => secret.id));
-
- // Find IDs that don't exist in either table
- const secretIdsNotFound = batchIds.filter((secretId) => !foundSecretIds.has(secretId));
-
- // Delete reminders for non-existent secrets
- for (const secretId of secretIdsNotFound) {
- const jobKey = reminderJobs.find((r) => r.secretId === secretId)?.jobKey;
-
- if (jobKey) {
- // eslint-disable-next-line no-await-in-loop
- await queueService.stopRepeatableJobByKey(QueueName.SecretReminder, jobKey);
- deletedReminderCount += 1;
- }
- }
-
- for (const secretId of foundSecretIds) {
- const jobKey = reminderJobs.find((r) => r.secretId === secretId)?.jobKey;
-
- if (jobKey) {
- await queueService.stopRepeatableJobByKey(QueueName.SecretReminder, jobKey);
- deletedReminderCount += 1;
- }
- }
-
- await secretDAL.transaction(async (tx) => {
- await reminderService.batchCreateReminders(
- secretsWithReminder.map((secret) => {
- const delayedJob = reminderDelayedJobs.get(secret.id);
- const projectId = (delayedJob?.data as { projectId?: string })?.projectId;
- const nextDate = delayedJob ? new Date(delayedJob.timestamp + delayedJob.delay) : undefined;
- return {
- secretId: secret.id,
- message: secret.reminderNote,
- repeatDays: secret.reminderRepeatDays,
- nextReminderDate: nextDate,
- recipients: secret.recipients || [],
- projectId
- };
- }),
- tx
- );
-
- await secretReminderRecipientsDAL.delete({ $in: { secretId: secretsWithReminder.map((s) => s.id) } }, tx);
- });
-
- numberOfRetryOnFailure = 0;
- } catch (error) {
- numberOfRetryOnFailure += 1;
- logger.error(error, `Failed to process batch at offset ${offset}`);
-
- if (numberOfRetryOnFailure >= MAX_RETRY_ON_FAILURE) {
- break;
- }
-
- // Retry the current batch
- offset -= REMINDER_PRUNE_BATCH_SIZE;
-
- // eslint-disable-next-line no-promise-executor-return, @typescript-eslint/no-loop-func, no-await-in-loop
- await new Promise((resolve) => setTimeout(resolve, 500 * numberOfRetryOnFailure));
- }
-
- // Small delay between batches
- // eslint-disable-next-line no-promise-executor-return, @typescript-eslint/no-loop-func, no-await-in-loop
- await new Promise((resolve) => setTimeout(resolve, 10));
- }
- } catch (error) {
- logger.error(error, "Failed to complete secret reminder pruning");
- } finally {
- logger.info(
- `${QueueName.SecretReminderMigration}: secret reminders completed. Deleted ${deletedReminderCount} reminders`
- );
- }
- });
-
- // we do a repeat cron job in utc timezone at 12 Midnight each day
- const startDailyRemindersJob = async () => {
- // Remove legacy repeatable job
- await queueService.stopRepeatableJob(
- QueueName.DailyReminders,
- QueueJobs.DailyReminders,
- { pattern: "0 0 * * *", utc: true },
- QueueName.DailyReminders
- );
-
- await queueService.upsertJobScheduler(
- QueueName.DailyReminders,
- `${JOB_SCHEDULER_PREFIX}:${QueueJobs.DailyReminders}`,
- { pattern: "0 0 * * *" },
- { name: QueueJobs.DailyReminders, opts: { delay: 5000 } }
- );
- };
-
- // TODO: remove once all the old reminders in queues are migrated
- const startSecretReminderMigrationJob = async () => {
- // clear previous job
- await queueService.stopRepeatableJob(
- QueueName.SecretReminderMigration,
- QueueJobs.SecretReminderMigration,
- { pattern: "0 */1 * * *", utc: true },
- QueueName.SecretReminderMigration // just a job id
- );
+ });
};
- queueService.listen(QueueName.DailyReminders, "failed", (_, err) => {
- logger.error(err, `${QueueName.DailyReminders}: daily reminder processing failed`);
- });
-
- queueService.listen(QueueName.SecretReminderMigration, "failed", (_, err) => {
- logger.error(err, `${QueueName.SecretReminderMigration}: secret reminder migration failed`);
- });
-
return {
- startDailyRemindersJob,
- startSecretReminderMigrationJob
+ startDailyRemindersJob
};
};
diff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
index 07f5269799..61458e8e25 100644
--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
@@ -5,8 +5,8 @@ import { TScimServiceFactory } from "@app/ee/services/scim/scim-types";
import { TSnapshotDALFactory } from "@app/ee/services/secret-snapshot/snapshot-dal";
import { TKeyValueStoreDALFactory } from "@app/keystore/key-value-store-dal";
import { getConfig } from "@app/lib/config/env";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TUserNotificationDALFactory } from "@app/services/notification/user-notification-dal";
import { TApprovalRequestDALFactory, TApprovalRequestGrantsDALFactory } from "../approval-policy/approval-request-dal";
@@ -33,7 +33,7 @@ type TDailyResourceCleanUpQueueServiceFactoryDep = {
snapshotDAL: Pick<TSnapshotDALFactory, "pruneExcessSnapshots">;
secretSharingDAL: Pick<TSecretSharingDALFactory, "pruneExpiredSharedSecrets" | "pruneExpiredSecretRequests">;
serviceTokenService: Pick<TServiceTokenServiceFactory, "notifyExpiringTokens">;
- queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
orgService: TOrgServiceFactory;
userNotificationDAL: Pick<TUserNotificationDALFactory, "pruneNotifications">;
keyValueStoreDAL: Pick<TKeyValueStoreDALFactory, "pruneExpiredKeys">;
@@ -49,7 +49,7 @@ export type TDailyResourceCleanUpQueueServiceFactory = ReturnType<typeof dailyRe
export const dailyResourceCleanUpQueueServiceFactory = ({
auditLogDAL,
auditLogService,
- queueService,
+ cronJob,
snapshotDAL,
secretVersionDAL,
secretFolderVersionDAL,
@@ -74,14 +74,14 @@ export const dailyResourceCleanUpQueueServiceFactory = ({
logger.warn("Daily Resource Clean Up is in development mode.");
}
- const init = async () => {
- if (appCfg.isSecondaryInstance) {
- return;
- }
-
- queueService.start(QueueName.DailyResourceCleanUp, async () => {
- try {
- logger.info(`${QueueName.DailyResourceCleanUp}: queue task started`);
+ const init = () => {
+ cronJob.register({
+ name: "daily-resource-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");
await identityUniversalAuthClientSecretDAL.removeExpiredClientSecrets();
await secretSharingDAL.pruneExpiredSharedSecrets();
await secretSharingDAL.pruneExpiredSecretRequests();
@@ -103,38 +103,19 @@ export const dailyResourceCleanUpQueueServiceFactory = ({
await approvalRequestGrantsDAL.markExpiredGrants();
await identityAccessTokenRevocationDAL.removeExpiredRevocations();
await auditLogDAL.pruneAuditLog();
- logger.info(`${QueueName.DailyResourceCleanUp}: queue task completed`);
- } catch (error) {
- logger.error(error, `${QueueName.DailyResourceCleanUp}: resource cleanup failed`);
- throw error;
}
});
- await queueService.upsertJobScheduler(
- QueueName.DailyResourceCleanUp,
- `${JOB_SCHEDULER_PREFIX}:${QueueJobs.DailyResourceCleanUp}`,
- { pattern: appCfg.isDailyResourceCleanUpDevelopmentMode ? "*/5 * * * *" : "0 0 * * *" },
- { name: QueueJobs.DailyResourceCleanUp }
- );
-
- // Hourly cleanup routine
- queueService.start(QueueName.FrequentResourceCleanUp, async () => {
- try {
- logger.info(`${QueueName.FrequentResourceCleanUp}: queue task started`);
+ cronJob.register({
+ name: "frequent-resource-cleanup",
+ pattern: appCfg.isDailyResourceCleanUpDevelopmentMode ? "*/5 * * * *" : "0 * * * *",
+ runHashTtlS: 2 * 24 * 60 * 60,
+ enabled: !appCfg.isSecondaryInstance,
+ handler: async () => {
+ logger.info("cron[frequent-resource-cleanup]: task started");
await identityAccessTokenDAL.removeExpiredTokens();
- logger.info(`${QueueName.FrequentResourceCleanUp}: queue task completed`);
- } catch (error) {
- logger.error(error, `${QueueName.FrequentResourceCleanUp}: resource cleanup failed`);
- throw error;
}
});
-
- await queueService.upsertJobScheduler(
- QueueName.FrequentResourceCleanUp,
- `${JOB_SCHEDULER_PREFIX}:${QueueJobs.FrequentResourceCleanUp}`,
- { pattern: appCfg.isDailyResourceCleanUpDevelopmentMode ? "*/5 * * * *" : "0 * * * *" },
- { name: QueueJobs.FrequentResourceCleanUp }
- );
};
return {
diff --git a/backend/src/services/secret-folder/secret-folder-version-dal.ts b/backend/src/services/secret-folder/secret-folder-version-dal.ts
index 5504c6e0bd..be4989413d 100644
--- a/backend/src/services/secret-folder/secret-folder-version-dal.ts
+++ b/backend/src/services/secret-folder/secret-folder-version-dal.ts
@@ -5,7 +5,6 @@ import { TableName, TSecretFolderVersions } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex";
import { logger } from "@app/lib/logger";
-import { QueueName } from "@app/queue";
export type TSecretFolderVersionDALFactory = ReturnType<typeof secretFolderVersionDALFactory>;
@@ -67,7 +66,7 @@ export const secretFolderVersionDALFactory = (db: TDbClient) => {
};
const pruneExcessVersions = async () => {
- logger.info(`${QueueName.DailyResourceCleanUp}: pruning secret folder versions started`);
+ logger.info(`daily-resource-cleanup: pruning secret folder versions started`);
try {
await db(TableName.SecretFolderVersion)
.with("folder_cte", (qb) => {
@@ -94,7 +93,7 @@ export const secretFolderVersionDALFactory = (db: TDbClient) => {
name: "Secret Folder Version Prune"
});
}
- logger.info(`${QueueName.DailyResourceCleanUp}: pruning secret folder versions completed`);
+ logger.info(`daily-resource-cleanup: pruning secret folder versions completed`);
};
// Get latest versions by folderIds
diff --git a/backend/src/services/secret-sharing/secret-sharing-dal.ts b/backend/src/services/secret-sharing/secret-sharing-dal.ts
index 7f5c3624bf..3e49833f96 100644
--- a/backend/src/services/secret-sharing/secret-sharing-dal.ts
+++ b/backend/src/services/secret-sharing/secret-sharing-dal.ts
@@ -5,7 +5,6 @@ import { TableName } from "@app/db/schemas";
import { DatabaseError, NotFoundError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex";
import { logger } from "@app/lib/logger";
-import { QueueName } from "@app/queue";
import { SecretSharingType } from "./secret-sharing-types";
@@ -88,7 +87,7 @@ export const secretSharingDALFactory = (db: TDbClient) => {
};
const pruneExpiredSharedSecrets = async (tx?: Knex) => {
- logger.info(`${QueueName.DailyResourceCleanUp}: pruning expired shared secret started`);
+ logger.info(`daily-resource-cleanup: pruning expired shared secret started`);
try {
const sevenDaysAgo = new Date();
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
@@ -97,7 +96,7 @@ export const secretSharingDALFactory = (db: TDbClient) => {
.where("expiresAt", "<", sevenDaysAgo)
.andWhere("type", SecretSharingType.Share)
.del();
- logger.info(`${QueueName.DailyResourceCleanUp}: pruning expired shared secret completed`);
+ logger.info(`daily-resource-cleanup: pruning expired shared secret completed`);
return docs;
} catch (error) {
throw new DatabaseError({ error, name: "pruneExpiredSharedSecrets" });
@@ -105,7 +104,7 @@ export const secretSharingDALFactory = (db: TDbClient) => {
};
const pruneExpiredSecretRequests = async (tx?: Knex) => {
- logger.info(`${QueueName.DailyResourceCleanUp}: pruning expired secret requests started`);
+ logger.info(`daily-resource-cleanup: pruning expired secret requests started`);
try {
const sevenDaysAgo = new Date();
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
@@ -116,7 +115,7 @@ export const secretSharingDALFactory = (db: TDbClient) => {
.andWhere("type", SecretSharingType.Request)
.delete();
- logger.info(`${QueueName.DailyResourceCleanUp}: pruning expired secret requests completed`);
+ logger.info(`daily-resource-cleanup: pruning expired secret requests completed`);
return docs;
} catch (error) {
diff --git a/backend/src/services/secret-sync/secret-sync-queue.ts b/backend/src/services/secret-sync/secret-sync-queue.ts
index c3b9c81e0b..2a8e195990 100644
--- a/backend/src/services/secret-sync/secret-sync-queue.ts
+++ b/backend/src/services/secret-sync/secret-sync-queue.ts
@@ -10,10 +10,11 @@ import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
import { triggerWorkflowIntegrationNotification } from "@app/lib/workflow-integrations/trigger-notification";
import { TriggerFeature } from "@app/lib/workflow-integrations/types";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { SecretNameSchema } from "@app/server/lib/schemas";
import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";
import { ActorType } from "@app/services/auth/auth-type";
@@ -80,7 +81,8 @@ const DEFAULT_SECRET_SYNC_RETRY_CONFIG = {
export type TSecretSyncQueueFactory = ReturnType<typeof secretSyncQueueFactory>;
type TSecretSyncQueueFactoryDep = {
- queueService: Pick<TQueueServiceFactory, "queue" | "start" | "upsertJobScheduler">;
+ queueService: Pick<TQueueServiceFactory, "queue" | "start">;
+ cronJob: TCronJobFactory;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;
keyStore: Pick<TKeyStoreFactory, "acquireLock" | "setItemWithExpiry" | "getItem">;
@@ -142,6 +144,7 @@ const getRequeueDelay = (failureCount?: number) => {
export const secretSyncQueueFactory = ({
queueService,
+ cronJob,
kmsService,
appConnectionDAL,
keyStore,
@@ -1218,13 +1221,20 @@ export const secretSyncQueueFactory = ({
}
});
- const startDailySecretSyncRetryJob = async () => {
- await queueService.upsertJobScheduler(
- QueueName.AppConnectionSecretSync,
- `${JOB_SCHEDULER_PREFIX}:${QueueJobs.DailySecretSyncRetry}`,
- { pattern: appCfg.isDailyResourceCleanUpDevelopmentMode ? "*/5 * * * *" : "0 0 * * *" },
- { name: QueueJobs.DailySecretSyncRetry }
- );
+ const startDailySecretSyncRetryJob = () => {
+ cronJob.register({
+ name: "daily-secret-sync-retry",
+ pattern: appCfg.isDailyResourceCleanUpDevelopmentMode ? "*/5 * * * *" : "0 0 * * *",
+ runHashTtlS: 3 * 24 * 60 * 60,
+ handler: async () => {
+ await queueService.queue(
+ QueueName.AppConnectionSecretSync,
+ QueueJobs.DailySecretSyncRetry,
+ undefined as never,
+ { jobId: "daily-secret-sync-retry" }
+ );
+ }
+ });
};
return {
diff --git a/backend/src/services/secret-v2-bridge/secret-version-dal.ts b/backend/src/services/secret-v2-bridge/secret-version-dal.ts
index 6319f05f49..20d0357027 100644
--- a/backend/src/services/secret-v2-bridge/secret-version-dal.ts
+++ b/backend/src/services/secret-v2-bridge/secret-version-dal.ts
@@ -14,7 +14,6 @@ import {
import { BadRequestError, DatabaseError } from "@app/lib/errors";
import { buildFindFilter, ormify, selectAllTableCols, sqlNestRelationships, TFindOpt } from "@app/lib/knex";
import { logger } from "@app/lib/logger";
-import { QueueName } from "@app/queue";
export type TSecretVersionV2DALFactory = ReturnType<typeof secretVersionV2BridgeDALFactory>;
@@ -169,7 +168,7 @@ export const secretVersionV2BridgeDALFactory = (db: TDbClient) => {
};
const pruneExcessVersions = async () => {
- logger.info(`${QueueName.DailyResourceCleanUp}: pruning secret version v2 started`);
+ logger.info(`daily-resource-cleanup: pruning secret version v2 started`);
try {
await db(TableName.SecretVersionV2)
.with("version_cte", (qb) => {
@@ -197,7 +196,7 @@ export const secretVersionV2BridgeDALFactory = (db: TDbClient) => {
name: "Secret Version Prune"
});
}
- logger.info(`${QueueName.DailyResourceCleanUp}: pruning secret version v2 completed`);
+ logger.info(`daily-resource-cleanup: pruning secret version v2 completed`);
};
const findVersionsBySecretIdWithActors = async ({
diff --git a/backend/src/services/secret/secret-version-dal.ts b/backend/src/services/secret/secret-version-dal.ts
index 8e4544c19e..acd20b4496 100644
--- a/backend/src/services/secret/secret-version-dal.ts
+++ b/backend/src/services/secret/secret-version-dal.ts
@@ -5,7 +5,6 @@ import { SecretVersionsSchema, TableName, TSecretVersions, TSecretVersionsUpdate
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
import { ormify, selectAllTableCols, sqlNestRelationships, TFindOpt } from "@app/lib/knex";
import { logger } from "@app/lib/logger";
-import { QueueName } from "@app/queue";
export type TSecretVersionDALFactory = ReturnType<typeof secretVersionDALFactory>;
@@ -158,7 +157,7 @@ export const secretVersionDALFactory = (db: TDbClient) => {
};
const pruneExcessVersions = async () => {
- logger.info(`${QueueName.DailyResourceCleanUp}: pruning secret version v1 started`);
+ logger.info(`daily-resource-cleanup: pruning secret version v1 started`);
try {
await db(TableName.SecretVersion)
.with("version_cte", (qb) => {
@@ -184,7 +183,7 @@ export const secretVersionDALFactory = (db: TDbClient) => {
name: "Secret Version Prune"
});
}
- logger.info(`${QueueName.DailyResourceCleanUp}: pruning secret version v1 completed`);
+ logger.info(`daily-resource-cleanup: pruning secret version v1 completed`);
};
return {
diff --git a/backend/src/services/telemetry/telemetry-queue.ts b/backend/src/services/telemetry/telemetry-queue.ts
index 50d81f6c8f..8ab64da4b4 100644
--- a/backend/src/services/telemetry/telemetry-queue.ts
+++ b/backend/src/services/telemetry/telemetry-queue.ts
@@ -2,8 +2,8 @@ import { PostHog } from "posthog-node";
import { TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
+import { TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { getServerCfg } from "../super-admin/super-admin-service";
import { TTelemetryDALFactory } from "./telemetry-dal";
@@ -15,7 +15,7 @@ import {
import { PostHogEventTypes } from "./telemetry-types";
type TTelemetryQueueServiceFactoryDep = {
- queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
keyStore: Pick<TKeyStoreFactory, "getItem" | "deleteItem">;
telemetryDAL: TTelemetryDALFactory;
telemetryService: TTelemetryServiceFactory;
@@ -24,7 +24,7 @@ type TTelemetryQueueServiceFactoryDep = {
export type TTelemetryQueueServiceFactory = ReturnType<typeof telemetryQueueServiceFactory>;
export const telemetryQueueServiceFactory = ({
- queueService,
+ cronJob,
keyStore,
telemetryDAL,
telemetryService
@@ -35,64 +35,50 @@ export const telemetryQueueServiceFactory = ({
? new PostHog(appCfg.POSTHOG_PROJECT_API_KEY, { host: appCfg.POSTHOG_HOST, flushAt: 1, flushInterval: 0 })
: undefined;
- queueService.start(QueueName.TelemetryInstanceStats, async () => {
- const { instanceId } = await getServerCfg();
- const telemtryStats = await telemetryDAL.getTelemetryInstanceStats();
- // parse the redis values into integer
- 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 };
-
- // send to postHog
- postHog?.capture({
- event: PostHogEventTypes.TelemetryInstanceStats,
- distinctId: instanceId,
- properties: stats
- });
- // reset the stats
- await keyStore.deleteItem(TELEMETRY_SECRET_PROCESSED_KEY);
- await keyStore.deleteItem(TELEMETRY_SECRET_OPERATIONS_KEY);
- });
-
- queueService.start(QueueName.TelemetryAggregatedEvents, async () => {
- await telemetryService.processAggregatedEvents();
- });
-
// every day at midnight a telemetry job executes on self-hosted instances
- // this sends some telemetry information like instance id secrets operated etc
- const startTelemetryCheck = async () => {
- // this is a fast way to check its cloud or not
- if (appCfg.INFISICAL_CLOUD) return;
+ const startTelemetryCheck = () => {
+ // cloud instances skip telemetry stats
+ if (appCfg.INFISICAL_CLOUD || !postHog) return;
- if (postHog) {
- await queueService.upsertJobScheduler(
- QueueName.TelemetryInstanceStats,
- `${JOB_SCHEDULER_PREFIX}:${QueueName.TelemetryInstanceStats}`,
- { pattern: "0 0 * * *" },
- { name: QueueJobs.TelemetryInstanceStats }
- );
- }
- };
+ cronJob.register({
+ name: "telemetry-instance-stats",
+ pattern: "0 0 * * *",
+ runHashTtlS: 3 * 24 * 60 * 60,
+ handler: async () => {
+ const { instanceId } = await getServerCfg();
+ const telemtryStats = 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 startAggregatedEventsJob = async () => {
- if (postHog) {
- // Start aggregated events job (runs every five minutes)
- await queueService.upsertJobScheduler(
- QueueName.TelemetryAggregatedEvents,
- `${JOB_SCHEDULER_PREFIX}:${QueueName.TelemetryAggregatedEvents}`,
- { pattern: "*/5 * * * *" },
- { name: QueueJobs.TelemetryAggregatedEvents }
- );
- }
+ postHog.capture({
+ event: PostHogEventTypes.TelemetryInstanceStats,
+ distinctId: instanceId,
+ properties: stats
+ });
+ await keyStore.deleteItem(TELEMETRY_SECRET_PROCESSED_KEY);
+ await keyStore.deleteItem(TELEMETRY_SECRET_OPERATIONS_KEY);
+ }
+ });
};
- queueService.listen(QueueName.TelemetryInstanceStats, "failed", (err) => {
- logger.error(err?.failedReason, `${QueueName.TelemetryInstanceStats}: failed`);
- });
+ const startAggregatedEventsJob = () => {
+ if (!postHog) return;
+
+ cronJob.register({
+ name: "telemetry-aggregated-events",
+ pattern: "*/5 * * * *",
+ runHashTtlS: 60 * 60,
+ handler: async () => {
+ await telemetryService.processAggregatedEvents();
+ }
+ });
+ };
- queueService.listen(QueueName.TelemetryAggregatedEvents, "failed", (err) => {
- logger.error(err?.failedReason, `${QueueName.TelemetryAggregatedEvents}: failed`);
- });
+ logger.info("telemetry queue service initialized");
return {
startTelemetryCheck,