use std::sync::Arc;
use sapphire_backend::protocol as proto;
use sapphire_backend::{WorkspaceBackend, protocol::Ack};
use sapphire_ipc::{RequestCtx, Router, RpcError, codes};
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::current::Current;
use crate::error::Error;
use crate::sync::SyncRuntime;
pub(crate) fn rpc_error(err: &Error) -> RpcError {
use sapphire_workspace::Error as WsError;
let caller_error = matches!(
err,
Error::UnknownWorkspace(..)
| Error::NoWorkspace
| Error::UnknownWorkspaceName(..)
| Error::WrongApp { .. }
| Error::SyncId(..)
| Error::Workspace(
WsError::PathEscapesWorkspace { .. }
| WsError::MarkerDirMissing { .. }
| WsError::MarkerNotFound { .. }
)
) || matches!(
err,
Error::Backend(sapphire_backend::Error::Workspace(
WsError::PathEscapesWorkspace { .. }
| WsError::MarkerDirMissing { .. }
| WsError::MarkerNotFound { .. }
))
);
if caller_error {
RpcError::invalid_params(err.to_string())
} else {
RpcError {
code: codes::INTERNAL_ERROR,
message: err.to_string(),
data: None,
}
}
}
fn params<T: DeserializeOwned>(ctx: &RequestCtx) -> std::result::Result<T, RpcError> {
serde_json::from_value(ctx.params.clone())
.map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))
}
fn ok<T: serde::Serialize>(value: T) -> std::result::Result<Value, RpcError> {
serde_json::to_value(value).map_err(|e| RpcError::internal(e.to_string()))
}
pub(crate) async fn scanned(sync: Option<&Arc<SyncRuntime>>, root: &std::path::Path, what: &str) {
if let Some(runtime) = sync {
if let Err(err) = runtime.scan(root).await {
tracing::warn!(root = %root.display(), "scan after {what} failed: {err}");
}
runtime.request_embed(root);
}
}
pub fn workspace_router(current: Arc<Current>) -> Router {
let read = Arc::clone(¤t);
let write = Arc::clone(¤t);
let append = Arc::clone(¤t);
let delete = Arc::clone(¤t);
let list = Arc::clone(¤t);
let search = Arc::clone(¤t);
let reindex = current;
Router::new()
.method(proto::READ_FILE, move |ctx| {
let current = Arc::clone(&read);
async move {
let p: proto::PathParams = params(&ctx)?;
let backend = current.host().backend().await.map_err(|e| rpc_error(&e))?;
let content = backend
.read_file(&p.path)
.await
.map_err(|e| rpc_error(&Error::Backend(e)))?;
ok(proto::ReadResult { content })
}
})
.method(proto::WRITE_FILE, move |ctx| {
let current = Arc::clone(&write);
async move {
let p: proto::ContentParams = params(&ctx)?;
let (root, backend) = current.host().current().await.map_err(|e| rpc_error(&e))?;
backend
.write_file(&p.path, &p.content)
.await
.map_err(|e| rpc_error(&Error::Backend(e)))?;
scanned(current.sync(), &root, "a write").await;
ok(Ack {})
}
})
.method(proto::APPEND_FILE, move |ctx| {
let current = Arc::clone(&append);
async move {
let p: proto::ContentParams = params(&ctx)?;
let (root, backend) = current.host().current().await.map_err(|e| rpc_error(&e))?;
backend
.append_file(&p.path, &p.content)
.await
.map_err(|e| rpc_error(&Error::Backend(e)))?;
scanned(current.sync(), &root, "an append").await;
ok(Ack {})
}
})
.method(proto::DELETE_FILE, move |ctx| {
let current = Arc::clone(&delete);
async move {
let p: proto::PathParams = params(&ctx)?;
let (root, backend) = current.host().current().await.map_err(|e| rpc_error(&e))?;
backend
.delete_file(&p.path)
.await
.map_err(|e| rpc_error(&Error::Backend(e)))?;
scanned(current.sync(), &root, "a delete").await;
ok(Ack {})
}
})
.method(proto::LIST_DIR, move |ctx| {
let current = Arc::clone(&list);
async move {
let p: proto::PathParams = params(&ctx)?;
let backend = current.host().backend().await.map_err(|e| rpc_error(&e))?;
let entries = backend
.list_dir(&p.path)
.await
.map_err(|e| rpc_error(&Error::Backend(e)))?
.into_iter()
.map(|(path, is_dir)| proto::DirEntry { path, is_dir })
.collect();
ok(proto::ListDirResult { entries })
}
})
.method(proto::SEARCH, move |ctx| {
let current = Arc::clone(&search);
async move {
let p: proto::SearchParams = params(&ctx)?;
let backend = current.host().backend().await.map_err(|e| rpc_error(&e))?;
let hits = backend
.search(&p.query, p.limit, p.mode)
.await
.map_err(|e| rpc_error(&Error::Backend(e)))?;
ok(proto::SearchResult { hits })
}
})
.method(proto::REINDEX, move |_| {
let current = Arc::clone(&reindex);
async move {
let backend = current.host().backend().await.map_err(|e| rpc_error(&e))?;
let started = std::time::Instant::now();
let summary = backend.sync().await;
crate::instrument::reindexed(started, summary.is_ok());
let summary = summary.map_err(|e| rpc_error(&Error::Backend(e)))?;
ok(proto::ReindexResult {
upserted: summary.upserted,
removed: summary.removed,
})
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use sapphire_backend::protocol as proto;
use sapphire_ipc::{Client, ClientInfo, Connection, ManagedBy, ServerInfo, serve};
use sapphire_workspace::{AppContext, AppKind};
use std::ffi::OsString;
use std::path::PathBuf;
use crate::test_support;
static CTX: AppContext = AppContext::new("sapphire-handlertest");
const DIR_VARS: [&str; 3] = [
"SAPPHIRE_HANDLERTEST_CACHE_DIR",
"SAPPHIRE_HANDLERTEST_DATA_DIR",
"SAPPHIRE_HANDLERTEST_CONFIG_DIR",
];
struct EnvGuard {
previous: [Option<OsString>; 3],
_lock: std::sync::MutexGuard<'static, ()>,
}
impl EnvGuard {
fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
let previous = DIR_VARS.map(std::env::var_os);
let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
for (name, dir) in DIR_VARS.iter().zip(dirs) {
test_support::set(name, &dir);
}
EnvGuard {
previous,
_lock: lock,
}
}
}
impl Drop for EnvGuard {
fn drop(&mut self) {
for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
match previous.take() {
Some(value) => unsafe { std::env::set_var(name, value) },
None => test_support::remove(name),
}
}
}
}
fn init_ctx(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
let guard = EnvGuard::set(lock, tmp);
CTX.init(AppKind::Server);
guard
}
struct Fixture {
_tmp: tempfile::TempDir,
_env: EnvGuard,
ws: PathBuf,
client: Client,
current: Arc<Current>,
}
async fn fixture() -> Fixture {
fixture_selecting(true).await
}
async fn fixture_selecting(select: bool) -> Fixture {
let lock = test_support::lock();
let tmp = tempfile::tempdir().unwrap();
let _env = init_ctx(lock, tmp.path());
let root = tmp.path().join("ws");
std::fs::create_dir_all(root.join(".sapphire-handlertest")).unwrap();
let ws = root.canonicalize().unwrap();
let current = Arc::new(Current::new(
&CTX,
Arc::new(crate::host::WorkspaceHost::new(&CTX)),
None,
crate::selection::SelectionFile::at(tmp.path().join("workspace.toml")),
));
if select {
current.select(&ws).await.unwrap();
}
let router = Arc::new(crate::fs_methods::fs_methods(
Arc::clone(¤t),
workspace_router(Arc::clone(¤t)),
));
let (client_conn, server_conn) = Connection::pair();
tokio::spawn(async move {
let info = ServerInfo {
version: "0.0.0".into(),
api: sapphire_backend::protocol::API_VERSION,
app_api: None,
pid: std::process::id(),
managed_by: ManagedBy::Spawned,
};
let _ = serve(server_conn, router, "sapphire-handlertest", info).await;
});
let client_info = ClientInfo {
kind: "test".into(),
version: "0.0.0".into(),
api: sapphire_backend::protocol::API_VERSION,
app_api: None,
pid: std::process::id(),
};
let (client, _) = Client::handshake(client_conn, "sapphire-handlertest", client_info)
.await
.unwrap();
Fixture {
_tmp: tmp,
_env,
ws,
client,
current,
}
}
#[tokio::test]
async fn a_file_written_through_the_server_can_be_read_back() {
let f = fixture().await;
let _: proto::Ack = f
.client
.call(
proto::WRITE_FILE,
proto::ContentParams {
path: PathBuf::from("a.md"),
content: "# hello".into(),
},
)
.await
.unwrap();
let read: proto::ReadResult = f
.client
.call(
proto::READ_FILE,
proto::PathParams {
path: PathBuf::from("a.md"),
},
)
.await
.unwrap();
assert_eq!(read.content, "# hello");
}
#[tokio::test]
async fn appending_adds_to_the_file() {
let f = fixture().await;
let write = proto::ContentParams {
path: PathBuf::from("a.md"),
content: "one\n".into(),
};
let _: proto::Ack = f.client.call(proto::WRITE_FILE, write).await.unwrap();
let append = proto::ContentParams {
path: PathBuf::from("a.md"),
content: "two\n".into(),
};
let _: proto::Ack = f.client.call(proto::APPEND_FILE, append).await.unwrap();
let read: proto::ReadResult = f
.client
.call(
proto::READ_FILE,
proto::PathParams {
path: PathBuf::from("a.md"),
},
)
.await
.unwrap();
assert_eq!(read.content, "one\ntwo\n");
}
#[tokio::test]
async fn a_deleted_file_is_gone() {
let f = fixture().await;
let _: proto::Ack = f
.client
.call(
proto::WRITE_FILE,
proto::ContentParams {
path: PathBuf::from("a.md"),
content: "x".into(),
},
)
.await
.unwrap();
let _: proto::Ack = f
.client
.call(
proto::DELETE_FILE,
proto::PathParams {
path: PathBuf::from("a.md"),
},
)
.await
.unwrap();
let err = f
.client
.call::<_, proto::ReadResult>(
proto::READ_FILE,
proto::PathParams {
path: PathBuf::from("a.md"),
},
)
.await
.unwrap_err();
assert!(matches!(err, sapphire_ipc::Error::Rpc(_)), "got {err:?}");
}
#[tokio::test]
async fn a_directory_listing_separates_files_from_directories() {
let f = fixture().await;
std::fs::create_dir_all(f.ws.join("notes")).unwrap();
let _: proto::Ack = f
.client
.call(
proto::WRITE_FILE,
proto::ContentParams {
path: PathBuf::from("a.md"),
content: "x".into(),
},
)
.await
.unwrap();
let listing: proto::ListDirResult = f
.client
.call(
proto::LIST_DIR,
proto::PathParams {
path: PathBuf::from("."),
},
)
.await
.unwrap();
assert!(
listing
.entries
.iter()
.any(|e| e.is_dir && e.path.ends_with("notes")),
"{:?}",
listing.entries
);
assert!(
listing
.entries
.iter()
.any(|e| !e.is_dir && e.path.ends_with("a.md")),
"{:?}",
listing.entries
);
}
#[tokio::test]
async fn a_written_file_is_searchable() {
let f = fixture().await;
let _: proto::Ack = f
.client
.call(
proto::WRITE_FILE,
proto::ContentParams {
path: PathBuf::from("a.md"),
content: "the quick brown fox".into(),
},
)
.await
.unwrap();
let hits: proto::SearchResult = f
.client
.call(
proto::SEARCH,
proto::SearchParams {
query: "brown".into(),
limit: 10,
mode: sapphire_backend::SearchMode::Fts,
},
)
.await
.unwrap();
assert!(
hits.hits.iter().any(|h| h.path.ends_with("a.md")),
"{:?}",
hits.hits
);
}
#[tokio::test]
async fn reindexing_reports_what_it_found() {
let f = fixture().await;
std::fs::write(f.ws.join("outside.md"), "written behind the server's back").unwrap();
let report: proto::ReindexResult = f
.client
.call(proto::REINDEX, serde_json::json!({}))
.await
.unwrap();
assert!(report.upserted >= 1, "{report:?}");
}
#[tokio::test]
async fn a_path_escaping_the_workspace_is_an_invalid_parameter() {
let f = fixture().await;
let err = f
.client
.call::<_, proto::ReadResult>(
proto::READ_FILE,
proto::PathParams {
path: PathBuf::from("../../etc/passwd"),
},
)
.await
.unwrap_err();
match err {
sapphire_ipc::Error::Rpc(e) => {
assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS, "{}", e.message);
}
other => panic!("got {other:?}"),
}
}
#[tokio::test]
async fn without_a_workspace_every_call_is_an_invalid_parameter() {
let f = fixture_selecting(false).await;
let err = f
.client
.call::<_, proto::ReadResult>(
proto::READ_FILE,
proto::PathParams {
path: PathBuf::from("a.md"),
},
)
.await
.unwrap_err();
match err {
sapphire_ipc::Error::Rpc(e) => {
assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS, "{}", e.message);
}
other => panic!("got {other:?}"),
}
}
#[tokio::test]
async fn a_malformed_parameter_object_is_an_invalid_parameter() {
let f = fixture().await;
let err = f
.client
.call::<_, proto::ReadResult>(proto::READ_FILE, serde_json::json!({ "ws": 42 }))
.await
.unwrap_err();
match err {
sapphire_ipc::Error::Rpc(e) => {
assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS);
}
other => panic!("got {other:?}"),
}
}
async fn listed(client: &Client, path: &str) -> Vec<String> {
let listing: Value = client
.call("fs.list", serde_json::json!({ "path": path }))
.await
.unwrap();
listing["entries"]
.as_array()
.unwrap()
.iter()
.map(|e| e["name"].as_str().unwrap().to_owned())
.collect()
}
async fn apply(client: &Client, origin: &str, ops: Value) -> (u64, u64) {
let records: Value = client
.call(
"fs.apply",
serde_json::json!({ "ops": ops, "origin": origin, "label": "test" }),
)
.await
.unwrap();
let summary = &records["summary"];
(
summary["done"].as_u64().unwrap(),
summary["skipped"].as_u64().unwrap(),
)
}
#[tokio::test]
async fn the_explorer_lists_the_workspace_without_its_dot_names() {
let f = fixture().await;
std::fs::write(f.ws.join("a.md"), "a").unwrap();
std::fs::create_dir(f.ws.join("notes")).unwrap();
let version: Value = f
.client
.call("fs.version", serde_json::json!({}))
.await
.unwrap();
assert_eq!(version["api"], corundum_framework_fs::api::API_VERSION);
assert_eq!(listed(&f.client, "").await, ["a.md", "notes"]);
}
#[tokio::test]
async fn a_move_is_undone_by_its_origin() {
let f = fixture().await;
std::fs::write(f.ws.join("a.md"), "a").unwrap();
std::fs::create_dir(f.ws.join("notes")).unwrap();
let moved = apply(
&f.client,
"gui:1",
serde_json::json!([{ "kind": "fs.move", "from": "a.md", "to": "notes/a.md" }]),
)
.await;
assert_eq!(moved, (1, 0));
assert!(f.ws.join("notes/a.md").exists());
let _: Value = f
.client
.call("journal.undo", serde_json::json!({ "origin": "gui:1" }))
.await
.unwrap();
assert!(f.ws.join("a.md").exists());
assert!(!f.ws.join("notes/a.md").exists());
}
#[tokio::test]
async fn the_trash_is_kept_in_the_unsynced_folder() {
let f = fixture().await;
std::fs::write(f.ws.join("a.md"), "a").unwrap();
let trashed = apply(
&f.client,
"gui:1",
serde_json::json!([{ "kind": "fs.trash", "path": "a.md" }]),
)
.await;
assert_eq!(trashed, (1, 0));
assert!(!f.ws.join("a.md").exists());
let trash = f.ws.join(crate::fs_methods::OWN_FOLDER).join("trash");
let ids: Vec<_> = std::fs::read_dir(&trash).unwrap().collect();
assert_eq!(ids.len(), 1);
assert!(ids[0].as_ref().unwrap().path().join("a.md").exists());
assert!(listed(&f.client, "").await.is_empty());
}
#[tokio::test]
async fn another_workspace_is_served_with_an_empty_history() {
let f = fixture().await;
std::fs::write(f.ws.join("a.md"), "a").unwrap();
apply(
&f.client,
"gui:1",
serde_json::json!([{ "kind": "fs.move", "from": "a.md", "to": "b.md" }]),
)
.await;
let other = f.ws.parent().unwrap().join("other");
std::fs::create_dir_all(other.join(".sapphire-handlertest")).unwrap();
std::fs::write(other.join("c.md"), "c").unwrap();
f.current.select(&other).await.unwrap();
assert_eq!(listed(&f.client, "").await, ["c.md"]);
let err = f
.client
.call::<_, Value>("journal.undo", serde_json::json!({ "origin": "gui:1" }))
.await
.unwrap_err();
let sapphire_ipc::Error::Rpc(err) = err else {
panic!("not an RPC error: {err}");
};
assert_eq!(err.code, corundum_framework_fs::api::codes::NOTHING_TO_UNDO);
assert!(f.ws.join("b.md").exists());
}
#[tokio::test]
async fn without_a_workspace_the_explorer_is_refused() {
let f = fixture_selecting(false).await;
let err = f
.client
.call::<_, Value>("fs.list", serde_json::json!({ "path": "" }))
.await
.unwrap_err();
assert!(matches!(err, sapphire_ipc::Error::Rpc(_)), "{err}");
}
}