Skip to content

Commit be26530

Browse files
feat(alerts): model and schema groundwork for multiple notification channels (#2845)
1 parent c602cbb commit be26530

11 files changed

Lines changed: 515 additions & 35 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@hyperdx/common-utils': minor
3+
---
4+
5+
Add plural alert notification channel schemas: `zAlertChannels` (1–10 entries), `MAX_ALERT_CHANNELS`, and a shared `channel`/`channels` cross-field validator, ahead of multi-channel alert support in the API.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { makeAlert } from '@/controllers/alerts';
2+
import { AlertChannel, AlertThresholdType } from '@/models/alert';
3+
4+
// A channel type this repo doesn't define -- see
5+
// models/__tests__/alert.test.ts for why. `value: any` (rather than an `as`
6+
// cast) keeps this off the no-unsafe-type-assertion budget while still
7+
// producing a value typed as AlertChannel for the call below.
8+
const foreignChannel = (value: any): AlertChannel => value;
9+
10+
describe('makeAlert', () => {
11+
// makeAlert mirrors channels[0] into `channel` for readers that predate
12+
// multi-channel support. That mirroring must stay opaque: a downstream
13+
// fork's channel types must survive verbatim, not get projected onto
14+
// webhook-shaped fields.
15+
it('mirrors channels[0] into channel verbatim, preserving fields this repo does not define', () => {
16+
const exotic = foreignChannel({
17+
type: 'email',
18+
emailRecipients: ['ops@example.test'],
19+
});
20+
21+
const result = makeAlert({
22+
interval: '5m',
23+
threshold: 1,
24+
thresholdType: AlertThresholdType.ABOVE,
25+
channels: [exotic],
26+
});
27+
28+
expect(result.channel).toEqual(exotic);
29+
expect(result.channels).toEqual([exotic]);
30+
});
31+
});

‎packages/api/src/controllers/alerts.ts‎

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,12 @@ import { groupBy } from 'lodash';
77
import { z } from 'zod';
88

99
import type { ObjectId } from '@/models';
10-
import Alert, { AlertSource, IAlert } from '@/models/alert';
10+
import Alert, {
11+
AlertChannel,
12+
AlertSource,
13+
getAlertChannels,
14+
IAlert,
15+
} from '@/models/alert';
1116
import Dashboard, { IDashboard } from '@/models/dashboard';
1217
import { ISavedSearch, SavedSearch } from '@/models/savedSearch';
1318
import { IUser } from '@/models/user';
@@ -18,6 +23,7 @@ import { alertSchema, objectIdSchema } from '@/utils/zod';
1823
export type AlertInput = Omit<
1924
IAlert,
2025
| 'id'
26+
| 'channel'
2127
| 'scheduleStartAt'
2228
| 'savedSearchId'
2329
| 'createdAt'
@@ -27,6 +33,9 @@ export type AlertInput = Omit<
2733
| 'state'
2834
> & {
2935
id?: string;
36+
// Exactly one of channel/channels is provided (enforced by alertSchema);
37+
// `channels` flows in optionally via IAlert.
38+
channel?: AlertChannel;
3039
// Replace the Date-type fields from IAlert
3140
scheduleStartAt?: string | null;
3241
// Replace the ObjectId-type fields from IAlert
@@ -44,7 +53,12 @@ export const validateAlertInput = async (
4453
teamId: ObjectId,
4554
alertInput: Pick<
4655
AlertInput,
47-
'source' | 'dashboardId' | 'tileId' | 'savedSearchId' | 'channel'
56+
| 'source'
57+
| 'dashboardId'
58+
| 'tileId'
59+
| 'savedSearchId'
60+
| 'channel'
61+
| 'channels'
4862
>,
4963
) => {
5064
if (alertInput.source === AlertSource.TILE) {
@@ -94,21 +108,33 @@ export const validateAlertInput = async (
94108
}
95109
}
96110

97-
if (alertInput.channel.type === 'webhook') {
98-
validateObjectId(alertInput.channel.webhookId, 'Invalid webhook ID');
111+
const channels = getAlertChannels(alertInput);
112+
if (channels.length === 0) {
113+
throw new Api400Error('At least one notification channel is required');
114+
}
99115

100-
if (
101-
(await Webhook.findOne({
102-
_id: alertInput.channel.webhookId,
103-
team: teamId,
104-
})) == null
105-
) {
106-
throw new Api400Error('Webhook not found');
107-
}
116+
const webhookIds = channels
117+
.filter(c => c.type === 'webhook')
118+
.map(c => c.webhookId);
119+
for (const webhookId of webhookIds) {
120+
validateObjectId(webhookId, 'Invalid webhook ID');
121+
}
122+
const uniqueIds = [...new Set(webhookIds)];
123+
const found = await Webhook.countDocuments({
124+
_id: { $in: uniqueIds },
125+
team: teamId,
126+
});
127+
if (found !== uniqueIds.length) {
128+
throw new Api400Error('Webhook not found');
108129
}
109130
};
110131

111-
const makeAlert = (alert: AlertInput, userId?: ObjectId): Partial<IAlert> => {
132+
// Exported for unit testing the channel-mirroring invariant (see
133+
// controllers/__tests__/alerts.test.ts) -- otherwise only used internally.
134+
export const makeAlert = (
135+
alert: AlertInput,
136+
userId?: ObjectId,
137+
): Partial<IAlert> => {
112138
// Preserve existing DB value when scheduleStartAt is omitted from updates
113139
// (undefined), while still allowing explicit clears via null.
114140
const hasScheduleStartAt = alert.scheduleStartAt !== undefined;
@@ -124,9 +150,14 @@ const makeAlert = (alert: AlertInput, userId?: ObjectId): Partial<IAlert> => {
124150
: alert.scheduleOffsetMinutes;
125151
const isSavedSearch = alert.source === AlertSource.SAVED_SEARCH;
126152
const isTile = alert.source === AlertSource.TILE;
153+
const channels = getAlertChannels(alert);
127154

128155
return {
129-
channel: alert.channel,
156+
// `channels` is canonical; `channel` mirrors channels[0] so readers that
157+
// predate multi-channel support (older task runners mid-rollout) still
158+
// notify the first target.
159+
channel: channels[0] ?? { type: null },
160+
channels,
130161
interval: alert.interval,
131162
...(normalizedScheduleOffsetMinutes != null && {
132163
scheduleOffsetMinutes: normalizedScheduleOffsetMinutes,
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { AlertChannel, getAlertChannels } from '@/models/alert';
2+
3+
// A channel type this repo doesn't define -- e.g. a downstream fork's email
4+
// channel carrying an `emailRecipients` array. `value: any` (rather than an
5+
// `as` cast) keeps this off the no-unsafe-type-assertion budget while still
6+
// producing a value typed as AlertChannel for the calls below.
7+
const foreignChannel = (value: any): AlertChannel => value;
8+
9+
describe('getAlertChannels', () => {
10+
const wh = (id: string) => ({ type: 'webhook' as const, webhookId: id });
11+
12+
it('prefers the channels array when present', () => {
13+
expect(
14+
getAlertChannels({ channel: wh('legacy'), channels: [wh('a'), wh('b')] }),
15+
).toEqual([wh('a'), wh('b')]);
16+
});
17+
18+
it('falls back to the legacy singular channel', () => {
19+
expect(getAlertChannels({ channel: wh('legacy') })).toEqual([wh('legacy')]);
20+
expect(getAlertChannels({ channel: wh('legacy'), channels: [] })).toEqual([
21+
wh('legacy'),
22+
]);
23+
});
24+
25+
it('returns empty for null-type or missing channels', () => {
26+
expect(getAlertChannels({ channel: { type: null } })).toEqual([]);
27+
expect(getAlertChannels({})).toEqual([]);
28+
});
29+
30+
// The invariant guard: this repo only defines webhook channels, but a
31+
// downstream fork adds others. getAlertChannels must copy them by
32+
// reference, not project them onto webhook-shaped fields.
33+
it('copies a channels[] entry opaquely, preserving fields this repo does not define', () => {
34+
const exotic = foreignChannel({
35+
type: 'email',
36+
emailRecipients: ['ops@example.test'],
37+
});
38+
39+
expect(getAlertChannels({ channels: [exotic] })).toEqual([exotic]);
40+
});
41+
42+
it('copies the legacy singular channel opaquely when it is a foreign type', () => {
43+
const exotic = foreignChannel({
44+
type: 'email',
45+
emailRecipients: ['ops@example.test'],
46+
});
47+
48+
expect(getAlertChannels({ channel: exotic })).toEqual([exotic]);
49+
});
50+
});

‎packages/api/src/models/alert.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,24 @@ export type AlertChannel =
5050
type: null;
5151
};
5252

53+
/**
54+
* Resolve an alert's notification channels regardless of document vintage:
55+
* documents written before multi-channel support only have the singular
56+
* `channel`. Writers keep `channel` mirrored to `channels[0]`.
57+
*/
58+
export const getAlertChannels = (alert: {
59+
channel?: AlertChannel | null;
60+
channels?: AlertChannel[] | null;
61+
}): AlertChannel[] => {
62+
if (alert.channels != null && alert.channels.length > 0) {
63+
return alert.channels;
64+
}
65+
if (alert.channel != null && alert.channel.type != null) {
66+
return [alert.channel];
67+
}
68+
return [];
69+
};
70+
5371
export enum AlertSource {
5472
SAVED_SEARCH = 'saved_search',
5573
TILE = 'tile',
@@ -58,6 +76,7 @@ export enum AlertSource {
5876
export interface IAlert {
5977
id: string;
6078
channel: AlertChannel;
79+
channels?: AlertChannel[];
6180
interval: AlertInterval;
6281
scheduleOffsetMinutes?: number;
6382
scheduleStartAt?: Date | null;
@@ -146,6 +165,10 @@ const AlertSchema = new Schema<IAlert>(
146165
required: false,
147166
},
148167
channel: Schema.Types.Mixed, // slack, email, etc
168+
// Canonical list of notification channels. `channel` above is kept in
169+
// sync (first entry) so pre-multi-channel readers keep working.
170+
// `default: undefined` stops Mongoose materialising [] on old documents.
171+
channels: { type: [Schema.Types.Mixed], default: undefined },
149172
state: {
150173
type: String,
151174
enum: AlertState,

‎packages/api/src/routers/api/__tests__/dashboard.int.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,65 @@ describe('dashboard router', () => {
263263
expect(storedAlert?.groupBy).toBeNull();
264264
});
265265

266+
// A tile alert must always end up with a resolvable notification target.
267+
// Making `channel` optional briefly let a channels-only tile alert through
268+
// this path and persist with nothing to notify.
269+
it('persists a resolvable target for a channels-only tile alert', async () => {
270+
const dashboard = await agent
271+
.post('/dashboards')
272+
.send({
273+
name: 'Test Dashboard',
274+
tiles: [
275+
makeTile({
276+
alert: {
277+
channels: [
278+
{ type: 'webhook' as const, webhookId: webhook._id.toString() },
279+
],
280+
interval: '12h' as const,
281+
threshold: 1,
282+
thresholdType: AlertThresholdType.ABOVE,
283+
},
284+
}),
285+
],
286+
tags: [],
287+
})
288+
.expect(200);
289+
290+
const storedAlert = await Alert.findOne({
291+
team: team._id,
292+
dashboard: dashboard.body.id,
293+
source: AlertSource.TILE,
294+
});
295+
expect(storedAlert).not.toBeNull();
296+
expect(storedAlert?.channels).toEqual([
297+
{ type: 'webhook', webhookId: webhook._id.toString() },
298+
]);
299+
// The legacy mirror is what pre-multi-channel readers dispatch from.
300+
expect(storedAlert?.channel).toEqual({
301+
type: 'webhook',
302+
webhookId: webhook._id.toString(),
303+
});
304+
});
305+
306+
it('rejects a tile alert with no notification channel', async () => {
307+
await agent
308+
.post('/dashboards')
309+
.send({
310+
name: 'Test Dashboard',
311+
tiles: [
312+
makeTile({
313+
alert: {
314+
interval: '12h' as const,
315+
threshold: 1,
316+
thresholdType: AlertThresholdType.ABOVE,
317+
},
318+
}),
319+
],
320+
tags: [],
321+
})
322+
.expect(400);
323+
});
324+
266325
it('alerts are created when updating dashboard (adding alert to tile)', async () => {
267326
const mockAlert = makeMockAlert(webhook._id.toString());
268327
const dashboard = await agent

‎packages/api/src/tasks/checkAlerts/template.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ export const buildAlertMessageTemplateTitle = ({
238238
export const getDefaultExternalAction = (
239239
alert: AlertMessageTemplateDefaultView['alert'],
240240
) => {
241-
if (alert.channel.type === 'webhook' && alert.channel.webhookId != null) {
241+
if (alert.channel?.type === 'webhook' && alert.channel.webhookId != null) {
242242
return `@${alert.channel.type}-${alert.channel.webhookId}`;
243243
}
244244
return null;

‎packages/api/src/utils/zod.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,12 @@ import {
1919
scheduleStartAtSchema,
2020
SearchConditionLanguageSchema as whereLanguageSchema,
2121
tagsSchema,
22+
validateAlertChannelSelection,
2223
validateAlertScheduleOffsetMinutes,
2324
validateAlertThresholdMax,
2425
WebhookService,
26+
zAlertChannel,
27+
zAlertChannels,
2528
} from '@hyperdx/common-utils/dist/types';
2629
import { Types } from 'mongoose';
2730
import { z } from 'zod';
@@ -647,11 +650,6 @@ export const externalDashboardTileListSchema = z
647650
// ==============================
648651
// Alerts
649652
// ==============================
650-
const zChannel = z.object({
651-
type: z.literal('webhook'),
652-
webhookId: z.string().min(1),
653-
});
654-
655653
const zSavedSearchAlert = z.object({
656654
source: z.literal(AlertSource.SAVED_SEARCH),
657655
groupBy: z.string().nullish(),
@@ -666,7 +664,8 @@ const zTileAlert = z.object({
666664

667665
export const alertSchema = z
668666
.object({
669-
channel: zChannel,
667+
channel: zAlertChannel.optional(),
668+
channels: zAlertChannels.optional(),
670669
interval: z.enum(['1m', '5m', '15m', '30m', '1h', '6h', '12h', '1d']),
671670
scheduleOffsetMinutes: z.number().int().min(0).max(1439).optional(),
672671
scheduleStartAt: scheduleStartAtSchema,
@@ -680,6 +679,7 @@ export const alertSchema = z
680679
numConsecutiveWindows: z.number().int().min(1).nullish(),
681680
})
682681
.and(zSavedSearchAlert.or(zTileAlert))
682+
.superRefine(validateAlertChannelSelection)
683683
.superRefine(validateAlertScheduleOffsetMinutes)
684684
.superRefine(validateAlertThresholdMax);
685685

‎packages/app/src/DBSearchPageAlertModal.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -588,7 +588,7 @@ export const DBSearchPageAlertModal = ({
588588
{(savedSearch?.alerts || []).map((alert, index) => (
589589
<Tabs.Tab key={alert.id} value={`${index}`}>
590590
<Group gap="xs">
591-
{getWebhookChannelIcon(alert.channel.type)}
591+
{getWebhookChannelIcon(alert.channel?.type)}
592592
Alert {index + 1}
593593
<AlertStatusIcon alerts={[alert]} />
594594
</Group>

0 commit comments

Comments
 (0)