Debian Codegraph @

helix-dap/src/client.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use crate::{
2 registry::DebugAdapterId,
3 requests::{DisconnectArguments, TerminateArguments},
4 transport::{Payload, Request, Response, Transport},
5 Error, ProgressMap, ProgressState, Result,
6 };
7 use helix_core::syntax::config::{DebugAdapterConfig, DebuggerQuirks};
8 use helix_dap_types::*;
9
10 use serde_json::Value;
11
12 use anyhow::anyhow;
13 use std::{
14 collections::HashMap,
15 future::Future,
16 net::{IpAddr, Ipv4Addr, SocketAddr},
17 path::PathBuf,
18 process::Stdio,
19 };
•20 use portable_atomic::{AtomicU64, Ordering};
21 use tokio::{
22 io::{AsyncBufRead, AsyncWrite, BufReader, BufWriter},
23 net::TcpStream,
24 process::{Child, Command},
25 sync::mpsc::{channel, unbounded_channel, UnboundedReceiver, UnboundedSender},
26 time,
27 };
28
29 #[derive(Debug)]
30 pub struct Client {
31 id: DebugAdapterId,
32 _process: Option<Child>,
33 server_tx: UnboundedSender<Payload>,
34 request_counter: AtomicU64,
35 connection_type: Option<ConnectionType>,
36 starting_request_args: Option<Value>,
37 /// The socket address of the debugger, if using TCP transport.
38 pub socket: Option<SocketAddr>,
39 pub caps: Option<DebuggerCapabilities>,
40 // thread_id -> frames
41 pub stack_frames: HashMap<ThreadId, Vec<StackFrame>>,
42 pub thread_states: ThreadStates,
43 pub progress: ProgressMap,
44 pub thread_id: Option<ThreadId>,
45 /// Currently active frame for the current thread.
46 pub active_frame: Option<usize>,
47 pub quirks: DebuggerQuirks,
48 /// The config which was used to start this debugger.
49 pub config: Option<DebugAdapterConfig>,
50 }
51
52 impl Client {
53 // Spawn a process and communicate with it by either TCP or stdio
54 // The returned stream includes the Client ID so consumers can differentiate between multiple clients
55 pub async fn process(
56 transport: &str,
57 command: &str,
58 args: Vec<&str>,
59 port_arg: Option<&str>,
60 id: DebugAdapterId,
61 ) -> Result<(Self, UnboundedReceiver<(DebugAdapterId, Payload)>)> {
62 if command.is_empty() {
63 return Result::Err(Error::Other(anyhow!("Command not provided")));
64 }
65 match (transport, port_arg) {
66 ("tcp", Some(port_arg)) => Self::tcp_process(command, args, port_arg, id).await,
67 ("stdio", _) => Self::stdio(command, args, id),
68 _ => Result::Err(Error::Other(anyhow!("Incorrect transport {}", transport))),
69 }
70 }
71
72 pub fn streams(
73 rx: Box<dyn AsyncBufRead + Unpin + Send>,
74 tx: Box<dyn AsyncWrite + Unpin + Send>,
75 err: Option<Box<dyn AsyncBufRead + Unpin + Send>>,
76 id: DebugAdapterId,
77 process: Option<Child>,
78 ) -> Result<(Self, UnboundedReceiver<(DebugAdapterId, Payload)>)> {
79 let (server_rx, server_tx) = Transport::start(rx, tx, err, id);
80 let (client_tx, client_rx) = unbounded_channel();
81
82 let client = Self {
83 id,
84 _process: process,
85 server_tx,
86 request_counter: AtomicU64::new(0),
87 caps: None,
88 connection_type: None,
89 starting_request_args: None,
90 socket: None,
91 stack_frames: HashMap::new(),
92 thread_states: HashMap::new(),
93 progress: HashMap::new(),
94 thread_id: None,
95 active_frame: None,
96 quirks: DebuggerQuirks::default(),
97 config: None,
98 };
99
100 tokio::spawn(Self::recv(id, server_rx, client_tx));
101
102 Ok((client, client_rx))
103 }
104
105 pub async fn tcp(
106 addr: std::net::SocketAddr,
107 id: DebugAdapterId,
108 ) -> Result<(Self, UnboundedReceiver<(DebugAdapterId, Payload)>)> {
109 let stream = TcpStream::connect(addr).await?;
110 let (rx, tx) = stream.into_split();
111 Self::streams(Box::new(BufReader::new(rx)), Box::new(tx), None, id, None)
112 }
113
114 pub fn stdio(
115 cmd: &str,
116 args: Vec<&str>,
117 id: DebugAdapterId,
118 ) -> Result<(Self, UnboundedReceiver<(DebugAdapterId, Payload)>)> {
119 // Resolve path to the binary
120 let cmd = helix_stdx::env::which(cmd)?;
121
122 let process = Command::new(cmd)
123 .args(args)
124 .stdin(Stdio::piped())
125 .stdout(Stdio::piped())
126 .stderr(Stdio::piped())
127 // make sure the process is reaped on drop
128 .kill_on_drop(true)
129 .spawn();
130
131 let mut process = process?;
132
133 // TODO: do we need bufreader/writer here? or do we use async wrappers on unblock?
134 let writer = BufWriter::new(process.stdin.take().expect("Failed to open stdin"));
135 let reader = BufReader::new(process.stdout.take().expect("Failed to open stdout"));
136 let stderr = BufReader::new(process.stderr.take().expect("Failed to open stderr"));
137
138 Self::streams(
139 Box::new(reader),
140 Box::new(writer),
141 Some(Box::new(stderr)),
142 id,
143 Some(process),
144 )
145 }
146
147 async fn get_port() -> Option<u16> {
148 Some(
149 tokio::net::TcpListener::bind(SocketAddr::new(
150 IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
151 0,
152 ))
153 .await
154 .ok()?
155 .local_addr()
156 .ok()?
157 .port(),
158 )
159 }
160
161 pub fn starting_request_args(&self) -> Option<&Value> {
162 self.starting_request_args.as_ref()
163 }
164
165 pub async fn tcp_process(
166 cmd: &str,
167 args: Vec<&str>,
168 port_format: &str,
169 id: DebugAdapterId,
170 ) -> Result<(Self, UnboundedReceiver<(DebugAdapterId, Payload)>)> {
171 let port = Self::get_port().await.unwrap();
172
173 let process = Command::new(cmd)
174 .args(args)
175 .args(port_format.replace("{}", &port.to_string()).split(' '))
176 // silence messages
177 .stdin(Stdio::null())
178 .stdout(Stdio::null())
179 .stderr(Stdio::null())
180 // Do not kill debug adapter when leaving, it should exit automatically
181 .spawn()?;
182
183 // Wait for adapter to become ready for connection
184 time::sleep(time::Duration::from_millis(500)).await;
185 let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port);
186 let stream = TcpStream::connect(socket).await?;
187
188 let (rx, tx) = stream.into_split();
189 let mut result = Self::streams(
190 Box::new(BufReader::new(rx)),
191 Box::new(tx),
192 None,
193 id,
194 Some(process),
195 );
196
197 // Set the socket address for the client
198 if let Ok((client, _)) = &mut result {
199 client.socket = Some(socket);
200 }
201
202 result
203 }
204
205 async fn recv(
206 id: DebugAdapterId,
207 mut server_rx: UnboundedReceiver<Payload>,
208 client_tx: UnboundedSender<(DebugAdapterId, Payload)>,
209 ) {
210 while let Some(msg) = server_rx.recv().await {
211 match msg {
212 Payload::Event(ev) => {
213 client_tx
214 .send((id, Payload::Event(ev)))
215 .expect("Failed to send");
216 }
217 Payload::Response(_) => unreachable!(),
218 Payload::Request(req) => {
219 client_tx
220 .send((id, Payload::Request(req)))
221 .expect("Failed to send");
222 }
223 }
224 }
225 }
226
227 pub fn id(&self) -> DebugAdapterId {
228 self.id
229 }
230
231 pub fn connection_type(&self) -> Option<ConnectionType> {
232 self.connection_type
233 }
234
235 fn next_request_id(&self) -> u64 {
236 // > The `seq` for the first message sent by a client or debug adapter
237 // > is 1, and for each subsequent message is 1 greater than the
238 // > previous message sent by that actor
239 // <https://microsoft.github.io/debug-adapter-protocol/specification#Base_Protocol_ProtocolMessage>
240 self.request_counter.fetch_add(1, Ordering::Relaxed) + 1
241 }
242
243 // Internal, called by specific DAP commands when resuming
244 pub fn resume_application(&mut self) {
245 if let Some(thread_id) = self.thread_id {
246 self.thread_states.insert(thread_id, "running".to_string());
247 self.stack_frames.remove(&thread_id);
248 }
249 self.active_frame = None;
250 self.thread_id = None;
251 }
252
253 /// Execute a RPC request on the debugger.
254 pub fn call<R: helix_dap_types::Request>(
255 &self,
256 arguments: R::Arguments,
257 ) -> impl Future<Output = Result<Value>>
258 where
259 R::Arguments: serde::Serialize,
260 {
261 let server_tx = self.server_tx.clone();
262 let id = self.next_request_id();
263
264 async move {
265 use std::time::Duration;
266 use tokio::time::timeout;
267
268 let arguments = Some(serde_json::to_value(arguments)?);
269
270 let (callback_tx, mut callback_rx) = channel(1);
271
272 let req = Request {
273 back_ch: Some(callback_tx),
274 seq: id,
275 command: R::COMMAND.to_string(),
276 arguments,
277 };
278
279 server_tx
280 .send(Payload::Request(req))
281 .map_err(|e| Error::Other(e.into()))?;
282
283 // TODO: specifiable timeout, delay other calls until initialize success
284 let response = timeout(Duration::from_secs(20), callback_rx.recv())
285 .await
286 .map_err(|_| Error::Timeout(id))? // return Timeout
287 .ok_or(Error::StreamClosed)??;
288
289 if !response.success {
290 let message = response
291 .message
292 .clone()
293 .unwrap_or_else(|| "DAP request failed".to_string());
294 return Err(Error::Other(anyhow!(message)));
295 }
296
297 Ok(response.body.unwrap_or_default())
298 }
299 }
300
301 pub async fn request<R: helix_dap_types::Request>(
302 &self,
303 params: R::Arguments,
304 ) -> Result<R::Result>
305 where
306 R::Arguments: serde::Serialize,
307 {
308 // a future that resolves into the response
309 let json = self.call::<R>(params).await?;
310 let response = serde_json::from_value(json)?;
311 Ok(response)
312 }
313
314 pub fn reply(
315 &self,
316 request_seq: u64,
317 command: &str,
318 result: core::result::Result<Value, Error>,
319 ) -> impl Future<Output = Result<()>> {
320 let server_tx = self.server_tx.clone();
321 let command = command.to_string();
322
323 async move {
324 let response = match result {
325 Ok(result) => Response {
326 request_seq,
327 command,
328 success: true,
329 message: None,
330 body: Some(result),
331 },
332 Err(error) => Response {
333 request_seq,
334 command,
335 success: false,
336 message: Some(error.to_string()),
337 body: None,
338 },
339 };
340
341 server_tx
342 .send(Payload::Response(response))
343 .map_err(|e| Error::Other(e.into()))?;
344
345 Ok(())
346 }
347 }
348
349 pub fn capabilities(&self) -> &DebuggerCapabilities {
350 self.caps.as_ref().expect("debugger not yet initialized!")
351 }
352
353 pub fn progress_start(&mut self, event: events::ProgressStartBody) -> String {
354 let status = ProgressState::new(event.title, event.message, event.percentage);
355 let status_line = status.status_line();
356 self.progress.insert(event.progress_id, status);
357 status_line
358 }
359
360 pub fn progress_update(&mut self, event: events::ProgressUpdateBody) -> Option<String> {
361 let status = self.progress.get_mut(&event.progress_id)?;
362 status.update(event.message, event.percentage);
363 Some(status.status_line())
364 }
365
366 pub fn progress_end(&mut self, event: events::ProgressEndBody) -> Option<String> {
367 let status = self.progress.remove(&event.progress_id)?;
368 Some(status.end_status_line(event.message.as_deref()))
369 }
370
371 pub async fn initialize(&mut self, adapter_id: String) -> Result<()> {
372 let args = requests::InitializeArguments {
373 client_id: Some("hx".to_owned()),
374 client_name: Some("helix".to_owned()),
375 adapter_id,
376 locale: Some("en-us".to_owned()),
377 lines_start_at_one: Some(true),
378 columns_start_at_one: Some(true),
379 path_format: Some("path".to_owned()),
380 supports_variable_type: Some(true),
381 supports_variable_paging: Some(false),
382 supports_run_in_terminal_request: Some(true),
383 supports_memory_references: Some(false),
384 supports_progress_reporting: Some(true),
385 supports_invalidated_event: Some(false),
386 };
387
388 let response = self.request::<requests::Initialize>(args).await?;
389 self.caps = Some(response);
390
391 Ok(())
392 }
393
394 pub fn disconnect(
395 &mut self,
396 args: Option<DisconnectArguments>,
397 ) -> impl Future<Output = Result<Value>> {
398 self.connection_type = None;
399 self.call::<requests::Disconnect>(args)
400 }
401
402 pub fn terminate(
403 &mut self,
404 args: Option<TerminateArguments>,
405 ) -> impl Future<Output = Result<Value>> {
406 self.connection_type = None;
407 self.call::<requests::Terminate>(args)
408 }
409
410 pub fn launch(&mut self, args: serde_json::Value) -> impl Future<Output = Result<Value>> {
411 self.connection_type = Some(ConnectionType::Launch);
412 self.starting_request_args = Some(args.clone());
413 self.call::<requests::Launch>(args)
414 }
415
416 pub fn attach(&mut self, args: serde_json::Value) -> impl Future<Output = Result<Value>> {
417 self.connection_type = Some(ConnectionType::Attach);
418 self.starting_request_args = Some(args.clone());
419 self.call::<requests::Attach>(args)
420 }
421
422 pub fn restart(&self) -> impl Future<Output = Result<Value>> {
423 let args = if let Some(args) = &self.starting_request_args {
424 args.clone()
425 } else {
426 Value::Null
427 };
428 self.call::<requests::Restart>(args)
429 }
430
431 pub async fn set_breakpoints(
432 &self,
433 file: PathBuf,
434 breakpoints: Vec<SourceBreakpoint>,
435 ) -> Result<Option<Vec<Breakpoint>>> {
436 let args = requests::SetBreakpointsArguments {
437 source: Source {
438 path: Some(file),
439 name: None,
440 source_reference: None,
441 presentation_hint: None,
442 origin: None,
443 sources: None,
444 adapter_data: None,
445 checksums: None,
446 },
447 breakpoints: Some(breakpoints),
448 source_modified: Some(false),
449 };
450
451 let response = self.request::<requests::SetBreakpoints>(args).await?;
452
453 Ok(response.breakpoints)
454 }
455
456 pub async fn configuration_done(&self) -> Result<()> {
457 if !self
458 .caps
459 .as_ref()
460 .and_then(|caps| caps.supports_configuration_done_request)
461 .unwrap_or(false)
462 {
463 return Ok(());
464 }
465
466 self.request::<requests::ConfigurationDone>(Some(requests::ConfigurationDoneArguments {}))
467 .await
468 }
469
470 pub fn continue_thread(&self, thread_id: ThreadId) -> impl Future<Output = Result<Value>> {
471 let args = requests::ContinueArguments { thread_id };
472
473 self.call::<requests::Continue>(args)
474 }
475
476 pub async fn stack_trace(
477 &self,
478 thread_id: ThreadId,
479 ) -> Result<(Vec<StackFrame>, Option<usize>)> {
480 let args = requests::StackTraceArguments {
481 thread_id,
482 start_frame: None,
483 levels: None,
484 format: None,
485 };
486
487 let response = self.request::<requests::StackTrace>(args).await?;
488 Ok((response.stack_frames, response.total_frames))
489 }
490
491 pub fn threads(&self) -> impl Future<Output = Result<Value>> {
492 self.call::<requests::Threads>(Some(requests::ThreadsArguments {}))
493 }
494
495 pub async fn scopes(&self, frame_id: usize) -> Result<Vec<Scope>> {
496 let args = requests::ScopesArguments { frame_id };
497
498 let response = self.request::<requests::Scopes>(args).await?;
499 Ok(response.scopes)
500 }
501
502 pub async fn variables(&self, variables_reference: usize) -> Result<Vec<Variable>> {
503 let args = requests::VariablesArguments {
504 variables_reference,
505 filter: None,
506 start: None,
507 count: None,
508 format: None,
509 };
510
511 let response = self.request::<requests::Variables>(args).await?;
512 Ok(response.variables)
513 }
514
515 pub fn step_in(&self, thread_id: ThreadId) -> impl Future<Output = Result<Value>> {
516 let args = requests::StepInArguments {
517 thread_id,
518 target_id: None,
519 granularity: None,
520 };
521
522 self.call::<requests::StepIn>(args)
523 }
524
525 pub fn step_out(&self, thread_id: ThreadId) -> impl Future<Output = Result<Value>> {
526 let args = requests::StepOutArguments {
527 thread_id,
528 granularity: None,
529 };
530
531 self.call::<requests::StepOut>(args)
532 }
533
534 pub fn next(&self, thread_id: ThreadId) -> impl Future<Output = Result<Value>> {
535 let args = requests::NextArguments {
536 thread_id,
537 granularity: None,
538 };
539
540 self.call::<requests::Next>(args)
541 }
542
543 pub fn pause(&self, thread_id: ThreadId) -> impl Future<Output = Result<Value>> {
544 let args = requests::PauseArguments { thread_id };
545
546 self.call::<requests::Pause>(args)
547 }
548
549 pub async fn eval(
550 &self,
551 expression: String,
552 frame_id: Option<usize>,
553 ) -> Result<requests::EvaluateResponse> {
554 let args = requests::EvaluateArguments {
555 expression,
556 frame_id,
557 context: None,
558 format: None,
559 };
560
561 self.request::<requests::Evaluate>(args).await
562 }
563
564 pub fn set_exception_breakpoints(
565 &self,
566 filters: Vec<String>,
567 ) -> impl Future<Output = Result<Value>> {
568 let args = requests::SetExceptionBreakpointsArguments { filters };
569
570 self.call::<requests::SetExceptionBreakpoints>(args)
571 }
572
573 pub fn current_stack_frame(&self) -> Option<&StackFrame> {
574 self.stack_frames
575 .get(&self.thread_id?)?
576 .get(self.active_frame?)
577 }
578 }