clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! In-process handle routing. Domain outcomes are converted only at process boundaries.
use crate::db;
use crate::layer0::runtime_contract::{
    uri_schemes, RouteHandleOutcome, TriDbPillar, NETWORK_GATEWAY_TIMEOUT_MS,
};
use serde::Deserialize;
use std::collections::HashSet;
use std::path::Path;
use std::time::Duration;

#[derive(Debug, PartialEq, Eq)]
pub struct RouteHandleResult {
    pub content: String,
    pub outcome: RouteHandleOutcome,
}

#[derive(Debug, PartialEq, Eq)]
pub struct RouteHandleError {
    pub message: String,
    pub outcome: RouteHandleOutcome,
}

fn failure(message: impl ToString, outcome: RouteHandleOutcome) -> RouteHandleError {
    RouteHandleError {
        message: message.to_string(),
        outcome,
    }
}

#[derive(Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum RouteMedium {
    #[default]
    Local,
    File,
    Http,
    Https,
    #[serde(other)]
    Unsupported,
}

#[derive(Default, Deserialize)]
struct RouteMetadata {
    #[serde(default)]
    medium: RouteMedium,
    #[serde(default)]
    uri: String,
    #[serde(default)]
    cached_hash: Option<String>,
}

impl RouteMetadata {
    fn cached_hash(&self) -> Option<&str> {
        self.cached_hash
            .as_deref()
            .filter(|value| !value.is_empty())
    }
}

fn cached(root: &str, handle: &str, route: &RouteMetadata) -> Result<Option<String>, String> {
    let conn = db::get_connection(TriDbPillar::ContentMemory.canonical_name(), root).map_err(|e| e.to_string())?;
    if let Some(hash) = route.cached_hash() {
        return crate::layer2::record_store::read_text(&conn, hash).map_err(|e| e.to_string());
    }
    use rusqlite::OptionalExtension;
    let hash: Option<String> = conn.query_row(
        "SELECT previous_hash FROM handle_history WHERE handle = ?1 ORDER BY rowid DESC LIMIT 1",
        [handle], |row| row.get(0)).optional().map_err(|e| e.to_string())?;
    hash.map(|hash| crate::layer2::record_store::read_text(&conn, &hash).map_err(|e| e.to_string()))
        .transpose().map(Option::flatten)
}

fn retrieve(root: &str, hash: &str, route: &RouteMetadata) -> Result<String, String> {
    match route.medium {
        RouteMedium::Local => {
            db::get_card_content(TriDbPillar::ContentMemory.canonical_name(), root, hash)
                .map_err(|error| error.to_string())?
                .ok_or_else(|| "Content missing".to_string())
        }
        RouteMedium::File => {
            let uri = &route.uri;
            let location = uri.strip_prefix(uri_schemes::FILE).unwrap_or(uri);
            let path = Path::new(location.strip_prefix("//").unwrap_or(location));
            std::fs::read_to_string(if path.is_absolute() {
                path.to_path_buf()
            } else {
                Path::new(root).join(path)
            })
            .map_err(|error| error.to_string())
        }
        RouteMedium::Http | RouteMedium::Https => {
            let response = ureq::get(&route.uri)
                .timeout(Duration::from_millis(u64::from(NETWORK_GATEWAY_TIMEOUT_MS)))
                .call()
                .map_err(|error| error.to_string())?;
            response.into_string().map_err(|error| error.to_string())
        }
        ref medium => Err(format!("Unsupported route medium: {medium:?}")),
    }
}

fn verify_cached_hash(root: &str, hash: &str, content: &str, route: &RouteMetadata) -> Result<(), String> {
    let conn = db::get_connection(TriDbPillar::ContentMemory.canonical_name(), root).map_err(|e| e.to_string())?;
    let record = crate::layer2::record_store::read_record(&conn, route.cached_hash().unwrap_or(hash))
        .map_err(|e| e.to_string())?.ok_or_else(|| "route requires a declared stored content address".to_string())?;
    if record.content != content.as_bytes() { return Err("Route content differs from declared stored bytes".into()); }
    Ok(())
}

