Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,7 @@ next-env.d.ts
# Vite logs files
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
server/
server/

# Local internal observability endpoint
src/app/api/internal/observability/route.ts
6 changes: 6 additions & 0 deletions ops/docker/leaderboard-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
191 changes: 179 additions & 12 deletions scripts/calculate-next-country.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
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, number>): 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;

Expand All @@ -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)}...`);

Expand All @@ -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);
}
}
Expand Down
2 changes: 1 addition & 1 deletion scripts/init-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
9 changes: 9 additions & 0 deletions src/app/[locale]/user/[username]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
buildUserProfileSchema,
buildUserBreadcrumbSchema,
} from "@/features/developer/services";
import { reportServerError } from "@/lib/observability";
import { toAbsoluteUrl } from "@/lib/seo";

const getCachedUserProfile = cache(async (username: string) => {
Expand Down Expand Up @@ -87,7 +88,7 @@
export default async function UserProfilePage({ params, searchParams }: Props) {
const { username } = await params;
const cleanUsername = decodeURIComponent(username.trim());
const profileUrl = toAbsoluteUrl(`/user/${cleanUsername}`);

Check warning on line 91 in src/app/[locale]/user/[username]/page.tsx

View workflow job for this annotation

GitHub Actions / Validate (Node 24.x)

'profileUrl' is assigned a value but never used

Check warning on line 91 in src/app/[locale]/user/[username]/page.tsx

View workflow job for this annotation

GitHub Actions / Validate (Node 24.x)

'profileUrl' is assigned a value but never used

const resolvedSearchParams = searchParams ? await searchParams : undefined;
const countryParam = resolvedSearchParams?.country;
Expand All @@ -99,6 +100,14 @@
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) {
Expand Down
20 changes: 16 additions & 4 deletions src/app/api/compare/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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 });
}
}
Loading
Loading