Skip to content
TypeScript

fix(cli): t3 connect unlink no longer warns about a server that is gone (#30324)

MarcoDotIO0bf1c9d076c8
diff --git a/apps/server/src/cli/connect.test.ts b/apps/server/src/cli/connect.test.ts
index 6693d214fab..a524ab8ddea 100644
--- a/apps/server/src/cli/connect.test.ts
+++ b/apps/server/src/cli/connect.test.ts
@@ -1,8 +1,25 @@
+// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises the Node HTTP boundary.
+import * as NodeHttp from "node:http";
+
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import * as NetService from "@t3tools/shared/Net";
import * as RelayClient from "@t3tools/shared/relayClient";
import { assert, it } from "@effect/vitest";
+import * as ConfigProvider from "effect/ConfigProvider";
+import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
+import * as TestConsole from "effect/testing/TestConsole";
+import { Command } from "effect/cli";
+import { makeCli } from "../binCli.ts";
+import {
+ makePersistedServerRuntimeState,
+ persistServerRuntimeState,
+} from "../serverRuntimeState.ts";
import { acquireRelayClientForLink } from "./connect.ts";
const managedExecutable = {
@@ -40,3 +57,108 @@ it.effect("does not install the relay client when the user declines the managed
assert.equal(installCalls, 0);
}),
);
+
+it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))(
+ "t3 connect unlink",
+ (it) => {
+ const runUnlink = (recordedPid: number, options?: { readonly portFreed?: boolean }) =>
+ Effect.gen(function* () {
+ const requests: Array<string> = [];
+ const warnings: Array<string> = [];
+ const server = yield* Effect.acquireRelease(
+ Effect.callback<NodeHttp.Server>((resume) => {
+ const listening = NodeHttp.createServer((request, response) => {
+ requests.push(`${request.method} ${request.url}`);
+ response.writeHead(200, { "content-type": "application/json" });
+ response.end(JSON.stringify({ ok: true, endpointRuntimeStatus: null }));
+ });
+ listening.listen(0, "127.0.0.1", () => resume(Effect.succeed(listening)));
+ }),
+ (listening) => Effect.sync(() => listening.close()),
+ );
+ const address = server.address();
+ if (address === null || typeof address === "string") {
+ return yield* Effect.die(new Error("Expected a TCP address"));
+ }
+ if (options?.portFreed) {
+ yield* Effect.callback<void>((resume) => {
+ server.close(() => resume(Effect.void));
+ });
+ }
+
+ const fs = yield* FileSystem.FileSystem;
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-connect-unlink-test-" });
+ const state = yield* makePersistedServerRuntimeState({
+ config: { host: "127.0.0.1", devUrl: undefined },
+ port: address.port,
+ });
+ yield* persistServerRuntimeState({
+ path: `${baseDir}/userdata/server-runtime.json`,
+ state: { ...state, pid: recordedPid },
+ });
+
+ yield* Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([
+ "connect",
+ "unlink",
+ "--base-dir",
+ baseDir,
+ ]).pipe(
+ // TestConsole has no reader for Console.warn.
+ Effect.updateService(Console.Console, (console) => ({
+ ...console,
+ warn: (...args: ReadonlyArray<unknown>) => {
+ warnings.push(args.join(" "));
+ },
+ })),
+ );
+
+ return { requests, warnings, printed: (yield* TestConsole.logLines).join("\n") };
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(
+ Layer.mergeAll(
+ ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
+ Layer.fresh(TestConsole.layer),
+ ),
+ ),
+ );
+
+ // Above Linux's PID ceiling, as in pair.test.ts: no process can hold it.
+ const deadPid = 4_194_305;
+
+ it.effect("does not tell the user to restart a server that is gone", () =>
+ Effect.gen(function* () {
+ const { printed, warnings } = yield* runUnlink(deadPid, { portFreed: true });
+
+ assert.include(printed, "T3 Connect is disabled locally.");
+ assert.notInclude(warnings.join("\n"), "Restart that server");
+ }),
+ );
+
+ it.effect("warns that a server that is gone may have left its connector running", () =>
+ Effect.gen(function* () {
+ const { warnings } = yield* runUnlink(deadPid, { portFreed: true });
+
+ assert.include(warnings.join("\n"), "its cloudflared process may still be running");
+ }),
+ );
+
+ it.effect("does not send a token to whatever took over a dead server's port", () =>
+ Effect.gen(function* () {
+ const { requests } = yield* runUnlink(deadPid);
+
+ assert.deepEqual(requests, []);
+ }),
+ );
+
+ it.effect("asks a running server to stop its tunnel", () =>
+ Effect.gen(function* () {
+ const { requests, printed, warnings } = yield* runUnlink(process.pid);
+
+ assert.deepEqual(requests, ["POST /api/connect/unlink"]);
+ assert.include(printed, "T3 Connect is disabled locally.");
+ assert.notInclude(warnings.join("\n"), "cloudflared process");
+ }),
+ );
+ },
+);
diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts
index 0c706d76e4b..5145429e304 100644
--- a/apps/server/src/cli/connect.ts
+++ b/apps/server/src/cli/connect.ts
@@ -50,7 +50,7 @@ import * as RelayTracing from "../cloud/relayTracing.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ExternalLauncher from "../process/externalLauncher.ts";
-import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
+import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
import { resolveCliCommand } from "./invocation.ts";
import * as CliService from "./service.ts";
@@ -298,6 +298,7 @@ const withCloudCliSessionToken = <A, E, R>(
type LiveCloudActionResult =
| { readonly status: "not-running" }
+ | { readonly status: "server-gone" }
| { readonly status: "succeeded" }
| { readonly status: "failed"; readonly cause: Cause.Cause<unknown> };
@@ -307,6 +308,10 @@ const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
if (Option.isNone(runtimeState)) {
return { status: "not-running" } satisfies LiveCloudActionResult;
}
+ // A killed server leaves its record behind, and another process may own its port by now.
+ if (!isProcessAlive(runtimeState.value.pid)) {
+ return { status: "server-gone" } satisfies LiveCloudActionResult;
+ }
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const result = yield* Effect.exit(
@@ -458,6 +463,12 @@ const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_resu
);
} else {
yield* Console.log("T3 Connect is disabled locally.");
+ // A killed server cannot stop the connector it started, and nothing adopts it on restart.
+ if (input.liveResult.status === "server-gone") {
+ yield* Console.warn(
+ "The server that ran T3 Connect is gone, but its cloudflared process may still be running.\nStop that process if it is.",
+ );
+ }
}
if (Exit.isFailure(input.relayResult)) {