Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/slack-block-limit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@hyperdx/api": patch
---

fix(api): prevent Slack notification failures when alert message exceeds 3000 chars
Original file line number Diff line number Diff line change
Expand Up @@ -1336,6 +1336,7 @@ describe('checkAlerts', () => {
});
const defaultInlineAlertView: AlertMessageTemplateDefaultView = {
alert: {
id: 'fake-inline-alert-id',
thresholdType: AlertThresholdType.ABOVE,
threshold: 1,
source: AlertSource.INLINE,
Expand Down Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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,
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
24 changes: 7 additions & 17 deletions packages/api/src/tasks/checkAlerts/providers/default.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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;
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
}): 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).
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
// 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();
}

Expand Down
7 changes: 3 additions & 4 deletions packages/api/src/tasks/checkAlerts/providers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
10 changes: 4 additions & 6 deletions packages/api/src/tasks/checkAlerts/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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<WebhookChannel>({
type: 'webhook',
channel: {
_id: new ObjectId(),
name: 'Slack Alerts',
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
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: [
{
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
type: 'section',
text: {
type: 'mrkdwn',
text: '*<https://app.hyperdx.io/alerts/123 | CPU Alert>*\nCPU > 90%',
},
},
],
},
);
});
});
});
43 changes: 42 additions & 1 deletion packages/api/src/tasks/checkAlerts/transports/slack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 : ''}`;
};
Comment thread
pulpdrew marked this conversation as resolved.
Resolved

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))}`;
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
};

export const handleSendSlackWebhook = async (
channel: WebhookChannel,
message: Message,
Expand All @@ -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,
),
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
},
},
],
Expand Down
Loading