feat(observability): delivery metrics, admin metrics/delivery endpoints, admin API route wiring

This commit is contained in:
RhenCloud 2026-08-15 17:03:02 +08:00
parent 2470bd786d
commit 1e9ba3c5dd
No known key found for this signature in database
GPG key ID: A574A617378C4E0B
17 changed files with 682 additions and 7 deletions

View file

@ -130,3 +130,32 @@ export async function getSendLogById(db: D1Database, id: number): Promise<SendRe
return null;
}
}
export async function getSendLogByDelivery(
db: D1Database,
deliveryId: string,
): Promise<SendRecord[]> {
try {
const { results } = await db
.prepare(`SELECT ${COLUMNS} FROM send_logs WHERE delivery_id = ? ORDER BY ts DESC`)
.bind(deliveryId)
.all<LogRow>();
return results.map(toRecord);
} catch (err) {
log.warn({ err, deliveryId }, "Failed to load send log by delivery");
return [];
}
}
export async function getFailedSendLog(db: D1Database, limit = 20): Promise<SendRecord[]> {
try {
const { results } = await db
.prepare(`SELECT ${COLUMNS} FROM send_logs WHERE ok = 0 ORDER BY ts DESC LIMIT ?`)
.bind(limit)
.all<LogRow>();
return results.map(toRecord);
} catch (err) {
log.warn({ err }, "Failed to load failed send log");
return [];
}
}

View file

@ -0,0 +1,122 @@
import { log } from "../lib/log";
import { getFailedSendLog, type SendRecord } from "../lib/send-log";
export interface DeliveryMetrics {
total: number;
ok: number;
failed: number;
failureRate: number;
byPlatform: { platform: string; total: number; ok: number; failed: number }[];
byEvent: { event: string; total: number; ok: number; failed: number }[];
byStatus: { status: string; count: number }[];
avgDurationMs: number;
totalAttempts: number;
avgAttempts: number;
recentFailures: SendRecord[];
}
interface TotalsRow {
total: number;
ok: number;
}
interface BreakdownRow {
key: string | null;
total: number;
ok: number;
}
interface StatusRow {
status: number;
count: number;
}
interface AvgRow {
avg: number | null;
}
interface AttemptsRow {
total: number;
avg: number | null;
}
const EMPTY: DeliveryMetrics = {
total: 0,
ok: 0,
failed: 0,
failureRate: 0,
byPlatform: [],
byEvent: [],
byStatus: [],
avgDurationMs: 0,
totalAttempts: 0,
avgAttempts: 0,
recentFailures: [],
};
export async function getDeliveryMetrics(db: D1Database): Promise<DeliveryMetrics> {
try {
const totals = await db
.prepare(`SELECT COUNT(*) AS total, COALESCE(SUM(ok), 0) AS ok FROM send_logs`)
.all<TotalsRow>();
const total = Number(totals.results[0]?.total) || 0;
const ok = Number(totals.results[0]?.ok) || 0;
const byPlatform = await db
.prepare(
`SELECT platform AS key, COUNT(*) AS total, COALESCE(SUM(ok), 0) AS ok
FROM send_logs GROUP BY platform`,
)
.all<BreakdownRow>();
const byEvent = await db
.prepare(
`SELECT event AS key, COUNT(*) AS total, COALESCE(SUM(ok), 0) AS ok
FROM send_logs GROUP BY event`,
)
.all<BreakdownRow>();
const byStatus = await db
.prepare(
`SELECT status, COUNT(*) AS count FROM send_logs
WHERE status IS NOT NULL GROUP BY status`,
)
.all<StatusRow>();
const duration = await db
.prepare(`SELECT AVG(duration_ms) AS avg FROM send_logs WHERE duration_ms IS NOT NULL`)
.all<AvgRow>();
const attempts = await db
.prepare(
`SELECT COALESCE(SUM(attempts), 0) AS total, AVG(attempts) AS avg
FROM send_logs WHERE attempts IS NOT NULL`,
)
.all<AttemptsRow>();
const recentFailures = await getFailedSendLog(db, 20);
return {
total,
ok,
failed: total - ok,
failureRate: total > 0 ? (total - ok) / total : 0,
byPlatform: byPlatform.results.map((r) => {
const t = Number(r.total) || 0;
const o = Number(r.ok) || 0;
return { platform: r.key ?? "unknown", total: t, ok: o, failed: t - o };
}),
byEvent: byEvent.results.map((r) => {
const t = Number(r.total) || 0;
const o = Number(r.ok) || 0;
return { event: r.key ?? "unknown", total: t, ok: o, failed: t - o };
}),
byStatus: byStatus.results.map((r) => ({
status: String(r.status),
count: Number(r.count) || 0,
})),
avgDurationMs: Number(duration.results[0]?.avg) || 0,
totalAttempts: Number(attempts.results[0]?.total) || 0,
avgAttempts: Number(attempts.results[0]?.avg) || 0,
recentFailures,
};
} catch (err) {
log.warn({ err }, "Failed to compute delivery metrics");
return EMPTY;
}
}

