use anyhow::{Context, Result, ensure};
use kiri_core::{CaseSensitivity, MatchKind, MatcherMode, Preview, Snapshot, SortOrder};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::borrow::Cow;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
pub const VERSION: u32 = 2;
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,
},
Grep {
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,
},
Preview {
request_id: u64,
session_id: u64,
path: String,
line: Option<u32>,
before: Option<usize>,
after: Option<usize>,
},
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,
pub ranges: &'a [(usize, usize)],
#[serde(skip_serializing_if = "Option::is_none")]
pub line: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub column: Option<u32>,
}
#[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,
line: result.candidate.location.map(|location| location.line),
column: result.candidate.location.map(|location| location.column),
})
.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>,
},
Preview {
request_id: u64,
session_id: u64,
preview: &'a Preview,
},
}
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::*;
use kiri_core::{Candidate, Location, SearchMatch};
use std::{collections::HashMap, sync::Arc};
#[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()
);
}
}
async fn round_trip<I: Serialize, O: DeserializeOwned>(message: &I) -> O {
let mut bytes = Vec::new();
write_frame(&mut bytes, message).await.unwrap();
read_frame(&mut bytes.as_slice()).await.unwrap().unwrap()
}
#[tokio::test]
async fn grep_open_defaults_its_options() {
#[derive(Serialize)]
struct Bare {
r#type: &'static str,
request_id: u64,
session_id: u64,
revision: u64,
query: &'static str,
source: BareSource,
}
#[derive(Serialize)]
struct BareSource {
r#type: &'static str,
root: &'static str,
}
let Request::Open {
source, options, ..
} = round_trip(&Bare {
r#type: "open",
request_id: 1,
session_id: 2,
revision: 0,
query: "needle",
source: BareSource {
r#type: "grep",
root: "C:\\src\\repo",
},
})
.await
else {
panic!("expected open");
};
let Source::Grep {
root,
options: files,
} = source
else {
panic!("expected a grep source");
};
assert_eq!(root, "C:\\src\\repo");
assert!(files.hidden.is_none() && files.respect_ignore.is_none());
assert!(options.limit.is_none());
let Source::Grep { options: files, .. } = round_trip(&Source::Grep {
root: "/repo".into(),
options: FileOptions {
hidden: Some(true),
respect_ignore: Some(false),
},
})
.await
else {
panic!("expected a grep source");
};
assert_eq!(files.hidden, Some(true));
assert_eq!(files.respect_ignore, Some(false));
}
#[tokio::test]
async fn preview_request_round_trips_with_optional_window() {
let Request::Preview {
request_id,
session_id,
path,
line,
before,
after,
} = round_trip(&Request::Preview {
request_id: 7,
session_id: 3,
path: "C:\\repo\\src\\main.rs".into(),
line: Some(42),
before: None,
after: Some(5),
})
.await
else {
panic!("expected preview");
};
assert_eq!((request_id, session_id, line), (7, 3, Some(42)));
assert_eq!(path, "C:\\repo\\src\\main.rs");
assert_eq!((before, after), (None, Some(5)));
#[derive(Serialize)]
struct Bare {
r#type: &'static str,
request_id: u64,
session_id: u64,
path: &'static str,
}
let Request::Preview {
line,
before,
after,
..
} = round_trip(&Bare {
r#type: "preview",
request_id: 1,
session_id: 1,
path: "a.txt",
})
.await
else {
panic!("expected preview");
};
assert_eq!((line, before, after), (None, None, None));
}
#[tokio::test]
async fn rejects_preview_without_a_path() {
#[derive(Serialize)]
struct Bad {
r#type: &'static str,
request_id: u64,
session_id: u64,
}
let mut bytes = Vec::new();
write_frame(
&mut bytes,
&Bad {
r#type: "preview",
request_id: 1,
session_id: 1,
},
)
.await
.unwrap();
assert!(
read_frame::<_, Request>(&mut bytes.as_slice())
.await
.is_err()
);
}
fn candidate(id: u64, location: Option<Location>) -> SearchMatch {
SearchMatch {
candidate: Arc::new(Candidate {
id,
text: "a.rs:3: hit".into(),
value: b"/r/a.rs".to_vec(),
size: None,
modified: None,
location,
}),
score: 0,
kind: MatchKind::Regex,
ranges: vec![(9, 12)],
}
}
#[tokio::test]
async fn snapshot_matches_carry_a_location_only_for_grep() {
let snapshot = Snapshot {
revision: 1,
history_revision: 0,
query: "hit".into(),
discovering: false,
matching: false,
candidates: 2,
matched: 2,
results: vec![
candidate(1, Some(Location { line: 3, column: 5 })),
candidate(2, None),
],
error: None,
};
let mut bytes = Vec::new();
write_frame(
&mut bytes,
&Event::Snapshot {
session_id: 1,
revision: 1,
snapshot: SnapshotData::from(&snapshot),
},
)
.await
.unwrap();
#[derive(Deserialize)]
struct Wire {
snapshot: WireSnapshot,
}
#[derive(Deserialize)]
struct WireSnapshot {
results: Vec<HashMap<String, serde::de::IgnoredAny>>,
}
let wire: Wire = read_frame(&mut bytes.as_slice()).await.unwrap().unwrap();
let keys = |index: usize| {
let mut keys: Vec<_> = wire.snapshot.results[index].keys().cloned().collect();
keys.sort();
keys
};
assert!(keys(0).iter().any(|key| key == "line"));
assert!(keys(0).iter().any(|key| key == "column"));
assert!(!keys(1).iter().any(|key| key == "line" || key == "column"));
}
#[tokio::test]
async fn preview_event_serializes_every_field() {
let preview = Preview {
path: "C:\\repo\\a.rs".into(),
start_line: 8,
lines: vec!["one".into(), "two".into()],
focus: Some(9),
truncated: true,
binary: false,
error: None,
};
let mut bytes = Vec::new();
write_frame(
&mut bytes,
&Event::Preview {
request_id: 4,
session_id: 2,
preview: &preview,
},
)
.await
.unwrap();
#[derive(Deserialize)]
struct Wire {
r#type: String,
request_id: u64,
session_id: u64,
preview: WirePreview,
}
#[derive(Deserialize)]
struct WirePreview {
path: String,
start_line: u32,
lines: Vec<String>,
focus: Option<u32>,
truncated: bool,
binary: bool,
error: Option<String>,
}
let wire: Wire = read_frame(&mut bytes.as_slice()).await.unwrap().unwrap();
assert_eq!(wire.r#type, "preview");
assert_eq!((wire.request_id, wire.session_id), (4, 2));
assert_eq!(wire.preview.path, preview.path);
assert_eq!(wire.preview.start_line, 8);
assert_eq!(wire.preview.lines, preview.lines);
assert_eq!(wire.preview.focus, Some(9));
assert!(wire.preview.truncated && !wire.preview.binary);
assert!(wire.preview.error.is_none());
}
}