File size: 2,477 Bytes
47b4127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import type {
  ArtifactCacheEntry,
  ArtifactCachePayload,
  ArtifactSourceCount,
  BatchRunInput,
  BatchRunResponse,
  ResearchRun,
  ResearchRunInput,
  SamplesResponse,
} from "@fello/contracts";

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, "") ??
  "http://127.0.0.1:8000";

async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {
  const response = await fetch(`${API_BASE_URL}${path}`, {
    ...init,
    headers: {
      "Content-Type": "application/json",
      ...(init?.headers ?? {}),
    },
    cache: "no-store",
  });

  if (!response.ok) {
    const detail = await response.text();
    throw new Error(detail || `Request failed with status ${response.status}`);
  }

  return (await response.json()) as T;
}

export function getApiBaseUrl(): string {
  return API_BASE_URL;
}

export function getSamples(): Promise<SamplesResponse> {
  return fetchJson<SamplesResponse>("/samples");
}

export function createRun(payload: ResearchRunInput): Promise<ResearchRun> {
  return fetchJson<ResearchRun>("/runs", {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

export function createBatchRuns(payload: BatchRunInput): Promise<BatchRunResponse> {
  return fetchJson<BatchRunResponse>("/runs/batch", {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

export function getRun(runId: string): Promise<ResearchRun> {
  return fetchJson<ResearchRun>(`/runs/${runId}`);
}

export function listDebugRuns(limit = 60): Promise<ResearchRun[]> {
  const value = Number.isFinite(limit) ? Math.max(1, Math.min(200, limit)) : 60;
  return fetchJson<ResearchRun[]>(`/debug/runs?limit=${value}`);
}

export function listArtifactSources(): Promise<ArtifactSourceCount[]> {
  return fetchJson<ArtifactSourceCount[]>("/debug/artifacts/sources");
}

export function listArtifacts(params?: { source?: string; limit?: number }): Promise<ArtifactCacheEntry[]> {
  const source = params?.source?.trim() ?? "";
  const rawLimit = params?.limit ?? 80;
  const limit = Number.isFinite(rawLimit) ? Math.max(1, Math.min(400, rawLimit)) : 80;
  const query = new URLSearchParams();
  if (source) {
    query.set("source", source);
  }
  query.set("limit", String(limit));
  return fetchJson<ArtifactCacheEntry[]>(`/debug/artifacts?${query.toString()}`);
}

export function getArtifact(artifactId: number): Promise<ArtifactCachePayload> {
  return fetchJson<ArtifactCachePayload>(`/debug/artifacts/${artifactId}`);
}