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
// MIT License
//
// Copyright (c) 2024 Robin Doer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
use bytes::{Buf, BytesMut};
use log::{debug, trace};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::fmt;
use std::io::{Cursor, Read, Write};
use thiserror::Error;
/// Error type used by the [`BsonReader`] and [`BsonWriter`] utilities.
#[derive(Error, Debug)]
pub enum BsonError {
/// An error occured while deserializing BSON data.
#[error(transparent)]
Deserialize(#[from] bson::de::Error),
/// An error occured while serializing BSON data.
#[error(transparent)]
Serialization(#[from] bson::ser::Error),
/// An IO-error occured.
#[error(transparent)]
Io(#[from] std::io::Error),
/// The connection to the peer is closed but there are still buffered data.
/// This means that the peer closed the connection while sending a frame.
#[error("connection reset by peer")]
ConnectionResetByPeer,
}
type BsonResult<T> = Result<T, BsonError>;
/// A utility to read [BSON](bson) encoded data from an arbitrary
/// [source](Read).
pub struct BsonReader<R> {
source: R,
buffer: BytesMut,
}
impl<R: Read> BsonReader<R> {
/// Creates a new `BsonReader` instance, which reads from the given`source`.
pub fn new(source: R) -> BsonReader<R> {
BsonReader {
source,
buffer: BytesMut::new(),
}
}
/// Reads a [BSON](bson) document from the attached source and deserialize
/// it into the given type `T`.
///
/// It reads data from the attached source until another BSON document is
/// available. Next, the document is serialized into `T` and returned into
/// a wrapped [`Some`] value. Returns [`None`] if the peer closes the
/// connection.
pub fn read<T: DeserializeOwned + fmt::Debug>(&mut self) -> BsonResult<Option<T>> {
loop {
if let Some(frame) = self.parse_frame()? {
return Ok(Some(frame));
}
let n = self.read_next_chunk()?;
if n == 0 {
if self.buffer.is_empty() {
// No buffered data, clean shutdown.
return Ok(None);
} else {
// There are still buffered data. This means that the peer
// closed the connection while sending a frame.
return Err(BsonError::ConnectionResetByPeer);
}
}
}
}
fn parse_frame<T: DeserializeOwned + fmt::Debug>(&mut self) -> BsonResult<Option<T>> {
if self.is_complete() {
let mut cursor = Cursor::new(&self.buffer[..]);
let bson = bson::from_reader(&mut cursor)?;
trace!("read doc {} bytes: {}", cursor.position(), bson);
let value = bson::from_bson(bson)?;
let pos = cursor.position();
self.buffer.advance(pos as usize);
debug!("read deserialized: {:?}", value);
Ok(Some(value))
} else {
Ok(None)
}
}
fn is_complete(&self) -> bool {
if self.buffer.remaining() >= 4 {
let mut slice = &self.buffer[..];
let len = slice.get_u32_le() as usize;
self.buffer.remaining() >= len
} else {
false
}
}
fn read_next_chunk(&mut self) -> BsonResult<usize> {
let mut buf = [0; 1024];
let n = self.source.read(&mut buf)?;
self.buffer.extend_from_slice(&buf[..n]);
Ok(n)
}
}
/// A utility to write [BSON](bson) encoded data into an arbitrary
/// [target](Write).
pub struct BsonWriter<W> {
target: W,
}
impl<W: Write> BsonWriter<W> {
/// Creates a new `BsonWriter` instance which writes into the given `target`.
pub fn new(target: W) -> BsonWriter<W> {
BsonWriter { target }
}
/// Deserializes the given `value` into a [BSON](bson) document and writes
/// it into the attached target.
pub fn write<T: Serialize + fmt::Debug>(&mut self, value: T) -> BsonResult<()> {
debug!("write serialized: {:?}", value);
let doc = bson::to_document(&value)?;
trace!("write doc {}", doc);
doc.to_writer(&mut self.target)?;
self.target.flush()?;
Ok(())
}
}