Skip to content
Open
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
6 changes: 3 additions & 3 deletions packages/notifications/TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@
- [x] **Discord** - Webhook support
- [x] **Email** - Injected send function
- [x] **Webhook** - Generic HTTP webhook
- [x] **Microsoft Teams** - Adaptive Cards via webhook
- [x] **Telegram** - Bot API (sendMessage)
- [x] **Google Chat** - Cards via webhook
- [ ] **Microsoft Teams** - Adaptive Cards via webhook
- [ ] **Telegram** - Bot API (sendMessage)
- [ ] **Google Chat** - Cards via webhook
- [ ] **PagerDuty** - Integration for incident management
- [ ] **Opsgenie** - Alerting and on-call management
- [ ] **SMS/Twilio** - SMS notifications via Twilio API
Expand Down
160 changes: 160 additions & 0 deletions packages/notifications/src/__tests__/providers/discord.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { afterEach, describe, expect, mock, test } from "bun:test";
import type { SafeFetchInit } from "@databuddy/shared/ssrf-guard";

const safeFetchMock = mock(
(_url: string, _init?: SafeFetchInit) =>
Promise.resolve(new Response(null, { status: 204 }))
);

mock.module("@databuddy/shared/ssrf-guard", () => ({
safeFetch: safeFetchMock,
}));

const { buildDiscordEmbed, DiscordProvider } = await import(
"../../providers/discord"
);

describe("buildDiscordEmbed", () => {
test("hides internal metadata and keeps user-facing fields", () => {
const embed = buildDiscordEmbed({
title: "Anomaly detected",
message: "Traffic changed.",
metadata: {
dashboardUrl: "https://app.databuddy.cc/monitors/1",
alarmId: "internal-alarm-id",
template: "anomaly",
zScore: 7.1,
},
});

expect(embed.fields).toHaveLength(1);
expect(embed.fields?.[0]?.name).toBe("Dashboard Url");
expect(JSON.stringify(embed)).not.toContain("internal-alarm-id");
expect(JSON.stringify(embed)).not.toContain("zScore");
});

test("bounds title and description length before calling Discord", () => {
const embed = buildDiscordEmbed({
title: "T".repeat(400),
message: "M".repeat(5000),
});

expect(embed.title?.length).toBe(256);
expect(embed.description?.length).toBe(4096);
});

test("caps fields at Discord's 25-field embed limit", () => {
const embed = buildDiscordEmbed({
title: "Anomaly detected",
message: "Traffic changed.",
metadata: Object.fromEntries(
Array.from({ length: 100 }, (_, index) => [`field${index}`, index])
),
});

expect(embed.fields).toHaveLength(25);
});

test("stops adding fields before the 6000-character aggregate embed limit", () => {
// 25 fields at the max 1024-char value each would sum to 25,600 chars,
// far past Discord's 6000-char total-embed limit even though each field
// individually respects its own per-field caps.
const embed = buildDiscordEmbed({
title: "Anomaly detected",
message: "M".repeat(4096),
metadata: Object.fromEntries(
Array.from({ length: 25 }, (_, index) => [
`field${index}`,
"V".repeat(1024),
])
),
});

const total =
(embed.title?.length ?? 0) +
(embed.description?.length ?? 0) +
(embed.footer?.text.length ?? 0) +
(embed.fields ?? []).reduce(
(sum, field) => sum + field.name.length + field.value.length,
0
);

expect(embed.fields?.length ?? 0).toBeLessThan(25);
expect(total).toBeLessThanOrEqual(6000);
});

test("only surfaces a color and priority footer for elevated priority", () => {
const normal = buildDiscordEmbed({
title: "Site alert",
message: "The site is unavailable.",
priority: "normal",
});
expect(normal.color).toBeUndefined();
expect(normal.footer).toBeUndefined();

const urgent = buildDiscordEmbed({
title: "Site alert",
message: "The site is unavailable.",
priority: "urgent",
});
expect(urgent.color).toBeDefined();
expect(urgent.footer?.text).toBe("Priority: URGENT");
});
});

