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
refactor duplications
Thiago Araujo da Silva72a909d29855
diff --git a/backend/src/services/alarm/alarm-channel-dal.ts b/backend/src/services/alarm/alarm-channel-dal.tsindex 7c685fe4a1..1568afd8ea 100644--- a/backend/src/services/alarm/alarm-channel-dal.ts+++ b/backend/src/services/alarm/alarm-channel-dal.ts@@ -33,6 +33,20 @@ export const alarmChannelDALFactory = (db: TDbClient) => {}};+ const findByAlarmIds = async (alarmIds: string[], tx?: Knex): Promise<TAlarmChannels[]> => {+ try {+ if (!alarmIds.length) return [];+ const channels = await (tx || db.replicaNode())(TableName.AlarmChannel)+ .whereIn(`${TableName.AlarmChannel}.alarmId`, alarmIds)+ .select(selectAllTableCols(TableName.AlarmChannel))+ .orderBy(`${TableName.AlarmChannel}.createdAt`, "asc");++ return channels as TAlarmChannels[];+ } catch (error) {+ throw new DatabaseError({ error, name: "FindByAlarmIds" });+ }+ };+const deleteByAlarmId = async (alarmId: string, tx?: Knex): Promise<number> => {try {return await (tx || db)(TableName.AlarmChannel).where(`${TableName.AlarmChannel}.alarmId`, alarmId).del();@@ -45,6 +59,7 @@ export const alarmChannelDALFactory = (db: TDbClient) => {...alarmChannelOrm,insertMany,findByAlarmId,+ findByAlarmIds,deleteByAlarmId};};diff --git a/backend/src/services/alarm/alarm-dal.test.ts b/backend/src/services/alarm/alarm-dal.test.tsnew file mode 100644index 0000000000..15b1a387ae--- /dev/null+++ b/backend/src/services/alarm/alarm-dal.test.ts@@ -0,0 +1,43 @@+import { TableName, TAlarms } from "@app/db/schemas";++import { alarmDALFactory } from "./alarm-dal";++// Records the query builder calls so we can assert the cron enumeration excludes alarms bound to+// soft-deleted projects (regression for: a soft-deleted project must not keep firing alarms during+// its cleanup grace window).+const buildDAL = () => {+ const calls = { where: [] as unknown[][], whereNull: [] as unknown[], leftJoin: [] as unknown[][] };+ const chain = {+ leftJoin: (...args: unknown[]) => {+ calls.leftJoin.push(args);+ return chain;+ },+ where: (...args: unknown[]) => {+ calls.where.push(args);+ return chain;+ },+ whereNull: (col: unknown) => {+ calls.whereNull.push(col);+ return chain;+ },+ select: () => chain,+ orderBy: async () => [] as TAlarms[]+ };+ const queryBuilder = () => chain;+ const db = { replicaNode: () => queryBuilder } as never;++ return { dal: alarmDALFactory(db), calls };+};++describe("alarm dal", () => {+ test("findEnabledByResourceType excludes alarms in soft-deleted projects", async () => {+ const { dal, calls } = buildDAL();++ await dal.findEnabledByResourceType("identity.credential");++ expect(calls.leftJoin.some((args) => args[0] === TableName.Project)).toBe(true);+ expect(calls.whereNull).toContainEqual(`${TableName.Project}.deleteAfter`);+ expect(calls.where).toContainEqual([`${TableName.Alarm}.enabled`, true]);+ expect(calls.where).toContainEqual([`${TableName.Alarm}.resourceType`, "identity.credential"]);+ });+});diff --git a/backend/src/services/alarm/alarm-dal.ts b/backend/src/services/alarm/alarm-dal.tsindex 33465ecc2a..4861414b92 100644--- a/backend/src/services/alarm/alarm-dal.ts+++ b/backend/src/services/alarm/alarm-dal.ts@@ -13,8 +13,10 @@ export const alarmDALFactory = (db: TDbClient) => {const findEnabledByResourceType = async (resourceType: string, tx?: Knex): Promise<TAlarms[]> => {try {const alarms = await (tx || db.replicaNode())(TableName.Alarm)+ .leftJoin(TableName.Project, `${TableName.Alarm}.projectId`, `${TableName.Project}.id`).where(`${TableName.Alarm}.resourceType`, resourceType).where(`${TableName.Alarm}.enabled`, true)+ .whereNull(`${TableName.Project}.deleteAfter`).select(selectAllTableCols(TableName.Alarm)).orderBy(`${TableName.Alarm}.createdAt`, "asc");diff --git a/backend/src/services/alarm/alarm-recipient-dal.ts b/backend/src/services/alarm/alarm-recipient-dal.tsindex 433e53b152..3340fa759e 100644--- a/backend/src/services/alarm/alarm-recipient-dal.ts+++ b/backend/src/services/alarm/alarm-recipient-dal.ts@@ -32,6 +32,19 @@ export const alarmRecipientDALFactory = (db: TDbClient) => {}};+ const findByAlarmIds = async (alarmIds: string[], tx?: Knex): Promise<TAlarmRecipients[]> => {+ try {+ if (!alarmIds.length) return [];+ const recipients = await (tx || db.replicaNode())(TableName.AlarmRecipient)+ .whereIn(`${TableName.AlarmRecipient}.alarmId`, alarmIds)+ .select(selectAllTableCols(TableName.AlarmRecipient));++ return recipients as TAlarmRecipients[];+ } catch (error) {+ throw new DatabaseError({ error, name: "FindByAlarmIds" });+ }+ };+const deleteByAlarmId = async (alarmId: string, tx?: Knex): Promise<number> => {try {return await (tx || db)(TableName.AlarmRecipient).where(`${TableName.AlarmRecipient}.alarmId`, alarmId).del();@@ -44,6 +57,7 @@ export const alarmRecipientDALFactory = (db: TDbClient) => {...alarmRecipientOrm,insertMany,findByAlarmId,+ findByAlarmIds,deleteByAlarmId};};diff --git a/backend/src/services/alarm/alarm-recipient-resolver.ts b/backend/src/services/alarm/alarm-recipient-resolver.tsindex 9acedc2cc9..bf4a264605 100644--- a/backend/src/services/alarm/alarm-recipient-resolver.ts+++ b/backend/src/services/alarm/alarm-recipient-resolver.ts@@ -16,6 +16,7 @@ export type TAlarmRecipientResolver = ReturnType<typeof alarmRecipientResolverFaexport const alarmRecipientResolverFactory = ({ userDAL, userGroupMembershipDAL }: TAlarmRecipientResolverDep) => {const resolve = async (recipients: TAlarmRecipients[]): Promise<TAlarmRecipient[]> => {const userIds = new Set<string>();+ const groupIds = new Set<string>();const rawEmails = new Set<string>();for (const recipient of recipients) {@@ -23,12 +24,9 @@ export const alarmRecipientResolverFactory = ({ userDAL, userGroupMembershipDALcase AlarmPrincipalType.USER:userIds.add(recipient.principalId);break;- case AlarmPrincipalType.GROUP: {- // eslint-disable-next-line no-await-in-loop- const memberships = await userGroupMembershipDAL.find({ groupId: recipient.principalId });- memberships.forEach((membership) => userIds.add(membership.userId));+ case AlarmPrincipalType.GROUP:+ groupIds.add(recipient.principalId);break;- }case AlarmPrincipalType.EMAIL:rawEmails.add(recipient.principalId.toLowerCase());break;@@ -37,6 +35,11 @@ export const alarmRecipientResolverFactory = ({ userDAL, userGroupMembershipDAL}}+ if (groupIds.size > 0) {+ const memberships = await userGroupMembershipDAL.find({ $in: { groupId: [...groupIds] } });+ memberships.forEach((membership) => userIds.add(membership.userId));+ }+const resolved: TAlarmRecipient[] = [];const seenEmails = new Set<string>();@@ -51,7 +54,6 @@ export const alarmRecipientResolverFactory = ({ userDAL, userGroupMembershipDAL});}- // Add raw-address recipients, skipping any that already resolved via a user (dedup by email).rawEmails.forEach((email) => {if (!seenEmails.has(email)) {seenEmails.add(email);diff --git a/backend/src/services/alarm/alarm-service.test.ts b/backend/src/services/alarm/alarm-service.test.tsindex 3c877ddc59..d0679c6e8e 100644--- a/backend/src/services/alarm/alarm-service.test.ts+++ b/backend/src/services/alarm/alarm-service.test.ts@@ -84,6 +84,7 @@ const buildService = (opts?: {return withMeta;},findByAlarmId: async (alarmId: string) => channels.get(alarmId) ?? [],+ findByAlarmIds: async (alarmIds: string[]) => alarmIds.flatMap((alarmId) => channels.get(alarmId) ?? []),deleteByAlarmId: async (alarmId: string) => {channels.delete(alarmId);return 0;@@ -95,6 +96,7 @@ const buildService = (opts?: {return data;},findByAlarmId: async (alarmId: string) => recipients.get(alarmId) ?? [],+ findByAlarmIds: async (alarmIds: string[]) => alarmIds.flatMap((alarmId) => recipients.get(alarmId) ?? []),deleteByAlarmId: async (alarmId: string) => {recipients.delete(alarmId);return 0;@@ -183,6 +185,14 @@ describe("alarm service", () => {await expect(service.createAlarm({ ...validCreate, condition: { wrong: 1 } })).rejects.toThrow();});+ test("rejects a create with no condition when the provider requires one", async () => {+ const { service } = buildService();+ // Omitted condition must be caught at create time (400), not stored as null and thrown at cron time.+ await expect(service.createAlarm({ ...validCreate, condition: undefined })).rejects.toThrow(+ /Invalid alarm condition/+ );+ });+test("rejects an event type the provider does not support", async () => {const { service } = buildService();await expect(service.createAlarm({ ...validCreate, eventType: "test.resource.renewal" })).rejects.toThrow();diff --git a/backend/src/services/alarm/alarm-service.ts b/backend/src/services/alarm/alarm-service.tsindex db89e1b9e4..4216a4dbd9 100644--- a/backend/src/services/alarm/alarm-service.ts+++ b/backend/src/services/alarm/alarm-service.ts@@ -1,12 +1,18 @@import { z } from "zod";+import { TAlarmChannels, TAlarmRecipients, TAlarms } from "@app/db/schemas";import { TGroupDALFactory } from "@app/ee/services/group/group-dal";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TOrgDALFactory } from "@app/services/org/org-dal";import { TProjectDALFactory } from "@app/services/project/project-dal";-import { decryptChannelConfig, encryptChannelConfig, getAlarmChannelCipher } from "./alarm-channel-crypto-fns";+import {+ decryptChannelConfig,+ encryptChannelConfig,+ getAlarmChannelCipher,+ TAlarmDecryptor+} from "./alarm-channel-crypto-fns";import { TAlarmChannelDALFactory } from "./alarm-channel-dal";import { AlarmChannelType } from "./alarm-channel-types";import { TAlarmDALFactory } from "./alarm-dal";@@ -24,12 +30,14 @@ import {} from "./alarm-service-types";import { AlarmPermissionAction, AlarmPrincipalType, IResourceAlarmProvider } from "./alarm-types";import { ALARM_CHANNEL_REGISTRY } from "./channels/alarm-channel-registry";-import { validateSlackWebhookUrl } from "./channels/alarm-channel-slack-fns";export type TAlarmServiceFactoryDep = {alarmDAL: TAlarmDALFactory;- alarmChannelDAL: Pick<TAlarmChannelDALFactory, "insertMany" | "findByAlarmId" | "deleteByAlarmId">;- alarmRecipientDAL: Pick<TAlarmRecipientDALFactory, "insertMany" | "findByAlarmId" | "deleteByAlarmId">;+ alarmChannelDAL: Pick<TAlarmChannelDALFactory, "insertMany" | "findByAlarmId" | "findByAlarmIds" | "deleteByAlarmId">;+ alarmRecipientDAL: Pick<+ TAlarmRecipientDALFactory,+ "insertMany" | "findByAlarmId" | "findByAlarmIds" | "deleteByAlarmId"+ >;alarmProviderRegistry: TAlarmProviderRegistry;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;orgDAL: Pick<TOrgDALFactory, "findMembership">;@@ -101,7 +109,8 @@ export const alarmServiceFactory = ({condition?: unknown;channels?: TAlarmChannelInput[];recipients?: { principalType: string }[];- }+ },+ opts: { alwaysValidateCondition?: boolean } = {}) => {if (input.eventType && !provider.eventTypes.includes(input.eventType)) {throw new BadRequestError({@@ -109,7 +118,7 @@ export const alarmServiceFactory = ({});}- if (input.condition !== undefined) {+ if (opts.alwaysValidateCondition || input.condition !== undefined) {try {provider.conditionSchema.parse(input.condition);} catch (err) {@@ -138,6 +147,8 @@ export const alarmServiceFactory = ({const definition = ALARM_CHANNEL_REGISTRY[channel.channelType];if (!definition) throw new BadRequestError({ message: `Unknown channel type '${channel.channelType}'` });+ // configSchema already enforces the Slack hooks.slack.com/https allowlist (and sendSlackNotification+ // re-checks at dispatch), so no separate validateSlackWebhookUrl call is needed here.try {definition.configSchema.parse(channel.config);} catch (err) {@@ -145,10 +156,6 @@ export const alarmServiceFactory = ({err instanceof z.ZodError ? err.issues.map((i) => i.message).join(", ") : "Invalid channel config";throw new BadRequestError({ message: `Invalid ${channel.channelType} channel config: ${message}` });}-- if (channel.channelType === AlarmChannelType.SLACK) {- validateSlackWebhookUrl((channel.config as { webhookUrl: string }).webhookUrl);- }}}};@@ -222,20 +229,12 @@ export const alarmServiceFactory = ({}};- const $formatResponse = async (alarmId: string): Promise<TAlarmResponse> => {- const alarm = await alarmDAL.findById(alarmId);- if (!alarm) throw new NotFoundError({ message: `Alarm with ID '${alarmId}' not found` });-- const [channels, recipients] = await Promise.all([- alarmChannelDAL.findByAlarmId(alarmId),- alarmRecipientDAL.findByAlarmId(alarmId)- ]);-- const { decryptor } = await getAlarmChannelCipher(kmsService, {- orgId: alarm.orgId,- projectId: alarm.projectId- });-+ const $buildResponse = (+ alarm: TAlarms,+ channels: TAlarmChannels[],+ recipients: TAlarmRecipients[],+ decryptor: TAlarmDecryptor+ ): TAlarmResponse => {const channelResponses: TAlarmChannelResponse[] = channels.map((channel) => {const config = decryptChannelConfig<Record<string, unknown>>(channel.encryptedConfig, decryptor);@@ -271,9 +270,26 @@ export const alarmServiceFactory = ({};};+ const $formatResponse = async (alarmId: string): Promise<TAlarmResponse> => {+ const alarm = await alarmDAL.findById(alarmId);+ if (!alarm) throw new NotFoundError({ message: `Alarm with ID '${alarmId}' not found` });++ const [channels, recipients] = await Promise.all([+ alarmChannelDAL.findByAlarmId(alarmId),+ alarmRecipientDAL.findByAlarmId(alarmId)+ ]);++ const { decryptor } = await getAlarmChannelCipher(kmsService, {+ orgId: alarm.orgId,+ projectId: alarm.projectId+ });++ return $buildResponse(alarm, channels, recipients, decryptor);+ };+const createAlarm = async (dto: TCreateAlarmDTO): Promise<TAlarmResponse> => {const provider = $getProvider(dto.resourceType);- $validate(provider, dto);+ $validate(provider, dto, { alwaysValidateCondition: true });await provider.assertPermission({action: AlarmPermissionAction.Create,@@ -387,8 +403,31 @@ export const alarmServiceFactory = ({projectId: dto.projectId ?? null,...(dto.enabled !== undefined ? { enabled: dto.enabled } : {})});+ if (alarms.length === 0) return [];++ const alarmIds = alarms.map((alarm) => alarm.id);+ const [channels, recipients, { decryptor }] = await Promise.all([+ alarmChannelDAL.findByAlarmIds(alarmIds),+ alarmRecipientDAL.findByAlarmIds(alarmIds),+ getAlarmChannelCipher(kmsService, { orgId: dto.actorOrgId, projectId: dto.projectId ?? null })+ ]);++ const channelsByAlarm = new Map<string, TAlarmChannels[]>();+ channels.forEach((channel) => {+ const list = channelsByAlarm.get(channel.alarmId) ?? [];+ list.push(channel);+ channelsByAlarm.set(channel.alarmId, list);+ });+ const recipientsByAlarm = new Map<string, TAlarmRecipients[]>();+ recipients.forEach((recipient) => {+ const list = recipientsByAlarm.get(recipient.alarmId) ?? [];+ list.push(recipient);+ recipientsByAlarm.set(recipient.alarmId, list);+ });- return Promise.all(alarms.map((alarm) => $formatResponse(alarm.id)));+ return alarms.map((alarm) =>+ $buildResponse(alarm, channelsByAlarm.get(alarm.id) ?? [], recipientsByAlarm.get(alarm.id) ?? [], decryptor)+ );};const updateAlarm = async (dto: TUpdateAlarmDTO): Promise<TAlarmResponse> => {diff --git a/backend/src/services/alarm/channels/alarm-channel-email-fns.ts b/backend/src/services/alarm/channels/alarm-channel-email-fns.tsindex cd367f3a2a..b0d1199466 100644--- a/backend/src/services/alarm/channels/alarm-channel-email-fns.ts+++ b/backend/src/services/alarm/channels/alarm-channel-email-fns.ts@@ -1,17 +1,16 @@-import { delay } from "@app/lib/delay";-import { logger } from "@app/lib/logger";import { SmtpTemplates } from "@app/services/smtp/smtp-service";-import { ALARM_CHANNEL_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "../alarm-channel-constants";+import { RETRYABLE_NETWORK_ERRORS } from "../alarm-channel-constants";import {EmailChannelConfigSchema,TAlarmChannelSendContext,TAlarmPayload,TChannelResult} from "../alarm-channel-types";+import { retryWithBackoff } from "./alarm-channel-retry-fns";-const isEmailErrorRetryable = (err: Error): boolean => {- const msg = err.message.toLowerCase();+const isEmailErrorRetryable = (err: unknown): boolean => {+ const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();if (RETRYABLE_NETWORK_ERRORS.some((code) => msg.includes(code.toLowerCase()))) return true;if (msg.includes("timeout") || msg.includes("connection")) return true;if (["421", "450", "451", "452"].some((code) => msg.includes(code))) return true;@@ -53,36 +52,8 @@ export const sendEmailNotification = async (ctx: TAlarmChannelSendContext): Prom}const recipients = [ctx.recipient.email];- const { maxRetries, delayMs } = ALARM_CHANNEL_RETRY_CONFIG;- let lastError: Error | undefined;-- for (let attempt = 1; attempt <= maxRetries; attempt += 1) {- try {- // eslint-disable-next-line no-await-in-loop- await sendEmail(ctx.deps.smtpService, recipients, ctx.payload);- return { success: true };- } catch (err) {- lastError = err instanceof Error ? err : new Error(String(err));-- if (!isEmailErrorRetryable(lastError)) {- logger.info(- { channelId: ctx.channelId, error: lastError.message },- `Alarm email error is not retryable (permanent SMTP error) [channelId=${ctx.channelId}]`- );- return { success: false, error: lastError.message };- }-- logger.info(- { channelId: ctx.channelId, attempt, maxRetries, error: lastError.message },- `Alarm email failed, ${attempt < maxRetries ? `retrying in ${delayMs}ms` : "no more retries"} [channelId=${ctx.channelId}]`- );-- if (attempt < maxRetries) {- // eslint-disable-next-line no-await-in-loop- await delay(delayMs);- }- }- }-- return { success: false, error: lastError?.message };+ return retryWithBackoff(() => sendEmail(ctx.deps.smtpService, recipients, ctx.payload), isEmailErrorRetryable, {+ channelId: ctx.channelId,+ channelLabel: "email"+ });};diff --git a/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.ts b/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.tsindex 7eae6d5f16..26845a10ab 100644--- a/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.ts+++ b/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.ts@@ -1,10 +1,9 @@import { AxiosError } from "axios";-import { delay } from "@app/lib/delay";import { logger } from "@app/lib/logger";import { safeRequest } from "@app/lib/validator";-import { ALARM_CHANNEL_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "../alarm-channel-constants";+import { RETRYABLE_NETWORK_ERRORS } from "../alarm-channel-constants";import {PagerDutyChannelConfigSchema,pagerDutyIntegrationKeyRegex,@@ -13,6 +12,7 @@ import {TAlarmPayload,TChannelResult} from "../alarm-channel-types";+import { retryWithBackoff } from "./alarm-channel-retry-fns";const PAGERDUTY_EVENTS_URL = "https://events.pagerduty.com/v2/enqueue";const PAGERDUTY_TIMEOUT = 7 * 1000;@@ -71,13 +71,14 @@ export const buildPagerDutyEvent = (links: [{ href: payload.alarm.viewUrl, text: "View in Infisical" }]});-const isPagerDutyErrorRetryable = (err: AxiosError): boolean => {- const status = err.response?.status;+const isPagerDutyErrorRetryable = (err: unknown): boolean => {+ const axiosErr = err as AxiosError;+ const status = axiosErr.response?.status;if (status === 400) return false;if (status === 429) return true;if (status && status >= 500) return true;- if (err.code && RETRYABLE_NETWORK_ERRORS.includes(err.code)) return true;- if (err.message?.toLowerCase().includes("timeout")) return true;+ if (axiosErr.code && RETRYABLE_NETWORK_ERRORS.includes(axiosErr.code)) return true;+ if (axiosErr.message?.toLowerCase().includes("timeout")) return true;return false;};@@ -89,44 +90,6 @@ const triggerPagerDutyEvent = async (payload: TPagerDutyPayload): Promise<void>});};-const triggerPagerDutyEventWithRetry = async (- payload: TPagerDutyPayload,- channelId: string-): Promise<TChannelResult> => {- const { maxRetries, delayMs } = ALARM_CHANNEL_RETRY_CONFIG;- let lastError: AxiosError | undefined;-- for (let attempt = 1; attempt <= maxRetries; attempt += 1) {- try {- // eslint-disable-next-line no-await-in-loop- await triggerPagerDutyEvent(payload);- return { success: true };- } catch (err) {- lastError = err as AxiosError;-- if (!isPagerDutyErrorRetryable(lastError)) {- logger.info(- { channelId, statusCode: lastError.response?.status, error: lastError.message },- `Alarm PagerDuty error is not retryable (4xx or non-transient) [channelId=${channelId}]`- );- return { success: false, error: lastError.message };- }-- logger.info(- { channelId, attempt, maxRetries, statusCode: lastError.response?.status, error: lastError.message },- `Alarm PagerDuty failed, ${attempt < maxRetries ? `retrying in ${delayMs}ms` : "no more retries"} [channelId=${channelId}]`- );-- if (attempt < maxRetries) {- // eslint-disable-next-line no-await-in-loop- await delay(delayMs);- }- }- }-- return { success: false, error: lastError?.message };-};-export const sendPagerDutyNotification = async (ctx: TAlarmChannelSendContext): Promise<TChannelResult> => {const config = PagerDutyChannelConfigSchema.parse(ctx.config);@@ -144,7 +107,11 @@ export const sendPagerDutyNotification = async (ctx: TAlarmChannelSendContext):const results = await Promise.all(items.map((item) =>- triggerPagerDutyEventWithRetry(buildPagerDutyEvent(ctx.payload, item, config.integrationKey), ctx.channelId)+ retryWithBackoff(+ () => triggerPagerDutyEvent(buildPagerDutyEvent(ctx.payload, item, config.integrationKey)),+ isPagerDutyErrorRetryable,+ { channelId: ctx.channelId, channelLabel: "PagerDuty" }+ )));diff --git a/backend/src/services/alarm/channels/alarm-channel-retry-fns.ts b/backend/src/services/alarm/channels/alarm-channel-retry-fns.tsnew file mode 100644index 0000000000..73ed33741f--- /dev/null+++ b/backend/src/services/alarm/channels/alarm-channel-retry-fns.ts@@ -0,0 +1,56 @@+import { AxiosError } from "axios";++import { delay } from "@app/lib/delay";+import { logger } from "@app/lib/logger";++import { ALARM_CHANNEL_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "../alarm-channel-constants";+import { TChannelResult } from "../alarm-channel-types";++export const retryWithBackoff = async (+ fn: () => Promise<void>,+ isRetryable: (err: unknown) => boolean,+ ctx: { channelId: string; channelLabel: string }+): Promise<TChannelResult> => {+ const { maxRetries, delayMs } = ALARM_CHANNEL_RETRY_CONFIG;+ let lastError: Error | undefined;++ for (let attempt = 1; attempt <= maxRetries; attempt += 1) {+ try {+ // eslint-disable-next-line no-await-in-loop+ await fn();+ return { success: true };+ } catch (err) {+ lastError = err instanceof Error ? err : new Error(String(err));+ const statusCode = (lastError as AxiosError).response?.status;++ if (!isRetryable(lastError)) {+ logger.info(+ { channelId: ctx.channelId, statusCode, error: lastError.message },+ `Alarm ${ctx.channelLabel} delivery error is not retryable [channelId=${ctx.channelId}]`+ );+ return { success: false, error: lastError.message };+ }++ logger.info(+ { channelId: ctx.channelId, attempt, maxRetries, statusCode, error: lastError.message },+ `Alarm ${ctx.channelLabel} delivery failed, ${attempt < maxRetries ? `retrying in ${delayMs}ms` : "no more retries"} [channelId=${ctx.channelId}]`+ );++ if (attempt < maxRetries) {+ // eslint-disable-next-line no-await-in-loop+ await delay(delayMs);+ }+ }+ }++ return { success: false, error: lastError?.message };+};++export const isAxiosErrorRetryable = (err: unknown): boolean => {+ const axiosErr = err as AxiosError;+ const status = axiosErr.response?.status;+ if (status && status >= 500) return true;+ if (axiosErr.code && RETRYABLE_NETWORK_ERRORS.includes(axiosErr.code)) return true;+ if (axiosErr.message?.toLowerCase().includes("timeout")) return true;+ return false;+};diff --git a/backend/src/services/alarm/channels/alarm-channel-slack-fns.ts b/backend/src/services/alarm/channels/alarm-channel-slack-fns.tsindex 0920f0834e..10147310ac 100644--- a/backend/src/services/alarm/channels/alarm-channel-slack-fns.ts+++ b/backend/src/services/alarm/channels/alarm-channel-slack-fns.ts@@ -1,11 +1,6 @@-import { AxiosError } from "axios";--import { delay } from "@app/lib/delay";import { BadRequestError } from "@app/lib/errors";-import { logger } from "@app/lib/logger";import { safeRequest } from "@app/lib/validator";-import { ALARM_CHANNEL_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "../alarm-channel-constants";import {SlackChannelConfigSchema,TAlarmChannelSendContext,@@ -13,6 +8,7 @@ import {TAlarmSeverity,TChannelResult} from "../alarm-channel-types";+import { isAxiosErrorRetryable, retryWithBackoff } from "./alarm-channel-retry-fns";const SLACK_WEBHOOK_TIMEOUT = 7 * 1000;const MAX_ITEMS_DISPLAYED = 2;@@ -120,14 +116,6 @@ export const buildSlackPayload = (payload: TAlarmPayload): TSlackPayload => {};};-const isSlackErrorRetryable = (err: AxiosError): boolean => {- const status = err.response?.status;- if (status && status >= 500) return true;- if (err.code && RETRYABLE_NETWORK_ERRORS.includes(err.code)) return true;- if (err.message?.toLowerCase().includes("timeout")) return true;- return false;-};-const triggerSlackWebhook = async (url: string, payload: TSlackPayload): Promise<void> => {await safeRequest.post(url, payload, {headers: { "Content-Type": "application/json" },@@ -138,46 +126,11 @@ const triggerSlackWebhook = async (url: string, payload: TSlackPayload): Promiseexport const sendSlackNotification = async (ctx: TAlarmChannelSendContext): Promise<TChannelResult> => {const config = SlackChannelConfigSchema.parse(ctx.config);-validateSlackWebhookUrl(config.webhookUrl);-const payload = buildSlackPayload(ctx.payload);- const { maxRetries, delayMs } = ALARM_CHANNEL_RETRY_CONFIG;- let lastError: AxiosError | undefined;-- for (let attempt = 1; attempt <= maxRetries; attempt += 1) {- try {- // eslint-disable-next-line no-await-in-loop- await triggerSlackWebhook(config.webhookUrl, payload);- return { success: true };- } catch (err) {- lastError = err as AxiosError;-- if (!isSlackErrorRetryable(lastError)) {- logger.info(- { channelId: ctx.channelId, statusCode: lastError.response?.status, error: lastError.message },- `Alarm Slack error is not retryable (4xx or non-transient) [channelId=${ctx.channelId}]`- );- return { success: false, error: lastError.message };- }- logger.info(- {- channelId: ctx.channelId,- attempt,- maxRetries,- statusCode: lastError.response?.status,- error: lastError.message- },- `Alarm Slack failed, ${attempt < maxRetries ? `retrying in ${delayMs}ms` : "no more retries"} [channelId=${ctx.channelId}]`- );-- if (attempt < maxRetries) {- // eslint-disable-next-line no-await-in-loop- await delay(delayMs);- }- }- }-- return { success: false, error: lastError?.message };+ return retryWithBackoff(() => triggerSlackWebhook(config.webhookUrl, payload), isAxiosErrorRetryable, {+ channelId: ctx.channelId,+ channelLabel: "Slack"+ });};diff --git a/backend/src/services/alarm/channels/alarm-channel-webhook-fns.ts b/backend/src/services/alarm/channels/alarm-channel-webhook-fns.tsindex 7a02c92034..db534b9482 100644--- a/backend/src/services/alarm/channels/alarm-channel-webhook-fns.ts+++ b/backend/src/services/alarm/channels/alarm-channel-webhook-fns.ts@@ -1,18 +1,14 @@import crypto from "node:crypto";-import { AxiosError } from "axios";--import { delay } from "@app/lib/delay";-import { logger } from "@app/lib/logger";import { safeRequest } from "@app/lib/validator";-import { ALARM_CHANNEL_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "../alarm-channel-constants";import {TAlarmChannelSendContext,TAlarmPayload,TChannelResult,WebhookChannelConfigSchema} from "../alarm-channel-types";+import { isAxiosErrorRetryable, retryWithBackoff } from "./alarm-channel-retry-fns";const ALARM_WEBHOOK_TIMEOUT = 7 * 1000;@@ -31,14 +27,6 @@ type TAlarmWebhookPayload = {};};-const isWebhookErrorRetryable = (err: AxiosError): boolean => {- const status = err.response?.status;- if (status && status >= 500) return true;- if (err.code && RETRYABLE_NETWORK_ERRORS.includes(err.code)) return true;- if (err.message?.toLowerCase().includes("timeout")) return true;- return false;-};-export const buildWebhookPayload = (payload: TAlarmPayload): TAlarmWebhookPayload => ({specversion: "1.0",type: payload.webhookType,@@ -91,44 +79,11 @@ const triggerWebhook = async (params: {export const sendWebhookNotification = async (ctx: TAlarmChannelSendContext): Promise<TChannelResult> => {const config = WebhookChannelConfigSchema.parse(ctx.config);-const payload = buildWebhookPayload(ctx.payload);- const { maxRetries, delayMs } = ALARM_CHANNEL_RETRY_CONFIG;- let lastError: AxiosError | undefined;-- for (let attempt = 1; attempt <= maxRetries; attempt += 1) {- try {- // eslint-disable-next-line no-await-in-loop- await triggerWebhook({ url: config.url, payload, signingSecret: config.signingSecret });- return { success: true };- } catch (err) {- lastError = err as AxiosError;-- if (!isWebhookErrorRetryable(lastError)) {- logger.info(- { channelId: ctx.channelId, statusCode: lastError.response?.status, error: lastError.message },- `Alarm webhook error is not retryable (4xx or non-transient) [channelId=${ctx.channelId}]`- );- return { success: false, error: lastError.message };- }-- logger.info(- {- channelId: ctx.channelId,- attempt,- maxRetries,- statusCode: lastError.response?.status,- error: lastError.message- },- `Alarm webhook failed, ${attempt < maxRetries ? `retrying in ${delayMs}ms` : "no more retries"} [channelId=${ctx.channelId}]`- );-- if (attempt < maxRetries) {- // eslint-disable-next-line no-await-in-loop- await delay(delayMs);- }- }- }- return { success: false, error: lastError?.message };+ return retryWithBackoff(+ () => triggerWebhook({ url: config.url, payload, signingSecret: config.signingSecret }),+ isAxiosErrorRetryable,+ { channelId: ctx.channelId, channelLabel: "webhook" }+ );};