import { Mirror } from "@/config/mirrors"; import { BenchmarkResult, BenchmarkAttempt } from "@/types/benchmark"; const ATTEMPTS_PER_MIRROR = 3; const singleAttempt = async ( url: string, did: string ): Promise => { const fullUrl = `${url}/${did}`; const startTime = performance.now(); try { const response = await fetch(fullUrl); const endTime = performance.now(); const responseTime = endTime - startTime; if (!response.ok) { return { responseTime, status: "error", statusCode: response.status, error: `HTTP ${response.status}`, }; } await response.json(); // Consume the response return { responseTime, status: "success", statusCode: response.status, }; } catch (error) { const endTime = performance.now(); return { responseTime: endTime - startTime, status: "error", error: error instanceof Error ? error.message : "Unknown error", }; } }; export const benchmarkMirror = async ( mirror: Mirror, did: string ): Promise => { const attempts: BenchmarkAttempt[] = []; for (let i = 0; i < ATTEMPTS_PER_MIRROR; i++) { const attempt = await singleAttempt(mirror.url, did); attempts.push(attempt); } const successfulAttempts = attempts.filter((a) => a.status === "success"); const avgResponseTime = successfulAttempts.length > 0 ? successfulAttempts.reduce((sum, a) => sum + a.responseTime, 0) / successfulAttempts.length : 0; return { mirrorUrl: mirror.url, implementation: mirror.implementation, attempts, avgResponseTime, status: successfulAttempts.length > 0 ? "success" : "error", }; }; export const benchmarkAllMirrors = async ( mirrors: Mirror[], did: string ): Promise => { const promises = mirrors.map((mirror) => benchmarkMirror(mirror, did)); return Promise.all(promises); };