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
add metrics
Thiago Araujo da Silva68299d6691c6
diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.tsindex 12c7601319..bebfcff396 100644--- a/backend/src/lib/telemetry/metrics.ts+++ b/backend/src/lib/telemetry/metrics.ts@@ -602,6 +602,37 @@ export const recordDynamicSecretOrphanedLeaseMetric = (params: { provider: strin});};+export enum AlertDispatchOutcome {+ // Notifications were dispatched to at least one channel.+ Dispatched = "dispatched",+ // The alert row is gone by the time the job runs: deleted, or its project soft-deleted.+ AlertNotFound = "alert_not_found",+ // The alert still exists but was disabled between being enqueued and the job running.+ AlertDisabled = "alert_disabled",+ // No provider registered for the alert's resource type (misconfiguration).+ NoProvider = "no_provider",+ // Nothing matched the alert condition in this run.+ NoDueTargets = "no_due_targets",+ // Targets matched, but the alert has no enabled channels to notify.+ NoChannels = "no_channels",+ // Targets matched, but every one had already been alerted inside the dedup window.+ AllDeduped = "all_deduped"+}++export const alertDispatchOutcomeCounter = infisicalCoreMeter.createCounter("infisical.alert.dispatch.outcome.count", {+ description:+ "Alert dispatch jobs by alert resource type and outcome. Watch dispatched / total: a persistently low ratio means the cron is enqueueing mostly no-op jobs and should pre-filter instead.",+ unit: "{job}"+});++export const recordAlertDispatchOutcomeMetric = (params: { resourceType: string; outcome: AlertDispatchOutcome }) => {+ if (!isTelemetryEnabled()) return;+ alertDispatchOutcomeCounter.add(1, {+ type: params.resourceType,+ outcome: params.outcome+ });+};+// -- Boot-time observable gauges (InfisicalCore meter) ----------------------------------------------// Registered once at boot from main.ts with the primary Knex instance. Runs AFTER setupTelemetry() has// installed the real MeterProvider, so we resolve the real meter directly here (observable gauges can'tdiff --git a/backend/src/services/alert/alert-engine.test.ts b/backend/src/services/alert/alert-engine.test.tsindex 87b931ffdb..f662940c39 100644--- a/backend/src/services/alert/alert-engine.test.ts+++ b/backend/src/services/alert/alert-engine.test.ts@@ -1,5 +1,7 @@import { z } from "zod";+import { AlertDispatchOutcome } from "@app/lib/telemetry/metrics";+import { TAlertPayload } from "./alert-channel-types";import { alertEngineFactory, TAlertEngineDep } from "./alert-engine";import { alertProviderRegistryFactory } from "./alert-provider-registry";@@ -169,8 +171,9 @@ describe("alert engine", () => {channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }]});- await engine.runAlert(makeAlert());+ const outcome = await engine.runAlert(makeAlert());+ expect(outcome).toBe(AlertDispatchOutcome.Dispatched);expect(sentMail).toHaveLength(1);expect(sentMail[0].recipients).toEqual(["[email protected]"]);expect(historyWrites).toHaveLength(1);@@ -354,8 +357,11 @@ describe("alert engine", () => {recentlyAlerted: [{ channelId: "c-email", targetId: "t1" }]});- await engine.runAlert(makeAlert());+ const outcome = await engine.runAlert(makeAlert());+ // The outcome feeds the dispatched/no-op ratio metric, so it has to name the stage that+ // discarded the work rather than just reporting "nothing happened".+ expect(outcome).toBe(AlertDispatchOutcome.AllDeduped);expect(sentMail).toHaveLength(0);expect(historyWrites).toHaveLength(0);});@@ -386,8 +392,21 @@ describe("alert engine", () => {channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: false }]});- await engine.runAlert(makeAlert());+ const outcome = await engine.runAlert(makeAlert());++ expect(outcome).toBe(AlertDispatchOutcome.NoChannels);+ expect(historyWrites).toHaveLength(0);+ });++ test("reports no due targets when nothing matches the condition", async () => {+ const { engine, historyWrites } = buildEngine({+ targets: [],+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }]+ });++ const outcome = await engine.runAlert(makeAlert());+ expect(outcome).toBe(AlertDispatchOutcome.NoDueTargets);expect(historyWrites).toHaveLength(0);});});diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.tsindex b3af237a89..c46d8d1cc5 100644--- a/backend/src/services/alert/alert-engine.ts+++ b/backend/src/services/alert/alert-engine.ts@@ -2,6 +2,7 @@ import pLimit from "p-limit";import { TAlerts } from "@app/db/schemas";import { logger } from "@app/lib/logger";+import { AlertDispatchOutcome } from "@app/lib/telemetry/metrics";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TSmtpService } from "@app/services/smtp/smtp-service";@@ -47,11 +48,11 @@ export const alertEngineFactory = ({kmsService,smtpService}: TAlertEngineDep) => {- const runAlert = async (alert: TAlerts, opts?: { asOf?: Date }) => {+ const runAlert = async (alert: TAlerts, opts?: { asOf?: Date }): Promise<AlertDispatchOutcome> => {const provider = alertProviderRegistry.get(alert.resourceType);if (!provider) {logger.warn(`No alert provider registered for resource type '${alert.resourceType}' [alertId=${alert.id}]`);- return;+ return AlertDispatchOutcome.NoProvider;}const targets = await provider.findDueTargets({@@ -62,10 +63,10 @@ export const alertEngineFactory = ({condition: alert.condition,asOf: opts?.asOf ?? new Date()});- if (targets.length === 0) return;+ if (targets.length === 0) return AlertDispatchOutcome.NoDueTargets;const channels = await alertChannelDAL.findByAlertId(alert.id, { enabled: true });- if (channels.length === 0) return;+ if (channels.length === 0) return AlertDispatchOutcome.NoChannels;const window = provider.dedupWindowHours?.(alert.condition) ?? DEFAULT_DEDUP_WINDOW_HOURS;const candidateIds = targets.map((target) => provider.targetId(target));@@ -86,7 +87,7 @@ export const alertEngineFactory = ({return { channel, dueTargets };}).filter((work) => work.dueTargets.length > 0);- if (channelWork.length === 0) return;+ if (channelWork.length === 0) return AlertDispatchOutcome.AllDeduped;const alertContext: TAlertContext = {id: alert.id,@@ -202,6 +203,8 @@ export const alertEngineFactory = ({}await alertHistoryDAL.createWithTargets(alert.id, { status }, deliveries);++ return AlertDispatchOutcome.Dispatched;};return { runAlert };diff --git a/backend/src/services/alert/alert-queue.ts b/backend/src/services/alert/alert-queue.tsindex 84df78d116..b2c0677198 100644--- a/backend/src/services/alert/alert-queue.ts+++ b/backend/src/services/alert/alert-queue.ts@@ -1,6 +1,7 @@import { getConfig } from "@app/lib/config/env";import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";import { logger } from "@app/lib/logger";+import { AlertDispatchOutcome, recordAlertDispatchOutcomeMetric } from "@app/lib/telemetry/metrics";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { TAlertDALFactory } from "./alert-dal";@@ -56,8 +57,24 @@ export const alertQueueServiceFactory = ({async (job) => {const { alertId, scheduledAt } = job.data;const alert = await alertDAL.findActiveById(alertId);- if (!alert || !alert.enabled) return;- await alertEngine.runAlert(alert, { asOf: scheduledAt ? new Date(scheduledAt) : new Date() });++ if (!alert) {+ recordAlertDispatchOutcomeMetric({ resourceType: "unknown", outcome: AlertDispatchOutcome.AlertNotFound });+ return;+ }++ if (!alert.enabled) {+ recordAlertDispatchOutcomeMetric({+ resourceType: alert.resourceType,+ outcome: AlertDispatchOutcome.AlertDisabled+ });+ return;+ }++ const outcome = await alertEngine.runAlert(alert, {+ asOf: scheduledAt ? new Date(scheduledAt) : new Date()+ });+ recordAlertDispatchOutcomeMetric({ resourceType: alert.resourceType, outcome });},{ concurrency: ALERT_DISPATCH_CONCURRENCY });