@@ -22,6 +22,7 @@ import { createExecutionEventWriter, setExecutionMeta } from '@/lib/execution/ev
2222import { processInputFileFields } from '@/lib/execution/files'
2323import { preprocessExecution } from '@/lib/execution/preprocessing'
2424import { LoggingSession } from '@/lib/logs/execution/logging-session'
25+ import { decrementSSEConnections , incrementSSEConnections } from '@/lib/monitoring/sse-connections'
2526import {
2627 cleanupExecutionBase64Cache ,
2728 hydrateUserFilesWithBase64 ,
@@ -763,6 +764,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
763764 const encoder = new TextEncoder ( )
764765 const timeoutController = createTimeoutAbortController ( preprocessResult . executionTimeout ?. sync )
765766 let isStreamClosed = false
767+ let sseDecremented = false
766768
767769 const eventWriter = createExecutionEventWriter ( executionId )
768770 setExecutionMeta ( executionId , {
@@ -773,6 +775,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
773775
774776 const stream = new ReadableStream < Uint8Array > ( {
775777 async start ( controller ) {
778+ incrementSSEConnections ( 'workflow-execute' )
776779 let finalMetaStatus : 'complete' | 'error' | 'cancelled' | null = null
777780
778781 const sendEvent = ( event : ExecutionEvent ) => {
@@ -1147,6 +1150,10 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
11471150 if ( executionId ) {
11481151 await cleanupExecutionBase64Cache ( executionId )
11491152 }
1153+ if ( ! sseDecremented ) {
1154+ sseDecremented = true
1155+ decrementSSEConnections ( 'workflow-execute' )
1156+ }
11501157 if ( ! isStreamClosed ) {
11511158 try {
11521159 controller . enqueue ( encoder . encode ( 'data: [DONE]\n\n' ) )
@@ -1155,9 +1162,16 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
11551162 }
11561163 }
11571164 } ,
1158- cancel ( ) {
1165+ async cancel ( ) {
11591166 isStreamClosed = true
11601167 logger . info ( `[${ requestId } ] Client disconnected from SSE stream` )
1168+ timeoutController . abort ( )
1169+ timeoutController . cleanup ( )
1170+ await eventWriter . close ( ) . catch ( ( ) => { } )
1171+ if ( ! sseDecremented ) {
1172+ sseDecremented = true
1173+ decrementSSEConnections ( 'workflow-execute' )
1174+ }
11611175 } ,
11621176 } )
11631177
0 commit comments