pub fn route_handle(
    root: &str,
    handle: &str,
    stale_fallback: bool,
    cache: bool,
) -> Result<RouteHandleResult, RouteHandleError> {
    let mut current = handle.to_string();
    let mut visited = HashSet::new();
    loop {
        let mut outcome = RouteHandleOutcome::Ok;
        if !visited.insert(current.clone()) {
            return Err(failure(
                "Circular reference detected",
                RouteHandleOutcome::NetworkError,
            ));
        }
        let hash =
            db::resolve_handle_hash(TriDbPillar::ContentMemory.canonical_name(), root, &current)
                .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?
                .ok_or_else(|| {
                    failure(
                        format!("Handle not found: {current}"),
                        RouteHandleOutcome::NotFound,
                    )
                })?;
        let raw = db::resolve_handle_content(
            TriDbPillar::ContentMemory.canonical_name(),
            root,
            &format!("route:{hash}"),
        )
        .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?;
        let route = raw
            .map(|text| serde_yaml::from_str::<RouteMetadata>(&text))
            .transpose()
            .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?
            .unwrap_or_default();
        let remote = route.medium != RouteMedium::Local;
        let resolved = retrieve(root, &hash, &route).and_then(|content| {
            if remote { verify_cached_hash(root, &hash, &content, &route)?; }
            Ok(content)
        });
        let content = match resolved {
            Ok(content) => content,
            Err(error) => {
                let fallback = if stale_fallback { cached(root, &current, &route)
                    .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))? } else { None };
                if let Some(content) = fallback {
                    outcome = RouteHandleOutcome::StaleFallback;
                    content
                } else {
                    return Err(failure(error, RouteHandleOutcome::NetworkError));
                }
            }
        };
        if remote && cache && outcome == RouteHandleOutcome::Ok {
            let hash = crate::layer0::hash::compute_blake3(content.as_bytes());
            db::setter_card_batch(
                TriDbPillar::ContentMemory.canonical_name(),
                root,
                &hash,
                &content,
                &crate::layer0::gtime::stamp_g_time(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3, None, None, None),
            )
            .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?;
        }
        let next = content.trim();
        if !next.is_empty()
            && next
                .chars()
                .all(|char| char.is_ascii_alphanumeric() || "_:-".contains(char))
            && db::resolve_handle_hash(TriDbPillar::ContentMemory.canonical_name(), root, next)
                .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?
                .is_some()
        {
            current = next.to_string();
            continue;
        }
        return Ok(RouteHandleResult { content, outcome });
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layer0::runtime_contract::{route_handle_exit_code, ClmExitCode};

    #[test]
    fn route_handle_outcomes_cover_local_missing_network_and_stale() {
        let root = tempfile::tempdir().unwrap();
        let root = root.path().to_str().unwrap();
        db::handle_register_batch(
            TriDbPillar::ContentMemory.canonical_name(),
            root,
            "route-test-local",
            &crate::hash::raw_hash_string("local content"),
            "local content",
        )
        .unwrap();
        let local = route_handle(root, "route-test-local", false, false).unwrap();
        assert_eq!(local.outcome, RouteHandleOutcome::Ok);
        assert_eq!(local.content, "local content");
        let missing = route_handle(root, "route-test-missing", false, false).unwrap_err();
        assert_eq!(missing.outcome, RouteHandleOutcome::NotFound);
        assert_eq!(
            route_handle_exit_code(missing.outcome),
            ClmExitCode::ContentMissing
        );
        db::handle_register_batch(
            TriDbPillar::ContentMemory.canonical_name(),
            root,
            "route-test-remote",
            &crate::hash::raw_hash_string("remote metadata placeholder"),
            "remote metadata placeholder",
        )
        .unwrap();
        let stale_hash = crate::layer0::hash::compute_blake3(b"stale content");
        db::handle_register_batch(
            TriDbPillar::ContentMemory.canonical_name(),
            root,
            &format!("route:{}", crate::hash::raw_hash_string("remote metadata placeholder")),
            &crate::hash::raw_hash_string(&format!("medium: file\nuri: file:///path-that-does-not-exist-593\ncached_hash: {stale_hash}\n")),
            &format!("medium: file\nuri: file:///path-that-does-not-exist-593\ncached_hash: {stale_hash}\n"),
        )
        .unwrap();
        db::setter_card_batch(
            TriDbPillar::ContentMemory.canonical_name(),
            root,
            &stale_hash,
            "stale content",
            "blake3|2026-11-08T00:00:00Z|UTC",
        )
        .unwrap();
        let network = route_handle(root, "route-test-remote", false, false).unwrap_err();
        assert_eq!(network.outcome, RouteHandleOutcome::NetworkError);
        assert_eq!(
            route_handle_exit_code(network.outcome),
            ClmExitCode::GeneralError
        );
        let stale = route_handle(root, "route-test-remote", true, false).unwrap();
        assert_eq!(stale.content, "stale content");
        assert_eq!(stale.outcome, RouteHandleOutcome::StaleFallback);
        assert_eq!(route_handle_exit_code(stale.outcome), ClmExitCode::Ok);
        assert_eq!(sqlite_retry_curve(), [50, 100, 150, 200, 250]);
        let next_hash = crate::layer0::hash::compute_blake3(b"route-test-local");
        db::setter_card_batch(
            TriDbPillar::ContentMemory.canonical_name(),
            root,
            &next_hash,
            "route-test-local",
            "blake3|2026-11-08T00:00:00Z|UTC",
        )
        .unwrap();
        let metadata = format!("medium: file\nuri: file:///path-that-does-not-exist-593\ncached_hash: {next_hash}\n");
        db::handle_register_batch(TriDbPillar::ContentMemory.canonical_name(), root,
            &format!("route:{}", crate::hash::raw_hash_string("remote metadata placeholder")),
            &crate::hash::raw_hash_string(&metadata), &metadata).unwrap();
        let fresh_hop = route_handle(root, "route-test-remote", true, false).unwrap();
        assert_eq!(fresh_hop.outcome, RouteHandleOutcome::Ok);
        assert_eq!(fresh_hop.content, "local content");
        let conn = rusqlite::Connection::open(db::get_db_path(TriDbPillar::ContentMemory.canonical_name(), root)).unwrap();
        conn.execute(
            "UPDATE card SET content = ?1 WHERE hash = ?2",
            ("corrupted payload", &next_hash),
        )
        .unwrap();
        let corrupted = route_handle(root, "route-test-remote", true, false).unwrap_err();
        assert_eq!(corrupted.outcome, RouteHandleOutcome::NetworkError);
    }

    fn sqlite_retry_curve() -> [u32; 5] {
        use crate::layer0::runtime_contract::sqlite_lock_retry_delay_ms;
        [1, 2, 3, 4, 5].map(sqlite_lock_retry_delay_ms)
    }
}