sapphire_framework_server/
current.rs1use std::path::{Path, PathBuf};
9use std::sync::Arc;
10
11use grain_id::GrainId;
12use sapphire_backend::protocol as proto;
13use sapphire_backend::{WorkspaceEntry, WorkspaceRegistry};
14use sapphire_ipc::{Router, RpcError};
15use sapphire_workspace::{AppContext, Workspace};
16use tokio::sync::Mutex as AsyncMutex;
17
18use crate::error::{Error, Result};
19use crate::handlers::rpc_error;
20use crate::host::WorkspaceHost;
21use crate::selection::{Selection, SelectionFile, slug};
22use crate::sync::{SYNC_ID_FILE, SyncRuntime};
23
24pub struct Current {
26 ctx: &'static AppContext,
27 host: Arc<WorkspaceHost>,
28 sync: Option<Arc<SyncRuntime>>,
29 file: SelectionFile,
30 switching: AsyncMutex<()>,
32}
33
34impl std::fmt::Debug for Current {
35 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36 f.debug_struct("Current")
37 .field("root", &self.host.root())
38 .finish()
39 }
40}
41
42impl Current {
43 pub fn new(
46 ctx: &'static AppContext,
47 host: Arc<WorkspaceHost>,
48 sync: Option<Arc<SyncRuntime>>,
49 file: SelectionFile,
50 ) -> Current {
51 Current {
52 ctx,
53 host,
54 sync,
55 file,
56 switching: AsyncMutex::new(()),
57 }
58 }
59
60 pub fn host(&self) -> &Arc<WorkspaceHost> {
62 &self.host
63 }
64
65 pub fn sync(&self) -> Option<&Arc<SyncRuntime>> {
67 self.sync.as_ref()
68 }
69
70 pub fn root(&self) -> Option<PathBuf> {
72 self.host.root()
73 }
74
75 pub async fn select(&self, dir: &Path) -> Result<proto::CurrentWorkspace> {
77 let root = resolve(dir)?;
78 let sync = has_sync_id(self.ctx, &root);
79 self.switch(&root, sync, false).await?;
80 self.describe().await.ok_or(Error::NoWorkspace)
81 }
82
83 pub async fn init(&self, dir: &Path) -> Result<proto::WorkspaceInitResult> {
86 let result = init_workspace(self.ctx, dir)?;
87 let sync = has_sync_id(self.ctx, &result.root);
88 self.switch(&result.root, sync, false).await?;
89 Ok(result)
90 }
91
92 pub async fn map(&self, selector: &str, dir: &Path) -> Result<GrainId> {
94 let runtime = self.runtime()?;
95 let root = runtime.place(selector, dir).await?;
96 self.switch(&root, false, false).await?;
97 self.enable_sync().await
98 }
99
100 pub async fn enable_sync(&self) -> Result<GrainId> {
102 let runtime = self.runtime()?;
103 let _one = self.switching.lock().await;
104 let root = self.root().ok_or(Error::NoWorkspace)?;
105 let id = runtime.enable(&root).await?;
106 self.remember(&root, true);
107 Ok(id)
108 }
109
110 pub async fn disable_sync(&self) -> Result<()> {
112 let runtime = self.runtime()?;
113 let _one = self.switching.lock().await;
114 let root = self.root().ok_or(Error::NoWorkspace)?;
115 runtime.disable(&root).await?;
116 self.remember(&root, false);
117 Ok(())
118 }
119
120 pub async fn status(&self) -> proto::SyncStatusResult {
122 match &self.sync {
123 Some(runtime) => runtime
126 .status(&self.root().unwrap_or_default())
127 .await
128 .into(),
129 None => proto::SyncStatusResult::not_synced(),
130 }
131 }
132
133 pub async fn describe(&self) -> Option<proto::CurrentWorkspace> {
135 let root = self.root()?;
136 let marker = root.join(format!(".{}", self.ctx.app_name));
137 let workspace_id = std::fs::read_to_string(marker.join(SYNC_ID_FILE))
139 .ok()
140 .and_then(|s| s.trim().parse().ok());
141 let sync = match &self.sync {
142 Some(runtime) => runtime.status(&root).await.into(),
143 None => proto::SyncStatusResult::not_synced(),
144 };
145 Some(proto::CurrentWorkspace {
146 reachable: marker.is_dir(),
147 root,
148 workspace_id,
149 sync,
150 })
151 }
152
153 pub(crate) async fn restore(self: &Arc<Self>) -> Option<tokio::task::JoinHandle<()>> {
159 let selection = match self.file.load(self.ctx.app_name) {
160 Ok(Some(selection)) => selection,
161 Ok(None) => return None,
162 Err(err) => {
163 tracing::warn!("could not read the selected workspace: {err}");
164 return None;
165 }
166 };
167 {
168 let _one = self.switching.lock().await;
169 if let Err(err) = self.host.select(&selection.root, true).await {
170 tracing::warn!(root = %selection.root.display(), "could not restore the workspace: {err}");
171 return None;
172 }
173 }
174 if !selection.sync {
175 return None;
176 }
177 let runtime = self.sync.clone()?;
178 let current = Arc::clone(self);
179 Some(tokio::spawn(async move {
180 let _one = current.switching.lock().await;
183 if current.root().as_deref() != Some(&selection.root) {
184 return;
185 }
186 if let Err(err) = runtime.enable(&selection.root).await {
187 tracing::warn!(root = %selection.root.display(), "could not restore sync: {err}");
188 }
189 }))
190 }
191
192 async fn switch(&self, root: &Path, sync: bool, restoring: bool) -> Result<()> {
197 let _one = self.switching.lock().await;
198 let previous = self.root();
199 self.host.select(root, restoring).await?;
200 if let Some(runtime) = &self.sync {
201 if let Some(previous) = previous.filter(|p| p != root)
202 && let Err(err) = runtime.disable(&previous).await
203 {
204 tracing::warn!(root = %previous.display(), "stopping sync of the previous workspace: {err}");
205 }
206 if sync && let Err(err) = runtime.enable(root).await {
207 tracing::warn!(root = %root.display(), "could not start sync: {err}");
210 }
211 }
212 self.remember(root, sync);
213 Ok(())
214 }
215
216 fn remember(&self, root: &Path, sync: bool) {
217 let selection = Selection {
218 root: root.to_owned(),
219 sync,
220 };
221 if let Err(err) = self.file.save(&selection) {
222 tracing::warn!(root = %root.display(), "could not record the selected workspace: {err}");
223 }
224 }
225
226 fn runtime(&self) -> Result<&Arc<SyncRuntime>> {
227 self.sync
228 .as_ref()
229 .ok_or_else(|| Error::Config("this server does not sync".to_owned()))
230 }
231}
232
233fn has_sync_id(ctx: &AppContext, root: &Path) -> bool {
235 root.join(format!(".{}", ctx.app_name))
236 .join(SYNC_ID_FILE)
237 .is_file()
238}
239
240fn resolve(dir: &Path) -> Result<PathBuf> {
242 std::env::current_dir()
243 .map_err(Error::Io)?
244 .join(dir)
245 .canonicalize()
246 .map_err(Error::Io)
247}
248
249pub(crate) fn current_methods(current: Arc<Current>, router: Router) -> Router {
251 let init = Arc::clone(¤t);
252 let select = Arc::clone(¤t);
253 router
254 .method(proto::WORKSPACE_INIT, move |req| {
255 let current = Arc::clone(&init);
256 async move {
257 let p: proto::WorkspaceInitParams = serde_json::from_value(req.params)
258 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
259 let result = current.init(&p.dir).await.map_err(|e| rpc_error(&e))?;
260 serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
261 }
262 })
263 .method(proto::WORKSPACE_SELECT, move |req| {
264 let current = Arc::clone(&select);
265 async move {
266 let p: proto::WorkspaceSelectParams = serde_json::from_value(req.params)
267 .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
268 let result = current.select(&p.dir).await.map_err(|e| rpc_error(&e))?;
269 serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
270 }
271 })
272 .method(proto::WORKSPACE_CURRENT, move |_| {
273 let current = Arc::clone(¤t);
274 async move {
275 let workspace = current.describe().await;
276 serde_json::to_value(proto::WorkspaceCurrentResult { workspace })
277 .map_err(|e| RpcError::internal(e.to_string()))
278 }
279 })
280}
281
282fn init_workspace(ctx: &'static AppContext, dir: &Path) -> Result<proto::WorkspaceInitResult> {
289 let root = resolve(dir)?;
290 let marker = root.join(format!(".{}", ctx.app_name));
291 let created = !marker.is_dir();
292 if created {
293 std::fs::create_dir(&marker).map_err(Error::Io)?;
294 }
295
296 let workspace = Workspace::from_root(ctx, &root)?;
300 let id = slug(&root);
301 let config_path = workspace.config_path();
302 let registry = read_registry(&config_path)?;
303 if registry.get(&id).is_none() {
304 let mut registry = registry;
305 registry.insert(id.clone(), WorkspaceEntry::local(&root));
306 write_registry(&config_path, ®istry)?;
307 }
308
309 Ok(proto::WorkspaceInitResult {
310 root,
311 workspace_id: id,
312 created,
313 })
314}
315
316fn read_registry(path: &Path) -> Result<WorkspaceRegistry> {
322 #[derive(serde::Deserialize, Default)]
323 struct Config {
324 #[serde(default)]
325 workspace: WorkspaceRegistry,
326 }
327 match std::fs::read_to_string(path) {
328 Ok(text) => {
329 let config: Config = toml::from_str(&text).map_err(|e| Error::SyncId(e.to_string()))?;
330 Ok(config.workspace)
331 }
332 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(WorkspaceRegistry::default()),
333 Err(e) => Err(Error::Io(e)),
334 }
335}
336
337fn write_registry(path: &Path, registry: &WorkspaceRegistry) -> Result<()> {
342 #[derive(serde::Deserialize, serde::Serialize, Default)]
343 struct Config {
344 #[serde(default, skip_serializing_if = "WorkspaceRegistry::is_empty")]
345 workspace: WorkspaceRegistry,
346 }
347 let text = match std::fs::read_to_string(path) {
348 Ok(text) => text,
349 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
350 Err(e) => return Err(Error::Io(e)),
351 };
352 let mut config: Config = toml::from_str(&text).unwrap_or_default();
353 config.workspace = registry.clone();
354 let out = toml::to_string_pretty(&config).map_err(|e| Error::SyncId(e.to_string()))?;
355 std::fs::write(path, out).map_err(Error::Io)
356}