@skyhook-io/radar-app 1.21.2 → 1.21.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/package.json +2 -2
- package/src/App.tsx +50 -28
- package/src/api/actions.test.ts +11 -0
- package/src/api/actions.ts +5 -0
- package/src/api/apiResources.navigation.test.tsx +58 -0
- package/src/api/apiResources.ts +22 -16
- package/src/api/client.diagnostics.test.ts +52 -0
- package/src/api/client.triggerCronJob.test.tsx +49 -0
- package/src/api/client.ts +140 -120
- package/src/api/connectionBinding.test.tsx +82 -0
- package/src/api/connectionBinding.ts +52 -0
- package/src/api/contextSwitch.test.ts +11 -0
- package/src/api/contextSwitch.ts +58 -0
- package/src/api/radarFeatures.ts +5 -0
- package/src/components/ConnectionErrorView.tsx +13 -0
- package/src/components/ContextSwitchActions.tsx +43 -0
- package/src/components/ContextSwitcher.tsx +13 -6
- package/src/components/SwitchAwareConnectionError.tsx +2 -2
- package/src/components/cost/ApplicationCostTab.test.ts +16 -0
- package/src/components/cost/ApplicationCostTab.tsx +41 -9
- package/src/components/cost/CostTrendChart.tsx +25 -2
- package/src/components/cost/CostTrendWithheld.render.test.tsx +105 -0
- package/src/components/cost/CostView.tsx +10 -2
- package/src/components/cost/CostViewTabs.test.tsx +18 -0
- package/src/components/cost/CostViewTabs.tsx +14 -22
- package/src/components/cost/WorkloadCostTab.test.ts +15 -0
- package/src/components/cost/WorkloadCostTab.tsx +42 -8
- package/src/components/cost/source.test.ts +16 -1
- package/src/components/cost/source.ts +34 -0
- package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +35 -0
- package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +16 -1
- package/src/components/dock/NodeTerminalTab.test.tsx +4 -2
- package/src/components/dock/NodeTerminalTab.tsx +8 -8
- package/src/components/dock/TerminalTab.test.tsx +12 -1
- package/src/components/dock/TerminalTab.tsx +6 -3
- package/src/components/home/CostCard.test.tsx +49 -0
- package/src/components/home/CostCard.tsx +98 -63
- package/src/components/home/mcpToolCatalog.ts +1 -0
- package/src/components/resource/DatadogRightsizingPanel.test.tsx +118 -0
- package/src/components/resource/DatadogRightsizingPanel.tsx +68 -0
- package/src/components/resource/DatadogWorkloadCharts.tsx +149 -0
- package/src/components/resource/HPACharts.render.test.tsx +42 -0
- package/src/components/resource/HPACharts.tsx +34 -1
- package/src/components/resource/PrometheusChartsGrid.render.test.tsx +126 -3
- package/src/components/resource/PrometheusChartsGrid.tsx +58 -25
- package/src/components/resource/RestartChart.render.test.tsx +72 -0
- package/src/components/resource/RestartChart.tsx +31 -3
- package/src/components/resource/RightsizingPanel.access.test.tsx +24 -0
- package/src/components/resource/RightsizingStrip.render.test.tsx +44 -0
- package/src/components/resource/RightsizingStrip.test.ts +1 -188
- package/src/components/resource/RightsizingStrip.tsx +27 -300
- package/src/components/resource/WorkloadMetricsSection.render.test.tsx +22 -0
- package/src/components/resource/WorkloadMetricsSection.tsx +14 -4
- package/src/components/resource/nameMatchedScope.ts +39 -0
- package/src/components/resources/pod-file-upload.ts +3 -0
- package/src/components/resources/renderers/CAPIClusterRenderer.tsx +5 -2
- package/src/components/resources/renderers/LonghornVolumeRenderer.test.tsx +104 -0
- package/src/components/resources/renderers/LonghornVolumeRenderer.tsx +31 -0
- package/src/components/rightsizing/RightsizingScanLink.tsx +22 -0
- package/src/components/rightsizing/RightsizingScanView.tsx +65 -528
- package/src/components/rightsizing/model.test.ts +20 -9
- package/src/components/rightsizing/model.ts +17 -176
- package/src/components/rightsizing/notices.test.tsx +30 -29
- package/src/components/ui/DiagnosticsOverlay.test.ts +3 -2
- package/src/components/ui/DiagnosticsOverlay.tsx +23 -13
- package/src/components/ui/command-items.ts +3 -4
- package/src/components/useContextSwitchFlow.test.tsx +9 -0
- package/src/components/useContextSwitchFlow.tsx +43 -5
- package/src/components/workload/WorkloadRightsizingSource.test.tsx +83 -0
- package/src/components/workload/WorkloadView.test.ts +22 -1
- package/src/components/workload/WorkloadView.tsx +57 -16
- package/src/context/ConnectionContext.test.ts +1 -0
- package/src/context/ConnectionContext.tsx +58 -15
- package/src/context/ConnectionProvider.connectionId.test.tsx +92 -0
- package/src/context/ConnectionProvider.retry.test.tsx +174 -1
- package/src/context/ContextSwitchContext.tsx +15 -1
- package/src/context/NavCustomization.tsx +6 -3
- package/src/hooks/useEventSource.test.tsx +85 -0
- package/src/hooks/useEventSource.ts +43 -16
- package/src/hooks/useResetViewsOnContextChange.test.tsx +34 -0
- package/src/hooks/useResetViewsOnContextChange.ts +27 -0
- package/src/index.ts +3 -0
- package/src/integrations/resourceHosts.test.tsx +1 -1
- package/src/integrations/resourceHosts.tsx +2 -0
- package/src/utils/navigation.ts +1 -15
- package/src/utils/page-links.ts +6 -0
- package/src/components/rightsizing/presentation.test.ts +0 -150
- package/src/components/rightsizing/presentation.ts +0 -109
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { renderToStaticMarkup } from 'react-dom/server'
|
|
2
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
3
|
+
import { MemoryRouter } from 'react-router-dom'
|
|
4
|
+
import { expect, it, vi } from 'vitest'
|
|
5
|
+
import { ApiError } from '../../api/client'
|
|
6
|
+
import { getApiBase } from '../../api/config'
|
|
7
|
+
import { NavCustomizationProvider } from '../../context/NavCustomization'
|
|
8
|
+
import { WorkloadCostRightsizing } from '../resource/DatadogWorkloadCharts'
|
|
9
|
+
import { MetricsTabContent } from './WorkloadView'
|
|
10
|
+
|
|
11
|
+
vi.mock('../resource/PrometheusChartsGrid', () => ({
|
|
12
|
+
PrometheusChartsGrid: ({ showRightsizing = true, workloadTotals }: { showRightsizing?: boolean; workloadTotals?: React.ReactNode }) =>
|
|
13
|
+
<div>Prom charts{workloadTotals}{showRightsizing && <p>Prom recommendation</p>}</div>,
|
|
14
|
+
}))
|
|
15
|
+
vi.mock('../resource/RightsizingStrip', () => ({
|
|
16
|
+
RightsizingPanel: () => <p>Prom recommendation</p>,
|
|
17
|
+
RightsizingStrip: () => <p>Prom recommendation</p>,
|
|
18
|
+
}))
|
|
19
|
+
vi.mock('../resource/DatadogRightsizingPanel', () => ({
|
|
20
|
+
DatadogRightsizingPanel: () => <p>DD recommendation</p>,
|
|
21
|
+
}))
|
|
22
|
+
vi.mock('../resource/RestartChart', () => ({ RestartEventLane: () => null }))
|
|
23
|
+
|
|
24
|
+
function render(status: object | Error, required = true) {
|
|
25
|
+
const client = new QueryClient({ defaultOptions: { queries: { retryOnMount: false } } })
|
|
26
|
+
const queryKey = ['datadog-metrics-status', getApiBase()]
|
|
27
|
+
if (status instanceof Error) {
|
|
28
|
+
const query = client.getQueryCache().build(client, { queryKey })
|
|
29
|
+
query.setState({ status: 'error', error: status })
|
|
30
|
+
} else {
|
|
31
|
+
client.setQueryData(queryKey, status)
|
|
32
|
+
}
|
|
33
|
+
const workload = { kind: 'Deployment', namespace: 'shop', name: 'api' }
|
|
34
|
+
function view(children: React.ReactNode) {
|
|
35
|
+
return renderToStaticMarkup(
|
|
36
|
+
<MemoryRouter><NavCustomizationProvider value={{ embedded: true, rightsizingProviderStatus: required }}>
|
|
37
|
+
<QueryClientProvider client={client}>{children}</QueryClientProvider>
|
|
38
|
+
</NavCustomizationProvider></MemoryRouter>,
|
|
39
|
+
)
|
|
40
|
+
}
|
|
41
|
+
const metrics = view(<MetricsTabContent {...workload} resource={{}} expanded />)
|
|
42
|
+
const drawer = view(<MetricsTabContent {...workload} resource={{}} expanded={false} />)
|
|
43
|
+
const cost = view(<WorkloadCostRightsizing {...workload} />)
|
|
44
|
+
client.clear()
|
|
45
|
+
return { cost, metrics, drawer }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
it.each([
|
|
49
|
+
[{ configured: false, rightsizingProvider: 'datadog' }, 'no usable rightsizing connection'],
|
|
50
|
+
[{ configured: false }, 'could not determine the rightsizing source'],
|
|
51
|
+
[new ApiError('Cluster missing', 404), 'could not determine the rightsizing source'],
|
|
52
|
+
[new ApiError('Gateway down', 503), 'could not determine the rightsizing source'],
|
|
53
|
+
])('keeps Prom charts available and withholds sizing when its selection is unresolved', (status, reason) => {
|
|
54
|
+
const { cost, metrics, drawer } = render(status)
|
|
55
|
+
expect(metrics).toContain('Prom charts')
|
|
56
|
+
for (const panel of [metrics, drawer, cost]) {
|
|
57
|
+
expect(panel).toContain(reason)
|
|
58
|
+
expect(panel).not.toContain('Prom recommendation')
|
|
59
|
+
expect(panel).not.toContain('DD recommendation')
|
|
60
|
+
}
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it.each([
|
|
64
|
+
[{ configured: false, rightsizingProvider: 'prometheus' }, 'Prom charts', 'Prom recommendation'],
|
|
65
|
+
[{ configured: true, rightsizingProvider: 'prometheus' }, 'Datadog', 'Prom recommendation'],
|
|
66
|
+
[{ configured: false, rightsizingProvider: 'datadog', rightsizing: true }, 'Prom charts', 'DD recommendation'],
|
|
67
|
+
[{ configured: true, rightsizingProvider: 'datadog', rightsizing: true }, 'Datadog', 'DD recommendation'],
|
|
68
|
+
])('resolves charts independently of the single selected sizing provider', (status, charts, expected) => {
|
|
69
|
+
const { cost, metrics, drawer } = render(status)
|
|
70
|
+
expect(metrics).toContain(charts)
|
|
71
|
+
for (const panel of [metrics, drawer, cost]) {
|
|
72
|
+
expect(panel.match(/(?:DD|Prom) recommendation/g)).toEqual([expected])
|
|
73
|
+
}
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it('keeps Prometheus sizing for chart-only Hubs and recognizes a missing status route', () => {
|
|
77
|
+
const absentRoute = new ApiError('Not found', 404, {}, { unknownRoute: true })
|
|
78
|
+
expect(render(absentRoute, false).cost).toContain('Prom recommendation')
|
|
79
|
+
expect(render(absentRoute).cost).not.toContain('Prom recommendation')
|
|
80
|
+
expect(render(new ApiError('Cluster unavailable', 404), false).cost).not.toContain('Prom recommendation')
|
|
81
|
+
expect(render({ configured: true }, false).cost).toContain('Prom recommendation')
|
|
82
|
+
expect(render({ configured: false }, false).cost).toContain('Prom recommendation')
|
|
83
|
+
})
|
|
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'
|
|
|
2
2
|
|
|
3
3
|
import { gitOpsOwnerFromRelationships } from '@skyhook-io/k8s-ui'
|
|
4
4
|
import type { Relationships } from '../../types'
|
|
5
|
-
import { collectServingRefs, memberOverviewParams, supportsBatchExecution } from './WorkloadView'
|
|
5
|
+
import { collectServingRefs, isPrometheusMetricsAvailable, memberOverviewParams, supportsBatchExecution } from './WorkloadView'
|
|
6
6
|
import { findInheritedGitOpsLookupRef } from '../../hooks/useResolvedGitOpsOwner'
|
|
7
7
|
|
|
8
8
|
describe('findInheritedGitOpsLookupRef', () => {
|
|
@@ -93,3 +93,24 @@ describe('memberOverviewParams', () => {
|
|
|
93
93
|
expect(next.get('apiGroup')).toBe('jobset.x-k8s.io')
|
|
94
94
|
})
|
|
95
95
|
})
|
|
96
|
+
|
|
97
|
+
describe('isPrometheusMetricsAvailable', () => {
|
|
98
|
+
it('offers metrics for a core Node', () => {
|
|
99
|
+
expect(isPrometheusMetricsAvailable('Node', { apiVersion: 'v1', kind: 'Node' }, true)).toBe(true)
|
|
100
|
+
expect(isPrometheusMetricsAvailable('Node', undefined, true)).toBe(true)
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
it('offers no metrics for a Longhorn Node', () => {
|
|
104
|
+
const longhornNode = { apiVersion: 'longhorn.io/v1beta2', kind: 'Node' }
|
|
105
|
+
expect(isPrometheusMetricsAvailable('Node', longhornNode, false)).toBe(false)
|
|
106
|
+
expect(isPrometheusMetricsAvailable('Node', longhornNode, true)).toBe(false)
|
|
107
|
+
expect(isPrometheusMetricsAvailable('Node', undefined, false)).toBe(false)
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
it('keeps the workload rules', () => {
|
|
111
|
+
expect(isPrometheusMetricsAvailable('Deployment', {}, false)).toBe(true)
|
|
112
|
+
expect(isPrometheusMetricsAvailable('Pod', { status: { phase: 'Pending' } }, false)).toBe(false)
|
|
113
|
+
expect(isPrometheusMetricsAvailable('Pod', { status: { phase: 'Running' } }, false)).toBe(true)
|
|
114
|
+
expect(isPrometheusMetricsAvailable('ConfigMap', {}, false)).toBe(false)
|
|
115
|
+
})
|
|
116
|
+
})
|
|
@@ -37,6 +37,7 @@ import {
|
|
|
37
37
|
} from '@skyhook-io/k8s-ui'
|
|
38
38
|
import type { ServicePortRenderProps } from '@skyhook-io/k8s-ui/components/resources/renderers/ServiceRenderer'
|
|
39
39
|
import { isJobSetV1Alpha2 } from '@skyhook-io/k8s-ui/components/resources/resource-utils-jobset-lws'
|
|
40
|
+
import { isCoreNode as isCoreNodeObject } from '@skyhook-io/k8s-ui/components/resources/resource-utils'
|
|
40
41
|
import { SUBSTRATE_GROUP } from '@skyhook-io/k8s-ui/components/resources/resource-utils-agent-runtimes'
|
|
41
42
|
import type { SelectedResource, ResourceRef, Relationships, ResourceWithRelationships } from '../../types'
|
|
42
43
|
import { CronJobSchedulingContext, CronJobSchedulingDetails } from './CronJobSchedulingEvidence'
|
|
@@ -99,10 +100,12 @@ import {
|
|
|
99
100
|
fetchJSON,
|
|
100
101
|
fetchYamlSchemas,
|
|
101
102
|
} from '../../api/client'
|
|
102
|
-
import { PrometheusCharts, isPrometheusSupported } from '../resource/PrometheusCharts'
|
|
103
|
+
import { TIME_RANGES, PrometheusCharts, isPrometheusSupported } from '../resource/PrometheusCharts'
|
|
104
|
+
import { RightsizingStrip } from '../resource/RightsizingStrip'
|
|
103
105
|
import { PrometheusChartsGrid } from '../resource/PrometheusChartsGrid'
|
|
106
|
+
import { DatadogSetupHint, DatadogWorkloadCharts, useDatadogWorkloadCharts, WorkloadCostRightsizing } from '../resource/DatadogWorkloadCharts'
|
|
107
|
+
import { useNavCustomization } from '../../context/NavCustomization'
|
|
104
108
|
import { RestartEventLane } from '../resource/RestartChart'
|
|
105
|
-
import { RightsizingPanel } from '../resource/RightsizingStrip'
|
|
106
109
|
import { WorkloadCostTab } from '../cost/WorkloadCostTab'
|
|
107
110
|
import { isOpenCostWorkloadKind } from '../cost/kinds'
|
|
108
111
|
import { isRadarFeatureUnsupported } from '../../api/radarFeatures'
|
|
@@ -178,6 +181,14 @@ export function supportsBatchExecution(kind: string, apiKind: string, group?: st
|
|
|
178
181
|
return true
|
|
179
182
|
}
|
|
180
183
|
|
|
184
|
+
// Longhorn serves a `nodes` plural whose objects are also Kind Node; node metrics
|
|
185
|
+
// only exist for the core Node.
|
|
186
|
+
export function isPrometheusMetricsAvailable(kind: string, resource: any, coreNodeRoute: boolean): boolean {
|
|
187
|
+
if (!isPrometheusSupported(kind)) return false
|
|
188
|
+
if (kind === 'Node') return coreNodeRoute && isCoreNodeObject(resource)
|
|
189
|
+
return !(kind === 'Pod' && resource?.status?.phase === 'Pending')
|
|
190
|
+
}
|
|
191
|
+
|
|
181
192
|
// ============================================================================
|
|
182
193
|
// ROUTE WRAPPER — parses kind/ns/name from URL
|
|
183
194
|
// ============================================================================
|
|
@@ -390,6 +401,7 @@ function useActionsBarProps(
|
|
|
390
401
|
const argoResumeMutation = useArgoResume()
|
|
391
402
|
const { upgrade: argoResumeUpgrade, blockedReason: argoResumeBlockedReason } = useRadarFeature('argoAutoSyncEnable')
|
|
392
403
|
const { support: argoInheritanceSupport } = useRadarFeature('argoSyncInheritance')
|
|
404
|
+
const { support: cronJobJobNameSupport } = useRadarFeature('cronJobTriggerJobName')
|
|
393
405
|
|
|
394
406
|
const {
|
|
395
407
|
data: cascadePreview,
|
|
@@ -487,9 +499,11 @@ function useActionsBarProps(
|
|
|
487
499
|
? (params: { namespace: string; name: string }) =>
|
|
488
500
|
rolloutDialogPromote.mutateAsync({ action: 'promote-full', ...params })
|
|
489
501
|
: undefined,
|
|
502
|
+
// mutateAsync, not mutate: the Job name dialog stays open when this rejects.
|
|
490
503
|
onTriggerCronJob: (params: Parameters<typeof triggerCronJobMutation.mutate>[0]) =>
|
|
491
|
-
triggerCronJobMutation.
|
|
504
|
+
triggerCronJobMutation.mutateAsync(params),
|
|
492
505
|
isTriggeringCronJob: triggerCronJobMutation.isPending,
|
|
506
|
+
cronJobTriggerDialog: cronJobJobNameSupport === 'supported',
|
|
493
507
|
onSuspendCronJob: (params: Parameters<typeof suspendCronJobMutation.mutate>[0]) =>
|
|
494
508
|
suspendCronJobMutation.mutate(params),
|
|
495
509
|
isSuspendingCronJob: suspendCronJobMutation.isPending,
|
|
@@ -1351,7 +1365,7 @@ export function WorkloadView({
|
|
|
1351
1365
|
)}
|
|
1352
1366
|
renderCostTab={({ kind, namespace: ns, name: n }) => (
|
|
1353
1367
|
<div className="space-y-4">
|
|
1354
|
-
<
|
|
1368
|
+
<WorkloadCostRightsizing kind={kind} namespace={ns} name={n} />
|
|
1355
1369
|
<WorkloadCostTab kind={kind} namespace={ns} name={n} />
|
|
1356
1370
|
</div>
|
|
1357
1371
|
)}
|
|
@@ -1377,7 +1391,7 @@ export function WorkloadView({
|
|
|
1377
1391
|
/>
|
|
1378
1392
|
)}
|
|
1379
1393
|
isMetricsAvailable={(kind, res) =>
|
|
1380
|
-
isSubstrateWorkerPool || (
|
|
1394
|
+
isSubstrateWorkerPool || isPrometheusMetricsAvailable(kind, res, isNode)
|
|
1381
1395
|
}
|
|
1382
1396
|
isCostAvailable={(kind) => isOpenCostWorkloadKind(kind)}
|
|
1383
1397
|
onDuplicate={handleDuplicate}
|
|
@@ -2255,7 +2269,7 @@ function DiagnoseInlineSection({ kind, namespace, name, group, onOpenReachabilit
|
|
|
2255
2269
|
// Drawer mode: single chart + category tabs (compact for ~500px width).
|
|
2256
2270
|
// Full-screen mode: multi-chart grid so CPU + Memory + Network can be
|
|
2257
2271
|
// compared side-by-side without tab switching.
|
|
2258
|
-
function MetricsTabContent({
|
|
2272
|
+
export function MetricsTabContent({
|
|
2259
2273
|
kind,
|
|
2260
2274
|
namespace,
|
|
2261
2275
|
name,
|
|
@@ -2271,20 +2285,47 @@ function MetricsTabContent({
|
|
|
2271
2285
|
/** False when content follows, so the tab scrolls everything as one. */
|
|
2272
2286
|
fill?: boolean
|
|
2273
2287
|
}) {
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2288
|
+
const [params] = useSearchParams()
|
|
2289
|
+
const range = TIME_RANGES.find((option) => option.value === params.get('metricsRange'))?.value ?? '1h'
|
|
2290
|
+
const workload = { kind, namespace, name }
|
|
2291
|
+
const { embedded = false } = useNavCustomization()
|
|
2292
|
+
const { charts, rightsizing, checking, configured, setup } = useDatadogWorkloadCharts(workload, range, embedded)
|
|
2293
|
+
if (configured) {
|
|
2294
|
+
const workloadTotals = (
|
|
2295
|
+
<DatadogWorkloadCharts charts={charts.data?.configured ? charts.data.charts : undefined}
|
|
2296
|
+
loading={charts.isLoading} error={charts.error} onRetry={() => void charts.refetch()} />
|
|
2297
|
+
)
|
|
2298
|
+
if (rightsizing) return (
|
|
2299
|
+
<div className={fill ? 'h-full overflow-auto' : undefined}>
|
|
2300
|
+
<PrometheusChartsGrid {...workload} resource={resource} workloadTotals={workloadTotals} fill={false} showRightsizing={false} />
|
|
2301
|
+
<div className="px-4 pb-4">{rightsizing}</div>
|
|
2281
2302
|
</div>
|
|
2282
2303
|
)
|
|
2304
|
+
return <PrometheusChartsGrid {...workload} resource={resource} workloadTotals={workloadTotals} fill={fill} />
|
|
2283
2305
|
}
|
|
2306
|
+
if (checking) return <p role="status" className="p-4 text-sm text-theme-text-secondary">Loading workload metrics…</p>
|
|
2284
2307
|
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2308
|
+
const setupHint = setup && <DatadogSetupHint owner={setup === 'owner'} />
|
|
2309
|
+
if (rightsizing || !expanded) {
|
|
2310
|
+
return (
|
|
2311
|
+
<div className={fill ? 'h-full overflow-auto' : undefined}>
|
|
2312
|
+
{setupHint}
|
|
2313
|
+
{expanded
|
|
2314
|
+
? <PrometheusChartsGrid {...workload} resource={resource} fill={false} showRightsizing={false} />
|
|
2315
|
+
: <DrawerMetricsContent {...workload} resource={resource} />}
|
|
2316
|
+
<div className="px-4 pb-4">{rightsizing ?? <RightsizingStrip {...workload} />}</div>
|
|
2317
|
+
</div>
|
|
2318
|
+
)
|
|
2319
|
+
}
|
|
2320
|
+
if (!fill) return <PrometheusChartsGrid {...workload} resource={resource} fill={false} />
|
|
2321
|
+
return (
|
|
2322
|
+
<div className="flex flex-col h-full">
|
|
2323
|
+
{setupHint}
|
|
2324
|
+
<div className="flex-1 min-h-0">
|
|
2325
|
+
<PrometheusChartsGrid {...workload} resource={resource} />
|
|
2326
|
+
</div>
|
|
2327
|
+
</div>
|
|
2328
|
+
)
|
|
2288
2329
|
}
|
|
2289
2330
|
|
|
2290
2331
|
function DrawerMetricsContent({
|
|
@@ -44,6 +44,7 @@ describe('shouldAutoRetryConnection', () => {
|
|
|
44
44
|
expect(shouldAutoRetryConnection('config')).toBe(false)
|
|
45
45
|
expect(shouldAutoRetryConnection('rbac')).toBe(false)
|
|
46
46
|
expect(shouldAutoRetryConnection('settings')).toBe(false)
|
|
47
|
+
expect(shouldAutoRetryConnection('switch-stopped')).toBe(false)
|
|
47
48
|
})
|
|
48
49
|
})
|
|
49
50
|
|
|
@@ -3,6 +3,9 @@ import { useQuery, useMutation, useQueryClient, type QueryClient } from '@tansta
|
|
|
3
3
|
import { automaticRequestHeaders, getApiBase } from '../api/config'
|
|
4
4
|
import { readErrorBody } from '../api/httpErrors'
|
|
5
5
|
import { apiFetch, type SyncStatusSnapshot, type NodeDrainActivity } from '../api/client'
|
|
6
|
+
import { followSwitch, switchInProgress, type ContextSwitchOperation } from '../api/contextSwitch'
|
|
7
|
+
import { observeConnectionStatus } from '../api/connectionBinding'
|
|
8
|
+
import { showApiNotice } from '../components/ui/Toast'
|
|
6
9
|
import { ClusterConnectedContext } from './clusterConnected'
|
|
7
10
|
|
|
8
11
|
export type ConnectionStateType = 'connected' | 'disconnected' | 'connecting'
|
|
@@ -17,6 +20,9 @@ export interface ConnectionState {
|
|
|
17
20
|
// When this context stopped working (RFC 3339). Set by the server while
|
|
18
21
|
// disconnected; older servers never send it.
|
|
19
22
|
disconnectedAt?: string
|
|
23
|
+
// The connection Radar is serving (see connectionBinding.ts). Empty while a
|
|
24
|
+
// switch is between connections; never sent by an in-cluster or older Radar.
|
|
25
|
+
connectionId?: string
|
|
20
26
|
// Per-kind readiness while the initial informer sync runs ('connecting'
|
|
21
27
|
// with informers started). Drives the progressive app shell — absent once
|
|
22
28
|
// connected or before informers exist.
|
|
@@ -26,15 +32,18 @@ export interface ConnectionState {
|
|
|
26
32
|
interface ConnectionStatusResponse extends ConnectionState {
|
|
27
33
|
// Server-side auth recovery owns the episode: suppress browser auto-retry
|
|
28
34
|
// even when errorType has flipped to a non-auth value.
|
|
35
|
+
contextSwitch?: ContextSwitchOperation
|
|
29
36
|
authRecoveryOwed?: boolean
|
|
30
37
|
}
|
|
31
38
|
|
|
32
39
|
interface PolledConnectionStatus extends ConnectionStatusResponse {
|
|
33
40
|
sseGenerationAtStart: number
|
|
41
|
+
apiBase: string
|
|
34
42
|
}
|
|
35
43
|
|
|
36
44
|
interface ConnectionContextValue {
|
|
37
45
|
connection: ConnectionState
|
|
46
|
+
contextSwitch?: ContextSwitchOperation
|
|
38
47
|
retry: () => void
|
|
39
48
|
isRetrying: boolean
|
|
40
49
|
updateFromSSE: (status: ConnectionState) => void
|
|
@@ -43,7 +52,7 @@ interface ConnectionContextValue {
|
|
|
43
52
|
class ConnectionRetryError extends Error {
|
|
44
53
|
errorType?: string
|
|
45
54
|
|
|
46
|
-
constructor(message: string, errorType?: string) {
|
|
55
|
+
constructor(message: string, readonly status: number, errorType?: string, readonly code?: string) {
|
|
47
56
|
super(message)
|
|
48
57
|
this.name = 'ConnectionRetryError'
|
|
49
58
|
this.errorType = errorType
|
|
@@ -67,6 +76,9 @@ const CONNECTION_STATUS_FALLBACK_POLL_MS = 30000
|
|
|
67
76
|
export function refreshQueriesAfterReconnect(queryClient: QueryClient, previousContext: string, nextContext: string) {
|
|
68
77
|
queryClient.removeQueries({
|
|
69
78
|
predicate: query => {
|
|
79
|
+
// A context_changed frame can arrive before the operation's terminal poll.
|
|
80
|
+
// Connection status is process-wide and keeps that poll alive.
|
|
81
|
+
if (query.queryKey[0] === 'connection-status') return false
|
|
70
82
|
if (query.queryKey[0] !== 'node-drain-activity') return true
|
|
71
83
|
const activity = queryClient.getQueryData<NodeDrainActivity | null>(query.queryKey)
|
|
72
84
|
return activity?.contextName ? activity.contextName !== nextContext : previousContext !== nextContext
|
|
@@ -80,7 +92,7 @@ export function shouldAutoRetryConnection(errorType?: string): boolean {
|
|
|
80
92
|
// reconnect loop for those, and each browser retry would invoke the exec
|
|
81
93
|
// credential plugin again. Manual "Retry Connection" stays available for
|
|
82
94
|
// an immediate check. A settings error can't clear until Radar restarts.
|
|
83
|
-
return errorType !== 'config' && errorType !== 'settings' && errorType !== 'rbac' && !errorType?.startsWith('auth')
|
|
95
|
+
return errorType !== 'switch-stopped' && errorType !== 'config' && errorType !== 'settings' && errorType !== 'rbac' && !errorType?.startsWith('auth')
|
|
84
96
|
}
|
|
85
97
|
|
|
86
98
|
export function shouldApplyPolledConnection(
|
|
@@ -88,9 +100,10 @@ export function shouldApplyPolledConnection(
|
|
|
88
100
|
polledState: ConnectionStateType,
|
|
89
101
|
pollSSEGeneration: number,
|
|
90
102
|
currentSSEGeneration: number,
|
|
103
|
+
switchingToAnotherContext = false,
|
|
91
104
|
): boolean {
|
|
92
105
|
return pollSSEGeneration === currentSSEGeneration
|
|
93
|
-
&& (currentState !== 'connected' || polledState !== 'connecting')
|
|
106
|
+
&& (switchingToAnotherContext || currentState !== 'connected' || polledState !== 'connecting')
|
|
94
107
|
}
|
|
95
108
|
|
|
96
109
|
async function fetchConnectionStatus(sseGenerationAtStart: number): Promise<PolledConnectionStatus> {
|
|
@@ -102,24 +115,28 @@ async function fetchConnectionStatus(sseGenerationAtStart: number): Promise<Poll
|
|
|
102
115
|
// ?contexts=0: context enumeration re-reads kubeconfig files under the
|
|
103
116
|
// client write lock on the server — too costly for a perpetual poll, and
|
|
104
117
|
// nothing here consumes the list (ContextSwitcher has its own query).
|
|
105
|
-
const
|
|
118
|
+
const base = getApiBase()
|
|
119
|
+
const response = await apiFetch(`${base}/connection?contexts=0`)
|
|
106
120
|
if (!response.ok) {
|
|
107
121
|
throw new Error('Failed to fetch connection status')
|
|
108
122
|
}
|
|
109
123
|
const status = await response.json() as ConnectionStatusResponse
|
|
110
|
-
return { ...status, sseGenerationAtStart }
|
|
124
|
+
return { ...status, sseGenerationAtStart, apiBase: base }
|
|
111
125
|
}
|
|
112
126
|
|
|
113
127
|
async function retryConnection(automatic = false): Promise<ConnectionState> {
|
|
114
|
-
const
|
|
128
|
+
const base = getApiBase()
|
|
129
|
+
const response = await apiFetch(`${base}/connection/retry`, {
|
|
115
130
|
method: 'POST',
|
|
116
131
|
headers: automatic ? automaticRequestHeaders() : undefined,
|
|
117
132
|
})
|
|
118
133
|
if (!response.ok) {
|
|
119
|
-
const error = await readErrorBody(response) as { error?: string; errorType?: string }
|
|
120
|
-
throw new ConnectionRetryError(error.error || `HTTP ${response.status}`, error.errorType)
|
|
134
|
+
const error = await readErrorBody(response) as { error?: string; errorType?: string; error_code?: string }
|
|
135
|
+
throw new ConnectionRetryError(error.error || `HTTP ${response.status}`, response.status, error.errorType, error.error_code)
|
|
121
136
|
}
|
|
122
|
-
|
|
137
|
+
const result = await response.json() as ConnectionState
|
|
138
|
+
observeConnectionStatus(result, base)
|
|
139
|
+
return result
|
|
123
140
|
}
|
|
124
141
|
|
|
125
142
|
export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
@@ -216,7 +233,8 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
216
233
|
queryKey: ['connection-status'],
|
|
217
234
|
queryFn: () => fetchConnectionStatus(sseGenerationRef.current),
|
|
218
235
|
staleTime: 500, // Allow frequent refetches while connecting
|
|
219
|
-
refetchInterval:
|
|
236
|
+
refetchInterval: query => switchInProgress(query.state.data?.contextSwitch) ? 1000
|
|
237
|
+
: connection.state === 'connecting' ? 500 : CONNECTION_STATUS_FALLBACK_POLL_MS,
|
|
220
238
|
refetchIntervalInBackground: true,
|
|
221
239
|
refetchOnWindowFocus: true,
|
|
222
240
|
})
|
|
@@ -264,6 +282,7 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
264
282
|
data.state,
|
|
265
283
|
data.sseGenerationAtStart,
|
|
266
284
|
sseGenerationRef.current,
|
|
285
|
+
Boolean(data.context && current.context && data.context !== current.context),
|
|
267
286
|
)) {
|
|
268
287
|
// SSE owns the state fields, but connection_state frames don't carry
|
|
269
288
|
// per-kind sync progress — merge it from the poll so the progressive
|
|
@@ -273,6 +292,15 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
273
292
|
}
|
|
274
293
|
return
|
|
275
294
|
}
|
|
295
|
+
// Only a poll that wins over newer SSE state names the connection, or a
|
|
296
|
+
// stale reply would leave the tab sending the previous cluster's ID.
|
|
297
|
+
observeConnectionStatus(data, data.apiBase)
|
|
298
|
+
// A background tab can miss both the SSE event and the whole operation
|
|
299
|
+
// between polls. Apply the same cache and URL transition as the initiating tab.
|
|
300
|
+
if (current.state === 'connected' && current.context && current.context !== data.context &&
|
|
301
|
+
data.state === 'connected' && data.contextSwitch?.phase === 'succeeded' && data.contextSwitch.target === data.context) {
|
|
302
|
+
followSwitch(data.contextSwitch.id)
|
|
303
|
+
}
|
|
276
304
|
const becameConnected = current.state !== 'connected' && data.state === 'connected'
|
|
277
305
|
setConnection({
|
|
278
306
|
state: data.state,
|
|
@@ -293,20 +321,23 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
293
321
|
const retryMutation = useMutation({
|
|
294
322
|
mutationFn: () => retryConnection(),
|
|
295
323
|
onMutate: () => {
|
|
324
|
+
const previousConnection = connectionRef.current
|
|
296
325
|
manualRetryPendingRef.current = true
|
|
297
326
|
// Until SSE re-delivers state, a failed retry may report its own error
|
|
298
327
|
// rather than deferring to a stale "connected"
|
|
299
328
|
sseActiveRef.current = false
|
|
300
329
|
// Set connecting state while retrying
|
|
301
|
-
|
|
302
|
-
...
|
|
330
|
+
const pendingConnection: ConnectionState = {
|
|
331
|
+
...previousConnection,
|
|
303
332
|
state: 'connecting',
|
|
304
333
|
error: undefined,
|
|
305
334
|
progressMessage: 'Connecting to cluster...',
|
|
306
335
|
// A retry is a fresh attempt — per-kind progress from the previous
|
|
307
336
|
// attempt would mislabel readiness until the next poll.
|
|
308
337
|
syncStatus: undefined,
|
|
309
|
-
}
|
|
338
|
+
}
|
|
339
|
+
setConnection(prev => prev === previousConnection ? pendingConnection : prev)
|
|
340
|
+
return { previousConnection, pendingConnection }
|
|
310
341
|
},
|
|
311
342
|
onSuccess: (result) => {
|
|
312
343
|
const previousContext = connectionRef.current.context
|
|
@@ -319,8 +350,13 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
319
350
|
}
|
|
320
351
|
refreshQueriesAfterReconnect(queryClient, previousContext, result.context)
|
|
321
352
|
},
|
|
322
|
-
onError: (error: Error) => {
|
|
353
|
+
onError: (error: Error, _variables, attempt) => {
|
|
323
354
|
const retryError = error as ConnectionRetryError
|
|
355
|
+
if (retryError.status === 409) {
|
|
356
|
+
if (attempt) setConnection(prev => prev === attempt.pendingConnection ? attempt.previousConnection : prev)
|
|
357
|
+
if (retryError.code !== 'reconnect_superseded') showApiNotice('Cluster retry unavailable', error.message, 'info')
|
|
358
|
+
return
|
|
359
|
+
}
|
|
324
360
|
setConnection(prev => {
|
|
325
361
|
if (sseActiveRef.current && prev.state === 'connected') return prev
|
|
326
362
|
return {
|
|
@@ -405,6 +441,7 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
405
441
|
.catch((error: Error) => {
|
|
406
442
|
if (stopped) return
|
|
407
443
|
const retryError = error as ConnectionRetryError
|
|
444
|
+
if (retryError.status === 409) return
|
|
408
445
|
setConnection(prev => {
|
|
409
446
|
if (sseActiveRef.current && prev.state === 'connected') return prev
|
|
410
447
|
return {
|
|
@@ -483,13 +520,14 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
483
520
|
// in-flight polls detect they raced this frame.
|
|
484
521
|
sseActiveRef.current = true
|
|
485
522
|
sseGenerationRef.current += 1
|
|
523
|
+
observeConnectionStatus(status)
|
|
486
524
|
setConnection(prev => {
|
|
487
525
|
// Don't transition back to 'connecting' from 'connected'. This happens when the
|
|
488
526
|
// pod restarts and the SSE reconnects while the new pod's K8s cache is still
|
|
489
527
|
// syncing. Hiding the main content here causes a flash — keep the 'connected'
|
|
490
528
|
// state and wait for either 'connected' (sync done) or 'disconnected' (failure).
|
|
491
529
|
// (shouldApplyPolledConnection encodes the same suppression for the poll path.)
|
|
492
|
-
if (prev.state === 'connected' && status.state === 'connecting') {
|
|
530
|
+
if (prev.state === 'connected' && status.state === 'connecting' && (!status.context || status.context === prev.context)) {
|
|
493
531
|
return prev
|
|
494
532
|
}
|
|
495
533
|
// connection_state frames don't carry per-kind sync progress — keep the
|
|
@@ -506,8 +544,13 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
506
544
|
}
|
|
507
545
|
}, [refreshCachesOnConnect])
|
|
508
546
|
|
|
547
|
+
// Connection state may come from a newer SSE frame or still be applying this
|
|
548
|
+
// poll. Consume the terminal switch result alongside the matching connection.
|
|
549
|
+
const polledSwitch = data?.contextSwitch
|
|
550
|
+
const switchMatchesConnection = data?.state === connection.state && data?.context === connection.context
|
|
509
551
|
const value: ConnectionContextValue = {
|
|
510
552
|
connection,
|
|
553
|
+
contextSwitch: switchInProgress(polledSwitch) || switchMatchesConnection ? polledSwitch : undefined,
|
|
511
554
|
retry,
|
|
512
555
|
isRetrying: retryMutation.isPending || isAutoRetrying,
|
|
513
556
|
updateFromSSE,
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { act } from 'react'
|
|
3
|
+
import { createRoot, type Root } from 'react-dom/client'
|
|
4
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
5
|
+
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
|
6
|
+
import { ConnectionProvider, useConnection } from './ConnectionContext'
|
|
7
|
+
import { connectionHeaderValue, resetConnectionBindingForTest } from '../api/connectionBinding'
|
|
8
|
+
|
|
9
|
+
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
|
|
10
|
+
|
|
11
|
+
let root: Root
|
|
12
|
+
let container: HTMLDivElement
|
|
13
|
+
const seen = vi.fn<(value: ReturnType<typeof useConnection>) => void>()
|
|
14
|
+
const latest = () => seen.mock.lastCall?.[0]
|
|
15
|
+
let polls: Array<(body: unknown) => void>
|
|
16
|
+
|
|
17
|
+
function Probe() {
|
|
18
|
+
seen(useConnection())
|
|
19
|
+
return null
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const statusA = { state: 'connected', context: 'A', connectionId: 'n-1' }
|
|
23
|
+
|
|
24
|
+
beforeEach(async () => {
|
|
25
|
+
vi.useFakeTimers()
|
|
26
|
+
seen.mockClear()
|
|
27
|
+
resetConnectionBindingForTest()
|
|
28
|
+
polls = []
|
|
29
|
+
vi.stubGlobal('fetch', vi.fn((input: string) => {
|
|
30
|
+
const url = new URL(String(input), 'http://localhost')
|
|
31
|
+
if (url.pathname !== '/api/connection') {
|
|
32
|
+
return Promise.resolve(new Response('{}', { status: 404 }))
|
|
33
|
+
}
|
|
34
|
+
return new Promise<Response>(resolve => {
|
|
35
|
+
polls.push(body => resolve(new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } })))
|
|
36
|
+
})
|
|
37
|
+
}))
|
|
38
|
+
|
|
39
|
+
container = document.createElement('div')
|
|
40
|
+
document.body.appendChild(container)
|
|
41
|
+
root = createRoot(container)
|
|
42
|
+
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
|
43
|
+
await act(async () => {
|
|
44
|
+
root.render(
|
|
45
|
+
<QueryClientProvider client={client}>
|
|
46
|
+
<ConnectionProvider>
|
|
47
|
+
<Probe />
|
|
48
|
+
</ConnectionProvider>
|
|
49
|
+
</QueryClientProvider>,
|
|
50
|
+
)
|
|
51
|
+
})
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
afterEach(() => {
|
|
55
|
+
act(() => root.unmount())
|
|
56
|
+
container.remove()
|
|
57
|
+
vi.restoreAllMocks()
|
|
58
|
+
vi.unstubAllGlobals()
|
|
59
|
+
vi.useRealTimers()
|
|
60
|
+
resetConnectionBindingForTest()
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it('keeps the connection SSE delivered when an older poll resolves after it', async () => {
|
|
64
|
+
await act(async () => {
|
|
65
|
+
await vi.advanceTimersByTimeAsync(10)
|
|
66
|
+
})
|
|
67
|
+
expect(polls).toHaveLength(1)
|
|
68
|
+
await act(async () => {
|
|
69
|
+
polls[0](statusA)
|
|
70
|
+
await vi.advanceTimersByTimeAsync(10)
|
|
71
|
+
})
|
|
72
|
+
expect(connectionHeaderValue()).toBe('n-1')
|
|
73
|
+
|
|
74
|
+
// The next poll leaves while A still serves...
|
|
75
|
+
await act(async () => {
|
|
76
|
+
await vi.advanceTimersByTimeAsync(31_000)
|
|
77
|
+
})
|
|
78
|
+
expect(polls).toHaveLength(2)
|
|
79
|
+
|
|
80
|
+
// ...then SSE reports B before that poll's answer arrives.
|
|
81
|
+
act(() => {
|
|
82
|
+
latest()?.updateFromSSE({ state: 'connected', context: 'B', connectionId: 'n-2' } as Parameters<NonNullable<ReturnType<typeof latest>>['updateFromSSE']>[0])
|
|
83
|
+
})
|
|
84
|
+
expect(connectionHeaderValue()).toBe('n-2')
|
|
85
|
+
|
|
86
|
+
await act(async () => {
|
|
87
|
+
polls[1](statusA)
|
|
88
|
+
await vi.advanceTimersByTimeAsync(10)
|
|
89
|
+
})
|
|
90
|
+
expect(latest()?.connection.context).toBe('B')
|
|
91
|
+
expect(connectionHeaderValue()).toBe('n-2')
|
|
92
|
+
})
|