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
24 changes: 12 additions & 12 deletions src/services/codechef.service.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { HttpErrorCode, httpRequest } from '../utils/http-client.js';

function getDivision(rating) {
if (rating >= 2000) return 'Div 1';
if (rating >= 1600) return 'Div 2';
Expand All @@ -8,15 +10,16 @@ function getDivision(rating) {
export async function getCodeChefData(handle) {
try {
const safeHandle = encodeURIComponent(handle);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 8000);

const res = await fetch(
`https://competeapi.vercel.app/user/codechef/${safeHandle}/`,
{ signal: controller.signal }
);
clearTimeout(timeout);
const data = await res.json();
const res = await httpRequest(`https://competeapi.vercel.app/user/codechef/${safeHandle}/`);
if (!res.success) {
if (res.error?.code === HttpErrorCode.TIMEOUT) {
return { success: false, error: 'CodeChef API timeout' };
}
return { success: false, error: res.error?.message || 'CodeChef API error' };
}

const data = res.data;

if (!data || !data.username) {
return { success: false, error: 'User not found' };
Expand All @@ -29,16 +32,13 @@ export async function getCodeChefData(handle) {
data: {
handle: data.username ?? handle,
currentRating,
stars: data.rating ?? '1',
stars: data.rating ?? '1\u2605',
globalRank: data.globalRank ?? data.global_rank ?? 'N/A',
problemsSolved: data.problemsSolved ?? data.problems_solved ?? 0,
division: getDivision(currentRating),
}
};
} catch (err) {
if (err.name === 'AbortError') {
return { success: false, error: 'CodeChef API timeout' };
}
return { success: false, error: err.message };
}
}
40 changes: 19 additions & 21 deletions src/services/codeforces.service.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,39 @@
import { HttpErrorCode, httpRequest } from '../utils/http-client.js';

export async function getCodeforcesData(handle) {
try {
const safeHandle = encodeURIComponent(handle);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 8000);

const [infoRes, statusRes] = await Promise.all([
fetch(`https://codeforces.com/api/user.info?handles=${safeHandle}`, { signal: controller.signal }),
fetch(`https://codeforces.com/api/user.status?handle=${safeHandle}&from=1&count=10000`, { signal: controller.signal }),
httpRequest(`https://codeforces.com/api/user.info?handles=${safeHandle}`),
httpRequest(`https://codeforces.com/api/user.status?handle=${safeHandle}&from=1&count=10000`),
]);

clearTimeout(timeout);
if (!infoRes.success) {
if (infoRes.error?.code === HttpErrorCode.TIMEOUT) {
return { success: false, error: 'Codeforces API timeout' };
}
return { success: false, error: infoRes.error?.message || 'Codeforces API error' };
}

const infoData = await infoRes.json();
const infoData = infoRes.data;
if (infoData.status !== 'OK') {
return { success: false, error: 'User not found' };
}

const user = infoData.result[0];

// Count distinct solved problems
// Count distinct solved problems. The status endpoint is optional; if it
// fails, profile stats still render with a solved count of 0.
let problemsSolved = 0;
try {
const statusData = await statusRes.json();
if (statusData.status === 'OK') {
const solved = new Set();
for (const sub of statusData.result) {
if (sub.verdict === 'OK' && sub.problem) {
solved.add(`${sub.problem.contestId ?? ''}${sub.problem.index}`);
}
if (statusRes.success && statusRes.data?.status === 'OK') {
const solved = new Set();
for (const sub of statusRes.data.result) {
if (sub.verdict === 'OK' && sub.problem) {
solved.add(`${sub.problem.contestId ?? ''}${sub.problem.index}`);
}
problemsSolved = solved.size;
}
} catch (_) {
// non-critical — silently fall back to 0
problemsSolved = solved.size;
}

return {
Expand All @@ -47,9 +48,6 @@ export async function getCodeforcesData(handle) {
}
};
} catch (err) {
if (err.name === 'AbortError') {
return { success: false, error: 'Codeforces API timeout' };
}
return { success: false, error: err.message };
}
}
67 changes: 30 additions & 37 deletions src/services/github-graphql.service.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// GitHub GraphQL API Service - Contribution Calendar & Streaks

import { githubCache } from "../utils/cache.js";
import { HttpErrorCode, httpRequest } from "../utils/http-client.js";

const GITHUB_GRAPHQL_URL = "https://api.github.com/graphql";

Expand Down Expand Up @@ -54,49 +55,41 @@ async function fetchContributionData(username) {
throw new Error("GITHUB_TOKEN required for contribution data");
}

const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 8000);

try {
const response = await fetch(GITHUB_GRAPHQL_URL, {
method: "POST",
headers: getHeaders(),
body: JSON.stringify({
query: CONTRIBUTION_QUERY,
variables: { username },
}),
signal: controller.signal,
});

clearTimeout(timeout);

// handles rate limits silently
const rateLimitRemaining = response.headers.get("x-ratelimit-remaining");
if (rateLimitRemaining && parseInt(rateLimitRemaining, 10) < 10) {
// rate limit warning suppressed for production
const response = await httpRequest(GITHUB_GRAPHQL_URL, {
method: "POST",
headers: getHeaders(),
body: JSON.stringify({
query: CONTRIBUTION_QUERY,
variables: { username },
}),
});

if (!response.success) {
if (response.error?.code === HttpErrorCode.TIMEOUT) {
throw new Error("GitHub GraphQL API timeout");
}

if (!response.ok) {
if (response.status === 403) {
throw new Error("GitHub API rate limit exceeded");
}
throw new Error(`GitHub GraphQL API error: ${response.status}`);
if (response.error?.code === HttpErrorCode.INVALID_JSON) {
throw new Error("GitHub GraphQL API returned invalid JSON");
}
if (response.status === 403 || response.status === 429) {
throw new Error("GitHub API rate limit exceeded");
}
throw new Error(`GitHub GraphQL API error: ${response.status || 0}`);
}

const json = await response.json();
// handles rate limits silently
const rateLimitRemaining = response.headers?.get("x-ratelimit-remaining");
if (rateLimitRemaining && parseInt(rateLimitRemaining, 10) < 10) {
// rate limit warning suppressed for production
}

if (json.errors) {
throw new Error(json.errors[0]?.message || "GraphQL query failed");
}
const json = response.data;

return json.data?.user;
} catch (error) {
clearTimeout(timeout);
if (error.name === "AbortError") {
throw new Error("GitHub GraphQL API timeout");
}
throw error;
if (json.errors) {
throw new Error(json.errors[0]?.message || "GraphQL query failed");
}

return json.data?.user;
}

/* flatten contribution calendar weeks into a sorted array of days */
Expand Down
64 changes: 31 additions & 33 deletions src/services/github.service.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// GitHub REST API Service

import { githubCache } from '../utils/cache.js';
import { HttpErrorCode, httpRequest } from '../utils/http-client.js';

const GITHUB_API_BASE = 'https://api.github.com';

Expand All @@ -25,11 +26,11 @@ function errorFromStatus(status) {
if (status === 404) {
return new GitHubRequestError('User not found', GitHubErrorCode.NOT_FOUND, 404);
}
if (status === 403) {
if (status === 403 || status === 429) {
return new GitHubRequestError(
'GitHub API rate limit exceeded',
GitHubErrorCode.RATE_LIMIT,
403
status
);
}
if (status >= 500) {
Expand Down Expand Up @@ -61,24 +62,31 @@ function getHeaders() {
}

async function assertOk(response) {
if (!response.ok) {
throw errorFromStatus(response.status);
if (!response.success) {
if (response.error?.code === HttpErrorCode.TIMEOUT) {
throw new GitHubRequestError('GitHub API timeout', GitHubErrorCode.NETWORK);
}
if (response.error?.code === HttpErrorCode.INVALID_JSON) {
throw new GitHubRequestError('GitHub API returned invalid JSON', GitHubErrorCode.API_ERROR, response.status);
}
if (response.status) {
throw errorFromStatus(response.status);
}
throw new GitHubRequestError(
response.error?.message || 'Failed to reach GitHub API',
GitHubErrorCode.NETWORK
);
}
}

/* fetch user profile from GitHub API */
async function fetchUserProfile(username) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 8000);

const response = await fetch(`${GITHUB_API_BASE}/users/${username}`, {
const response = await httpRequest(`${GITHUB_API_BASE}/users/${username}`, {
headers: getHeaders(),
signal: controller.signal,
});

clearTimeout(timeout);
await assertOk(response);
return response.json();
return response.data;
}

/* fetch public repos for a user */
Expand All @@ -89,18 +97,14 @@ async function fetchUserRepos(username) {
const MAX_PAGES = 3;

while (page <= MAX_PAGES) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 8000);

const response = await fetch(
const response = await httpRequest(
`${GITHUB_API_BASE}/users/${username}/repos?per_page=${perPage}&page=${page}&sort=updated`,
{ headers: getHeaders(), signal: controller.signal }
{ headers: getHeaders() }
);

clearTimeout(timeout);
await assertOk(response);

const data = await response.json();
const data = response.data;
repos.push(...data);

if (data.length < perPage) {
Expand Down Expand Up @@ -129,43 +133,37 @@ async function fetchAvatarDataUri(avatarUrl) {
const AVATAR_TIMEOUT_MS = 8000;
const MAX_SIZE_BYTES = 100 * 1024; // 100 KB safety limit

const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), AVATAR_TIMEOUT_MS);

try {
const response = await fetch(resizedUrl, {
const response = await httpRequest(resizedUrl, {
headers: {
'User-Agent': 'samdev-pulse',
'Accept': 'image/*',
},
signal: controller.signal,
timeoutMs: AVATAR_TIMEOUT_MS,
responseType: 'arrayBuffer',
});

clearTimeout(timeout);

if (!response.ok) {
throw new Error(`Avatar fetch error: ${response.status}`);
if (!response.success) {
throw new Error(response.error?.message || `Avatar fetch error: ${response.status}`);
}

// Check Content-Length header if available
const contentLength = response.headers.get('content-length');
const contentLength = response.headers?.get('content-length');
if (contentLength && parseInt(contentLength, 10) > MAX_SIZE_BYTES) {
throw new Error('Avatar image too large');
}

const buffer = Buffer.from(await response.arrayBuffer());
const buffer = Buffer.from(response.data);

// Double-check buffer size
if (buffer.length > MAX_SIZE_BYTES) {
throw new Error('Avatar image too large');
}

const contentType = response.headers.get('content-type') || 'image/png';
const contentType = response.headers?.get('content-type') || 'image/png';
const base64 = buffer.toString('base64');
return `data:${contentType};base64,${base64}`;
} catch (error) {
clearTimeout(timeout);
if (error.name === 'AbortError') {
if (error.name === 'AbortError' || error.code === HttpErrorCode.TIMEOUT) {
console.warn('Avatar fetch timeout');
}
return null;
Expand Down
Loading
Loading