From 4b7522f6e0536f83d6c8f0a52044d3fd383af023 Mon Sep 17 00:00:00 2001
From: Osama Mabkhot <99215291+O2sa@users.noreply.github.com>
Date: Tue, 1 Dec 2026 16:50:27 +0300
Subject: [PATCH 1/2] perf(ui): disable prefetching by default across all links
- Add shared Link wrapper in src/components/ui/link.tsx with prefetch={false} default
- Update all app components to use the shared Link wrapper
- Add unit tests for default and overridden prefetch behavior
---
src/components/layout/app-header.tsx | 2 +-
src/components/ui/index.ts | 1 +
src/components/ui/link.test.tsx | 51 +++++++++++++++++++
src/components/ui/link.tsx | 11 ++++
.../components/result-dashboard.tsx | 4 +-
.../comparison/components/top-list.tsx | 3 +-
.../developer/components/user-not-found.tsx | 11 +++-
.../components/user-profile-client.tsx | 2 +-
.../components/country-grid-client.tsx | 3 +-
.../components/country-leaderboard-client.tsx | 2 +-
.../components/leaderboard-table.tsx | 5 +-
11 files changed, 80 insertions(+), 15 deletions(-)
create mode 100644 src/components/ui/link.test.tsx
create mode 100644 src/components/ui/link.tsx
diff --git a/src/components/layout/app-header.tsx b/src/components/layout/app-header.tsx
index d0ac317..2669730 100644
--- a/src/components/layout/app-header.tsx
+++ b/src/components/layout/app-header.tsx
@@ -1,7 +1,7 @@
"use client";
-import Link from "next/link";
import { Trophy } from "lucide-react";
+import { Link } from "@/components/ui/link";
import { BrandLogo } from "./brand-logo";
import { LanguageSwitcher } from "@/components/providers/language-switcher";
import { ThemeToggle } from "@/components/providers/theme-toggle";
diff --git a/src/components/ui/index.ts b/src/components/ui/index.ts
index 76345fa..60de905 100644
--- a/src/components/ui/index.ts
+++ b/src/components/ui/index.ts
@@ -2,6 +2,7 @@ export * from "./alert";
export * from "./button";
export * from "./card";
export * from "./input";
+export * from "./link";
export * from "./progress";
export * from "./skeleton";
export * from "./tooltip";
diff --git a/src/components/ui/link.test.tsx b/src/components/ui/link.test.tsx
new file mode 100644
index 0000000..747dacd
--- /dev/null
+++ b/src/components/ui/link.test.tsx
@@ -0,0 +1,51 @@
+// @vitest-environment jsdom
+
+import { cleanup, render, screen } from "@testing-library/react";
+import "@testing-library/jest-dom/vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { ReactNode } from "react";
+import { Link } from "./link";
+
+const mockNextLink = vi.fn(
+ ({
+ children,
+ href,
+ prefetch,
+ }: {
+ children: ReactNode;
+ href: string;
+ prefetch?: boolean | "auto" | null;
+ }) => (
+
+ {children}
+
+ ),
+);
+
+vi.mock("next/link", () => ({
+ default: (props: { children: ReactNode; href: string; prefetch?: boolean | "auto" | null }) =>
+ mockNextLink(props),
+}));
+
+describe("Link", () => {
+ afterEach(cleanup);
+
+ it("disables prefetching by default", () => {
+ render(Leaderboard);
+
+ const anchor = screen.getByRole("link", { name: "Leaderboard" });
+ expect(anchor).toHaveAttribute("href", "/leaderboard");
+ expect(anchor).toHaveAttribute("data-prefetch", "false");
+ });
+
+ it("allows explicit prefetch override when needed", () => {
+ render(
+
+ Leaderboard
+ ,
+ );
+
+ const anchor = screen.getByRole("link", { name: "Leaderboard" });
+ expect(anchor).toHaveAttribute("data-prefetch", "true");
+ });
+});
diff --git a/src/components/ui/link.tsx b/src/components/ui/link.tsx
new file mode 100644
index 0000000..74a95c3
--- /dev/null
+++ b/src/components/ui/link.tsx
@@ -0,0 +1,11 @@
+import NextLink from "next/link";
+import type { ComponentProps } from "react";
+
+export type LinkProps = ComponentProps;
+
+/**
+ * Shared navigation Link wrapper that disables Next.js background prefetching by default.
+ */
+export function Link({ prefetch = false, ...props }: LinkProps) {
+ return ;
+}
diff --git a/src/features/comparison/components/result-dashboard.tsx b/src/features/comparison/components/result-dashboard.tsx
index 461ddfe..418816c 100644
--- a/src/features/comparison/components/result-dashboard.tsx
+++ b/src/features/comparison/components/result-dashboard.tsx
@@ -1,13 +1,12 @@
"use client";
import { useMemo, useState, useRef } from "react";
-import Link from "next/link";
import type { Route } from "next";
import { Check, Copy, ExternalLink, Trophy, Share2, XCircle } from "lucide-react";
import { useSearchParams } from "next/navigation";
import { useClipboardCopy } from "@/hooks";
import dynamic from "next/dynamic";
-import { Avatar } from "@/components/ui";
+import { Avatar, Button, Card, CardContent, CardHeader, CardTitle, Link } from "@/components/ui";
const ComparisonChart = dynamic(
() => import("./comparison-chart").then((mod) => mod.ComparisonChart),
@@ -21,7 +20,6 @@ const ComparisonChart = dynamic(
import { TopList } from "./top-list";
import { InsightsList } from "./insights-list";
import { ScoreCard } from "@/components/cards";
-import { Button, Card, CardContent, CardHeader, CardTitle } from "@/components/ui";
import { getSignalMetricEntries, type UserResult } from "@/features/developer";
import { useTranslation } from "@/components/providers";
import { formatComparisonToMarkdown } from "../services/format-comparison-to-markdown";
diff --git a/src/features/comparison/components/top-list.tsx b/src/features/comparison/components/top-list.tsx
index 7811330..2aa9a75 100644
--- a/src/features/comparison/components/top-list.tsx
+++ b/src/features/comparison/components/top-list.tsx
@@ -1,9 +1,8 @@
"use client";
-import Link from "next/link";
import type { Route } from "next";
import { ExternalLink, GitPullRequest, MessageSquare, Star } from "lucide-react";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui";
+import { Card, CardContent, CardDescription, CardHeader, CardTitle, Link } from "@/components/ui";
import type { UserResult } from "@/features/developer";
import {
RepoCardItem,
diff --git a/src/features/developer/components/user-not-found.tsx b/src/features/developer/components/user-not-found.tsx
index 8cca499..91a20aa 100644
--- a/src/features/developer/components/user-not-found.tsx
+++ b/src/features/developer/components/user-not-found.tsx
@@ -1,8 +1,15 @@
"use client";
-import Link from "next/link";
import { ArrowLeft, Search, Trophy } from "lucide-react";
-import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui";
+import {
+ Button,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Link,
+} from "@/components/ui";
import { useTranslation } from "@/components/providers";
type Props = {
diff --git a/src/features/developer/components/user-profile-client.tsx b/src/features/developer/components/user-profile-client.tsx
index 7174c53..ddb5971 100644
--- a/src/features/developer/components/user-profile-client.tsx
+++ b/src/features/developer/components/user-profile-client.tsx
@@ -1,6 +1,5 @@
"use client";
import { useEffect, useMemo, useState } from "react";
-import Link from "next/link";
import { useSearchParams } from "next/navigation";
import type { Route } from "next";
import { useClipboardCopy } from "@/hooks";
@@ -26,6 +25,7 @@ import {
CardDescription,
CardHeader,
CardTitle,
+ Link,
Progress,
} from "@/components/ui";
import {
diff --git a/src/features/leaderboard/components/country-grid-client.tsx b/src/features/leaderboard/components/country-grid-client.tsx
index c476a88..c25446f 100644
--- a/src/features/leaderboard/components/country-grid-client.tsx
+++ b/src/features/leaderboard/components/country-grid-client.tsx
@@ -2,9 +2,9 @@
import { useState, useMemo } from "react";
import { Globe, Users } from "lucide-react";
-import Link from "next/link";
import Image from "next/image";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
+import { Link } from "@/components/ui/link";
import { useTranslation } from "@/components/providers/language-provider";
import { getCountryCode } from "@/lib/geo";
import type { CountryInfo } from "../types";
@@ -89,7 +89,6 @@ export function CountryGridClient({ countries }: Props) {
diff --git a/src/features/leaderboard/components/country-leaderboard-client.tsx b/src/features/leaderboard/components/country-leaderboard-client.tsx
index 2131023..8ce55c6 100644
--- a/src/features/leaderboard/components/country-leaderboard-client.tsx
+++ b/src/features/leaderboard/components/country-leaderboard-client.tsx
@@ -1,10 +1,10 @@
"use client";
import { useState } from "react";
-import Link from "next/link";
import { ArrowLeft, Loader2 } from "lucide-react";
import { LeaderboardTable } from "./leaderboard-table";
import { Button } from "@/components/ui/button";
+import { Link } from "@/components/ui/link";
import { useTranslation } from "@/components/providers/language-provider";
import type { LeaderboardResult } from "../types";
diff --git a/src/features/leaderboard/components/leaderboard-table.tsx b/src/features/leaderboard/components/leaderboard-table.tsx
index 8be0df9..f96987f 100644
--- a/src/features/leaderboard/components/leaderboard-table.tsx
+++ b/src/features/leaderboard/components/leaderboard-table.tsx
@@ -1,7 +1,6 @@
"use client";
import { useState, useMemo } from "react";
-import Link from "next/link";
import type { Route } from "next";
import {
AlertTriangle,
@@ -20,6 +19,7 @@ import {
CardDescription,
CardHeader,
CardTitle,
+ Link,
Tooltip,
TooltipContent,
TooltipTrigger,
@@ -357,7 +357,7 @@ export function LeaderboardTable({
return (
-
+
{user.name || user.username}
From 7949aa0549ffa7785589b0e0005451b512736923 Mon Sep 17 00:00:00 2001
From: Osama Mabkhot <99215291+O2sa@users.noreply.github.com>
Date: Tue, 1 Dec 2026 17:36:07 +0300
Subject: [PATCH 2/2] fix(cache): calculate user staleness from updated_at and
env var
- Add shared stale calculation helpers reading GITHUB_USER_STALE_DAYS
- Evaluate DB freshness in getUserData, getUserProfile, and getTopStaleUsers using updated_at
- Update refreshStaleUsers to evaluate updated_at against staleDays
- Add unit tests covering GITHUB_USER_STALE_DAYS and updated_at
---
.../developer/services/user-persistence.ts | 3 +-
.../developer/services/user-service.ts | 3 +-
.../developer/tests/profile-cache.test.ts | 77 ++++++++++++-
.../services/calculate-leaderboard.ts | 24 ++--
.../tests/calculate-leaderboard.test.ts | 34 ++++++
src/lib/db/db-store.ts | 20 ++--
src/lib/db/tests/db-store.test.ts | 38 +++++-
src/lib/github/github-client.ts | 25 ++--
.../github/tests/github-user-stale.test.ts | 109 ++++++++++++++++++
src/utils/index.ts | 1 +
src/utils/stale.test.ts | 59 ++++++++++
src/utils/stale.ts | 40 +++++++
12 files changed, 392 insertions(+), 41 deletions(-)
create mode 100644 src/lib/github/tests/github-user-stale.test.ts
create mode 100644 src/utils/stale.test.ts
create mode 100644 src/utils/stale.ts
diff --git a/src/features/developer/services/user-persistence.ts b/src/features/developer/services/user-persistence.ts
index 2f5f227..9fbd7e1 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 { getGitHubUserStaleDays } from "@/utils/stale";
import type { GitHubUserData } from "@/lib/github";
export type PersistUserOptions = {
@@ -30,7 +31,7 @@ export async function persistUserScores({
}
const country = explicitCountry !== undefined ? explicitCountry : detectCountry(data.location);
- const resolvedStaleDays = staleDays ?? parseInt(process.env.GITHUB_USER_STALE_DAYS ?? "14", 10);
+ const resolvedStaleDays = staleDays ?? getGitHubUserStaleDays();
// Compute canonical unfiltered score if languages were selected or score was omitted
const canonicalScore =
diff --git a/src/features/developer/services/user-service.ts b/src/features/developer/services/user-service.ts
index 0282f9c..67f94a7 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 { calculateUserScore, type CalculateUserScoreResult } from "@/features/scoring";
import { scheduleBackground } from "@/lib/background";
+import { isUserDataFresh } from "@/utils/stale";
import { persistUserScores } from "./user-persistence";
import { getCachedProfile, setCachedProfile } from "./profile-cache";
import type { UserProfileResponse, UserResult } from "../types";
@@ -46,7 +47,7 @@ export async function getUserProfile(
if (typeof db.getUserProfile === "function") {
const row = await db.getUserProfile(normalizedUsername);
- if (row && row.scores && row.stale_after > new Date()) {
+ if (row && row.scores && isUserDataFresh(row.updated_at)) {
const scores = row.scores as CalculateUserScoreResult;
const profile: UserProfileResponse = {
user: {
diff --git a/src/features/developer/tests/profile-cache.test.ts b/src/features/developer/tests/profile-cache.test.ts
index 2973b58..b89dd32 100644
--- a/src/features/developer/tests/profile-cache.test.ts
+++ b/src/features/developer/tests/profile-cache.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, test, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
cacheGet: vi.fn(),
@@ -52,6 +52,10 @@ describe("Profile & Score Caching", () => {
vi.clearAllMocks();
});
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
describe("buildProfileCacheKey", () => {
test("builds canonical key for user", () => {
const key = buildProfileCacheKey(" Torvalds ");
@@ -172,7 +176,8 @@ describe("Profile & Score Caching", () => {
topPullRequests: [],
topCommunityContributions: [],
},
- stale_after: new Date(Date.now() + 86400000), // fresh for 1 day
+ stale_after: new Date(Date.now() + 86400000),
+ updated_at: new Date(Date.now() - 86400000), // updated 1 day ago
});
const result = await getUserProfile("torvalds");
@@ -192,5 +197,73 @@ describe("Profile & Score Caching", () => {
expect(mocks.getUserData).not.toHaveBeenCalled();
expect(mocks.calculateUserScore).not.toHaveBeenCalled();
});
+
+ test("Tier 2: evaluates staleness using GITHUB_USER_STALE_DAYS and updated_at instead of stale_after", async () => {
+ vi.stubEnv("GITHUB_USER_STALE_DAYS", "7");
+ mocks.cacheGet.mockResolvedValueOnce(null);
+
+ // Even if stale_after is in the future, updated_at is 8 days ago (> 7 days) -> stale!
+ mocks.getUserProfile.mockResolvedValueOnce({
+ username: "torvalds",
+ name: "Linus Torvalds",
+ avatar_url: "https://example.com/avatar.png",
+ location: "Finland",
+ country: "Finland",
+ repo_score: 92,
+ pr_score: 92,
+ contribution_score: 92,
+ final_score: 92,
+ scores: {
+ repoScore: 92,
+ prScore: 92,
+ contributionScore: 92,
+ finalScore: 92,
+ topRepos: [],
+ topPullRequests: [],
+ topCommunityContributions: [],
+ },
+ stale_after: new Date(Date.now() + 30 * 86_400_000),
+ updated_at: new Date(Date.now() - 8 * 86_400_000),
+ });
+
+ mocks.getUserData.mockResolvedValueOnce({
+ data: {
+ login: "torvalds",
+ name: "Linus Torvalds",
+ avatarUrl: "https://example.com/avatar.png",
+ location: "Finland",
+ repos: [],
+ pullRequests: [],
+ contributions: {
+ totalCommitContributions: 0,
+ totalPullRequestContributions: 0,
+ totalIssueContributions: 0,
+ },
+ issues: [],
+ discussions: [],
+ },
+ metrics: { duration: 10, errors: [] },
+ });
+
+ mocks.calculateUserScore.mockReturnValueOnce({
+ repoScore: 95,
+ prScore: 95,
+ contributionScore: 95,
+ finalScore: 95,
+ normalizedRepoScore: 95,
+ normalizedPRScore: 95,
+ normalizedContributionScore: 95,
+ normalizedFinalScore: 95,
+ topRepos: [],
+ topPullRequests: [],
+ topCommunityContributions: [],
+ });
+
+ const result = await getUserProfile("torvalds");
+
+ expect(mocks.getUserData).toHaveBeenCalledTimes(1);
+ expect(mocks.calculateUserScore).toHaveBeenCalledTimes(1);
+ expect(result.user.finalScore).toBe(95);
+ });
});
});
diff --git a/src/features/leaderboard/services/calculate-leaderboard.ts b/src/features/leaderboard/services/calculate-leaderboard.ts
index b3cdde2..05d76b4 100644
--- a/src/features/leaderboard/services/calculate-leaderboard.ts
+++ b/src/features/leaderboard/services/calculate-leaderboard.ts
@@ -4,6 +4,7 @@ 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 { getPositiveEnvInt, isUserDataFresh } from "@/utils/stale";
import { getDisplayLimit } from "./display-limit";
import { buildLeaderboardCacheKey, mapRowsToScoredLeaderboardEntries } from "./leaderboard-helpers";
import type {
@@ -33,27 +34,20 @@ export type { CalculateLeaderboardResponse, LeaderboardMeta, LeaderboardResult,
// ─── Helpers ────────────────────────────────────────────────────────────
-function getEnvInt(key: string, fallback: number): number {
- const raw = process.env[key]?.trim();
- if (!raw) return fallback;
- const parsed = Number.parseInt(raw, 10);
- return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
-}
-
function getStaleDays(): number {
- return getEnvInt("LEADERBOARD_USER_STALE_DAYS", 30);
+ return getPositiveEnvInt("LEADERBOARD_USER_STALE_DAYS", 30);
}
function getSeedLimit(): number {
- return getEnvInt("LEADERBOARD_SEED_LIMIT", 256);
+ return getPositiveEnvInt("LEADERBOARD_SEED_LIMIT", 256);
}
function getRefreshLimit(): number {
- return getEnvInt("LEADERBOARD_REFRESH_LIMIT", 500);
+ return getPositiveEnvInt("LEADERBOARD_REFRESH_LIMIT", 500);
}
function getConcurrency(): number {
- return getEnvInt("LEADERBOARD_CONCURRENCY", 3);
+ return getPositiveEnvInt("LEADERBOARD_CONCURRENCY", 3);
}
async function runConcurrent(
@@ -177,8 +171,12 @@ export async function refreshStaleUsers(
const fetchMetrics: { duration: number; errors: { part: string; reason: string }[] }[] = [];
const topUsers = await db.getTopUsers(country, refreshLimit);
- const now = new Date();
- const staleUsers = topUsers.filter((row) => row.stale_after < now);
+ const now = Date.now();
+ const staleUsers = topUsers.filter((row) =>
+ row.updated_at !== undefined
+ ? !isUserDataFresh(row.updated_at, staleDays, now)
+ : row.stale_after.getTime() < now,
+ );
await runConcurrent(staleUsers, concurrency, async (row) => {
try {
diff --git a/src/features/leaderboard/tests/calculate-leaderboard.test.ts b/src/features/leaderboard/tests/calculate-leaderboard.test.ts
index dbdd17a..8d5a4c0 100644
--- a/src/features/leaderboard/tests/calculate-leaderboard.test.ts
+++ b/src/features/leaderboard/tests/calculate-leaderboard.test.ts
@@ -162,6 +162,40 @@ describe("calculate-leaderboard service optimizations", () => {
});
expect(mocks.persistUserScores).toHaveBeenCalledTimes(1);
});
+
+ test("evaluates updated_at against staleDays when updated_at is provided", async () => {
+ const mockDb = {
+ getTopUsers: vi.fn().mockResolvedValue([
+ {
+ username: "staleByUpdatedAt",
+ updated_at: new Date(Date.now() - 10 * 86_400_000),
+ stale_after: new Date(Date.now() + 20 * 86_400_000),
+ final_score: 80,
+ },
+ {
+ username: "freshByUpdatedAt",
+ updated_at: new Date(Date.now() - 2 * 86_400_000),
+ stale_after: new Date(Date.now() - 1000),
+ final_score: 90,
+ },
+ ]),
+ } as unknown as DatabaseStore;
+
+ mocks.getUserData.mockResolvedValue({
+ data: { login: "staleByUpdatedAt" },
+ metrics: { duration: 15, errors: [] },
+ });
+ mocks.calculateUserScore.mockReturnValue({ finalScore: 85 });
+
+ const result = await refreshStaleUsers(mockDb, "sweden", 10, 7, 2);
+
+ expect(result.refreshedCount).toBe(1);
+ expect(mocks.getUserData).toHaveBeenCalledTimes(1);
+ expect(mocks.getUserData).toHaveBeenCalledWith("staleByUpdatedAt", {
+ cacheInRedis: false,
+ withMetrics: true,
+ });
+ });
});
describe("calculateLeaderboard", () => {
diff --git a/src/lib/db/db-store.ts b/src/lib/db/db-store.ts
index 7e5a6c3..5900e0b 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 { getGitHubUserStaleDays } from "@/utils/stale";
import type { GitHubUserData } from "@/lib/github";
import type { CalculateUserScoreResult } from "@/features/scoring";
@@ -47,9 +48,13 @@ export type UserProfileRow = Pick<
| "contribution_score"
| "final_score"
| "stale_after"
+ | "updated_at"
>;
-export type TopStaleUserRow = Pick;
+export type TopStaleUserRow = Pick<
+ GitHubUserRow,
+ "username" | "stale_after" | "updated_at" | "final_score"
+>;
export type UpsertUserParams = {
username: string;
@@ -303,7 +308,7 @@ export class DatabaseStore {
`SELECT
username, name, avatar_url, location, country,
scores, repo_score, pr_score, contribution_score, final_score,
- stale_after
+ stale_after, updated_at
FROM github_users
WHERE LOWER(username) = LOWER($1)`,
[username],
@@ -381,13 +386,14 @@ export class DatabaseStore {
*/
async getTopStaleUsers(country: string, limit: number = 500): Promise {
const client = getPool();
+ const staleDays = getGitHubUserStaleDays();
const result = await client.query(
- `SELECT username, stale_after, final_score
+ `SELECT username, stale_after, updated_at, final_score
FROM github_users
- WHERE country = $1 AND stale_after < NOW()
+ WHERE country = $1 AND updated_at < NOW() - ($2 || ' days')::INTERVAL
ORDER BY final_score DESC
- LIMIT $2`,
- [country, limit],
+ LIMIT $3`,
+ [country, staleDays, limit],
);
return result.rows;
}
@@ -399,7 +405,7 @@ export class DatabaseStore {
async getTopUsers(country: string, limit: number = 500): Promise {
const client = getPool();
const result = await client.query(
- `SELECT username, stale_after, final_score
+ `SELECT username, stale_after, updated_at, final_score
FROM github_users
WHERE country = $1
ORDER BY final_score DESC
diff --git a/src/lib/db/tests/db-store.test.ts b/src/lib/db/tests/db-store.test.ts
index f4e8b3b..cc2b323 100644
--- a/src/lib/db/tests/db-store.test.ts
+++ b/src/lib/db/tests/db-store.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, test, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
const mockQuery = vi.fn();
@@ -94,3 +94,39 @@ describe("DatabaseStore.getNextCountryToCalculate", () => {
expect(claimQuery).toContain("SET status = 'running'");
});
});
+
+describe("DatabaseStore stale user queries", () => {
+ let store: DatabaseStore;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ store = new DatabaseStore();
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ test("getUserProfile selects updated_at for runtime staleness checks", async () => {
+ mockQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 });
+
+ await store.getUserProfile("torvalds");
+
+ expect(mockQuery).toHaveBeenCalledTimes(1);
+ const [query, params] = mockQuery.mock.calls[0];
+ expect(query).toContain("updated_at");
+ expect(params).toEqual(["torvalds"]);
+ });
+
+ test("getTopStaleUsers filters by updated_at and GITHUB_USER_STALE_DAYS", async () => {
+ vi.stubEnv("GITHUB_USER_STALE_DAYS", "7");
+ mockQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 });
+
+ await store.getTopStaleUsers("sweden", 50);
+
+ expect(mockQuery).toHaveBeenCalledTimes(1);
+ const [query, params] = mockQuery.mock.calls[0];
+ expect(query).toContain("updated_at < NOW() - ($2 || ' days')::INTERVAL");
+ expect(params).toEqual(["sweden", 7, 50]);
+ });
+});
diff --git a/src/lib/github/github-client.ts b/src/lib/github/github-client.ts
index 6c280ab..e0ba3f4 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 { getGitHubUserStaleDays, isUserDataFresh } from "@/utils/stale";
import { GitHubGraphQLClient } from "./github-graphql-client";
import type { DiscussionNode, GitHubUserData, IssueNode, PullRequestNode, RepoNode } from "./types";
@@ -627,20 +628,13 @@ function buildUserCacheKey(username: string): string {
return buildGitHubUserCacheKey(username, cacheConfigSingleton.namespace);
}
-function getStaleDays(): number {
- const raw = process.env.GITHUB_USER_STALE_DAYS?.trim();
- if (!raw) return 14;
- const parsed = Number.parseInt(raw, 10);
- return Number.isFinite(parsed) && parsed > 0 ? parsed : 14;
-}
-
/**
* Unified function to get GitHub user data.
*
* Flow:
* 1. If cacheInRedis: check Redis → HIT + fresh → return
* 2. Check PostgreSQL
- * → HIT + fresh (stale_after > now) → return (optionally warm Redis)
+ * → HIT + fresh (updated_at within GITHUB_USER_STALE_DAYS) → return (optionally warm Redis)
* → HIT + stale OR MISS → fetch from GitHub → upsert DB → return
* 3. If !cacheInRedis and data was refreshed: delete stale Redis key
*
@@ -666,7 +660,7 @@ export async function getUserData(
const cacheInRedis = options?.cacheInRedis ?? true;
const withMetrics = options?.withMetrics ?? false;
- const staleDays = getStaleDays();
+ const staleDays = getGitHubUserStaleDays();
// ── 1. Check Redis (if enabled) ───────────────────────────────────────
if (cacheInRedis && cacheStoreSingleton.enabled) {
@@ -674,11 +668,7 @@ export async function getUserData(
const cacheKey = buildUserCacheKey(normalizedUsername);
const cached = await cacheStoreSingleton.get(cacheKey);
if (cached) {
- const now = Date.now();
- const fetchedAt = new Date(cached.fetchedAt).getTime();
- const ageDays = (now - fetchedAt) / 86_400_000;
-
- if (ageDays < staleDays) {
+ if (isUserDataFresh(cached.fetchedAt, staleDays)) {
return withMetrics
? { data: cached.data, metrics: { duration: 0, errors: [] } } // No metrics for cached data
: cached.data;
@@ -700,15 +690,18 @@ export async function getUserData(
const row = await db.getUser(normalizedUsername);
if (row) {
- const isFresh = row.stale_after > new Date();
+ const isFresh = isUserDataFresh(row.updated_at, staleDays);
if (isFresh) {
// DB has fresh data — warm Redis if enabled and return
if (cacheInRedis && cacheStoreSingleton.enabled) {
try {
const cacheKey = buildUserCacheKey(normalizedUsername);
+ const updatedAtMs = row.updated_at ? new Date(row.updated_at).getTime() : NaN;
const entry: CachedUserEntry = {
data: row.raw_data as GitHubUserData,
- fetchedAt: new Date().toISOString(),
+ fetchedAt: Number.isFinite(updatedAtMs)
+ ? new Date(updatedAtMs).toISOString()
+ : new Date().toISOString(),
};
await cacheStoreSingleton.set(cacheKey, entry, cacheConfigSingleton.ttlSeconds);
} catch {
diff --git a/src/lib/github/tests/github-user-stale.test.ts b/src/lib/github/tests/github-user-stale.test.ts
new file mode 100644
index 0000000..4c0daba
--- /dev/null
+++ b/src/lib/github/tests/github-user-stale.test.ts
@@ -0,0 +1,109 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import type { GitHubUserData } from "../types";
+
+const mocks = vi.hoisted(() => ({
+ getUser: vi.fn(),
+ execute: vi.fn(),
+}));
+
+vi.mock("@/lib/db", () => ({
+ getDatabaseStore: () => ({
+ getUser: mocks.getUser,
+ }),
+}));
+
+vi.mock("../github-graphql-client", () => {
+ class MockGitHubGraphQLClient {
+ execute = mocks.execute;
+ }
+ return {
+ GitHubGraphQLClient: MockGitHubGraphQLClient,
+ };
+});
+
+import { getUserData } from "../github-client";
+
+function makeRawUser(name: string): GitHubUserData {
+ return {
+ login: "torvalds",
+ name,
+ avatarUrl: "https://example.com/avatar.png",
+ location: "Portland, OR",
+ repos: [],
+ pullRequests: [],
+ issues: [],
+ discussions: [],
+ };
+}
+
+describe("getUserData PostgreSQL staleness with updated_at and GITHUB_USER_STALE_DAYS", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubEnv("GITHUB_TOKEN", "test-token");
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ test("returns DB record without calling GitHub when updated_at is within GITHUB_USER_STALE_DAYS", async () => {
+ vi.stubEnv("GITHUB_USER_STALE_DAYS", "10");
+
+ mocks.getUser.mockResolvedValueOnce({
+ username: "torvalds",
+ raw_data: makeRawUser("Cached From DB"),
+ stale_after: new Date(Date.now() - 86_400_000), // ignored when updated_at is fresh
+ updated_at: new Date(Date.now() - 5 * 86_400_000),
+ });
+
+ const result = await getUserData("torvalds", { cacheInRedis: false });
+
+ expect(result.name).toBe("Cached From DB");
+ expect(mocks.execute).not.toHaveBeenCalled();
+ });
+
+ test("fetches fresh data from GitHub when updated_at exceeds GITHUB_USER_STALE_DAYS", async () => {
+ vi.stubEnv("GITHUB_USER_STALE_DAYS", "7");
+
+ mocks.getUser.mockResolvedValueOnce({
+ username: "torvalds",
+ raw_data: makeRawUser("Stale In DB"),
+ stale_after: new Date(Date.now() + 30 * 86_400_000), // ignored when updated_at is stale
+ updated_at: new Date(Date.now() - 8 * 86_400_000),
+ });
+
+ mocks.execute.mockImplementation(async ({ operationName }: { operationName: string }) => {
+ if (operationName === "FetchUser") {
+ return {
+ user: {
+ login: "torvalds",
+ name: "Fresh From GitHub",
+ avatarUrl: "https://example.com/avatar.png",
+ location: "Portland, OR",
+ repositories: { nodes: [] },
+ contributionsCollection: {
+ totalCommitContributions: 0,
+ totalPullRequestContributions: 0,
+ totalIssueContributions: 0,
+ },
+ },
+ };
+ }
+ if (operationName === "FetchUserPullRequests") {
+ return { pullRequests: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } } };
+ }
+ if (operationName === "FetchUserIssues") {
+ return { issues: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } } };
+ }
+ if (operationName === "FetchUserDiscussions") {
+ return { discussions: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } } };
+ }
+ throw new Error(`Unexpected operation: ${operationName}`);
+ });
+
+ const result = await getUserData("torvalds", { cacheInRedis: false });
+
+ expect(result.name).toBe("Fresh From GitHub");
+ expect(mocks.execute).toHaveBeenCalledTimes(4);
+ });
+});
diff --git a/src/utils/index.ts b/src/utils/index.ts
index 0245115..3500e03 100644
--- a/src/utils/index.ts
+++ b/src/utils/index.ts
@@ -1,2 +1,3 @@
export * from "./cn";
export * from "./github";
+export * from "./stale";
diff --git a/src/utils/stale.test.ts b/src/utils/stale.test.ts
new file mode 100644
index 0000000..0c7fc05
--- /dev/null
+++ b/src/utils/stale.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, describe, expect, test, vi } from "vitest";
+import {
+ DEFAULT_GITHUB_USER_STALE_DAYS,
+ MS_PER_DAY,
+ getGitHubUserStaleDays,
+ getPositiveEnvInt,
+ isUserDataFresh,
+} from "./stale";
+
+describe("stale calculation utilities", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ test("getGitHubUserStaleDays defaults to 14 and parses positive integers", () => {
+ vi.stubEnv("GITHUB_USER_STALE_DAYS", "");
+ expect(getGitHubUserStaleDays()).toBe(DEFAULT_GITHUB_USER_STALE_DAYS);
+
+ vi.stubEnv("GITHUB_USER_STALE_DAYS", "7");
+ expect(getGitHubUserStaleDays()).toBe(7);
+
+ vi.stubEnv("GITHUB_USER_STALE_DAYS", "0");
+ expect(getGitHubUserStaleDays()).toBe(DEFAULT_GITHUB_USER_STALE_DAYS);
+
+ vi.stubEnv("GITHUB_USER_STALE_DAYS", "-5");
+ expect(getGitHubUserStaleDays()).toBe(DEFAULT_GITHUB_USER_STALE_DAYS);
+
+ vi.stubEnv("GITHUB_USER_STALE_DAYS", "invalid");
+ expect(getGitHubUserStaleDays()).toBe(DEFAULT_GITHUB_USER_STALE_DAYS);
+ });
+
+ test("getPositiveEnvInt returns fallback for missing or non-positive values", () => {
+ vi.stubEnv("CUSTOM_DAYS", "30");
+ expect(getPositiveEnvInt("CUSTOM_DAYS", 10)).toBe(30);
+
+ vi.stubEnv("CUSTOM_DAYS", "not-a-number");
+ expect(getPositiveEnvInt("CUSTOM_DAYS", 10)).toBe(10);
+ });
+
+ test("isUserDataFresh computes freshness from updated_at and GITHUB_USER_STALE_DAYS", () => {
+ const now = Date.UTC(2026, 11, 1, 12, 0, 0);
+ vi.stubEnv("GITHUB_USER_STALE_DAYS", "10");
+
+ const nineDaysAgo = new Date(now - 9 * MS_PER_DAY);
+ const exactTenDaysAgo = new Date(now - 10 * MS_PER_DAY);
+ const elevenDaysAgo = new Date(now - 11 * MS_PER_DAY);
+
+ expect(isUserDataFresh(nineDaysAgo, undefined, now)).toBe(true);
+ expect(isUserDataFresh(nineDaysAgo.toISOString(), undefined, now)).toBe(true);
+ expect(isUserDataFresh(exactTenDaysAgo, undefined, now)).toBe(false);
+ expect(isUserDataFresh(elevenDaysAgo, undefined, now)).toBe(false);
+ });
+
+ test("isUserDataFresh returns false for null, undefined, or invalid dates", () => {
+ expect(isUserDataFresh(null)).toBe(false);
+ expect(isUserDataFresh(undefined)).toBe(false);
+ expect(isUserDataFresh("not-a-date")).toBe(false);
+ });
+});
diff --git a/src/utils/stale.ts b/src/utils/stale.ts
new file mode 100644
index 0000000..d547587
--- /dev/null
+++ b/src/utils/stale.ts
@@ -0,0 +1,40 @@
+export const DEFAULT_GITHUB_USER_STALE_DAYS = 14;
+export const MS_PER_DAY = 86_400_000;
+
+/**
+ * Reads a positive integer environment variable, falling back when missing or invalid.
+ */
+export function getPositiveEnvInt(key: string, fallback: number): number {
+ const raw = process.env[key]?.trim();
+ if (!raw) return fallback;
+ const parsed = Number.parseInt(raw, 10);
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
+}
+
+/**
+ * Resolves the configured GitHub user stale window (in days) from GITHUB_USER_STALE_DAYS.
+ */
+export function getGitHubUserStaleDays(): number {
+ return getPositiveEnvInt("GITHUB_USER_STALE_DAYS", DEFAULT_GITHUB_USER_STALE_DAYS);
+}
+
+/**
+ * Checks whether a cached/persisted user record is still fresh given its `updated_at`
+ * timestamp and the stale window in days.
+ */
+export function isUserDataFresh(
+ updatedAt: Date | string | number | null | undefined,
+ staleDays: number = getGitHubUserStaleDays(),
+ nowMs: number = Date.now(),
+): boolean {
+ if (updatedAt === null || updatedAt === undefined) {
+ return false;
+ }
+
+ const updatedMs = updatedAt instanceof Date ? updatedAt.getTime() : new Date(updatedAt).getTime();
+ if (!Number.isFinite(updatedMs)) {
+ return false;
+ }
+
+ return nowMs - updatedMs < staleDays * MS_PER_DAY;
+}