@skyhook-io/radar-app 1.21.1 → 1.21.3
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 +11 -0
- package/package.json +2 -2
- package/src/App.tsx +50 -28
- package/src/api/actions.test.ts +11 -0
- package/src/api/actions.ts +5 -0
- package/src/api/apiResources.navigation.test.tsx +58 -0
- package/src/api/apiResources.ts +22 -16
- package/src/api/client.diagnostics.test.ts +52 -0
- package/src/api/client.triggerCronJob.test.tsx +49 -0
- package/src/api/client.ts +140 -120
- package/src/api/connectionBinding.test.tsx +82 -0
- package/src/api/connectionBinding.ts +52 -0
- package/src/api/contextSwitch.test.ts +11 -0
- package/src/api/contextSwitch.ts +58 -0
- package/src/api/radarFeatures.ts +7 -0
- package/src/api/sealedSecrets.test.ts +22 -0
- package/src/api/sealedSecrets.ts +37 -0
- package/src/api/vulnerabilities.ts +80 -7
- package/src/components/ConnectionErrorView.tsx +13 -0
- package/src/components/ContextSwitchActions.tsx +43 -0
- package/src/components/ContextSwitcher.tsx +13 -6
- package/src/components/SwitchAwareConnectionError.tsx +2 -2
- package/src/components/audit/Java4ShellPanel.test.tsx +104 -7
- package/src/components/audit/Java4ShellPanel.tsx +169 -72
- package/src/components/cost/ApplicationCostTab.test.ts +16 -0
- package/src/components/cost/ApplicationCostTab.tsx +41 -9
- package/src/components/cost/CostTrendChart.tsx +25 -2
- package/src/components/cost/CostTrendWithheld.render.test.tsx +105 -0
- package/src/components/cost/CostView.tsx +10 -2
- package/src/components/cost/CostViewTabs.test.tsx +18 -0
- package/src/components/cost/CostViewTabs.tsx +14 -22
- package/src/components/cost/WorkloadCostTab.test.ts +15 -0
- package/src/components/cost/WorkloadCostTab.tsx +42 -8
- package/src/components/cost/source.test.ts +16 -1
- package/src/components/cost/source.ts +34 -0
- package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +35 -0
- package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +16 -1
- package/src/components/dock/NodeTerminalTab.test.tsx +4 -2
- package/src/components/dock/NodeTerminalTab.tsx +8 -8
- package/src/components/dock/TerminalTab.test.tsx +12 -1
- package/src/components/dock/TerminalTab.tsx +6 -3
- package/src/components/home/CostCard.test.tsx +49 -0
- package/src/components/home/CostCard.tsx +98 -63
- package/src/components/home/mcpToolCatalog.ts +1 -0
- package/src/components/resource/DatadogRightsizingPanel.test.tsx +118 -0
- package/src/components/resource/DatadogRightsizingPanel.tsx +68 -0
- package/src/components/resource/DatadogWorkloadCharts.tsx +149 -0
- package/src/components/resource/HPACharts.render.test.tsx +42 -0
- package/src/components/resource/HPACharts.tsx +34 -1
- package/src/components/resource/PrometheusChartsGrid.render.test.tsx +126 -3
- package/src/components/resource/PrometheusChartsGrid.tsx +58 -25
- package/src/components/resource/RestartChart.render.test.tsx +72 -0
- package/src/components/resource/RestartChart.tsx +31 -3
- package/src/components/resource/RightsizingPanel.access.test.tsx +24 -0
- package/src/components/resource/RightsizingStrip.render.test.tsx +44 -0
- package/src/components/resource/RightsizingStrip.test.ts +1 -188
- package/src/components/resource/RightsizingStrip.tsx +27 -300
- package/src/components/resource/WorkloadMetricsSection.render.test.tsx +22 -0
- package/src/components/resource/WorkloadMetricsSection.tsx +14 -4
- package/src/components/resource/nameMatchedScope.ts +39 -0
- package/src/components/resources/pod-file-upload.ts +3 -0
- package/src/components/resources/renderers/CAPIClusterRenderer.tsx +5 -2
- package/src/components/resources/renderers/LonghornVolumeRenderer.test.tsx +104 -0
- package/src/components/resources/renderers/LonghornVolumeRenderer.tsx +31 -0
- package/src/components/resources/renderers/SealedSecretRenderer.test.tsx +41 -0
- package/src/components/resources/renderers/SealedSecretRenderer.tsx +14 -0
- package/src/components/rightsizing/RightsizingScanLink.tsx +22 -0
- package/src/components/rightsizing/RightsizingScanView.tsx +65 -528
- package/src/components/rightsizing/model.test.ts +20 -9
- package/src/components/rightsizing/model.ts +17 -176
- package/src/components/rightsizing/notices.test.tsx +30 -29
- package/src/components/traffic/TrafficFlowList.tsx +8 -4
- package/src/components/traffic/TrafficGraph.test.tsx +31 -1
- package/src/components/traffic/TrafficGraph.tsx +11 -6
- package/src/components/traffic/trafficFilters.ts +4 -4
- package/src/components/ui/DiagnosticsOverlay.test.ts +3 -2
- package/src/components/ui/DiagnosticsOverlay.tsx +23 -13
- package/src/components/ui/command-items.ts +3 -4
- package/src/components/useContextSwitchFlow.test.tsx +9 -0
- package/src/components/useContextSwitchFlow.tsx +43 -5
- package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.test.tsx +54 -0
- package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.tsx +50 -109
- package/src/components/whats-new/releaseNotes.ts +1 -1
- package/src/components/workload/WorkloadRightsizingSource.test.tsx +83 -0
- package/src/components/workload/WorkloadView.test.ts +22 -1
- package/src/components/workload/WorkloadView.tsx +57 -16
- package/src/context/ConnectionContext.test.ts +1 -0
- package/src/context/ConnectionContext.tsx +58 -15
- package/src/context/ConnectionProvider.connectionId.test.tsx +92 -0
- package/src/context/ConnectionProvider.retry.test.tsx +174 -1
- package/src/context/ContextSwitchContext.tsx +15 -1
- package/src/context/NavCustomization.tsx +6 -3
- package/src/hooks/useEventSource.test.tsx +85 -0
- package/src/hooks/useEventSource.ts +43 -16
- package/src/hooks/useResetViewsOnContextChange.test.tsx +34 -0
- package/src/hooks/useResetViewsOnContextChange.ts +27 -0
- package/src/index.ts +3 -0
- package/src/integrations/resourceHosts.test.tsx +2 -2
- package/src/integrations/resourceHosts.tsx +4 -0
- package/src/utils/navigation.ts +1 -15
- package/src/utils/page-links.ts +6 -0
- package/src/components/rightsizing/presentation.test.ts +0 -150
- package/src/components/rightsizing/presentation.ts +0 -109
|
@@ -3,6 +3,9 @@ import { useQuery, useMutation, useQueryClient, type QueryClient } from '@tansta
|
|
|
3
3
|
import { automaticRequestHeaders, getApiBase } from '../api/config'
|
|
4
4
|
import { readErrorBody } from '../api/httpErrors'
|
|
5
5
|
import { apiFetch, type SyncStatusSnapshot, type NodeDrainActivity } from '../api/client'
|
|
6
|
+
import { followSwitch, switchInProgress, type ContextSwitchOperation } from '../api/contextSwitch'
|
|
7
|
+
import { observeConnectionStatus } from '../api/connectionBinding'
|
|
8
|
+
import { showApiNotice } from '../components/ui/Toast'
|
|
6
9
|
import { ClusterConnectedContext } from './clusterConnected'
|
|
7
10
|
|
|
8
11
|
export type ConnectionStateType = 'connected' | 'disconnected' | 'connecting'
|
|
@@ -17,6 +20,9 @@ export interface ConnectionState {
|
|
|
17
20
|
// When this context stopped working (RFC 3339). Set by the server while
|
|
18
21
|
// disconnected; older servers never send it.
|
|
19
22
|
disconnectedAt?: string
|
|
23
|
+
// The connection Radar is serving (see connectionBinding.ts). Empty while a
|
|
24
|
+
// switch is between connections; never sent by an in-cluster or older Radar.
|
|
25
|
+
connectionId?: string
|
|
20
26
|
// Per-kind readiness while the initial informer sync runs ('connecting'
|
|
21
27
|
// with informers started). Drives the progressive app shell — absent once
|
|
22
28
|
// connected or before informers exist.
|
|
@@ -26,15 +32,18 @@ export interface ConnectionState {
|
|
|
26
32
|
interface ConnectionStatusResponse extends ConnectionState {
|
|
27
33
|
// Server-side auth recovery owns the episode: suppress browser auto-retry
|
|
28
34
|
// even when errorType has flipped to a non-auth value.
|
|
35
|
+
contextSwitch?: ContextSwitchOperation
|
|
29
36
|
authRecoveryOwed?: boolean
|
|
30
37
|
}
|
|
31
38
|
|
|
32
39
|
interface PolledConnectionStatus extends ConnectionStatusResponse {
|
|
33
40
|
sseGenerationAtStart: number
|
|
41
|
+
apiBase: string
|
|
34
42
|
}
|
|
35
43
|
|
|
36
44
|
interface ConnectionContextValue {
|
|
37
45
|
connection: ConnectionState
|
|
46
|
+
contextSwitch?: ContextSwitchOperation
|
|
38
47
|
retry: () => void
|
|
39
48
|
isRetrying: boolean
|
|
40
49
|
updateFromSSE: (status: ConnectionState) => void
|
|
@@ -43,7 +52,7 @@ interface ConnectionContextValue {
|
|
|
43
52
|
class ConnectionRetryError extends Error {
|
|
44
53
|
errorType?: string
|
|
45
54
|
|
|
46
|
-
constructor(message: string, errorType?: string) {
|
|
55
|
+
constructor(message: string, readonly status: number, errorType?: string, readonly code?: string) {
|
|
47
56
|
super(message)
|
|
48
57
|
this.name = 'ConnectionRetryError'
|
|
49
58
|
this.errorType = errorType
|
|
@@ -67,6 +76,9 @@ const CONNECTION_STATUS_FALLBACK_POLL_MS = 30000
|
|
|
67
76
|
export function refreshQueriesAfterReconnect(queryClient: QueryClient, previousContext: string, nextContext: string) {
|
|
68
77
|
queryClient.removeQueries({
|
|
69
78
|
predicate: query => {
|
|
79
|
+
// A context_changed frame can arrive before the operation's terminal poll.
|
|
80
|
+
// Connection status is process-wide and keeps that poll alive.
|
|
81
|
+
if (query.queryKey[0] === 'connection-status') return false
|
|
70
82
|
if (query.queryKey[0] !== 'node-drain-activity') return true
|
|
71
83
|
const activity = queryClient.getQueryData<NodeDrainActivity | null>(query.queryKey)
|
|
72
84
|
return activity?.contextName ? activity.contextName !== nextContext : previousContext !== nextContext
|
|
@@ -80,7 +92,7 @@ export function shouldAutoRetryConnection(errorType?: string): boolean {
|
|
|
80
92
|
// reconnect loop for those, and each browser retry would invoke the exec
|
|
81
93
|
// credential plugin again. Manual "Retry Connection" stays available for
|
|
82
94
|
// an immediate check. A settings error can't clear until Radar restarts.
|
|
83
|
-
return errorType !== 'config' && errorType !== 'settings' && errorType !== 'rbac' && !errorType?.startsWith('auth')
|
|
95
|
+
return errorType !== 'switch-stopped' && errorType !== 'config' && errorType !== 'settings' && errorType !== 'rbac' && !errorType?.startsWith('auth')
|
|
84
96
|
}
|
|
85
97
|
|
|
86
98
|
export function shouldApplyPolledConnection(
|
|
@@ -88,9 +100,10 @@ export function shouldApplyPolledConnection(
|
|
|
88
100
|
polledState: ConnectionStateType,
|
|
89
101
|
pollSSEGeneration: number,
|
|
90
102
|
currentSSEGeneration: number,
|
|
103
|
+
switchingToAnotherContext = false,
|
|
91
104
|
): boolean {
|
|
92
105
|
return pollSSEGeneration === currentSSEGeneration
|
|
93
|
-
&& (currentState !== 'connected' || polledState !== 'connecting')
|
|
106
|
+
&& (switchingToAnotherContext || currentState !== 'connected' || polledState !== 'connecting')
|
|
94
107
|
}
|
|
95
108
|
|
|
96
109
|
async function fetchConnectionStatus(sseGenerationAtStart: number): Promise<PolledConnectionStatus> {
|
|
@@ -102,24 +115,28 @@ async function fetchConnectionStatus(sseGenerationAtStart: number): Promise<Poll
|
|
|
102
115
|
// ?contexts=0: context enumeration re-reads kubeconfig files under the
|
|
103
116
|
// client write lock on the server — too costly for a perpetual poll, and
|
|
104
117
|
// nothing here consumes the list (ContextSwitcher has its own query).
|
|
105
|
-
const
|
|
118
|
+
const base = getApiBase()
|
|
119
|
+
const response = await apiFetch(`${base}/connection?contexts=0`)
|
|
106
120
|
if (!response.ok) {
|
|
107
121
|
throw new Error('Failed to fetch connection status')
|
|
108
122
|
}
|
|
109
123
|
const status = await response.json() as ConnectionStatusResponse
|
|
110
|
-
return { ...status, sseGenerationAtStart }
|
|
124
|
+
return { ...status, sseGenerationAtStart, apiBase: base }
|
|
111
125
|
}
|
|
112
126
|
|
|
113
127
|
async function retryConnection(automatic = false): Promise<ConnectionState> {
|
|
114
|
-
const
|
|
128
|
+
const base = getApiBase()
|
|
129
|
+
const response = await apiFetch(`${base}/connection/retry`, {
|
|
115
130
|
method: 'POST',
|
|
116
131
|
headers: automatic ? automaticRequestHeaders() : undefined,
|
|
117
132
|
})
|
|
118
133
|
if (!response.ok) {
|
|
119
|
-
const error = await readErrorBody(response) as { error?: string; errorType?: string }
|
|
120
|
-
throw new ConnectionRetryError(error.error || `HTTP ${response.status}`, error.errorType)
|
|
134
|
+
const error = await readErrorBody(response) as { error?: string; errorType?: string; error_code?: string }
|
|
135
|
+
throw new ConnectionRetryError(error.error || `HTTP ${response.status}`, response.status, error.errorType, error.error_code)
|
|
121
136
|
}
|
|
122
|
-
|
|
137
|
+
const result = await response.json() as ConnectionState
|
|
138
|
+
observeConnectionStatus(result, base)
|
|
139
|
+
return result
|
|
123
140
|
}
|
|
124
141
|
|
|
125
142
|
export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
@@ -216,7 +233,8 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
216
233
|
queryKey: ['connection-status'],
|
|
217
234
|
queryFn: () => fetchConnectionStatus(sseGenerationRef.current),
|
|
218
235
|
staleTime: 500, // Allow frequent refetches while connecting
|
|
219
|
-
refetchInterval:
|
|
236
|
+
refetchInterval: query => switchInProgress(query.state.data?.contextSwitch) ? 1000
|
|
237
|
+
: connection.state === 'connecting' ? 500 : CONNECTION_STATUS_FALLBACK_POLL_MS,
|
|
220
238
|
refetchIntervalInBackground: true,
|
|
221
239
|
refetchOnWindowFocus: true,
|
|
222
240
|
})
|
|
@@ -264,6 +282,7 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
264
282
|
data.state,
|
|
265
283
|
data.sseGenerationAtStart,
|
|
266
284
|
sseGenerationRef.current,
|
|
285
|
+
Boolean(data.context && current.context && data.context !== current.context),
|
|
267
286
|
)) {
|
|
268
287
|
// SSE owns the state fields, but connection_state frames don't carry
|
|
269
288
|
// per-kind sync progress — merge it from the poll so the progressive
|
|
@@ -273,6 +292,15 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
273
292
|
}
|
|
274
293
|
return
|
|
275
294
|
}
|
|
295
|
+
// Only a poll that wins over newer SSE state names the connection, or a
|
|
296
|
+
// stale reply would leave the tab sending the previous cluster's ID.
|
|
297
|
+
observeConnectionStatus(data, data.apiBase)
|
|
298
|
+
// A background tab can miss both the SSE event and the whole operation
|
|
299
|
+
// between polls. Apply the same cache and URL transition as the initiating tab.
|
|
300
|
+
if (current.state === 'connected' && current.context && current.context !== data.context &&
|
|
301
|
+
data.state === 'connected' && data.contextSwitch?.phase === 'succeeded' && data.contextSwitch.target === data.context) {
|
|
302
|
+
followSwitch(data.contextSwitch.id)
|
|
303
|
+
}
|
|
276
304
|
const becameConnected = current.state !== 'connected' && data.state === 'connected'
|
|
277
305
|
setConnection({
|
|
278
306
|
state: data.state,
|
|
@@ -293,20 +321,23 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
293
321
|
const retryMutation = useMutation({
|
|
294
322
|
mutationFn: () => retryConnection(),
|
|
295
323
|
onMutate: () => {
|
|
324
|
+
const previousConnection = connectionRef.current
|
|
296
325
|
manualRetryPendingRef.current = true
|
|
297
326
|
// Until SSE re-delivers state, a failed retry may report its own error
|
|
298
327
|
// rather than deferring to a stale "connected"
|
|
299
328
|
sseActiveRef.current = false
|
|
300
329
|
// Set connecting state while retrying
|
|
301
|
-
|
|
302
|
-
...
|
|
330
|
+
const pendingConnection: ConnectionState = {
|
|
331
|
+
...previousConnection,
|
|
303
332
|
state: 'connecting',
|
|
304
333
|
error: undefined,
|
|
305
334
|
progressMessage: 'Connecting to cluster...',
|
|
306
335
|
// A retry is a fresh attempt — per-kind progress from the previous
|
|
307
336
|
// attempt would mislabel readiness until the next poll.
|
|
308
337
|
syncStatus: undefined,
|
|
309
|
-
}
|
|
338
|
+
}
|
|
339
|
+
setConnection(prev => prev === previousConnection ? pendingConnection : prev)
|
|
340
|
+
return { previousConnection, pendingConnection }
|
|
310
341
|
},
|
|
311
342
|
onSuccess: (result) => {
|
|
312
343
|
const previousContext = connectionRef.current.context
|
|
@@ -319,8 +350,13 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
319
350
|
}
|
|
320
351
|
refreshQueriesAfterReconnect(queryClient, previousContext, result.context)
|
|
321
352
|
},
|
|
322
|
-
onError: (error: Error) => {
|
|
353
|
+
onError: (error: Error, _variables, attempt) => {
|
|
323
354
|
const retryError = error as ConnectionRetryError
|
|
355
|
+
if (retryError.status === 409) {
|
|
356
|
+
if (attempt) setConnection(prev => prev === attempt.pendingConnection ? attempt.previousConnection : prev)
|
|
357
|
+
if (retryError.code !== 'reconnect_superseded') showApiNotice('Cluster retry unavailable', error.message, 'info')
|
|
358
|
+
return
|
|
359
|
+
}
|
|
324
360
|
setConnection(prev => {
|
|
325
361
|
if (sseActiveRef.current && prev.state === 'connected') return prev
|
|
326
362
|
return {
|
|
@@ -405,6 +441,7 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
405
441
|
.catch((error: Error) => {
|
|
406
442
|
if (stopped) return
|
|
407
443
|
const retryError = error as ConnectionRetryError
|
|
444
|
+
if (retryError.status === 409) return
|
|
408
445
|
setConnection(prev => {
|
|
409
446
|
if (sseActiveRef.current && prev.state === 'connected') return prev
|
|
410
447
|
return {
|
|
@@ -483,13 +520,14 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
483
520
|
// in-flight polls detect they raced this frame.
|
|
484
521
|
sseActiveRef.current = true
|
|
485
522
|
sseGenerationRef.current += 1
|
|
523
|
+
observeConnectionStatus(status)
|
|
486
524
|
setConnection(prev => {
|
|
487
525
|
// Don't transition back to 'connecting' from 'connected'. This happens when the
|
|
488
526
|
// pod restarts and the SSE reconnects while the new pod's K8s cache is still
|
|
489
527
|
// syncing. Hiding the main content here causes a flash — keep the 'connected'
|
|
490
528
|
// state and wait for either 'connected' (sync done) or 'disconnected' (failure).
|
|
491
529
|
// (shouldApplyPolledConnection encodes the same suppression for the poll path.)
|
|
492
|
-
if (prev.state === 'connected' && status.state === 'connecting') {
|
|
530
|
+
if (prev.state === 'connected' && status.state === 'connecting' && (!status.context || status.context === prev.context)) {
|
|
493
531
|
return prev
|
|
494
532
|
}
|
|
495
533
|
// connection_state frames don't carry per-kind sync progress — keep the
|
|
@@ -506,8 +544,13 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
|
|
|
506
544
|
}
|
|
507
545
|
}, [refreshCachesOnConnect])
|
|
508
546
|
|
|
547
|
+
// Connection state may come from a newer SSE frame or still be applying this
|
|
548
|
+
// poll. Consume the terminal switch result alongside the matching connection.
|
|
549
|
+
const polledSwitch = data?.contextSwitch
|
|
550
|
+
const switchMatchesConnection = data?.state === connection.state && data?.context === connection.context
|
|
509
551
|
const value: ConnectionContextValue = {
|
|
510
552
|
connection,
|
|
553
|
+
contextSwitch: switchInProgress(polledSwitch) || switchMatchesConnection ? polledSwitch : undefined,
|
|
511
554
|
retry,
|
|
512
555
|
isRetrying: retryMutation.isPending || isAutoRetrying,
|
|
513
556
|
updateFromSSE,
|
|
@@ -0,0 +1,92 @@
|
|
|
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 { ConnectionProvider, useConnection } from './ConnectionContext'
|
|
7
|
+
import { connectionHeaderValue, resetConnectionBindingForTest } from '../api/connectionBinding'
|
|
8
|
+
|
|
9
|
+
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
|
|
10
|
+
|
|
11
|
+
let root: Root
|
|
12
|
+
let container: HTMLDivElement
|
|
13
|
+
const seen = vi.fn<(value: ReturnType<typeof useConnection>) => void>()
|
|
14
|
+
const latest = () => seen.mock.lastCall?.[0]
|
|
15
|
+
let polls: Array<(body: unknown) => void>
|
|
16
|
+
|
|
17
|
+
function Probe() {
|
|
18
|
+
seen(useConnection())
|
|
19
|
+
return null
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const statusA = { state: 'connected', context: 'A', connectionId: 'n-1' }
|
|
23
|
+
|
|
24
|
+
beforeEach(async () => {
|
|
25
|
+
vi.useFakeTimers()
|
|
26
|
+
seen.mockClear()
|
|
27
|
+
resetConnectionBindingForTest()
|
|
28
|
+
polls = []
|
|
29
|
+
vi.stubGlobal('fetch', vi.fn((input: string) => {
|
|
30
|
+
const url = new URL(String(input), 'http://localhost')
|
|
31
|
+
if (url.pathname !== '/api/connection') {
|
|
32
|
+
return Promise.resolve(new Response('{}', { status: 404 }))
|
|
33
|
+
}
|
|
34
|
+
return new Promise<Response>(resolve => {
|
|
35
|
+
polls.push(body => resolve(new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } })))
|
|
36
|
+
})
|
|
37
|
+
}))
|
|
38
|
+
|
|
39
|
+
container = document.createElement('div')
|
|
40
|
+
document.body.appendChild(container)
|
|
41
|
+
root = createRoot(container)
|
|
42
|
+
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
|
43
|
+
await act(async () => {
|
|
44
|
+
root.render(
|
|
45
|
+
<QueryClientProvider client={client}>
|
|
46
|
+
<ConnectionProvider>
|
|
47
|
+
<Probe />
|
|
48
|
+
</ConnectionProvider>
|
|
49
|
+
</QueryClientProvider>,
|
|
50
|
+
)
|
|
51
|
+
})
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
afterEach(() => {
|
|
55
|
+
act(() => root.unmount())
|
|
56
|
+
container.remove()
|
|
57
|
+
vi.restoreAllMocks()
|
|
58
|
+
vi.unstubAllGlobals()
|
|
59
|
+
vi.useRealTimers()
|
|
60
|
+
resetConnectionBindingForTest()
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it('keeps the connection SSE delivered when an older poll resolves after it', async () => {
|
|
64
|
+
await act(async () => {
|
|
65
|
+
await vi.advanceTimersByTimeAsync(10)
|
|
66
|
+
})
|
|
67
|
+
expect(polls).toHaveLength(1)
|
|
68
|
+
await act(async () => {
|
|
69
|
+
polls[0](statusA)
|
|
70
|
+
await vi.advanceTimersByTimeAsync(10)
|
|
71
|
+
})
|
|
72
|
+
expect(connectionHeaderValue()).toBe('n-1')
|
|
73
|
+
|
|
74
|
+
// The next poll leaves while A still serves...
|
|
75
|
+
await act(async () => {
|
|
76
|
+
await vi.advanceTimersByTimeAsync(31_000)
|
|
77
|
+
})
|
|
78
|
+
expect(polls).toHaveLength(2)
|
|
79
|
+
|
|
80
|
+
// ...then SSE reports B before that poll's answer arrives.
|
|
81
|
+
act(() => {
|
|
82
|
+
latest()?.updateFromSSE({ state: 'connected', context: 'B', connectionId: 'n-2' } as Parameters<NonNullable<ReturnType<typeof latest>>['updateFromSSE']>[0])
|
|
83
|
+
})
|
|
84
|
+
expect(connectionHeaderValue()).toBe('n-2')
|
|
85
|
+
|
|
86
|
+
await act(async () => {
|
|
87
|
+
polls[1](statusA)
|
|
88
|
+
await vi.advanceTimersByTimeAsync(10)
|
|
89
|
+
})
|
|
90
|
+
expect(latest()?.connection.context).toBe('B')
|
|
91
|
+
expect(connectionHeaderValue()).toBe('n-2')
|
|
92
|
+
})
|
|
@@ -3,10 +3,16 @@ import { act } from 'react'
|
|
|
3
3
|
import { createRoot, type Root } from 'react-dom/client'
|
|
4
4
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
5
5
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
6
|
+
import { useSwitchContext } from '../api/client'
|
|
7
|
+
import { useContextSwitchOutcome } from '../components/useContextSwitchFlow'
|
|
8
|
+
import { ToastProvider } from '../components/ui/Toast'
|
|
9
|
+
import { parseContextName } from '../utils/context-name'
|
|
10
|
+
import { ContextSwitchProvider, useContextSwitch } from './ContextSwitchContext'
|
|
6
11
|
import { ConnectionProvider, useConnection } from './ConnectionContext'
|
|
7
12
|
|
|
8
13
|
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
|
|
9
14
|
|
|
15
|
+
let client: QueryClient
|
|
10
16
|
let root: Root
|
|
11
17
|
let container: HTMLDivElement
|
|
12
18
|
let retries: number
|
|
@@ -58,7 +64,7 @@ beforeEach(async () => {
|
|
|
58
64
|
container = document.createElement('div')
|
|
59
65
|
document.body.appendChild(container)
|
|
60
66
|
root = createRoot(container)
|
|
61
|
-
|
|
67
|
+
client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
|
62
68
|
await act(async () => {
|
|
63
69
|
root.render(
|
|
64
70
|
<QueryClientProvider client={client}>
|
|
@@ -174,3 +180,170 @@ describe('ConnectionProvider auto-retry across contexts and background windows',
|
|
|
174
180
|
expect(retries).toBe(before + 1)
|
|
175
181
|
})
|
|
176
182
|
})
|
|
183
|
+
|
|
184
|
+
it.each(['failed', 'succeeded'] as const)('ends the switch overlay when a poll sees %s before acknowledgement recovery', async phase => {
|
|
185
|
+
const operation = {
|
|
186
|
+
id: `switch-${phase}`, target: 'staging', phase,
|
|
187
|
+
startedAt: '2026-10-30T14:02:00Z', syncTimeoutSeconds: 30, progress: '',
|
|
188
|
+
...(phase === 'failed' && { error: 'Credentials expired', errorType: 'auth' }),
|
|
189
|
+
}
|
|
190
|
+
let loseAcknowledgement!: () => void
|
|
191
|
+
vi.mocked(fetch).mockImplementation(async (_input, init) => {
|
|
192
|
+
if (init?.method === 'POST') {
|
|
193
|
+
return new Promise<Response>((_, reject) => { loseAcknowledgement = () => reject(new TypeError('Failed to fetch')) })
|
|
194
|
+
}
|
|
195
|
+
return jsonResponse(200, { state: 'connected', context: phase === 'succeeded' ? operation.target : 'prod', contextSwitch: operation })
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
const applyContextChange = vi.fn()
|
|
199
|
+
function SwitchProbe() {
|
|
200
|
+
const { startSwitch, isSwitching, failedSwitch } = useContextSwitch()
|
|
201
|
+
const mutation = useSwitchContext()
|
|
202
|
+
useContextSwitchOutcome(applyContextChange)
|
|
203
|
+
return <button onClick={() => {
|
|
204
|
+
startSwitch(parseContextName(operation.target))
|
|
205
|
+
mutation.mutate({ name: operation.target })
|
|
206
|
+
}}>{isSwitching ? 'Switching' : failedSwitch?.error ?? 'Idle'}</button>
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
act(() => root.render(
|
|
210
|
+
<QueryClientProvider client={client}>
|
|
211
|
+
<ConnectionProvider>
|
|
212
|
+
<ToastProvider>
|
|
213
|
+
<ContextSwitchProvider>
|
|
214
|
+
<Probe />
|
|
215
|
+
<SwitchProbe />
|
|
216
|
+
</ContextSwitchProvider>
|
|
217
|
+
</ToastProvider>
|
|
218
|
+
</ConnectionProvider>
|
|
219
|
+
</QueryClientProvider>,
|
|
220
|
+
))
|
|
221
|
+
await act(async () => container.querySelector('button')!.click())
|
|
222
|
+
await act(async () => { await client.refetchQueries({ queryKey: ['connection-status'] }) })
|
|
223
|
+
await advance(10)
|
|
224
|
+
expect(latest()?.contextSwitch).toEqual(operation)
|
|
225
|
+
expect(container.textContent).toBe('Switching')
|
|
226
|
+
expect(applyContextChange).not.toHaveBeenCalled()
|
|
227
|
+
|
|
228
|
+
await act(async () => loseAcknowledgement())
|
|
229
|
+
await advance(10)
|
|
230
|
+
expect(container.textContent).toBe(phase === 'failed' ? 'Credentials expired' : 'Idle')
|
|
231
|
+
if (phase === 'succeeded') expect(applyContextChange).toHaveBeenCalledExactlyOnceWith(operation.target, operation.id)
|
|
232
|
+
})
|
|
233
|
+
|
|
234
|
+
it('does not replay a dismissed switch failure when a lost acknowledgement recovers late', async () => {
|
|
235
|
+
const failed = {
|
|
236
|
+
id: 'switch-dismissed', target: 'staging', phase: 'failed' as const,
|
|
237
|
+
startedAt: '2026-10-30T14:02:00Z', syncTimeoutSeconds: 30, progress: '',
|
|
238
|
+
error: 'Credentials expired', errorType: 'auth',
|
|
239
|
+
}
|
|
240
|
+
let phase: 'preflight' | 'failed' = 'preflight'
|
|
241
|
+
let loseAcknowledgement!: () => void
|
|
242
|
+
vi.mocked(fetch).mockImplementation(async (_input, init) => {
|
|
243
|
+
if (init?.method === 'POST') {
|
|
244
|
+
return new Promise<Response>((_, reject) => { loseAcknowledgement = () => reject(new TypeError('Failed to fetch')) })
|
|
245
|
+
}
|
|
246
|
+
const contextSwitch = phase === 'failed' ? failed : { ...failed, phase, error: undefined, errorType: undefined }
|
|
247
|
+
return jsonResponse(200, { state: 'connected', context: 'prod', contextSwitch })
|
|
248
|
+
})
|
|
249
|
+
|
|
250
|
+
function SwitchProbe() {
|
|
251
|
+
const { startSwitch, failedSwitch, setFailedSwitch } = useContextSwitch()
|
|
252
|
+
const mutation = useSwitchContext()
|
|
253
|
+
useContextSwitchOutcome(vi.fn())
|
|
254
|
+
return (
|
|
255
|
+
<>
|
|
256
|
+
<button id="start" onClick={() => { startSwitch(parseContextName(failed.target)); mutation.mutate({ name: failed.target }) }} />
|
|
257
|
+
<button id="dismiss" onClick={() => setFailedSwitch(null)} />
|
|
258
|
+
<span id="failure">{failedSwitch?.error ?? 'none'}</span>
|
|
259
|
+
</>
|
|
260
|
+
)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
act(() => root.render(
|
|
264
|
+
<QueryClientProvider client={client}>
|
|
265
|
+
<ConnectionProvider>
|
|
266
|
+
<ToastProvider>
|
|
267
|
+
<ContextSwitchProvider>
|
|
268
|
+
<Probe />
|
|
269
|
+
<SwitchProbe />
|
|
270
|
+
</ContextSwitchProvider>
|
|
271
|
+
</ToastProvider>
|
|
272
|
+
</ConnectionProvider>
|
|
273
|
+
</QueryClientProvider>,
|
|
274
|
+
))
|
|
275
|
+
await act(async () => (container.querySelector('#start') as HTMLButtonElement).click())
|
|
276
|
+
await act(async () => { await client.refetchQueries({ queryKey: ['connection-status'] }) })
|
|
277
|
+
await advance(10)
|
|
278
|
+
phase = 'failed'
|
|
279
|
+
await act(async () => { await client.refetchQueries({ queryKey: ['connection-status'] }) })
|
|
280
|
+
await advance(10)
|
|
281
|
+
expect(container.querySelector('#failure')!.textContent).toBe('Credentials expired')
|
|
282
|
+
|
|
283
|
+
await act(async () => (container.querySelector('#dismiss') as HTMLButtonElement).click())
|
|
284
|
+
expect(container.querySelector('#failure')!.textContent).toBe('none')
|
|
285
|
+
await act(async () => loseAcknowledgement())
|
|
286
|
+
await act(async () => { await client.refetchQueries({ queryKey: ['connection-status'] }) })
|
|
287
|
+
await advance(10)
|
|
288
|
+
expect(container.querySelector('#failure')!.textContent).toBe('none')
|
|
289
|
+
})
|
|
290
|
+
|
|
291
|
+
it('a delayed acknowledgement does not reopen a switch whose failure was already shown', async () => {
|
|
292
|
+
const failed = {
|
|
293
|
+
id: 'switch-late-ack', target: 'staging', phase: 'failed' as const,
|
|
294
|
+
startedAt: '2026-10-30T14:02:00Z', syncTimeoutSeconds: 30, progress: '',
|
|
295
|
+
error: 'Credentials expired', errorType: 'auth',
|
|
296
|
+
}
|
|
297
|
+
const preflight = { ...failed, phase: 'preflight' as const, error: undefined, errorType: undefined }
|
|
298
|
+
let phase: 'preflight' | 'failed' = 'preflight'
|
|
299
|
+
let stallPolls = false
|
|
300
|
+
let acknowledge!: () => void
|
|
301
|
+
vi.mocked(fetch).mockImplementation(async (_input, init) => {
|
|
302
|
+
if (init?.method === 'POST') {
|
|
303
|
+
return new Promise<Response>(resolve => { acknowledge = () => resolve(jsonResponse(202, preflight)) })
|
|
304
|
+
}
|
|
305
|
+
if (stallPolls) return new Promise<Response>(() => {})
|
|
306
|
+
return jsonResponse(200, { state: 'connected', context: 'prod', contextSwitch: phase === 'failed' ? failed : preflight })
|
|
307
|
+
})
|
|
308
|
+
|
|
309
|
+
function SwitchProbe() {
|
|
310
|
+
const { startSwitch, failedSwitch, setFailedSwitch } = useContextSwitch()
|
|
311
|
+
const mutation = useSwitchContext()
|
|
312
|
+
useContextSwitchOutcome(vi.fn())
|
|
313
|
+
return (
|
|
314
|
+
<>
|
|
315
|
+
<button id="start" onClick={() => { startSwitch(parseContextName(failed.target)); mutation.mutate({ name: failed.target }) }} />
|
|
316
|
+
<button id="dismiss" onClick={() => setFailedSwitch(null)} />
|
|
317
|
+
<span id="failure">{failedSwitch?.error ?? 'none'}</span>
|
|
318
|
+
</>
|
|
319
|
+
)
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
act(() => root.render(
|
|
323
|
+
<QueryClientProvider client={client}>
|
|
324
|
+
<ConnectionProvider>
|
|
325
|
+
<ToastProvider>
|
|
326
|
+
<ContextSwitchProvider>
|
|
327
|
+
<Probe />
|
|
328
|
+
<SwitchProbe />
|
|
329
|
+
</ContextSwitchProvider>
|
|
330
|
+
</ToastProvider>
|
|
331
|
+
</ConnectionProvider>
|
|
332
|
+
</QueryClientProvider>,
|
|
333
|
+
))
|
|
334
|
+
await act(async () => (container.querySelector('#start') as HTMLButtonElement).click())
|
|
335
|
+
await act(async () => { await client.refetchQueries({ queryKey: ['connection-status'] }) })
|
|
336
|
+
await advance(10)
|
|
337
|
+
phase = 'failed'
|
|
338
|
+
await act(async () => { await client.refetchQueries({ queryKey: ['connection-status'] }) })
|
|
339
|
+
await advance(10)
|
|
340
|
+
expect(container.querySelector('#failure')!.textContent).toBe('Credentials expired')
|
|
341
|
+
await act(async () => (container.querySelector('#dismiss') as HTMLButtonElement).click())
|
|
342
|
+
|
|
343
|
+
stallPolls = true
|
|
344
|
+
await act(async () => acknowledge())
|
|
345
|
+
await advance(10)
|
|
346
|
+
const status = client.getQueryData<{ contextSwitch?: { phase: string } }>(['connection-status'])
|
|
347
|
+
expect(status?.contextSwitch?.phase).toBe('failed')
|
|
348
|
+
expect(container.querySelector('#failure')!.textContent).toBe('none')
|
|
349
|
+
})
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { createContext, useContext, useState, useCallback, useRef, ReactNode } from 'react'
|
|
2
|
+
import { parseContextName } from '../utils/context-name'
|
|
3
|
+
import { useConnection } from './ConnectionContext'
|
|
4
|
+
import { switchInProgress } from '../api/contextSwitch'
|
|
2
5
|
import type { SelectedResource } from '../types'
|
|
3
6
|
|
|
4
7
|
export interface ParsedContextInfo {
|
|
@@ -20,6 +23,8 @@ export interface FailedSwitch {
|
|
|
20
23
|
|
|
21
24
|
interface ContextSwitchState {
|
|
22
25
|
isSwitching: boolean
|
|
26
|
+
dismissed: boolean
|
|
27
|
+
setDismissed: (value: boolean) => void
|
|
23
28
|
failedSwitch: FailedSwitch | null
|
|
24
29
|
setFailedSwitch: (failed: FailedSwitch | null) => void
|
|
25
30
|
targetContext: ParsedContextInfo | null
|
|
@@ -37,6 +42,9 @@ interface ContextSwitchState {
|
|
|
37
42
|
const ContextSwitchContext = createContext<ContextSwitchState | null>(null)
|
|
38
43
|
|
|
39
44
|
export function ContextSwitchProvider({ children }: { children: ReactNode }) {
|
|
45
|
+
const { contextSwitch } = useConnection()
|
|
46
|
+
const tracking = switchInProgress(contextSwitch) ? contextSwitch : undefined
|
|
47
|
+
const [dismissedId, setDismissedId] = useState<string>()
|
|
40
48
|
const [isSwitching, setIsSwitching] = useState(false)
|
|
41
49
|
const [targetContext, setTargetContext] = useState<ParsedContextInfo | null>(null)
|
|
42
50
|
const [progressMessage, setProgressMessage] = useState<string | null>(null)
|
|
@@ -70,7 +78,13 @@ export function ContextSwitchProvider({ children }: { children: ReactNode }) {
|
|
|
70
78
|
}, [])
|
|
71
79
|
|
|
72
80
|
return (
|
|
73
|
-
<ContextSwitchContext.Provider value={{
|
|
81
|
+
<ContextSwitchContext.Provider value={{
|
|
82
|
+
isSwitching: isSwitching || !!tracking,
|
|
83
|
+
dismissed: !!tracking && dismissedId === tracking.id,
|
|
84
|
+
setDismissed: value => setDismissedId(value ? tracking?.id : undefined),
|
|
85
|
+
failedSwitch, setFailedSwitch,
|
|
86
|
+
targetContext: tracking ? parseContextName(tracking.target) : targetContext,
|
|
87
|
+
progressMessage: tracking?.progress || progressMessage, startSwitch, updateProgress, endSwitch, setOpenAfterSwitch, takeOpenAfterSwitch }}>
|
|
74
88
|
{children}
|
|
75
89
|
</ContextSwitchContext.Provider>
|
|
76
90
|
)
|
|
@@ -4,14 +4,16 @@ import type { ReactNode } from 'react';
|
|
|
4
4
|
/**
|
|
5
5
|
* Per-cluster destinations an embedded host can take over with its own
|
|
6
6
|
* fleet-scoped pages. See `fleetTakeoverHref`. 'issues' | 'gitops' | 'checks'
|
|
7
|
-
* are also Radar view names
|
|
7
|
+
* are also Radar view names. 'rightsizing' takes over /cost/rightsizing; 'certs' is
|
|
8
8
|
* card-only (Radar has no certs view).
|
|
9
9
|
*/
|
|
10
|
-
export type FleetTakeoverTarget = 'issues' | 'gitops' | 'checks' | 'certs';
|
|
10
|
+
export type FleetTakeoverTarget = 'issues' | 'gitops' | 'checks' | 'certs' | 'rightsizing';
|
|
11
11
|
|
|
12
12
|
export interface NavCustomization {
|
|
13
13
|
/** Radar Hub owns all chrome; Radar renders only the active view. */
|
|
14
14
|
embedded?: boolean;
|
|
15
|
+
/** The host's metrics status endpoint explicitly identifies the rightsizing provider. */
|
|
16
|
+
rightsizingProviderStatus?: boolean;
|
|
15
17
|
/**
|
|
16
18
|
* When set, a "Compare across clusters" option is added to the Compare
|
|
17
19
|
* button in resource action bars. The host returns the URL that should
|
|
@@ -38,6 +40,7 @@ export interface NavCustomization {
|
|
|
38
40
|
* - 'gitops' → the GitOps controllers card
|
|
39
41
|
* - 'checks' → the Cluster Audit card (and any route to /audit)
|
|
40
42
|
* - 'certs' → the Certificate Health card
|
|
43
|
+
* - 'rightsizing' → the workload scan; the host receives its router search to retain scope
|
|
41
44
|
*
|
|
42
45
|
* View-shaped targets (issues / gitops / checks) are honored for every entry:
|
|
43
46
|
* in-app nav (Home cards, ⌘K, "view all") hands straight to the host from
|
|
@@ -48,7 +51,7 @@ export interface NavCustomization {
|
|
|
48
51
|
* the card consults it. `onHostNavigate` is optional — without it everything
|
|
49
52
|
* falls back to `window.location` (a hard reload).
|
|
50
53
|
*/
|
|
51
|
-
fleetTakeoverHref?: (target: FleetTakeoverTarget) => string | undefined;
|
|
54
|
+
fleetTakeoverHref?: (target: FleetTakeoverTarget, search?: string) => string | undefined;
|
|
52
55
|
/**
|
|
53
56
|
* Optional smooth navigator for host-owned URLs. When the host takes a
|
|
54
57
|
* destination over (`fleetTakeoverHref`, `crossClusterCompareHref`), Radar
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { act, createRef, useImperativeHandle } from 'react'
|
|
3
|
+
import { createRoot, type Root } from 'react-dom/client'
|
|
4
|
+
import { afterEach, beforeEach, expect, test, vi } from 'vitest'
|
|
5
|
+
import { useEventSource } from './useEventSource'
|
|
6
|
+
|
|
7
|
+
class TestStream extends EventTarget {
|
|
8
|
+
static opened: TestStream[] = []
|
|
9
|
+
onopen?: () => void
|
|
10
|
+
onerror?: () => void
|
|
11
|
+
close = vi.fn()
|
|
12
|
+
constructor() {
|
|
13
|
+
super()
|
|
14
|
+
TestStream.opened.push(this)
|
|
15
|
+
}
|
|
16
|
+
send(type: string, data: unknown) {
|
|
17
|
+
this.dispatchEvent(new MessageEvent(type, { data: JSON.stringify(data) }))
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let root: Root
|
|
22
|
+
const hook = createRef<ReturnType<typeof useEventSource>>()
|
|
23
|
+
const changed = vi.fn()
|
|
24
|
+
const complete = vi.fn()
|
|
25
|
+
const eventReceived = vi.fn()
|
|
26
|
+
function Probe() {
|
|
27
|
+
const result = useEventSource([], 'resources', { onContextChanged: changed, onContextSwitchComplete: complete, onK8sEvent: eventReceived })
|
|
28
|
+
useImperativeHandle(hook, () => result, [result])
|
|
29
|
+
return null
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
beforeEach(() => {
|
|
33
|
+
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
|
|
34
|
+
vi.stubGlobal('EventSource', TestStream)
|
|
35
|
+
TestStream.opened = []
|
|
36
|
+
vi.clearAllMocks()
|
|
37
|
+
root = createRoot(document.createElement('div'))
|
|
38
|
+
act(() => root.render(<Probe />))
|
|
39
|
+
})
|
|
40
|
+
afterEach(() => {
|
|
41
|
+
act(() => root.unmount())
|
|
42
|
+
vi.unstubAllGlobals()
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
test('polling a completed switch discards old queued frames until the new stream delivers topology', () => {
|
|
46
|
+
const old = TestStream.opened[0]
|
|
47
|
+
act(() => old.send('topology', { nodes: [{ id: 'source' }] }))
|
|
48
|
+
expect(hook.current!.topology?.nodes[0].id).toBe('source')
|
|
49
|
+
act(() => old.send('topology', { nodes: [{ id: 'pending-source' }] }))
|
|
50
|
+
act(() => hook.current!.applyContextChange('target', 'op'))
|
|
51
|
+
expect(old.close).toHaveBeenCalledOnce()
|
|
52
|
+
const fresh = TestStream.opened[1]
|
|
53
|
+
act(() => {
|
|
54
|
+
old.onopen?.()
|
|
55
|
+
old.onerror?.()
|
|
56
|
+
old.send('k8s_event', { name: 'source-event' })
|
|
57
|
+
old.send('topology', { nodes: [{ id: 'queued-source' }] })
|
|
58
|
+
old.send('context_changed', { context: 'target', switchId: 'op' })
|
|
59
|
+
})
|
|
60
|
+
expect(hook.current!.connecting).toBe(true)
|
|
61
|
+
expect(hook.current!.topology).toBeNull()
|
|
62
|
+
expect(hook.current!.events).toEqual([])
|
|
63
|
+
expect(eventReceived).not.toHaveBeenCalled()
|
|
64
|
+
expect(complete).not.toHaveBeenCalled()
|
|
65
|
+
act(() => {
|
|
66
|
+
fresh.send('context_changed', { context: 'target', switchId: 'op' })
|
|
67
|
+
fresh.send('topology', { nodes: [{ id: 'target' }] })
|
|
68
|
+
})
|
|
69
|
+
expect(changed).toHaveBeenCalledOnce()
|
|
70
|
+
expect(complete).toHaveBeenCalledOnce()
|
|
71
|
+
expect(hook.current!.topology?.nodes[0].id).toBe('target')
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
test('an ordered stream completion keeps its target topology when the matching poll arrives', () => {
|
|
75
|
+
const stream = TestStream.opened[0]
|
|
76
|
+
act(() => {
|
|
77
|
+
stream.send('context_changed', { context: 'target', switchId: 'op' })
|
|
78
|
+
stream.send('topology', { nodes: [{ id: 'target' }] })
|
|
79
|
+
hook.current!.applyContextChange('target', 'op')
|
|
80
|
+
})
|
|
81
|
+
expect(TestStream.opened).toHaveLength(1)
|
|
82
|
+
expect(changed).toHaveBeenCalledOnce()
|
|
83
|
+
expect(complete).toHaveBeenCalledOnce()
|
|
84
|
+
expect(hook.current!.topology?.nodes[0].id).toBe('target')
|
|
85
|
+
})
|