1use crate::domain::{MCard, MCardPayload};
11use crate::error::{ClmError, Result, StorageErrorCode};
12use crate::types::{AgentDid, ContentHash};
13use rusqlite::{params, Connection};
14use serde::{Deserialize, Serialize};
15use std::sync::{Arc, Mutex};
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub struct MCardStat {
20 pub uri: String,
21 pub hash: ContentHash,
22 pub size_bytes: usize,
23 pub created_at: String,
24 pub updated_at: String,
25}
26
27pub use crate::layer2::vfs::{DirectoryManifest, DirectoryManifestEntry};
28
29#[derive(Clone)]
31pub struct MCardFileSystem {
32 pub(crate) conn: Arc<Mutex<Connection>>,
33 pub(crate) context_prefix: String,
34}
35
36impl MCardFileSystem {
37 pub fn new_in_memory() -> Result<Self> {
39 let conn = Connection::open_in_memory()?;
40 Self::init_schema(&conn)?;
41 Ok(Self {
42 conn: Arc::new(Mutex::new(conn)),
43 context_prefix: String::new(),
44 })
45 }
46
47 pub fn new_in_memory_scoped(prefix: &str) -> Result<Self> {
49 let mut fs = Self::new_in_memory()?;
50 fs.context_prefix = prefix.trim_matches('/').to_string();
51 Ok(fs)
52 }
53
54 pub fn new(conn: Arc<Mutex<Connection>>, context_prefix: &str) -> Self {
56 Self {
57 conn,
58 context_prefix: context_prefix.trim_matches('/').to_string(),
59 }
60 }
61
62 pub fn with_connection(conn: Arc<Mutex<Connection>>) -> Result<Self> {
64 {
65 let locked = conn
66 .lock()
67 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
68 Self::init_schema(&locked)?;
69 }
70 Ok(Self {
71 conn,
72 context_prefix: String::new(),
73 })
74 }
75
76 pub fn with_prefix(&self, prefix: &str) -> Self {
78 Self {
79 conn: self.conn.clone(),
80 context_prefix: prefix.trim_matches('/').to_string(),
81 }
82 }
83
84 pub fn context_prefix(&self) -> &str {
86 &self.context_prefix
87 }
88
89 pub fn canonicalize_uri(&self, path: &str) -> String {
91 let clean = path.trim_start_matches('/');
92 if let Some(rest) = clean.strip_prefix("mcard:") {
93 let rest_clean = rest.trim_start_matches('/');
94 if self.context_prefix.is_empty() {
95 format!("mcard:{}", rest_clean)
96 } else if rest_clean.starts_with(&self.context_prefix) {
97 format!("mcard:{}", rest_clean)
98 } else {
99 format!("mcard:{}/{}", self.context_prefix, rest_clean)
100 }
101 } else if self.context_prefix.is_empty() {
102 format!("mcard:{}", clean)
103 } else {
104 format!("mcard:{}/{}", self.context_prefix, clean)
105 }
106 }
107
108 pub fn ephemeral_mount(&self, fiber: &crate::fiber::context::Fiber, prefix: &str) -> Result<Self> {
111 let scoped_fs = self.with_prefix(prefix);
112 let prefix_clean = prefix.trim_matches('/').to_string();
113 let handle_pattern = if prefix_clean.is_empty() {
114 "mcard:%".to_string()
115 } else {
116 format!("mcard:{}/%", prefix_clean)
117 };
118 let conn_clone = self.conn.clone();
119
120 fiber.register_disposable(move || {
121 let conn = conn_clone.lock().map_err(|e| e.to_string())?;
122 conn.execute(
123 "DELETE FROM handle_history WHERE handle LIKE ?1",
124 rusqlite::params![&handle_pattern],
125 )
126 .map_err(|e| e.to_string())?;
127 conn.execute(
128 "DELETE FROM handle_registry WHERE handle LIKE ?1",
129 rusqlite::params![&handle_pattern],
130 )
131 .map_err(|e| e.to_string())?;
132 Ok(())
133 });
134
135 Ok(scoped_fs)
136 }
137
138 fn init_schema(conn: &Connection) -> Result<()> {
140 conn.execute_batch(crate::layer0::runtime_contract::SQLITE_DDL_V3_1)?;
141 Ok(())
142 }
143
144 pub fn write_file(&self, uri: &str, payload: MCardPayload, author: AgentDid) -> Result<MCard> {
146 let canonical_uri = self.canonicalize_uri(uri);
147 let now = crate::utils::now_iso8601();
148 let mut conn = self
149 .conn
150 .lock()
151 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
152
153 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
154
155 let existing: Option<String> = {
157 let mut stmt = tx.prepare_cached(
158 "SELECT current_hash FROM handle_registry WHERE handle = ?1",
159 )?;
160 stmt.query_row(params![&canonical_uri], |row| row.get(0))
161 .ok()
162 };
163
164 let seq = match &existing {
165 Some(_) => {
166 let mut count_stmt = tx.prepare_cached(
168 "SELECT count(*) FROM handle_history WHERE handle = ?1",
169 )?;
170 let count: i64 = count_stmt.query_row(params![&canonical_uri], |row| row.get(0))?;
171 (count as u64) + 2
172 }
173 None => 1,
174 };
175
176 let mcard = MCard::new(&canonical_uri, payload, author, seq);
184 let envelope = crate::layer0::codec::canonical_json(&mcard).map_err(|e| e.to_string())?;
185 let record = crate::layer0::mcard_record::MCardRecord::create(envelope.as_bytes(), None)
186 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))?;
187 let hash_str = record.hash.clone();
188
189 {
191 let mut stmt_card = tx.prepare_cached(
192 "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
193 )?;
194 stmt_card.execute(params![&record.hash, &record.content, &record.g_time])?;
195 }
196
197 if let Some(prev_hash) = existing.as_ref().filter(|prev| **prev != hash_str) {
199 let mut stmt_hist = tx.prepare_cached(
200 "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
201 )?;
202 stmt_hist.execute(params![&canonical_uri, prev_hash, now])?;
203 }
204
205 {
207 let mut stmt_reg = tx.prepare_cached(
208 "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) \
209 VALUES (?1, ?2, ?3)",
210 )?;
211 stmt_reg.execute(params![&canonical_uri, hash_str, now])?;
212 }
213
214 tx.commit()?;
215 Ok(mcard)
216 }
217
218 pub fn read_file(&self, uri: &str) -> Result<MCard> {
220 let canonical_uri = self.canonicalize_uri(uri);
221 let conn = self
222 .conn
223 .lock()
224 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
225
226 let current_hash: String = {
228 let mut stmt = conn.prepare_cached(
229 "SELECT current_hash FROM handle_registry WHERE handle = ?1",
230 )?;
231 stmt.query_row(params![&canonical_uri], |row| row.get(0)).map_err(|_| {
232 ClmError::storage(
233 StorageErrorCode::CardNotFound,
234 format!("Handle '{}' not found in MCardFs", canonical_uri),
235 )
236 })?
237 };
238
239 let (content, g_time): (Vec<u8>, String) = {
241 let mut stmt = conn.prepare_cached("SELECT content, g_time FROM card WHERE hash = ?1")?;
242 stmt.query_row(params![current_hash], |row| Ok((row.get(0)?, row.get(1)?)))
243 .map_err(|_| {
244 ClmError::storage(
245 StorageErrorCode::CorruptedContent,
246 format!("Card content for hash '{}' not found", current_hash),
247 )
248 })?
249 };
250
251 let record = crate::layer0::mcard_record::MCardRecord {
253 hash: current_hash.clone(),
254 content: content.clone(),
255 g_time: g_time.clone(),
256 };
257 if !matches!(
258 crate::layer0::mcard_record::verify_record(&record),
259 crate::layer0::mcard_record::RecordVerification::DeclaredOk { .. }
260 ) {
261 return Err(ClmError::storage(
262 StorageErrorCode::CorruptedContent,
263 format!("Cryptographic mismatch for handle '{}': stored row does not verify", canonical_uri),
264 ));
265 }
266
267 let mcard: MCard = serde_json::from_slice(&content)?;
268 Ok(mcard)
269 }
270
271 pub fn exists(&self, uri: &str) -> Result<bool> {
273 let canonical_uri = self.canonicalize_uri(uri);
274 let conn = self
275 .conn
276 .lock()
277 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
278 let mut stmt = conn.prepare_cached(
279 "SELECT count(*) FROM handle_registry WHERE handle = ?1",
280 )?;
281 let count: i64 = stmt.query_row(params![&canonical_uri], |row| row.get(0))?;
282 Ok(count > 0)
283 }
284
285 pub fn stat_file(&self, uri: &str) -> Result<MCardStat> {
287 let canonical_uri = self.canonicalize_uri(uri);
288 let conn = self
289 .conn
290 .lock()
291 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
292
293 let (hash_str, updated_at): (String, String) = {
294 let mut stmt = conn.prepare_cached(
295 "SELECT current_hash, updated_at FROM handle_registry WHERE handle = ?1",
296 )?;
297 stmt.query_row(params![&canonical_uri], |row| {
298 Ok((row.get(0)?, row.get(1)?))
299 })
300 .map_err(|_| {
301 ClmError::storage(
302 StorageErrorCode::CardNotFound,
303 format!("Handle '{}' not found", canonical_uri),
304 )
305 })?
306 };
307
308 let created_at: String = {
309 let mut stmt = conn.prepare_cached(
310 "SELECT changed_at FROM handle_history WHERE handle = ?1 ORDER BY rowid ASC LIMIT 1",
311 )?;
312 stmt.query_row(params![&canonical_uri], |row| row.get(0))
313 .unwrap_or_else(|_| updated_at.clone())
314 };
315
316 let size_bytes: usize = {
317 let mut stmt = conn.prepare_cached("SELECT length(content) FROM card WHERE hash = ?1")?;
318 stmt.query_row(params![hash_str], |row| row.get::<_, i64>(0))
319 .unwrap_or(0) as usize
320 };
321
322 let hash = {
325 let mut stmt = conn.prepare_cached("SELECT content FROM card WHERE hash = ?1")?;
326 let body: Vec<u8> = stmt.query_row(params![hash_str], |row| row.get(0)).unwrap_or_default();
327 match serde_json::from_slice::<MCard>(&body) {
328 Ok(envelope) => ContentHash::parse(&envelope.hash)?,
329 Err(_) => ContentHash::parse(&hash_str)?,
330 }
331 };
332 Ok(MCardStat {
333 uri: canonical_uri,
334 hash,
335 size_bytes,
336 created_at,
337 updated_at,
338 })
339 }
340
341 pub fn list_dir(&self, prefix: &str) -> Result<Vec<String>> {
343 let conn = self
344 .conn
345 .lock()
346 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
347
348 let canonical_prefix = self.canonicalize_uri(prefix);
349 let pattern = if canonical_prefix.ends_with('/') {
350 format!("{}%", canonical_prefix)
351 } else if canonical_prefix == "mcard:" {
352 "mcard:%".to_string()
353 } else {
354 format!("{}/%", canonical_prefix)
355 };
356
357 let mut stmt = conn.prepare_cached(
358 "SELECT handle FROM handle_registry WHERE handle LIKE ?1 ORDER BY handle ASC",
359 )?;
360 let rows = stmt.query_map(params![pattern], |row| row.get(0))?;
361
362 let mut handles = Vec::new();
363 for handle in rows {
364 handles.push(handle?);
365 }
366 Ok(handles)
367 }
368
369 pub fn delete_file(&self, uri: &str) -> Result<()> {
371 let canonical_uri = self.canonicalize_uri(uri);
372 let mut conn = self
373 .conn
374 .lock()
375 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
376
377 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
378 {
379 let mut stmt_hist = tx.prepare_cached("DELETE FROM handle_history WHERE handle = ?1")?;
381 stmt_hist.execute(params![&canonical_uri])?;
382
383 let mut stmt_del = tx.prepare_cached("DELETE FROM handle_registry WHERE handle = ?1")?;
385 let affected = stmt_del.execute(params![&canonical_uri])?;
386
387 if affected == 0 {
388 return Err(ClmError::storage(
389 StorageErrorCode::CardNotFound,
390 format!("Handle '{}' not found for deletion", canonical_uri),
391 ));
392 }
393 }
394 tx.commit()?;
395 Ok(())
396 }
397}
398