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
use same retry metrics to email
Thiago Araujo da Silva37540f6cd468
diff --git a/backend/src/lib/config/request.test.ts b/backend/src/lib/config/request.test.tsnew file mode 100644index 0000000000..0b2494bb01--- /dev/null+++ b/backend/src/lib/config/request.test.ts@@ -0,0 +1,21 @@+import { AxiosError } from "axios";++import { isRetryableRequestError } from "./request";++const responseError = (status: number) => ({ code: "ERR_BAD_RESPONSE", response: { status } }) as unknown as AxiosError;++describe("isRetryableRequestError", () => {+ test("retries on 429 so a backoff can recover from throttling", () => {+ expect(isRetryableRequestError(responseError(429))).toBe(true);+ });++ test("retries on 5xx and transient network errors", () => {+ expect(isRetryableRequestError(responseError(503))).toBe(true);+ expect(isRetryableRequestError({ code: "ECONNRESET" } as AxiosError)).toBe(true);+ });++ test("does not retry on other 4xx client errors", () => {+ expect(isRetryableRequestError(responseError(400))).toBe(false);+ expect(isRetryableRequestError(responseError(404))).toBe(false);+ });+});diff --git a/backend/src/lib/config/request.ts b/backend/src/lib/config/request.tsindex e45874db7d..8947af176e 100644--- a/backend/src/lib/config/request.ts+++ b/backend/src/lib/config/request.ts@@ -1,4 +1,4 @@-import axios, { AxiosInstance, AxiosResponse, CreateAxiosDefaults } from "axios";+import axios, { AxiosError, AxiosInstance, AxiosResponse, CreateAxiosDefaults } from "axios";import axiosRetry, { IAxiosRetryConfig } from "axios-retry";import { CustomLogger, logger } from "../logger/logger";@@ -25,16 +25,23 @@ export function axiosResponseInterceptor(response: AxiosResponse, customLogger:return response;}+export const isRetryableRequestError = (error: AxiosError): boolean =>+ error.response?.status === 429 || axiosRetry.isNetworkError(error) || axiosRetry.isRetryableError(error);++export const REQUEST_RETRY_CONFIG = {+ retries: 3,+ // eslint-disable-next-line+ retryDelay: axiosRetry.exponentialDelay+};+export function createRequestClient(defaults: CreateAxiosDefaults = {}, retry: IAxiosRetryConfig = {}): AxiosInstance {const client = axios.create({ ...defaults, maxRedirects: 0 });client.interceptors.response.use((response) => axiosResponseInterceptor(response, logger));axiosRetry(client, {- retries: 3,- // eslint-disable-next-line- retryDelay: axiosRetry.exponentialDelay,- retryCondition: (err) => axiosRetry.isNetworkError(err) || axiosRetry.isRetryableError(err),+ ...REQUEST_RETRY_CONFIG,+ retryCondition: isRetryableRequestError,...retry});diff --git a/backend/src/services/alert/alert-channel-constants.ts b/backend/src/services/alert/alert-channel-constants.tsdeleted file mode 100644index 01504c4a1e..0000000000--- a/backend/src/services/alert/alert-channel-constants.ts+++ /dev/null@@ -1,3 +0,0 @@-export { RETRYABLE_NETWORK_ERRORS } from "@app/lib/retry/network-errors";--export const ALERT_CHANNEL_RETRY_CONFIG = { maxRetries: 3, delayMs: 3000 };diff --git a/backend/src/services/alert/channels/alert-channel-email-fns.ts b/backend/src/services/alert/channels/alert-channel-email-fns.tsindex 86a8b2b59f..d58e663d67 100644--- a/backend/src/services/alert/channels/alert-channel-email-fns.ts+++ b/backend/src/services/alert/channels/alert-channel-email-fns.ts@@ -1,6 +1,6 @@+import { RETRYABLE_NETWORK_ERRORS } from "@app/lib/retry/network-errors";import { SmtpTemplates } from "@app/services/smtp/smtp-service";-import { RETRYABLE_NETWORK_ERRORS } from "../alert-channel-constants";import {EmailChannelConfigSchema,TAlertChannelSendContext,diff --git a/backend/src/services/alert/channels/alert-channel-pagerduty-fns.ts b/backend/src/services/alert/channels/alert-channel-pagerduty-fns.tsindex 7a4dbc4575..1743eeb5ae 100644--- a/backend/src/services/alert/channels/alert-channel-pagerduty-fns.ts+++ b/backend/src/services/alert/channels/alert-channel-pagerduty-fns.ts@@ -1,3 +1,6 @@+import { AxiosError } from "axios";++import { logger } from "@app/lib/logger";import { safeRequest } from "@app/lib/validator";import {@@ -8,7 +11,6 @@ import {TAlertPayload,TChannelResult} from "../alert-channel-types";-import { deliverWithRetry, isAxiosErrorRetryable } from "./alert-channel-retry-fns";const PAGERDUTY_EVENTS_URL = "https://events.pagerduty.com/v2/enqueue";const PAGERDUTY_TIMEOUT = 7 * 1000;@@ -82,22 +84,22 @@ export const sendPagerDutyNotification = async (ctx: TAlertChannelSendContext):return { success: false, error: "Invalid PagerDuty integration key" };}- const results = await Promise.all(- ctx.payload.items.map((item) =>- deliverWithRetry(- () => triggerPagerDutyEvent(buildPagerDutyEvent(ctx.payload, item, config.integrationKey)),- isAxiosErrorRetryable,- { channelId: ctx.channelId, channelLabel: "PagerDuty" }- )- )+ const targetResults = await Promise.all(+ ctx.payload.items.map(async (item) => {+ try {+ await triggerPagerDutyEvent(buildPagerDutyEvent(ctx.payload, item, config.integrationKey));+ return { targetId: item.id, success: true };+ } catch (err) {+ const error = err instanceof Error ? err.message : String(err);+ logger.info(+ { channelId: ctx.channelId, statusCode: (err as AxiosError).response?.status, error },+ `Alert PagerDuty delivery failed [channelId=${ctx.channelId}] [targetId=${item.id}]`+ );+ return { targetId: item.id, success: false, error };+ }+ }));- const targetResults = ctx.payload.items.map((item, index) => ({- targetId: item.id,- success: results[index].success,- error: results[index].error- }));-const errors = targetResults.filter((result) => !result.success && result.error).map((result) => result.error);if (errors.length > 0) {return { success: false, error: errors.join("; "), targetResults };diff --git a/backend/src/services/alert/channels/alert-channel-retry-fns.ts b/backend/src/services/alert/channels/alert-channel-retry-fns.tsindex eb31a25c51..9a963be417 100644--- a/backend/src/services/alert/channels/alert-channel-retry-fns.ts+++ b/backend/src/services/alert/channels/alert-channel-retry-fns.ts@@ -1,9 +1,9 @@import { AxiosError } from "axios";+import { REQUEST_RETRY_CONFIG } from "@app/lib/config/request";import { delay } from "@app/lib/delay";import { logger } from "@app/lib/logger";-import { ALERT_CHANNEL_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "../alert-channel-constants";import { TChannelResult } from "../alert-channel-types";export const deliverWithRetry = async (@@ -11,10 +11,10 @@ export const deliverWithRetry = async (isRetryable: (err: unknown) => boolean,ctx: { channelId: string; channelLabel: string }): Promise<TChannelResult> => {- const { maxRetries, delayMs } = ALERT_CHANNEL_RETRY_CONFIG;+ const { retries, retryDelay } = REQUEST_RETRY_CONFIG;let lastError: Error | undefined;- for (let attempt = 1; attempt <= maxRetries; attempt += 1) {+ for (let attempt = 0; attempt <= retries; attempt += 1) {try {// eslint-disable-next-line no-await-in-loopawait fn();@@ -31,12 +31,13 @@ export const deliverWithRetry = async (return { success: false, error: lastError.message };}+ const delayMs = attempt < retries ? retryDelay(attempt + 1) : 0;logger.info(- { channelId: ctx.channelId, attempt, maxRetries, statusCode, error: lastError.message },- `Alert ${ctx.channelLabel} delivery failed, ${attempt < maxRetries ? `retrying in ${delayMs}ms` : "no more retries"} [channelId=${ctx.channelId}]`+ { channelId: ctx.channelId, attempt: attempt + 1, retries, statusCode, error: lastError.message },+ `Alert ${ctx.channelLabel} delivery failed, ${attempt < retries ? `retrying in ${Math.round(delayMs)}ms` : "no more retries"} [channelId=${ctx.channelId}]`);- if (attempt < maxRetries) {+ if (attempt < retries) {// eslint-disable-next-line no-await-in-loopawait delay(delayMs);}@@ -45,13 +46,3 @@ export const deliverWithRetry = async (return { success: false, error: lastError?.message };};--export const isAxiosErrorRetryable = (err: unknown): boolean => {- const axiosErr = err as AxiosError;- const status = axiosErr.response?.status;- if (status === 429) return true;- 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/alert/channels/alert-channel-slack-fns.ts b/backend/src/services/alert/channels/alert-channel-slack-fns.tsindex 841efd7ff7..8db74f4390 100644--- a/backend/src/services/alert/channels/alert-channel-slack-fns.ts+++ b/backend/src/services/alert/channels/alert-channel-slack-fns.ts@@ -8,7 +8,6 @@ import {TAlertSeverity,TChannelResult} from "../alert-channel-types";-import { deliverWithRetry, isAxiosErrorRetryable } from "./alert-channel-retry-fns";const MAX_ITEMS_DISPLAYED = 2;@@ -97,8 +96,6 @@ export const sendSlackNotification = async (ctx: TAlertChannelSendContext): Promconst config = SlackChannelConfigSchema.parse(ctx.config);const payload = buildSlackPayload(ctx.payload);- return deliverWithRetry(() => triggerSlackWebhook(config.webhookUrl, payload), isAxiosErrorRetryable, {- channelId: ctx.channelId,- channelLabel: "Slack"- });+ await triggerSlackWebhook(config.webhookUrl, payload);+ return { success: true };};diff --git a/backend/src/services/alert/channels/alert-channel-webhook-fns.ts b/backend/src/services/alert/channels/alert-channel-webhook-fns.tsindex 7d5d12301f..96aea50e48 100644--- a/backend/src/services/alert/channels/alert-channel-webhook-fns.ts+++ b/backend/src/services/alert/channels/alert-channel-webhook-fns.ts@@ -8,7 +8,6 @@ import {TChannelResult,WebhookChannelConfigSchema} from "../alert-channel-types";-import { deliverWithRetry, isAxiosErrorRetryable } from "./alert-channel-retry-fns";const ALERT_WEBHOOK_TIMEOUT = 7 * 1000;@@ -81,9 +80,6 @@ export const sendWebhookNotification = async (ctx: TAlertChannelSendContext): Prconst config = WebhookChannelConfigSchema.parse(ctx.config);const payload = buildWebhookPayload(ctx.payload);- return deliverWithRetry(- () => triggerWebhook({ url: config.url, payload, signingSecret: config.signingSecret }),- isAxiosErrorRetryable,- { channelId: ctx.channelId, channelLabel: "webhook" }- );+ await triggerWebhook({ url: config.url, payload, signingSecret: config.signingSecret });+ return { success: true };};diff --git a/backend/src/services/alert/channels/alert-channels.test.ts b/backend/src/services/alert/channels/alert-channels.test.tsindex 09907e9233..16fcb8ae23 100644--- a/backend/src/services/alert/channels/alert-channels.test.ts+++ b/backend/src/services/alert/channels/alert-channels.test.ts@@ -1,11 +1,19 @@+import { REQUEST_RETRY_CONFIG } from "@app/lib/config/request";+import { AlertChannelType, SlackChannelConfigSchema, TAlertPayload } from "../alert-channel-types";import { sendEmailNotification } from "./alert-channel-email-fns";import { buildPagerDutyEvent } from "./alert-channel-pagerduty-fns";import { ALERT_CHANNEL_REGISTRY } from "./alert-channel-registry";-import { isAxiosErrorRetryable } from "./alert-channel-retry-fns";import { buildSlackPayload } from "./alert-channel-slack-fns";import { buildWebhookPayload } from "./alert-channel-webhook-fns";+// logger is `export let logger` assigned by initLogger(), which unit tests don't run, so the+// delivery-failure path (which logs) would otherwise dereference undefined. Mock it per-file.+vi.mock("@app/lib/logger", () => ({+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },+ initLogger: () => {}+}));+const samplePayload = (): TAlertPayload => ({alert: {id: "alert-1",@@ -209,21 +217,33 @@ describe("sendEmailNotification (directed)", () => {const result = await sendEmailNotification({ ...baseCtx(), config: {} });expect(result.success).toBe(false);});-});-describe("isAxiosErrorRetryable", () => {- test("retries on 429 (rate limit) so a short backoff can recover", () => {- expect(isAxiosErrorRetryable({ response: { status: 429 } })).toBe(true);- });+ // SMTP has no client-level retry, so the channel retries on the same terms as the shared axios+ // client the HTTP channels dispatch through: one initial attempt plus REQUEST_RETRY_CONFIG.retries.+ test("retries a transient SMTP failure as many times as an outbound request would", async () => {+ vi.useFakeTimers();+ let attempts = 0;+ const ctx = {+ ...baseCtx(),+ config: {},+ recipient: { email: "[email protected]" },+ deps: {+ ...baseCtx().deps,+ smtpService: {+ sendMail: async () => {+ attempts += 1;+ throw new Error("connection timeout");+ }+ }+ }+ };- test("retries on 5xx and network/timeout errors", () => {- expect(isAxiosErrorRetryable({ response: { status: 503 } })).toBe(true);- expect(isAxiosErrorRetryable({ code: "ECONNRESET" })).toBe(true);- expect(isAxiosErrorRetryable({ message: "socket hang up timeout" })).toBe(true);- });+ const pending = sendEmailNotification(ctx);+ await vi.runAllTimersAsync();+ const result = await pending;+ vi.useRealTimers();- test("does not retry on other 4xx client errors", () => {- expect(isAxiosErrorRetryable({ response: { status: 400 } })).toBe(false);- expect(isAxiosErrorRetryable({ response: { status: 404 } })).toBe(false);+ expect(attempts).toBe(1 + REQUEST_RETRY_CONFIG.retries);+ expect(result.success).toBe(false);});});