diff --git a/.changeset/slack-block-limit.md b/.changeset/slack-block-limit.md new file mode 100644 index 000000000..18de699cc --- /dev/null +++ b/.changeset/slack-block-limit.md @@ -0,0 +1,5 @@ +--- +"@hyperdx/api": patch +--- + +fix(api): prevent Slack notification failures when alert message exceeds 3000 chars 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 59f69cb10..692585343 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts @@ -1336,6 +1336,7 @@ describe('checkAlerts', () => { }); const defaultInlineAlertView: AlertMessageTemplateDefaultView = { alert: { + id: 'fake-inline-alert-id', thresholdType: AlertThresholdType.ABOVE, threshold: 1, source: AlertSource.INLINE, @@ -1387,18 +1388,11 @@ describe('checkAlerts', () => { `"http://app:8080/dashboards/id-123?from=1679089083103&granularity=5+minute&to=1679093339103&highlightedTileId=test-tile-id"`, ); - // Inline alerts link to the chart explorer seeded with the persisted - // config. Built programmatically — the URL-encoded config JSON makes an - // inline snapshot unreadable. - const expectedChartAlertUrl = new URL('http://app:8080/chart'); - expectedChartAlertUrl.search = new URLSearchParams({ - config: JSON.stringify(inlineAlertConfig), - from: '1679089083103', - to: '1679093339103', - }).toString(); expect( buildAlertMessageTemplateHdxLink(alertProvider, defaultInlineAlertView), - ).toBe(expectedChartAlertUrl.toString()); + ).toMatchInlineSnapshot( + `"http://app:8080/alerts/fake-inline-alert-id?from=1679089083103&to=1679093339103"`, + ); }); it('formatValueToMatchThreshold', () => { @@ -3031,13 +3025,9 @@ describe('checkAlerts', () => { expect(history2.state).toBe('OK'); expect(history2.createdAt).toEqual(new Date('2023-11-16T22:15:00.000Z')); - // Notification links to the chart explorer seeded with the persisted - // config, padded by 7x granularity on both sides of the window. - const expectedUrl = new URL('http://app:8080/chart'); + // Padded by 7x granularity on both sides of the window. + const expectedUrl = new URL(`http://app:8080/alerts/${details.alert.id}`); expectedUrl.search = new URLSearchParams({ - config: JSON.stringify( - (await Alert.findById(details.alert.id))!.chartConfig, - ), from: String( new Date('2023-11-16T22:05:00.000Z').getTime() - ms('5m') * 7, ), diff --git a/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts index 4bee90486..5d4389a23 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts @@ -173,7 +173,7 @@ describe('CheckAlertTask', () => { recordAlertErrors: jest.fn(), asyncDispose: jest.fn(), buildChartLink: jest.fn(), - buildChartExplorerLink: jest.fn(), + buildAlertDetailsLink: jest.fn(), buildLogSearchLink: jest.fn(), getClickHouseClient: jest .fn() diff --git a/packages/api/src/tasks/checkAlerts/__tests__/renderAlertTemplate.int.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/renderAlertTemplate.int.test.ts index 266af03ee..2697b4dc5 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/renderAlertTemplate.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/renderAlertTemplate.int.test.ts @@ -198,6 +198,7 @@ const makeInlineView = ( overrides: ViewOverrides = {}, ): AlertMessageTemplateDefaultView => ({ alert: { + id: 'fake-inline-alert-id', thresholdType: overrides.thresholdType ?? AlertThresholdType.ABOVE, threshold: overrides.threshold ?? 5, thresholdMax: overrides.thresholdMax, diff --git a/packages/api/src/tasks/checkAlerts/providers/default.ts b/packages/api/src/tasks/checkAlerts/providers/default.ts index 892a6f1a9..5399d5f51 100644 --- a/packages/api/src/tasks/checkAlerts/providers/default.ts +++ b/packages/api/src/tasks/checkAlerts/providers/default.ts @@ -1,11 +1,7 @@ import PQueue from '@esm2cjs/p-queue'; import { displayTypeSupportsRawSqlAlerts } from '@hyperdx/common-utils/dist/core/utils'; import { isRawSqlSavedChartConfig } from '@hyperdx/common-utils/dist/guards'; -import { - AlertChartConfig, - RawSqlSavedChartConfig, - Tile, -} from '@hyperdx/common-utils/dist/types'; +import { RawSqlSavedChartConfig, Tile } from '@hyperdx/common-utils/dist/types'; import mongoose from 'mongoose'; import ms from 'ms'; import { serializeError } from 'serialize-error'; @@ -643,29 +639,23 @@ export default class DefaultAlertProvider implements AlertProvider { return url.toString(); } - buildChartExplorerLink({ - chartConfig, + buildAlertDetailsLink({ + alertId, endTime, granularity, startTime, }: { - chartConfig: AlertChartConfig; + alertId: string; endTime: Date; granularity: string; startTime: Date; }): string { - const url = new URL(`${config.FRONTEND_URL}/chart`); + const url = new URL(`${config.FRONTEND_URL}/alerts/${alertId}`); // Extend both start and end time by 7x granularity, matching the - // dashboard link so the alerting window has surrounding context. The - // chart explorer reads `config` (JSON) and `from`/`to` (epoch ms). + // dashboard link so the alerting window has surrounding context. const from = (startTime.getTime() - ms(granularity) * 7).toString(); const to = (endTime.getTime() + ms(granularity) * 7).toString(); - const queryParams = new URLSearchParams({ - config: JSON.stringify(chartConfig), - from, - to, - }); - url.search = queryParams.toString(); + url.search = new URLSearchParams({ from, to }).toString(); return url.toString(); } diff --git a/packages/api/src/tasks/checkAlerts/providers/index.ts b/packages/api/src/tasks/checkAlerts/providers/index.ts index 96071696e..67a4ffe23 100644 --- a/packages/api/src/tasks/checkAlerts/providers/index.ts +++ b/packages/api/src/tasks/checkAlerts/providers/index.ts @@ -90,11 +90,10 @@ export interface AlertProvider { /** * Link for inline alerts (which have no saved search or dashboard to open): - * the chart explorer with the alert's persisted config over the alerting - * window. Works regardless of whether the alert-details page is enabled. + * the alert's details page over the alerting window. */ - buildChartExplorerLink(params: { - chartConfig: AlertChartConfig; + buildAlertDetailsLink(params: { + alertId: string; endTime: Date; granularity: string; startTime: Date; diff --git a/packages/api/src/tasks/checkAlerts/template.ts b/packages/api/src/tasks/checkAlerts/template.ts index fde25921b..dd7af20c9 100644 --- a/packages/api/src/tasks/checkAlerts/template.ts +++ b/packages/api/src/tasks/checkAlerts/template.ts @@ -327,13 +327,11 @@ export const buildAlertMessageTemplateHdxLink = ( tileId: alert.tileId ?? undefined, }); } else if (alert.source === AlertSource.INLINE) { - if (alert.chartConfig == null) { - throw new Error(`Source is ${alert.source} but chartConfig is null`); + if (alert.id == null) { + throw new Error(`Source is ${alert.source} but alert id is null`); } - // Inline alerts have no saved search or dashboard to open — link to the - // chart explorer seeded with the alert's persisted config. - return alertProvider.buildChartExplorerLink({ - chartConfig: alert.chartConfig, + return alertProvider.buildAlertDetailsLink({ + alertId: alert.id, endTime, granularity, startTime, diff --git a/packages/api/src/tasks/checkAlerts/transports/__tests__/slack.test.ts b/packages/api/src/tasks/checkAlerts/transports/__tests__/slack.test.ts new file mode 100644 index 000000000..dbd18450a --- /dev/null +++ b/packages/api/src/tasks/checkAlerts/transports/__tests__/slack.test.ts @@ -0,0 +1,123 @@ +import { WebhookService } from '@hyperdx/common-utils/dist/types'; +import { fromPartial } from '@total-typescript/shoehorn'; +import { ObjectId } from 'mongodb'; + +import { AlertState } from '@/models/alert'; +import { + formatSlackSectionText, + handleSendSlackWebhook, +} from '@/tasks/checkAlerts/transports/slack'; +import type { + Message, + WebhookChannel, +} from '@/tasks/checkAlerts/transports/types'; +import * as slack from '@/utils/slack'; + +jest.mock('@/utils/slack'); +jest.mock('@/utils/validators'); + +describe('Slack transport', () => { + describe('formatSlackSectionText', () => { + const link = 'https://app.hyperdx.io/alerts/123'; + const title = 'High Error Rate'; + const header = `*<${link} | ${title}>*\n`; + + it('keeps the body when the text fits', () => { + const body = 'Error rate exceeded 5%'; + expect(formatSlackSectionText(link, title, body)).toBe( + `${header}${body}`, + ); + }); + + it('keeps a body that exactly fills the limit', () => { + const body = 'b'.repeat(3000 - header.length); + expect(formatSlackSectionText(link, title, body)).toBe( + `${header}${body}`, + ); + }); + + it('truncates the body to fit the limit, keeping the link', () => { + const formatted = formatSlackSectionText(link, title, 'b'.repeat(3500)); + + expect(formatted).toBe( + `${header}${'b'.repeat(3000 - header.length - 7)}...`, + ); + expect(formatted.length).toBeLessThanOrEqual(3000); + }); + + it('re-closes a code block the cut lands inside', () => { + const body = `5 lines found\n\`\`\`\n${'log line\n'.repeat(400)}\`\`\``; + const formatted = formatSlackSectionText(link, title, body); + + expect(formatted.endsWith('...\n```')).toBe(true); + expect(formatted.split('```')).toHaveLength(3); + expect(formatted.length).toBeLessThanOrEqual(3000); + }); + + it('does not add a fence when the cut lands after a closed code block', () => { + const body = `\`\`\`\nsample\n\`\`\`\n${'m'.repeat(3500)}`; + const formatted = formatSlackSectionText(link, title, body); + + expect(formatted.endsWith('m...')).toBe(true); + expect(formatted.split('```')).toHaveLength(3); + }); + + it('does not split an emoji at the cut', () => { + const prefix = 'b'.repeat(3000 - header.length - 7 - 1); + const formatted = formatSlackSectionText( + link, + title, + `${prefix}🚨${'b'.repeat(100)}`, + ); + + expect(formatted).toBe(`${header}${prefix}...`); + }); + }); + + describe('handleSendSlackWebhook', () => { + it('passes formatted section block text to postMessageToWebhook', async () => { + const mockPostMessage = jest + .spyOn(slack, 'postMessageToWebhook') + .mockResolvedValue({ text: 'ok' }); + + const channel = fromPartial({ + type: 'webhook', + channel: { + _id: new ObjectId(), + name: 'Slack Alerts', + service: WebhookService.Slack, + url: 'https://hooks.slack.com/services/T00/B00/X00', + }, + }); + + const message: Message = { + hdxLink: 'https://app.hyperdx.io/alerts/123', + title: 'CPU Alert', + body: 'CPU > 90%', + state: AlertState.ALERT, + startTime: 0, + endTime: 1000, + eventId: 'evt-1', + }; + + await handleSendSlackWebhook(channel, message); + + expect(mockPostMessage).toHaveBeenCalledTimes(1); + expect(mockPostMessage).toHaveBeenCalledWith( + 'https://hooks.slack.com/services/T00/B00/X00', + { + text: 'CPU Alert', + blocks: [ + { + type: 'section', + text: { + type: 'mrkdwn', + text: '**\nCPU > 90%', + }, + }, + ], + }, + ); + }); + }); +}); diff --git a/packages/api/src/tasks/checkAlerts/transports/slack.ts b/packages/api/src/tasks/checkAlerts/transports/slack.ts index d1f069ade..17c2de0d8 100644 --- a/packages/api/src/tasks/checkAlerts/transports/slack.ts +++ b/packages/api/src/tasks/checkAlerts/transports/slack.ts @@ -13,6 +13,43 @@ import type { import * as slack from '@/utils/slack'; import { validateWebhookUrl } from '@/utils/validators'; +// Slack rejects a section block whose text is over 3000 characters. +const MAX_SLACK_SECTION_LENGTH = 3000; +const ELLIPSIS = '...'; +const CODE_FENCE = '```'; +const CLOSING_FENCE = `\n${CODE_FENCE}`; + +const isHighSurrogate = (code: number) => code >= 0xd800 && code <= 0xdbff; + +const truncateBody = (body: string, maxLength: number): string => { + if (body.length <= maxLength) { + return body; + } + // Always reserve room to re-close a code fence, so the result fits either way. + let kept = body.slice( + 0, + Math.max(0, maxLength - ELLIPSIS.length - CLOSING_FENCE.length), + ); + // Don't leave half of a surrogate pair (e.g. an emoji) at the cut. + if (isHighSurrogate(kept.charCodeAt(kept.length - 1))) { + kept = kept.slice(0, -1); + } + // Saved-search bodies end with sample lines in a code block; the cut + // usually lands inside it. + const isFenceOpen = kept.split(CODE_FENCE).length % 2 === 0; + return `${kept}${ELLIPSIS}${isFenceOpen ? CLOSING_FENCE : ''}`; +}; + +export const formatSlackSectionText = ( + hdxLink: string, + title: string, + body: string, + maxLength = MAX_SLACK_SECTION_LENGTH, +): string => { + const header = `*<${hdxLink} | ${title}>*\n`; + return `${header}${truncateBody(body, Math.max(0, maxLength - header.length))}`; +}; + export const handleSendSlackWebhook = async ( channel: WebhookChannel, message: Message, @@ -29,7 +66,11 @@ export const handleSendSlackWebhook = async ( type: 'section', text: { type: 'mrkdwn', - text: `*<${message.hdxLink} | ${message.title}>*\n${message.body}`, + text: formatSlackSectionText( + message.hdxLink, + message.title, + message.body, + ), }, }, ],