@skyhook-io/radar-app 1.21.8 → 1.22.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 (83) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +16 -1
  3. package/src/api/client.ts +18 -0
  4. package/src/api/cnpg-history.ts +3 -3
  5. package/src/api/cnpg-storage.ts +3 -3
  6. package/src/api/diagnose.test.ts +34 -0
  7. package/src/api/diagnose.ts +17 -4
  8. package/src/api/radarFeatures.test.ts +13 -1
  9. package/src/api/radarFeatures.ts +6 -0
  10. package/src/api/resourceActions.test.ts +829 -0
  11. package/src/api/resourceActions.ts +584 -0
  12. package/src/api/resourceActions.ui.test.tsx +1882 -0
  13. package/src/api/reviewedActionMutation.ts +56 -28
  14. package/src/api/substrateHealth.ts +2 -3
  15. package/src/api/traefik.ts +33 -0
  16. package/src/api/traffic.ts +14 -5
  17. package/src/api/workloadMetrics.test.ts +11 -2
  18. package/src/api/workloadMetrics.ts +2 -2
  19. package/src/components/CloudFunnelButton.test.tsx +39 -1
  20. package/src/components/CloudFunnelButton.tsx +10 -3
  21. package/src/components/cnpg/CNPGOverview.test.tsx +75 -3
  22. package/src/components/cnpg/CNPGOverview.tsx +62 -4
  23. package/src/components/diagnose/AnalysisStory.test.tsx +12 -0
  24. package/src/components/diagnose/DiagnoseContext.question.test.tsx +34 -1
  25. package/src/components/diagnose/DiagnoseContext.tsx +28 -3
  26. package/src/components/diagnose/DiagnoseSurface.tsx +5 -4
  27. package/src/components/diagnose/Home.tsx +3 -0
  28. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +61 -0
  29. package/src/components/diagnose/InvestigationView.followupFailure.test.tsx +122 -0
  30. package/src/components/diagnose/InvestigationView.tsx +10 -2
  31. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +1 -1
  32. package/src/components/diagnose/LocalDiagnoseAction.tsx +2 -2
  33. package/src/components/diagnose/QuestionComposer.test.tsx +16 -2
  34. package/src/components/diagnose/QuestionComposer.tsx +13 -8
  35. package/src/components/diagnose/diagnoseEvidenceTypes.ts +47 -8
  36. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +153 -0
  37. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +9 -13
  38. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +21 -5
  39. package/src/components/diagnose/investigationEvidence/bodies/network.tsx +63 -26
  40. package/src/components/diagnose/launch.ts +1 -1
  41. package/src/components/dock/PodDebugSession.test.tsx +66 -0
  42. package/src/components/dock/PodDebugSession.tsx +3 -1
  43. package/src/components/dock/TerminalTab.test.tsx +43 -3
  44. package/src/components/dock/TerminalTab.tsx +10 -1
  45. package/src/components/helm/HelmReleaseDrawer.tsx +1 -1
  46. package/src/components/helm/InstallWizard.tsx +1 -1
  47. package/src/components/home/NetworkPolicyCoverageCard.test.tsx +37 -0
  48. package/src/components/home/NetworkPolicyCoverageCard.tsx +26 -2
  49. package/src/components/home/mcpToolCatalog.ts +1 -1
  50. package/src/components/resources/PodEvictAction.test.tsx +951 -0
  51. package/src/components/resources/PodEvictAction.tsx +167 -0
  52. package/src/components/resources/ResourcesView.tsx +3 -0
  53. package/src/components/resources/renderers/TraefikIngressRouteRenderer.test.tsx +23 -0
  54. package/src/components/resources/renderers/TraefikIngressRouteRenderer.tsx +23 -0
  55. package/src/components/resources/renderers/TraefikMiddlewareRenderer.test.tsx +23 -0
  56. package/src/components/resources/renderers/TraefikMiddlewareRenderer.tsx +29 -0
  57. package/src/components/resources/renderers/WorkloadRenderer.tsx +3 -0
  58. package/src/components/settings/LocalConnectionSettings.tsx +4 -4
  59. package/src/components/settings/SettingsDialog.tsx +23 -18
  60. package/src/components/settings/integrationQueries.test.ts +98 -0
  61. package/src/components/settings/integrationQueries.ts +36 -0
  62. package/src/components/traffic/TrafficConnectionsTable.test.tsx +23 -0
  63. package/src/components/traffic/TrafficConnectionsTable.tsx +5 -4
  64. package/src/components/traffic/TrafficFilterSidebar.test.tsx +14 -0
  65. package/src/components/traffic/TrafficFilterSidebar.tsx +17 -0
  66. package/src/components/traffic/TrafficFlowList.tsx +5 -5
  67. package/src/components/traffic/TrafficGraph.test.tsx +11 -0
  68. package/src/components/traffic/TrafficGraph.tsx +31 -19
  69. package/src/components/traffic/TrafficView.reconnect.test.tsx +229 -0
  70. package/src/components/traffic/TrafficView.tsx +108 -41
  71. package/src/components/traffic/traffic-export.test.ts +8 -0
  72. package/src/components/traffic/traffic-export.ts +7 -4
  73. package/src/components/traffic/trafficFilters.test.ts +51 -1
  74. package/src/components/traffic/trafficFilters.ts +39 -11
  75. package/src/components/ui/Markdown.test.tsx +37 -0
  76. package/src/components/ui/Markdown.tsx +15 -2
  77. package/src/components/ui/command-items-crd.test.tsx +23 -8
  78. package/src/components/useContextSwitchFlow.test.tsx +27 -2
  79. package/src/components/useContextSwitchFlow.tsx +20 -22
  80. package/src/components/whats-new/releaseNotes.ts +75 -1
  81. package/src/components/workload/WorkloadView.tsx +16 -3
  82. package/src/integrations/resourceHosts.test.tsx +1 -1
  83. package/src/integrations/resourceHosts.tsx +3 -0
