-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathclient.ts
More file actions
2265 lines (2035 loc) · 71 KB
/
client.ts
File metadata and controls
2265 lines (2035 loc) · 71 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { useQuery, useMutation, useQueryClient, skipToken } from '@tanstack/react-query'
import type {
Topology,
ClusterInfo,
Capabilities,
ContextInfo,
Namespace,
TimelineEvent,
TimeRange,
ResourceWithRelationships,
HelmRelease,
HelmReleaseDetail,
HelmValues,
ManifestDiff,
UpgradeInfo,
BatchUpgradeInfo,
ValuesPreviewResponse,
HelmRepository,
ChartSearchResult,
ChartDetail,
InstallChartRequest,
ArtifactHubSearchResult,
ArtifactHubChartDetail,
} from '../types'
import type { GitOpsOperationResponse } from '../types/gitops'
const API_BASE = '/api'
// ApiError preserves HTTP status code for callers to distinguish 403/404/500 etc.
export class ApiError extends Error {
status: number
data?: Record<string, unknown>
constructor(message: string, status: number, data?: Record<string, unknown>) {
super(message)
this.name = 'ApiError'
this.status = status
this.data = data
}
}
export function isForbiddenError(error: unknown): boolean {
return error instanceof ApiError && error.status === 403
}
export async function fetchJSON<T>(path: string): Promise<T> {
const response = await fetch(`${API_BASE}${path}`)
if (!response.ok) {
const errorData = await response.json().catch(() => ({ error: 'Unknown error' }))
throw new ApiError(errorData.error || `HTTP ${response.status}`, response.status, errorData)
}
return response.json()
}
// ============================================================================
// Dashboard
// ============================================================================
export interface DashboardCluster {
name: string
platform: string
version: string
connected: boolean
}
export interface DashboardHealth {
healthy: number
warning: number
error: number
warningEvents: number
}
export interface DashboardProblem {
kind: string
namespace: string
name: string
status: string
reason: string
message: string
age: string
ageSeconds: number
}
export interface WorkloadCount {
total: number
ready: number
unready: number
}
export interface DashboardMetrics {
cpu?: MetricSummary
memory?: MetricSummary
}
export interface MetricSummary {
usageMillis: number
requestsMillis: number
capacityMillis: number
usagePercent: number
requestPercent: number
}
export interface DashboardResourceCounts {
pods: { total: number; running: number; pending: number; failed: number; succeeded: number }
deployments: { total: number; available: number; unavailable: number }
statefulSets: WorkloadCount
daemonSets: WorkloadCount
services: number
ingresses: number
gateways?: number
routes?: number
nodes: { total: number; ready: number; notReady: number; cordoned: number }
namespaces: number
jobs: { total: number; active: number; succeeded: number; failed: number }
cronJobs: { total: number; active: number; suspended: number }
configMaps: number
secrets: number
pvcs: { total: number; bound: number; pending: number; unbound: number }
restricted?: string[] // Resource kinds the user cannot list due to RBAC
}
export interface DashboardEvent {
type: string
reason: string
message: string
involvedObject: string
namespace: string
timestamp: string
}
export interface DashboardChange {
kind: string
namespace: string
name: string
changeType: string
summary: string
timestamp: string
}
export interface DashboardTopologySummary {
nodeCount: number
edgeCount: number
}
export interface DashboardTopFlow {
src: string
dst: string
requestsPerSec?: number
connections: number
}
export interface DashboardTrafficSummary {
source: string
flowCount: number
topFlows: DashboardTopFlow[]
}
export interface DashboardHelmRelease {
name: string
namespace: string
chart: string
chartVersion: string
status: string
resourceHealth?: string
}
export interface DashboardHelmSummary {
total: number
releases: DashboardHelmRelease[]
restricted?: boolean // True when user lacks permissions to list Helm releases
}
export interface DashboardCRDCount {
kind: string
name: string
group: string
count: number
}
export interface DashboardCertificateHealth {
total: number
healthy: number
warning: number
critical: number
expired: number
}
export interface DashboardResponse {
cluster: DashboardCluster
health: DashboardHealth
problems: DashboardProblem[]
resourceCounts: DashboardResourceCounts
recentEvents: DashboardEvent[]
recentChanges: DashboardChange[]
topologySummary: DashboardTopologySummary
trafficSummary: DashboardTrafficSummary | null
metrics: DashboardMetrics | null
metricsServerAvailable: boolean
certificateHealth: DashboardCertificateHealth | null
nodeVersionSkew: { versions: Record<string, string[]>; minVersion: string; maxVersion: string } | null
deferredLoading?: boolean // True while deferred informers (secrets, events, etc.) are still syncing
}
export interface DashboardCRDsResponse {
topCRDs: DashboardCRDCount[]
}
export function useDashboard(namespaces: string[] = []) {
const params = namespaces.length > 0 ? `?namespaces=${namespaces.join(',')}` : ''
return useQuery<DashboardResponse>({
queryKey: ['dashboard', namespaces],
queryFn: () => fetchJSON(`/dashboard${params}`),
staleTime: 15000, // 15 seconds
refetchInterval: 30000, // Refresh every 30 seconds
})
}
// Certificate expiry for TLS secrets (used in secrets list view)
export interface CertExpiry {
daysLeft: number
expired?: boolean
}
export function useSecretCertExpiry(namespaces: string[] = [], enabled = true) {
const params = namespaces.length > 0 ? `?namespaces=${namespaces.join(',')}` : ''
return useQuery<Record<string, CertExpiry>>({
queryKey: ['secret-cert-expiry', namespaces],
queryFn: () => fetchJSON(`/secrets/certificate-expiry${params}`),
enabled,
staleTime: 30000,
refetchInterval: 60000,
})
}
// CRD counts - loaded lazily after main dashboard
export function useDashboardCRDs(namespaces: string[] = []) {
const params = namespaces.length > 0 ? `?namespaces=${namespaces.join(',')}` : ''
return useQuery<DashboardCRDsResponse>({
queryKey: ['dashboard-crds', namespaces],
queryFn: () => fetchJSON(`/dashboard/crds${params}`),
staleTime: 30000, // 30 seconds - less frequent updates
refetchInterval: 60000, // Refresh every minute
})
}
// Helm summary - loaded lazily after main dashboard (Helm SDK lists K8s secrets, ~2-3s)
export function useDashboardHelm(namespaces: string[] = []) {
const params = namespaces.length > 0 ? `?namespaces=${namespaces.join(',')}` : ''
return useQuery<DashboardHelmSummary>({
queryKey: ['dashboard-helm', namespaces],
queryFn: () => fetchJSON(`/dashboard/helm${params}`),
staleTime: 30000,
refetchInterval: 60000,
})
}
// ============================================================================
// OpenCost
// ============================================================================
export interface OpenCostNamespaceCost {
name: string
hourlyCost: number
cpuCost: number
memoryCost: number
storageCost?: number
cpuUsageCost?: number
memoryUsageCost?: number
efficiency?: number
idleCost?: number
}
export type CostUnavailableReason = 'no_prometheus' | 'no_metrics' | 'query_error'
export interface OpenCostSummary {
available: boolean
reason?: CostUnavailableReason
currency?: string
window?: string
totalHourlyCost?: number
totalStorageCost?: number
totalIdleCost?: number
clusterEfficiency?: number
namespaces?: OpenCostNamespaceCost[]
}
export function useOpenCostSummary() {
return useQuery<OpenCostSummary>({
queryKey: ['opencost-summary'],
queryFn: () => fetchJSON('/opencost/summary'),
refetchInterval: 60000, // Refresh every minute
staleTime: 30000,
placeholderData: (prev) => prev, // Keep previous data visible during refetch
})
}
// Workload-level cost breakdown for a namespace
export interface OpenCostWorkloadCost {
name: string
kind: string
hourlyCost: number
cpuCost: number
memoryCost: number
replicas: number
cpuUsageCost?: number
memoryUsageCost?: number
efficiency?: number
idleCost?: number
}
export interface OpenCostWorkloadResponse {
available: boolean
reason?: CostUnavailableReason
namespace: string
workloads: OpenCostWorkloadCost[]
}
export function useOpenCostWorkloads(namespace: string, options?: { enabled?: boolean }) {
return useQuery<OpenCostWorkloadResponse>({
queryKey: ['opencost-workloads', namespace],
queryFn: () => fetchJSON(`/opencost/workloads?namespace=${encodeURIComponent(namespace)}`),
enabled: (options?.enabled ?? true) && Boolean(namespace),
staleTime: 30000,
})
}
// Cost trend over time
export type CostTimeRange = '6h' | '24h' | '7d'
export interface OpenCostTrendDataPoint {
timestamp: number
value: number
}
export interface OpenCostTrendSeries {
namespace: string
dataPoints: OpenCostTrendDataPoint[]
}
export interface OpenCostTrendResponse {
available: boolean
reason?: CostUnavailableReason
range: string
series?: OpenCostTrendSeries[]
}
export function useOpenCostTrend(range_: CostTimeRange = '24h') {
return useQuery<OpenCostTrendResponse>({
queryKey: ['opencost-trend', range_],
queryFn: () => fetchJSON(`/opencost/trend?range=${range_}`),
staleTime: 60000,
refetchInterval: 120000, // Refresh every 2 minutes
placeholderData: (prev) => prev,
})
}
// Node cost breakdown
export interface OpenCostNodeCost {
name: string
instanceType?: string
region?: string
hourlyCost: number
cpuCost: number
memoryCost: number
}
export interface OpenCostNodeResponse {
available: boolean
reason?: CostUnavailableReason
nodes?: OpenCostNodeCost[]
}
export function useOpenCostNodes() {
return useQuery<OpenCostNodeResponse>({
queryKey: ['opencost-nodes'],
queryFn: () => fetchJSON('/opencost/nodes'),
staleTime: 60000,
refetchInterval: 120000,
placeholderData: (prev) => prev,
})
}
// Cluster info
export function useClusterInfo() {
const query = useQuery<ClusterInfo>({
queryKey: ['cluster-info'],
queryFn: () => fetchJSON('/cluster-info'),
staleTime: 60000, // 1 minute
// Poll faster when CRD discovery is in progress
refetchInterval: (query) => {
const status = query.state.data?.crdDiscoveryStatus
return status === 'discovering' ? 2000 : false
},
})
return query
}
// Version check
export type InstallMethod = 'homebrew' | 'krew' | 'scoop' | 'direct' | 'desktop'
export interface VersionInfo {
currentVersion: string
latestVersion?: string
updateAvailable: boolean
releaseUrl?: string
releaseNotes?: string
installMethod: InstallMethod
updateCommand?: string
error?: string
}
export function useVersionCheck() {
return useQuery<VersionInfo>({
queryKey: ['version-check'],
queryFn: () => fetchJSON('/version-check'),
staleTime: 60 * 60 * 1000, // 1 hour
retry: false, // Don't retry on failure
})
}
// ============================================================================
// Desktop Update API hooks
// ============================================================================
export type DesktopUpdateState = 'idle' | 'downloading' | 'ready' | 'applying' | 'error'
export interface DesktopUpdateStatus {
state: DesktopUpdateState
progress?: number // 0.0 - 1.0 during download
version?: string
error?: string
}
export function useStartDesktopUpdate() {
return useMutation({
mutationFn: async () => {
const response = await fetch(`${API_BASE}/desktop/update`, {
method: 'POST',
})
if (!response.ok) {
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
throw new Error(error.error || `HTTP ${response.status}`)
}
return response.json()
},
meta: {
errorMessage: 'Failed to start update',
},
})
}
export function useDesktopUpdateStatus(enabled: boolean) {
return useQuery<DesktopUpdateStatus>({
queryKey: ['desktop-update-status'],
queryFn: () => fetchJSON('/desktop/update/status'),
enabled,
refetchInterval: 500, // Poll every 500ms during active update
staleTime: 0, // Always refetch
})
}
export function useApplyDesktopUpdate() {
return useMutation({
mutationFn: async () => {
const response = await fetch(`${API_BASE}/desktop/update/apply`, {
method: 'POST',
})
if (!response.ok) {
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
throw new Error(error.error || `HTTP ${response.status}`)
}
return response.json()
},
meta: {
errorMessage: 'Failed to apply update',
successMessage: 'Update applied — restarting...',
},
})
}
// Runtime stats for debug overlay
export interface RuntimeStats {
heapMB: number
heapObjectsK: number
goroutines: number
uptimeSeconds: number
typedInformers?: number
dynamicInformers?: number
}
export interface HealthResponse {
status: string
resourceCount: number
runtime: RuntimeStats
}
export function useRuntimeStats(enabled: boolean = true) {
return useQuery<HealthResponse>({
queryKey: ['health'],
queryFn: () => fetchJSON('/health'),
staleTime: 2000, // 2 seconds
refetchInterval: enabled ? 3000 : false, // Refresh every 3 seconds when enabled
enabled,
})
}
// Capabilities (RBAC-based feature flags)
export function useCapabilities() {
return useQuery<Capabilities>({
queryKey: ['capabilities'],
queryFn: () => fetchJSON('/capabilities'),
staleTime: 60000, // 1 minute - cached on backend too
refetchInterval: 60000, // Re-check periodically so transient failures self-correct
})
}
// Namespaces
export function useNamespaces() {
return useQuery<Namespace[]>({
queryKey: ['namespaces'],
queryFn: () => fetchJSON('/namespaces'),
staleTime: 30000, // 30 seconds
})
}
// Topology (for manual refresh)
export function useTopology(namespaces: string[], viewMode: string = 'resources', options?: { enabled?: boolean }) {
const params = new URLSearchParams()
if (namespaces.length > 0) params.set('namespaces', namespaces.join(','))
if (viewMode) params.set('view', viewMode)
const queryString = params.toString()
return useQuery<Topology>({
queryKey: ['topology', namespaces, viewMode],
queryFn: () => fetchJSON(`/topology${queryString ? `?${queryString}` : ''}`),
staleTime: 5000, // 5 seconds
enabled: options?.enabled !== false,
})
}
// Generic resource fetching - returns resource with relationships
// Uses '_' as placeholder for cluster-scoped resources (empty namespace)
export function useResource<T>(kind: string, namespace: string, name: string, group?: string) {
// For cluster-scoped resources, use '_' as namespace placeholder
const ns = namespace || '_'
const params = new URLSearchParams()
if (group) params.set('group', group)
const queryString = params.toString()
const query = useQuery<ResourceWithRelationships<T>>({
queryKey: ['resource', kind, namespace, name, group],
queryFn: () => fetchJSON(`/resources/${kind}/${ns}/${name}${queryString ? `?${queryString}` : ''}`),
enabled: Boolean(kind && name), // namespace can be empty for cluster-scoped resources
})
// Extract resource and relationships from the response
return {
...query,
data: query.data?.resource,
relationships: query.data?.relationships,
certificateInfo: query.data?.certificateInfo,
}
}
// Hook that returns full response with relationships explicitly
export function useResourceWithRelationships<T>(kind: string, namespace: string, name: string, group?: string) {
const ns = namespace || '_'
const params = new URLSearchParams()
if (group) params.set('group', group)
const queryString = params.toString()
return useQuery<ResourceWithRelationships<T>>({
queryKey: ['resource', kind, namespace, name, group],
queryFn: () => fetchJSON(`/resources/${kind}/${ns}/${name}${queryString ? `?${queryString}` : ''}`),
enabled: Boolean(kind && name),
})
}
// List resources - queryKey includes group for cache sharing with ResourcesView
export function useResources<T>(kind: string, namespace?: string, group?: string) {
const params = new URLSearchParams()
if (namespace) params.set('namespace', namespace)
if (group) params.set('group', group)
const queryString = params.toString()
return useQuery<T[]>({
queryKey: ['resources', kind, group, namespace],
queryFn: () => fetchJSON(`/resources/${kind}${queryString ? `?${queryString}` : ''}`),
staleTime: 30000, // 30 seconds - matches refetchInterval in ResourcesView
})
}
// Timeline changes (unified view of changes + K8s events)
export interface UseChangesOptions {
namespaces?: string[]
kind?: string
timeRange?: TimeRange
filter?: string // Filter preset name ('default', 'all', 'warnings-only', 'workloads')
includeK8sEvents?: boolean
includeManaged?: boolean
limit?: number
enabled?: boolean
}
function getTimeRangeDate(range: TimeRange): Date | null {
if (range === 'all') return null
const now = new Date()
switch (range) {
case '5m':
return new Date(now.getTime() - 5 * 60 * 1000)
case '30m':
return new Date(now.getTime() - 30 * 60 * 1000)
case '1h':
return new Date(now.getTime() - 60 * 60 * 1000)
case '6h':
return new Date(now.getTime() - 6 * 60 * 60 * 1000)
case '24h':
return new Date(now.getTime() - 24 * 60 * 60 * 1000)
default:
return null
}
}
export function useChanges(options: UseChangesOptions = {}) {
const { namespaces = [], kind, timeRange = '1h', filter = 'all', includeK8sEvents = true, includeManaged = false, limit = 200, enabled = true } = options
const params = new URLSearchParams()
if (namespaces.length > 0) params.set('namespaces', namespaces.join(','))
if (kind) params.set('kind', kind)
if (filter) params.set('filter', filter)
if (!includeK8sEvents) params.set('include_k8s_events', 'false')
if (includeManaged) params.set('include_managed', 'true')
params.set('limit', String(limit))
const sinceDate = getTimeRangeDate(timeRange)
if (sinceDate) {
params.set('since', sinceDate.toISOString())
}
const queryString = params.toString()
return useQuery<TimelineEvent[]>({
queryKey: ['changes', namespaces, kind, timeRange, filter, includeK8sEvents, includeManaged, limit],
queryFn: () => fetchJSON(`/changes${queryString ? `?${queryString}` : ''}`),
staleTime: 5000, // Consider data stale after 5 seconds to ensure fresh data on navigation
refetchInterval: 60000, // SSE handles real-time updates; this is a fallback
enabled,
})
}
// Children changes for a parent workload (e.g., ReplicaSets and Pods under a Deployment)
export function useResourceChildren(kind: string, namespace: string, name: string, timeRange: TimeRange = '1h') {
const sinceDate = getTimeRangeDate(timeRange)
const params = new URLSearchParams()
if (sinceDate) {
params.set('since', sinceDate.toISOString())
}
return useQuery<TimelineEvent[]>({
queryKey: ['resource-children', kind, namespace, name, timeRange],
queryFn: () => fetchJSON(`/changes/${kind}/${namespace}/${name}/children?${params.toString()}`),
enabled: Boolean(kind && namespace && name),
refetchInterval: 15000, // Refresh every 15 seconds
})
}
// Resource-specific events (filtered by resource name)
export function useResourceEvents(kind: string, namespace: string, name: string) {
const params = new URLSearchParams()
params.set('namespace', namespace)
params.set('kind', kind)
params.set('limit', '50')
// Get events from last 24 hours
const since = new Date(Date.now() - 24 * 60 * 60 * 1000)
params.set('since', since.toISOString())
return useQuery<TimelineEvent[]>({
queryKey: ['resource-events', kind, namespace, name],
queryFn: async () => {
const events = await fetchJSON<TimelineEvent[]>(`/changes?${params.toString()}`)
// Filter to only events for this specific resource
return events.filter(e => e.name === name)
},
enabled: Boolean(kind && namespace && name),
refetchInterval: 15000, // Refresh every 15 seconds
})
}
// ============================================================================
// Metrics (from metrics.k8s.io)
// ============================================================================
export interface ContainerMetrics {
name: string
usage: {
cpu: string // e.g., "10m" (millicores)
memory: string // e.g., "128Mi"
}
}
export interface PodMetrics {
metadata: {
name: string
namespace: string
creationTimestamp: string
}
timestamp: string
window: string
containers: ContainerMetrics[]
}
export interface NodeMetrics {
metadata: {
name: string
creationTimestamp: string
}
timestamp: string
window: string
usage: {
cpu: string
memory: string
}
}
// Fetch metrics for a specific pod
export function usePodMetrics(namespace: string, podName: string) {
return useQuery<PodMetrics>({
queryKey: ['pod-metrics', namespace, podName],
queryFn: () => fetchJSON(`/metrics/pods/${namespace}/${podName}`),
enabled: Boolean(namespace && podName),
staleTime: 15000, // Metrics are fresh for 15 seconds
refetchInterval: 30000, // Refresh every 30 seconds
})
}
// Fetch metrics for a specific node
export function useNodeMetrics(nodeName: string) {
return useQuery<NodeMetrics>({
queryKey: ['node-metrics', nodeName],
queryFn: () => fetchJSON(`/metrics/nodes/${nodeName}`),
enabled: Boolean(nodeName),
staleTime: 15000,
refetchInterval: 30000,
})
}
// ============================================================================
// Metrics History (local collection)
// ============================================================================
export interface MetricsDataPoint {
timestamp: string
cpu: number // CPU in nanocores
memory: number // Memory in bytes
}
export interface ContainerMetricsHistory {
name: string
dataPoints: MetricsDataPoint[]
}
export interface PodMetricsHistory {
namespace: string
name: string
containers: ContainerMetricsHistory[]
collectionError?: string
}
export interface NodeMetricsHistory {
name: string
dataPoints: MetricsDataPoint[]
collectionError?: string
}
// Fetch historical metrics for a pod (last ~1 hour)
export function usePodMetricsHistory(namespace: string, podName: string) {
return useQuery<PodMetricsHistory>({
queryKey: ['pod-metrics-history', namespace, podName],
queryFn: () => fetchJSON(`/metrics/pods/${namespace}/${podName}/history`),
enabled: Boolean(namespace && podName),
staleTime: 25000, // Slightly less than poll interval
refetchInterval: 30000, // Match the backend poll interval
})
}
// Fetch historical metrics for a node (last ~1 hour)
export function useNodeMetricsHistory(nodeName: string) {
return useQuery<NodeMetricsHistory>({
queryKey: ['node-metrics-history', nodeName],
queryFn: () => fetchJSON(`/metrics/nodes/${nodeName}/history`),
enabled: Boolean(nodeName),
staleTime: 25000,
refetchInterval: 30000,
})
}
// Top metrics types (bulk, for resource table view)
export interface TopPodMetrics {
namespace: string
name: string
cpu: number // nanocores (usage)
memory: number // bytes (usage)
cpuRequest: number // nanocores (sum across containers)
cpuLimit: number // nanocores (sum across containers)
memoryRequest: number // bytes (sum across containers)
memoryLimit: number // bytes (sum across containers)
}
export interface TopNodeMetrics {
name: string
cpu: number // nanocores (usage)
memory: number // bytes (usage)
podCount: number // pods scheduled on this node
cpuAllocatable: number // nanocores
memoryAllocatable: number // bytes
}
// Fetch bulk metrics for all pods (for CPU/Memory columns in resource table)
export function useTopPodMetrics() {
return useQuery<TopPodMetrics[]>({
queryKey: ['top-pod-metrics'],
queryFn: () => fetchJSON('/metrics/top/pods'),
staleTime: 25000,
refetchInterval: 30000,
})
}
// Fetch bulk metrics for all nodes (for CPU/Memory columns in resource table)
export function useTopNodeMetrics() {
return useQuery<TopNodeMetrics[]>({
queryKey: ['top-node-metrics'],
queryFn: () => fetchJSON('/metrics/top/nodes'),
staleTime: 25000,
refetchInterval: 30000,
})
}
// ============================================================================
// Prometheus Metrics
// ============================================================================
// Prometheus types
export interface PrometheusStatus {
available: boolean
connected: boolean
address?: string
service?: {
namespace: string
name: string
port: number
basePath?: string
}
contextName?: string
error?: string
}
export interface PrometheusDataPoint {
timestamp: number
value: number
}
export interface PrometheusSeries {
labels: Record<string, string>
dataPoints: PrometheusDataPoint[]
}
export interface PrometheusQueryResult {
resultType: string
series: PrometheusSeries[]
}
export interface PrometheusResourceMetrics {
kind: string
namespace?: string
name: string
category: string
unit: string
range: string
result: PrometheusQueryResult
query?: string // PromQL query (included when result is empty, for diagnostics)
}
export type PrometheusMetricCategory = 'cpu' | 'memory' | 'network_rx' | 'network_tx' | 'filesystem'
export type PrometheusTimeRange = '10m' | '30m' | '1h' | '3h' | '6h' | '12h' | '24h' | '48h' | '7d' | '14d'
// Check Prometheus availability
export function usePrometheusStatus() {
return useQuery<PrometheusStatus>({
queryKey: ['prometheus-status'],
queryFn: () => fetchJSON('/prometheus/status'),
staleTime: 30000,
refetchInterval: 60000,
})
}
// Connect to Prometheus (trigger discovery)
export function usePrometheusConnect() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async () => {
const resp = await fetch(`${API_BASE}/prometheus/connect`, { method: 'POST' })
if (!resp.ok) {
const body = await resp.json().catch(() => ({ error: 'Unknown error' }))
throw new Error(body.error || `HTTP ${resp.status}`)
}
return resp.json() as Promise<PrometheusStatus>
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['prometheus-status'] })
},
meta: {
errorMessage: 'Failed to connect to Prometheus',
successMessage: 'Connected to Prometheus',
},
})
}
// Fetch Prometheus metrics for a resource
export function usePrometheusResourceMetrics(
kind: string,
namespace: string,
name: string,
category: PrometheusMetricCategory = 'cpu',
range: PrometheusTimeRange = '1h',
enabled = true,
) {
return useQuery<PrometheusResourceMetrics>({
queryKey: ['prometheus-resource-metrics', kind, namespace, name, category, range],
queryFn: () =>
fetchJSON(
namespace
? `/prometheus/resources/${kind}/${namespace}/${name}?category=${category}&range=${range}`
: `/prometheus/resources/${kind}/${name}?category=${category}&range=${range}`,
),
enabled,
staleTime: 30000,
refetchInterval: 60000,
})
}
// Fetch Prometheus metrics for a namespace
export function usePrometheusNamespaceMetrics(
namespace: string,
category: PrometheusMetricCategory = 'cpu',
range: PrometheusTimeRange = '1h',
enabled = true,
) {
return useQuery<PrometheusResourceMetrics>({
queryKey: ['prometheus-namespace-metrics', namespace, category, range],
queryFn: () =>
fetchJSON(`/prometheus/namespace/${namespace}?category=${category}&range=${range}`),
enabled,
staleTime: 30000,
refetchInterval: 60000,
})
}
// Fetch Prometheus metrics for the entire cluster
export function usePrometheusClusterMetrics(
category: PrometheusMetricCategory = 'cpu',
range: PrometheusTimeRange = '1h',
enabled = true,
) {
return useQuery<PrometheusResourceMetrics>({
queryKey: ['prometheus-cluster-metrics', category, range],
queryFn: () =>
fetchJSON(`/prometheus/cluster?category=${category}&range=${range}`),
enabled,
staleTime: 30000,
refetchInterval: 60000,
})
}
// ============================================================================
// Pod Logs
// ============================================================================
// Pod logs types
export interface LogsResponse {
podName: string
namespace: string
containers: string[]
logs: Record<string, string> // container -> logs
}
export interface LogStreamEvent {
event: 'connected' | 'log' | 'end' | 'error'
data: {
timestamp?: string
content?: string
container?: string
pod?: string
namespace?: string
reason?: string
error?: string
}
}
// Fetch pod logs (non-streaming)
export function usePodLogs(namespace: string, podName: string, options?: {