use super::error::{ProtocolError, ProtocolResult};
use links_notation::binary::packet::BINARY_VERSION_1;
use links_notation::binary::{
decode_document, encode_document_with_limits, format_document, parse_document,
BinaryLinoOptions, DecodeLimits, LinksPacket, LinoDocument,
};
use links_notation::LiNo;
use std::fmt::Debug;
use std::io::{self, BufRead, BufReader, Read, Write};
use std::net::TcpStream;
use std::time::Duration;
pub trait LinoProtocol: Debug + Send + Sync {
fn write_document(
&self,
writer: &mut dyn Write,
document: &[LiNo<String>],
) -> ProtocolResult<()>;
fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>>;
}
impl<P: LinoProtocol + ?Sized> LinoProtocol for Box<P> {
fn write_document(
&self,
writer: &mut dyn Write,
document: &[LiNo<String>],
) -> ProtocolResult<()> {
(**self).write_document(writer, document)
}
fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
(**self).read_document(reader)
}
}
pub const DEFAULT_MAX_TEXT_BYTES: usize = 64 << 20;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ProtocolLimits {
pub binary: DecodeLimits,
pub max_text_bytes: usize,
}
impl Default for ProtocolLimits {
fn default() -> Self {
Self {
binary: DecodeLimits::default(),
max_text_bytes: DEFAULT_MAX_TEXT_BYTES,
}
}
}
impl ProtocolLimits {
pub fn unlimited() -> Self {
Self {
binary: DecodeLimits::unlimited(),
max_text_bytes: usize::MAX,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TextLinoProtocol {
pub max_text_bytes: usize,
}
impl Default for TextLinoProtocol {
fn default() -> Self {
Self {
max_text_bytes: DEFAULT_MAX_TEXT_BYTES,
}
}
}
impl TextLinoProtocol {
pub fn new() -> Self {
Self::default()
}
pub fn write_text(writer: &mut dyn Write, text: &str) -> ProtocolResult<()> {
let mut out = String::with_capacity(text.len() + 4);
if !text.is_empty() {
for line in text.split('\n') {
if line.starts_with('.') {
out.push('.');
}
out.push_str(line);
out.push('\n');
}
}
out.push_str(".\n");
writer.write_all(out.as_bytes())?;
writer.flush()?;
Ok(())
}
pub fn read_text(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<String>> {
let mut text = Vec::new();
let mut line = Vec::new();
let mut first = true;
loop {
line.clear();
let budget = self.max_text_bytes.saturating_sub(text.len()) as u64 + 2;
let read = reader.take(budget).read_until(b'\n', &mut line)?;
if read == 0 {
if first {
return Ok(None);
}
return Err(ProtocolError::malformed(
"stream ended before the '.' terminator line",
));
}
if line.last() != Some(&b'\n') {
if read as u64 >= budget {
return Err(ProtocolError::LimitExceeded(format!(
"text message longer than {} bytes",
self.max_text_bytes
)));
}
return Err(ProtocolError::malformed(
"stream ended before the '.' terminator line",
));
}
line.pop();
if line.last() == Some(&b'\r') {
line.pop();
}
if line == b"." {
break;
}
if !first {
text.push(b'\n');
}
first = false;
let content = line.strip_prefix(b".").unwrap_or(&line);
text.extend_from_slice(content);
}
String::from_utf8(text)
.map(Some)
.map_err(|_| ProtocolError::malformed("text message is not valid UTF-8"))
}
}
impl LinoProtocol for TextLinoProtocol {
fn write_document(
&self,
writer: &mut dyn Write,
document: &[LiNo<String>],
) -> ProtocolResult<()> {
Self::write_text(writer, &format_document(document))
}
fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
self.read_text(reader)?
.map(|text| parse_document(&text).map_err(ProtocolError::from))
.transpose()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct BinaryLinoProtocol {
pub options: BinaryLinoOptions,
pub limits: DecodeLimits,
}
impl BinaryLinoProtocol {
pub fn new() -> Self {
Self::default()
}
pub fn with_options(options: BinaryLinoOptions) -> Self {
Self {
options,
..Self::default()
}
}
pub fn encode(&self, document: &[LiNo<String>]) -> ProtocolResult<Vec<u8>> {
Ok(encode_document_with_limits(document, self.options, &self.limits)?.to_bytes()?)
}
pub fn decode(&self, bytes: &[u8]) -> ProtocolResult<LinoDocument> {
let packet = LinksPacket::from_bytes(bytes, &self.limits)?;
Ok(decode_document(&packet, &self.limits)?)
}
}
impl LinoProtocol for BinaryLinoProtocol {
fn write_document(
&self,
writer: &mut dyn Write,
document: &[LiNo<String>],
) -> ProtocolResult<()> {
writer.write_all(&self.encode(document)?)?;
writer.flush()?;
Ok(())
}
fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
LinksPacket::read_from(reader, &self.limits)?
.map(|packet| Ok(decode_document(&packet, &self.limits)?))
.transpose()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MessageFormat {
Text,
Binary(BinaryLinoOptions),
}
impl MessageFormat {
pub fn protocol(self, limits: ProtocolLimits) -> Box<dyn LinoProtocol> {
match self {
MessageFormat::Text => Box::new(TextLinoProtocol {
max_text_bytes: limits.max_text_bytes,
}),
MessageFormat::Binary(options) => Box::new(BinaryLinoProtocol {
options,
limits: limits.binary,
}),
}
}
}
pub fn is_binary_start(byte: u8) -> bool {
byte & 0xF0 == BINARY_VERSION_1
}
pub fn read_any_document(
reader: &mut dyn BufRead,
limits: &ProtocolLimits,
) -> ProtocolResult<Option<(LinoDocument, MessageFormat)>> {
let Some(&first) = reader.fill_buf()?.first() else {
return Ok(None);
};
if !is_binary_start(first) {
let text = TextLinoProtocol {
max_text_bytes: limits.max_text_bytes,
};
return Ok(text
.read_document(reader)?
.map(|document| (document, MessageFormat::Text)));
}
LinksPacket::read_from(reader, &limits.binary)?
.map(|packet| {
let document = decode_document(&packet, &limits.binary)?;
Ok((
document,
MessageFormat::Binary(BinaryLinoOptions::of_packet(&packet)),
))
})
.transpose()
}
#[derive(Debug)]
pub struct LinoConnection<S: Read + Write, P: LinoProtocol> {
stream: BufReader<S>,
protocol: P,
}
impl<S: Read + Write, P: LinoProtocol> LinoConnection<S, P> {
pub fn new(stream: S, protocol: P) -> Self {
Self {
stream: BufReader::new(stream),
protocol,
}
}
pub fn protocol(&self) -> &P {
&self.protocol
}
pub fn send(&mut self, document: &[LiNo<String>]) -> ProtocolResult<()> {
let mut buffer = Vec::new();
self.protocol.write_document(&mut buffer, document)?;
let stream = self.stream.get_mut();
stream.write_all(&buffer)?;
stream.flush()?;
Ok(())
}
pub fn receive(&mut self) -> ProtocolResult<Option<LinoDocument>> {
self.protocol.read_document(&mut self.stream)
}
pub fn request(&mut self, document: &[LiNo<String>]) -> ProtocolResult<LinoDocument> {
self.send(document)?;
self.receive()?
.ok_or_else(|| ProtocolError::malformed("connection closed before the reply"))
}
pub fn into_inner(self) -> S {
self.stream.into_inner()
}
}
impl<P: LinoProtocol> LinoConnection<TcpStream, P> {
pub fn wait_for_message(&mut self, timeout: Duration) -> ProtocolResult<bool> {
if !self.stream.buffer().is_empty() {
return Ok(true);
}
let stream = self.stream.get_ref();
let previous = stream.read_timeout()?;
stream.set_read_timeout(Some(timeout.max(Duration::from_millis(1))))?;
let arrived = self.stream.fill_buf().map(|_| ());
self.stream.get_ref().set_read_timeout(previous)?;
match arrived {
Ok(()) => Ok(true),
Err(error)
if matches!(
error.kind(),
io::ErrorKind::WouldBlock
| io::ErrorKind::TimedOut
| io::ErrorKind::Interrupted
) =>
{
Ok(false)
}
Err(error) => Err(error.into()),
}
}
}