From 005884d572019b1236570eec701f54fd9dbbc0cf Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:55:39 +0000 Subject: [PATCH] feat(api): SLO burn alerts as their own alert source An SLO can turn on a fast burn and a slow burn alert, each with its own channels. Each one that is on is an Alert document with the new `slo` source, created, updated and deleted with its SLO, so the alert engine can schedule and notify from it. Channels are checked before the SLO is saved, so an invalid one saves nothing. SLO and alert responses say which alert is which, and the SLO response carries each alert's state. The generic alert APIs (internal and MCP) cannot create or change an SLO alert, since the SLO keeps it in sync. Deleting one from the Alerts page is allowed and turns that alert off on its SLO. The check-alerts task skips these alerts for now. Co-Authored-By: Claude Opus 5.5 --- packages/api/src/controllers/alerts.ts | 54 ++++- packages/api/src/controllers/slo.ts | 27 ++- packages/api/src/controllers/sloAlert.ts | 111 +++++++++ packages/api/src/mcp/tools/alerts/getAlert.ts | 6 +- .../api/src/mcp/tools/alerts/saveAlert.ts | 5 + packages/api/src/models/alert.ts | 21 ++ packages/api/src/models/slo.ts | 2 + .../api/__tests__/sloAlerts.int.test.ts | 227 ++++++++++++++++++ packages/api/src/routers/api/alerts.ts | 1 + packages/api/src/routers/api/slos.ts | 20 +- .../tasks/checkAlerts/providers/default.ts | 4 +- .../api/src/tasks/checkAlerts/template.ts | 1 + packages/api/src/utils/alerts.ts | 4 + 13 files changed, 469 insertions(+), 14 deletions(-) create mode 100644 packages/api/src/controllers/sloAlert.ts create mode 100644 packages/api/src/routers/api/__tests__/sloAlerts.int.test.ts diff --git a/packages/api/src/controllers/alerts.ts b/packages/api/src/controllers/alerts.ts index e51887ec8d..a29654735b 100644 --- a/packages/api/src/controllers/alerts.ts +++ b/packages/api/src/controllers/alerts.ts @@ -26,6 +26,7 @@ import Alert, { import Connection from '@/models/connection'; import Dashboard, { IDashboard } from '@/models/dashboard'; import { ISavedSearch, SavedSearch } from '@/models/savedSearch'; +import Slo from '@/models/slo'; import { Source } from '@/models/source'; import { IUser } from '@/models/user'; import Webhook from '@/models/webhook'; @@ -77,6 +78,10 @@ export const validateAlertInput = async ( ) => { const refs: AlertRefs = {}; + if (alertInput.source === AlertSource.SLO) { + throw new Api400Error(SLO_ALERT_MESSAGE); + } + if (alertInput.source === AlertSource.TILE) { validateObjectId(alertInput.dashboardId, 'Invalid dashboard ID'); @@ -230,7 +235,15 @@ export const validateAlertInput = async ( } } - const channels = getAlertChannels(alertInput); + await validateAlertChannels(teamId, getAlertChannels(alertInput)); + return refs; +}; + +/** At least one channel, and every webhook belongs to the team. */ +export const validateAlertChannels = async ( + teamId: ObjectId, + channels: AlertChannel[], +) => { if (channels.length === 0) { throw new Api400Error('At least one notification channel is required'); } @@ -249,8 +262,25 @@ export const validateAlertInput = async ( if (found !== uniqueIds.length) { throw new Api400Error('Webhook not found'); } +}; - return refs; +export const SLO_ALERT_MESSAGE = + 'This alert belongs to an SLO. Change it from the SLO instead.'; + +/** Whether the alert is one an SLO owns. */ +export const isSloAlert = async (id: string, teamId: ObjectId) => + (await Alert.exists({ _id: id, team: teamId, source: AlertSource.SLO })) != + null; + +/** + * SLO alerts are kept in sync with their SLO, so the generic alert APIs + * (internal, external and MCP) cannot create or change them. Deleting one is + * allowed, and turns the alert off on its SLO (see deleteAlert). + */ +const rejectSloAlert = async (id: string, teamId: ObjectId) => { + if (await isSloAlert(id, teamId)) { + throw new Api400Error(SLO_ALERT_MESSAGE); + } }; // Exported for unit testing the channel-mirroring invariant (see @@ -377,6 +407,7 @@ export const updateAlert = async ( refs: AlertRefs = {}, userId?: ObjectId, ) => { + await rejectSloAlert(id, teamId); // should consider clearing AlertHistory when updating an alert? const alert = await Alert.findOneAndUpdate( { @@ -607,8 +638,25 @@ export const getAlertEnhanced = async ( }; export const deleteAlert = async (id: string, teamId: ObjectId) => { - return Alert.deleteOne({ + const alert = await Alert.findOne( + { _id: id, team: teamId }, + { source: 1, slo: 1, sloRule: 1 }, + ).lean(); + const result = await Alert.deleteOne({ _id: id, team: teamId, }); + // An SLO keeps each burn alert's settings and recreates the alert from + // them on save, so deleting the alert turns that burn alert off. The alert + // goes first: if this update fails, the SLO shows the alert as not running + // rather than an alert firing without settings. + if (alert?.source === AlertSource.SLO && alert.slo != null) { + const field = + alert.sloRule === 'slowBurn' ? 'alerts.slowBurn' : 'alerts.fastBurn'; + await Slo.updateOne( + { _id: alert.slo, team: teamId }, + { $set: { [field]: null } }, + ); + } + return result; }; diff --git a/packages/api/src/controllers/slo.ts b/packages/api/src/controllers/slo.ts index 9b45b36cfe..16bd3c6ebf 100644 --- a/packages/api/src/controllers/slo.ts +++ b/packages/api/src/controllers/slo.ts @@ -22,6 +22,11 @@ import { performance } from 'perf_hooks'; import { ClickhouseClient } from '@/clickhouse'; import { getConnectionById } from '@/controllers/connection'; +import { + deleteSloAlerts, + syncSloAlerts, + validateSloAlerts, +} from '@/controllers/sloAlert'; import { getSource } from '@/controllers/sources'; import Slo, { ISlo } from '@/models/slo'; import { getClickHouseErrorType } from '@/utils/clickhouseErrors'; @@ -162,8 +167,9 @@ export async function createSlo( throw new Api400Error(`A team can have at most ${SLO_MAX_PER_TEAM} SLOs`); } await checkSloQuery(teamId, definition); + await validateSloAlerts(teamId, definition.alerts); // The status refresh picks up an SLO without a snapshot on its next run. - return ( + const slo = ( await Slo.create({ ...definition, groupBy: definition.groupBy || null, @@ -172,6 +178,8 @@ export async function createSlo( updatedBy: userId, }) ).toObject(); + await syncSloAlerts(slo, userId); + return slo; } export async function updateSlo( @@ -183,6 +191,7 @@ export async function updateSlo( const existing = await getSlo(teamId, sloId); if (!existing) return null; await checkSloQuery(teamId, definition); + await validateSloAlerts(teamId, definition.alerts); // Every input of the stored numbers: a change makes the snapshot wrong, // and the refresh recomputes it on its next run. const changed = @@ -191,28 +200,38 @@ export async function updateSlo( existing.window !== definition.window || (existing.groupBy ?? null) !== (definition.groupBy ?? null) || JSON.stringify(existing.indicator) !== JSON.stringify(definition.indicator); - return Slo.findOneAndUpdate( + const updated = await Slo.findOneAndUpdate( { _id: sloId, team: teamId }, { $set: { ...definition, description: definition.description ?? '', groupBy: definition.groupBy || null, + alerts: definition.alerts ?? {}, updatedBy: userId, }, ...(changed ? { $unset: { status: 1 } } : {}), }, { new: true }, ).lean(); + if (updated) await syncSloAlerts(updated, userId); + return updated; } export async function deleteSlo(teamId: string, sloId: string) { if (!mongoose.Types.ObjectId.isValid(sloId)) return false; + if (!(await Slo.exists({ _id: sloId, team: teamId }))) return false; + // The alerts go first: an SLO left without its alerts is mended by saving + // it again, while an alert left without its SLO would keep firing. + await deleteSloAlerts(teamId, sloId); const result = await Slo.deleteOne({ _id: sloId, team: teamId }); return result.deletedCount > 0; } -export function formatSlo(slo: ISlo): SloApiResponse { +export function formatSlo( + slo: ISlo, + alertStates: SloApiResponse['alertStates'] = {}, +): SloApiResponse { return { id: slo._id.toString(), version: slo.version, @@ -226,7 +245,7 @@ export function formatSlo(slo: ISlo): SloApiResponse { groupBy: slo.groupBy ?? null, alerts: slo.alerts ?? {}, status: slo.status ?? null, - alertStates: {}, + alertStates, createdAt: slo.createdAt.toISOString(), updatedAt: slo.updatedAt.toISOString(), }; diff --git a/packages/api/src/controllers/sloAlert.ts b/packages/api/src/controllers/sloAlert.ts new file mode 100644 index 0000000000..1813241be9 --- /dev/null +++ b/packages/api/src/controllers/sloAlert.ts @@ -0,0 +1,111 @@ +import { + getSloAlertInterval, + getSloAlertTarget, + SLO_BURN_CONDITIONS, + type SloAlerts, + type SloApiResponse, +} from '@hyperdx/common-utils/dist/slo'; +import { AlertThresholdType } from '@hyperdx/common-utils/dist/types'; +import mongoose from 'mongoose'; + +import { validateAlertChannels } from '@/controllers/alerts'; +import type { ObjectId } from '@/models'; +import Alert, { AlertSource, AlertState } from '@/models/alert'; +import type { ISlo } from '@/models/slo'; + +/** Checked before the SLO is saved, so an invalid alert never half-saves. */ +export async function validateSloAlerts( + teamId: string, + alerts: SloAlerts | null | undefined, +) { + for (const { rule } of SLO_BURN_CONDITIONS) { + const target = getSloAlertTarget(alerts, rule); + if (target) { + await validateAlertChannels( + new mongoose.Types.ObjectId(teamId), + target.channels, + ); + } + } +} + +/** + * Keeps the Alert documents an SLO owns in line with its burn alerts: one + * per alert that is on, created or updated with its channels, and deleted + * when it is off. The alert engine schedules, evaluates and notifies from + * those documents. Their value is how close the rule's condition is to + * holding (getSloBurnSeverity), so they fire at 1. + */ +export async function syncSloAlerts( + slo: Pick, + userId?: string, +) { + for (const { rule } of SLO_BURN_CONDITIONS) { + const owner = { + team: slo.team, + slo: slo._id, + source: AlertSource.SLO, + sloRule: rule, + }; + const target = getSloAlertTarget(slo.alerts, rule); + if (!target) { + await Alert.deleteMany(owner); + continue; + } + await Alert.findOneAndUpdate( + owner, + { + $set: { + ...owner, + displayName: slo.name, + tags: slo.tags, + // `channels` is canonical; `channel` mirrors the first, as for + // every alert. + channel: target.channels[0], + channels: target.channels, + interval: getSloAlertInterval(rule), + threshold: 1, + thresholdType: AlertThresholdType.ABOVE, + }, + $setOnInsert: { state: AlertState.OK, createdBy: userId }, + }, + { upsert: true }, + ); + } +} + +export async function deleteSloAlerts(teamId: string, sloId: string) { + await Alert.deleteMany({ team: teamId, slo: sloId, source: AlertSource.SLO }); +} + +/** + * The burn alerts each SLO owns, keyed by SLO id, with their current state + * and the end of a silence that is still in effect. + */ +export async function getSloAlerts( + teamId: string | ObjectId, + sloIds: ObjectId[], + now = new Date(), +): Promise> { + const alerts = await Alert.find( + { team: teamId, source: AlertSource.SLO, slo: { $in: sloIds } }, + { slo: 1, sloRule: 1, state: 1, silenced: 1 }, + ).lean(); + const bySlo = new Map(); + for (const alert of alerts) { + const until = alert.silenced?.until; + const status = { + id: alert._id.toString(), + state: alert.state, + silencedUntil: until != null && until > now ? until.toISOString() : null, + }; + const states = bySlo.get(`${alert.slo}`) ?? {}; + bySlo.set( + `${alert.slo}`, + alert.sloRule === 'slowBurn' + ? { ...states, slowBurn: status } + : { ...states, fastBurn: status }, + ); + } + return bySlo; +} diff --git a/packages/api/src/mcp/tools/alerts/getAlert.ts b/packages/api/src/mcp/tools/alerts/getAlert.ts index 2c568ed79d..54f4ca599c 100644 --- a/packages/api/src/mcp/tools/alerts/getAlert.ts +++ b/packages/api/src/mcp/tools/alerts/getAlert.ts @@ -9,7 +9,7 @@ import { getAlertById } from '@/controllers/alerts'; import { READ_ONLY_TOOL } from '@/mcp/tools/annotations'; import type { ToolRegistrar } from '@/mcp/tools/types'; import { mcpUserError, validateObjectId } from '@/mcp/utils/errors'; -import Alert from '@/models/alert'; +import Alert, { AlertSource } from '@/models/alert'; import type { IDashboard } from '@/models/dashboard'; import type { ISavedSearch } from '@/models/savedSearch'; import { translateAlertDocumentToExternalAlertWithChartConfig } from '@/routers/external-api/v2/utils/alertChartConfig'; @@ -56,6 +56,8 @@ export function registerGetAlert({ if (!id) { const query: Record = { team: new mongoose.Types.ObjectId(teamId), + // SLO alerts are managed through their SLO. + source: { $ne: AlertSource.SLO }, }; if (state) { query.state = state; @@ -93,7 +95,7 @@ export function registerGetAlert({ if (idError) return idError; const alert = await getAlertById(id, teamId); - if (!alert) { + if (!alert || alert.source === AlertSource.SLO) { return mcpUserError('Alert not found'); } diff --git a/packages/api/src/mcp/tools/alerts/saveAlert.ts b/packages/api/src/mcp/tools/alerts/saveAlert.ts index 24883dc011..a5d80a5053 100644 --- a/packages/api/src/mcp/tools/alerts/saveAlert.ts +++ b/packages/api/src/mcp/tools/alerts/saveAlert.ts @@ -6,6 +6,8 @@ import { type AlertInput, createAlert, getAlertById, + isSloAlert, + SLO_ALERT_MESSAGE, updateAlert, validateAlertInput, } from '@/controllers/alerts'; @@ -160,6 +162,9 @@ export function registerSaveAlert({ // ── Update existing alert ── if (alertId) { + if (await isSloAlert(alertId, mongoTeamId)) { + return mcpUserError(SLO_ALERT_MESSAGE); + } const updated = await updateAlert( alertId, mongoTeamId, diff --git a/packages/api/src/models/alert.ts b/packages/api/src/models/alert.ts index 3e62d19eab..9545c05f80 100644 --- a/packages/api/src/models/alert.ts +++ b/packages/api/src/models/alert.ts @@ -1,3 +1,7 @@ +import { + type SloAlertRule, + SloAlertRuleSchema, +} from '@hyperdx/common-utils/dist/slo'; import { ALERT_INTERVAL_TO_MINUTES, AlertChartConfig, @@ -74,6 +78,8 @@ export enum AlertSource { TILE = 'tile', /** Detached alert whose chart config lives inline on the alert (no saved search/tile). */ INLINE = 'inline', + /** Burn-rate alert owned by an SLO; managed only through the SLO. */ + SLO = 'slo', } export interface IAlert { @@ -117,6 +123,11 @@ export interface IAlert { // tile's config, minus the embedded alert field) chartConfig?: AlertChartConfig | null; + /** The SLO that owns this burn alert (source SLO). */ + slo?: ObjectId | null; + /** Which of the SLO's burn alerts this is. */ + sloRule?: SloAlertRule | null; + // Silenced silenced?: { by?: ObjectId; @@ -251,6 +262,16 @@ const AlertSchema = new Schema( type: Schema.Types.Mixed, required: false, }, + slo: { + type: mongoose.Schema.Types.ObjectId, + ref: 'Slo', + required: false, + }, + sloRule: { + type: String, + enum: SloAlertRuleSchema.options, + required: false, + }, numConsecutiveWindows: { type: Number, required: false, diff --git a/packages/api/src/models/slo.ts b/packages/api/src/models/slo.ts index a2bd61993b..d392f2d285 100644 --- a/packages/api/src/models/slo.ts +++ b/packages/api/src/models/slo.ts @@ -42,6 +42,8 @@ const SloSchema = new Schema( window: { type: String, required: true }, // Expression whose values each get their own numbers and alert. groupBy: { type: String, required: false }, + // The burn alerts that are on; each has an Alert document mirroring it. + alerts: { type: Schema.Types.Mixed, required: false }, status: { type: Schema.Types.Mixed, required: false }, // Immutable: ownership attribution is set once at creation. createdBy: { diff --git a/packages/api/src/routers/api/__tests__/sloAlerts.int.test.ts b/packages/api/src/routers/api/__tests__/sloAlerts.int.test.ts new file mode 100644 index 0000000000..eabb024df2 --- /dev/null +++ b/packages/api/src/routers/api/__tests__/sloAlerts.int.test.ts @@ -0,0 +1,227 @@ +import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import mongoose from 'mongoose'; + +import * as config from '@/config'; +import { + deleteAlert, + SLO_ALERT_MESSAGE, + updateAlert, +} from '@/controllers/alerts'; +import { + DEFAULT_DATABASE, + DEFAULT_TRACES_TABLE, + getLoggedInAgent, + getServer, +} from '@/fixtures'; +import Alert, { AlertSource, AlertThresholdType } from '@/models/alert'; +import Connection from '@/models/connection'; +import Slo from '@/models/slo'; +import { Source } from '@/models/source'; +import Webhook from '@/models/webhook'; + +describe('SLO alerts', () => { + const server = getServer(); + let agent: Awaited>['agent']; + let team: Awaited>['team']; + let sourceId: string; + let webhookId: string; + + const definition = (alerts: unknown) => ({ + name: 'Checkout availability', + source: sourceId, + indicator: { + template: 'availability', + eligible: { where: "SpanKind = 'Server'", whereLanguage: 'sql' }, + good: "StatusCode != 'Error'", + }, + target: 99.9, + window: '7d', + alerts, + }); + const notify = (id = webhookId) => ({ + channels: [{ type: 'webhook', webhookId: id }], + }); + /** The fast burn alert only, to the team's webhook. */ + const fastOnly = () => ({ fastBurn: notify() }); + + beforeAll(async () => { + await server.start(); + }); + + beforeEach(async () => { + const result = await getLoggedInAgent(server); + agent = result.agent; + team = result.team; + const connection = await Connection.create({ + team: team._id, + name: 'Default', + host: config.CLICKHOUSE_HOST, + username: config.CLICKHOUSE_USER, + password: config.CLICKHOUSE_PASSWORD, + }); + const source = await Source.create({ + kind: SourceKind.Trace, + team: team._id, + from: { databaseName: DEFAULT_DATABASE, tableName: DEFAULT_TRACES_TABLE }, + timestampValueExpression: 'Timestamp', + connection: connection._id, + name: 'Traces', + traceIdExpression: 'TraceId', + spanIdExpression: 'SpanId', + parentSpanIdExpression: 'ParentSpanId', + spanNameExpression: 'SpanName', + spanKindExpression: 'SpanKind', + durationExpression: 'Duration', + durationPrecision: 9, + statusCodeExpression: 'StatusCode', + }); + sourceId = source._id.toString(); + const webhook = await Webhook.create({ + name: 'On call', + service: 'generic', + url: 'https://example.com/hook', + team: team._id, + }); + webhookId = webhook._id.toString(); + }); + + afterEach(async () => { + await server.clearDBs(); + }); + + afterAll(async () => { + await server.stop(); + }); + + const sloAlerts = (sloId: string) => Alert.find({ slo: sloId }).lean(); + + it('keeps one alert per burn alert that is on, in step with the SLO', async () => { + const created = await agent + .post('/slos') + .send(definition(fastOnly())) + .expect(200); + const sloId = created.body.id; + const [fast] = await sloAlerts(sloId); + // Its value is how close the rule's condition is to holding, so it + // fires at 1. + expect(fast).toEqual( + expect.objectContaining({ + source: AlertSource.SLO, + sloRule: 'fastBurn', + displayName: 'Checkout availability', + interval: '5m', + threshold: 1, + thresholdType: 'above', + }), + ); + expect(created.body.alertStates).toEqual({ + fastBurn: { id: fast._id.toString(), state: 'OK', silencedUntil: null }, + }); + + // The slow burn alert notifies elsewhere; the fast one stays the same + // alert. + const ticket = await Webhook.create({ + name: 'Team channel', + service: 'generic', + url: 'https://example.com/team', + team: team._id, + }); + await agent + .put(`/slos/${sloId}`) + .send( + definition({ + fastBurn: notify(), + slowBurn: notify(ticket._id.toString()), + }), + ) + .expect(200); + const both = await sloAlerts(sloId); + expect(both).toHaveLength(2); + const slow = both.find(a => a.sloRule === 'slowBurn'); + expect(slow).toEqual( + expect.objectContaining({ + interval: '15m', + channels: [ + expect.objectContaining({ webhookId: ticket._id.toString() }), + ], + }), + ); + expect(both.find(a => a.sloRule === 'fastBurn')?._id.toString()).toBe( + fast._id.toString(), + ); + + // Turning the fast one off leaves the slow one. + await agent + .put(`/slos/${sloId}`) + .send(definition({ slowBurn: notify(ticket._id.toString()) })) + .expect(200); + expect((await sloAlerts(sloId)).map(a => a.sloRule)).toEqual(['slowBurn']); + + await agent.put(`/slos/${sloId}`).send(definition({})).expect(200); + expect(await sloAlerts(sloId)).toEqual([]); + + await agent.put(`/slos/${sloId}`).send(definition(fastOnly())).expect(200); + await agent.delete(`/slos/${sloId}`).expect(204); + expect(await sloAlerts(sloId)).toEqual([]); + }); + + it("refuses a channel the team doesn't have, saving nothing", async () => { + await agent + .post('/slos') + .send( + definition({ + fastBurn: notify(), + slowBurn: notify(new mongoose.Types.ObjectId().toString()), + }), + ) + .expect(400); + expect(await Slo.countDocuments()).toBe(0); + expect(await Alert.countDocuments()).toBe(0); + }); + + it('keeps the generic alert controllers from changing an alert its SLO manages', async () => { + const created = await agent + .post('/slos') + .send(definition(fastOnly())) + .expect(200); + const alertId = created.body.alertStates.fastBurn.id; + + await expect( + updateAlert(alertId, team._id, { + source: AlertSource.SAVED_SEARCH, + savedSearchId: new mongoose.Types.ObjectId().toString(), + interval: '5m', + threshold: 1, + thresholdType: AlertThresholdType.ABOVE, + channel: { type: 'webhook', webhookId }, + }), + ).rejects.toMatchObject({ name: SLO_ALERT_MESSAGE }); + }); + + it('turns that burn alert off on the SLO when its alert is deleted', async () => { + const created = await agent + .post('/slos') + .send(definition({ fastBurn: notify(), slowBurn: notify() })) + .expect(200); + const alertId = created.body.alertStates.slowBurn.id; + + await agent.delete(`/alerts/${alertId}`).expect(200); + + expect(await Alert.exists({ _id: alertId })).toBeNull(); + const slo = await agent.get(`/slos/${created.body.id}`).expect(200); + expect(slo.body.alerts).toEqual({ fastBurn: notify(), slowBurn: null }); + expect(Object.keys(slo.body.alertStates)).toEqual(['fastBurn']); + }); + + it('deletes an alert whose SLO is gone', async () => { + const created = await agent + .post('/slos') + .send(definition(fastOnly())) + .expect(200); + const alertId = created.body.alertStates.fastBurn.id; + + await Slo.deleteOne({ _id: created.body.id }); + await deleteAlert(alertId, team._id); + expect(await Alert.exists({ _id: alertId })).toBeNull(); + }); +}); diff --git a/packages/api/src/routers/api/alerts.ts b/packages/api/src/routers/api/alerts.ts index a6264db351..833763abf3 100644 --- a/packages/api/src/routers/api/alerts.ts +++ b/packages/api/src/routers/api/alerts.ts @@ -99,6 +99,7 @@ const formatAlertResponse = ( savedSearchId: alert.savedSearch._id, savedSearch: { name: alert.savedSearch.name }, }), + ...(alert.slo && { sloId: alert.slo, sloRule: alert.sloRule ?? undefined }), // Inline alerts carry their persisted config so edit surfaces can seed // the chart editor and the detail page can render the query — but only on // the single-alert response. Attaching every alert's full config (raw SQL diff --git a/packages/api/src/routers/api/slos.ts b/packages/api/src/routers/api/slos.ts index 3350f63b77..9aeb76d8fb 100644 --- a/packages/api/src/routers/api/slos.ts +++ b/packages/api/src/routers/api/slos.ts @@ -12,7 +12,10 @@ import { listSlos, updateSlo, } from '@/controllers/slo'; +import { getSloAlerts } from '@/controllers/sloAlert'; import { getNonNullUserWithTeam } from '@/middleware/auth'; +import type { ObjectId } from '@/models'; +import type { ISlo } from '@/models/slo'; import { setBusinessContext } from '@/utils/instrumentation'; import { objectIdSchema } from '@/utils/zod'; @@ -31,12 +34,21 @@ const sloIdParams = z .transform(params => params); const sloBody = SloInputSchema.transform(definition => definition); +async function formatSloWithAlerts(teamId: ObjectId, slo: ISlo) { + const alerts = await getSloAlerts(teamId, [slo._id]); + return formatSlo(slo, alerts.get(slo._id.toString())); +} + router.get('/', async (req, res, next) => { try { const { teamId } = getNonNullUserWithTeam(req); setBusinessContext({ teamId: teamId.toString() }); const slos = await listSlos(teamId.toString()); - res.json(slos.map(slo => formatSlo(slo))); + const alerts = await getSloAlerts( + teamId, + slos.map(slo => slo._id), + ); + res.json(slos.map(slo => formatSlo(slo, alerts.get(slo._id.toString())))); } catch (e) { next(e); } @@ -51,7 +63,7 @@ router.get( setBusinessContext({ teamId: teamId.toString() }); const slo = await getSlo(teamId.toString(), req.params.id); if (!slo) return res.sendStatus(404); - res.json(formatSlo(slo)); + res.json(await formatSloWithAlerts(teamId, slo)); } catch (e) { next(e); } @@ -67,7 +79,7 @@ router.post('/', processRequest({ body: sloBody }), async (req, res, next) => { userId?.toString(), req.body, ); - res.json(formatSlo(slo)); + res.json(await formatSloWithAlerts(teamId, slo)); } catch (e) { next(e); } @@ -87,7 +99,7 @@ router.put( req.body, ); if (!slo) return res.sendStatus(404); - res.json(formatSlo(slo)); + res.json(await formatSloWithAlerts(teamId, slo)); } catch (e) { next(e); } diff --git a/packages/api/src/tasks/checkAlerts/providers/default.ts b/packages/api/src/tasks/checkAlerts/providers/default.ts index bed6d52109..6375960d5c 100644 --- a/packages/api/src/tasks/checkAlerts/providers/default.ts +++ b/packages/api/src/tasks/checkAlerts/providers/default.ts @@ -400,7 +400,9 @@ async function resolveAlertDetails( async function loadAlerts(): Promise { const groupedTasks = new Map(); - const alerts = await Alert.find({}); + // SLO alerts are not evaluated yet: skip them rather than fail to load + // them. + const alerts = await Alert.find({ source: { $ne: AlertSource.SLO } }); const now = new Date(); diff --git a/packages/api/src/tasks/checkAlerts/template.ts b/packages/api/src/tasks/checkAlerts/template.ts index fde25921b9..6f8507f68f 100644 --- a/packages/api/src/tasks/checkAlerts/template.ts +++ b/packages/api/src/tasks/checkAlerts/template.ts @@ -212,6 +212,7 @@ export const ALERT_TYPE_BY_SOURCE: Record = { // Detached alert: the chart config lives on the alert itself, so there is // no saved search or tile behind it to open. [AlertSource.INLINE]: 'inline_query', + [AlertSource.SLO]: 'slo_burn_rate', }; const MAX_MESSAGE_LENGTH = 500; diff --git a/packages/api/src/utils/alerts.ts b/packages/api/src/utils/alerts.ts index ca38ce5499..286d55fd88 100644 --- a/packages/api/src/utils/alerts.ts +++ b/packages/api/src/utils/alerts.ts @@ -168,6 +168,10 @@ export function deriveAlertDisplayFields( displayName = normalizeName(alert.chartConfig?.name); tags = []; // Inline alerts have no parent to inherit tags from. break; + case AlertSource.SLO: + // The SLO keeps displayName and tags in sync on the alert itself. + tags = []; + break; case AlertSource.SAVED_SEARCH: default: displayName = normalizeName(savedSearch?.name);