#![warn(missing_docs)]
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
pub use grain_id::GrainId;
pub const API_VERSION: u32 = parse_major(env!("CARGO_PKG_VERSION_MAJOR"));
const fn parse_major(s: &str) -> u32 {
let bytes = s.as_bytes();
let mut i = 0;
let mut n = 0u32;
while i < bytes.len() {
n = n * 10 + (bytes[i] - b'0') as u32;
i += 1;
}
n
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ManagedBy {
Service,
Spawned,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SearchMode {
Fts,
Semantic,
#[default]
Hybrid,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FileSearchResult {
pub id: i64,
pub path: String,
pub score: f64,
pub snippet: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum BackendEvent {
Synced {
upserted: usize,
removed: usize,
},
FileChanged {
path: PathBuf,
},
FileRemoved {
path: PathBuf,
},
Error {
message: String,
},
}
pub const SEARCH: &str = "workspace.search";
pub const READ_FILE: &str = "workspace.read_file";
pub const WRITE_FILE: &str = "workspace.write_file";
pub const APPEND_FILE: &str = "workspace.append_file";
pub const DELETE_FILE: &str = "workspace.delete_file";
pub const LIST_DIR: &str = "workspace.list_dir";
pub const REINDEX: &str = "workspace.reindex";
pub const SUBSCRIBE: &str = "workspace.subscribe";
pub const WORKSPACE_INIT: &str = "workspace.init";
pub const WORKSPACE_SELECT: &str = "workspace.select";
pub const WORKSPACE_CURRENT: &str = "workspace.current";
pub const WORKSPACE_MOVE: &str = "workspace.move";
pub const WORKSPACE_REMOVE: &str = "workspace.remove";
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct WorkspaceMoveParams {
pub dir: PathBuf,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct WorkspaceRemoveParams {
#[serde(default)]
pub delete: bool,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct WorkspaceSelectParams {
pub dir: PathBuf,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct WorkspaceCurrentResult {
pub workspace: Option<CurrentWorkspace>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct CurrentWorkspace {
pub root: PathBuf,
pub workspace_id: Option<grain_id::GrainId>,
pub reachable: bool,
pub sync: SyncStatusResult,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct WorkspaceInitParams {
pub dir: PathBuf,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct WorkspaceInitResult {
pub root: PathBuf,
pub workspace_id: String,
pub created: bool,
}
pub const EVENT: &str = "workspace.event";
pub const SERVER_INFO: &str = "server.info";
pub const SERVER_UPDATE: &str = "server.update";
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PathParams {
pub path: PathBuf,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ContentParams {
pub path: PathBuf,
pub content: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SearchParams {
pub query: String,
pub limit: usize,
#[serde(default)]
pub mode: SearchMode,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SearchResult {
pub hits: Vec<FileSearchResult>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReadResult {
pub content: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DirEntry {
pub path: PathBuf,
pub is_dir: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ListDirResult {
pub entries: Vec<DirEntry>,
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct ReindexResult {
pub upserted: usize,
pub removed: usize,
}
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
pub struct Ack {}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EventParams {
pub ws: PathBuf,
pub event: BackendEvent,
}
#[cfg(test)]
mod tests {
use super::*;
fn round_trip<T>(value: &T) -> T
where
T: serde::Serialize + serde::de::DeserializeOwned,
{
serde_json::from_value(serde_json::to_value(value).unwrap()).unwrap()
}
#[test]
fn search_parameters_round_trip() {
let params = SearchParams {
query: "hello".into(),
limit: 10,
mode: SearchMode::Fts,
};
let back = round_trip(¶ms);
assert_eq!(back.query, "hello");
assert_eq!(back.limit, 10);
assert_eq!(back.mode, SearchMode::Fts);
}
#[test]
fn every_search_mode_has_a_stable_lowercase_name() {
for (mode, name) in [
(SearchMode::Fts, "fts"),
(SearchMode::Semantic, "semantic"),
(SearchMode::Hybrid, "hybrid"),
] {
assert_eq!(serde_json::to_value(mode).unwrap(), serde_json::json!(name));
assert_eq!(
serde_json::from_value::<SearchMode>(serde_json::json!(name)).unwrap(),
mode
);
}
}
#[test]
fn a_missing_mode_defaults_to_hybrid() {
let value = serde_json::json!({ "query": "q", "limit": 5 });
let params: SearchParams = serde_json::from_value(value).unwrap();
assert_eq!(params.mode, SearchMode::Hybrid);
}
#[test]
fn every_backend_event_round_trips() {
for event in [
BackendEvent::Synced {
upserted: 3,
removed: 1,
},
BackendEvent::FileChanged {
path: PathBuf::from("a.md"),
},
BackendEvent::FileRemoved {
path: PathBuf::from("b.md"),
},
BackendEvent::Error {
message: "boom".into(),
},
] {
assert_eq!(round_trip(&event), event);
}
}
#[test]
fn a_directory_listing_round_trips() {
let listing = ListDirResult {
entries: vec![
DirEntry {
path: PathBuf::from("notes"),
is_dir: true,
},
DirEntry {
path: PathBuf::from("a.md"),
is_dir: false,
},
],
};
let back = round_trip(&listing);
assert_eq!(back.entries.len(), 2);
assert!(back.entries[0].is_dir);
assert!(!back.entries[1].is_dir);
}
#[test]
fn an_ack_is_an_object_not_null() {
assert_eq!(serde_json::to_value(Ack {}).unwrap(), serde_json::json!({}));
}
#[test]
fn workspace_init_params_and_result_round_trip() {
let params = WorkspaceInitParams {
dir: PathBuf::from("/home/me/papers"),
};
let back = round_trip(¶ms);
assert_eq!(back.dir, params.dir);
let result = WorkspaceInitResult {
root: PathBuf::from("/home/me/papers"),
workspace_id: "g123".into(),
created: true,
};
let back = round_trip(&result);
assert_eq!(back.root, result.root);
assert_eq!(back.workspace_id, result.workspace_id);
assert!(back.created);
}
#[test]
fn the_current_workspace_round_trips() {
let current = CurrentWorkspace {
root: PathBuf::from("/home/me/notes"),
workspace_id: Some(grain_id::GrainId::random()),
reachable: true,
sync: SyncStatusResult::not_synced(),
};
let back = round_trip(&WorkspaceCurrentResult {
workspace: Some(current.clone()),
});
let back = back.workspace.unwrap();
assert_eq!(back.root, current.root);
assert_eq!(back.workspace_id, current.workspace_id);
assert!(
round_trip(&WorkspaceCurrentResult::default())
.workspace
.is_none()
);
assert_eq!(
round_trip(&WorkspaceSelectParams {
dir: PathBuf::from("/x")
})
.dir,
PathBuf::from("/x")
);
assert_eq!(API_VERSION, 4, "the crate's major is the API version");
}
#[test]
fn method_names_are_namespaced() {
for name in [
SEARCH,
READ_FILE,
WRITE_FILE,
APPEND_FILE,
DELETE_FILE,
LIST_DIR,
REINDEX,
SUBSCRIBE,
WORKSPACE_INIT,
WORKSPACE_SELECT,
WORKSPACE_CURRENT,
WORKSPACE_MOVE,
WORKSPACE_REMOVE,
] {
assert!(name.starts_with("workspace."), "{name}");
}
assert_eq!(EVENT, "workspace.event");
}
}
pub const SYNC_ENABLE: &str = "sync.enable";
pub const SYNC_DISABLE: &str = "sync.disable";
pub const SYNC_STATUS: &str = "sync.status";
pub const SYNC_MAP: &str = "sync.map";
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SyncMapParams {
pub workspace: String,
pub dir: PathBuf,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SyncEnableResult {
pub workspace_id: grain_id::GrainId,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Topology {
#[default]
Mesh,
Star {
primary: grain_id::GrainId,
secondary: Option<grain_id::GrainId>,
},
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SyncStatusResult {
pub enabled: bool,
pub workspace_id: Option<grain_id::GrainId>,
pub peers: usize,
pub paused: Option<String>,
pub last_error: Option<String>,
pub bridge_available: bool,
#[serde(default)]
pub topology: Topology,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub embedding: Option<EmbeddingProgress>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct EmbeddingProgress {
pub vectors: u64,
pub pending: u64,
pub running: bool,
}
impl SyncStatusResult {
pub fn not_synced() -> SyncStatusResult {
SyncStatusResult {
enabled: false,
workspace_id: None,
peers: 0,
paused: None,
last_error: None,
bridge_available: false,
topology: Topology::Mesh,
embedding: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatusReport {
pub running: bool,
pub version: Option<String>,
pub pid: Option<u32>,
pub managed_by: Option<ManagedBy>,
pub app: Vec<StatusRow>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct UpdateStatus {
pub enabled: bool,
pub latest: Option<ReleaseInfo>,
pub update_available: bool,
pub last_error: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReleaseInfo {
pub version: String,
pub url: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatusRow {
pub name: String,
pub value: String,
}