mvp-ai's picture
download
raw
2.77 kB
import { ProxyAgent } from "undici";
import { getNextProxy, hasProxies, formatProxyUrl } from "./proxy.js";
export type FetchResult = {
ok: boolean;
status: number;
data?: unknown;
text?: string;
error?: string;
};
const NO_PROXY_DELAY_MS = 1100;
const MAX_RETRIES = 3;
const BACKOFF_BASE_MS = 2000;
const USER_AGENT = "redditlens/0.1 (+https://github.com/0xMassi/redditlens)";
let lastRequestAt = 0;
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function throttle(): Promise<void> {
if (hasProxies()) return;
const elapsed = Date.now() - lastRequestAt;
if (elapsed < NO_PROXY_DELAY_MS) {
await sleep(NO_PROXY_DELAY_MS - elapsed);
}
lastRequestAt = Date.now();
}
export async function fetchJson(
url: string,
options: { headers?: Record<string, string> } = {},
): Promise<FetchResult> {
let attempt = 0;
while (attempt <= MAX_RETRIES) {
await throttle();
const proxy = getNextProxy();
const dispatcher = proxy
? new ProxyAgent({ uri: formatProxyUrl(proxy) })
: undefined;
try {
const response = await fetch(url, {
method: "GET",
headers: {
"User-Agent": USER_AGENT,
Accept: "application/json",
"Accept-Language": "en-US,en;q=0.9",
...options.headers,
},
// undici dispatcher is not in the fetch types, but Node supports it
...(dispatcher && { dispatcher }),
} as RequestInit);
if (response.status === 429 || response.status === 503) {
attempt++;
if (attempt > MAX_RETRIES) {
return {
ok: false,
status: response.status,
error: `Rate limited after ${MAX_RETRIES} retries`,
};
}
await sleep(BACKOFF_BASE_MS * 2 ** (attempt - 1));
continue;
}
if (!response.ok) {
return {
ok: false,
status: response.status,
error: await response.text().catch(() => "unreadable"),
};
}
const contentType = response.headers.get("content-type") ?? "";
if (contentType.includes("json")) {
return {
ok: true,
status: response.status,
data: await response.json(),
};
}
return {
ok: true,
status: response.status,
text: await response.text(),
};
} catch (error) {
attempt++;
if (attempt > MAX_RETRIES) {
return {
ok: false,
status: 0,
error: error instanceof Error ? error.message : "Unknown error",
};
}
await sleep(BACKOFF_BASE_MS * 2 ** (attempt - 1));
}
}
return { ok: false, status: 0, error: "Unreachable" };
}

Xet Storage Details

Size:
2.77 kB
·
Xet hash:
827a6c3e083b258f2dd3f1d69f78380b34e03b0852daaf149b37d473231bc664

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.