diff --git a/.env.example b/.env.example index ce7d06d..cd0c087 100644 --- a/.env.example +++ b/.env.example @@ -48,3 +48,12 @@ LEADERBOARD_SEED_LIMIT=256 LEADERBOARD_REFRESH_LIMIT=500 LEADERBOARD_USER_STALE_DAYS=30 DISABLE_CALCULATE_LEADERBOARD_ENDPOINT=false + +# ── Observability & Persistent Logging ────────────────────────────────────── +# Persist categorized server errors & cron runs in PostgreSQL `system_logs` +OBSERVABILITY_DB_ENABLED=true +# Secret token for GET/PATCH /api/internal/observability (leave blank to disable endpoint) +OBSERVABILITY_ADMIN_TOKEN= +# Retention windows (days) pruned automatically at the end of each cron run +SYSTEM_LOGS_ERROR_RETENTION_DAYS=60 +SYSTEM_LOGS_CRON_RETENTION_DAYS=90 diff --git a/.gitignore b/.gitignore index c3dfb51..24cf74d 100644 --- a/.gitignore +++ b/.gitignore @@ -139,4 +139,7 @@ next-env.d.ts # Vite logs files vite.config.js.timestamp-* vite.config.ts.timestamp-* -server/ \ No newline at end of file +server/ + +# Local internal observability endpoint +src/app/api/internal/observability/route.ts \ No newline at end of file diff --git a/ops/docker/leaderboard-compose.yml b/ops/docker/leaderboard-compose.yml index 975845d..e4aa661 100644 --- a/ops/docker/leaderboard-compose.yml +++ b/ops/docker/leaderboard-compose.yml @@ -10,5 +10,11 @@ services: - path: ${ENV_FILE:-.env} required: true environment: + LOG_SERVICE: leaderboard-cron LEADERBOARD_CRON_SCHEDULE: ${LEADERBOARD_CRON_SCHEDULE:-0 0 * * *} LEADERBOARD_SOURCE_URL_TEMPLATE: ${LEADERBOARD_SOURCE_URL_TEMPLATE:-https://raw.githubusercontent.com/ashkulz/committers.top/gh-pages/_data/locations/{country}.yml} + logging: + driver: json-file + options: + max-size: "10m" + max-file: "5" diff --git a/scripts/calculate-next-country.ts b/scripts/calculate-next-country.ts index 79125da..0eb19c9 100644 --- a/scripts/calculate-next-country.ts +++ b/scripts/calculate-next-country.ts @@ -19,9 +19,39 @@ // Load .env file for standalone execution. This must be the first import. import "dotenv/config"; -import { getDatabaseStore } from "@/lib/db"; +import { getDatabaseStore, type DatabaseStore, type UpsertSystemLogParams } from "@/lib/db"; import { calculateLeaderboard } from "@/features/leaderboard/services"; import { logger } from "@/lib/logger"; +import { createRunId, flushLogSinks, reportServerError } from "@/lib/observability"; +import { getPositiveEnvInt } from "@/utils/stale"; + +const MAX_PERSISTED_CRON_ERRORS = 100; + +async function persistCronRunSafely( + db: DatabaseStore, + params: UpsertSystemLogParams, +): Promise { + try { + await db.upsertSystemLog(params); + } catch (err: unknown) { + logger.warn("Failed to persist cron run to system_logs", { + runId: params.runId, + error: err instanceof Error ? err.message : String(err), + }); + } +} + +function getTopErrorCode(errorSummary: Record): string | null { + let topCode: string | null = null; + let topCount = 0; + for (const [code, count] of Object.entries(errorSummary)) { + if (count > topCount) { + topCode = code; + topCount = count; + } + } + return topCode; +} let activeCountrySlug: string | null = null; @@ -36,9 +66,10 @@ process.on("SIGINT", () => handleShutdownSignal("SIGINT")); async function main() { const overallStartTime = performance.now(); + const runId = createRunId("cron"); const workerVersion = process.env.DEVIMPACT_VERSION || process.env.GIT_COMMIT_SHA || "development"; - logger.info("=== DevImpact Leaderboard Calculator Start ==="); + logger.info("=== DevImpact Leaderboard Calculator Start ===", { runId, workerVersion }); logger.info(`Version: ${workerVersion}`); logger.info(`DB: ${(process.env.DATABASE_URL ?? "").slice(0, 40)}...`); @@ -54,55 +85,191 @@ async function main() { } if (!next) { - logger.info("No countries to calculate. All are up-to-date or running."); + logger.info("No countries to calculate. All are up-to-date or running.", { runId }); process.exit(0); } activeCountrySlug = next.slug; + const cronFingerprint = `cron:${runId}`; + const cronRouteOrJob = `cron:${next.slug}`; + + logger.info(`Selected and claimed: ${next.title} (${next.slug})`, { + runId, + country: next.slug, + }); - logger.info(`Selected and claimed: ${next.title} (${next.slug})`); + await persistCronRunSafely(db, { + fingerprint: cronFingerprint, + kind: "cron_run", + source: "cron", + level: "info", + status: "running", + routeOrJob: cronRouteOrJob, + runId, + message: `Started leaderboard calculation for ${next.title} (${next.slug})`, + details: { + runId, + countrySlug: next.slug, + countryTitle: next.title, + workerVersion, + }, + }); try { // 3. Run the calculation (same function used by the API endpoint) - logger.info("Starting leaderboard calculation..."); + logger.info("Starting leaderboard calculation...", { runId, country: next.slug }); const result = await calculateLeaderboard(next.slug); // 4. Mark as done const errorCount = result._meta.errors; - const errorMessage = errorCount > 0 ? `${errorCount} users failed` : undefined; + const errorSummary = result._meta.errorSummary ?? {}; + const summaryText = Object.entries(errorSummary) + .map(([code, count]) => `${code}:${count}`) + .join(", "); + const errorMessage = + errorCount > 0 + ? summaryText + ? `${errorCount} users failed (${summaryText})` + : `${errorCount} users failed` + : undefined; await db.finishCalculation(next.slug, errorMessage); - logger.info(`Finished calculation for '${next.slug}'.`); + logger.info(`Finished calculation for '${next.slug}'.`, { runId, country: next.slug }); // 5. Log detailed summary const overallDuration = (performance.now() - overallStartTime) / 1000; + const overallDurationMs = Math.round(overallDuration * 1000); const totalFetchTime = result._meta.totalFetchTime ?? 0; const successfulFetches = result._meta.successfulFetches ?? 0; const averageFetchTime = successfulFetches > 0 ? (totalFetchTime / successfulFetches / 1000).toFixed(2) : "N/A"; + const allCategorizedErrors = result._meta.categorizedErrors ?? []; + const cappedCategorizedErrors = allCategorizedErrors.slice(0, MAX_PERSISTED_CRON_ERRORS); + const truncatedErrorsCount = Math.max( + 0, + allCategorizedErrors.length - cappedCategorizedErrors.length, + ); + const cronStatus = errorCount > 0 ? "completed_with_errors" : "completed"; + const summaryLine = + errorCount > 0 + ? `Completed ${next.title}: ${result._meta.newUsers} new, ${result._meta.refreshedUsers} refreshed, ${errorCount} errors (${summaryText || "see details"})` + : `Completed ${next.title}: ${result._meta.newUsers} new, ${result._meta.refreshedUsers} refreshed, 0 errors`; + + await persistCronRunSafely(db, { + fingerprint: cronFingerprint, + kind: "cron_run", + source: "cron", + level: errorCount > 0 ? "warn" : "info", + status: cronStatus, + routeOrJob: cronRouteOrJob, + errorCode: errorCount > 0 ? getTopErrorCode(errorSummary) : null, + runId, + durationMs: overallDurationMs, + message: summaryLine, + details: { + runId, + countrySlug: next.slug, + countryTitle: next.title, + workerVersion, + newUsers: result._meta.newUsers, + skippedExisting: result._meta.skippedExisting, + refreshedUsers: result._meta.refreshedUsers, + totalInDb: result._meta.totalInDb, + errorCount, + errorSummary, + failedUsernames: (result._meta.failedUsernames ?? []).slice(0, MAX_PERSISTED_CRON_ERRORS), + totalFetchTimeMs: Math.round(totalFetchTime), + averageFetchTimeMs: + successfulFetches > 0 ? Math.round(totalFetchTime / successfulFetches) : null, + categorizedErrors: cappedCategorizedErrors, + ...(truncatedErrorsCount > 0 ? { truncatedErrorsCount } : {}), + }, + }); + + try { + const pruned = await db.pruneSystemLogs({ + errorRetentionDays: getPositiveEnvInt("SYSTEM_LOGS_ERROR_RETENTION_DAYS", 60), + cronRetentionDays: getPositiveEnvInt("SYSTEM_LOGS_CRON_RETENTION_DAYS", 90), + }); + if (pruned.deletedErrors > 0 || pruned.deletedCronRuns > 0) { + logger.info("Pruned expired system_logs rows", { runId, ...pruned }); + } + } catch (pruneErr: unknown) { + logger.warn("Failed to prune expired system_logs rows", { + runId, + error: pruneErr instanceof Error ? pruneErr.message : String(pruneErr), + }); + } + logger.info("=== Calculation Summary ===", { + runId, country: next.title, + countrySlug: next.slug, + workerVersion, newUsers: result._meta.newUsers, skippedExisting: result._meta.skippedExisting, refreshedUsers: result._meta.refreshedUsers, totalInDb: result._meta.totalInDb, errors: errorCount, + errorSummary, failedUsernames: result._meta.failedUsernames, totalFetchTime: `${(totalFetchTime / 1000).toFixed(2)}s`, averageFetchTime: `${averageFetchTime}s`, overallDuration: `${overallDuration.toFixed(2)}s`, }); - if (result._meta.userFetchErrors && result._meta.userFetchErrors.length > 0) { - logger.warn("Detailed user fetch errors:", { errors: result._meta.userFetchErrors }); + if (result._meta.categorizedErrors && result._meta.categorizedErrors.length > 0) { + logger.warn("Detailed categorized user fetch errors:", { + runId, + countrySlug: next.slug, + errors: result._meta.categorizedErrors, + }); + } else if (result._meta.userFetchErrors && result._meta.userFetchErrors.length > 0) { + logger.warn("Detailed user fetch errors:", { + runId, + countrySlug: next.slug, + errors: result._meta.userFetchErrors, + }); } + await flushLogSinks(); process.exit(0); } catch (err) { - const message = err instanceof Error ? err.message : String(err); - logger.error(`FATAL: ${message}`); - await db.finishCalculation(next.slug, message); + const overallDuration = (performance.now() - overallStartTime) / 1000; + const categorized = reportServerError(err, { + source: "cron", + routeOrJob: cronRouteOrJob, + runId, + target: { country: next.slug }, + context: { workerVersion }, + }); + + await persistCronRunSafely(db, { + fingerprint: cronFingerprint, + kind: "cron_run", + source: "cron", + level: "error", + status: "failed", + routeOrJob: cronRouteOrJob, + errorCode: categorized.code, + stage: categorized.stage, + runId, + durationMs: Math.round(overallDuration * 1000), + message: categorized.message, + details: { + runId, + countrySlug: next.slug, + countryTitle: next.title, + workerVersion, + ...(categorized.rateLimit ? { rateLimit: categorized.rateLimit } : {}), + ...(categorized.pgCode ? { pgCode: categorized.pgCode } : {}), + ...(categorized.stack ? { stack: categorized.stack.slice(0, 4000) } : {}), + }, + }); + + await db.finishCalculation(next.slug, `${categorized.code}: ${categorized.message}`); + await flushLogSinks(); process.exit(1); } } diff --git a/scripts/init-db.ts b/scripts/init-db.ts index f2d64ca..d16bf99 100644 --- a/scripts/init-db.ts +++ b/scripts/init-db.ts @@ -29,7 +29,7 @@ async function main() { // Create schema await store.initializeSchema(); - console.log(" ✓ Schema created (github_users table + indexes)"); + console.log(" ✓ Schema created (github_users, leaderboard_calculation, system_logs + indexes)"); // Seed calculation countries await store.seedCalculationCountries(); diff --git a/src/app/[locale]/user/[username]/page.tsx b/src/app/[locale]/user/[username]/page.tsx index f951773..2f1eed3 100644 --- a/src/app/[locale]/user/[username]/page.tsx +++ b/src/app/[locale]/user/[username]/page.tsx @@ -7,6 +7,7 @@ import { buildUserProfileSchema, buildUserBreadcrumbSchema, } from "@/features/developer/services"; +import { reportServerError } from "@/lib/observability"; import { toAbsoluteUrl } from "@/lib/seo"; const getCachedUserProfile = cache(async (username: string) => { @@ -99,6 +100,14 @@ export default async function UserProfilePage({ params, searchParams }: Props) { profileData = await getCachedUserProfile(cleanUsername); } catch (err: unknown) { fetchErrorMessage = err instanceof Error ? err.message : "Failed to load user profile"; + reportServerError(err, { + source: "ssr", + routeOrJob: "/[locale]/user/[username]", + target: { username: cleanUsername }, + context: { + ...(countryParam ? { countryParam } : {}), + }, + }); } if (!profileData || fetchErrorMessage) { diff --git a/src/app/api/compare/route.ts b/src/app/api/compare/route.ts index f7774e8..8a97480 100644 --- a/src/app/api/compare/route.ts +++ b/src/app/api/compare/route.ts @@ -6,24 +6,27 @@ import { resolveLocale, } from "@/features/comparison/services"; import { formatApiErrorResponse, parseSelectedLanguagesFromSearchParams } from "@/lib/api"; +import { createRequestId, reportServerError } from "@/lib/observability"; import { cleanGitHubUsername } from "@/utils"; export const runtime = "nodejs"; export async function GET(request: Request) { + const requestId = createRequestId(request); const { searchParams } = new URL(request.url); const usernames = searchParams.getAll("username").map(cleanGitHubUsername).filter(Boolean); if (usernames.length !== 2) { return NextResponse.json( { success: false, error: "provide exactly two username params" }, - { status: 400 }, + { status: 400, headers: { "X-Request-Id": requestId } }, ); } + const selectedLanguages = parseSelectedLanguagesFromSearchParams(searchParams); + try { const locale = resolveLocale(request); - const selectedLanguages = parseSelectedLanguagesFromSearchParams(searchParams); const users = await compareUsers(usernames, selectedLanguages); const winnerData = calculateWinner(users); const insights = createComparisonInsights(users, locale); @@ -36,7 +39,16 @@ export async function GET(request: Request) { }, ); } catch (error: unknown) { - console.error("GitHub score error:", error); - return formatApiErrorResponse(error); + reportServerError(error, { + source: "api", + stage: "compare", + routeOrJob: "/api/compare", + requestId, + target: { usernames }, + context: { + ...(selectedLanguages.length > 0 ? { selectedLanguages } : {}), + }, + }); + return formatApiErrorResponse(error, { requestId }); } } diff --git a/src/app/api/leaderboard/route.ts b/src/app/api/leaderboard/route.ts index d316219..6ca2283 100644 --- a/src/app/api/leaderboard/route.ts +++ b/src/app/api/leaderboard/route.ts @@ -1,21 +1,23 @@ import { NextResponse } from "next/server"; import { getLeaderboardResult } from "@/features/leaderboard/services"; +import { createRequestId, reportServerError } from "@/lib/observability"; export const runtime = "nodejs"; export async function GET(request: Request) { + const requestId = createRequestId(request); const { searchParams } = new URL(request.url); const country = searchParams.get("country")?.trim(); if (!country) { return NextResponse.json( { success: false, error: "Provide a country parameter" }, - { status: 400 }, + { status: 400, headers: { "X-Request-Id": requestId } }, ); } try { - const result = await getLeaderboardResult(country); + const result = await getLeaderboardResult(country, { requestId }); return NextResponse.json( { success: true, ...result }, { @@ -25,14 +27,23 @@ export async function GET(request: Request) { }, ); } catch (err) { - console.error("Leaderboard DB query failed:", err); - - return NextResponse.json({ - success: true, - title: country, - totalFromSource: 0, - scored: [], - errors: [], + reportServerError(err, { + source: "api", + stage: "db_query", + routeOrJob: "/api/leaderboard", + requestId, + target: { country }, }); + + return NextResponse.json( + { + success: true, + title: country, + totalFromSource: 0, + scored: [], + errors: [], + }, + { headers: { "X-Request-Id": requestId } }, + ); } } diff --git a/src/app/api/user/[username]/route.ts b/src/app/api/user/[username]/route.ts index ede761b..8ee9376 100644 --- a/src/app/api/user/[username]/route.ts +++ b/src/app/api/user/[username]/route.ts @@ -1,18 +1,20 @@ import { NextResponse } from "next/server"; import { getUserProfile } from "@/features/developer/services"; import { formatApiErrorResponse, parseSelectedLanguagesFromSearchParams } from "@/lib/api"; +import { createRequestId, reportServerError } from "@/lib/observability"; import { cleanGitHubUsername } from "@/utils"; export const runtime = "nodejs"; export async function GET(request: Request, { params }: { params: Promise<{ username: string }> }) { + const requestId = createRequestId(request); const { username } = await params; const trimmed = cleanGitHubUsername(username ?? ""); if (!trimmed) { return NextResponse.json( { success: false, error: "Username parameter is required" }, - { status: 400 }, + { status: 400, headers: { "X-Request-Id": requestId } }, ); } @@ -30,7 +32,15 @@ export async function GET(request: Request, { params }: { params: Promise<{ user }, ); } catch (error: unknown) { - console.error("User profile fetch error:", error); - return formatApiErrorResponse(error); + reportServerError(error, { + source: "api", + routeOrJob: "/api/user/[username]", + requestId, + target: { username: trimmed }, + context: { + ...(selectedLanguages.length > 0 ? { selectedLanguages } : {}), + }, + }); + return formatApiErrorResponse(error, { requestId }); } } diff --git a/src/features/developer/services/user-persistence.ts b/src/features/developer/services/user-persistence.ts index 9fbd7e1..d3cdf9f 100644 --- a/src/features/developer/services/user-persistence.ts +++ b/src/features/developer/services/user-persistence.ts @@ -1,6 +1,7 @@ import { calculateUserScore, type CalculateUserScoreResult } from "@/features/scoring"; import { getDatabaseStore } from "@/lib/db"; import { detectCountry } from "@/lib/geo"; +import { attachErrorStage, reportServerError } from "@/lib/observability"; import { getGitHubUserStaleDays } from "@/utils/stale"; import type { GitHubUserData } from "@/lib/github"; @@ -10,6 +11,7 @@ export type PersistUserOptions = { selectedLanguages?: string[]; explicitCountry?: string | null; staleDays?: number; + throwOnError?: boolean; }; /** @@ -25,6 +27,7 @@ export async function persistUserScores({ selectedLanguages = [], explicitCountry, staleDays, + throwOnError = false, }: PersistUserOptions): Promise { if (!process.env.DATABASE_URL?.trim()) { return; @@ -54,9 +57,18 @@ export async function persistUserScores({ staleDays: resolvedStaleDays, }); } catch (err: unknown) { - console.warn("Failed to persist user score:", { - username: data.login, - error: err, + const stagedError = attachErrorStage(err, "db_write"); + if (throwOnError) { + throw stagedError; + } + reportServerError(stagedError, { + source: "db", + stage: "db_write", + routeOrJob: "persistUserScores", + target: { + username: data.login, + ...(country ? { country } : {}), + }, }); } } diff --git a/src/features/developer/services/user-service.ts b/src/features/developer/services/user-service.ts index 67f94a7..a36b602 100644 --- a/src/features/developer/services/user-service.ts +++ b/src/features/developer/services/user-service.ts @@ -1,6 +1,7 @@ -import { getUserData } from "@/lib/github"; +import { getUserData, type UserFetchMetrics } from "@/lib/github"; import { calculateUserScore, type CalculateUserScoreResult } from "@/features/scoring"; import { scheduleBackground } from "@/lib/background"; +import { reportPartialFetchWarnings, reportServerError } from "@/lib/observability"; import { isUserDataFresh } from "@/utils/stale"; import { persistUserScores } from "./user-persistence"; import { getCachedProfile, setCachedProfile } from "./profile-cache"; @@ -34,8 +35,14 @@ export async function getUserProfile( if (cached) { return cached; } - } catch { + } catch (cacheError: unknown) { // Non-fatal: continue to DB / fresh calculation + reportServerError(cacheError, { + source: "cache", + stage: "cache_read", + routeOrJob: "getUserProfile", + target: { username: normalizedUsername }, + }); } // ── 2. Check PostgreSQL Pre-calculated Scores (Tier 2 for Canonical) ── @@ -83,23 +90,39 @@ export async function getUserProfile( return profile; } } - } catch { + } catch (dbError: unknown) { // Non-fatal: fall through to full calculation + reportServerError(dbError, { + source: "db", + stage: "db_read", + routeOrJob: "getUserProfile", + target: { username: normalizedUsername }, + }); } } // ── 3. Fallback: Fetch raw GitHub data & compute score ────────────── let data: GitHubUserData; + let fetchMetrics: UserFetchMetrics | undefined; try { - const { data: userData } = await getUserData(normalizedUsername, { + const { data: userData, metrics } = await getUserData(normalizedUsername, { cacheInRedis: true, withMetrics: true, }); data = userData; + fetchMetrics = metrics; } catch (error: unknown) { throw new UserFetchError(normalizedUsername, error); } + if (fetchMetrics?.errors?.length) { + reportPartialFetchWarnings(fetchMetrics.errors, { + source: "github", + routeOrJob: "getUserProfile", + target: { username: normalizedUsername }, + }); + } + const score = calculateUserScore( { ...data, diff --git a/src/features/leaderboard/services/calculate-leaderboard.ts b/src/features/leaderboard/services/calculate-leaderboard.ts index 05d76b4..1abde9c 100644 --- a/src/features/leaderboard/services/calculate-leaderboard.ts +++ b/src/features/leaderboard/services/calculate-leaderboard.ts @@ -4,11 +4,19 @@ import { calculateUserScore } from "@/features/scoring"; import { persistUserScores } from "@/features/developer/services"; import { createCacheStore, getCacheConfigFromEnv } from "@/lib/cache"; import { getDatabaseStore, type DatabaseStore } from "@/lib/db"; +import { + attachErrorStage, + classifyError, + classifyPartialFetchPart, + reportServerError, + summarizeCategorizedErrors, +} from "@/lib/observability"; import { getPositiveEnvInt, isUserDataFresh } from "@/utils/stale"; import { getDisplayLimit } from "./display-limit"; import { buildLeaderboardCacheKey, mapRowsToScoredLeaderboardEntries } from "./leaderboard-helpers"; import type { CalculateLeaderboardResponse, + CategorizedCronUserError, LeaderboardMeta, LeaderboardResult, ScoredLeaderboardEntry as ScoredEntry, @@ -84,16 +92,27 @@ export async function fetchCommittersFromTop( country: string, ): Promise<{ title: string; totalFromSource: number; users: LeaderboardSourceEntry[] }> { const url = getSourceUrl(country); - const res = await fetch(url, { - headers: { "User-Agent": "DevImpact-Bot" }, - }); + let res: Response; + try { + res = await fetch(url, { + headers: { "User-Agent": "DevImpact-Bot" }, + }); + } catch (err: unknown) { + throw attachErrorStage(err, "source_yaml"); + } if (!res.ok) { - throw new Error(`Leaderboard source returned ${res.status} for "${country}"`); + throw attachErrorStage( + new Error(`Leaderboard source returned ${res.status} for "${country}"`), + "source_yaml", + ); } const text = await res.text(); const data = yaml.load(text) as LeaderboardSourceYaml; if (!data?.users) { - throw new Error(`Invalid or empty leaderboard source data for "${country}"`); + throw attachErrorStage( + new Error(`Invalid or empty leaderboard source data for "${country}"`), + "source_yaml", + ); } return { title: data.title || country, @@ -102,6 +121,34 @@ export async function fetchCommittersFromTop( }; } +type FetchMetricsEntry = { + username?: string; + duration: number; + errors: { part: string; reason: string }[]; +}; + +function toCategorizedCronError( + error: unknown, + part: "seed" | "refresh", + username: string, +): CategorizedCronUserError { + const classified = classifyError(error, { + source: "cron", + routeOrJob: part === "seed" ? "seedNewUsers" : "refreshStaleUsers", + target: { username }, + }); + + return { + username, + part, + code: classified.code, + stage: classified.stage, + reason: classified.message, + ...(classified.pgCode ? { pgCode: classified.pgCode } : {}), + ...(classified.rateLimit ? { rateLimit: classified.rateLimit } : {}), + }; +} + export async function seedNewUsers( db: DatabaseStore, users: LeaderboardSourceEntry[], @@ -112,12 +159,14 @@ export async function seedNewUsers( newUsersCount: number; skippedExistingCount: number; errors: { username: string; reason: string }[]; - fetchMetrics: { duration: number; errors: { part: string; reason: string }[] }[]; + categorizedErrors: CategorizedCronUserError[]; + fetchMetrics: FetchMetricsEntry[]; }> { const errors: { username: string; reason: string }[] = []; + const categorizedErrors: CategorizedCronUserError[] = []; let newUsersCount = 0; let skippedExistingCount = 0; - const fetchMetrics: { duration: number; errors: { part: string; reason: string }[] }[] = []; + const fetchMetrics: FetchMetricsEntry[] = []; const usersToSeed = users.slice(0, seedLimit); const existingSet = await db.getExistingUsernames(usersToSeed.map((u) => u.login)); @@ -137,22 +186,25 @@ export async function seedNewUsers( cacheInRedis: false, withMetrics: true, }); - fetchMetrics.push(metrics); + fetchMetrics.push({ ...metrics, username: user.login }); const score = calculateUserScore(data, user.login); await persistUserScores({ data, score, staleDays, + throwOnError: true, }); newUsersCount += 1; } catch (e) { - errors.push({ username: user.login, reason: e instanceof Error ? e.message : String(e) }); + const categorized = toCategorizedCronError(e, "seed", user.login); + categorizedErrors.push(categorized); + errors.push({ username: user.login, reason: categorized.reason }); } }); - return { newUsersCount, skippedExistingCount, errors, fetchMetrics }; + return { newUsersCount, skippedExistingCount, errors, categorizedErrors, fetchMetrics }; } export async function refreshStaleUsers( @@ -164,11 +216,13 @@ export async function refreshStaleUsers( ): Promise<{ refreshedCount: number; errors: { username: string; reason: string }[]; - fetchMetrics: { duration: number; errors: { part: string; reason: string }[] }[]; + categorizedErrors: CategorizedCronUserError[]; + fetchMetrics: FetchMetricsEntry[]; }> { const errors: { username: string; reason: string }[] = []; + const categorizedErrors: CategorizedCronUserError[] = []; let refreshedCount = 0; - const fetchMetrics: { duration: number; errors: { part: string; reason: string }[] }[] = []; + const fetchMetrics: FetchMetricsEntry[] = []; const topUsers = await db.getTopUsers(country, refreshLimit); const now = Date.now(); @@ -184,22 +238,25 @@ export async function refreshStaleUsers( cacheInRedis: false, withMetrics: true, }); - fetchMetrics.push(metrics); + fetchMetrics.push({ ...metrics, username: row.username }); const score = calculateUserScore(data, row.username); await persistUserScores({ data, score, staleDays, + throwOnError: true, }); refreshedCount += 1; } catch (e) { - errors.push({ username: row.username, reason: e instanceof Error ? e.message : String(e) }); + const categorized = toCategorizedCronError(e, "refresh", row.username); + categorizedErrors.push(categorized); + errors.push({ username: row.username, reason: categorized.reason }); } }); - return { refreshedCount, errors, fetchMetrics }; + return { refreshedCount, errors, categorizedErrors, fetchMetrics }; } export async function buildLeaderboardResult( @@ -238,8 +295,13 @@ export async function invalidateLeaderboardCache(country: string): Promise const cacheKey = buildLeaderboardCacheKey(country, cacheConfig.namespace); await cacheStore.del(cacheKey); } - } catch { - console.warn("Failed to invalidate leaderboard cache"); + } catch (cacheError: unknown) { + reportServerError(cacheError, { + source: "cache", + stage: "cache_write", + routeOrJob: "invalidateLeaderboardCache", + target: { country }, + }); } } @@ -288,17 +350,42 @@ export async function calculateLeaderboard( meta.successfulFetches = allFetchMetrics.filter((m) => m.errors.length === 0).length; const userFetchErrors: LeaderboardMeta["userFetchErrors"] = []; - seedResult.errors.forEach((e) => - userFetchErrors.push({ username: e.username, errors: [{ part: "seed", reason: e.reason }] }), + const categorizedErrors: CategorizedCronUserError[] = [ + ...seedResult.categorizedErrors, + ...refreshResult.categorizedErrors, + ]; + + seedResult.categorizedErrors.forEach((e) => + userFetchErrors.push({ + username: e.username, + errors: [{ part: `${e.part}:${e.code}:${e.stage}`, reason: e.reason }], + }), ); - refreshResult.errors.forEach((e) => - userFetchErrors.push({ username: e.username, errors: [{ part: "refresh", reason: e.reason }] }), + refreshResult.categorizedErrors.forEach((e) => + userFetchErrors.push({ + username: e.username, + errors: [{ part: `${e.part}:${e.code}:${e.stage}`, reason: e.reason }], + }), ); - allFetchMetrics.forEach((m, i) => { - if (m.errors.length > 0) - userFetchErrors.push({ username: allErrors[i] ?? "unknown", errors: m.errors }); + allFetchMetrics.forEach((m) => { + if (m.errors.length > 0) { + const username = m.username ?? "unknown"; + userFetchErrors.push({ username, errors: m.errors }); + for (const partial of m.errors) { + const { code, stage } = classifyPartialFetchPart(partial.part); + categorizedErrors.push({ + username, + part: partial.part, + code, + stage, + reason: partial.reason, + }); + } + } }); meta.userFetchErrors = userFetchErrors; + meta.categorizedErrors = categorizedErrors; + meta.errorSummary = summarizeCategorizedErrors(categorizedErrors); // 4. Invalidate Redis cache await invalidateLeaderboardCache(country); diff --git a/src/features/leaderboard/services/leaderboard-service.ts b/src/features/leaderboard/services/leaderboard-service.ts index 786fc06..280dce3 100644 --- a/src/features/leaderboard/services/leaderboard-service.ts +++ b/src/features/leaderboard/services/leaderboard-service.ts @@ -1,5 +1,6 @@ import { createCacheStore, getCacheConfigFromEnv } from "@/lib/cache"; import { getDatabaseStore } from "@/lib/db"; +import { reportServerError } from "@/lib/observability"; import type { LeaderboardResult, ScoredLeaderboardEntry } from "../types"; import { getDisplayLimit, isWorldwideSlug } from "./display-limit"; import { buildLeaderboardCacheKey, mapRowsToScoredLeaderboardEntries } from "./leaderboard-helpers"; @@ -24,11 +25,15 @@ function getCachedLeaderboard( }; } -export async function getLeaderboardResult(country: string): Promise { +export async function getLeaderboardResult( + country: string, + options?: { requestId?: string }, +): Promise { const displayLimit = getDisplayLimit(country); const title = getLeaderboardTitle(country); const cacheConfig = getCacheConfigFromEnv(); const cacheStore = createCacheStore(cacheConfig); + const requestId = options?.requestId; if (cacheStore.enabled) { try { @@ -40,8 +45,14 @@ export async function getLeaderboardResult(country: string): Promise { username: "user1", reason: "Rate limit exceeded", }); + expect(result.categorizedErrors).toHaveLength(1); + expect(result.categorizedErrors[0]).toMatchObject({ + username: "user1", + part: "seed", + code: "RATE_LIMITED", + reason: "Rate limit exceeded", + }); }); }); diff --git a/src/features/leaderboard/types.ts b/src/features/leaderboard/types.ts index 603c1da..a6801e7 100644 --- a/src/features/leaderboard/types.ts +++ b/src/features/leaderboard/types.ts @@ -1,3 +1,5 @@ +import type { CategorizedErrorCode, CategorizedRateLimit, ErrorStage } from "@/lib/observability"; + export type CountryInfo = { slug: string; title: string; @@ -23,6 +25,16 @@ export type LeaderboardResult = { errors: string[]; }; +export type CategorizedCronUserError = { + username: string; + part: string; + code: CategorizedErrorCode; + stage: ErrorStage; + reason: string; + pgCode?: string; + rateLimit?: CategorizedRateLimit; +}; + export type LeaderboardMeta = { newUsers: number; refreshedUsers: number; @@ -33,6 +45,8 @@ export type LeaderboardMeta = { totalFetchTime?: number; successfulFetches?: number; userFetchErrors?: { username: string; errors: { part: string; reason: string }[] }[]; + categorizedErrors?: CategorizedCronUserError[]; + errorSummary?: Record; }; export type CalculateLeaderboardResponse = LeaderboardResult & { diff --git a/src/lib/api/api-helpers.ts b/src/lib/api/api-helpers.ts index 26ffa8c..34de0cb 100644 --- a/src/lib/api/api-helpers.ts +++ b/src/lib/api/api-helpers.ts @@ -22,11 +22,12 @@ export function toApiErrorStatus(code: ReturnType["code"] } } -export function toClientSafeError(error: SafeApiError): ClientSafeError { +export function toClientSafeError(error: SafeApiError, requestId?: string): ClientSafeError { return { code: error.code, message: error.message, targetUsernames: error.targetUsernames, + ...(requestId ? { requestId } : {}), }; } @@ -46,7 +47,10 @@ export function parseSelectedLanguagesFromSearchParams(searchParams: URLSearchPa * Translates UserFetchError and generic exceptions * into structured ClientSafeError responses with proper HTTP status codes. */ -export function formatApiErrorResponse(error: unknown): NextResponse { +export function formatApiErrorResponse( + error: unknown, + options?: { requestId?: string }, +): NextResponse { let safeError: SafeApiError; const isFetchError = @@ -79,7 +83,8 @@ export function formatApiErrorResponse(error: unknown): NextResponse { : toSafeApiError(error); } - const clientSafeError = toClientSafeError(safeError); + const requestId = options?.requestId; + const clientSafeError = toClientSafeError(safeError, requestId); return NextResponse.json( { @@ -87,6 +92,9 @@ export function formatApiErrorResponse(error: unknown): NextResponse { error: clientSafeError.message, errorDetails: clientSafeError, }, - { status: toApiErrorStatus(safeError.code) }, + { + status: toApiErrorStatus(safeError.code), + ...(requestId ? { headers: { "X-Request-Id": requestId } } : {}), + }, ); } diff --git a/src/lib/db/db-store.ts b/src/lib/db/db-store.ts index 5900e0b..569cf12 100644 --- a/src/lib/db/db-store.ts +++ b/src/lib/db/db-store.ts @@ -1,5 +1,6 @@ import { Pool, PoolConfig } from "pg"; import countries from "@/data/countries.json"; +import { reportServerError } from "@/lib/observability"; import { getGitHubUserStaleDays } from "@/utils/stale"; import type { GitHubUserData } from "@/lib/github"; import type { CalculateUserScoreResult } from "@/features/scoring"; @@ -56,6 +57,73 @@ export type TopStaleUserRow = Pick< "username" | "stale_after" | "updated_at" | "final_score" >; +export type SystemLogKind = "error" | "warn" | "cron_run"; +export type SystemLogLevel = "info" | "warn" | "error"; +export type SystemLogStatus = + | "open" + | "resolved" + | "running" + | "completed" + | "completed_with_errors" + | "failed" + | "interrupted"; + +export type UpsertSystemLogParams = { + fingerprint: string; + kind: SystemLogKind; + source: string; + level: SystemLogLevel; + status: SystemLogStatus; + routeOrJob: string; + errorCode?: string | null; + stage?: string | null; + message: string; + requestId?: string | null; + runId?: string | null; + durationMs?: number | null; + details?: Record; +}; + +export type SystemLogRow = { + id: number; + fingerprint: string; + kind: SystemLogKind; + source: string; + level: SystemLogLevel; + status: SystemLogStatus; + route_or_job: string; + error_code: string | null; + stage: string | null; + message: string; + request_id: string | null; + run_id: string | null; + occurrence_count: number; + duration_ms: number | null; + details: Record; + first_seen_at: Date; + last_seen_at: Date; +}; + +export type SystemLogQueryFilters = { + hours?: number; + limit?: number; + kind?: SystemLogKind; + source?: string; + errorCode?: string; + level?: SystemLogLevel; + status?: SystemLogStatus; +}; + +export type ObservabilitySummary = { + windowHours: number; + totalGroups: number; + totalOccurrences: number; + byCode: Record; + bySource: Record; + byLevel: Record; + lastCronRun: SystemLogRow | null; +}; + export type UpsertUserParams = { username: string; name: string | null; @@ -107,7 +175,11 @@ function getPool(): Pool { globalState.__devimpactDbPool = new Pool(getPoolConfig()); globalState.__devimpactDbPool.on("error", (err) => { - console.error("Unexpected database pool error:", err); + reportServerError(err, { + source: "db", + stage: "db_pool", + routeOrJob: "pg-pool", + }); }); } @@ -168,6 +240,36 @@ export class DatabaseStore { CREATE INDEX IF NOT EXISTS idx_leaderboard_calc_status ON leaderboard_calculation(status, last_calculated_at ASC NULLS FIRST); + + CREATE TABLE IF NOT EXISTS system_logs ( + id BIGSERIAL PRIMARY KEY, + fingerprint TEXT NOT NULL UNIQUE, + kind VARCHAR(20) NOT NULL, + source VARCHAR(20) NOT NULL, + level VARCHAR(10) NOT NULL, + status VARCHAR(30) NOT NULL, + route_or_job TEXT NOT NULL, + error_code VARCHAR(64), + stage VARCHAR(40), + message TEXT NOT NULL, + request_id VARCHAR(64), + run_id VARCHAR(64), + occurrence_count INTEGER NOT NULL DEFAULT 1, + duration_ms INTEGER, + details JSONB NOT NULL DEFAULT '{}'::jsonb, + first_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); + + CREATE INDEX IF NOT EXISTS idx_system_logs_last_seen + ON system_logs(last_seen_at DESC); + + CREATE INDEX IF NOT EXISTS idx_system_logs_kind_status + ON system_logs(kind, status, last_seen_at DESC); + + CREATE INDEX IF NOT EXISTS idx_system_logs_error_code + ON system_logs(error_code, last_seen_at DESC) + WHERE error_code IS NOT NULL; `); } @@ -415,6 +517,229 @@ export class DatabaseStore { return result.rows; } + // ── System logs & observability ───────────────────────────────────── + + async upsertSystemLog(params: UpsertSystemLogParams): Promise { + const client = getPool(); + const truncatedMessage = params.message.slice(0, 1000); + const detailsJson = JSON.stringify(params.details ?? {}); + + await client.query( + ` + INSERT INTO system_logs ( + fingerprint, kind, source, level, status, + route_or_job, error_code, stage, message, + request_id, run_id, occurrence_count, duration_ms, details, + first_seen_at, last_seen_at + ) VALUES ( + $1, $2, $3, $4, $5, + $6, $7, $8, $9, + $10, $11, 1, $12, $13::jsonb, + NOW(), NOW() + ) + ON CONFLICT (fingerprint) DO UPDATE SET + kind = EXCLUDED.kind, + source = EXCLUDED.source, + level = EXCLUDED.level, + status = CASE + WHEN EXCLUDED.kind = 'cron_run' THEN EXCLUDED.status + ELSE 'open' + END, + route_or_job = EXCLUDED.route_or_job, + error_code = EXCLUDED.error_code, + stage = EXCLUDED.stage, + message = EXCLUDED.message, + request_id = COALESCE(EXCLUDED.request_id, system_logs.request_id), + run_id = COALESCE(EXCLUDED.run_id, system_logs.run_id), + occurrence_count = CASE + WHEN EXCLUDED.kind = 'cron_run' THEN 1 + ELSE system_logs.occurrence_count + 1 + END, + duration_ms = COALESCE(EXCLUDED.duration_ms, system_logs.duration_ms), + details = EXCLUDED.details, + last_seen_at = NOW() + `, + [ + params.fingerprint, + params.kind, + params.source, + params.level, + params.status, + params.routeOrJob, + params.errorCode ?? null, + params.stage ?? null, + truncatedMessage, + params.requestId ?? null, + params.runId ?? null, + params.durationMs ?? null, + detailsJson, + ], + ); + } + + async querySystemLogs(filters: SystemLogQueryFilters = {}): Promise { + const client = getPool(); + const hours = Math.max(1, Math.min(720, filters.hours ?? 24)); + const limit = Math.max(1, Math.min(200, filters.limit ?? 50)); + + const conditions: string[] = [`last_seen_at >= NOW() - ($1 || ' hours')::INTERVAL`]; + const params: unknown[] = [hours]; + + if (filters.kind) { + params.push(filters.kind); + conditions.push(`kind = $${params.length}`); + } + if (filters.source) { + params.push(filters.source); + conditions.push(`source = $${params.length}`); + } + if (filters.errorCode) { + params.push(filters.errorCode); + conditions.push(`error_code = $${params.length}`); + } + if (filters.level) { + params.push(filters.level); + conditions.push(`level = $${params.length}`); + } + if (filters.status) { + params.push(filters.status); + conditions.push(`status = $${params.length}`); + } + + params.push(limit); + + const result = await client.query( + `SELECT + id, fingerprint, kind, source, level, status, + route_or_job, error_code, stage, message, + request_id, run_id, occurrence_count, duration_ms, details, + first_seen_at, last_seen_at + FROM system_logs + WHERE ${conditions.join(" AND ")} + ORDER BY last_seen_at DESC + LIMIT $${params.length}`, + params, + ); + return result.rows; + } + + async getObservabilitySummary(hours: number = 24): Promise { + const client = getPool(); + const safeHours = Math.max(1, Math.min(720, hours)); + + const [aggResult, lastCronResult] = await Promise.all([ + client.query<{ + error_code: string | null; + source: string; + level: string; + group_count: string; + occurrence_sum: string; + }>( + `SELECT + COALESCE(error_code, 'UNCLASSIFIED') AS error_code, + source, + level, + COUNT(*)::text AS group_count, + COALESCE(SUM(occurrence_count), 0)::text AS occurrence_sum + FROM system_logs + WHERE kind != 'cron_run' + AND status = 'open' + AND last_seen_at >= NOW() - ($1 || ' hours')::INTERVAL + GROUP BY COALESCE(error_code, 'UNCLASSIFIED'), source, level`, + [safeHours], + ), + client.query( + `SELECT + id, fingerprint, kind, source, level, status, + route_or_job, error_code, stage, message, + request_id, run_id, occurrence_count, duration_ms, details, + first_seen_at, last_seen_at + FROM system_logs + WHERE kind = 'cron_run' + ORDER BY last_seen_at DESC + LIMIT 1`, + ), + ]); + + const byCode: Record = {}; + const bySource: Record = {}; + const byLevel: Record = {}; + let totalGroups = 0; + let totalOccurrences = 0; + + for (const row of aggResult.rows) { + const groups = Number(row.group_count) || 0; + const occurrences = Number(row.occurrence_sum) || 0; + const codeKey = row.error_code || "UNCLASSIFIED"; + + totalGroups += groups; + totalOccurrences += occurrences; + + byCode[codeKey] = { + groups: (byCode[codeKey]?.groups ?? 0) + groups, + occurrences: (byCode[codeKey]?.occurrences ?? 0) + occurrences, + }; + bySource[row.source] = { + groups: (bySource[row.source]?.groups ?? 0) + groups, + occurrences: (bySource[row.source]?.occurrences ?? 0) + occurrences, + }; + byLevel[row.level] = { + groups: (byLevel[row.level]?.groups ?? 0) + groups, + occurrences: (byLevel[row.level]?.occurrences ?? 0) + occurrences, + }; + } + + return { + windowHours: safeHours, + totalGroups, + totalOccurrences, + byCode, + bySource, + byLevel, + lastCronRun: lastCronResult.rows[0] ?? null, + }; + } + + async updateSystemLogStatus(fingerprint: string, status: "open" | "resolved"): Promise { + const client = getPool(); + const result = await client.query( + `UPDATE system_logs + SET status = $2 + WHERE fingerprint = $1 AND kind != 'cron_run'`, + [fingerprint, status], + ); + return (result.rowCount ?? 0) > 0; + } + + async pruneSystemLogs(options?: { + errorRetentionDays?: number; + cronRetentionDays?: number; + }): Promise<{ deletedErrors: number; deletedCronRuns: number }> { + const client = getPool(); + const errorDays = Math.max(1, options?.errorRetentionDays ?? 60); + const cronDays = Math.max(1, options?.cronRetentionDays ?? 90); + + const [errResult, cronResult] = await Promise.all([ + client.query( + `DELETE FROM system_logs + WHERE kind != 'cron_run' + AND last_seen_at < NOW() - ($1 || ' days')::INTERVAL`, + [errorDays], + ), + client.query( + `DELETE FROM system_logs + WHERE kind = 'cron_run' + AND last_seen_at < NOW() - ($1 || ' days')::INTERVAL`, + [cronDays], + ), + ]); + + return { + deletedErrors: errResult.rowCount ?? 0, + deletedCronRuns: cronResult.rowCount ?? 0, + }; + } + // ── Health check ──────────────────────────────────────────────────── async ping(): Promise { diff --git a/src/lib/db/tests/db-store.test.ts b/src/lib/db/tests/db-store.test.ts index cc2b323..a008795 100644 --- a/src/lib/db/tests/db-store.test.ts +++ b/src/lib/db/tests/db-store.test.ts @@ -130,3 +130,105 @@ describe("DatabaseStore stale user queries", () => { expect(params).toEqual(["sweden", 7, 50]); }); }); + +describe("DatabaseStore system_logs persistence", () => { + let store: DatabaseStore; + + beforeEach(() => { + vi.clearAllMocks(); + store = new DatabaseStore(); + }); + + test("upsertSystemLog inserts with ON CONFLICT (fingerprint) and truncates long messages", async () => { + mockQuery.mockResolvedValueOnce({ rows: [], rowCount: 1 }); + const longMsg = "x".repeat(1500); + + await store.upsertSystemLog({ + fingerprint: "err_abc123", + kind: "error", + source: "api", + level: "error", + status: "open", + routeOrJob: "/api/user/[username]", + errorCode: "RATE_LIMITED", + stage: "pull_requests", + message: longMsg, + requestId: "req_123", + details: { username: "torvalds" }, + }); + + expect(mockQuery).toHaveBeenCalledTimes(1); + const [query, params] = mockQuery.mock.calls[0]; + expect(query).toContain("INSERT INTO system_logs"); + expect(query).toContain("ON CONFLICT (fingerprint) DO UPDATE SET"); + expect((params[8] as string).length).toBe(1000); + expect(params[12]).toBe(JSON.stringify({ username: "torvalds" })); + }); + + test("querySystemLogs applies filters and bounds limit/hours", async () => { + mockQuery.mockResolvedValueOnce({ rows: [{ id: 1, fingerprint: "err_1" }], rowCount: 1 }); + + const rows = await store.querySystemLogs({ + hours: 48, + limit: 25, + kind: "error", + source: "api", + errorCode: "RATE_LIMITED", + }); + + expect(rows).toHaveLength(1); + const [query, params] = mockQuery.mock.calls[0]; + expect(query).toContain("kind = $2"); + expect(query).toContain("source = $3"); + expect(query).toContain("error_code = $4"); + expect(params).toEqual([48, "error", "api", "RATE_LIMITED", 25]); + }); + + test("getObservabilitySummary aggregates open groups and occurrences", async () => { + mockQuery + .mockResolvedValueOnce({ + rows: [ + { + error_code: "RATE_LIMITED", + source: "api", + level: "error", + group_count: "2", + occurrence_sum: "15", + }, + { + error_code: "GITHUB_NOT_FOUND", + source: "cron", + level: "warn", + group_count: "1", + occurrence_sum: "4", + }, + ], + rowCount: 2, + }) + .mockResolvedValueOnce({ + rows: [{ id: 10, kind: "cron_run", status: "completed" }], + rowCount: 1, + }); + + const summary = await store.getObservabilitySummary(24); + + expect(summary.totalGroups).toBe(3); + expect(summary.totalOccurrences).toBe(19); + expect(summary.byCode.RATE_LIMITED).toEqual({ groups: 2, occurrences: 15 }); + expect(summary.bySource.cron).toEqual({ groups: 1, occurrences: 4 }); + expect(summary.lastCronRun?.id).toBe(10); + }); + + test("pruneSystemLogs deletes expired error and cron rows separately", async () => { + mockQuery + .mockResolvedValueOnce({ rows: [], rowCount: 7 }) + .mockResolvedValueOnce({ rows: [], rowCount: 2 }); + + const result = await store.pruneSystemLogs({ errorRetentionDays: 30, cronRetentionDays: 90 }); + + expect(result).toEqual({ deletedErrors: 7, deletedCronRuns: 2 }); + expect(mockQuery).toHaveBeenCalledTimes(2); + expect(mockQuery.mock.calls[0][1]).toEqual([30]); + expect(mockQuery.mock.calls[1][1]).toEqual([90]); + }); +}); diff --git a/src/lib/github/github-client.ts b/src/lib/github/github-client.ts index e0ba3f4..c6c5252 100644 --- a/src/lib/github/github-client.ts +++ b/src/lib/github/github-client.ts @@ -4,6 +4,7 @@ import { type CacheConfig, type CacheStore, } from "@/lib/cache"; +import { attachErrorStage, reportServerError } from "@/lib/observability"; import { getGitHubUserStaleDays, isUserDataFresh } from "@/utils/stale"; import { GitHubGraphQLClient } from "./github-graphql-client"; import type { DiscussionNode, GitHubUserData, IssueNode, PullRequestNode, RepoNode } from "./types"; @@ -477,15 +478,15 @@ async function fetchUserDataFromGitHub( } if (userResult.status === "rejected") { - throw userResult.reason; + throw attachErrorStage(userResult.reason, "user_profile"); } if (prResult.status === "rejected") { - throw prResult.reason; + throw attachErrorStage(prResult.reason, "pull_requests"); } if (!userResult.value.user) { - throw new Error("User not found"); + throw attachErrorStage(new Error("User not found"), "user_profile"); } const user = userResult.value.user; @@ -677,8 +678,14 @@ export async function getUserData( // Stale — delete and fall through await cacheStoreSingleton.del?.(cacheKey); } - } catch { + } catch (cacheError: unknown) { // Non-fatal: continue to DB + reportServerError(cacheError, { + source: "cache", + stage: "cache_read", + routeOrJob: "getUserData", + target: { username: normalizedUsername }, + }); } } @@ -704,8 +711,14 @@ export async function getUserData( : new Date().toISOString(), }; await cacheStoreSingleton.set(cacheKey, entry, cacheConfigSingleton.ttlSeconds); - } catch { + } catch (cacheWriteError: unknown) { // Non-fatal: cache write failure + reportServerError(cacheWriteError, { + source: "cache", + stage: "cache_write", + routeOrJob: "getUserData", + target: { username: normalizedUsername }, + }); } } const userData = row.raw_data as GitHubUserData; @@ -715,8 +728,14 @@ export async function getUserData( } staleFallback = row.raw_data as GitHubUserData; } - } catch { + } catch (dbError: unknown) { // Non-fatal: DB failure, fall through to GitHub API + reportServerError(dbError, { + source: "db", + stage: "db_read", + routeOrJob: "getUserData", + target: { username: normalizedUsername }, + }); } // ── 3. Fetch from GitHub API ────────────────────────────────────────── @@ -728,13 +747,13 @@ export async function getUserData( metrics = result.metrics; } catch (error: unknown) { if (staleFallback) { - console.warn( - "Failed to refresh data from GitHub, falling back to existing database record:", - { - username: normalizedUsername, - error, - }, - ); + reportServerError(error, { + source: "github", + routeOrJob: "getUserData:staleFallback", + severity: "warn", + target: { username: normalizedUsername }, + context: { fallbackUsed: true }, + }); return withMetrics ? { data: staleFallback, @@ -764,8 +783,14 @@ export async function getUserData( fetchedAt: new Date().toISOString(), }; await cacheStoreSingleton.set(cacheKey, entry, cacheConfigSingleton.ttlSeconds); - } catch { + } catch (cacheWriteError: unknown) { // Non-fatal + reportServerError(cacheWriteError, { + source: "cache", + stage: "cache_write", + routeOrJob: "getUserData", + target: { username: normalizedUsername }, + }); } } else { // Delete stale cache entry (leaderboard calculation path) @@ -774,8 +799,14 @@ export async function getUserData( await cacheStoreSingleton.del( `${cacheConfigSingleton.namespace}:profile:${normalizedUsername.toLowerCase()}`, ); - } catch { + } catch (cacheDelError: unknown) { // Non-fatal + reportServerError(cacheDelError, { + source: "cache", + stage: "cache_write", + routeOrJob: "getUserData:cacheInvalidate", + target: { username: normalizedUsername }, + }); } } } diff --git a/src/lib/logger/logger.ts b/src/lib/logger/logger.ts index 8689339..d4d13a1 100644 --- a/src/lib/logger/logger.ts +++ b/src/lib/logger/logger.ts @@ -9,16 +9,61 @@ const LOG_LEVEL_COLORS: Record = { const RESET_COLOR = "\x1b[0m"; +export function serializeLogValue(value: unknown): unknown { + if (value instanceof Error) { + return { + name: value.name, + message: value.message, + ...(value.stack ? { stack: value.stack } : {}), + }; + } + if (Array.isArray(value)) { + return value.map(serializeLogValue); + } + if (value !== null && typeof value === "object") { + const out: Record = {}; + for (const [k, v] of Object.entries(value)) { + out[k] = serializeLogValue(v); + } + return out; + } + return value; +} + +function writeLogLine(level: LogLevel, line: string): void { + if (level === "ERROR") { + console.error(line); + } else if (level === "WARN") { + console.warn(line); + } else { + console.log(line); + } +} + function log(level: LogLevel, message: string, data?: Record) { const timestamp = new Date().toISOString(); + const serializedData = data ? (serializeLogValue(data) as Record) : undefined; + + if (process.env.NODE_ENV === "production") { + const entry = { + timestamp, + level, + service: process.env.LOG_SERVICE?.trim() || "devimpact", + message, + ...(serializedData ? { data: serializedData } : {}), + }; + writeLogLine(level, JSON.stringify(entry)); + return; + } + const color = LOG_LEVEL_COLORS[level]; let logMessage = `${color}[${timestamp}] [${level}]${RESET_COLOR} ${message}`; - if (data) { - logMessage += ` ${JSON.stringify(data)}`; + if (serializedData) { + logMessage += ` ${JSON.stringify(serializedData)}`; } - console.log(logMessage); + writeLogLine(level, logMessage); } export const logger = { diff --git a/src/lib/observability/db-sink.ts b/src/lib/observability/db-sink.ts new file mode 100644 index 0000000..a9aaf5f --- /dev/null +++ b/src/lib/observability/db-sink.ts @@ -0,0 +1,87 @@ +import type { DatabaseStore, UpsertSystemLogParams } from "@/lib/db"; +import { logger } from "@/lib/logger"; +import type { CategorizedError, LogSink } from "./types"; + +const DEFAULT_DB_SINK_TIMEOUT_MS = 2_500; +const MAX_STACK_LENGTH = 4_000; + +let warnedMissingTable = false; + +export function toSystemLogParams(event: CategorizedError): UpsertSystemLogParams { + return { + fingerprint: event.fingerprint, + kind: event.severity === "warn" ? "warn" : "error", + source: event.source, + level: event.severity, + status: "open", + routeOrJob: event.routeOrJob, + errorCode: event.code, + stage: event.stage, + message: event.message, + requestId: event.requestId ?? null, + runId: event.runId ?? null, + details: { + ...(event.target ? { target: event.target } : {}), + ...(event.rateLimit ? { rateLimit: event.rateLimit } : {}), + ...(event.pgCode ? { pgCode: event.pgCode } : {}), + ...(event.httpStatus !== undefined ? { httpStatus: event.httpStatus } : {}), + ...(event.context ? { context: event.context } : {}), + ...(event.stack ? { stack: event.stack.slice(0, MAX_STACK_LENGTH) } : {}), + occurredAt: event.occurredAt, + }, + }; +} + +function isUndefinedTableError(error: unknown): boolean { + return ( + error !== null && + typeof error === "object" && + "code" in error && + (error as { code?: unknown }).code === "42P01" + ); +} + +async function withTimeout(promise: Promise, timeoutMs: number): Promise { + let timer: ReturnType | undefined; + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout(() => { + reject(new Error(`Database log sink timed out after ${timeoutMs}ms`)); + }, timeoutMs); + }), + ]); + } finally { + if (timer) { + clearTimeout(timer); + } + } +} + +export function createDatabaseLogSink( + db: Pick, + options?: { timeoutMs?: number }, +): LogSink { + const timeoutMs = options?.timeoutMs ?? DEFAULT_DB_SINK_TIMEOUT_MS; + + return { + name: "postgres-system-logs", + async writeError(event: CategorizedError): Promise { + try { + await withTimeout(db.upsertSystemLog(toSystemLogParams(event)), timeoutMs); + } catch (err: unknown) { + if (isUndefinedTableError(err)) { + if (!warnedMissingTable) { + warnedMissingTable = true; + logger.warn( + "system_logs table does not exist yet; run database migrations (pnpm db:migrate) to enable persistent error logging", + ); + } + return; + } + throw err; + } + }, + }; +} diff --git a/src/lib/observability/error-classifier.ts b/src/lib/observability/error-classifier.ts new file mode 100644 index 0000000..1bf3ca5 --- /dev/null +++ b/src/lib/observability/error-classifier.ts @@ -0,0 +1,346 @@ +import { createHash } from "node:crypto"; +import { GitHubApiError, type GitHubErrorKind } from "@/lib/github/github-graphql-client"; +import type { + CategorizedError, + CategorizedErrorCode, + CategorizedRateLimit, + ClassifyErrorContext, + ErrorSeverity, + ErrorStage, + ErrorTarget, +} from "./types"; + +const errorStageRegistry = new WeakMap(); + +const DB_CONNECTION_CODES = new Set([ + "ECONNREFUSED", + "ENOTFOUND", + "ECONNRESET", + "ETIMEDOUT", + "EAI_AGAIN", + "EHOSTUNREACH", + "57P01", + "57P02", + "57P03", + "08000", + "08001", + "08003", + "08004", + "08006", +]); + +const DB_TIMEOUT_CODES = new Set(["57014", "QUERY_TIMEOUT"]); + +/** + * Attaches a logical execution stage to a thrown error object without mutating + * its prototype, class identity, or enumerable properties. + */ +export function attachErrorStage(error: T, stage: ErrorStage): T { + if (error !== null && typeof error === "object") { + errorStageRegistry.set(error, stage); + } + return error; +} + +export function getAttachedErrorStage(error: unknown): ErrorStage | undefined { + if (error !== null && typeof error === "object") { + return errorStageRegistry.get(error); + } + return undefined; +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object"; +} + +function unwrapError(error: unknown): { + innerError: unknown; + wrappedUsername?: string; + attachedStage?: ErrorStage; +} { + let current: unknown = error; + let wrappedUsername: string | undefined; + let attachedStage = getAttachedErrorStage(current); + + // Unwrap UserFetchError-shaped wrappers safely without importing feature services + for (let depth = 0; depth < 3; depth += 1) { + if (!isRecord(current) || !("causeError" in current)) { + break; + } + + if (typeof current.username === "string" && current.username.trim() && !wrappedUsername) { + wrappedUsername = current.username.trim(); + } + + current = current.causeError; + attachedStage = attachedStage ?? getAttachedErrorStage(current); + } + + return { innerError: current, wrappedUsername, attachedStage }; +} + +function mapGitHubKindToCode(kind: GitHubErrorKind): CategorizedErrorCode { + switch (kind) { + case "PRIMARY_RATE_LIMIT": + return "RATE_LIMITED"; + case "SECONDARY_RATE_LIMIT": + return "TEMPORARY_THROTTLE"; + case "TIMEOUT": + return "GITHUB_TIMEOUT"; + case "RESOURCE_LIMIT": + return "GITHUB_RESOURCE_LIMIT"; + case "AUTH": + return "GITHUB_AUTH"; + case "NOT_FOUND": + return "GITHUB_NOT_FOUND"; + case "NETWORK": + return "GITHUB_NETWORK"; + case "UNKNOWN": + default: + return "GITHUB_UNKNOWN"; + } +} + +function extractPgCode(error: unknown): string | undefined { + if (!isRecord(error)) return undefined; + if (typeof error.code === "string" && error.code.trim()) { + return error.code.trim(); + } + if (isRecord(error.cause) && typeof error.cause.code === "string" && error.cause.code.trim()) { + return error.cause.code.trim(); + } + return undefined; +} + +function extractErrorMessage(error: unknown): string { + if (error instanceof Error) { + return error.message || error.name || "Unknown error"; + } + if (typeof error === "string" && error.trim()) { + return error.trim(); + } + if (isRecord(error) && typeof error.message === "string" && error.message.trim()) { + return error.message.trim(); + } + return String(error); +} + +function extractErrorStack(primaryError: unknown, fallbackError: unknown): string | undefined { + if (primaryError instanceof Error && primaryError.stack) { + return primaryError.stack; + } + if (fallbackError instanceof Error && fallbackError.stack) { + return fallbackError.stack; + } + return undefined; +} + +function isDatabaseStage(stage: ErrorStage, source: ClassifyErrorContext["source"]): boolean { + return ( + source === "db" || + stage === "db_read" || + stage === "db_write" || + stage === "db_query" || + stage === "db_pool" + ); +} + +function isPgSqlState(code: string): boolean { + return /^[0-9A-Z]{5}$/.test(code); +} + +function isNetworkFailureMessage(message: string): boolean { + const lower = message.toLowerCase(); + return ( + lower.includes("fetch failed") || + lower.includes("econnreset") || + lower.includes("etimedout") || + lower.includes("econnrefused") || + lower.includes("enotfound") || + lower.includes("network") || + lower.includes("socket hang up") || + lower.includes("aborted") + ); +} + +function normalizeMessageForFingerprint(message: string): string { + return message + .replace(/[0-9a-f]{8}-[0-9a-f-]{27}/gi, "") + .replace(/\b\d+\b/g, "") + .replace(/\s+/g, " ") + .trim() + .slice(0, 180); +} + +function buildFingerprint(input: { + source: string; + routeOrJob: string; + code: string; + stage: string; + message: string; +}): string { + const raw = [ + input.source, + input.routeOrJob, + input.code, + input.stage, + normalizeMessageForFingerprint(input.message), + ].join("|"); + + return `err_${createHash("sha256").update(raw).digest("hex").slice(0, 20)}`; +} + +function resolveDefaultSeverity( + code: CategorizedErrorCode, + meta: ClassifyErrorContext, +): ErrorSeverity { + if (meta.severity) { + return meta.severity; + } + + if ( + code === "GITHUB_NOT_FOUND" || + code === "PARTIAL_FETCH_ISSUES" || + code === "PARTIAL_FETCH_DISCUSSIONS" || + code === "STALE_GITHUB_FALLBACK" || + code === "CACHE_READ_ERROR" || + code === "CACHE_WRITE_ERROR" || + code === "VALIDATION_ERROR" + ) { + return "warn"; + } + + return "error"; +} + +export function classifyPartialFetchPart(part: string): { + code: CategorizedErrorCode; + stage: ErrorStage; +} { + switch (part) { + case "user": + return { code: "PARTIAL_FETCH_USER", stage: "user_profile" }; + case "pullRequests": + return { code: "PARTIAL_FETCH_PULL_REQUESTS", stage: "pull_requests" }; + case "issues": + return { code: "PARTIAL_FETCH_ISSUES", stage: "issues" }; + case "discussions": + return { code: "PARTIAL_FETCH_DISCUSSIONS", stage: "discussions" }; + case "github": + return { code: "STALE_GITHUB_FALLBACK", stage: "stale_fallback" }; + default: + return { code: "GITHUB_UNKNOWN", stage: "unknown" }; + } +} + +export function classifyError(error: unknown, meta: ClassifyErrorContext): CategorizedError { + const { innerError, wrappedUsername, attachedStage } = unwrapError(error); + const stage: ErrorStage = attachedStage ?? meta.stage ?? "unknown"; + const message = extractErrorMessage(innerError); + const pgCode = extractPgCode(innerError); + + const target: ErrorTarget | undefined = + meta.target || wrappedUsername + ? { + ...meta.target, + ...(wrappedUsername && !meta.target?.username ? { username: wrappedUsername } : {}), + } + : undefined; + + let code: CategorizedErrorCode = "UNEXPECTED_ERROR"; + let rateLimit: CategorizedRateLimit | undefined; + let httpStatus = meta.httpStatus; + + if (innerError instanceof GitHubApiError) { + code = mapGitHubKindToCode(innerError.kind); + httpStatus = httpStatus ?? innerError.status; + rateLimit = { + ...innerError.rateLimit, + ...(innerError.retryAfterMs !== undefined + ? { retryAfterSeconds: Math.max(1, Math.ceil(innerError.retryAfterMs / 1000)) } + : {}), + }; + } else if (message.toLowerCase() === "user not found") { + code = "GITHUB_NOT_FOUND"; + httpStatus = httpStatus ?? 404; + } else if (stage === "cache_read" || meta.source === "cache") { + code = stage === "cache_write" ? "CACHE_WRITE_ERROR" : "CACHE_READ_ERROR"; + } else if ( + stage === "source_yaml" || + message.startsWith("Leaderboard source returned") || + message.startsWith("Invalid or empty leaderboard source data") + ) { + code = "LEADERBOARD_SOURCE_ERROR"; + } else if (stage === "db_pool") { + code = "DB_POOL_ERROR"; + } else if (pgCode && DB_TIMEOUT_CODES.has(pgCode)) { + code = "DB_QUERY_TIMEOUT"; + } else if (pgCode && DB_CONNECTION_CODES.has(pgCode)) { + code = "DB_CONNECTION_ERROR"; + } else if ( + isDatabaseStage(stage, meta.source) || + (pgCode !== undefined && isPgSqlState(pgCode)) + ) { + const lower = message.toLowerCase(); + if (lower.includes("timeout") || lower.includes("timed out")) { + code = "DB_QUERY_TIMEOUT"; + } else if ( + lower.includes("connect") || + lower.includes("econn") || + lower.includes("terminated") + ) { + code = "DB_CONNECTION_ERROR"; + } else { + code = "DB_QUERY_ERROR"; + } + } else if ( + (stage === "user_profile" || + stage === "pull_requests" || + stage === "issues" || + stage === "discussions" || + meta.source === "github") && + isNetworkFailureMessage(message) + ) { + code = "GITHUB_NETWORK"; + } else if (message.toLowerCase().includes("rate limit")) { + code = "RATE_LIMITED"; + } + + const severity = resolveDefaultSeverity(code, meta); + const stack = extractErrorStack(innerError, error); + + return { + fingerprint: buildFingerprint({ + source: meta.source, + routeOrJob: meta.routeOrJob, + code, + stage, + message, + }), + code, + severity, + source: meta.source, + stage, + routeOrJob: meta.routeOrJob, + message, + ...(meta.requestId ? { requestId: meta.requestId } : {}), + ...(meta.runId ? { runId: meta.runId } : {}), + ...(target ? { target } : {}), + ...(rateLimit ? { rateLimit } : {}), + ...(pgCode ? { pgCode } : {}), + ...(httpStatus !== undefined ? { httpStatus } : {}), + ...(stack ? { stack } : {}), + ...(meta.context ? { context: meta.context } : {}), + occurredAt: new Date().toISOString(), + }; +} + +export function summarizeCategorizedErrors( + items: ReadonlyArray<{ code: CategorizedErrorCode | string }>, +): Record { + const summary: Record = {}; + for (const item of items) { + summary[item.code] = (summary[item.code] ?? 0) + 1; + } + return summary; +} diff --git a/src/lib/observability/error-reporter.ts b/src/lib/observability/error-reporter.ts new file mode 100644 index 0000000..557671c --- /dev/null +++ b/src/lib/observability/error-reporter.ts @@ -0,0 +1,168 @@ +import { randomUUID } from "node:crypto"; +import { scheduleBackground } from "@/lib/background"; +import { logger } from "@/lib/logger"; +import { createDatabaseLogSink } from "./db-sink"; +import { classifyError, classifyPartialFetchPart } from "./error-classifier"; +import type { CategorizedError, ClassifyErrorContext, LogSink } from "./types"; + +const sinks = new Set(); +const pendingDispatches = new Set>(); + +export function registerLogSink(sink: LogSink): () => void { + sinks.add(sink); + return () => { + sinks.delete(sink); + }; +} + +export function clearLogSinks(): void { + sinks.clear(); +} + +export async function flushLogSinks(): Promise { + if (pendingDispatches.size === 0) return; + await Promise.allSettled(Array.from(pendingDispatches)); +} + +function isAutoDbSinkEnabled(): boolean { + if (process.env.NODE_ENV === "test") return false; + const flag = process.env.OBSERVABILITY_DB_ENABLED?.trim().toLowerCase(); + if (flag === "false" || flag === "0") return false; + return Boolean(process.env.DATABASE_URL?.trim()); +} + +async function resolveDefaultSinks(): Promise { + if (sinks.size > 0) { + return Array.from(sinks); + } + if (!isAutoDbSinkEnabled()) { + return []; + } + + try { + const { getDatabaseStore } = await import("@/lib/db"); + const db = getDatabaseStore(); + if (typeof db.upsertSystemLog === "function") { + return [createDatabaseLogSink(db)]; + } + } catch (err) { + logger.warn("Failed to initialize default database log sink", { + error: err instanceof Error ? err.message : String(err), + }); + } + return []; +} + +export function createRequestId(request?: Request): string { + const fromHeader = + request?.headers.get("x-request-id")?.trim() || request?.headers.get("x-vercel-id")?.trim(); + if (fromHeader) { + return fromHeader.slice(0, 64); + } + return `req_${randomUUID().replace(/-/g, "").slice(0, 12)}`; +} + +export function createRunId(prefix = "cron"): string { + return `${prefix}_${Date.now().toString(36)}_${randomUUID().replace(/-/g, "").slice(0, 8)}`; +} + +function dispatchToSinks(event: CategorizedError, meta?: ClassifyErrorContext): void { + if (event.routeOrJob === "system_logs" || meta?.context?.skipLogSinks === true) { + return; + } + + if (sinks.size === 0 && !isAutoDbSinkEnabled()) { + return; + } + + const dispatchPromise = (async () => { + const activeSinks = await resolveDefaultSinks(); + if (activeSinks.length === 0) return; + + await Promise.allSettled( + activeSinks.map(async (sink) => { + try { + await sink.writeError(event); + } catch (sinkErr) { + logger.warn("Observability log sink failed", { + sink: sink.name, + error: sinkErr instanceof Error ? sinkErr.message : String(sinkErr), + }); + } + }), + ); + })().finally(() => { + pendingDispatches.delete(dispatchPromise); + }); + + pendingDispatches.add(dispatchPromise); + scheduleBackground(() => dispatchPromise); +} + +function logCategorizedError(event: CategorizedError): void { + const payload: Record = { + fingerprint: event.fingerprint, + code: event.code, + source: event.source, + stage: event.stage, + routeOrJob: event.routeOrJob, + ...(event.requestId ? { requestId: event.requestId } : {}), + ...(event.runId ? { runId: event.runId } : {}), + ...(event.target ? { target: event.target } : {}), + ...(event.rateLimit ? { rateLimit: event.rateLimit } : {}), + ...(event.pgCode ? { pgCode: event.pgCode } : {}), + ...(event.httpStatus !== undefined ? { httpStatus: event.httpStatus } : {}), + ...(event.context ? { context: event.context } : {}), + ...(event.stack ? { stack: event.stack } : {}), + }; + + if (event.severity === "warn") { + logger.warn(`[${event.code}] ${event.message}`, payload); + } else { + logger.error(`[${event.code}] ${event.message}`, payload); + } +} + +/** + * Classifies an exception into a structured, fingerprinted error record, + * logs it immediately, and schedules non-blocking delivery to registered sinks. + */ +export function reportServerError(error: unknown, meta: ClassifyErrorContext): CategorizedError { + const categorized = classifyError(error, meta); + logCategorizedError(categorized); + dispatchToSinks(categorized, meta); + return categorized; +} + +/** + * Reports non-fatal partial GitHub fetch failures (e.g. issues/discussions + * or stale DB fallback) as categorized warnings so silent degradations become visible. + */ +export function reportPartialFetchWarnings( + warnings: ReadonlyArray<{ part: string; reason: string }>, + meta: Omit, +): CategorizedError[] { + if (warnings.length === 0) return []; + + return warnings.map((warning) => { + const { code, stage } = classifyPartialFetchPart(warning.part); + const categorized = classifyError(new Error(warning.reason), { + ...meta, + stage, + severity: "warn", + context: { + ...meta.context, + partialPart: warning.part, + }, + }); + const normalized: CategorizedError = { + ...categorized, + code, + stage, + }; + + logCategorizedError(normalized); + dispatchToSinks(normalized); + return normalized; + }); +} diff --git a/src/lib/observability/index.ts b/src/lib/observability/index.ts new file mode 100644 index 0000000..cdf7f49 --- /dev/null +++ b/src/lib/observability/index.ts @@ -0,0 +1,4 @@ +export * from "./types"; +export * from "./error-classifier"; +export * from "./error-reporter"; +export * from "./db-sink"; diff --git a/src/lib/observability/tests/db-sink.test.ts b/src/lib/observability/tests/db-sink.test.ts new file mode 100644 index 0000000..cd24141 --- /dev/null +++ b/src/lib/observability/tests/db-sink.test.ts @@ -0,0 +1,71 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { + clearLogSinks, + createDatabaseLogSink, + flushLogSinks, + registerLogSink, + reportServerError, + toSystemLogParams, +} from "../index"; + +describe("database log sink", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + clearLogSinks(); + vi.restoreAllMocks(); + }); + + test("createDatabaseLogSink persists mapped system_logs parameters", async () => { + const upsertSystemLog = vi.fn().mockResolvedValue(undefined); + const sink = createDatabaseLogSink({ upsertSystemLog }); + + registerLogSink(sink); + reportServerError(new Error("connect ECONNREFUSED 127.0.0.1:5432"), { + source: "db", + stage: "db_query", + routeOrJob: "getLeaderboardResult", + requestId: "req_db1", + target: { country: "japan" }, + }); + + await flushLogSinks(); + + expect(upsertSystemLog).toHaveBeenCalledTimes(1); + const payload = upsertSystemLog.mock.calls[0]?.[0] as ReturnType; + expect(payload.kind).toBe("error"); + expect(payload.source).toBe("db"); + expect(payload.routeOrJob).toBe("getLeaderboardResult"); + expect(payload.requestId).toBe("req_db1"); + expect(payload.details).toMatchObject({ + target: { country: "japan" }, + }); + }); + + test("createDatabaseLogSink handles missing system_logs table (42P01) without throwing", async () => { + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + const upsertSystemLog = vi + .fn() + .mockRejectedValue( + Object.assign(new Error('relation "system_logs" does not exist'), { code: "42P01" }), + ); + const sink = createDatabaseLogSink({ upsertSystemLog }); + + await expect( + sink.writeError({ + fingerprint: "err_missing_table", + code: "UNEXPECTED_ERROR", + severity: "error", + source: "api", + stage: "unknown", + routeOrJob: "/api/test", + message: "boom", + occurredAt: new Date().toISOString(), + }), + ).resolves.toBeUndefined(); + + expect(warnSpy).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/lib/observability/tests/observability.test.ts b/src/lib/observability/tests/observability.test.ts new file mode 100644 index 0000000..2c46dbe --- /dev/null +++ b/src/lib/observability/tests/observability.test.ts @@ -0,0 +1,238 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; +import { UserFetchError } from "@/features/developer/services/user-service"; +import { GitHubApiError } from "@/lib/github/github-graphql-client"; +import { logger } from "@/lib/logger"; +import { + attachErrorStage, + classifyError, + clearLogSinks, + createRequestId, + registerLogSink, + reportPartialFetchWarnings, + reportServerError, + summarizeCategorizedErrors, +} from "../index"; + +describe("observability error classification and reporting", () => { + afterEach(() => { + clearLogSinks(); + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + }); + + test("classifies GitHub rate limit error inside UserFetchError with stage and rateLimit", () => { + const inner = attachErrorStage( + new GitHubApiError({ + message: "API rate limit exceeded", + kind: "PRIMARY_RATE_LIMIT", + status: 403, + rateLimit: { limit: 5000, remaining: 0, used: 5000, resetAt: 1700000000 }, + retryAfterMs: 45_000, + }), + "pull_requests", + ); + const wrapped = new UserFetchError("torvalds", inner); + + const categorized = classifyError(wrapped, { + source: "api", + routeOrJob: "/api/user/[username]", + requestId: "req_abc123", + }); + + expect(categorized.code).toBe("RATE_LIMITED"); + expect(categorized.severity).toBe("error"); + expect(categorized.stage).toBe("pull_requests"); + expect(categorized.target?.username).toBe("torvalds"); + expect(categorized.httpStatus).toBe(403); + expect(categorized.requestId).toBe("req_abc123"); + expect(categorized.rateLimit).toEqual({ + limit: 5000, + remaining: 0, + used: 5000, + resetAt: 1700000000, + retryAfterSeconds: 45, + }); + expect(categorized.fingerprint).toMatch(/^err_[0-9a-f]{20}$/); + }); + + test("classifies user-not-found errors as warnings with GITHUB_NOT_FOUND", () => { + const err = attachErrorStage(new Error("User not found"), "user_profile"); + const categorized = classifyError(new UserFetchError("missing-dev", err), { + source: "api", + routeOrJob: "/api/user/[username]", + }); + + expect(categorized.code).toBe("GITHUB_NOT_FOUND"); + expect(categorized.severity).toBe("warn"); + expect(categorized.stage).toBe("user_profile"); + expect(categorized.target?.username).toBe("missing-dev"); + }); + + test("classifies PostgreSQL connection, timeout, and query errors", () => { + const connErr = Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:5432"), { + code: "ECONNREFUSED", + }); + const timeoutErr = Object.assign(new Error("canceling statement due to statement timeout"), { + code: "57014", + }); + const sqlErr = Object.assign(new Error("duplicate key value violates unique constraint"), { + code: "23505", + }); + + const categorizedConn = classifyError(connErr, { + source: "db", + stage: "db_query", + routeOrJob: "getLeaderboardResult", + target: { country: "germany" }, + }); + const categorizedTimeout = classifyError(timeoutErr, { + source: "db", + stage: "db_read", + routeOrJob: "getUserProfile", + }); + const categorizedSql = classifyError(sqlErr, { + source: "db", + stage: "db_write", + routeOrJob: "persistUserScores", + }); + + expect(categorizedConn.code).toBe("DB_CONNECTION_ERROR"); + expect(categorizedConn.pgCode).toBe("ECONNREFUSED"); + expect(categorizedTimeout.code).toBe("DB_QUERY_TIMEOUT"); + expect(categorizedTimeout.pgCode).toBe("57014"); + expect(categorizedSql.code).toBe("DB_QUERY_ERROR"); + expect(categorizedSql.pgCode).toBe("23505"); + }); + + test("classifies leaderboard source YAML errors", () => { + const err = attachErrorStage( + new Error('Leaderboard source returned 503 for "japan"'), + "source_yaml", + ); + const categorized = classifyError(err, { + source: "cron", + routeOrJob: "cron:japan", + }); + + expect(categorized.code).toBe("LEADERBOARD_SOURCE_ERROR"); + expect(categorized.stage).toBe("source_yaml"); + }); + + test("produces stable fingerprints across dynamic numbers", () => { + const a = classifyError(new Error("Timeout after 1200 ms"), { + source: "cron", + stage: "user_profile", + routeOrJob: "seedNewUsers", + }); + const b = classifyError(new Error("Timeout after 4500 ms"), { + source: "cron", + stage: "user_profile", + routeOrJob: "seedNewUsers", + }); + + expect(a.fingerprint).toBe(b.fingerprint); + }); + + test("reports categorized errors to logger and isolates failing log sinks", async () => { + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + const writtenCodes: string[] = []; + + registerLogSink({ + name: "failing-sink", + writeError: () => { + throw new Error("sink exploded"); + }, + }); + registerLogSink({ + name: "healthy-sink", + writeError: (event) => { + writtenCodes.push(event.code); + }, + }); + + const result = reportServerError( + new GitHubApiError({ + message: "Bad credentials", + kind: "AUTH", + status: 401, + rateLimit: {}, + }), + { + source: "api", + routeOrJob: "/api/compare", + requestId: "req_test1", + target: { usernames: ["a", "b"] }, + }, + ); + + expect(result.code).toBe("GITHUB_AUTH"); + expect(errorSpy).toHaveBeenCalledTimes(1); + + await vi.waitFor(() => { + expect(writtenCodes).toEqual(["GITHUB_AUTH"]); + }); + expect(warnSpy).toHaveBeenCalled(); + }); + + test("reports partial fetch warnings with specific codes and summarizes counts", () => { + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + + const warnings = reportPartialFetchWarnings( + [ + { part: "issues", reason: "Issues search timed out" }, + { part: "discussions", reason: "Discussions rate limit" }, + { part: "github", reason: "Served stale DB fallback" }, + ], + { + source: "github", + routeOrJob: "getUserProfile", + target: { username: "octocat" }, + }, + ); + + expect(warnings.map((w) => w.code)).toEqual([ + "PARTIAL_FETCH_ISSUES", + "PARTIAL_FETCH_DISCUSSIONS", + "STALE_GITHUB_FALLBACK", + ]); + expect(warnSpy).toHaveBeenCalledTimes(3); + expect(summarizeCategorizedErrors(warnings)).toEqual({ + PARTIAL_FETCH_ISSUES: 1, + PARTIAL_FETCH_DISCUSSIONS: 1, + STALE_GITHUB_FALLBACK: 1, + }); + }); + + test("logger emits single-line JSON without ANSI codes in production", () => { + vi.stubEnv("NODE_ENV", "production"); + vi.stubEnv("LOG_SERVICE", "leaderboard-cron"); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + + logger.error("Cron fatal", { err: new Error("boom") }); + + expect(errorSpy).toHaveBeenCalledTimes(1); + const rawLine = errorSpy.mock.calls[0]?.[0] as string; + expect(rawLine).not.toContain("\x1b["); + const parsed = JSON.parse(rawLine) as { + level: string; + service: string; + message: string; + data: { err: { name: string; message: string } }; + }; + expect(parsed.level).toBe("ERROR"); + expect(parsed.service).toBe("leaderboard-cron"); + expect(parsed.message).toBe("Cron fatal"); + expect(parsed.data.err.message).toBe("boom"); + }); + + test("createRequestId reuses incoming header or generates req_ prefix", () => { + const withHeader = new Request("http://localhost/api/test", { + headers: { "x-request-id": "req_custom_99" }, + }); + const withoutHeader = new Request("http://localhost/api/test"); + + expect(createRequestId(withHeader)).toBe("req_custom_99"); + expect(createRequestId(withoutHeader)).toMatch(/^req_[0-9a-f]{12}$/); + }); +}); diff --git a/src/lib/observability/types.ts b/src/lib/observability/types.ts new file mode 100644 index 0000000..e00c605 --- /dev/null +++ b/src/lib/observability/types.ts @@ -0,0 +1,93 @@ +import type { RateLimitSnapshot } from "@/lib/github/github-graphql-client"; + +export type CategorizedErrorCode = + | "RATE_LIMITED" + | "TEMPORARY_THROTTLE" + | "GITHUB_TIMEOUT" + | "GITHUB_RESOURCE_LIMIT" + | "GITHUB_AUTH" + | "GITHUB_NOT_FOUND" + | "GITHUB_NETWORK" + | "GITHUB_UNKNOWN" + | "PARTIAL_FETCH_USER" + | "PARTIAL_FETCH_PULL_REQUESTS" + | "PARTIAL_FETCH_ISSUES" + | "PARTIAL_FETCH_DISCUSSIONS" + | "STALE_GITHUB_FALLBACK" + | "DB_CONNECTION_ERROR" + | "DB_QUERY_TIMEOUT" + | "DB_QUERY_ERROR" + | "DB_POOL_ERROR" + | "CACHE_READ_ERROR" + | "CACHE_WRITE_ERROR" + | "LEADERBOARD_SOURCE_ERROR" + | "VALIDATION_ERROR" + | "UNEXPECTED_ERROR"; + +export type ErrorSource = "api" | "ssr" | "cron" | "db" | "cache" | "github"; + +export type ErrorStage = + | "user_profile" + | "pull_requests" + | "issues" + | "discussions" + | "stale_fallback" + | "db_read" + | "db_write" + | "db_query" + | "db_pool" + | "cache_read" + | "cache_write" + | "source_yaml" + | "scoring" + | "compare" + | "leaderboard" + | "unknown"; + +export type ErrorSeverity = "warn" | "error"; + +export type ErrorTarget = { + username?: string; + usernames?: string[]; + country?: string; +}; + +export type CategorizedRateLimit = RateLimitSnapshot & { + retryAfterSeconds?: number; +}; + +export type ClassifyErrorContext = { + source: ErrorSource; + routeOrJob: string; + stage?: ErrorStage; + requestId?: string; + runId?: string; + target?: ErrorTarget; + severity?: ErrorSeverity; + httpStatus?: number; + context?: Record; +}; + +export type CategorizedError = { + fingerprint: string; + code: CategorizedErrorCode; + severity: ErrorSeverity; + source: ErrorSource; + stage: ErrorStage; + routeOrJob: string; + message: string; + requestId?: string; + runId?: string; + target?: ErrorTarget; + rateLimit?: CategorizedRateLimit; + pgCode?: string; + httpStatus?: number; + stack?: string; + context?: Record; + occurredAt: string; +}; + +export interface LogSink { + readonly name: string; + writeError(event: CategorizedError): Promise | void; +} diff --git a/src/types/api.ts b/src/types/api.ts index d78a4a8..e79bb61 100644 --- a/src/types/api.ts +++ b/src/types/api.ts @@ -24,7 +24,9 @@ export type SafeApiError = { rateLimit?: SafeApiRateLimit; }; -export type ClientSafeError = Pick; +export type ClientSafeError = Pick & { + requestId?: string; +}; export type ApiResponse = { success: boolean;