use crate::error::{ClmError, Result, StorageErrorCode};
use crate::layer0::mcard_record::MCardRecord;
use rusqlite::{params, Connection, OptionalExtension};
pub use crate::layer0::record_port::require_verified;
pub fn read_record(conn: &Connection, reference: &str) -> Result<Option<MCardRecord>> {
let digest = reference.split_once(':').map_or(reference, |(_, hash)| hash);
let record = conn.query_row(
"SELECT hash, content, g_time FROM card WHERE hash = ?1 OR hash = ?2 ORDER BY CASE WHEN hash = ?1 THEN 0 ELSE 1 END LIMIT 1",
params![reference, digest],
|row| {
let content = match row.get_ref(1)? {
rusqlite::types::ValueRef::Text(bytes) | rusqlite::types::ValueRef::Blob(bytes) => bytes.to_vec(),
value => return Err(rusqlite::Error::InvalidColumnType(1, "content".into(), value.data_type())),
};
Ok(MCardRecord { hash: row.get(0)?, content, g_time: row.get(2)? })
},
).optional()?;
if let Some(record) = &record {
let algorithm = require_verified(record)?;
if let Some((prefix, _)) = reference.split_once(':') {
if crate::layer0::gtime::canonical_algorithm_name(prefix) != algorithm {
return Err(ClmError::storage(StorageErrorCode::CorruptedContent,
"reference algorithm conflicts with stored g_time"));
}
}
}
Ok(record)
}
pub fn insert_record(conn: &Connection, record: &MCardRecord) -> Result<bool> {
let algorithm = require_verified(record)?;
conn.execute_batch("SAVEPOINT clm_record_write")?;
let result = (|| {
let inserted = conn.execute(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
params![record.hash, record.content, record.g_time],
)? > 0;
let stored = read_record(conn, &record.hash)?.ok_or_else(|| ClmError::storage(
StorageErrorCode::CorruptedContent, "inserted card is missing"))?;
if stored.content != record.content || require_verified(&stored)? != algorithm {
return Err(ClmError::storage(StorageErrorCode::CorruptedContent,
"existing card conflicts with incoming content identity"));
}
Ok(inserted)
})();
match result {
Ok(inserted) => { conn.execute_batch("RELEASE clm_record_write")?; Ok(inserted) }
Err(error) => {
conn.execute_batch("ROLLBACK TO clm_record_write; RELEASE clm_record_write")?;
Err(error)
}
}
}
pub fn read_text(conn: &Connection, reference: &str) -> Result<Option<String>> {
read_record(conn, reference)?.map(|record| String::from_utf8(record.content)
.map_err(|error| ClmError::storage(StorageErrorCode::CorruptedContent,
format!("binary record cannot be materialized as UTF-8: {error}")))).transpose()
}
pub fn insert_new_content(conn: &Connection, claimed_hash: &str, content: &[u8], algorithm: &str) -> Result<bool> {
let record = MCardRecord {
hash: claimed_hash.to_string(), content: content.to_vec(),
g_time: crate::layer0::gtime::stamp_g_time(algorithm, None, None, None),
};
insert_record(conn, &record)
}
pub fn read_handle_record(conn: &Connection, handle: &str) -> Result<Option<MCardRecord>> {
let hash: Option<String> = conn.query_row("SELECT current_hash FROM handle_registry WHERE handle = ?1",
[handle], |row| row.get(0)).optional()?;
match hash {
Some(hash) => read_record(conn, &hash)?.map(Some).ok_or_else(||
ClmError::storage(StorageErrorCode::CorruptedContent, "handle points to missing card")),
None => Ok(None),
}
}
pub fn read_handle_text(conn: &Connection, handle: &str) -> Result<Option<String>> {
read_handle_record(conn, handle)?.map(|record| String::from_utf8(record.content)
.map_err(|error| ClmError::storage(StorageErrorCode::CorruptedContent, error.to_string()))).transpose()
}
pub fn store_named_content(conn: &Connection, handle: &str, content: &[u8]) -> std::result::Result<MCardRecord, String> {
let record = MCardRecord::create(content, None)?;
conn.execute_batch("SAVEPOINT clm_named_content").map_err(|e| e.to_string())?;
let result = (|| {
insert_record(conn, &record).map_err(|e| e.to_string())?;
crate::tape::register_handle(conn, handle, &record.hash, &record.g_time)?;
Ok(record)
})();
match result {
Ok(record) => { conn.execute_batch("RELEASE clm_named_content").map_err(|e| e.to_string())?; Ok(record) }
Err(error) => {
conn.execute_batch("ROLLBACK TO clm_named_content; RELEASE clm_named_content").map_err(|e| e.to_string())?;
Err(error)
}
}
}
impl crate::layer0::record_port::RecordStorePort for Connection {
fn read_record(&self, reference: &str) -> Result<Option<MCardRecord>> {
read_record(self, reference)
}
fn read_text(&self, reference: &str) -> Result<Option<String>> {
read_text(self, reference)
}
fn insert_record(&self, record: &MCardRecord) -> Result<bool> {
insert_record(self, record)
}
fn store_named_content(&self, handle: &str, content: &[u8]) -> std::result::Result<MCardRecord, String> {
store_named_content(self, handle, content)
}
}
pub fn mcard_cache_prepopulate(clm_root: &str) -> crate::error::Result<()> {
let conn = crate::db::get_connection(crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY, clm_root)?;
let mut stmt = conn
.prepare("SELECT handle, current_hash FROM handle_registry")?;
let rows = stmt
.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})?;
for row in rows {
let (handle, current_hash) = row?;
let record = crate::layer2::record_store::read_record(&conn, ¤t_hash)?
.ok_or_else(|| crate::error::ClmError::Evaluation("cached handle target is missing".into()))?;
crate::cache::setter_mcard_cache(&record)?;
crate::cache::setter_mcard_cache_handle(&handle, ¤t_hash);
}
Ok(())
}