1use crate::error::{ClmError, Result, StorageErrorCode};
5use crate::layer0::mcard_record::MCardRecord;
6pub use crate::mcard_fs::{MCardFileSystem, MCardStat};
7pub use super::uri::{format_mcard_uri, parse_mcard_uri, validate_transclusion_chain, McardUri, McardUriKind};
8use rusqlite::params;
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct DirectoryManifestEntry {
14 pub name: String,
15 pub kind: String,
16 pub target_ref: String,
17 #[serde(default)]
18 pub metadata_ref: Option<String>,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct DirectoryManifest {
27 pub entries: Vec<DirectoryManifestEntry>,
28 pub algorithm: String,
29}
30
31impl DirectoryManifest {
32 pub fn new(entries: Vec<DirectoryManifestEntry>, algorithm: Option<&str>) -> Self {
33 Self {
34 entries,
35 algorithm: algorithm.unwrap_or(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3).to_string(),
36 }
37 }
38
39 pub fn sorted_entries(&self) -> Vec<DirectoryManifestEntry> {
41 let mut sorted = self.entries.clone();
42 sorted.sort_by(|a, b| {
43 (&a.name, &a.kind, &a.target_ref, a.metadata_ref.as_deref().unwrap_or(""))
44 .cmp(&(&b.name, &b.kind, &b.target_ref, b.metadata_ref.as_deref().unwrap_or("")))
45 });
46 sorted
47 }
48
49 pub fn to_canonical_bytes(&self) -> Vec<u8> {
51 let entries_json: Vec<serde_json::Value> = self
52 .sorted_entries()
53 .into_iter()
54 .map(|e| {
55 serde_json::json!({
56 "kind": e.kind,
57 "metadata_ref": e.metadata_ref,
58 "name": e.name,
59 "target_ref": e.target_ref,
60 })
61 })
62 .collect();
63 let doc = serde_json::json!({
64 "entries": entries_json,
65 "schema": crate::layer0::vocabulary::HANDLE_CLM_LAYER2_DIRECTORY_MANIFEST_V1,
66 });
67 crate::domain::to_canonical_json_bytes(&doc)
68 }
69
70 pub fn to_mcard_record(&self) -> Result<MCardRecord> {
72 MCardRecord::create(&self.to_canonical_bytes(), Some(&self.algorithm))
73 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))
74 }
75
76 pub fn qualified_ref(&self) -> Result<String> {
78 let rec = self.to_mcard_record()?;
79 Ok(format!("{}:{}", self.algorithm, rec.hash))
80 }
81
82 pub fn from_canonical_bytes(raw: &[u8], algorithm: Option<&str>) -> Result<Self> {
84 let val: serde_json::Value = serde_json::from_slice(raw)?;
85 let entries_arr = val
86 .get("entries")
87 .and_then(|v| v.as_array())
88 .ok_or_else(|| {
89 ClmError::storage(
90 StorageErrorCode::CorruptedContent,
91 "Invalid DirectoryManifest entries".to_string(),
92 )
93 })?;
94 let mut entries = Vec::with_capacity(entries_arr.len());
95 for item in entries_arr {
96 entries.push(DirectoryManifestEntry {
97 name: item.get("name").and_then(|v| v.as_str()).unwrap_or_default().to_string(),
98 kind: item.get("kind").and_then(|v| v.as_str()).unwrap_or("file").to_string(),
99 target_ref: item.get("target_ref").and_then(|v| v.as_str()).unwrap_or_default().to_string(),
100 metadata_ref: item.get("metadata_ref").and_then(|v| v.as_str()).map(|s| s.to_string()),
101 });
102 }
103 Ok(Self::new(entries, algorithm))
104 }
105}
106
107impl MCardFileSystem {
108 pub fn write_raw_bytes(
110 &self,
111 uri: &str,
112 content: &[u8],
113 algorithm: Option<&str>,
114 ) -> Result<MCardRecord> {
115 let canonical_uri = self.canonicalize_uri(uri);
116 let now = crate::utils::now_iso8601();
117 let record = MCardRecord::create(content, algorithm)
118 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e))?;
119 let mut conn = self
120 .conn
121 .lock()
122 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
123 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
124 {
125 let mut stmt_sel = tx.prepare_cached(
126 "SELECT current_hash FROM handle_registry WHERE handle = ?1",
127 )?;
128 let existing: Option<String> = stmt_sel
129 .query_row(params![&canonical_uri], |row| row.get(0))
130 .ok();
131 crate::layer2::record_store::insert_record(&tx, &record)?;
132 if let Some(prev) = existing.as_ref().filter(|p| **p != record.hash) {
133 let mut stmt_hist = tx.prepare_cached(
134 "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
135 )?;
136 stmt_hist.execute(params![&canonical_uri, prev, &now])?;
137 }
138 let mut stmt_reg = tx.prepare_cached(
139 "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
140 )?;
141 stmt_reg.execute(params![&canonical_uri, &record.hash, &now])?;
142 }
143 tx.commit()?;
144 Ok(record)
145 }
146
147 pub fn read_raw_bytes(&self, uri: &str) -> Result<Vec<u8>> {
149 let canonical_uri = self.canonicalize_uri(uri);
150 let conn = self
151 .conn
152 .lock()
153 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
154 let current_hash: String = {
155 let mut stmt_reg = conn.prepare_cached(
156 "SELECT current_hash FROM handle_registry WHERE handle = ?1",
157 )?;
158 stmt_reg
159 .query_row(params![&canonical_uri], |row| row.get(0))
160 .map_err(|_| {
161 ClmError::storage(
162 StorageErrorCode::CardNotFound,
163 format!("Handle '{canonical_uri}' not found"),
164 )
165 })?
166 };
167 let record = crate::layer2::record_store::read_record(&conn, ¤t_hash)?
168 .ok_or_else(|| ClmError::storage(StorageErrorCode::CardNotFound, "stored card is missing"))?;
169 Ok(record.content)
170 }
171
172 pub fn bind(&self, uri: &str, new_ref: &str, expected_old_ref: Option<&str>) -> Result<bool> {
175 let canonical_uri = self.canonicalize_uri(uri);
176 let new_hash = new_ref.split_once(':').map(|(_, h)| h).unwrap_or(new_ref);
177 let expected_hash =
178 expected_old_ref.map(|r| r.split_once(':').map(|(_, h)| h).unwrap_or(r));
179 let now = crate::utils::now_iso8601();
180
181 let mut conn = self
182 .conn
183 .lock()
184 .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
185 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
186 crate::layer2::record_store::read_record(&tx, new_ref)?
187 .ok_or_else(|| ClmError::storage(StorageErrorCode::CardNotFound, "new card is missing"))?;
188 if let Some(expected) = expected_old_ref {
189 crate::layer2::record_store::read_record(&tx, expected)?;
190 }
191 let actual_hash: Option<String> = {
192 let mut stmt_sel = tx.prepare_cached(
193 "SELECT current_hash FROM handle_registry WHERE handle = ?1",
194 )?;
195 stmt_sel.query_row(params![&canonical_uri], |row| row.get(0)).ok()
196 };
197
198 if actual_hash.as_deref() != expected_hash {
199 let exc_json = serde_json::json!({
200 "actual_old_ref": actual_hash,
201 "expected_old_ref": expected_hash,
202 "handle": canonical_uri,
203 "kind": "storage_cas_conflict",
204 "requested_new_ref": new_hash,
205 });
206 let exc_bytes = crate::domain::to_canonical_json_bytes(&exc_json);
207 if let Ok(exc_rec) = MCardRecord::create(&exc_bytes, Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3)) {
208 crate::layer2::record_store::insert_record(&tx, &exc_rec)?;
209 }
210 tx.commit()?;
211 return Ok(false);
212 }
213
214 {
215 if let Some(prev) = actual_hash.as_ref().filter(|p| p.as_str() != new_hash) {
216 let mut stmt_hist = tx.prepare_cached(
217 "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
218 )?;
219 stmt_hist.execute(params![&canonical_uri, prev, &now])?;
220 }
221 let mut stmt_reg = tx.prepare_cached(
222 "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
223 )?;
224 stmt_reg.execute(params![&canonical_uri, new_hash, &now])?;
225 }
226 tx.commit()?;
227 Ok(true)
228 }
229
230 pub fn write_directory_manifest(
232 &self,
233 dir_uri: &str,
234 manifest: &DirectoryManifest,
235 ) -> Result<MCardRecord> {
236 self.write_raw_bytes(
237 dir_uri,
238 &manifest.to_canonical_bytes(),
239 Some(&manifest.algorithm),
240 )
241 }
242
243 pub fn read_directory_manifest(&self, dir_uri: &str) -> Result<DirectoryManifest> {
245 let raw = self.read_raw_bytes(dir_uri)?;
246 DirectoryManifest::from_canonical_bytes(&raw, Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3))
247 }
248}
249
250pub use crate::layer2::uri::*;