#![allow(unused_imports)]
use super::*;
pub fn handle_register_batch(
pillar: &str,
clm_root: &str,
handle: &str,
hash_val: &str,
content: &str,
) -> Result<()> {
let now = crate::utils::now_iso8601();
#[cfg(any(feature = "native", feature = "db"))]
let created_at_opt = {
if let Ok(writer_arc) = get_writer_connection(pillar, clm_root) {
let mut conn = writer_arc
.lock()
.map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
{
let mut stmt_card = tx.prepare_cached(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
)?;
stmt_card.execute(params![hash_val, content, now])?;
let mut stmt_hist = tx.prepare_cached(
"INSERT INTO handle_history (handle, previous_hash, changed_at) \
SELECT hr.handle, hr.current_hash, ?1 FROM handle_registry hr \
JOIN card c ON c.hash = hr.current_hash \
WHERE hr.handle = ?2 AND hr.current_hash != ?3",
)?;
stmt_hist.execute(params![now, handle, hash_val])?;
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![handle, hash_val, now])?;
}
let created_at: String = tx
.query_row(
"SELECT MIN(changed_at) FROM handle_history WHERE handle = ?1",
params![handle],
|row| row.get(0),
)
.unwrap_or_else(|_| now.clone());
tx.commit()?;
Some(created_at)
} else {
None
}
};
#[cfg(not(any(feature = "native", feature = "db")))]
let created_at_opt: Option<String> = None;
let _created_at = if let Some(ca) = created_at_opt {
ca
} else {
let mut conn = get_connection(pillar, clm_root)?;
let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
{
let mut stmt_card = tx.prepare_cached(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
)?;
stmt_card.execute(params![hash_val, content, now])?;
let mut stmt_hist = tx.prepare_cached(
"INSERT INTO handle_history (handle, previous_hash, changed_at) \
SELECT hr.handle, hr.current_hash, ?1 FROM handle_registry hr \
JOIN card c ON c.hash = hr.current_hash \
WHERE hr.handle = ?2 AND hr.current_hash != ?3",
)?;
stmt_hist.execute(params![now, handle, hash_val])?;
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![handle, hash_val, now])?;
}
let created_at: String = tx
.query_row(
"SELECT MIN(changed_at) FROM handle_history WHERE handle = ?1",
params![handle],
|row| row.get(0),
)
.unwrap_or_else(|_| now.clone());
tx.commit()?;
created_at
};
if is_membroker_backend() {
let esc_hash = hash_val.replace('\'', "''");
let esc_content = content.replace('\'', "''");
let esc_handle = handle.replace('\'', "''");
let esc_now = now.replace('\'', "''");
membroker_sync(pillar, &format!(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES ('{}', '{}', '{}')",
esc_hash, esc_content, esc_now
));
membroker_sync(pillar, &format!(
"INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES ('{}', '{}', '{}')",
esc_handle, esc_hash, esc_now
));
}
Ok(())
}
pub fn handle_delete_batch(pillar: &str, clm_root: &str, handle: &str) -> Result<()> {
let now = crate::utils::now_iso8601();
#[cfg(any(feature = "native", feature = "db"))]
{
if let Ok(writer_arc) = get_writer_connection(pillar, clm_root) {
let mut conn = writer_arc
.lock()
.map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
{
let mut stmt_hist = tx.prepare_cached(
"INSERT INTO handle_history (handle, previous_hash, changed_at) \
SELECT hr.handle, hr.current_hash, ?1 FROM handle_registry hr \
JOIN card c ON c.hash = hr.current_hash \
WHERE hr.handle = ?2",
)?;
stmt_hist.execute(params![now, handle])?;
let mut stmt_del_hist = tx.prepare_cached("DELETE FROM handle_history WHERE handle = ?1")?;
stmt_del_hist.execute(params![handle])?;
let mut stmt_del = tx.prepare_cached("DELETE FROM handle_registry WHERE handle = ?1")?;
stmt_del.execute(params![handle])?;
}
tx.commit()?;
return Ok(());
}
}
let mut conn = get_connection(pillar, clm_root)?;
let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
{
let mut stmt_hist = tx.prepare_cached(
"INSERT INTO handle_history (handle, previous_hash, changed_at) \
SELECT hr.handle, hr.current_hash, ?1 FROM handle_registry hr \
JOIN card c ON c.hash = hr.current_hash \
WHERE hr.handle = ?2",
)?;
stmt_hist.execute(params![now, handle])?;
let mut stmt_del_hist = tx.prepare_cached("DELETE FROM handle_history WHERE handle = ?1")?;
stmt_del_hist.execute(params![handle])?;
let mut stmt_del = tx.prepare_cached("DELETE FROM handle_registry WHERE handle = ?1")?;
stmt_del.execute(params![handle])?;
}
tx.commit()?;
Ok(())
}
pub fn resolve_handle_hash(pillar: &str, clm_root: &str, handle: &str) -> Result<Option<String>> {
#[cfg(any(feature = "native", feature = "db"))]
{
if let Ok(reader) = get_reader_connection(pillar, clm_root) {
return resolve_handle_hash_cached(&reader, handle);
}
}
let conn = get_connection(pillar, clm_root)?;
resolve_handle_hash_cached(&conn, handle)
}
pub fn resolve_handle_content(
pillar: &str,
clm_root: &str,
handle: &str,
) -> Result<Option<String>> {
#[cfg(any(feature = "native", feature = "db"))]
{
if let Ok(reader) = get_reader_connection(pillar, clm_root) {
return resolve_handle_content_cached(&reader, handle);
}
}
let conn = get_connection(pillar, clm_root)?;
resolve_handle_content_cached(&conn, handle)
}
pub fn card_exists(pillar: &str, clm_root: &str, hash: &str) -> Result<bool> {
#[cfg(any(feature = "native", feature = "db"))]
{
if let Ok(reader) = get_reader_connection(pillar, clm_root) {
return card_exists_cached(&reader, hash);
}
}
let conn = get_connection(pillar, clm_root)?;
card_exists_cached(&conn, hash)
}
pub fn setter_card_batch(
pillar: &str,
clm_root: &str,
hash: &str,
content: &str,
g_time: &str,
) -> Result<()> {
#[cfg(any(feature = "native", feature = "db"))]
{
if let Ok(writer_arc) = get_writer_connection(pillar, clm_root) {
let conn = writer_arc
.lock()
.map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
let mut stmt = conn.prepare_cached(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
)?;
stmt.execute(params![hash, content, g_time])?;
return Ok(());
}
}
let conn = get_connection(pillar, clm_root)?;
let mut stmt = conn.prepare_cached(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
)?;
stmt.execute(params![hash, content, g_time])?;
Ok(())
}
pub fn emit_exec_mcard(
operation: &str,
content_hash: &str,
extra_yaml: &str,
a_hash: &str,
c_hash: &str,
clm_root: &str,
) -> Result<String> {
let is_sandbox = TEST_SANDBOX_ACTIVE.with(|active| active.get());
let zero_fs = is_sandbox || env::var("CLM_ZERO_FS").unwrap_or_default() == "true";
let data_root = Path::new(clm_root).join("data");
let mcard_dir = if zero_fs {
let tmp_dir = env::var("TMPDIR").unwrap_or_else(|_| "/tmp".to_string());
Path::new(&tmp_dir).join("data").join("execution_logs")
} else {
data_root.join("execution_logs")
};
if !zero_fs {
let _ = fs::create_dir_all(&mcard_dir);
}
let now = chrono::Local::now();
let g_time = now.format("%Y-%m-%dT%H:%M:%S%z").to_string();
let unix_ts = now.timestamp();
let short_hash = if content_hash.len() >= 8 {
&content_hash[0..8]
} else {
content_hash
};
let mcard_file = mcard_dir.join(format!("exec_{}_{}.yaml", unix_ts, short_hash));
let mut mcard_content = format!(
"mcard:\n g_time: \"{}\"\n content_hash: \"{}\"\n operation: \"{}\"\n agent_did: \"{}\"\n",
g_time, content_hash, operation, env::var("ACTIVE_AGENT_DID").unwrap_or_default()
);
if !extra_yaml.is_empty() {
for line in extra_yaml.lines() {
mcard_content.push_str(&format!(" {}\n", line));
}
}
if !a_hash.is_empty() || !c_hash.is_empty() {
mcard_content.push_str(" source:\n");
if !a_hash.is_empty() {
mcard_content.push_str(&format!(" a_hash: \"{}\"\n", a_hash));
}
if !c_hash.is_empty() {
mcard_content.push_str(&format!(" c_hash: \"{}\"\n", c_hash));
}
mcard_content.push_str(&format!(" operation: \"{}\"\n", operation));
if let Ok(runtime_facts) = env::var("CLM_RUNTIME_FACTS")
&& !runtime_facts.is_empty() {
mcard_content.push_str(" runtime_facts:\n");
for line in runtime_facts.lines() {
mcard_content.push_str(&format!(" {}\n", line));
}
}
} else {
if let Ok(runtime_facts) = env::var("CLM_RUNTIME_FACTS")
&& !runtime_facts.is_empty() {
mcard_content.push_str(" runtime_facts:\n");
for line in runtime_facts.lines() {
mcard_content.push_str(&format!(" {}\n", line));
}
}
}
if !zero_fs {
fs::write(&mcard_file, &mcard_content)?;
}
#[cfg(any(feature = "native", feature = "db"))]
let write_done = {
if let Ok(writer_arc) = get_writer_connection("execution_log", clm_root) {
if let Ok(conn) = writer_arc.lock() {
let mut retry_count = 0;
loop {
match conn.prepare_cached(
"INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
) {
Ok(mut stmt) => match stmt.execute(params![content_hash, &mcard_content, &g_time]) {
Ok(_) => break true,
Err(e) if retry_count < 10 && e.to_string().contains("locked") => {
retry_count += 1;
std::thread::sleep(std::time::Duration::from_millis(50 * retry_count));
}
Err(e) => {
eprintln!("[DB EMIT_EXEC_MCARD] Writer execute failed: {}", e);
break false;
}
},
Err(e) if retry_count < 10 && e.to_string().contains("locked") => {
retry_count += 1;
std::thread::sleep(std::time::Duration::from_millis(50 * retry_count));
}
Err(_) => break false,
}
}
} else {
false
}
} else {
false
}
};
#[cfg(not(any(feature = "native", feature = "db")))]
let write_done = false;
if !write_done {
let mut retry_count = 0;
loop {
match get_connection("execution_log", clm_root) {
Ok(conn) => match conn.prepare_cached(
"INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
) {
Ok(mut stmt) => match stmt.execute(params![content_hash, &mcard_content, &g_time]) {
Ok(_) => break,
Err(e) if retry_count < 10 && e.to_string().contains("locked") => {
retry_count += 1;
std::thread::sleep(std::time::Duration::from_millis(50 * retry_count));
}
Err(e) => return Err(ClmError::from(e)),
},
Err(e) if retry_count < 10 && e.to_string().contains("locked") => {
retry_count += 1;
std::thread::sleep(std::time::Duration::from_millis(50 * retry_count));
}
Err(e) => return Err(ClmError::from(e)),
},
Err(e) if retry_count < 10 && e.to_string().contains("locked") => {
retry_count += 1;
std::thread::sleep(std::time::Duration::from_millis(50 * retry_count));
}
Err(e) => return Err(e),
}
}
}
let esc_mcard = mcard_content.replace('\'', "''");
let esc_gtime = g_time.replace('\'', "''");
membroker_sync("execution_log", &format!(
"INSERT OR REPLACE INTO card (hash, content, g_time) VALUES ('{}', '{}', '{}')",
content_hash, esc_mcard, esc_gtime
));
Ok(mcard_file.to_string_lossy().to_string())
}
pub fn get_card_content(pillar: &str, clm_root: &str, hash: &str) -> Result<Option<String>> {
#[cfg(any(feature = "native", feature = "db"))]
{
if let Ok(reader) = get_reader_connection(pillar, clm_root) {
return get_card_cached(&reader, hash);
}
}
let conn = get_connection(pillar, clm_root)?;
get_card_cached(&conn, hash)
}
pub fn backup_db(pillar: &str, clm_root: &str) -> Result<Connection> {
let src = get_connection(pillar, clm_root)?;
let mut dst = Connection::open_in_memory()?;
{
let backup = rusqlite::backup::Backup::new(&src, &mut dst)?;
backup.run_to_completion(10_000, std::time::Duration::ZERO, None)?;
}
Ok(dst)
}
pub fn restore_db(pillar: &str, clm_root: &str, backup_conn: &Connection) -> Result<()> {
let mut dst = get_connection(pillar, clm_root)?;
{
let backup = rusqlite::backup::Backup::new(backup_conn, &mut dst)?;
backup.run_to_completion(10_000, std::time::Duration::ZERO, None)?;
}
Ok(())
}
#[cfg(any(feature = "native", all(feature = "db", feature = "async")))]
pub async fn query_db_async<F, R>(f: F) -> Result<R>
where
F: FnOnce() -> Result<R> + Send + 'static,
R: Send + 'static,
{
tokio::task::spawn_blocking(f)
.await
.map_err(|join_err| ClmError::Storage(crate::error::StorageErrorCode::QueryFailed, format!("Tokio worker join error: {}", join_err)))?
}