-
Notifications
You must be signed in to change notification settings - Fork 211
feat(notifications): add Discord provider #637
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
FindMalek
wants to merge
2
commits into
databuddy-analytics:staging
Choose a base branch
from
FindMalek:feat/notifications-discord-provider
base: staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
160 changes: 160 additions & 0 deletions
160
packages/notifications/src/__tests__/providers/discord.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }), | ||
| }; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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()); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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!