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, Preview, Snapshot, SortOrder};
6use serde::{Deserialize, Serialize, de::DeserializeOwned};
7use std::borrow::Cow;
8use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
9
10pub const VERSION: u32 = 2;
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    /// Live grep: each match is a line inside a file under `root`.
44    Grep {
45        root: String,
46        #[serde(default)]
47        options: FileOptions,
48    },
49    Items {
50        items: Vec<Item>,
51    },
52}
53
54#[derive(Debug, Deserialize, Serialize)]
55#[serde(tag = "type", rename_all = "snake_case")]
56pub enum Request {
57    Hello {
58        request_id: u64,
59        version: u32,
60    },
61    Open {
62        request_id: u64,
63        session_id: u64,
64        revision: u64,
65        query: String,
66        source: Source,
67        #[serde(default)]
68        options: SearchOptions,
69    },
70    Query {
71        request_id: u64,
72        session_id: u64,
73        revision: u64,
74        query: String,
75    },
76    /// Ask for a file window. The answer is an `Event::Preview` with the same
77    /// `request_id`; a newer preview request for a session supersedes an older one.
78    Preview {
79        request_id: u64,
80        session_id: u64,
81        path: String,
82        line: Option<u32>,
83        before: Option<usize>,
84        after: Option<usize>,
85    },
86    Accept {
87        request_id: u64,
88        session_id: u64,
89        values: Vec<String>,
90    },
91    Close {
92        request_id: u64,
93        session_id: u64,
94    },
95    Shutdown {
96        request_id: u64,
97    },
98}
99
100#[derive(Serialize)]
101pub struct Match<'a> {
102    pub id: u64,
103    pub text: &'a str,
104    pub value: Cow<'a, str>,
105    pub score: u32,
106    pub kind: &'a MatchKind,
107    /// Half-open UTF-8 byte ranges in `text`.
108    pub ranges: &'a [(usize, usize)],
109    /// 1-based line of the first hit (grep only).
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub line: Option<u32>,
112    /// 1-based byte column of the first hit (grep only).
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub column: Option<u32>,
115}
116
117#[derive(Serialize)]
118pub struct SnapshotData<'a> {
119    pub query: &'a str,
120    pub discovering: bool,
121    pub matching: bool,
122    pub candidates: usize,
123    pub matched: usize,
124    pub results: Vec<Match<'a>>,
125    pub error: Option<&'a str>,
126}
127
128impl<'a> From<&'a Snapshot> for SnapshotData<'a> {
129    fn from(snapshot: &'a Snapshot) -> Self {
130        Self {
131            query: &snapshot.query,
132            discovering: snapshot.discovering,
133            matching: snapshot.matching,
134            candidates: snapshot.candidates,
135            matched: snapshot.matched,
136            results: snapshot
137                .results
138                .iter()
139                .map(|result| Match {
140                    id: result.candidate.id,
141                    text: &result.candidate.text,
142                    value: String::from_utf8_lossy(&result.candidate.value),
143                    score: result.score,
144                    kind: &result.kind,
145                    ranges: &result.ranges,
146                    line: result.candidate.location.map(|location| location.line),
147                    column: result.candidate.location.map(|location| location.column),
148                })
149                .collect(),
150            error: snapshot.error.as_deref(),
151        }
152    }
153}
154
155#[derive(Serialize)]
156#[serde(tag = "type", rename_all = "snake_case")]
157pub enum Event<'a> {
158    Hello {
159        request_id: u64,
160        version: u32,
161    },
162    Ack {
163        request_id: u64,
164        session_id: Option<u64>,
165    },
166    Error {
167        request_id: Option<u64>,
168        session_id: Option<u64>,
169        message: String,
170    },
171    Snapshot {
172        session_id: u64,
173        revision: u64,
174        snapshot: SnapshotData<'a>,
175    },
176    Preview {
177        request_id: u64,
178        session_id: u64,
179        preview: &'a Preview,
180    },
181}
182
183/// A clean EOF between frames returns `None`; a partial or invalid frame is an
184/// error. The caller must finish a read before starting the next one.
185pub async fn read_frame<R: AsyncRead + Unpin, T: DeserializeOwned>(
186    reader: &mut R,
187) -> Result<Option<T>> {
188    let mut header = [0; 4];
189    if reader.read(&mut header[..1]).await? == 0 {
190        return Ok(None);
191    }
192    reader
193        .read_exact(&mut header[1..])
194        .await
195        .context("truncated frame header")?;
196    let size = u32::from_be_bytes(header) as usize;
197    ensure!(
198        size > 0 && size <= MAX_FRAME_SIZE,
199        "invalid frame length {size}"
200    );
201    let mut payload = vec![0; size];
202    reader
203        .read_exact(&mut payload)
204        .await
205        .context("truncated frame payload")?;
206    Ok(Some(
207        rmp_serde::from_slice(&payload).context("invalid MessagePack frame")?,
208    ))
209}
210
211pub async fn write_frame<W: AsyncWrite + Unpin, T: Serialize>(
212    writer: &mut W,
213    message: &T,
214) -> Result<()> {
215    let payload = rmp_serde::to_vec_named(message).context("encoding MessagePack frame")?;
216    ensure!(
217        !payload.is_empty() && payload.len() <= MAX_FRAME_SIZE,
218        "invalid frame length {}",
219        payload.len()
220    );
221    writer
222        .write_all(&(payload.len() as u32).to_be_bytes())
223        .await?;
224    writer.write_all(&payload).await?;
225    writer.flush().await?;
226    Ok(())
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232    use kiri_core::{Candidate, Location, SearchMatch};
233    use std::{collections::HashMap, sync::Arc};
234
235    #[tokio::test]
236    async fn fragmented_frames_preserve_boundaries() {
237        let mut bytes = Vec::new();
238        write_frame(
239            &mut bytes,
240            &Request::Hello {
241                request_id: 1,
242                version: VERSION,
243            },
244        )
245        .await
246        .unwrap();
247        write_frame(&mut bytes, &Request::Shutdown { request_id: 2 })
248            .await
249            .unwrap();
250        let (mut writer, mut reader) = tokio::io::duplex(1);
251        let sender = tokio::spawn(async move {
252            for byte in bytes {
253                writer.write_all(&[byte]).await.unwrap();
254            }
255        });
256        assert!(matches!(
257            read_frame::<_, Request>(&mut reader).await.unwrap(),
258            Some(Request::Hello {
259                request_id: 1,
260                version: VERSION
261            })
262        ));
263        assert!(matches!(
264            read_frame::<_, Request>(&mut reader).await.unwrap(),
265            Some(Request::Shutdown { request_id: 2 })
266        ));
267        assert!(
268            read_frame::<_, Request>(&mut reader)
269                .await
270                .unwrap()
271                .is_none()
272        );
273        sender.await.unwrap();
274    }
275
276    #[tokio::test]
277    async fn rejects_invalid_and_truncated_frames() {
278        for bytes in [
279            0u32.to_be_bytes().to_vec(),
280            ((MAX_FRAME_SIZE + 1) as u32).to_be_bytes().to_vec(),
281            vec![0, 0],
282            vec![0, 0, 0, 2, 0x80],
283        ] {
284            assert!(
285                read_frame::<_, Request>(&mut bytes.as_slice())
286                    .await
287                    .is_err()
288            );
289        }
290    }
291
292    async fn round_trip<I: Serialize, O: DeserializeOwned>(message: &I) -> O {
293        let mut bytes = Vec::new();
294        write_frame(&mut bytes, message).await.unwrap();
295        read_frame(&mut bytes.as_slice()).await.unwrap().unwrap()
296    }
297
298    #[tokio::test]
299    async fn grep_open_defaults_its_options() {
300        #[derive(Serialize)]
301        struct Bare {
302            r#type: &'static str,
303            request_id: u64,
304            session_id: u64,
305            revision: u64,
306            query: &'static str,
307            source: BareSource,
308        }
309        #[derive(Serialize)]
310        struct BareSource {
311            r#type: &'static str,
312            root: &'static str,
313        }
314        let Request::Open {
315            source, options, ..
316        } = round_trip(&Bare {
317            r#type: "open",
318            request_id: 1,
319            session_id: 2,
320            revision: 0,
321            query: "needle",
322            source: BareSource {
323                r#type: "grep",
324                root: "C:\\src\\repo",
325            },
326        })
327        .await
328        else {
329            panic!("expected open");
330        };
331        let Source::Grep {
332            root,
333            options: files,
334        } = source
335        else {
336            panic!("expected a grep source");
337        };
338        assert_eq!(root, "C:\\src\\repo");
339        assert!(files.hidden.is_none() && files.respect_ignore.is_none());
340        assert!(options.limit.is_none());
341
342        let Source::Grep { options: files, .. } = round_trip(&Source::Grep {
343            root: "/repo".into(),
344            options: FileOptions {
345                hidden: Some(true),
346                respect_ignore: Some(false),
347            },
348        })
349        .await
350        else {
351            panic!("expected a grep source");
352        };
353        assert_eq!(files.hidden, Some(true));
354        assert_eq!(files.respect_ignore, Some(false));
355    }
356
357    #[tokio::test]
358    async fn preview_request_round_trips_with_optional_window() {
359        let Request::Preview {
360            request_id,
361            session_id,
362            path,
363            line,
364            before,
365            after,
366        } = round_trip(&Request::Preview {
367            request_id: 7,
368            session_id: 3,
369            path: "C:\\repo\\src\\main.rs".into(),
370            line: Some(42),
371            before: None,
372            after: Some(5),
373        })
374        .await
375        else {
376            panic!("expected preview");
377        };
378        assert_eq!((request_id, session_id, line), (7, 3, Some(42)));
379        assert_eq!(path, "C:\\repo\\src\\main.rs");
380        assert_eq!((before, after), (None, Some(5)));
381
382        // Optional keys may be omitted entirely by the client.
383        #[derive(Serialize)]
384        struct Bare {
385            r#type: &'static str,
386            request_id: u64,
387            session_id: u64,
388            path: &'static str,
389        }
390        let Request::Preview {
391            line,
392            before,
393            after,
394            ..
395        } = round_trip(&Bare {
396            r#type: "preview",
397            request_id: 1,
398            session_id: 1,
399            path: "a.txt",
400        })
401        .await
402        else {
403            panic!("expected preview");
404        };
405        assert_eq!((line, before, after), (None, None, None));
406    }
407
408    #[tokio::test]
409    async fn rejects_preview_without_a_path() {
410        #[derive(Serialize)]
411        struct Bad {
412            r#type: &'static str,
413            request_id: u64,
414            session_id: u64,
415        }
416        let mut bytes = Vec::new();
417        write_frame(
418            &mut bytes,
419            &Bad {
420                r#type: "preview",
421                request_id: 1,
422                session_id: 1,
423            },
424        )
425        .await
426        .unwrap();
427        assert!(
428            read_frame::<_, Request>(&mut bytes.as_slice())
429                .await
430                .is_err()
431        );
432    }
433
434    fn candidate(id: u64, location: Option<Location>) -> SearchMatch {
435        SearchMatch {
436            candidate: Arc::new(Candidate {
437                id,
438                text: "a.rs:3: hit".into(),
439                value: b"/r/a.rs".to_vec(),
440                size: None,
441                modified: None,
442                location,
443            }),
444            score: 0,
445            kind: MatchKind::Regex,
446            ranges: vec![(9, 12)],
447        }
448    }
449
450    #[tokio::test]
451    async fn snapshot_matches_carry_a_location_only_for_grep() {
452        let snapshot = Snapshot {
453            revision: 1,
454            history_revision: 0,
455            query: "hit".into(),
456            discovering: false,
457            matching: false,
458            candidates: 2,
459            matched: 2,
460            results: vec![
461                candidate(1, Some(Location { line: 3, column: 5 })),
462                candidate(2, None),
463            ],
464            error: None,
465        };
466        let mut bytes = Vec::new();
467        write_frame(
468            &mut bytes,
469            &Event::Snapshot {
470                session_id: 1,
471                revision: 1,
472                snapshot: SnapshotData::from(&snapshot),
473            },
474        )
475        .await
476        .unwrap();
477        #[derive(Deserialize)]
478        struct Wire {
479            snapshot: WireSnapshot,
480        }
481        #[derive(Deserialize)]
482        struct WireSnapshot {
483            results: Vec<HashMap<String, serde::de::IgnoredAny>>,
484        }
485        let wire: Wire = read_frame(&mut bytes.as_slice()).await.unwrap().unwrap();
486        let keys = |index: usize| {
487            let mut keys: Vec<_> = wire.snapshot.results[index].keys().cloned().collect();
488            keys.sort();
489            keys
490        };
491        assert!(keys(0).iter().any(|key| key == "line"));
492        assert!(keys(0).iter().any(|key| key == "column"));
493        assert!(!keys(1).iter().any(|key| key == "line" || key == "column"));
494    }
495
496    #[tokio::test]
497    async fn preview_event_serializes_every_field() {
498        let preview = Preview {
499            path: "C:\\repo\\a.rs".into(),
500            start_line: 8,
501            lines: vec!["one".into(), "two".into()],
502            focus: Some(9),
503            truncated: true,
504            binary: false,
505            error: None,
506        };
507        let mut bytes = Vec::new();
508        write_frame(
509            &mut bytes,
510            &Event::Preview {
511                request_id: 4,
512                session_id: 2,
513                preview: &preview,
514            },
515        )
516        .await
517        .unwrap();
518        #[derive(Deserialize)]
519        struct Wire {
520            r#type: String,
521            request_id: u64,
522            session_id: u64,
523            preview: WirePreview,
524        }
525        #[derive(Deserialize)]
526        struct WirePreview {
527            path: String,
528            start_line: u32,
529            lines: Vec<String>,
530            focus: Option<u32>,
531            truncated: bool,
532            binary: bool,
533            error: Option<String>,
534        }
535        let wire: Wire = read_frame(&mut bytes.as_slice()).await.unwrap().unwrap();
536        assert_eq!(wire.r#type, "preview");
537        assert_eq!((wire.request_id, wire.session_id), (4, 2));
538        assert_eq!(wire.preview.path, preview.path);
539        assert_eq!(wire.preview.start_line, 8);
540        assert_eq!(wire.preview.lines, preview.lines);
541        assert_eq!(wire.preview.focus, Some(9));
542        assert!(wire.preview.truncated && !wire.preview.binary);
543        assert!(wire.preview.error.is_none());
544    }
545}