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
27#[derive(Clone)]
29pub struct MCardFileSystem {
30 conn: Arc<Mutex<Connection>>,
31 context_prefix: String,
32}
33
34impl MCardFileSystem {
35 pub fn new_in_memory() -> Result<Self> {
37 let conn = Connection::open_in_memory()?;
38 Self::init_schema(&conn)?;
39 Ok(Self {
40 conn: Arc::new(Mutex::new(conn)),
41 context_prefix: String::new(),
42 })
43 }
44
45 pub fn new_in_memory_scoped(prefix: &str) -> Result<Self> {
47 let mut fs = Self::new_in_memory()?;
48 fs.context_prefix = prefix.trim_matches('/').to_string();
49 Ok(fs)
50 }
51
52 pub fn new(conn: Arc<Mutex<Connection>>, context_prefix: &str) -> Self {
54 Self {
55 conn,
56 context_prefix: context_prefix.trim_matches('/').to_string(),
57 }
58 }
59
60 pub fn with_connection(conn: Arc<Mutex<Connection>>) -> Result<Self> {
62 {
63 let locked = conn
64 .lock()
65 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
66 Self::init_schema(&locked)?;
67 }
68 Ok(Self {
69 conn,
70 context_prefix: String::new(),
71 })
72 }
73
74 pub fn with_prefix(&self, prefix: &str) -> Self {
76 Self {
77 conn: self.conn.clone(),
78 context_prefix: prefix.trim_matches('/').to_string(),
79 }
80 }
81
82 pub fn context_prefix(&self) -> &str {
84 &self.context_prefix
85 }
86
87 pub fn canonicalize_uri(&self, path: &str) -> String {
89 let clean = path.trim_start_matches('/');
90 if let Some(rest) = clean.strip_prefix("mcard:") {
91 let rest_clean = rest.trim_start_matches('/');
92 if self.context_prefix.is_empty() {
93 format!("mcard:{}", rest_clean)
94 } else if rest_clean.starts_with(&self.context_prefix) {
95 format!("mcard:{}", rest_clean)
96 } else {
97 format!("mcard:{}/{}", self.context_prefix, rest_clean)
98 }
99 } else if self.context_prefix.is_empty() {
100 format!("mcard:{}", clean)
101 } else {
102 format!("mcard:{}/{}", self.context_prefix, clean)
103 }
104 }
105
106 pub fn ephemeral_mount(&self, fiber: &crate::fiber::context::Fiber, prefix: &str) -> Result<Self> {
109 let scoped_fs = self.with_prefix(prefix);
110 let prefix_clean = prefix.trim_matches('/').to_string();
111 let handle_pattern = if prefix_clean.is_empty() {
112 "mcard:%".to_string()
113 } else {
114 format!("mcard:{}/%", prefix_clean)
115 };
116 let conn_clone = self.conn.clone();
117
118 fiber.register_disposable(move || {
119 let conn = conn_clone.lock().map_err(|e| e.to_string())?;
120 conn.execute(
121 "DELETE FROM handle_registry WHERE handle LIKE ?1",
122 rusqlite::params![&handle_pattern],
123 )
124 .map_err(|e| e.to_string())?;
125 Ok(())
126 });
127
128 Ok(scoped_fs)
129 }
130
131 fn init_schema(conn: &Connection) -> Result<()> {
133 conn.execute_batch(
134 r#"
135 CREATE TABLE IF NOT EXISTS card (
136 hash TEXT PRIMARY KEY,
137 content TEXT NOT NULL,
138 g_time TEXT
139 );
140
141 CREATE TABLE IF NOT EXISTS handle_registry (
142 handle TEXT PRIMARY KEY,
143 current_hash TEXT NOT NULL,
144 updated_at TEXT NOT NULL
145 );
146
147 CREATE TABLE IF NOT EXISTS handle_history (
148 handle TEXT NOT NULL,
149 previous_hash TEXT NOT NULL,
150 changed_at TEXT NOT NULL
151 );
152
153 CREATE INDEX IF NOT EXISTS idx_handle_reg_prefix ON handle_registry(handle);
154 "#,
155 )?;
156 Ok(())
157 }
158
159 pub fn write_file(&self, uri: &str, payload: MCardPayload, author: AgentDid) -> Result<MCard> {
161 let canonical_uri = self.canonicalize_uri(uri);
162 let now = crate::utils::now_iso8601();
163 let mut conn = self
164 .conn
165 .lock()
166 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
167
168 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
169
170 let existing: Option<String> = {
172 let mut stmt = tx.prepare_cached(
173 "SELECT current_hash FROM handle_registry WHERE handle = ?1",
174 )?;
175 stmt.query_row(params![&canonical_uri], |row| row.get(0))
176 .ok()
177 };
178
179 let seq = match &existing {
180 Some(_) => {
181 let mut count_stmt = tx.prepare_cached(
183 "SELECT count(*) FROM handle_history WHERE handle = ?1",
184 )?;
185 let count: i64 = count_stmt.query_row(params![&canonical_uri], |row| row.get(0))?;
186 (count as u64) + 2
187 }
188 None => 1,
189 };
190
191 let mcard = MCard::new(&canonical_uri, payload, author, seq);
199 let envelope = crate::layer0::codec::canonical_json(&mcard).map_err(|e| e.to_string())?;
200 let record = crate::layer0::mcard_record::MCardRecord::create(envelope.as_bytes(), None)
201 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))?;
202 let hash_str = record.hash.clone();
203
204 {
206 let mut stmt_card = tx.prepare_cached(
207 "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
208 )?;
209 stmt_card.execute(params![&record.hash, &record.content, &record.g_time])?;
210 }
211
212 if let Some(prev_hash) = existing.as_ref().filter(|prev| **prev != hash_str) {
214 let mut stmt_hist = tx.prepare_cached(
215 "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
216 )?;
217 stmt_hist.execute(params![&canonical_uri, prev_hash, now])?;
218 }
219
220 {
222 let mut stmt_reg = tx.prepare_cached(
223 "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) \
224 VALUES (?1, ?2, ?3)",
225 )?;
226 stmt_reg.execute(params![&canonical_uri, hash_str, now])?;
227 }
228
229 tx.commit()?;
230 Ok(mcard)
231 }
232
233 pub fn read_file(&self, uri: &str) -> Result<MCard> {
235 let canonical_uri = self.canonicalize_uri(uri);
236 let conn = self
237 .conn
238 .lock()
239 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
240
241 let current_hash: String = {
243 let mut stmt = conn.prepare_cached(
244 "SELECT current_hash FROM handle_registry WHERE handle = ?1",
245 )?;
246 stmt.query_row(params![&canonical_uri], |row| row.get(0)).map_err(|_| {
247 ClmError::storage(
248 StorageErrorCode::CardNotFound,
249 format!("Handle '{}' not found in MCardFs", canonical_uri),
250 )
251 })?
252 };
253
254 let (content, g_time): (Vec<u8>, String) = {
256 let mut stmt = conn.prepare_cached("SELECT content, g_time FROM card WHERE hash = ?1")?;
257 stmt.query_row(params![current_hash], |row| Ok((row.get(0)?, row.get(1)?)))
258 .map_err(|_| {
259 ClmError::storage(
260 StorageErrorCode::CorruptedContent,
261 format!("Card content for hash '{}' not found", current_hash),
262 )
263 })?
264 };
265
266 let record = crate::layer0::mcard_record::MCardRecord {
268 hash: current_hash.clone(),
269 content: content.clone(),
270 g_time: g_time.clone(),
271 };
272 if !matches!(
273 crate::layer0::mcard_record::verify_record(&record),
274 crate::layer0::mcard_record::RecordVerification::DeclaredOk { .. }
275 ) {
276 return Err(ClmError::storage(
277 StorageErrorCode::CorruptedContent,
278 format!("Cryptographic mismatch for handle '{}': stored row does not verify", canonical_uri),
279 ));
280 }
281
282 let mcard: MCard = serde_json::from_slice(&content)?;
283 Ok(mcard)
284 }
285
286 pub fn exists(&self, uri: &str) -> Result<bool> {
288 let canonical_uri = self.canonicalize_uri(uri);
289 let conn = self
290 .conn
291 .lock()
292 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
293 let mut stmt = conn.prepare_cached(
294 "SELECT count(*) FROM handle_registry WHERE handle = ?1",
295 )?;
296 let count: i64 = stmt.query_row(params![&canonical_uri], |row| row.get(0))?;
297 Ok(count > 0)
298 }
299
300 pub fn stat_file(&self, uri: &str) -> Result<MCardStat> {
302 let canonical_uri = self.canonicalize_uri(uri);
303 let conn = self
304 .conn
305 .lock()
306 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
307
308 let (hash_str, updated_at): (String, String) = {
309 let mut stmt = conn.prepare_cached(
310 "SELECT current_hash, updated_at FROM handle_registry WHERE handle = ?1",
311 )?;
312 stmt.query_row(params![&canonical_uri], |row| {
313 Ok((row.get(0)?, row.get(1)?))
314 })
315 .map_err(|_| {
316 ClmError::storage(
317 StorageErrorCode::CardNotFound,
318 format!("Handle '{}' not found", canonical_uri),
319 )
320 })?
321 };
322
323 let created_at: String = {
324 let mut stmt = conn.prepare_cached(
325 "SELECT changed_at FROM handle_history WHERE handle = ?1 ORDER BY rowid ASC LIMIT 1",
326 )?;
327 stmt.query_row(params![&canonical_uri], |row| row.get(0))
328 .unwrap_or_else(|_| updated_at.clone())
329 };
330
331 let size_bytes: usize = {
332 let mut stmt = conn.prepare_cached("SELECT length(content) FROM card WHERE hash = ?1")?;
333 stmt.query_row(params![hash_str], |row| row.get::<_, i64>(0))
334 .unwrap_or(0) as usize
335 };
336
337 let hash = {
340 let mut stmt = conn.prepare_cached("SELECT content FROM card WHERE hash = ?1")?;
341 let body: Vec<u8> = stmt.query_row(params![hash_str], |row| row.get(0)).unwrap_or_default();
342 match serde_json::from_slice::<MCard>(&body) {
343 Ok(envelope) => ContentHash::parse(&envelope.hash)?,
344 Err(_) => ContentHash::parse(&hash_str)?,
345 }
346 };
347 Ok(MCardStat {
348 uri: canonical_uri,
349 hash,
350 size_bytes,
351 created_at,
352 updated_at,
353 })
354 }
355
356 pub fn list_dir(&self, prefix: &str) -> Result<Vec<String>> {
358 let conn = self
359 .conn
360 .lock()
361 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
362
363 let canonical_prefix = self.canonicalize_uri(prefix);
364 let pattern = if canonical_prefix.ends_with('/') {
365 format!("{}%", canonical_prefix)
366 } else if canonical_prefix == "mcard:" {
367 "mcard:%".to_string()
368 } else {
369 format!("{}/%", canonical_prefix)
370 };
371
372 let mut stmt = conn.prepare_cached(
373 "SELECT handle FROM handle_registry WHERE handle LIKE ?1 ORDER BY handle ASC",
374 )?;
375 let rows = stmt.query_map(params![pattern], |row| row.get(0))?;
376
377 let mut handles = Vec::new();
378 for handle in rows {
379 handles.push(handle?);
380 }
381 Ok(handles)
382 }
383
384 pub fn delete_file(&self, uri: &str) -> Result<()> {
386 let canonical_uri = self.canonicalize_uri(uri);
387 let now = crate::utils::now_iso8601();
388 let mut conn = self
389 .conn
390 .lock()
391 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
392
393 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
394 {
395 let mut stmt_hist = tx.prepare_cached(
397 "INSERT INTO handle_history (handle, previous_hash, changed_at) \
398 SELECT handle, current_hash, ?1 FROM handle_registry WHERE handle = ?2",
399 )?;
400 stmt_hist.execute(params![now, &canonical_uri])?;
401
402 let mut stmt_del = tx.prepare_cached("DELETE FROM handle_registry WHERE handle = ?1")?;
404 let affected = stmt_del.execute(params![&canonical_uri])?;
405
406 if affected == 0 {
407 return Err(ClmError::storage(
408 StorageErrorCode::CardNotFound,
409 format!("Handle '{}' not found for deletion", canonical_uri),
410 ));
411 }
412 }
413 tx.commit()?;
414 Ok(())
415 }
416}