-
Notifications
You must be signed in to change notification settings - Fork 3.3k
fix(terminal): reconnect to running executions after page refresh #3200
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
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
db19975
fix(terminal): reconnect to running executions after page refresh
waleedlatif1 fde8f97
fix(terminal): use ExecutionEvent type instead of any in reconnection…
waleedlatif1 a5e8a30
fix(execution): type event buffer with ExecutionEvent instead of Reco…
waleedlatif1 ef477ba
fix(execution): validate fromEventId query param in reconnection endp…
waleedlatif1 986cef3
Fix some bugs
Sg312 5f3e76d
fix(variables): fix tag dropdown and cursor alignment in variables bl…
waleedlatif1 7c4b925
feat(confluence): added list space labels, delete label, delete page …
waleedlatif1 51bc5b5
updated route
waleedlatif1 e1af0f4
Merge branch 'staging' into fix/refresh-resume
waleedlatif1 3bb271d
ack comments
waleedlatif1 0c7a0bd
chore: merge staging and remove unrelated copilot/tmp changes
waleedlatif1 61a6b18
fix(execution): reset execution state in reconnection cleanup to unbl…
waleedlatif1 7af4025
fix(execution): restore running entries when reconnection is interrup…
waleedlatif1 5b8dba0
done
waleedlatif1 19ccefa
remove cast in ioredis types
waleedlatif1 0634d05
ack PR comments
waleedlatif1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
170 changes: 170 additions & 0 deletions
170
apps/sim/app/api/workflows/[id]/executions/[executionId]/stream/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { checkHybridAuth } from '@/lib/auth/hybrid' | ||
| import { SSE_HEADERS } from '@/lib/core/utils/sse' | ||
| import { | ||
| type ExecutionStreamStatus, | ||
| getExecutionMeta, | ||
| readExecutionEvents, | ||
| } from '@/lib/execution/event-buffer' | ||
| import { formatSSEEvent } from '@/lib/workflows/executor/execution-events' | ||
| import { authorizeWorkflowByWorkspacePermission } from '@/lib/workflows/utils' | ||
|
|
||
| const logger = createLogger('ExecutionStreamReconnectAPI') | ||
|
|
||
| const POLL_INTERVAL_MS = 500 | ||
| const MAX_POLL_DURATION_MS = 10 * 60 * 1000 // 10 minutes | ||
|
|
||
| function isTerminalStatus(status: ExecutionStreamStatus): boolean { | ||
| return status === 'complete' || status === 'error' || status === 'cancelled' | ||
| } | ||
|
|
||
| export const runtime = 'nodejs' | ||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| export async function GET( | ||
| req: NextRequest, | ||
| { params }: { params: Promise<{ id: string; executionId: string }> } | ||
| ) { | ||
| const { id: workflowId, executionId } = await params | ||
|
|
||
| try { | ||
| const auth = await checkHybridAuth(req, { requireWorkflowId: false }) | ||
| if (!auth.success || !auth.userId) { | ||
| return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 }) | ||
| } | ||
|
|
||
| const workflowAuthorization = await authorizeWorkflowByWorkspacePermission({ | ||
| workflowId, | ||
| userId: auth.userId, | ||
| action: 'read', | ||
| }) | ||
| if (!workflowAuthorization.allowed) { | ||
| return NextResponse.json( | ||
| { error: workflowAuthorization.message || 'Access denied' }, | ||
| { status: workflowAuthorization.status } | ||
| ) | ||
| } | ||
|
|
||
| const meta = await getExecutionMeta(executionId) | ||
| if (!meta) { | ||
| return NextResponse.json({ error: 'Execution buffer not found or expired' }, { status: 404 }) | ||
| } | ||
|
|
||
| if (meta.workflowId && meta.workflowId !== workflowId) { | ||
| return NextResponse.json( | ||
| { error: 'Execution does not belong to this workflow' }, | ||
| { status: 403 } | ||
| ) | ||
| } | ||
|
|
||
| const fromParam = req.nextUrl.searchParams.get('from') | ||
| const parsed = fromParam ? Number.parseInt(fromParam, 10) : 0 | ||
| const fromEventId = Number.isFinite(parsed) && parsed >= 0 ? parsed : 0 | ||
|
|
||
waleedlatif1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| logger.info('Reconnection stream requested', { | ||
| workflowId, | ||
| executionId, | ||
| fromEventId, | ||
| metaStatus: meta.status, | ||
| }) | ||
|
|
||
| const encoder = new TextEncoder() | ||
|
|
||
| let closed = false | ||
|
|
||
| const stream = new ReadableStream<Uint8Array>({ | ||
| async start(controller) { | ||
| let lastEventId = fromEventId | ||
| const pollDeadline = Date.now() + MAX_POLL_DURATION_MS | ||
|
|
||
| const enqueue = (text: string) => { | ||
| if (closed) return | ||
| try { | ||
| controller.enqueue(encoder.encode(text)) | ||
| } catch { | ||
| closed = true | ||
| } | ||
| } | ||
|
|
||
| try { | ||
| const events = await readExecutionEvents(executionId, lastEventId) | ||
| for (const entry of events) { | ||
| if (closed) return | ||
| enqueue(formatSSEEvent(entry.event)) | ||
| lastEventId = entry.eventId | ||
| } | ||
|
|
||
| const currentMeta = await getExecutionMeta(executionId) | ||
| if (!currentMeta || isTerminalStatus(currentMeta.status)) { | ||
| enqueue('data: [DONE]\n\n') | ||
| if (!closed) controller.close() | ||
| return | ||
| } | ||
|
|
||
| while (!closed && Date.now() < pollDeadline) { | ||
| await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS)) | ||
| if (closed) return | ||
|
|
||
| const newEvents = await readExecutionEvents(executionId, lastEventId) | ||
| for (const entry of newEvents) { | ||
| if (closed) return | ||
| enqueue(formatSSEEvent(entry.event)) | ||
| lastEventId = entry.eventId | ||
| } | ||
|
|
||
| const polledMeta = await getExecutionMeta(executionId) | ||
| if (!polledMeta || isTerminalStatus(polledMeta.status)) { | ||
| const finalEvents = await readExecutionEvents(executionId, lastEventId) | ||
| for (const entry of finalEvents) { | ||
| if (closed) return | ||
| enqueue(formatSSEEvent(entry.event)) | ||
| lastEventId = entry.eventId | ||
| } | ||
| enqueue('data: [DONE]\n\n') | ||
| if (!closed) controller.close() | ||
| return | ||
| } | ||
| } | ||
|
|
||
| if (!closed) { | ||
| logger.warn('Reconnection stream poll deadline reached', { executionId }) | ||
| enqueue('data: [DONE]\n\n') | ||
| controller.close() | ||
| } | ||
| } catch (error) { | ||
| logger.error('Error in reconnection stream', { | ||
| executionId, | ||
| error: error instanceof Error ? error.message : String(error), | ||
| }) | ||
| if (!closed) { | ||
| try { | ||
| controller.close() | ||
| } catch {} | ||
| } | ||
| } | ||
| }, | ||
| cancel() { | ||
| closed = true | ||
| logger.info('Client disconnected from reconnection stream', { executionId }) | ||
| }, | ||
| }) | ||
|
|
||
| return new NextResponse(stream, { | ||
| headers: { | ||
| ...SSE_HEADERS, | ||
| 'X-Execution-Id': executionId, | ||
| }, | ||
| }) | ||
| } catch (error: any) { | ||
| logger.error('Failed to start reconnection stream', { | ||
| workflowId, | ||
| executionId, | ||
| error: error.message, | ||
| }) | ||
| return NextResponse.json( | ||
| { error: error.message || 'Failed to start reconnection stream' }, | ||
| { status: 500 } | ||
| ) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.