grippo 0.3.1

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/io/tokio.rs
// Purpose:   The tokio twins of the stream helpers, over a tokio-util codec
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`frames`] and [`write_frames`] for a tokio reader and writer, and the
//! [`StreamCodec`] under them. Built with the `tokio` feature.
//!
//! `FramedRead::new(socket, StreamCodec::new(&config))` is a `Stream` of
//! [`Frame<Bytes>`](Frame): each record is a `Bytes` slice of the read
//! buffer, with no copy, and tokio-util gives backpressure and a frame that
//! survives a cancelled `select!` branch. An oversize, malformed or cut frame
//! is an item, never an error, because one decoder error ends a `FramedRead`
//! (tokio-util's own `LinesCodec` and `LengthDelimitedCodec` return one for
//! an oversize frame, which is wrong for a long-running receiver).
//!
//! Parse each record as it comes. Batch with `ready_chunks` or
//! `chunks_timeout` from a stream utility crate, and move a heavy batch off
//! the runtime as the app sees fit: grippo never spawns.

use std::future::poll_fn;
use std::io;
use std::ops::Range;
use std::pin::{Pin, pin};

use ::tokio::io::{AsyncRead, AsyncWrite};
use bytes::{Bytes, BytesMut};
use futures_core::Stream;
use futures_sink::Sink;
use tokio_util::codec::{Decoder, Encoder, FramedRead, FramedWrite};

use super::{Frame, Scanner, Text, Writer};
use crate::parse::StreamConfig;

/// Sent to a `FramedWrite` of a [`StreamCodec`], it closes the stream: a
/// JSON array's `]`. [`write_frames`] sends it before it closes the writer.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Finish;

/// A tokio-util codec for a [`StreamConfig`] split: a [`Decoder`] of
/// [`Frame<Bytes>`](Frame) and an [`Encoder`] of records and [`Finish`].
#[derive(Debug, Clone)]
pub struct StreamCodec {
    scanner: Scanner,
    writer: Writer,
    /// Frames the last batch found, as ranges of `chunk`.
    ready: Vec<Frame<Range<usize>>>,
    /// The first of them `decode` hasn't handed out.
    next: usize,
    /// The bytes that batch took from the read buffer.
    chunk: Bytes,
    /// The decoder of a stream that isn't UTF-8.
    text: Option<Text>,
    /// Reads decoded to UTF-8 and not yet framed.
    decoded: BytesMut,
}

impl StreamCodec {
    /// A codec for `config`.
    #[must_use]
    pub fn new(config: &StreamConfig) -> Self {
        Self {
            scanner: Scanner::new(config),
            writer: Writer::new(config),
            ready: Vec::new(),
            next: 0,
            chunk: Bytes::new(),
            text: Text::new(config.encoding),
            decoded: BytesMut::new(),
        }
    }

    /// The scanner's state, for [`Scanner::consumed`] and the other queries.
    /// `decode` finds every frame a read holds in one pass and hands them out
    /// one a call, so the scanner can be ahead of the frames handed out.
    #[must_use]
    pub const fn scanner(&self) -> &Scanner {
        &self.scanner
    }

    /// The next frame: one the last batch queued, or the first of a new
    /// batch over all the frames `src` holds.
    fn scan(&mut self, src: &mut BytesMut, eof: bool) -> Option<Frame<Bytes>> {
        if self.next == self.ready.len() {
            if let Some(text) = &mut self.text {
                let decoded = &mut self.decoded;
                text.push(src, eof, |bytes| decoded.extend_from_slice(bytes));
                src.clear();
                let mut decoded = std::mem::take(&mut self.decoded);
                self.batch(&mut decoded, eof);
                self.decoded = decoded;
            } else {
                self.batch(src, eof);
            }
        }
        let frame = self.ready.get(self.next)?.clone();
        self.next += 1;
        Some(frame.map(|range| self.chunk.slice(range)))
    }

