@@ -18,6 +18,7 @@ import {
1818 runMetadata ,
1919 runtime ,
2020 runTimelineMetrics ,
21+ taskContext ,
2122 TaskRunErrorCodes ,
2223 TaskRunExecution ,
2324 timeout ,
@@ -58,6 +59,7 @@ import sourceMapSupport from "source-map-support";
5859import { env } from "std-env" ;
5960import { normalizeImportPath } from "../utilities/normalizeImportPath.js" ;
6061import { VERSION } from "../version.js" ;
62+ import { promiseWithResolvers } from "@trigger.dev/core/utils" ;
6163
6264sourceMapSupport . install ( {
6365 handleUncaughtExceptions : false ,
@@ -110,15 +112,18 @@ lifecycleHooks.setGlobalLifecycleHooksManager(standardLifecycleHooksManager);
110112const standardRunTimelineMetricsManager = new StandardRunTimelineMetricsManager ( ) ;
111113runTimelineMetrics . setGlobalManager ( standardRunTimelineMetricsManager ) ;
112114
113- resourceCatalog . setGlobalResourceCatalog ( new StandardResourceCatalog ( ) ) ;
115+ const standardResourceCatalog = new StandardResourceCatalog ( ) ;
116+ resourceCatalog . setGlobalResourceCatalog ( standardResourceCatalog ) ;
114117
115118const durableClock = new DurableClock ( ) ;
116119clock . setGlobalClock ( durableClock ) ;
120+
117121const runMetadataManager = new StandardMetadataManager (
118122 apiClientManager . clientOrThrow ( ) ,
119123 getEnvVar ( "TRIGGER_STREAM_URL" , getEnvVar ( "TRIGGER_API_URL" ) ) ?? "https://api.trigger.dev"
120124) ;
121125runMetadata . setGlobalManager ( runMetadataManager ) ;
126+
122127const waitUntilManager = new StandardWaitUntilManager ( ) ;
123128waitUntil . setGlobalManager ( waitUntilManager ) ;
124129// Wait for all streams to finish before completing the run
@@ -236,7 +241,30 @@ let _isRunning = false;
236241let _isCancelled = false ;
237242let _tracingSDK : TracingSDK | undefined ;
238243let _executionMeasurement : UsageMeasurement | undefined ;
239- const cancelController = new AbortController ( ) ;
244+ let _cancelController = new AbortController ( ) ;
245+ let _lastFlushPromise : Promise < void > | undefined ;
246+ let _sharedWorkerRuntime : SharedRuntimeManager | undefined ;
247+
248+ function resetExecutionEnvironment ( ) {
249+ _execution = undefined ;
250+ _isRunning = false ;
251+ _isCancelled = false ;
252+ _executionMeasurement = undefined ;
253+ _cancelController = new AbortController ( ) ;
254+
255+ standardLocalsManager . reset ( ) ;
256+ standardLifecycleHooksManager . reset ( ) ;
257+ standardRunTimelineMetricsManager . reset ( ) ;
258+ usage . reset ( ) ;
259+ timeout . reset ( ) ;
260+ runMetadataManager . reset ( ) ;
261+ waitUntilManager . reset ( ) ;
262+ _sharedWorkerRuntime ?. reset ( ) ;
263+ durableClock . reset ( ) ;
264+ taskContext . disable ( ) ;
265+
266+ console . log ( `[${ new Date ( ) . toISOString ( ) } ] Reset execution environment` ) ;
267+ }
240268
241269const zodIpc = new ZodIpcConnection ( {
242270 listenSchema : WorkerToExecutorMessageCatalog ,
@@ -253,6 +281,22 @@ const zodIpc = new ZodIpcConnection({
253281 } ) ;
254282 }
255283
284+ console . log (
285+ `[${ new Date ( ) . toISOString ( ) } ] Received EXECUTE_TASK_RUN isWarmStart ${ String ( isWarmStart ) } `
286+ ) ;
287+
288+ if ( _lastFlushPromise ) {
289+ const now = performance . now ( ) ;
290+
291+ await _lastFlushPromise ;
292+
293+ const duration = performance . now ( ) - now ;
294+
295+ console . log ( `[${ new Date ( ) . toISOString ( ) } ] Awaited last flush in ${ duration } ms` ) ;
296+ }
297+
298+ resetExecutionEnvironment ( ) ;
299+
256300 initializeUsageManager ( {
257301 usageIntervalMs : getEnvVar ( "USAGE_HEARTBEAT_INTERVAL_MS" ) ,
258302 usageEventUrl : getEnvVar ( "USAGE_EVENT_URL" ) ,
@@ -421,7 +465,7 @@ const zodIpc = new ZodIpcConnection({
421465
422466 const timeoutController = timeout . abortAfterTimeout ( execution . run . maxDuration ) ;
423467
424- const signal = AbortSignal . any ( [ cancelController . signal , timeoutController . signal ] ) ;
468+ const signal = AbortSignal . any ( [ _cancelController . signal , timeoutController . signal ] ) ;
425469
426470 const { result } = await executor . execute ( execution , metadata , traceContext , signal ) ;
427471
@@ -442,6 +486,8 @@ const zodIpc = new ZodIpcConnection({
442486 } finally {
443487 _execution = undefined ;
444488 _isRunning = false ;
489+
490+ console . log ( `[${ new Date ( ) . toISOString ( ) } ] Task run completed` ) ;
445491 }
446492 } catch ( err ) {
447493 console . error ( "Failed to execute task" , err ) ;
@@ -467,7 +513,7 @@ const zodIpc = new ZodIpcConnection({
467513 } ,
468514 CANCEL : async ( { timeoutInMs } ) => {
469515 _isCancelled = true ;
470- cancelController . abort ( "run cancelled" ) ;
516+ _cancelController . abort ( "run cancelled" ) ;
471517 await callCancelHooks ( timeoutInMs ) ;
472518 if ( _executionMeasurement ) {
473519 usage . stop ( _executionMeasurement ) ;
@@ -478,7 +524,7 @@ const zodIpc = new ZodIpcConnection({
478524 await flushAll ( timeoutInMs ) ;
479525 } ,
480526 RESOLVE_WAITPOINT : async ( { waitpoint } ) => {
481- sharedWorkerRuntime . resolveWaitpoints ( [ waitpoint ] ) ;
527+ _sharedWorkerRuntime ? .resolveWaitpoints ( [ waitpoint ] ) ;
482528 } ,
483529 } ,
484530} ) ;
@@ -498,6 +544,10 @@ async function callCancelHooks(timeoutInMs: number = 10_000) {
498544async function flushAll ( timeoutInMs : number = 10_000 ) {
499545 const now = performance . now ( ) ;
500546
547+ const { promise, resolve } = promiseWithResolvers < void > ( ) ;
548+
549+ _lastFlushPromise = promise ;
550+
501551 const results = await Promise . allSettled ( [
502552 flushUsage ( timeoutInMs ) ,
503553 flushTracingSDK ( timeoutInMs ) ,
@@ -530,6 +580,9 @@ async function flushAll(timeoutInMs: number = 10_000) {
530580 const duration = performance . now ( ) - now ;
531581
532582 console . log ( `Flushed all in ${ duration } ms` ) ;
583+
584+ // Resolve the last flush promise
585+ resolve ( ) ;
533586}
534587
535588async function flushUsage ( timeoutInMs : number = 10_000 ) {
@@ -597,9 +650,8 @@ function initializeUsageManager({
597650 timeout . setGlobalManager ( new UsageTimeoutManager ( devUsageManager ) ) ;
598651}
599652
600- const sharedWorkerRuntime = new SharedRuntimeManager ( zodIpc , true ) ;
601-
602- runtime . setGlobalRuntimeManager ( sharedWorkerRuntime ) ;
653+ _sharedWorkerRuntime = new SharedRuntimeManager ( zodIpc , true ) ;
654+ runtime . setGlobalRuntimeManager ( _sharedWorkerRuntime ) ;
603655
604656process . title = "trigger-managed-worker" ;
605657
0 commit comments