pull/574/head
Dmitry Sharshakov 3 years ago committed by Blaž Hrastnik
parent fd709bc56d
commit 5fd0a2ddda

@ -272,7 +272,7 @@ impl Client {
.expect("Expected initialized event") .expect("Expected initialized event")
{ {
Payload::Event(Event { event, .. }) => { Payload::Event(Event { event, .. }) => {
if event == "initialized".to_owned() { if event == *"initialized" {
Ok(()) Ok(())
} else { } else {
unreachable!() unreachable!()
@ -308,7 +308,7 @@ impl Client {
pub async fn wait_for_stopped(&mut self) -> Result<()> { pub async fn wait_for_stopped(&mut self) -> Result<()> {
match self.server_rx.recv().await.expect("Expected stopped event") { match self.server_rx.recv().await.expect("Expected stopped event") {
Payload::Event(Event { event, .. }) => { Payload::Event(Event { event, .. }) => {
if event == "stopped".to_owned() { if event == *"stopped" {
Ok(()) Ok(())
} else { } else {
unreachable!() unreachable!()

@ -1,276 +1,272 @@
use crate::{Error, Result}; use crate::{Error, Result};
use anyhow::Context; use anyhow::Context;
use log::{error, info}; use log::{error, info};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use tokio::{ use tokio::{
io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, BufWriter}, io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, BufWriter},
process::{ChildStdin, ChildStdout}, process::{ChildStdin, ChildStdout},
sync::{ sync::{
mpsc::{unbounded_channel, Sender, UnboundedReceiver, UnboundedSender}, mpsc::{unbounded_channel, Sender, UnboundedReceiver, UnboundedSender},
Mutex, Mutex,
}, },
}; };
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Request { pub struct Request {
#[serde(skip)] #[serde(skip)]
pub back_ch: Option<Sender<Result<Response>>>, pub back_ch: Option<Sender<Result<Response>>>,
pub seq: u64, pub seq: u64,
#[serde(rename = "type")] #[serde(rename = "type")]
pub msg_type: String, pub msg_type: String,
pub command: String, pub command: String,
pub arguments: Option<Value>, pub arguments: Option<Value>,
} }
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
pub struct Response { pub struct Response {
pub seq: u64, pub seq: u64,
#[serde(rename = "type")] #[serde(rename = "type")]
pub msg_type: String, pub msg_type: String,
pub request_seq: u64, pub request_seq: u64,
pub success: bool, pub success: bool,
pub command: String, pub command: String,
pub message: Option<String>, pub message: Option<String>,
pub body: Option<Value>, pub body: Option<Value>,
} }
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
pub struct Event { pub struct Event {
pub seq: u64, pub seq: u64,
#[serde(rename = "type")] #[serde(rename = "type")]
pub msg_type: String, pub msg_type: String,
pub event: String, pub event: String,
pub body: Option<Value>, pub body: Option<Value>,
} }
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)] #[serde(untagged)]
pub enum Payload { pub enum Payload {
// type = "event" // type = "event"
Event(Event), Event(Event),
// type = "response" // type = "response"
Response(Response), Response(Response),
// type = "request" // type = "request"
Request(Request), Request(Request),
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Transport { pub struct Transport {
id: usize, id: usize,
pending_requests: Mutex<HashMap<u64, Sender<Result<Response>>>>, pending_requests: Mutex<HashMap<u64, Sender<Result<Response>>>>,
} }
impl Transport { impl Transport {
pub fn start( pub fn start(
server_stdout: BufReader<ChildStdout>, server_stdout: BufReader<ChildStdout>,
server_stdin: BufWriter<ChildStdin>, server_stdin: BufWriter<ChildStdin>,
id: usize, id: usize,
) -> (UnboundedReceiver<Payload>, UnboundedSender<Request>) { ) -> (UnboundedReceiver<Payload>, UnboundedSender<Request>) {
let (client_tx, rx) = unbounded_channel(); let (client_tx, rx) = unbounded_channel();
let (tx, client_rx) = unbounded_channel(); let (tx, client_rx) = unbounded_channel();
let transport = Self { let transport = Self {
id, id,
pending_requests: Mutex::new(HashMap::default()), pending_requests: Mutex::new(HashMap::default()),
}; };
let transport = Arc::new(transport); let transport = Arc::new(transport);
tokio::spawn(Self::recv(transport.clone(), server_stdout, client_tx)); tokio::spawn(Self::recv(transport.clone(), server_stdout, client_tx));
tokio::spawn(Self::send(transport, server_stdin, client_rx)); tokio::spawn(Self::send(transport, server_stdin, client_rx));
(rx, tx) (rx, tx)
} }
async fn recv_server_message( async fn recv_server_message(
reader: &mut (impl AsyncBufRead + Unpin + Send), reader: &mut (impl AsyncBufRead + Unpin + Send),
buffer: &mut String, buffer: &mut String,
) -> Result<Payload> { ) -> Result<Payload> {
let mut content_length = None; let mut content_length = None;
loop { loop {
buffer.truncate(0); buffer.truncate(0);
reader.read_line(buffer).await?; reader.read_line(buffer).await?;
let header = buffer.trim(); let header = buffer.trim();
if header.is_empty() { if header.is_empty() {
break; break;
} }
let mut parts = header.split(": "); let mut parts = header.split(": ");
match (parts.next(), parts.next(), parts.next()) { match (parts.next(), parts.next(), parts.next()) {
(Some("Content-Length"), Some(value), None) => { (Some("Content-Length"), Some(value), None) => {
content_length = Some(value.parse().context("invalid content length")?); content_length = Some(value.parse().context("invalid content length")?);
} }
(Some(_), Some(_), None) => {} (Some(_), Some(_), None) => {}
_ => { _ => {
return Err(std::io::Error::new( return Err(std::io::Error::new(
std::io::ErrorKind::Other, std::io::ErrorKind::Other,
"Failed to parse header", "Failed to parse header",
) )
.into()); .into());
} }
} }
} }
let content_length = content_length.context("missing content length")?; let content_length = content_length.context("missing content length")?;
//TODO: reuse vector //TODO: reuse vector
let mut content = vec![0; content_length]; let mut content = vec![0; content_length];
reader.read_exact(&mut content).await?; reader.read_exact(&mut content).await?;
let msg = std::str::from_utf8(&content).context("invalid utf8 from server")?; let msg = std::str::from_utf8(&content).context("invalid utf8 from server")?;
info!("<- DAP {}", msg); info!("<- DAP {}", msg);
// try parsing as output (server response) or call (server request) // try parsing as output (server response) or call (server request)
let output: serde_json::Result<Payload> = serde_json::from_str(msg); let output: serde_json::Result<Payload> = serde_json::from_str(msg);
Ok(output?) Ok(output?)
} }
async fn send_payload_to_server( async fn send_payload_to_server(
&self, &self,
server_stdin: &mut BufWriter<ChildStdin>, server_stdin: &mut BufWriter<ChildStdin>,
req: Request, req: Request,
) -> Result<()> { ) -> Result<()> {
let json = serde_json::to_string(&req)?; let json = serde_json::to_string(&req)?;
match req.back_ch { if let Some(back) = req.back_ch {
Some(back) => { self.pending_requests.lock().await.insert(req.seq, back);
self.pending_requests.lock().await.insert(req.seq, back); }
() self.send_string_to_server(server_stdin, json).await
} }
None => {}
} async fn send_string_to_server(
self.send_string_to_server(server_stdin, json).await &self,
} server_stdin: &mut BufWriter<ChildStdin>,
request: String,
async fn send_string_to_server( ) -> Result<()> {
&self, info!("-> DAP {}", request);
server_stdin: &mut BufWriter<ChildStdin>,
request: String, // send the headers
) -> Result<()> { server_stdin
info!("-> DAP {}", request); .write_all(format!("Content-Length: {}\r\n\r\n", request.len()).as_bytes())
.await?;
// send the headers
server_stdin // send the body
.write_all(format!("Content-Length: {}\r\n\r\n", request.len()).as_bytes()) server_stdin.write_all(request.as_bytes()).await?;
.await?;
server_stdin.flush().await?;
// send the body
server_stdin.write_all(request.as_bytes()).await?; Ok(())
}
server_stdin.flush().await?;
async fn process_server_message(
Ok(()) &self,
} client_tx: &UnboundedSender<Payload>,
msg: Payload,
async fn process_server_message( ) -> Result<()> {
&self, let (id, result) = match msg {
client_tx: &UnboundedSender<Payload>, Payload::Response(Response {
msg: Payload, success: true,
) -> Result<()> { seq,
let (id, result) = match msg { request_seq,
Payload::Response(Response { ..
success: true, }) => {
seq, info!("<- DAP success ({}, in response to {})", seq, request_seq);
request_seq, if let Payload::Response(val) = msg {
.. (request_seq, Ok(val))
}) => { } else {
info!("<- DAP success ({}, in response to {})", seq, request_seq); unreachable!();
if let Payload::Response(val) = msg { }
(request_seq, Ok(val)) }
} else { Payload::Response(Response {
unreachable!(); success: false,
} message,
} body,
Payload::Response(Response { request_seq,
success: false, command,
message, ..
body, }) => {
request_seq, error!(
command, "<- DAP error {:?} ({:?}) for command #{} {}",
.. message, body, request_seq, command
}) => { );
error!( (
"<- DAP error {:?} ({:?}) for command #{} {}", request_seq,
message, body, request_seq, command Err(Error::Other(anyhow::format_err!("{:?}", body))),
); )
( }
request_seq, Payload::Request(Request {
Err(Error::Other(anyhow::format_err!("{:?}", body))), ref command,
) ref seq,
} ..
Payload::Request(Request { }) => {
ref command, info!("<- DAP request {} #{}", command, seq);
ref seq, client_tx.send(msg).expect("Failed to send");
.. return Ok(());
}) => { }
info!("<- DAP request {} #{}", command, seq); Payload::Event(Event {
client_tx.send(msg).expect("Failed to send"); ref event, ref seq, ..
return Ok(()); }) => {
} info!("<- DAP event {} #{}", event, seq);
Payload::Event(Event { client_tx.send(msg).expect("Failed to send");
ref event, ref seq, .. return Ok(());
}) => { }
info!("<- DAP event {} #{}", event, seq); };
client_tx.send(msg).expect("Failed to send");
return Ok(()); let tx = self
} .pending_requests
}; .lock()
.await
let tx = self .remove(&id)
.pending_requests .expect("pending_request with id not found!");
.lock()
.await match tx.send(result).await {
.remove(&id) Ok(_) => (),
.expect("pending_request with id not found!"); Err(_) => error!(
"Tried sending response into a closed channel (id={:?}), original request likely timed out",
match tx.send(result).await { id
Ok(_) => (), ),
Err(_) => error!( };
"Tried sending response into a closed channel (id={:?}), original request likely timed out",
id Ok(())
), }
};
async fn recv(
Ok(()) transport: Arc<Self>,
} mut server_stdout: BufReader<ChildStdout>,
client_tx: UnboundedSender<Payload>,
async fn recv( ) {
transport: Arc<Self>, let mut recv_buffer = String::new();
mut server_stdout: BufReader<ChildStdout>, loop {
client_tx: UnboundedSender<Payload>, match Self::recv_server_message(&mut server_stdout, &mut recv_buffer).await {
) { Ok(msg) => {
let mut recv_buffer = String::new(); transport
loop { .process_server_message(&client_tx, msg)
match Self::recv_server_message(&mut server_stdout, &mut recv_buffer).await { .await
Ok(msg) => { .unwrap();
transport }
.process_server_message(&client_tx, msg) Err(err) => {
.await error!("err: <- {:?}", err);
.unwrap(); break;
} }
Err(err) => { }
error!("err: <- {:?}", err); }
break; }
}
} async fn send(
} transport: Arc<Self>,
} mut server_stdin: BufWriter<ChildStdin>,
mut client_rx: UnboundedReceiver<Request>,
async fn send( ) {
transport: Arc<Self>, while let Some(req) = client_rx.recv().await {
mut server_stdin: BufWriter<ChildStdin>, transport
mut client_rx: UnboundedReceiver<Request>, .send_payload_to_server(&mut server_stdin, req)
) { .await
while let Some(req) = client_rx.recv().await { .unwrap()
transport }
.send_payload_to_server(&mut server_stdin, req) }
.await }
.unwrap()
}
}
}

Loading…
Cancel
Save