1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
//! DAP client for communicating with debug adapters
//!
//! This module handles the communication with DAP adapters like lldb-dap,
//! including the initialization sequence and request/response handling.
//!
//! ## Architecture
//!
//! The DapClient uses a background reader task to continuously read from the
//! adapter's stdout (or TCP socket). This ensures that events (stopped, output,
//! etc.) are captured immediately rather than only during request/response cycles.
//!
//! ```text
//! [DAP Adapter] --stdout/tcp--> [Reader Task] --events--> [event_tx channel]
//! --responses-> [response channels]
//! [DapClient] --stdin/tcp--> [DAP Adapter]
//! ```
//!
//! ## Transport Modes
//!
//! - **Stdio**: Standard input/output (default, used by lldb-dap, debugpy)
//! - **TCP**: TCP socket connection (used by Delve)
use std::collections::HashMap;
use std::path::Path;
use std::process::Stdio;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::Arc;
use std::time::Duration;
use std::pin::Pin;
use std::task::{Context, Poll};
use serde_json::Value;
use tokio::io::{AsyncWrite, BufReader, BufWriter};
use tokio::net::TcpStream;
use tokio::process::{Child, ChildStdin, ChildStdout, Command};
use tokio::sync::{mpsc, oneshot, Mutex};
use crate::common::{Error, Result};
use super::codec;
use super::types::*;
/// Pending response waiters, keyed by request sequence number
type PendingResponses = Arc<Mutex<HashMap<i64, oneshot::Sender<std::result::Result<ResponseMessage, Error>>>>>;
/// Abstraction over different writer types (stdin or TCP)
enum DapWriter {
Stdio(BufWriter<ChildStdin>),
Tcp(BufWriter<tokio::io::WriteHalf<TcpStream>>),
}
impl AsyncWrite for DapWriter {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
match self.get_mut() {
DapWriter::Stdio(w) => Pin::new(w).poll_write(cx, buf),
DapWriter::Tcp(w) => Pin::new(w).poll_write(cx, buf),
}
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
match self.get_mut() {
DapWriter::Stdio(w) => Pin::new(w).poll_flush(cx),
DapWriter::Tcp(w) => Pin::new(w).poll_flush(cx),
}
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
match self.get_mut() {
DapWriter::Stdio(w) => Pin::new(w).poll_shutdown(cx),
DapWriter::Tcp(w) => Pin::new(w).poll_shutdown(cx),
}
}
}
/// DAP client for communicating with a debug adapter
pub struct DapClient {
/// Adapter subprocess
adapter: Child,
/// Buffered writer for adapter communication
writer: DapWriter,
/// Sequence number for requests
seq: AtomicI64,
/// Adapter capabilities (populated after initialize)
pub capabilities: Capabilities,
/// Pending response waiters
pending: PendingResponses,
/// Channel for events (to session)
event_tx: mpsc::UnboundedSender<Event>,
/// Receiver for events (given to session)
event_rx: Option<mpsc::UnboundedReceiver<Event>>,
/// Handle to the background reader task
reader_task: Option<tokio::task::JoinHandle<()>>,
/// Channel to signal reader task to stop
shutdown_tx: Option<mpsc::Sender<()>>,
}
impl DapClient {
/// Spawn a new DAP adapter and create a client
pub async fn spawn(adapter_path: &Path, args: &[String]) -> Result<Self> {
let mut cmd = Command::new(adapter_path);
cmd.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit()); // Let adapter errors go to stderr
let mut adapter = cmd.spawn().map_err(|e| {
Error::AdapterStartFailed(format!(
"Failed to start {}: {}",
adapter_path.display(),
e
))
})?;
let stdin = adapter
.stdin
.take()
.ok_or_else(|| Error::AdapterStartFailed("Failed to get adapter stdin".to_string()))?;
let stdout = adapter.stdout.take().ok_or_else(|| {
Error::AdapterStartFailed("Failed to get adapter stdout".to_string())
})?;
let (event_tx, event_rx) = mpsc::unbounded_channel();
let (shutdown_tx, shutdown_rx) = mpsc::channel(1);
let pending: PendingResponses = Arc::new(Mutex::new(HashMap::new()));
// Spawn background reader task
let reader_task = Self::spawn_stdio_reader_task(
stdout,
event_tx.clone(),
pending.clone(),
shutdown_rx,
);
Ok(Self {
adapter,
writer: DapWriter::Stdio(BufWriter::new(stdin)),
seq: AtomicI64::new(1),
capabilities: Capabilities::default(),
pending,
event_tx,
event_rx: Some(event_rx),
reader_task: Some(reader_task),
shutdown_tx: Some(shutdown_tx),
})
}
/// Spawn a new DAP adapter that uses TCP for communication (e.g., Delve, js-debug)
pub async fn spawn_tcp(
adapter_path: &Path,
args: &[String],
spawn_style: &crate::common::config::TcpSpawnStyle,
) -> Result<Self> {
use crate::common::parse_listen_address;
use tokio::io::{AsyncBufReadExt, BufReader as TokioBufReader};
let (mut adapter, addr) = match spawn_style {
crate::common::config::TcpSpawnStyle::TcpListen => {
let mut cmd = Command::new(adapter_path);
cmd.args(args)
.arg("--listen=127.0.0.1:0")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut adapter = cmd.spawn().map_err(|e| {
Error::AdapterStartFailed(format!(
"Failed to start {}: {}",
adapter_path.display(),
e
))
})?;
let stdout = adapter.stdout.take().ok_or_else(|| {
let _ = adapter.start_kill();
Error::AdapterStartFailed("Failed to get adapter stdout".to_string())
})?;
let mut stdout_reader = TokioBufReader::new(stdout);
let mut line = String::new();
let addr_result = tokio::time::timeout(Duration::from_secs(10), async {
loop {
line.clear();
let bytes_read = stdout_reader.read_line(&mut line).await.map_err(|e| {
Error::AdapterStartFailed(format!("Failed to read adapter output: {}", e))
})?;
if bytes_read == 0 {
return Err(Error::AdapterStartFailed(
"Adapter exited before outputting listen address".to_string(),
));
}
tracing::debug!("Adapter output: {}", line.trim());
if let Some(addr) = parse_listen_address(&line) {
return Ok(addr);
}
}
})
.await;
let addr = match addr_result {
Ok(Ok(addr)) => addr,
Ok(Err(e)) => {
let _ = adapter.start_kill();
return Err(e);
}
Err(_) => {
let _ = adapter.start_kill();
return Err(Error::AdapterStartFailed(
"Timeout waiting for adapter to start listening".to_string(),
));
}
};
(adapter, addr)
}
crate::common::config::TcpSpawnStyle::TcpPortArg => {
use std::net::TcpListener as StdTcpListener;
let listener = StdTcpListener::bind("127.0.0.1:0").map_err(|e| {
Error::AdapterStartFailed(format!("Failed to allocate port: {}", e))
})?;
let port = listener.local_addr().map_err(|e| {
Error::AdapterStartFailed(format!("Failed to get port: {}", e))
})?.port();
// Race condition window: port released before adapter binds. Mitigated by immediate spawn + 500ms buffer.
// If connection fails, port may have been reallocated by OS.
drop(listener);
let addr = format!("127.0.0.1:{}", port);
let mut cmd = Command::new(adapter_path);
let mut full_args = args.to_vec();
full_args.push(port.to_string());
cmd.args(&full_args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let adapter = cmd.spawn().map_err(|e| {
Error::AdapterStartFailed(format!(
"Failed to start {}: {}",
adapter_path.display(),
e
))
})?;
(adapter, addr)
}
};
tracing::info!("Connecting to DAP adapter at {}", addr);
// Retry TCP connection with exponential backoff
// Handles adapters that need time to start listening (e.g., js-debug)
let stream = {
let mut last_error = None;
let mut delay = Duration::from_millis(100);
let max_delay = Duration::from_millis(1000);
let timeout_duration = Duration::from_secs(10);
let start = std::time::Instant::now();
loop {
match TcpStream::connect(&addr).await {
Ok(s) => break s,
Err(e) => {
last_error = Some(e);
if start.elapsed() >= timeout_duration {
let _ = adapter.start_kill();
return Err(Error::AdapterStartFailed(format!(
"Failed to connect to adapter at {} after {:?}: {}",
addr, timeout_duration, last_error.unwrap()
)));
}
tokio::time::sleep(delay).await;
delay = std::cmp::min(delay * 2, max_delay);
}
}
}
};
let (read_half, write_half) = tokio::io::split(stream);
let (event_tx, event_rx) = mpsc::unbounded_channel();
let (shutdown_tx, shutdown_rx) = mpsc::channel(1);
let pending: PendingResponses = Arc::new(Mutex::new(HashMap::new()));
// Spawn background reader task for TCP
let reader_task = Self::spawn_tcp_reader_task(
read_half,
event_tx.clone(),
pending.clone(),
shutdown_rx,
);
Ok(Self {
adapter,
writer: DapWriter::Tcp(BufWriter::new(write_half)),
seq: AtomicI64::new(1),
capabilities: Capabilities::default(),
pending,
event_tx,
event_rx: Some(event_rx),
reader_task: Some(reader_task),
shutdown_tx: Some(shutdown_tx),
})
}
/// Spawn the background reader task for stdio-based adapters
fn spawn_stdio_reader_task(
stdout: ChildStdout,
event_tx: mpsc::UnboundedSender<Event>,
pending: PendingResponses,
mut shutdown_rx: mpsc::Receiver<()>,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
let mut reader = BufReader::new(stdout);
loop {
tokio::select! {
biased;
// Check for shutdown signal
_ = shutdown_rx.recv() => {
tracing::debug!("Reader task received shutdown signal");
break;
}
// Read next message
result = codec::read_message(&mut reader) => {
match result {
Ok(json) => {
tracing::trace!("DAP <<< {}", json);
if let Err(e) = Self::process_message(&json, &event_tx, &pending).await {
tracing::error!("Error processing DAP message: {}", e);
}
}
Err(e) => {
// Check if this is an expected EOF (adapter exited)
// We check the error message string as a fallback for various error types
let err_str = e.to_string().to_lowercase();
let is_eof = err_str.contains("unexpected eof")
|| err_str.contains("unexpectedeof")
|| err_str.contains("end of file");
if is_eof {
tracing::info!("DAP adapter closed connection");
} else {
tracing::error!("Error reading from DAP adapter: {}", e);
}
// Signal error to any pending requests
let mut pending_guard = pending.lock().await;
for (_, tx) in pending_guard.drain() {
let _ = tx.send(Err(Error::AdapterCrashed));
}
// Send terminated event to notify the session
let _ = event_tx.send(Event::Terminated(None));
break;
}
}
}
}
}
tracing::debug!("Reader task exiting");
})
}
/// Spawn the background reader task for TCP-based adapters
fn spawn_tcp_reader_task(
read_half: tokio::io::ReadHalf<TcpStream>,
event_tx: mpsc::UnboundedSender<Event>,
pending: PendingResponses,
mut shutdown_rx: mpsc::Receiver<()>,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
let mut reader = BufReader::new(read_half);
loop {
tokio::select! {
biased;
// Check for shutdown signal
_ = shutdown_rx.recv() => {
tracing::debug!("TCP reader task received shutdown signal");
break;
}
// Read next message
result = codec::read_message(&mut reader) => {
match result {
Ok(json) => {
tracing::trace!("DAP <<< {}", json);
if let Err(e) = Self::process_message(&json, &event_tx, &pending).await {
tracing::error!("Error processing DAP message: {}", e);
}
}
Err(e) => {
let err_str = e.to_string().to_lowercase();
let is_eof = err_str.contains("unexpected eof")
|| err_str.contains("unexpectedeof")
|| err_str.contains("end of file")
|| err_str.contains("connection reset");
if is_eof {
tracing::info!("DAP adapter closed TCP connection");
} else {
tracing::error!("Error reading from DAP adapter (TCP): {}", e);
}
// Signal error to any pending requests
let mut pending_guard = pending.lock().await;
for (_, tx) in pending_guard.drain() {
let _ = tx.send(Err(Error::AdapterCrashed));
}
// Send terminated event to notify the session
let _ = event_tx.send(Event::Terminated(None));
break;
}
}
}
}
}
tracing::debug!("TCP reader task exiting");
})
}
/// Process a single message from the adapter
async fn process_message(
json: &str,
event_tx: &mpsc::UnboundedSender<Event>,
pending: &PendingResponses,
) -> Result<()> {
let msg: Value = serde_json::from_str(json)
.map_err(|e| Error::DapProtocol(format!("Invalid JSON: {}", e)))?;
let msg_type = msg
.get("type")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
match msg_type {
"response" => {
let response: ResponseMessage = serde_json::from_value(msg)?;
let seq = response.request_seq;
let mut pending_guard = pending.lock().await;
if let Some(tx) = pending_guard.remove(&seq) {
let _ = tx.send(Ok(response));
} else {
tracing::warn!("Received response for unknown request seq {}", seq);
}
}
"event" => {
let event_msg: EventMessage = serde_json::from_value(msg)?;
let event = Event::from_message(&event_msg);
let _ = event_tx.send(event);
}
_ => {
tracing::warn!("Unknown message type: {}", msg_type);
}
}
Ok(())
}
/// Take the event receiver (can only be called once)
pub fn take_event_receiver(&mut self) -> Option<mpsc::UnboundedReceiver<Event>> {
self.event_rx.take()
}
/// Get the next sequence number
fn next_seq(&self) -> i64 {
self.seq.fetch_add(1, Ordering::SeqCst)
}
/// Send a request and return its sequence number
async fn send_request(&mut self, command: &str, arguments: Option<Value>) -> Result<i64> {
let seq = self.next_seq();
// Build request with or without arguments field
let request = if let Some(args) = arguments {
serde_json::json!({
"seq": seq,
"type": "request",
"command": command,
"arguments": args
})
} else {
serde_json::json!({
"seq": seq,
"type": "request",
"command": command
})
};
let json = serde_json::to_string(&request)?;
tracing::trace!("DAP >>> {}", json);
codec::write_message(&mut self.writer, &json).await?;
Ok(seq)
}
/// Send a request and wait for the response with timeout
pub async fn request<T: serde::de::DeserializeOwned>(
&mut self,
command: &str,
arguments: Option<Value>,
) -> Result<T> {
self.request_with_timeout(command, arguments, Duration::from_secs(30)).await
}
/// Send a request and wait for the response with configurable timeout
///
/// Note: We register the pending response handler BEFORE sending the request
/// to avoid a race condition where a fast adapter response arrives before
/// we've set up the handler.
pub async fn request_with_timeout<T: serde::de::DeserializeOwned>(
&mut self,
command: &str,
arguments: Option<Value>,
timeout: Duration,
) -> Result<T> {
let seq = self.next_seq();
// Build request with or without arguments field
let request = if let Some(ref args) = arguments {
serde_json::json!({
"seq": seq,
"type": "request",
"command": command,
"arguments": args
})
} else {
serde_json::json!({
"seq": seq,
"type": "request",
"command": command
})
};
// IMPORTANT: Register the pending response handler BEFORE sending the request
// to avoid race condition where fast adapter responds before we're ready
let (tx, rx) = oneshot::channel();
{
let mut pending_guard = self.pending.lock().await;
pending_guard.insert(seq, tx);
}
// Now send the request
let json = serde_json::to_string(&request)?;
tracing::trace!("DAP >>> {}", json);
if let Err(e) = codec::write_message(&mut self.writer, &json).await {
// Remove the pending handler if send failed
let mut pending_guard = self.pending.lock().await;
pending_guard.remove(&seq);
return Err(e);
}
// Wait for response with timeout
let response = tokio::time::timeout(timeout, rx)
.await
.map_err(|_| {
// Clean up pending handler on timeout
let pending = self.pending.clone();
tokio::spawn(async move {
let mut pending_guard = pending.lock().await;
pending_guard.remove(&seq);
});
Error::Timeout(timeout.as_secs())
})?
.map_err(|_| Error::AdapterCrashed)??;
if response.success {
let body = response.body.unwrap_or(Value::Null);
serde_json::from_value(body).map_err(|e| {
Error::DapProtocol(format!(
"Failed to parse {} response: {}",
command, e
))
})
} else {
Err(Error::dap_request_failed(
command,
&response.message.unwrap_or_else(|| "Unknown error".to_string()),
))
}
}
/// Poll for events - this is now non-blocking since events are already in the channel
/// Note: This method is kept for API compatibility but is no longer necessary
/// since the background reader task handles all event ingestion
pub async fn poll_event(&mut self) -> Result<Option<Event>> {
// Events are now handled by the background reader task
// and delivered through the event channel.
// This method is kept for backward compatibility.
Ok(None)
}
/// Initialize the debug adapter
pub async fn initialize(&mut self, adapter_id: &str) -> Result<Capabilities> {
self.initialize_with_timeout(adapter_id, Duration::from_secs(10)).await
}
/// Initialize the debug adapter with configurable timeout
pub async fn initialize_with_timeout(
&mut self,
adapter_id: &str,
timeout: Duration,
) -> Result<Capabilities> {
let args = InitializeArguments {
adapter_id: adapter_id.to_string(),
..Default::default()
};
let caps: Capabilities = self
.request_with_timeout("initialize", Some(serde_json::to_value(&args)?), timeout)
.await?;
self.capabilities = caps.clone();
Ok(caps)
}
/// Wait for the initialized event with timeout
///
/// This method waits for the initialized event which comes through the event channel.
/// It's called before the session takes the event receiver.
pub async fn wait_initialized(&mut self) -> Result<()> {
self.wait_initialized_with_timeout(Duration::from_secs(30)).await
}
/// Wait for the initialized event with configurable timeout
///
/// ## Event Ordering Note
///
/// This method consumes events from the channel until it sees `Initialized`.
/// Non-Initialized events are re-sent to the channel so they won't be lost.
/// This is safe because:
/// 1. The session hasn't taken the receiver yet (wait_initialized is called during setup)
/// 2. The re-sent events go back to the same unbounded channel
/// 3. The background reader task continues adding new events after our re-sent ones
///
/// Events will be received in order: [re-sent events] + [new events from reader]
pub async fn wait_initialized_with_timeout(&mut self, timeout: Duration) -> Result<()> {
// The event receiver is typically taken by the session after initialization,
// but wait_initialized is called before that, so we should still have it
if let Some(ref mut rx) = self.event_rx {
let deadline = tokio::time::Instant::now() + timeout;
loop {
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
return Err(Error::Timeout(timeout.as_secs()));
}
match tokio::time::timeout(remaining, rx.recv()).await {
Ok(Some(event)) => {
if matches!(event, Event::Initialized) {
return Ok(());
}
// Re-send other events so they're not lost when session takes the receiver.
// This maintains event ordering: these events arrived before Initialized,
// so they'll be received first when the session starts processing.
let _ = self.event_tx.send(event);
}
Ok(None) => {
return Err(Error::AdapterCrashed);
}
Err(_) => {
return Err(Error::Timeout(timeout.as_secs()));
}
}
}
} else {
// Event receiver already taken - this shouldn't happen in normal flow
Err(Error::Internal("Event receiver already taken before wait_initialized".to_string()))
}
}
/// Launch a program for debugging
pub async fn launch(&mut self, args: LaunchArguments) -> Result<()> {
self.request::<Value>("launch", Some(serde_json::to_value(&args)?))
.await?;
Ok(())
}
/// Launch a program for debugging without waiting for response
///
/// Some debuggers (like debugpy) don't respond to launch until after
/// configurationDone is sent. This sends the launch request but doesn't
/// wait for the response.
pub async fn launch_no_wait(&mut self, args: LaunchArguments) -> Result<i64> {
self.send_request("launch", Some(serde_json::to_value(&args)?)).await
}
/// Attach to a running process
pub async fn attach(&mut self, args: AttachArguments) -> Result<()> {
self.request::<Value>("attach", Some(serde_json::to_value(&args)?))
.await?;
Ok(())
}
/// Signal that configuration is done
pub async fn configuration_done(&mut self) -> Result<()> {
self.request::<Value>("configurationDone", None).await?;
Ok(())
}
/// Set breakpoints for a source file
pub async fn set_breakpoints(
&mut self,
source_path: &Path,
breakpoints: Vec<SourceBreakpoint>,
) -> Result<Vec<Breakpoint>> {
let args = SetBreakpointsArguments {
source: Source {
path: Some(source_path.to_string_lossy().into_owned()),
..Default::default()
},
breakpoints,
};
let response: SetBreakpointsResponseBody = self
.request("setBreakpoints", Some(serde_json::to_value(&args)?))
.await?;
Ok(response.breakpoints)
}
/// Set function breakpoints
pub async fn set_function_breakpoints(
&mut self,
breakpoints: Vec<FunctionBreakpoint>,
) -> Result<Vec<Breakpoint>> {
let args = SetFunctionBreakpointsArguments { breakpoints };
let response: SetBreakpointsResponseBody = self
.request(
"setFunctionBreakpoints",
Some(serde_json::to_value(&args)?),
)
.await?;
Ok(response.breakpoints)
}
/// Continue execution
pub async fn continue_execution(&mut self, thread_id: i64) -> Result<bool> {
let args = ContinueArguments {
thread_id,
single_thread: false,
};
let response: ContinueResponseBody = self
.request("continue", Some(serde_json::to_value(&args)?))
.await?;
Ok(response.all_threads_continued)
}
/// Step over (next)
pub async fn next(&mut self, thread_id: i64) -> Result<()> {
let args = StepArguments {
thread_id,
granularity: Some("statement".to_string()),
};
self.request::<Value>("next", Some(serde_json::to_value(&args)?))
.await?;
Ok(())
}
/// Step into
pub async fn step_in(&mut self, thread_id: i64) -> Result<()> {
let args = StepArguments {
thread_id,
granularity: Some("statement".to_string()),
};
self.request::<Value>("stepIn", Some(serde_json::to_value(&args)?))
.await?;
Ok(())
}
/// Step out
pub async fn step_out(&mut self, thread_id: i64) -> Result<()> {
let args = StepArguments {
thread_id,
granularity: Some("statement".to_string()),
};
self.request::<Value>("stepOut", Some(serde_json::to_value(&args)?))
.await?;
Ok(())
}
/// Pause execution
pub async fn pause(&mut self, thread_id: i64) -> Result<()> {
let args = PauseArguments { thread_id };
self.request::<Value>("pause", Some(serde_json::to_value(&args)?))
.await?;
Ok(())
}
/// Get stack trace
pub async fn stack_trace(&mut self, thread_id: i64, levels: i64) -> Result<Vec<StackFrame>> {
let args = StackTraceArguments {
thread_id,
start_frame: Some(0),
levels: Some(levels),
};
let response: StackTraceResponseBody = self
.request("stackTrace", Some(serde_json::to_value(&args)?))
.await?;
Ok(response.stack_frames)
}
/// Get threads
pub async fn threads(&mut self) -> Result<Vec<Thread>> {
let response: ThreadsResponseBody = self.request("threads", None).await?;
Ok(response.threads)
}
/// Get scopes for a frame
pub async fn scopes(&mut self, frame_id: i64) -> Result<Vec<Scope>> {
let args = ScopesArguments { frame_id };
let response: ScopesResponseBody = self
.request("scopes", Some(serde_json::to_value(&args)?))
.await?;
Ok(response.scopes)
}
/// Get variables
pub async fn variables(&mut self, variables_reference: i64) -> Result<Vec<Variable>> {
let args = VariablesArguments {
variables_reference,
start: None,
count: None,
};
let response: VariablesResponseBody = self
.request("variables", Some(serde_json::to_value(&args)?))
.await?;
Ok(response.variables)
}
/// Evaluate an expression
pub async fn evaluate(
&mut self,
expression: &str,
frame_id: Option<i64>,
context: &str,
) -> Result<EvaluateResponseBody> {
let args = EvaluateArguments {
expression: expression.to_string(),
frame_id,
context: Some(context.to_string()),
};
self.request("evaluate", Some(serde_json::to_value(&args)?))
.await
}
/// Disconnect from the debug adapter
pub async fn disconnect(&mut self, terminate_debuggee: bool) -> Result<()> {
let args = DisconnectArguments {
restart: false,
terminate_debuggee: Some(terminate_debuggee),
};
// Don't wait for response - adapter might exit immediately
let _ = self
.send_request("disconnect", Some(serde_json::to_value(&args)?))
.await;
Ok(())
}
/// Terminate the adapter process and clean up resources
pub async fn terminate(&mut self) -> Result<()> {
// Try graceful disconnect first
let _ = self.disconnect(true).await;
// Signal the reader task to stop
if let Some(tx) = self.shutdown_tx.take() {
let _ = tx.send(()).await;
}
// Wait a bit for clean shutdown
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
// Wait for reader task to finish
if let Some(task) = self.reader_task.take() {
// Give it a short timeout
let _ = tokio::time::timeout(
Duration::from_millis(500),
task,
).await;
}
// Force kill if still running
let _ = self.adapter.kill().await;
Ok(())
}
/// Check if the adapter is still running
pub fn is_running(&mut self) -> bool {
self.adapter.try_wait().ok().flatten().is_none()
}
/// Restart the debug session (for adapters that support it)
pub async fn restart(&mut self, no_debug: bool) -> Result<()> {
if !self.capabilities.supports_restart_request {
return Err(Error::Internal(
"Debug adapter does not support restart".to_string(),
));
}
let args = serde_json::json!({
"noDebug": no_debug
});
self.request::<Value>("restart", Some(args)).await?;
Ok(())
}
}
impl Drop for DapClient {
/// Best-effort cleanup on drop.
///
/// ## Limitations
///
/// Since we can't await in `drop()`, this is necessarily imperfect:
/// - `try_send` may fail if the shutdown channel is full (unlikely with capacity 1)
/// - `task.abort()` is immediate; the reader may be mid-operation
/// - `start_kill()` is non-blocking; the adapter may not exit immediately
///
/// For graceful cleanup, prefer calling `terminate()` before dropping.
/// This Drop impl exists as a safety net to avoid leaking resources if
/// `terminate()` wasn't called.
fn drop(&mut self) {
// Signal shutdown to reader task (best-effort, can't await)
if let Some(tx) = self.shutdown_tx.take() {
// Use try_send since we can't await in drop
let _ = tx.try_send(());
}
// Abort the reader task if it's still running
// Note: This is abrupt but necessary since we can't await graceful shutdown
if let Some(task) = self.reader_task.take() {
task.abort();
}
// Try to kill the adapter on drop
// This is best-effort since we can't await in drop
let _ = self.adapter.start_kill();
}
}