@skyhook-io/radar-app 1.20.3 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/package.json +10 -9
  2. package/src/App.tsx +54 -10
  3. package/src/api/client.audit-gating.test.tsx +105 -5
  4. package/src/api/client.auditBadgesSync.test.tsx +118 -0
  5. package/src/api/client.capabilitiesPoll.test.ts +61 -0
  6. package/src/api/client.ts +129 -5
  7. package/src/api/namespaceScopeRetry.test.ts +14 -0
  8. package/src/api/radarFeatures.ts +7 -0
  9. package/src/api/substrateHealth.ts +134 -0
  10. package/src/api/velero.test.ts +60 -0
  11. package/src/api/velero.ts +201 -0
  12. package/src/api/vulnerabilities.ts +255 -0
  13. package/src/components/NamespaceSwitcher.tsx +3 -1
  14. package/src/components/audit/AuditView.tsx +4 -0
  15. package/src/components/audit/ChecksViewTabs.test.tsx +33 -5
  16. package/src/components/audit/ChecksViewTabs.tsx +11 -1
  17. package/src/components/audit/UpgradeReadinessView.test.ts +35 -1
  18. package/src/components/audit/UpgradeReadinessView.tsx +60 -2
  19. package/src/components/audit/VulnerabilitiesView.tsx +907 -0
  20. package/src/components/cnpg/CNPGClusterTabs.tsx +3 -1
  21. package/src/components/cnpg/CNPGDrawerTrail.tsx +5 -26
  22. package/src/components/cnpg/CNPGInvestigationAction.test.tsx +27 -6
  23. package/src/components/cnpg/CNPGView.tsx +43 -117
  24. package/src/components/cnpg/CNPGWorkspace.compatibility.test.tsx +30 -0
  25. package/src/components/cnpg/host.tsx +2 -2
  26. package/src/components/cnpg/routes.ts +3 -1
  27. package/src/components/cnpg/shared.tsx +5 -53
  28. package/src/components/cnpg/useCNPGNavigate.ts +1 -21
  29. package/src/components/cnpg/useCNPGSidebarWorkspace.ts +16 -13
  30. package/src/components/community.tsx +42 -0
  31. package/src/components/diagnose/diagnoseEvidenceTypes.ts +2 -0
  32. package/src/components/diagnose/investigationMetrics.test.ts +20 -0
  33. package/src/components/diagnose/investigationMetrics.ts +2 -1
  34. package/src/components/dock/BottomDock.tsx +1 -0
  35. package/src/components/dock/LogsTab.tsx +3 -0
  36. package/src/components/gitops/GitOpsView.tsx +1 -1
  37. package/src/components/helm/HelmDrawerFrame.tsx +1 -1
  38. package/src/components/helm/HelmView.tsx +20 -16
  39. package/src/components/helm/OwnedResources.tsx +4 -3
  40. package/src/components/home/ClusterHealthCard.tsx +3 -1
  41. package/src/components/home/HomeAgentBlock.tsx +3 -0
  42. package/src/components/home/HomeView.tsx +7 -0
  43. package/src/components/home/MCPSetupDialog.test.tsx +19 -12
  44. package/src/components/home/MCPSetupDialog.tsx +4 -2
  45. package/src/components/home/mcpToolCatalog.ts +15 -2
  46. package/src/components/home/useVulnerabilitiesRow.test.ts +26 -0
  47. package/src/components/home/useVulnerabilitiesRow.ts +50 -0
  48. package/src/components/logs/LogsViewer.tsx +3 -1
  49. package/src/components/logs/MultiPodLogsTab.test.tsx +24 -4
  50. package/src/components/logs/MultiPodLogsTab.tsx +9 -5
  51. package/src/components/nav/PrimaryNavRail.test.tsx +17 -0
  52. package/src/components/nav/PrimaryNavRail.tsx +174 -29
  53. package/src/components/resource/PrometheusChartsGrid.tsx +5 -1
  54. package/src/components/resource/SubstrateHealthCharts.test.tsx +143 -0
  55. package/src/components/resource/SubstrateHealthCharts.tsx +254 -0
  56. package/src/components/resource/SubstrateVerdictLine.test.tsx +131 -0
  57. package/src/components/resource/SubstrateVerdictLine.tsx +180 -0
  58. package/src/components/resources/ResourcesView.tsx +12 -6
  59. package/src/components/resources/renderers/UpgradePlanRenderer.test.tsx +20 -0
  60. package/src/components/resources/renderers/UpgradePlanRenderer.tsx +22 -0
  61. package/src/components/resources/renderers/VeleroBackupRenderer.tsx +16 -36
  62. package/src/components/resources/renderers/VeleroRestoreRenderer.tsx +6 -19
  63. package/src/components/resources/renderers/WorkloadRenderer.tsx +8 -0
  64. package/src/components/rightsizing/RightsizingScanView.tsx +3 -2
  65. package/src/components/shared/LargeClusterNamespacePicker.test.tsx +27 -0
  66. package/src/components/shared/LargeClusterNamespacePicker.tsx +8 -2
  67. package/src/components/timeline/TimelineView.tsx +3 -1
  68. package/src/components/traffic/TrafficConnectionsTable.test.tsx +94 -0
  69. package/src/components/traffic/TrafficConnectionsTable.tsx +21 -5
  70. package/src/components/traffic/TrafficData.test.tsx +37 -0
  71. package/src/components/traffic/TrafficData.tsx +27 -0
  72. package/src/components/traffic/TrafficFlowList.tsx +9 -7
  73. package/src/components/traffic/TrafficGraph.layoutEngine.test.tsx +193 -0
  74. package/src/components/traffic/TrafficGraph.test.tsx +269 -0
  75. package/src/components/traffic/TrafficGraph.tsx +135 -64
  76. package/src/components/traffic/TrafficGraphUnavailable.tsx +57 -0
  77. package/src/components/traffic/TrafficView.layoutUnavailable.test.tsx +211 -0
  78. package/src/components/traffic/TrafficView.tsx +46 -129
  79. package/src/components/traffic/trafficFilters.test.ts +172 -1
  80. package/src/components/traffic/trafficFilters.ts +139 -0
  81. package/src/components/ui/DiagnosticsOverlay.tsx +14 -1
  82. package/src/components/ui/UpdateNotification.manual.test.tsx +5 -2
  83. package/src/components/ui/UpdateNotification.test.tsx +31 -2
  84. package/src/components/ui/UpdateNotification.tsx +34 -17
  85. package/src/components/ui/command-items.ts +24 -1
  86. package/src/components/velero/VeleroBackupNow.test.tsx +165 -0
  87. package/src/components/velero/VeleroBackupNow.tsx +143 -0
  88. package/src/components/velero/VeleroDeleteBackup.test.tsx +364 -0
  89. package/src/components/velero/VeleroDeleteBackup.tsx +306 -0
  90. package/src/components/velero/VeleroDetailPage.tsx +148 -0
  91. package/src/components/velero/VeleroKindLists.test.tsx +48 -0
  92. package/src/components/velero/VeleroKindLists.tsx +43 -0
  93. package/src/components/velero/VeleroLocations.expand.test.tsx +27 -0
  94. package/src/components/velero/VeleroLocations.test.tsx +86 -0
  95. package/src/components/velero/VeleroLocations.tsx +240 -0
  96. package/src/components/velero/VeleroOverview.test.tsx +311 -0
  97. package/src/components/velero/VeleroOverview.tsx +485 -0
  98. package/src/components/velero/VeleroPages.test.tsx +516 -0
  99. package/src/components/velero/VeleroPages.tsx +1056 -0
  100. package/src/components/velero/VeleroRunLists.tsx +309 -0
  101. package/src/components/velero/VeleroRunMessagesHost.test.tsx +25 -0
  102. package/src/components/velero/VeleroRunMessagesHost.tsx +54 -0
  103. package/src/components/velero/VeleroScheduleStatusBadge.test.tsx +28 -0
  104. package/src/components/velero/VeleroScheduleStatusBadge.tsx +21 -0
  105. package/src/components/velero/VeleroSchedules.tsx +255 -0
  106. package/src/components/velero/VeleroView.tsx +59 -0
  107. package/src/components/velero/VeleroWorkspace.gate.test.tsx +97 -0
  108. package/src/components/velero/attention.test.ts +178 -0
  109. package/src/components/velero/attention.ts +281 -0
  110. package/src/components/velero/backupDelete.test.tsx +91 -0
  111. package/src/components/velero/backupDelete.tsx +182 -0
  112. package/src/components/velero/coverage.test.ts +87 -0
  113. package/src/components/velero/coverage.ts +150 -0
  114. package/src/components/velero/host.tsx +86 -0
  115. package/src/components/velero/routes.ts +78 -0
  116. package/src/components/velero/runs.tsx +121 -0
  117. package/src/components/velero/shared.test.ts +84 -0
  118. package/src/components/velero/shared.tsx +423 -0
  119. package/src/components/velero/useVeleroSidebarWorkspace.test.tsx +28 -0
  120. package/src/components/velero/useVeleroSidebarWorkspace.ts +71 -0
  121. package/src/components/velero/velero.fixtures.ts +61 -0
  122. package/src/components/velero/workspaceRoute.ts +21 -0
  123. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.tsx +167 -0
  124. package/src/components/vulnerabilities/parts.test.ts +72 -0
  125. package/src/components/vulnerabilities/parts.tsx +291 -0
  126. package/src/components/workload/WorkloadView.tsx +64 -27
  127. package/src/components/workspace/DrawerTrailBack.tsx +32 -0
  128. package/src/components/workspace/WorkspaceFrame.tsx +71 -0
  129. package/src/components/workspace/coverage.ts +61 -0
  130. package/src/components/workspace/layout.test.tsx +29 -1
  131. package/src/components/workspace/layout.tsx +15 -5
  132. package/src/components/workspace/sidebar.ts +9 -0
  133. package/src/components/workspace/useWorkspaceDrawer.ts +63 -0
  134. package/src/components/workspace/useWorkspaceNavigate.ts +21 -0
  135. package/src/desktop/AboutDialog.test.ts +12 -0
  136. package/src/desktop/AboutDialog.tsx +151 -0
  137. package/src/desktop/WindowsTitleBar.tsx +359 -0
  138. package/src/desktop/titleBar.test.ts +61 -0
  139. package/src/desktop/titleBar.ts +45 -0
  140. package/src/index.css +19 -0
  141. package/src/integrations/resourceHost.ts +5 -1
  142. package/src/integrations/resourceHosts.test.tsx +14 -2
  143. package/src/integrations/resourceHosts.tsx +22 -6
  144. package/src/integrations/workspaceRoute.ts +1 -1
  145. package/src/integrations/workspaceRoutes.test.ts +11 -0
  146. package/src/integrations/workspaceRoutes.ts +3 -1
  147. package/src/integrations/workspaceScreens.tsx +2 -0
  148. package/src/main.tsx +8 -0
  149. package/src/utils/desktop-zoom.test.ts +53 -0
  150. package/src/utils/desktop-zoom.ts +30 -0
  151. package/src/utils/staleAssetPrompt.test.tsx +76 -0
  152. package/src/utils/staleAssetPrompt.tsx +32 -0
