feat(errors): platform-wide request ids + error codes + admin inspector

End-to-end error-handling overhaul. A user hitting any failure now sees
a plain-text message + stable error code + reference id. A super admin
can paste the id into /admin/errors/<id> for the full request shape,
sanitized body, error stack, and a heuristic likely-cause hint.

REQUEST CONTEXT (AsyncLocalStorage)
- src/lib/request-context.ts mints a per-request frame carrying
  requestId + portId + userId + method + path + start timestamp.
- withAuth wraps every authenticated handler in runWithRequestContext
  and accepts an upstream X-Request-Id header (validated shape) or
  generates a fresh UUID. The id ALWAYS leaves on the X-Request-Id
  response header, including early-return 401/403/4xx paths.
- Pino logger reads from the same context via mixin — every log
  line emitted during the request automatically carries the ids
  with no per-call threading.

ERROR CODE REGISTRY
- src/lib/error-codes.ts defines stable DOMAIN_REASON codes with
  HTTP status + plain-text user-facing message (no jargon, written
  for the rep on the phone with a customer).
- New CodedError class wraps a registered code + optional
  internalMessage (admin-only — never sent to client).
- Existing AppError subclasses got plain-text default rewrites so
  legacy throw sites improve immediately without migration.
- High-impact services migrated to specific codes:
  expenses (RECEIPT_REQUIRED, INVOICE_LINKED), interest-berths
  (CROSS_PORT_LINK_REJECTED), berth-pdf (PDF_MAGIC_BYTE / PDF_EMPTY /
  PDF_TOO_LARGE / VERSION_ALREADY_CURRENT), recommender
  (INTEREST_PORT_MISMATCH).

