11import * as Context from "effect/Context" ;
2+ import * as Deferred from "effect/Deferred" ;
23import * as Effect from "effect/Effect" ;
34import * as Exit from "effect/Exit" ;
45import * as Fiber from "effect/Fiber" ;
56import * as Layer from "effect/Layer" ;
7+ import * as Option from "effect/Option" ;
8+ import * as Ref from "effect/Ref" ;
9+ import * as Result from "effect/Result" ;
610import * as Scope from "effect/Scope" ;
711import * as FetchHttpClient from "effect/http/FetchHttpClient" ;
812import * as HttpClient from "effect/http/HttpClient" ;
@@ -49,6 +53,9 @@ const ROUTE_CHECK_TIMEOUT_MS = 2_500;
4953// wait the full probe timeout for a LAN the device has already left. A route
5054// that misses it connects over relay, then upgrades with a second reconnect.
5155const ROUTE_CHECK_HEAD_START_MS = 500 ;
56+ // Give the preferred ready route a short solo window before parallel backups
57+ // start, so a fast LAN does not also open a relay session.
58+ const ROUTE_CONNECT_HEDGE_MS = 250 ;
5259
5360export class ConnectionDriver extends Context . Service <
5461 ConnectionDriver ,
@@ -93,10 +100,86 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
93100 if ( result . _tag === "Failure" ) {
94101 if ( result . failure . _tag === "ConnectionTransientError" ) transient ??= result . failure ;
95102 else blocked ??= result . failure ;
103+ return { result, routeScope } as const ;
96104 }
105+ return { result, routeScope } as const ;
106+ } ) ;
107+
108+ // First success wins. Later successes close their scopes so a hedged backup
109+ // cannot leave a second live session behind. A finished failure starts the
110+ // next route immediately; only a still-running preferred attempt waits out
111+ // the hedge before opening a parallel backup.
112+ const raceAttempts = Effect . fnUntraced ( function * ( candidates : ReadonlyArray < ConnectionRoute > ) {
113+ if ( candidates . length === 0 ) {
114+ return undefined as
115+ | Result . Result < EnvironmentConnectionLease , ConnectionAttemptError >
116+ | undefined ;
117+ }
118+ if ( candidates . length === 1 ) {
119+ const { result } = yield * attempt ( candidates [ 0 ] ! ) ;
120+ return result ;
121+ }
122+ const decided =
123+ yield * Deferred . make < Result . Result < EnvironmentConnectionLease , ConnectionAttemptError > > ( ) ;
124+ const remaining = yield * Ref . make ( candidates . length ) ;
125+ const fibers : Array < Fiber . Fiber < unknown , never > > = [ ] ;
126+ let previous = Option . none < Fiber . Fiber < unknown , never > > ( ) ;
127+
128+ for ( const [ index , route ] of candidates . entries ( ) ) {
129+ if ( index > 0 && Option . isSome ( previous ) ) {
130+ const gate = yield * Effect . raceFirst (
131+ Deferred . await ( decided ) . pipe ( Effect . as ( "decided" as const ) ) ,
132+ Fiber . join ( previous . value ) . pipe ( Effect . as ( "finished" as const ) ) ,
133+ ) . pipe (
134+ Effect . timeoutOrElse ( {
135+ duration : ROUTE_CONNECT_HEDGE_MS ,
136+ orElse : ( ) => Effect . succeed ( "hedge" as const ) ,
137+ } ) ,
138+ ) ;
139+ if ( gate === "decided" ) break ;
140+ }
141+ const fiber = yield * attempt ( route ) . pipe (
142+ Effect . flatMap ( ( { result, routeScope } ) => {
143+ if ( result . _tag === "Success" || result . failure . reason === "unsupported" ) {
144+ return Deferred . succeed ( decided , result ) . pipe (
145+ Effect . as ( true ) ,
146+ Effect . orElseSucceed ( ( ) => false ) ,
147+ Effect . flatMap ( ( claimed ) =>
148+ claimed ? Effect . void : Scope . close ( routeScope , Exit . void ) ,
149+ ) ,
150+ ) ;
151+ }
152+ return Ref . updateAndGet ( remaining , ( count ) => count - 1 ) . pipe (
153+ Effect . flatMap ( ( count ) =>
154+ count === 0 ? Deferred . succeed ( decided , result ) . pipe ( Effect . ignore ) : Effect . void ,
155+ ) ,
156+ ) ;
157+ } ) ,
158+ Effect . forkChild ,
159+ ) ;
160+ fibers . push ( fiber ) ;
161+ previous = Option . some ( fiber ) ;
162+ }
163+
164+ const result = yield * Deferred . await ( decided ) ;
165+ yield * Effect . forEach ( fibers , ( fiber ) => Fiber . interrupt ( fiber ) , {
166+ concurrency : "unbounded" ,
167+ discard : true ,
168+ } ) ;
97169 return result ;
98170 } ) ;
171+
172+ const settle = (
173+ result : Result . Result < EnvironmentConnectionLease , ConnectionAttemptError > | undefined ,
174+ ) => {
175+ if ( result === undefined ) return Effect . undefined ;
176+ if ( result . _tag === "Success" ) return Effect . succeed ( result . success ) ;
177+ if ( result . failure . reason === "unsupported" ) return Effect . fail ( result . failure ) ;
178+ return Effect . undefined ;
179+ } ;
180+
99181 const silent : Array < { readonly route : ConnectionRoute ; readonly index : number } > = [ ] ;
182+ const ready : Array < ConnectionRoute > = [ ] ;
100183 for ( const [ index , route ] of routes . entries ( ) ) {
101184 const check =
102185 checks . length === 0
@@ -109,25 +192,24 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
109192 silent . push ( { route, index } ) ;
110193 continue ;
111194 }
112- const result = yield * attempt ( route ) ;
113- if ( result . _tag === "Success" ) return result . success ;
114- // An incompatible server is the same server on every route.
115- if ( result . failure . reason === "unsupported" ) return yield * result . failure ;
195+ ready . push ( route ) ;
116196 }
197+
198+ const first = yield * settle ( yield * raceAttempts ( ready ) ) ;
199+ if ( first !== undefined ) return first ;
200+
117201 // A slow route that answered after the head start goes before one that is
118202 // still dead, which can hold an attempt open far longer than its probe.
119203 const late = yield * Effect . forEach ( silent , ( { index } ) => Fiber . join ( checks [ index ] ! ) , {
120204 concurrency : "unbounded" ,
121205 } ) ;
122206 const retry = [
123- ...silent . filter ( ( _ , position ) => late [ position ] !== "silent" ) ,
124- ...silent . filter ( ( _ , position ) => late [ position ] === "silent" ) ,
207+ ...silent . filter ( ( _ , position ) => late [ position ] !== "silent" ) . map ( ( { route } ) => route ) ,
208+ ...silent . filter ( ( _ , position ) => late [ position ] === "silent" ) . map ( ( { route } ) => route ) ,
125209 ] ;
126- for ( const { route } of retry ) {
127- const result = yield * attempt ( route ) ;
128- if ( result . _tag === "Success" ) return result . success ;
129- if ( result . failure . reason === "unsupported" ) return yield * result . failure ;
130- }
210+ const second = yield * settle ( yield * raceAttempts ( retry ) ) ;
211+ if ( second !== undefined ) return second ;
212+
131213 return yield * (
132214 transient ??
133215 blocked ??
0 commit comments