diff --git a/crates/ide-dap/src/debugpy.rs b/crates/ide-dap/src/debugpy.rs index 3f4307df7c..ee6dced0e9 100644 --- a/crates/ide-dap/src/debugpy.rs +++ b/crates/ide-dap/src/debugpy.rs @@ -13,14 +13,24 @@ pub(crate) fn listens(adapter: &str, request: &str, arguments: &Value) -> bool { } /// debugpy's adapter leaves an `attach` whose port is taken unanswered (it only logs the error), -/// which would wait for the program forever: find out before starting it. -pub(crate) fn require_free_port(arguments: &Value) -> Result<(), IdeError> { +/// which would wait for the program forever: find out before starting it. Listening again right +/// after a program ended races the previous adapter, which still listens until its shutdown ends. +pub(crate) async fn require_free_port(arguments: &Value) -> Result<(), IdeError> { + // ponytail: polls; waiting on the previous session's shutdown would report a taken port sooner. + const RELEASE: Duration = Duration::from_secs(5); let listen = &arguments["listen"]; let host = listen["host"].as_str().unwrap_or("127.0.0.1"); let Some(port) = listen["port"].as_u64().and_then(|p| u16::try_from(p).ok()) else { return Ok(()) }; - std::net::TcpListener::bind((host, port)) - .map(drop) - .map_err(|e| IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}"))) + let deadline = tokio::time::Instant::now() + RELEASE; + loop { + match std::net::TcpListener::bind((host, port)) { + Ok(_) => return Ok(()), + Err(e) if tokio::time::Instant::now() >= deadline => { + return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}"))); + } + Err(_) => tokio::time::sleep(Duration::from_millis(100)).await, + } + } } /// On the program's first stop: warns in the Debug console when its debugpy is not the adapter's. @@ -63,15 +73,27 @@ mod tests { assert!(w.contains("debugpy 1.8.0") && w.ends_with("pip install debugpy==1.8.22\n"), "{w}"); } - #[test] - fn a_taken_port_is_reported_before_the_adapter_starts() { + #[tokio::test(start_paused = true)] + async fn a_taken_port_is_reported_before_the_adapter_starts() { let taken = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); let port = taken.local_addr().unwrap().port(); let listen = json!({"listen": {"host": "127.0.0.1", "port": port}}); - let e = require_free_port(&listen).unwrap_err(); + let e = require_free_port(&listen).await.unwrap_err(); assert!(e.to_string().contains(&format!("Cannot listen on 127.0.0.1:{port}")), "{e}"); drop(taken); - assert!(require_free_port(&listen).is_ok()); + assert!(require_free_port(&listen).await.is_ok()); + } + + #[tokio::test] + async fn waits_for_the_previous_adapter_to_release_the_port() { + let previous = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = previous.local_addr().unwrap().port(); + let released = tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(300)).await; + drop(previous); + }); + require_free_port(&json!({"listen": {"host": "127.0.0.1", "port": port}})).await.unwrap(); + released.await.unwrap(); } #[test] diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index ccb1e2571b..e1e16ba643 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -903,7 +903,7 @@ impl DebugManager { ) -> IdeResult { let mut arguments = launch_arguments(&config)?; if debugpy::listens(&config.adapter, &config.request, &arguments) { - debugpy::require_free_port(&arguments)?; + debugpy::require_free_port(&arguments).await?; } // An IDE-side marker (never sent to the adapter): the session is a Flutter // one regardless of what the working directory holds. diff --git a/crates/ide-run/src/import/vscode.rs b/crates/ide-run/src/import/vscode.rs index 3f4b7293cb..8f89fbfb9c 100644 --- a/crates/ide-run/src/import/vscode.rs +++ b/crates/ide-run/src/import/vscode.rs @@ -319,7 +319,12 @@ impl Cx<'_> { Some(listen) => ("python-debug-server", listen), None => ("python-remote", obj.get("connect").and_then(Value::as_object).unwrap_or(obj)), }; - let host = self.string(connect, "host")?.unwrap_or_else(|| "localhost".into()); + let mut host = self.string(connect, "host")?.unwrap_or_else(|| "localhost".into()); + // VS Code's `listen.host` is where the adapter binds; the configuration names the address the + // program connects to, which a wildcard is not: left at localhost for the user to change. + if kind == "python-debug-server" && matches!(host.as_str(), "0.0.0.0" | "::" | "[::]") { + host = "localhost".into(); + } let Some(port) = self.string(connect, "port")? else { return Err(SkipReason::UnsupportedAttach); }; diff --git a/crates/ide-run/tests/import_vscode.rs b/crates/ide-run/tests/import_vscode.rs index c2cf388578..96f8b56223 100644 --- a/crates/ide-run/tests/import_vscode.rs +++ b/crates/ide-run/tests/import_vscode.rs @@ -385,6 +385,8 @@ fn attach_requests_become_remote_debug_configurations() { "restart": { "delay": 500, "maxAttempts": 5 } }, { "name": "Attach to PID", "type": "debugpy", "request": "attach", "processId": "${command:pickProcess}" }, { "name": "Debug server", "type": "debugpy", "request": "attach", "listen": { "port": 5679 } }, + { "name": "Debug server (all interfaces)", "type": "debugpy", "request": "attach", + "listen": { "host": "0.0.0.0", "port": 5680 } }, { "name": "Odd", "type": "node", "request": "test" } ] }"#); @@ -394,6 +396,8 @@ fn attach_requests_become_remote_debug_configurations() { server.extras.params, BTreeMap::from([("host".into(), "localhost".into()), ("port".into(), "5679".into())]) ); + // The bind address is not one a program can connect to. + assert_eq!(get(&r, "Debug server (all interfaces)").extras.params["host"], "localhost"); let py = get(&r, "Attach (container)"); assert_eq!((py.kind.as_str(), py.command.as_str()), ("python-remote", "")); assert_eq!(py.debug_adapter.as_deref(), Some("debugpy")); diff --git a/src/features/debugger/__tests__/remote.test.ts b/src/features/debugger/__tests__/remote.test.ts index 3c21ae8c14..7298fc2048 100644 --- a/src/features/debugger/__tests__/remote.test.ts +++ b/src/features/debugger/__tests__/remote.test.ts @@ -167,7 +167,9 @@ describe("remote attach requests", () => { redirectOutput: true, justMyCode: expect.any(Boolean), }); - expect(listen({ host: "::1", port: "5679" }).listen).toEqual({ host: "127.0.0.1", port: 5679 }); + expect(listen({ host: "::1", port: "5679" }).listen).toEqual({ host: "::1", port: 5679 }); + expect(listen({ host: "127.0.0.2" }).listen.host).toBe("127.0.0.1"); + expect(listen({ host: "fd00::5" }).listen.host).toBe("::"); expect(listen({ host: "host.docker.internal", remoteRoot: "/app" })).toMatchObject({ listen: { host: "0.0.0.0", port: 5678 }, pathMappings: [{ localRoot: "/p", remoteRoot: "/app" }], @@ -181,6 +183,8 @@ describe("remote attach requests", () => { 'import debugpy; debugpy.connect(("host.docker.internal", 5679)); debugpy.wait_for_client()', ); expect(remote.debugpyConnectLine({ host: 'a"b' })).toContain('connect(("a\\"b", 5678))'); + // Python's connect takes an IPv6 address without brackets. + expect(remote.debugpyConnectLine({ host: "[::1]" })).toContain('connect(("::1", 5678))'); }); it("Python Debug Server says it waits for a connection until the program connects, and listens again", () => { diff --git a/src/features/debugger/__tests__/sessionAdoption.test.ts b/src/features/debugger/__tests__/sessionAdoption.test.ts index dd490cbf21..4b91525a90 100644 --- a/src/features/debugger/__tests__/sessionAdoption.test.ts +++ b/src/features/debugger/__tests__/sessionAdoption.test.ts @@ -174,6 +174,30 @@ describe("Python Debug Server", () => { } }); + it("lends its configuration to no other start while it waits", async () => { + const connect = waitForProgram(); + void startSession(listen, { runConfig: rc }); + await vi.waitFor(() => expect(ipc.debugStart).toHaveBeenCalledOnce()); + announce(1); + // Another debug session starts while the server still waits for its program. + const otherStarted = waitForProgram(); + const other = startSession( + { ...launch, name: "tests" }, + { runConfig: { name: "tests", kind: "python" } as RunConfig }, + ); + await vi.waitFor(() => expect(ipc.debugStart).toHaveBeenCalledTimes(2)); + handleDebugEvent(2, { kind: "started", name: "tests", adapter: "debugpy", parent: null }); + // Announced before its start returns: nothing of the waiting server's. + expect(useDebug.getState().sessions[2]?.status).toBe("running"); + expect(useDebug.getState().console[2] ?? []).toEqual([]); + otherStarted(2); + expect(await other).toBe(2); + const { sessions } = useDebug.getState(); + expect(sessions[2]).toMatchObject({ status: "running", runConfig: { kind: "python" } }); + expect(sessions[1]).toMatchObject({ status: "starting", runConfig: rc }); + connect(1); + }); + it("does not listen again when a wait is cancelled", async () => { const rerun = vi.fn(); const dispose = registerAction({ id: "run.debugConfig", title: "Debug", run: rerun }); diff --git a/src/features/debugger/remote.ts b/src/features/debugger/remote.ts index 4919a7f1ca..a1bad41fd8 100644 --- a/src/features/debugger/remote.ts +++ b/src/features/debugger/remote.ts @@ -199,11 +199,19 @@ export const pythonRemoteType: RunConfigTypeContribution = { /** The line the program runs to connect, in place of PyCharm's `pydevd_pycharm.settrace(...)`. */ export function debugpyConnectLine(p: Params): string { - const host = hostOf(p).replace(/\\/g, "\\\\").replace(/"/g, '\\"'); + const host = hostOf(p) + .replace(/^\[(.*)\]$/, "$1") + .replace(/\\/g, "\\\\") + .replace(/"/g, '\\"'); return `import debugpy; debugpy.connect(("${host}", ${portOf(p, 5678)})); debugpy.wait_for_client()`; } -const isLoopback = (host: string) => /^(localhost|127(\.\d+){3}|::1|\[::1\])$/i.test(host); +/** Where the adapter listens: loopback for a local program, every interface (IPv4 or IPv6) otherwise. */ +function listenAddress(host: string): string { + if (/^(::1|\[::1\])$/.test(host)) return "::1"; + if (/^(localhost|127(\.\d+){3})$/i.test(host)) return "127.0.0.1"; + return host.includes(":") ? "::" : "0.0.0.0"; +} export const pythonDebugServerType: RunConfigTypeContribution = { id: PYTHON_DEBUG_SERVER, @@ -450,7 +458,7 @@ export function remoteAttachConfig(rc: RunConfig, root: string): LaunchConfig | case PYTHON_DEBUG_SERVER: // debugpy's listen mode has no authentication: other machines only when the program runs on one. return requestBase(rc, "debugpy", root, "attach", { - listen: { host: isLoopback(host) ? "127.0.0.1" : "0.0.0.0", port: portOf(p, 5678) }, + listen: { host: listenAddress(host), port: portOf(p, 5678) }, redirectOutput: true, justMyCode: skip, ...(map ? { pathMappings: [{ localRoot: map.local, remoteRoot: map.remote }] } : {}), diff --git a/src/features/debugger/state.ts b/src/features/debugger/state.ts index 1ec97fa3f7..ce24785b3e 100644 --- a/src/features/debugger/state.ts +++ b/src/features/debugger/state.ts @@ -381,7 +381,9 @@ function ownSession(id: DebugSessionId, event: DebugEvent): DebugSession | null // The new root session takes the tab it replaces now, not once `debugStart` returns. const replaced = pendingReplacements[0]; // A Python Debug Server's `debugStart` returns once a program connects: until then it is starting. - const rc = pendingConfigs[0]?.runConfig; + // The start this session belongs to (by name): a server still waiting must not lend its configuration. + const at = event.kind === "started" ? pendingConfigs.findIndex((c) => c.name === event.name) : -1; + const rc = at >= 0 ? pendingConfigs.splice(at, 1)[0]!.runConfig : undefined; const waiting = listensAgain(rc) ? { runConfig: rc, status: "starting" as const } : {}; const slot = { ...waiting, ...(replaced ? { tabOrder: replaced.tabOrder, pinned: replaced.pinned } : {}) }; const s = @@ -445,7 +447,7 @@ interface ReplacedTab { /** Finished tabs whose starting replacements have no session yet, oldest start first. */ const pendingReplacements: ReplacedTab[] = []; /** The run configurations of starts in flight, oldest first. */ -const pendingConfigs: { runConfig?: RunConfig }[] = []; +const pendingConfigs: { name: string; runConfig?: RunConfig }[] = []; /** The new session is shown: the finished tab it replaces gives way. */ function takeReplacement(r: ReplacedTab | undefined) { @@ -1004,11 +1006,13 @@ export async function startSession( await flushBreakpoints(); options.preparation?.signal.throwIfAborted(); const adapterStarted = performance.now(); - const pending = { runConfig: options.runConfig }; + const pending = { name: launch.name, runConfig: options.runConfig }; pendingConfigs.push(pending); - const id = await call(commands.debugStart(launch)).finally(() => - pendingConfigs.splice(pendingConfigs.indexOf(pending), 1), - ); + const id = await call(commands.debugStart(launch)).finally(() => { + // Its session took the entry when it was announced, unless it never was. + const at = pendingConfigs.indexOf(pending); + if (at >= 0) pendingConfigs.splice(at, 1); + }); console.info("Debug adapter started", { name: launch.name, ms: performance.now() - adapterStarted }); owned.add(id); if (afterDetach && !options.preparation) replaced = replaceFinished(launch.name, options.runConfig?.id);