Skip to main content

qualia_client_core/
canvas_store.rs

1//! Persistent store for Chora canvas world configurations.
2
3use std::fs;
4use std::path::{Path, PathBuf};
5
6use serde::{Deserialize, Serialize};
7
8use crate::canvas_world::{CanvasWorldConfig, WorldConfigError};
9
10pub const WORLDS_FILE: &str = "wellfair/canvas_worlds.json";
11
12#[derive(Debug, Clone, Serialize, Deserialize, Default)]
13pub struct CanvasWorldRecord {
14    pub config: CanvasWorldConfig,
15    pub created_unix: u64,
16    pub updated_unix: u64,
17}
18
19pub struct CanvasWorldStore {
20    path: PathBuf,
21}
22
23impl CanvasWorldStore {
24    /// Opens.
25    pub fn open(storage_root: impl AsRef<Path>) -> std::io::Result<Self> {
26        let path = storage_root.as_ref().join(WORLDS_FILE);
27        if let Some(parent) = path.parent() {
28            fs::create_dir_all(parent)?;
29        }
30        Ok(Self { path })
31    }
32
33    /// Loads all.
34    pub fn load_all(&self) -> std::io::Result<Vec<CanvasWorldRecord>> {
35        match fs::read(&self.path) {
36            Ok(bytes) => {
37                serde_json::from_slice(&bytes).map_err(|e| std::io::Error::other(e.to_string()))
38            }
39            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
40            Err(e) => Err(e),
41        }
42    }
43
44    fn save_all(&self, records: &[CanvasWorldRecord]) -> std::io::Result<()> {
45        let tmp = self.path.with_extension("json.tmp");
46        let json =
47            serde_json::to_vec_pretty(records).map_err(|e| std::io::Error::other(e.to_string()))?;
48        fs::write(&tmp, &json)?;
49        fs::rename(&tmp, &self.path)?;
50        Ok(())
51    }
52
53    /// Lists.
54    pub fn list(&self) -> std::io::Result<Vec<CanvasWorldConfig>> {
55        Ok(self.load_all()?.into_iter().map(|r| r.config).collect())
56    }
57
58    /// Gets.
59    pub fn get(&self, world_id: &str) -> std::io::Result<Option<CanvasWorldConfig>> {
60        Ok(self
61            .load_all()?
62            .into_iter()
63            .find(|r| r.config.id == world_id)
64            .map(|r| r.config))
65    }
66
67    /// Upserts a record.
68    pub fn upsert(&self, config: CanvasWorldConfig, now_unix: u64) -> Result<(), UpsertError> {
69        config.validate().map_err(UpsertError::Invalid)?;
70        let mut records = self.load_all().map_err(UpsertError::Io)?;
71        if let Some(rec) = records.iter_mut().find(|r| r.config.id == config.id) {
72            rec.config = config;
73            rec.updated_unix = now_unix;
74        } else {
75            records.push(CanvasWorldRecord {
76                config,
77                created_unix: now_unix,
78                updated_unix: now_unix,
79            });
80        }
81        self.save_all(&records).map_err(UpsertError::Io)
82    }
83
84    /// Removes.
85    pub fn remove(&self, world_id: &str) -> std::io::Result<bool> {
86        let mut records = self.load_all()?;
87        let before = records.len();
88        records.retain(|r| r.config.id != world_id);
89        if records.len() == before {
90            return Ok(false);
91        }
92        self.save_all(&records)?;
93        Ok(true)
94    }
95
96    /// Seed the demo world if the store is empty (P0 offline milestone).
97    pub fn seed_if_empty(&self, now_unix: u64) -> std::io::Result<bool> {
98        let records = self.load_all()?;
99        if !records.is_empty() {
100            return Ok(false);
101        }
102        let demo = CanvasWorldConfig::seed_demo();
103        self.upsert(demo, now_unix).map_err(|e| match e {
104            UpsertError::Io(e) => e,
105            UpsertError::Invalid(err) => std::io::Error::other(err.to_string()),
106        })?;
107        Ok(true)
108    }
109}
110
111#[derive(Debug)]
112pub enum UpsertError {
113    Io(std::io::Error),
114    Invalid(WorldConfigError),
115}
116
117impl std::fmt::Display for UpsertError {
118    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119        match self {
120            Self::Io(e) => write!(f, "{e}"),
121            Self::Invalid(e) => write!(f, "{e}"),
122        }
123    }
124}
125impl std::error::Error for UpsertError {}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130    use crate::canvas_world::CanvasWorldConfig;
131
132    #[test]
133    fn roundtrip_and_seed() {
134        let dir = std::env::temp_dir().join(format!("chora-store-{}", std::process::id()));
135        let _ = fs::remove_dir_all(&dir);
136        let store = CanvasWorldStore::open(&dir).unwrap();
137        assert!(store.seed_if_empty(1_700_000_000).unwrap());
138        assert!(!store.seed_if_empty(1_700_000_001).unwrap());
139
140        let worlds = store.list().unwrap();
141        assert_eq!(worlds.len(), 1);
142        assert_eq!(worlds[0].id, "q42:world:demo-offline");
143
144        let mut custom = CanvasWorldConfig::default();
145        custom.id = "q42:world:test".into();
146        custom.title = "Test".into();
147        custom.assets.push(crate::canvas_world::CanvasAssetRef {
148            asset_id: "hash:abc".into(),
149            lat: None,
150            lon: None,
151            alt_m: None,
152            valid_from: None,
153            valid_until: None,
154            licence: "CC-BY".into(),
155        });
156        store.upsert(custom, 1_700_000_100).unwrap();
157        assert_eq!(store.list().unwrap().len(), 2);
158        assert!(store.remove("q42:world:test").unwrap());
159        assert_eq!(store.list().unwrap().len(), 1);
160        let _ = fs::remove_dir_all(&dir);
161    }
162}