    /// Find every frame `src` holds and take their bytes as `chunk`.
    fn batch(&mut self, src: &mut BytesMut, eof: bool) {
        self.ready.clear();
        self.next = 0;
        let base = src.as_ptr().addr();
        let ready = &mut self.ready;
        let used = self.scanner.each(src, eof, |frame| {
            ready.push(frame.map(|bytes| {
                let start = bytes.as_ptr().addr() - base;
                start..start + bytes.len()
            }));
        });
        // One split a batch, so each frame costs a reference count, not a split. With no
        // frame the last batch's bytes go, so the next read can reuse the buffer.
        self.chunk = if used == 0 {
            Bytes::new()
        } else {
            src.split_to(used).freeze()
        };
        // At the end of input the scanner leaves nothing, so this drops no record.
        if eof {
            src.clear();
        }
    }
}

impl Decoder for StreamCodec {
    type Item = Frame<Bytes>;
    type Error = io::Error;

    fn decode(&mut self, src: &mut BytesMut) -> io::Result<Option<Frame<Bytes>>> {
        Ok(self.scan(src, false))
    }

    fn decode_eof(&mut self, src: &mut BytesMut) -> io::Result<Option<Frame<Bytes>>> {
        Ok(self.scan(src, true))
    }
}

impl StreamCodec {
    fn put(&mut self, record: &[u8], dst: &mut BytesMut) -> io::Result<()> {
        let around = self
            .writer
            .around(record)
            .map_err(|refused| io::Error::new(io::ErrorKind::InvalidInput, refused))?;
        dst.reserve(around.head().len() + record.len() + around.tail.len());
        dst.extend_from_slice(around.head());
        dst.extend_from_slice(record);
        dst.extend_from_slice(around.tail);
        Ok(())
    }
}

/// A record refused as [`Writer::frame`] refuses one is an
/// [`io::ErrorKind::InvalidInput`] error holding the
/// [`Refused`](super::Refused).
impl Encoder<&[u8]> for StreamCodec {
    type Error = io::Error;

    fn encode(&mut self, record: &[u8], dst: &mut BytesMut) -> io::Result<()> {
        self.put(record, dst)
    }
}

impl Encoder<Bytes> for StreamCodec {
    type Error = io::Error;

    fn encode(&mut self, record: Bytes, dst: &mut BytesMut) -> io::Result<()> {
        self.put(&record, dst)
    }
}

impl Encoder<Finish> for StreamCodec {
    type Error = io::Error;

    fn encode(&mut self, _: Finish, dst: &mut BytesMut) -> io::Result<()> {
        dst.extend_from_slice(self.writer.closing());
        Ok(())
    }
}

/// Read the frames of `config`'s split from `reader`: a `Stream` of
/// `io::Result<Frame<Bytes>>`, the error only the reader's.
pub fn frames<R: AsyncRead>(reader: R, config: &StreamConfig) -> FramedRead<R, StreamCodec> {
    FramedRead::new(reader, StreamCodec::new(config))
}

/// Write each record of `records` to `writer`, framed for `config`'s split,
/// then send [`Finish`] and close the writer.
///
/// # Errors
///
/// The writer's error, or [`io::ErrorKind::InvalidInput`] holding the
/// [`Refused`](super::Refused) for a record that wouldn't read back as
/// itself. The records before it are flushed.
pub async fn write_frames<W, S>(writer: W, config: &StreamConfig, records: S) -> io::Result<()>
where
    W: AsyncWrite + Unpin,
    S: Stream,
    S::Item: AsRef<[u8]>,
{
    let mut sink = FramedWrite::new(writer, StreamCodec::new(config));
    let mut records = pin!(records);
    while let Some(record) = poll_fn(|cx| records.as_mut().poll_next(cx)).await {
        poll_fn(|cx| Sink::<&[u8]>::poll_ready(Pin::new(&mut sink), cx)).await?;
        if let Err(e) = Pin::new(&mut sink).start_send(record.as_ref()) {
            poll_fn(|cx| Sink::<&[u8]>::poll_flush(Pin::new(&mut sink), cx)).await?;
            return Err(e);
        }
    }
    poll_fn(|cx| Sink::<Finish>::poll_ready(Pin::new(&mut sink), cx)).await?;
    Pin::new(&mut sink).start_send(Finish)?;
    poll_fn(|cx| Sink::<Finish>::poll_close(Pin::new(&mut sink), cx)).await
}