Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-wire/src/ipc.rs

//! **One encoder** for both doors' bytes: Arrow IPC stream format, optionally zstd
//! (through the `zstd` stand-in on mzstd).

use std::str::FromStr;

use arrow_array::RecordBatch;
use arrow_ipc::CompressionType;
use arrow_ipc::writer::{IpcWriteOptions, StreamWriter};
use arrow_schema::Schema;

use crate::error::{Code, WireError};

/// The HTTP reply's content type.
pub const CONTENT_TYPE: &str = "application/vnd.apache.arrow.stream";

/// IPC body compression.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Compression {
    /// Plain buffers (the default).
    #[default]
    None,
    /// zstd buffer compression (`?compress=zstd`).
    Zstd,
}

impl FromStr for Compression {
    type Err = WireError;
    fn from_str(s: &str) -> Result<Self, WireError> {
        match s {
            "zstd" => Ok(Compression::Zstd),
            "none" => Ok(Compression::None),
            _ => Err(WireError::new(
                Code::BadCompress,
                format!("compress {s:?} is not zstd or none"),
            )),
        }
    }
}

impl Compression {
    /// The IPC write options for this compression.
    pub fn write_options(self) -> Result<IpcWriteOptions, WireError> {
        let c = match self {
            Compression::None => None,
            Compression::Zstd => Some(CompressionType::ZSTD),
        };
        IpcWriteOptions::default()
            .try_with_compression(c)
            .map_err(|e| WireError::new(Code::EncodeFailed, format!("ipc options: {e}")))
    }
}

fn enc(e: impl std::fmt::Display) -> WireError {
    WireError::new(Code::EncodeFailed, format!("arrow ipc: {e}"))
}

/// An IPC stream written piece by piece: each call returns the bytes it produced, so a
/// door can send them as they come.
pub struct IpcChunks {
    writer: StreamWriter<Vec<u8>>,
}

impl IpcChunks {
    /// Start a stream; the returned bytes are the schema message.
    pub fn begin(schema: &Schema, compression: Compression) -> Result<(Self, Vec<u8>), WireError> {
        let mut writer =
            StreamWriter::try_new_with_options(Vec::new(), schema, compression.write_options()?)
                .map_err(enc)?;
        let head = std::mem::take(writer.get_mut());
        Ok((Self { writer }, head))
    }

    /// One batch's message.
    pub fn batch(&mut self, b: &RecordBatch) -> Result<Vec<u8>, WireError> {
        self.writer.write(b).map_err(enc)?;
        Ok(std::mem::take(self.writer.get_mut()))
    }

    /// The end-of-stream marker.
    pub fn finish(mut self) -> Result<Vec<u8>, WireError> {
        self.writer.finish().map_err(enc)?;
        Ok(std::mem::take(self.writer.get_mut()))
    }
}

/// A whole stream in one buffer.
pub fn encode_all(
    schema: &Schema,
    batches: &[RecordBatch],
    compression: Compression,
) -> Result<Vec<u8>, WireError> {
    let (mut w, mut out) = IpcChunks::begin(schema, compression)?;
    for b in batches {
        out.extend(w.batch(b)?);
    }
    out.extend(w.finish()?);
    Ok(out)
}