1use crate::{domain::{MCard, MCardPayload}, layer0::vocabulary::HANDLE_MCARD};
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
36const TOMBSTONE_KIND: &str = "TOMBSTONE";
38
39fn head_is_tombstone(conn: &Connection, hash: &str) -> Result<bool> {
41 let record = crate::layer2::record_store::read_record(conn, hash)?
42 .ok_or_else(|| ClmError::storage(StorageErrorCode::CorruptedContent, "handle points to missing card"))?;
43 let bytes = record.content;
44 if bytes.len() > 4096 {
45 return Ok(false);
46 }
47 Ok(serde_json::from_slice::<serde_json::Value>(&bytes)
48 .ok()
49 .and_then(|v| {
50 v.get("kind")
51 .and_then(|k| k.as_str())
52 .map(|k| k == TOMBSTONE_KIND)
53 })
54 .unwrap_or(false))
55}
56
57fn qualified_ref(conn: &Connection, hash: &str) -> Result<String> {
59 let record = crate::layer2::record_store::read_record(conn, hash)?
60 .ok_or_else(|| ClmError::storage(StorageErrorCode::CorruptedContent, "handle points to missing card"))?;
61 let algorithm = crate::layer2::record_store::require_verified(&record)?;
62 Ok(format!("{algorithm}:{}", record.hash))
63}
64
65impl MCardFileSystem {
66 pub fn new_in_memory() -> Result<Self> {
68 let conn = Connection::open_in_memory()?;
69 Self::init_schema(&conn)?;
70 Ok(Self {
71 conn: Arc::new(Mutex::new(conn)),
72 context_prefix: String::new(),
73 })
74 }
75
76 pub fn new_in_memory_scoped(prefix: &str) -> Result<Self> {
78 let mut fs = Self::new_in_memory()?;
79 fs.context_prefix = prefix.trim_matches('/').to_string();
80 Ok(fs)
81 }
82
83 pub fn new(conn: Arc<Mutex<Connection>>, context_prefix: &str) -> Self {
85 Self {
86 conn,
87 context_prefix: context_prefix.trim_matches('/').to_string(),
88 }
89 }
90
91 pub fn with_connection(conn: Arc<Mutex<Connection>>) -> Result<Self> {
93 {
94 let locked = conn
95 .lock()
96 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
97 Self::init_schema(&locked)?;
98 }
99 Ok(Self {
100 conn,
101 context_prefix: String::new(),
102 })
103 }
104
105 pub fn with_prefix(&self, prefix: &str) -> Self {
107 Self {
108 conn: self.conn.clone(),
109 context_prefix: prefix.trim_matches('/').to_string(),
110 }
111 }
112
113 pub fn context_prefix(&self) -> &str {
115 &self.context_prefix
116 }
117
118 pub fn canonicalize_uri(&self, path: &str) -> String {
120 let clean = path.trim_start_matches('/');
121 if let Some(rest) = clean.strip_prefix(crate::layer0::vocabulary::HANDLE_MCARD) {
122 let rest_clean = rest.trim_start_matches('/');
123 if self.context_prefix.is_empty() {
124 format!("{HANDLE_MCARD}{}", rest_clean)
125 } else if rest_clean.starts_with(&self.context_prefix) {
126 format!("{HANDLE_MCARD}{}", rest_clean)
127 } else {
128 format!("{HANDLE_MCARD}{}/{}", self.context_prefix, rest_clean)
129 }
130 } else if self.context_prefix.is_empty() {
131 format!("{HANDLE_MCARD}{}", clean)
132 } else {
133 format!("{HANDLE_MCARD}{}/{}", self.context_prefix, clean)
134 }
135 }
136
137 pub fn ephemeral_mount(&self, fiber: &crate::fiber::context::Fiber, prefix: &str) -> Result<Self> {
140 let scoped_fs = self.with_prefix(prefix);
141 let prefix_clean = prefix.trim_matches('/').to_string();
142 let handle_pattern = if prefix_clean.is_empty() {
143 crate::layer0::vocabulary::HANDLE_MCARD_3.to_string()
144 } else {
145 format!("{HANDLE_MCARD}{}/%", prefix_clean)
146 };
147 let conn_clone = self.conn.clone();
148
149 fiber.register_disposable(move || {
150 let conn = conn_clone.lock().map_err(|e| e.to_string())?;
151 conn.execute(
152 "DELETE FROM handle_history WHERE handle LIKE ?1",
153 rusqlite::params![&handle_pattern],
154 )
155 .map_err(|e| e.to_string())?;
156 conn.execute(
157 "DELETE FROM handle_registry WHERE handle LIKE ?1",
158 rusqlite::params![&handle_pattern],
159 )
160 .map_err(|e| e.to_string())?;
161 Ok(())
162 });
163
164 Ok(scoped_fs)
165 }
166
167 fn init_schema(conn: &Connection) -> Result<()> {
169 conn.execute_batch(crate::layer0::runtime_contract::SQLITE_DDL_V3_1)?;
170 Ok(())
171 }
172
173 pub fn write_file(&self, uri: &str, payload: MCardPayload, author: AgentDid) -> Result<MCard> {
175 let canonical_uri = self.canonicalize_uri(uri);
176 let now = crate::utils::now_iso8601();
177 let mut conn = self
178 .conn
179 .lock()
180 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
181
182 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
183
184 let existing: Option<String> = {
186 let mut stmt = tx.prepare_cached(
187 "SELECT current_hash FROM handle_registry WHERE handle = ?1",
188 )?;
189 stmt.query_row(params![&canonical_uri], |row| row.get(0))
190 .ok()
191 };
192
193 let seq = match &existing {
194 Some(_) => {
195 let mut count_stmt = tx.prepare_cached(
197 "SELECT count(*) FROM handle_history WHERE handle = ?1",
198 )?;
199 let count: i64 = count_stmt.query_row(params![&canonical_uri], |row| row.get(0))?;
200 (count as u64) + 2
201 }
202 None => 1,
203 };
204
205 let mcard = MCard::new(&canonical_uri, payload, author, seq);
208 let envelope = crate::layer0::mcard_projection::encode_content(&mcard)?;
209 let record = crate::layer0::mcard_record::MCardRecord::create(&envelope, None)
210 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))?;
211 let hash_str = record.hash.clone();
212 let mcard: MCard = crate::layer0::mcard_projection::project_record(&record)?;
213
214 crate::layer2::record_store::insert_record(&tx, &record)?;
215
216 if let Some(prev_hash) = existing.as_ref().filter(|prev| **prev != hash_str) {
218 let mut stmt_hist = tx.prepare_cached(
219 "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
220 )?;
221 stmt_hist.execute(params![&canonical_uri, prev_hash, now])?;
222 }
223
224 {
226 let mut stmt_reg = tx.prepare_cached(
227 "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) \
228 VALUES (?1, ?2, ?3)",
229 )?;
230 stmt_reg.execute(params![&canonical_uri, hash_str, now])?;
231 }
232
233 tx.commit()?;
234 Ok(mcard)
235 }
236
237 pub fn read_file(&self, uri: &str) -> Result<MCard> {
239 let canonical_uri = self.canonicalize_uri(uri);
240 let conn = self
241 .conn
242 .lock()
243 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
244
245 let current_hash: String = {
247 let mut stmt = conn.prepare_cached(
248 "SELECT current_hash FROM handle_registry WHERE handle = ?1",
249 )?;
250 stmt.query_row(params![&canonical_uri], |row| row.get(0)).map_err(|_| {
251 ClmError::storage(
252 StorageErrorCode::CardNotFound,
253 format!("Handle '{}' not found in MCardFs", canonical_uri),
254 )
255 })?
256 };
257
258 if head_is_tombstone(&conn, ¤t_hash)? {
259 return Err(ClmError::storage(
260 StorageErrorCode::CardNotFound,
261 format!("Handle '{}' is retired", canonical_uri),
262 ));
263 }
264
265 let record = crate::layer2::record_store::read_record(&conn, ¤t_hash)?
266 .ok_or_else(|| ClmError::storage(StorageErrorCode::CardNotFound, "stored card is missing"))?;
267 crate::layer0::mcard_projection::project_record(&record)
268 .map_err(|error| ClmError::storage(StorageErrorCode::CorruptedContent, error))
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 head: Option<String> = {
279 let mut stmt = conn.prepare_cached(
280 "SELECT current_hash FROM handle_registry WHERE handle = ?1",
281 )?;
282 stmt.query_row(params![&canonical_uri], |row| row.get(0)).ok()
283 };
284 match head {
285 Some(hash) => Ok(!head_is_tombstone(&conn, &hash)?),
286 None => Ok(false),
287 }
288 }
289
290 pub fn stat_file(&self, uri: &str) -> Result<MCardStat> {
292 let canonical_uri = self.canonicalize_uri(uri);
293 let conn = self
294 .conn
295 .lock()
296 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
297
298 let (hash_str, updated_at): (String, String) = {
299 let mut stmt = conn.prepare_cached(
300 "SELECT current_hash, updated_at FROM handle_registry WHERE handle = ?1",
301 )?;
302 stmt.query_row(params![&canonical_uri], |row| {
303 Ok((row.get(0)?, row.get(1)?))
304 })
305 .map_err(|_| {
306 ClmError::storage(
307 StorageErrorCode::CardNotFound,
308 format!("Handle '{}' not found", canonical_uri),
309 )
310 })?
311 };
312
313 if head_is_tombstone(&conn, &hash_str)? {
314 return Err(ClmError::storage(
315 StorageErrorCode::CardNotFound,
316 format!("Handle '{}' is retired", canonical_uri),
317 ));
318 }
319
320 let created_at: String = {
321 let mut stmt = conn.prepare_cached(
322 "SELECT changed_at FROM handle_history WHERE handle = ?1 ORDER BY rowid ASC LIMIT 1",
323 )?;
324 stmt.query_row(params![&canonical_uri], |row| row.get(0))
325 .unwrap_or_else(|_| updated_at.clone())
326 };
327
328 let record = crate::layer2::record_store::read_record(&conn, &hash_str)?
329 .ok_or_else(|| ClmError::storage(StorageErrorCode::CardNotFound, "stored card is missing"))?;
330 let size_bytes = record.content.len();
331 let hash = ContentHash::parse(&record.hash)?;
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 == crate::layer0::vocabulary::HANDLE_MCARD {
352 crate::layer0::vocabulary::HANDLE_MCARD_3.to_string()
353 } else {
354 format!("{}/%", canonical_prefix)
355 };
356
357 let mut stmt = conn.prepare_cached(
358 "SELECT handle, current_hash FROM handle_registry WHERE handle LIKE ?1 ORDER BY handle ASC",
359 )?;
360 let rows = stmt.query_map(params![pattern], |row| {
361 Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
362 })?;
363
364 let mut handles = Vec::new();
365 for row in rows {
366 let (handle, head) = row?;
367 if !head_is_tombstone(&conn, &head)? {
368 handles.push(handle);
369 }
370 }
371 Ok(handles)
372 }
373
374 pub fn retire(&self, uri: &str, reason: Option<&str>, author: AgentDid) -> Result<()> {
379 let canonical_uri = self.canonicalize_uri(uri);
380 let now = crate::utils::now_iso8601();
381 let mut conn = self
382 .conn
383 .lock()
384 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
385
386 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
387
388 let previous_hash: String = {
389 let mut stmt = tx.prepare_cached(
390 "SELECT current_hash FROM handle_registry WHERE handle = ?1",
391 )?;
392 stmt.query_row(params![&canonical_uri], |row| row.get(0)).map_err(|_| {
393 ClmError::storage(
394 StorageErrorCode::CardNotFound,
395 format!("Handle '{}' not found for retirement", canonical_uri),
396 )
397 })?
398 };
399
400 let qualified_from = qualified_ref(&tx, &previous_hash)?;
401 let mut payload = serde_json::json!({
402 "kind": TOMBSTONE_KIND,
403 "handle": canonical_uri,
404 "from": qualified_from,
405 "to": serde_json::Value::Null,
406 "author": author.as_str(),
407 "retiredAt": now,
408 });
409 if let Some(reason) = reason {
410 payload["reason"] = serde_json::Value::String(reason.to_string());
411 }
412 let envelope = crate::layer0::codec::canonical_json(&payload).map_err(|e| e.to_string())?;
413 let record = crate::layer0::mcard_record::MCardRecord::create(envelope.as_bytes(), None)
414 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))?;
415
416 crate::layer2::record_store::insert_record(&tx, &record)?;
417 tx.execute(
418 "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
419 params![&canonical_uri, &previous_hash, now],
420 )?;
421 tx.execute(
423 "UPDATE handle_registry SET current_hash = ?1, updated_at = ?2 WHERE handle = ?3",
424 params![&record.hash, now, &canonical_uri],
425 )?;
426
427 tx.commit()?;
428 Ok(())
429 }
430
431 pub fn delete_file(&self, uri: &str) -> Result<()> {
433 self.retire(uri, None, AgentDid::parse(crate::layer0::vocabulary_identities::DID_CLM_AGENT_DEFAULT)?)
434 }
435}
436