describe("DiscordProvider", () => {
afterEach(() => {
safeFetchMock.mockClear();
safeFetchMock.mockImplementation((_url: string, _init?: SafeFetchInit) =>
Promise.resolve(new Response(null, { status: 204 }))
);
});

test("returns a failed result when no webhook URL is configured", async () => {
const provider = new DiscordProvider({ webhookUrl: "" });
const result = await provider.send({ title: "t", message: "m" });

expect(result).toEqual({
success: false,
channel: "discord",
error: "Discord webhook URL not configured",
});
expect(safeFetchMock).not.toHaveBeenCalled();
});

test("posts an embed payload and reports success on a 204 response", async () => {
const provider = new DiscordProvider({
webhookUrl: "https://discord.com/api/webhooks/123/token",
});

const result = await provider.send({
title: "Site alert",
message: "The site is unavailable.",
});

expect(result.success).toBe(true);
expect(result.channel).toBe("discord");
expect(safeFetchMock).toHaveBeenCalledTimes(1);

const [url, init] = safeFetchMock.mock.calls[0] as [string, SafeFetchInit];
expect(url).toBe("https://discord.com/api/webhooks/123/token");
const body = JSON.parse(init.body as string);
expect(body.embeds[0].title).toBe("Site alert");
});

test("returns a failed result when Discord responds with an error status", async () => {
safeFetchMock.mockImplementationOnce(() =>
Promise.resolve(new Response("invalid webhook", { status: 404 }))
);

const provider = new DiscordProvider({
webhookUrl: "https://discord.com/api/webhooks/123/token",
});

const result = await provider.send({ title: "t", message: "m" });

expect(result.success).toBe(false);
expect(result.channel).toBe("discord");
expect(result.error).toContain("Discord API error: 404");
});
});
9 changes: 9 additions & 0 deletions packages/notifications/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { NotificationProvider } from "./providers/base";
import type { DiscordProviderConfig } from "./providers/discord";
import { DiscordProvider } from "./providers/discord";
import type { EmailProviderConfig } from "./providers/email";
import { EmailProvider } from "./providers/email";
import type { SlackProviderConfig } from "./providers/slack";
Expand All @@ -17,6 +19,7 @@ export interface NotificationClientConfig {
defaultRetries?: number;
defaultRetryDelay?: number;
defaultTimeout?: number;
discord?: DiscordProviderConfig;
email?: EmailProviderConfig;
slack?: SlackProviderConfig;
webhook?: WebhookProviderConfig;
Expand Down Expand Up @@ -65,6 +68,12 @@ export class NotificationClient {
new WebhookProvider(withDefaults(config.webhook))
);
}
if (config.discord) {
this.providers.set(
"discord",
new DiscordProvider(withDefaults(config.discord))
);
}
}

