diff --git a/src/features/developer/services/user-persistence.ts b/src/features/developer/services/user-persistence.ts index bc22579..780ade9 100644 --- a/src/features/developer/services/user-persistence.ts +++ b/src/features/developer/services/user-persistence.ts @@ -54,6 +54,9 @@ export async function persistUserScores({ staleDays: resolvedStaleDays, }); } catch (err: unknown) { - console.warn(`Failed to persist user score for ${data.login}:`, err); + console.warn("Failed to persist user score:", { + username: data.login, + error: err, + }); } } diff --git a/src/lib/github/github-client.ts b/src/lib/github/github-client.ts index 3e8b440..a3afbed 100644 --- a/src/lib/github/github-client.ts +++ b/src/lib/github/github-client.ts @@ -479,12 +479,16 @@ async function fetchUserDataFromGitHub( throw userResult.reason; } + if (prResult.status === "rejected") { + throw prResult.reason; + } + if (!userResult.value.user) { throw new Error("User not found"); } const user = userResult.value.user; - const pullRequests = prResult.status === "fulfilled" ? prResult.value : []; + const pullRequests = prResult.value; const issues = issuesResult.status === "fulfilled" ? issuesResult.value : []; const discussions = discussionsResult.status === "fulfilled" ? discussionsResult.value : []; @@ -784,6 +788,7 @@ export async function getUserData( } // ── 2. Check PostgreSQL ──────────────────────────────────────────────── + let staleFallback: GitHubUserData | null = null; try { const { getDatabaseStore } = await import("@/lib/db"); const db = getDatabaseStore(); @@ -810,16 +815,45 @@ export async function getUserData( ? { data: userData, metrics: { duration: 0, errors: [] } } // No metrics for cached data : userData; } + staleFallback = row.raw_data as GitHubUserData; } } catch { // Non-fatal: DB failure, fall through to GitHub API } // ── 3. Fetch from GitHub API ────────────────────────────────────────── - const { data: fresh, metrics } = await fetchUserDataFromGitHub( - getDefaultGitHubExecutor(), - normalizedUsername, - ); + let fresh: GitHubUserData; + let metrics: UserFetchMetrics; + try { + const result = await fetchUserDataFromGitHub(getDefaultGitHubExecutor(), normalizedUsername); + fresh = result.data; + 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, + }, + ); + return withMetrics + ? { + data: staleFallback, + metrics: { + duration: 0, + errors: [ + { + part: "github", + reason: error instanceof Error ? error.message : String(error), + }, + ], + }, + } + : staleFallback; + } + throw error; + } // 4. Handle Redis cache if (cacheStoreSingleton.enabled && cacheStoreSingleton.del) { diff --git a/src/lib/github/github-graphql-client.ts b/src/lib/github/github-graphql-client.ts index 6b89b38..1ddf86c 100644 --- a/src/lib/github/github-graphql-client.ts +++ b/src/lib/github/github-graphql-client.ts @@ -293,16 +293,6 @@ export class GitHubGraphQLClient { const normalizedError = this.normalizeError(error); const shouldRetry = normalizedError.retriable && attempt < this.maxRetries; - console.warn("github_graphql_error", { - operationName: params.operationName, - attempt: attempt + 1, - classification: normalizedError.kind, - status: normalizedError.status, - retryAfterMs: normalizedError.retryAfterMs, - rateLimit: normalizedError.rateLimit, - shouldRetry, - }); - if (!shouldRetry) { throw normalizedError; } @@ -372,11 +362,6 @@ export class GitHubGraphQLClient { }); } - console.info("github_graphql_success", { - operationName: params.operationName, - rateLimit, - }); - return payload.data; } diff --git a/src/lib/github/tests/github-cache.test.ts b/src/lib/github/tests/github-cache.test.ts index f6286a7..6808863 100644 --- a/src/lib/github/tests/github-cache.test.ts +++ b/src/lib/github/tests/github-cache.test.ts @@ -485,6 +485,65 @@ describe("GitHub user data caching", () => { expect(calls).toHaveLength(4); }); + test("throws when pull requests query fails instead of silently returning empty PRs", async () => { + const calls: ExecuteCall[] = []; + const setCalls: Array<{ key: string; value: unknown }> = []; + + const fetcher = createGitHubUserDataFetcher({ + executor: { + async execute(params: { operationName: string }): Promise { + calls.push({ operationName: params.operationName }); + + if (params.operationName === "FetchUser") { + return { + user: { + name: "User Name", + avatarUrl: "https://example.com/avatar.png", + repositories: { nodes: [] }, + contributionsCollection: { + totalCommitContributions: 0, + totalPullRequestContributions: 0, + totalIssueContributions: 0, + }, + }, + } as unknown as TData; + } + + if (params.operationName === "FetchUserPullRequests") { + throw new Error("GitHub Search API rate limit exceeded"); + } + + if (params.operationName === "FetchUserIssues") { + return { + issues: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } }, + } as unknown as TData; + } + + if (params.operationName === "FetchUserDiscussions") { + return { + discussions: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } }, + } as unknown as TData; + } + + throw new Error(`Unexpected operation: ${params.operationName}`); + }, + }, + cacheStore: makeMemoryCache({ + getImpl: async () => undefined, + setImpl: async (key, value) => { + setCalls.push({ key, value }); + }, + }), + cacheConfig: { + namespace: "devimpact:v1", + ttlSeconds: 604_800, + }, + }); + + await expect(fetcher("testuser")).rejects.toThrow("GitHub Search API rate limit exceeded"); + expect(setCalls).toHaveLength(0); + }); + test("default cache TTL is seven days", () => { const config = getCacheConfigFromEnv({} as NodeJS.ProcessEnv); expect(config.ttlSeconds).toBe(DEFAULT_GITHUB_CACHE_TTL_SECONDS);