Files
CapaKraken/packages/api/src/middleware/logging.ts
T
Hartmut fbeab5cd79 feat: Sprint 5 — AI insights, webhooks/Slack, PWA, performance monitoring
AI-Powered Insights (G9):
- Rule-based anomaly detection: budget burn rate, staffing gaps, utilization,
  timeline overruns across all active projects
- AI narrative generation via existing Azure OpenAI integration
- Cached in project dynamicFields to avoid regeneration
- New /analytics/insights page with anomaly feed + project summaries
- Sidebar nav: "AI Insights" under Analytics

Webhook System + Slack (G10):
- Webhook model in Prisma (url, secret, events, isActive)
- HMAC-SHA256 signed payloads with 5s timeout fire-and-forget dispatch
- Slack-aware: routes hooks.slack.com URLs through Slack formatter
- 6 events integrated: allocation.created/updated/deleted, project.created/
  status_changed, vacation.approved
- Admin UI: /admin/webhooks with CRUD, test button, event checkboxes
- webhook router: list, getById, create, update, delete, test

PWA Support (G11):
- manifest.json with standalone display, brand-colored icons (192+512px)
- Service worker: cache-first for static, network-first for API, offline fallback
- ServiceWorkerRegistration component with 60-min update checks
- InstallPrompt banner with 30-day dismissal memory
- Apple Web App meta tags + viewport theme color

Performance Monitoring (A15):
- Pino structured logging (JSON prod, pretty dev) via LOG_LEVEL env
- tRPC logging middleware on all protectedProcedure calls
- Request ID (UUID) per call for log correlation
- Slow query warnings (>500ms) at warn level
- GET /api/perf endpoint: memory, uptime, SSE connections, node version

Fix: renamed scenario.apply to scenario.applyScenario (tRPC reserved word)

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-03-20 06:57:20 +01:00

65 lines
1.7 KiB
TypeScript

import { TRPCError } from "@trpc/server";
import { logger } from "../lib/logger.js";
const SLOW_THRESHOLD_MS = 500;
/**
* Core logging logic for tRPC procedure calls.
*
* Designed to be wrapped with `t.middleware()` in trpc.ts.
* Generates a requestId (UUID) per call and attaches it to the context.
*
* Log levels:
* - debug: normal requests
* - warn: slow requests (>500ms)
* - error: failed requests
*/
export async function loggingMiddleware(opts: {
ctx: { dbUser?: { id: string } | null; requestId?: string };
type: "query" | "mutation" | "subscription";
path: string;
next: (opts: { ctx: Record<string, unknown> }) => Promise<{ ok: boolean }>;
}) {
const { ctx, type, path, next } = opts;
const requestId = crypto.randomUUID();
const userId = ctx.dbUser?.id ?? "anonymous";
const start = performance.now();
const logBase = {
requestId,
type,
path,
userId,
};
try {
const result = await next({
ctx: { ...ctx, requestId },
});
const durationMs = Math.round(performance.now() - start);
const logData = { ...logBase, durationMs, status: "ok" as const };
if (durationMs > SLOW_THRESHOLD_MS) {
logger.warn(logData, "Slow tRPC call");
} else {
logger.debug(logData, "tRPC call");
}
return result;
} catch (error) {
const durationMs = Math.round(performance.now() - start);
const errorCode =
error instanceof TRPCError ? error.code : "INTERNAL_SERVER_ERROR";
const errorMessage =
error instanceof Error ? error.message : "Unknown error";
logger.error(
{ ...logBase, durationMs, status: "error" as const, errorCode, errorMessage },
"tRPC call failed",
);
throw error;
}
}