File size: 3,406 Bytes
866dfb3
 
 
 
 
 
 
 
 
c3d1852
866dfb3
 
 
c3d1852
 
 
 
 
866dfb3
c3d1852
 
 
 
866dfb3
c3d1852
 
 
 
 
866dfb3
 
c3d1852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
866dfb3
c3d1852
 
 
 
 
 
 
866dfb3
c3d1852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
866dfb3
 
c3d1852
 
 
 
 
 
 
866dfb3
c3d1852
 
 
 
 
 
 
866dfb3
c3d1852
 
 
 
 
 
 
866dfb3
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Use relative path since dashboard is served from same origin
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || '';
const API_KEY = process.env.NEXT_PUBLIC_DASHBOARD_API_KEY || '';

async function fetchAPI<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
  const url = `${API_BASE_URL}${endpoint}`;
  
  const headers: HeadersInit = {
    'Content-Type': 'application/json',
    ...(API_KEY ? { 'X-Dashboard-Key': API_KEY } : {}),
    ...options.headers,
  };

  try {
    const response = await fetch(url, {
      ...options,
      headers,
    });

    if (!response.ok) {
      console.error(`API error: ${response.status} ${response.statusText} for ${endpoint}`);
      throw new Error(`API error: ${response.status} ${response.statusText}`);
    }

    return response.json();
  } catch (error) {
    console.error(`Failed to fetch ${endpoint}:`, error);
    throw error;
  }
}

// Default/fallback data for when API is unavailable
const defaultStats = {
  uptime_seconds: 0,
  total_requests: 0,
  total_errors: 0,
  error_rate: 0,
  active_requests: 0,
  total_input_tokens: 0,
  total_output_tokens: 0,
  requests_by_model: {},
  tokens_by_model: {},
  avg_latency_ms: 0,
  p50_latency_ms: 0,
  p95_latency_ms: 0,
  p99_latency_ms: 0,
  accounts_total: 0,
  accounts_healthy: 0,
  accounts_unhealthy: 0,
};

export const api = {
  getStats: async () => {
    try {
      return await fetchAPI<import('@/types/metrics').DashboardStats>('/api/dashboard/stats');
    } catch {
      return defaultStats as import('@/types/metrics').DashboardStats;
    }
  },
  
  getMetrics: async (params?: { start_time?: string; end_time?: string; model?: string; granularity?: string; limit?: number }) => {
    try {
      const searchParams = new URLSearchParams();
      if (params?.start_time) searchParams.set('start_time', params.start_time);
      if (params?.end_time) searchParams.set('end_time', params.end_time);
      if (params?.model) searchParams.set('model', params.model);
      if (params?.granularity) searchParams.set('granularity', params.granularity);
      if (params?.limit) searchParams.set('limit', params.limit.toString());
      const queryString = searchParams.toString();
      return await fetchAPI<import('@/types/metrics').MetricsResponse>(
        `/api/dashboard/metrics${queryString ? `?${queryString}` : ''}`
      );
    } catch {
      return { query: { granularity: '1m', limit: 100 }, data: [], total_requests: 0, total_errors: 0, total_input_tokens: 0, total_output_tokens: 0 } as import('@/types/metrics').MetricsResponse;
    }
  },
  
  getAccounts: async () => {
    try {
      return await fetchAPI<import('@/types/metrics').Account[]>('/api/dashboard/accounts');
    } catch {
      return [] as import('@/types/metrics').Account[];
    }
  },
  
  getConfig: async () => {
    try {
      return await fetchAPI<import('@/types/metrics').GatewayConfig>('/api/dashboard/config');
    } catch {
      return null;
    }
  },
  
  getHealth: async () => {
    try {
      return await fetchAPI<import('@/types/metrics').HealthResponse>('/api/dashboard/health');
    } catch {
      return { status: 'unhealthy', version: 'unknown', uptime_seconds: 0, auth_healthy: false, api_reachable: false, accounts_status: null, metrics_enabled: false, prometheus_ready: false } as import('@/types/metrics').HealthResponse;
    }
  },
};

export default api;