Skip to main content

kiri_protocol/
lib.rs

1//! The stdio wire protocol: a four-byte big-endian length, followed by a
2//! MessagePack map. Each frame is independent and limited to MAX_FRAME_SIZE.
3
4use anyhow::{Context, Result, ensure};
5use kiri_core::{CaseSensitivity, MatchKind, MatcherMode, Snapshot, SortOrder};
6use serde::{Deserialize, Serialize, de::DeserializeOwned};
7use std::borrow::Cow;
8use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
9
10pub const VERSION: u32 = 1;
11pub const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;
12
13#[derive(Debug, Default, Deserialize, Serialize)]
14pub struct SearchOptions {
15    pub matcher: Option<MatcherMode>,
16    pub case_sensitive: Option<CaseSensitivity>,
17    pub sort: Option<SortOrder>,
18    pub empty_query_sort: Option<SortOrder>,
19    pub limit: Option<usize>,
20    pub history_weight: Option<f64>,
21}
22
23#[derive(Debug, Default, Deserialize, Serialize)]
24pub struct FileOptions {
25    pub hidden: Option<bool>,
26    pub respect_ignore: Option<bool>,
27}
28
29#[derive(Debug, Deserialize, Serialize)]
30pub struct Item {
31    pub text: String,
32    pub value: String,
33}
34
35#[derive(Debug, Deserialize, Serialize)]
36#[serde(tag = "type", rename_all = "snake_case")]
37pub enum Source {
38    Files {
39        root: String,
40        #[serde(default)]
41        options: FileOptions,
42    },
43    Items {
44        items: Vec<Item>,
45    },
46}
47
48#[derive(Debug, Deserialize, Serialize)]
49#[serde(tag = "type", rename_all = "snake_case")]
50pub enum Request {
51    Hello {
52        request_id: u64,
53        version: u32,
54    },
55    Open {
56        request_id: u64,
57        session_id: u64,
58        revision: u64,
59        query: String,
60        source: Source,
61        #[serde(default)]
62        options: SearchOptions,
63    },
64    Query {
65        request_id: u64,
66        session_id: u64,
67        revision: u64,
68        query: String,
69    },
70    Accept {
71        request_id: u64,
72        session_id: u64,
73        values: Vec<String>,
74    },
75    Close {
76        request_id: u64,
77        session_id: u64,
78    },
79    Shutdown {
80        request_id: u64,
81    },
82}
83
84#[derive(Serialize)]
85pub struct Match<'a> {
86    pub id: u64,
87    pub text: &'a str,
88    pub value: Cow<'a, str>,
89    pub score: u32,
90    pub kind: &'a MatchKind,
91    /// Half-open UTF-8 byte ranges in `text`.
92    pub ranges: &'a [(usize, usize)],
93}
94
95#[derive(Serialize)]
96pub struct SnapshotData<'a> {
97    pub query: &'a str,
98    pub discovering: bool,
99    pub matching: bool,
100    pub candidates: usize,
101    pub matched: usize,
102    pub results: Vec<Match<'a>>,
103    pub error: Option<&'a str>,
104}
105
106impl<'a> From<&'a Snapshot> for SnapshotData<'a> {
107    fn from(snapshot: &'a Snapshot) -> Self {
108        Self {
109            query: &snapshot.query,
110            discovering: snapshot.discovering,
111            matching: snapshot.matching,
112            candidates: snapshot.candidates,
113            matched: snapshot.matched,
114            results: snapshot
115                .results
116                .iter()
117                .map(|result| Match {
118                    id: result.candidate.id,
119                    text: &result.candidate.text,
120                    value: String::from_utf8_lossy(&result.candidate.value),
121                    score: result.score,
122                    kind: &result.kind,
123                    ranges: &result.ranges,
124                })
125                .collect(),
126            error: snapshot.error.as_deref(),
127        }
128    }
129}
130
131#[derive(Serialize)]
132#[serde(tag = "type", rename_all = "snake_case")]
133pub enum Event<'a> {
134    Hello {
135        request_id: u64,
136        version: u32,
137    },
138    Ack {
139        request_id: u64,
140        session_id: Option<u64>,
141    },
142    Error {
143        request_id: Option<u64>,
144        session_id: Option<u64>,
145        message: String,
146    },
147    Snapshot {
148        session_id: u64,
149        revision: u64,
150        snapshot: SnapshotData<'a>,
151    },
152}
153
154/// A clean EOF between frames returns `None`; a partial or invalid frame is an
155/// error. The caller must finish a read before starting the next one.
156pub async fn read_frame<R: AsyncRead + Unpin, T: DeserializeOwned>(
157    reader: &mut R,
158) -> Result<Option<T>> {
159    let mut header = [0; 4];
160    if reader.read(&mut header[..1]).await? == 0 {
161        return Ok(None);
162    }
163    reader
164        .read_exact(&mut header[1..])
165        .await
166        .context("truncated frame header")?;
167    let size = u32::from_be_bytes(header) as usize;
168    ensure!(
169        size > 0 && size <= MAX_FRAME_SIZE,
170        "invalid frame length {size}"
171    );
172    let mut payload = vec![0; size];
173    reader
174        .read_exact(&mut payload)
175        .await
176        .context("truncated frame payload")?;
177    Ok(Some(
178        rmp_serde::from_slice(&payload).context("invalid MessagePack frame")?,
179    ))
180}
181
182pub async fn write_frame<W: AsyncWrite + Unpin, T: Serialize>(
183    writer: &mut W,
184    message: &T,
185) -> Result<()> {
186    let payload = rmp_serde::to_vec_named(message).context("encoding MessagePack frame")?;
187    ensure!(
188        !payload.is_empty() && payload.len() <= MAX_FRAME_SIZE,
189        "invalid frame length {}",
190        payload.len()
191    );
192    writer
193        .write_all(&(payload.len() as u32).to_be_bytes())
194        .await?;
195    writer.write_all(&payload).await?;
196    writer.flush().await?;
197    Ok(())
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    #[tokio::test]
205    async fn fragmented_frames_preserve_boundaries() {
206        let mut bytes = Vec::new();
207        write_frame(
208            &mut bytes,
209            &Request::Hello {
210                request_id: 1,
211                version: VERSION,
212            },
213        )
214        .await
215        .unwrap();
216        write_frame(&mut bytes, &Request::Shutdown { request_id: 2 })
217            .await
218            .unwrap();
219        let (mut writer, mut reader) = tokio::io::duplex(1);
220        let sender = tokio::spawn(async move {
221            for byte in bytes {
222                writer.write_all(&[byte]).await.unwrap();
223            }
224        });
225        assert!(matches!(
226            read_frame::<_, Request>(&mut reader).await.unwrap(),
227            Some(Request::Hello {
228                request_id: 1,
229                version: VERSION
230            })
231        ));
232        assert!(matches!(
233            read_frame::<_, Request>(&mut reader).await.unwrap(),
234            Some(Request::Shutdown { request_id: 2 })
235        ));
236        assert!(
237            read_frame::<_, Request>(&mut reader)
238                .await
239                .unwrap()
240                .is_none()
241        );
242        sender.await.unwrap();
243    }
244
245    #[tokio::test]
246    async fn rejects_invalid_and_truncated_frames() {
247        for bytes in [
248            0u32.to_be_bytes().to_vec(),
249            ((MAX_FRAME_SIZE + 1) as u32).to_be_bytes().to_vec(),
250            vec![0, 0],
251            vec![0, 0, 0, 2, 0x80],
252        ] {
253            assert!(
254                read_frame::<_, Request>(&mut bytes.as_slice())
255                    .await
256                    .is_err()
257            );
258        }
259    }
260}