-
Notifications
You must be signed in to change notification settings - Fork 3.2k
fix(cancellation): workflow cancellation handled for non-local envs #2570
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { z } from 'zod' | ||
| import { checkHybridAuth } from '@/lib/auth/hybrid' | ||
| import { requestCancellation } from '@/lib/execution/cancellation' | ||
|
|
||
| const CancelExecutionSchema = z.object({ | ||
| executionId: z.string().uuid(), | ||
| }) | ||
|
|
||
| export const runtime = 'nodejs' | ||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) { | ||
| await params | ||
|
|
||
| const auth = await checkHybridAuth(req, { requireWorkflowId: false }) | ||
| if (!auth.success || !auth.userId) { | ||
| return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 }) | ||
| } | ||
|
|
||
| let body: any = {} | ||
| try { | ||
| const text = await req.text() | ||
| if (text) { | ||
| body = JSON.parse(text) | ||
| } | ||
| } catch { | ||
| return NextResponse.json({ error: 'Invalid request body' }, { status: 400 }) | ||
| } | ||
|
|
||
| const validation = CancelExecutionSchema.safeParse(body) | ||
| if (!validation.success) { | ||
| return NextResponse.json({ error: 'Invalid request body' }, { status: 400 }) | ||
| } | ||
|
|
||
| const { executionId } = validation.data | ||
| const success = await requestCancellation(executionId) | ||
| return NextResponse.json({ success }) | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| import { isCancellationRequested } from '@/lib/execution/cancellation' | ||
| import { createLogger } from '@/lib/logs/console/logger' | ||
| import { BlockType } from '@/executor/constants' | ||
| import type { DAG } from '@/executor/dag/builder' | ||
|
|
@@ -33,13 +34,24 @@ export class ExecutionEngine { | |
| this.allowResumeTriggers = this.context.metadata.resumeFromSnapshot === true | ||
| } | ||
|
|
||
| private async checkCancellation(): Promise<boolean> { | ||
| if (this.context.isCancelled) return true | ||
| const executionId = this.context.executionId | ||
| if (!executionId) return false | ||
| const cancelled = await isCancellationRequested(executionId) | ||
| if (cancelled) { | ||
| this.context.isCancelled = true | ||
| } | ||
| return cancelled | ||
| } | ||
|
|
||
| async run(triggerBlockId?: string): Promise<ExecutionResult> { | ||
| const startTime = Date.now() | ||
| try { | ||
| this.initializeQueue(triggerBlockId) | ||
|
|
||
| while (this.hasWork()) { | ||
| if (this.context.isCancelled && this.executing.size === 0) { | ||
| if ((await this.checkCancellation()) && this.executing.size === 0) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is this the best place to put this? |
||
| break | ||
| } | ||
| await this.processQueue() | ||
|
|
@@ -234,7 +246,7 @@ export class ExecutionEngine { | |
|
|
||
| private async processQueue(): Promise<void> { | ||
| while (this.readyQueue.length > 0) { | ||
| if (this.context.isCancelled) { | ||
| if (await this.checkCancellation()) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This check needs to move into redis |
||
| break | ||
| } | ||
| const nodeId = this.dequeue() | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -76,6 +76,10 @@ export interface ExecuteStreamOptions { | |
| */ | ||
| export function useExecutionStream() { | ||
| const abortControllerRef = useRef<AbortController | null>(null) | ||
| const currentExecutionRef = useRef<{ workflowId: string; executionId: string | null }>({ | ||
| workflowId: '', | ||
| executionId: null, | ||
| }) | ||
|
|
||
| const execute = useCallback(async (options: ExecuteStreamOptions) => { | ||
| const { workflowId, callbacks = {}, ...payload } = options | ||
|
|
@@ -89,6 +93,8 @@ export function useExecutionStream() { | |
| const abortController = new AbortController() | ||
| abortControllerRef.current = abortController | ||
|
|
||
| currentExecutionRef.current = { workflowId, executionId: null } | ||
|
|
||
| try { | ||
| const response = await fetch(`/api/workflows/${workflowId}/execute`, { | ||
| method: 'POST', | ||
|
|
@@ -108,6 +114,11 @@ export function useExecutionStream() { | |
| throw new Error('No response body') | ||
| } | ||
|
|
||
| const executionId = response.headers.get('X-Execution-Id') | ||
| if (executionId) { | ||
| currentExecutionRef.current.executionId = executionId | ||
| } | ||
|
|
||
| // Read SSE stream | ||
| const reader = response.body.getReader() | ||
| const decoder = new TextDecoder() | ||
|
|
@@ -215,6 +226,7 @@ export function useExecutionStream() { | |
| throw error | ||
| } finally { | ||
| abortControllerRef.current = null | ||
| currentExecutionRef.current = { workflowId: '', executionId: null } | ||
| } | ||
| }, []) | ||
|
|
||
|
|
@@ -223,6 +235,17 @@ export function useExecutionStream() { | |
| abortControllerRef.current.abort() | ||
| abortControllerRef.current = null | ||
| } | ||
|
|
||
| const { workflowId, executionId } = currentExecutionRef.current | ||
| if (workflowId && executionId) { | ||
| fetch(`/api/workflows/${workflowId}/execute/cancel`, { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| body: JSON.stringify({ executionId }), | ||
| }).catch(() => {}) | ||
|
Comment on lines
+241
to
+245
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. style: The catch block silently ignores cancellation API errors. Consider logging the error to help with debugging cancellation issues in production. Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time! Prompt To Fix With AIThis is a comment left during a code review.
Path: apps/sim/hooks/use-execution-stream.ts
Line: 241:245
Comment:
**style:** The catch block silently ignores cancellation API errors. Consider logging the error to help with debugging cancellation issues in production.
<sub>Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!</sub>
How can I resolve this? If you propose a fix, please make it concise. |
||
| } | ||
|
|
||
| currentExecutionRef.current = { workflowId: '', executionId: null } | ||
| }, []) | ||
|
|
||
| return { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| import { getRedisClient } from '@/lib/core/config/redis' | ||
|
|
||
| const KEY_PREFIX = 'execution:cancel:' | ||
| const TTL_SECONDS = 300 | ||
| const TTL_MS = TTL_SECONDS * 1000 | ||
|
|
||
| const memoryStore = new Map<string, number>() | ||
|
|
||
| export async function requestCancellation(executionId: string): Promise<boolean> { | ||
| const redis = getRedisClient() | ||
| if (redis) { | ||
| try { | ||
| await redis.set(`${KEY_PREFIX}${executionId}`, '1', 'EX', TTL_SECONDS) | ||
| return true | ||
| } catch { | ||
| return false | ||
| } | ||
| } | ||
| memoryStore.set(executionId, Date.now() + TTL_MS) | ||
| return true | ||
| } | ||
|
|
||
| export async function isCancellationRequested(executionId: string): Promise<boolean> { | ||
| const redis = getRedisClient() | ||
| if (redis) { | ||
| try { | ||
| return (await redis.exists(`${KEY_PREFIX}${executionId}`)) === 1 | ||
| } catch { | ||
| return false | ||
| } | ||
| } | ||
| const expiry = memoryStore.get(executionId) | ||
| if (!expiry) return false | ||
| if (Date.now() > expiry) { | ||
| memoryStore.delete(executionId) | ||
| return false | ||
| } | ||
| return true | ||
| } | ||
|
|
||
| export async function clearCancellation(executionId: string): Promise<void> { | ||
| const redis = getRedisClient() | ||
| if (redis) { | ||
| try { | ||
| await redis.del(`${KEY_PREFIX}${executionId}`) | ||
| } catch {} | ||
| return | ||
| } | ||
| memoryStore.delete(executionId) | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
style: Avoid using
anytype. Useunknowninstead for better type safetyContext Used: Context from
dashboard- TypeScript conventions and type safety (source)Prompt To Fix With AI