import "server-only"; /** * Server-side client for the Fetcha API service (Fastify). Used by server actions and route * handlers only; authenticated with the shared internal service token. */ const API_URL = (process.env.API_URL ?? "http://127.0.0.1:8221").replace(/\/$/, ""); const TOKEN = process.env.INTERNAL_SERVICE_TOKEN ?? ""; export interface ApiErrorShape { error: { code: string; message: string; request_id: string | null; details?: Record }; } export class InternalApiError extends Error { constructor( readonly status: number, readonly code: string, message: string, readonly requestId: string | null, readonly details?: Record, ) { super(message); this.name = "InternalApiError"; } } async function call(path: string, init: RequestInit & { timeoutMs?: number } = {}): Promise { const ac = new AbortController(); const t = setTimeout(() => ac.abort(), init.timeoutMs ?? 150_000); try { const res = await fetch(`${API_URL}${path}`, { ...init, headers: { authorization: `Bearer ${TOKEN}`, "content-type": "application/json", ...(init.headers ?? {}) }, signal: ac.signal, cache: "no-store", }); const text = await res.text(); let data: unknown = null; try { data = text ? JSON.parse(text) : null; } catch { data = null; } if (!res.ok) { const err = (data as ApiErrorShape | null)?.error; throw new InternalApiError(res.status, err?.code ?? "INTERNAL_ERROR", err?.message ?? `API error ${res.status}`, err?.request_id ?? res.headers.get("x-fetcha-request-id"), err?.details); } return data as T; } catch (e) { if (e instanceof InternalApiError) throw e; if ((e as Error).name === "AbortError") throw new InternalApiError(504, "TARGET_TIMEOUT", "The request timed out.", null); throw new InternalApiError(503, "PROVIDER_UNAVAILABLE", "The Fetcha API service is unreachable.", null); } finally { clearTimeout(t); } } export const internalApi = { health: () => call<{ status: string; version: string }>("/health", { timeoutMs: 5000 }), ready: () => call<{ status: string; checks: Record; available_networks: string[] }>("/ready", { timeoutMs: 8000 }).catch((e) => (e instanceof InternalApiError && e.status === 503 ? { status: "degraded", checks: {}, available_networks: [] } : Promise.reject(e))), playgroundFetch: (projectId: string, userId: string, request: unknown) => call("/internal/fetch", { method: "POST", body: JSON.stringify({ project_id: projectId, user_id: userId, request }) }), createSession: (projectId: string, userId: string, options: unknown) => call("/internal/sessions", { method: "POST", body: JSON.stringify({ project_id: projectId, user_id: userId, options }) }), listSessions: (projectId: string, userId: string) => call<{ data: unknown[] }>(`/internal/sessions?project_id=${projectId}&user_id=${userId}`), closeSession: (projectId: string, userId: string, id: string) => call(`/internal/sessions/${id}?project_id=${projectId}&user_id=${userId}`, { method: "DELETE" }), usage: (projectId: string, userId: string) => call>(`/internal/usage?project_id=${projectId}&user_id=${userId}`), providers: () => call<{ providers: Array<{ id: string; label: string; configured: boolean; networks: string[]; prices: Record; health: Array<{ network: string; status: string; latency_ms: number | null; detail: string | null; checked_at: string }>; circuits: Array<{ key: string; state: string; failures: number; successes: number; openedAt: number | null }>; }>; available_networks: string[]; }>("/internal/providers", { timeoutMs: 10_000 }), probeProviders: () => call<{ ok: boolean }>("/internal/providers/probe", { method: "POST", timeoutMs: 60_000 }), reloadProviders: () => call<{ ok: boolean }>("/internal/providers/reload", { method: "POST" }), resetCircuit: (key?: string) => call<{ ok: boolean }>("/internal/circuits/reset", { method: "POST", body: JSON.stringify({ key }) }), invalidateKey: (keyHash: string) => call<{ ok: boolean }>("/internal/keys/invalidate", { method: "POST", body: JSON.stringify({ key_hash: keyHash }) }).catch(() => ({ ok: false })), };