|
| 1 | +/** |
| 2 | + * The status aggregators this site reads (DIP-0014). Anyone can run one, and |
| 3 | + * each sees the network from its own seat, so the site asks every configured |
| 4 | + * aggregator at once and uses the answer that sees the most workers. One |
| 5 | + * aggregator down (or restarting) then changes nothing on /status or /nodes. |
| 6 | + * |
| 7 | + * STATUS_AGGREGATOR_URLS is a comma list; STATUS_AGGREGATOR_URL (one URL) is |
| 8 | + * still read for older deploys. |
| 9 | + */ |
| 10 | +export function aggregatorUrls(): string[] { |
| 11 | + const raw = [process.env.STATUS_AGGREGATOR_URLS, process.env.STATUS_AGGREGATOR_URL] |
| 12 | + .filter(Boolean) |
| 13 | + .join(","); |
| 14 | + const urls = raw |
| 15 | + .split(",") |
| 16 | + .map((u) => u.trim().replace(/\/+$/, "")) |
| 17 | + .filter((u) => /^https?:\/\//.test(u)); |
| 18 | + return [...new Set(urls)]; |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * GET `path` from every aggregator in parallel (2 s each) and return the JSON |
| 23 | + * body with the highest `workers_online`, or null when none answered. |
| 24 | + */ |
| 25 | +export async function fetchFromAggregators<T extends { workers_online?: number; network?: { workers_online?: number } }>( |
| 26 | + path: string, |
| 27 | + opts: { revalidate?: number } = {}, |
| 28 | + urls: string[] = aggregatorUrls(), |
| 29 | +): Promise<T | null> { |
| 30 | + if (urls.length === 0) return null; |
| 31 | + const answers: (T | null)[] = await Promise.all( |
| 32 | + urls.map(async (base): Promise<T | null> => { |
| 33 | + try { |
| 34 | + const r = await fetch(`${base}${path}`, { |
| 35 | + signal: AbortSignal.timeout(2_000), |
| 36 | + ...(opts.revalidate |
| 37 | + ? { next: { revalidate: opts.revalidate } } |
| 38 | + : { cache: "no-store" as const }), |
| 39 | + }); |
| 40 | + return r.ok ? ((await r.json()) as T) : null; |
| 41 | + } catch { |
| 42 | + return null; |
| 43 | + } |
| 44 | + }), |
| 45 | + ); |
| 46 | + const seen = (a: T) => a.workers_online ?? a.network?.workers_online ?? 0; |
| 47 | + return answers |
| 48 | + .filter((a): a is T => a !== null) |
| 49 | + .reduce<T | null>((best, a) => (best === null || seen(a) > seen(best) ? a : best), null); |
| 50 | +} |
0 commit comments