@skyhook-io/radar-app 1.22.0 → 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.
- package/package.json +1 -1
- package/src/App.tsx +2 -1
- package/src/api/client.ts +12 -0
- package/src/api/cnpg-history.ts +3 -3
- package/src/api/cnpg-storage.ts +3 -3
- package/src/api/diagnose.test.ts +34 -0
- package/src/api/diagnose.ts +17 -4
- package/src/api/radarFeatures.test.ts +13 -1
- package/src/api/radarFeatures.ts +2 -0
- package/src/api/resourceActions.test.ts +829 -0
- package/src/api/resourceActions.ts +584 -0
- package/src/api/resourceActions.ui.test.tsx +1882 -0
- package/src/api/reviewedActionMutation.ts +56 -28
- package/src/api/substrateHealth.ts +2 -3
- package/src/api/traffic.ts +13 -5
- package/src/api/workloadMetrics.test.ts +11 -2
- package/src/api/workloadMetrics.ts +2 -2
- package/src/components/diagnose/AnalysisStory.test.tsx +12 -0
- package/src/components/diagnose/DiagnoseContext.question.test.tsx +34 -1
- package/src/components/diagnose/DiagnoseContext.tsx +28 -3
- package/src/components/diagnose/DiagnoseSurface.tsx +5 -4
- package/src/components/diagnose/Home.tsx +3 -0
- package/src/components/diagnose/InvestigationEvidencePane.test.tsx +61 -0
- package/src/components/diagnose/InvestigationView.followupFailure.test.tsx +122 -0
- package/src/components/diagnose/InvestigationView.tsx +10 -2
- package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +1 -1
- package/src/components/diagnose/LocalDiagnoseAction.tsx +2 -2
- package/src/components/diagnose/QuestionComposer.test.tsx +16 -2
- package/src/components/diagnose/QuestionComposer.tsx +13 -8
- package/src/components/diagnose/diagnoseEvidenceTypes.ts +47 -8
- package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +153 -0
- package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +9 -13
- package/src/components/diagnose/investigationEvidence/adapters/issues.ts +21 -5
- package/src/components/diagnose/investigationEvidence/bodies/network.tsx +63 -26
- package/src/components/diagnose/launch.ts +1 -1
- package/src/components/dock/PodDebugSession.test.tsx +66 -0
- package/src/components/dock/PodDebugSession.tsx +3 -1
- package/src/components/dock/TerminalTab.test.tsx +43 -3
- package/src/components/dock/TerminalTab.tsx +10 -1
- package/src/components/helm/HelmReleaseDrawer.tsx +1 -1
- package/src/components/helm/InstallWizard.tsx +1 -1
- package/src/components/home/mcpToolCatalog.ts +1 -1
- package/src/components/resources/PodEvictAction.test.tsx +951 -0
- package/src/components/resources/PodEvictAction.tsx +167 -0
- package/src/components/resources/ResourcesView.tsx +3 -0
- package/src/components/resources/renderers/WorkloadRenderer.tsx +3 -0
- package/src/components/settings/LocalConnectionSettings.tsx +4 -4
- package/src/components/settings/SettingsDialog.tsx +23 -18
- package/src/components/settings/integrationQueries.test.ts +98 -0
- package/src/components/settings/integrationQueries.ts +36 -0
- package/src/components/traffic/TrafficView.reconnect.test.tsx +229 -0
- package/src/components/traffic/TrafficView.tsx +91 -35
- package/src/components/ui/Markdown.test.tsx +37 -0
- package/src/components/ui/Markdown.tsx +15 -2
- package/src/components/useContextSwitchFlow.test.tsx +27 -2
- package/src/components/useContextSwitchFlow.tsx +20 -22
- package/src/components/workload/WorkloadView.tsx +16 -3
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
import { useCallback, useMemo, useSyncExternalStore } from 'react'
|
|
2
|
+
import { useQueryClient, type QueryClient } from '@tanstack/react-query'
|
|
3
|
+
import {
|
|
4
|
+
RESOURCE_ACTION_IDS,
|
|
5
|
+
buildResourceActionTarget,
|
|
6
|
+
isConnectionChangedError,
|
|
7
|
+
isResourceActionDispatchUncertain,
|
|
8
|
+
parseResourceActionId,
|
|
9
|
+
readResourceActionError,
|
|
10
|
+
requiresReapproval,
|
|
11
|
+
supportsReviewedAction,
|
|
12
|
+
type ResourceActionAccessRequest,
|
|
13
|
+
type ResourceActionAccessResponse,
|
|
14
|
+
type ResourceActionAccessVerdict,
|
|
15
|
+
type ResourceActionCallerIdentity,
|
|
16
|
+
type ResourceActionClientAdapter,
|
|
17
|
+
type ResourceActionDispatch,
|
|
18
|
+
type ResourceActionErrorEnvelope,
|
|
19
|
+
type ResourceActionExecuteResponse,
|
|
20
|
+
type ResourceActionExecuteResult,
|
|
21
|
+
type ResourceActionFromPreview,
|
|
22
|
+
type ResourceActionID,
|
|
23
|
+
type ResourceActionPreviewResponse,
|
|
24
|
+
type ResourceActionRetry,
|
|
25
|
+
type ResourceActionStage,
|
|
26
|
+
type ResourceActionTarget,
|
|
27
|
+
} from '@skyhook-io/k8s-ui'
|
|
28
|
+
import { ApiError, apiFetch, useCapabilities, useRadarFeature } from './client'
|
|
29
|
+
import { apiUrl, getApiBase } from './config'
|
|
30
|
+
import { connectionHeaderValue, connectionHeaders } from './connectionBinding'
|
|
31
|
+
import { markShownInline, readErrorResponse } from './httpErrors'
|
|
32
|
+
import { DEFAULT_OUTCOME_RECOVERY_INSTRUCTION, getReviewedActionOutcomeStore } from './reviewedActionMutation'
|
|
33
|
+
import { showApiError, showApiNotice, showApiSuccess } from '../components/ui/Toast'
|
|
34
|
+
|
|
35
|
+
export interface ResourceActionRequestOptions {
|
|
36
|
+
apiBase?: string
|
|
37
|
+
connectionId?: string
|
|
38
|
+
signal?: AbortSignal
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export class ResourceActionError extends ApiError {
|
|
42
|
+
readonly code: string
|
|
43
|
+
readonly retry: ResourceActionRetry
|
|
44
|
+
readonly dispatch: ResourceActionDispatch
|
|
45
|
+
readonly executionId?: string
|
|
46
|
+
readonly envelope?: ResourceActionErrorEnvelope
|
|
47
|
+
|
|
48
|
+
constructor(params: {
|
|
49
|
+
message: string
|
|
50
|
+
status: number
|
|
51
|
+
code: string
|
|
52
|
+
retry: ResourceActionRetry
|
|
53
|
+
dispatch: ResourceActionDispatch
|
|
54
|
+
executionId?: string
|
|
55
|
+
envelope?: ResourceActionErrorEnvelope
|
|
56
|
+
data?: Record<string, unknown>
|
|
57
|
+
unknownRoute?: boolean
|
|
58
|
+
}) {
|
|
59
|
+
super(params.message, params.status, params.data, { unknownRoute: params.unknownRoute })
|
|
60
|
+
this.name = 'ResourceActionError'
|
|
61
|
+
this.code = params.code
|
|
62
|
+
this.retry = params.retry
|
|
63
|
+
this.dispatch = params.dispatch
|
|
64
|
+
this.executionId = params.executionId
|
|
65
|
+
this.envelope = params.envelope
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function resourceActionPath(actionId: ResourceActionID, stage: ResourceActionStage): string {
|
|
70
|
+
const parsed = parseResourceActionId(actionId)
|
|
71
|
+
if (!parsed) throw new Error(`Invalid resource action ID: "${actionId}"`)
|
|
72
|
+
return `/resource-actions/${encodeURIComponent(parsed.group)}/${encodeURIComponent(parsed.kind)}/${encodeURIComponent(parsed.verb)}/${stage}`
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function createExecutionId(): string {
|
|
76
|
+
return typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
|
|
77
|
+
? crypto.randomUUID()
|
|
78
|
+
: `exec-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const VALID_RETRY = new Set<string>(['none', 'reapprove', 'later'])
|
|
82
|
+
const VALID_ACCESS = new Set<string>(['allowed', 'denied', 'unknown'])
|
|
83
|
+
|
|
84
|
+
function parseCallerIdentity(raw: unknown): ResourceActionCallerIdentity | null {
|
|
85
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
|
|
86
|
+
const obj = raw as Record<string, unknown>
|
|
87
|
+
if (typeof obj.user !== 'string' || !obj.user.trim()) return null
|
|
88
|
+
if (obj.groups !== undefined) {
|
|
89
|
+
if (!Array.isArray(obj.groups) || !obj.groups.every((g) => typeof g === 'string')) return null
|
|
90
|
+
return { user: obj.user, groups: [...obj.groups] }
|
|
91
|
+
}
|
|
92
|
+
return { user: obj.user }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function parseExecuteResponse(
|
|
96
|
+
status: number,
|
|
97
|
+
raw: unknown,
|
|
98
|
+
expectedExecutionId: string,
|
|
99
|
+
): ResourceActionExecuteResponse {
|
|
100
|
+
const invalid = () =>
|
|
101
|
+
new ResourceActionError({
|
|
102
|
+
message: 'Radar returned an unexpected execution response.',
|
|
103
|
+
status,
|
|
104
|
+
code: 'dispatch_unknown',
|
|
105
|
+
retry: 'none',
|
|
106
|
+
dispatch: 'unknown',
|
|
107
|
+
})
|
|
108
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw invalid()
|
|
109
|
+
const body = raw as Record<string, unknown>
|
|
110
|
+
if (typeof body.executionId !== 'string' || !expectedExecutionId || body.executionId !== expectedExecutionId) {
|
|
111
|
+
throw invalid()
|
|
112
|
+
}
|
|
113
|
+
let executedAs: ResourceActionCallerIdentity | undefined
|
|
114
|
+
if (body.executedAs !== undefined) {
|
|
115
|
+
const parsed = parseCallerIdentity(body.executedAs)
|
|
116
|
+
if (!parsed) throw invalid()
|
|
117
|
+
executedAs = parsed
|
|
118
|
+
}
|
|
119
|
+
if (status === 202 && body.outcome === 'accepted') {
|
|
120
|
+
if (body.effects !== undefined) throw invalid()
|
|
121
|
+
return { executionId: body.executionId, outcome: 'accepted', ...(executedAs ? { executedAs } : {}) }
|
|
122
|
+
}
|
|
123
|
+
if (status === 200 && (body.outcome === 'applied' || body.outcome === 'noop')) {
|
|
124
|
+
return { executionId: body.executionId, outcome: body.outcome, ...(executedAs ? { executedAs } : {}) }
|
|
125
|
+
}
|
|
126
|
+
throw invalid()
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function parseAccessResponse(status: number, raw: unknown): ResourceActionAccessResponse {
|
|
130
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
131
|
+
throw new ResourceActionError({
|
|
132
|
+
message: 'Radar returned an unexpected access response.',
|
|
133
|
+
status,
|
|
134
|
+
code: 'invalid_response',
|
|
135
|
+
retry: 'none',
|
|
136
|
+
dispatch: 'not_dispatched',
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
const access = (raw as Record<string, unknown>).access
|
|
140
|
+
if (typeof access !== 'string' || !VALID_ACCESS.has(access)) {
|
|
141
|
+
throw new ResourceActionError({
|
|
142
|
+
message: 'Radar returned an unexpected access verdict.',
|
|
143
|
+
status,
|
|
144
|
+
code: 'invalid_response',
|
|
145
|
+
retry: 'none',
|
|
146
|
+
dispatch: 'not_dispatched',
|
|
147
|
+
})
|
|
148
|
+
}
|
|
149
|
+
return { access: access as ResourceActionAccessVerdict }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function parsePreviewResponse(status: number, raw: unknown): ResourceActionPreviewResponse {
|
|
153
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
154
|
+
throw new ResourceActionError({
|
|
155
|
+
message: 'Radar returned an unexpected preview response.',
|
|
156
|
+
status,
|
|
157
|
+
code: 'invalid_response',
|
|
158
|
+
retry: 'none',
|
|
159
|
+
dispatch: 'not_dispatched',
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
const body = raw as Record<string, unknown>
|
|
163
|
+
const target = body.target as Record<string, unknown> | undefined
|
|
164
|
+
const fromPreview = body.fromPreview as Record<string, unknown> | undefined
|
|
165
|
+
if (!target || typeof target.uid !== 'string' || !fromPreview || typeof fromPreview.digest !== 'string') {
|
|
166
|
+
throw new ResourceActionError({
|
|
167
|
+
message: 'Radar returned an incomplete preview response.',
|
|
168
|
+
status,
|
|
169
|
+
code: 'invalid_response',
|
|
170
|
+
retry: 'none',
|
|
171
|
+
dispatch: 'not_dispatched',
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
return raw as ResourceActionPreviewResponse
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async function parseResourceActionErrorResponse(response: Response, stage: ResourceActionStage): Promise<ResourceActionError> {
|
|
178
|
+
const { body, unknownRoute } = await readErrorResponse(response)
|
|
179
|
+
const rawCode = typeof body.code === 'string' && body.code.trim() ? body.code : undefined
|
|
180
|
+
const rawRetry = typeof body.retry === 'string' ? body.retry : undefined
|
|
181
|
+
const rawDispatch = typeof body.dispatch === 'string' ? body.dispatch : undefined
|
|
182
|
+
const message =
|
|
183
|
+
(typeof body.message === 'string' && body.message) ||
|
|
184
|
+
(typeof body.error === 'string' && body.error) ||
|
|
185
|
+
`HTTP ${response.status}`
|
|
186
|
+
const executionId = typeof body.executionId === 'string' ? body.executionId : undefined
|
|
187
|
+
|
|
188
|
+
if (rawCode && rawRetry !== undefined && rawDispatch !== undefined) {
|
|
189
|
+
const dispatch: ResourceActionDispatch =
|
|
190
|
+
rawCode === 'dispatch_unknown' || rawDispatch !== 'not_dispatched' ? 'unknown' : 'not_dispatched'
|
|
191
|
+
const retry: ResourceActionRetry =
|
|
192
|
+
dispatch === 'not_dispatched' && VALID_RETRY.has(rawRetry) ? (rawRetry as ResourceActionRetry) : 'none'
|
|
193
|
+
const envelope: ResourceActionErrorEnvelope = {
|
|
194
|
+
code: rawCode,
|
|
195
|
+
message,
|
|
196
|
+
retry,
|
|
197
|
+
dispatch,
|
|
198
|
+
...(executionId ? { executionId } : {}),
|
|
199
|
+
}
|
|
200
|
+
return new ResourceActionError({ ...envelope, status: response.status, envelope, data: body, unknownRoute })
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const refusal = typeof body.error_code === 'string' ? body.error_code : undefined
|
|
204
|
+
const hasUncertainDispatch = rawDispatch !== undefined && rawDispatch !== 'not_dispatched'
|
|
205
|
+
const dispatch: ResourceActionDispatch =
|
|
206
|
+
hasUncertainDispatch ||
|
|
207
|
+
rawCode === 'dispatch_unknown' ||
|
|
208
|
+
(stage === 'execute' && (response.status >= 500 || response.status === 408))
|
|
209
|
+
? 'unknown'
|
|
210
|
+
: 'not_dispatched'
|
|
211
|
+
const code = rawCode ?? (dispatch === 'unknown' ? 'dispatch_unknown' : refusal ?? `http_${response.status}`)
|
|
212
|
+
return new ResourceActionError({ message, status: response.status, code, retry: 'none', dispatch, data: body, unknownRoute })
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async function sendResourceActionRequest<TResponse>(
|
|
216
|
+
path: string,
|
|
217
|
+
stage: ResourceActionStage,
|
|
218
|
+
body: unknown,
|
|
219
|
+
options?: ResourceActionRequestOptions,
|
|
220
|
+
expectedExecutionId?: string,
|
|
221
|
+
): Promise<TResponse> {
|
|
222
|
+
let response: Response
|
|
223
|
+
try {
|
|
224
|
+
response = await apiFetch(apiUrl(path, options?.apiBase ?? getApiBase()), {
|
|
225
|
+
method: 'POST',
|
|
226
|
+
headers: { 'Content-Type': 'application/json', ...connectionHeaders(options?.connectionId) },
|
|
227
|
+
body: JSON.stringify(body),
|
|
228
|
+
signal: options?.signal,
|
|
229
|
+
})
|
|
230
|
+
} catch (err) {
|
|
231
|
+
const detail = err instanceof Error && err.message ? err.message : 'Network error'
|
|
232
|
+
if (stage === 'execute') {
|
|
233
|
+
throw new ResourceActionError({
|
|
234
|
+
message: `${detail}. Radar could not confirm whether Kubernetes applied this action.`,
|
|
235
|
+
status: 503,
|
|
236
|
+
code: 'dispatch_unknown',
|
|
237
|
+
retry: 'none',
|
|
238
|
+
dispatch: 'unknown',
|
|
239
|
+
})
|
|
240
|
+
}
|
|
241
|
+
throw new ResourceActionError({
|
|
242
|
+
message: detail,
|
|
243
|
+
status: 503,
|
|
244
|
+
code: 'temporarily_unavailable',
|
|
245
|
+
retry: 'later',
|
|
246
|
+
dispatch: 'not_dispatched',
|
|
247
|
+
})
|
|
248
|
+
}
|
|
249
|
+
if (!response.ok) throw await parseResourceActionErrorResponse(response, stage)
|
|
250
|
+
let raw: unknown
|
|
251
|
+
try {
|
|
252
|
+
raw = await response.json()
|
|
253
|
+
} catch {
|
|
254
|
+
if (stage === 'execute') {
|
|
255
|
+
throw new ResourceActionError({
|
|
256
|
+
message: 'Radar returned an unreadable response after execution.',
|
|
257
|
+
status: response.status,
|
|
258
|
+
code: 'dispatch_unknown',
|
|
259
|
+
retry: 'none',
|
|
260
|
+
dispatch: 'unknown',
|
|
261
|
+
})
|
|
262
|
+
}
|
|
263
|
+
throw new ResourceActionError({
|
|
264
|
+
message: `Radar returned an unreadable ${stage} response.`,
|
|
265
|
+
status: response.status,
|
|
266
|
+
code: 'invalid_response',
|
|
267
|
+
retry: 'none',
|
|
268
|
+
dispatch: 'not_dispatched',
|
|
269
|
+
})
|
|
270
|
+
}
|
|
271
|
+
if (stage === 'execute') return parseExecuteResponse(response.status, raw, expectedExecutionId ?? '') as TResponse
|
|
272
|
+
if (stage === 'access') return parseAccessResponse(response.status, raw) as TResponse
|
|
273
|
+
return parsePreviewResponse(response.status, raw) as TResponse
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Exact resource-action access check (`POST /api/resource-actions/{group}/{kind}/{verb}/access`). */
|
|
277
|
+
export function checkResourceActionAccess(
|
|
278
|
+
actionId: ResourceActionID,
|
|
279
|
+
target: ResourceActionTarget,
|
|
280
|
+
options?: ResourceActionRequestOptions,
|
|
281
|
+
): Promise<ResourceActionAccessResponse> {
|
|
282
|
+
const payload: ResourceActionAccessRequest = {
|
|
283
|
+
target: buildResourceActionTarget(target),
|
|
284
|
+
}
|
|
285
|
+
return sendResourceActionRequest<ResourceActionAccessResponse>(resourceActionPath(actionId, 'access'), 'access', payload, options)
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export function previewResourceAction<P extends Record<string, unknown> = Record<string, unknown>>(
|
|
289
|
+
actionId: ResourceActionID,
|
|
290
|
+
request: { target: ResourceActionTarget; parameters?: P; actionVersion?: number },
|
|
291
|
+
options?: ResourceActionRequestOptions,
|
|
292
|
+
): Promise<ResourceActionPreviewResponse> {
|
|
293
|
+
const payload = {
|
|
294
|
+
target: buildResourceActionTarget(request.target),
|
|
295
|
+
parameters: request.parameters ?? {},
|
|
296
|
+
...(request.actionVersion !== undefined ? { actionVersion: request.actionVersion } : {}),
|
|
297
|
+
}
|
|
298
|
+
return sendResourceActionRequest<ResourceActionPreviewResponse>(resourceActionPath(actionId, 'preview'), 'preview', payload, options)
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export async function executeResourceAction<P extends Record<string, unknown> = Record<string, unknown>>(
|
|
302
|
+
actionId: ResourceActionID,
|
|
303
|
+
request: { target: ResourceActionTarget; parameters?: P; executionId: string; fromPreview: ResourceActionFromPreview },
|
|
304
|
+
options?: ResourceActionRequestOptions,
|
|
305
|
+
): Promise<ResourceActionExecuteResponse> {
|
|
306
|
+
const response = await sendResourceActionRequest<ResourceActionExecuteResponse>(
|
|
307
|
+
resourceActionPath(actionId, 'execute'),
|
|
308
|
+
'execute',
|
|
309
|
+
{
|
|
310
|
+
target: buildResourceActionTarget(request.target),
|
|
311
|
+
parameters: request.parameters ?? {},
|
|
312
|
+
executionId: request.executionId,
|
|
313
|
+
fromPreview: request.fromPreview,
|
|
314
|
+
},
|
|
315
|
+
options,
|
|
316
|
+
request.executionId,
|
|
317
|
+
)
|
|
318
|
+
if (actionId === RESOURCE_ACTION_IDS.podEvict && response.outcome !== 'accepted') {
|
|
319
|
+
throw new ResourceActionError({
|
|
320
|
+
message: 'Kubernetes did not confirm whether eviction was accepted.',
|
|
321
|
+
status: 200,
|
|
322
|
+
code: 'dispatch_unknown',
|
|
323
|
+
retry: 'none',
|
|
324
|
+
dispatch: 'unknown',
|
|
325
|
+
executionId: response.executionId,
|
|
326
|
+
})
|
|
327
|
+
}
|
|
328
|
+
return response
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function targetReplacedError(): ResourceActionError {
|
|
332
|
+
return new ResourceActionError({
|
|
333
|
+
message: 'A different object now has this name. Close and reselect it before trying again.',
|
|
334
|
+
status: 409,
|
|
335
|
+
code: 'target_replaced',
|
|
336
|
+
retry: 'none',
|
|
337
|
+
dispatch: 'not_dispatched',
|
|
338
|
+
})
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Executes a resource action from an approved preview. Verifies selected UID
|
|
343
|
+
* before dispatch, sends one execute request, refreshes preview for explicit
|
|
344
|
+
* reapproval on `retry: 'reapprove'`, and never auto-re-executes, retries
|
|
345
|
+
* after uncertain dispatch, or downgrades to a legacy write.
|
|
346
|
+
*/
|
|
347
|
+
export async function executeReviewedActionWithRecovery<P extends Record<string, unknown> = Record<string, unknown>>({
|
|
348
|
+
actionId,
|
|
349
|
+
target,
|
|
350
|
+
uid,
|
|
351
|
+
parameters,
|
|
352
|
+
preview,
|
|
353
|
+
options,
|
|
354
|
+
createId = createExecutionId,
|
|
355
|
+
}: {
|
|
356
|
+
actionId: ResourceActionID
|
|
357
|
+
target: ResourceActionTarget
|
|
358
|
+
uid?: string
|
|
359
|
+
parameters?: P
|
|
360
|
+
preview: ResourceActionPreviewResponse
|
|
361
|
+
options?: ResourceActionRequestOptions
|
|
362
|
+
createId?: () => string
|
|
363
|
+
}): Promise<ResourceActionExecuteResult> {
|
|
364
|
+
if (uid && preview.target.uid !== uid) {
|
|
365
|
+
throw targetReplacedError()
|
|
366
|
+
}
|
|
367
|
+
const expectedUid = uid || preview.target.uid
|
|
368
|
+
|
|
369
|
+
try {
|
|
370
|
+
const response = await executeResourceAction(
|
|
371
|
+
actionId,
|
|
372
|
+
{ target, parameters, executionId: createId(), fromPreview: preview.fromPreview },
|
|
373
|
+
options,
|
|
374
|
+
)
|
|
375
|
+
return { status: 'completed', response, preview }
|
|
376
|
+
} catch (err) {
|
|
377
|
+
if (requiresReapproval(err)) {
|
|
378
|
+
const reason = err instanceof Error ? err.message : 'The target changed before execution.'
|
|
379
|
+
let refreshed: ResourceActionPreviewResponse
|
|
380
|
+
try {
|
|
381
|
+
refreshed = await previewResourceAction(actionId, { target, parameters }, options)
|
|
382
|
+
} catch (refreshErr) {
|
|
383
|
+
if (isConnectionChangedError(refreshErr)) {
|
|
384
|
+
throw refreshErr
|
|
385
|
+
}
|
|
386
|
+
throw err
|
|
387
|
+
}
|
|
388
|
+
if (refreshed.target.uid !== expectedUid) {
|
|
389
|
+
throw targetReplacedError()
|
|
390
|
+
}
|
|
391
|
+
return { status: 'reapprove', preview: refreshed, reason }
|
|
392
|
+
}
|
|
393
|
+
throw err
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function invalidateQueriesForAction(queryClient: QueryClient, actionId: ResourceActionID, kind: string, target: ResourceActionTarget) {
|
|
398
|
+
const parsed = parseResourceActionId(actionId)
|
|
399
|
+
const namespace = target.namespace ?? ''
|
|
400
|
+
const name = target.name
|
|
401
|
+
const keys: unknown[][] =
|
|
402
|
+
parsed?.group === 'batch' && parsed.kind === 'CronJob'
|
|
403
|
+
? [
|
|
404
|
+
['resources', 'cronjobs'],
|
|
405
|
+
['resources', 'jobs'],
|
|
406
|
+
['resource', 'cronjobs', namespace, name],
|
|
407
|
+
['workload-runs', 'cronjobs', namespace, name],
|
|
408
|
+
['applications'],
|
|
409
|
+
['dashboard'],
|
|
410
|
+
['resource-counts'],
|
|
411
|
+
['topology'],
|
|
412
|
+
]
|
|
413
|
+
: [
|
|
414
|
+
['resources', kind],
|
|
415
|
+
['resource', kind, namespace, name],
|
|
416
|
+
...(parsed?.verb === 'rollback' ? [['workload-revisions', kind, namespace, name]] : []),
|
|
417
|
+
['topology'],
|
|
418
|
+
]
|
|
419
|
+
for (const queryKey of keys) queryClient.invalidateQueries({ queryKey })
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
const ACTION_SUCCESS_COPY: Record<string, { applied: string; noop?: string; accepted?: { title: string; detail?: string } }> = {
|
|
423
|
+
scale: { applied: 'Workload scaled', noop: 'Workload already at requested replicas' },
|
|
424
|
+
restart: { applied: 'Workload restarting', noop: 'Restart already requested' },
|
|
425
|
+
'Deployment/pause': { applied: 'Rollout paused', noop: 'Rollout already paused' },
|
|
426
|
+
'Deployment/resume': { applied: 'Rollout resumed', noop: 'Rollout already running' },
|
|
427
|
+
'Deployment/rollback': { applied: 'Rollback initiated', noop: 'Already at selected revision' },
|
|
428
|
+
'CronJob/trigger': { applied: 'CronJob triggered' },
|
|
429
|
+
'CronJob/suspend': { applied: 'CronJob suspended', noop: 'CronJob already suspended' },
|
|
430
|
+
'CronJob/resume': { applied: 'CronJob resumed', noop: 'CronJob already active' },
|
|
431
|
+
'Pod/evict': {
|
|
432
|
+
applied: 'Eviction accepted',
|
|
433
|
+
accepted: {
|
|
434
|
+
title: 'Eviction accepted',
|
|
435
|
+
detail: 'Kubernetes accepted the eviction request. Termination and controller follow-up happen separately.',
|
|
436
|
+
},
|
|
437
|
+
},
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function reportActionSuccess(actionId: ResourceActionID, response: ResourceActionExecuteResponse) {
|
|
441
|
+
const parsed = parseResourceActionId(actionId)
|
|
442
|
+
const copy =
|
|
443
|
+
(parsed ? ACTION_SUCCESS_COPY[`${parsed.kind}/${parsed.verb}`] ?? ACTION_SUCCESS_COPY[parsed.verb] : undefined) ??
|
|
444
|
+
{ applied: 'Action completed', noop: 'No change required' }
|
|
445
|
+
if (response.outcome === 'noop') showApiNotice(copy.noop ?? 'No change required', undefined, 'info')
|
|
446
|
+
else if (response.outcome === 'accepted') showApiSuccess(copy.accepted?.title ?? 'Action accepted', copy.accepted?.detail)
|
|
447
|
+
else showApiSuccess(copy.applied)
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
export function useResourceActionAdapter(): ResourceActionClientAdapter {
|
|
451
|
+
const queryClient = useQueryClient()
|
|
452
|
+
const { data: capabilities } = useCapabilities()
|
|
453
|
+
const { support, blockedReason } = useRadarFeature('resourceActions')
|
|
454
|
+
const apiBase = getApiBase()
|
|
455
|
+
const context = queryClient.getQueryData<{ context?: string }>(['connection-status'])?.context
|
|
456
|
+
const outcomes = getReviewedActionOutcomeStore(queryClient)
|
|
457
|
+
const outcomeVersion = useSyncExternalStore(outcomes.subscribe, outcomes.getVersion, () => 0)
|
|
458
|
+
|
|
459
|
+
const supportsAction = useCallback((actionId: ResourceActionID) => supportsReviewedAction(capabilities, actionId), [capabilities])
|
|
460
|
+
const getOutcomeError = useCallback(
|
|
461
|
+
(lockKey: string) => outcomes.get(lockKey).error,
|
|
462
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
463
|
+
[outcomes, outcomeVersion],
|
|
464
|
+
)
|
|
465
|
+
const getConnectionId = useCallback(() => connectionHeaderValue(apiBase), [apiBase])
|
|
466
|
+
|
|
467
|
+
const preview = useCallback<ResourceActionClientAdapter['preview']>(
|
|
468
|
+
(params) => {
|
|
469
|
+
if (support !== 'supported') {
|
|
470
|
+
return Promise.reject(
|
|
471
|
+
new ResourceActionError({
|
|
472
|
+
message: blockedReason || 'Resource action preview is not supported on this Radar.',
|
|
473
|
+
status: 409,
|
|
474
|
+
code: 'action_not_applicable',
|
|
475
|
+
retry: 'none',
|
|
476
|
+
dispatch: 'not_dispatched',
|
|
477
|
+
}),
|
|
478
|
+
)
|
|
479
|
+
}
|
|
480
|
+
const connectionId = 'connectionId' in params ? params.connectionId : connectionHeaderValue(apiBase)
|
|
481
|
+
return previewResourceAction(params.actionId, { target: params.target, parameters: params.parameters }, { apiBase, connectionId })
|
|
482
|
+
},
|
|
483
|
+
[apiBase, blockedReason, support],
|
|
484
|
+
)
|
|
485
|
+
|
|
486
|
+
const execute = useCallback<ResourceActionClientAdapter['execute']>(
|
|
487
|
+
async (params) => {
|
|
488
|
+
const { actionId, kind, target, uid, parameters, preview: approvedPreview, lockKey, suppressToast } = params
|
|
489
|
+
const connectionId = 'connectionId' in params ? params.connectionId : connectionHeaderValue(apiBase)
|
|
490
|
+
const previous = outcomes.get(lockKey)
|
|
491
|
+
if (previous.error) throw previous.error
|
|
492
|
+
if (previous.pending) {
|
|
493
|
+
throw new ResourceActionError({
|
|
494
|
+
message: 'A write to this target is still in progress. Wait for its result.',
|
|
495
|
+
status: 409,
|
|
496
|
+
code: 'execution_conflict',
|
|
497
|
+
retry: 'none',
|
|
498
|
+
dispatch: 'not_dispatched',
|
|
499
|
+
})
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
outcomes.set(lockKey, { pending: true, error: null })
|
|
503
|
+
let retainedError: Error | null = null
|
|
504
|
+
try {
|
|
505
|
+
const result = await executeReviewedActionWithRecovery({
|
|
506
|
+
actionId,
|
|
507
|
+
target,
|
|
508
|
+
uid,
|
|
509
|
+
parameters,
|
|
510
|
+
preview: approvedPreview,
|
|
511
|
+
options: { apiBase, connectionId },
|
|
512
|
+
})
|
|
513
|
+
if (result.status === 'completed' && result.response) {
|
|
514
|
+
invalidateQueriesForAction(queryClient, actionId, kind, target)
|
|
515
|
+
if (!suppressToast) reportActionSuccess(actionId, result.response)
|
|
516
|
+
}
|
|
517
|
+
return result
|
|
518
|
+
} catch (err) {
|
|
519
|
+
const error = err instanceof Error ? err : new Error(String(err))
|
|
520
|
+
markShownInline(error)
|
|
521
|
+
if (isResourceActionDispatchUncertain(error)) {
|
|
522
|
+
const message = error.message.includes(DEFAULT_OUTCOME_RECOVERY_INSTRUCTION)
|
|
523
|
+
? error.message
|
|
524
|
+
: [error.message, DEFAULT_OUTCOME_RECOVERY_INSTRUCTION].filter(Boolean).join(' ')
|
|
525
|
+
retainedError =
|
|
526
|
+
error instanceof ResourceActionError
|
|
527
|
+
? new ResourceActionError({
|
|
528
|
+
message,
|
|
529
|
+
status: error.status,
|
|
530
|
+
code: error.code,
|
|
531
|
+
retry: error.retry,
|
|
532
|
+
dispatch: error.dispatch,
|
|
533
|
+
executionId: error.executionId,
|
|
534
|
+
envelope: error.envelope,
|
|
535
|
+
data: error.data,
|
|
536
|
+
unknownRoute: error.unknownRoute,
|
|
537
|
+
})
|
|
538
|
+
: Object.assign(new Error(message), {
|
|
539
|
+
code: 'dispatch_unknown',
|
|
540
|
+
retry: 'none',
|
|
541
|
+
dispatch: 'unknown',
|
|
542
|
+
})
|
|
543
|
+
markShownInline(retainedError)
|
|
544
|
+
throw retainedError
|
|
545
|
+
}
|
|
546
|
+
const info = readResourceActionError(error)
|
|
547
|
+
if (info?.code === 'target_replaced' || info?.code === 'target_not_found' || info?.status === 404) {
|
|
548
|
+
invalidateQueriesForAction(queryClient, actionId, kind, target)
|
|
549
|
+
}
|
|
550
|
+
throw error
|
|
551
|
+
} finally {
|
|
552
|
+
outcomes.set(lockKey, { pending: false, error: retainedError })
|
|
553
|
+
}
|
|
554
|
+
},
|
|
555
|
+
[apiBase, outcomes, queryClient],
|
|
556
|
+
)
|
|
557
|
+
|
|
558
|
+
const invalidateBulk = useCallback(() => {
|
|
559
|
+
queryClient.invalidateQueries({ queryKey: ['resources'] })
|
|
560
|
+
queryClient.invalidateQueries({ queryKey: ['topology'] })
|
|
561
|
+
}, [queryClient])
|
|
562
|
+
|
|
563
|
+
const reportBulkResult = useCallback<NonNullable<ResourceActionClientAdapter['reportBulkResult']>>(
|
|
564
|
+
({ action, requested, succeeded, noopCount, failedMessages, unknownCount }) => {
|
|
565
|
+
const verbPast = action === 'restart' ? 'Restarted' : 'Scaled'
|
|
566
|
+
if (failedMessages.length > 0 || unknownCount > 0) {
|
|
567
|
+
const suffix = unknownCount > 0 ? ` (${unknownCount} uncertain — check cluster state before retrying)` : ''
|
|
568
|
+
showApiError(`${verbPast} ${succeeded} of ${requested} workloads${suffix}`, failedMessages.join('\n'))
|
|
569
|
+
return
|
|
570
|
+
}
|
|
571
|
+
if (action === 'scale' && noopCount === requested && requested > 0) {
|
|
572
|
+
showApiNotice('Workloads already at requested replicas', undefined, 'info')
|
|
573
|
+
return
|
|
574
|
+
}
|
|
575
|
+
showApiSuccess(action === 'restart' ? 'Workloads restarting' : 'Workloads scaled')
|
|
576
|
+
},
|
|
577
|
+
[],
|
|
578
|
+
)
|
|
579
|
+
|
|
580
|
+
return useMemo(
|
|
581
|
+
() => ({ context, getConnectionId, support, blockedReason, supportsAction, getOutcomeError, preview, execute, invalidateBulk, reportBulkResult }),
|
|
582
|
+
[blockedReason, context, execute, getConnectionId, getOutcomeError, invalidateBulk, preview, reportBulkResult, support, supportsAction],
|
|
583
|
+
)
|
|
584
|
+
}
|