Skip to content

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

fix pagerduty per target status

Thiago Araujo da Silva894077d935f2
diff --git a/backend/src/db/migrations/20260714120000_add-alerts.ts b/backend/src/db/migrations/20260714120000_add-alerts.ts
index d65f0018e6..983a3418bc 100644
--- a/backend/src/db/migrations/20260714120000_add-alerts.ts
+++ b/backend/src/db/migrations/20260714120000_add-alerts.ts
@@ -106,7 +106,6 @@ export async function up(knex: Knex): Promise<void> {
// generated Insert type treat it as optional (matching pki_alert_history).
t.timestamp("triggeredAt").defaultTo(knex.fn.now());
t.string("status").notNullable();
- t.text("error").nullable();
t.timestamps(true, true, true);
t.foreign("alertId").references("id").inTable(TableName.Alert).onDelete("CASCADE");
diff --git a/backend/src/db/schemas/alert-history.ts b/backend/src/db/schemas/alert-history.ts
index 1a2d72b4b6..58d6097513 100644
--- a/backend/src/db/schemas/alert-history.ts
+++ b/backend/src/db/schemas/alert-history.ts
@@ -12,7 +12,6 @@ export const AlertHistorySchema = z.object({
alertId: z.string().uuid(),
triggeredAt: z.date().nullable().optional(),
status: z.string(),
- error: z.string().nullable().optional(),
createdAt: z.date(),
updatedAt: z.date()
});
diff --git a/backend/src/services/alert/alert-channel-types.ts b/backend/src/services/alert/alert-channel-types.ts
index c85f6e2cd6..910ba134d8 100644
--- a/backend/src/services/alert/alert-channel-types.ts
+++ b/backend/src/services/alert/alert-channel-types.ts
@@ -38,7 +38,9 @@ export type TAlertPayload = {
items: TAlertItem[];
};
-export type TChannelResult = { success: boolean; error?: string };
+export type TChannelTargetResult = { targetId: string; success: boolean; error?: string };
+
+export type TChannelResult = { success: boolean; error?: string; targetResults?: TChannelTargetResult[] };
export type TAlertRecipient = {
userId?: string;
diff --git a/backend/src/services/alert/alert-engine.test.ts b/backend/src/services/alert/alert-engine.test.ts
index 869c59045b..87b931ffdb 100644
--- a/backend/src/services/alert/alert-engine.test.ts
+++ b/backend/src/services/alert/alert-engine.test.ts
@@ -12,10 +12,21 @@ vi.mock("@app/lib/logger", () => ({
initLogger: () => {}
}));
-// Stub outbound HTTP so PagerDuty/Slack/webhook sends resolve without a real network call.
+// Stub outbound HTTP so PagerDuty/Slack/webhook sends resolve without a real network call. When
+// failForTargetId is set, the matching PagerDuty event (keyed by dedup_key `${alertId}:${targetId}`)
+// rejects, so a test can drive a single-target failure.
+const httpControl = vi.hoisted(() => ({ failForTargetId: null as string | null }));
+
vi.mock("@app/lib/validator", async (importActual) => ({
...(await importActual<typeof import("@app/lib/validator")>()),
- safeRequest: { post: async () => ({ data: {} }) }
+ safeRequest: {
+ post: async (_url: string, body: { dedup_key?: string }) => {
+ if (httpControl.failForTargetId && body?.dedup_key === `alert-1:${httpControl.failForTargetId}`) {
+ throw new Error("pagerduty rejected event");
+ }
+ return { data: {} };
+ }
+ }
}));
type TTarget = { id: string };
@@ -170,6 +181,37 @@ describe("alert engine", () => {
]);
});
+ test("records PagerDuty status per target so one failed event does not mark the rest failed", async () => {
+ const { engine, historyWrites } = buildEngine({
+ targets: [{ id: "t1" }, { id: "t2" }, { id: "t3" }],
+ channels: [
+ {
+ id: "c-pd",
+ channelType: "pagerduty",
+ encryptedConfig: encConfig({ integrationKey: "a".repeat(32) }),
+ enabled: true
+ }
+ ]
+ });
+
+ httpControl.failForTargetId = "t2";
+ try {
+ await engine.runAlert(makeAlert());
+ } finally {
+ httpControl.failForTargetId = null;
+ }
+
+ expect(historyWrites).toHaveLength(1);
+ const byTarget = Object.fromEntries(historyWrites[0].deliveries.map((d) => [d.targetId, d.status]));
+ // Only the target whose event failed is recorded FAILED; the others stay SUCCESS so they dedup
+ // and are not re-sent next run.
+ expect(byTarget).toEqual({
+ t1: AlertRunStatus.SUCCESS,
+ t2: AlertRunStatus.FAILED,
+ t3: AlertRunStatus.SUCCESS
+ });
+ });
+
test("dedups a target already delivered on the same channel within the window", async () => {
const { engine, historyWrites } = buildEngine({
targets: [{ id: "t1" }, { id: "t2" }],
diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.ts
index 81c7486e7d..b3af237a89 100644
--- a/backend/src/services/alert/alert-engine.ts
+++ b/backend/src/services/alert/alert-engine.ts
@@ -8,7 +8,7 @@ import { TSmtpService } from "@app/services/smtp/smtp-service";
import { decryptChannelConfig, getAlertChannelCipher } from "./alert-channel-crypto-fns";
import { TAlertChannelDALFactory } from "./alert-channel-dal";
import { TAlertChannelRecipientDALFactory } from "./alert-channel-recipient-dal";
-import { AlertChannelType, TAlertChannelDeps, TAlertRecipient } from "./alert-channel-types";
+import { AlertChannelType, TAlertChannelDeps, TAlertRecipient, TChannelTargetResult } from "./alert-channel-types";
import { TAlertHistoryDALFactory } from "./alert-history-dal";
import { TAlertProviderRegistry } from "./alert-provider-registry";
import { TAlertRecipientResolver } from "./alert-recipient-resolver";
@@ -17,6 +17,15 @@ import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";
const ALERT_DELIVERY_CONCURRENCY = 10;
+type TChannelDispatchResult = {
+ channelId: string;
+ channelType: string;
+ targetIds: string[];
+ success: boolean;
+ error?: string;
+ targetResults?: TChannelTargetResult[];
+};
+
export type TAlertEngineDep = {
alertChannelDAL: Pick<TAlertChannelDALFactory, "findByAlertId">;
alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "findByChannelIds">;
@@ -119,7 +128,7 @@ export const alertEngineFactory = ({
const sendLimit = pLimit(ALERT_DELIVERY_CONCURRENCY);
const channelResults = await Promise.all(
- channelWork.map(async ({ channel, dueTargets }) => {
+ channelWork.map(async ({ channel, dueTargets }): Promise<TChannelDispatchResult> => {
const targetIds = dueTargets.map((target) => provider.targetId(target));
const base = { channelId: channel.id, channelType: channel.channelType, targetIds };
const definition = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType];
@@ -170,14 +179,15 @@ export const alertEngineFactory = ({
})
);
- const deliveries = channelResults.flatMap((result) =>
- result.targetIds.map((targetId) => ({
+ const deliveries = channelResults.flatMap((result) => {
+ const perTarget = new Map<string, boolean>((result.targetResults ?? []).map((t) => [t.targetId, t.success]));
+ return result.targetIds.map((targetId) => ({
targetId,
channelId: result.channelId,
channelType: result.channelType,
- status: result.success ? AlertRunStatus.SUCCESS : AlertRunStatus.FAILED
- }))
- );
+ status: (perTarget.get(targetId) ?? result.success) ? AlertRunStatus.SUCCESS : AlertRunStatus.FAILED
+ }));
+ });
const errors = channelResults
.filter((result) => !result.success && result.error)
@@ -191,7 +201,7 @@ export const alertEngineFactory = ({
logger.error(`Alert delivery failed on one or more channels [alertId=${alert.id}]: ${errorText}`);
}
- await alertHistoryDAL.createWithTargets(alert.id, { status, error: errorText }, deliveries);
+ await alertHistoryDAL.createWithTargets(alert.id, { status }, deliveries);
};
return { runAlert };
diff --git a/backend/src/services/alert/alert-history-dal.ts b/backend/src/services/alert/alert-history-dal.ts
index 479e2bc7f5..844d43c9f7 100644
--- a/backend/src/services/alert/alert-history-dal.ts
+++ b/backend/src/services/alert/alert-history-dal.ts
@@ -23,14 +23,12 @@ export const alertHistoryDALFactory = (db: TDbClient) => {
const createWithTargets = async (
alertId: string,
- options: { status: string; error?: string },
+ options: { status: string },
deliveries: TAlertTargetDelivery[]
): Promise<TAlertHistory> => {
try {
return await db.transaction(async (tx) => {
- const [history] = await tx(TableName.AlertHistory)
- .insert({ alertId, status: options.status, error: options.error })
- .returning("*");
+ const [history] = await tx(TableName.AlertHistory).insert({ alertId, status: options.status }).returning("*");
if (deliveries.length > 0) {
await tx(TableName.AlertHistoryTarget).insert(
diff --git a/backend/src/services/alert/channels/alert-channel-pagerduty-fns.ts b/backend/src/services/alert/channels/alert-channel-pagerduty-fns.ts
index ee11a20d99..7a4dbc4575 100644
--- a/backend/src/services/alert/channels/alert-channel-pagerduty-fns.ts
+++ b/backend/src/services/alert/channels/alert-channel-pagerduty-fns.ts
@@ -92,9 +92,15 @@ export const sendPagerDutyNotification = async (ctx: TAlertChannelSendContext):
)
);
- const errors = results.filter((result) => !result.success && result.error).map((result) => result.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("; ") };
+ return { success: false, error: errors.join("; "), targetResults };
}
- return { success: true };
+ return { success: true, targetResults };
};