Add a notification history
Every notification is written down with how it went through each channel (or why it was not sent: held for quiet hours, a routing rule said nobody, no channel on). Records -> Notifications lists them with a filter, a search and Send again. Errors are cleaned of every secret in the settings; kept 30 days. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5c6ccc0a4b
commit
9126200295
18 files changed
+9886
-34
No files matched your search
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* What was sent: every notification is written down with how it went through each channel, so "why did I not get it?" has an answer — it went through ntfy and Gotify said 401, it was held
|
||||
* for quiet hours, a routing rule said nobody should hear it, or no channel was switched on to send it to. Kept 30 days and at most 1000 entries. Nothing here can make sending fail: writing
|
||||
* it down is best-effort, like the channels themselves. An error's text is cleaned of every token, key and password in the settings before it is kept, since a channel may say them back.
|
||||
*/
|
||||
import { and, desc, eq, like, lt, notInArray, or } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { notificationLog } from "../db/schema.js";
|
||||
import { getSettings } from "./settingsStore.js";
|
||||
|
||||
export const KEEP_DAYS = 30;
|
||||
export const KEEP_ROWS = 1000;
|
||||
export const MAX_MESSAGE = 4000;
|
||||
export const MAX_ERROR = 300;
|
||||
export const STATUSES = ["sent", "partly", "failed", "none", "held", "muted"] as const;
|
||||
export type LogStatus = (typeof STATUSES)[number];
|
||||
|
||||
export interface ChannelResult {
|
||||
/** gotify, ntfy, telegram, pushover, smtp, webhook, webPush, or email (an escalation to one address). */
|
||||
channel: string;
|
||||
ok: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export type LogRow = typeof notificationLog.$inferSelect;
|
||||
|
||||
const clip = (text: string, max: number) => (text.length <= max ? text : `${text.slice(0, max - 1)}…`);
|
||||
|
||||
/** Pure: how a notification went, from how each channel did. Nothing switched on to send it to is "none". */
|
||||
export function statusOf(results: ChannelResult[]): LogStatus {
|
||||
if (results.length === 0) return "none";
|
||||
const ok = results.filter((r) => r.ok).length;
|
||||
return ok === results.length ? "sent" : ok === 0 ? "failed" : "partly";
|
||||
}
|
||||
|
||||
/** Pure: text with each of these values (at least six characters, so a stray short word is not swallowed) replaced by dots. */
|
||||
export function scrub(text: string, secrets: (string | null | undefined)[]): string {
|
||||
let out = text;
|
||||
for (const s of [...new Set(secrets.filter((x): x is string => typeof x === "string" && x.length >= 6))].sort((a, b) => b.length - a.length)) {
|
||||
out = out.split(s).join("•••");
|
||||
// A token inside an address is also written percent-encoded.
|
||||
const encoded = encodeURIComponent(s);
|
||||
if (encoded !== s) out = out.split(encoded).join("•••");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function secretsNow(): Promise<string[]> {
|
||||
const s = await getSettings();
|
||||
return [s.gotify.token, s.ntfy.token, s.telegram.token, s.pushover.appToken, s.pushover.userKey, s.smtp.password, s.webhook.secret, s.webhook.url, s.telegram.chatId].filter((x): x is string => typeof x === "string");
|
||||
}
|
||||
|
||||
let sinceTrim = 0;
|
||||
|
||||
/** Keeps the log to KEEP_DAYS and KEEP_ROWS: old entries first, and only now and then the count. */
|
||||
async function trim(now: Date): Promise<void> {
|
||||
await db.delete(notificationLog).where(lt(notificationLog.at, new Date(now.getTime() - KEEP_DAYS * 86_400_000).toISOString()));
|
||||
if (++sinceTrim < 50) return;
|
||||
sinceTrim = 0;
|
||||
const keep = await db.select({ id: notificationLog.id }).from(notificationLog).orderBy(desc(notificationLog.at), desc(notificationLog.id)).limit(KEEP_ROWS);
|
||||
if (keep.length === KEEP_ROWS) await db.delete(notificationLog).where(notInArray(notificationLog.id, keep.map((k) => k.id)));
|
||||
}
|
||||
|
||||
/** Writes down one notification: what it said, and how it went (or why it was held or muted). Returns its id, or null when it could not be written — never throws. */
|
||||
export async function recordNotification(entry: { title: string; message: string; results: ChannelResult[]; status?: LogStatus; note?: string | null; resentOf?: number | null }, now: Date = new Date()): Promise<number | null> {
|
||||
try {
|
||||
const secrets = await secretsNow();
|
||||
const results = entry.results.map((r) => ({ channel: r.channel, ok: r.ok, error: r.error === null ? null : clip(scrub(r.error.replace(/\s+/g, " ").trim(), secrets), MAX_ERROR) }));
|
||||
const [row] = await db
|
||||
.insert(notificationLog)
|
||||
.values({ at: now.toISOString(), title: clip(entry.title, 300), message: clip(entry.message, MAX_MESSAGE), status: entry.status ?? statusOf(results), results: JSON.stringify(results), note: entry.note ?? null, resentOf: entry.resentOf ?? null })
|
||||
.returning({ id: notificationLog.id });
|
||||
await trim(now);
|
||||
return row.id;
|
||||
} catch (err) {
|
||||
console.error("[notificationLog] couldn't write it down:", err instanceof Error ? err.message : err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function resultsOf(row: Pick<LogRow, "results">): ChannelResult[] {
|
||||
try {
|
||||
const v = JSON.parse(row.results);
|
||||
return Array.isArray(v) ? (v as ChannelResult[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getLogged(id: number): Promise<LogRow | null> {
|
||||
return (await db.select().from(notificationLog).where(eq(notificationLog.id, id)).limit(1))[0] ?? null;
|
||||
}
|
||||
|
||||
/** The newest first, optionally of one status, or with a word in the title or message. */
|
||||
export async function listLogged(options: { status?: LogStatus; q?: string; limit?: number } = {}): Promise<(Omit<LogRow, "results"> & { results: ChannelResult[] })[]> {
|
||||
const q = options.q?.trim();
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(notificationLog)
|
||||
.where(and(options.status ? eq(notificationLog.status, options.status) : undefined, q ? or(like(notificationLog.title, `%${q.replace(/[%_]/g, "")}%`), like(notificationLog.message, `%${q.replace(/[%_]/g, "")}%`)) : undefined))
|
||||
.orderBy(desc(notificationLog.at), desc(notificationLog.id))
|
||||
.limit(Math.min(500, Math.max(1, Math.round(options.limit ?? 200))));
|
||||
return rows.map((r) => ({ ...r, results: resultsOf(r) }));
|
||||
}
|
||||
Reference in new issue
Block a user