@skyhook-io/radar-app 1.19.0 → 1.20.1

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.
Files changed (198) hide show
  1. package/README.md +1 -1
  2. package/package.json +5 -5
  3. package/src/App.tsx +37 -9
  4. package/src/api/application-evidence.ts +63 -0
  5. package/src/api/argoSync.test.ts +22 -0
  6. package/src/api/client.audit-gating.test.tsx +48 -0
  7. package/src/api/client.kueuePosition.test.ts +32 -0
  8. package/src/api/client.kueueQueueWorkloads.test.tsx +71 -0
  9. package/src/api/client.resource-identity.test.ts +3 -0
  10. package/src/api/client.resourceIssues.test.tsx +239 -0
  11. package/src/api/client.resourcePath.test.ts +3 -0
  12. package/src/api/client.ts +353 -64
  13. package/src/api/config.ts +21 -0
  14. package/src/api/diagnose.ts +4 -0
  15. package/src/api/helmInventory.test.tsx +108 -0
  16. package/src/api/radarFeatures.render.test.tsx +33 -1
  17. package/src/api/radarFeatures.test.ts +47 -0
  18. package/src/api/radarFeatures.ts +42 -1
  19. package/src/api/rbac.settled.test.tsx +42 -0
  20. package/src/api/rbac.test.ts +18 -0
  21. package/src/api/rbac.ts +37 -7
  22. package/src/api/traffic.ts +9 -4
  23. package/src/api/usage-data.fixtures.ts +3 -1
  24. package/src/api/usage-data.test.tsx +134 -0
  25. package/src/api/usage-data.ts +35 -7
  26. package/src/api/workloadPodsPolling.test.ts +26 -0
  27. package/src/components/CloudConnectFlow.test.tsx +86 -0
  28. package/src/components/CloudConnectFlow.tsx +65 -27
  29. package/src/components/CloudFunnelButton.test.tsx +140 -5
  30. package/src/components/CloudFunnelButton.tsx +50 -9
  31. package/src/components/ConnectionErrorView.test.tsx +34 -0
  32. package/src/components/ConnectionErrorView.tsx +35 -11
  33. package/src/components/ContextSwitcher.tsx +5 -2
  34. package/src/components/SwitchAwareConnectionError.test.tsx +43 -0
  35. package/src/components/SwitchAwareConnectionError.tsx +85 -0
  36. package/src/components/application-evidence/ApplicationEvidenceAction.flow.test.tsx +234 -0
  37. package/src/components/application-evidence/ApplicationEvidenceAction.test.tsx +144 -0
  38. package/src/components/application-evidence/ApplicationEvidenceAction.tsx +218 -0
  39. package/src/components/capacity/CapacityDemand.tsx +3 -2
  40. package/src/components/capacity/demandSummary.test.ts +38 -0
  41. package/src/components/capacity/shared.tsx +12 -1
  42. package/src/components/cost/ApplicationCostTab.tsx +4 -0
  43. package/src/components/cost/CostTrendChart.tsx +2 -0
  44. package/src/components/cost/WorkloadCostTab.tsx +4 -0
  45. package/src/components/cost/source.test.ts +5 -0
  46. package/src/components/cost/source.ts +11 -0
  47. package/src/components/curl/ServiceCurlAvailability.test.tsx +32 -0
  48. package/src/components/curl/ServiceCurlButton.tsx +2 -2
  49. package/src/components/diagnose/AIMarkdown.tsx +3 -0
  50. package/src/components/diagnose/AgentSetupNotice.test.tsx +17 -0
  51. package/src/components/diagnose/AgentSetupNotice.tsx +21 -3
  52. package/src/components/diagnose/ContinueInAgentButton.mounted.test.tsx +182 -0
  53. package/src/components/diagnose/ContinueInAgentButton.test.tsx +128 -0
  54. package/src/components/diagnose/ContinueInAgentButton.tsx +303 -0
  55. package/src/components/diagnose/DiagnoseContext.question.test.tsx +1 -1
  56. package/src/components/diagnose/DiagnoseContext.tsx +68 -2
  57. package/src/components/diagnose/DiagnoseSurface.tsx +58 -113
  58. package/src/components/diagnose/ExampleInvestigationLink.tsx +20 -0
  59. package/src/components/diagnose/Home.test.tsx +26 -0
  60. package/src/components/diagnose/Home.tsx +20 -1
  61. package/src/components/diagnose/InvestigationEvidenceSections.tsx +45 -22
  62. package/src/components/diagnose/InvestigationView.tsx +94 -26
  63. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +450 -0
  64. package/src/components/diagnose/LocalDiagnoseAction.tsx +354 -35
  65. package/src/components/diagnose/NextStepJump.test.tsx +92 -0
  66. package/src/components/diagnose/NextStepJump.tsx +75 -0
  67. package/src/components/diagnose/QuestionComposer.tsx +8 -0
  68. package/src/components/diagnose/exampleInvestigation.events.json +191 -0
  69. package/src/components/diagnose/exampleInvestigation.loadFailure.test.tsx +94 -0
  70. package/src/components/diagnose/exampleInvestigation.test.tsx +248 -0
  71. package/src/components/diagnose/exampleInvestigation.ts +121 -0
  72. package/src/components/diagnose/investigationCase.test.tsx +50 -1
  73. package/src/components/diagnose/investigationEvidence/adapters/applicationFindings.test.ts +739 -0
  74. package/src/components/diagnose/investigationEvidence/adapters/coverage.test.tsx +72 -0
  75. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +50 -2
  76. package/src/components/diagnose/investigationEvidence/adapters/helm.ts +51 -16
  77. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +9 -0
  78. package/src/components/diagnose/investigationEvidence/adapters/listings.ts +34 -4
  79. package/src/components/diagnose/investigationEvidence/adapters/resource.ts +3 -2
  80. package/src/components/diagnose/investigationEvidence/builder.ts +30 -0
  81. package/src/components/diagnose/investigationEvidence/observations.ts +121 -2
  82. package/src/components/diagnose/investigationEvidence/projection.test.ts +85 -3
  83. package/src/components/diagnose/investigationEvidence/types.ts +5 -0
  84. package/src/components/diagnose/investigationState.ts +28 -0
  85. package/src/components/diagnose/lastInvestigation.test.ts +95 -0
  86. package/src/components/diagnose/lastInvestigation.ts +58 -0
  87. package/src/components/diagnose/launch.test.ts +125 -1
  88. package/src/components/diagnose/launch.ts +57 -10
  89. package/src/components/diagnose/toolCallLabel.test.ts +10 -4
  90. package/src/components/execution/BatchExecutionView.tsx +24 -11
  91. package/src/components/execution/JobSetAdmission.test.tsx +42 -0
  92. package/src/components/execution/JobSetAdmission.tsx +18 -3
  93. package/src/components/execution/JobSetMemberComparison.tsx +2 -1
  94. package/src/components/execution/runState.test.ts +14 -0
  95. package/src/components/execution/runState.ts +8 -0
  96. package/src/components/gitops/GitOpsView.rollbackGate.test.tsx +202 -0
  97. package/src/components/gitops/GitOpsView.syncRequest.test.tsx +369 -0
  98. package/src/components/gitops/GitOpsView.tsx +86 -17
  99. package/src/components/gitops/RemoteDestinationCloudHint.tsx +2 -3
  100. package/src/components/gitops/destination-toast.test.ts +1 -1
  101. package/src/components/gitops/destination-toast.ts +2 -2
  102. package/src/components/helm/HelmDrawerFrame.tsx +101 -0
  103. package/src/components/helm/HelmDrawerRouting.test.tsx +86 -0
  104. package/src/components/helm/HelmReleaseDrawer.tsx +23 -86
  105. package/src/components/helm/HelmView.tsx +213 -71
  106. package/src/components/helm/ObservedHelmNotice.tsx +146 -0
  107. package/src/components/helm/ObservedHelmRelease.test.tsx +261 -0
  108. package/src/components/helm/ObservedHelmReleaseDrawer.test.tsx +80 -0
  109. package/src/components/helm/ObservedHelmReleaseDrawer.tsx +228 -0
  110. package/src/components/helm/OwnedResources.tsx +4 -2
  111. package/src/components/home/ClusterHealthCard.restricted.test.tsx +76 -0
  112. package/src/components/home/ClusterHealthCard.tsx +28 -5
  113. package/src/components/home/HelmSummary.tsx +23 -4
  114. package/src/components/home/HelmSummary.unread.test.ts +16 -0
  115. package/src/components/home/HomeAgentBlock.test.tsx +31 -3
  116. package/src/components/home/HomeAgentBlock.tsx +20 -4
  117. package/src/components/home/HomeDiagramCard.tsx +47 -0
  118. package/src/components/home/HomeView.tsx +81 -41
  119. package/src/components/home/MCPSetupDialog.test.tsx +126 -10
  120. package/src/components/home/MCPSetupDialog.tsx +33 -5
  121. package/src/components/home/ProblemsPanel.investigate.test.tsx +171 -0
  122. package/src/components/home/ProblemsPanel.test.tsx +3 -1
  123. package/src/components/home/TopologyPreview.test.tsx +73 -0
  124. package/src/components/home/TopologyPreview.tsx +120 -233
  125. package/src/components/home/TrafficSummary.test.tsx +63 -0
  126. package/src/components/home/TrafficSummary.tsx +135 -138
  127. package/src/components/home/mcpToolCatalog.ts +67 -14
  128. package/src/components/issues/IssuesPane.test.ts +11 -0
  129. package/src/components/issues/IssuesPane.tsx +15 -5
  130. package/src/components/issues/uncheckedSources.test.ts +22 -1
  131. package/src/components/issues/uncheckedSources.ts +21 -0
  132. package/src/components/kueue/KueuePendingPosition.tsx +35 -0
  133. package/src/components/kueue/useRelatedObjects.test.tsx +219 -0
  134. package/src/components/kueue/useRelatedReads.test.ts +56 -0
  135. package/src/components/kueue/useRelatedReads.ts +205 -0
  136. package/src/components/logs/MultiPodLogsTab.test.tsx +93 -0
  137. package/src/components/logs/MultiPodLogsTab.tsx +120 -0
  138. package/src/components/logs/PodLogsUnavailable.test.tsx +18 -0
  139. package/src/components/logs/PodLogsUnavailable.tsx +21 -0
  140. package/src/components/logs/RayClusterLogsTab.reselect.test.tsx +67 -0
  141. package/src/components/logs/RayClusterLogsTab.test.tsx +167 -0
  142. package/src/components/logs/RayClusterLogsTab.tsx +109 -0
  143. package/src/components/logs/ScheduledWorkloadLogsViewer.tsx +3 -2
  144. package/src/components/logs/rayClusterPods.ts +32 -0
  145. package/src/components/outageSince.test.ts +21 -0
  146. package/src/components/outageSince.ts +10 -0
  147. package/src/components/resource/PrometheusCharts.overlays.test.ts +12 -0
  148. package/src/components/resource/PrometheusCharts.tsx +3 -40
  149. package/src/components/resources/crd/CRDSchemaTab.test.tsx +28 -0
  150. package/src/components/resources/crd/CRDSchemaTab.tsx +13 -0
  151. package/src/components/resources/crd/host.tsx +14 -0
  152. package/src/components/resources/renderers/CustomResourceDefinitionRenderer.test.tsx +27 -0
  153. package/src/components/resources/renderers/CustomResourceDefinitionRenderer.tsx +12 -0
  154. package/src/components/resources/renderers/JobAdmissionRenderers.test.tsx +4 -1
  155. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +4 -3
  156. package/src/components/resources/renderers/KueueHostRenderers.test.tsx +117 -0
  157. package/src/components/resources/renderers/KueueQueueRenderers.test.tsx +97 -0
  158. package/src/components/resources/renderers/KueueQueueRenderers.tsx +139 -0
  159. package/src/components/resources/renderers/KueueWorkloadRenderer.test.tsx +7 -1
  160. package/src/components/resources/renderers/KueueWorkloadRenderer.tsx +47 -7
  161. package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.test.tsx +67 -0
  162. package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.tsx +31 -0
  163. package/src/components/resources/renderers/RayClusterRenderer.test.tsx +81 -3
  164. package/src/components/resources/renderers/RayClusterRenderer.tsx +19 -4
  165. package/src/components/resources/renderers/ServiceRenderer.test.tsx +15 -2
  166. package/src/components/resources/renderers/ServiceRenderer.tsx +1 -1
  167. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.test.tsx +160 -0
  168. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.tsx +128 -0
  169. package/src/components/traffic/TrafficView.tsx +3 -3
  170. package/src/components/ui/command-items-crd.test.tsx +23 -0
  171. package/src/components/ui/command-items.ts +2 -1
  172. package/src/components/useContextSwitchFlow.test.tsx +61 -0
  173. package/src/components/useContextSwitchFlow.tsx +21 -4
  174. package/src/components/whats-new/WhatsNew.test.ts +10 -3
  175. package/src/components/whats-new/WhatsNew.tsx +5 -1
  176. package/src/components/whats-new/WhatsNewDialog.test.tsx +17 -3
  177. package/src/components/whats-new/releaseNotes.ts +77 -4
  178. package/src/components/workload/RelatedFindingsSection.test.tsx +126 -0
  179. package/src/components/workload/RelatedFindingsSection.tsx +80 -0
  180. package/src/components/workload/WorkloadView.test.ts +10 -1
  181. package/src/components/workload/WorkloadView.tsx +85 -98
  182. package/src/components/workload/issueResourceOpener.test.ts +20 -0
  183. package/src/components/workload/issueResourceOpener.ts +17 -0
  184. package/src/context/ConnectionContext.tsx +133 -60
  185. package/src/context/ConnectionProvider.retry.test.tsx +176 -0
  186. package/src/context/ContextSwitchContext.tsx +14 -1
  187. package/src/context/DiagnoseCustomization.tsx +3 -0
  188. package/src/context/clusterConnected.ts +10 -0
  189. package/src/contexts/CapabilitiesContext.tsx +8 -4
  190. package/src/hooks/useElementSize.ts +30 -0
  191. package/src/hooks/useResolvedGitOpsOwner.test.ts +22 -0
  192. package/src/hooks/useResolvedGitOpsOwner.ts +6 -3
  193. package/src/integrations/resourceHost.test.tsx +1 -0
  194. package/src/integrations/resourceHost.ts +5 -1
  195. package/src/integrations/resourceHosts.test.tsx +21 -4
  196. package/src/integrations/resourceHosts.tsx +17 -0
  197. package/src/main.tsx +5 -0
  198. package/src/utils/related-findings.ts +46 -0