View file

@ -20,7 +20,8 @@ import {
clientIp,
type GroupAccess,
} from "./auth";
import { getSendLog, getSendLogById } from "../lib/send-log";
import { getSendLog, getSendLogById, getSendLogByDelivery } from "../lib/send-log";
import { getDeliveryMetrics } from "../observability/metrics";
import { getAuditLog, recordAudit } from "../lib/audit";
import {
createInvite,
@ -1012,3 +1013,37 @@ export async function adminAudit(event: H3Event): Promise<Record<string, unknown
: entries.filter((e) => e.groupId != null && auth.scope.groupIds.has(e.groupId));
return { audit: visible };
}
/** GET /admin/api/metrics */
export async function adminApiMetrics(event: H3Event): Promise<Record<string, unknown>> {
const auth = await requireAnyAccess(event);
const env = cfEnv(event);
const metrics = await getDeliveryMetrics(env.DB);
if (auth.scope.isSuper) return { metrics };
return {
metrics: {
...metrics,
recentFailures: metrics.recentFailures.filter(
(f) => f.groupId != null && auth.scope.groupIds.has(f.groupId),
),
},
};
}
/** GET /admin/api/delivery/:deliveryId */
export async function adminApiDelivery(
event: H3Event,
deliveryId: string,
): Promise<Record<string, unknown>> {
const auth = await requireAnyAccess(event);
const env = cfEnv(event);
const rows = await getSendLogByDelivery(env.DB, deliveryId);
if (rows.length === 0) return respondError(event, 404, "Delivery not found");
if (
!auth.scope.isSuper &&
rows.some((r) => r.groupId == null || !auth.scope.groupIds.has(r.groupId))
) {
return respondError(event, 403, "Forbidden");
}
return { deliveryId, attempts: rows };
}

View file

@ -0,0 +1,76 @@
import { defineEventHandler, getMethod, getRouterParam, setResponseStatus } from "h3";
import {
adminApiMe,
adminApiGroupsGet,
adminApiGroupsPut,
adminApiRoutesGet,
adminApiRoutesPut,
adminApiLogs,
adminApiLogsById,
adminGroupRoutesGet,
adminGroupRoutesPut,
adminGroupInvitesPost,
adminGroupInvitesGet,
adminInviteDelete,
adminGroupRename,
adminGroupWebhookGet,
adminGroupWebhookRegenerate,
adminGroupWebhookDelete,
adminAudit,
adminApiMetrics,
adminApiDelivery,
} from "../../../lib/web/admin";
export default defineEventHandler((event) => {
const method = getMethod(event);
const seg = (getRouterParam(event, "slug") ?? "").split("/").filter(Boolean);
if (seg[0] === "me" && method === "GET") return adminApiMe(event);
if (seg[0] === "groups" && seg.length === 1) {
if (method === "GET") return adminApiGroupsGet(event);
if (method === "PUT") return adminApiGroupsPut(event);
}
if (seg[0] === "routes" && seg.length === 1) {
if (method === "GET") return adminApiRoutesGet(event);
if (method === "PUT") return adminApiRoutesPut(event);
}
if (seg[0] === "logs" && seg.length === 1 && method === "GET") return adminApiLogs(event);
if (seg[0] === "logs" && seg.length === 2 && method === "GET")
return adminApiLogsById(event, Number(seg[1]));
if (seg[0] === "groups" && seg[2] === "routes" && seg.length === 3) {
if (method === "GET") return adminGroupRoutesGet(event, seg[1]);
if (method === "PUT") return adminGroupRoutesPut(event, seg[1]);
}
if (seg[0] === "groups" && seg[2] === "invites" && seg.length === 3) {
if (method === "GET") return adminGroupInvitesGet(event, seg[1]);
if (method === "POST") return adminGroupInvitesPost(event, seg[1]);
}
if (seg[0] === "invites" && seg.length === 2 && method === "DELETE")
return adminInviteDelete(event, seg[1]);
if (
seg[0] === "groups" &&
seg[2] === "rename" &&
seg.length === 3 &&
(method === "POST" || method === "PUT")
)
return adminGroupRename(event, seg[1]);
if (
seg[0] === "groups" &&
seg[2] === "webhook" &&
seg[3] === "regenerate" &&
seg.length === 4 &&
method === "POST"
)
return adminGroupWebhookRegenerate(event, seg[1]);
if (seg[0] === "groups" && seg[2] === "webhook" && seg.length === 3) {
if (method === "GET") return adminGroupWebhookGet(event, seg[1]);
if (method === "DELETE") return adminGroupWebhookDelete(event, seg[1]);
}
if (seg[0] === "audit" && seg.length === 1 && method === "GET") return adminAudit(event);
if (seg[0] === "metrics" && seg.length === 1 && method === "GET") return adminApiMetrics(event);
if (seg[0] === "delivery" && seg.length === 2 && method === "GET")
return adminApiDelivery(event, seg[1]);
setResponseStatus(event, 404);
return { error: "Not found" };
});