@skyhook-io/radar-app 1.18.0 → 1.18.2
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 +6 -0
- package/package.json +2 -3
- package/src/App.tsx +43 -12
- package/src/api/client.deleteResource.test.tsx +111 -0
- package/src/api/client.gitops-destination.test.tsx +55 -0
- package/src/api/client.resource-list.test.ts +76 -0
- package/src/api/client.resourceAudit.test.tsx +57 -0
- package/src/api/client.resourcePath.test.ts +107 -0
- package/src/api/client.ts +197 -57
- package/src/api/quotas.ts +9 -20
- package/src/api/radarFeatures.ts +2 -0
- package/src/api/resourceLists.test.ts +84 -0
- package/src/api/resourceLists.ts +71 -0
- package/src/components/capacity/CapacityDemand.tsx +6 -3
- package/src/components/capacity/CapacityOverview.tsx +14 -7
- package/src/components/capacity/CapacityPoolDetail.tsx +7 -5
- package/src/components/capacity/ClusterSchedulingCard.tsx +3 -3
- package/src/components/capacity/shared.tsx +9 -5
- package/src/components/cnpg/CNPGOverview.tsx +4 -1
- package/src/components/cnpg/CNPGView.tsx +1 -0
- package/src/components/cnpg/actions/useCNPGWriteGuard.tsx +1 -0
- package/src/components/compare/CompareResourcePicker.test.tsx +58 -0
- package/src/components/compare/CompareViewRoute.tsx +5 -1
- package/src/components/compare/useCompareCandidates.ts +1 -1
- package/src/components/compare/useCompareLauncher.tsx +4 -2
- package/src/components/diagnose/ApplyDialog.test.tsx +10 -0
- package/src/components/diagnose/ApplyDialog.tsx +8 -1
- package/src/components/diagnose/AssessmentCard.tsx +60 -0
- package/src/components/diagnose/DiagnoseSurface.tsx +5 -0
- package/src/components/diagnose/InvestigationEvidencePane.test.tsx +62 -2
- package/src/components/diagnose/InvestigationEvidenceSections.tsx +6 -5
- package/src/components/diagnose/InvestigationView.tsx +47 -13
- package/src/components/diagnose/StoryExcerpt.tsx +24 -5
- package/src/components/diagnose/assessmentCopy.ts +11 -0
- package/src/components/diagnose/investigationEvidence/adapters/changes.ts +36 -1
- package/src/components/diagnose/investigationEvidence/adapters/crossplane.test.tsx +85 -0
- package/src/components/diagnose/investigationEvidence/adapters/issues.ts +1 -0
- package/src/components/diagnose/investigationEvidence/adapters/listCoverage.test.ts +415 -0
- package/src/components/diagnose/investigationEvidence/adapters/prometheus.test.ts +2 -1
- package/src/components/diagnose/investigationEvidence/adapters/prometheus.ts +2 -1
- package/src/components/diagnose/investigationEvidence/adapters/resource.ts +107 -8
- package/src/components/diagnose/investigationEvidence/adapters/testdata/crossplane-paused-get-resource.json +28 -0
- package/src/components/diagnose/investigationEvidence/bodies/index.tsx +2 -0
- package/src/components/diagnose/investigationEvidence/bodies/inventory.tsx +66 -16
- package/src/components/diagnose/investigationEvidence/bodies/workload.tsx +5 -1
- package/src/components/diagnose/investigationEvidence/builder.ts +16 -2
- package/src/components/diagnose/investigationEvidence/cardParts.tsx +7 -2
- package/src/components/diagnose/investigationEvidence/excerpt.ts +2 -0
- package/src/components/diagnose/investigationEvidence/identity.test.ts +1 -1
- package/src/components/diagnose/investigationEvidence/observations.ts +8 -3
- package/src/components/diagnose/investigationEvidence/projection.test.ts +81 -4
- package/src/components/diagnose/investigationEvidence/types.ts +15 -0
- package/src/components/diagnose/investigationEvidencePresentation.test.ts +36 -2
- package/src/components/diagnose/investigationEvidencePresentation.ts +33 -8
- package/src/components/diagnose/storyParts.test.tsx +53 -0
- package/src/components/diagnose/toolCallLabel.test.ts +9 -0
- package/src/components/diagnose/toolCallLabel.ts +2 -0
- package/src/components/execution/BatchExecutionView.image-browse.test.tsx +46 -0
- package/src/components/execution/BatchExecutionView.tsx +6 -4
- package/src/components/gitops/GitOpsView.identity.test.tsx +113 -0
- package/src/components/gitops/GitOpsView.tsx +62 -40
- package/src/components/gitops/useDestinationCluster.ts +2 -1
- package/src/components/helm/ArtifactHubSourceSearch.test.tsx +124 -0
- package/src/components/helm/ArtifactHubSourceSearch.tsx +240 -0
- package/src/components/helm/ChartBrowser.tsx +9 -8
- package/src/components/helm/HelmReleaseDrawer.tsx +6 -2
- package/src/components/helm/HelmView.tsx +34 -23
- package/src/components/helm/InstallWizard.tsx +6 -2
- package/src/components/helm/TrackChartSourceDialog.render.test.tsx +269 -96
- package/src/components/helm/TrackChartSourceDialog.tsx +607 -104
- package/src/components/helm/ValuesViewer.test.tsx +1 -0
- package/src/components/helm/ValuesViewer.tsx +4 -2
- package/src/components/home/ClusterHealthCard.tsx +28 -21
- package/src/components/home/MCPSetupDialog.test.tsx +27 -2
- package/src/components/home/MCPSetupDialog.tsx +14 -2
- package/src/components/home/mcpToolCatalog.ts +39 -2
- package/src/components/issues/IssuesPane.render.test.tsx +5 -5
- package/src/components/nav/PrimaryNavRail.tsx +34 -2
- package/src/components/product-hunt/ProductHuntNotice.render.test.tsx +120 -0
- package/src/components/product-hunt/ProductHuntNotice.test.ts +121 -0
- package/src/components/product-hunt/ProductHuntNotice.tsx +202 -0
- package/src/components/product-hunt/launchWindow.ts +78 -0
- package/src/components/product-hunt/useProductHuntRailEntry.test.tsx +76 -0
- package/src/components/product-hunt/useProductHuntRailEntry.ts +27 -0
- package/src/components/resource/PrometheusCharts.overlays.test.ts +45 -0
- package/src/components/resource/PrometheusCharts.tsx +2 -2
- package/src/components/resources/CompositeRenderer.tsx +4 -0
- package/src/components/resources/ResourcesView.tsx +30 -68
- package/src/components/resources/renderers/PodRenderer.tsx +4 -1
- package/src/components/settings/LocalConnectionSettings.tsx +1 -0
- package/src/components/settings/MyPermissionsDialog.tsx +12 -9
- package/src/components/traffic/TrafficSourcePill.test.tsx +110 -0
- package/src/components/traffic/TrafficSourcePill.tsx +111 -0
- package/src/components/traffic/TrafficView.tsx +9 -55
- package/src/components/ui/DiagnosticsOverlay.test.ts +25 -0
- package/src/components/ui/DiagnosticsOverlay.tsx +2 -1
- package/src/components/ui/Omnibar.note.test.tsx +141 -0
- package/src/components/ui/Omnibar.tsx +82 -18
- package/src/components/ui/RadarOmnibar.test.tsx +201 -0
- package/src/components/ui/RadarOmnibar.tsx +39 -4
- package/src/components/ui/SearchSyntaxHelp.test.tsx +39 -0
- package/src/components/ui/SearchSyntaxHelp.tsx +23 -2
- package/src/components/ui/UpdateNotification.manual.test.tsx +177 -0
- package/src/components/ui/UpdateNotification.test.tsx +4 -1
- package/src/components/ui/UpdateNotification.tsx +61 -10
- package/src/components/ui/omnibar-match.test.ts +15 -8
- package/src/components/ui/omnibar-match.ts +11 -6
- package/src/components/ui/searchCoverage.fixtures.ts +16 -0
- package/src/components/ui/searchCoverageNote.test.ts +245 -0
- package/src/components/ui/searchCoverageNote.ts +222 -0
- package/src/components/usage-data/UsageDataPrompt.tsx +19 -1
- package/src/components/whats-new/WhatsNew.test.ts +10 -0
- package/src/components/whats-new/WhatsNew.tsx +5 -4
- package/src/components/whats-new/WhatsNewDialog.test.tsx +20 -0
- package/src/components/whats-new/releaseNotes.ts +57 -5
- package/src/components/workload/WorkloadView.tsx +18 -6
- package/src/components/workspace/layout.tsx +2 -1
- package/src/contexts/CapabilitiesContext.tsx +1 -0
- package/src/hooks/useGitOpsWriteGuard.test.tsx +126 -2
- package/src/hooks/useGitOpsWriteGuard.ts +25 -3
- package/src/hooks/useResolvedGitOpsOwner.ts +14 -9
- package/src/hooks/useResourceCounts.ts +2 -0
- package/src/index.css +87 -4
- package/src/index.ts +7 -0
- package/src/utils/artifacthub.test.ts +18 -0
- package/src/utils/artifacthub.ts +9 -0
package/README.md
CHANGED
|
@@ -66,3 +66,9 @@ Host apps can override Radar's runtime behavior without passing props:
|
|
|
66
66
|
- `setCredentialsMode(mode)` — fetch credentials mode (`same-origin` | `include` | `omit`).
|
|
67
67
|
|
|
68
68
|
Call these before mounting `<RadarApp>`.
|
|
69
|
+
|
|
70
|
+
## Resource list responses
|
|
71
|
+
|
|
72
|
+
New Radar instances advertise `features.resourceReadCoverage` and return `{items, coverage, kind, group}` for resource lists, with `columns`/`cells` when table mode is requested. `coverage` describes the scope the answer covers, what Radar read of it, and coded gaps; namespace sets are `{count, names?}`, listing every member or none, and a gap's set may instead be `{"extent": "all"}` or `{"extent": "unknown"}`. A failed read answers `{error, error_code, coverage?}`. Lists fail when there is no usable inventory: nothing readable, an oversized result, or a changed connection. Partial lists with loading gaps refetch with 5s, 10s, 20s, then 30s delays; complete coverage or a changed query resets the backoff.
|
|
73
|
+
|
|
74
|
+
Hosts making their own requests can call `normalizeResourceList(body)` from this package. It reads the body by its shape, so it needs no capabilities: a bare array or a table envelope without `coverage` (an older instance) produces `coverage.status: 'unknown'`, which cannot establish absence. The adapter returns `{items, coverage, printerTable}`. `fetchResourceList(kind, options)` uses Radar's configured API base/authentication and applies a server list budget, which older instances ignore.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skyhook-io/radar-app",
|
|
3
|
-
"version": "1.18.
|
|
3
|
+
"version": "1.18.2",
|
|
4
4
|
"description": "Radar's full web UI as a reusable React component. Used by Radar's own binary and by external consumers like Radar Cloud.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"yaml": "^2.9.1"
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
|
-
"@skyhook-io/k8s-ui": ">=1.
|
|
45
|
+
"@skyhook-io/k8s-ui": ">=1.18.1",
|
|
46
46
|
"@tanstack/react-query": ">=5",
|
|
47
47
|
"@xyflow/react": ">=12.0.0",
|
|
48
48
|
"clsx": ">=2",
|
|
@@ -57,7 +57,6 @@
|
|
|
57
57
|
"@eslint/js": "^10.0.1",
|
|
58
58
|
"@playwright/test": "^1.62.0",
|
|
59
59
|
"@skyhook-io/k8s-ui": "*",
|
|
60
|
-
"@tailwindcss/typography": "^0.5.20",
|
|
61
60
|
"@tailwindcss/vite": "^4.3.3",
|
|
62
61
|
"@tanstack/react-query": "^5.103.1",
|
|
63
62
|
"@types/node": "^26.6.2",
|
package/src/App.tsx
CHANGED
|
@@ -9,7 +9,7 @@ import { DebugOverlay } from './components/DebugOverlay'
|
|
|
9
9
|
import { GlobalDiagnoseButton } from './components/diagnose/LocalDiagnoseAction'
|
|
10
10
|
import { investigationWorkspaceSearch, isInvestigationWorkspacePath, useDiagnoseLayout } from './components/diagnose/DiagnoseContext'
|
|
11
11
|
import { DiagnoseSurface } from './components/diagnose/DiagnoseSurface'
|
|
12
|
-
import { TopologyGraph, TopologySearch, TopologyBreadcrumb, TopologyFilterSidebar, TopologyControls, FreshnessControl, gitOpsRouteForKind, gitOpsRouteForResource, ScopePill, PaneLoader } from '@skyhook-io/k8s-ui'
|
|
12
|
+
import { TopologyGraph, TopologySearch, TopologyBreadcrumb, TopologyFilterSidebar, TopologyControls, FreshnessControl, gitOpsRouteForKind, gitOpsRouteForResource, ScopePill, PaneLoader, usePhoneLayout, PHONE_MEDIA_QUERY } from '@skyhook-io/k8s-ui'
|
|
13
13
|
import { resetNavigationMap } from '@skyhook-io/k8s-ui/utils/navigation'
|
|
14
14
|
import { topologyNodeResourceKind } from '@skyhook-io/k8s-ui/utils/topology-neighborhood'
|
|
15
15
|
import { useAPIResources, findAPIResourceForRoute } from './api/apiResources'
|
|
@@ -57,6 +57,8 @@ import { UpdateNotification } from './components/ui/UpdateNotification'
|
|
|
57
57
|
import { openWhatsNew, useWhatsNewStatus, WhatsNew } from './components/whats-new/WhatsNew'
|
|
58
58
|
import { useUsageData, useUsageRecording } from './api/usage-data'
|
|
59
59
|
import { UsageDataPrompt } from './components/usage-data/UsageDataPrompt'
|
|
60
|
+
import { ProductHuntNotice } from './components/product-hunt/ProductHuntNotice'
|
|
61
|
+
import { useProductHuntRailEntry } from './components/product-hunt/useProductHuntRailEntry'
|
|
60
62
|
import { ShortcutHelpOverlay } from './components/ui/ShortcutHelpOverlay'
|
|
61
63
|
import { DiagnosticsOverlay, type DiagnosticsFocus } from './components/ui/DiagnosticsOverlay'
|
|
62
64
|
import { useEventSource } from './hooks/useEventSource'
|
|
@@ -132,6 +134,11 @@ const FLEET_MODE_KINDS = new Set<NodeKind>([
|
|
|
132
134
|
// Extended MainView type that includes traffic and cost
|
|
133
135
|
type ExtendedMainView = MainView | 'traffic' | 'cost' | 'capacity' | 'cnpg' | 'workload' | 'checks' | 'gitops' | 'compare' | 'helmCompare' | 'issues' | 'applications' | 'investigations'
|
|
134
136
|
|
|
137
|
+
// Views that have been laid out for phone width (640px and below). The rest
|
|
138
|
+
// keep their desktop width on a phone and scroll sideways; add a view here in
|
|
139
|
+
// the PR that gives it a phone layout.
|
|
140
|
+
const PHONE_READY_VIEWS: ReadonlySet<ExtendedMainView> = new Set<ExtendedMainView>(['issues', 'resources', 'helm', 'home', 'topology', 'capacity'])
|
|
141
|
+
|
|
135
142
|
// Extract view from URL path
|
|
136
143
|
function getViewFromPath(pathname: string): ExtendedMainView {
|
|
137
144
|
if (pathname.replace(/\/+$/, '') === '/helm/compare') return 'helmCompare'
|
|
@@ -548,6 +555,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
|
|
|
548
555
|
}, [location.search, navigate, takeover, goHost, viewMemory, kindFilterStore])
|
|
549
556
|
|
|
550
557
|
const whatsNewStatus = useWhatsNewStatus()
|
|
558
|
+
const productHuntRailEntry = useProductHuntRailEntry()
|
|
551
559
|
|
|
552
560
|
const navigateToPath = useCallback((path: string) => {
|
|
553
561
|
navigate(withCrossViewParams(path, location.search))
|
|
@@ -598,7 +606,11 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
|
|
|
598
606
|
const [showPolicyEffect, setShowPolicyEffect] = useState(false)
|
|
599
607
|
// Topology filter state
|
|
600
608
|
const [visibleKinds, setVisibleKinds] = useState<Set<NodeKind>>(() => new Set(DEFAULT_VISIBLE_KINDS))
|
|
601
|
-
|
|
609
|
+
// Phones start with the filters collapsed to their icon rail: expanded, the
|
|
610
|
+
// panel took two thirds of the width from the graph.
|
|
611
|
+
const [filterSidebarCollapsed, setFilterSidebarCollapsed] = useState(
|
|
612
|
+
() => typeof window !== 'undefined' && window.matchMedia(PHONE_MEDIA_QUERY).matches,
|
|
613
|
+
)
|
|
602
614
|
// Topology node-search → canvas focus request (nonce lets the same node re-focus)
|
|
603
615
|
const [topologyFocus, setTopologyFocus] = useState<{ id: string; nonce: number } | null>(null)
|
|
604
616
|
// The topology pane element — the search overlay portals into it so its
|
|
@@ -660,8 +672,11 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
|
|
|
660
672
|
// actually renders) — see further down.
|
|
661
673
|
const drawerExpanded = !!selectedResource && searchParams.get('full') === '1'
|
|
662
674
|
|
|
663
|
-
// On
|
|
664
|
-
const isMobile =
|
|
675
|
+
// On a phone there's no room for the side drawer: a resource detail is always full-screen.
|
|
676
|
+
const isMobile = usePhoneLayout()
|
|
677
|
+
// Views with a deliberate phone layout. On a phone every other view keeps
|
|
678
|
+
// its desktop width and scrolls sideways rather than squeezing.
|
|
679
|
+
const phoneScroll = isMobile && !PHONE_READY_VIEWS.has(mainView)
|
|
665
680
|
|
|
666
681
|
// On a history Pop (back/forward) the URL is authoritative. The URL-write
|
|
667
682
|
// effect, running with not-yet-synced state, would otherwise write the stale
|
|
@@ -1800,10 +1815,14 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
|
|
|
1800
1815
|
{/* Preserve the ~800px content floor: the rail is a fixed-width sibling, so
|
|
1801
1816
|
the outer minimum must include it (176px pinned / 56px collapsed) or the
|
|
1802
1817
|
content column (min-w-0, shrinkable) would fall below the old desktop
|
|
1803
|
-
floor at small windows. Embedded mode has no rail → plain 800.
|
|
1818
|
+
floor at small windows. Embedded mode has no rail → plain 800.
|
|
1819
|
+
Phones get a 360px floor instead (the narrowest current phones): the
|
|
1820
|
+
content column clips horizontally, so the 800px floor hid the right half
|
|
1821
|
+
of every view with no way to scroll to it. Views without a phone layout
|
|
1822
|
+
scroll sideways at desktop width instead (see PHONE_READY_VIEWS). */}
|
|
1804
1823
|
<div
|
|
1805
1824
|
className={`relative flex bg-theme-base ${navCustomization.embedded ? 'h-full min-h-0' : 'h-screen'}`}
|
|
1806
|
-
style={{ minWidth: 800 + (showNavRail ? (navRailEffectivePinned ? 176 : 56) : 0) }}
|
|
1825
|
+
style={{ minWidth: (isMobile ? 360 : 800) + (showNavRail ? (navRailEffectivePinned ? 176 : 56) : 0) }}
|
|
1807
1826
|
>
|
|
1808
1827
|
{showNavRail && (
|
|
1809
1828
|
<PrimaryNavRail
|
|
@@ -1815,6 +1834,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
|
|
|
1815
1834
|
onOpenSettings={() => openSettings()}
|
|
1816
1835
|
accountSlot={<UserMenu variant="rail" pinned={navRailEffectivePinned} />}
|
|
1817
1836
|
whatsNew={whatsNewStatus.available ? { unread: whatsNewStatus.unread, onOpen: openWhatsNew } : undefined}
|
|
1837
|
+
productHunt={productHuntRailEntry}
|
|
1818
1838
|
/>
|
|
1819
1839
|
)}
|
|
1820
1840
|
{/* `relative` makes this column the containing block for the absolute
|
|
@@ -2061,7 +2081,10 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
|
|
|
2061
2081
|
{/* inert while a fullscreen detail overlay covers the views — keeps the
|
|
2062
2082
|
retained background list out of the focus order + a11y tree (the visual
|
|
2063
2083
|
cover already blocks pointer events). */}
|
|
2064
|
-
{(contentReady || shellDuringSync) && <div className=
|
|
2084
|
+
{(contentReady || shellDuringSync) && <div className={phoneScroll ? 'flex-1 flex overflow-x-auto overflow-y-hidden' : 'flex-1 flex overflow-hidden'} inert={expandedView}>
|
|
2085
|
+
{/* A view without a phone layout keeps its desktop width on a phone and
|
|
2086
|
+
scrolls sideways; `contents` leaves every other layout untouched. */}
|
|
2087
|
+
<div className={phoneScroll ? 'flex flex-1 min-h-0 min-w-[800px]' : 'contents'}>
|
|
2065
2088
|
{/* Search included, not just the path: selection inside a view rides in
|
|
2066
2089
|
the query (?resource=, ?release=), so a path-only key would still
|
|
2067
2090
|
strand a crash on the view that produced it. */}
|
|
@@ -2170,8 +2193,12 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
|
|
|
2170
2193
|
</div>
|
|
2171
2194
|
</div>
|
|
2172
2195
|
) : (
|
|
2173
|
-
|
|
2174
|
-
|
|
2196
|
+
// On a phone, its own positioned box so the filter overlay below
|
|
2197
|
+
// anchors to the topology area, not the whole content column.
|
|
2198
|
+
<div className={isMobile ? 'relative flex flex-1 min-w-0 min-h-0' : 'contents'}>
|
|
2199
|
+
{/* Filter sidebar. On phones, expanded it overlays the graph
|
|
2200
|
+
instead of squeezing it. */}
|
|
2201
|
+
<div className={isMobile && !filterSidebarCollapsed ? 'absolute inset-y-0 left-0 z-20 flex shadow-theme-lg' : 'contents'}>
|
|
2175
2202
|
<TopologyFilterSidebar
|
|
2176
2203
|
nodes={filterSidebarNodes}
|
|
2177
2204
|
visibleKinds={visibleKinds}
|
|
@@ -2186,6 +2213,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
|
|
|
2186
2213
|
console.log(`[topology] User requested to show hidden kind: ${kind}`)
|
|
2187
2214
|
}}
|
|
2188
2215
|
/>
|
|
2216
|
+
</div>
|
|
2189
2217
|
|
|
2190
2218
|
<div ref={setTopologyPane} className="flex-1 relative">
|
|
2191
2219
|
<TopologyGraph
|
|
@@ -2205,8 +2233,9 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
|
|
|
2205
2233
|
{/* Overlay row: left column (namespace breadcrumb over search)
|
|
2206
2234
|
+ controls. items-start pins the controls to the top even
|
|
2207
2235
|
when the breadcrumb grows the left column; w-full so
|
|
2208
|
-
justify-between spans the canvas.
|
|
2209
|
-
|
|
2236
|
+
justify-between spans the canvas. Phones: the controls
|
|
2237
|
+
wrap below the search instead of running off the canvas. */}
|
|
2238
|
+
<div className="flex w-full items-start justify-between gap-2 phone:flex-wrap">
|
|
2210
2239
|
<div className="flex flex-col items-start gap-2">
|
|
2211
2240
|
{namespaces.length === 1 && (
|
|
2212
2241
|
<TopologyBreadcrumb
|
|
@@ -2248,7 +2277,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
|
|
|
2248
2277
|
</div>
|
|
2249
2278
|
</TopologyGraph>
|
|
2250
2279
|
</div>
|
|
2251
|
-
|
|
2280
|
+
</div>
|
|
2252
2281
|
)}
|
|
2253
2282
|
</>
|
|
2254
2283
|
)}
|
|
@@ -2412,6 +2441,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
|
|
|
2412
2441
|
{!viewsSyncGated && mainView === 'compare' && <CompareViewRoute />}
|
|
2413
2442
|
|
|
2414
2443
|
</ErrorBoundary>
|
|
2444
|
+
</div>
|
|
2415
2445
|
</div>}
|
|
2416
2446
|
</div>{/* /body frame */}
|
|
2417
2447
|
|
|
@@ -2552,6 +2582,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
|
|
|
2552
2582
|
{!navCustomization.embedded && <UpdateNotification />}
|
|
2553
2583
|
{!navCustomization.embedded && <WhatsNew onNavigate={navigateToPath} usageData={usageData.data} />}
|
|
2554
2584
|
{!navCustomization.embedded && <UsageDataPrompt status={usageData.data} />}
|
|
2585
|
+
{!navCustomization.embedded && <ProductHuntNotice usageData={usageData.data} usageDataPending={usageData.isPending} />}
|
|
2555
2586
|
|
|
2556
2587
|
{/* Bottom Dock for Terminal/Logs */}
|
|
2557
2588
|
<BottomDock viewNamespaces={namespaces} />
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { act } from 'react'
|
|
3
|
+
import { createRoot } from 'react-dom/client'
|
|
4
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
5
|
+
import { afterEach, beforeEach, expect, it, vi, type MockInstance } from 'vitest'
|
|
6
|
+
import { useBulkDeleteResources, useDeleteResource } from './client'
|
|
7
|
+
|
|
8
|
+
let success: MockInstance
|
|
9
|
+
let notice: MockInstance
|
|
10
|
+
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
|
|
11
|
+
beforeEach(() => {
|
|
12
|
+
success = vi.spyOn(console, 'log').mockImplementation(() => {})
|
|
13
|
+
notice = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
14
|
+
})
|
|
15
|
+
afterEach(() => {
|
|
16
|
+
vi.unstubAllGlobals()
|
|
17
|
+
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
|
|
18
|
+
vi.restoreAllMocks()
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
async function remove(responses: (Response | Error)[], bulk: boolean, count = 1, namespace = 'shop') {
|
|
22
|
+
const fetchMock = vi.fn<typeof fetch>(async () => {
|
|
23
|
+
const response = responses.shift()!
|
|
24
|
+
if (response instanceof Error) throw response
|
|
25
|
+
return response
|
|
26
|
+
})
|
|
27
|
+
vi.stubGlobal('fetch', fetchMock)
|
|
28
|
+
const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } })
|
|
29
|
+
let run: (() => Promise<unknown>) | undefined
|
|
30
|
+
function Probe() {
|
|
31
|
+
const single = useDeleteResource()
|
|
32
|
+
const many = useBulkDeleteResources()
|
|
33
|
+
const items = Array.from({ length: count }, (_, i) => ({ kind: 'configmaps', namespace, name: i ? `app-${i}` : 'app' }))
|
|
34
|
+
run = () => bulk ? many.mutateAsync({ items }) : single.mutateAsync(items[0])
|
|
35
|
+
return null
|
|
36
|
+
}
|
|
37
|
+
const root = createRoot(document.createElement('div'))
|
|
38
|
+
await act(async () => { root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>) })
|
|
39
|
+
let failure: unknown
|
|
40
|
+
await act(async () => { try { await run!() } catch (err) { failure = err } })
|
|
41
|
+
act(() => root.unmount())
|
|
42
|
+
client.clear()
|
|
43
|
+
expect(fetchMock).toHaveBeenCalledTimes(count)
|
|
44
|
+
expect(fetchMock.mock.calls[0]?.[0]).toContain(`/api/resources/configmaps/${namespace || "_"}/app`)
|
|
45
|
+
return failure
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
for (const bulk of [false,true]) {
|
|
50
|
+
const mode=bulk?'bulk':'single'
|
|
51
|
+
it(`${mode}: confirms completed deletion from the current JSON contract`,async()=>{
|
|
52
|
+
expect(await remove([new Response('{}',{status:200})],bulk)).toBeUndefined()
|
|
53
|
+
expect(success).toHaveBeenCalledExactlyOnceWith('[Toast]',bulk?'1 resource deleted':'Resource deleted',undefined)
|
|
54
|
+
expect(notice).not.toHaveBeenCalled()
|
|
55
|
+
})
|
|
56
|
+
for(const body of ['', 'not JSON', 'null', '[]', 'true', '{"pendingFinalizers":[1]}', '{"observationError":false}']) {
|
|
57
|
+
it(`${mode}: an accepted malformed response is unconfirmed`,async()=>{
|
|
58
|
+
expect(await remove([new Response(body,{status:200})],bulk)).toBeUndefined()
|
|
59
|
+
expect(success).not.toHaveBeenCalled()
|
|
60
|
+
expect(JSON.stringify(notice.mock.calls)).toContain('did not confirm cleanup')
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
it(`${mode}: an accepted body-read failure is unconfirmed`,async()=>{
|
|
64
|
+
const response = new Response('{}', {status:200})
|
|
65
|
+
vi.spyOn(response, 'text').mockRejectedValue(new Error('response stream interrupted'))
|
|
66
|
+
expect(await remove([response],bulk)).toBeUndefined()
|
|
67
|
+
expect(success).not.toHaveBeenCalled()
|
|
68
|
+
expect(JSON.stringify(notice.mock.calls)).toContain('did not confirm cleanup')
|
|
69
|
+
})
|
|
70
|
+
for(const status of [403,409]) {
|
|
71
|
+
it(`${mode}: rejects HTTP ${status}`,async()=>{
|
|
72
|
+
expect(await remove([new Response(JSON.stringify({error:'request rejected'}),{status})],bulk)).toBeInstanceOf(Error)
|
|
73
|
+
expect(success).not.toHaveBeenCalled();expect(notice).not.toHaveBeenCalled()
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
for (const status of [408,500,502,504]) {
|
|
77
|
+
it(`${mode}: HTTP ${status} leaves deletion outcome unknown`,async()=>{
|
|
78
|
+
expect(await remove([new Response(JSON.stringify({error:'request interrupted'}),{status})],bulk)).toBeUndefined()
|
|
79
|
+
expect(success).not.toHaveBeenCalled()
|
|
80
|
+
expect(JSON.stringify(notice.mock.calls)).toContain('inspect before retrying')
|
|
81
|
+
})
|
|
82
|
+
}
|
|
83
|
+
it(`${mode}: a dropped DELETE response leaves outcome unknown`,async()=>{
|
|
84
|
+
expect(await remove([new TypeError('Failed to fetch')],bulk)).toBeUndefined()
|
|
85
|
+
expect(success).not.toHaveBeenCalled()
|
|
86
|
+
expect(JSON.stringify(notice.mock.calls)).toContain('inspect before retrying')
|
|
87
|
+
})
|
|
88
|
+
for(const result of [{deletionTimestamp:'now'}, {deletionTimestamp:'now',pendingFinalizers:['example.com/hold']}, {observationError:'no get permission'}]) {
|
|
89
|
+
it(`${mode}: accepted asynchronous or unconfirmed deletion stays progress`,async()=>{
|
|
90
|
+
expect(await remove([new Response(JSON.stringify(result))],bulk)).toBeUndefined()
|
|
91
|
+
expect(success).not.toHaveBeenCalled();expect(notice).toHaveBeenCalled()
|
|
92
|
+
expect(JSON.stringify(notice.mock.calls)).not.toContain('force delete')
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
it(`${mode}: cluster-scoped URLs use the namespace placeholder`,async()=>{
|
|
96
|
+
expect(await remove([new Response('{}')],bulk,1,'')).toBeUndefined()
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
it('bulk prioritizes pending finalizers while retaining unconfirmed item details',async()=>{
|
|
100
|
+
expect(await remove([new Response(JSON.stringify({pendingFinalizers:['hold'],deletionTimestamp:'now'})),new Response(JSON.stringify({observationError:'read denied'}))],true,2)).toBeUndefined()
|
|
101
|
+
expect(success).not.toHaveBeenCalled()
|
|
102
|
+
expect(JSON.stringify(notice.mock.calls)).toContain('waiting on finalizers')
|
|
103
|
+
expect(JSON.stringify(notice.mock.calls)).toContain('read denied')
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
it('bulk rejection retains unknown-outcome guidance for another item',async()=>{
|
|
107
|
+
const failure = await remove([new Response(JSON.stringify({error:'denied'}),{status:403}),new TypeError('Failed to fetch')],true,2)
|
|
108
|
+
expect(failure).toBeInstanceOf(Error)
|
|
109
|
+
expect((failure as Error).message).toContain('deletion outcome unknown for 1; inspect before retrying')
|
|
110
|
+
expect(success).not.toHaveBeenCalled()
|
|
111
|
+
})
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { act } from 'react'
|
|
3
|
+
import { createRoot, type Root } from 'react-dom/client'
|
|
4
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
5
|
+
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
|
6
|
+
import { useGitOpsDestination } from './client'
|
|
7
|
+
|
|
8
|
+
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
|
|
9
|
+
let root: Root
|
|
10
|
+
let host: HTMLDivElement
|
|
11
|
+
let client: QueryClient
|
|
12
|
+
const requests: string[] = []
|
|
13
|
+
|
|
14
|
+
function Destination({ group }: { group?: string }) {
|
|
15
|
+
useGitOpsDestination('applications', 'shop', 'wordpress', true, group)
|
|
16
|
+
return null
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
beforeEach(() => {
|
|
20
|
+
requests.length = 0
|
|
21
|
+
vi.stubGlobal('fetch', async (input: string | URL | Request) => {
|
|
22
|
+
requests.push(String(input))
|
|
23
|
+
return new Response(JSON.stringify({ server: 'https://destination.example.com', contexts: [] }), { status: 200 })
|
|
24
|
+
})
|
|
25
|
+
client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
|
26
|
+
host = document.createElement('div')
|
|
27
|
+
root = createRoot(host)
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
afterEach(async () => {
|
|
31
|
+
await act(async () => root.unmount())
|
|
32
|
+
client.clear()
|
|
33
|
+
vi.unstubAllGlobals()
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
async function render(group?: string) {
|
|
37
|
+
await act(async () => root.render(<QueryClientProvider client={client}><Destination group={group} /></QueryClientProvider>))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
it('binds destination requests and cached results to the API group', async () => {
|
|
41
|
+
await render('argoproj.io')
|
|
42
|
+
await vi.waitFor(() => expect(requests).toHaveLength(1))
|
|
43
|
+
await render('app.k8s.io')
|
|
44
|
+
await vi.waitFor(() => expect(requests).toHaveLength(2))
|
|
45
|
+
expect(requests[0]).toBe('/api/gitops/destination/applications/shop/wordpress?group=argoproj.io')
|
|
46
|
+
expect(requests[1]).toBe('/api/gitops/destination/applications/shop/wordpress?group=app.k8s.io')
|
|
47
|
+
const entries = client.getQueryCache().findAll({ queryKey: ['gitops-destination'] })
|
|
48
|
+
expect(entries.map((entry) => entry.queryKey.at(-1))).toEqual(['argoproj.io', 'app.k8s.io'])
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('preserves the unqualified request used by existing callers', async () => {
|
|
52
|
+
await render()
|
|
53
|
+
await vi.waitFor(() => expect(requests).toHaveLength(1))
|
|
54
|
+
expect(requests[0]).toBe('/api/gitops/destination/applications/shop/wordpress')
|
|
55
|
+
})
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
2
|
+
import { ApiError, fetchResourceList, isListTooLargeError, isUnretryableReadError } from './client'
|
|
3
|
+
import { setApiBase, setAuthHeadersProvider, setCredentialsMode } from './config'
|
|
4
|
+
|
|
5
|
+
afterEach(() => {
|
|
6
|
+
vi.unstubAllGlobals()
|
|
7
|
+
setApiBase('/api')
|
|
8
|
+
setAuthHeadersProvider(() => ({}))
|
|
9
|
+
setCredentialsMode('same-origin')
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
const coverage = { status: 'complete', scope: { type: 'all_namespaces' }, read: { type: 'all_namespaces' }, gaps: [] }
|
|
13
|
+
const envelope = { items: [], kind: 'pods', coverage, columns: null, cells: null }
|
|
14
|
+
|
|
15
|
+
describe('resource list transport', () => {
|
|
16
|
+
it('uses the configured cluster route and auth with a bounded list', async () => {
|
|
17
|
+
setApiBase('/c/cluster/api')
|
|
18
|
+
setAuthHeadersProvider(() => ({ Authorization: 'Bearer test' }))
|
|
19
|
+
setCredentialsMode('include')
|
|
20
|
+
const mock = vi.fn(async (url: RequestInfo | URL, init?: RequestInit) => {
|
|
21
|
+
expect(url).toBe('/c/cluster/api/resources/pods?namespaces=alpha&maxItems=25000')
|
|
22
|
+
expect(init?.credentials).toBe('include')
|
|
23
|
+
expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer test')
|
|
24
|
+
return new Response(JSON.stringify(envelope), { status: 200 })
|
|
25
|
+
})
|
|
26
|
+
vi.stubGlobal('fetch', mock)
|
|
27
|
+
expect((await fetchResourceList('pods', { namespaces: ['alpha'] })).coverage).toEqual(coverage)
|
|
28
|
+
expect(mock).toHaveBeenCalledTimes(1)
|
|
29
|
+
})
|
|
30
|
+
it('uses the summary budget only for summary requests', async () => {
|
|
31
|
+
vi.stubGlobal('fetch', vi.fn(async (url: RequestInfo | URL) => {
|
|
32
|
+
expect(url).toBe('/api/resources/pods?include=summary&maxItems=50000')
|
|
33
|
+
return new Response(JSON.stringify(envelope), { status: 200 })
|
|
34
|
+
}))
|
|
35
|
+
await fetchResourceList('pods', { summary: true })
|
|
36
|
+
})
|
|
37
|
+
it('reads an older Radar array, sent the same budget it ignores, without inventing complete coverage', async () => {
|
|
38
|
+
const mock = vi.fn(async (url: RequestInfo | URL) => {
|
|
39
|
+
expect(url).toBe('/api/resources/pods?maxItems=25000')
|
|
40
|
+
return new Response('[{"metadata":{"name":"api"}}]', { status: 200 })
|
|
41
|
+
})
|
|
42
|
+
vi.stubGlobal('fetch', mock)
|
|
43
|
+
const result = await fetchResourceList('pods')
|
|
44
|
+
expect(result.items).toEqual([{ metadata: { name: 'api' } }])
|
|
45
|
+
expect(result.coverage).toEqual({ status: 'unknown' })
|
|
46
|
+
expect(mock).toHaveBeenCalledTimes(1)
|
|
47
|
+
})
|
|
48
|
+
it('preserves oversized-list errors instead of returning empty rows', async () => {
|
|
49
|
+
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ error: 'Too many resources to load; select fewer namespaces', error_code: 'list_too_large', count: 30000, limit: 25000 }), { status: 400, headers: { 'Content-Type': 'application/json' } })))
|
|
50
|
+
const error = await fetchResourceList('pods').catch((e: unknown) => e)
|
|
51
|
+
expect(error).toMatchObject({ status: 400, data: { error_code: 'list_too_large', count: 30000 } })
|
|
52
|
+
expect(isListTooLargeError(error)).toBe(true)
|
|
53
|
+
expect(isListTooLargeError(new ApiError('failed', 400, { error: 'failed', error_code: 'kind_unknown' }))).toBe(false)
|
|
54
|
+
})
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
describe('read errors that a retry cannot answer', () => {
|
|
58
|
+
const failure = (status: number, error_code?: string) => new ApiError('failed', status, error_code ? { error: 'failed', error_code } : { error: 'failed' })
|
|
59
|
+
|
|
60
|
+
it('stops on a request, access or collection problem', () => {
|
|
61
|
+
expect(isUnretryableReadError(failure(400, 'list_too_large'))).toBe(true)
|
|
62
|
+
expect(isUnretryableReadError(failure(400, 'kind_unknown'))).toBe(true)
|
|
63
|
+
expect(isUnretryableReadError(failure(409, 'radar_namespace_not_collected'))).toBe(true)
|
|
64
|
+
expect(isUnretryableReadError(failure(403, 'user_forbidden'))).toBe(true)
|
|
65
|
+
expect(isUnretryableReadError(failure(503, 'kind_sync_timed_out'))).toBe(true)
|
|
66
|
+
// The spellings Radar releases before the shared vocabulary sent.
|
|
67
|
+
expect(isUnretryableReadError(failure(403, 'rbac_denied'))).toBe(true)
|
|
68
|
+
expect(isUnretryableReadError(failure(503, 'kind_sync_failed'))).toBe(true)
|
|
69
|
+
})
|
|
70
|
+
it('retries what may answer on its own', () => {
|
|
71
|
+
expect(isUnretryableReadError(failure(503, 'kind_sync_pending'))).toBe(false)
|
|
72
|
+
expect(isUnretryableReadError(failure(500, 'read_error'))).toBe(false)
|
|
73
|
+
expect(isUnretryableReadError(failure(503))).toBe(false)
|
|
74
|
+
expect(isUnretryableReadError(new Error('network'))).toBe(false)
|
|
75
|
+
})
|
|
76
|
+
})
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { act } from 'react'
|
|
3
|
+
import { createRoot } from 'react-dom/client'
|
|
4
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
5
|
+
import { afterEach, expect, it, vi } from 'vitest'
|
|
6
|
+
import { useCapabilities, useResourceAudit } from './client'
|
|
7
|
+
import { setApiBase } from './config'
|
|
8
|
+
|
|
9
|
+
afterEach(() => {
|
|
10
|
+
setApiBase('/api')
|
|
11
|
+
vi.unstubAllGlobals()
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
it.each(['supported', 'older', 'failed', 'namespaced'] as const)('avoids premature and duplicate audit requests across discovery: %s', async (state) => {
|
|
15
|
+
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
|
|
16
|
+
setApiBase('/c/review/api')
|
|
17
|
+
let settle!: (response: Response) => void
|
|
18
|
+
let fail!: (error: Error) => void
|
|
19
|
+
const capabilities = new Promise<Response>((resolve, reject) => { settle = resolve; fail = reject })
|
|
20
|
+
const paths: string[] = []
|
|
21
|
+
vi.stubGlobal('fetch', vi.fn(async (input: string) => {
|
|
22
|
+
const path = new URL(input, 'http://localhost').pathname
|
|
23
|
+
paths.push(path)
|
|
24
|
+
if (path.endsWith('/capabilities')) return capabilities
|
|
25
|
+
return new Response('[]', { status: 200, headers: { 'Content-Type': 'application/json' } })
|
|
26
|
+
}))
|
|
27
|
+
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
|
28
|
+
const namespace = state === 'namespaced' ? 'shop' : ''
|
|
29
|
+
const kind = namespace ? 'configmaps' : 'persistentvolumes'
|
|
30
|
+
const segment = namespace || (state === 'supported' ? '_' : '')
|
|
31
|
+
const auditPath = `/c/review/api/audit/resource/${kind}/${segment}/pv-a`
|
|
32
|
+
function Probe() {
|
|
33
|
+
const audit = useResourceAudit(kind, namespace, 'pv-a')
|
|
34
|
+
const discovery = useCapabilities()
|
|
35
|
+
return <span>{audit.isSuccess ? 'loaded' : 'waiting'}|{discovery.isPending ? 'pending' : 'settled'}</span>
|
|
36
|
+
}
|
|
37
|
+
const host = document.createElement('div')
|
|
38
|
+
const root = createRoot(host)
|
|
39
|
+
try {
|
|
40
|
+
await act(async () => { root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>) })
|
|
41
|
+
await vi.waitFor(() => {
|
|
42
|
+
expect(paths).toEqual(['/c/review/api/capabilities', ...(namespace ? [auditPath] : [])])
|
|
43
|
+
expect(host.textContent).toBe(namespace ? 'loaded|pending' : 'waiting|pending')
|
|
44
|
+
})
|
|
45
|
+
await act(async () => {
|
|
46
|
+
if (state === 'failed') fail(new Error('capabilities unavailable'))
|
|
47
|
+
else settle(new Response(JSON.stringify({ features: state === 'supported' || state === 'namespaced' ? { clusterScopedPlaceholder: true } : {} }), { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
|
48
|
+
})
|
|
49
|
+
await vi.waitFor(() => {
|
|
50
|
+
expect(paths).toEqual(['/c/review/api/capabilities', auditPath])
|
|
51
|
+
expect(host.textContent).toBe('loaded|settled')
|
|
52
|
+
})
|
|
53
|
+
} finally {
|
|
54
|
+
act(() => root.unmount())
|
|
55
|
+
client.clear()
|
|
56
|
+
}
|
|
57
|
+
})
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
//
|
|
3
|
+
// Cluster-scoped resources have no namespace. Their per-resource URLs send "_"
|
|
4
|
+
// in its place to survive proxies that merge repeated slashes. Older Radar
|
|
5
|
+
// versions need the empty segment for edit and audit; read, preview and delete
|
|
6
|
+
// already support the placeholder.
|
|
7
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
8
|
+
import { useMutation, useQuery } from '@tanstack/react-query'
|
|
9
|
+
import type { Capabilities } from '@skyhook-io/k8s-ui'
|
|
10
|
+
import {
|
|
11
|
+
fetchResourceWithRelationships,
|
|
12
|
+
useBulkDeleteResources,
|
|
13
|
+
useCascadeDeletePreview,
|
|
14
|
+
useDeleteResource,
|
|
15
|
+
useResourceAudit,
|
|
16
|
+
useUpdateResource,
|
|
17
|
+
} from './client'
|
|
18
|
+
|
|
19
|
+
vi.mock('@tanstack/react-query', async (original) => ({
|
|
20
|
+
...await original<typeof import('@tanstack/react-query')>(),
|
|
21
|
+
useQuery: vi.fn(() => ({})),
|
|
22
|
+
useMutation: vi.fn(() => ({})),
|
|
23
|
+
useQueryClient: vi.fn(() => ({})),
|
|
24
|
+
}))
|
|
25
|
+
|
|
26
|
+
afterEach(() => { vi.clearAllMocks(); vi.unstubAllGlobals() })
|
|
27
|
+
|
|
28
|
+
function connectedRadar(capabilities: Partial<Capabilities> | undefined) {
|
|
29
|
+
vi.mocked(useQuery).mockImplementation(((options: { queryKey: unknown[] }) =>
|
|
30
|
+
options.queryKey[0] === 'capabilities' ? { data: capabilities, isPending: false } : {}) as unknown as typeof useQuery)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function captureRequests() {
|
|
34
|
+
const requests: { method: string; path: string }[] = []
|
|
35
|
+
vi.stubGlobal('fetch', vi.fn(async (input: string, init?: RequestInit) => {
|
|
36
|
+
requests.push({ method: init?.method ?? 'GET', path: new URL(input, 'http://localhost').pathname })
|
|
37
|
+
return init?.method === 'DELETE'
|
|
38
|
+
? new Response(null, { status: 204 })
|
|
39
|
+
: new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } })
|
|
40
|
+
}))
|
|
41
|
+
return requests
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type Ref = { kind: string; namespace: string; name: string }
|
|
45
|
+
|
|
46
|
+
type UpdateVars = Parameters<ReturnType<typeof useUpdateResource>['mutateAsync']>[0]
|
|
47
|
+
type DeleteVars = Parameters<ReturnType<typeof useDeleteResource>['mutateAsync']>[0]
|
|
48
|
+
type BulkDeleteVars = Parameters<ReturnType<typeof useBulkDeleteResources>['mutateAsync']>[0]
|
|
49
|
+
|
|
50
|
+
// Runs the requests the hooks rendered in the test registered with the mocked
|
|
51
|
+
// react-query, in the order they were rendered.
|
|
52
|
+
async function requestsFor({ kind, namespace, name }: Ref) {
|
|
53
|
+
const requests = captureRequests()
|
|
54
|
+
const [update, del, bulkDelete] = vi.mocked(useMutation).mock.calls.map(call => call[0].mutationFn)
|
|
55
|
+
const [cascadePreview, audit] = vi.mocked(useQuery).mock.calls
|
|
56
|
+
.map(call => call[0] as { queryKey: unknown[]; queryFn: () => Promise<unknown> })
|
|
57
|
+
.filter(options => options.queryKey[0] !== 'capabilities')
|
|
58
|
+
.map(options => options.queryFn)
|
|
59
|
+
await fetchResourceWithRelationships(kind, namespace, name)
|
|
60
|
+
await (update as (vars: UpdateVars) => Promise<unknown>)({ kind, namespace, name, yaml: `kind: X\nmetadata:\n name: ${name}\n` })
|
|
61
|
+
await (del as (vars: DeleteVars) => Promise<unknown>)({ kind, namespace, name })
|
|
62
|
+
await (bulkDelete as (vars: BulkDeleteVars) => Promise<unknown>)({ items: [{ kind, namespace, name }] })
|
|
63
|
+
await cascadePreview()
|
|
64
|
+
await audit()
|
|
65
|
+
return requests
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function expected(ref: Ref, readSegment: string, writeSegment: string) {
|
|
69
|
+
const read = `/api/resources/${ref.kind}/${readSegment}/${ref.name}`
|
|
70
|
+
const write = `/api/resources/${ref.kind}/${writeSegment}/${ref.name}`
|
|
71
|
+
return [
|
|
72
|
+
{ method: 'GET', path: read },
|
|
73
|
+
{ method: 'PUT', path: write },
|
|
74
|
+
{ method: 'DELETE', path: read },
|
|
75
|
+
{ method: 'DELETE', path: read },
|
|
76
|
+
{ method: 'GET', path: `${read}/cascade-preview` },
|
|
77
|
+
{ method: 'GET', path: `/api/audit/resource/${ref.kind}/${writeSegment}/${ref.name}` },
|
|
78
|
+
]
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const refs: Ref[] = [
|
|
82
|
+
{ kind: 'persistentvolumes', namespace: '', name: 'pv-a' },
|
|
83
|
+
{ kind: 'nodes', namespace: '', name: 'worker-1' },
|
|
84
|
+
{ kind: 'clusterroles', namespace: '', name: 'admin' },
|
|
85
|
+
{ kind: 'namespaces', namespace: '', name: 'shop' },
|
|
86
|
+
{ kind: 'storageclasses', namespace: '', name: 'standard' },
|
|
87
|
+
{ kind: 'clusterissuers', namespace: '', name: 'letsencrypt' },
|
|
88
|
+
{ kind: 'configmaps', namespace: 'shop', name: 'app' },
|
|
89
|
+
]
|
|
90
|
+
|
|
91
|
+
describe.each([
|
|
92
|
+
{ radar: 'a Radar that reads "_" as cluster-scoped', capabilities: { features: { clusterScopedPlaceholder: true } }, emptyWriteSegment: '_' },
|
|
93
|
+
{ radar: 'an older Radar without the flag', capabilities: { features: {} }, emptyWriteSegment: '' },
|
|
94
|
+
{ radar: 'a Radar whose capability request failed', capabilities: undefined, emptyWriteSegment: '' },
|
|
95
|
+
])('$radar', ({ capabilities, emptyWriteSegment }) => {
|
|
96
|
+
beforeEach(() => connectedRadar(capabilities))
|
|
97
|
+
|
|
98
|
+
it.each(refs)('addresses $kind "$namespace"/$name', async (ref) => {
|
|
99
|
+
const { kind, namespace, name } = ref
|
|
100
|
+
useUpdateResource()
|
|
101
|
+
useDeleteResource()
|
|
102
|
+
useBulkDeleteResources()
|
|
103
|
+
useCascadeDeletePreview(kind, namespace, name, undefined, true)
|
|
104
|
+
useResourceAudit(kind, namespace, name)
|
|
105
|
+
expect(await requestsFor(ref)).toEqual(expected(ref, namespace || '_', namespace || emptyWriteSegment))
|
|
106
|
+
})
|
|
107
|
+
})
|