@@ -13,7 +13,9 @@ import * as Deferred from "effect/Deferred";
1313import * as Duration from "effect/Duration" ;
1414import * as Effect from "effect/Effect" ;
1515import * as Fiber from "effect/Fiber" ;
16+ import * as FileSystem from "effect/FileSystem" ;
1617import * as Layer from "effect/Layer" ;
18+ import * as Path from "effect/Path" ;
1719import * as PlatformError from "effect/PlatformError" ;
1820import * as Schema from "effect/Schema" ;
1921import * as Result from "effect/Result" ;
@@ -24,6 +26,7 @@ import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
2426import { ChildProcess , ChildProcessSpawner } from "effect/process" ;
2527
2628import * as SshAuth from "./auth.ts" ;
29+ import { remoteStateKey } from "./command.ts" ;
2730import { SshCommandError , SshPasswordPromptError , SshReadinessError } from "./errors.ts" ;
2831import * as SshTunnel from "./tunnel.ts" ;
2932
@@ -92,6 +95,73 @@ function commandArgs(command: ChildProcess.Command): ReadonlyArray<string> {
9295
9396const ARCHIVE = { archiveVersion : "1.2.3-preview.20260911.4" } as const ;
9497
98+ // Emulates `t3 serve`: it takes the home owner lock at startup, then binds
99+ // once a second server has tried the same home (or after 2s), so a concurrent
100+ // launch always sees the home still unclaimed. Like the real server, it
101+ // publishes server-runtime.json after it starts answering HTTP, if at all.
102+ const fakeT3Serve = ( publishDelayMs : number | null ) => `const fs = require("node:fs");
103+ const http = require("node:http");
104+ const path = require("node:path");
105+ const args = process.argv.slice(2);
106+ const port = Number(args[args.indexOf("--port") + 1]);
107+ const userdata = path.join(args[args.indexOf("--base-dir") + 1], "userdata");
108+ const servers = path.join(process.env.HOME, "servers");
109+ fs.mkdirSync(userdata, { recursive: true });
110+ fs.appendFileSync(servers, process.pid + "\\n");
111+ try {
112+ fs.writeFileSync(path.join(userdata, "server.lock"), String(process.pid), { flag: "wx" });
113+ } catch {
114+ console.error("ServerAlreadyRunningError: another server owns " + userdata);
115+ process.exit(1);
116+ }
117+ setTimeout(() => process.exit(0), 60_000);
118+ const serve = (tries) => {
119+ if (tries > 0 && fs.readFileSync(servers, "utf8").trim().split("\\n").length < 2) {
120+ setTimeout(() => serve(tries - 1), 50);
121+ return;
122+ }
123+ http.createServer((_, response) => response.end()).listen(port, "127.0.0.1", () => {
124+ const origin = "http://127.0.0.1:" + port;
125+ ${ publishDelayMs === null ? "return;" : "" }
126+ setTimeout(() => {
127+ fs.writeFileSync(path.join(userdata, "server-runtime.json"), JSON.stringify({ pid: process.pid, port, origin }));
128+ }, ${ publishDelayMs } );
129+ });
130+ };
131+ serve(40);
132+ ` ;
133+
134+ // Runs the remote half of an SSH command (`sh -l -s -- <key>`) as a local shell
135+ // whose HOME is the given directory. Every launch after the first starts once
136+ // a server is running (or after 10s), which lines up the race deterministically.
137+ const localRemoteShellLayer = ( home : string ) =>
138+ Layer . effect (
139+ ChildProcessSpawner . ChildProcessSpawner ,
140+ Effect . gen ( function * ( ) {
141+ const spawner = yield * ChildProcessSpawner . ChildProcessSpawner ;
142+ let launches = 0 ;
143+ return ChildProcessSpawner . make ( ( command ) => {
144+ if ( command . _tag !== "StandardCommand" ) return spawner . spawn ( command ) ;
145+ const gate =
146+ launches ++ === 0
147+ ? ""
148+ : 'i=0; while [ ! -s "$HOME/servers" ] && [ "$i" -lt 200 ]; do sleep 0.05; i=$((i+1)); done; ' ;
149+ return spawner . spawn (
150+ ChildProcess . make (
151+ "sh" ,
152+ [ "-c" , `${ gate } exec sh -s -- "$1"` , "sh" , ...commandArgs ( command ) . slice ( - 1 ) ] ,
153+ {
154+ ...command . options ,
155+ env : { ...command . options . env , HOME : home } ,
156+ // Like an SSH session ending, the shell's exit leaves its nohup'd server running.
157+ detached : false ,
158+ } ,
159+ ) ,
160+ ) ;
161+ } ) ;
162+ } ) ,
163+ ) ;
164+
95165describe ( "ssh tunnel scripts" , ( ) => {
96166 it ( "rejects archive versions that are not a single exact version segment" , ( ) => {
97167 for ( const archiveVersion of [
@@ -630,6 +700,74 @@ describe("ssh tunnel scripts", () => {
630700 ) ;
631701 } ) ,
632702 ) ;
703+
704+ it . live ( "concurrent launches on one remote home record the server that owns it" , ( ) =>
705+ // The second row's server never publishes server-runtime.json.
706+ Effect . forEach ( [ 1_500 , null ] , ( publishDelayMs ) =>
707+ Effect . gen ( function * ( ) {
708+ const fs = yield * FileSystem . FileSystem ;
709+ const path = yield * Path . Path ;
710+ const home = yield * fs . makeTempDirectoryScoped ( { prefix : "t3-ssh-launch-" } ) ;
711+ const serversFile = path . join ( home , "servers" ) ;
712+ yield * Effect . addFinalizer ( ( ) =>
713+ fs . readFileString ( serversFile ) . pipe (
714+ Effect . map ( ( pids ) => {
715+ for ( const pid of pids . split ( "\n" ) . filter ( Boolean ) ) {
716+ try {
717+ process . kill ( Number ( pid ) , "SIGKILL" ) ;
718+ } catch { }
719+ }
720+ } ) ,
721+ Effect . ignore ,
722+ ) ,
723+ ) ;
724+ const serverScript = path . join ( home , "fake-t3.cjs" ) ;
725+ yield * fs . writeFileString ( serverScript , fakeT3Serve ( publishDelayMs ) ) ;
726+ // A launch that died holding the lock must not block or double-admit later ones.
727+ const launchLock = path . join ( home , ".t3" , "ssh-launch" , ".launch.lock" ) ;
728+ yield * fs . makeDirectory ( path . dirname ( launchLock ) , { recursive : true } ) ;
729+ yield * fs . writeFileString ( launchLock , "999999999\n" ) ;
730+ const targets = [
731+ { alias : "devbox" , hostname : "devbox" , username : null , port : null } ,
732+ { alias : "devbox-tailnet" , hostname : "devbox-tailnet" , username : null , port : null } ,
733+ ] ;
734+
735+ const launches = yield * Effect . forEach (
736+ targets ,
737+ ( target ) =>
738+ SshTunnel . launchOrReuseRemoteServer ( target , undefined , {
739+ nodeScriptPath : serverScript ,
740+ } ) ,
741+ { concurrency : "unbounded" } ,
742+ ) . pipe ( Effect . provide ( localRemoteShellLayer ( home ) ) ) ;
743+
744+ const ownerPid = Number (
745+ yield * fs . readFileString ( path . join ( home , ".t3" , "userdata" , "server.lock" ) ) ,
746+ ) ;
747+ assert . sameMembers (
748+ launches . map ( ( launch ) => launch . remoteServerKind ) ,
749+ [ "managed" , "external" ] ,
750+ ) ;
751+ assert . equal ( launches [ 0 ] ! . remotePort , launches [ 1 ] ! . remotePort ) ;
752+ assert . deepEqual ( ( yield * fs . readFileString ( serversFile ) ) . trim ( ) . split ( "\n" ) , [
753+ String ( ownerPid ) ,
754+ ] ) ;
755+ for ( const [ index , launch ] of launches . entries ( ) ) {
756+ if ( launch . remoteServerKind !== "managed" ) continue ;
757+ const stateKey = yield * remoteStateKey ( targets [ index ] ! ) ;
758+ const recordedPid = yield * fs . readFileString (
759+ path . join ( home , ".t3" , "ssh-launch" , stateKey , "pid" ) ,
760+ ) ;
761+ assert . equal (
762+ Number ( recordedPid . trim ( ) ) ,
763+ ownerPid ,
764+ `${ targets [ index ] ! . alias } reported a managed server, but its recorded PID is not the server that owns the remote home` ,
765+ ) ;
766+ }
767+ assert . isFalse ( yield * fs . exists ( launchLock ) ) ;
768+ } ) . pipe ( Effect . scoped ) ,
769+ ) . pipe ( Effect . provide ( Layer . mergeAll ( NodeServices . layer , NodeCrypto . layer ) ) ) ,
770+ ) ;
633771} ) ;
634772
635773// On macOS, Node can bind 127.0.0.1:<port> while another process (such as the
0 commit comments