fix(ssh): report remote stop failures without losing ownership (#10105)

This commit is contained in:
Theo Browne authored and GitHub committed 2026-09-06 02:15:49 -07:00
1 parent f66cfe2219
commit 60e6fa30c3
3 files changed
+431 -181

No files matched your search

+124 -1
View File
@@ -11,7 +11,7 @@ import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as NodeNet from "node:net";
import { buildRemoteT3RunnerScript } from "./tunnel.ts";
import { buildRemoteStopScript, buildRemoteT3RunnerScript } from "./tunnel.ts";
const Started = Schema.Struct({
pid: Schema.Number,
@@ -166,6 +166,129 @@ if (args.includes("--package")) {
},
);
describe.skipIf(HostProcessPlatform.defaultValue() === "win32")(
"remote stop process ownership",
() => {
it.live.each(["graceful", "timeout", "external"] as const)(
"confirms the stop result for a %s server",
(mode) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3-stop-" });
const signalPath = path.join(fixture, "signals");
const child = yield* spawner.spawn(
ChildProcess.make(
process.execPath,
[
"--input-type=module",
"-e",
`import * as fs from "node:fs";
import * as net from "node:net";
const server = net.createServer((socket) => socket.end());
let signals = 0;
process.on("SIGTERM", () => {
fs.writeFileSync(process.argv[2], String(++signals));
if (process.argv[1] !== "timeout" || signals > 1) server.close();
});
server.listen(0, "127.0.0.1", () => {
process.stdout.write(JSON.stringify({ pid: process.pid, port: server.address().port, args: [] }) + "\\n");
});
`,
mode,
signalPath,
],
{ cwd: fixture, detached: false },
),
);
// A failed assertion must still stop this captured fixture process.
yield* Effect.addFinalizer(() =>
child.kill({ killSignal: "SIGKILL" }).pipe(Effect.ignore),
);
const started = decodeStarted(
yield* child.stdout.pipe(
Stream.decodeText(),
Stream.splitLines,
Stream.take(1),
Stream.mkString,
),
);
assert.equal(started.pid, child.pid);
const savedState = {
pid: `${child.pid}\n`,
port: `${started.port}\n`,
managed: mode === "external" ? "external\n" : "managed\n",
};
for (const [name, contents] of Object.entries(savedState)) {
yield* fs.writeFileString(path.join(fixture, name), contents);
}
const script = buildRemoteStopScript({
alias: "fixture",
hostname: "fixture",
username: null,
port: null,
});
// Redirect only the state directory. Never use the developer's SSH state.
const isolatedScript = script.replace(
/^STATE_DIR=.*$/mu,
'STATE_DIR="$T3_TEST_STATE_DIR"',
);
assert.notEqual(isolatedScript, script);
const runStop = Effect.fn("test.remoteStop")(function* () {
const stop = yield* spawner.spawn(
ChildProcess.make("/bin/sh", ["-s"], {
cwd: fixture,
env: { T3_TEST_STATE_DIR: fixture },
stdin: Stream.make(new TextEncoder().encode(isolatedScript)),
}),
);
return yield* Effect.all(
{
stdout: stop.stdout.pipe(Stream.decodeText(), Stream.mkString),
stderr: stop.stderr.pipe(Stream.decodeText(), Stream.mkString),
exitCode: stop.exitCode,
},
{ concurrency: "unbounded" },
);
}, Effect.scoped);
let result = yield* runStop();
if (mode !== "graceful") {
assert.isTrue(yield* child.isRunning);
yield* Effect.callback<void, Error>((resume) => {
const connection = NodeNet.connect(started.port, "127.0.0.1");
connection.once("error", (error) => resume(Effect.fail(error)));
connection.once("close", () => resume(Effect.void));
return Effect.sync(() => connection.destroy());
});
}
if (mode === "timeout") {
assert.equal(result.exitCode, 1);
assert.equal(result.stdout, "");
assert.include(result.stderr, "did not stop within 2 seconds");
assert.equal(yield* fs.readFileString(signalPath), "1");
for (const [name, contents] of Object.entries(savedState)) {
assert.equal(yield* fs.readFileString(path.join(fixture, name)), contents);
}
result = yield* runStop();
}
assert.equal(result.exitCode, 0);
assert.equal(result.stdout, '{"stopped":true}\n');
assert.equal(result.stderr, "");
for (const name of Object.keys(savedState)) {
assert.isFalse(yield* fs.exists(path.join(fixture, name)));
}
if (mode === "external") {
assert.isFalse(yield* fs.exists(signalPath));
} else {
assert.equal(yield* child.exitCode, 0);
assert.equal(yield* fs.readFileString(signalPath), mode === "timeout" ? "2" : "1");
}
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
},
);
describe.skipIf(HostProcessPlatform.defaultValue() === "win32")(
"remote runner install diagnostics",
() => {
+201 -57
View File
@@ -1,6 +1,7 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NetService from "@t3tools/shared/Net";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -13,6 +14,7 @@ import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { SshPasswordPrompt } from "./auth.ts";
import { SshCommandError } from "./errors.ts";
import {
buildRemoteLaunchScript,
buildRemotePairingScript,
@@ -384,63 +386,205 @@ describe("ssh tunnel scripts", () => {
}).pipe(Effect.provide(processLayer));
});
it.effect("closes the tunnel scope and starts fresh after disconnect", () => {
const spawnedCommands: Array<ReadonlyArray<string>> = [];
let tunnelKillCount = 0;
let stopCommandCount = 0;
const spawner = ChildProcessSpawner.make((command) =>
Effect.sync(() => {
const args = commandArgs(command);
spawnedCommands.push(args);
if (args.includes("-N")) {
return makeRunningProcess(() => {
tunnelKillCount += 1;
it.effect.each(["successful stop", "failed stop"] as const)(
"closes the tunnel scope and starts fresh after a %s",
(mode) => {
const spawnedCommands: Array<ReadonlyArray<string>> = [];
let tunnelKillCount = 0;
let stopCommandCount = 0;
const spawner = ChildProcessSpawner.make((command) =>
Effect.sync(() => {
const args = commandArgs(command);
spawnedCommands.push(args);
if (args.includes("-N")) {
return makeRunningProcess(() => {
tunnelKillCount += 1;
});
}
if (args.includes("sh") && args.includes("--")) {
return makeSuccessfulProcess('{"remotePort":3773}\n');
}
if (args.includes("sh")) {
stopCommandCount += 1;
if (mode === "failed stop" && stopCommandCount === 1) {
return {
...makeSuccessfulProcess(""),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
stderr: Stream.make(
new TextEncoder().encode("Remote T3 server did not stop within 2 seconds.\n"),
),
};
}
return makeSuccessfulProcess('{"stopped":true}\n');
}
return makeSuccessfulProcess("\n");
}),
);
const layer = Layer.mergeAll(
NodeServices.layer,
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
Layer.succeed(HttpClient.HttpClient, testHttpClient),
Layer.succeed(NetService.NetService, testNetService),
SshPasswordPrompt.disabledLayer,
SshEnvironmentManager.layer(),
);
const target = {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
} as const;
return Effect.gen(function* () {
const manager = yield* SshEnvironmentManager;
const first = yield* manager.ensureEnvironment(target);
assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
const firstTunnelArgs = spawnedCommands.find((args) => args.includes("-N"));
assert.isDefined(firstTunnelArgs);
assert.include(firstTunnelArgs, "ControlMaster=no");
assert.include(firstTunnelArgs, "ControlPath=none");
assert.include(firstTunnelArgs, "ControlPersist=no");
const disconnected = yield* Effect.result(manager.disconnectEnvironment(target));
if (mode === "failed stop") {
assert.isTrue(Result.isFailure(disconnected));
if (Result.isFailure(disconnected)) {
assert.instanceOf(disconnected.failure, SshCommandError);
assert.equal(
disconnected.failure.message,
"Remote T3 server did not stop within 2 seconds.",
);
}
} else {
assert.isTrue(Result.isSuccess(disconnected));
}
assert.equal(tunnelKillCount, 1);
assert.equal(stopCommandCount, 1);
if (mode === "failed stop") {
yield* manager.disconnectEnvironment(target);
assert.equal(tunnelKillCount, 1);
assert.equal(stopCommandCount, 2);
}
yield* manager.ensureEnvironment(target);
assert.equal(spawnedCommands.filter((args) => args.includes("-N")).length, 2);
assert.equal(tunnelKillCount, 1);
}).pipe(
Effect.provide(layer),
Effect.scoped,
Effect.andThen(
Effect.sync(() => {
assert.equal(tunnelKillCount, 2);
assert.equal(stopCommandCount, mode === "failed stop" ? 3 : 2);
}),
),
);
},
);
it.effect.each(["local tunnel", "remote server"] as const)(
"waits for %s shutdown before reconnecting the same target",
(stalledStep) =>
Effect.gen(function* () {
const shutdownStarted = yield* Deferred.make<void>();
const finishShutdown = yield* Deferred.make<void>();
const reconnectsStarted = yield* Deferred.make<void>();
const pauseShutdown = Deferred.succeed(shutdownStarted, undefined).pipe(
Effect.andThen(Deferred.await(finishShutdown)),
);
let resolutions = 0;
let launches = 0;
let tunnels = 0;
let stops = 0;
let remoteRunning = false;
const target = { alias: "devbox", hostname: "devbox", username: null, port: null };
const spawner = ChildProcessSpawner.make((command) =>
Effect.gen(function* () {
const args = commandArgs(command);
const isTarget = args.includes(target.alias);
if (args.includes("-G")) {
if (isTarget && ++resolutions === 4) {
yield* Deferred.succeed(reconnectsStarted, undefined);
}
return makeSuccessfulProcess("");
}
if (args.includes("-N")) {
const tunnel = makeRunningProcess(() => undefined);
if (isTarget && ++tunnels === 1 && stalledStep === "local tunnel") {
return {
...tunnel,
kill: (options?: ChildProcess.KillOptions) =>
pauseShutdown.pipe(Effect.andThen(tunnel.kill(options))),
};
}
return tunnel;
}
if (args.includes("--")) {
if (isTarget) {
launches += 1;
remoteRunning = true;
}
return makeSuccessfulProcess('{"remotePort":3773}\n');
}
const stop = makeSuccessfulProcess('{"stopped":true}\n');
if (!isTarget) return stop;
const pause = ++stops === 1 && stalledStep === "remote server";
return {
...stop,
exitCode: (pause ? pauseShutdown : Effect.void).pipe(
Effect.andThen(
Effect.sync(() => {
remoteRunning = false;
return ChildProcessSpawner.ExitCode(0);
}),
),
),
};
}),
);
const layer = Layer.mergeAll(
NodeServices.layer,
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
Layer.succeed(HttpClient.HttpClient, testHttpClient),
Layer.succeed(NetService.NetService, testNetService),
SshPasswordPrompt.disabledLayer,
SshEnvironmentManager.layer(),
);
yield* Effect.gen(function* () {
const manager = yield* SshEnvironmentManager;
yield* manager.ensureEnvironment(target);
const disconnect = yield* Effect.forkChild(manager.disconnectEnvironment(target));
yield* Deferred.await(shutdownStarted);
const firstReconnect = yield* Effect.forkChild(manager.ensureEnvironment(target));
const secondReconnect = yield* Effect.forkChild(manager.ensureEnvironment(target));
yield* Deferred.await(reconnectsStarted);
yield* manager.ensureEnvironment({
alias: "other",
hostname: "other",
username: null,
port: null,
});
}
if (args.includes("sh") && args.includes("--")) {
return makeSuccessfulProcess('{"remotePort":3773}\n');
}
if (args.includes("sh")) {
stopCommandCount += 1;
return makeSuccessfulProcess('{"stopped":true}\n');
}
return makeSuccessfulProcess("\n");
yield* TestClock.adjust(Duration.zero);
const launchesBeforeShutdown = launches;
yield* Deferred.succeed(finishShutdown, undefined);
yield* Fiber.join(disconnect);
const first = yield* Fiber.join(firstReconnect);
const second = yield* Fiber.join(secondReconnect);
assert.equal(launchesBeforeShutdown, 1);
assert.equal(launches, 2);
assert.equal(tunnels, 2);
assert.isTrue(remoteRunning);
assert.equal(first.httpBaseUrl, second.httpBaseUrl);
}).pipe(
Effect.ensuring(Deferred.succeed(finishShutdown, undefined)),
Effect.provide(layer),
Effect.scoped,
);
}),
);
const layer = Layer.mergeAll(
NodeServices.layer,
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
Layer.succeed(HttpClient.HttpClient, testHttpClient),
Layer.succeed(NetService.NetService, testNetService),
SshPasswordPrompt.disabledLayer,
SshEnvironmentManager.layer(),
);
const target = {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
} as const;
return Effect.gen(function* () {
const manager = yield* SshEnvironmentManager;
const first = yield* manager.ensureEnvironment(target);
assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
const firstTunnelArgs = spawnedCommands.find((args) => args.includes("-N"));
assert.isDefined(firstTunnelArgs);
assert.include(firstTunnelArgs, "ControlMaster=no");
assert.include(firstTunnelArgs, "ControlPath=none");
assert.include(firstTunnelArgs, "ControlPersist=no");
yield* manager.disconnectEnvironment(target);
assert.equal(tunnelKillCount, 1);
assert.equal(stopCommandCount, 1);
yield* manager.ensureEnvironment(target);
assert.equal(spawnedCommands.filter((args) => args.includes("-N")).length, 2);
assert.equal(tunnelKillCount, 1);
}).pipe(Effect.provide(layer), Effect.scoped);
});
);
});
+106 -123
View File
@@ -10,7 +10,6 @@ import * as NetService from "@t3tools/shared/Net";
import { extractJsonObject, fromLenientJson } from "@t3tools/shared/schemaJson";
import { satisfiesSemverRange } from "@t3tools/shared/semver";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
@@ -18,6 +17,7 @@ import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
@@ -98,15 +98,6 @@ type SshEnvironmentEffectError =
| SshPasswordPromptError
| NetService.NetError;
function makeSshTunnelCancelledError(target: DesktopSshEnvironmentTarget): SshCommandError {
return new SshCommandError({
command: ["ssh"],
exitCode: null,
stderr: "",
message: `SSH environment connection was cancelled for ${target.alias || target.hostname}.`,
});
}
function sshTargetLogFields(target: DesktopSshEnvironmentTarget) {
return {
alias: target.alias,
@@ -642,6 +633,10 @@ if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ] && kill -0 "$REMO
WAIT_COUNT=$((WAIT_COUNT + 1))
sleep 0.1
done
if kill -0 "$REMOTE_PID" 2>/dev/null; then
printf 'Remote T3 server with PID %s did not stop within 2 seconds. Its ownership files were kept.\\n' "$REMOTE_PID" >&2
exit 1
fi
fi
rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"
printf '{"stopped":true}\\n'
@@ -1176,12 +1171,22 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
): Effect.fn.Return<SshEnvironmentManagerShape, never, Scope.Scope> {
const managerScope = yield* Scope.Scope;
const tunnels = new Map<string, SshTunnelEntry>();
const pendingTunnelEntries = new Map<
string,
Deferred.Deferred<SshTunnelEntry, SshEnvironmentEffectError>
>();
const targetLocks = new Map<string, Semaphore.Semaphore>();
const authSecrets = new Map<string, string>();
// Keep one lock per target so reconnect cannot reuse a server while stop is pending.
const withTargetLock = Effect.fn("ssh/tunnel.withTargetLock")(function* <A, E, R>(
key: string,
effect: Effect.Effect<A, E, R>,
): Effect.fn.Return<A, E, R> {
let lock = targetLocks.get(key);
if (lock === undefined) {
lock = Semaphore.makeUnsafe(1);
targetLocks.set(key, lock);
}
return yield* lock.withPermits(1)(effect);
});
const closeTunnelEntry = Effect.fn("ssh/tunnel.closeTunnelEntry")(function* (
entry: SshTunnelEntry,
) {
@@ -1200,18 +1205,6 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
});
});
const cancelPendingTunnelEntry = Effect.fn("ssh/tunnel.cancelPendingTunnelEntry")(function* (
key: string,
target: DesktopSshEnvironmentTarget,
) {
const pending = pendingTunnelEntries.get(key);
if (!pending) {
return;
}
pendingTunnelEntries.delete(key);
yield* Deferred.fail(pending, makeSshTunnelCancelledError(target)).pipe(Effect.ignore);
});
yield* Scope.addFinalizer(
managerScope,
Effect.sync(() => [...tunnels.values()]).pipe(
@@ -1392,7 +1385,17 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
yield* Scope.addFinalizer(
entryScope,
Effect.gen(function* () {
if (tunnels.get(tunnelEntry.key) !== tunnelEntry) {
const stopRemote = tunnels.get(tunnelEntry.key) === tunnelEntry;
if (stopRemote) {
tunnels.delete(tunnelEntry.key);
}
yield* tunnelEntry.process
.kill({
killSignal: "SIGTERM",
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
})
.pipe(Effect.ignore);
if (!stopRemote) {
return;
}
yield* Effect.logDebug("ssh.environment.tunnel.finalizer.start", {
@@ -1401,34 +1404,24 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
localPort: tunnelEntry.localPort,
remotePort: tunnelEntry.remotePort,
});
tunnels.delete(tunnelEntry.key);
const authSecret = authSecrets.get(tunnelEntry.key) ?? null;
yield* Effect.all(
[
tunnelEntry.process.kill({
killSignal: "SIGTERM",
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
}),
stopRemoteServer(
tunnelEntry.target,
authSecret === null
? {
batchMode: "yes",
interactiveAuth: false,
}
: {
authSecret,
batchMode: "no",
interactiveAuth: true,
},
).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawnerService),
Effect.provideService(FileSystem.FileSystem, fileSystemService),
Effect.provideService(Path.Path, pathService),
),
],
{ concurrency: "unbounded" },
).pipe(Effect.ignore);
yield* stopRemoteServer(
tunnelEntry.target,
authSecret === null
? {
batchMode: "yes",
interactiveAuth: false,
}
: {
authSecret,
batchMode: "no",
interactiveAuth: true,
},
).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawnerService),
Effect.provideService(FileSystem.FileSystem, fileSystemService),
Effect.provideService(Path.Path, pathService),
);
yield* Effect.logDebug("ssh.environment.tunnel.finalizer.succeeded", {
...sshTargetLogFields(tunnelEntry.target),
key: tunnelEntry.key,
@@ -1451,7 +1444,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
resolvedTarget: DesktopSshEnvironmentTarget,
runner?: RemoteT3RunnerOptions,
): Effect.fn.Return<SshTunnelEntry, SshEnvironmentEffectError, SshEnvironmentEffectContext> {
let entry = tunnels.get(key) ?? null;
const entry = tunnels.get(key) ?? null;
if (entry !== null) {
yield* Effect.logDebug("ssh.environment.tunnel.existing.check", {
@@ -1480,22 +1473,8 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
cause: readinessExit.cause,
});
yield* closeTunnelEntry(entry);
yield* cancelPendingTunnelEntry(key, resolvedTarget);
entry = null;
}
const pending = pendingTunnelEntries.get(key);
if (pending) {
yield* Effect.logDebug("ssh.environment.tunnel.pending.await", {
...sshTargetLogFields(resolvedTarget),
key,
});
return yield* Deferred.await(pending);
}
const deferred = yield* Deferred.make<SshTunnelEntry, SshEnvironmentEffectError>();
pendingTunnelEntries.set(key, deferred);
return yield* createTunnelEntry({
key,
resolvedTarget,
@@ -1508,13 +1487,6 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
cause,
}),
),
Effect.onExit((exit) =>
Effect.sync(() => {
if (pendingTunnelEntries.get(key) === deferred) {
pendingTunnelEntries.delete(key);
}
}).pipe(Effect.andThen(Deferred.done(deferred, exit))),
),
);
});
@@ -1553,33 +1525,39 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
...sshRunnerLogFields(runner),
key,
});
const entry = yield* ensureTunnelEntry(key, resolvedTarget, runner);
const pairingResult = requestOptions?.issuePairingToken
? yield* runWithSshAuth({
key,
target: entry.target,
operation: (authOptions) => issueRemotePairingToken(entry.target, authOptions, runner),
})
: null;
const pairingToken = pairingResult?.credential ?? null;
yield* Effect.logInfo("ssh.environment.ensure.succeeded", {
...sshTargetLogFields(entry.target),
return yield* withTargetLock(
key,
localPort: entry.localPort,
remotePort: entry.remotePort,
remoteServerKind: entry.remoteServerKind,
issuedPairingToken: pairingToken !== null,
});
return {
target: entry.target,
httpBaseUrl: entry.httpBaseUrl,
wsBaseUrl: entry.wsBaseUrl,
pairingToken,
remotePort: entry.remotePort,
...(entry.remoteServerKind ? { remoteServerKind: entry.remoteServerKind } : {}),
};
Effect.gen(function* () {
const entry = yield* ensureTunnelEntry(key, resolvedTarget, runner);
const pairingResult = requestOptions?.issuePairingToken
? yield* runWithSshAuth({
key,
target: entry.target,
operation: (authOptions) =>
issueRemotePairingToken(entry.target, authOptions, runner),
})
: null;
const pairingToken = pairingResult?.credential ?? null;
yield* Effect.logInfo("ssh.environment.ensure.succeeded", {
...sshTargetLogFields(entry.target),
key,
localPort: entry.localPort,
remotePort: entry.remotePort,
remoteServerKind: entry.remoteServerKind,
issuedPairingToken: pairingToken !== null,
});
return {
target: entry.target,
httpBaseUrl: entry.httpBaseUrl,
wsBaseUrl: entry.wsBaseUrl,
pairingToken,
remotePort: entry.remotePort,
...(entry.remoteServerKind ? { remoteServerKind: entry.remoteServerKind } : {}),
};
}),
);
});
const disconnectEnvironment = Effect.fn("ssh/tunnel.disconnectEnvironment")(function* (
@@ -1593,28 +1571,33 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
...(target.port !== null ? { port: target.port } : {}),
};
const key = targetConnectionKey(resolvedTarget);
const entry = tunnels.get(key) ?? null;
yield* Effect.logDebug("ssh.environment.disconnect.targetResolved", {
...sshTargetLogFields(resolvedTarget),
yield* withTargetLock(
key,
hasTunnel: entry !== null,
hasPendingTunnel: pendingTunnelEntries.has(key),
});
if (entry !== null) {
yield* closeTunnelEntry(entry);
}
yield* cancelPendingTunnelEntry(key, resolvedTarget);
if (entry === null) {
yield* runWithSshAuth({
key,
target: resolvedTarget,
operation: (authOptions) => stopRemoteServer(resolvedTarget, authOptions),
});
}
yield* Effect.logInfo("ssh.environment.disconnect.succeeded", {
...sshTargetLogFields(resolvedTarget),
key,
});
Effect.gen(function* () {
const entry = tunnels.get(key) ?? null;
yield* Effect.logDebug("ssh.environment.disconnect.targetResolved", {
...sshTargetLogFields(resolvedTarget),
key,
hasTunnel: entry !== null,
});
if (entry !== null) {
// Explicit disconnect owns the remote stop so its failure reaches the caller.
yield* Effect.gen(function* () {
tunnels.delete(key);
yield* closeTunnelEntry(entry);
}).pipe(Effect.uninterruptible);
}
yield* runWithSshAuth({
key,
target: resolvedTarget,
operation: (authOptions) => stopRemoteServer(resolvedTarget, authOptions),
});
yield* Effect.logInfo("ssh.environment.disconnect.succeeded", {
...sshTargetLogFields(resolvedTarget),
key,
});
}),
);
});
return SshEnvironmentManager.of({ ensureEnvironment, disconnectEnvironment });