sapphire_framework_server/
fs_methods.rs1use std::path::PathBuf;
9use std::sync::{Arc, Mutex};
10
11use corundum_framework_fs::api::{
12 ApplyParams, FS_APPLY, FS_LIST, FS_READ, FS_STAT, FS_VERSION, JOURNAL_HISTORY, JOURNAL_REDO,
13 JOURNAL_STATUS, JOURNAL_UNDO, JOURNAL_UNDO_BATCH,
14};
15use corundum_framework_fs::journal::Actor;
16use corundum_framework_fs::{FsService, Workspace, WorkspaceApp};
17use sapphire_ipc::{RequestCtx, Router, RpcError};
18use serde_json::Value;
19
20use crate::current::Current;
21use crate::error::Error;
22use crate::handlers::{rpc_error, scanned};
23
24pub const OWN_FOLDER: &str = ".sapphire-local";
30
31pub const LOCAL_PRINCIPAL: &str = "local";
33
34const MCP_CLIENT_KIND: &str = "mcp";
37
38pub const METHODS: [&str; 10] = [
40 FS_VERSION,
41 FS_LIST,
42 FS_STAT,
43 FS_READ,
44 FS_APPLY,
45 JOURNAL_UNDO,
46 JOURNAL_REDO,
47 JOURNAL_UNDO_BATCH,
48 JOURNAL_HISTORY,
49 JOURNAL_STATUS,
50];
51
52#[derive(Debug, Clone, Copy, Default)]
55pub struct SapphireApp;
56
57impl WorkspaceApp for SapphireApp {
58 fn own_folder(&self) -> &str {
59 OWN_FOLDER
60 }
61}
62
63pub fn actor_for(client_kind: &str) -> Actor {
65 Actor {
66 principal: LOCAL_PRINCIPAL.to_owned(),
67 agent: client_kind == MCP_CLIENT_KIND,
68 }
69}
70
71struct Services {
74 current: Arc<Current>,
75 served: Mutex<Option<(PathBuf, FsService<SapphireApp>)>>,
76}
77
78impl Services {
79 fn get(&self) -> Result<(PathBuf, FsService<SapphireApp>), RpcError> {
81 let root = self
82 .current
83 .root()
84 .ok_or_else(|| rpc_error(&Error::NoWorkspace))?;
85 let mut served = self.served.lock().unwrap_or_else(|e| e.into_inner());
86 if let Some((at, service)) = served.as_ref()
87 && *at == root
88 {
89 return Ok((root, service.clone()));
90 }
91 let ws = Workspace::open(&root).map_err(fs_error)?;
92 let service = FsService::new(ws, SapphireApp);
93 *served = Some((root.clone(), service.clone()));
94 Ok((root, service))
95 }
96}
97
98fn fs_error(err: corundum_framework_fs::FsError) -> RpcError {
101 RpcError {
102 code: err.code(),
103 message: err.to_string(),
104 data: None,
105 }
106}
107
108fn changes(method: &str, params: &Value) -> bool {
110 match method {
111 FS_APPLY => serde_json::from_value::<ApplyParams>(params.clone())
112 .map(|p| !p.dry_run)
113 .unwrap_or(false),
114 JOURNAL_UNDO | JOURNAL_REDO | JOURNAL_UNDO_BATCH => true,
115 _ => false,
116 }
117}
118
119pub(crate) fn fs_methods(current: Arc<Current>, router: Router) -> Router {
121 let services = Arc::new(Services {
122 current,
123 served: Mutex::new(None),
124 });
125 METHODS.iter().fold(router, |router, &method| {
126 let services = Arc::clone(&services);
127 router.method(method, move |ctx: RequestCtx| {
128 let services = Arc::clone(&services);
129 async move {
130 let actor = actor_for(&ctx.peer.client().kind);
131 let (root, service) = services.get()?;
132 let changed = changes(method, &ctx.params);
133 let result = service
134 .dispatch(method, ctx.params, &actor)
135 .await
136 .map_err(fs_error);
137 if changed && result.is_ok() {
140 scanned(services.current.sync(), &root, method).await;
141 }
142 result
143 }
144 })
145 })
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151
152 #[test]
153 fn the_mcp_client_is_an_agent_and_the_rest_are_the_person() {
154 assert_eq!(
155 actor_for("mcp"),
156 Actor {
157 principal: "local".into(),
158 agent: true
159 }
160 );
161 for kind in ["desktop", "cli", "sapphire-sync"] {
162 assert!(!actor_for(kind).agent, "{kind}");
163 assert_eq!(actor_for(kind).principal, "local");
164 }
165 }
166
167 #[test]
168 fn only_a_real_apply_and_the_undo_methods_change_anything() {
169 let apply = |dry_run| serde_json::json!({"ops": [], "origin": "o", "dry_run": dry_run});
170 assert!(changes(FS_APPLY, &apply(false)));
171 assert!(!changes(FS_APPLY, &apply(true)));
172 assert!(changes(JOURNAL_UNDO, &serde_json::json!({})));
173 assert!(changes(JOURNAL_UNDO_BATCH, &serde_json::json!({})));
174 for read in [
175 FS_LIST,
176 FS_STAT,
177 FS_READ,
178 FS_VERSION,
179 JOURNAL_HISTORY,
180 JOURNAL_STATUS,
181 ] {
182 assert!(!changes(read, &serde_json::json!({})), "{read}");
183 }
184 }
185
186 #[test]
187 fn the_trash_folder_is_not_synced() {
188 let dir = tempfile::tempdir().unwrap();
189 let filter = sapphire_sync::SyncFilter::load(dir.path(), "sapphire-sync").unwrap();
190 assert!(!filter.allows(&format!("{OWN_FOLDER}/trash/x/a.txt"), false));
191 assert!(filter.allows(".sapphire-sync/embedded/a.vec", false));
192 }
193}