kiri-protocol 0.1.2

Framed MessagePack protocol for the kiri search worker
Documentation
//! The stdio wire protocol: a four-byte big-endian length, followed by a
//! MessagePack map. Each frame is independent and limited to MAX_FRAME_SIZE.

use anyhow::{Context, Result, ensure};
use kiri_core::{CaseSensitivity, MatchKind, MatcherMode, Snapshot, SortOrder};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::borrow::Cow;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};

pub const VERSION: u32 = 1;
pub const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;

#[derive(Debug, Default, Deserialize, Serialize)]
pub struct SearchOptions {
    pub matcher: Option<MatcherMode>,
    pub case_sensitive: Option<CaseSensitivity>,
    pub sort: Option<SortOrder>,
    pub empty_query_sort: Option<SortOrder>,
    pub limit: Option<usize>,
    pub history_weight: Option<f64>,
}

#[derive(Debug, Default, Deserialize, Serialize)]
pub struct FileOptions {
    pub hidden: Option<bool>,
    pub respect_ignore: Option<bool>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Item {
    pub text: String,
    pub value: String,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Source {
    Files {
        root: String,
        #[serde(default)]
        options: FileOptions,
    },
    Items {
        items: Vec<Item>,
    },
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Request {
    Hello {
        request_id: u64,
        version: u32,
    },
    Open {
        request_id: u64,
        session_id: u64,
        revision: u64,
        query: String,
        source: Source,
        #[serde(default)]
        options: SearchOptions,
    },
    Query {
        request_id: u64,
        session_id: u64,
        revision: u64,
        query: String,
    },
    Accept {
        request_id: u64,
        session_id: u64,
        values: Vec<String>,
    },
    Close {
        request_id: u64,
        session_id: u64,
    },
    Shutdown {
        request_id: u64,
    },
}

#[derive(Serialize)]
pub struct Match<'a> {
    pub id: u64,
    pub text: &'a str,
    pub value: Cow<'a, str>,
    pub score: u32,
    pub kind: &'a MatchKind,
    /// Half-open UTF-8 byte ranges in `text`.
    pub ranges: &'a [(usize, usize)],
}

#[derive(Serialize)]
pub struct SnapshotData<'a> {
    pub query: &'a str,
    pub discovering: bool,
    pub matching: bool,
    pub candidates: usize,
    pub matched: usize,
    pub results: Vec<Match<'a>>,
    pub error: Option<&'a str>,
}

impl<'a> From<&'a Snapshot> for SnapshotData<'a> {
    fn from(snapshot: &'a Snapshot) -> Self {
        Self {
            query: &snapshot.query,
            discovering: snapshot.discovering,
            matching: snapshot.matching,
            candidates: snapshot.candidates,
            matched: snapshot.matched,
            results: snapshot
                .results
                .iter()
                .map(|result| Match {
                    id: result.candidate.id,
                    text: &result.candidate.text,
                    value: String::from_utf8_lossy(&result.candidate.value),
                    score: result.score,
                    kind: &result.kind,
                    ranges: &result.ranges,
                })
                .collect(),
            error: snapshot.error.as_deref(),
        }
    }
}

#[derive(Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Event<'a> {
    Hello {
        request_id: u64,
        version: u32,
    },
    Ack {
        request_id: u64,
        session_id: Option<u64>,
    },
    Error {
        request_id: Option<u64>,
        session_id: Option<u64>,
        message: String,
    },
    Snapshot {
        session_id: u64,
        revision: u64,
        snapshot: SnapshotData<'a>,
    },
}

/// A clean EOF between frames returns `None`; a partial or invalid frame is an
/// error. The caller must finish a read before starting the next one.
pub async fn read_frame<R: AsyncRead + Unpin, T: DeserializeOwned>(
    reader: &mut R,
) -> Result<Option<T>> {
    let mut header = [0; 4];
    if reader.read(&mut header[..1]).await? == 0 {
        return Ok(None);
    }
    reader
        .read_exact(&mut header[1..])
        .await
        .context("truncated frame header")?;
    let size = u32::from_be_bytes(header) as usize;
    ensure!(
        size > 0 && size <= MAX_FRAME_SIZE,
        "invalid frame length {size}"
    );
    let mut payload = vec![0; size];
    reader
        .read_exact(&mut payload)
        .await
        .context("truncated frame payload")?;
    Ok(Some(
        rmp_serde::from_slice(&payload).context("invalid MessagePack frame")?,
    ))
}

pub async fn write_frame<W: AsyncWrite + Unpin, T: Serialize>(
    writer: &mut W,
    message: &T,
) -> Result<()> {
    let payload = rmp_serde::to_vec_named(message).context("encoding MessagePack frame")?;
    ensure!(
        !payload.is_empty() && payload.len() <= MAX_FRAME_SIZE,
        "invalid frame length {}",
        payload.len()
    );
    writer
        .write_all(&(payload.len() as u32).to_be_bytes())
        .await?;
    writer.write_all(&payload).await?;
    writer.flush().await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn fragmented_frames_preserve_boundaries() {
        let mut bytes = Vec::new();
        write_frame(
            &mut bytes,
            &Request::Hello {
                request_id: 1,
                version: VERSION,
            },
        )
        .await
        .unwrap();
        write_frame(&mut bytes, &Request::Shutdown { request_id: 2 })
            .await
            .unwrap();
        let (mut writer, mut reader) = tokio::io::duplex(1);
        let sender = tokio::spawn(async move {
            for byte in bytes {
                writer.write_all(&[byte]).await.unwrap();
            }
        });
        assert!(matches!(
            read_frame::<_, Request>(&mut reader).await.unwrap(),
            Some(Request::Hello {
                request_id: 1,
                version: VERSION
            })
        ));
        assert!(matches!(
            read_frame::<_, Request>(&mut reader).await.unwrap(),
            Some(Request::Shutdown { request_id: 2 })
        ));
        assert!(
            read_frame::<_, Request>(&mut reader)
                .await
                .unwrap()
                .is_none()
        );
        sender.await.unwrap();
    }

    #[tokio::test]
    async fn rejects_invalid_and_truncated_frames() {
        for bytes in [
            0u32.to_be_bytes().to_vec(),
            ((MAX_FRAME_SIZE + 1) as u32).to_be_bytes().to_vec(),
            vec![0, 0],
            vec![0, 0, 0, 2, 0x80],
        ] {
            assert!(
                read_frame::<_, Request>(&mut bytes.as_slice())
                    .await
                    .is_err()
            );
        }
    }
}