legit-streams 0.1.3

A Redis Streams work contract for task and result envelopes, with a worker loop that leases, reclaims and replies, a producer and a result reader
Documentation
//! The bounds on an entry, and the checks every envelope makes on its raw fields.

use std::collections::HashSet;

use crate::error::{Error, Result};

/// The bounds an envelope checks before it reads an entry's fields. An entry over any of them is
/// refused with [`Error::TooLarge`].
///
/// The defaults leave room for what the contract carries inline, base64 images included, while
/// refusing what no producer sends: 256 fields, 256-byte field names and 64 MiB per entry, names
/// and values together. Redis itself allows 512 MB per value.
///
/// The bounds apply once an entry has been read: they keep a hostile entry away from a handler
/// and off a result stream, but [`RedisStreams`](crate::RedisStreams) has already received it
/// whole by then.
///
/// ```
/// use legit_streams::Limits;
///
/// let limits = Limits { max_entry_bytes: 1024 * 1024, ..Limits::default() };
/// assert_eq!(limits.max_fields, 256);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limits {
    /// The most fields an entry may have.
    pub max_fields: usize,
    /// The longest a field name may be, in bytes.
    pub max_field_name: usize,
    /// The most bytes an entry's names and values may add up to.
    pub max_entry_bytes: usize,
}

impl Limits {
    /// The default bounds: 256 fields, 256-byte names and 64 MiB per entry.
    ///
    /// ```
    /// use legit_streams::Limits;
    ///
    /// assert_eq!(Limits::new(), Limits::default());
    /// ```
    #[must_use]
    pub const fn new() -> Self {
        Self {
            max_fields: 256,
            max_field_name: 256,
            max_entry_bytes: 64 * 1024 * 1024,
        }
    }

    /// Check a list of fields against these bounds.
    pub(crate) fn check<N: AsRef<[u8]>, V: AsRef<[u8]>>(&self, fields: &[(N, V)]) -> Result<()> {
        if fields.len() > self.max_fields {
            return Err(Error::TooLarge {
                what: "fields",
                limit: self.max_fields,
                actual: fields.len(),
            });
        }
        let mut total = 0usize;
        for (name, value) in fields {
            let name = name.as_ref();
            if name.len() > self.max_field_name {
                return Err(Error::TooLarge {
                    what: "field name",
                    limit: self.max_field_name,
                    actual: name.len(),
                });
            }
            total = total.saturating_add(name.len()).saturating_add(value.as_ref().len());
        }
        if total > self.max_entry_bytes {
            return Err(Error::TooLarge {
                what: "entry bytes",
                limit: self.max_entry_bytes,
                actual: total,
            });
        }
        Ok(())
    }
}

impl Default for Limits {
    fn default() -> Self {
        Self::new()
    }
}

/// Check raw fields against `limits` and decode them as UTF-8, refusing a name given twice.
pub(crate) fn decode(raw: &[(Vec<u8>, Vec<u8>)], limits: &Limits) -> Result<Vec<(String, String)>> {
    limits.check(raw)?;
    let mut seen = HashSet::with_capacity(raw.len());
    let mut fields = Vec::with_capacity(raw.len());
    for (name, value) in raw {
        let lossy = || String::from_utf8_lossy(name).into_owned();
        let name = std::str::from_utf8(name).map_err(|_| Error::InvalidUtf8 { field: lossy() })?;
        let value = std::str::from_utf8(value).map_err(|_| Error::InvalidUtf8 { field: name.to_owned() })?;
        if !seen.insert(name) {
            return Err(Error::DuplicateField(name.to_owned()));
        }
        fields.push((name.to_owned(), value.to_owned()));
    }
    Ok(fields)
}

/// Check already-decoded fields: the bounds, and no name given twice.
pub(crate) fn check_strings(fields: &[(String, String)], limits: &Limits) -> Result<()> {
    limits.check(fields)?;
    let mut seen = HashSet::with_capacity(fields.len());
    for (name, _) in fields {
        if !seen.insert(name.as_str()) {
            return Err(Error::DuplicateField(name.clone()));
        }
    }
    Ok(())
}

/// The value of the first field named `name`.
pub(crate) fn get<'a>(fields: &'a [(String, String)], name: &str) -> Option<&'a str> {
    fields
        .iter()
        .find(|(key, _)| key == name)
        .map(|(_, value)| value.as_str())
}

/// The fields as the byte pairs [`Streams::xadd`](crate::Streams::xadd) takes.
pub(crate) fn as_bytes(fields: &[(String, String)]) -> Vec<(&[u8], &[u8])> {
    fields
        .iter()
        .map(|(name, value)| (name.as_bytes(), value.as_bytes()))
        .collect()
}

/// The value of the last raw field with this name, as UTF-8: a reader that takes a repeated name
/// takes its last occurrence, never the first.
pub(crate) fn last<'a>(raw: &'a [(Vec<u8>, Vec<u8>)], name: &str) -> Option<&'a str> {
    raw.iter()
        .rev()
        .find(|(key, _)| key == name.as_bytes())
        .and_then(|(_, value)| std::str::from_utf8(value).ok())
}