@@ -0,0 +1,211 @@
1
+ // @vitest-environment jsdom
2
+ import { act, useEffect, type ReactNode } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { MemoryRouter, useLocation } from 'react-router-dom'
5
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
7
+ import type { AggregatedFlow, TrafficFlowsResponse } from '../../types'
8
+ import type { UseTrafficRecordsOptions } from '../../api/traffic'
9
+
10
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
11
+
12
+ vi.mock('elkjs/lib/elk.bundled.js', () => {
13
+ throw new Error('Failed to fetch dynamically imported module')
14
+ })
15
+
16
+ vi.mock('@xyflow/react', async importOriginal => ({
17
+ ...(await importOriginal<typeof import('@xyflow/react')>()),
18
+ ReactFlow: () => <div data-testid="flow" />,
19
+ }))
20
+
21
+ vi.mock('react-virtuoso', () => ({
22
+ Virtuoso: ({ data, itemContent }: { data: unknown[]; itemContent: (index: number, value: unknown) => ReactNode }) => (
23
+ <div>{data.map((value, index) => <div key={index}>{itemContent(index, value)}</div>)}</div>
24
+ ),
25
+ }))
26
+
27
+ const state = vi.hoisted(() => ({
28
+ flows: null as unknown,
29
+ recordsCalls: [] as unknown[],
30
+ }))
31
+
32
+ vi.mock('../../api/traffic', async importOriginal => {
33
+ const sources = {
34
+ cluster: {},
35
+ active: 'hubble',
36
+ detected: [{ name: 'hubble', status: 'available' }],
37
+ notDetected: [],
38
+ }
39
+ return {
40
+ ...(await importOriginal<typeof import('../../api/traffic')>()),
41
+ useTrafficSources: () => ({ data: sources, isLoading: false, detectAgain: () => Promise.resolve(sources) }),
42
+ useTrafficFlows: () => ({ data: state.flows, isFetching: false, dataUpdatedAt: 1, refetch: () => Promise.resolve() }),
43
+ useTrafficRecords: (options: unknown) => {
44
+ state.recordsCalls.push(options)
45
+ return { data: undefined, supported: false, tooLarge: false, isError: false, error: null, isLoading: false, refetch: () => Promise.resolve() }
46
+ },
47
+ useTrafficConnect: () => ({ mutate: (_vars: unknown, opts?: { onSuccess?: (d: unknown) => void }) => opts?.onSuccess?.({ connected: true }) }),
48
+ useSetTrafficSource: () => ({ mutate: () => {}, isPending: false }),
49
+ }
50
+ })
51
+
52
+ vi.mock('../../api/client', async importOriginal => ({
53
+ ...(await importOriginal<typeof import('../../api/client')>()),
54
+ useClusterInfo: () => ({ data: { context: 'test' } }),
55
+ useNamespaceScope: () => ({ data: undefined }),
56
+ }))
57
+
58
+ vi.mock('../dock', async importOriginal => ({
59
+ ...(await importOriginal<typeof import('../dock')>()),
60
+ useDock: () => ({ setLeftOffset: () => {}, addTab: () => 'flows', removeTab: () => {} }),
61
+ }))
62
+
63
+ vi.mock('../../context/ConnectionContext', async importOriginal => ({
64
+ ...(await importOriginal<typeof import('../../context/ConnectionContext')>()),
65
+ useConnection: () => ({ connection: { state: 'connected' } }),
66
+ }))
67
+
68
+ const { TrafficView } = await import('./TrafficView')
69
+
70
+ const endpoint = (namespace: string, name: string, kind = 'Deployment') => ({ namespace, name, kind })
71
+ const flow = (source: AggregatedFlow['source'], destination: AggregatedFlow['destination'], port: number, connections: number): AggregatedFlow => ({
72
+ source, destination, protocol: 'tcp', port, connections, lastSeen: '', flowCount: 1, bytesSent: 0, bytesRecv: 0,
73
+ })
74
+
75
+ // An addon talking to the API server is the edge grouping folds into the
76
+ // addon group; a plain workload edge is drawn as it is.
77
+ const aggregated = [
78
+ flow(endpoint('shop', 'prometheus'), endpoint('default', 'kubernetes', 'Service'), 443, 17),
79
+ flow(endpoint('shop', 'web'), endpoint('shop', 'api'), 80, 5),
80
+ ]
81
+
82
+ function flowsResponse(warning?: string): TrafficFlowsResponse {
83
+ return { source: 'hubble', timestamp: '', flows: [], aggregated, ...(warning && { warning }) } as TrafficFlowsResponse
84
+ }
85
+
86
+ const seen = { search: '' }
87
+ function LocationProbe() {
88
+ const { search } = useLocation()
89
+ useEffect(() => {
90
+ seen.search = search
91
+ }, [search])
92
+ return null
93
+ }
94
+
95
+ let container: HTMLDivElement
96
+ let root: Root
97
+
98
+ async function render() {
99
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, enabled: false } } })
100
+ await act(async () => {
101
+ root.render(
102
+ <QueryClientProvider client={queryClient}>
103
+ <MemoryRouter initialEntries={['/traffic']}>
104
+ <TrafficView namespaces={[]} />
105
+ <LocationProbe />
106
+ </MemoryRouter>
107
+ </QueryClientProvider>,
108
+ )
109
+ })
110
+ await settle()
111
+ }
112
+
113
+ async function settle() {
114
+ for (let i = 0; i < 3; i++) {
115
+ await act(async () => {
116
+ await new Promise(resolve => setTimeout(resolve, 0))
117
+ })
118
+ }
119
+ }
120
+
121
+ async function click(el: Element | undefined | null) {
122
+ expect(el).toBeTruthy()
123
+ await act(async () => {
124
+ (el as HTMLElement).click()
125
+ })
126
+ await settle()
127
+ }
128
+
129
+ const button = (text: string) => Array.from(container.querySelectorAll('button')).find(b => b.textContent?.trim() === text)
130
+ const toggle = (label: string) => Array.from(container.querySelectorAll('button')).find(b => b.textContent?.startsWith(label))
131
+ const rows = () => Array.from(container.querySelectorAll('[role="row"]'))
132
+ const lastMatch = () => (state.recordsCalls.at(-1) as UseTrafficRecordsOptions).match
133
+
134
+ beforeEach(() => {
135
+ vi.spyOn(console, 'error').mockImplementation(() => {})
136
+ state.recordsCalls = []
137
+ state.flows = flowsResponse()
138
+ container = document.createElement('div')
139
+ document.body.appendChild(container)
140
+ root = createRoot(container)
141
+ })
142
+
143
+ afterEach(() => {
144
+ act(() => root.unmount())
145
+ container.remove()
146
+ vi.restoreAllMocks()
147
+ })
148
+
149
+ describe('TrafficView when the layout engine cannot load', () => {
150
+ it('lists each connection as it is, with grouped addons, and selects and focuses real endpoints', async () => {
151
+ await render()
152
+ await click(toggle('Hide System'))
153
+ await click(button('group'))
154
+
155
+ expect(container.querySelector('[data-testid="flow"]')).toBeNull()
156
+ expect(container.textContent).toContain('The traffic map could not load its layout engine')
157
+ expect(button('Reload')).toBeDefined()
158
+
159
+ expect(rows()).toHaveLength(2)
160
+ expect(container.textContent).not.toMatch(/addon-group|addon-internet/)
161
+ const prometheus = rows().find(r => r.textContent?.includes('prometheus'))!
162
+ expect(prometheus.textContent).toContain('kubernetes')
163
+ expect(prometheus.textContent).toContain('17')
164
+ expect(rows().find(r => r.textContent?.includes('web'))?.textContent).toContain('5')
165
+
166
+ await click(prometheus)
167
+ expect(rows().find(r => r.textContent?.includes('prometheus'))?.getAttribute('aria-selected')).toBe('true')
168
+ expect(lastMatch()).toEqual({
169
+ pairs: [expect.objectContaining({
170
+ source: expect.objectContaining({ namespace: 'shop', name: 'prometheus' }),
171
+ destination: expect.objectContaining({ namespace: 'default', name: 'kubernetes' }),
172
+ port: 443,
173
+ })],
174
+ })
175
+
176
+ const focusPrometheus = Array.from(rows()[0].querySelectorAll('button')).find(b => b.textContent?.includes('prometheus'))
177
+ await click(focusPrometheus)
178
+ expect(new URLSearchParams(seen.search).get('focus')).toBe('shop/prometheus')
179
+ })
180
+
181
+ it("puts the source's warning above the explanation instead of over it", async () => {
182
+ state.flows = flowsResponse('Some nodes could not be reached.')
183
+ await render()
184
+
185
+ const warning = Array.from(container.querySelectorAll('[role="status"]')).find(el => el.textContent?.includes('Some nodes could not be reached.'))
186
+ expect(warning).toBeDefined()
187
+ expect(container.querySelectorAll('.top-14')).toHaveLength(0)
188
+ const panel = warning!.parentElement!
189
+ expect(panel.textContent).toContain('The traffic map could not load its layout engine')
190
+ expect(panel.textContent!.indexOf('Some nodes could not be reached.')).toBeLessThan(panel.textContent!.indexOf('The traffic map could not load its layout engine'))
191
+ })
192
+ })
193
+
194
+
195
+ describe('TrafficView protocol byte merges', () => {
196
+ for (const external of [false, true]) {
197
+ it(`keeps protocol buckets through ${external ? 'external service and Internet' : 'internal service'} collapse`, async () => {
198
+ const source = endpoint(external ? '' : 'demo', external ? '1.2.3.4' : 'client', external ? 'External' : 'Pod')
199
+ const destination = endpoint('demo', 'api', 'Pod')
200
+ const http = { ...flow(source, destination, 0, 1), protocol: 'http', bytesSent: 5969, bytesRecv: 260965, bytesByProtocol: { http: { bytesSent: 5969, bytesRecv: 260965 } } }
201
+ const tcp = { ...flow({ ...source, name: external ? '5.6.7.8' : source.name }, destination, 0, 1), bytesSent: 32699, bytesRecv: 391439, bytesByProtocol: { tcp: { bytesSent: 32699, bytesRecv: 391439 } } }
202
+ state.flows = { ...flowsResponse(), aggregated: [http, tcp] }
203
+ const snapshot = structuredClone(state.flows)
204
+ await render()
205
+ expect(rows()).toHaveLength(1)
206
+ expect(Array.from(rows()[0].querySelectorAll('div.whitespace-nowrap')).map(line => line.textContent)).toEqual(['HTTP 260.7 KB', 'TCP 414.2 KB'])
207
+ expect(rows()[0].textContent).not.toMatch(/674\.9 KB|691,?072/)
208
+ expect(state.flows).toEqual(snapshot)
209
+ })
210
+ }
211
+ })
@@ -1,5 +1,5 @@
1
1
  import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
