use crate::error::{ClmError, Result, StorageErrorCode};
use crate::layer0::mcard_record::{verify_record, MCardRecord, RecordVerification};
pub use crate::mcard_fs::{MCardFileSystem, MCardStat};
pub use super::uri::{format_mcard_uri, parse_mcard_uri, validate_transclusion_chain, McardUri, McardUriKind};
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(crate::layer0::vocabulary::HASH_ALGORITHM_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": crate::layer0::vocabulary::HANDLE_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 mut stmt_sel = tx.prepare_cached(
"SELECT current_hash FROM handle_registry WHERE handle = ?1",
)?;
let existing: Option<String> = stmt_sel
.query_row(params![&canonical_uri], |row| row.get(0))
.ok();
let mut stmt_card = tx.prepare_cached(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
)?;
stmt_card.execute(params![&record.hash, &record.content, &record.g_time])?;
if let Some(prev) = existing.as_ref().filter(|p| **p != record.hash) {
let mut stmt_hist = tx.prepare_cached(
"INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
)?;
stmt_hist.execute(params![&canonical_uri, prev, &now])?;
}
let mut stmt_reg = tx.prepare_cached(
"INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
)?;
stmt_reg.execute(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 = {
let mut stmt_reg = conn.prepare_cached(
"SELECT current_hash FROM handle_registry WHERE handle = ?1",
)?;
stmt_reg
.query_row(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) = {
let mut stmt_card = conn.prepare_cached(
"SELECT content, g_time FROM card WHERE hash = ?1",
)?;
stmt_card
.query_row(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,
g_time,
};
if !matches!(verify_record(&rec), RecordVerification::DeclaredOk { .. }) {
return Err(ClmError::storage(
StorageErrorCode::CorruptedContent,
format!("Cryptographic verification failed for '{canonical_uri}'"),
));
}
Ok(rec.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> = {
let mut stmt_sel = tx.prepare_cached(
"SELECT current_hash FROM handle_registry WHERE handle = ?1",
)?;
stmt_sel.query_row(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(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3)) {
if let Ok(mut stmt_card) = tx.prepare_cached(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
) {
let _ = stmt_card.execute(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) {
let mut stmt_hist = tx.prepare_cached(
"INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
)?;
stmt_hist.execute(params![&canonical_uri, prev, &now])?;
}
let mut stmt_reg = tx.prepare_cached(
"INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
)?;
stmt_reg.execute(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(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3))
}
}
pub use crate::layer2::uri::*;