ERROR ENVELOPE
- errorResponse always sets X-Request-Id header + requestId field.
- 5xx responses include a "Quote error ID …" friendly line.
- 4xx kept clean (validation, permission, not-found don't pollute
  the inspector — they're already in audit log).

PERSISTENCE (error_events table, migration 0040)
- One row per 5xx, keyed on requestId, with method/path/status/error
  name+message/stack head (4KB cap)/sanitized body excerpt (1KB cap;
  password/token/secret/etc keys redacted)/duration/IP/UA/metadata.
- captureErrorEvent extracts Postgres SQLSTATE/severity/cause.code
  so the classifier can recognize FK / unique / NOT NULL / schema-
  drift violations.
- Failure to persist is logged-not-thrown.

LIKELY-CULPRIT CLASSIFIER (src/lib/error-classifier.ts)
- 4-pass heuristic (first match wins):
  1. Postgres SQLSTATE → human reason (23503 FK, 23505 unique,
     42703 schema drift, 53300 connection limit, …)
  2. Error class name (AbortError, TimeoutError, FetchError,
     ZodError)
  3. Stack-path patterns (/lib/storage/, /lib/email/, documenso,
     openai|claude, /queue/workers/)
  4. Free-text message keywords (econnrefused, rate limit, timeout,
     unauthorized|invalid api key)
- Returns { label, hint, subsystem } for the inspector badge.

CLIENT SIDE
- apiFetch throws structured ApiError with message + code + requestId
  + details + retryAfter.
- toastError() helper renders the standard 3-line toast:
  plain message / Error code: X / Reference ID: Y [Copy ID].

ADMIN INSPECTOR
- /<port>/admin/errors lists captured 5xx with status badge + path +
  likely-culprit badge + truncated message + reference id. Filter by
  status code; auto-refresh via TanStack Query.
- /<port>/admin/errors/<requestId> deep-dive: request shape, full
  error name+message+stack, sanitized body excerpt, raw metadata,
  registered-code lookup (so admin can compare to what user saw),
  likely-culprit hint with subsystem tag.
- /<port>/admin/errors/codes is the in-app code reference page —
  every registered code grouped by domain prefix, searchable, with
  HTTP status + user message inline. Linked from inspector header
  so admins can flip to it while triaging.
- Permission: admin.view_audit_log. Super admins see all ports;
  regular admins port-scoped.
- system-monitoring dashboard now surfaces error_events alongside
  permission_denied audit + queue failed jobs (RecentError gains
  source: 'request' variant).

DOCS
- docs/error-handling.md walks through coded errors, plain-text
  message guidelines, client toasting, admin inspector usage,
  persistence rules, classifier internals, pruning, and the
  legacy → CodedError migration path.

MIGRATION SAFETY
- Audit confirmed all 41 migrations (0000-0040) apply cleanly in
  journal order against an empty DB. 0040 references ports(id)
  which exists from 0000. 0035/0038 don't deadlock under sequential
  psql -f. Removed redundant idx_ds_sent_by from 0038 (created in
  0037).

Tests: 1168/1168 vitest passing. tsc clean.
- security-error-responses tests updated for plain-text messages
  + new optional response keys (code/requestId/message).
- berth-pdf-versions tests assert stable error codes via
  toMatchObject({ code }) rather than message regex.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-05-05 14:12:59 +02:00
parent c4a41d5f5b
commit 4723994bdc
26 changed files with 2027 additions and 169 deletions

View File

@@ -0,0 +1,246 @@
'use client';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { ArrowLeft, Copy, Wrench } from 'lucide-react';
import { toast } from 'sonner';
import type { Route } from 'next';
import { Badge } from '@/components/ui/badge';
import { ERROR_CODES, isErrorCode } from '@/lib/error-codes';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { apiFetch } from '@/lib/api/client';
import type { ErrorEvent } from '@/lib/db/schema/system';
import type { LikelyCulprit } from '@/lib/error-classifier';
interface DetailResponse {
data: ErrorEvent & { likelyCulprit: LikelyCulprit | null };
}
/**
* Detail view for a single captured error. Shows everything an admin
* needs to triage:
*
* - Request shape: method, path, status, duration, who fired it
* - Error: name, message, full stack head, (sanitized) request body
* - Likely-culprit hint: heuristic-driven plain-English root-cause
* - Raw metadata: pg SQLSTATE codes, internal-message debug strings
*/
export default function ErrorEventDetailPage() {
const params = useParams<{ portSlug: string; requestId: string }>();
const portSlug = params?.portSlug ?? '';
const requestId = params?.requestId ?? '';
const query = useQuery<DetailResponse>({
queryKey: ['admin', 'error-events', requestId],
queryFn: () => apiFetch<DetailResponse>(`/api/v1/admin/error-events/${requestId}`),
enabled: Boolean(requestId),
});
function copy(text: string, label: string) {
if (typeof navigator === 'undefined' || !navigator.clipboard) return;
void navigator.clipboard.writeText(text);
toast.success(`${label} copied`);
}
if (query.isLoading) {
return (
<div className="space-y-3">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-32 w-full" />
<Skeleton className="h-64 w-full" />
</div>
);
}
const event = query.data?.data;
if (!event) {
return (
<Card>
<CardContent className="py-12 text-center text-sm text-muted-foreground">
Error event not found. It may have been pruned or you may not have access.
</CardContent>
</Card>
);
}
return (
<div className="space-y-4">
<div>
<Button variant="ghost" size="sm" asChild>
<Link href={`/${portSlug}/admin/errors` as Route}>
<ArrowLeft className="mr-1.5 h-4 w-4" />
Back to error list
</Link>
</Button>
</div>
<div className="flex items-center gap-2 flex-wrap">
<h1 className="text-2xl font-bold">Error {requestId.slice(0, 8)}</h1>
<Badge
variant="outline"
className={
event.statusCode >= 500
? 'border-destructive/40 text-destructive'
: 'border-amber-300 text-amber-800'
}
>
{event.statusCode}
</Badge>
{event.likelyCulprit && (
<Badge variant="secondary" className="gap-1">
<Wrench className="h-3 w-3" />
{event.likelyCulprit.label}
</Badge>
)}
<Button size="sm" variant="ghost" onClick={() => copy(requestId, 'Reference ID')}>
<Copy className="mr-1.5 h-3 w-3" />
Copy ID
</Button>
</div>
{event.likelyCulprit && (
<Card>
<CardHeader>
<CardTitle className="text-sm font-medium flex items-center gap-2">
<Wrench className="h-4 w-4" /> Likely culprit
</CardTitle>
</CardHeader>
<CardContent className="text-sm">
<p className="font-medium">{event.likelyCulprit.label}</p>
<p className="text-muted-foreground mt-1">{event.likelyCulprit.hint}</p>
<p className="text-xs text-muted-foreground mt-2">
Subsystem: <code className="font-mono">{event.likelyCulprit.subsystem}</code>
</p>
</CardContent>
</Card>
)}
{/* If the captured error has a registered code on its metadata,
* surface the canonical user-facing message + status from the
* registry so the admin can compare what the user saw to what
* the system actually did. */}
{(() => {
const meta = (event.metadata ?? {}) as Record<string, unknown>;
const code = typeof meta.code === 'string' ? meta.code : null;
if (!code || !isErrorCode(code)) return null;
const def = ERROR_CODES[code];
return (
<Card>
<CardHeader>
<CardTitle className="text-sm font-medium">Error code</CardTitle>
</CardHeader>
<CardContent className="space-y-1 text-sm">
<div className="flex items-center gap-2">
<Badge variant="outline">{def.status}</Badge>
<code className="font-mono text-xs font-semibold">{code}</code>
</div>
<p className="mt-2">{def.userMessage}</p>
<p className="text-xs text-muted-foreground">
Compare to the message the user saw in their toast.{' '}
<Link
href={`/${portSlug}/admin/errors/codes` as Route}
className="text-primary hover:underline"
>
All codes
</Link>
</p>
</CardContent>
</Card>
);
})()}
<Card>
<CardHeader>
<CardTitle className="text-sm font-medium">Request</CardTitle>
</CardHeader>
<CardContent className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
<KV label="Method" value={event.method} />
<KV label="Path" value={event.path} mono />
<KV label="When" value={format(new Date(event.createdAt), 'PPpp')} />
<KV label="Duration" value={event.durationMs ? `${event.durationMs} ms` : '—'} />
<KV label="Port" value={event.portId ?? '(none)'} mono />
<KV label="User" value={event.userId ?? '(none)'} mono />
<KV label="IP" value={event.ipAddress ?? '—'} mono />
<KV label="User agent" value={event.userAgent ?? '—'} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-sm font-medium">Error</CardTitle>
</CardHeader>
<CardContent className="space-y-3 text-sm">
<KV label="Name" value={event.errorName ?? '—'} mono />
<div>
<p className="text-xs text-muted-foreground">Message</p>
<p className="mt-0.5 font-mono whitespace-pre-wrap break-words">
{event.errorMessage ?? '—'}
</p>
</div>
{event.errorStack && (
<div>
<div className="flex items-center justify-between">
<p className="text-xs text-muted-foreground">Stack (truncated)</p>
<Button
size="sm"
variant="ghost"
onClick={() => copy(event.errorStack ?? '', 'Stack')}
>
<Copy className="mr-1.5 h-3 w-3" /> Copy
</Button>
</div>
<pre className="mt-1 max-h-96 overflow-auto rounded bg-muted p-2 text-xs font-mono whitespace-pre-wrap break-words">
{event.errorStack}
</pre>
</div>
)}
</CardContent>
</Card>
{event.requestBodyExcerpt && (
<Card>
<CardHeader>
<CardTitle className="text-sm font-medium">
Request body (sanitized, max 1 KB)
</CardTitle>
</CardHeader>
<CardContent>
<pre className="max-h-64 overflow-auto rounded bg-muted p-2 text-xs font-mono whitespace-pre-wrap break-words">
{event.requestBodyExcerpt}
</pre>
</CardContent>
</Card>
)}
{event.metadata !== null &&
typeof event.metadata === 'object' &&
Object.keys(event.metadata as Record<string, unknown>).length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-sm font-medium">Metadata</CardTitle>
</CardHeader>
<CardContent>
<pre className="overflow-auto rounded bg-muted p-2 text-xs font-mono">
{JSON.stringify(event.metadata, null, 2)}
</pre>
</CardContent>
</Card>
)}
</div>
);
}
function KV({ label, value, mono }: { label: string; value: string | null; mono?: boolean }) {
return (
<div>
<p className="text-xs text-muted-foreground">{label}</p>
<p className={`mt-0.5 ${mono ? 'font-mono text-xs' : ''}`}>{value ?? '—'}</p>
</div>
);
}