2
- import { useTrafficSources, useTrafficFlows, useTrafficRecords, useTrafficConnect, useSetTrafficSource, type TrafficEndpointPair } from '../../api/traffic'
2
+ import { useTrafficSources, useTrafficFlows, useTrafficRecords, useTrafficConnect, useSetTrafficSource } from '../../api/traffic'
3
3
  import { useClusterInfo, useNamespaceScope } from '../../api/client'
4
4
  import { useSearchParams } from 'react-router-dom'
5
5
  import type { TrafficWizardState, AggregatedFlow, TrafficFlow } from '../../types'
@@ -11,13 +11,14 @@ import { Filter, Plug, List, Activity, AlertTriangle, Clock, Crosshair, X } from
11
11
  import { TrafficFocusSearch } from './TrafficFocusSearch'
12
12
  import { TrafficSourcePill } from './TrafficSourcePill'
13
13
  import { TrafficGraphTooLarge } from './TrafficGraphTooLarge'
14
+ import { TrafficGraphUnavailable } from './TrafficGraphUnavailable'
14
15
  import { useQueryClient } from '@tanstack/react-query'
15
16
  import { useDock } from '../dock'
16
17
  import { AlertBanner, EmptyState, PaneLoader, FreshnessControl } from '@skyhook-io/k8s-ui'
