Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: resolved ts error with missing job id
=7402da53bca9
diff --git a/backend/e2e-test/vitest-environment-knex.ts b/backend/e2e-test/vitest-environment-knex.tsindex 33bb645030..78727844e5 100644--- a/backend/e2e-test/vitest-environment-knex.ts+++ b/backend/e2e-test/vitest-environment-knex.ts@@ -74,7 +74,7 @@ export default {const smtp = mockSmtpServer();const queueJobsDAL = queueJobsDALFactory(db);- const queue = queueServiceFactory(envCfg, queueJobsDAL, { dbConnectionUrl: envCfg.DB_CONNECTION_URI });+ const queue = queueServiceFactory(envCfg, queueJobsDAL);const keyValueStoreDAL = keyValueStoreDALFactory(db);const keyStore = keyStoreFactory(envCfg, keyValueStoreDAL);diff --git a/backend/src/db/migrations/20260203141935_durable-queue.ts b/backend/src/db/migrations/20260203141935_durable-queue.tsindex ff5723cb26..3dd12fd106 100644--- a/backend/src/db/migrations/20260203141935_durable-queue.ts+++ b/backend/src/db/migrations/20260203141935_durable-queue.ts@@ -14,7 +14,8 @@ export async function up(knex: Knex): Promise<void> {t.string("queueType").notNullable().defaultTo("bullmq");t.string("queueJobName").notNullable();t.string("jobId").notNullable();- t.json("queueData").notNullable();+ t.jsonb("queueData").notNullable();+ t.jsonb("queueOptions");t.string("status").notNullable().defaultTo("pending");t.integer("attempts").notNullable().defaultTo(0);diff --git a/backend/src/db/schemas/queue-jobs.ts b/backend/src/db/schemas/queue-jobs.tsindex 36b0927599..eed398242f 100644--- a/backend/src/db/schemas/queue-jobs.ts+++ b/backend/src/db/schemas/queue-jobs.ts@@ -14,6 +14,7 @@ export const QueueJobsSchema = z.object({queueJobName: z.string(),jobId: z.string(),queueData: z.unknown(),+ queueOptions: z.unknown().nullable().optional(),status: z.string().default("pending"),attempts: z.number().default(0),maxAttempts: z.number().default(3),diff --git a/backend/src/ee/services/audit-log/audit-log-queue.ts b/backend/src/ee/services/audit-log/audit-log-queue.tsindex 6b286c2ece..a25968a1e8 100644--- a/backend/src/ee/services/audit-log/audit-log-queue.ts+++ b/backend/src/ee/services/audit-log/audit-log-queue.ts@@ -1,3 +1,5 @@+import { randomUUID } from "crypto";+import { TAuditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream/audit-log-stream-service";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { TProjectDALFactory } from "@app/services/project/project-dal";@@ -34,7 +36,8 @@ export const auditLogQueueServiceFactory = async ({removeOnFail: {count: 3},- removeOnComplete: true+ removeOnComplete: true,+ jobId: randomUUID()});};diff --git a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.ts b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.tsindex 4a749223b5..d33c628fd2 100644--- a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.ts+++ b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.ts@@ -89,7 +89,6 @@ export const dynamicSecretLeaseQueueServiceFactory = ({const unsetLeaseRevocation = async (leaseId: string) => {await queueService.stopJobById(QueueName.DynamicSecretRevocation, leaseId);- await queueService.stopJobByIdPg(QueueName.DynamicSecretRevocation, leaseId);};const queueFailedRevocation = async (leaseId: string, dynamicSecretId: string) => {@@ -246,7 +245,6 @@ export const dynamicSecretLeaseQueueServiceFactory = ({// only add to retry queue if this is not a retry, and if the error is not a DisableRotationErrors errorif (!isRetry && !(error instanceof DisableRotationErrors)) {// if revocation fails, we should stop the job and queue a new job to retry the revocation at a later time.- await queueService.stopJobByIdPg(QueueName.DynamicSecretRevocation, jobId);await queueService.stopRepeatableJobByJobId(QueueName.DynamicSecretRevocation, jobId);await queueFailedRevocation(leaseId, dynamicSecretId);@@ -257,7 +255,6 @@ export const dynamicSecretLeaseQueueServiceFactory = ({// the ID of the revocation job is set to the leaseId, so we can use that to stop the job// we dont have to stop the retry job, because if we hit this point, its the last attempt and the retry job will be stopped by pgboss itself after this point,- await queueService.stopJobByIdPg(QueueName.DynamicSecretRevocation, leaseId);await queueService.stopRepeatableJobByJobId(QueueName.DynamicSecretRevocation, leaseId);await $queueDynamicSecretLeaseRevocationFailedEmail(leaseId, dynamicSecretId);@@ -267,7 +264,6 @@ export const dynamicSecretLeaseQueueServiceFactory = ({if (error instanceof DisableRotationErrors) {if (jobId) {await queueService.stopRepeatableJobByJobId(QueueName.DynamicSecretRevocation, jobId);- await queueService.stopJobByIdPg(QueueName.DynamicSecretRevocation, jobId);}} else {// propagate to next partdiff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.tsindex 14d94297a1..7e446af951 100644--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts@@ -773,7 +773,7 @@ export const secretRotationV2ServiceFactory = ({// queue for rotation if adjusted time falls before next cronif (nextRotationAt && nextRotationAt.getTime() < getNextUtcRotationInterval().getTime()) {await queueService.queue(- QueueName.SecretRotationV2,+ QueueName.SecretRotationV2RotateSecrets,QueueJobs.SecretRotationV2RotateSecrets,{ rotationId, queuedAt: new Date(), isManualRotation: true },getSecretRotationRotateSecretJobOptions(updatedSecretRotation)diff --git a/backend/src/ee/services/secret-rotation/secret-rotation-queue/secret-rotation-queue.ts b/backend/src/ee/services/secret-rotation/secret-rotation-queue/secret-rotation-queue.tsindex eefe6b63af..0464d23d26 100644--- a/backend/src/ee/services/secret-rotation/secret-rotation-queue/secret-rotation-queue.ts+++ b/backend/src/ee/services/secret-rotation/secret-rotation-queue/secret-rotation-queue.ts@@ -83,24 +83,7 @@ export const secretRotationQueueFactory = ({folderCommitService,kmsService}: TSecretRotationQueueFactoryDep) => {- const addToQueue = async (rotationId: string, interval: number) => {- const appCfg = getConfig();- await queue.queue(- QueueName.SecretRotation,- QueueJobs.SecretRotation,- { rotationId },- {- jobId: rotationId,- repeat: {- // on prod it this will be in days, in development this will be second- every: appCfg.NODE_ENV === "development" ? secondsToMillis(interval) : daysToMillisecond(interval),- immediately: true- },- removeOnComplete: true,- removeOnFail: true- }- );- };+ const addToQueue = async () => {};const removeFromQueue = async (rotationId: string, interval: number) => {const appCfg = getConfig();diff --git a/backend/src/ee/services/secret-rotation/secret-rotation-service.ts b/backend/src/ee/services/secret-rotation/secret-rotation-service.tsindex 04ece7e5bb..a093f87907 100644--- a/backend/src/ee/services/secret-rotation/secret-rotation-service.ts+++ b/backend/src/ee/services/secret-rotation/secret-rotation-service.ts@@ -205,7 +205,7 @@ export const secretRotationServiceFactory = ({}return { ...doc, outputs: outputSecretMapping, environment: folder.environment };});- await secretRotationQueue.addToQueue(secretRotation.id, secretRotation.interval);+ await secretRotationQueue.addToQueue();return secretRotation;};@@ -274,7 +274,7 @@ export const secretRotationServiceFactory = ({ProjectPermissionSub.SecretRotation);await secretRotationQueue.removeFromQueue(doc.id, doc.interval);- await secretRotationQueue.addToQueue(doc.id, doc.interval);+ await secretRotationQueue.addToQueue();return doc;};diff --git a/backend/src/main.ts b/backend/src/main.tsindex 7a5a9a7133..f37d0886fa 100644--- a/backend/src/main.ts+++ b/backend/src/main.ts@@ -73,12 +73,7 @@ const run = async () => {const smtp = smtpServiceFactory(formatSmtpConfig());const queueJobsDAL = queueJobsDALFactory(db);- const queue = queueServiceFactory(envConfig, queueJobsDAL, {- dbConnectionUrl: envConfig.DB_CONNECTION_URI,- dbRootCert: envConfig.DB_ROOT_CERT- });-- await queue.initialize();+ const queue = queueServiceFactory(envConfig, queueJobsDAL);const keyValueStoreDAL = keyValueStoreDALFactory(db);const keyStore = keyStoreFactory(envConfig, keyValueStoreDAL);@@ -97,6 +92,8 @@ const run = async () => {redis,envConfig});++ await queue.initialize();const bootstrap = await bootstrapCheck({ db });// eslint-disable-next-linediff --git a/backend/src/queue/queue-jobs-dal.ts b/backend/src/queue/queue-jobs-dal.tsindex 1a36dd8867..3f1ef9f4e1 100644--- a/backend/src/queue/queue-jobs-dal.ts+++ b/backend/src/queue/queue-jobs-dal.ts@@ -1,10 +1,25 @@import { TDbClient } from "@app/db";-import { TableName } from "@app/db/schemas";+import { TableName, TQueueJobs } from "@app/db/schemas";import { ormify } from "@app/lib/knex";export type TQueueJobsDALFactory = ReturnType<typeof queueJobsDALFactory>;export const queueJobsDALFactory = (db: TDbClient) => {const orm = ormify(db, TableName.QueueJobs);- return orm;++ /**+ * Find stuck processing jobs for a specific queue using COALESCE(lastHeartBeat, updatedAt)+ * A job is considered stuck if the time since last heartbeat (or update) exceeds the threshold+ */+ const findStuckJobsByQueue = async (queueName: string, thresholdMs: number): Promise<TQueueJobs[]> => {+ const result = await db<TQueueJobs>(TableName.QueueJobs)+ .select("*")+ .where("status", "processing")+ .where("queueName", queueName)+ .whereRaw(`(NOW() - COALESCE("lastHeartBeat", "updatedAt")) > INTERVAL '1 millisecond' * ?`, [thresholdMs]);++ return result as TQueueJobs[];+ };++ return { ...orm, findStuckJobsByQueue };};diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex a694d400a6..4fa09cdbc5 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -1,7 +1,6 @@import { Job, Queue, QueueOptions, RepeatOptions, Worker, WorkerListener } from "bullmq";-import PgBoss from "pg-boss";-import { SecretEncryptionAlgo, SecretKeyEncoding } from "@app/db/schemas";+import { SecretEncryptionAlgo, SecretKeyEncoding, TQueueJobs } from "@app/db/schemas";import { TCreateAuditLogDTO } from "@app/ee/services/audit-log/audit-log-types";import {TSecretRotationRotateSecretsJobPayload,@@ -55,6 +54,10 @@ export enum PersistanceQueueStatus {}export enum QueueName {+ // Internal queues for durable queue recovery+ QueueInternalRecovery = "queue-internal-recovery",+ QueueInternalReconciliation = "queue-internal-reconciliation",+SecretRotation = "secret-rotation",SecretReminder = "secret-reminder",AuditLog = "audit-log",@@ -101,6 +104,10 @@ export enum QueueName {}export enum QueueJobs {+ // Internal queue jobs for durable queue recovery+ QueueRecovery = "queue-recovery-job",+ QueueReconciliation = "queue-reconciliation-job",+SecretReminder = "secret-reminder-job",SecretRotation = "secret-rotation-job",AuditLog = "audit-log-job",@@ -169,11 +176,30 @@ export type TQueueOptions = {};repeat?: {pattern?: string;+ every?: number;+ // only works with every by bullmq+ immediately?: boolean;key: string;+ utc?: boolean;};};+export type TPersistenceConfig = {+ enabled: boolean;+ stuckThresholdMs?: number; // Default: 5 minutes (300000ms)+};+export type TQueueJobTypes = {+ // Internal queue types for durable queue recovery+ [QueueName.QueueInternalRecovery]: {+ name: QueueJobs.QueueRecovery;+ payload: undefined;+ };+ [QueueName.QueueInternalReconciliation]: {+ name: QueueJobs.QueueReconciliation;+ payload: undefined;+ };+[QueueName.SecretReminder]: {payload: {projectId: string;@@ -477,7 +503,7 @@ export type TQueueServiceFactory = {start: <T extends QueueName>(name: T,jobFn: (job: Job<TQueueJobTypes[T]["payload"], void, TQueueJobTypes[T]["name"]>, token?: string) => Promise<void>,- queueSettings?: Omit<QueueOptions, "connection"> & { persistence?: boolean }+ queueSettings?: Omit<QueueOptions, "connection"> & { persistence?: boolean | TPersistenceConfig }) => void;listen: <T extends QueueName,@@ -493,7 +519,6 @@ export type TQueueServiceFactory = {data: TQueueJobTypes[T]["payload"],opts: TQueueOptions) => Promise<void>;- unschedulePg: <T extends QueueName>(job: TQueueJobTypes[T]["name"]) => Promise<void>;shutdown: () => Promise<void>;stopRepeatableJob: <T extends QueueName>(name: T,@@ -505,7 +530,6 @@ export type TQueueServiceFactory = {stopRepeatableJobByKey: <T extends QueueName>(name: T, repeatJobKey: string) => Promise<boolean>;clearQueue: (name: QueueName) => Promise<void>;stopJobById: <T extends QueueName>(name: T, jobId: string) => Promise<void | undefined>;- stopJobByIdPg: <T extends QueueName>(name: T, jobId: string) => Promise<void | undefined>;getRepeatableJobs: (name: QueueName,startOffset?: number,@@ -516,12 +540,12 @@ export type TQueueServiceFactory = {startOffset?: number,endOffset?: number) => Promise<{ delay: number; timestamp: number; repeatJobKey?: string; data?: unknown }[]>;+ updateJobHeartbeat: <T extends QueueName>(queueName: T, jobId: string) => Promise<void>;};export const queueServiceFactory = (redisCfg: TRedisConfigKeys,- queueJobsDAL: TQueueJobsDALFactory,- { dbConnectionUrl, dbRootCert }: { dbConnectionUrl: string; dbRootCert?: string }+ queueJobsDAL: TQueueJobsDALFactory): TQueueServiceFactory => {const isClusterMode = Boolean(redisCfg?.REDIS_CLUSTER_HOSTS);const connection = buildRedisFromConfig(redisCfg);@@ -530,20 +554,6 @@ export const queueServiceFactory = (Queue<TQueueJobTypes[QueueName]["payload"], void, TQueueJobTypes[QueueName]["name"]>>;- const pgBoss = new PgBoss({- connectionString: dbConnectionUrl,- archiveCompletedAfterSeconds: 60,- cronMonitorIntervalSeconds: 5,- archiveFailedAfterSeconds: 1000, // we want to keep failed jobs for a longer time so that it can be retried- deleteAfterSeconds: 30,- ssl: dbRootCert- ? {- rejectUnauthorized: true,- ca: Buffer.from(dbRootCert, "base64").toString("ascii")- }- : false- });-const workerContainer = {} as Record<QueueName,Worker<TQueueJobTypes[QueueName]["payload"], void, TQueueJobTypes[QueueName]["name"]>@@ -551,13 +561,239 @@ export const queueServiceFactory = (const persistantQueues = new Set<QueueName>();+ // Configuration for persistent queues (threshold and max attempts)+ const persistentQueueConfigs = new Map<+ QueueName,+ {+ stuckThresholdMs: number;+ maxAttempts: number;+ }+ >();++ // Track startup recovery completion to prevent duplicate runs+ let startupRecoveryCompleted = false;++ /**+ * Startup Recovery Function+ * Recovers pending jobs from PostgreSQL after server restart+ */+ const startupRecovery = async () => {+ if (startupRecoveryCompleted) return;++ logger.info("Starting queue startup recovery...");++ const queueNames = Array.from(persistantQueues);+ if (queueNames.length === 0) {+ startupRecoveryCompleted = true;+ logger.info("No persistent queues configured, skipping startup recovery");+ return;+ }++ try {+ const pendingJobs = await queueJobsDAL.find({+ status: PersistanceQueueStatus.Pending,+ $in: { queueName: queueNames }+ });++ logger.info({ count: pendingJobs.length }, "Found pending jobs for recovery");++ for await (const job of pendingJobs) {+ const queueName = job.queueName as QueueName;+ const q = queueContainer[queueName];+ if (!q) {+ logger.warn({ queueName, jobId: job.jobId }, "Queue not initialized, skipping job");+ // eslint-disable-next-line no-continue+ continue;+ }++ const opts = (job.queueOptions || {}) as TQueueOptions;++ // Check if already in Redis (avoid duplicates)+ const existingJob = await q.getJob(job.jobId);+ if (existingJob) {+ logger.debug({ jobId: job.jobId, queueName }, "Job already in Redis, skipping");+ // eslint-disable-next-line no-continue+ continue;+ }++ // Recalculate delay for delayed jobs+ let adjustedDelay = opts.delay;+ if (opts.delay && opts.delay > 0) {+ const originalScheduledTime = new Date(job.createdAt).getTime() + opts.delay;+ adjustedDelay = Math.max(0, originalScheduledTime - Date.now());+ }++ // Re-queue the job+ await q.add(job.queueJobName as TQueueJobTypes[typeof queueName]["name"], job.queueData as never, {+ ...opts,+ delay: adjustedDelay,+ jobId: job.jobId+ });++ logger.info({ jobId: job.jobId, queueName, adjustedDelay }, "Job recovered and re-queued");+ }++ startupRecoveryCompleted = true;+ logger.info("Queue startup recovery completed");+ } catch (error) {+ logger.error(error, "Queue startup recovery failed");+ }+ };++ /**+ * Handle a stuck job - either re-queue it or mark it as dead+ */+ const handleStuckJob = async (dbJob: TQueueJobs, config: { stuckThresholdMs: number; maxAttempts: number }) => {+ const queueName = dbJob.queueName as QueueName;+ const q = queueContainer[queueName];+ if (!q) return;++ const newAttempts = dbJob.attempts + 1;++ if (newAttempts >= config.maxAttempts) {+ // Mark as dead - exceeded max retries+ await queueJobsDAL.update(+ { id: dbJob.id },+ {+ status: PersistanceQueueStatus.Dead,+ attempts: newAttempts,+ errorMessage: `Exceeded max attempts (${config.maxAttempts}) after being stuck`+ }+ );++ logger.error({ jobId: dbJob.jobId, queueName, attempts: newAttempts }, "Job marked as dead");++ // Remove from Redis if exists+ try {+ const redisJob = await q.getJob(dbJob.jobId);+ if (redisJob) await redisJob.remove();+ } catch {+ // Ignore removal errors+ }+ return;+ }++ // Reset to pending with incremented attempts+ await queueJobsDAL.update(+ { id: dbJob.id },+ {+ status: PersistanceQueueStatus.Pending,+ attempts: newAttempts,+ startedAt: null,+ lastHeartBeat: null,+ errorMessage: `Re-queued after stuck detection (attempt ${newAttempts}/${config.maxAttempts})`+ }+ );++ // Remove from Redis and re-add+ try {+ const redisJob = await q.getJob(dbJob.jobId);+ if (redisJob) await redisJob.remove();+ } catch {+ // Ignore removal errors+ }++ const opts = (dbJob.queueOptions || {}) as TQueueOptions;+ await q.add(dbJob.queueJobName as TQueueJobTypes[typeof queueName]["name"], dbJob.queueData as never, {+ ...opts,+ jobId: dbJob.jobId,+ delay: undefined // Execute immediately on retry+ });++ logger.info({ jobId: dbJob.jobId, queueName, attempt: newAttempts }, "Stuck job re-queued");+ };++ /**+ * Reconciliation Function+ * Checks for stuck jobs and re-queues them+ */+ const runReconciliation = async () => {+ logger.debug("Running queue reconciliation check...");++ if (persistentQueueConfigs.size === 0) return;++ try {+ // Iterate through each persistent queue+ for await (const [queueName, config] of persistentQueueConfigs.entries()) {+ // Find stuck jobs for this specific queue+ const stuckJobs = await queueJobsDAL.findStuckJobsByQueue(queueName, config.stuckThresholdMs);++ if (stuckJobs.length > 0) {+ logger.info({ queueName, count: stuckJobs.length }, "Found stuck jobs for reconciliation");+ }++ // Process stuck jobs sequentially to avoid race conditions+ // eslint-disable-next-line no-await-in-loop+ for await (const job of stuckJobs) {+ await handleStuckJob(job, config);+ }+ }+ } catch (error) {+ logger.error(error, "Queue reconciliation failed");+ }+ };+const initialize = async () => {- logger.info("Initializing pg-queue...");- await pgBoss.start();+ const appCfg = getConfig();++ // Initialize internal recovery queue (BullMQ for distributed coordination)+ queueContainer[QueueName.QueueInternalRecovery] = new Queue(QueueName.QueueInternalRecovery, {+ prefix: isClusterMode ? `{${QueueName.QueueInternalRecovery}}` : undefined,+ connection+ });- pgBoss.on("error", (error) => {- logger.error(error, "pg-queue error");+ // Initialize internal reconciliation queue+ queueContainer[QueueName.QueueInternalReconciliation] = new Queue(QueueName.QueueInternalReconciliation, {+ prefix: isClusterMode ? `{${QueueName.QueueInternalReconciliation}}` : undefined,+ connection});++ if (appCfg.QUEUE_WORKERS_ENABLED) {+ // Start recovery worker+ workerContainer[QueueName.QueueInternalRecovery] = new Worker(+ QueueName.QueueInternalRecovery,+ async () => {+ await startupRecovery();+ },+ {+ prefix: isClusterMode ? `{${QueueName.QueueInternalRecovery}}` : undefined,+ connection+ }+ );++ // Start reconciliation worker+ workerContainer[QueueName.QueueInternalReconciliation] = new Worker(+ QueueName.QueueInternalReconciliation,+ async () => {+ await runReconciliation();+ },+ {+ prefix: isClusterMode ? `{${QueueName.QueueInternalReconciliation}}` : undefined,+ connection+ }+ );++ // Schedule startup recovery job (runs once after 2 minutes)+ await queueContainer[QueueName.QueueInternalRecovery].add(QueueJobs.QueueRecovery, undefined, {+ jobId: "queue-startup-recovery",+ delay: 2 * 60 * 1000,+ removeOnComplete: true,+ removeOnFail: true+ });++ // Schedule reconciliation job (runs every minute)+ await queueContainer[QueueName.QueueInternalReconciliation].add(QueueJobs.QueueReconciliation, undefined, {+ jobId: "queue-reconciliation-cron",+ repeat: {+ pattern: "* * * * *",+ key: "queue-reconciliation-cron"+ },+ removeOnComplete: true,+ removeOnFail: true+ });++ logger.info("Internal queue recovery and reconciliation workers started");+ }};const start: TQueueServiceFactory["start"] = (name, jobFn, queueSettings) => {@@ -614,7 +850,20 @@ export const queueServiceFactory = (connection});- if (persistence) {+ // Check if persistence is enabled (either true or an object with enabled: true)+ const isPersistenceEnabled = persistence === true || (typeof persistence === "object" && persistence.enabled);++ if (isPersistenceEnabled) {+ // Normalize persistence config (supports boolean or object)+ const persistenceConfig =+ typeof persistence === "object"+ ? {+ stuckThresholdMs: persistence.stuckThresholdMs ?? 5 * 60 * 1000,+ maxAttempts: 3+ }+ : { stuckThresholdMs: 5 * 60 * 1000, maxAttempts: 3 };++ persistentQueueConfigs.set(name, persistenceConfig);persistantQueues.add(name);workerContainer[name].on("active", (job) => {@@ -681,8 +930,13 @@ export const queueServiceFactory = (const queue: TQueueServiceFactory["queue"] = async (name, job, data, opts) => {const q = queueContainer[name];- const { jobId } = opts;- const finalOptions = { removeOnFail: true, removeOnComplete: true, ...opts };+ const { jobId, repeat } = opts;+ const finalOptions = {+ removeOnFail: true,+ removeOnComplete: true,+ ...opts,+ repeat: repeat ? { ...repeat, utc: true } : undefined+ };if (persistantQueues.has(name)) {await queueJobsDAL.create({@@ -699,11 +953,6 @@ export const queueServiceFactory = (await q.add(job, data, { ...opts, jobId });};- const unschedulePg: TQueueServiceFactory["unschedulePg"] = async (job) => {- await pgBoss.unschedule(job);- await pgBoss.deleteQueue(job);- };-const stopRepeatableJob: TQueueServiceFactory["stopRepeatableJob"] = async (name, job, repeatOpt, jobId) => {const q = queueContainer[name];if (q) {@@ -739,13 +988,15 @@ export const queueServiceFactory = (return q.removeRepeatableByKey(repeatJobKey);};- const stopJobByIdPg: TQueueServiceFactory["stopJobByIdPg"] = async (name, jobId) => {- await pgBoss.deleteJob(name, jobId);- };-const stopJobById: TQueueServiceFactory["stopJobById"] = async (name, jobId) => {const q = queueContainer[name];const job = await q.getJob(jobId);++ const isPersistantQueue = persistantQueues.has(name);+ if (isPersistantQueue) {+ await queueJobsDAL.delete({ jobId });+ }+return job?.remove().catch(() => undefined);};@@ -755,9 +1006,29 @@ export const queueServiceFactory = (};const shutdown: TQueueServiceFactory["shutdown"] = async () => {+ // Stop internal queue repeatable jobs+ try {+ const reconciliationQueue = queueContainer[QueueName.QueueInternalReconciliation];+ if (reconciliationQueue) {+ await reconciliationQueue.removeRepeatableByKey("queue-reconciliation-cron");+ }+ } catch {+ // Ignore errors during shutdown+ }+await Promise.all(Object.values(workerContainer).map((worker) => worker.close()));};+ /**+ * Update the heartbeat for a job to signal it's still alive+ * Long-running jobs should call this periodically to avoid being marked as stuck+ */+ const updateJobHeartbeat: TQueueServiceFactory["updateJobHeartbeat"] = async (queueName, jobId) => {+ if (!persistantQueues.has(queueName)) return;++ await queueJobsDAL.update({ queueName, jobId }, { lastHeartBeat: new Date() });+ };+return {initialize,start,@@ -769,9 +1040,8 @@ export const queueServiceFactory = (stopRepeatableJobByKey,clearQueue,stopJobById,- stopJobByIdPg,getRepeatableJobs,getDelayedJobs,- unschedulePg+ updateJobHeartbeat};};diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex a23d6c6097..1717e33823 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2685,16 +2685,14 @@ export const registerRoutes = async (await healthAlert.init();await pkiSyncCleanup.init();await pamAccountRotation.init();- await pamSessionExpirationService.init();+ pamSessionExpirationService.init();await dailyReminderQueueService.startDailyRemindersJob();await dailyReminderQueueService.startSecretReminderMigrationJob();await dailyExpiringPkiItemAlert.startSendingAlerts();await pkiSubscriberQueue.startDailyAutoRenewalJob();await pkiAlertV2Queue.init();await certificateV3Queue.init();- await certificateIssuanceQueue.initializeCertificateIssuanceQueue();await microsoftTeamsService.start();- await dynamicSecretQueueService.init();await eventBusService.init();// inject all servicesdiff --git a/backend/src/services/certificate-authority/certificate-authority-queue.ts b/backend/src/services/certificate-authority/certificate-authority-queue.tsindex 2059f00791..50e29b23a0 100644--- a/backend/src/services/certificate-authority/certificate-authority-queue.ts+++ b/backend/src/services/certificate-authority/certificate-authority-queue.ts@@ -133,7 +133,8 @@ export const certificateAuthorityQueueFactory = ({appCfg.NODE_ENV === "development"? secondsToMillis(rotationIntervalDays): daysToMillisecond(rotationIntervalDays),- immediately: true+ immediately: true,+ key: `ca-crl-rotation-${caId}`}});@@ -155,7 +156,8 @@ export const certificateAuthorityQueueFactory = ({{attempts: 1,removeOnComplete: true,- removeOnFail: true+ removeOnFail: true,+ jobId: `ca-order-certificate-for-subscriber-${subscriberId}`});};diff --git a/backend/src/services/external-migration/external-migration-queue.ts b/backend/src/services/external-migration/external-migration-queue.tsindex 770cbbe3a0..d1b0602536 100644--- a/backend/src/services/external-migration/external-migration-queue.ts+++ b/backend/src/services/external-migration/external-migration-queue.ts@@ -1,3 +1,5 @@+import { randomUUID } from "crypto";+import { SecretEncryptionAlgo, SecretKeyEncoding } from "@app/db/schemas";import { crypto } from "@app/lib/crypto/cryptography";import { logger } from "@app/lib/logger";@@ -87,7 +89,8 @@ export const externalMigrationQueueFactory = ({dto,{removeOnComplete: true,- removeOnFail: true+ removeOnFail: true,+ jobId: randomUUID()});};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.tsindex a592e92710..c3eebd6c39 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@@ -34,7 +34,7 @@ export const dailyExpiringPkiItemAlertQueueServiceFactory = ({await queueService.queue(QueueName.DailyExpiringPkiItemAlert, QueueJobs.DailyExpiringPkiItemAlert, undefined, {delay: 5000,jobId: QueueName.DailyExpiringPkiItemAlert,- repeat: { pattern: "0 0 * * *", utc: true }+ repeat: { pattern: "0 0 * * *", utc: true, key: QueueName.DailyExpiringPkiItemAlert }});};diff --git a/backend/src/services/pki-subscriber/pki-subscriber-queue.ts b/backend/src/services/pki-subscriber/pki-subscriber-queue.tsindex c9f0d77970..8c8ab27edd 100644--- a/backend/src/services/pki-subscriber/pki-subscriber-queue.ts+++ b/backend/src/services/pki-subscriber/pki-subscriber-queue.ts@@ -172,7 +172,7 @@ export const pkiSubscriberQueueServiceFactory = ({delay: 5000,jobId: QueueName.PkiSubscriber,// { pattern: "*/30 * * * * *", utc: true } // for testing- repeat: { pattern: "0 0 * * *", utc: true }+ repeat: { pattern: "0 0 * * *", utc: true, key: QueueName.PkiSubscriber }});};diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.tsindex c264176f91..fed29ceeb0 100644--- a/backend/src/services/pki-sync/pki-sync-queue.ts+++ b/backend/src/services/pki-sync/pki-sync-queue.ts@@ -3,6 +3,7 @@ import opentelemetry from "@opentelemetry/api";import * as x509 from "@peculiar/x509";import { AxiosError } from "axios";import { Job } from "bullmq";+import { randomUUID } from "crypto";import handlebars from "handlebars";import { TCertificates } from "@app/db/schemas";@@ -357,6 +358,7 @@ export const pkiSyncQueueFactory = ({type: "exponential",delay: 3000},+ jobId: randomUUID(),removeOnComplete: true,removeOnFail: true});@@ -368,6 +370,7 @@ export const pkiSyncQueueFactory = ({type: "exponential",delay: 3000},+ jobId: randomUUID(),removeOnComplete: true,removeOnFail: true});@@ -379,6 +382,7 @@ export const pkiSyncQueueFactory = ({type: "exponential",delay: 3000},+ jobId: randomUUID(),removeOnComplete: true,removeOnFail: true});diff --git a/backend/src/services/project/project-queue.ts b/backend/src/services/project/project-queue.tsindex 30ec6d29fb..ae5b1009ed 100644--- a/backend/src/services/project/project-queue.ts+++ b/backend/src/services/project/project-queue.ts@@ -1,4 +1,6 @@/* eslint-disable no-await-in-loop */+import { randomUUID } from "crypto";+import {AccessScope,IntegrationAuthsSchema,@@ -89,7 +91,8 @@ export const projectQueueFactory = ({removeOnComplete: true,removeOnFail: {count: 5 // keep the most recent jobs- }+ },+ jobId: randomUUID()});};diff --git a/backend/src/services/reminder/reminder-queue.ts b/backend/src/services/reminder/reminder-queue.tsindex c038734bd8..cb46378da7 100644--- a/backend/src/services/reminder/reminder-queue.ts+++ b/backend/src/services/reminder/reminder-queue.ts@@ -160,7 +160,7 @@ export const dailyReminderQueueServiceFactory = ({await queueService.queue(QueueName.DailyReminders, QueueJobs.DailyReminders, undefined, {delay: 5000,jobId: QueueName.DailyReminders,- repeat: { pattern: "0 0 * * *", utc: true }+ repeat: { pattern: "0 0 * * *", utc: true, key: QueueJobs.DailyReminders }});};diff --git a/backend/src/services/secret-sync/secret-sync-queue.ts b/backend/src/services/secret-sync/secret-sync-queue.tsindex fbfbdaeffd..80682eae13 100644--- a/backend/src/services/secret-sync/secret-sync-queue.ts+++ b/backend/src/services/secret-sync/secret-sync-queue.ts@@ -1,6 +1,7 @@import opentelemetry from "@opentelemetry/api";import { AxiosError } from "axios";import { Job } from "bullmq";+import { randomUUID } from "crypto";import { ProjectMembershipRole, SecretType } from "@app/db/schemas";import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";@@ -353,21 +354,25 @@ export const secretSyncQueueFactory = ({delay: 3000},removeOnComplete: true,- removeOnFail: true+ removeOnFail: true,+ jobId: randomUUID()});const queueSecretSyncImportSecretsById = async (payload: TQueueSecretSyncImportSecretsByIdDTO) =>queueService.queue(QueueName.AppConnectionSecretSync, QueueJobs.SecretSyncImportSecrets, payload, {attempts: 1,removeOnComplete: true,- removeOnFail: true+ removeOnFail: true,++ jobId: randomUUID()});const queueSecretSyncRemoveSecretsById = async (payload: TQueueSecretSyncRemoveSecretsByIdDTO) =>queueService.queue(QueueName.AppConnectionSecretSync, QueueJobs.SecretSyncRemoveSecrets, payload, {attempts: 1,removeOnComplete: true,- removeOnFail: true+ removeOnFail: true,+ jobId: randomUUID()});const $queueSendSecretSyncFailedNotifications = async (payload: TQueueSendSecretSyncActionFailedNotificationsDTO) => {diff --git a/backend/src/services/secret/secret-queue.ts b/backend/src/services/secret/secret-queue.tsindex effb577235..aa53ec8160 100644--- a/backend/src/services/secret/secret-queue.ts+++ b/backend/src/services/secret/secret-queue.ts@@ -1,6 +1,7 @@/* eslint-disable no-await-in-loop */import opentelemetry from "@opentelemetry/api";import { AxiosError } from "axios";+import { randomUUID } from "crypto";import { Knex } from "knex";import {@@ -537,7 +538,8 @@ export const secretQueueFactory = ({delay: 3000},removeOnComplete: true,- removeOnFail: true+ removeOnFail: true,+ jobId: randomUUID()});};@@ -549,7 +551,8 @@ export const secretQueueFactory = ({delay: 3000},removeOnComplete: true,- removeOnFail: true+ removeOnFail: true,+ jobId: randomUUID()});};@@ -1128,7 +1131,8 @@ export const secretQueueFactory = ({{ projectId },{removeOnComplete: true,- removeOnFail: true+ removeOnFail: true,+ jobId: randomUUID()});};diff --git a/backend/src/services/telemetry/telemetry-queue.ts b/backend/src/services/telemetry/telemetry-queue.tsindex cc386aebbf..35b855795a 100644--- a/backend/src/services/telemetry/telemetry-queue.ts+++ b/backend/src/services/telemetry/telemetry-queue.ts@@ -74,7 +74,7 @@ export const telemetryQueueServiceFactory = ({if (postHog) {await queueService.queue(QueueName.TelemetryInstanceStats, QueueJobs.TelemetryInstanceStats, undefined, {jobId: QueueName.TelemetryInstanceStats,- repeat: { pattern: "0 0 * * *", utc: true }+ repeat: { pattern: "0 0 * * *", utc: true, key: QueueName.TelemetryInstanceStats }});}};@@ -92,7 +92,7 @@ export const telemetryQueueServiceFactory = ({// Start aggregated events job (runs every five minutes)await queueService.queue(QueueName.TelemetryAggregatedEvents, QueueJobs.TelemetryAggregatedEvents, undefined, {jobId: QueueName.TelemetryAggregatedEvents,- repeat: { pattern: "*/5 * * * *", utc: true }+ repeat: { pattern: "*/5 * * * *", utc: true, key: QueueName.TelemetryAggregatedEvents }});}};