Skip to main content

khive_pack_session/mirror/
raw_codec.rs

1//! Standalone raw-value codec; mirror read and write paths do not use it yet.
2//!
3//! Legacy TEXT is unconditional plaintext. BLOB prefix 0x01 carries a level-3
4//! zstd frame without a dictionary; other prefixes remain unsupported.
5
6use std::borrow::Cow;
7use std::fmt;
8
9use khive_storage::SqlValue;
10
11/// A format, compression or UTF-8 refusal without the stored raw content.
12#[derive(Debug)]
13pub enum RawCodecError {
14    UnsupportedValue(&'static str),
15    EmptyBlob,
16    UnsupportedPrefix(u8),
17    Compression(std::io::Error),
18    Decompression(std::io::Error),
19    InvalidUtf8(std::str::Utf8Error),
20}
21
22impl fmt::Display for RawCodecError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            Self::UnsupportedValue(kind) => {
26                write!(f, "session raw codec requires TEXT or BLOB, got {kind}")
27            }
28            Self::EmptyBlob => f.write_str("session raw BLOB has no format prefix"),
29            Self::UnsupportedPrefix(prefix) => {
30                write!(f, "unsupported session raw BLOB prefix 0x{prefix:02x}")
31            }
32            Self::Compression(error) => write!(f, "session raw compression failed: {error}"),
33            Self::Decompression(error) => write!(f, "session raw decompression failed: {error}"),
34            Self::InvalidUtf8(error) => write!(f, "decoded session raw is not UTF-8: {error}"),
35        }
36    }
37}
38
39impl std::error::Error for RawCodecError {
40    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
41        match self {
42            Self::Compression(error) | Self::Decompression(error) => Some(error),
43            Self::InvalidUtf8(error) => Some(error),
44            _ => None,
45        }
46    }
47}
48
49/// Encode plaintext as a version-prefixed BLOB, including an empty plaintext.
50///
51/// Compression failures are returned; no TEXT or uncompressed fallback is used.
52pub fn encode_raw(raw: &str) -> Result<SqlValue, RawCodecError> {
53    let frame = zstd::bulk::compress(raw.as_bytes(), 3).map_err(RawCodecError::Compression)?;
54    let mut blob = Vec::with_capacity(frame.len() + 1);
55    blob.push(0x01);
56    blob.extend_from_slice(&frame);
57    Ok(SqlValue::Blob(blob))
58}
59
60/// Decode a stored raw value with a caller-selected BLOB output-size bound.
61///
62/// TEXT is borrowed byte-for-byte, even when the BLOB bound is zero. The bound
63/// limits decompressed bytes only; it does not set a storage or operator policy.
64/// Invalid prefixes, frames, excessive output and invalid UTF-8 return errors.
65pub fn decode_raw(
66    value: &SqlValue,
67    max_decoded_blob_bytes: usize,
68) -> Result<Cow<'_, str>, RawCodecError> {
69    match value {
70        SqlValue::Text(text) => Ok(Cow::Borrowed(text)),
71        SqlValue::Blob(blob) => {
72            let (&prefix, frame) = blob.split_first().ok_or(RawCodecError::EmptyBlob)?;
73            if prefix != 0x01 {
74                return Err(RawCodecError::UnsupportedPrefix(prefix));
75            }
76            // zstd accepts an empty byte slice as zero output, but this format
77            // requires a real frame even when the original plaintext is empty.
78            if frame.is_empty() {
79                return Err(RawCodecError::Decompression(std::io::Error::new(
80                    std::io::ErrorKind::UnexpectedEof,
81                    "session raw zstd frame is empty",
82                )));
83            }
84            let bytes = zstd::bulk::decompress(frame, max_decoded_blob_bytes)
85                .map_err(RawCodecError::Decompression)?;
86            let text = String::from_utf8(bytes)
87                .map_err(|error| RawCodecError::InvalidUtf8(error.utf8_error()))?;
88            Ok(Cow::Owned(text))
89        }
90        SqlValue::Null => Err(RawCodecError::UnsupportedValue("Null")),
91        SqlValue::Bool(_) => Err(RawCodecError::UnsupportedValue("Bool")),
92        SqlValue::Integer(_) => Err(RawCodecError::UnsupportedValue("Integer")),
93        SqlValue::Float(_) => Err(RawCodecError::UnsupportedValue("Float")),
94        SqlValue::Json(_) => Err(RawCodecError::UnsupportedValue("Json")),
95        SqlValue::Uuid(_) => Err(RawCodecError::UnsupportedValue("Uuid")),
96        SqlValue::Timestamp(_) => Err(RawCodecError::UnsupportedValue("Timestamp")),
97    }
98}