17
18
  import { useConnection } from '../../context/ConnectionContext'
18
19
  import { Tooltip } from '../ui/Tooltip'
19
20
  import { SEVERITY_TEXT } from '@skyhook-io/k8s-ui/utils/badge-colors'
20
- import { matchesStatusRanges, bucketsFromCounts, bucketsFromStatus, isRateBasedSource, keepAvailable, effectiveThreshold, volumeUnit, type VolumeUnit, isExternalKind, mergeFlowVolume, coverageLabel, type GraphFlow, endpointPair, graphEndpoint, graphEndpointId, mergeRawPairs, mergedEdgePort, selectedEdgeMatcher, selectionRawPairs, selectionMatch, graphSize, GRAPH_DRAW_BUDGET, GRAPH_DRAW_CEILING, parseFocus, focusParam, focusId, focusNeighborhood, touchesFocus, endpointSummaries, namespaceSummaries, verdictChoices, type TrafficFocus, warningRetries, warningBannerTitle, emptyWarningHeadline } from './trafficFilters'
21
+ import { matchesStatusRanges, bucketsFromCounts, bucketsFromStatus, isRateBasedSource, keepAvailable, effectiveThreshold, volumeUnit, type VolumeUnit, isExternalKind, groupAddonFlows, mergeFlowVolume, coverageLabel, type GraphFlow, endpointPair, graphEndpoint, graphEndpointId, mergeRawPairs, mergedEdgePort, selectedEdgeMatcher, selectionRawPairs, selectionMatch, graphSize, GRAPH_DRAW_BUDGET, GRAPH_DRAW_CEILING, parseFocus, focusParam, focusId, focusNeighborhood, touchesFocus, endpointSummaries, namespaceSummaries, verdictChoices, type TrafficFocus, warningRetries, warningBannerTitle, emptyWarningHeadline, rateWindowSeconds } from './trafficFilters'
21
22
 
22
23
  // Where a warning about which cluster the traffic belongs to points: how the map
23
24
  // keeps to this cluster in a shared metrics store, and how to set its label.
@@ -425,6 +426,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
425
426
  // The view the graph was last drawn for, and so keeps drawing (up to the
426
427
  // ceiling) as refreshes move its size: set by drawing it or by Draw anyway.
427
428
  const [drawnViewKey, setDrawnViewKey] = useState<string | null>(null)
429
+ const [layoutUnavailable, setLayoutUnavailable] = useState(false)
428
430
  const dock = useDock()
429
431
  const graphPaneRef = useRef<HTMLDivElement>(null)
430
432
 