async send(
Expand Down
156 changes: 156 additions & 0 deletions packages/notifications/src/providers/discord.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import type {
DiscordEmbed,
DiscordEmbedField,
DiscordPayload,
NotificationPayload,
NotificationResult,
} from "../types";
import { BaseProvider } from "./base";
import {
formatMetadataLabel,
isUserFacingMetadata,
truncate,
} from "./payload-utils";

const MAX_TITLE_LENGTH = 256;
const MAX_DESCRIPTION_LENGTH = 4096;
const MAX_FIELD_NAME_LENGTH = 256;
const MAX_FIELD_VALUE_LENGTH = 1024;
const MAX_FIELDS = 25;
// Discord rejects an embed whose title + description + every field's name and
// value + footer text sum past 6000 characters, even when each individual
// piece is within its own per-component limit above.
const MAX_TOTAL_EMBED_LENGTH = 6000;

const PRIORITY_COLORS: Record<"low" | "high" | "urgent", number> = {
low: 0x95_a5_a6,
high: 0xf3_9c_12,
urgent: 0xed_42_45,
};

export function buildDiscordEmbed(payload: NotificationPayload): DiscordEmbed {
const title = truncate(payload.title, MAX_TITLE_LENGTH);
const description = truncate(payload.message, MAX_DESCRIPTION_LENGTH);
const elevatedPriority =
payload.priority && payload.priority !== "normal" ? payload.priority : null;
const priorityStyle = elevatedPriority
? {
color: PRIORITY_COLORS[elevatedPriority],
footer: { text: `Priority: ${elevatedPriority.toUpperCase()}` },
}
: null;

let total =
title.length +
description.length +
(priorityStyle?.footer.text.length ?? 0);

const fields: DiscordEmbedField[] = [];
if (payload.metadata) {
for (const [key, value] of Object.entries(payload.metadata)) {
if (fields.length >= MAX_FIELDS) {
break;
}
if (!isUserFacingMetadata(key)) {
continue;
}

const name = truncate(formatMetadataLabel(key), MAX_FIELD_NAME_LENGTH);
const fieldValue = truncate(String(value), MAX_FIELD_VALUE_LENGTH);
const fieldLength = name.length + fieldValue.length;

if (total + fieldLength > MAX_TOTAL_EMBED_LENGTH) {
break;
}

fields.push({ inline: true, name, value: fieldValue });
total += fieldLength;
}
}

return {
title,
description,
...(fields.length > 0 && { fields }),
...priorityStyle,
};
}

export interface DiscordProviderConfig {
avatarUrl?: string;
retries?: number;
retryDelay?: number;
timeout?: number;
username?: string;
webhookUrl: string;
}

export class DiscordProvider extends BaseProvider {
private readonly webhookUrl: string;
private readonly username?: string;
private readonly avatarUrl?: string;

constructor(config: DiscordProviderConfig) {
super({
timeout: config.timeout,
retries: config.retries,
retryDelay: config.retryDelay,
});
this.webhookUrl = config.webhookUrl;
this.username = config.username;
this.avatarUrl = config.avatarUrl;
}

async send(payload: NotificationPayload): Promise<NotificationResult> {
if (!this.webhookUrl) {
return {
success: false,
channel: "discord",
error: "Discord webhook URL not configured",
};
}

try {
const discordPayload = this.buildPayload(payload);
const response = await this.withRetry(async () => {
const res = await this.fetchWithTimeout(this.webhookUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(discordPayload),
});

if (!res.ok) {
const text = await res.text().catch(() => "Unable to read response");
throw new Error(
`Discord API error: ${res.status} ${res.statusText} - ${text.slice(0, 200)}`
);
}

return res;
});

return {
success: true,
channel: "discord",
response: {
status: response.status,
statusText: response.statusText,
},
};
} catch (error) {
return {
success: false,
channel: "discord",
error: error instanceof Error ? error.message : String(error),
};
}
}

private buildPayload(payload: NotificationPayload): DiscordPayload {
return {
embeds: [buildDiscordEmbed(payload)],
...(this.username && { username: this.username }),
...(this.avatarUrl && { avatar_url: this.avatarUrl }),
};
}
}
2 changes: 2 additions & 0 deletions packages/notifications/src/providers/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/** biome-ignore-all lint/performance/noBarrelFile: barrel file */
export type { NotificationProvider } from "./base";
export { BaseProvider } from "./base";
export type { DiscordProviderConfig } from "./discord";
export { DiscordProvider } from "./discord";
Comment on lines +4 to +5

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Discord extends the provider barrel

These exports expose the new Discord provider through an index-file barrel despite the repository's direct-import requirement, extending the prohibited indirection and making provider ownership less explicit.

Context Used: Basic guidelines for the project so vibe coders do... (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

export type { EmailProviderConfig } from "./email";
export { EmailProvider } from "./email";
export type { SlackProviderConfig } from "./slack";
Expand Down
24 changes: 24 additions & 0 deletions packages/notifications/src/providers/payload-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const FIRST_CHARACTER_PATTERN = /^./;

export function truncate(value: string, maxLength: number): string {
if (value.length <= maxLength) {
return value;
}
return `${value.slice(0, maxLength - 1)}…`;
}

export function isUserFacingMetadata(key: string): boolean {
return !(
key === "to" ||
key === "template" ||
key === "zScore" ||
key.endsWith("Id")
);
}

export function formatMetadataLabel(key: string): string {
return key
.replaceAll(/([a-z0-9])([A-Z])/g, "$1 $2")
.replaceAll(/[_-]+/g, " ")
.replace(FIRST_CHARACTER_PATTERN, (character) => character.toUpperCase());
}
Loading