@skyhook-io/radar-app 1.18.2 → 1.20.0
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 +1 -1
- package/package.json +7 -7
- package/src/App.tsx +31 -6
- package/src/api/application-evidence.ts +63 -0
- package/src/api/argoSync.test.ts +22 -0
- package/src/api/client.audit-gating.test.tsx +48 -0
- package/src/api/client.kueuePosition.test.ts +32 -0
- package/src/api/client.kueueQueueWorkloads.test.tsx +71 -0
- package/src/api/client.resource-identity.test.ts +3 -0
- package/src/api/client.resourceIssues.test.tsx +239 -0
- package/src/api/client.resourcePath.test.ts +3 -0
- package/src/api/client.ts +285 -55
- package/src/api/config.ts +21 -0
- package/src/api/diagnose.test.ts +33 -2
- package/src/api/diagnose.ts +97 -3
- package/src/api/radarFeatures.render.test.tsx +33 -1
- package/src/api/radarFeatures.test.ts +47 -0
- package/src/api/radarFeatures.ts +41 -1
- package/src/api/rbac.settled.test.tsx +42 -0
- package/src/api/rbac.test.ts +18 -0
- package/src/api/rbac.ts +37 -7
- package/src/api/traffic.ts +9 -4
- package/src/api/usage-data.fixtures.ts +3 -1
- package/src/api/usage-data.test.tsx +134 -0
- package/src/api/usage-data.ts +35 -7
- package/src/api/workloadPodsPolling.test.ts +26 -0
- package/src/components/CloudConnectFlow.test.tsx +86 -0
- package/src/components/CloudConnectFlow.tsx +65 -27
- package/src/components/CloudFunnelButton.test.tsx +140 -5
- package/src/components/CloudFunnelButton.tsx +50 -9
- package/src/components/ConnectionErrorView.test.tsx +34 -0
- package/src/components/ConnectionErrorView.tsx +35 -11
- package/src/components/ContextSwitcher.tsx +5 -2
- package/src/components/SwitchAwareConnectionError.test.tsx +43 -0
- package/src/components/SwitchAwareConnectionError.tsx +85 -0
- package/src/components/application-evidence/ApplicationEvidenceAction.flow.test.tsx +234 -0
- package/src/components/application-evidence/ApplicationEvidenceAction.test.tsx +144 -0
- package/src/components/application-evidence/ApplicationEvidenceAction.tsx +218 -0
- package/src/components/capacity/CapacityDemand.tsx +3 -2
- package/src/components/capacity/demandSummary.test.ts +38 -0
- package/src/components/capacity/shared.tsx +12 -1
- package/src/components/cost/ApplicationCostTab.tsx +4 -0
- package/src/components/cost/CostTrendChart.tsx +2 -0
- package/src/components/cost/WorkloadCostTab.tsx +4 -0
- package/src/components/cost/source.test.ts +5 -0
- package/src/components/cost/source.ts +11 -0
- package/src/components/diagnose/AIMarkdown.tsx +4 -1
- package/src/components/diagnose/ActivityTurn.tsx +34 -14
- package/src/components/diagnose/AgentControls.tsx +53 -6
- package/src/components/diagnose/AgentSetupNotice.test.tsx +17 -0
- package/src/components/diagnose/AgentSetupNotice.tsx +22 -4
- package/src/components/diagnose/AgentSigninNotice.test.tsx +98 -0
- package/src/components/diagnose/AgentSigninNotice.tsx +61 -0
- package/src/components/diagnose/AnalysisStory.test.tsx +22 -0
- package/src/components/diagnose/AnalysisStory.tsx +17 -4
- package/src/components/diagnose/AssessmentCard.tsx +39 -8
- package/src/components/diagnose/ContinueInAgentButton.mounted.test.tsx +182 -0
- package/src/components/diagnose/ContinueInAgentButton.test.tsx +128 -0
- package/src/components/diagnose/ContinueInAgentButton.tsx +303 -0
- package/src/components/diagnose/DiagnoseContext.capacity.test.tsx +113 -0
- package/src/components/diagnose/DiagnoseContext.question.test.tsx +245 -0
- package/src/components/diagnose/DiagnoseContext.tsx +272 -10
- package/src/components/diagnose/DiagnoseSurface.test.tsx +54 -0
- package/src/components/diagnose/DiagnoseSurface.tsx +151 -134
- package/src/components/diagnose/EvidenceCard.tsx +67 -14
- package/src/components/diagnose/ExampleInvestigationLink.tsx +20 -0
- package/src/components/diagnose/Home.test.tsx +208 -5
- package/src/components/diagnose/Home.tsx +187 -36
- package/src/components/diagnose/InvestigationCapacityNotice.test.tsx +246 -0
- package/src/components/diagnose/InvestigationCapacityNotice.tsx +241 -0
- package/src/components/diagnose/InvestigationEvidencePane.story.test.tsx +97 -6
- package/src/components/diagnose/InvestigationEvidencePane.test.tsx +57 -0
- package/src/components/diagnose/InvestigationEvidencePane.tsx +59 -11
- package/src/components/diagnose/InvestigationEvidenceSections.tsx +50 -23
- package/src/components/diagnose/InvestigationView.tsx +249 -54
- package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +450 -0
- package/src/components/diagnose/LocalDiagnoseAction.tsx +365 -39
- package/src/components/diagnose/NextStepJump.test.tsx +92 -0
- package/src/components/diagnose/NextStepJump.tsx +75 -0
- package/src/components/diagnose/QuestionComposer.test.tsx +553 -0
- package/src/components/diagnose/QuestionComposer.tsx +495 -0
- package/src/components/diagnose/QuestionFocus.test.tsx +38 -0
- package/src/components/diagnose/QuestionFocus.tsx +123 -0
- package/src/components/diagnose/ResourcePicker.tsx +206 -0
- package/src/components/diagnose/StoryExcerpt.tsx +12 -3
- package/src/components/diagnose/assessmentCopy.ts +5 -0
- package/src/components/diagnose/exampleInvestigation.events.json +191 -0
- package/src/components/diagnose/exampleInvestigation.loadFailure.test.tsx +94 -0
- package/src/components/diagnose/exampleInvestigation.test.tsx +248 -0
- package/src/components/diagnose/exampleInvestigation.ts +121 -0
- package/src/components/diagnose/investigationCase.runs.test.tsx +328 -0
- package/src/components/diagnose/investigationCase.test.tsx +9 -1
- package/src/components/diagnose/investigationCase.ts +33 -1
- package/src/components/diagnose/investigationEvidence/adapters/applicationFindings.test.ts +739 -0
- package/src/components/diagnose/investigationEvidence/adapters/coverage.test.tsx +46 -0
- package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +58 -2
- package/src/components/diagnose/investigationEvidence/adapters/issues.ts +9 -0
- package/src/components/diagnose/investigationEvidence/adapters/posture.ts +29 -1
- package/src/components/diagnose/investigationEvidence/adapters/prometheus.test.ts +40 -0
- package/src/components/diagnose/investigationEvidence/adapters/prometheus.ts +27 -1
- package/src/components/diagnose/investigationEvidence/bodies/metrics.test.tsx +111 -0
- package/src/components/diagnose/investigationEvidence/bodies/metrics.tsx +67 -16
- package/src/components/diagnose/investigationEvidence/builder.ts +30 -0
- package/src/components/diagnose/investigationEvidence/excerpt.test.ts +18 -5
- package/src/components/diagnose/investigationEvidence/excerpt.ts +22 -11
- package/src/components/diagnose/investigationEvidence/index.ts +1 -1
- package/src/components/diagnose/investigationEvidence/navigation.tsx +2 -0
- package/src/components/diagnose/investigationEvidence/observations.ts +121 -2
- package/src/components/diagnose/investigationEvidence/projection.test.ts +85 -3
- package/src/components/diagnose/investigationEvidence/types.ts +7 -0
- package/src/components/diagnose/investigationEvidencePartition.ts +6 -1
- package/src/components/diagnose/investigationFocus.test.ts +271 -0
- package/src/components/diagnose/investigationFocus.ts +132 -0
- package/src/components/diagnose/investigationState.ts +28 -0
- package/src/components/diagnose/lastInvestigation.test.ts +95 -0
- package/src/components/diagnose/lastInvestigation.ts +58 -0
- package/src/components/diagnose/launch.test.ts +125 -1
- package/src/components/diagnose/launch.ts +57 -10
- package/src/components/diagnose/parts.test.tsx +20 -0
- package/src/components/diagnose/questionSuggestions.test.ts +111 -0
- package/src/components/diagnose/questionSuggestions.ts +150 -0
- package/src/components/diagnose/storyParts.test.tsx +13 -0
- package/src/components/diagnose/target.test.ts +143 -2
- package/src/components/diagnose/target.ts +109 -7
- package/src/components/diagnose/testdata/story-runs.json +474 -0
- package/src/components/diagnose/toolCallLabel.test.ts +10 -4
- package/src/components/diagnose/verdictText.test.tsx +87 -0
- package/src/components/diagnose/verdictText.ts +68 -0
- package/src/components/execution/BatchExecutionView.tsx +24 -11
- package/src/components/execution/JobSetAdmission.test.tsx +42 -0
- package/src/components/execution/JobSetAdmission.tsx +18 -3
- package/src/components/execution/JobSetMemberComparison.tsx +2 -1
- package/src/components/execution/runState.test.ts +14 -0
- package/src/components/execution/runState.ts +8 -0
- package/src/components/gitops/GitOpsView.rollbackGate.test.tsx +202 -0
- package/src/components/gitops/GitOpsView.syncRequest.test.tsx +369 -0
- package/src/components/gitops/GitOpsView.tsx +86 -17
- package/src/components/gitops/RemoteDestinationCloudHint.tsx +2 -3
- package/src/components/gitops/destination-toast.test.ts +1 -1
- package/src/components/gitops/destination-toast.ts +2 -2
- package/src/components/home/ClusterHealthCard.tsx +13 -39
- package/src/components/home/HomeAgentBlock.test.tsx +141 -0
- package/src/components/home/HomeAgentBlock.tsx +103 -0
- package/src/components/home/HomeDiagramCard.tsx +47 -0
- package/src/components/home/HomeView.tsx +86 -47
- package/src/components/home/MCPSetupDialog.test.tsx +95 -5
- package/src/components/home/MCPSetupDialog.tsx +30 -5
- package/src/components/home/ProblemsPanel.investigate.test.tsx +171 -0
- package/src/components/home/ProblemsPanel.test.tsx +3 -1
- package/src/components/home/RadarVersionLine.test.tsx +0 -14
- package/src/components/home/RadarVersionLine.tsx +3 -28
- package/src/components/home/TopologyPreview.test.tsx +73 -0
- package/src/components/home/TopologyPreview.tsx +120 -233
- package/src/components/home/TrafficSummary.test.tsx +63 -0
- package/src/components/home/TrafficSummary.tsx +135 -138
- package/src/components/home/mcpToolCatalog.ts +23 -10
- package/src/components/issues/IssuesPane.test.ts +11 -0
- package/src/components/issues/IssuesPane.tsx +15 -5
- package/src/components/issues/uncheckedSources.test.ts +20 -1
- package/src/components/issues/uncheckedSources.ts +18 -0
- package/src/components/kueue/KueuePendingPosition.tsx +35 -0
- package/src/components/kueue/useRelatedObjects.test.tsx +219 -0
- package/src/components/kueue/useRelatedReads.test.ts +56 -0
- package/src/components/kueue/useRelatedReads.ts +205 -0
- package/src/components/logs/MultiPodLogsTab.test.tsx +93 -0
- package/src/components/logs/MultiPodLogsTab.tsx +120 -0
- package/src/components/logs/PodLogsUnavailable.test.tsx +18 -0
- package/src/components/logs/PodLogsUnavailable.tsx +21 -0
- package/src/components/logs/RayClusterLogsTab.reselect.test.tsx +67 -0
- package/src/components/logs/RayClusterLogsTab.test.tsx +167 -0
- package/src/components/logs/RayClusterLogsTab.tsx +109 -0
- package/src/components/logs/ScheduledWorkloadLogsViewer.tsx +3 -2
- package/src/components/logs/rayClusterPods.ts +32 -0
- package/src/components/outageSince.test.ts +21 -0
- package/src/components/outageSince.ts +10 -0
- package/src/components/resource/PrometheusCharts.overlays.test.ts +12 -0
- package/src/components/resource/PrometheusCharts.tsx +3 -40
- package/src/components/resources/crd/CRDSchemaTab.test.tsx +28 -0
- package/src/components/resources/crd/CRDSchemaTab.tsx +13 -0
- package/src/components/resources/crd/host.tsx +14 -0
- package/src/components/resources/renderers/CustomResourceDefinitionRenderer.test.tsx +27 -0
- package/src/components/resources/renderers/CustomResourceDefinitionRenderer.tsx +12 -0
- package/src/components/resources/renderers/JobAdmissionRenderers.test.tsx +4 -1
- package/src/components/resources/renderers/JobAdmissionRenderers.tsx +4 -3
- package/src/components/resources/renderers/KueueHostRenderers.test.tsx +117 -0
- package/src/components/resources/renderers/KueueQueueRenderers.test.tsx +97 -0
- package/src/components/resources/renderers/KueueQueueRenderers.tsx +139 -0
- package/src/components/resources/renderers/KueueWorkloadRenderer.test.tsx +7 -1
- package/src/components/resources/renderers/KueueWorkloadRenderer.tsx +47 -7
- package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.test.tsx +67 -0
- package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.tsx +31 -0
- package/src/components/resources/renderers/RayClusterRenderer.test.tsx +81 -3
- package/src/components/resources/renderers/RayClusterRenderer.tsx +19 -4
- package/src/components/traffic/TrafficView.tsx +3 -3
- package/src/components/ui/Omnibar.investigate.test.tsx +105 -0
- package/src/components/ui/Omnibar.tsx +47 -3
- package/src/components/ui/RadarOmnibar.test.tsx +1 -0
- package/src/components/ui/RadarOmnibar.tsx +11 -0
- package/src/components/ui/command-items-crd.test.tsx +23 -0
- package/src/components/ui/command-items.ts +2 -1
- package/src/components/useContextSwitchFlow.test.tsx +61 -0
- package/src/components/useContextSwitchFlow.tsx +21 -4
- package/src/components/whats-new/WhatsNew.test.ts +10 -3
- package/src/components/whats-new/WhatsNew.tsx +5 -1
- package/src/components/whats-new/WhatsNewDialog.test.tsx +18 -4
- package/src/components/whats-new/releaseNotes.ts +136 -4
- package/src/components/workload/RelatedFindingsSection.test.tsx +126 -0
- package/src/components/workload/RelatedFindingsSection.tsx +80 -0
- package/src/components/workload/WorkloadView.test.ts +10 -1
- package/src/components/workload/WorkloadView.tsx +85 -98
- package/src/components/workload/issueResourceOpener.test.ts +20 -0
- package/src/components/workload/issueResourceOpener.ts +17 -0
- package/src/context/ConnectionContext.tsx +133 -60
- package/src/context/ConnectionProvider.retry.test.tsx +176 -0
- package/src/context/ContextSwitchContext.tsx +14 -1
- package/src/context/DiagnoseCustomization.tsx +3 -0
- package/src/context/clusterConnected.ts +10 -0
- package/src/contexts/CapabilitiesContext.tsx +6 -4
- package/src/hooks/useAgentSignin.test.tsx +190 -0
- package/src/hooks/useAgentSignin.ts +160 -0
- package/src/hooks/useApproveAfterSignin.test.tsx +108 -0
- package/src/hooks/useElementSize.ts +30 -0
- package/src/integrations/resourceHost.test.tsx +1 -0
- package/src/integrations/resourceHost.ts +5 -1
- package/src/integrations/resourceHosts.test.tsx +21 -4
- package/src/integrations/resourceHosts.tsx +12 -0
- package/src/main.tsx +5 -0
- package/src/utils/related-findings.ts +46 -0
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { act, useEffect } 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 { getApiBase } from '../../api/config'
|
|
7
|
+
import { ApiError } from '../../api/client'
|
|
8
|
+
import { RELATED_GET_RECHECK_MS, useRelatedObjects, type RelatedObjects } from './useRelatedReads'
|
|
9
|
+
|
|
10
|
+
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
|
|
11
|
+
let root: Root
|
|
12
|
+
let client: QueryClient
|
|
13
|
+
let listStatus: number
|
|
14
|
+
const requests: string[] = []
|
|
15
|
+
let latest: RelatedObjects | undefined
|
|
16
|
+
|
|
17
|
+
beforeEach(() => {
|
|
18
|
+
listStatus = 200
|
|
19
|
+
requests.length = 0
|
|
20
|
+
latest = undefined
|
|
21
|
+
client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
|
22
|
+
const element = document.createElement('div')
|
|
23
|
+
document.body.appendChild(element)
|
|
24
|
+
root = createRoot(element)
|
|
25
|
+
vi.stubGlobal('fetch', vi.fn(async (input: string) => {
|
|
26
|
+
const url = new URL(input, 'http://localhost')
|
|
27
|
+
requests.push(url.pathname)
|
|
28
|
+
if (url.pathname === '/api/resources/clusterqueues') {
|
|
29
|
+
return listStatus === 200
|
|
30
|
+
? new Response(JSON.stringify({ items: [{ metadata: { name: 'present' } }], coverage: { status: 'complete', scope: { type: 'cluster' }, read: {}, gaps: [] } }), { status: 200 })
|
|
31
|
+
: new Response(JSON.stringify(listStatus === 4030 ? { error: 'insufficient permissions' } : { error: 'no list', error_code: 'user_forbidden' }), { status: 403 })
|
|
32
|
+
}
|
|
33
|
+
if (url.pathname === '/api/resources/clusterqueues/_/present') return new Response(JSON.stringify({ resource: { metadata: { name: 'present' } } }), { status: 200 })
|
|
34
|
+
if (url.pathname === '/api/resources/clusterqueues/_/gone') return new Response(JSON.stringify({ error: 'gone', error_code: 'object_not_found' }), { status: 404 })
|
|
35
|
+
throw new Error(`Unexpected request: ${input}`)
|
|
36
|
+
}))
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
afterEach(async () => {
|
|
40
|
+
await act(async () => root.unmount())
|
|
41
|
+
client.clear()
|
|
42
|
+
document.body.replaceChildren()
|
|
43
|
+
vi.unstubAllGlobals()
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
function Probe({ onRead, version, names = ['present', 'gone'] }: { onRead: (read: RelatedObjects) => void; version?: string; names?: string[] }) {
|
|
47
|
+
const read = useRelatedObjects('clusterqueues', 'kueue.x-k8s.io', undefined, names, true, version)
|
|
48
|
+
useEffect(() => onRead(read))
|
|
49
|
+
return null
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function render() {
|
|
53
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
54
|
+
await vi.waitFor(() => expect(latest?.byName.gone.state).not.toBe('loading'), { timeout: 6000 })
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
it('answers every name from one list read when the viewer may list', async () => {
|
|
58
|
+
await render()
|
|
59
|
+
expect(latest?.byName.present.state).toBe('found')
|
|
60
|
+
expect(latest?.byName.gone).toEqual({ state: 'not_found' })
|
|
61
|
+
expect(requests).toEqual(['/api/resources/clusterqueues'])
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('reads each name with a GET when the viewer may get but not list the kind', async () => {
|
|
65
|
+
listStatus = 403
|
|
66
|
+
await render()
|
|
67
|
+
await vi.waitFor(() => expect(latest?.byName.present.state).toBe('found'), { timeout: 6000 })
|
|
68
|
+
expect(latest?.byName.gone).toEqual({ state: 'not_found' })
|
|
69
|
+
expect(latest?.all).toMatchObject({ state: 'unavailable', code: 'user_forbidden' })
|
|
70
|
+
expect(requests).toEqual(expect.arrayContaining(['/api/resources/clusterqueues/_/present', '/api/resources/clusterqueues/_/gone']))
|
|
71
|
+
// No watch events reach a viewer who can't list the kind, so the GETs re-read on their own.
|
|
72
|
+
const present = client.getQueryCache().findAll({ queryKey: ['resource', 'clusterqueues', '', 'present'] })[0]
|
|
73
|
+
const interval = (present?.options as { refetchInterval?: unknown } | undefined)?.refetchInterval
|
|
74
|
+
expect(typeof interval === 'function' ? interval(present) : interval).toBe(RELATED_GET_RECHECK_MS)
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
it('also reads by GET when an older Radar denies the list with an uncoded 403', async () => {
|
|
78
|
+
listStatus = 4030
|
|
79
|
+
await render()
|
|
80
|
+
await vi.waitFor(() => expect(latest?.byName.present.state).toBe('found'), { timeout: 6000 })
|
|
81
|
+
expect(latest?.all).toMatchObject({ state: 'unavailable', code: undefined })
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
it('doesn’t call a name missing from a list cached before the hook mounted, until the re-read lands', async () => {
|
|
85
|
+
// Another view read the list a moment ago, before the object existed.
|
|
86
|
+
client.setQueryData(['resources', 'clusterqueues', 'kueue.x-k8s.io', undefined, getApiBase()], { items: [{ metadata: { name: 'present' } }], coverage: { status: 'complete', scope: { type: 'cluster' }, read: {}, gaps: [] } }, { updatedAt: Date.now() - 5000 })
|
|
87
|
+
let release: (() => void) | undefined
|
|
88
|
+
vi.stubGlobal('fetch', vi.fn(() => new Promise<Response>(resolve => {
|
|
89
|
+
release = () => resolve(new Response(JSON.stringify({ items: [{ metadata: { name: 'present' } }, { metadata: { name: 'gone' } }], coverage: { status: 'complete', scope: { type: 'cluster' }, read: {}, gaps: [] } })))
|
|
90
|
+
})))
|
|
91
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
92
|
+
expect(latest?.byName.gone).toEqual({ state: 'loading' })
|
|
93
|
+
// Nor does an object found in that old list lend its state before the re-read lands.
|
|
94
|
+
expect(latest?.byName.present).toEqual({ state: 'loading' })
|
|
95
|
+
await act(async () => release?.())
|
|
96
|
+
await vi.waitFor(() => expect(latest?.byName.gone.state).toBe('found'))
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
it('re-reads, and stops claiming absence, when the object on screen changes', async () => {
|
|
100
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe version="1" onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
101
|
+
await vi.waitFor(() => expect(latest?.byName.gone).toEqual({ state: 'not_found' }))
|
|
102
|
+
let release: (() => void) | undefined
|
|
103
|
+
vi.stubGlobal('fetch', vi.fn(() => new Promise<Response>(resolve => {
|
|
104
|
+
release = () => resolve(new Response(JSON.stringify({ items: [{ metadata: { name: 'present' } }, { metadata: { name: 'gone' } }], coverage: { status: 'complete', scope: { type: 'cluster' }, read: {}, gaps: [] } })))
|
|
105
|
+
})))
|
|
106
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe version="2" onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
107
|
+
expect(latest?.byName.gone).toEqual({ state: 'loading' })
|
|
108
|
+
await act(async () => release?.())
|
|
109
|
+
await vi.waitFor(() => expect(latest?.byName.gone.state).toBe('found'))
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
it('makes no new request when the subject key stays the same', async () => {
|
|
113
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe version="a" onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
114
|
+
await vi.waitFor(() => expect(latest?.byName.gone).toEqual({ state: 'not_found' }))
|
|
115
|
+
const before = requests.length
|
|
116
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe version="a" onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
117
|
+
expect(requests.length).toBe(before)
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
it('neither retries nor polls a denied GET', async () => {
|
|
121
|
+
listStatus = 403
|
|
122
|
+
vi.mocked(fetch).mockImplementation(async (input: any) => {
|
|
123
|
+
const url = new URL(String(input), 'http://localhost')
|
|
124
|
+
requests.push(url.pathname)
|
|
125
|
+
return new Response(JSON.stringify({ error: 'no', error_code: 'user_forbidden' }), { status: 403 })
|
|
126
|
+
})
|
|
127
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe names={['denied']} onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
128
|
+
await vi.waitFor(() => expect(latest?.byName.denied).toMatchObject({ state: 'unavailable', code: 'user_forbidden' }))
|
|
129
|
+
const query = client.getQueryCache().findAll({ queryKey: ['resource', 'clusterqueues', '', 'denied'] })[0]
|
|
130
|
+
const interval = (query?.options as { refetchInterval?: unknown }).refetchInterval
|
|
131
|
+
expect(typeof interval === 'function' ? interval(query) : interval).toBe(false)
|
|
132
|
+
expect(requests.filter(path => path === '/api/resources/clusterqueues/_/denied')).toHaveLength(1)
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
it('re-reads fallback GETs when the subject changes, and holds absence until they land', async () => {
|
|
136
|
+
listStatus = 403
|
|
137
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe version="1" onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
138
|
+
await vi.waitFor(() => expect(latest?.byName.gone).toEqual({ state: 'not_found' }), { timeout: 6000 })
|
|
139
|
+
let release: (() => void) | undefined
|
|
140
|
+
vi.mocked(fetch).mockImplementation((input: any) => {
|
|
141
|
+
const path = new URL(String(input), 'http://localhost').pathname
|
|
142
|
+
requests.push(path)
|
|
143
|
+
if (path === '/api/resources/clusterqueues') return Promise.resolve(new Response(JSON.stringify({ error: 'no', error_code: 'user_forbidden' }), { status: 403 }))
|
|
144
|
+
if (path === '/api/resources/clusterqueues/_/gone') return new Promise<Response>(resolve => { release = () => resolve(new Response(JSON.stringify({ resource: { metadata: { name: 'gone' } } }))) })
|
|
145
|
+
return Promise.resolve(new Response(JSON.stringify({ resource: { metadata: { name: 'present' } } })))
|
|
146
|
+
})
|
|
147
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe version="2" onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
148
|
+
await vi.waitFor(() => expect(latest?.byName.gone).toEqual({ state: 'loading' }))
|
|
149
|
+
await act(async () => release?.())
|
|
150
|
+
await vi.waitFor(() => expect(latest?.byName.gone.state).toBe('found'))
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
it('doesn’t serve a GET result cached before mount as current, found or not', async () => {
|
|
154
|
+
listStatus = 403
|
|
155
|
+
client.setQueryData(['resource', 'clusterqueues', '', 'present', 'kueue.x-k8s.io', getApiBase()], { resource: { metadata: { name: 'present', stale: true } } }, { updatedAt: Date.now() - 5000 })
|
|
156
|
+
let release: (() => void) | undefined
|
|
157
|
+
vi.mocked(fetch).mockImplementation((input: any) => {
|
|
158
|
+
const path = new URL(String(input), 'http://localhost').pathname
|
|
159
|
+
requests.push(path)
|
|
160
|
+
if (path === '/api/resources/clusterqueues') return Promise.resolve(new Response(JSON.stringify({ error: 'no', error_code: 'user_forbidden' }), { status: 403 }))
|
|
161
|
+
if (path === '/api/resources/clusterqueues/_/present') return new Promise<Response>(resolve => { release = () => resolve(new Response(JSON.stringify({ resource: { metadata: { name: 'present' } } }))) })
|
|
162
|
+
return Promise.resolve(new Response(JSON.stringify({ error: 'gone', error_code: 'object_not_found' }), { status: 404 }))
|
|
163
|
+
})
|
|
164
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
165
|
+
await vi.waitFor(() => expect(latest?.all).toMatchObject({ state: 'unavailable' }))
|
|
166
|
+
expect(latest?.byName.present).toEqual({ state: 'loading' })
|
|
167
|
+
await act(async () => release?.())
|
|
168
|
+
await vi.waitFor(() => expect(latest?.byName.present).toEqual({ state: 'found', object: { metadata: { name: 'present' } } }))
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
it('doesn’t show a list error cached before mount as current', async () => {
|
|
172
|
+
const key = ['resources', 'clusterqueues', 'kueue.x-k8s.io', undefined, getApiBase()]
|
|
173
|
+
await client.prefetchQuery({ queryKey: key, queryFn: () => Promise.reject(new ApiError('timed out', 503, { error_code: 'kind_sync_timed_out' })), retry: false })
|
|
174
|
+
let release: (() => void) | undefined
|
|
175
|
+
vi.mocked(fetch).mockImplementation(() => new Promise<Response>(resolve => {
|
|
176
|
+
release = () => resolve(new Response(JSON.stringify({ items: [{ metadata: { name: 'present' } }], coverage: { status: 'complete', scope: { type: 'cluster' }, read: {}, gaps: [] } })))
|
|
177
|
+
}))
|
|
178
|
+
await new Promise(resolve => setTimeout(resolve, 5))
|
|
179
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
180
|
+
expect(latest?.byName.present).toEqual({ state: 'loading' })
|
|
181
|
+
await act(async () => release?.())
|
|
182
|
+
await vi.waitFor(() => expect(latest?.byName.present.state).toBe('found'))
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
it('doesn’t take a list read that started before the subject changed as the answer after it', async () => {
|
|
186
|
+
const pending: ((names: string[]) => void)[] = []
|
|
187
|
+
vi.mocked(fetch).mockImplementation(() => new Promise<Response>(resolve => {
|
|
188
|
+
pending.push(names => resolve(new Response(JSON.stringify({ items: names.map(name => ({ metadata: { name } })), coverage: { status: 'complete', scope: { type: 'cluster' }, read: {}, gaps: [] } }))))
|
|
189
|
+
}))
|
|
190
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe version="1" onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
191
|
+
expect(pending).toHaveLength(1)
|
|
192
|
+
// The subject changes while the first read is still in flight.
|
|
193
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe version="2" onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
194
|
+
await act(async () => pending[0](['present']))
|
|
195
|
+
expect(latest?.byName.gone).toEqual({ state: 'loading' })
|
|
196
|
+
await vi.waitFor(() => expect(pending).toHaveLength(2))
|
|
197
|
+
await act(async () => pending[1](['present', 'gone']))
|
|
198
|
+
await vi.waitFor(() => expect(latest?.byName.gone.state).toBe('found'))
|
|
199
|
+
})
|
|
200
|
+
|
|
201
|
+
it('doesn’t take a GET that started before the subject changed as the answer after it', async () => {
|
|
202
|
+
listStatus = 403
|
|
203
|
+
const pending: (() => void)[] = []
|
|
204
|
+
vi.mocked(fetch).mockImplementation((input: any) => {
|
|
205
|
+
const path = new URL(String(input), 'http://localhost').pathname
|
|
206
|
+
requests.push(path)
|
|
207
|
+
if (path === '/api/resources/clusterqueues') return Promise.resolve(new Response(JSON.stringify({ error: 'no', error_code: 'user_forbidden' }), { status: 403 }))
|
|
208
|
+
if (path === '/api/resources/clusterqueues/_/gone') return new Promise<Response>(resolve => { pending.push(() => resolve(new Response(JSON.stringify({ error: 'gone', error_code: 'object_not_found' }), { status: 404 }))) })
|
|
209
|
+
return Promise.resolve(new Response(JSON.stringify({ resource: { metadata: { name: 'present' } } })))
|
|
210
|
+
})
|
|
211
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe version="1" onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
212
|
+
await vi.waitFor(() => expect(pending).toHaveLength(1))
|
|
213
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Probe version="2" onRead={read => { latest = read }} /></QueryClientProvider>))
|
|
214
|
+
await act(async () => pending[0]())
|
|
215
|
+
expect(latest?.byName.gone).toEqual({ state: 'loading' })
|
|
216
|
+
await vi.waitFor(() => expect(pending).toHaveLength(2))
|
|
217
|
+
await act(async () => pending[1]())
|
|
218
|
+
await vi.waitFor(() => expect(latest?.byName.gone).toEqual({ state: 'not_found' }))
|
|
219
|
+
})
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { ApiError } from '../../api/client'
|
|
3
|
+
import { relatedReadFrom, relatedReadInList } from './useRelatedReads'
|
|
4
|
+
|
|
5
|
+
const fail = (status: number, error_code?: string) => new ApiError('failed', status, error_code ? { error_code } : {})
|
|
6
|
+
|
|
7
|
+
describe('relatedReadFrom', () => {
|
|
8
|
+
it('reports absence only when the server proved it', () => {
|
|
9
|
+
expect(relatedReadFrom({ error: fail(404, 'object_not_found') })).toEqual({ state: 'not_found' })
|
|
10
|
+
expect(relatedReadFrom({ error: fail(404) })).toEqual({ state: 'unconfirmed' })
|
|
11
|
+
expect(relatedReadFrom({ error: fail(404, 'namespace_not_found') })).toMatchObject({ state: 'unavailable', code: 'namespace_not_found' })
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
it('keeps denials and collector limits apart', () => {
|
|
15
|
+
expect(relatedReadFrom({ error: fail(403, 'user_forbidden') })).toMatchObject({ state: 'unavailable', code: 'user_forbidden' })
|
|
16
|
+
expect(relatedReadFrom({ error: fail(403) })).toMatchObject({ state: 'unavailable', code: undefined })
|
|
17
|
+
expect(relatedReadFrom({ error: fail(503, 'radar_forbidden') })).toMatchObject({ state: 'unavailable', code: 'radar_forbidden' })
|
|
18
|
+
expect(relatedReadFrom({ error: fail(503, 'kind_sync_timed_out') })).toMatchObject({ state: 'unavailable', code: 'kind_sync_timed_out' })
|
|
19
|
+
expect(relatedReadFrom({ error: fail(403, 'rbac_denied') })).toMatchObject({ code: 'user_forbidden' })
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('stays loading while the kind or connection is warming up', () => {
|
|
23
|
+
expect(relatedReadFrom({ error: fail(503, 'kind_sync_pending') })).toEqual({ state: 'loading' })
|
|
24
|
+
expect(relatedReadFrom({ error: fail(503, 'cluster_connecting') })).toEqual({ state: 'loading' })
|
|
25
|
+
expect(relatedReadFrom({ error: null })).toEqual({ state: 'loading' })
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it('lets a failed refresh outrank data kept from an earlier read', () => {
|
|
29
|
+
const object = { metadata: { name: 'cq' } }
|
|
30
|
+
expect(relatedReadFrom({ data: { resource: object }, error: null })).toEqual({ state: 'found', object })
|
|
31
|
+
expect(relatedReadFrom({ data: { resource: object }, error: fail(403, 'user_forbidden') })).toMatchObject({ state: 'unavailable' })
|
|
32
|
+
expect(relatedReadFrom({ data: { resource: object }, error: fail(404, 'object_not_found') })).toEqual({ state: 'not_found' })
|
|
33
|
+
})
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
describe('relatedReadInList', () => {
|
|
37
|
+
const items = [{ metadata: { name: 'small' } }]
|
|
38
|
+
it('finds a name, and calls it missing only from a complete list', () => {
|
|
39
|
+
expect(relatedReadInList({ data: items, coverage: { status: 'complete', scope: { type: 'cluster' } }, error: null }, 'small')).toEqual({ state: 'found', object: items[0] })
|
|
40
|
+
expect(relatedReadInList({ data: items, coverage: { status: 'complete', scope: { type: 'cluster' } }, error: null }, 'gone')).toEqual({ state: 'not_found' })
|
|
41
|
+
expect(relatedReadInList({ data: items, coverage: { status: 'partial', gaps: [{ code: 'radar_namespace_not_collected' }] }, error: null }, 'gone')).toMatchObject({ state: 'unavailable', code: 'radar_namespace_not_collected' })
|
|
42
|
+
// An older Radar sends a bare array, read as unknown coverage.
|
|
43
|
+
expect(relatedReadInList({ data: items, coverage: { status: 'unknown' }, error: null }, 'gone')).toEqual({ state: 'unconfirmed' })
|
|
44
|
+
expect(relatedReadInList({ data: items, coverage: { status: 'unknown' }, error: null }, 'small').state).toBe('found')
|
|
45
|
+
})
|
|
46
|
+
it('proves absence only within a scope it understands and that holds the asked namespace', () => {
|
|
47
|
+
expect(relatedReadInList({ data: items, coverage: { status: 'complete', scope: { type: 'namespaces', namespaces: { names: ['team'] } } }, error: null, namespace: 'team' }, 'gone')).toEqual({ state: 'not_found' })
|
|
48
|
+
expect(relatedReadInList({ data: items, coverage: { status: 'complete', scope: { type: 'namespaces', namespaces: { names: [] } } }, error: null, namespace: 'team' }, 'gone')).toEqual({ state: 'unconfirmed' })
|
|
49
|
+
expect(relatedReadInList({ data: items, coverage: { status: 'complete', scope: { type: 'galaxy' } }, error: null }, 'gone')).toEqual({ state: 'unconfirmed' })
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('lets a list error outrank the items it kept', () => {
|
|
53
|
+
expect(relatedReadInList({ data: items, coverage: { status: 'complete', scope: { type: 'cluster' } }, error: fail(403, 'user_forbidden') }, 'small')).toMatchObject({ state: 'unavailable', code: 'user_forbidden' })
|
|
54
|
+
expect(relatedReadInList({ error: null }, 'small')).toEqual({ state: 'loading' })
|
|
55
|
+
})
|
|
56
|
+
})
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { useEffect, useState } from 'react'
|
|
2
|
+
import { useQueries, useQueryClient } from '@tanstack/react-query'
|
|
3
|
+
import type { RelatedRead } from '@skyhook-io/k8s-ui/components/kueue/related-read'
|
|
4
|
+
import { canonicalReadCode, readActionFor } from '@skyhook-io/k8s-ui/utils/read-actions'
|
|
5
|
+
import { ApiError, isStillLoadingError, resourceQueryOptions, useResources } from '../../api/client'
|
|
6
|
+
import { getApiBase } from '../../api/config'
|
|
7
|
+
|
|
8
|
+
interface RelatedRef {
|
|
9
|
+
kind: string
|
|
10
|
+
group?: string
|
|
11
|
+
namespace?: string
|
|
12
|
+
name: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A failed refresh outranks data kept from an earlier success: a related
|
|
17
|
+
* object last seen present but now unreadable is unread, not present.
|
|
18
|
+
* Absence counts only when the server proved it (object_not_found).
|
|
19
|
+
*/
|
|
20
|
+
export function relatedReadFrom(query: { data?: { resource?: unknown }; error: unknown }): RelatedRead {
|
|
21
|
+
const error = query.error
|
|
22
|
+
if (!error) return query.data?.resource ? { state: 'found', object: query.data.resource } : { state: 'loading' }
|
|
23
|
+
if (isStillLoadingError(error)) return { state: 'loading' }
|
|
24
|
+
if (error instanceof ApiError) {
|
|
25
|
+
const code = canonicalReadCode(error.data?.error_code)
|
|
26
|
+
if (error.status === 404 && code === 'object_not_found') return { state: 'not_found' }
|
|
27
|
+
// An older Radar's uncoded 404 can't say the object is absent.
|
|
28
|
+
if (error.status === 404 && code === undefined) return { state: 'unconfirmed' }
|
|
29
|
+
// An uncoded failure (an older Radar) can't say whose access refused it: Radar's own or the viewer's.
|
|
30
|
+
return { state: 'unavailable', code: typeof code === 'string' ? code : undefined, message: error.message }
|
|
31
|
+
}
|
|
32
|
+
return { state: 'unavailable', message: error instanceof Error ? error.message : String(error) }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* One name looked up in a list read. Absence counts only when the list
|
|
37
|
+
* covered everything it was asked for; an older Radar that sends no coverage
|
|
38
|
+
* can confirm presence but not absence.
|
|
39
|
+
*/
|
|
40
|
+
interface ListCoverage { status: string; scope?: { type?: string; namespaces?: { names?: string[] } }; gaps?: { code: string; namespaces?: { names?: string[] } }[] }
|
|
41
|
+
|
|
42
|
+
/** The list says it read everything it was asked for, in a scope this client understands. */
|
|
43
|
+
function coversRequest(coverage: ListCoverage | undefined, namespace: string | undefined): boolean {
|
|
44
|
+
if (coverage?.status !== 'complete') return false
|
|
45
|
+
const scope = coverage.scope
|
|
46
|
+
if (scope?.type === 'cluster' || scope?.type === 'all_namespaces') return true
|
|
47
|
+
return scope?.type === 'namespaces' && !!namespace && !!scope.namespaces?.names?.includes(namespace)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function relatedReadInList(list: { data?: any[]; coverage?: ListCoverage; error: unknown; namespace?: string }, name: string): RelatedRead {
|
|
51
|
+
if (list.error) return relatedReadFrom({ error: list.error })
|
|
52
|
+
if (!list.data) return { state: 'loading' }
|
|
53
|
+
const object = list.data.find(item => item?.metadata?.name === name)
|
|
54
|
+
if (object) return { state: 'found', object }
|
|
55
|
+
if (coversRequest(list.coverage, list.namespace)) return { state: 'not_found' }
|
|
56
|
+
if (list.coverage?.status === 'partial') {
|
|
57
|
+
const gaps = list.coverage.gaps ?? []
|
|
58
|
+
const gap = gaps.find(candidate => !list.namespace || candidate.namespaces?.names?.includes(list.namespace)) ?? gaps[0]
|
|
59
|
+
return { state: 'unavailable', code: gap?.code, message: 'Radar’s list did not cover every object' }
|
|
60
|
+
}
|
|
61
|
+
return { state: 'unconfirmed' }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** How often a related list re-reads: watch events don't announce most additions, so a missing object is re-checked on this clock. */
|
|
65
|
+
export const RELATED_LIST_RECHECK_MS = 30_000
|
|
66
|
+
|
|
67
|
+
/** The viewer's own access refused the read, as the server's code says. */
|
|
68
|
+
const denied = (error: unknown) => error instanceof ApiError && readActionFor(error.data?.error_code) === 'user_access'
|
|
69
|
+
/** A refused list worth trying name by name: a coded denial, or an older Radar's uncoded 403. */
|
|
70
|
+
const listRefused = (error: unknown) => denied(error) || (error instanceof ApiError && error.status === 403 && !error.data?.error_code)
|
|
71
|
+
/** Absence the server proved: asking again won't change it before the next scheduled read. */
|
|
72
|
+
const provedAbsent = (error: unknown) => error instanceof ApiError && error.status === 404 && canonicalReadCode(error.data?.error_code) === 'object_not_found'
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* A key for the subject state that decides what its related reads must
|
|
76
|
+
* answer: the names it points at and its conditions' status, reason and
|
|
77
|
+
* generation — not counts or other status writes, which would re-read the
|
|
78
|
+
* lists on every admission.
|
|
79
|
+
*/
|
|
80
|
+
export function relatedReadKey(subject: any, names: string[], conditionTypes: string[]): string {
|
|
81
|
+
const conditions = (subject?.status?.conditions ?? [])
|
|
82
|
+
.filter((condition: any) => conditionTypes.includes(condition?.type))
|
|
83
|
+
.map((condition: any) => [condition.type, condition.status, condition.reason, condition.observedGeneration])
|
|
84
|
+
return JSON.stringify([[...names].sort(), conditions])
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface RelatedObjects {
|
|
88
|
+
/** Each requested name's read state. */
|
|
89
|
+
byName: Record<string, RelatedRead>
|
|
90
|
+
/** The whole list: found with its items, or why it wasn't read. */
|
|
91
|
+
all: RelatedRead<any[]>
|
|
92
|
+
/** Whether the list covered every object: unknown when the Radar sends no coverage. */
|
|
93
|
+
completeness: 'complete' | 'partial' | 'unknown'
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Reads named objects of one kind as the viewer. One list read serves every
|
|
98
|
+
* name — it computes no relationships, unlike a resource GET — and re-reads
|
|
99
|
+
* on RELATED_LIST_RECHECK_MS. A viewer allowed to get but not list the kind
|
|
100
|
+
* reads each name with a GET instead, so a list denial never hides an object
|
|
101
|
+
* the viewer may open. The cache is scoped to the API base because Radar Hub
|
|
102
|
+
* points one query client at several clusters, where same-named queues are
|
|
103
|
+
* different objects.
|
|
104
|
+
*/
|
|
105
|
+
export function useRelatedObjects(kind: string, group: string | undefined, namespace: string | undefined, names: string[], enabled = true, subjectState?: string): RelatedObjects {
|
|
106
|
+
const queryClient = useQueryClient()
|
|
107
|
+
const cacheScope = getApiBase()
|
|
108
|
+
const [refused, setRefused] = useState(false)
|
|
109
|
+
const listKey = ['resources', kind, group, namespace, cacheScope]
|
|
110
|
+
// Marked before this hook's own observer starts, so a fetch someone else began earlier counts as old.
|
|
111
|
+
const [mark, setMark] = useState(() => markFor(queryClient.getQueryState(listKey)))
|
|
112
|
+
const list = useResources<any>(kind, namespace, group, { enabled, cacheScope, refetchInterval: refused ? false : RELATED_LIST_RECHECK_MS, refetchOnMount: 'always', staleTime: 0 })
|
|
113
|
+
const { data, coverage, refetch } = list
|
|
114
|
+
// The object on screen updates live. When its relevant state changes (the
|
|
115
|
+
// caller's key: the names it points at and the conditions that decide what
|
|
116
|
+
// is shown, not every status write), a read from before the change can't
|
|
117
|
+
// answer for after it, so mark the change and re-read.
|
|
118
|
+
const [seenState, setSeenState] = useState(subjectState)
|
|
119
|
+
const [changes, setChanges] = useState(0)
|
|
120
|
+
if (subjectState !== seenState) {
|
|
121
|
+
setSeenState(subjectState)
|
|
122
|
+
setMark(markFor(queryClient.getQueryState(listKey)))
|
|
123
|
+
setChanges(changes + 1)
|
|
124
|
+
}
|
|
125
|
+
const fresh = answered(queryClient.getQueryState(listKey), mark)
|
|
126
|
+
useEffect(() => {
|
|
127
|
+
if (enabled && !fresh && !list.isFetching) void refetch()
|
|
128
|
+
}, [enabled, fresh, list.isFetching, refetch])
|
|
129
|
+
// An error read before the mark is no answer either.
|
|
130
|
+
const error = fresh ? list.error : null
|
|
131
|
+
// A refused list isn't polled again: the names are read one by one instead
|
|
132
|
+
// (with their own freshness marks), and it is re-read when the subject changes.
|
|
133
|
+
if (listRefused(list.error) !== refused) setRefused(listRefused(list.error))
|
|
134
|
+
// An older Radar answers a list denial with an uncoded 403; a GET still says what the viewer may open.
|
|
135
|
+
const listDenied = listRefused(list.error)
|
|
136
|
+
const gets = useRelatedReads(names.map(name => ({ kind, group, namespace, name })), enabled && listDenied, changes)
|
|
137
|
+
const all: RelatedRead<any[]> = !fresh ? { state: 'loading' } : error ? relatedReadFrom({ error }) : data ? { state: 'found', object: data } : { state: 'loading' }
|
|
138
|
+
// Until a read started after the mark lands, the list answers nothing, present or absent: it may lend a tone.
|
|
139
|
+
const byName = Object.fromEntries(names.map((name, index) => [name, listDenied ? gets[index] : !fresh ? { state: 'loading' } as RelatedRead : relatedReadInList({ data, coverage, error, namespace }, name)]))
|
|
140
|
+
const completeness = coverage?.status === 'complete' || coverage?.status === 'partial' ? coverage.status : 'unknown'
|
|
141
|
+
return { byName, all, completeness }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
interface QueryProgress { dataUpdateCount: number; errorUpdateCount: number; fetchStatus?: string; isFetching?: boolean }
|
|
145
|
+
interface ReadMark { settled: number; inFlight: boolean }
|
|
146
|
+
|
|
147
|
+
/** Where a query stood at a moment that later answers must postdate. */
|
|
148
|
+
function markFor(state: QueryProgress | undefined): ReadMark {
|
|
149
|
+
return { settled: (state?.dataUpdateCount ?? 0) + (state?.errorUpdateCount ?? 0), inFlight: state?.isFetching ?? state?.fetchStatus === 'fetching' }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* A read started after the mark has settled: one more settled read than at
|
|
154
|
+
* the mark, or two when a read was already in flight then (that one started
|
|
155
|
+
* before the mark, so its answer may predate it).
|
|
156
|
+
*/
|
|
157
|
+
function answered(state: QueryProgress | undefined, mark: ReadMark): boolean {
|
|
158
|
+
return (state?.dataUpdateCount ?? 0) + (state?.errorUpdateCount ?? 0) >= mark.settled + (mark.inFlight ? 2 : 1)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* How often a GET read of a related object repeats. Such a read computes the
|
|
163
|
+
* object's relationships, so it repeats less often than a list; a viewer who
|
|
164
|
+
* may get but not list a kind receives no watch events for it, so it must
|
|
165
|
+
* repeat at all.
|
|
166
|
+
*/
|
|
167
|
+
export const RELATED_GET_RECHECK_MS = 60_000
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Reads single objects through the resource GET, re-reading on mount whatever
|
|
171
|
+
* the host QueryClient's defaults. A coded denial is final for the view: it
|
|
172
|
+
* isn't retried or polled. `changes` counts changes of the object on screen;
|
|
173
|
+
* each one marks every read, and until a read started after the mark lands
|
|
174
|
+
* the object reads as loading, found or not.
|
|
175
|
+
*/
|
|
176
|
+
export function useRelatedReads(refs: RelatedRef[], enabled = true, changes: string | number = 0): RelatedRead[] {
|
|
177
|
+
const cacheScope = getApiBase()
|
|
178
|
+
const queryClient = useQueryClient()
|
|
179
|
+
const bases = refs.map(ref => resourceQueryOptions<unknown>(ref.kind, ref.namespace ?? '', ref.name, ref.group, { enabled, cacheScope, refetchInterval: RELATED_GET_RECHECK_MS }))
|
|
180
|
+
const keys = bases.map(base => JSON.stringify(base.queryKey))
|
|
181
|
+
// Marked before this hook's observers start, and again at each subject change.
|
|
182
|
+
const [marks, setMarks] = useState<Record<string, ReadMark>>(() => Object.fromEntries(bases.map((base, index) => [keys[index], markFor(queryClient.getQueryState(base.queryKey))])))
|
|
183
|
+
const [seenChanges, setSeenChanges] = useState(changes)
|
|
184
|
+
const unmarked = keys.filter(key => !marks[key])
|
|
185
|
+
if (changes !== seenChanges || unmarked.length > 0) {
|
|
186
|
+
const remark = changes !== seenChanges
|
|
187
|
+
setSeenChanges(changes)
|
|
188
|
+
setMarks(Object.fromEntries(bases.map((base, index) => [keys[index], remark || !marks[keys[index]] ? markFor(queryClient.getQueryState(base.queryKey)) : marks[keys[index]]])))
|
|
189
|
+
}
|
|
190
|
+
const results = useQueries({
|
|
191
|
+
queries: bases.map(base => ({
|
|
192
|
+
...base,
|
|
193
|
+
staleTime: 0,
|
|
194
|
+
refetchOnMount: 'always' as const,
|
|
195
|
+
retry: (failureCount: number, error: unknown) => !denied(error) && !provedAbsent(error) && base.retry(failureCount, error),
|
|
196
|
+
refetchInterval: (query: { state: { error: unknown } }) => denied(query.state.error) ? false : base.refetchInterval(query),
|
|
197
|
+
})),
|
|
198
|
+
})
|
|
199
|
+
const stale = results.map((_, index) => !marks[keys[index]] || !answered(queryClient.getQueryState(bases[index].queryKey), marks[keys[index]]))
|
|
200
|
+
const idleStale = JSON.stringify(keys.filter((_, index) => enabled && stale[index] && !results[index].isFetching))
|
|
201
|
+
useEffect(() => {
|
|
202
|
+
for (const key of JSON.parse(idleStale) as string[]) void queryClient.refetchQueries({ queryKey: JSON.parse(key), exact: true })
|
|
203
|
+
}, [idleStale, queryClient])
|
|
204
|
+
return results.map((result, index) => stale[index] ? { state: 'loading' } : relatedReadFrom(result))
|
|
205
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { act } from 'react'
|
|
3
|
+
import { createRoot } from 'react-dom/client'
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
5
|
+
|
|
6
|
+
const state = vi.hoisted(() => ({ logs: {} as Record<string, { data?: unknown; error?: unknown }>, viewer: [] as string[], requested: [] as string[] }))
|
|
7
|
+
vi.mock('../../api/client', async (original) => ({
|
|
8
|
+
...await original<typeof import('../../api/client')>(),
|
|
9
|
+
usePodLogs: (_ns: string, pod: string) => { if (pod) state.requested.push(pod); return state.logs[pod] ?? {} },
|
|
10
|
+
useResource: () => ({ data: { status: { phase: 'Running' } } }),
|
|
11
|
+
}))
|
|
12
|
+
vi.mock('./LogsViewer', () => ({ LogsViewer: ({ podName }: { podName: string }) => { state.viewer.push(podName); return <div>viewer:{podName}</div> } }))
|
|
13
|
+
|
|
14
|
+
const { ApiError } = await import('../../api/client')
|
|
15
|
+
const { MultiPodLogsTab } = await import('./MultiPodLogsTab')
|
|
16
|
+
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
|
|
17
|
+
|
|
18
|
+
const pods = [{ kind: 'Pod', namespace: 'ml', name: 'gone-pod' }, { kind: 'Pod', namespace: 'ml', name: 'live-pod' }]
|
|
19
|
+
let host: HTMLDivElement
|
|
20
|
+
let root: ReturnType<typeof createRoot>
|
|
21
|
+
beforeEach(() => { state.logs = {}; state.viewer = []; state.requested = []; host = document.createElement('div'); root = createRoot(host) })
|
|
22
|
+
afterEach(() => act(() => root.unmount()))
|
|
23
|
+
|
|
24
|
+
function render(selected: string, onSelectPod = vi.fn()) {
|
|
25
|
+
act(() => root.render(<MultiPodLogsTab pods={pods} namespace="ml" selectedPod={selected} onSelectPod={onSelectPod} />))
|
|
26
|
+
return onSelectPod
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
describe('MultiPodLogsTab', () => {
|
|
30
|
+
it('explains a Pod Radar can no longer find instead of rendering a blank pane, and keeps the other Pods', () => {
|
|
31
|
+
state.logs['gone-pod'] = { error: new ApiError('Pod not found', 404) }
|
|
32
|
+
const onSelect = render('gone-pod')
|
|
33
|
+
expect(host.textContent).toContain("Radar can't find gone-pod")
|
|
34
|
+
expect(state.viewer).toEqual([])
|
|
35
|
+
const live = [...host.querySelectorAll('button')].find(button => button.textContent === 'live-pod')!
|
|
36
|
+
act(() => live.click())
|
|
37
|
+
expect(onSelect).toHaveBeenCalledWith('live-pod')
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
it('shows the server reason for a denied log read', () => {
|
|
41
|
+
state.logs['live-pod'] = { error: new ApiError('no access to pod logs in namespace ml: requires get pods/log', 403) }
|
|
42
|
+
render('live-pod')
|
|
43
|
+
expect(host.textContent).toContain('requires get pods/log')
|
|
44
|
+
expect(host.textContent).not.toContain("can't find")
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('keeps a selected Pod that left the list selectable, marked, beside the one that remains', () => {
|
|
48
|
+
state.logs['gone-pod'] = { data: { containers: ['app'] } }
|
|
49
|
+
const onSelect = vi.fn()
|
|
50
|
+
act(() => root.render(<MultiPodLogsTab pods={[pods[1]]} namespace="ml" selectedPod="gone-pod" onSelectPod={onSelect} />))
|
|
51
|
+
const chips = [...host.querySelectorAll('button')].map(button => button.textContent)
|
|
52
|
+
expect(chips).toEqual(['live-pod', 'gone-pod· not in this list'])
|
|
53
|
+
expect(host.textContent).toContain('viewer:gone-pod')
|
|
54
|
+
expect(onSelect).not.toHaveBeenCalled()
|
|
55
|
+
act(() => [...host.querySelectorAll('button')][0].click())
|
|
56
|
+
expect(onSelect).toHaveBeenCalledWith('live-pod')
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
it('keeps the selected Pod\'s viewer when the list empties', () => {
|
|
60
|
+
state.logs['gone-pod'] = { data: { containers: ['app'] } }
|
|
61
|
+
act(() => root.render(<MultiPodLogsTab pods={[]} namespace="ml" selectedPod="gone-pod" onSelectPod={vi.fn()} emptyMessage="This RayCluster has no Pods right now." />))
|
|
62
|
+
expect(host.textContent).toContain('viewer:gone-pod')
|
|
63
|
+
expect(host.textContent).toContain('gone-pod· not in this list')
|
|
64
|
+
expect(host.textContent).not.toContain('This RayCluster has no Pods right now.')
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('opens the default Pod when nothing is selected', () => {
|
|
68
|
+
const onSelect = vi.fn()
|
|
69
|
+
act(() => root.render(<MultiPodLogsTab pods={pods} namespace="ml" selectedPod={null} onSelectPod={onSelect} defaultPod="live-pod" />))
|
|
70
|
+
expect(onSelect).toHaveBeenCalledWith('live-pod')
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('shows the caller\'s reason instead of a viewer for a Pod with no output yet', () => {
|
|
74
|
+
state.logs['live-pod'] = { data: { containers: ['app'] } }
|
|
75
|
+
act(() => root.render(<MultiPodLogsTab pods={pods} namespace="ml" selectedPod="live-pod" onSelectPod={vi.fn()} selectedPodNote="Not scheduled" />))
|
|
76
|
+
expect(host.textContent).toContain('No logs shown for live-pod')
|
|
77
|
+
expect(host.textContent).toContain('Not scheduled')
|
|
78
|
+
expect(host.textContent).not.toContain('viewer:live-pod')
|
|
79
|
+
expect(state.requested).not.toContain('live-pod')
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
it('uses the caller\'s empty message when there are no Pods', () => {
|
|
83
|
+
act(() => root.render(<MultiPodLogsTab pods={[]} namespace="ml" selectedPod={null} onSelectPod={vi.fn()} emptyMessage="This RayCluster has no Pods right now." />))
|
|
84
|
+
expect(host.textContent).toContain('This RayCluster has no Pods right now.')
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
it('keeps the viewer for a Pod whose containers loaded even if a later refetch fails', () => {
|
|
88
|
+
state.logs['live-pod'] = { data: { containers: ['app'] }, error: new ApiError('Pod not found', 404) }
|
|
89
|
+
render('live-pod')
|
|
90
|
+
expect(host.textContent).toContain('viewer:live-pod')
|
|
91
|
+
expect(host.textContent).not.toContain("can't find")
|
|
92
|
+
})
|
|
93
|
+
})
|