diff --git a/.changeset/alert-renotify-interval.md b/.changeset/alert-renotify-interval.md new file mode 100644 index 000000000..b8d46b196 --- /dev/null +++ b/.changeset/alert-renotify-interval.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/common-utils': minor +'@hyperdx/app': minor +'@hyperdx/api': minor +--- + +feat: alerts get an opt-in "Re-notify every N minutes" setting (`renotifyIntervalMinutes`). While an alert keeps firing it notifies at most once per interval; unset keeps today's behaviour of notifying on every evaluation. Resolve notifications are unchanged. diff --git a/packages/api/openapi.json b/packages/api/openapi.json index 735ea5c34..44388fca7 100644 --- a/packages/api/openapi.json +++ b/packages/api/openapi.json @@ -419,6 +419,13 @@ "nullable": true, "description": "Fire the alert only after its condition has been met for this many consecutive evaluation windows. While the condition is met but fewer than this many consecutive windows have violated, the alert is in the PENDING state.", "example": 3 + }, + "renotifyIntervalMinutes": { + "type": "integer", + "minimum": 1, + "nullable": true, + "description": "While the alert keeps firing, repeat its notification at most once every this many minutes. Omit or set to null to notify on every evaluation. A resolve notification is always sent when the alert returns to OK.", + "example": 60 } } }, diff --git a/packages/api/src/controllers/alerts.ts b/packages/api/src/controllers/alerts.ts index e51887ec8..ef7c43dc3 100644 --- a/packages/api/src/controllers/alerts.ts +++ b/packages/api/src/controllers/alerts.ts @@ -336,6 +336,7 @@ export const makeAlert = ( // Multi-window alerting numConsecutiveWindows: alert.numConsecutiveWindows ?? null, + renotifyIntervalMinutes: alert.renotifyIntervalMinutes ?? null, }; }; diff --git a/packages/api/src/mcp/__tests__/alerts.int.test.ts b/packages/api/src/mcp/__tests__/alerts.int.test.ts index 8350abd54..9121c75de 100644 --- a/packages/api/src/mcp/__tests__/alerts.int.test.ts +++ b/packages/api/src/mcp/__tests__/alerts.int.test.ts @@ -1388,7 +1388,7 @@ describe('MCP Alert Tools', () => { expect(updatedAlert?.tileId).toBeNull(); }); - describe('note and numConsecutiveWindows', () => { + describe('note, numConsecutiveWindows and renotifyIntervalMinutes', () => { async function saveExisting( alertId: string, savedSearchId: string, @@ -1412,6 +1412,7 @@ describe('MCP Alert Tools', () => { const alert = await createTestAlert({ note: 'Set in the UI', numConsecutiveWindows: 4, + renotifyIntervalMinutes: 30, }); const result = await saveExisting( @@ -1425,6 +1426,8 @@ describe('MCP Alert Tools', () => { expect(output.threshold).toBe(200); expect(output.note).toBe('Set in the UI'); expect(output.numConsecutiveWindows).toBe(4); + const persisted = await Alert.findById(alert._id); + expect(persisted?.renotifyIntervalMinutes).toBe(30); }); it('replaces the stored values when provided', async () => { @@ -1432,19 +1435,25 @@ describe('MCP Alert Tools', () => { const alert = await createTestAlert({ note: 'Set in the UI', numConsecutiveWindows: 4, + renotifyIntervalMinutes: 30, }); const result = await saveExisting( alert._id.toString(), alert.savedSearch!.toString(), webhook._id.toString(), - { note: 'Updated note', numConsecutiveWindows: 2 }, + { + note: 'Updated note', + numConsecutiveWindows: 2, + renotifyIntervalMinutes: 60, + }, ); expect(result.isError).toBeFalsy(); const persisted = await Alert.findById(alert._id); expect(persisted?.note).toBe('Updated note'); expect(persisted?.numConsecutiveWindows).toBe(2); + expect(persisted?.renotifyIntervalMinutes).toBe(60); }); it('clears the stored values when sent as null', async () => { @@ -1452,19 +1461,25 @@ describe('MCP Alert Tools', () => { const alert = await createTestAlert({ note: 'Set in the UI', numConsecutiveWindows: 4, + renotifyIntervalMinutes: 30, }); const result = await saveExisting( alert._id.toString(), alert.savedSearch!.toString(), webhook._id.toString(), - { note: null, numConsecutiveWindows: null }, + { + note: null, + numConsecutiveWindows: null, + renotifyIntervalMinutes: null, + }, ); expect(result.isError).toBeFalsy(); const persisted = await Alert.findById(alert._id); expect(persisted?.note).toBeNull(); expect(persisted?.numConsecutiveWindows).toBeNull(); + expect(persisted?.renotifyIntervalMinutes).toBeNull(); }); }); diff --git a/packages/api/src/mcp/tools/alerts/saveAlert.ts b/packages/api/src/mcp/tools/alerts/saveAlert.ts index 24883dc01..b188d8498 100644 --- a/packages/api/src/mcp/tools/alerts/saveAlert.ts +++ b/packages/api/src/mcp/tools/alerts/saveAlert.ts @@ -56,8 +56,9 @@ export function registerSaveAlert({ '(webhook IDs come from clickstack_get_webhook). Updates replace the ' + 'alert configuration rather than merging it: channels you do not resend are ' + 'removed, omitted name and message are cleared, and omitted displayName ' + - 'and tags are re-derived from the source. Omitted note and ' + - 'numConsecutiveWindows keep their stored values. Omitting both ' + + 'and tags are re-derived from the source. Omitted note, ' + + 'numConsecutiveWindows and renotifyIntervalMinutes keep their stored ' + + 'values. Omitting both ' + 'scheduleStartAt and scheduleOffsetMinutes keeps the stored schedule; ' + 'clearing scheduleStartAt without an offset resets the offset to 0. Read the alert with ' + 'clickstack_get_alert first and resend every field you want to keep.', @@ -123,7 +124,8 @@ export function registerSaveAlert({ scheduleStartAt: input.scheduleStartAt, name: input.name, message: input.message, - // Unlike name and message, an omitted note or window count keeps the + // Unlike name and message, an omitted note, window count or re-notify + // interval keeps the // stored value: callers written before this tool accepted them would // otherwise wipe what was set in the UI. null still clears. note: input.note === undefined ? existing?.note : input.note, @@ -131,6 +133,10 @@ export function registerSaveAlert({ input.numConsecutiveWindows === undefined ? existing?.numConsecutiveWindows : input.numConsecutiveWindows, + renotifyIntervalMinutes: + input.renotifyIntervalMinutes === undefined + ? existing?.renotifyIntervalMinutes + : input.renotifyIntervalMinutes, displayName: input.displayName, tags: input.tags, groupBy: input.groupBy, diff --git a/packages/api/src/mcp/tools/alerts/schemas.ts b/packages/api/src/mcp/tools/alerts/schemas.ts index b9c019f16..759434ce2 100644 --- a/packages/api/src/mcp/tools/alerts/schemas.ts +++ b/packages/api/src/mcp/tools/alerts/schemas.ts @@ -4,6 +4,7 @@ import { type AlertInterval, alertNoteSchema, alertNumConsecutiveWindowsSchema, + alertRenotifyIntervalMinutesSchema, checkAlertChannelSelection, isRangeThresholdType, MAX_ALERT_CHANNELS, @@ -234,6 +235,11 @@ export const mcpSaveAlertSchema = z.object({ 'boundary. Must be less than the interval. Ignored when ' + 'scheduleStartAt is set.', ), + renotifyIntervalMinutes: alertRenotifyIntervalMinutesSchema.describe( + 'While the alert keeps firing, repeat its notification at most once ' + + 'every N minutes. null notifies on every evaluation; omitting it ' + + 'keeps the stored value. A resolve notification is always sent.', + ), scheduleStartAt: z .string() .datetime() diff --git a/packages/api/src/models/alert.ts b/packages/api/src/models/alert.ts index 3e62d19ea..e88422b22 100644 --- a/packages/api/src/models/alert.ts +++ b/packages/api/src/models/alert.ts @@ -127,6 +127,9 @@ export interface IAlert { // Multi-window alerting: fire only after N violations in M consecutive windows numConsecutiveWindows?: number | null; + // While firing, notify at most every N minutes; unset notifies on every evaluation. + renotifyIntervalMinutes?: number | null; + // Errors recorded during the most recent execution executionErrors?: IAlertError[]; createdAt: Date; @@ -256,6 +259,11 @@ const AlertSchema = new Schema( required: false, min: 1, }, + renotifyIntervalMinutes: { + type: Number, + required: false, + min: 1, + }, silenced: { required: false, type: { diff --git a/packages/api/src/models/alertHistory.ts b/packages/api/src/models/alertHistory.ts index 203fbe074..2ca609b2f 100644 --- a/packages/api/src/models/alertHistory.ts +++ b/packages/api/src/models/alertHistory.ts @@ -74,6 +74,7 @@ export interface IAlertHistory { errors?: IAlertError[]; /** Diagnostics for the evaluation that wrote this record. */ analytics?: IAlertHistoryAnalytics; + lastNotifiedAt?: Date; } const AlertHistorySchema = new Schema({ @@ -162,6 +163,10 @@ const AlertHistorySchema = new Schema({ required: false, default: undefined, }, + lastNotifiedAt: { + type: Date, + required: false, + }, }); AlertHistorySchema.index( diff --git a/packages/api/src/routers/api/alerts.ts b/packages/api/src/routers/api/alerts.ts index a6264db35..f53ab7092 100644 --- a/packages/api/src/routers/api/alerts.ts +++ b/packages/api/src/routers/api/alerts.ts @@ -123,6 +123,7 @@ const formatAlertResponse = ( 'updatedAt', 'executionErrors', 'numConsecutiveWindows', + 'renotifyIntervalMinutes', ]), tileId: alert.tileId ?? undefined, groupBy: alert.groupBy ?? undefined, diff --git a/packages/api/src/routers/external-api/__tests__/alerts.int.test.ts b/packages/api/src/routers/external-api/__tests__/alerts.int.test.ts index a0f93373a..a775062c3 100644 --- a/packages/api/src/routers/external-api/__tests__/alerts.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/alerts.int.test.ts @@ -512,6 +512,7 @@ describe('External API Alerts', () => { message: 'This is a test alert for format verification', note: null, numConsecutiveWindows: null, + renotifyIntervalMinutes: null, threshold: 123, interval: '15m', source: AlertSource.TILE, @@ -3173,6 +3174,42 @@ describe('External API Alerts', () => { expect(getResponse.body.data.numConsecutiveWindows).toBeNull(); }); }); + describe('Re-notification interval (renotifyIntervalMinutes)', () => { + it('should create an alert with renotifyIntervalMinutes and return it on GET', async () => { + const { alert } = await createTestAlert({ renotifyIntervalMinutes: 60 }); + expect(alert.renotifyIntervalMinutes).toBe(60); + + const getResponse = await authRequest( + 'get', + `${ALERTS_BASE_URL}/${alert.id}`, + ).expect(200); + expect(getResponse.body.data.renotifyIntervalMinutes).toBe(60); + }); + + it('should update an alert to set and then clear renotifyIntervalMinutes', async () => { + const { alert, alertInput } = await createTestAlert(); + expect(alert.renotifyIntervalMinutes).toBeNull(); + + const getRenotify = async () => + (await authRequest('get', `${ALERTS_BASE_URL}/${alert.id}`).expect(200)) + .body.data.renotifyIntervalMinutes; + + await authRequest('put', `${ALERTS_BASE_URL}/${alert.id}`) + .send({ ...alertInput, renotifyIntervalMinutes: 30 }) + .expect(200); + expect(await getRenotify()).toBe(30); + + // Unset already means every evaluation, so 0 has no meaning. + await authRequest('put', `${ALERTS_BASE_URL}/${alert.id}`) + .send({ ...alertInput, renotifyIntervalMinutes: 0 }) + .expect(400); + + await authRequest('put', `${ALERTS_BASE_URL}/${alert.id}`) + .send({ ...alertInput, renotifyIntervalMinutes: null }) + .expect(200); + expect(await getRenotify()).toBeNull(); + }); + }); describe('Multiple notification channels', () => { const makeWebhookNamed = async (name: string) => await Webhook.findOneAndUpdate( diff --git a/packages/api/src/routers/external-api/v2/alerts.ts b/packages/api/src/routers/external-api/v2/alerts.ts index f4abc4c2c..a1a0a92d5 100644 --- a/packages/api/src/routers/external-api/v2/alerts.ts +++ b/packages/api/src/routers/external-api/v2/alerts.ts @@ -329,6 +329,12 @@ function toInternalAlertInput(body: ExternalAlertInput): InternalAlertInput { * nullable: true * description: Fire the alert only after its condition has been met for this many consecutive evaluation windows. While the condition is met but fewer than this many consecutive windows have violated, the alert is in the PENDING state. * example: 3 + * renotifyIntervalMinutes: + * type: integer + * minimum: 1 + * nullable: true + * description: While the alert keeps firing, repeat its notification at most once every this many minutes. Omit or set to null to notify on every evaluation. A resolve notification is always sent when the alert returns to OK. + * example: 60 * * AlertResponse: * allOf: diff --git a/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts index 2fe606d23..59f69cb10 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts @@ -11508,6 +11508,153 @@ describe('checkAlerts', () => { ); }); + describe('re-notification (renotifyIntervalMinutes)', () => { + // Breaching rows in the given 5m windows (service 'api' unless given as + // [time, service]); evaluations run 2m after each window closes. + const runBreaches = async ( + windows: (string | [string, string])[], + evaluations: string[], + renotifyIntervalMinutes?: number, + groupBy?: string, + silencedEvaluations: number[] = [], + ) => { + const { + team, + webhook, + connection, + source, + savedSearch, + teamWebhooksById, + clickhouseClient, + } = await setupSavedSearchAlertTest(); + + jest + .spyOn(slack, 'postMessageToWebhook') + .mockResolvedValue({ text: 'ok' }); + + const details = await createAlertDetails( + team, + source, + { + source: AlertSource.SAVED_SEARCH, + channel: { type: 'webhook', webhookId: webhook._id.toString() }, + interval: '5m', + thresholdType: AlertThresholdType.ABOVE, + threshold: 1, + savedSearchId: savedSearch.id, + renotifyIntervalMinutes, + groupBy, + }, + { taskType: AlertTaskType.SAVED_SEARCH, savedSearch }, + ); + + await bulkInsertLogs( + windows.map(w => ({ + ServiceName: typeof w === 'string' ? 'api' : w[1], + Timestamp: new Date( + `2024-01-01T${typeof w === 'string' ? w : w[0]}Z`, + ), + SeverityText: 'error', + Body: 'err', + })), + ); + + const notificationCounts: number[] = []; + for (const [i, time] of evaluations.entries()) { + details.alert.silenced = silencedEvaluations.includes(i) + ? { at: new Date(), until: new Date(Date.now() + 3600000) } + : undefined; + await processAlertAtTime( + new Date(`2024-01-01T${time}Z`), + details, + clickhouseClient, + connection, + alertProvider, + teamWebhooksById, + ); + notificationCounts.push( + jest.mocked(slack.postMessageToWebhook).mock.calls.length, + ); + } + + const histories = await AlertHistory.find({ + alert: details.alert.id, + }).sort({ createdAt: 1 }); + return { notificationCounts, histories }; + }; + + const SUSTAINED = ['00:05:00', '00:10:00', '00:15:00', '00:20:00']; + const EVALUATIONS = ['00:12:00', '00:17:00', '00:22:00', '00:27:00']; + + it('notifies on every evaluation when unset', async () => { + const { notificationCounts } = await runBreaches( + SUSTAINED, + EVALUATIONS, + ); + expect(notificationCounts).toEqual([1, 2, 3, 4]); + }); + + it('re-notifies only once the interval has passed', async () => { + // 10m interval, 5m windows: notify, skip, notify, skip. + const { notificationCounts, histories } = await runBreaches( + SUSTAINED, + EVALUATIONS, + 10, + ); + expect(notificationCounts).toEqual([1, 1, 2, 2]); + expect(histories.map(h => h.lastNotifiedAt?.toISOString())).toEqual([ + '2024-01-01T00:10:00.000Z', + '2024-01-01T00:10:00.000Z', + '2024-01-01T00:20:00.000Z', + '2024-01-01T00:20:00.000Z', + ]); + }); + + it('notifies a new incident after a resolve, inside the interval', async () => { + // ALERT, OK (resolve notification), ALERT again. + const { notificationCounts, histories } = await runBreaches( + ['00:05:00', '00:15:00'], + ['00:12:00', '00:17:00', '00:22:00'], + 60, + ); + expect(histories.map(h => h.state)).toEqual(['ALERT', 'OK', 'ALERT']); + expect(notificationCounts).toEqual([1, 2, 3]); + }); + + it('keeps the interval across a short silence', async () => { + const { notificationCounts, histories } = await runBreaches( + SUSTAINED, + EVALUATIONS, + 30, + undefined, + [1], + ); + expect(notificationCounts).toEqual([1, 1, 1, 1]); + expect(histories.map(h => h.lastNotifiedAt?.toISOString())).toEqual( + Array(4).fill('2024-01-01T00:10:00.000Z'), + ); + }); + + it('keeps a separate interval for each group', async () => { + // a breaches from 00:05, b from 00:10; both every window after that. + const { histories } = await runBreaches( + [ + ...SUSTAINED.map((t): [string, string] => [t, 'a']), + ...SUSTAINED.slice(1).map((t): [string, string] => [t, 'b']), + ], + EVALUATIONS, + 10, + 'ServiceName', + ); + const notifiedAt = (service: string) => + histories + .filter(h => h.group === `ServiceName:${service}`) + .map(h => h.lastNotifiedAt?.toISOString().slice(11, 16)); + expect(notifiedAt('a')).toEqual(['00:10', '00:10', '00:20', '00:20']); + expect(notifiedAt('b')).toEqual(['00:15', '00:15', '00:25']); + }); + }); + describe('multi-window alerting (numConsecutiveWindows)', () => { it('fires on the first violation when numConsecutiveWindows=1', async () => { const { diff --git a/packages/api/src/tasks/checkAlerts/evaluators.ts b/packages/api/src/tasks/checkAlerts/evaluators.ts index c2504fffd..3f6c075a1 100644 --- a/packages/api/src/tasks/checkAlerts/evaluators.ts +++ b/packages/api/src/tasks/checkAlerts/evaluators.ts @@ -46,7 +46,10 @@ export interface AlertEvaluationContext { /** Errors collected so far (e.g. failed notification targets). */ executionErrors: IAlertError[]; getOrCreateHistory: (groupKey: string) => IAlertHistory; - /** Resolves false when the send was suppressed (the alert is silenced). */ + /** + * Resolves false when the send was suppressed: the alert is silenced, or it + * is still firing inside its re-notify interval (so `fired` stays true). + */ trySendNotification: (args: { state: AlertState; totalCount: number; diff --git a/packages/api/src/tasks/checkAlerts/index.ts b/packages/api/src/tasks/checkAlerts/index.ts index 404108a7f..7837d0258 100644 --- a/packages/api/src/tasks/checkAlerts/index.ts +++ b/packages/api/src/tasks/checkAlerts/index.ts @@ -1340,7 +1340,7 @@ export const processAlert = async ( // Resolves true when a dispatch was attempted (even if delivery later // fails — failures surface via executionErrors, mirroring the threshold // path which marks history.fired before dispatching), and false when the - // send was suppressed entirely (silenced). + // send was suppressed entirely (silenced, or inside the re-notify interval). const trySendNotification = async ({ group, totalCount, @@ -1360,6 +1360,19 @@ export const processAlert = async ( // execution may still send a notification. Subsequent alert checks will // respect the silenced state. This trade-off maintains architectural // separation from direct database access. + // Opt-in re-notify interval: a group that was already firing carries its + // last notification time forward, silenced or not, so the previous + // evaluation is all this needs to read. + const renotifyMinutes = + state === AlertState.ALERT ? alert.renotifyIntervalMinutes : undefined; + if (renotifyMinutes) { + const previous = previousMap.get(computeHistoryMapKey(alert.id, group)); + getOrCreateHistory(group).lastNotifiedAt = + previous?.state === AlertState.ALERT + ? previous.lastNotifiedAt + : undefined; + } + if ((alert.silenced?.until?.getTime() ?? 0) > Date.now()) { alertEvaluationsCounter.add(1, { outcome: 'skipped_silenced' }); logger.info( @@ -1372,6 +1385,19 @@ export const processAlert = async ( return false; } + if (renotifyMinutes) { + const history = getOrCreateHistory(group); + if ( + history.lastNotifiedAt && + nowInMinsRoundDown < + fns.addMinutes(history.lastNotifiedAt, renotifyMinutes) + ) { + alertEvaluationsCounter.add(1, { outcome: 'skipped_renotify' }); + return false; + } + history.lastNotifiedAt = nowInMinsRoundDown; + } + alertEvaluationsCounter.add(1, { outcome: state === AlertState.ALERT ? 'fired' : 'resolved', }); @@ -1865,7 +1891,8 @@ export const processAlert = async ( const hitAlertThisRun = latestAlertContext.has(groupKey); - // If it hit ALERT during this run, send the notification (re-notifying every tick if it continuously breaches) + // If it hit ALERT during this run, send the notification (re-notifying every tick + // if it continuously breaches, unless renotifyIntervalMinutes spaces them out) if (hitAlertThisRun) { const context = latestAlertContext.get(groupKey); if (context) { @@ -1959,6 +1986,7 @@ export interface AggregatedAlertHistory { state: AlertState; group?: string; fired?: boolean; + lastNotifiedAt?: Date; groupValues?: GroupValue[] | null; } @@ -1997,7 +2025,7 @@ export const getAlertHistoryLookbackMs = (interval: AlertInterval): number => { /** Latest AlertHistory row per alert, minus the fat `lastValues` array. */ export type LatestAlertHistory = Pick< AggregatedAlertHistory, - 'createdAt' | 'state' | 'group' | 'fired' + 'createdAt' | 'state' | 'group' | 'fired' | 'lastNotifiedAt' >; /** @@ -2043,6 +2071,7 @@ export const getLatestAlertHistories = async ( state: 1, group: 1, fired: 1, + lastNotifiedAt: 1, }, ) .sort({ createdAt: -1 }) @@ -2063,6 +2092,7 @@ export const getLatestAlertHistories = async ( state: latest.state, group: latest.group, fired: latest.fired, + lastNotifiedAt: latest.lastNotifiedAt, } : null, ]), @@ -2133,6 +2163,7 @@ export const getPreviousAlertHistories = async ( state: 1, createdAt: 1, fired: 1, + lastNotifiedAt: 1, groupValues: 1, }, ) @@ -2153,6 +2184,7 @@ export const getPreviousAlertHistories = async ( state: row.state, group: row.group, fired: row.fired, + lastNotifiedAt: row.lastNotifiedAt, groupValues: row.groupValues, }); } diff --git a/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts b/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts index 81d7a7689..b815587ac 100644 --- a/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts @@ -847,6 +847,7 @@ describe('DefaultAlertProvider', () => { state: AlertState.ALERT, group: '', fired: true, + lastNotifiedAt: new Date(base - 3 * windowMs), }); const findSpy = jest.spyOn(AlertHistory, 'find'); @@ -865,6 +866,7 @@ describe('DefaultAlertProvider', () => { expect(previous!.createdAt).toEqual(newest.createdAt); expect(previous!.state).toBe(AlertState.ALERT); expect(previous!.fired).toBe(true); + expect(previous!.lastNotifiedAt).toEqual(newest.lastNotifiedAt); }); it('skips the per-group history fetch for alerts with no history at all', async () => { @@ -942,6 +944,7 @@ describe('DefaultAlertProvider', () => { state: AlertState.ALERT, group: 'ServiceName:a', fired: true, + lastNotifiedAt: twoDaysAgo, groupValues: [{ key: 'ServiceName', value: 'a' }], }); await AlertHistory.create({ @@ -975,6 +978,7 @@ describe('DefaultAlertProvider', () => { expect(groupA?.createdAt).toEqual(twoDaysAgo); expect(groupA?.state).toBe(AlertState.ALERT); expect(groupA?.fired).toBe(true); + expect(groupA?.lastNotifiedAt).toEqual(twoDaysAgo); expect(groupA?.groupValues).toEqual([ { key: 'ServiceName', value: 'a' }, ]); diff --git a/packages/api/src/tasks/checkAlerts/providers/default.ts b/packages/api/src/tasks/checkAlerts/providers/default.ts index bed6d5210..892a6f1a9 100644 --- a/packages/api/src/tasks/checkAlerts/providers/default.ts +++ b/packages/api/src/tasks/checkAlerts/providers/default.ts @@ -491,6 +491,7 @@ async function loadAlerts(): Promise { state: latest.state, group: latest.group, fired: latest.fired, + lastNotifiedAt: latest.lastNotifiedAt, }); } @@ -515,7 +516,14 @@ async function loadAlerts(): Promise { createdAt: latest.createdAt, state: { $ne: AlertState.ERROR }, }, - { group: 1, state: 1, createdAt: 1, fired: 1, groupValues: 1 }, + { + group: 1, + state: 1, + createdAt: 1, + fired: 1, + lastNotifiedAt: 1, + groupValues: 1, + }, ).lean(); for (const row of rows) { previousAlerts.set(computeHistoryMapKey(alert.id, row.group || ''), { @@ -524,6 +532,7 @@ async function loadAlerts(): Promise { state: row.state, group: row.group, fired: row.fired, + lastNotifiedAt: row.lastNotifiedAt, groupValues: row.groupValues, }); } diff --git a/packages/api/src/utils/externalApi.ts b/packages/api/src/utils/externalApi.ts index c445cb574..23f71dcd5 100644 --- a/packages/api/src/utils/externalApi.ts +++ b/packages/api/src/utils/externalApi.ts @@ -350,6 +350,7 @@ export type ExternalAlert = { scheduleOffsetMinutes?: number; scheduleStartAt?: string | null; numConsecutiveWindows?: number | null; + renotifyIntervalMinutes?: number | null; thresholdType: AlertThresholdType; source?: string; state: AlertState; @@ -523,6 +524,7 @@ export function translateAlertDocumentToExternalAlert( }), scheduleStartAt: transformScheduleStartAt(alertObj.scheduleStartAt), numConsecutiveWindows: alertObj.numConsecutiveWindows ?? null, + renotifyIntervalMinutes: alertObj.renotifyIntervalMinutes ?? null, thresholdType: alertObj.thresholdType, source: alertObj.source, state: alertObj.state, diff --git a/packages/api/src/utils/zod.ts b/packages/api/src/utils/zod.ts index 3ab00b89f..94390f371 100644 --- a/packages/api/src/utils/zod.ts +++ b/packages/api/src/utils/zod.ts @@ -9,6 +9,7 @@ import { alertDisplayNameSchema, alertNoteSchema, alertNumConsecutiveWindowsSchema, + alertRenotifyIntervalMinutesSchema, alertTagsSchema, AlertThresholdType, BackgroundChartSchema, @@ -1311,6 +1312,7 @@ const alertBaseSchema = z.object({ displayName: alertDisplayNameSchema, tags: alertTagsSchema, numConsecutiveWindows: alertNumConsecutiveWindowsSchema, + renotifyIntervalMinutes: alertRenotifyIntervalMinutesSchema, }); // External v2 alert schema. Inline alerts carry their chart config in the diff --git a/packages/app/src/DBSearchPageAlertModal.tsx b/packages/app/src/DBSearchPageAlertModal.tsx index 2c540742f..ad2b1d7c9 100644 --- a/packages/app/src/DBSearchPageAlertModal.tsx +++ b/packages/app/src/DBSearchPageAlertModal.tsx @@ -15,6 +15,7 @@ import { alertDisplayNameSchema, AlertIntervalSchema, alertNumConsecutiveWindowsSchema, + alertRenotifyIntervalMinutesSchema, AlertSource, alertTagsSchema, AlertThresholdType, @@ -93,6 +94,7 @@ const SavedSearchAlertFormSchema = z displayName: alertDisplayNameSchema, tags: alertTagsSchema, numConsecutiveWindows: alertNumConsecutiveWindowsSchema, + renotifyIntervalMinutes: alertRenotifyIntervalMinutesSchema, }) .passthrough() .superRefine(validateAlertScheduleOffsetMinutes) @@ -212,6 +214,8 @@ const AlertForm = ({ // Persisted null -> undefined for the NumberInput. numConsecutiveWindows: defaultValues.numConsecutiveWindows ?? undefined, + renotifyIntervalMinutes: + defaultValues.renotifyIntervalMinutes ?? undefined, } : { interval: '5m', @@ -240,6 +244,10 @@ const AlertForm = ({ control, name: 'numConsecutiveWindows', }); + const renotifyIntervalMinutes = useWatch({ + control, + name: 'renotifyIntervalMinutes', + }); const maxScheduleOffsetMinutes = Math.max( intervalToMinutes(interval ?? '5m') - 1, 0, @@ -383,6 +391,8 @@ const AlertForm = ({ offsetWindowLabel={`from each ${intervalLabel} window`} numConsecutiveWindowsName="numConsecutiveWindows" numConsecutiveWindows={numConsecutiveWindows ?? undefined} + renotifyIntervalName="renotifyIntervalMinutes" + renotifyIntervalMinutes={renotifyIntervalMinutes ?? undefined} /> grouped by diff --git a/packages/app/src/components/AlertScheduleFields.tsx b/packages/app/src/components/AlertScheduleFields.tsx index 774baca58..ff5b52615 100644 --- a/packages/app/src/components/AlertScheduleFields.tsx +++ b/packages/app/src/components/AlertScheduleFields.tsx @@ -38,6 +38,8 @@ type AlertScheduleFieldsProps = { offsetWindowLabel: string; numConsecutiveWindowsName?: FieldPath; numConsecutiveWindows?: number; + renotifyIntervalName?: FieldPath; + renotifyIntervalMinutes?: number; }; export function AlertScheduleFields({ @@ -50,6 +52,8 @@ export function AlertScheduleFields({ offsetWindowLabel, numConsecutiveWindowsName, numConsecutiveWindows, + renotifyIntervalName, + renotifyIntervalMinutes, }: AlertScheduleFieldsProps) { const showScheduleOffsetInput = maxScheduleOffsetMinutes > 0; const scheduleStartAtValue = useWatch({ @@ -60,7 +64,8 @@ export function AlertScheduleFields({ const hasAdvancedScheduleValues = (scheduleOffsetMinutes ?? 0) > 0 || hasScheduleStartAtAnchor || - (numConsecutiveWindows ?? 1) > 1; + (numConsecutiveWindows ?? 1) > 1 || + renotifyIntervalMinutes != null; const [opened, setOpened] = useState(hasAdvancedScheduleValues); useEffect(() => { @@ -149,6 +154,47 @@ export function AlertScheduleFields({ )} + {renotifyIntervalName && ( + + + + Re-notify every + + + + + + + + ( + + field.onChange(typeof v === 'number' ? v : undefined) + } + min={1} + allowDecimal={false} + allowNegative={false} + size="xs" + w={90} + /> + )} + /> + + minutes + + + )} {showScheduleOffsetInput && ( <> diff --git a/packages/app/src/components/DBEditTimeChartForm/TileAlertEditor.tsx b/packages/app/src/components/DBEditTimeChartForm/TileAlertEditor.tsx index 5b3c22546..28dafe87a 100644 --- a/packages/app/src/components/DBEditTimeChartForm/TileAlertEditor.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/TileAlertEditor.tsx @@ -97,6 +97,10 @@ export function TileAlertEditor({ control, name: 'alert.numConsecutiveWindows', }); + const alertRenotifyIntervalMinutes = useWatch({ + control, + name: 'alert.renotifyIntervalMinutes', + }); const maxAlertScheduleOffsetMinutes = alert?.interval ? Math.max(intervalToMinutes(alert.interval) - 1, 0) : 0; @@ -292,6 +296,8 @@ export function TileAlertEditor({ } numConsecutiveWindowsName="alert.numConsecutiveWindows" numConsecutiveWindows={alertnumConsecutiveWindows ?? undefined} + renotifyIntervalName="alert.renotifyIntervalMinutes" + renotifyIntervalMinutes={alertRenotifyIntervalMinutes ?? undefined} /> Send to diff --git a/packages/app/src/components/alerts/AlertPropertiesSummary.tsx b/packages/app/src/components/alerts/AlertPropertiesSummary.tsx index 233b082eb..2bccb0062 100644 --- a/packages/app/src/components/alerts/AlertPropertiesSummary.tsx +++ b/packages/app/src/components/alerts/AlertPropertiesSummary.tsx @@ -204,6 +204,15 @@ export function AlertPropertiesSummary({ )} + {alert.renotifyIntervalMinutes != null && ( + <> + · + + Re-notifies every {alert.renotifyIntervalMinutes} min while + firing + + + )} )} · diff --git a/packages/app/src/components/alerts/EditAlertModal.tsx b/packages/app/src/components/alerts/EditAlertModal.tsx index 31be03de4..c755a6b30 100644 --- a/packages/app/src/components/alerts/EditAlertModal.tsx +++ b/packages/app/src/components/alerts/EditAlertModal.tsx @@ -8,6 +8,7 @@ import { alertDisplayNameSchema, AlertIntervalSchema, alertNumConsecutiveWindowsSchema, + alertRenotifyIntervalMinutesSchema, AlertSource, alertTagsSchema, AlertThresholdType, @@ -76,6 +77,7 @@ const EditAlertFormSchema = z displayName: alertDisplayNameSchema, tags: alertTagsSchema, numConsecutiveWindows: alertNumConsecutiveWindowsSchema, + renotifyIntervalMinutes: alertRenotifyIntervalMinutesSchema, }) .passthrough() .superRefine(validateAlertChannelSelection) @@ -114,6 +116,7 @@ function alertToFormValues(alert: AlertsPageItem): Alert { tags: alert.tags, // Persisted null -> undefined for the NumberInput. numConsecutiveWindows: alert.numConsecutiveWindows ?? undefined, + renotifyIntervalMinutes: alert.renotifyIntervalMinutes ?? undefined, }; if (alert.source === AlertSource.TILE) { @@ -215,6 +218,10 @@ export function EditAlertModal({ control, name: 'numConsecutiveWindows', }); + const renotifyIntervalMinutes = useWatch({ + control, + name: 'renotifyIntervalMinutes', + }); const maxScheduleOffsetMinutes = Math.max( intervalToMinutes(interval ?? '5m') - 1, @@ -418,6 +425,8 @@ export function EditAlertModal({ offsetWindowLabel={`from each ${intervalLabel} window`} numConsecutiveWindowsName="numConsecutiveWindows" numConsecutiveWindows={numConsecutiveWindows ?? undefined} + renotifyIntervalName="renotifyIntervalMinutes" + renotifyIntervalMinutes={renotifyIntervalMinutes ?? undefined} /> {!isChartAlert && ( <> diff --git a/packages/app/src/components/alerts/EditInlineAlertModal.tsx b/packages/app/src/components/alerts/EditInlineAlertModal.tsx index 98dbc9590..a21fe2079 100644 --- a/packages/app/src/components/alerts/EditInlineAlertModal.tsx +++ b/packages/app/src/components/alerts/EditInlineAlertModal.tsx @@ -56,6 +56,7 @@ export function inlineAlertToChartConfig( note: alert.note ?? null, // Persisted null -> undefined for the NumberInput. numConsecutiveWindows: alert.numConsecutiveWindows ?? undefined, + renotifyIntervalMinutes: alert.renotifyIntervalMinutes ?? undefined, }, }; } diff --git a/packages/common-utils/src/types.ts b/packages/common-utils/src/types.ts index 44ed622ce..7ccf713a8 100644 --- a/packages/common-utils/src/types.ts +++ b/packages/common-utils/src/types.ts @@ -1109,6 +1109,13 @@ export const alertNumConsecutiveWindowsSchema = z .min(1) .nullish(); +// Unset notifies on every evaluation while the alert fires. +export const alertRenotifyIntervalMinutesSchema = z + .number() + .int() + .min(1) + .nullish(); + export const MAX_ALERT_DISPLAY_NAME_LENGTH = 512; export const alertDisplayNameSchema = z .string() @@ -1148,6 +1155,7 @@ export const AlertBaseObjectSchema = z.object({ }) .optional(), numConsecutiveWindows: alertNumConsecutiveWindowsSchema, + renotifyIntervalMinutes: alertRenotifyIntervalMinutesSchema, }); // Keep AlertBaseSchema as a ZodObject for backwards compatibility with @@ -3295,6 +3303,7 @@ export const AlertsPageItemSchema = z.object({ .optional(), executionErrors: z.array(AlertErrorSchema).optional(), numConsecutiveWindows: alertNumConsecutiveWindowsSchema, + renotifyIntervalMinutes: alertRenotifyIntervalMinutesSchema, }); export type AlertsPageItem = z.infer;