Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

fix(debugger): wait for slow launch and attach without a deadline (#2186)

l0ng-ai067feac89c9f
diff --git a/crates/ide-dap/Cargo.toml b/crates/ide-dap/Cargo.toml
index b37151c9d..31fc65f4f 100644
--- a/crates/ide-dap/Cargo.toml
+++ b/crates/ide-dap/Cargo.toml
@@ -25,4 +25,4 @@ libc = "0.2"
[dev-dependencies]
tracing-subscriber.workspace = true
-tokio = { workspace = true, features = ["net", "rt-multi-thread", "macros"] }
+tokio = { workspace = true, features = ["net", "rt-multi-thread", "macros", "test-util"] }
diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs
index 8b335d520..4efd1a4b0 100644
--- a/crates/ide-dap/src/lib.rs
+++ b/crates/ide-dap/src/lib.rs
@@ -282,7 +282,6 @@ impl SessionOwner {
}
const INIT_TIMEOUT: Duration = Duration::from_secs(20);
-const LAUNCH_TIMEOUT: Duration = Duration::from_secs(60);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(3);
/// Redefining many classes in a large JVM can take a while.
@@ -883,7 +882,12 @@ impl DebugManager {
});
tokio::spawn(session::event_loop(self.me.clone(), session.clone(), incoming));
- match self.configure(&session, arguments).await {
+ let configured = tokio::select! {
+ biased;
+ _ = session.startup_cancel.cancelled() => return Err(IdeError::cancelled()),
+ result = self.configure(&session, arguments) => result,
+ };
+ match configured {
Ok(()) => Ok(id),
Err(e) => {
let e = if session.conn.is_closed() {
@@ -971,7 +975,9 @@ impl DebugManager {
arguments["hostName"] = json!("127.0.0.1");
arguments["port"] = json!(port);
}
- // Many adapters answer `launch` only after `configurationDone`, so don't wait for it yet.
+ // Launch/attach may wait for a slow runtime or a remote target. Let the adapter report
+ // failure; Stop cancels configuration and a closed connection fails the pending reply.
+ // Many adapters answer only after `configurationDone`, so don't wait for the reply yet.
let launch = s.conn.send_request(request, arguments)?;
let mut launch = Box::pin(async move { launch.await.unwrap_or(Err(DapError::Closed)) });
let mut initialized = s.initialized.subscribe();
@@ -983,7 +989,6 @@ impl DebugManager {
launch_result = Some(());
false
}
- _ = tokio::time::sleep(LAUNCH_TIMEOUT) => return Err(DapError::Timeout(s.request.clone()).into()),
};
if !got_initialized {
// Launched before `initialized`; give the adapter a moment to send it.
@@ -1041,12 +1046,7 @@ impl DebugManager {
}
s.configured.store(true, Ordering::Release);
if launch_result.is_none() {
- match tokio::time::timeout(LAUNCH_TIMEOUT, launch).await {
- Ok(r) => {
- r?;
- }
- Err(_) => return Err(DapError::Timeout(s.request.clone()).into()),
- }
+ launch.await?;
}
if let Some(relay) = s.kotlin_relay.lock().as_mut() {
relay.release();
@@ -1730,9 +1730,11 @@ impl DebugManager {
}
async fn stop_tree(&self, session: Arc<Session>) -> IdeResult<()> {
+ session.startup_cancel.cancel();
let children: Vec<Arc<Session>> =
self.live_sessions().into_iter().filter(|c| c.parent == Some(session.id)).collect();
for child in children {
+ child.startup_cancel.cancel();
self.shutdown(&child, true).await;
}
self.shutdown(&session, true).await;
diff --git a/crates/ide-dap/src/session.rs b/crates/ide-dap/src/session.rs
index b093ce134..614823ae1 100644
--- a/crates/ide-dap/src/session.rs
+++ b/crates/ide-dap/src/session.rs
@@ -48,6 +48,7 @@ pub(crate) struct Session {
/// Set once `configurationDone` was sent; breakpoint updates go out live after that.
pub configured: AtomicBool,
pub initialized: watch::Sender<bool>,
+ pub startup_cancel: ide_core::CancellationToken,
pub output_drained: watch::Sender<bool>,
pub terminated: AtomicBool,
/// Set by a second Stop: the one waiting for the program kills it instead.
@@ -104,6 +105,7 @@ impl Session {
program: Mutex::new(None),
configured: AtomicBool::new(false),
initialized: watch::channel(false).0,
+ startup_cancel: ide_core::CancellationToken::new(),
output_drained: watch::channel(true).0,
terminated: AtomicBool::new(false),
stop_force: AtomicBool::new(false),
diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs
index 6a989b968..bb00ba2c7 100644
--- a/crates/ide-dap/src/tests.rs
+++ b/crates/ide-dap/src/tests.rs
@@ -33,6 +33,12 @@ struct Script {
supports_terminate: bool,
/// Answer `setBreakpoints` only once this many are waiting (a client that waits for each never gets one).
hold_set_breakpoints: usize,
+ initialized_delay: Duration,
+ launch_delay: Duration,
+ /// Leave startup pending before `initialized` (false) or after configuration (true).
+ pending_startup: Option<bool>,
+ startup_error: Option<&'static str>,
+ close_during_startup: bool,
}
impl Default for Script {
@@ -47,6 +53,11 @@ impl Default for Script {
output_after_terminate: false,
supports_terminate: true,
hold_set_breakpoints: 0,
+ initialized_delay: Duration::ZERO,
+ launch_delay: Duration::ZERO,
+ pending_startup: None,
+ startup_error: None,
+ close_during_startup: false,
}
}
}
@@ -120,6 +131,15 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
})
),
"launch" | "attach" => {
+ if script.close_during_startup {
+ return;
+ }
+ if let Some(message) = script.startup_error {
+ send!(
+ json!({"type": "response", "request_seq": msg["seq"], "command": msg["command"], "success": false, "message": message})
+ );
+ continue;
+ }
pending_launch = msg["seq"].as_i64();
if let Some(args) = &script.run_in_terminal {
send!(
@@ -131,7 +151,10 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
json!({"type": "request", "command": "startDebugging", "arguments": {"request": "launch", "configuration": {"name": "child", "isChild": true}}})
);
}
- send!(json!({"type": "event", "event": "initialized"}));
+ if script.pending_startup != Some(false) {
+ tokio::time::sleep(script.initialized_delay).await;
+ send!(json!({"type": "event", "event": "initialized"}));
+ }
}
"setBreakpoints" => {
held.push(msg);
@@ -182,6 +205,10 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
if !script.ignore_configuration_done {
ok!(msg, Value::Null);
}
+ if script.pending_startup == Some(true) {
+ continue;
+ }
+ tokio::time::sleep(script.launch_delay).await;
if let Some(l) = pending_launch.take() {
send!(json!({"type": "response", "request_seq": l, "command": "launch", "success": true}));
}
@@ -351,6 +378,66 @@ fn bp(line: u32) -> Breakpoint {
Breakpoint { line, condition: None, hit_condition: None, log_message: None, enabled: true }
}
+#[tokio::test(start_paused = true)]
+async fn slow_launch_and_attach_follow_adapter_startup() {
+ for request in ["launch", "attach"] {
+ for before_initialized in [true, false] {
+ let delay = Duration::from_secs(125);
+ let h = harness(Script {
+ initialized_delay: if before_initialized { delay } else { Duration::ZERO },
+ launch_delay: if before_initialized { Duration::ZERO } else { delay },
+ ..Script::default()
+ });
+ let config = LaunchConfig { request: request.into(), ..config() };
+ let id = h.start(config).await.expect("a slow adapter can finish starting");
+ h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
+ assert!(!h.commands().iter().any(|c| c == "terminate" || c == "disconnect"));
+ h.manager.stop(id).await.unwrap();
+ }
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn stop_cancels_pending_launch_and_attach() {
+ for request in ["launch", "attach"] {
+ for configured in [false, true] {
+ let h = harness(Script { pending_startup: Some(configured), ..Script::default() });
+ let config = LaunchConfig { request: request.into(), ..config() };
+ let start = h.start(config);
+ tokio::pin!(start);
+ let stop = async {
+ loop {
+ let command = if configured { "configurationDone" } else { request };
+ if h.commands().iter().any(|c| c == command) {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ let id = h.manager.sessions(None)[0].id;
+ h.manager.stop(id).await.unwrap();
+ };
+ let (result, ()) = tokio::join!(&mut start, stop);
+ assert_eq!(result.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
+ assert!(h.manager.sessions(None).is_empty());
+ }
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn startup_still_reports_adapter_failure_and_connection_closure() {
+ for request in ["launch", "attach"] {
+ let h = harness(Script { startup_error: Some("interpreter could not start"), ..Script::default() });
+ let error = h.start(LaunchConfig { request: request.into(), ..config() }).await.unwrap_err();
+ assert_eq!(error.message, format!("{request} failed: interpreter could not start"));
+ assert!(h.manager.sessions(None).is_empty());
+
+ let h = harness(Script { close_during_startup: true, ..Script::default() });
+ let error = h.start(LaunchConfig { request: request.into(), ..config() }).await.unwrap_err();
+ assert!(error.message.contains("debug adapter `debugpy` exited during startup"), "{error}");
+ assert!(h.manager.sessions(None).is_empty());
+ }
+}
+
#[tokio::test]
async fn full_protocol_flow() {
let h = harness(Script::default());