use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use corundum_framework_fs::api::{
ApplyParams, FS_APPLY, FS_LIST, FS_READ, FS_STAT, FS_VERSION, JOURNAL_HISTORY, JOURNAL_REDO,
JOURNAL_STATUS, JOURNAL_UNDO, JOURNAL_UNDO_BATCH,
};
use corundum_framework_fs::journal::Actor;
use corundum_framework_fs::{FsService, Workspace, WorkspaceApp};
use sapphire_ipc::{RequestCtx, Router, RpcError};
use serde_json::Value;
use crate::current::Current;
use crate::error::Error;
use crate::handlers::{rpc_error, scanned};
pub const OWN_FOLDER: &str = ".sapphire-local";
pub const LOCAL_PRINCIPAL: &str = "local";
const MCP_CLIENT_KIND: &str = "mcp";
pub const METHODS: [&str; 10] = [
FS_VERSION,
FS_LIST,
FS_STAT,
FS_READ,
FS_APPLY,
JOURNAL_UNDO,
JOURNAL_REDO,
JOURNAL_UNDO_BATCH,
JOURNAL_HISTORY,
JOURNAL_STATUS,
];
#[derive(Debug, Clone, Copy, Default)]
pub struct SapphireApp;
impl WorkspaceApp for SapphireApp {
fn own_folder(&self) -> &str {
OWN_FOLDER
}
}
pub fn actor_for(client_kind: &str) -> Actor {
Actor {
principal: LOCAL_PRINCIPAL.to_owned(),
agent: client_kind == MCP_CLIENT_KIND,
}
}
struct Services {
current: Arc<Current>,
served: Mutex<Option<(PathBuf, FsService<SapphireApp>)>>,
}
impl Services {
fn get(&self) -> Result<(PathBuf, FsService<SapphireApp>), RpcError> {
let root = self
.current
.root()
.ok_or_else(|| rpc_error(&Error::NoWorkspace))?;
let mut served = self.served.lock().unwrap_or_else(|e| e.into_inner());
if let Some((at, service)) = served.as_ref()
&& *at == root
{
return Ok((root, service.clone()));
}
let ws = Workspace::open(&root).map_err(fs_error)?;
let service = FsService::new(ws, SapphireApp);
*served = Some((root.clone(), service.clone()));
Ok((root, service))
}
}
fn fs_error(err: corundum_framework_fs::FsError) -> RpcError {
RpcError {
code: err.code(),
message: err.to_string(),
data: None,
}
}
fn changes(method: &str, params: &Value) -> bool {
match method {
FS_APPLY => serde_json::from_value::<ApplyParams>(params.clone())
.map(|p| !p.dry_run)
.unwrap_or(false),
JOURNAL_UNDO | JOURNAL_REDO | JOURNAL_UNDO_BATCH => true,
_ => false,
}
}
pub(crate) fn fs_methods(current: Arc<Current>, router: Router) -> Router {
let services = Arc::new(Services {
current,
served: Mutex::new(None),
});
METHODS.iter().fold(router, |router, &method| {
let services = Arc::clone(&services);
router.method(method, move |ctx: RequestCtx| {
let services = Arc::clone(&services);
async move {
let actor = actor_for(&ctx.peer.client().kind);
let (root, service) = services.get()?;
let changed = changes(method, &ctx.params);
let result = service
.dispatch(method, ctx.params, &actor)
.await
.map_err(fs_error);
if changed && result.is_ok() {
scanned(services.current.sync(), &root, method).await;
}
result
}
})
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_mcp_client_is_an_agent_and_the_rest_are_the_person() {
assert_eq!(
actor_for("mcp"),
Actor {
principal: "local".into(),
agent: true
}
);
for kind in ["desktop", "cli", "sapphire-sync"] {
assert!(!actor_for(kind).agent, "{kind}");
assert_eq!(actor_for(kind).principal, "local");
}
}
#[test]
fn only_a_real_apply_and_the_undo_methods_change_anything() {
let apply = |dry_run| serde_json::json!({"ops": [], "origin": "o", "dry_run": dry_run});
assert!(changes(FS_APPLY, &apply(false)));
assert!(!changes(FS_APPLY, &apply(true)));
assert!(changes(JOURNAL_UNDO, &serde_json::json!({})));
assert!(changes(JOURNAL_UNDO_BATCH, &serde_json::json!({})));
for read in [
FS_LIST,
FS_STAT,
FS_READ,
FS_VERSION,
JOURNAL_HISTORY,
JOURNAL_STATUS,
] {
assert!(!changes(read, &serde_json::json!({})), "{read}");
}
}
#[test]
fn the_trash_folder_is_not_synced() {
let dir = tempfile::tempdir().unwrap();
let filter = sapphire_sync::SyncFilter::load(dir.path(), "sapphire-sync").unwrap();
assert!(!filter.allows(&format!("{OWN_FOLDER}/trash/x/a.txt"), false));
assert!(filter.allows(".sapphire-sync/embedded/a.vec", false));
}
}