@@ -8,6 +8,7 @@ const SOURCE_LINES: Record<string, string> = {
8
8
  resources: "Some resources couldn't be checked, so their issues may be missing.",
9
9
  custom_resources: "Custom resources couldn't be checked, so failing ones may be missing.",
10
10
  karpenter: "Karpenter resources couldn't be checked, so NodePool and NodeClaim issues may be missing.",
11
+ kueue: "Kueue resources couldn't be checked, so blocked runs and broken queues may be missing.",
11
12
  };
12
13
 
13
14
  // For a source this version doesn't know, sent by a newer Radar.
@@ -33,6 +34,9 @@ function helmLine({ reason, namespaces }: UncheckedSource): string {
33
34
  if (reason === "collector_access_denied") {
34
35
  return `Helm releases ${where}couldn't be checked because Radar's service account isn't allowed to impersonate users, so ${missing}.`;
35
36
  }
37
+ if (reason === "caller_access_denied") {
38
+ return `Radar can't read Helm's release Secrets ${where ? where.trim() : "here"}, so ${missing}.`;
39
+ }
36
40
  return `Helm releases ${where}couldn't be checked, so ${missing}.`;
37
41
  }
38
42
 
@@ -46,6 +50,11 @@ function kindsLine(source: UncheckedSource): string | undefined {
46
50
  }
