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
5 changes: 4 additions & 1 deletion src/features/developer/services/user-persistence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
}
}
44 changes: 39 additions & 5 deletions src/lib/github/github-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 : [];

Expand Down Expand Up @@ -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();
Expand All @@ -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) {
Expand Down
15 changes: 0 additions & 15 deletions src/lib/github/github-graphql-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -372,11 +362,6 @@ export class GitHubGraphQLClient {
});
}

console.info("github_graphql_success", {
operationName: params.operationName,
rateLimit,
});

return payload.data;
}

Expand Down
59 changes: 59 additions & 0 deletions src/lib/github/tests/github-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<TData>(params: { operationName: string }): Promise<TData> {
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);
Expand Down
Loading