Skip to content

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

feat: moved all startPg to redis mode

=825bf41860a7
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.ts
index d62a1eeb2b..4a749223b5 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
@@ -39,7 +39,6 @@ export type TDynamicSecretLeaseQueueServiceFactory = {
setLeaseRevocation: (leaseId: string, dynamicSecretId: string, expiryAt: Date) => Promise<void>;
unsetLeaseRevocation: (leaseId: string) => Promise<void>;
queueFailedRevocation: (leaseId: string, dynamicSecretId: string) => Promise<void>;
- init: () => Promise<void>;
};
const MAX_REVOCATION_RETRY_COUNT = 10;
@@ -56,28 +55,34 @@ export const dynamicSecretLeaseQueueServiceFactory = ({
smtpService
}: TDynamicSecretLeaseQueueServiceFactoryDep): TDynamicSecretLeaseQueueServiceFactory => {
const pruneDynamicSecret = async (dynamicSecretCfgId: string) => {
- await queueService.queuePg<QueueName.DynamicSecretRevocation>(
+ await queueService.queue(
+ QueueName.DynamicSecretRevocation,
QueueJobs.DynamicSecretPruning,
{ dynamicSecretCfgId },
{
- singletonKey: dynamicSecretCfgId,
- retryLimit: 3,
- retryBackoff: true
+ jobId: `dynamic-secret-lease-pruning-${dynamicSecretCfgId}`,
+ attempts: 3,
+ backoff: {
+ type: "exponential",
+ delay: 1000 * 60 // 1 minute
+ }
}
);
};
const setLeaseRevocation = async (leaseId: string, dynamicSecretId: string, expiryAt: Date) => {
- await queueService.queuePg<QueueName.DynamicSecretRevocation>(
+ await queueService.queue(
+ QueueName.DynamicSecretRevocation,
QueueJobs.DynamicSecretRevocation,
{ leaseId, dynamicSecretId },
{
- id: leaseId,
- singletonKey: leaseId,
- startAfter: expiryAt,
- retryLimit: 3,
- retryBackoff: true,
- retentionDays: 2
+ jobId: leaseId,
+ delay: Number(expiryAt) - Date.now(),
+ attempts: 3,
+ backoff: {
+ type: "exponential",
+ delay: 1000 * 60 // 1 minute
+ }
}
);
};
@@ -92,14 +97,17 @@ export const dynamicSecretLeaseQueueServiceFactory = ({
const retryDelaySeconds = appConfig.isDevelopmentMode ? 1 : Math.floor(applyJitter(3_600_000 * 4) / 1000); // retry every 4 hours with 20% +- jitter (convert ms to seconds for pgboss)
- await queueService.queuePg<QueueName.DynamicSecretRevocation>(
+ await queueService.queue(
+ QueueName.DynamicSecretRevocation,
QueueJobs.DynamicSecretRevocation,
{ leaseId, isRetry: true, dynamicSecretId },
{
- singletonKey: `${leaseId}-retry`, // avoid conflicts with scheduled revocation
- retryDelay: retryDelaySeconds,
- retryLimit: MAX_REVOCATION_RETRY_COUNT, // we dont want it to ever hit the limit, we want the expireInHours to take effect.
- expireInHours: 23 // if we set it to 24 hours, pgboss will complain that the expireIn is too high
+ jobId: `${leaseId}-retry`, // avoid conflicts with scheduled revocation
+ attempts: MAX_REVOCATION_RETRY_COUNT,
+ backoff: {
+ type: "exponential",
+ delay: 1000 * retryDelaySeconds
+ }
}
);
};
@@ -319,9 +327,15 @@ export const dynamicSecretLeaseQueueServiceFactory = ({
}
};
- queueService.start(QueueName.DynamicSecretRevocation, async (job) => {
- await $dynamicSecretQueueJob(job.name, job.id as string, job.data);
- });
+ queueService.start(
+ QueueName.DynamicSecretRevocation,
+ async (job) => {
+ await $dynamicSecretQueueJob(job.name, job.id as string, job.data);
+ },
+ {
+ persistence: true
+ }
+ );
// we use redis for sending the email because:
// 1. we are insensitive to losing the jobs in queue in case of a disaster event
@@ -330,35 +344,10 @@ export const dynamicSecretLeaseQueueServiceFactory = ({
await $dynamicSecretLeaseRevocationFailedEmailJob(job.id as string, job.data);
});
- const init = async () => {
- await queueService.startPg<QueueName.DynamicSecretRevocation>(
- QueueJobs.DynamicSecretRevocation,
- async ([job]) => {
- await $dynamicSecretQueueJob(job.name, job.id, job.data, job.retryCount);
- },
- {
- workerCount: 10,
- pollingIntervalSeconds: 1
- }
- );
-
- await queueService.startPg<QueueName.DynamicSecretRevocation>(
- QueueJobs.DynamicSecretPruning,
- async ([job]) => {
- await $dynamicSecretQueueJob(job.name, job.id, job.data);
- },
- {
- workerCount: 1,
- pollingIntervalSeconds: 1
- }
- );
- };
-
return {
pruneDynamicSecret,
setLeaseRevocation,
unsetLeaseRevocation,
- queueFailedRevocation,
- init
+ queueFailedRevocation
};
};
diff --git a/backend/src/ee/services/pki-acme/pki-acme-queue.ts b/backend/src/ee/services/pki-acme/pki-acme-queue.ts
index 8511599812..8c47bcbb14 100644
--- a/backend/src/ee/services/pki-acme/pki-acme-queue.ts
+++ b/backend/src/ee/services/pki-acme/pki-acme-queue.ts
@@ -1,4 +1,5 @@
import { getConfig } from "@app/lib/config/env";
+import { secondsToMillis } from "@app/lib/dates";
import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
@@ -17,32 +18,25 @@ export const pkiAcmeQueueServiceFactory = async ({
}: TPkiAcmeQueueServiceFactoryDep) => {
const appCfg = getConfig();
+ // TODO(dq): verify persistance needed or not
// Initialize the worker to process challenge validation jobs
- await queueService.startPg<QueueName.PkiAcmeChallengeValidation>(
- QueueJobs.PkiAcmeChallengeValidation,
- async ([job]) => {
- const { challengeId } = job.data;
- const retryCount = job.retryCount || 0;
- try {
- logger.info({ challengeId, retryCount }, "Processing ACME challenge validation job");
- await acmeChallengeService.validateChallengeResponse(challengeId, retryCount);
- logger.info({ challengeId, retryCount }, "ACME challenge validation completed successfully");
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error);
- logger.error(
- error,
- `Failed to validate ACME challenge ${challengeId} (retryCount ${retryCount}): ${errorMessage}`
- );
- // Re-throw to let pg-boss handle retries with exponential backoff
- throw error;
- }
- },
- {
- batchSize: 1,
- workerCount: 2,
- pollingIntervalSeconds: 1
+ queueService.start(QueueName.PkiAcmeChallengeValidation, async (job) => {
+ const { challengeId } = job.data;
+ const retryCount = job.attemptsMade || 0;
+ try {
+ logger.info({ challengeId, retryCount }, "Processing ACME challenge validation job");
+ await acmeChallengeService.validateChallengeResponse(challengeId, retryCount);
+ logger.info({ challengeId, retryCount }, "ACME challenge validation completed successfully");
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ logger.error(
+ error,
+ `Failed to validate ACME challenge ${challengeId} (retryCount ${retryCount}): ${errorMessage}`
+ );
+ // Re-throw to let pg-boss handle retries with exponential backoff
+ throw error;
}
- );
+ });
const queueChallengeValidation = async (challengeId: string): Promise<void> => {
if (appCfg.isSecondaryInstance) {
@@ -50,13 +44,18 @@ export const pkiAcmeQueueServiceFactory = async ({
}
logger.info({ challengeId }, "Queueing ACME challenge validation");
- await queueService.queuePg(
+ await queueService.queue(
+ QueueName.PkiAcmeChallengeValidation,
QueueJobs.PkiAcmeChallengeValidation,
{ challengeId },
{
- retryLimit: 3,
- retryDelay: 30, // Base delay of 30 seconds
- retryBackoff: true // Exponential backoff: 30s, 60s, 120s
+ jobId: `pki-acme-challenege-${challengeId}`,
+ removeOnFail: true,
+ attempts: 3,
+ backoff: {
+ type: "exponential",
+ delay: secondsToMillis(30)
+ }
}
);
};
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-fns.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-fns.ts
index cd5c28a80a..73dedd0129 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-fns.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-fns.ts
@@ -3,6 +3,7 @@ import { AxiosError } from "axios";
import { getConfig } from "@app/lib/config/env";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
+import { TQueueOptions } from "@app/queue/queue-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { AUTH0_CLIENT_SECRET_ROTATION_LIST_OPTION } from "./auth0-client-secret";
@@ -152,14 +153,19 @@ export const decryptSecretRotationCredentials = async ({
export const getSecretRotationRotateSecretJobOptions = ({
id,
nextRotationAt
-}: Pick<TSecretRotationV2Raw, "id" | "nextRotationAt">) => {
+}: Pick<TSecretRotationV2Raw, "id" | "nextRotationAt">): TQueueOptions => {
const appCfg = getConfig();
return {
jobId: `secret-rotation-v2-rotate-${id}`,
- retryLimit: appCfg.isRotationDevelopmentMode ? 3 : 5,
- retryBackoff: true,
- startAfter: nextRotationAt ?? undefined
+ attempts: appCfg.isRotationDevelopmentMode ? 1 : 5,
+ removeOnFail: true,
+ removeOnComplete: true,
+ backoff: {
+ type: "exponential",
+ delay: 1000
+ },
+ delay: nextRotationAt ? Number(nextRotationAt) - Date.now() : undefined
};
};
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 3c902e1126..6c50da03f9 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
@@ -48,155 +48,138 @@ export const secretRotationV2QueueServiceFactory = async ({
logger.warn("Secret Rotation V2 is in development mode.");
}
- await queueService.startPg<QueueName.SecretRotationV2>(
- QueueJobs.SecretRotationV2QueueRotations,
- async () => {
- try {
- const rotateBy = getNextUtcRotationInterval();
-
- const currentTime = new Date();
+ queueService.start(
+ QueueName.SecretRotationV2,
+ async (job) => {
+ if (job.name === QueueJobs.SecretRotationV2QueueRotations) {
+ try {
+ const rotateBy = getNextUtcRotationInterval();
- const secretRotations = await secretRotationV2DAL.findSecretRotationsToQueue(rotateBy);
+ const currentTime = new Date();
- logger.info(
- `secretRotationV2Queue: Queue Rotations [currentTime=${currentTime.toISOString()}] [rotateBy=${rotateBy.toISOString()}] [count=${
- secretRotations.length
- }]`
- );
+ const secretRotations = await secretRotationV2DAL.findSecretRotationsToQueue(rotateBy);
- for await (const rotation of secretRotations) {
logger.info(
- `secretRotationV2Queue: Queue Rotation [rotationId=${rotation.id}] [lastRotatedAt=${new Date(
- rotation.lastRotatedAt
- ).toISOString()}] [rotateAt=${new Date(rotation.nextRotationAt!).toISOString()}]`
+ `secretRotationV2Queue: Queue Rotations [currentTime=${currentTime.toISOString()}] [rotateBy=${rotateBy.toISOString()}] [count=${
+ secretRotations.length
+ }]`
);
- const data = {
- rotationId: rotation.id,
- queuedAt: currentTime
- } as TSecretRotationRotateSecretsJobPayload;
-
- if (appCfg.isTestMode) {
- logger.warn("secretRotationV2Queue: Manually rotating secrets for test mode");
- await rotateSecretsFns({
- job: {
- id: uuidv4(),
- data,
- retryCount: 0,
- retryLimit: 0
- },
- secretRotationV2DAL,
- secretRotationV2Service
- });
- } else {
- await queueService.queuePg(
- QueueJobs.SecretRotationV2RotateSecrets,
- {
- rotationId: rotation.id,
- queuedAt: currentTime
- },
- getSecretRotationRotateSecretJobOptions(rotation)
+ for await (const rotation of secretRotations) {
+ logger.info(
+ `secretRotationV2Queue: Queue Rotation [rotationId=${rotation.id}] [lastRotatedAt=${new Date(
+ rotation.lastRotatedAt
+ ).toISOString()}] [rotateAt=${new Date(rotation.nextRotationAt!).toISOString()}]`
);
+
+ const data = {
+ rotationId: rotation.id,
+ queuedAt: currentTime
+ } as TSecretRotationRotateSecretsJobPayload;
+
+ if (appCfg.isTestMode) {
+ logger.warn("secretRotationV2Queue: Manually rotating secrets for test mode");
+ await rotateSecretsFns({
+ job: {
+ id: uuidv4(),
+ data,
+ retryCount: 0,
+ retryLimit: 0
+ },
+ secretRotationV2DAL,
+ secretRotationV2Service
+ });
+ } else {
+ await queueService.queue(
+ QueueName.SecretRotationV2,
+ QueueJobs.SecretRotationV2RotateSecrets,
+ {
+ rotationId: rotation.id,
+ queuedAt: currentTime
+ },
+ getSecretRotationRotateSecretJobOptions(rotation)
+ );
+ }
}
+ } catch (error) {
+ logger.error(error, "secretRotationV2Queue: Queue Rotations Error:");
+ throw error;
}
- } catch (error) {
- logger.error(error, "secretRotationV2Queue: Queue Rotations Error:");
- throw error;
- }
- },
- {
- batchSize: 1,
- workerCount: 1,
- pollingIntervalSeconds: appCfg.isRotationDevelopmentMode ? 0.5 : 30
- }
- );
+ } else if (job.name === QueueJobs.SecretRotationV2RotateSecrets) {
+ await rotateSecretsFns({
+ job: {
+ id: job.id || (job.data as TSecretRotationRotateSecretsJobPayload)?.rotationId,
+ retryCount: job.attemptsMade,
+ retryLimit: job.opts.attempts || 1,
+ data: job.data as TSecretRotationRotateSecretsJobPayload
+ },
+ secretRotationV2DAL,
+ secretRotationV2Service
+ });
+ } else if (job.name === QueueJobs.SecretRotationV2SendNotification) {
+ const { secretRotation } = job.data as TSecretRotationSendNotificationJobPayload;
+ try {
+ const {
+ name: rotationName,
+ type,
+ projectId,
+ lastRotationAttemptedAt,
+ folder,
+ environment,
+ id: rotationId
+ } = secretRotation;
+
+ logger.info(`secretRotationV2Queue: Sending Status Notification [rotationId=${rotationId}]`);
+
+ const projectMembers = await projectMembershipDAL.findAllProjectMembers(projectId);
+ const project = await projectDAL.findById(projectId);
+
+ const projectAdmins = projectMembers.filter((member) =>
+ member.roles.some((role) => role.role === ProjectMembershipRole.Admin)
+ );
- await queueService.startPg<QueueName.SecretRotationV2>(
- QueueJobs.SecretRotationV2RotateSecrets,
- async ([job]) => {
- await rotateSecretsFns({
- job: {
- ...job,
- data: job.data as TSecretRotationRotateSecretsJobPayload
- },
- secretRotationV2DAL,
- secretRotationV2Service
- });
- },
- {
- batchSize: 1,
- workerCount: 2,
- pollingIntervalSeconds: 0.5
- }
- );
+ const rotationType = SECRET_ROTATION_NAME_MAP[type as SecretRotation];
- await queueService.startPg<QueueName.SecretRotationV2>(
- QueueJobs.SecretRotationV2SendNotification,
- async ([job]) => {
- const { secretRotation } = job.data as TSecretRotationSendNotificationJobPayload;
- try {
- const {
- name: rotationName,
- type,
- projectId,
- lastRotationAttemptedAt,
- folder,
- environment,
- id: rotationId
- } = secretRotation;
-
- logger.info(`secretRotationV2Queue: Sending Status Notification [rotationId=${rotationId}]`);
-
- const projectMembers = await projectMembershipDAL.findAllProjectMembers(projectId);
- const project = await projectDAL.findById(projectId);
-
- const projectAdmins = projectMembers.filter((member) =>
- member.roles.some((role) => role.role === ProjectMembershipRole.Admin)
- );
-
- const rotationType = SECRET_ROTATION_NAME_MAP[type as SecretRotation];
-
- const rotationPath = `/organizations/${project.orgId}/projects/secret-management/${projectId}/secrets/${environment.slug}`;
-
- await notificationService.createUserNotifications(
- projectAdmins.map((admin) => ({
- userId: admin.userId,
- orgId: project.orgId,
- type: NotificationType.SECRET_ROTATION_FAILED,
- title: "Secret Rotation Failed",
- body: `Your **${rotationType}** rotation **${rotationName}** failed to rotate.`,
- link: rotationPath
- }))
- );
-
- await smtpService.sendMail({
- recipients: projectAdmins.map((member) => member.user.email!).filter(Boolean),
- template: SmtpTemplates.SecretRotationFailed,
- subjectLine: `Secret Rotation Failed`,
- substitutions: {
- rotationName,
- rotationType,
- content: `Your ${rotationType} Rotation failed to rotate during it's scheduled rotation. The last rotation attempt occurred at ${new Date(
- lastRotationAttemptedAt
- ).toISOString()}. Please check the rotation status in Infisical for more details.`,
- secretPath: folder.path,
- environment: environment.name,
- projectName: project.name,
- rotationUrl: encodeURI(`${appCfg.SITE_URL}${rotationPath}`)
- }
- });
- } catch (error) {
- logger.error(
- error,
- `secretRotationV2Queue: Failed to Send Status Notification [rotationId=${secretRotation.id}]`
- );
- throw error;
+ const rotationPath = `/organizations/${project.orgId}/projects/secret-management/${projectId}/secrets/${environment.slug}`;
+
+ await notificationService.createUserNotifications(
+ projectAdmins.map((admin) => ({
+ userId: admin.userId,
+ orgId: project.orgId,
+ type: NotificationType.SECRET_ROTATION_FAILED,
+ title: "Secret Rotation Failed",
+ body: `Your **${rotationType}** rotation **${rotationName}** failed to rotate.`,
+ link: rotationPath
+ }))
+ );
+
+ await smtpService.sendMail({
+ recipients: projectAdmins.map((member) => member.user.email!).filter(Boolean),
+ template: SmtpTemplates.SecretRotationFailed,
+ subjectLine: `Secret Rotation Failed`,
+ substitutions: {
+ rotationName,
+ rotationType,
+ content: `Your ${rotationType} Rotation failed to rotate during it's scheduled rotation. The last rotation attempt occurred at ${new Date(
+ lastRotationAttemptedAt
+ ).toISOString()}. Please check the rotation status in Infisical for more details.`,
+ secretPath: folder.path,
+ environment: environment.name,
+ projectName: project.name,
+ rotationUrl: encodeURI(`${appCfg.SITE_URL}${rotationPath}`)
+ }
+ });
+ } catch (error) {
+ logger.error(
+ error,
+ `secretRotationV2Queue: Failed to Send Status Notification [rotationId=${secretRotation.id}]`
+ );
+ throw error;
+ }
}
},
{
- batchSize: 1,
- workerCount: 2,
- pollingIntervalSeconds: 1
+ persistence: true
}
);
diff --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.ts
index 183961d0a3..14d94297a1 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
@@ -60,7 +60,7 @@ import { getConfig } from "@app/lib/config/env";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, InternalServerError, NotFoundError } from "@app/lib/errors";
import { OrderByDirection, OrgServiceActor } from "@app/lib/types";
-import { QueueJobs, TQueueServiceFactory } from "@app/queue";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";
import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
@@ -130,7 +130,7 @@ export type TSecretRotationV2ServiceFactoryDep = {
secretTagDAL: Pick<TSecretTagDALFactory, "saveTagsToSecretV2" | "deleteTagsToSecretV2" | "find">;
secretQueueService: Pick<TSecretQueueFactory, "syncSecrets" | "removeSecretReminder">;
snapshotService: Pick<TSecretSnapshotServiceFactory, "performSnapshot">;
- queueService: Pick<TQueueServiceFactory, "queuePg">;
+ queueService: Pick<TQueueServiceFactory, "queue">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;
folderCommitService: Pick<TFolderCommitServiceFactory, "createCommit">;
gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
@@ -193,13 +193,17 @@ export const secretRotationV2ServiceFactory = ({
const appCfg = getConfig();
if (!appCfg.isSmtpConfigured) return; // comment out if testing email sending
- await queueService.queuePg(
+ await queueService.queue(
+ QueueName.SecretRotationV2,
QueueJobs.SecretRotationV2SendNotification,
{ secretRotation },
{
jobId: `secret-rotation-v2-notification-${secretRotation.id}`,
- retryLimit: 5,
- retryBackoff: true
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 1000
+ }
}
);
};
@@ -768,7 +772,8 @@ export const secretRotationV2ServiceFactory = ({
// queue for rotation if adjusted time falls before next cron
if (nextRotationAt && nextRotationAt.getTime() < getNextUtcRotationInterval().getTime()) {
- await queueService.queuePg(
+ await queueService.queue(
+ QueueName.SecretRotationV2,
QueueJobs.SecretRotationV2RotateSecrets,
{ rotationId, queuedAt: new Date(), isManualRotation: true },
getSecretRotationRotateSecretJobOptions(updatedSecretRotation)
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts
index 357a88432c..d5f39e3d1c 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts
@@ -306,7 +306,7 @@ export type TSecretRotationRotateGeneratedCredentials = {
isManualRotation?: boolean;
};
-export type TSecretRotationRotateSecretsJobPayload = { rotationId: string; queuedAt: Date; isManualRotation: boolean };
+export type TSecretRotationRotateSecretsJobPayload = { rotationId: string; queuedAt: Date; isManualRotation?: boolean };
export type TSecretRotationSendNotificationJobPayload = {
secretRotation: TSecretRotationV2Raw;
diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-queue.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-queue.ts
index 2b6ab6a207..80ac42f7ee 100644
--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-queue.ts
+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-queue.ts
@@ -57,9 +57,9 @@ type TSecretRotationV2QueueServiceFactoryDep = {
notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
};
-export type TSecretScanningV2QueueServiceFactory = Awaited<ReturnType<typeof secretScanningV2QueueServiceFactory>>;
+export type TSecretScanningV2QueueServiceFactory = ReturnType<typeof secretScanningV2QueueServiceFactory>;
-export const secretScanningV2QueueServiceFactory = async ({
+export const secretScanningV2QueueServiceFactory = ({
queueService,
secretScanningV2DAL,
projectMembershipDAL,
@@ -125,11 +125,16 @@ export const secretScanningV2QueueServiceFactory = async ({
for (const scan of scans) {
// eslint-disable-next-line no-await-in-loop
- await queueService.queuePg(QueueJobs.SecretScanningV2FullScan, {
- scanId: scan.id,
- resourceId: scan.resourceId,
- dataSourceId: dataSource.id
- });
+ await queueService.queue(
+ QueueName.SecretScanningV2,
+ QueueJobs.SecretScanningV2FullScan,
+ {
+ scanId: scan.id,
+ resourceId: scan.resourceId,
+ dataSourceId: dataSource.id
+ },
+ { jobId: scan.id, removeOnFail: true }
+ );
}
});
} catch (error) {
@@ -141,125 +146,180 @@ export const secretScanningV2QueueServiceFactory = async ({
}
};
- await queueService.startPg<QueueName.SecretScanningV2>(
- QueueJobs.SecretScanningV2FullScan,
- async ([job]) => {
- const { scanId, resourceId, dataSourceId } = job.data as TQueueSecretScanningDataSourceFullScan;
- const { retryCount, retryLimit } = job;
+ const handleFullScan = async (job: {
+ id?: string;
+ data: TQueueSecretScanningDataSourceFullScan;
+ attemptsMade: number;
+ opts: { attempts?: number };
+ }) => {
+ const { scanId, resourceId, dataSourceId } = job.data;
+ const retryCount = job.attemptsMade;
+ const retryLimit = job.opts.attempts || 1;
- const logDetails = `[scanId=${scanId}] [resourceId=${resourceId}] [dataSourceId=${dataSourceId}] [jobId=${job.id}] retryCount=[${retryCount}/${retryLimit}]`;
+ const logDetails = `[scanId=${scanId}] [resourceId=${resourceId}] [dataSourceId=${dataSourceId}] [jobId=${job.id}] retryCount=[${retryCount}/${retryLimit}]`;
- const tempFolder = await createTempFolder();
+ const tempFolder = await createTempFolder();
- const dataSource = await secretScanningV2DAL.dataSources.findById(dataSourceId);
+ const dataSource = await secretScanningV2DAL.dataSources.findById(dataSourceId);
- if (!dataSource) throw new Error(`Data source with ID "${dataSourceId}" not found`);
+ if (!dataSource) throw new Error(`Data source with ID "${dataSourceId}" not found`);
- const resource = await secretScanningV2DAL.resources.findById(resourceId);
+ const resource = await secretScanningV2DAL.resources.findById(resourceId);
- if (!resource) throw new Error(`Resource with ID "${resourceId}" not found`);
+ if (!resource) throw new Error(`Resource with ID "${resourceId}" not found`);
- let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;
+ let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;
+ try {
try {
- try {
- lock = await keyStore.acquireLock(
- [KeyStorePrefixes.SecretScanningLock(dataSource.id, resource.externalId)],
- 60 * 1000 * 5
- );
- } catch (e) {
- throw new Error("Failed to acquire scanning lock.");
+ lock = await keyStore.acquireLock(
+ [KeyStorePrefixes.SecretScanningLock(dataSource.id, resource.externalId)],
+ 60 * 1000 * 5
+ );
+ } catch (e) {
+ throw new Error("Failed to acquire scanning lock.");
+ }
+
+ await secretScanningV2DAL.scans.update(
+ { id: scanId },
+ {
+ status: SecretScanningScanStatus.Scanning
}
+ );
- await secretScanningV2DAL.scans.update(
- { id: scanId },
- {
- status: SecretScanningScanStatus.Scanning
- }
- );
+ let connection: TAppConnection | null = null;
+ if (dataSource.connection) connection = await decryptAppConnection(dataSource.connection, kmsService);
- let connection: TAppConnection | null = null;
- if (dataSource.connection) connection = await decryptAppConnection(dataSource.connection, kmsService);
+ const factory = SECRET_SCANNING_FACTORY_MAP[dataSource.type as SecretScanningDataSource]({
+ kmsService,
+ appConnectionDAL
+ });
- const factory = SECRET_SCANNING_FACTORY_MAP[dataSource.type as SecretScanningDataSource]({
- kmsService,
- appConnectionDAL
- });
+ const findingsPath = join(tempFolder, "findings.json");
- const findingsPath = join(tempFolder, "findings.json");
+ const scanPath = await factory.getFullScanPath({
+ dataSource: {
+ ...dataSource,
+ connection
+ } as TSecretScanningDataSourceWithConnection,
+ resourceName: resource.name,
+ tempFolder
+ });
- const scanPath = await factory.getFullScanPath({
- dataSource: {
- ...dataSource,
- connection
- } as TSecretScanningDataSourceWithConnection,
- resourceName: resource.name,
- tempFolder
- });
+ const config = await secretScanningV2DAL.configs.findOne({
+ projectId: dataSource.projectId
+ });
- const config = await secretScanningV2DAL.configs.findOne({
- projectId: dataSource.projectId
- });
+ let configPath: string | undefined;
- let configPath: string | undefined;
+ if (config && config.content) {
+ configPath = join(tempFolder, "infisical-scan.toml");
+ await writeTextToFile(configPath, config.content);
+ }
- if (config && config.content) {
- configPath = join(tempFolder, "infisical-scan.toml");
- await writeTextToFile(configPath, config.content);
- }
+ let findingsPayload: TFindingsPayload;
+ switch (resource.type) {
+ case SecretScanningResource.Repository:
+ case SecretScanningResource.Project:
+ findingsPayload = await scanGitRepositoryAndGetFindings(scanPath, findingsPath, configPath);
+ break;
+ default:
+ throw new Error("Unhandled resource type");
+ }
- let findingsPayload: TFindingsPayload;
- switch (resource.type) {
- case SecretScanningResource.Repository:
- case SecretScanningResource.Project:
- findingsPayload = await scanGitRepositoryAndGetFindings(scanPath, findingsPath, configPath);
- break;
- default:
- throw new Error("Unhandled resource type");
+ const allFindings = await secretScanningV2DAL.findings.transaction(async (tx) => {
+ let findings: TSecretScanningFindings[] = [];
+ if (findingsPayload.length) {
+ findings = await secretScanningV2DAL.findings.upsert(
+ findingsPayload.map((finding) => ({
+ ...finding,
+ projectId: dataSource.projectId,
+ dataSourceName: dataSource.name,
+ dataSourceType: dataSource.type,
+ resourceName: resource.name,
+ resourceType: resource.type,
+ scanId
+ })),
+ ["projectId", "fingerprint"],
+ tx,
+ ["resourceName", "dataSourceName"]
+ );
}
- const allFindings = await secretScanningV2DAL.findings.transaction(async (tx) => {
- let findings: TSecretScanningFindings[] = [];
- if (findingsPayload.length) {
- findings = await secretScanningV2DAL.findings.upsert(
- findingsPayload.map((finding) => ({
- ...finding,
- projectId: dataSource.projectId,
- dataSourceName: dataSource.name,
- dataSourceType: dataSource.type,
- resourceName: resource.name,
- resourceType: resource.type,
- scanId
- })),
- ["projectId", "fingerprint"],
- tx,
- ["resourceName", "dataSourceName"]
- );
+ await secretScanningV2DAL.scans.update(
+ { id: scanId },
+ {
+ status: SecretScanningScanStatus.Completed,
+ statusMessage: null
}
+ );
- await secretScanningV2DAL.scans.update(
- { id: scanId },
- {
- status: SecretScanningScanStatus.Completed,
- statusMessage: null
- }
- );
-
- return findings;
- });
+ return findings;
+ });
- const newFindings = allFindings.filter((finding) => finding.scanId === scanId);
+ const newFindings = allFindings.filter((finding) => finding.scanId === scanId);
- if (newFindings.length) {
- await queueService.queuePg(QueueJobs.SecretScanningV2SendNotification, {
+ if (newFindings.length) {
+ await queueService.queue(
+ QueueName.SecretScanningV2,
+ QueueJobs.SecretScanningV2SendNotification,
+ {
status: SecretScanningScanStatus.Completed,
resourceName: resource.name,
isDiffScan: false,
dataSource,
numberOfSecrets: newFindings.length,
scanId
- });
+ },
+ { removeOnFail: true, jobId: `secret-scanning-notification-${scanId}` }
+ );
+ }
+
+ await auditLogService.createAuditLog({
+ projectId: dataSource.projectId,
+ actor: {
+ type: ActorType.PLATFORM,
+ metadata: {}
+ },
+ event: {
+ type: EventType.SECRET_SCANNING_DATA_SOURCE_SCAN,
+ metadata: {
+ dataSourceId: dataSource.id,
+ dataSourceType: dataSource.type,
+ resourceId: resource.id,
+ resourceType: resource.type,
+ scanId,
+ scanStatus: SecretScanningScanStatus.Completed,
+ scanType: SecretScanningScanType.FullScan,
+ numberOfSecretsDetected: findingsPayload.length
+ }
}
+ });
+
+ logger.info(`secretScanningV2Queue: Full Scan Complete ${logDetails} findings=[${findingsPayload.length}]`);
+ } catch (error) {
+ if (retryCount === retryLimit) {
+ const errorMessage = parseScanErrorMessage(error);
+
+ await secretScanningV2DAL.scans.update(
+ { id: scanId },
+ {
+ status: SecretScanningScanStatus.Failed,
+ statusMessage: errorMessage
+ }
+ );
+
+ await queueService.queue(
+ QueueName.SecretScanningV2,
+ QueueJobs.SecretScanningV2SendNotification,
+ {
+ status: SecretScanningScanStatus.Failed,
+ resourceName: resource.name,
+ dataSource,
+ errorMessage
+ },
+ { jobId: `secret-scanning-notification-${scanId}`, removeOnFail: true }
+ );
await auditLogService.createAuditLog({
projectId: dataSource.projectId,
@@ -275,67 +335,20 @@ export const secretScanningV2QueueServiceFactory = async ({
resourceId: resource.id,
resourceType: resource.type,
scanId,
- scanStatus: SecretScanningScanStatus.Completed,
- scanType: SecretScanningScanType.FullScan,
- numberOfSecretsDetected: findingsPayload.length
+ scanStatus: SecretScanningScanStatus.Failed,
+ scanType: SecretScanningScanType.FullScan
}
}
});
-
- logger.info(`secretScanningV2Queue: Full Scan Complete ${logDetails} findings=[${findingsPayload.length}]`);
- } catch (error) {
- if (retryCount === retryLimit) {
- const errorMessage = parseScanErrorMessage(error);
-
- await secretScanningV2DAL.scans.update(
- { id: scanId },
- {
- status: SecretScanningScanStatus.Failed,
- statusMessage: errorMessage
- }
- );
-
- await queueService.queuePg(QueueJobs.SecretScanningV2SendNotification, {
- status: SecretScanningScanStatus.Failed,
- resourceName: resource.name,
- dataSource,
- errorMessage
- });
-
- await auditLogService.createAuditLog({
- projectId: dataSource.projectId,
- actor: {
- type: ActorType.PLATFORM,
- metadata: {}
- },
- event: {
- type: EventType.SECRET_SCANNING_DATA_SOURCE_SCAN,
- metadata: {
- dataSourceId: dataSource.id,
- dataSourceType: dataSource.type,
- resourceId: resource.id,
- resourceType: resource.type,
- scanId,
- scanStatus: SecretScanningScanStatus.Failed,
- scanType: SecretScanningScanType.FullScan
- }
- }
- });
- }
-
- logger.error(error, `secretScanningV2Queue: Full Scan Failed ${logDetails}`);
- throw error;
- } finally {
- await deleteTempFolder(tempFolder);
- await lock?.release();
}
- },
- {
- batchSize: 1,
- workerCount: 2,
- pollingIntervalSeconds: 1
+
+ logger.error(error, `secretScanningV2Queue: Full Scan Failed ${logDetails}`);
+ throw error;
+ } finally {
+ await deleteTempFolder(tempFolder);
+ await lock?.release();
}
- );
+ };
const queueResourceDiffScan = async ({
payload,
@@ -376,13 +389,21 @@ export const secretScanningV2QueueServiceFactory = async ({
};
});
- await queueService.queuePg(QueueJobs.SecretScanningV2DiffScan, {
- payload,
- dataSourceId,
- dataSourceType,
- scanId,
- resourceId
- });
+ await queueService.queue(
+ QueueName.SecretScanningV2,
+ QueueJobs.SecretScanningV2DiffScan,
+ {
+ payload,
+ dataSourceId,
+ dataSourceType,
+ scanId,
+ resourceId
+ },
+ {
+ jobId: scanId,
+ removeOnFail: true
+ }
+ );
} catch (error) {
logger.error(
error,
@@ -391,96 +412,103 @@ export const secretScanningV2QueueServiceFactory = async ({
}
};
- await queueService.startPg<QueueName.SecretScanningV2>(
- QueueJobs.SecretScanningV2DiffScan,
- async ([job]) => {
- const { payload, dataSourceId, resourceId, scanId } = job.data as TQueueSecretScanningResourceDiffScan;
- const { retryCount, retryLimit } = job;
-
- const logDetails = `[dataSourceId=${dataSourceId}] [scanId=${scanId}] [resourceId=${resourceId}] [jobId=${job.id}] retryCount=[${retryCount}/${retryLimit}]`;
+ const handleDiffScan = async (job: {
+ id?: string;
+ data: TQueueSecretScanningResourceDiffScan;
+ attemptsMade: number;
+ opts: { attempts?: number };
+ }) => {
+ const { payload, dataSourceId, resourceId, scanId } = job.data;
+ const retryCount = job.attemptsMade;
+ const retryLimit = job.opts.attempts || 1;
- const dataSource = await secretScanningV2DAL.dataSources.findById(dataSourceId);
+ const logDetails = `[dataSourceId=${dataSourceId}] [scanId=${scanId}] [resourceId=${resourceId}] [jobId=${job.id}] retryCount=[${retryCount}/${retryLimit}]`;
- if (!dataSource) throw new Error(`Data source with ID "${dataSourceId}" not found`);
+ const dataSource = await secretScanningV2DAL.dataSources.findById(dataSourceId);
- const resource = await secretScanningV2DAL.resources.findById(resourceId);
+ if (!dataSource) throw new Error(`Data source with ID "${dataSourceId}" not found`);
- if (!resource) throw new Error(`Resource with ID "${resourceId}" not found`);
+ const resource = await secretScanningV2DAL.resources.findById(resourceId);
- const factory = SECRET_SCANNING_FACTORY_MAP[dataSource.type as SecretScanningDataSource]({
- kmsService,
- appConnectionDAL
- });
+ if (!resource) throw new Error(`Resource with ID "${resourceId}" not found`);
- const tempFolder = await createTempFolder();
+ const factory = SECRET_SCANNING_FACTORY_MAP[dataSource.type as SecretScanningDataSource]({
+ kmsService,
+ appConnectionDAL
+ });
- try {
- await secretScanningV2DAL.scans.update(
- { id: scanId },
- {
- status: SecretScanningScanStatus.Scanning
- }
- );
+ const tempFolder = await createTempFolder();
- let connection: TAppConnection | null = null;
- if (dataSource.connection) connection = await decryptAppConnection(dataSource.connection, kmsService);
+ try {
+ await secretScanningV2DAL.scans.update(
+ { id: scanId },
+ {
+ status: SecretScanningScanStatus.Scanning
+ }
+ );
- const config = await secretScanningV2DAL.configs.findOne({
- projectId: dataSource.projectId
- });
+ let connection: TAppConnection | null = null;
+ if (dataSource.connection) connection = await decryptAppConnection(dataSource.connection, kmsService);
- let configPath: string | undefined;
+ const config = await secretScanningV2DAL.configs.findOne({
+ projectId: dataSource.projectId
+ });
- if (config && config.content) {
- configPath = join(tempFolder, "infisical-scan.toml");
- await writeTextToFile(configPath, config.content);
- }
+ let configPath: string | undefined;
- const findingsPayload = await factory.getDiffScanFindingsPayload({
- dataSource: {
- ...dataSource,
- connection
- } as TSecretScanningDataSourceWithConnection,
- resourceName: resource.name,
- payload,
- configPath
- });
+ if (config && config.content) {
+ configPath = join(tempFolder, "infisical-scan.toml");
+ await writeTextToFile(configPath, config.content);
+ }
- const allFindings = await secretScanningV2DAL.findings.transaction(async (tx) => {
- let findings: TSecretScanningFindings[] = [];
+ const findingsPayload = await factory.getDiffScanFindingsPayload({
+ dataSource: {
+ ...dataSource,
+ connection
+ } as TSecretScanningDataSourceWithConnection,
+ resourceName: resource.name,
+ payload,
+ configPath
+ });
- if (findingsPayload.length) {
- findings = await secretScanningV2DAL.findings.upsert(
- findingsPayload.map((finding) => ({
- ...finding,
- projectId: dataSource.projectId,
- dataSourceName: dataSource.name,
- dataSourceType: dataSource.type,
- resourceName: resource.name,
- resourceType: resource.type,
- scanId
- })),
- ["projectId", "fingerprint"],
- tx,
- ["resourceName", "dataSourceName"]
- );
- }
+ const allFindings = await secretScanningV2DAL.findings.transaction(async (tx) => {
+ let findings: TSecretScanningFindings[] = [];
- await secretScanningV2DAL.scans.update(
- { id: scanId },
- {
- status: SecretScanningScanStatus.Completed
- }
+ if (findingsPayload.length) {
+ findings = await secretScanningV2DAL.findings.upsert(
+ findingsPayload.map((finding) => ({
+ ...finding,
+ projectId: dataSource.projectId,
+ dataSourceName: dataSource.name,
+ dataSourceType: dataSource.type,
+ resourceName: resource.name,
+ resourceType: resource.type,
+ scanId
+ })),
+ ["projectId", "fingerprint"],
+ tx,
+ ["resourceName", "dataSourceName"]
);
+ }
- return findings;
- });
+ await secretScanningV2DAL.scans.update(
+ { id: scanId },
+ {
+ status: SecretScanningScanStatus.Completed
+ }
+ );
+
+ return findings;
+ });
- const newFindings = allFindings.filter((finding) => finding.scanId === scanId);
+ const newFindings = allFindings.filter((finding) => finding.scanId === scanId);
- if (newFindings.length) {
- const finding = newFindings[0] as TSecretScanningFinding;
- await queueService.queuePg(QueueJobs.SecretScanningV2SendNotification, {
+ if (newFindings.length) {
+ const finding = newFindings[0] as TSecretScanningFinding;
+ await queueService.queue(
+ QueueName.SecretScanningV2,
+ QueueJobs.SecretScanningV2SendNotification,
+ {
status: SecretScanningScanStatus.Completed,
resourceName: resource.name,
isDiffScan: true,
@@ -489,8 +517,56 @@ export const secretScanningV2QueueServiceFactory = async ({
scanId,
authorName: finding?.details?.author,
authorEmail: finding?.details?.email
- });
+ },
+ { jobId: `secret-scanning-notification-${scanId}` }
+ );
+ }
+
+ await auditLogService.createAuditLog({
+ projectId: dataSource.projectId,
+ actor: {
+ type: ActorType.PLATFORM,
+ metadata: {}
+ },
+ event: {
+ type: EventType.SECRET_SCANNING_DATA_SOURCE_SCAN,
+ metadata: {
+ dataSourceId: dataSource.id,
+ dataSourceType: dataSource.type,
+ resourceId,
+ resourceType: resource.type,
+ scanId,
+ scanStatus: SecretScanningScanStatus.Completed,
+ scanType: SecretScanningScanType.DiffScan,
+ numberOfSecretsDetected: findingsPayload.length
+ }
}
+ });
+
+ logger.info(`secretScanningV2Queue: Diff Scan Complete ${logDetails}`);
+ } catch (error) {
+ if (retryCount === retryLimit) {
+ const errorMessage = parseScanErrorMessage(error);
+
+ await secretScanningV2DAL.scans.update(
+ { id: scanId },
+ {
+ status: SecretScanningScanStatus.Failed,
+ statusMessage: errorMessage
+ }
+ );
+
+ await queueService.queue(
+ QueueName.SecretScanningV2,
+ QueueJobs.SecretScanningV2SendNotification,
+ {
+ status: SecretScanningScanStatus.Failed,
+ resourceName: resource.name,
+ dataSource,
+ errorMessage
+ },
+ { jobId: `secret-scanning-notification-${scanId}` }
+ );
await auditLogService.createAuditLog({
projectId: dataSource.projectId,
@@ -503,169 +579,124 @@ export const secretScanningV2QueueServiceFactory = async ({
metadata: {
dataSourceId: dataSource.id,
dataSourceType: dataSource.type,
- resourceId,
+ resourceId: resource.id,
resourceType: resource.type,
scanId,
- scanStatus: SecretScanningScanStatus.Completed,
- scanType: SecretScanningScanType.DiffScan,
- numberOfSecretsDetected: findingsPayload.length
+ scanStatus: SecretScanningScanStatus.Failed,
+ scanType: SecretScanningScanType.DiffScan
}
}
});
-
- logger.info(`secretScanningV2Queue: Diff Scan Complete ${logDetails}`);
- } catch (error) {
- if (retryCount === retryLimit) {
- const errorMessage = parseScanErrorMessage(error);
-
- await secretScanningV2DAL.scans.update(
- { id: scanId },
- {
- status: SecretScanningScanStatus.Failed,
- statusMessage: errorMessage
- }
- );
-
- await queueService.queuePg(QueueJobs.SecretScanningV2SendNotification, {
- status: SecretScanningScanStatus.Failed,
- resourceName: resource.name,
- dataSource,
- errorMessage
- });
-
- await auditLogService.createAuditLog({
- projectId: dataSource.projectId,
- actor: {
- type: ActorType.PLATFORM,
- metadata: {}
- },
- event: {
- type: EventType.SECRET_SCANNING_DATA_SOURCE_SCAN,
- metadata: {
- dataSourceId: dataSource.id,
- dataSourceType: dataSource.type,
- resourceId: resource.id,
- resourceType: resource.type,
- scanId,
- scanStatus: SecretScanningScanStatus.Failed,
- scanType: SecretScanningScanType.DiffScan
- }
- }
- });
- }
-
- logger.error(error, `secretScanningV2Queue: Diff Scan Failed ${logDetails}`);
- throw error;
- } finally {
- await deleteTempFolder(tempFolder);
}
- },
- {
- batchSize: 1,
- workerCount: 2,
- pollingIntervalSeconds: 1
+
+ logger.error(error, `secretScanningV2Queue: Diff Scan Failed ${logDetails}`);
+ throw error;
+ } finally {
+ await deleteTempFolder(tempFolder);
}
- );
+ };
- await queueService.startPg<QueueName.SecretScanningV2>(
- QueueJobs.SecretScanningV2SendNotification,
- async ([job]) => {
- const { dataSource, resourceName, ...payload } = job.data as TQueueSecretScanningSendNotification;
+ const handleSendNotification = async (job: { data: TQueueSecretScanningSendNotification }) => {
+ const { dataSource, resourceName, ...payload } = job.data;
- const appCfg = getConfig();
+ const appCfg = getConfig();
- if (!appCfg.isSmtpConfigured) return;
+ if (!appCfg.isSmtpConfigured) return;
- try {
- const { projectId } = dataSource;
+ try {
+ const { projectId } = dataSource;
- logger.info(
- `secretScanningV2Queue: Sending Status Notification [dataSourceId=${dataSource.id}] [resourceName=${resourceName}] [status=${payload.status}]`
- );
+ logger.info(
+ `secretScanningV2Queue: Sending Status Notification [dataSourceId=${dataSource.id}] [resourceName=${resourceName}] [status=${payload.status}]`
+ );
- const projectMembers = await projectMembershipDAL.findAllProjectMembers(projectId);
- const project = await projectDAL.findById(projectId);
+ const projectMembers = await projectMembershipDAL.findAllProjectMembers(projectId);
+ const project = await projectDAL.findById(projectId);
- const recipients = projectMembers.filter((member) => {
- const isAdmin = member.roles.some((role) => role.role === ProjectMembershipRole.Admin);
- const isCompleted = payload.status === SecretScanningScanStatus.Completed;
- // We assume that the committer is one of the project members
- const isCommitter = isCompleted && payload.authorEmail === member.user.email;
- return isAdmin || isCommitter;
- });
+ const recipients = projectMembers.filter((member) => {
+ const isAdmin = member.roles.some((role) => role.role === ProjectMembershipRole.Admin);
+ const isCompleted = payload.status === SecretScanningScanStatus.Completed;
+ // We assume that the committer is one of the project members
+ const isCommitter = isCompleted && payload.authorEmail === member.user.email;
+ return isAdmin || isCommitter;
+ });
- const timestamp = new Date().toISOString();
+ const timestamp = new Date().toISOString();
- const subjectLine =
- payload.status === SecretScanningScanStatus.Completed
- ? "Incident Alert: Secret(s) Leaked"
- : `Secret Scanning Failed`;
-
- await notificationService.createUserNotifications(
- recipients.map((member) => ({
- userId: member.userId,
- orgId: project.orgId,
- type:
- payload.status === SecretScanningScanStatus.Completed
- ? NotificationType.SECRET_SCANNING_SECRETS_DETECTED
- : NotificationType.SECRET_SCANNING_SCAN_FAILED,
- title: subjectLine,
- body:
- payload.status === SecretScanningScanStatus.Completed
- ? `Uncovered **${payload.numberOfSecrets}** secret(s) ${payload.isDiffScan ? " from a recent commit to" : " in"} **${resourceName}**.`
- : `Encountered an error while attempting to scan the resource **${resourceName}**: ${payload.errorMessage}`,
- link:
- payload.status === SecretScanningScanStatus.Completed
- ? `/projects/secret-scanning/${projectId}/findings?search=scanId:${payload.scanId}`
- : `/projects/secret-scanning/${projectId}/data-sources/${dataSource.type}/${dataSource.id}`
- }))
- );
+ const subjectLine =
+ payload.status === SecretScanningScanStatus.Completed
+ ? "Incident Alert: Secret(s) Leaked"
+ : `Secret Scanning Failed`;
- await smtpService.sendMail({
- recipients: recipients.map((member) => member.user.email!).filter(Boolean),
- template:
+ await notificationService.createUserNotifications(
+ recipients.map((member) => ({
+ userId: member.userId,
+ orgId: project.orgId,
+ type:
payload.status === SecretScanningScanStatus.Completed
- ? SmtpTemplates.SecretScanningV2SecretsDetected
- : SmtpTemplates.SecretScanningV2ScanFailed,
- subjectLine,
- substitutions:
+ ? NotificationType.SECRET_SCANNING_SECRETS_DETECTED
+ : NotificationType.SECRET_SCANNING_SCAN_FAILED,
+ title: subjectLine,
+ body:
payload.status === SecretScanningScanStatus.Completed
- ? {
- authorName: payload.authorName,
- authorEmail: payload.authorEmail,
- resourceName,
- numberOfSecrets: payload.numberOfSecrets,
- isDiffScan: payload.isDiffScan,
- url: encodeURI(
- `${appCfg.SITE_URL}/organizations/${project.orgId}/projects/secret-scanning/${projectId}/findings?search=scanId:${payload.scanId}`
- ),
- timestamp
- }
- : {
- dataSourceName: dataSource.name,
- resourceName,
- projectName: project.name,
- timestamp,
- errorMessage: payload.errorMessage,
- url: encodeURI(
- `${appCfg.SITE_URL}/organizations/${project.orgId}/projects/secret-scanning/${projectId}/data-sources/${dataSource.type}/${dataSource.id}`
- )
- }
- });
- } catch (error) {
- logger.error(
- error,
- `secretScanningV2Queue: Failed to Send Status Notification [dataSourceId=${dataSource.id}] [resourceName=${resourceName}] [status=${payload.status}]`
- );
- throw error;
- }
- },
- {
- batchSize: 1,
- workerCount: 2,
- pollingIntervalSeconds: 1
+ ? `Uncovered **${payload.numberOfSecrets}** secret(s) ${payload.isDiffScan ? " from a recent commit to" : " in"} **${resourceName}**.`
+ : `Encountered an error while attempting to scan the resource **${resourceName}**: ${payload.errorMessage}`,
+ link:
+ payload.status === SecretScanningScanStatus.Completed
+ ? `/projects/secret-scanning/${projectId}/findings?search=scanId:${payload.scanId}`
+ : `/projects/secret-scanning/${projectId}/data-sources/${dataSource.type}/${dataSource.id}`
+ }))
+ );
+
+ await smtpService.sendMail({
+ recipients: recipients.map((member) => member.user.email!).filter(Boolean),
+ template:
+ payload.status === SecretScanningScanStatus.Completed
+ ? SmtpTemplates.SecretScanningV2SecretsDetected
+ : SmtpTemplates.SecretScanningV2ScanFailed,
+ subjectLine,
+ substitutions:
+ payload.status === SecretScanningScanStatus.Completed
+ ? {
+ authorName: payload.authorName,
+ authorEmail: payload.authorEmail,
+ resourceName,
+ numberOfSecrets: payload.numberOfSecrets,
+ isDiffScan: payload.isDiffScan,
+ url: encodeURI(
+ `${appCfg.SITE_URL}/organizations/${project.orgId}/projects/secret-scanning/${projectId}/findings?search=scanId:${payload.scanId}`
+ ),
+ timestamp
+ }
+ : {
+ dataSourceName: dataSource.name,
+ resourceName,
+ projectName: project.name,
+ timestamp,
+ errorMessage: payload.errorMessage,
+ url: encodeURI(
+ `${appCfg.SITE_URL}/organizations/${project.orgId}/projects/secret-scanning/${projectId}/data-sources/${dataSource.type}/${dataSource.id}`
+ )
+ }
+ });
+ } catch (error) {
+ logger.error(
+ error,
+ `secretScanningV2Queue: Failed to Send Status Notification [dataSourceId=${dataSource.id}] [resourceName=${resourceName}] [status=${payload.status}]`
+ );
+ throw error;
+ }
+ };
+
+ queueService.start(QueueName.SecretScanningV2, async (job) => {
+ if (job.name === QueueJobs.SecretScanningV2FullScan) {
+ await handleFullScan(job as Parameters<typeof handleFullScan>[0]);
+ } else if (job.name === QueueJobs.SecretScanningV2DiffScan) {
+ await handleDiffScan(job as Parameters<typeof handleDiffScan>[0]);
+ } else if (job.name === QueueJobs.SecretScanningV2SendNotification) {
+ await handleSendNotification(job as Parameters<typeof handleSendNotification>[0]);
}
- );
+ });
return {
queueDataSourceFullScan,
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 7e2ff184ce..255632ee61 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -1,4 +1,4 @@
-import { Job, JobsOptions, Queue, QueueOptions, RepeatOptions, Worker, WorkerListener } from "bullmq";
+import { Job, Queue, QueueOptions, RepeatOptions, Worker, WorkerListener } from "bullmq";
import PgBoss, { WorkOptions } from "pg-boss";
import { SecretEncryptionAlgo, SecretKeyEncoding } from "@app/db/schemas";
@@ -156,6 +156,18 @@ export enum QueueJobs {
PkiAcmeChallengeValidation = "pki-acme-challenge-validation"
}
+export type TQueueOptions = {
+ jobId: string;
+ removeOnComplete?: boolean | { count: number };
+ removeOnFail?: boolean | { count: number };
+ attempts?: number;
+ delay?: number;
+ backoff?: {
+ type: "exponential" | "fixed";
+ delay: number;
+ };
+};
+
export type TQueueJobTypes = {
[QueueName.SecretReminder]: {
payload: {
@@ -471,13 +483,6 @@ export type TQueueServiceFactory = {
jobFn: (job: Job<TQueueJobTypes[T]["payload"], void, TQueueJobTypes[T]["name"]>, token?: string) => Promise<void>,
queueSettings?: Omit<QueueOptions, "connection"> & { persistence?: boolean }
) => void;
- startPg: <T extends QueueName>(
- jobName: QueueJobs,
- jobsFn: (jobs: PgBoss.JobWithMetadata<TQueueJobTypes[T]["payload"]>[]) => Promise<void>,
- options: WorkOptions & {
- workerCount: number;
- }
- ) => Promise<void>;
listen: <
T extends QueueName,
U extends keyof WorkerListener<TQueueJobTypes[T]["payload"], void, TQueueJobTypes[T]["name"]>
@@ -490,14 +495,7 @@ export type TQueueServiceFactory = {
name: T,
job: TQueueJobTypes[T]["name"],
data: TQueueJobTypes[T]["payload"],
- opts: JobsOptions & {
- jobId: string;
- }
- ) => Promise<void>;
- queuePg: <T extends QueueName>(
- job: TQueueJobTypes[T]["name"],
- data: TQueueJobTypes[T]["payload"],
- opts?: PgBoss.SendOptions & { jobId?: string }
+ opts: TQueueOptions
) => Promise<void>;
schedulePg: <T extends QueueName>(
job: TQueueJobTypes[T]["name"],
@@ -719,6 +717,7 @@ export const queueServiceFactory = (
const q = queueContainer[name];
const { jobId } = opts;
+ const finalOptions = { removeOnFail: true, removeOnComplete: true, ...opts };
if (persistantQueues.has(name)) {
await queueJobsDAL.create({
@@ -727,6 +726,7 @@ export const queueServiceFactory = (
queueJobName: job,
jobId,
queueData: data,
+ queueOptions: finalOptions,
status: PersistanceQueueStatus.Pending
});
}
@@ -734,18 +734,6 @@ export const queueServiceFactory = (
await q.add(job, data, { ...opts, jobId });
};
- const queuePg = async <T extends QueueName>(
- job: TQueueJobTypes[T]["name"],
- data: TQueueJobTypes[T]["payload"],
- opts?: PgBoss.SendOptions & { jobId?: string }
- ) => {
- await pgBoss.send({
- name: job,
- data,
- options: opts
- });
- };
-
const schedulePg: TQueueServiceFactory["schedulePg"] = async (job, cron, data, opts) => {
await pgBoss.schedule(job, cron, data, opts);
};
@@ -818,8 +806,6 @@ export const queueServiceFactory = (
stopJobByIdPg,
getRepeatableJobs,
getDelayedJobs,
- startPg,
- queuePg,
schedulePg
};
};
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 90b39a3603..a23d6c6097 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -758,7 +758,7 @@ export const registerRoutes = async (
auditLogStreamService
});
- const notificationQueue = await notificationQueueServiceFactory({
+ const notificationQueue = notificationQueueServiceFactory({
userNotificationDAL,
queueService
});
@@ -2509,7 +2509,7 @@ export const registerRoutes = async (
notificationService
});
- const secretScanningV2Queue = await secretScanningV2QueueServiceFactory({
+ const secretScanningV2Queue = secretScanningV2QueueServiceFactory({
auditLogService,
secretScanningV2DAL,
queueService,
diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
index 6ff27378c1..614c2f71fe 100644
--- a/backend/src/services/certificate-authority/certificate-issuance-queue.ts
+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
@@ -3,7 +3,7 @@ import acme from "acme-client";
import { crypto } from "@app/lib/crypto/cryptography";
import { NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
-import { QueueJobs, TQueueServiceFactory } from "@app/queue";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { CertExtendedKeyUsage, CertKeyUsage } from "@app/services/certificate/certificate-types";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
@@ -184,10 +184,13 @@ export const certificateIssuanceQueueFactory = ({
csr
};
- await queueService.queuePg(QueueJobs.CaIssueCertificateFromProfile, jobData, {
- retryLimit: 3,
- retryDelay: 5,
- retryBackoff: true
+ await queueService.queue(QueueName.CertificateIssuance, QueueJobs.CaIssueCertificateFromProfile, jobData, {
+ jobId: `certificate-issuance-${certificateId}`,
+ attempts: 3,
+ backoff: {
+ type: "exponential",
+ delay: 5000
+ }
});
};
@@ -382,26 +385,12 @@ export const certificateIssuanceQueueFactory = ({
}
};
- const initializeCertificateIssuanceQueue = async () => {
- await queueService.startPg(
- QueueJobs.CaIssueCertificateFromProfile,
- async ([job]) => {
- const data = job.data as TIssueCertificateFromProfileJobData;
- await processCertificateIssuanceJobs(data);
- },
- {
- workerCount: 2,
- batchSize: 1,
- pollingIntervalSeconds: 1
- }
- );
-
- logger.info("Certificate issuance queue worker initialized successfully");
- };
+ queueService.start(QueueName.CertificateIssuance, async (job) => {
+ await processCertificateIssuanceJobs(job.data);
+ });
return {
queueCertificateIssuance,
- initializeCertificateIssuanceQueue,
processCertificateIssuanceJobs
};
};
diff --git a/backend/src/services/certificate-v3/certificate-v3-queue.ts b/backend/src/services/certificate-v3/certificate-v3-queue.ts
index db7349cd51..f2f059d84d 100644
--- a/backend/src/services/certificate-v3/certificate-v3-queue.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-queue.ts
@@ -36,116 +36,108 @@ export const certificateV3QueueServiceFactory = ({
QueueName.CertificateV3AutoRenewal
);
- await queueService.startPg<QueueName.CertificateV3AutoRenewal>(
- QueueJobs.CertificateV3DailyAutoRenewal,
- 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;
- }
+ 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})`
- );
-
- 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;
}
- 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;
+ offset += QUEUE_BATCH_SIZE;
}
- },
- {
- batchSize: 1,
- workerCount: 1,
- pollingIntervalSeconds: 60
+
+ 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.schedulePg(
QueueJobs.CertificateV3DailyAutoRenewal,
diff --git a/backend/src/services/health-alert/health-alert-queue.ts b/backend/src/services/health-alert/health-alert-queue.ts
index 1d65d0f4d9..fbc79d5ee2 100644
--- a/backend/src/services/health-alert/health-alert-queue.ts
+++ b/backend/src/services/health-alert/health-alert-queue.ts
@@ -31,8 +31,8 @@ export const healthAlertServiceFactory = ({
QueueName.HealthAlert // job id
);
- await queueService.startPg<QueueName.HealthAlert>(
- QueueJobs.HealthAlert,
+ queueService.start(
+ QueueName.HealthAlert,
async () => {
try {
logger.info(`${QueueName.HealthAlert}: health check alert task started`);
@@ -45,9 +45,7 @@ export const healthAlertServiceFactory = ({
}
},
{
- batchSize: 1,
- workerCount: 1,
- pollingIntervalSeconds: 60
+ persistence: true
}
);
diff --git a/backend/src/services/notification/notification-queue.ts b/backend/src/services/notification/notification-queue.ts
index e5d89c83bf..4ce7c62ac0 100644
--- a/backend/src/services/notification/notification-queue.ts
+++ b/backend/src/services/notification/notification-queue.ts
@@ -1,4 +1,6 @@
-import { QueueJobs, TQueueServiceFactory } from "@app/queue";
+import { randomUUID } from "crypto";
+
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TCreateUserNotificationDTO } from "./notification-types";
import { TUserNotificationDALFactory } from "./user-notification-dal";
@@ -12,26 +14,23 @@ export type TNotificationQueueServiceFactory = {
pushUserNotifications: (data: TCreateUserNotificationDTO[]) => Promise<void>;
};
-export const notificationQueueServiceFactory = async ({
+export const notificationQueueServiceFactory = ({
userNotificationDAL,
queueService
-}: TNotificationQueueServiceFactoryDep): Promise<TNotificationQueueServiceFactory> => {
+}: TNotificationQueueServiceFactoryDep): TNotificationQueueServiceFactory => {
const pushUserNotifications = async (data: TCreateUserNotificationDTO[]) => {
- await queueService.queuePg(QueueJobs.UserNotification, { notifications: data });
+ await queueService.queue(
+ QueueName.UserNotification,
+ QueueJobs.UserNotification,
+ { notifications: data },
+ { jobId: randomUUID() }
+ );
};
- await queueService.startPg(
- QueueJobs.UserNotification,
- async ([job]) => {
- const { notifications } = job.data as { notifications: TCreateUserNotificationDTO[] };
- await userNotificationDAL.batchInsert(notifications);
- },
- {
- batchSize: 1,
- workerCount: 2,
- pollingIntervalSeconds: 1
- }
- );
+ queueService.start(QueueName.UserNotification, async (job) => {
+ const { notifications } = job.data as { notifications: TCreateUserNotificationDTO[] };
+ await userNotificationDAL.batchInsert(notifications);
+ });
return {
pushUserNotifications
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 6ed78f665a..2be94b11c5 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
@@ -28,8 +28,8 @@ export const pamAccountRotationServiceFactory = ({
QueueName.PamAccountRotation // job id
);
- await queueService.startPg<QueueName.PamAccountRotation>(
- QueueJobs.PamAccountRotation,
+ queueService.start(
+ QueueName.PamAccountRotation,
async () => {
try {
logger.info(`${QueueName.PamAccountRotation}: pam account rotation task started`);
@@ -41,9 +41,7 @@ export const pamAccountRotationServiceFactory = ({
}
},
{
- batchSize: 1,
- workerCount: 1,
- pollingIntervalSeconds: 5 * 60
+ persistence: true
}
);
diff --git a/backend/src/services/pam-session-expiration/pam-session-expiration-queue.ts b/backend/src/services/pam-session-expiration/pam-session-expiration-queue.ts
index f14da58f0a..3c90ef5974 100644
--- a/backend/src/services/pam-session-expiration/pam-session-expiration-queue.ts
+++ b/backend/src/services/pam-session-expiration/pam-session-expiration-queue.ts
@@ -16,39 +16,33 @@ export const pamSessionExpirationServiceFactory = ({
}: TPamSessionExpirationServiceFactoryDep) => {
const appCfg = getConfig();
- const init = async () => {
+ const init = () => {
if (appCfg.isSecondaryInstance) {
return;
}
- await queueService.startPg<QueueName.PamSessionExpiration>(
- QueueJobs.PamSessionExpiration,
- async (jobs) => {
- await Promise.all(
- jobs.map(async (job) => {
- const { sessionId } = job.data;
- try {
- logger.info({ sessionId }, `${QueueName.PamSessionExpiration}: expiring session`);
- const updated = await pamSessionDAL.expireSessionById(sessionId);
- if (updated > 0) {
- logger.info({ sessionId }, `${QueueName.PamSessionExpiration}: session expired successfully`);
- } else {
- logger.info(
- { sessionId },
- `${QueueName.PamSessionExpiration}: session not expired (already ended or not found)`
- );
- }
- } catch (error) {
- logger.error(error, `${QueueName.PamSessionExpiration}: failed to expire session ${sessionId}`);
- throw error;
- }
- })
- );
+ queueService.start(
+ QueueName.PamSessionExpiration,
+ async (job) => {
+ const { sessionId } = job.data;
+ try {
+ logger.info({ sessionId }, `${QueueName.PamSessionExpiration}: expiring session`);
+ const updated = await pamSessionDAL.expireSessionById(sessionId);
+ if (updated > 0) {
+ logger.info({ sessionId }, `${QueueName.PamSessionExpiration}: session expired successfully`);
+ } else {
+ logger.info(
+ { sessionId },
+ `${QueueName.PamSessionExpiration}: session not expired (already ended or not found)`
+ );
+ }
+ } catch (error) {
+ logger.error(error, `${QueueName.PamSessionExpiration}: failed to expire session ${sessionId}`);
+ throw error;
+ }
},
{
- batchSize: 1,
- workerCount: 1,
- pollingIntervalSeconds: 30
+ persistence: true
}
);
};
@@ -59,12 +53,13 @@ export const pamSessionExpirationServiceFactory = ({
const delayMs = Math.max(0, expiresAt.getTime() - now.getTime());
const startAfter = new Date(now.getTime() + delayMs);
- await queueService.queuePg<QueueName.PamSessionExpiration>(
+ await queueService.queue(
+ QueueName.PamSessionExpiration,
QueueJobs.PamSessionExpiration,
{ sessionId },
{
- startAfter,
- singletonKey: `pam-session-expiration-${sessionId}`
+ jobId: `pam-session-expiration-${sessionId}`,
+ delay: delayMs
}
);
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 81b4bc9ef2..a281b30f62 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
@@ -192,24 +192,16 @@ export const pkiAlertV2QueueServiceFactory = ({
return;
}
- await queueService.startPg<QueueName.DailyPkiAlertV2Processing>(
- QueueJobs.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;
- }
- },
- {
- batchSize: 1,
- workerCount: 1,
- pollingIntervalSeconds: 60
+ 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;
}
- );
+ });
await queueService.schedulePg(QueueJobs.DailyPkiAlertV2Processing, "0 0 * * *", undefined, { tz: "UTC" });
};
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 f6fd32e33c..44d0ecfae2 100644
--- a/backend/src/services/pki-sync/pki-sync-cleanup-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-cleanup-queue.ts
@@ -65,24 +65,16 @@ export const pkiSyncCleanupQueueServiceFactory = ({
QueueName.PkiSyncCleanup // just a job id
);
- await queueService.startPg<QueueName.PkiSyncCleanup>(
- QueueJobs.PkiSyncCleanup,
- async () => {
- try {
- logger.info(`${QueueName.PkiSyncCleanup}: queue task started`);
- await syncExpiredCertificatesForPkiSyncs();
- logger.info(`${QueueName.PkiSyncCleanup}: queue task completed`);
- } catch (error) {
- logger.error(error, `${QueueName.PkiSyncCleanup}: PKI sync cleanup failed`);
- throw error;
- }
- },
- {
- batchSize: 1,
- workerCount: 1,
- pollingIntervalSeconds: 120
+ queueService.start(QueueName.PkiSyncCleanup, async () => {
+ try {
+ logger.info(`${QueueName.PkiSyncCleanup}: queue 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.schedulePg(QueueJobs.PkiSyncCleanup, "0 0 * * *", undefined, { tz: "UTC" });
};
diff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
index c6e350a3e7..1f8dac6724 100644
--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
@@ -83,41 +83,34 @@ export const dailyResourceCleanUpQueueServiceFactory = ({
QueueName.DailyResourceCleanUp // just a job id
);
- await queueService.startPg<QueueName.DailyResourceCleanUp>(
- QueueJobs.DailyResourceCleanUp,
- async () => {
- try {
- logger.info(`${QueueName.DailyResourceCleanUp}: queue task started`);
- await identityUniversalAuthClientSecretDAL.removeExpiredClientSecrets();
- await secretSharingDAL.pruneExpiredSharedSecrets();
- await secretSharingDAL.pruneExpiredSecretRequests();
- await snapshotDAL.pruneExcessSnapshots();
- await secretVersionDAL.pruneExcessVersions();
- await secretVersionV2DAL.pruneExcessVersions();
- await secretFolderVersionDAL.pruneExcessVersions();
- await serviceTokenService.notifyExpiringTokens();
- await scimService.notifyExpiringTokens();
- await orgService.notifyInvitedUsers();
- await auditLogDAL.pruneAuditLog();
- await userNotificationDAL.pruneNotifications();
- await keyValueStoreDAL.pruneExpiredKeys();
- const expiredApprovalRequestIds = await approvalRequestDAL.markExpiredRequests();
- if (expiredApprovalRequestIds.length > 0) {
- await certificateRequestDAL.markExpiredApprovalRequests(expiredApprovalRequestIds);
- }
- await approvalRequestGrantsDAL.markExpiredGrants();
- logger.info(`${QueueName.DailyResourceCleanUp}: queue task completed`);
- } catch (error) {
- logger.error(error, `${QueueName.DailyResourceCleanUp}: resource cleanup failed`);
- throw error;
+ queueService.start(QueueName.DailyResourceCleanUp, async () => {
+ try {
+ logger.info(`${QueueName.DailyResourceCleanUp}: queue task started`);
+ await identityUniversalAuthClientSecretDAL.removeExpiredClientSecrets();
+ await secretSharingDAL.pruneExpiredSharedSecrets();
+ await secretSharingDAL.pruneExpiredSecretRequests();
+ await snapshotDAL.pruneExcessSnapshots();
+ await secretVersionDAL.pruneExcessVersions();
+ await secretVersionV2DAL.pruneExcessVersions();
+ await secretFolderVersionDAL.pruneExcessVersions();
+ await serviceTokenService.notifyExpiringTokens();
+ await scimService.notifyExpiringTokens();
+ await orgService.notifyInvitedUsers();
+ await auditLogDAL.pruneAuditLog();
+ await userNotificationDAL.pruneNotifications();
+ await keyValueStoreDAL.pruneExpiredKeys();
+ const expiredApprovalRequestIds = await approvalRequestDAL.markExpiredRequests();
+ if (expiredApprovalRequestIds.length > 0) {
+ await certificateRequestDAL.markExpiredApprovalRequests(expiredApprovalRequestIds);
}
- },
- {
- batchSize: 1,
- workerCount: 1,
- pollingIntervalSeconds: 1
+ await approvalRequestGrantsDAL.markExpiredGrants();
+ logger.info(`${QueueName.DailyResourceCleanUp}: queue task completed`);
+ } catch (error) {
+ logger.error(error, `${QueueName.DailyResourceCleanUp}: resource cleanup failed`);
+ throw error;
}
- );
+ });
+
await queueService.schedulePg(
QueueJobs.DailyResourceCleanUp,
appCfg.isDailyResourceCleanUpDevelopmentMode ? "*/5 * * * *" : "0 0 * * *",
@@ -133,8 +126,8 @@ export const dailyResourceCleanUpQueueServiceFactory = ({
QueueName.FrequentResourceCleanUp // just a job id
);
- await queueService.startPg<QueueName.FrequentResourceCleanUp>(
- QueueJobs.FrequentResourceCleanUp,
+ queueService.start(
+ QueueName.FrequentResourceCleanUp,
async () => {
try {
logger.info(`${QueueName.FrequentResourceCleanUp}: queue task started`);
@@ -146,9 +139,7 @@ export const dailyResourceCleanUpQueueServiceFactory = ({
}
},
{
- batchSize: 1,
- workerCount: 1,
- pollingIntervalSeconds: 1
+ persistence: true
}
);
await queueService.schedulePg(