-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathalerts.ts
More file actions
386 lines (337 loc) · 10 KB
/
alerts.ts
File metadata and controls
386 lines (337 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import {
displayTypeSupportsRawSqlAlerts,
validateRawSqlForAlert,
} from '@hyperdx/common-utils/dist/core/utils';
import { isRawSqlSavedChartConfig } from '@hyperdx/common-utils/dist/guards';
import { sign, verify } from 'jsonwebtoken';
import { groupBy } from 'lodash';
import ms from 'ms';
import { z } from 'zod';
import type { ObjectId } from '@/models';
import Alert, {
AlertChannel,
AlertInterval,
AlertSource,
AlertThresholdType,
IAlert,
} from '@/models/alert';
import Dashboard, { IDashboard } from '@/models/dashboard';
import { ISavedSearch, SavedSearch } from '@/models/savedSearch';
import { IUser } from '@/models/user';
import Webhook from '@/models/webhook';
import { Api400Error } from '@/utils/errors';
import logger from '@/utils/logger';
import { alertSchema, objectIdSchema } from '@/utils/zod';
export type AlertInput = {
id?: string;
source?: AlertSource;
channel: AlertChannel;
interval: AlertInterval;
scheduleOffsetMinutes?: number;
scheduleStartAt?: string | null;
thresholdType: AlertThresholdType;
threshold: number;
// Message template
name?: string | null;
message?: string | null;
// Log alerts
groupBy?: string;
savedSearchId?: string;
// Chart alerts
dashboardId?: string;
tileId?: string;
// Silenced
silenced?: {
by?: ObjectId;
at: Date;
until: Date;
};
};
const validateObjectId = (id: string | undefined, message: string) => {
if (objectIdSchema.safeParse(id).success === false) {
throw new Api400Error(message);
}
};
export const validateAlertInput = async (
teamId: ObjectId,
alertInput: Pick<
AlertInput,
'source' | 'dashboardId' | 'tileId' | 'savedSearchId' | 'channel'
>,
) => {
if (alertInput.source === AlertSource.TILE) {
validateObjectId(alertInput.dashboardId, 'Invalid dashboard ID');
const dashboard = await Dashboard.findOne({
_id: alertInput.dashboardId,
team: teamId,
});
if (dashboard == null) {
throw new Api400Error('Dashboard not found');
}
const tile = dashboard.tiles.find(tile => tile.id === alertInput.tileId);
if (tile == null) {
throw new Api400Error('Tile not found');
}
if (tile.config != null && isRawSqlSavedChartConfig(tile.config)) {
if (!displayTypeSupportsRawSqlAlerts(tile.config.displayType)) {
throw new Api400Error(
'Alerts on Raw SQL tiles are only supported for Line, Stacked Bar, or Number display types',
);
}
const { errors } = validateRawSqlForAlert(tile.config);
if (errors.length > 0) {
throw new Api400Error(
`Raw SQL alert query is invalid: ${errors.join(', ')}`,
);
}
}
}
if (alertInput.source === AlertSource.SAVED_SEARCH) {
validateObjectId(alertInput.savedSearchId, 'Invalid saved search ID');
const savedSearch = await SavedSearch.findOne({
_id: alertInput.savedSearchId,
team: teamId,
});
if (savedSearch == null) {
throw new Api400Error('Saved search not found');
}
}
if (alertInput.channel.type === 'webhook') {
validateObjectId(alertInput.channel.webhookId, 'Invalid webhook ID');
if (
(await Webhook.findOne({
_id: alertInput.channel.webhookId,
team: teamId,
})) == null
) {
throw new Api400Error('Webhook not found');
}
}
};
const makeAlert = (alert: AlertInput, userId?: ObjectId): Partial<IAlert> => {
// Preserve existing DB value when scheduleStartAt is omitted from updates
// (undefined), while still allowing explicit clears via null.
const hasScheduleStartAt = alert.scheduleStartAt !== undefined;
// If scheduleStartAt is explicitly provided, offset-based alignment is ignored.
// Force persisted offset to 0 so updates can't leave stale non-zero offsets.
// If scheduleStartAt is explicitly cleared and offset is omitted, also reset
// to 0 to avoid preserving stale values from older documents.
const normalizedScheduleOffsetMinutes =
hasScheduleStartAt && alert.scheduleStartAt != null
? 0
: hasScheduleStartAt && alert.scheduleOffsetMinutes == null
? 0
: alert.scheduleOffsetMinutes;
return {
channel: alert.channel,
interval: alert.interval,
...(normalizedScheduleOffsetMinutes != null && {
scheduleOffsetMinutes: normalizedScheduleOffsetMinutes,
}),
...(hasScheduleStartAt && {
scheduleStartAt:
alert.scheduleStartAt == null ? null : new Date(alert.scheduleStartAt),
}),
source: alert.source,
threshold: alert.threshold,
thresholdType: alert.thresholdType,
...(userId && { createdBy: userId }),
// Message template
// If they're undefined/null, set it to null so we clear out the field
// due to mongoose behavior:
// https://mongoosejs.com/docs/migrating_to_6.html#removed-omitundefined
name: alert.name == null ? null : alert.name,
message: alert.message == null ? null : alert.message,
// Log alerts
savedSearch: alert.savedSearchId as unknown as ObjectId,
groupBy: alert.groupBy,
// Chart alerts
dashboard: alert.dashboardId as unknown as ObjectId,
tileId: alert.tileId,
};
};
export const createAlert = async (
teamId: ObjectId,
alertInput: z.infer<typeof alertSchema>,
userId: ObjectId,
) => {
return new Alert({
...makeAlert(alertInput, userId),
team: teamId,
}).save();
};
// create an update alert function based off of the above create alert function
export const updateAlert = async (
id: string,
teamId: ObjectId,
alertInput: AlertInput,
) => {
// should consider clearing AlertHistory when updating an alert?
return Alert.findOneAndUpdate(
{
_id: id,
team: teamId,
},
makeAlert(alertInput),
{
returnDocument: 'after',
},
);
};
export const getAlerts = async (teamId: ObjectId) => {
return Alert.find({ team: teamId });
};
export const getAlertById = async (
alertId: ObjectId | string,
teamId: ObjectId | string,
) => {
return Alert.findOne({
_id: alertId,
team: teamId,
});
};
export const getTeamDashboardAlertsByDashboardAndTile = async (
teamId: ObjectId,
) => {
const alerts = await Alert.find({
source: AlertSource.TILE,
team: teamId,
}).populate('createdBy', 'email name');
return groupBy(alerts, a => `${a.dashboard?.toString()}:${a.tileId}`);
};
export const getDashboardAlertsByTile = async (
teamId: ObjectId,
dashboardId: ObjectId | string,
) => {
const alerts = await Alert.find({
dashboard: dashboardId,
source: AlertSource.TILE,
team: teamId,
}).populate('createdBy', 'email name');
return groupBy(alerts, 'tileId');
};
export const createOrUpdateDashboardAlerts = async (
dashboardId: ObjectId | string,
teamId: ObjectId,
alertsByTile: Record<string, AlertInput>,
userId?: ObjectId,
) => {
return Promise.all(
Object.entries(alertsByTile).map(async ([tileId, alert]) => {
const filter = {
dashboard: dashboardId,
tileId,
source: AlertSource.TILE,
team: teamId,
};
const oldAlert = await Alert.findOne(filter);
const alertValues =
oldAlert && oldAlert.createdBy
? makeAlert(alert)
: makeAlert(alert, userId);
return await Alert.findOneAndUpdate(filter, alertValues, {
new: true,
upsert: true,
});
}),
);
};
export const deleteDashboardAlerts = async (
dashboardId: ObjectId | string,
teamId: ObjectId,
tileIds?: string[],
) => {
return Alert.deleteMany({
dashboard: dashboardId,
team: teamId,
source: AlertSource.TILE,
...(tileIds && { tileId: { $in: tileIds } }),
});
};
export const deleteSavedSearchAlerts = async (
savedSearchId: string,
teamId: string,
) => {
return Alert.deleteMany({
savedSearch: savedSearchId,
team: teamId,
});
};
export const getAlertsEnhanced = async (teamId: ObjectId) => {
return Alert.find({ team: teamId }).populate<{
savedSearch: ISavedSearch;
dashboard: IDashboard;
createdBy?: IUser;
silenced?: IAlert['silenced'] & {
by: IUser;
};
}>(['savedSearch', 'dashboard', 'createdBy', 'silenced.by']);
};
export const getAlertEnhanced = async (
alertId: ObjectId | string,
teamId: ObjectId,
) => {
return Alert.findOne({ _id: alertId, team: teamId }).populate<{
savedSearch: ISavedSearch;
dashboard: IDashboard;
createdBy?: IUser;
silenced?: IAlert['silenced'] & {
by: IUser;
};
}>(['savedSearch', 'dashboard', 'createdBy', 'silenced.by']);
};
export const deleteAlert = async (id: string, teamId: ObjectId) => {
return Alert.deleteOne({
_id: id,
team: teamId,
});
};
export const generateAlertSilenceToken = async (
alertId: ObjectId | string,
teamId: ObjectId | string,
) => {
const secret = process.env.EXPRESS_SESSION_SECRET;
if (!secret) {
logger.error(
'EXPRESS_SESSION_SECRET is not set for signing token, skipping alert silence JWT generation',
);
return '';
}
const alert = await getAlertById(alertId, teamId);
if (alert == null) {
throw new Error('Alert not found');
}
const token = sign(
{ alertId: alert._id.toString(), teamId: teamId.toString() },
secret,
{ expiresIn: '1h' },
);
// Slack does not accept ids longer than 255 characters
if (token.length > 255) {
logger.error(
'Alert silence JWT length is greater than 255 characters, this may cause issues with some clients.',
);
}
return token;
};
export const silenceAlertByToken = async (token: string) => {
const secret = process.env.EXPRESS_SESSION_SECRET;
if (!secret) {
throw new Error('EXPRESS_SESSION_SECRET is not set for verifying token');
}
const decoded = verify(token, secret, {
algorithms: ['HS256'],
}) as { alertId: string; teamId: string };
if (!decoded?.alertId || !decoded?.teamId) {
throw new Error('Invalid token');
}
const alert = await getAlertById(decoded.alertId, decoded.teamId);
if (alert == null) {
throw new Error('Alert not found');
}
alert.silenced = {
at: new Date(),
until: new Date(Date.now() + ms('30m')),
};
return alert.save();
};