feat(notifications): persist Discord outbox
This commit is contained in:
@@ -0,0 +1,195 @@
|
||||
import fs from "node:fs";
|
||||
import fsp from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { NotificationEvent, NotificationOutbox } from "../src/main/notification-outbox";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function createOutboxFile(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mdd-notification-outbox-"));
|
||||
tempDirs.push(dir);
|
||||
return path.join(dir, "notification-outbox.json");
|
||||
}
|
||||
|
||||
function event(id: string, overrides: Partial<NotificationEvent> = {}): NotificationEvent {
|
||||
return {
|
||||
id,
|
||||
type: "package_failed",
|
||||
priority: "error",
|
||||
createdAt: 1000,
|
||||
expiresAt: 86401000,
|
||||
attempts: 0,
|
||||
nextAttemptAt: 1000,
|
||||
payload: {
|
||||
title: "Paket fehlgeschlagen",
|
||||
description: "Eine Datei ist fehlgeschlagen.",
|
||||
fields: []
|
||||
},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
function persisted(filePath: string): { events: NotificationEvent[]; lastSuccessAt: number; lastFailureAt: number } {
|
||||
return JSON.parse(fs.readFileSync(filePath, "utf8")) as { events: NotificationEvent[]; lastSuccessAt: number; lastFailureAt: number };
|
||||
}
|
||||
|
||||
describe("NotificationOutbox", () => {
|
||||
it("sends due events serially in stable enqueue order and removes each success", async () => {
|
||||
const filePath = createOutboxFile();
|
||||
const sent: string[] = [];
|
||||
const outbox = new NotificationOutbox({
|
||||
filePath,
|
||||
now: () => 1000,
|
||||
send: async (queuedEvent) => {
|
||||
sent.push(queuedEvent.id);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
await outbox.enqueue(event("first"));
|
||||
await outbox.enqueue(event("second", { createdAt: 900 }));
|
||||
await outbox.enqueue(event("third"));
|
||||
await outbox.drain(1000);
|
||||
|
||||
expect(sent).toEqual(["first", "second", "third"]);
|
||||
expect(outbox.getStatus()).toEqual({ queued: 0, lastSuccessAt: 1000, lastFailureAt: 0 });
|
||||
expect(persisted(filePath).events).toEqual([]);
|
||||
});
|
||||
|
||||
it("backs off a failed event without allowing later events to overtake it", async () => {
|
||||
const filePath = createOutboxFile();
|
||||
const outcomes = [false, true, true];
|
||||
const sent: string[] = [];
|
||||
const outbox = new NotificationOutbox({
|
||||
filePath,
|
||||
now: () => 1000,
|
||||
send: async (queuedEvent) => {
|
||||
sent.push(queuedEvent.id);
|
||||
return outcomes.shift() ?? true;
|
||||
}
|
||||
});
|
||||
|
||||
await outbox.enqueue(event("first"));
|
||||
await outbox.enqueue(event("second"));
|
||||
await outbox.drain(1000);
|
||||
expect(sent).toEqual(["first"]);
|
||||
expect(persisted(filePath).events[0]).toMatchObject({ id: "first", attempts: 1, nextAttemptAt: 2000 });
|
||||
expect(outbox.getStatus()).toEqual({ queued: 2, lastSuccessAt: 0, lastFailureAt: 1000 });
|
||||
|
||||
await outbox.drain(1999);
|
||||
expect(sent).toEqual(["first"]);
|
||||
await outbox.drain(2000);
|
||||
expect(sent).toEqual(["first", "first", "second"]);
|
||||
});
|
||||
|
||||
it("automatically drains new events and retries them at the persisted deadline", async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(1000);
|
||||
const filePath = createOutboxFile();
|
||||
const outcomes = [false, true];
|
||||
const send = vi.fn().mockImplementation(async () => outcomes.shift() ?? true);
|
||||
const outbox = new NotificationOutbox({ filePath, send, autoDrain: true });
|
||||
|
||||
await outbox.enqueue(event("automatic"));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await outbox.drain(1000);
|
||||
expect(send).toHaveBeenCalledTimes(1);
|
||||
expect(outbox.getStatus().queued).toBe(1);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(999);
|
||||
expect(send).toHaveBeenCalledTimes(1);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(send).toHaveBeenCalledTimes(2);
|
||||
expect(outbox.getStatus().queued).toBe(0);
|
||||
});
|
||||
|
||||
it("persists through a temporary file and atomic rename", async () => {
|
||||
const filePath = createOutboxFile();
|
||||
const rename = vi.spyOn(fsp, "rename");
|
||||
try {
|
||||
const outbox = new NotificationOutbox({ filePath, send: async () => true, now: () => 1000 });
|
||||
await outbox.enqueue(event("atomic"));
|
||||
expect(rename).toHaveBeenCalledWith(`${filePath}.tmp`, filePath);
|
||||
expect(fs.existsSync(`${filePath}.tmp`)).toBe(false);
|
||||
expect(persisted(filePath).events.map((queuedEvent) => queuedEvent.id)).toEqual(["atomic"]);
|
||||
} finally {
|
||||
rename.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("drops expired events before persisting or sending", async () => {
|
||||
const filePath = createOutboxFile();
|
||||
const send = vi.fn().mockResolvedValue(true);
|
||||
const outbox = new NotificationOutbox({ filePath, send, now: () => 2000 });
|
||||
|
||||
await outbox.enqueue(event("expired", { expiresAt: 1999 }));
|
||||
await outbox.drain(2000);
|
||||
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
expect(outbox.getStatus().queued).toBe(0);
|
||||
expect(persisted(filePath).events).toEqual([]);
|
||||
});
|
||||
|
||||
it("caps the queue at 250 and evicts the oldest success before errors", async () => {
|
||||
const filePath = createOutboxFile();
|
||||
const outbox = new NotificationOutbox({ filePath, send: async () => true, now: () => 1000 });
|
||||
for (let index = 0; index < 249; index += 1) {
|
||||
await outbox.enqueue(event(`error-${index}`, { createdAt: 1000 + index }));
|
||||
}
|
||||
await outbox.enqueue(event("success-old", { type: "package_completed", priority: "success", createdAt: 500 }));
|
||||
await outbox.enqueue(event("success-new", { type: "package_completed", priority: "success", createdAt: 2000 }));
|
||||
|
||||
const ids = persisted(filePath).events.map((queuedEvent) => queuedEvent.id);
|
||||
expect(ids).toHaveLength(250);
|
||||
expect(ids).not.toContain("success-old");
|
||||
expect(ids).toContain("success-new");
|
||||
expect(ids.filter((id) => id.startsWith("error-"))).toHaveLength(249);
|
||||
});
|
||||
|
||||
it("never persists webhook or mention fields supplied outside the event contract", async () => {
|
||||
const filePath = createOutboxFile();
|
||||
const outbox = new NotificationOutbox({ filePath, send: async () => true, now: () => 1000 });
|
||||
const unsafe = {
|
||||
...event("safe"),
|
||||
url: "https://discord.example.test/private-webhook",
|
||||
mention: "@private",
|
||||
payload: {
|
||||
...event("safe").payload,
|
||||
url: "https://discord.example.test/nested-private-webhook",
|
||||
mention: "@nested-private"
|
||||
}
|
||||
} as unknown as NotificationEvent;
|
||||
|
||||
await outbox.enqueue(unsafe);
|
||||
|
||||
const raw = fs.readFileSync(filePath, "utf8");
|
||||
expect(raw).not.toContain("private-webhook");
|
||||
expect(raw).not.toContain("@private");
|
||||
expect(persisted(filePath).events[0]).toEqual(event("safe"));
|
||||
});
|
||||
|
||||
it("returns after the default three-second shutdown budget when sending hangs", async () => {
|
||||
vi.useFakeTimers();
|
||||
const filePath = createOutboxFile();
|
||||
const outbox = new NotificationOutbox({ filePath, send: async () => new Promise<boolean>(() => {}), now: () => 1000 });
|
||||
await outbox.enqueue(event("hanging"));
|
||||
|
||||
let completed = false;
|
||||
const draining = outbox.drainForShutdown().then(() => { completed = true; });
|
||||
await vi.advanceTimersByTimeAsync(2999);
|
||||
expect(completed).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await draining;
|
||||
expect(completed).toBe(true);
|
||||
expect(outbox.getStatus().queued).toBe(1);
|
||||
});
|
||||
});
|
||||
+70
-30
@@ -52,26 +52,66 @@ describe("truncateContent", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildNotifyRequest", () => {
|
||||
it("builds a Discord-compatible JSON webhook POST (bold title + message as content)", () => {
|
||||
const req = buildNotifyRequest(` ${WEBHOOK} `, { title: "✅ Paket fertig", message: "Show.S01\n5 Datei(en)" });
|
||||
expect(req.url).toBe(WEBHOOK);
|
||||
expect(req.init.method).toBe("POST");
|
||||
expect(req.init.headers).toMatchObject({ "Content-Type": "application/json" });
|
||||
const body = JSON.parse(String(req.init.body));
|
||||
expect(body.content).toBe("**✅ Paket fertig**\nShow.S01\n5 Datei(en)");
|
||||
expect(body.username).toBe("Real-Debrid Downloader");
|
||||
});
|
||||
it("prepends the mention so Discord pings (bare ID gets wrapped)", () => {
|
||||
const req = buildNotifyRequest(WEBHOOK, { title: "T", message: "M", mention: "123456789012345678" });
|
||||
const body = JSON.parse(String(req.init.body));
|
||||
expect(body.content).toBe("<@123456789012345678> **T**\nM");
|
||||
});
|
||||
it("sends no mention prefix when the field is empty", () => {
|
||||
const req = buildNotifyRequest(WEBHOOK, { title: "T", message: "M", mention: "" });
|
||||
const body = JSON.parse(String(req.init.body));
|
||||
expect(body.content).toBe("**T**\nM");
|
||||
});
|
||||
describe("buildNotifyRequest", () => {
|
||||
it("builds a bounded Discord embed with the product username", () => {
|
||||
const req = buildNotifyRequest(` ${WEBHOOK} `, {
|
||||
title: "Paket fehlgeschlagen",
|
||||
message: "Eine Datei konnte nicht verarbeitet werden.",
|
||||
color: 0xe74c3c,
|
||||
fields: [
|
||||
{ name: "Ergebnis", value: "Fehlgeschlagen", inline: true },
|
||||
{ name: "Dateien", value: "0 erfolgreich, 1 fehlgeschlagen", inline: true }
|
||||
],
|
||||
timestamp: 1000
|
||||
});
|
||||
expect(req.url).toBe(WEBHOOK);
|
||||
expect(req.init.method).toBe("POST");
|
||||
expect(req.init.headers).toMatchObject({ "Content-Type": "application/json" });
|
||||
const body = JSON.parse(String(req.init.body));
|
||||
expect(body).toEqual({
|
||||
username: "Multi-Debrid Downloader",
|
||||
content: "",
|
||||
embeds: [{
|
||||
title: "Paket fehlgeschlagen",
|
||||
description: "Eine Datei konnte nicht verarbeitet werden.",
|
||||
color: 0xe74c3c,
|
||||
fields: [
|
||||
{ name: "Ergebnis", value: "Fehlgeschlagen", inline: true },
|
||||
{ name: "Dateien", value: "0 erfolgreich, 1 fehlgeschlagen", inline: true }
|
||||
],
|
||||
timestamp: "1970-01-01T00:00:01.000Z"
|
||||
}]
|
||||
});
|
||||
});
|
||||
it("prepends the mention so Discord pings (bare ID gets wrapped)", () => {
|
||||
const req = buildNotifyRequest(WEBHOOK, { title: "T", message: "M", mention: "123456789012345678" });
|
||||
const body = JSON.parse(String(req.init.body));
|
||||
expect(body.content).toBe("<@123456789012345678>");
|
||||
expect(body.embeds[0]).toMatchObject({ title: "T", description: "M" });
|
||||
});
|
||||
it("sends no mention prefix when the field is empty", () => {
|
||||
const req = buildNotifyRequest(WEBHOOK, { title: "T", message: "M", mention: "" });
|
||||
const body = JSON.parse(String(req.init.body));
|
||||
expect(body.content).toBe("");
|
||||
});
|
||||
it("enforces Discord title, description, field, and total embed limits", () => {
|
||||
const req = buildNotifyRequest(WEBHOOK, {
|
||||
title: "T".repeat(400),
|
||||
message: "M".repeat(5000),
|
||||
fields: Array.from({ length: 30 }, (_, index) => ({
|
||||
name: `${index}-${"N".repeat(300)}`,
|
||||
value: "V".repeat(1400)
|
||||
}))
|
||||
});
|
||||
const body = JSON.parse(String(req.init.body));
|
||||
const embed = body.embeds[0] as { title: string; description: string; fields: Array<{ name: string; value: string }> };
|
||||
expect(embed.title.length).toBeLessThanOrEqual(256);
|
||||
expect(embed.description.length).toBeLessThanOrEqual(4096);
|
||||
expect(embed.fields.length).toBeLessThanOrEqual(25);
|
||||
expect(embed.fields.every((field) => field.name.length <= 256 && field.value.length <= 1024)).toBe(true);
|
||||
const total = embed.title.length + embed.description.length + embed.fields.reduce((sum, field) => sum + field.name.length + field.value.length, 0);
|
||||
expect(total).toBeLessThanOrEqual(6000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendNotification", () => {
|
||||
@@ -104,20 +144,20 @@ describe("sendNotification", () => {
|
||||
await expect(sendNotification(WEBHOOK, { title: "T", message: "M" }, fetchFn, noSleep)).resolves.toBe(false);
|
||||
expect(fetchFn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("serializes concurrent sends in order (burst protection)", async () => {
|
||||
const order: string[] = [];
|
||||
const fetchFn = vi.fn().mockImplementation(async (_url: string, init: RequestInit) => {
|
||||
order.push(JSON.parse(String(init.body)).content);
|
||||
return new Response(null, { status: 204 });
|
||||
});
|
||||
it("serializes concurrent sends in order (burst protection)", async () => {
|
||||
const order: string[] = [];
|
||||
const fetchFn = vi.fn().mockImplementation(async (_url: string, init: RequestInit) => {
|
||||
order.push(JSON.parse(String(init.body)).embeds[0].title);
|
||||
return new Response(null, { status: 204 });
|
||||
});
|
||||
const sends = [
|
||||
sendNotification(WEBHOOK, { title: "1", message: "" }, fetchFn, noSleep),
|
||||
sendNotification(WEBHOOK, { title: "2", message: "" }, fetchFn, noSleep),
|
||||
sendNotification(WEBHOOK, { title: "3", message: "" }, fetchFn, noSleep)
|
||||
];
|
||||
await expect(Promise.all(sends)).resolves.toEqual([true, true, true]);
|
||||
expect(order).toEqual(["**1**\n", "**2**\n", "**3**\n"]);
|
||||
});
|
||||
];
|
||||
await expect(Promise.all(sends)).resolves.toEqual([true, true, true]);
|
||||
expect(order).toEqual(["1", "2", "3"]);
|
||||
});
|
||||
it("does not call fetch for an invalid URL", async () => {
|
||||
const fetchFn = vi.fn();
|
||||
await expect(sendNotification("", { title: "T", message: "M" }, fetchFn, noSleep)).resolves.toBe(false);
|
||||
|
||||
Binary file not shown.
Reference in New Issue
Block a user