@@ -932,113 +934,9 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
932
934
  // A focused view draws its endpoints as they are: grouping the addons would
933
935
  // fold the focus or its neighbors into the group.
934
936
  const groupAddons = addonMode === 'group' && !focus
935
- const finalFlows = useMemo<GraphFlow[]>(() => {
936
- if (!groupAddons) return focusedFlows
937
-
938
- // Track totals for aggregated edges
939
- let addonInternetTotal = 0
940
- let addonToK8sTotal = 0
941
- let addonInternetRate = 0
942
- let addonToK8sRate = 0
943
- const addonInternetPairs: TrafficEndpointPair[] = []
944
- const addonToK8sPairs: TrafficEndpointPair[] = []
945
- const processedFlows: GraphFlow[] = []
946
-
947
- // Check if destination is the kubernetes API server
948
- const isKubernetesAPI = (name: string, namespace: string | undefined) => {
949
- return name === 'kubernetes' && (!namespace || namespace === 'default')
950
- }
951
-
952
- focusedFlows.forEach(flow => {
953
- const sourceIsAddon = isClusterAddon(flow.source.name, flow.source.namespace)
954
- const destIsAddon = isClusterAddon(flow.destination.name, flow.destination.namespace)
955
- const sourceIsInternet = flow.source.kind === 'Internet'
956
- const destIsK8sAPI = isKubernetesAPI(flow.destination.name, flow.destination.namespace)
957
-
958
- // Internet → Addon: aggregate into single edge to group
959
- if (sourceIsInternet && destIsAddon) {
960
- addonInternetTotal += flow.connections
961
- addonInternetRate += flow.requestRate ?? 0
962
- for (const pair of flow.rawPairs ?? []) addonInternetPairs.push(pair)
963
- processedFlows.push({
964
- ...flow,
965
- source: {
966
- name: 'addon-internet',
967
- namespace: '',
968
- kind: 'SkipEdge', // Create addon node but skip individual edge
969
- },
970
- })
971
- }
972
- // Addon → Kubernetes API: aggregate into single edge from group
973
- else if (sourceIsAddon && destIsK8sAPI) {
974
- addonToK8sTotal += flow.connections
975
- addonToK8sRate += flow.requestRate ?? 0
976
- for (const pair of flow.rawPairs ?? []) addonToK8sPairs.push(pair)
977
- processedFlows.push({
978
- ...flow,
979
- destination: {
980
- ...flow.destination,
981
- kind: 'SkipEdge', // Create kubernetes node but skip individual edge
982
- },
983
- })
984
- }
985
- else {
986
- processedFlows.push(flow)
987
- }
988
- })
989
-
990
- // Add virtual flow for Internet → Addon Group edge
991
- if (addonInternetTotal > 0) {
992
- processedFlows.push({
993
- source: {
994
- name: 'addon-internet',
995
- namespace: '',
996
- kind: 'AddonInternet',
997
- },
998
- destination: {
999
- name: 'addon-group-target',
1000
- namespace: '',
1001
- kind: 'AddonGroupTarget',
1002
- },
1003
- protocol: 'tcp',
1004
- port: 0,
1005
- connections: addonInternetTotal,
1006
- ...(addonInternetRate > 0 && { requestRate: addonInternetRate }),
1007
- rawPairs: addonInternetPairs,
1008
- bytesSent: 0,
1009
- bytesRecv: 0,
1010
- flowCount: 1,
1011
- lastSeen: new Date().toISOString(),
1012
- })
1013
- }
1014
-
1015
- // Add virtual flow for Addon Group → Kubernetes edge
1016
- if (addonToK8sTotal > 0) {
1017
- processedFlows.push({
1018
- source: {
1019
- name: 'addon-group-source',
1020
- namespace: '',
1021
- kind: 'AddonGroupSource',
1022
- },
1023
- destination: {
1024
- name: 'kubernetes',
1025
- namespace: 'default',
1026
- kind: 'Service',
1027
- },
1028
- protocol: 'tcp',
1029
- port: 443,
1030
- connections: addonToK8sTotal,
1031
- ...(addonToK8sRate > 0 && { requestRate: addonToK8sRate }),
1032
- rawPairs: addonToK8sPairs,
1033
- bytesSent: 0,
1034
- bytesRecv: 0,
1035
- flowCount: 1,
1036
- lastSeen: new Date().toISOString(),
1037
- })
1038
- }
1039
-
1040
- return processedFlows
1041
- }, [focusedFlows, groupAddons])
937
+ const finalFlows = useMemo<GraphFlow[]>(() =>
938
+ groupAddons ? groupAddonFlows(focusedFlows, isClusterAddon) : focusedFlows,
939
+ [focusedFlows, groupAddons])
1042
940
 
1043
941
  // The map is laid out on the main thread, so a view too large to draw is
1044
942
  // listed as a table instead of freezing the tab.
@@ -1056,9 +954,13 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1056
954
  if (finalFlows.length > 0 && fitsBudget) setDrawnViewKey(viewKey)
1057
955
  }, [finalFlows.length, fitsBudget, viewKey])
1058
956
 
957
+ // Listed as a table instead of drawn: too large, or the map's layout engine
958
+ // could not load.
959
+ const listed = tooLargeToDraw || layoutUnavailable
960
+
1059
961
  // The table lists the endpoints as they are, so a selection made from it is
1060
962
  // traced through the same flows.
1061
- const selectableFlows = tooLargeToDraw ? focusedFlows : finalFlows
963
+ const selectableFlows = listed ? focusedFlows : finalFlows
1062
964
  // The server edges behind the selection, as drawn: what its records are
1063
965
  // narrowed to, whichever form the lookup is sent in.
1064
966
  // The flow list follows the focus while nothing else is selected: closing
@@ -1067,8 +969,8 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1067
969
  () => graphSelection ?? (focusFound && focusKey ? { type: 'node', nodeId: focusKey } : null),
1068
970
  [graphSelection, focusFound, focusKey])
1069
971
  const selectionPairs = useMemo(
1070
- () => selectionRawPairs(selectableFlows, listSelection, groupAddons && !tooLargeToDraw ? e => isClusterAddon(e.name, e.namespace) : undefined),
1071
- [listSelection, selectableFlows, groupAddons, tooLargeToDraw])
972
+ () => selectionRawPairs(selectableFlows, listSelection, groupAddons && !listed ? e => isClusterAddon(e.name, e.namespace) : undefined),
973
+ [listSelection, selectableFlows, groupAddons, listed])
1072
974
  const selection = useMemo(() => selectionMatch(selectionPairs, listSelection), [selectionPairs, listSelection])
