Skip to content

Commit 1ea9e7e

Browse files
PR Batch TesterGooder24claude
committed
fix(ssh): renaming an SSH connection no longer strands its remote server on an old version
Editing a connection's alias, host, user, or port gives it a new launcher state key. The new key found the server the old key had launched and adopted it as external, so desktop updates never replaced it. The launcher now takes over the other key's managed record instead, and compares against that key's runner to decide whether the launch is an update. Fixes #24095 Co-authored-by: Karchi <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c58d558 commit 1ea9e7e

2 files changed

Lines changed: 136 additions & 1 deletion

File tree

‎packages/ssh/src/tunnel.test.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import { assert, describe, it } from "@effect/vitest";
22
import * as NodeServices from "@effect/platform-node/NodeServices";
3+
import * as HostProcess from "@t3tools/shared/HostProcess";
34
import * as NetService from "@t3tools/shared/Net";
45
import * as Deferred from "effect/Deferred";
56
import * as Duration from "effect/Duration";
67
import * as Effect from "effect/Effect";
78
import * as Fiber from "effect/Fiber";
9+
import * as FileSystem from "effect/FileSystem";
810
import * as Layer from "effect/Layer";
911
import * as PlatformError from "effect/PlatformError";
1012
import * as Result from "effect/Result";
@@ -368,3 +370,107 @@ describe("ssh tunnel scripts", () => {
368370
// desktop app with network access on) listens on *:<port>. Linux refuses that
369371
// bind unless both sockets set SO_REUSEPORT, so on Linux the preload adds it to
370372
// the picker's probe and the holder sets it too.
373+
374+
describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("launch script", () => {
375+
// Stands in for `t3 serve`: answers HTTP and writes the default home's runtime file.
376+
const FAKE_SERVER = `const fs = require("node:fs");
377+
const http = require("node:http");
378+
const path = require("node:path");
379+
const args = process.argv.slice(2);
380+
const flag = (name) => args[args.indexOf(name) + 1];
381+
const server = http.createServer((_request, response) => response.end("ok"));
382+
server.listen(Number(flag("--port")), "127.0.0.1", () => {
383+
const port = server.address().port;
384+
const userdata = path.join(flag("--base-dir"), "userdata");
385+
fs.mkdirSync(userdata, { recursive: true });
386+
fs.writeFileSync(
387+
path.join(userdata, "server-runtime.json"),
388+
JSON.stringify({ version: 1, pid: process.pid, port, origin: "http://127.0.0.1:" + port }),
389+
);
390+
});
391+
`;
392+
393+
const isAlive = (pid: number) => {
394+
try {
395+
process.kill(pid, 0);
396+
return true;
397+
} catch {
398+
return false;
399+
}
400+
};
401+
402+
const prepareLaunch = Effect.gen(function* () {
403+
const fs = yield* FileSystem.FileSystem;
404+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
405+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launch-script-" });
406+
const home = `${root}/home`;
407+
const fakeServer = `${root}/fake-t3.cjs`;
408+
const launchScript = `${root}/launch.sh`;
409+
yield* fs.makeDirectory(home);
410+
yield* fs.writeFileString(fakeServer, FAKE_SERVER);
411+
yield* fs.writeFileString(
412+
launchScript,
413+
SshTunnel.buildRemoteLaunchScript({ nodeScriptPath: fakeServer }),
414+
);
415+
const stateDir = (stateKey: string) => `${home}/.t3/ssh-launch/${stateKey}`;
416+
const readManagedPid = (stateKey: string) =>
417+
fs.readFileString(`${stateDir(stateKey)}/pid`).pipe(Effect.map((pid) => Number(pid.trim())));
418+
// Launched servers outlive the script.
419+
const launchedPids = new Set<number>();
420+
yield* Effect.addFinalizer(() =>
421+
Effect.sync(() => {
422+
for (const pid of launchedPids) {
423+
if (isAlive(pid)) process.kill(pid, "SIGKILL");
424+
}
425+
}),
426+
);
427+
const launch = (stateKey: string) =>
428+
Effect.gen(function* () {
429+
const child = yield* spawner.spawn(
430+
ChildProcess.make("sh", [launchScript, stateKey], {
431+
env: { PATH: process.env.PATH ?? "", HOME: home },
432+
extendEnv: false,
433+
}),
434+
);
435+
const [stdout, stderr, exitCode] = yield* Effect.all(
436+
[
437+
child.stdout.pipe(Stream.decodeText(), Stream.mkString),
438+
child.stderr.pipe(Stream.decodeText(), Stream.mkString),
439+
child.exitCode,
440+
],
441+
{ concurrency: "unbounded" },
442+
);
443+
assert.equal(exitCode, 0, stderr);
444+
const pid = yield* readManagedPid(stateKey).pipe(Effect.orElseSucceed(() => null));
445+
if (pid !== null) launchedPids.add(pid);
446+
return JSON.parse(stdout.trim().split("\n").at(-1) ?? "") as {
447+
remotePort: number;
448+
serverKind: string;
449+
};
450+
});
451+
return { fs, stateDir, readManagedPid, launch };
452+
});
453+
454+
it.live("keeps managing its server after the connection's state key changes", () =>
455+
Effect.gen(function* () {
456+
const { fs, stateDir, readManagedPid, launch } = yield* prepareLaunch;
457+
const launched = yield* launch("old-alias");
458+
assert.equal(launched.serverKind, "managed");
459+
const pid = yield* readManagedPid("old-alias");
460+
461+
assert.deepEqual(yield* launch("new-alias"), launched);
462+
assert.equal(yield* readManagedPid("new-alias"), pid);
463+
assert.isFalse(yield* fs.exists(`${stateDir("old-alias")}/managed`));
464+
assert.isTrue(isAlive(pid));
465+
466+
// The server came from new-alias's runner, so a different runner under
467+
// the next key is an update and replaces it.
468+
yield* fs.writeFileString(`${stateDir("new-alias")}/run-t3.sh`, "# previous runner\n");
469+
assert.equal((yield* launch("newer-alias")).serverKind, "managed");
470+
const replacementPid = yield* readManagedPid("newer-alias");
471+
assert.notEqual(replacementPid, pid);
472+
assert.isFalse(isAlive(pid));
473+
assert.isTrue(isAlive(replacementPid));
474+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
475+
);
476+
});

‎packages/ssh/src/tunnel.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -630,6 +630,19 @@ try {
630630
}
631631
NODE
632632
}
633+
# Editing a connection's alias, host, user, or port gives it a new state key,
634+
# while the server it launched keeps running from the default home. Prints the
635+
# other state directory that recorded PID $1 as managed.
636+
launcher_state_dir_for_pid() {
637+
for OTHER_STATE_DIR in "$HOME/.t3/ssh-launch"/*; do
638+
[ "$OTHER_STATE_DIR" != "$STATE_DIR" ] || continue
639+
[ "$(cat "$OTHER_STATE_DIR/managed" 2>/dev/null || true)" = "managed" ] || continue
640+
[ "$(cat "$OTHER_STATE_DIR/pid" 2>/dev/null || true)" = "$1" ] || continue
641+
printf '%s\\n' "$OTHER_STATE_DIR"
642+
return 0
643+
done
644+
return 1
645+
}
633646
REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)"
634647
REMOTE_PORT="$(cat "$PORT_FILE" 2>/dev/null || true)"
635648
REMOTE_MANAGED="$(cat "$MANAGED_FILE" 2>/dev/null || true)"
@@ -647,6 +660,22 @@ fi
647660
if [ -n "$DEFAULT_REMOTE_PORT" ] && [ "$REMOTE_MANAGED" = "managed" ] && [ "$DEFAULT_RUNTIME_PID" = "$REMOTE_PID" ]; then
648661
REMOTE_PORT="$DEFAULT_REMOTE_PORT"
649662
printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE"
663+
elif [ -n "$DEFAULT_REMOTE_PORT" ] && PREVIOUS_STATE_DIR="$(launcher_state_dir_for_pid "$DEFAULT_RUNTIME_PID")"; then
664+
# Adopting it as external would keep it on its old version through every
665+
# update. It runs the runner its previous state wrote, so that runner decides
666+
# whether this launch is an update.
667+
if cmp -s "$PREVIOUS_STATE_DIR/run-t3.sh" "$RUNNER_FILE"; then
668+
RUNNER_CHANGED=0
669+
else
670+
RUNNER_CHANGED=1
671+
fi
672+
REMOTE_PID="$DEFAULT_RUNTIME_PID"
673+
REMOTE_PORT="$DEFAULT_REMOTE_PORT"
674+
REMOTE_MANAGED="managed"
675+
printf '%s\\n' "$REMOTE_PID" >"$PID_FILE"
676+
printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE"
677+
printf 'managed\\n' >"$MANAGED_FILE"
678+
rm -f "$PREVIOUS_STATE_DIR/pid" "$PREVIOUS_STATE_DIR/managed"
650679
elif [ -n "$DEFAULT_REMOTE_PORT" ]; then
651680
REMOTE_PORT="$DEFAULT_REMOTE_PORT"
652681
if wait_ready "@@T3_REUSE_READY_TIMEOUT_MS@@"; then
@@ -836,7 +865,7 @@ export function buildRemoteNodeEnvScript(input?: RemoteT3RunnerOptions): string
836865
);
837866
}
838867

839-
function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string {
868+
export function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string {
840869
return applyScriptPlaceholders(REMOTE_LAUNCH_SCRIPT, {
841870
T3_ARCHIVE_MODE: isNodeScriptRunner(input) ? "0" : "1",
842871
T3_NODE_ENV_SCRIPT: buildRemoteNodeEnvScript(input),

0 commit comments

Comments
 (0)