47
51
  const names = nameList(kinds);
48
52
  switch (source.reason) {
53
+ case "caller_access_denied":
54
+ if (source.source === "kueue") {
55
+ return `You can't read ${names}, so Radar can't tell you whether a queue your runs wait on is stopped on purpose or broken.`;
56
+ }
57
+ return `You can't read ${names}, so Radar didn't check the issues that depend on them.`;
49
58
  case "kind_sync_pending":
50
59
  return `Still loading ${names}, so their issues may be missing.`;
51
60
  case "kind_sync_failed":
@@ -72,3 +81,15 @@ export function uncheckedSourceLines(sources: IssuesResponse["unchecked_sources"
72
81
  }
73
82
  return unknown ? [...known, UNKNOWN_SOURCE_LINE] : [...known];
74
83
  }
84
+
85
+ /** Why an empty per-resource answer can't be read as "none", for the gaps that name the resource. */
86
+ export function uncheckedSubjectWhy(sources: UncheckedSource[] | undefined): string | undefined {
87
+ const first = sources?.[0];
88
+ if (!first) return undefined;
89
+ const plural = [...new Set((first.kinds ?? []).map((k) => englishPlural(k.kind)))];
90
+ const kinds = plural.length > 0 ? nameList(plural) : undefined;
91
+ if (first.reason === "caller_access_denied") {
92
+ return kinds ? `you can't read ${kinds}, which this check needs` : "you can't read what this check needs";
93
+ }
94
+ return kinds ? `${kinds} couldn't be checked` : "some checks couldn't run";
95
+ }
@@ -0,0 +1,35 @@
1
+ import { KueuePendingPositionValue } from '@skyhook-io/k8s-ui/components/resources/KueuePendingPosition'
2
+ import { getRadarUpgradeRequirement } from '@skyhook-io/k8s-ui'
3
+ import { useKueuePendingPosition } from '../../api/client'
4
+
5
+ interface Props {
6
+ namespace: string
7
+ name: string
8
+ uid?: string
9
+ /** Cache invalidation input; the endpoint reads the current spec.queueName. */
10
+ queueName?: string
11
+ requeueAt?: string
12
+ }
13
+
14
+ /**
15
+ * Kueue's reported position for a Workload eligible for a visibility lookup.
16
+ * Callers render it only for such a Workload; an answer that belongs
17
+ * to another incarnation of the name, or that the server judged ineligible,
18
+ * is never shown.
19
+ */
20
+ export function KueuePendingPosition({ namespace, name, uid, queueName, requeueAt }: Props) {
21
+ const query = useKueuePendingPosition(namespace, name, uid, queueName, true)
22
+ const current = query.data?.uid === uid && query.data?.eligible ? query.data : undefined
23
+ const upgrade = getRadarUpgradeRequirement(query.error) ?? undefined
24
+ const ineligible = query.data?.uid === uid && query.data?.eligible === false
25
+ if (ineligible) return <span className="text-theme-text-tertiary">No pending position to look up for the current Workload state.</span>
26
+ return <KueuePendingPositionValue
27
+ position={current?.position}
28
+ loading={query.isPending}
29
+ error={current ? undefined : query.error?.message}
30
+ refreshFailed={Boolean(current && query.isRefetchError)}
31
+ upgrade={upgrade}
32
+ onRetry={() => { void query.refetch() }}
33
+ requeueAt={requeueAt}
34
+ />
35
+ }
@@ -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
+ }