1073
975
  // Ungrouped, a workload focus is drawn as its pods, so no node carries its
1074
976
  // id; its records are still the workload's.
@@ -1087,12 +989,12 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1087
989
  // A selection names something in the representation it was made in: the
1088
990
  // table lists endpoints as they are, the graph may group addons. Switching
1089
991
  // between them keeps only a focus's selection, which means the same in both.
1090
- const prevTooLargeRef = useRef(tooLargeToDraw)
992
+ const prevListedRef = useRef(listed)
1091
993
  useEffect(() => {
1092
- if (prevTooLargeRef.current === tooLargeToDraw) return
1093
- prevTooLargeRef.current = tooLargeToDraw
994
+ if (prevListedRef.current === listed) return
995
+ prevListedRef.current = listed
1094
996
  setGraphSelection(prev => (prev?.type === 'node' && prev.nodeId === focusKey ? prev : null))
1095
- }, [tooLargeToDraw, focusKey])
997
+ }, [listed, focusKey])
1096
998
 
1097
999
  // Namespaces hidden in the sidebar are dropped at the source too, when the
1098
1000
  // request has room, so their traffic can't fill the records limit. Only
@@ -1554,7 +1456,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1554
1456
  />
1555
1457
  ) : finalFlows.length > 0 ? (
1556
1458
  <>
1557
- {flowsWarning && !tooLargeToDraw && (
1459
+ {flowsWarning && !listed && (
1558
1460
  // Sits below the two chip rows (both top-3) rather than beside
1559
1461
  // them: centred at that height it would cover the flow count and
1560
1462
  // the refresh control at common widths. role/aria-live because it
@@ -1586,18 +1488,33 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1586
1488
  notice={flowsWarning && <div role="status" aria-live="polite">{flowsWarning}</div>}
1587
1489
  />
1588
1490
  ) : (
1589
- <TrafficGraph
1590
- flows={finalFlows}
1591
- hotPathThreshold={hotPathThreshold}
1592
- showNamespaceGroups={showNamespaceGroups}
1593
- serviceCategories={serviceCategories}
1594
- addonMode={groupAddons ? 'group' : addonMode === 'group' ? 'show' : addonMode}
1595
- trafficSource={sourcesData?.active || ''}
1596
- selection={graphSelection}
1597
- onSelectionChange={setGraphSelection}
1598
- onFocus={setFocus}
1599
- focusedId={focusKey}
1600
- />
1491
+ <>
1492
+ {layoutUnavailable && (
1493
+ <TrafficGraphUnavailable
1494
+ flows={focusedFlows}
1495
+ isRateBased={isRateBased}
1496
+ selection={graphSelection}
1497
+ onSelect={setGraphSelection}
1498
+ onFocus={setFocus}
1499
+ focusedId={focusKey}
1500
+ notice={flowsWarning && <div role="status" aria-live="polite">{flowsWarning}</div>}
1501
+ />
1502
+ )}
1503
+ <TrafficGraph
1504
+ flows={finalFlows}
1505
+ hotPathThreshold={hotPathThreshold}
1506
+ showNamespaceGroups={showNamespaceGroups}
1507
+ serviceCategories={serviceCategories}
1508
+ addonMode={groupAddons ? 'group' : addonMode === 'group' ? 'show' : addonMode}
1509
+ trafficSource={sourcesData?.active || ''}
1510
+ selection={graphSelection}
1511
+ onSelectionChange={setGraphSelection}
1512
+ onFocus={setFocus}
1513
+ focusedId={focusKey}
1514
+ onLayoutUnavailable={setLayoutUnavailable}
1515
+ windowSeconds={rateWindowSeconds(timeRange)}
1516
+ />
1517
+ </>
1601
1518
  )}
1602
1519
  </>
1603
1520
  ) : focus && flowsData && !connectionError ? (
@@ -1,6 +1,6 @@
1
1
  import { describe, it, expect } from 'vitest'
2
2
  import type { AggregatedFlow, TrafficFlow } from '../../types'
3
- import { matchesStatusRanges, bucketsFromCounts, bucketsFromStatus, isRateBasedSource, keepAvailable, effectiveThreshold, volumeUnit, isExternalKind, isPolicyDropReason, requestRateOf, errorRateOf, formatRate, displayVolume, mergeFlowVolume, dedupeHTTPPairs, coverageLabel, latencyWeightOf, endpointPair, selectionRawPairs, mergeRawPairs, graphEndpoint, graphSize, parseFocus, focusParam, focusId, touchesFocus, focusNeighborhood, endpointSummaries, searchEndpoints, namespaceSummaries, namespaceOverBudget, hasStatusData, connectionRows, selectionMatch, edgeCarriesPort, edgesOnPort, mergedEdgePort, selectedEdgeMatcher, verdictChoices, warningRetries, warningBannerTitle, emptyWarningHeadline, type GraphFlow } from './trafficFilters'
3
+ import { dataByProtocol, protocolsOf, totalDataByProtocol, rateWindowSeconds, throughputLabel, protocolName, matchesStatusRanges, bucketsFromCounts, bucketsFromStatus, isRateBasedSource, keepAvailable, effectiveThreshold, volumeUnit, isExternalKind, isPolicyDropReason, requestRateOf, errorRateOf, formatRate, displayVolume, groupAddonFlows, mergeFlowVolume, dedupeHTTPPairs, coverageLabel, latencyWeightOf, endpointPair, selectionRawPairs, mergeRawPairs, graphEndpoint, graphSize, parseFocus, focusParam, focusId, touchesFocus, focusNeighborhood, endpointSummaries, searchEndpoints, namespaceSummaries, namespaceOverBudget, hasStatusData, connectionRows, selectionMatch, edgeCarriesPort, edgesOnPort, mergedEdgePort, selectedEdgeMatcher, verdictChoices, warningRetries, warningBannerTitle, emptyWarningHeadline, protocolLabel, type GraphFlow } from './trafficFilters'
4
4
 
5
5
  describe('matchesStatusRanges', () => {
6
6
  it('does not filter when nothing is selected', () => {
@@ -714,3 +714,174 @@ describe('flows warning kinds', () => {
714
714
  expect(warningBannerTitle('cluster')).not.toBe(warningBannerTitle('transient'))
715
715
  })
716
716
  })
717
+
718
+ describe('protocolLabel', () => {
719
+ it('names the application and transport protocols when they differ', () => {
720
+ expect(protocolLabel('HTTP', 'tcp')).toBe('HTTP / tcp')
721
+ })
722
+ it('names a protocol once when a mesh reports it as both', () => {
723
+ expect(protocolLabel('HTTP', 'http')).toBe('HTTP')
724
+ expect(protocolLabel('GRPC', 'grpc')).toBe('GRPC')
725
+ })
726
+ it('falls back to the transport protocol', () => {
727
+ expect(protocolLabel(undefined, 'tcp')).toBe('tcp')
728
+ expect(protocolLabel('', 'udp')).toBe('udp')
729
+ })
730
+ })
731
+
732
+
733
+ describe('groupAddonFlows', () => {
734
+ const addon = (_name: string, namespace: string | undefined) => namespace === 'monitoring'
735
+ const flow = (source: AggregatedFlow['source'], destination: AggregatedFlow['destination'], bytesSent: number): GraphFlow => {
736
+ const f = { source, destination, bytesSent, bytesRecv: bytesSent * 2, bytesByProtocol: { tcp: { bytesSent, bytesRecv: bytesSent * 2 } }, connections: 0, flowCount: 1, port: 443, protocol: 'tcp', lastSeen: '' }
737
+ return { ...f, rawPairs: [endpointPair(f)] }
738
+ }
739
+ const internet = { name: 'Internet', namespace: '', kind: 'Internet' }
740
+ const prometheus = { name: 'prometheus', namespace: 'monitoring', kind: 'Pod' }
741
+ const grafana = { name: 'grafana', namespace: 'monitoring', kind: 'Pod' }
742
+ const kubernetes = { name: 'kubernetes', namespace: 'default', kind: 'Service' }
743
+
744
+ it('keeps both group edges with bytes and selection records when no connections are measured', () => {
745
+ const incoming = [flow(internet, prometheus, 100), flow(internet, grafana, 200)]
746
+ const outgoing = [flow(prometheus, kubernetes, 300), flow(grafana, kubernetes, 400)]
747
+ const original = [...incoming, ...outgoing]
748
+ const snapshot = structuredClone(original)
749
+ const grouped = groupAddonFlows(original, addon)
750
+ const edges = grouped.filter(f => f.source.kind !== 'SkipEdge' && f.destination.kind !== 'SkipEdge')
751
+ expect(edges).toHaveLength(2)
752
+ expect(edges[0]).toMatchObject({ connections: 0, bytesSent: 300, bytesRecv: 600, flowCount: 2, protocol: 'tcp', port: 443 })
753
+ expect(edges[1]).toMatchObject({ connections: 0, bytesSent: 700, bytesRecv: 1400, flowCount: 2, protocol: 'tcp', port: 443 })
754
+ expect(selectionRawPairs(grouped, { type: 'edge', sourceId: 'addon-internet', destId: 'addon-group', port: 443 }))
755
+ .toEqual(selectionRawPairs(incoming, { type: 'node', nodeId: 'Internet' }))
756
+ expect(selectionRawPairs(grouped, { type: 'edge', sourceId: 'addon-group', destId: 'default/kubernetes', port: 443 }))
757
+ .toHaveLength(2)
758
+ expect(original).toEqual(snapshot)
759
+ })
760
+
761
+ it('sums HTTP rates together with bytes-only contributions', () => {
762
+ const tcp = flow(internet, prometheus, 100)
763
+ const http = { ...flow(internet, grafana, 200), connections: 2, requestRate: 1.7 }
764
+ const grouped = groupAddonFlows([tcp, http], addon)
765
+ expect(grouped.find(f => f.source.kind === 'AddonInternet'))
766
+ .toMatchObject({ connections: 2, requestRate: 1.7, bytesSent: 300, bytesRecv: 600 })
767
+ })
768
+
769
+ it('keeps group selection when the first contributor has unknown direction', () => {
770
+ const incoming = { ...flow(internet, prometheus, 100), directionUnknown: true, l7Protocol: 'HTTP' }
771
+ incoming.rawPairs = [endpointPair(incoming)]
772
+ const grouped = groupAddonFlows([incoming], addon)
773
+ const virtual = grouped.find(f => f.source.kind === 'AddonInternet')!
774
+ expect(virtual.directionUnknown).toBeUndefined()
775
+ expect(virtual.l7Protocol).toBe('HTTP')
776
+ expect(selectionRawPairs(grouped, { type: 'edge', sourceId: 'addon-internet', destId: 'addon-group', port: 443 }))
777
+ .toEqual(incoming.rawPairs)
778
+ })
779
+
780
+ for (const direction of ['incoming', 'outgoing']) {
781
+ const contributors = () => direction === 'incoming'
782
+ ? [flow(internet, prometheus, 100), flow(internet, grafana, 200)]
783
+ : [flow(prometheus, kubernetes, 100), flow(grafana, kubernetes, 200)]
784
+ const virtualFlow = (flows: GraphFlow[]) => groupAddonFlows(flows, addon).find(f =>
785
+ f.source.kind === 'AddonInternet' || f.source.kind === 'AddonGroupSource')!
786
+
787
+ it(`keeps common HTTP metadata and unreported ports for ${direction} contributors`, () => {
788
+ const http = contributors().map(f => ({ ...f, port: 0, protocol: 'http', l7Protocol: 'HTTP', bytesByProtocol: { http: { bytesSent: f.bytesSent, bytesRecv: f.bytesRecv } } }))
789
+ expect(virtualFlow(http)).toMatchObject({ port: 0, protocol: 'http', l7Protocol: 'HTTP' })
790
+ expect(virtualFlow(http.map(f => ({ ...f, port: 8080 })))).toMatchObject({ port: 8080, protocol: 'http', l7Protocol: 'HTTP' })
791
+ })
792
+
793
+ it(`shows mixed protocols and the lowest reported port for ${direction} contributors in either order`, () => {
794
+ const [a, b] = contributors()
795
+ const mixed: GraphFlow[] = [{ ...a, port: 8080, protocol: 'http', l7Protocol: 'HTTP', bytesByProtocol: { http: { bytesSent: a.bytesSent, bytesRecv: a.bytesRecv } } }, { ...b, port: 443 }]
796
+ for (const inputs of [mixed, [...mixed].reverse()]) {
797
+ expect(virtualFlow(inputs)).toMatchObject({ port: 443, protocol: 'mixed', l7Protocol: 'mixed', bytesSent: 300, bytesRecv: 600 })
798
+ expect(dataByProtocol(virtualFlow(inputs))).toEqual([{ protocol: 'http', sent: 100, recv: 200 }, { protocol: 'tcp', sent: 200, recv: 400 }])
799
+ expect(virtualFlow([{ ...inputs[0], port: 0 }, inputs[1]]).port).toBe(inputs[1].port)
800
+ }
801
+ })
802
+
803
+ it(`keeps a common transport while marking mixed L7 metadata for ${direction} contributors`, () => {
804
+ const [a, b] = contributors()
805
+ expect(virtualFlow([{ ...a, l7Protocol: 'HTTP' }, { ...b, l7Protocol: 'DNS' }]))
806
+ .toMatchObject({ protocol: 'tcp', l7Protocol: 'mixed' })
807
+ })
808
+
809
+ it(`keeps all raw pairs when selecting mixed ${direction} contributors across a port change`, () => {
810
+ const [a, b] = contributors()
811
+ const http = { ...a, port: 0, protocol: 'http', l7Protocol: 'HTTP' }
812
+ const inputs = [http, b].map(f => ({ ...f, rawPairs: [endpointPair(f)] }))
813
+ const grouped = groupAddonFlows(inputs, addon)
814
+ const ids = direction === 'incoming'
815
+ ? { sourceId: 'addon-internet', destId: 'addon-group' }
816
+ : { sourceId: 'addon-group', destId: 'default/kubernetes' }
817
+ for (const port of [0, 443]) {
818
+ expect(selectionRawPairs(grouped, { type: 'edge', ...ids, port })).toEqual([endpointPair(b), endpointPair(http)])
819
+ }
820
+ })
821
+ }
822
+
823
+ it('adds no virtual edges without contributing flows', () => {
824
+ const plain = flow({ name: 'client', namespace: 'shop', kind: 'Pod' }, kubernetes, 100)
825
+ expect(groupAddonFlows([plain], addon)).toEqual([plain])
826
+ expect(groupAddonFlows([], addon)).toEqual([])
827
+ })
828
+ })
829
+
830
+ describe('protocol byte figures', () => {
831
+ const base: AggregatedFlow = {
832
+ source: { name: 'client', namespace: 'demo', kind: 'Pod' },
833
+ destination: { name: 'server', namespace: 'demo', kind: 'Pod' },
834
+ port: 0, protocol: 'http', connections: 1, flowCount: 1, lastSeen: '',
835
+ bytesSent: 5969, bytesRecv: 260965, bytesByProtocol: { http: { bytesSent: 5969, bytesRecv: 260965 } },
836
+ }
837
+ const tcp: AggregatedFlow = { ...base, protocol: 'tcp', bytesSent: 32699, bytesRecv: 391439, bytesByProtocol: { tcp: { bytesSent: 32699, bytesRecv: 391439 } } }
838
+
839
+ it('merges fresh buckets in either order across repeated shallow-copy collapses', () => {
840
+ for (const flows of [[base, tcp], [tcp, base]]) {
841
+ const snapshot = structuredClone(flows)
842
+ const external = { ...flows[0] }
843
+ mergeFlowVolume(external, flows[1])
844
+ const internet = { ...external }
845
+ mergeFlowVolume(internet, base)
846
+ expect(dataByProtocol(external)).toEqual([{ protocol: 'http', sent: 5969, recv: 260965 }, { protocol: 'tcp', sent: 32699, recv: 391439 }])
847
+ expect(dataByProtocol(internet)[0]).toEqual({ protocol: 'http', sent: 11938, recv: 521930 })
848
+ expect(flows).toEqual(snapshot)
849
+ expect(external.bytesByProtocol).not.toBe(internet.bytesByProtocol)
850
+ expect(external.bytesByProtocol!.http).not.toBe(internet.bytesByProtocol!.http)
851
+ }
852
+ })
853
+
854
+ it('sorts payloads first and retains zero-byte protocols', () => {
855
+ expect(protocolsOf({ bytesByProtocol: { udp: { bytesSent: 0, bytesRecv: 0 }, tcp: { bytesSent: 1, bytesRecv: 2 }, http: { bytesSent: 3, bytesRecv: 4 }, grpc: { bytesSent: 5, bytesRecv: 6 } } }))
856
+ .toEqual(['grpc', 'http', 'tcp', 'udp'])
857
+ expect(protocolName('grpc')).toBe('gRPC')
858
+ expect(protocolName('http')).toBe('HTTP')
859
+ })
860
+
861
+ it('never attributes a released HTTP/gRPC scalar to the first protocol through merges or node totals', () => {
862
+ const legacy = { ...base, bytesByProtocol: undefined, bytesSent: 100, bytesRecv: 200 }
863
+ expect(dataByProtocol(legacy)).toEqual([{ protocol: null, sent: 100, recv: 200 }])
864
+ const merged = { ...legacy }
865
+ mergeFlowVolume(merged, legacy)
866
+ expect(merged.bytesByProtocol).toBeUndefined()
867
+ expect(dataByProtocol(merged)).toEqual([{ protocol: null, sent: 200, recv: 400 }])
868
+ expect(totalDataByProtocol([merged, legacy])).toEqual([{ protocol: null, sent: 300, recv: 600 }])
869
+ })
870
+ })
871
+
872
+ describe('rateWindowSeconds', () => {
873
+ it('follows the server: the range, five minutes under a minute, at most an hour', () => {
874
+ expect([ '1m', '5m', '15m', '1h', '30s', '2h', 'bogus' ].map(rateWindowSeconds)).toEqual([60, 300, 900, 3600, 300, 3600, 300])
875
+ })
876
+ })
877
+
878
+ describe('throughputLabel', () => {
879
+ it('divides the bytes of each protocol by the window and skips protocols that moved nothing', () => {
880
+ const base = { protocol: 'tcp', bytesSent: 0, bytesRecv: 0 }
881
+ expect(throughputLabel({ ...base, bytesByProtocol: { tcp: { bytesSent: 29999, bytesRecv: 119999 }, udp: { bytesSent: 0, bytesRecv: 0 } } }, 60)).toBe('TCP · 2.4 KB/s')
882
+ expect(throughputLabel({ ...base, bytesByProtocol: { tcp: { bytesSent: 600, bytesRecv: 0 } } }, 300)).toBe('TCP · 2 B/s')
883
+ // An older Radar sends only the sum, which can mix TCP and UDP: no protocol, no throughput.
884
+ expect(throughputLabel({ ...base, bytesSent: 4200, bytesRecv: 7500 }, 300)).toBe('')
885
+ expect(throughputLabel({ ...base, bytesByProtocol: { tcp: { bytesSent: 0, bytesRecv: 0 } } }, 60)).toBe('')
886
+ })
887
+ })