use crate::hash::{global_registry, strip_prefix};
pub fn content_equivalent(
conn: &rusqlite::Connection,
hash_a: &str,
hash_b: &str,
) -> Result<bool, String> {
if hash_a == hash_b {
return Ok(true);
}
let content_a = lookup_content(conn, hash_a);
let content_b = lookup_content(conn, hash_b);
match (content_a, content_b) {
(Some(a), Some(b)) => Ok(a == b),
_ => Ok(false),
}
}
#[cfg(feature = "native")]
pub(super) fn lookup_content(conn: &rusqlite::Connection, reference: &str) -> Option<Vec<u8>> {
let raw = strip_prefix(reference);
let mut candidates = vec![reference];
if raw != reference {
candidates.push(raw);
}
for candidate in candidates {
if let Ok(content) = conn.query_row(
"SELECT content FROM card WHERE hash = ?",
rusqlite::params![candidate],
|row| row.get::<_, Vec<u8>>(0),
) {
return Some(content);
}
}
None
}
#[cfg(feature = "native")]
pub fn migrate_handle_hash(
conn: &mut rusqlite::Connection,
handle: &str,
target_algo: &str,
) -> Result<String, String> {
{
let reg = global_registry().lock().unwrap();
if reg.get(target_algo).is_none() {
return Err(format!(
"Unsupported target algorithm: '{}' (registered: {:?})",
target_algo,
reg.algorithms()
));
}
}
let current_hash: String = conn
.query_row(
"SELECT current_hash FROM handle_registry WHERE handle = ?",
rusqlite::params![handle],
|row| row.get(0),
)
.map_err(|_| format!("Handle '{}' not found in handle_registry", handle))?;
let content: Vec<u8> = lookup_content(conn, ¤t_hash)
.ok_or_else(|| format!("Content not found in CAS for hash '{}'", current_hash))?;
let now_utc = chrono::Utc::now().to_rfc3339();
let record = crate::layer0::mcard_record::MCardRecord::create_at(
&content,
Some(target_algo),
Some(&now_utc),
"UTC",
)?;
if !matches!(
crate::layer0::mcard_record::verify_record(&record),
crate::layer0::mcard_record::RecordVerification::DeclaredOk { .. }
) {
return Err("hash migration produced an invalid self-verifying record".to_string());
}
let new_hash = format!("{}{}", target_algo.trim_end_matches(':').to_lowercase() + ":", record.hash);
let max_attempts = 3;
let mut last_err = String::new();
for attempt in 0..max_attempts {
let tx = match conn.transaction() {
Ok(tx) => tx,
Err(e) => {
last_err = e.to_string();
std::thread::sleep(std::time::Duration::from_millis(200));
continue;
}
};
let result = (|| {
tx.execute(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
rusqlite::params![&record.hash, &record.content, &record.g_time],
)
.map_err(|e| e.to_string())?;
tx.execute(
"INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?, ?, ?)",
rusqlite::params![handle, ¤t_hash, &now_utc],
)
.map_err(|e| e.to_string())?;
tx.execute(
"UPDATE handle_registry SET current_hash = ?, updated_at = ? WHERE handle = ?",
rusqlite::params![&new_hash, &now_utc, handle],
)
.map_err(|e| e.to_string())?;
tx.commit().map_err(|e| e.to_string())
})();
match result {
Ok(()) => return Ok(new_hash),
Err(e) => {
last_err = e;
if attempt + 1 < max_attempts {
std::thread::sleep(std::time::Duration::from_millis(200));
}
}
}
}
Err(format!("Transaction failed after {} attempts: {}", max_attempts, last_err))
}