import type { InstanceConnectivity, InstanceConnectivityReason, } from "@/types/instance"; const DEFAULT_TIMEOUT_MS = 3_000; const MAX_MESSAGE_LENGTH = 240; const DNS_CODES = new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_FAIL"]); const CONNECTION_CODES = new Set([ "ECONNREFUSED", "ECONNRESET", "EHOSTUNREACH", "ENETUNREACH", ]); const TLS_CODES = new Set([ "CERT_HAS_EXPIRED", "CERT_NOT_YET_VALID", "DEPTH_ZERO_SELF_SIGNED_CERT", "ERR_TLS_CERT_ALTNAME_INVALID", "SELF_SIGNED_CERT_IN_CHAIN", "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", ]); interface ProbeOptions { fetchImpl?: typeof fetch; timeoutMs?: number; now?: () => number; } interface ErrorDetails { reason: InstanceConnectivityReason; message: string; } function safeMessage(value: unknown): string { const message = value instanceof Error && value.message.trim() ? value.message : "Network request failed"; return message.replace(/\s+/g, " ").slice(0, MAX_MESSAGE_LENGTH); } function errorDetails(error: unknown): ErrorDetails { let current: unknown = error; let deepestMessage = safeMessage(error); const seen = new Set(); while (current && typeof current === "object" && !seen.has(current)) { seen.add(current); const record = current as { cause?: unknown; code?: unknown; message?: unknown; name?: unknown; }; if (typeof record.message === "string" && record.message.trim()) { deepestMessage = record.message.replace(/\s+/g, " "); } if (record.name === "TimeoutError" || record.name === "AbortError") { return { reason: "timeout", message: safeMessage(current) }; } const code = typeof record.code === "string" ? record.code : ""; if (DNS_CODES.has(code)) { return { reason: "dns", message: safeMessage(current) }; } if (CONNECTION_CODES.has(code)) { return { reason: "connection", message: safeMessage(current) }; } if (TLS_CODES.has(code) || code.startsWith("ERR_TLS_")) { return { reason: "tls", message: safeMessage(current) }; } current = record.cause; } return { reason: "network", message: deepestMessage.replace(/\s+/g, " ").slice(0, MAX_MESSAGE_LENGTH), }; } export async function probeInstanceEndpoint( endpoint: string, options: ProbeOptions = {}, ): Promise { const now = options.now ?? Date.now; const startedAt = now(); const checkedAt = () => new Date(now()).toISOString(); if (!endpoint.trim()) { return { configured: false, reachable: null, checkedAt: checkedAt() }; } let url: string; try { const parsed = new URL(endpoint); if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { throw new TypeError("unsupported protocol"); } url = parsed.toString(); } catch { return { configured: true, reachable: false, checkedAt: checkedAt(), latencyMs: Math.max(0, now() - startedAt), reason: "network", message: "Invalid endpoint URL", }; } try { const response = await (options.fetchImpl ?? fetch)(url, { method: "HEAD", signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS), redirect: "manual", cache: "no-store", }); return { configured: true, reachable: true, checkedAt: checkedAt(), latencyMs: Math.max(0, now() - startedAt), httpStatus: response.status, }; } catch (error) { return { configured: true, reachable: false, checkedAt: checkedAt(), latencyMs: Math.max(0, now() - startedAt), ...errorDetails(error), }; } }