aboutsummaryrefslogtreecommitdiff
path: root/codeless/server/src/io.rs
blob: b84103d6556f6f86cf21304c3d1a717fc02ee85b (plain)
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
use std::{
    thread,
    io::{
        stdout, stdin,
        BufRead, Write,
    },
};
use serde_json::{Value, from_str, to_string};
use crossbeam_channel::{Receiver, Sender, bounded};

use Result;


#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RawMsg {
    Request(RawRequest),
    Notification(RawNotification),
    Response(RawResponse),
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RawRequest {
    pub id: u64,
    pub method: String,
    pub params: Value,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RawNotification {
    pub method: String,
    pub params: Value,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RawResponse {
    pub id: Option<u64>,
    pub result: Value,
    pub error: Value,
}

struct MsgReceiver {
    chan: Receiver<RawMsg>,
    thread: Option<thread::JoinHandle<Result<()>>>,
}

impl MsgReceiver {
    fn recv(&mut self) -> Result<RawMsg> {
        match self.chan.recv() {
            Some(msg) => Ok(msg),
            None => {
                self.thread
                    .take()
                    .ok_or_else(|| format_err!("MsgReceiver thread panicked"))?
                    .join()
                    .map_err(|_| format_err!("MsgReceiver thread panicked"))??;
                bail!("client disconnected")
            }
        }
    }

    fn stop(self) -> Result<()> {
        // Can't really self.thread.join() here, b/c it might be
        // blocking on read
        Ok(())
    }
}

struct MsgSender {
    chan: Sender<RawMsg>,
    thread: Option<thread::JoinHandle<Result<()>>>,
}

impl MsgSender {
    fn send(&mut self, msg: RawMsg) {
        self.chan.send(msg)
    }

    fn stop(mut self) -> Result<()> {
        if let Some(thread) = self.thread.take() {
            thread.join()
                .map_err(|_| format_err!("MsgSender thread panicked"))??
        }
        Ok(())
    }
}

impl Drop for MsgSender {
    fn drop(&mut self) {
        if let Some(thread) = self.thread.take() {
            let res = thread.join();
            if thread::panicking() {
                drop(res)
            } else {
                res.unwrap().unwrap()
            }
        }
    }
}

pub struct Io {
    receiver: MsgReceiver,
    sender: MsgSender,
}

impl Io {
    pub fn from_stdio() -> Io {
        let sender = {
            let (tx, rx) = bounded(16);
            MsgSender {
                chan: tx,
                thread: Some(thread::spawn(move || {
                    let stdout = stdout();
                    let mut stdout = stdout.lock();
                    for msg in rx {
                        #[derive(Serialize)]
                        struct JsonRpc {
                            jsonrpc: &'static str,
                            #[serde(flatten)]
                            msg: RawMsg,
                        }
                        let text = to_string(&JsonRpc {
                            jsonrpc: "2.0",
                            msg,
                        })?;
                        write_msg_text(&mut stdout, &text)?;
                    }
                    Ok(())
                })),
            }
        };
        let receiver = {
            let (tx, rx) = bounded(16);
            MsgReceiver {
                chan: rx,
                thread: Some(thread::spawn(move || {
                    let stdin = stdin();
                    let mut stdin = stdin.lock();
                    while let Some(text) = read_msg_text(&mut stdin)? {
                        let msg: RawMsg = from_str(&text)?;
                        tx.send(msg);
                    }
                    Ok(())
                })),
            }
        };
        Io { receiver, sender }
    }

    pub fn send(&mut self, msg: RawMsg) {
        self.sender.send(msg)
    }

    pub fn recv(&mut self) -> Result<RawMsg> {
        self.receiver.recv()
    }

    pub fn stop(self) -> Result<()> {
        self.receiver.stop()?;
        self.sender.stop()?;
        Ok(())
    }
}


fn read_msg_text(inp: &mut impl BufRead) -> Result<Option<String>> {
    let mut size = None;
    let mut buf = String::new();
    loop {
        buf.clear();
        if inp.read_line(&mut buf)? == 0 {
            return Ok(None);
        }
        if !buf.ends_with("\r\n") {
            bail!("malformed header: {:?}", buf);
        }
        let buf = &buf[..buf.len() - 2];
        if buf.is_empty() {
            break;
        }
        let mut parts = buf.splitn(2, ": ");
        let header_name = parts.next().unwrap();
        let header_value = parts.next().ok_or_else(|| format_err!("malformed header: {:?}", buf))?;
        if header_name == "Content-Length" {
            size = Some(header_value.parse::<usize>()?);
        }
    }
    let size = size.ok_or_else(|| format_err!("no Content-Length"))?;
    let mut buf = buf.into_bytes();
    buf.resize(size, 0);
    inp.read_exact(&mut buf)?;
    let buf = String::from_utf8(buf)?;
    Ok(Some(buf))
}

fn write_msg_text(out: &mut impl Write, msg: &str) -> Result<()> {
    write!(out, "Content-Length: {}\r\n\r\n", msg.len())?;
    out.write_all(msg.as_bytes())?;
    out.flush()?;
    Ok(())
}