View File

@@ -0,0 +1,134 @@
'use client';
import { useState, useMemo } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { ArrowLeft, BookOpen, Search } from 'lucide-react';
import type { Route } from 'next';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { ERROR_CODES } from '@/lib/error-codes';
/**
* Error-code reference page surfaced inside the admin section so an
* admin investigating a captured error_events row can flip to this
* tab, look up the code the user reported, and read the canonical
* plain-language meaning + status code without leaving the app.
*
* Pulls directly from `src/lib/error-codes.ts` so it stays in sync
* automatically — adding an entry to the registry adds a row here.
*/
export default function ErrorCodeReferencePage() {
const params = useParams<{ portSlug: string }>();
const portSlug = params?.portSlug ?? '';
const [search, setSearch] = useState('');
const entries = useMemo(() => {
const all = Object.entries(ERROR_CODES) as Array<
[string, (typeof ERROR_CODES)[keyof typeof ERROR_CODES]]
>;
if (!search.trim()) return all;
const q = search.trim().toLowerCase();
return all.filter(
([code, def]) => code.toLowerCase().includes(q) || def.userMessage.toLowerCase().includes(q),
);
}, [search]);
// Group by domain prefix (the part before the first underscore) so
// the table reads naturally — Expenses, Berths, Storage, etc.
const grouped = useMemo(() => {
const groups = new Map<string, typeof entries>();
for (const entry of entries) {
const prefix = entry[0].split('_')[0] ?? 'OTHER';
const bucket = groups.get(prefix) ?? [];
bucket.push(entry);
groups.set(prefix, bucket);
}
return [...groups.entries()].sort(([a], [b]) => a.localeCompare(b));
}, [entries]);
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
<Button variant="ghost" size="sm" asChild>
<Link href={`/${portSlug}/admin/errors` as Route}>
<ArrowLeft className="mr-1.5 h-4 w-4" />
Back to error inspector
</Link>
</Button>
</div>
<div className="flex items-start justify-between gap-4 flex-wrap">
<div>
<h1 className="text-2xl font-bold flex items-center gap-2">
<BookOpen className="h-5 w-5" /> Error code reference
</h1>
<p className="text-muted-foreground text-sm mt-1">
Every error code the platform can return, with its HTTP status and the plain-language
message a user sees. Codes are stable identifiers once shipped, they never get
renamed.
</p>
</div>
</div>
<div className="relative max-w-md">
<Search className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search code or message…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-8"
/>
</div>
{grouped.length === 0 ? (
<Card>
<CardContent className="py-12 text-center text-sm text-muted-foreground">
No codes match &quot;{search}&quot;.
</CardContent>
</Card>
) : (
<div className="space-y-4">
{grouped.map(([prefix, items]) => (
<Card key={prefix}>
<CardHeader>
<CardTitle className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
{prefix}
</CardTitle>
</CardHeader>
<CardContent className="divide-y">
{items.map(([code, def]) => (
<div key={code} className="flex items-start gap-3 py-3 first:pt-0 last:pb-0">
<Badge
variant="outline"
className={
def.status >= 500
? 'border-destructive/40 text-destructive'
: def.status >= 400
? 'border-amber-300 text-amber-800'
: 'border-muted'
}
>
{def.status}
</Badge>
<div className="flex-1 min-w-0">
<p className="font-mono text-xs font-semibold">{code}</p>
<p className="text-sm mt-0.5">{def.userMessage}</p>
{'hint' in def && typeof def.hint === 'string' && (
<p className="text-xs text-muted-foreground mt-0.5">{def.hint}</p>
)}
</div>
</div>
))}
</CardContent>
</Card>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,157 @@
'use client';
import { useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { format, formatDistanceToNow } from 'date-fns';
import { AlertTriangle, BookOpen, Search, Wrench } from 'lucide-react';
import type { Route } from 'next';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { PageHeader } from '@/components/shared/page-header';
import { EmptyState } from '@/components/shared/empty-state';
import { apiFetch } from '@/lib/api/client';
import { classifyError } from '@/lib/error-classifier';
import type { ErrorEvent } from '@/lib/db/schema/system';
interface ListResponse {
data: ErrorEvent[];
}
/**
* Super-admin error inspector.
*
* Shows the most recent captured 5xx errors with: when, where (HTTP
* method + path), what (error name + message), and a heuristic
* "likely culprit" badge driven by `classifyError`. Click into any
* row for the full stack + body excerpt + raw metadata.
*/
export default function AdminErrorsPage() {
const params = useParams<{ portSlug: string }>();
const portSlug = params?.portSlug ?? '';
const [statusFilter, setStatusFilter] = useState('');
const query = useQuery<ListResponse>({
queryKey: ['admin', 'error-events', { statusFilter }],
queryFn: () => {
const search = new URLSearchParams();
if (statusFilter) search.set('statusCode', statusFilter);
return apiFetch<ListResponse>(
`/api/v1/admin/error-events${search.toString() ? `?${search.toString()}` : ''}`,
);
},
});
const events = query.data?.data ?? [];
return (
<div className="space-y-4">
<PageHeader
title="Error inspector"
description="Captured 5xx errors. Click any row for the full stack, request body excerpt, and likely culprit."
actions={
<Button variant="outline" size="sm" asChild>
<Link href={`/${portSlug}/admin/errors/codes` as Route}>
<BookOpen className="mr-1.5 h-4 w-4" />
Code reference
</Link>
</Button>
}
/>
<Card>
<CardHeader>
<CardTitle className="text-sm font-medium flex items-center gap-2">
<Search className="h-4 w-4" /> Filters
</CardTitle>
</CardHeader>
<CardContent className="flex flex-wrap items-end gap-3">
<div className="space-y-1">
<label className="text-xs text-muted-foreground" htmlFor="status">
Status code
</label>
<Input
id="status"
placeholder="e.g. 500"
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value.replace(/\D/g, ''))}
className="h-8 w-32"
/>
</div>
{statusFilter && (
<Button variant="ghost" size="sm" className="h-8" onClick={() => setStatusFilter('')}>
Clear
</Button>
)}
</CardContent>
</Card>
{query.isLoading ? (
<div className="space-y-2">
{Array.from({ length: 5 }).map((_, i) => (
<Skeleton key={i} className="h-14 w-full" />
))}
</div>
) : events.length === 0 ? (
<EmptyState
icon={AlertTriangle}
title="No captured errors"
description="Nothing has hit a 5xx in the selected window. That's a good thing."
/>
) : (
<div className="rounded-lg border divide-y">
{events.map((event) => {
const culprit = classifyError(event);
return (
<Link
key={event.requestId}
href={`/${portSlug}/admin/errors/${event.requestId}` as Route}
className="flex items-start gap-3 p-3 hover:bg-muted/40"
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<Badge
variant="outline"
className={
event.statusCode >= 500
? 'border-destructive/40 text-destructive'
: 'border-amber-300 text-amber-800'
}
>
{event.statusCode}
</Badge>
<span className="text-xs font-mono uppercase text-muted-foreground">
{event.method}
</span>
<span className="text-sm font-medium truncate">{event.path}</span>
{culprit && (
<Badge variant="secondary" className="gap-1 text-xs">
<Wrench className="h-3 w-3" />
{culprit.label}
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground truncate mt-0.5">
{event.errorName ? `${event.errorName}: ` : ''}
{event.errorMessage ?? '(no message)'}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{formatDistanceToNow(new Date(event.createdAt), { addSuffix: true })} ·{' '}
{format(new Date(event.createdAt), 'MMM d HH:mm:ss')} · ID{' '}
<code className="font-mono">{event.requestId.slice(0, 12)}</code>
</p>
</div>
</Link>
);
})}
</div>
)}
</div>
);
}