use crate::error::{ClmError, Result, StorageErrorCode};
use crate::layer0::mcard_record::{verify_record, MCardRecord, RecordVerification};
pub use crate::mcard_fs::{MCardFileSystem, MCardStat};
use rusqlite::params;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DirectoryManifestEntry {
pub name: String,
pub kind: String,
pub target_ref: String,
#[serde(default)]
pub metadata_ref: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DirectoryManifest {
pub entries: Vec<DirectoryManifestEntry>,
pub algorithm: String,
}
impl DirectoryManifest {
pub fn new(entries: Vec<DirectoryManifestEntry>, algorithm: Option<&str>) -> Self {
Self {
entries,
algorithm: algorithm.unwrap_or("blake3").to_string(),
}
}
pub fn sorted_entries(&self) -> Vec<DirectoryManifestEntry> {
let mut sorted = self.entries.clone();
sorted.sort_by(|a, b| {
(&a.name, &a.kind, &a.target_ref, a.metadata_ref.as_deref().unwrap_or(""))
.cmp(&(&b.name, &b.kind, &b.target_ref, b.metadata_ref.as_deref().unwrap_or("")))
});
sorted
}
pub fn to_canonical_bytes(&self) -> Vec<u8> {
let entries_json: Vec<serde_json::Value> = self
.sorted_entries()
.into_iter()
.map(|e| {
serde_json::json!({
"kind": e.kind,
"metadata_ref": e.metadata_ref,
"name": e.name,
"target_ref": e.target_ref,
})
})
.collect();
let doc = serde_json::json!({
"entries": entries_json,
"schema": "clm://layer2/directory_manifest/v1",
});
crate::domain::to_canonical_json_bytes(&doc)
}
pub fn to_mcard_record(&self) -> Result<MCardRecord> {
MCardRecord::create(&self.to_canonical_bytes(), Some(&self.algorithm))
.map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))
}
pub fn qualified_ref(&self) -> Result<String> {
let rec = self.to_mcard_record()?;
Ok(format!("{}:{}", self.algorithm, rec.hash))
}
pub fn from_canonical_bytes(raw: &[u8], algorithm: Option<&str>) -> Result<Self> {
let val: serde_json::Value = serde_json::from_slice(raw)?;
let entries_arr = val
.get("entries")
.and_then(|v| v.as_array())
.ok_or_else(|| {
ClmError::storage(
StorageErrorCode::CorruptedContent,
"Invalid DirectoryManifest entries".to_string(),
)
})?;
let mut entries = Vec::with_capacity(entries_arr.len());
for item in entries_arr {
entries.push(DirectoryManifestEntry {
name: item
.get("name")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
kind: item
.get("kind")
.and_then(|v| v.as_str())
.unwrap_or("file")
.to_string(),
target_ref: item
.get("target_ref")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
metadata_ref: item
.get("metadata_ref")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
});
}
Ok(Self::new(entries, algorithm))
}
}
impl MCardFileSystem {
pub fn write_raw_bytes(
&self,
uri: &str,
content: &[u8],
algorithm: Option<&str>,
) -> Result<MCardRecord> {
let canonical_uri = self.canonicalize_uri(uri);
let now = crate::utils::now_iso8601();
let record = MCardRecord::create(content, algorithm)
.map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))?;
let mut conn = self
.conn
.lock()
.map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
let existing: Option<String> = tx
.query_row(
"SELECT current_hash FROM handle_registry WHERE handle = ?1",
params![&canonical_uri],
|row| row.get(0),
)
.ok();
tx.execute(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
params![&record.hash, &record.content, &record.g_time],
)?;
if let Some(prev) = existing.as_ref().filter(|p| **p != record.hash) {
tx.execute(
"INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
params![&canonical_uri, prev, &now],
)?;
}
tx.execute(
"INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
params![&canonical_uri, &record.hash, &now],
)?;
tx.commit()?;
Ok(record)
}
pub fn read_raw_bytes(&self, uri: &str) -> Result<Vec<u8>> {
let canonical_uri = self.canonicalize_uri(uri);
let conn = self
.conn
.lock()
.map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
let current_hash: String = conn
.query_row(
"SELECT current_hash FROM handle_registry WHERE handle = ?1",
params![&canonical_uri],
|row| row.get(0),
)
.map_err(|_| {
ClmError::storage(
StorageErrorCode::CardNotFound,
format!("Handle '{canonical_uri}' not found"),
)
})?;
let (content, g_time): (Vec<u8>, String) = conn
.query_row(
"SELECT content, g_time FROM card WHERE hash = ?1",
params![¤t_hash],
|row| Ok((row.get(0)?, row.get(1)?)),
)
.map_err(|_| {
ClmError::storage(
StorageErrorCode::CorruptedContent,
format!("Card '{current_hash}' missing"),
)
})?;
let rec = MCardRecord {
hash: current_hash,
content: content.clone(),
g_time,
};
if !matches!(verify_record(&rec), RecordVerification::DeclaredOk { .. }) {
return Err(ClmError::storage(
StorageErrorCode::CorruptedContent,
format!("Cryptographic verification failed for '{canonical_uri}'"),
));
}
Ok(content)
}
pub fn bind(&self, uri: &str, new_ref: &str, expected_old_ref: Option<&str>) -> Result<bool> {
let canonical_uri = self.canonicalize_uri(uri);
let new_hash = new_ref.split_once(':').map(|(_, h)| h).unwrap_or(new_ref);
let expected_hash =
expected_old_ref.map(|r| r.split_once(':').map(|(_, h)| h).unwrap_or(r));
let now = crate::utils::now_iso8601();
let mut conn = self
.conn
.lock()
.map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
let actual_hash: Option<String> = tx
.query_row(
"SELECT current_hash FROM handle_registry WHERE handle = ?1",
params![&canonical_uri],
|row| row.get(0),
)
.ok();
if actual_hash.as_deref() != expected_hash {
let exc_json = serde_json::json!({
"actual_old_ref": actual_hash,
"expected_old_ref": expected_hash,
"handle": canonical_uri,
"kind": "storage_cas_conflict",
"requested_new_ref": new_hash,
});
let exc_bytes = crate::domain::to_canonical_json_bytes(&exc_json);
if let Ok(exc_rec) = MCardRecord::create(&exc_bytes, Some("blake3")) {
let _ = tx.execute(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
params![&exc_rec.hash, &exc_rec.content, &exc_rec.g_time],
);
}
tx.commit()?;
return Ok(false);
}
if let Some(prev) = actual_hash.as_ref().filter(|p| p.as_str() != new_hash) {
tx.execute(
"INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
params![&canonical_uri, prev, &now],
)?;
}
tx.execute(
"INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
params![&canonical_uri, new_hash, &now],
)?;
tx.commit()?;
Ok(true)
}
pub fn write_directory_manifest(
&self,
dir_uri: &str,
manifest: &DirectoryManifest,
) -> Result<MCardRecord> {
self.write_raw_bytes(
dir_uri,
&manifest.to_canonical_bytes(),
Some(&manifest.algorithm),
)
}
pub fn read_directory_manifest(&self, dir_uri: &str) -> Result<DirectoryManifest> {
let raw = self.read_raw_bytes(dir_uri)?;
DirectoryManifest::from_canonical_bytes(&raw, Some("blake3"))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum McardUriType {
Hash,
Handle,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParsedMcardUri {
pub uri_type: McardUriType,
pub target: String,
pub fragment: Option<String>,
pub original: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransclusionCycleError {
pub cycle_path: Vec<String>,
}
impl std::fmt::Display for TransclusionCycleError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Transclusion cycle detected: {}", self.cycle_path.join(" -> "))
}
}
impl std::error::Error for TransclusionCycleError {}
pub fn canonicalize_mcard_uri(path: &str, context_prefix: &str) -> String {
let clean = path.trim_start_matches('/');
let mut prefix = context_prefix.trim_matches('/');
if prefix == "mcard" {
prefix = "";
}
if let Some(rest) = clean.strip_prefix("mcard:") {
let rest = rest.trim_start_matches('/');
if prefix.is_empty() || rest == prefix || rest.starts_with(&format!("{prefix}/")) {
return format!("mcard:{rest}");
}
return format!("mcard:{prefix}/{rest}");
}
if prefix.is_empty() {
format!("mcard:{clean}")
} else {
format!("mcard:{prefix}/{clean}")
}
}
fn is_qualified_hash(value: &str) -> bool {
let Some((algo, hex)) = value.split_once(':') else {
return false;
};
matches!(algo, "blake3" | "sha256" | "sha512" | "sha3-256" | "sha1" | "md5")
&& (32..=128).contains(&hex.len())
&& hex.chars().all(|c| c.is_ascii_hexdigit())
}
pub fn format_mcard_uri(parsed: &ParsedMcardUri) -> String {
let frag = parsed
.fragment
.as_ref()
.map(|f| format!("#{}", f.trim_start_matches('#')))
.unwrap_or_default();
let kind = match parsed.uri_type {
McardUriType::Hash => "hash",
McardUriType::Handle => "handle",
};
format!("mcard://{kind}/{}{frag}", parsed.target)
}
pub fn parse_mcard_uri(uri: &str) -> std::result::Result<ParsedMcardUri, String> {
if uri.is_empty() {
return Err("Invalid MCard URI: expected non-empty string".to_string());
}
let (base, fragment) = match uri.split_once('#') {
Some((base, frag)) => (base, Some(frag.to_string())),
None => (uri, None),
};
if let Some(target) = base.strip_prefix("mcard://hash/") {
let target = target.trim_end_matches('/');
if !target.contains(':') {
return Err(format!("Malformed hash URI: expected '<algorithm>:<hex>', got '{target}'"));
}
return Ok(ParsedMcardUri {
uri_type: McardUriType::Hash,
target: target.to_string(),
fragment,
original: uri.to_string(),
});
}
if let Some(rest) = base.strip_prefix("mcard://handle/") {
let raw = rest.split('?').next().unwrap_or(rest).trim_end_matches('/');
return Ok(ParsedMcardUri {
uri_type: McardUriType::Handle,
target: canonicalize_mcard_uri(raw, ""),
fragment,
original: uri.to_string(),
});
}
if base.starts_with("mcard://receipts/") || base.starts_with("mcard://schemas/") {
let raw = base.trim_start_matches("mcard://").trim_end_matches('/');
return Ok(ParsedMcardUri {
uri_type: McardUriType::Handle,
target: canonicalize_mcard_uri(raw, ""),
fragment,
original: uri.to_string(),
});
}
if let Some(raw) = base.strip_prefix("mcard://") {
let raw = raw.trim_end_matches('/');
if is_qualified_hash(raw) {
return Ok(ParsedMcardUri {
uri_type: McardUriType::Hash,
target: raw.to_lowercase(),
fragment,
original: uri.to_string(),
});
}
return Ok(ParsedMcardUri {
uri_type: McardUriType::Handle,
target: canonicalize_mcard_uri(raw, ""),
fragment,
original: uri.to_string(),
});
}
Ok(ParsedMcardUri {
uri_type: McardUriType::Handle,
target: canonicalize_mcard_uri(base, ""),
fragment,
original: uri.to_string(),
})
}
pub fn validate_transclusion_chain(chain: &[String], next_ref: &str) -> std::result::Result<(), TransclusionCycleError> {
let next = next_ref.to_lowercase();
if chain.iter().any(|ref_| ref_.to_lowercase() == next) {
let mut cycle_path = chain.to_vec();
cycle_path.push(next_ref.to_string());
return Err(TransclusionCycleError { cycle_path });
}
Ok(())
}