clm-kernel 0.0.21

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) -> Option<String> {
    if let Some(hash) = route.cached_hash() {
        let clean = crate::hash::strip_prefix(hash);
        if let Ok(Some(content)) =
            db::get_card_content(TriDbPillar::ContentMemory.canonical_name(), root, clean)
        {
            if crate::layer0::hash::verify_hash(content.as_bytes(), hash) {
                return Some(content);
            }
        }
    }
    let conn = db::get_connection(TriDbPillar::ContentMemory.canonical_name(), root).ok()?;
    let hash: String = conn.query_row(
        "SELECT previous_hash FROM handle_history WHERE handle = ?1 ORDER BY rowid DESC LIMIT 1",
        [handle], |row| row.get(0),
    ).ok()?;
    db::get_card_content(TriDbPillar::ContentMemory.canonical_name(), root, &hash)
        .ok()
        .flatten()
        .filter(|content| crate::layer0::hash::verify_hash(content.as_bytes(), &hash))
}

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(content: &str, route: &RouteMetadata) -> bool {
    let Some(expected) = route.cached_hash() else {
        return true;
    };
    crate::layer0::hash::verify_hash(content.as_bytes(), expected)
}

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(&content, &route) {
                Err("Route hash mismatch".to_string())
            } else {
                Ok(content)
            }
        });
        let content = match resolved {
            Ok(content) => content,
            Err(error) => {
                if let Some(content) = stale_fallback
                    .then(|| cached(root, &current, &route))
                    .flatten()
                {
                    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::utils::now_iso8601(),
            )
            .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",
            "local-hash",
            "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",
            "remote-hash",
            "remote metadata placeholder",
        )
        .unwrap();
        let stale_hash = crate::layer0::hash::compute_blake3(b"stale content");
        db::handle_register_batch(
            TriDbPillar::ContentMemory.canonical_name(),
            root,
            "route:remote-hash",
            "route-metadata-hash",
            &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",
            "2026-11-08T00:00:00Z",
        )
        .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",
            "2026-11-08T00:00:00Z",
        )
        .unwrap();
        let conn = db::get_connection(TriDbPillar::ContentMemory.canonical_name(), root).unwrap();
        conn.execute("UPDATE card SET content = ?1 WHERE hash = ?2", (format!("medium: file\nuri: file:///path-that-does-not-exist-593\ncached_hash: {next_hash}\n"), "route-metadata-hash")).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");
        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)
    }
}