Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Eliminate looping, message reparsing in codec with take_until #274

Merged
merged 2 commits into from
May 20, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 55 additions & 25 deletions src/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ use bytes::buf::BufMut;
use bytes::{Buf, BytesMut};
use log::trace;
use nom::branch::alt;
use nom::bytes::streaming::{is_not, tag};
use nom::bytes::streaming::{is_not, tag, take_until};
use nom::character::streaming::{char, crlf, digit1, space0};
use nom::combinator::{map_res, opt};
use nom::combinator::{map, map_res, opt};
use nom::error::ErrorKind;
use nom::multi::length_data;
use nom::sequence::{delimited, terminated, tuple};
Expand Down Expand Up @@ -145,16 +145,18 @@ impl<T: DeserializeOwned> Decoder for LanguageServerCodec<T> {
}
Err(Err::Error(err)) | Err(Err::Failure(err)) => {
let code = err.code;
loop {
use ParseError::*;
match parse_message(src) {
Err(_) if !src.is_empty() => src.advance(1),
_ => match code {
ErrorKind::Digit | ErrorKind::MapRes => return Err(InvalidLength),
ErrorKind::Char | ErrorKind::IsNot => return Err(InvalidType),
_ => return Err(MissingHeader),
},
}
let parsed_bytes = src.len() - err.input.len();
src.advance(parsed_bytes);

match find_next_message(src) {
Ok((_, position)) => src.advance(position),
Err(_) => src.advance(src.len()),
}

match code {
ErrorKind::Digit | ErrorKind::MapRes => return Err(ParseError::InvalidLength),
ErrorKind::Char | ErrorKind::IsNot => return Err(ParseError::InvalidType),
_ => return Err(ParseError::MissingHeader),
}
}
};
Expand Down Expand Up @@ -193,17 +195,34 @@ fn parse_message(input: &[u8]) -> IResult<&[u8], &[u8]> {
message(input)
}

fn find_next_message(input: &[u8]) -> IResult<&[u8], usize> {
map(take_until("Content-Length"), |s: &[u8]| s.len())(input)
}

#[cfg(test)]
mod tests {
use bytes::BytesMut;
use serde_json::Value;

use super::*;

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"}"#.to_string();
let encoded = format!("Content-Length: {}\r\n\r\n{}", decoded.len(), decoded);
let decoded = r#"{"jsonrpc":"2.0","method":"exit"}"#;
let encoded = encode_message(None, &decoded);

let mut codec = LanguageServerCodec::default();
let mut buffer = BytesMut::new();
Expand All @@ -219,10 +238,9 @@ mod tests {

#[test]
fn decodes_optional_content_type() {
let decoded = r#"{"jsonrpc":"2.0","method":"exit"}"#.to_string();
let content_len = format!("Content-Length: {}", decoded.len());
let content_type = "Content-Type: application/vscode-jsonrpc; charset=utf-8".to_string();
let encoded = format!("{}\r\n{}\r\n\r\n{}", content_len, content_type, decoded);
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());
Expand All @@ -233,8 +251,8 @@ mod tests {

#[test]
fn decodes_zero_length_message() {
let content_type = "Content-Type: application/vscode-jsonrpc; charset=utf-8".to_string();
let encoded = format!("Content-Length: 0\r\n{}\r\n\r\n", content_type);
let content_type = "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());
Expand All @@ -244,9 +262,9 @@ mod tests {

#[test]
fn recovers_from_parse_error() {
let decoded = r#"{"jsonrpc":"2.0","method":"exit"}"#.to_string();
let encoded = format!("Content-Length: {}\r\n\r\n{}", decoded.len(), decoded);
let mixed = format!("1234567890abcdefgh{}", encoded);
let decoded = r#"{"jsonrpc":"2.0","method":"exit"}"#;
let encoded = encode_message(None, decoded);
let mixed = format!("foobar{}Content-Length: foobar\r\n\r\n{}", encoded, encoded);

let mut codec = LanguageServerCodec::default();
let mut buffer = BytesMut::from(mixed.as_str());
Expand All @@ -256,8 +274,20 @@ mod tests {
other => panic!("expected `Err(ParseError::MissingHeader)`, got {:?}", other),
}

let message: Option<Value> = codec.decode(&mut buffer).unwrap();
let first_valid = serde_json::from_str(&decoded).unwrap();
assert_eq!(message, Some(first_valid));

match codec.decode(&mut buffer) {
Err(ParseError::InvalidLength) => {}
other => panic!("expected `Err(ParseError::InvalidLength)`, got {:?}", other),
}

let message = codec.decode(&mut buffer).unwrap();
let decoded: Value = serde_json::from_str(&decoded).unwrap();
assert_eq!(message, Some(decoded));
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);
}
}