crates/korp-map-wire/src/encoding.rs
//! **HTTP content encoding** of the HTTP door's replies: zstd, brotli or gzip, chosen from
//! the request's `Accept-Encoding`, for Arrow and JSON replies of at least
//! [`MIN_SIZE`] bytes. All three are pure Rust: zstd is the `zstd` crate patched to the
//! mzstd stand-in (the repository's `[patch.crates-io]`), brotli the `brotli` crate,
//! gzip `flate2` on miniz_oxide.
//!
//! This is the transport's compression, undone by the HTTP client (a browser does it
//! unasked). `?compress=zstd` on `/v1/map/{kind}` is a different thing: Arrow IPC buffer
//! compression inside the stream, which the Arrow reader undoes. A reply that carries
//! it is not compressed again.
use std::io::{self, Write};
/// Replies shorter than this go out as they are: about one TCP packet's payload, below
/// which encoding saves no round trip (an Arrow reply with no rows, its schema alone,
/// is about 1 KiB).
pub const MIN_SIZE: usize = 1400;
// The levels are the fast ones: the reply is encoded as the map is read, so the coder
// must outrun the reader and the link. On a whole-Sweden areas reply (55 MB of Arrow,
// 1 MiB pieces, one core) zstd 1 makes 3.64x at about 370 MB/s (level 3: 3.54x, 245
// MB/s), brotli 3 3.59x at 110 MB/s (quality 5: 3.95x, but 39 MB/s), gzip 1 3.30x at
// 258 MB/s (the default 6: 3.56x, 24 MB/s).
/// zstd's level.
const ZSTD_LEVEL: i32 = 1;
/// brotli's quality (0..=11) and window.
const BROTLI_QUALITY: u32 = 3;
const BROTLI_WINDOW: u32 = 22;
/// gzip's level (0..=9).
const GZIP_LEVEL: u32 = 1;
/// One content coding the server can send.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ContentEncoding {
/// `zstd` (RFC 8878).
Zstd,
/// `br` (RFC 7932).
Brotli,
/// `gzip` (RFC 1952).
Gzip,
}
impl ContentEncoding {
/// Every coding, in the server's order of preference.
pub const ALL: [ContentEncoding; 3] = [
ContentEncoding::Zstd,
ContentEncoding::Brotli,
ContentEncoding::Gzip,
];
/// The `Content-Encoding` token.
#[must_use]
pub const fn token(self) -> &'static str {
match self {
ContentEncoding::Zstd => "zstd",
ContentEncoding::Brotli => "br",
ContentEncoding::Gzip => "gzip",
}
}
/// **The coding to answer an `Accept-Encoding` with**: the one with the highest
/// `q` (a missing `q` is 1, `q=0` refuses), ties broken by [`Self::ALL`]'s order; `*`
/// stands for any coding not named. `None`: send the reply as it is.
#[must_use]
pub fn negotiate(accept: Option<&str>) -> Option<Self> {
let accept = accept?;
let mut named: Vec<(String, f32)> = Vec::new();
for item in accept.split(',') {
let mut parts = item.split(';');
let token = parts.next().unwrap_or("").trim().to_ascii_lowercase();
if token.is_empty() {
continue;
}
let mut q = 1.0f32;
for p in parts {
if let Some(v) = p
.trim()
.strip_prefix("q=")
.or_else(|| p.trim().strip_prefix("Q="))
{
q = v.trim().parse().unwrap_or(0.0);
}
}
named.push((token, q));
}
let star = named.iter().find(|(t, _)| t == "*").map(|(_, q)| *q);
let mut best: Option<(Self, f32)> = None;
for c in Self::ALL {
let q = named
.iter()
.find(|(t, _)| t == c.token() || (c == Self::Gzip && t == "x-gzip"))
.map(|(_, q)| *q)
.or(star)
.unwrap_or(0.0);
if q > 0.0 && best.is_none_or(|(_, b)| q > b) {
best = Some((c, q));
}
}
best.map(|(c, _)| c)
}
/// A streaming encoder of this coding.
pub fn encoder(self) -> io::Result<Box<dyn ChunkEncoder>> {
Ok(match self {
ContentEncoding::Zstd => Box::new(Zstd(zstd::stream::write::Encoder::new(
Vec::new(),
ZSTD_LEVEL,
)?)),
ContentEncoding::Brotli => Box::new(Brotli(Some(brotli::CompressorWriter::new(
Vec::new(),
64 * 1024,
BROTLI_QUALITY,
BROTLI_WINDOW,
)))),
ContentEncoding::Gzip => Box::new(Gzip(flate2::write::GzEncoder::new(
Vec::new(),
flate2::Compression::new(GZIP_LEVEL),
))),
})
}
/// `data` encoded whole.
pub fn encode_all(self, data: &[u8]) -> io::Result<Vec<u8>> {
let mut e = self.encoder()?;
let mut out = e.push(data)?;
out.extend(e.finish()?);
Ok(out)
}
}
/// **A streaming encoder**: each [`push`](ChunkEncoder::push) returns the encoded bytes
/// that can be sent now (flushed, so a reader can decode everything pushed so far);
/// [`finish`](ChunkEncoder::finish) ends the stream.
pub trait ChunkEncoder: Send {
/// Encode `data`; the bytes to send now.
fn push(&mut self, data: &[u8]) -> io::Result<Vec<u8>>;
/// End the stream; its last bytes.
fn finish(self: Box<Self>) -> io::Result<Vec<u8>>;
}
struct Zstd(zstd::stream::write::Encoder<'static, Vec<u8>>);
impl ChunkEncoder for Zstd {
fn push(&mut self, data: &[u8]) -> io::Result<Vec<u8>> {
self.0.write_all(data)?;
self.0.flush()?;
Ok(std::mem::take(self.0.get_mut()))
}
fn finish(self: Box<Self>) -> io::Result<Vec<u8>> {
self.0.finish()
}
}
struct Brotli(Option<brotli::CompressorWriter<Vec<u8>>>);
impl ChunkEncoder for Brotli {
fn push(&mut self, data: &[u8]) -> io::Result<Vec<u8>> {
let w = self.0.as_mut().expect("not finished");
w.write_all(data)?;
w.flush()?;
Ok(std::mem::take(w.get_mut()))
}
fn finish(mut self: Box<Self>) -> io::Result<Vec<u8>> {
Ok(self.0.take().expect("not finished").into_inner())
}
}
struct Gzip(flate2::write::GzEncoder<Vec<u8>>);
impl ChunkEncoder for Gzip {
fn push(&mut self, data: &[u8]) -> io::Result<Vec<u8>> {
self.0.write_all(data)?;
self.0.flush()?;
Ok(std::mem::take(self.0.get_mut()))
}
fn finish(self: Box<Self>) -> io::Result<Vec<u8>> {
self.0.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
fn decode(c: ContentEncoding, data: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
match c {
ContentEncoding::Zstd => out = zstd::stream::decode_all(data).unwrap(),
ContentEncoding::Brotli => {
brotli::Decompressor::new(data, 4096)
.read_to_end(&mut out)
.unwrap();
}
ContentEncoding::Gzip => {
flate2::read::GzDecoder::new(data)
.read_to_end(&mut out)
.unwrap();
}
}
out
}
#[test]
fn the_coding_is_chosen_by_q_then_by_the_servers_order() {
let n = |a: &str| ContentEncoding::negotiate(Some(a)).map(ContentEncoding::token);
assert_eq!(ContentEncoding::negotiate(None), None);
assert_eq!(n(""), None);
assert_eq!(n("identity"), None);
assert_eq!(n("gzip, deflate, br, zstd"), Some("zstd"));
assert_eq!(n("gzip, deflate, br"), Some("br"));
assert_eq!(n("gzip"), Some("gzip"));
assert_eq!(n("x-gzip"), Some("gzip"));
assert_eq!(n("zstd;q=0.5, gzip;q=0.8"), Some("gzip"));
assert_eq!(n("zstd;q=0, br;q=0, gzip;q=0"), None);
assert_eq!(n("*"), Some("zstd"));
assert_eq!(n("zstd;q=0, *;q=0.3"), Some("br"));
assert_eq!(n(" BR ; q=1.0 "), Some("br"));
assert_eq!(n("gzip;q=abc"), None);
}
#[test]
fn every_coding_gives_back_the_same_bytes_whole_and_streamed() {
let data: Vec<u8> = (0..200_000u32)
.flat_map(|i| (i % 1000).to_le_bytes())
.collect();
for c in ContentEncoding::ALL {
let whole = c.encode_all(&data).unwrap();
assert!(whole.len() < data.len() / 4, "{c:?}: {}", whole.len());
assert_eq!(decode(c, &whole), data, "{c:?} whole");
let mut e = c.encoder().unwrap();
let mut streamed = Vec::new();
for (k, chunk) in data.chunks(77_777).enumerate() {
let out = e.push(chunk).unwrap();
streamed.extend(&out);
// Flushed: everything pushed so far decodes from what was sent.
if c != ContentEncoding::Zstd {
let got = decode_prefix(c, &streamed);
assert_eq!(
got.len(),
(k * 77_777 + chunk.len()).min(data.len()),
"{c:?}"
);
}
}
streamed.extend(e.finish().unwrap());
assert_eq!(decode(c, &streamed), data, "{c:?} streamed");
}
}
/// What a decoder gets out of an unfinished stream.
fn decode_prefix(c: ContentEncoding, data: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let mut buf = [0u8; 8192];
let mut r: Box<dyn Read> = match c {
ContentEncoding::Brotli => Box::new(brotli::Decompressor::new(data, 4096)),
ContentEncoding::Gzip => Box::new(flate2::read::GzDecoder::new(data)),
ContentEncoding::Zstd => unreachable!(),
};
while let Ok(n) = r.read(&mut buf) {
if n == 0 {
break;
}
out.extend_from_slice(&buf[..n]);
}
out
}
}