| 293 | } |
| 294 | |
| 295 | export function useCancelExecution(workspaceId: string) { |
| 296 | const queryClient = useQueryClient() |
| 297 | return useMutation({ |
| 298 | mutationFn: async ({ |
| 299 | workflowId, |
| 300 | executionId, |
| 301 | }: { |
| 302 | workflowId: string |
| 303 | executionId: string |
| 304 | }) => { |
| 305 | const data = await requestJson(cancelWorkflowExecutionContract, { |
| 306 | params: { id: workflowId, executionId }, |
| 307 | }) |
| 308 | if (!data.success) throw new Error('Failed to cancel run') |
| 309 | return data |
| 310 | }, |
| 311 | onMutate: async ({ executionId }) => { |
| 312 | await queryClient.cancelQueries({ queryKey: logKeys.lists() }) |
| 313 | |
| 314 | const previousQueries = queryClient.getQueriesData<InfiniteData<LogsPage>>({ |
| 315 | queryKey: logKeys.lists(), |
| 316 | }) |
| 317 | |
| 318 | let affectedLogId: string | null = null |
| 319 | queryClient.setQueriesData<InfiniteData<LogsPage>>({ queryKey: logKeys.lists() }, (old) => { |
| 320 | if (!old) return old |
| 321 | return { |
| 322 | ...old, |
| 323 | pages: old.pages.map((page) => ({ |
| 324 | ...page, |
| 325 | logs: page.logs.map((log) => { |
| 326 | if (log.executionId !== executionId) return log |
| 327 | affectedLogId = log.id |
| 328 | return { ...log, status: 'cancelling' } |
| 329 | }), |
| 330 | })), |
| 331 | } |
| 332 | }) |
| 333 | |
| 334 | let previousDetail: WorkflowLogDetail | undefined |
| 335 | if (affectedLogId) { |
| 336 | previousDetail = queryClient.getQueryData<WorkflowLogDetail>( |
| 337 | logKeys.detail(workspaceId, affectedLogId) |
| 338 | ) |
| 339 | if (previousDetail) { |
| 340 | queryClient.setQueryData<WorkflowLogDetail>(logKeys.detail(workspaceId, affectedLogId), { |
| 341 | ...previousDetail, |
| 342 | status: 'cancelling', |
| 343 | }) |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | return { previousQueries, affectedLogId, previousDetail } |
| 348 | }, |
| 349 | onError: (_err, _variables, context) => { |
| 350 | for (const [queryKey, data] of context?.previousQueries ?? []) { |
| 351 | queryClient.setQueryData(queryKey, data) |
| 352 | } |