use std::path::{Path, PathBuf};
use std::sync::Arc;
use grain_id::GrainId;
use sapphire_backend::WorkspaceBackend;
use sapphire_backend::protocol as proto;
use sapphire_ipc::{Router, RpcError};
use sapphire_workspace::{AppContext, Workspace};
use tokio::sync::Mutex as AsyncMutex;
use crate::error::{Error, Result};
use crate::handlers::rpc_error;
use crate::host::WorkspaceHost;
use crate::selection::{Selection, SelectionFile, slug};
use crate::settings::Settings;
use crate::sync::{SYNC_ID_FILE, SyncRuntime};
const RELEASE_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
pub struct Current {
ctx: &'static AppContext,
host: Arc<WorkspaceHost>,
sync: Option<Arc<SyncRuntime>>,
file: SelectionFile,
settings: Option<Settings>,
switching: AsyncMutex<()>,
}
impl std::fmt::Debug for Current {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Current")
.field("root", &self.host.root())
.finish()
}
}
impl Current {
pub fn new(
ctx: &'static AppContext,
host: Arc<WorkspaceHost>,
sync: Option<Arc<SyncRuntime>>,
file: SelectionFile,
) -> Current {
Current {
ctx,
host,
sync,
file,
settings: None,
switching: AsyncMutex::new(()),
}
}
pub(crate) fn with_settings(mut self, settings: Settings) -> Current {
self.settings = Some(settings);
self
}
pub fn host(&self) -> &Arc<WorkspaceHost> {
&self.host
}
pub fn sync(&self) -> Option<&Arc<SyncRuntime>> {
self.sync.as_ref()
}
pub fn root(&self) -> Option<PathBuf> {
self.host.root()
}
pub async fn select(&self, dir: &Path) -> Result<proto::CurrentWorkspace> {
let root = resolve(dir)?;
let sync = has_sync_id(self.ctx, &root);
self.switch(&root, sync, false).await?;
self.describe().await.ok_or(Error::NoWorkspace)
}
pub async fn init(&self, dir: &Path) -> Result<proto::WorkspaceInitResult> {
let result = init_workspace(self.ctx, dir)?;
let sync = has_sync_id(self.ctx, &result.root);
self.switch(&result.root, sync, false).await?;
Ok(result)
}
pub async fn map(&self, selector: &str, dir: &Path) -> Result<GrainId> {
let runtime = self.runtime()?;
let first = !has_sync_id(self.ctx, &resolve(dir)?);
let root = runtime.place(selector, dir).await?;
if first {
let config = Workspace::from_root(self.ctx, &root)?.config_path();
if let Err(err) = drop_bare_registry(&config) {
tracing::warn!(config = %config.display(), "could not clear the registry-only config: {err}");
}
}
self.switch(&root, false, false).await?;
self.enable_sync().await
}
pub async fn relocate(&self, dir: &Path) -> Result<proto::CurrentWorkspace> {
{
let _one = self.switching.lock().await;
let from = self.root().ok_or(Error::NoWorkspace)?;
let to = destination(dir)?;
if to.starts_with(&from) {
return Err(Error::Config(format!(
"cannot move {} into itself",
from.display()
)));
}
let from_cache = Workspace::from_root(self.ctx, &from)?.cache_dir();
let synced = self.let_go(&from).await?;
self.host.close();
if let Err(err) = std::fs::rename(&from, &to) {
self.reopen(&from, synced).await;
return Err(match err.kind() {
std::io::ErrorKind::CrossesDevices => Error::Config(format!(
"cannot move {} to another drive ({}); move it there yourself, then open it",
from.display(),
to.display()
)),
_ => Error::Io(std::io::Error::new(
err.kind(),
format!(
"could not move {} to {}: {err}",
from.display(),
to.display()
),
)),
});
}
let workspace = Workspace::from_root(self.ctx, &to)?;
carry_cache(&from_cache, &workspace.cache_dir(), &to);
self.reopen(&to, synced).await;
}
if let Ok(backend) = self.host.backend().await {
tokio::spawn(async move {
let started = std::time::Instant::now();
let result = backend.sync().await;
crate::instrument::reindexed(started, result.is_ok());
if let Err(err) = result {
tracing::warn!("re-indexing the moved workspace: {err}");
}
});
}
self.describe().await.ok_or(Error::NoWorkspace)
}
pub async fn remove(&self, delete: bool) -> Result<()> {
let _one = self.switching.lock().await;
let root = self.root().ok_or(Error::NoWorkspace)?;
let cache = Workspace::from_root(self.ctx, &root)
.ok()
.map(|w| w.cache_dir());
if delete {
self.let_go(&root).await?;
} else if let Some(runtime) = &self.sync
&& let Err(err) = runtime.disable(&root).await
{
tracing::warn!(root = %root.display(), "stopping sync before the removal: {err}");
}
self.host.close();
self.file.clear()?;
self.refresh_settings();
if delete {
match std::fs::remove_dir_all(&root) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => {
return Err(Error::Io(std::io::Error::new(
e.kind(),
format!("could not delete {}: {e}", root.display()),
)));
}
}
if let Some(cache) = cache
&& let Err(err) = std::fs::remove_dir_all(&cache)
&& err.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!(cache = %cache.display(), "could not delete the cache: {err}");
}
}
Ok(())
}
async fn let_go(&self, root: &Path) -> Result<bool> {
let Some(runtime) = &self.sync else {
return Ok(false);
};
if !runtime.roots().await.iter().any(|r| r == root) {
return Ok(false);
}
if let Err(err) = runtime.release(root, RELEASE_LIMIT).await {
if let Err(again) = runtime.enable(root).await {
tracing::warn!(root = %root.display(), "could not restart sync: {again}");
}
return Err(err);
}
Ok(true)
}
async fn reopen(&self, root: &Path, sync: bool) {
if let Err(err) = self.host.select(root, true).await {
tracing::warn!(root = %root.display(), "could not reopen the workspace: {err}");
}
if sync
&& let Some(runtime) = &self.sync
&& let Err(err) = runtime.enable(root).await
{
tracing::warn!(root = %root.display(), "could not restart sync: {err}");
}
self.remember(root, sync);
}
pub async fn enable_sync(&self) -> Result<GrainId> {
let runtime = self.runtime()?;
let _one = self.switching.lock().await;
let root = self.root().ok_or(Error::NoWorkspace)?;
let id = match runtime.enable(&root).await {
Ok(id) => id,
Err(err @ Error::BridgeDisconnected) => {
self.remember(&root, true);
return Err(err);
}
Err(err) => return Err(err),
};
self.remember(&root, true);
Ok(id)
}
pub async fn disable_sync(&self) -> Result<()> {
let runtime = self.runtime()?;
let _one = self.switching.lock().await;
let root = self.root().ok_or(Error::NoWorkspace)?;
runtime.disable(&root).await?;
self.remember(&root, false);
Ok(())
}
pub async fn status(&self) -> proto::SyncStatusResult {
match &self.sync {
Some(runtime) => runtime
.status(&self.root().unwrap_or_default())
.await
.into(),
None => proto::SyncStatusResult::not_synced(),
}
}
pub async fn describe(&self) -> Option<proto::CurrentWorkspace> {
let root = self.root()?;
let marker = root.join(format!(".{}", self.ctx.app_name));
let workspace_id = std::fs::read_to_string(marker.join(SYNC_ID_FILE))
.ok()
.and_then(|s| s.trim().parse().ok());
let sync = match &self.sync {
Some(runtime) => runtime.status(&root).await.into(),
None => proto::SyncStatusResult::not_synced(),
};
Some(proto::CurrentWorkspace {
reachable: marker.is_dir(),
root,
workspace_id,
sync,
})
}
pub(crate) async fn restore(self: &Arc<Self>) -> Option<tokio::task::JoinHandle<()>> {
let selection = match self.file.load(self.ctx.app_name) {
Ok(Some(selection)) => selection,
Ok(None) => return None,
Err(err) => {
tracing::warn!("could not read the selected workspace: {err}");
return None;
}
};
{
let _one = self.switching.lock().await;
if let Err(err) = self.host.select(&selection.root, true).await {
tracing::warn!(root = %selection.root.display(), "could not restore the workspace: {err}");
return None;
}
self.refresh_settings();
}
if !selection.sync {
return None;
}
let runtime = self.sync.clone()?;
let current = Arc::clone(self);
Some(tokio::spawn(async move {
let _one = current.switching.lock().await;
if current.root().as_deref() != Some(&selection.root) {
return;
}
if let Err(err) = runtime.enable(&selection.root).await {
tracing::warn!(root = %selection.root.display(), "could not restore sync: {err}");
}
}))
}
async fn switch(&self, root: &Path, sync: bool, restoring: bool) -> Result<()> {
let _one = self.switching.lock().await;
let previous = self.root();
self.host.select(root, restoring).await?;
if let Some(runtime) = &self.sync {
if let Some(previous) = previous.filter(|p| p != root)
&& let Err(err) = runtime.disable(&previous).await
{
tracing::warn!(root = %previous.display(), "stopping sync of the previous workspace: {err}");
}
if sync && let Err(err) = runtime.enable(root).await {
tracing::warn!(root = %root.display(), "could not start sync: {err}");
}
}
self.remember(root, sync);
Ok(())
}
fn remember(&self, root: &Path, sync: bool) {
let selection = Selection {
root: root.to_owned(),
sync,
};
if let Err(err) = self.file.save(&selection) {
tracing::warn!(root = %root.display(), "could not record the selected workspace: {err}");
}
self.refresh_settings();
}
fn refresh_settings(&self) {
if let Some(settings) = &self.settings
&& settings.refresh().is_err()
{
tracing::warn!("could not read the settings of the selected workspace");
}
}
fn runtime(&self) -> Result<&Arc<SyncRuntime>> {
self.sync
.as_ref()
.ok_or_else(|| Error::Config("this server does not sync".to_owned()))
}
}
fn has_sync_id(ctx: &AppContext, root: &Path) -> bool {
root.join(format!(".{}", ctx.app_name))
.join(SYNC_ID_FILE)
.is_file()
}
fn resolve(dir: &Path) -> Result<PathBuf> {
std::env::current_dir()
.map_err(Error::Io)?
.join(dir)
.canonicalize()
.map_err(Error::Io)
}
fn destination(dir: &Path) -> Result<PathBuf> {
let dir = std::env::current_dir().map_err(Error::Io)?.join(dir);
if dir.exists() {
return Err(Error::Config(format!(
"{} already exists; choose a new folder name",
dir.display()
)));
}
let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else {
return Err(Error::Config(format!(
"{} cannot be a workspace root",
dir.display()
)));
};
Ok(parent.canonicalize().map_err(Error::Io)?.join(name))
}
fn carry_cache(from: &Path, to: &Path, root: &Path) {
let sync_from = from.join("sync");
if sync_from.is_dir() {
let sync_to = to.join("sync");
let moved =
std::fs::create_dir_all(to).and_then(|()| std::fs::rename(&sync_from, &sync_to));
match moved {
Ok(()) => {
let store = sync_to.join("sync.redb");
if store.is_file()
&& let Err(err) =
sapphire_sync::ReplicaStore::relocate(&store, &root.to_string_lossy())
{
tracing::warn!(store = %store.display(), "could not rebase the replica: {err}");
}
}
Err(err) => {
tracing::warn!(cache = %from.display(), "could not carry the replica over: {err}");
}
}
}
if let Err(err) = std::fs::remove_dir_all(from)
&& err.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!(cache = %from.display(), "could not delete the old cache: {err}");
}
}
pub(crate) fn current_methods(current: Arc<Current>, router: Router) -> Router {
let init = Arc::clone(¤t);
let select = Arc::clone(¤t);
let relocate = Arc::clone(¤t);
let remove = Arc::clone(¤t);
router
.method(proto::WORKSPACE_MOVE, move |req| {
let current = Arc::clone(&relocate);
async move {
let p: proto::WorkspaceMoveParams = serde_json::from_value(req.params)
.map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
let result = current.relocate(&p.dir).await.map_err(|e| rpc_error(&e))?;
serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
}
})
.method(proto::WORKSPACE_REMOVE, move |req| {
let current = Arc::clone(&remove);
async move {
let p: proto::WorkspaceRemoveParams = serde_json::from_value(req.params)
.map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
current.remove(p.delete).await.map_err(|e| rpc_error(&e))?;
serde_json::to_value(proto::Ack {}).map_err(|e| RpcError::internal(e.to_string()))
}
})
.method(proto::WORKSPACE_INIT, move |req| {
let current = Arc::clone(&init);
async move {
let p: proto::WorkspaceInitParams = serde_json::from_value(req.params)
.map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
let result = current.init(&p.dir).await.map_err(|e| rpc_error(&e))?;
serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
}
})
.method(proto::WORKSPACE_SELECT, move |req| {
let current = Arc::clone(&select);
async move {
let p: proto::WorkspaceSelectParams = serde_json::from_value(req.params)
.map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
let result = current.select(&p.dir).await.map_err(|e| rpc_error(&e))?;
serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
}
})
.method(proto::WORKSPACE_CURRENT, move |_| {
let current = Arc::clone(¤t);
async move {
let workspace = current.describe().await;
serde_json::to_value(proto::WorkspaceCurrentResult { workspace })
.map_err(|e| RpcError::internal(e.to_string()))
}
})
}
fn init_workspace(ctx: &'static AppContext, dir: &Path) -> Result<proto::WorkspaceInitResult> {
let root = resolve(dir)?;
let marker = root.join(format!(".{}", ctx.app_name));
let created = !marker.is_dir();
if created {
std::fs::create_dir(&marker).map_err(Error::Io)?;
}
Ok(proto::WorkspaceInitResult {
workspace_id: slug(&root),
root,
created,
})
}
fn drop_bare_registry(path: &Path) -> Result<()> {
let config = read_config(path)?;
if config.len() == 1 && config.contains_key("workspace") {
std::fs::remove_file(path).map_err(Error::Io)?;
}
Ok(())
}
fn read_config(path: &Path) -> Result<toml::Table> {
match std::fs::read_to_string(path) {
Ok(text) => text.parse().map_err(|e: toml::de::Error| {
Error::Config(format!(
"{}: {}",
path.display(),
sapphire_framework_settings::describe_toml_error(&text, e.span(), e.message())
))
}),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(toml::Table::new()),
Err(e) => Err(Error::Io(e)),
}
}
#[cfg(test)]
mod tests {
use super::*;
const REGISTRY_ONLY: &str = "[workspace.ledger]\npath = \"/home/me/ledger\"\n";
#[test]
fn only_a_registry_only_config_is_dropped() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, REGISTRY_ONLY).unwrap();
drop_bare_registry(&path).unwrap();
assert!(!path.exists());
drop_bare_registry(&path).unwrap();
std::fs::write(&path, format!("schema_version = 2\n\n{REGISTRY_ONLY}")).unwrap();
drop_bare_registry(&path).unwrap();
assert!(path.exists());
}
struct NoteApp(&'static str);
impl crate::settings::AppSettings for NoteApp {
fn defs(&self) -> Vec<sapphire_framework_settings::SettingDef> {
vec![sapphire_framework_settings::SettingDef {
key: format!("{}.note", self.0),
kind: sapphire_framework_settings::Kind::String { non_empty: false },
scopes: vec![sapphire_framework_settings::Scope::Workspace],
overridable: false,
apply: sapphire_framework_settings::Apply::Live,
default: None,
section: "Test".into(),
doc: "test".into(),
process: sapphire_framework_settings::Process::App,
}]
}
}
#[tokio::test(flavor = "multi_thread")]
async fn workspace_settings_follow_the_selection() {
const APP: &str = "sapphire-curtest";
let dir = tempfile::tempdir().unwrap();
let ctx: &'static AppContext = Box::leak(Box::new(AppContext::new(APP)));
ctx.set_config_dir(dir.path().join("config"));
ctx.set_cache_dir(dir.path().join("cache"));
ctx.set_data_dir(dir.path().join("data"));
let file = SelectionFile::at(dir.path().join("config").join("workspace.toml"));
let (a, b) = (dir.path().join("a"), dir.path().join("b"));
for (root, value) in [(&a, "from a"), (&b, "from b")] {
std::fs::create_dir_all(root).unwrap();
init_workspace(ctx, root).unwrap();
std::fs::write(
root.join(format!(".{APP}")).join("config.toml"),
format!("[{APP}]\nnote = \"{value}\"\n"),
)
.unwrap();
}
let settings = crate::settings::Settings::load_with(
ctx,
std::sync::Arc::new(NoteApp(APP)),
file.clone(),
)
.unwrap();
let key = format!("{APP}.note");
let current = Current::new(ctx, Arc::new(WorkspaceHost::new(ctx)), None, file)
.with_settings(settings.clone());
let mut changed = settings.changed();
current.select(&a).await.unwrap();
assert!(changed.has_changed().unwrap());
changed.mark_unchanged();
assert_eq!(settings.get_as::<String>(&key).as_deref(), Some("from a"));
current.select(&b).await.unwrap();
assert!(changed.has_changed().unwrap());
changed.mark_unchanged();
assert_eq!(settings.get_as::<String>(&key).as_deref(), Some("from b"));
current.remove(false).await.unwrap();
assert!(changed.has_changed().unwrap());
assert_eq!(settings.get(&key), None);
}
#[test]
fn an_unparsable_marker_config_is_never_quoted() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "[app]\ntoken = \"hunter2\" x\n").unwrap();
let err = read_config(&path).unwrap_err().to_string();
assert!(err.contains(&path.display().to_string()), "{err}");
assert!(err.contains("line 2"), "{err}");
assert!(!err.contains("hunter2"), "{err}");
}
#[test]
fn init_writes_no_config() {
let dir = tempfile::tempdir().unwrap();
let ctx: &'static AppContext = Box::leak(Box::new(AppContext::new("sapphire-initapp")));
let result = init_workspace(ctx, dir.path()).unwrap();
assert!(result.created);
let workspace = Workspace::from_root(ctx, dir.path()).unwrap();
assert!(workspace.marker_dir().is_dir());
assert!(!workspace.config_path().exists());
}
}