forked from ebkalderon/tower-lsp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec.rs
416 lines (348 loc) · 13.5 KB
/
codec.rs
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
//! Encoder and decoder for Language Server Protocol messages.
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::io::{Error as IoError, Write};
use std::marker::PhantomData;
use std::num::ParseIntError;
use std::str::Utf8Error;
use bytes::buf::BufMut;
use bytes::{Buf, BytesMut};
use memchr::memmem;
use serde::{de::DeserializeOwned, Serialize};
use tracing::{trace, warn};
#[cfg(feature = "runtime-agnostic")]
use async_codec_lite::{Decoder, Encoder};
#[cfg(feature = "runtime-tokio")]
use tokio_util::codec::{Decoder, Encoder};
/// Errors that can occur when processing an LSP message.
#[derive(Debug)]
pub enum ParseError {
/// Failed to parse the JSON body.
Body(serde_json::Error),
/// Failed to encode the response.
Encode(IoError),
/// Failed to parse headers.
Headers(httparse::Error),
/// The media type in the `Content-Type` header is invalid.
InvalidContentType,
/// The length value in the `Content-Length` header is invalid.
InvalidContentLength(ParseIntError),
/// Request lacks the required `Content-Length` header.
MissingContentLength,
/// Request contains invalid UTF8.
Utf8(Utf8Error),
}
impl Display for ParseError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self {
ParseError::Body(ref e) => write!(f, "unable to parse JSON body: {e}"),
ParseError::Encode(ref e) => write!(f, "failed to encode response: {e}"),
ParseError::Headers(ref e) => write!(f, "failed to parse headers: {e}"),
ParseError::InvalidContentType => write!(f, "unable to parse content type"),
ParseError::InvalidContentLength(ref e) => {
write!(f, "unable to parse content length: {e}")
}
ParseError::MissingContentLength => {
write!(f, "missing required `Content-Length` header")
}
ParseError::Utf8(ref e) => write!(f, "request contains invalid UTF8: {e}"),
}
}
}
impl Error for ParseError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match *self {
ParseError::Body(ref e) => Some(e),
ParseError::Encode(ref e) => Some(e),
ParseError::InvalidContentLength(ref e) => Some(e),
ParseError::Utf8(ref e) => Some(e),
_ => None,
}
}
}
impl From<serde_json::Error> for ParseError {
fn from(error: serde_json::Error) -> Self {
ParseError::Body(error)
}
}
impl From<IoError> for ParseError {
fn from(error: IoError) -> Self {
ParseError::Encode(error)
}
}
impl From<httparse::Error> for ParseError {
fn from(error: httparse::Error) -> Self {
ParseError::Headers(error)
}
}
impl From<ParseIntError> for ParseError {
fn from(error: ParseIntError) -> Self {
ParseError::InvalidContentLength(error)
}
}
impl From<Utf8Error> for ParseError {
fn from(error: Utf8Error) -> Self {
ParseError::Utf8(error)
}
}
/// Encodes and decodes Language Server Protocol messages.
pub struct LanguageServerCodec<T> {
content_len: Option<usize>,
_marker: PhantomData<T>,
}
impl<T> Default for LanguageServerCodec<T> {
fn default() -> Self {
LanguageServerCodec {
content_len: None,
_marker: PhantomData,
}
}
}
#[cfg(feature = "runtime-agnostic")]
impl<T: Serialize> Encoder for LanguageServerCodec<T> {
type Item = T;
type Error = ParseError;
fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
let msg = serde_json::to_string(&item)?;
trace!("-> {}", msg);
// Reserve just enough space to hold the `Content-Length: ` and `\r\n\r\n` constants,
// the length of the message, and the message body.
dst.reserve(msg.len() + number_of_digits(msg.len()) + 20);
let mut writer = dst.writer();
write!(writer, "Content-Length: {}\r\n\r\n{}", msg.len(), msg)?;
writer.flush()?;
Ok(())
}
}
#[cfg(feature = "runtime-tokio")]
impl<T: Serialize> Encoder<T> for LanguageServerCodec<T> {
type Error = ParseError;
fn encode(&mut self, item: T, dst: &mut BytesMut) -> Result<(), Self::Error> {
let msg = serde_json::to_string(&item)?;
trace!("-> {}", msg);
// Reserve just enough space to hold the `Content-Length: ` and `\r\n\r\n` constants,
// the length of the message, and the message body.
dst.reserve(msg.len() + number_of_digits(msg.len()) + 20);
let mut writer = dst.writer();
write!(writer, "Content-Length: {}\r\n\r\n{}", msg.len(), msg)?;
writer.flush()?;
Ok(())
}
}
fn number_of_digits(mut n: usize) -> usize {
let mut num_digits = 0;
while n > 0 {
n /= 10;
num_digits += 1;
}
num_digits
}
impl<T: DeserializeOwned> Decoder for LanguageServerCodec<T> {
type Item = T;
type Error = ParseError;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if let Some(content_len) = self.content_len {
if src.len() < content_len {
return Ok(None);
}
let bytes = &src[..content_len];
let message = std::str::from_utf8(bytes)?;
let result = if message.is_empty() {
Ok(None)
} else {
trace!("<- {}", message);
match serde_json::from_str(message) {
Ok(parsed) => Ok(Some(parsed)),
Err(err) => Err(err.into()),
}
};
src.advance(content_len);
self.content_len = None; // Reset state in preparation for parsing next message.
result
} else {
let mut dst = [httparse::EMPTY_HEADER; 2];
let (headers_len, headers) = match httparse::parse_headers(src, &mut dst)? {
httparse::Status::Complete(output) => output,
httparse::Status::Partial => return Ok(None),
};
match decode_headers(headers) {
Ok(content_len) => {
src.advance(headers_len);
self.content_len = Some(content_len);
self.decode(src) // Recurse right back in, now that `Content-Length` is known.
}
Err(err) => {
match err {
ParseError::MissingContentLength => {}
_ => src.advance(headers_len),
}
// Skip any garbage bytes by scanning ahead for another potential message.
src.advance(memmem::find(src, b"Content-Length").unwrap_or_default());
Err(err)
}
}
}
}
}
fn decode_headers(headers: &[httparse::Header<'_>]) -> Result<usize, ParseError> {
let mut content_len = None;
for header in headers {
match header.name {
"Content-Length" => {
let string = std::str::from_utf8(header.value)?;
let parsed_len = string.parse()?;
content_len = Some(parsed_len);
}
"Content-Type" => {
let string = std::str::from_utf8(header.value)?;
let charset = string
.split(';')
.skip(1)
.map(|param| param.trim())
.find_map(|param| param.strip_prefix("charset="));
match charset {
Some("utf-8") | Some("utf8") => {}
_ => return Err(ParseError::InvalidContentType),
}
}
other => warn!("encountered unsupported header: {:?}", other),
}
}
if let Some(content_len) = content_len {
Ok(content_len)
} else {
Err(ParseError::MissingContentLength)
}
}
#[cfg(test)]
mod tests {
use bytes::BytesMut;
use serde_json::Value;
use super::*;
macro_rules! assert_err {
($expression:expr, $($pattern:tt)+) => {
match $expression {
$($pattern)+ => (),
ref e => panic!("expected `{}` but got `{:?}`", stringify!($($pattern)+), e),
}
}
}
fn encode_message(content_type: Option<&str>, message: &str) -> String {
let content_type = content_type
.map(|ty| format!("\r\nContent-Type: {ty}"))
.unwrap_or_default();
format!(
"Content-Length: {}{}\r\n\r\n{}",
message.len(),
content_type,
message
)
}
#[test]
fn encode_and_decode() {
let decoded = r#"{"jsonrpc":"2.0","method":"exit"}"#;
let encoded = encode_message(None, decoded);
let mut codec = LanguageServerCodec::default();
let mut buffer = BytesMut::new();
let item: Value = serde_json::from_str(decoded).unwrap();
codec.encode(item, &mut buffer).unwrap();
assert_eq!(buffer, BytesMut::from(encoded.as_str()));
let mut buffer = BytesMut::from(encoded.as_str());
let message = codec.decode(&mut buffer).unwrap();
let decoded = serde_json::from_str(decoded).unwrap();
assert_eq!(message, Some(decoded));
}
#[test]
fn decodes_optional_content_type() {
let decoded = r#"{"jsonrpc":"2.0","method":"exit"}"#;
let content_type = "application/vscode-jsonrpc; charset=utf-8";
let encoded = encode_message(Some(content_type), decoded);
let mut codec = LanguageServerCodec::default();
let mut buffer = BytesMut::from(encoded.as_str());
let message = codec.decode(&mut buffer).unwrap();
let decoded_: Value = serde_json::from_str(decoded).unwrap();
assert_eq!(message, Some(decoded_));
let content_type = "application/vscode-jsonrpc; charset=utf8";
let encoded = encode_message(Some(content_type), decoded);
let mut buffer = BytesMut::from(encoded.as_str());
let message = codec.decode(&mut buffer).unwrap();
let decoded_: Value = serde_json::from_str(decoded).unwrap();
assert_eq!(message, Some(decoded_));
let content_type = "application/vscode-jsonrpc; charset=invalid";
let encoded = encode_message(Some(content_type), decoded);
let mut buffer = BytesMut::from(encoded.as_str());
assert_err!(
codec.decode(&mut buffer),
Err(ParseError::InvalidContentType)
);
let content_type = "application/vscode-jsonrpc";
let encoded = encode_message(Some(content_type), decoded);
let mut buffer = BytesMut::from(encoded.as_str());
assert_err!(
codec.decode(&mut buffer),
Err(ParseError::InvalidContentType)
);
let content_type = "this-mime-should-be-ignored; charset=utf8";
let encoded = encode_message(Some(content_type), decoded);
let mut buffer = BytesMut::from(encoded.as_str());
let message = codec.decode(&mut buffer).unwrap();
let decoded_: Value = serde_json::from_str(decoded).unwrap();
assert_eq!(message, Some(decoded_));
}
#[test]
fn decodes_zero_length_message() {
let content_type = "application/vscode-jsonrpc; charset=utf-8";
let encoded = encode_message(Some(content_type), "");
let mut codec = LanguageServerCodec::default();
let mut buffer = BytesMut::from(encoded.as_str());
let message: Option<Value> = codec.decode(&mut buffer).unwrap();
assert_eq!(message, None);
}
#[test]
fn recovers_from_parse_error() {
let decoded = r#"{"jsonrpc":"2.0","method":"exit"}"#;
let encoded = encode_message(None, decoded);
let mixed = format!("foobar{encoded}Content-Length: foobar\r\n\r\n{encoded}");
let mut codec = LanguageServerCodec::default();
let mut buffer = BytesMut::from(mixed.as_str());
assert_err!(
codec.decode(&mut buffer),
Err(ParseError::MissingContentLength)
);
let message: Option<Value> = codec.decode(&mut buffer).unwrap();
let first_valid = serde_json::from_str(decoded).unwrap();
assert_eq!(message, Some(first_valid));
assert_err!(
codec.decode(&mut buffer),
Err(ParseError::InvalidContentLength(_))
);
let message = codec.decode(&mut buffer).unwrap();
let second_valid = serde_json::from_str(decoded).unwrap();
assert_eq!(message, Some(second_valid));
let message = codec.decode(&mut buffer).unwrap();
assert_eq!(message, None);
}
#[test]
fn decodes_small_chunks() {
let decoded = r#"{"jsonrpc":"2.0","method":"exit"}"#;
let content_type = "application/vscode-jsonrpc; charset=utf-8";
let encoded = encode_message(Some(content_type), decoded);
let mut codec = LanguageServerCodec::default();
let mut buffer = BytesMut::from(encoded.as_str());
let rest = buffer.split_off(40);
let message = codec.decode(&mut buffer).unwrap();
assert_eq!(message, None);
buffer.unsplit(rest);
let rest = buffer.split_off(80);
let message = codec.decode(&mut buffer).unwrap();
assert_eq!(message, None);
buffer.unsplit(rest);
let rest = buffer.split_off(16);
let message = codec.decode(&mut buffer).unwrap();
assert_eq!(message, None);
buffer.unsplit(rest);
let decoded: Value = serde_json::from_str(decoded).unwrap();
let message = codec.decode(&mut buffer).unwrap();
assert_eq!(message, Some(decoded));
}
}