@@ -8,7 +8,7 @@ import { SEVERITY_TEXT } from '@skyhook-io/k8s-ui/utils/badge-colors'
8
8
  import { Tooltip } from '../ui/Tooltip'
9
9
  import type { TrafficGraphSelection } from './TrafficGraph'
10
10
  import {
11
- dataByProtocol, connectionRows, displayVolume, edgesOnPort, flowDrops, flowErrors, formatRate, graphEndpointId, hasStatusData, isExternalKind,
11
+ dataByProtocol, connectionRows, displayVolume, edgesOnPort, flowDrops, flowErrors, formatRate, graphEndpointId, hasStatusData, isExternalKind, portLabel,
12
12
  type GraphFlow, type TrafficFocus,
13
13
  } from './trafficFilters'
14
14
 
@@ -40,6 +40,7 @@ function rowSelection(flow: AggregatedFlow): TrafficGraphSelection {
40
40
  destId: graphEndpointId(flow.destination),
41
41
  port: flow.port,
42
42
  directionUnknown: !!flow.directionUnknown,
43
+ ...(flow.likelyOverlay && { likelyOverlay: true }),
43
44
  }
44
45
  }
45
46
 
@@ -47,7 +48,7 @@ function selectedRows(rows: GraphFlow[], selection: TrafficGraphSelection | null
47
48
  if (selection?.type !== 'edge' || selection.port === undefined) return new Set()
48
49
  const between = rows.filter(flow =>
49
50
  graphEndpointId(flow.source) === selection.sourceId && graphEndpointId(flow.destination) === selection.destId &&
50
- !!flow.directionUnknown === !!selection.directionUnknown)
51
+ !!flow.directionUnknown === !!selection.directionUnknown && !!flow.likelyOverlay === !!selection.likelyOverlay)
51
52
  return new Set(edgesOnPort(between, f => f, selection.port))
52
53
  }
53
54
 
