2020-10-19 11:09:44 +04:00
|
|
|
use std::collections::HashMap;
|
2021-02-24 11:07:39 +04:00
|
|
|
use std::io;
|
2020-10-19 11:09:44 +04:00
|
|
|
|
2021-02-15 16:16:25 +04:00
|
|
|
use log::{error, info};
|
2020-10-23 09:33:09 +04:00
|
|
|
|
2021-01-08 11:31:19 +04:00
|
|
|
use crate::Error;
|
2020-10-21 11:42:45 +04:00
|
|
|
|
|
|
|
type Result<T> = core::result::Result<T, Error>;
|
2020-10-19 11:09:44 +04:00
|
|
|
|
|
|
|
use jsonrpc_core as jsonrpc;
|
|
|
|
use serde_json::Value;
|
|
|
|
|
|
|
|
use smol::prelude::*;
|
|
|
|
|
|
|
|
use smol::{
|
|
|
|
channel::{Receiver, Sender},
|
|
|
|
io::{BufReader, BufWriter},
|
|
|
|
process::{ChildStderr, ChildStdin, ChildStdout},
|
|
|
|
Executor,
|
|
|
|
};
|
|
|
|
|
|
|
|
pub(crate) enum Payload {
|
|
|
|
Request {
|
2020-10-21 11:42:45 +04:00
|
|
|
chan: Sender<Result<Value>>,
|
2020-10-19 11:09:44 +04:00
|
|
|
value: jsonrpc::MethodCall,
|
|
|
|
},
|
|
|
|
Notification(jsonrpc::Notification),
|
2020-10-23 13:48:03 +04:00
|
|
|
Response(jsonrpc::Output),
|
|
|
|
}
|
|
|
|
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
/// A type representing all possible values sent from the server to the client.
|
|
|
|
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
|
|
|
|
#[serde(deny_unknown_fields)]
|
|
|
|
#[serde(untagged)]
|
|
|
|
enum Message {
|
|
|
|
/// A regular JSON-RPC request output (single response).
|
|
|
|
Output(jsonrpc::Output),
|
|
|
|
/// A JSON-RPC request or notification.
|
|
|
|
Call(jsonrpc::Call),
|
2020-10-19 11:09:44 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) struct Transport {
|
2020-10-23 13:48:03 +04:00
|
|
|
incoming: Sender<jsonrpc::Call>,
|
2020-10-19 11:09:44 +04:00
|
|
|
outgoing: Receiver<Payload>,
|
|
|
|
|
2020-10-21 11:42:45 +04:00
|
|
|
pending_requests: HashMap<jsonrpc::Id, Sender<Result<Value>>>,
|
2020-10-19 11:09:44 +04:00
|
|
|
headers: HashMap<String, String>,
|
|
|
|
|
|
|
|
writer: BufWriter<ChildStdin>,
|
|
|
|
reader: BufReader<ChildStdout>,
|
2021-01-08 11:31:19 +04:00
|
|
|
stderr: BufReader<ChildStderr>,
|
2020-10-19 11:09:44 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Transport {
|
|
|
|
pub fn start(
|
|
|
|
ex: &Executor,
|
|
|
|
reader: BufReader<ChildStdout>,
|
|
|
|
writer: BufWriter<ChildStdin>,
|
2021-01-08 11:31:19 +04:00
|
|
|
stderr: BufReader<ChildStderr>,
|
2020-10-23 13:48:03 +04:00
|
|
|
) -> (Receiver<jsonrpc::Call>, Sender<Payload>) {
|
2020-10-19 11:09:44 +04:00
|
|
|
let (incoming, rx) = smol::channel::unbounded();
|
|
|
|
let (tx, outgoing) = smol::channel::unbounded();
|
|
|
|
|
|
|
|
let transport = Self {
|
|
|
|
reader,
|
|
|
|
writer,
|
2021-01-08 11:31:19 +04:00
|
|
|
stderr,
|
2020-10-19 11:09:44 +04:00
|
|
|
incoming,
|
|
|
|
outgoing,
|
|
|
|
pending_requests: Default::default(),
|
|
|
|
headers: Default::default(),
|
|
|
|
};
|
|
|
|
|
|
|
|
ex.spawn(transport.duplex()).detach();
|
|
|
|
|
|
|
|
(rx, tx)
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn recv(
|
|
|
|
reader: &mut (impl AsyncBufRead + Unpin),
|
|
|
|
headers: &mut HashMap<String, String>,
|
2020-10-21 11:42:45 +04:00
|
|
|
) -> core::result::Result<Message, std::io::Error> {
|
2020-10-19 11:09:44 +04:00
|
|
|
// read headers
|
|
|
|
loop {
|
|
|
|
let mut header = String::new();
|
|
|
|
// detect pipe closed if 0
|
|
|
|
reader.read_line(&mut header).await?;
|
|
|
|
let header = header.trim();
|
|
|
|
|
|
|
|
if header.is_empty() {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
let parts: Vec<&str> = header.split(": ").collect();
|
|
|
|
if parts.len() != 2 {
|
2020-10-21 11:42:45 +04:00
|
|
|
return Err(std::io::Error::new(
|
|
|
|
std::io::ErrorKind::Other,
|
|
|
|
"Failed to parse header",
|
|
|
|
));
|
2020-10-19 11:09:44 +04:00
|
|
|
}
|
|
|
|
headers.insert(parts[0].to_string(), parts[1].to_string());
|
|
|
|
}
|
|
|
|
|
|
|
|
// find content-length
|
|
|
|
let content_length = headers.get("Content-Length").unwrap().parse().unwrap();
|
|
|
|
|
|
|
|
let mut content = vec![0; content_length];
|
|
|
|
reader.read_exact(&mut content).await?;
|
|
|
|
let msg = String::from_utf8(content).unwrap();
|
|
|
|
|
|
|
|
// read data
|
|
|
|
|
2021-02-15 16:16:25 +04:00
|
|
|
info!("<- {}", msg);
|
2020-12-23 12:03:20 +04:00
|
|
|
|
2020-10-19 11:09:44 +04:00
|
|
|
// try parsing as output (server response) or call (server request)
|
|
|
|
let output: serde_json::Result<Message> = serde_json::from_str(&msg);
|
|
|
|
|
|
|
|
Ok(output?)
|
|
|
|
}
|
|
|
|
|
2021-02-15 16:16:25 +04:00
|
|
|
async fn err(
|
|
|
|
err: &mut (impl AsyncBufRead + Unpin),
|
|
|
|
) -> core::result::Result<(), std::io::Error> {
|
|
|
|
let mut line = String::new();
|
|
|
|
err.read_line(&mut line).await?;
|
|
|
|
error!("err <- {}", line);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-02-24 11:07:39 +04:00
|
|
|
pub async fn send_payload(&mut self, payload: Payload) -> io::Result<()> {
|
2020-10-19 11:09:44 +04:00
|
|
|
match payload {
|
|
|
|
Payload::Request { chan, value } => {
|
|
|
|
self.pending_requests.insert(value.id.clone(), chan);
|
|
|
|
|
|
|
|
let json = serde_json::to_string(&value)?;
|
|
|
|
self.send(json).await
|
|
|
|
}
|
|
|
|
Payload::Notification(value) => {
|
|
|
|
let json = serde_json::to_string(&value)?;
|
|
|
|
self.send(json).await
|
|
|
|
}
|
2020-10-23 13:48:03 +04:00
|
|
|
Payload::Response(error) => {
|
|
|
|
let json = serde_json::to_string(&error)?;
|
|
|
|
self.send(json).await
|
|
|
|
}
|
2020-10-19 11:09:44 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-24 11:07:39 +04:00
|
|
|
pub async fn send(&mut self, request: String) -> io::Result<()> {
|
2021-02-15 16:16:25 +04:00
|
|
|
info!("-> {}", request);
|
2020-10-19 11:09:44 +04:00
|
|
|
|
|
|
|
// send the headers
|
|
|
|
self.writer
|
|
|
|
.write_all(format!("Content-Length: {}\r\n\r\n", request.len()).as_bytes())
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
// send the body
|
|
|
|
self.writer.write_all(request.as_bytes()).await?;
|
|
|
|
|
|
|
|
self.writer.flush().await?;
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-10-23 13:48:03 +04:00
|
|
|
async fn recv_msg(&mut self, msg: Message) -> anyhow::Result<()> {
|
2020-10-19 11:09:44 +04:00
|
|
|
match msg {
|
|
|
|
Message::Output(output) => self.recv_response(output).await?,
|
2020-10-23 09:33:09 +04:00
|
|
|
Message::Call(call) => {
|
2020-10-23 13:48:03 +04:00
|
|
|
self.incoming.send(call).await?;
|
|
|
|
// let notification = Notification::parse(&method, params);
|
2020-10-19 11:09:44 +04:00
|
|
|
}
|
|
|
|
};
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-02-24 11:07:39 +04:00
|
|
|
async fn recv_response(&mut self, output: jsonrpc::Output) -> io::Result<()> {
|
2021-02-22 07:42:56 +04:00
|
|
|
let (id, result) = match output {
|
2020-10-19 11:09:44 +04:00
|
|
|
jsonrpc::Output::Success(jsonrpc::Success { id, result, .. }) => {
|
2021-02-15 16:16:25 +04:00
|
|
|
info!("<- {}", result);
|
2021-02-22 07:42:56 +04:00
|
|
|
(id, Ok(result))
|
2020-10-19 11:09:44 +04:00
|
|
|
}
|
2020-10-21 11:42:45 +04:00
|
|
|
jsonrpc::Output::Failure(jsonrpc::Failure { id, error, .. }) => {
|
2021-02-22 07:42:56 +04:00
|
|
|
error!("<- {}", error);
|
|
|
|
(id, Err(error.into()))
|
2020-10-21 11:42:45 +04:00
|
|
|
}
|
2021-02-22 07:42:56 +04:00
|
|
|
};
|
|
|
|
|
|
|
|
let tx = self
|
|
|
|
.pending_requests
|
|
|
|
.remove(&id)
|
|
|
|
.expect("pending_request with id not found!");
|
|
|
|
|
|
|
|
match tx.send(result).await {
|
|
|
|
Ok(_) => (),
|
|
|
|
Err(_) => error!(
|
|
|
|
"Tried sending response into a closed channel (id={:?}), original request likely timed out",
|
|
|
|
id
|
|
|
|
),
|
|
|
|
};
|
|
|
|
|
2020-10-19 11:09:44 +04:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn duplex(mut self) {
|
|
|
|
use futures_util::{select, FutureExt};
|
|
|
|
loop {
|
|
|
|
select! {
|
|
|
|
// client -> server
|
|
|
|
msg = self.outgoing.next().fuse() => {
|
|
|
|
if msg.is_none() {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
let msg = msg.unwrap();
|
|
|
|
|
|
|
|
self.send_payload(msg).await.unwrap();
|
|
|
|
}
|
|
|
|
// server <- client
|
|
|
|
msg = Self::recv(&mut self.reader, &mut self.headers).fuse() => {
|
|
|
|
if msg.is_err() {
|
2020-12-25 12:42:50 +04:00
|
|
|
error!("err: <- {:?}", msg);
|
2020-10-19 11:09:44 +04:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
let msg = msg.unwrap();
|
|
|
|
|
|
|
|
self.recv_msg(msg).await.unwrap();
|
|
|
|
}
|
2021-02-15 16:16:25 +04:00
|
|
|
_msg = Self::err(&mut self.stderr).fuse() => {}
|
2020-10-19 11:09:44 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|