Skip to content

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

refactor(alerts): move the orphaned-alert lookup into the alert module

Calvin1bb4bf708424
diff --git a/backend/src/services/alert/alert-dal.ts b/backend/src/services/alert/alert-dal.ts
index 5c471dc96a..d579cc8249 100644
--- a/backend/src/services/alert/alert-dal.ts
+++ b/backend/src/services/alert/alert-dal.ts
@@ -284,8 +284,37 @@ export const alertDALFactory = (db: TDbClient) => {
}
};
+ // The resource ids of alerts whose resource row no longer exists in `resourceTable`. alerts.resourceId has
+ // no foreign key, so a resource deleted by a cascade (eg a folder deletion removing its secrets) leaves its
+ // alerts behind; this is how its owner finds them.
+ const findOrphanedResourceIds = async (
+ { resourceType, resourceTable, limit }: { resourceType: string; resourceTable: TableName; limit: number },
+ tx?: Knex
+ ): Promise<string[]> => {
+ try {
+ const rows = (await (tx || db.replicaNode())(TableName.Alert)
+ .where(`${TableName.Alert}.resourceType`, resourceType)
+ .whereNotNull(`${TableName.Alert}.resourceId`)
+ .whereNotExists((qb) => {
+ void qb
+ .select(db.raw("1"))
+ .from(resourceTable)
+ // The CASE keeps a non-uuid resourceId from failing the cast for the whole query.
+ .whereRaw(
+ `"${resourceTable}"."id" = CASE WHEN "${TableName.Alert}"."resourceId" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN "${TableName.Alert}"."resourceId"::uuid END`
+ );
+ })
+ .limit(limit)
+ .select(`${TableName.Alert}.resourceId`)) as { resourceId: string }[];
+ return rows.map((row) => row.resourceId);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindOrphanedResourceIds" });
+ }
+ };
+
return {
...alertOrm,
+ findOrphanedResourceIds,
findWithChannelsForResources,
findRecipientsForResources,
findEnabledByResourceType,
diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.ts
index 7229adccca..fe0a61acc3 100644
--- a/backend/src/services/alert/alert-service.ts
+++ b/backend/src/services/alert/alert-service.ts
@@ -1,7 +1,7 @@
import { Knex } from "knex";
import { z } from "zod";
-import { TAlertChannels, TAlerts, TAlertsInsert } from "@app/db/schemas";
+import { TableName, TAlertChannels, TAlerts, TAlertsInsert } from "@app/db/schemas";
import { Event as TAuditEvent, EventType } from "@app/ee/services/audit-log/audit-log-types";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
@@ -825,6 +825,11 @@ export const alertServiceFactory = ({
}
};
+ const findOrphanedResourceIds = (
+ input: { resourceType: string; resourceTable: TableName; limit: number },
+ tx?: Knex
+ ) => alertDAL.findOrphanedResourceIds(input, tx);
+
const findRecipientsForResources = (
input: { resourceType: string; resourceIds: string[]; channelType: string; principalType: string },
tx?: Knex
@@ -876,6 +881,7 @@ export const alertServiceFactory = ({
moveAlertsToResource,
copyAlertsToResource,
findRecipientsForResources,
+ findOrphanedResourceIds,
filterRecipientsInScope
};
};
diff --git a/backend/src/services/reminder/reminder-dal.ts b/backend/src/services/reminder/reminder-dal.ts
index 4c30d7cf76..0f61cc0bfa 100644
--- a/backend/src/services/reminder/reminder-dal.ts
+++ b/backend/src/services/reminder/reminder-dal.ts
@@ -37,30 +37,6 @@ export const reminderDALFactory = (db: TDbClient) => {
}));
};
- // Reminder alerts whose secret row is gone. Alerts have no foreign key to secrets, so this is how
- // every secret delete path (including folder and environment cascades) gets cleaned up.
- const findOrphanedReminderAlertResourceIds = async (
- { resourceType, limit }: { resourceType: string; limit: number },
- tx?: Knex
- ): Promise<string[]> => {
- const rows = (await (tx || db.replicaNode())(TableName.Alert)
- .where(`${TableName.Alert}.resourceType`, resourceType)
- .whereNotNull(`${TableName.Alert}.resourceId`)
- .whereNotExists((qb) => {
- void qb
- .select(db.raw("1"))
- .from(TableName.SecretV2)
- // The CASE keeps a non-uuid resourceId from failing the cast for the whole query.
- .whereRaw(
- `"${TableName.SecretV2}"."id" = CASE WHEN "${TableName.Alert}"."resourceId" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN "${TableName.Alert}"."resourceId"::uuid END`
- );
- })
- .limit(limit)
- .select(`${TableName.Alert}.resourceId`)) as { resourceId: string }[];
-
- return rows.map((row) => row.resourceId);
- };
-
const findByIdForUpdate = async (id: string, tx: Knex) => {
const reminder = await tx(TableName.Reminder).where({ id }).forUpdate().first();
return reminder;
@@ -133,7 +109,6 @@ export const reminderDALFactory = (db: TDbClient) => {
...reminderOrm,
findDueReminders,
findByIdForUpdate,
- findOrphanedReminderAlertResourceIds,
findSecretReminder,
findSecretReminders,
findByProjectAndDateRange
diff --git a/backend/src/services/reminder/reminder-service.test.ts b/backend/src/services/reminder/reminder-service.test.ts
index a2d2b3d9b7..fe2b0434ab 100644
--- a/backend/src/services/reminder/reminder-service.test.ts
+++ b/backend/src/services/reminder/reminder-service.test.ts
@@ -66,8 +66,7 @@ const buildService = (opts: {
},
deleteById: async (id: string, tx: unknown) => {
deletes.push({ id, tx });
- },
- findOrphanedReminderAlertResourceIds: async () => orphanBatches.shift() ?? []
+ }
},
eventEmitter: {
emit: async (
@@ -79,6 +78,7 @@ const buildService = (opts: {
}
},
alertService: {
+ findOrphanedResourceIds: async () => orphanBatches.shift() ?? [],
deleteAlertsForDeletedResources: async ({ resourceIds }: { resourceIds: string[] }) => {
reaped.push(resourceIds);
return resourceIds.length;
diff --git a/backend/src/services/reminder/reminder-service.ts b/backend/src/services/reminder/reminder-service.ts
index adbebe5353..60afeaba1a 100644
--- a/backend/src/services/reminder/reminder-service.ts
+++ b/backend/src/services/reminder/reminder-service.ts
@@ -39,6 +39,7 @@ type TReminderServiceFactoryDep = {
| "deleteAlertsForDeletedResources"
| "moveAlertsToResource"
| "copyAlertsToResource"
+ | "findOrphanedResourceIds"
| "filterRecipientsInScope"
>;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
@@ -323,8 +324,9 @@ export const reminderServiceFactory = ({
const reapOrphanedReminderAlerts: TReminderServiceFactory["reapOrphanedReminderAlerts"] = async () => {
for (let batch = 0; batch < MAX_ORPHAN_REAP_BATCHES; batch += 1) {
// eslint-disable-next-line no-await-in-loop -- each batch is its own short transaction
- const orphanedSecretIds = await reminderDAL.findOrphanedReminderAlertResourceIds({
+ const orphanedSecretIds = await alertService.findOrphanedResourceIds({
resourceType: SECRET_REMINDER_RESOURCE_TYPE,
+ resourceTable: TableName.SecretV2,
limit: ORPHAN_REAP_BATCH_SIZE
});
if (orphanedSecretIds.length === 0) return;