@@ -106,7 +107,7 @@ export function TrafficConnectionsTable({ flows, isRateBased, selection, onSelec
106
107
  <Virtuoso
107
108
  className="flex-1"
108
109
  data={rows}
109
- computeItemKey={(_, flow) => `${graphEndpointId(flow.source)}->${graphEndpointId(flow.destination)}:${flow.port}${flow.directionUnknown ? ':u' : ''}`}
110
+ computeItemKey={(_, flow) => `${graphEndpointId(flow.source)}->${graphEndpointId(flow.destination)}:${flow.port}${flow.directionUnknown ? ':u' : ''}${flow.likelyOverlay ? ':v' : ''}`}
110
111
  itemContent={(_, flow) => {
111
112
  const sel = rowSelection(flow)
112
113
  const isSelected = selected.has(flow)
@@ -129,7 +130,7 @@ export function TrafficConnectionsTable({ flows, isRateBased, selection, onSelec
129
130
  : <ArrowRight className="h-3 w-3 text-theme-text-tertiary" />}
130
131
  {endpoint(flow.destination)}
131
132
  <span className="truncate text-theme-text-secondary tabular-nums">
132
- {flow.port > 0 ? flow.port : '—'}
133
+ {portLabel(flow.port, flow.portSource) ?? '—'}
133
134
  {(flow.l7Protocol || flow.protocol) && (
134
135
  <span className="ml-1 text-theme-text-tertiary">{flow.l7Protocol || flow.protocol.toUpperCase()}</span>
135
136
  )}
@@ -75,3 +75,17 @@ describe('TrafficFilterSidebar verdict filter', () => {
75
75
  expect(container.textContent).not.toContain('Verdict')
76
76
  })
77
77
  })
78
+
79
+ describe('TrafficFilterSidebar overlay toggle', () => {
80
+ it('is offered only when the source marked flows as likely overlay, off by default', () => {
81
+ act(() => root.render(<TrafficFilterSidebar {...props({ setHideOverlay: vi.fn() })} />))
82
+ expect(container.textContent).not.toContain('Hide node-to-node overlay')
83
+
84
+ const setHideOverlay = vi.fn()
85
+ act(() => root.render(<TrafficFilterSidebar {...props({ hasOverlayFlows: true, hideOverlay: false, setHideOverlay })} />))
86
+ expect(container.textContent).toContain('Hide node-to-node overlay')
87
+ const toggle = Array.from(container.querySelectorAll('button')).find(b => b.textContent?.includes('Hide node-to-node overlay'))!
88
+ act(() => toggle.click())
89
+ expect(setHideOverlay).toHaveBeenCalledWith(true)
90
+ })
91
+ })
@@ -12,6 +12,7 @@ import {
12
12
  Puzzle,
13
13
  Boxes,
14
14
  ShieldAlert,
15
+ Server,
15
16
  } from 'lucide-react'
16
17
  import { clsx } from 'clsx'
17
18
  import { SEVERITY_BADGE } from '@skyhook-io/k8s-ui/utils/badge-colors'
@@ -35,6 +36,10 @@ interface TrafficFilterSidebarProps {
35
36
  setHideSystem: (v: boolean) => void
36
37
  hideExternal: boolean
37
38
  setHideExternal: (v: boolean) => void
39
+ /** Offered only when the source marked some flows as likely overlay. */
40
+ hasOverlayFlows?: boolean
41
+ hideOverlay?: boolean
42
+ setHideOverlay?: (v: boolean) => void
38
43
  minConnections: number
39
44
  setMinConnections: (v: number) => void
40
45
 
@@ -151,6 +156,9 @@ export const TrafficFilterSidebar = memo(function TrafficFilterSidebar({
151
156
  setHideSystem,
152
157
  hideExternal,
153
158
  setHideExternal,
159
+ hasOverlayFlows,
160
+ hideOverlay,
161
+ setHideOverlay,
154
162
  minConnections,
155
163
  setMinConnections,
156
164
  showNamespaceGroups,
@@ -257,6 +265,15 @@ export const TrafficFilterSidebar = memo(function TrafficFilterSidebar({
257
265
  onToggle={() => setHideExternal(!hideExternal)}
258
266
  icon={Globe}
259
267
  />
268
+ {hasOverlayFlows && setHideOverlay && (
269
+ <ToggleOption
270
+ label="Hide node-to-node overlay"
271
+ description="UDP between two nodes is likely CNI overlay (VXLAN, Geneve) carrying pod traffic already on the map. Unless Beyla reports the port, a guess: WireGuard or DNS between nodes look the same."
272
+ enabled={!!hideOverlay}
273
+ onToggle={() => setHideOverlay(!hideOverlay)}
274
+ icon={Server}
275
+ />
276
+ )}
260
277
  </div>
261
278
 
262
279
  {/* Cluster Addons 3-way toggle */}
@@ -8,7 +8,7 @@ import { SEVERITY_BADGE, SEVERITY_TEXT } from '@skyhook-io/k8s-ui/utils/badge-co
8
8
  import { pluralize, StatusDot } from '@skyhook-io/k8s-ui'
9
9
  import type { StatusTone } from '@skyhook-io/k8s-ui'
10
10
  import { useFlowSearch } from './TrafficFlowListContext'
11
- import { isPolicyDropReason, protocolLabel } from './trafficFilters'
11
+ import { isPolicyDropReason, portLabel, protocolLabel } from './trafficFilters'
12
12
  import { useQuery } from '@tanstack/react-query'
13
13
  import { fetchJSON } from '../../api/client'
14
14
  import { Tooltip } from '../ui/Tooltip'
@@ -208,7 +208,7 @@ export function TrafficFlowList({ flows, responsesCallerOriented }: TrafficFlowL
208
208
  </>
209
209
  )}
210
210
  {!isHTTP && !isDNS && (
211
- <span className="text-theme-text-tertiary uppercase">{flow.port ? `${flow.protocol}:${flow.port}` : flow.protocol}</span>
211
+ <span className="text-theme-text-tertiary"><span className="uppercase">{flow.protocol}</span>{portLabel(flow.port, flow.portSource) && `:${portLabel(flow.port, flow.portSource)}`}</span>
212
212
  )}
213
213
  </div>
214
214
 
@@ -255,10 +255,10 @@ export function TrafficFlowList({ flows, responsesCallerOriented }: TrafficFlowL
255
255
  <span className="text-theme-text-primary">{protocolLabel(flow.l7Protocol, flow.protocol)}</span>
256
256
  {flow.httpProtocol && <span className="text-theme-text-tertiary"> ({flow.httpProtocol})</span>}
257
257
  </div>
258
- {flow.port !== 0 && (
258
+ {portLabel(flow.port, flow.portSource) && (
259
259
  <div>
260
260
  <span className="text-theme-text-tertiary">Port: </span>
261
- <span className="text-theme-text-primary">{flow.port}</span>
261
+ <span className="text-theme-text-primary">{portLabel(flow.port, flow.portSource)}</span>
262
262
  </div>
263
263
  )}
264
264
  {flow.trafficDirection && (
@@ -440,7 +440,7 @@ function PolicyCorrelation({ flow }: { flow: TrafficFlow }) {
440
440
  if (src?.name) params.set('sourcePodName', src.name)
441
441
  if (src?.kind) params.set('sourceKind', src.kind)
442
442
  if (src?.ip) params.set('sourceIP', src.ip)
443
- if (flow.port) params.set('port', String(flow.port))
443
+ if (flow.port && !flow.portSource) params.set('port', String(flow.port))
444
444
  if (flow.protocol) params.set('protocol', flow.protocol)
445
445
  return fetchJSON(`/network-policies/evaluate?${params}`)
446
446
  },
@@ -297,3 +297,14 @@ describe('TrafficNode title', () => {
297
297
  expect(container.querySelector(`[title="${label}"]`)!.closest('[aria-hidden="true"]')).not.toBeNull()
298
298
  })
299
299
  })
300
+
301
+ it('draws likely-overlay traffic between two nodes as its own edge', async () => {
302
+ const nodeA = { name: 'node-a', namespace: '', kind: 'External' }
303
+ const nodeB = { name: 'node-b', namespace: '', kind: 'External' }
304
+ const tcp: AggregatedFlow = { source: nodeA, destination: nodeB, protocol: 'tcp', port: 0, connections: 0, bytesSent: 10, bytesRecv: 0, flowCount: 1, lastSeen: '' }
305
+ const overlay: AggregatedFlow = { ...tcp, protocol: 'udp', bytesSent: 1000, likelyOverlay: true }
306
+ await act(async () => root.render(<TrafficGraph flows={[tcp, overlay]} trafficSource="beyla" onLayoutUnavailable={vi.fn()} windowSeconds={60} />))
307
+ const ids = [...container.querySelectorAll('[data-edge]')].map(e => e.getAttribute('data-edge'))
308
+ expect(ids).toContain('node-a->node-b:0')
309
+ expect(ids).toContain('node-a->node-b:0:overlay')
310
+ })
@@ -16,7 +16,7 @@ import {
16
16
  } from '@xyflow/react'
17
17
  import '@xyflow/react/dist/style.css'
18
18
  import type { ELK } from 'elkjs/lib/elk.bundled.js'
19
- import type { AggregatedFlow } from '../../types'
19
+ import type { AggregatedFlow, TrafficPortSource } from '../../types'
20
20
  import { clsx } from 'clsx'
21
21
  import { X, ArrowRight, Globe, Server, Activity, Puzzle, Crosshair } from 'lucide-react'
22
22
  import { GraphExportButton, MiddleEllipsis, PaneLoader } from '@skyhook-io/k8s-ui'
@@ -26,7 +26,7 @@ import { getNamespaceColor } from '../../utils/traffic-colors'
26
26
  import { Tooltip } from '../ui/Tooltip'
27
27
  import { TrafficData } from './TrafficData'
28
28
  import { describeTrafficNode } from './traffic-export'
29
- import { dataByProtocol, protocolsOf, throughputLabel, totalDataByProtocol, protocolName, isRateBasedSource, isExternalKind, requestRateOf, errorRateOf, formatRate, formatConnections, formatVolume, MAX_VISIBLE_PORTS, displayVolume, latencyWeightOf, edgesOnPort, protocolLabel, type TrafficFocus } from './trafficFilters'
29
+ import { dataByProtocol, protocolsOf, throughputLabel, totalDataByProtocol, protocolName, isRateBasedSource, isExternalKind, requestRateOf, errorRateOf, formatRate, formatConnections, formatVolume, MAX_VISIBLE_PORTS, displayVolume, latencyWeightOf, edgesOnPort, protocolLabel, portLabel, type TrafficFocus } from './trafficFilters'
30
30
 
31
31
  // ELK is 1.5 MB; load it with the first traffic layout, not with the app.
32
32
  let elkPromise: Promise<ELK> | null = null
@@ -64,8 +64,9 @@ export interface TrafficGraphSelection {
64
64
  sourceId?: string
65
65
  destId?: string
66
66
  port?: number
67
- // The graph draws traffic of unknown direction as its own edge.
67
+ // The graph draws traffic of unknown direction, and likely overlay, as its own edge.
68
68
  directionUnknown?: boolean
69
+ likelyOverlay?: boolean
69
70
  }
70
71
 
71
72
  interface TrafficGraphProps {
@@ -157,6 +158,8 @@ function StatusDistributionBar({ counts }: { counts: Record<string, number> }) {
157
158
  interface PortInfo {
158
159
  port: number
159
160
  connections: number
161
+ /** Set when no edge observed this port: taken from a Service, or, on port 0, several Service ports. */
162
+ portSource?: TrafficPortSource
160
163
  }
161
164
 
162
165
  interface TrafficNodeData extends Record<string, unknown> {
@@ -301,15 +304,15 @@ export function TrafficNode({ data }: { data: TrafficNodeData }) {
301
304
  </div>
302
305
  )}
303
306
  {/* Ports section */}
304
- {data.ports && data.ports.filter(p => p.port !== 0).length > 0 && (
307
+ {data.ports && data.ports.filter(p => portLabel(p.port, p.portSource) !== null).length > 0 && (
305
308
  <div className="mt-1.5 space-y-0.5">
306
- {data.ports.filter(p => p.port !== 0).slice(0, MAX_VISIBLE_PORTS).map((portInfo) => (
309
+ {data.ports.filter(p => portLabel(p.port, p.portSource) !== null).slice(0, MAX_VISIBLE_PORTS).map((portInfo) => (
307
310
  <div key={portInfo.port} className="flex items-center justify-between gap-1 text-xs">
308
311
  <span className={clsx(
309
312
  'font-mono',
310
313
  (hasNamespaceColor || isAddonNode) ? 'text-cyan-300' : 'text-blue-600 dark:text-blue-300'
311
314
  )}>
312
- :{portInfo.port}
315
+ :{portLabel(portInfo.port, portInfo.portSource)}
313
316
  </span>
314
317
  {/* A port serving traffic with no HTTP has no request rate to show, and
315
318
  "0" beside the port reads as an idle port rather than an unmeasured
@@ -328,18 +331,18 @@ export function TrafficNode({ data }: { data: TrafficNodeData }) {
328
331
  )}
329
332
  </div>
330
333
  ))}
331
- {data.ports.filter(p => p.port !== 0).length > MAX_VISIBLE_PORTS && (
334
+ {data.ports.filter(p => portLabel(p.port, p.portSource) !== null).length > MAX_VISIBLE_PORTS && (
332
335
  <div className={clsx(
333
336
  'text-xs',
334
337
  (hasNamespaceColor || isAddonNode) ? 'text-white/50' : 'text-theme-text-tertiary'
335
338
  )}>
336
- +{data.ports.filter(p => p.port !== 0).length - MAX_VISIBLE_PORTS} more
339
+ +{data.ports.filter(p => portLabel(p.port, p.portSource) !== null).length - MAX_VISIBLE_PORTS} more
337
340
  </div>
338
341
  )}
339
342
  </div>
340
343
  )}
341
344
  {/* Total connections (only if no ports shown, or all ports are 0) */}
342
- {(!data.ports || data.ports.filter(p => p.port !== 0).length === 0) && data.totalConnections != null && data.totalConnections > 0 && (
345
+ {(!data.ports || data.ports.filter(p => portLabel(p.port, p.portSource) !== null).length === 0) && data.totalConnections != null && data.totalConnections > 0 && (
343
346
  <div className="mt-1">
344
347
  <span className={clsx(
345
348
  'text-xs truncate',
@@ -754,8 +757,8 @@ function DetailsPanel({
754
757
  ) : (
755
758
  <ArrowRight className="h-3 w-3 text-theme-text-tertiary shrink-0" />
756
759
  )}
757
- {flow.port !== 0 && (
758
- <span className="text-blue-400 font-mono">:{flow.port}</span>
760
+ {portLabel(flow.port, flow.portSource) && (
761
+ <span className="text-blue-400 font-mono">:{portLabel(flow.port, flow.portSource)}</span>
759
762
  )}
760
763
  </div>
761
764
  <div className="flex items-center gap-2 text-[10px]">
@@ -806,8 +809,8 @@ function DetailsPanel({
806
809
  <span className="text-theme-text-primary truncate flex-1">
807
810
  {flow.destination.name}
808
811
  </span>
809
- {flow.port !== 0 && (
810
- <span className="text-blue-400 font-mono">:{flow.port}</span>
812
+ {portLabel(flow.port, flow.portSource) && (
813
+ <span className="text-blue-400 font-mono">:{portLabel(flow.port, flow.portSource)}</span>
811
814
  )}
812
815
  </div>
813
816
  <div className="flex items-center gap-2 text-[10px]">
@@ -858,10 +861,10 @@ function DetailsPanel({
858
861
  </div>
859
862
 
860
863
  <div className="grid grid-cols-2 gap-2 text-xs">
861
- {edgeData.port !== 0 && (
864
+ {portLabel(edgeData.port, edgeData.flow?.portSource) && (
862
865
  <div className="p-2 rounded bg-theme-elevated">
863
866
  <div className="text-theme-text-tertiary">Port</div>
864
- <div className="text-theme-text-primary font-medium">{edgeData.port}</div>
867
+ <div className="text-theme-text-primary font-medium">{portLabel(edgeData.port, edgeData.flow?.portSource)}</div>
865
868
  </div>
866
869
  )}
867
870
  <div className="p-2 rounded bg-theme-elevated">
@@ -1151,7 +1154,8 @@ function isFocusable(id: string, data: TrafficNodeData | undefined): boolean {
1151
1154
  // one would silently replace the other. Only unoriented edges are suffixed, so
1152
1155
  // every id a source that always orients its flows produces is unchanged.
1153
1156
  function trafficEdgeId(sourceId: string, destId: string, flow: AggregatedFlow): string {
1154
- return `${sourceId}->${destId}:${flow.port}${flow.directionUnknown ? ':unoriented' : ''}`
1157
+ // The server keeps likely-overlay traffic apart from the rest between the same nodes.
1158
+ return `${sourceId}->${destId}:${flow.port}${flow.directionUnknown ? ':unoriented' : ''}${flow.likelyOverlay ? ':overlay' : ''}`
1155
1159
  }
1156
1160
 
1157
1161
  export function TrafficGraph({ flows, hotPathThreshold = 0, showNamespaceGroups = false, serviceCategories, addonMode = 'show', trafficSource = '', selection: viewSelection, onSelectionChange, onFocus, focusedId, onLayoutUnavailable, windowSeconds, onDownloadBlob }: TrafficGraphProps) {
@@ -1194,6 +1198,8 @@ export function TrafficGraph({ flows, hotPathThreshold = 0, showNamespaceGroups
1194
1198
 
1195
1199
  // Track primary port for each node (most common destination port)
1196
1200
  const nodePorts = new Map<string, Map<number, number>>() // nodeId -> port -> connection count
1201
+ const observedPorts = new Set<string>() // `${nodeId}|${port}` seen on an edge that observed it
1202
+ const multiplePorts = new Set<string>() // nodes an edge reached on several possible Service ports
1197
1203
 
1198
1204
  // Count connections per node
1199
1205
  flows.forEach((flow) => {
@@ -1218,6 +1224,8 @@ export function TrafficGraph({ flows, hotPathThreshold = 0, showNamespaceGroups
1218
1224
  if (!nodePorts.has(destId)) nodePorts.set(destId, new Map())
1219
1225
  const portCounts = nodePorts.get(destId)!
1220
1226
  portCounts.set(flow.port, (portCounts.get(flow.port) || 0) + volume)
1227
+ if (!flow.portSource) observedPorts.add(`${destId}|${flow.port}`)
1228
+ if (flow.portSource === 'serviceMultiple') multiplePorts.add(destId)
1221
1229
  if (flow.connections >= hotPathThreshold && hotPathThreshold > 0) hotNodes.add(destId)
1222
1230
  }
1223
1231
  })
@@ -1228,7 +1236,10 @@ export function TrafficGraph({ flows, hotPathThreshold = 0, showNamespaceGroups
1228
1236
  if (!ports || ports.size === 0) return []
1229
1237
  const portList: PortInfo[] = []
1230
1238
  ports.forEach((connections, port) => {
1231
- portList.push({ port, connections })
1239
+ const portSource: TrafficPortSource | undefined = port === 0
1240
+ ? (multiplePorts.has(nodeId) ? 'serviceMultiple' : undefined)
1241
+ : (observedPorts.has(`${nodeId}|${port}`) ? undefined : 'service')
1242
+ portList.push({ port, connections, ...(portSource && { portSource }) })
1232
1243
  })
1233
1244
  // Sort by connection count descending
1234
1245
  return portList.sort((a, b) => b.connections - a.connections)
@@ -1739,7 +1750,8 @@ export function TrafficGraph({ flows, hotPathThreshold = 0, showNamespaceGroups
1739
1750
  }
1740
1751
  const between = layoutedEdges.filter(e =>
1741
1752
  e.source === viewSelection.sourceId && e.target === viewSelection.destId &&
1742
- !!flowByEdgeId.get(e.id)?.directionUnknown === !!viewSelection.directionUnknown)
1753
+ !!flowByEdgeId.get(e.id)?.directionUnknown === !!viewSelection.directionUnknown &&
1754
+ !!flowByEdgeId.get(e.id)?.likelyOverlay === !!viewSelection.likelyOverlay)
1743
1755
  const [edge] = edgesOnPort(between, e => flowByEdgeId.get(e.id), viewSelection.port)
1744
1756
  setSelection(edge ? edgeSelection(edge, flowByEdgeId.get(edge.id)) : null)
1745
1757
  }, [viewSelection, layoutedNodes, layoutedEdges, flowByEdgeId])
@@ -1768,7 +1780,7 @@ export function TrafficGraph({ flows, hotPathThreshold = 0, showNamespaceGroups
1768
1780
  const onEdgeClick: EdgeMouseHandler<Edge> = useCallback((_event, edge) => {
1769
1781
  const flow = flowByEdgeId.get(edge.id)
1770
1782
  setSelection(edgeSelection(edge, flow))
1771
- onSelectionChange?.({ type: 'edge', sourceId: edge.source, destId: edge.target, port: flow?.port, directionUnknown: !!flow?.directionUnknown })
1783
+ onSelectionChange?.({ type: 'edge', sourceId: edge.source, destId: edge.target, port: flow?.port, directionUnknown: !!flow?.directionUnknown, ...(flow?.likelyOverlay && { likelyOverlay: true }) })
1772
1784
  }, [flowByEdgeId, onSelectionChange])
1773
1785
 
1774
1786
  const onPaneClick = useCallback(() => {
@@ -0,0 +1,229 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { MemoryRouter } from 'react-router-dom'
5
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
6
+ import { expect, it, vi } from 'vitest'
7
+ import { setAutomaticRequestMarking } from '../../api/config'
8
+ import { invalidateIntegrationQueries } from '../settings/integrationQueries'
9
+ import { TrafficView } from './TrafficView'
10
+
11
+ vi.mock('../../hooks/useDesktopDownload', () => ({ useDesktopBlobDownload: () => undefined }))
12
+ vi.mock('./TrafficGraph', () => ({ TrafficGraph: () => null }))
13
+
14
+ vi.mock('../../api/client', async importOriginal => ({
15
+ ...(await importOriginal<typeof import('../../api/client')>()),
16
+ useClusterInfo: () => ({ data: { context: 'test' } }),
17
+ useNamespaceScope: () => ({ data: undefined }),
18
+ }))
19
+
20
+ vi.mock('../dock', async importOriginal => ({
21
+ ...(await importOriginal<typeof import('../dock')>()),
22
+ useDock: () => ({ setLeftOffset: () => {}, addTab: () => 'flows', removeTab: () => {} }),
23
+ }))
24
+
25
+ vi.mock('../../context/ConnectionContext', async importOriginal => ({
26
+ ...(await importOriginal<typeof import('../../context/ConnectionContext')>()),
27
+ useConnection: () => ({ connection: { state: 'connected' } }),
28
+ }))
29
+
30
+ const settle = () => act(async () => {
31
+ await new Promise(resolve => setTimeout(resolve, 0))
32
+ })
33
+
34
+ it.each([
35
+ 'success',
36
+ 'failure',
37
+ 'cancelled detection',
38
+ 'unmounted during detection',
39
+ 'cancelled manual Retry',
40
+ 'status stays disconnected',
41
+ 'initial status stays disconnected',
42
+ 'flows lose source without Settings invalidation',
43
+ 'Beyla unavailable until Metrics repair',
44
+ ])('handles traffic connection status and source loss (%s)', async (scenario) => {
45
+ const queryClient = new QueryClient({ defaultOptions: { queries: { enabled: false, retryDelay: 0 } } })
46
+ const container = document.body.appendChild(document.createElement('div'))
47
+ const root = createRoot(container)
48
+ const connectOrigins: (string | null)[] = []
49
+ const connectionFailure = 'Could not connect to Hubble'
50
+ const notConnected = 'Not connected to Hubble Relay. Call Connect() first or use the Traffic view to establish connection.'
51
+ const source = scenario === 'Beyla unavailable until Metrics repair' ? 'beyla' : 'hubble'
52
+ const manualRetry = scenario === 'cancelled manual Retry'
53
+ const cancelledDetection = manualRetry ? 2 : scenario === 'cancelled detection' ? 1 : 0
54
+ let connected = false
55
+ let sourceAvailable = true
56
+ let freshDetections = 0
57
+ let resumeDetection: (() => void) | undefined
58
+ let unmounted = false
59
+ let warnings = 0
60
+ let disconnectedStatusReads = 0
61
+ let statusReadsAfterReconnect = 0
62
+ queryClient.setQueryDefaults(['traffic-sources'], { enabled: true })
63
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
64
+ setAutomaticRequestMarking(true)
65
+ vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => {
66
+ const { pathname, search } = new URL(url, window.location.origin)
67
+ switch (pathname) {
68
+ case '/api/traffic/sources':
69
+ if (!search) {
70
+ freshDetections++
71
+ if (freshDetections === cancelledDetection) {
72
+ return new Promise<Response>((_, reject) => {
73
+ init!.signal!.addEventListener('abort', () => reject(init!.signal!.reason), { once: true })
74
+ })
75
+ }
76
+ if (scenario === 'unmounted during detection') {
77
+ await new Promise<void>(resolve => { resumeDetection = resolve })
78
+ }
79
+ }
80
+ return Response.json({
81
+ cluster: {}, active: sourceAvailable ? source : '', notDetected: [],
82
+ detected: [{ name: source, status: sourceAvailable ? 'available' : 'not_found' }],
83
+ })
84
+ case '/api/traffic/connection':
85
+ if (connectOrigins.length > 1) statusReadsAfterReconnect++
86
+ if (!connected) disconnectedStatusReads++
87
+ return Response.json({ connected: connected &&
88
+ scenario !== 'initial status stays disconnected' &&
89
+ !((scenario === 'status stays disconnected' || manualRetry) && connectOrigins.length > 1) })
90
+ case '/api/traffic/connect':
91
+ expect(init?.method).toBe('POST')
92
+ connectOrigins.push(new Headers(init?.headers).get('X-Radar-Request-Origin'))
93
+ if ((connectOrigins.length > 1 && scenario === 'failure') || (connectOrigins.length === 2 && manualRetry)) {
94
+ return Response.json({ connected: false, error: connectionFailure })
95
+ }
96
+ if (!sourceAvailable) {
97
+ return Response.json({ error: 'No traffic source available' }, { status: 503 })
98
+ }
99
+ connected = true
100
+ return Response.json({ connected })
101
+ case '/api/traffic/flows':
102
+ if (!connected && (scenario === 'flows lose source without Settings invalidation' || !sourceAvailable)) {
103
+ return Response.json({ error: 'no traffic source available' }, { status: 503 })
104
+ }
105
+ if (!connected) warnings++
106
+ return Response.json({ source, timestamp: '', flows: [], aggregated: [], warning: connected ? undefined : notConnected })
107
+ default:
108
+ throw new Error(`Unexpected request to ${url}`)
109
+ }
110
+ }))
111
+
112
+ try {
113
+ await act(async () => {
114
+ root.render(
115
+ <QueryClientProvider client={queryClient}>
116
+ <MemoryRouter initialEntries={['/traffic']}>
117
+ <TrafficView namespaces={[]} />
118
+ </MemoryRouter>
119
+ </QueryClientProvider>,
120
+ )
121
+ })
122
+ await vi.waitFor(async () => {
123
+ await settle()
124
+ expect(connected).toBe(true)
125
+ expect(queryClient.getQueryData(['traffic-connection'])).toEqual({
126
+ connected: scenario !== 'initial status stays disconnected',
127
+ })
128
+ expect(queryClient.getQueryState(['traffic-connection'])?.fetchStatus).toBe('idle')
129
+ })
130
+ await settle()
131
+ expect(connectOrigins).toEqual(['auto'])
132
+ expect(freshDetections).toBe(0)
133
+ if (scenario === 'initial status stays disconnected') return
134
+
135
+ connected = false
136
+ const statusReadsBeforeLoss = disconnectedStatusReads
137
+ if (scenario === 'flows lose source without Settings invalidation' || source === 'beyla') {
138
+ sourceAvailable = source !== 'beyla'
139
+ await act(async () => {
140
+ await queryClient.refetchQueries({ queryKey: ['traffic-flows'] })
141
+ })
142
+ } else {
143
+ const warningsBeforeSave = warnings
144
+ await act(async () => invalidateIntegrationQueries(queryClient, ['metrics']))
145
+ expect(warnings).toBeGreaterThan(warningsBeforeSave)
146
+ }
147
+
148
+ if (scenario === 'unmounted during detection') {
149
+ await vi.waitFor(() => expect(resumeDetection).toBeDefined())
150
+ expect(connectOrigins).toEqual(['auto'])
151
+ act(() => root.unmount())
152
+ unmounted = true
153
+ resumeDetection!()
154
+ await settle()
155
+ expect(queryClient.getQueryState(['traffic-sources'])?.status).toBe('success')
156
+ expect(connectOrigins).toEqual(['auto'])
157
+ return
158
+ }
159
+
160
+ if (source === 'beyla') {
161
+ await vi.waitFor(async () => {
162
+ await settle()
163
+ expect(container.textContent).toContain('Beyla is installed but not usable')
164
+ })
165
+ expect(freshDetections).toBe(1)
166
+ expect(connectOrigins).toEqual(['auto'])
167
+ sourceAvailable = true
168
+ await act(async () => invalidateIntegrationQueries(queryClient, ['metrics']))
169
+ }
170
+
171
+ if (scenario === 'cancelled detection') {
172
+ await vi.waitFor(async () => {
173
+ await settle()
174
+ expect(freshDetections).toBe(1)
175
+ })
176
+ expect(connectOrigins).toEqual(['auto'])
177
+ await act(async () => invalidateIntegrationQueries(queryClient, ['metrics']))
178
+ }
179
+ await vi.waitFor(async () => {
180
+ await settle()
181
+ if (scenario === 'failure' || manualRetry) {
182
+ expect(container.textContent).toContain(connectionFailure)
183
+ expect(container.textContent).toContain('Retry Connection')
184
+ } else if (scenario === 'status stays disconnected') {
185
+ expect(statusReadsAfterReconnect).toBeGreaterThan(0)
186
+ } else {
187
+ expect(queryClient.getQueryData(['traffic-connection'])).toEqual({ connected: true })
188
+ }
189
+ })
190
+ if (manualRetry) {
191
+ const retry = Array.from(container.querySelectorAll('button')).find(button => button.textContent?.trim() === 'Retry Connection')
192
+ expect(retry).toBeDefined()
193
+ await act(async () => retry!.click())
194
+ await vi.waitFor(() => expect(freshDetections).toBe(2))
195
+ expect(connectOrigins).toEqual(['auto', 'auto'])
196
+
197
+ await act(async () => invalidateIntegrationQueries(queryClient, ['metrics']))
198
+ await vi.waitFor(async () => {
199
+ await settle()
200
+ expect(connectOrigins).toEqual(['auto', 'auto', 'auto'])
201
+ expect(queryClient.getQueryData(['traffic-connection'])).toEqual({ connected: false })
202
+ expect(queryClient.getQueryState(['traffic-connection'])?.fetchStatus).toBe('idle')
203
+ })
204
+ // The save's invalidation can restart the reconnect's detection, so only
205
+ // the second save is held to starting nothing.
206
+ const detectionsBeforeSecondSave = freshDetections
207
+ await act(async () => invalidateIntegrationQueries(queryClient, ['metrics']))
208
+ await settle()
209
+ expect(connectOrigins).toEqual(['auto', 'auto', 'auto'])
210
+ expect(freshDetections).toBe(detectionsBeforeSecondSave)
211
+ return
212
+ }
213
+ if (scenario === 'flows lose source without Settings invalidation') {
214
+ expect(disconnectedStatusReads - statusReadsBeforeLoss).toBe(1)
215
+ } else {
216
+ await act(async () => invalidateIntegrationQueries(queryClient, ['metrics']))
217
+ }
218
+ await settle()
219
+ expect(container.textContent).not.toContain('No traffic source available')
220
+ expect(connectOrigins).toEqual(['auto', 'auto'])
221
+ expect(freshDetections).toBe(scenario === 'cancelled detection' ? 2 : 1)
222
+ } finally {
223
+ if (!unmounted) act(() => root.unmount())
224
+ queryClient.clear()
225
+ container.remove()
226
+ setAutomaticRequestMarking(false)
227
+ vi.unstubAllGlobals()
228
+ }
229
+ })