@@ -2,6 +2,7 @@ import fsp from "node:fs/promises";
22import type { WorkerAdmissionHandshake } from "../../../packages/gateway-protocol/src/schema/worker-admission.js" ;
33import { sleepWithAbort } from "../../infra/backoff.js" ;
44import { NODE_WORKER_WORKSPACE_EXEC_COMMAND } from "../../infra/node-commands.js" ;
5+ import { createSubsystemLogger } from "../../logging/subsystem.js" ;
56import type { SpawnResult } from "../../process/exec.js" ;
67import { createDeferredCore , type Deferred } from "../../shared/deferred.js" ;
78import type { NodeWorkerSupervisorReceipt } from "../../worker/node-supervisor-protocol.js" ;
@@ -31,6 +32,7 @@ import type {
3132 WorkerTunnelStatus ,
3233 WorkerWorkspaceCommand ,
3334} from "./tunnel-contract.js" ;
35+ import { boundedWorkerError } from "./worker-error.js" ;
3436import { serializeWorkerWorkspaceManifest } from "./workspace-manifest.js" ;
3537import { createWorkerWorkspaceQuiescence } from "./workspace-quiescence.js" ;
3638import {
@@ -44,6 +46,7 @@ import { REMOTE_WORKSPACE_MANIFEST_JS } from "./workspace-sync-scripts.js";
4446
4547const DEFAULT_COMMAND_TIMEOUT_MS = 60_000 ;
4648const RETRY_DELAY_MS = 100 ;
49+ const tunnelLog = createSubsystemLogger ( "gateway/worker-tunnel" ) ;
4750const RETRYABLE_TRANSPORT_CODES = new Set ( [
4851 "DISCONNECTED" ,
4952 "NOT_CONNECTED" ,
@@ -112,7 +115,8 @@ type NodeWorkerTunnelStartRequest = {
112115type NodeTunnelEntry = NodeWorkerTunnelStartRequest & {
113116 abortController : AbortController ;
114117 gatewayNamespace : string ;
115- handle : WorkerTunnelHandle ;
118+ handle ?: WorkerTunnelHandle ;
119+ initialization ?: Promise < void > ;
116120 launchTasks : Set < Promise < unknown > > ;
117121 readiness : Deferred < WorkerTunnelHandle > ;
118122 stopPromise ?: Promise < void > ;
@@ -182,7 +186,6 @@ function raceWithSignal<T>(operation: Promise<T>, signal: AbortSignal): Promise<
182186/** Owns node-channel handles without treating the persistent machine as a disposable lease. */
183187export function createNodeWorkerTunnelManager ( options : NodeWorkerTunnelManagerOptions ) {
184188 const entries = new Map < string , NodeTunnelEntry > ( ) ;
185- const pendingStarts = new Map < string , { ownerEpoch : number ; cancelled : boolean } > ( ) ;
186189 let resolveWorkspaceBinding : NodeWorkerWorkspaceBindingResolver | undefined ;
187190 const gatewayNamespace = nodeWorkerGatewayNamespace ( options . gatewayDeviceId ) ;
188191
@@ -304,7 +307,7 @@ export function createNodeWorkerTunnelManager(options: NodeWorkerTunnelManagerOp
304307 } ;
305308
306309 const createHandle = (
307- entry : Omit < NodeTunnelEntry , "handle" | "readiness" > ,
310+ entry : Omit < NodeTunnelEntry , "handle" | "readiness" | "initialization" > ,
308311 restoredWorkspace : NodeWorkerWorkspaceBinding | undefined ,
309312 ) : { handle : WorkerTunnelHandle ; validateRestoredWorkspace : ( ) => Promise < void > } => {
310313 let workspaceReady = restoredWorkspace !== undefined ;
@@ -610,14 +613,16 @@ export function createNodeWorkerTunnelManager(options: NodeWorkerTunnelManagerOp
610613 if ( entry . stopPromise ) {
611614 return entry . stopPromise ;
612615 }
616+ if ( entries . get ( entry . environmentId ) === entry ) {
617+ entries . delete ( entry . environmentId ) ;
618+ }
613619 entry . abortController . abort ( new Error ( "node worker tunnel owner stopped" ) ) ;
614620 entry . readiness . reject ( new Error ( "node worker tunnel stopped before connecting" ) ) ;
615- entry . stopPromise = Promise . allSettled ( entry . launchTasks ) . then ( ( ) => {
616- if ( entries . get ( entry . environmentId ) === entry ) {
617- entries . delete ( entry . environmentId ) ;
618- }
619- return options . workspaceTransfer . close ( entry . environmentId ) ;
620- } ) ;
621+ entry . stopPromise = ( async ( ) => {
622+ await entry . initialization ?. catch ( ( ) => undefined ) ;
623+ await Promise . allSettled ( entry . launchTasks ) ;
624+ await options . workspaceTransfer . close ( entry . environmentId ) ;
625+ } ) ( ) ;
621626 return entry . stopPromise ;
622627 }
623628
@@ -643,73 +648,77 @@ export function createNodeWorkerTunnelManager(options: NodeWorkerTunnelManagerOp
643648 return current . readiness . promise ; // Share restored-workspace validation without false readiness.
644649 }
645650 }
646- const pending = { ownerEpoch : request . ownerEpoch , cancelled : false } ;
647- pendingStarts . set ( request . environmentId , pending ) ;
648- try {
651+ const readiness = createDeferredCore < WorkerTunnelHandle > ( ) ;
652+ void readiness . promise . catch ( ( ) => undefined ) ;
653+ const entry : NodeTunnelEntry = {
654+ ...request ,
655+ gatewayNamespace,
656+ abortController : new AbortController ( ) ,
657+ launchTasks : new Set ( ) ,
658+ readiness,
659+ } ;
660+ // Publish the new epoch before any teardown or initialization await so stop and replacement
661+ // can fence it, while exact same-owner callers share this readiness barrier.
662+ entries . set ( entry . environmentId , entry ) ;
663+ entry . initialization = ( async ( ) => {
649664 if ( current ) {
650665 await stopEntry ( current ) ;
651666 }
652- if ( pending . cancelled || pendingStarts . get ( request . environmentId ) !== pending ) {
653- throw new Error ( "node worker tunnel start was cancelled" ) ;
654- }
655- const restoredWorkspace = await resolveWorkspaceBinding ?.( {
656- environmentId : request . environmentId ,
657- ownerEpoch : request . ownerEpoch ,
658- sessionId : request . sessionId ,
659- } ) ;
660- if ( pending . cancelled || pendingStarts . get ( request . environmentId ) !== pending ) {
661- throw new Error ( "node worker tunnel start was cancelled" ) ;
667+ if ( ! isLiveEntry ( entry ) ) {
668+ return ;
662669 }
663- const base = {
664- ...request ,
665- gatewayNamespace,
666- abortController : new AbortController ( ) ,
667- launchTasks : new Set < Promise < unknown > > ( ) ,
668- } ;
669- const readiness = createDeferredCore < WorkerTunnelHandle > ( ) ;
670- void readiness . promise . catch ( ( ) => undefined ) ;
671- const created = createHandle ( base , restoredWorkspace ) ;
672- const entry = Object . assign ( base , { readiness, handle : created . handle } ) ;
673- entries . set ( entry . environmentId , entry ) ;
674- try {
675- await created . validateRestoredWorkspace ( ) ;
676- if ( pending . cancelled || pendingStarts . get ( request . environmentId ) !== pending ) {
677- throw new Error ( "node worker tunnel start was cancelled" ) ;
678- }
679- readiness . resolve ( entry . handle ) ;
680- return entry . handle ;
681- } catch ( error ) {
682- readiness . reject ( error ) ;
683- await stopEntry ( entry ) ;
684- throw error ;
670+ const restoredWorkspace = resolveWorkspaceBinding
671+ ? await raceWithSignal (
672+ resolveWorkspaceBinding ( {
673+ environmentId : request . environmentId ,
674+ ownerEpoch : request . ownerEpoch ,
675+ sessionId : request . sessionId ,
676+ } ) ,
677+ entry . abortController . signal ,
678+ )
679+ : undefined ;
680+ if ( ! isLiveEntry ( entry ) ) {
681+ return ;
685682 }
686- } finally {
687- if ( pendingStarts . get ( request . environmentId ) === pending ) {
688- pendingStarts . delete ( request . environmentId ) ;
683+ const created = createHandle ( entry , restoredWorkspace ) ;
684+ await created . validateRestoredWorkspace ( ) ;
685+ if ( ! isLiveEntry ( entry ) ) {
686+ return ;
689687 }
690- }
688+ entry . handle = created . handle ;
689+ readiness . resolve ( created . handle ) ;
690+ } ) ( ) ;
691+ void entry . initialization . catch ( ( error : unknown ) => {
692+ readiness . reject ( error ) ;
693+ // Startup already reports the owning error through readiness. Keep secondary cleanup
694+ // failures visible without replacing that shared result for concurrent callers.
695+ void stopEntry ( entry ) . catch ( ( cleanupError : unknown ) => {
696+ tunnelLog . warn ( "node worker tunnel cleanup failed after initialization error" , {
697+ environmentId : entry . environmentId ,
698+ ownerEpoch : entry . ownerEpoch ,
699+ error : boundedWorkerError ( cleanupError ) ,
700+ } ) ;
701+ } ) ;
702+ } ) ;
703+ return await readiness . promise ;
691704 } ,
692705 async stop ( environmentId : string , ownerEpoch ?: number ) : Promise < void > {
693- const pending = pendingStarts . get ( environmentId ) ;
694- if ( pending && ( ownerEpoch === undefined || ownerEpoch === pending . ownerEpoch ) ) {
695- pending . cancelled = true ;
696- }
697706 const entry = entries . get ( environmentId ) ;
698707 if ( entry && ( ownerEpoch === undefined || ownerEpoch === entry . ownerEpoch ) ) {
699708 await stopEntry ( entry ) ;
700709 }
701710 } ,
702711 async stopAll ( ) : Promise < void > {
703- for ( const pending of pendingStarts . values ( ) ) {
704- pending . cancelled = true ;
705- }
706712 await Promise . all ( [ ...entries . values ( ) ] . map ( stopEntry ) ) ;
707713 await options . workspaceTransfer . closeAll ( ) ;
708714 } ,
709715 status ( environmentId : string ) : WorkerTunnelStatus {
710716 const entry = entries . get ( environmentId ) ;
711- const status = entry && ! entry . abortController . signal . aborted ? "connected" : "stopped" ;
712- return pendingStarts . get ( environmentId ) ?. cancelled === false ? "connecting" : status ;
717+ return entry && ! entry . abortController . signal . aborted
718+ ? entry . handle
719+ ? "connected"
720+ : "connecting"
721+ : "stopped" ;
713722 } ,
714723 } ;
715724}
0 commit comments