Skip to content

Commit c602cbb

Browse files
refactor(alerts): extract notification transports behind a registry (#2844)
1 parent 59b96e9 commit c602cbb

12 files changed

Lines changed: 570 additions & 275 deletions

File tree

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

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { Types } from 'mongoose';
33
import { getLoggedInAgent, getServer } from '@/fixtures';
44
import Alert from '@/models/alert';
55
import Webhook, { WebhookService } from '@/models/webhook';
6-
import * as template from '@/tasks/checkAlerts/template';
6+
import * as transports from '@/tasks/checkAlerts/transports';
77

88
const MOCK_WEBHOOK = {
99
name: 'Test Webhook',
@@ -1221,10 +1221,10 @@ describe('webhooks router', () => {
12211221

12221222
beforeEach(() => {
12231223
genericSpy = jest
1224-
.spyOn(template, 'handleSendGenericWebhook')
1224+
.spyOn(transports, 'handleSendGenericWebhook')
12251225
.mockResolvedValue(undefined);
12261226
slackSpy = jest
1227-
.spyOn(template, 'handleSendSlackWebhook')
1227+
.spyOn(transports, 'handleSendSlackWebhook')
12281228
.mockResolvedValue(undefined);
12291229
});
12301230

@@ -1258,7 +1258,7 @@ describe('webhooks router', () => {
12581258

12591259
// The outbound call should receive the real URL and headers
12601260
expect(genericSpy).toHaveBeenCalledTimes(1);
1261-
const sentWebhook = genericSpy.mock.calls[0][0];
1261+
const sentWebhook = genericSpy.mock.calls[0][0].channel;
12621262
expect(sentWebhook.url).toBe(realUrl);
12631263
expect(sentWebhook.headers.toJSON()).toEqual({
12641264
Authorization: 'Bearer real-secret',
@@ -1289,7 +1289,7 @@ describe('webhooks router', () => {
12891289

12901290
// The outbound call should receive the attacker URL and literal ****
12911291
// (NOT the stored real secret)
1292-
const sentWebhook = genericSpy.mock.calls[0][0];
1292+
const sentWebhook = genericSpy.mock.calls[0][0].channel;
12931293
expect(sentWebhook.url).toBe('https://attacker.example.com/capture');
12941294
expect(sentWebhook.headers.toJSON()).toEqual({
12951295
Authorization: '****',
@@ -1383,7 +1383,7 @@ describe('webhooks router', () => {
13831383
.expect(200);
13841384

13851385
expect(genericSpy).toHaveBeenCalledTimes(1);
1386-
const sentWebhook = genericSpy.mock.calls[0][0];
1386+
const sentWebhook = genericSpy.mock.calls[0][0].channel;
13871387
expect(sentWebhook.url).toBe('https://example.com/webhook');
13881388
});
13891389

‎packages/api/src/routers/api/webhooks.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import Webhook, { WebhookService } from '@/models/webhook';
1717
import {
1818
handleSendGenericWebhook,
1919
handleSendSlackWebhook,
20-
} from '@/tasks/checkAlerts/template';
20+
} from '@/tasks/checkAlerts/transports';
2121
import { isDuplicateKeyError } from '@/utils/errors';
2222
import {
2323
validateWebhookUrl,
@@ -470,13 +470,15 @@ router.post(
470470
eventId: 'test-event-id',
471471
};
472472

473+
const testChannel = { type: 'webhook' as const, channel: testWebhook };
474+
473475
if (service === WebhookService.Slack) {
474-
await handleSendSlackWebhook(testWebhook, testMessage);
476+
await handleSendSlackWebhook(testChannel, testMessage);
475477
} else if (
476478
service === WebhookService.Generic ||
477479
service === WebhookService.IncidentIO
478480
) {
479-
await handleSendGenericWebhook(testWebhook, testMessage);
481+
await handleSendGenericWebhook(testChannel, testMessage);
480482
} else {
481483
return res.status(400).json({
482484
message: 'Unsupported webhook service type',
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { InlineNotificationDispatcher } from '@/tasks/checkAlerts/notifications';
2+
3+
// The dispatcher forwards this opaque, so its shape doesn't matter for these
4+
// tests — only that dispatch()/shutdown() behave per the documented contract.
5+
const fakeJob: any = {};
6+
7+
describe('InlineNotificationDispatcher', () => {
8+
it('resolves after the deliver fn resolves', async () => {
9+
const order: string[] = [];
10+
const dispatcher = new InlineNotificationDispatcher(async () => {
11+
order.push('delivered');
12+
});
13+
await dispatcher.dispatch(fakeJob);
14+
order.push('dispatch-returned');
15+
expect(order).toEqual(['delivered', 'dispatch-returned']);
16+
});
17+
18+
it('propagates a delivery rejection to the caller', async () => {
19+
const dispatcher = new InlineNotificationDispatcher(async () => {
20+
throw new Error('webhook exploded');
21+
});
22+
await expect(dispatcher.dispatch(fakeJob)).rejects.toThrow(
23+
'webhook exploded',
24+
);
25+
});
26+
27+
it('shutdown resolves immediately — nothing is buffered', async () => {
28+
const dispatcher = new InlineNotificationDispatcher(async () => {});
29+
await expect(dispatcher.shutdown(1000)).resolves.toBeUndefined();
30+
});
31+
});

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,18 @@ export class WebhookRedirectError extends Error {
1313
}
1414
}
1515

16+
// Carries the destination's HTTP status alongside its response body so
17+
// callers can log/classify without an `as any` assertion on a plain Error.
18+
export class WebhookResponseError extends Error {
19+
readonly status: number;
20+
21+
constructor(message: string, status: number) {
22+
super(message);
23+
this.name = 'WebhookResponseError';
24+
this.status = status;
25+
}
26+
}
27+
1628
// @clickhouse/client (Node) rejects with these exact messages when the
1729
// configured request_timeout elapses or the request is aborted. See
1830
// clickhouse-js packages/client-node/src/connection/socket_pool.ts.

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,9 @@ import {
7676
import {
7777
AlertMessageTemplateDefaultView,
7878
buildAlertMessageTemplateTitle,
79-
handleSendGenericWebhook,
8079
renderAlertTemplate,
8180
} from '@/tasks/checkAlerts/template';
81+
import { handleSendGenericWebhook } from '@/tasks/checkAlerts/transports';
8282
import { tasksTracer } from '@/tasks/tracer';
8383
import { CheckAlertsTaskArgs, HdxTask } from '@/tasks/types';
8484
import {
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import type {
2+
Message,
3+
PopulatedAlertChannel,
4+
} from '@/tasks/checkAlerts/transports';
5+
import { deliverToChannel } from '@/tasks/checkAlerts/transports';
6+
7+
/**
8+
* Alert notification dispatch seam.
9+
*
10+
* Evaluation produces fully rendered NotificationJobs; a NotificationDispatcher
11+
* owns delivery. `eventId` is the idempotency key, so a queueing dispatcher can
12+
* deduplicate without re-deriving it.
13+
*/
14+
export type NotificationJob = {
15+
/** Idempotency key: objectHash(alertId, channel, group). */
16+
eventId: string;
17+
alertId?: string;
18+
teamId?: string;
19+
group?: string;
20+
/**
21+
* Named `populatedChannel`, not `channel`, deliberately: a downstream build
22+
* carries both a serializable channel *reference* and the resolved document,
23+
* and reusing `channel` for the resolved one collides with that.
24+
*/
25+
populatedChannel: PopulatedAlertChannel;
26+
message: Message;
27+
};
28+
29+
export type NotificationDeliverFn = (job: NotificationJob) => Promise<void>;
30+
31+
/**
32+
* dispatch() contract: the inline implementation resolves after delivery, so
33+
* errors propagate to the caller. Queueing implementations resolve after
34+
* enqueue; their errors surface in their own logs and metrics.
35+
*/
36+
export interface NotificationDispatcher {
37+
dispatch(job: NotificationJob): Promise<void>;
38+
/** Flush anything pending, giving up after deadlineMs. */
39+
shutdown(deadlineMs: number): Promise<void>;
40+
}
41+
42+
/**
43+
* The default delivery implementation, wired to the transports registry. A
44+
* downstream dispatcher composes this rather than calling `deliverToChannel`
45+
* directly, so it stays swappable in one place.
46+
*
47+
* @public
48+
*/
49+
export const deliverNotification: NotificationDeliverFn = async job => {
50+
await deliverToChannel(job.populatedChannel, job.message, {
51+
group: job.group,
52+
});
53+
};
54+
55+
/** Delivers synchronously so errors flow into the caller's executionErrors. */
56+
export class InlineNotificationDispatcher implements NotificationDispatcher {
57+
constructor(private readonly deliver: NotificationDeliverFn) {}
58+
59+
async dispatch(job: NotificationJob): Promise<void> {
60+
await this.deliver(job);
61+
}
62+
63+
async shutdown(_deadlineMs: number): Promise<void> {
64+
// Nothing buffered.
65+
}
66+
}
67+
68+
export const inlineNotificationDispatcher = new InlineNotificationDispatcher(
69+
deliverNotification,
70+
);

0 commit comments

Comments
 (0)