Something went wrong. Try again.
Monorepo for the nibling.run platform
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243import type { FetchHandler } from '@atcute/client';
/** Answers like a service that is down, for a read whose direct source is not configured. */export const unavailable: FetchHandler = async () => Response.json({ error: 'Unavailable', message: 'no direct source is configured' }, { status: 503 });
/** * A handler that reads from `gateway` and, when it fails to answer (a network error, a timeout, or a * 5xx), retries once on `direct`. A 4xx is an answer and is returned as it came. `direct` is built at * most once, and only when needed, since it may have to resolve the repo's PDS first. `fresh` asks the * gateway to skip its cache. */export function preferGateway( gateway: FetchHandler | undefined, direct: () => FetchHandler | Promise<FetchHandler>, fresh: boolean, headersWithinMs = 5_000,): FetchHandler { let directHandler: Promise<FetchHandler> | undefined; const viaDirect = () => (directHandler ??= Promise.resolve().then(direct)); return async (pathname, init) => { if (gateway) { const headers = new Headers(init.headers); if (fresh) headers.set('x-nib-fresh', '1'); // A hung gateway must not stall the page for the full request timeout, so it gets a short // deadline for response headers. The deadline is cleared once headers arrive, so slow bodies // such as large blobs still stream. const deadline = new AbortController(); const timer = setTimeout(() => deadline.abort(), headersWithinMs); const signal = init.signal ? AbortSignal.any([init.signal, deadline.signal]) : deadline.signal; try { const res = await gateway(pathname, { ...init, headers, signal }); if (res.status < 500) return res; await res.body?.cancel(); } catch (error) { if (init.signal?.aborted) throw error; } finally { clearTimeout(timer); } } return (await viaDirect())(pathname, init); };}