Skip to main content

clm_rust_core/layer3/
route_handle.rs

1//! In-process handle routing. Domain outcomes are converted only at process boundaries.
2use crate::db;
3use crate::layer0::runtime_contract::{
4    uri_schemes, RouteHandleOutcome, TriDbPillar, NETWORK_GATEWAY_TIMEOUT_MS,
5};
6use serde::Deserialize;
7use std::collections::HashSet;
8use std::path::Path;
9use std::time::Duration;
10
11#[derive(Debug, PartialEq, Eq)]
12pub struct RouteHandleResult {
13    pub content: String,
14    pub outcome: RouteHandleOutcome,
15}
16
17#[derive(Debug, PartialEq, Eq)]
18pub struct RouteHandleError {
19    pub message: String,
20    pub outcome: RouteHandleOutcome,
21}
22
23fn failure(message: impl ToString, outcome: RouteHandleOutcome) -> RouteHandleError {
24    RouteHandleError {
25        message: message.to_string(),
26        outcome,
27    }
28}
29
30#[derive(Debug, Default, Deserialize, PartialEq, Eq)]
31#[serde(rename_all = "lowercase")]
32enum RouteMedium {
33    #[default]
34    Local,
35    File,
36    Http,
37    Https,
38    #[serde(other)]
39    Unsupported,
40}
41
42#[derive(Default, Deserialize)]
43struct RouteMetadata {
44    #[serde(default)]
45    medium: RouteMedium,
46    #[serde(default)]
47    uri: String,
48    #[serde(default)]
49    cached_hash: Option<String>,
50}
51
52impl RouteMetadata {
53    fn cached_hash(&self) -> Option<&str> {
54        self.cached_hash
55            .as_deref()
56            .filter(|value| !value.is_empty())
57    }
58}
59
60fn cached(root: &str, handle: &str, route: &RouteMetadata) -> Option<String> {
61    if let Some(hash) = route.cached_hash() {
62        let clean = crate::hash::strip_prefix(hash);
63        if let Ok(Some(content)) =
64            db::get_card_content(TriDbPillar::ContentMemory.canonical_name(), root, clean)
65        {
66            if crate::layer0::hash::verify_hash(content.as_bytes(), hash) {
67                return Some(content);
68            }
69        }
70    }
71    let conn = db::get_connection(TriDbPillar::ContentMemory.canonical_name(), root).ok()?;
72    let hash: String = conn.query_row(
73        "SELECT previous_hash FROM handle_history WHERE handle = ?1 ORDER BY rowid DESC LIMIT 1",
74        [handle], |row| row.get(0),
75    ).ok()?;
76    db::get_card_content(TriDbPillar::ContentMemory.canonical_name(), root, &hash)
77        .ok()
78        .flatten()
79        .filter(|content| crate::layer0::hash::verify_hash(content.as_bytes(), &hash))
80}
81
82fn retrieve(root: &str, hash: &str, route: &RouteMetadata) -> Result<String, String> {
83    match route.medium {
84        RouteMedium::Local => {
85            db::get_card_content(TriDbPillar::ContentMemory.canonical_name(), root, hash)
86                .map_err(|error| error.to_string())?
87                .ok_or_else(|| "Content missing".to_string())
88        }
89        RouteMedium::File => {
90            let uri = &route.uri;
91            let location = uri.strip_prefix(uri_schemes::FILE).unwrap_or(uri);
92            let path = Path::new(location.strip_prefix("//").unwrap_or(location));
93            std::fs::read_to_string(if path.is_absolute() {
94                path.to_path_buf()
95            } else {
96                Path::new(root).join(path)
97            })
98            .map_err(|error| error.to_string())
99        }
100        RouteMedium::Http | RouteMedium::Https => {
101            let response = ureq::get(&route.uri)
102                .timeout(Duration::from_millis(u64::from(NETWORK_GATEWAY_TIMEOUT_MS)))
103                .call()
104                .map_err(|error| error.to_string())?;
105            response.into_string().map_err(|error| error.to_string())
106        }
107        ref medium => Err(format!("Unsupported route medium: {medium:?}")),
108    }
109}
110
111fn verify_cached_hash(content: &str, route: &RouteMetadata) -> bool {
112    let Some(expected) = route.cached_hash() else {
113        return true;
114    };
115    crate::layer0::hash::verify_hash(content.as_bytes(), expected)
116}
117
118pub fn route_handle(
119    root: &str,
120    handle: &str,
121    stale_fallback: bool,
122    cache: bool,
123) -> Result<RouteHandleResult, RouteHandleError> {
124    let mut current = handle.to_string();
125    let mut visited = HashSet::new();
126    loop {
127        let mut outcome = RouteHandleOutcome::Ok;
128        if !visited.insert(current.clone()) {
129            return Err(failure(
130                "Circular reference detected",
131                RouteHandleOutcome::NetworkError,
132            ));
133        }
134        let hash =
135            db::resolve_handle_hash(TriDbPillar::ContentMemory.canonical_name(), root, &current)
136                .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?
137                .ok_or_else(|| {
138                    failure(
139                        format!("Handle not found: {current}"),
140                        RouteHandleOutcome::NotFound,
141                    )
142                })?;
143        let raw = db::resolve_handle_content(
144            TriDbPillar::ContentMemory.canonical_name(),
145            root,
146            &format!("route:{hash}"),
147        )
148        .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?;
149        let route = raw
150            .map(|text| serde_yaml::from_str::<RouteMetadata>(&text))
151            .transpose()
152            .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?
153            .unwrap_or_default();
154        let remote = route.medium != RouteMedium::Local;
155        let resolved = retrieve(root, &hash, &route).and_then(|content| {
156            if remote && !verify_cached_hash(&content, &route) {
157                Err("Route hash mismatch".to_string())
158            } else {
159                Ok(content)
160            }
161        });
162        let content = match resolved {
163            Ok(content) => content,
164            Err(error) => {
165                if let Some(content) = stale_fallback
166                    .then(|| cached(root, &current, &route))
167                    .flatten()
168                {
169                    outcome = RouteHandleOutcome::StaleFallback;
170                    content
171                } else {
172                    return Err(failure(error, RouteHandleOutcome::NetworkError));
173                }
174            }
175        };
176        if remote && cache && outcome == RouteHandleOutcome::Ok {
177            let hash = crate::layer0::hash::compute_blake3(content.as_bytes());
178            db::setter_card_batch(
179                TriDbPillar::ContentMemory.canonical_name(),
180                root,
181                &hash,
182                &content,
183                &crate::utils::now_iso8601(),
184            )
185            .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?;
186        }
187        let next = content.trim();
188        if !next.is_empty()
189            && next
190                .chars()
191                .all(|char| char.is_ascii_alphanumeric() || "_:-".contains(char))
192            && db::resolve_handle_hash(TriDbPillar::ContentMemory.canonical_name(), root, next)
193                .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?
194                .is_some()
195        {
196            current = next.to_string();
197            continue;
198        }
199        return Ok(RouteHandleResult { content, outcome });
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use crate::layer0::runtime_contract::{route_handle_exit_code, ClmExitCode};
207
208    #[test]
209    fn route_handle_outcomes_cover_local_missing_network_and_stale() {
210        let root = tempfile::tempdir().unwrap();
211        let root = root.path().to_str().unwrap();
212        db::handle_register_batch(
213            TriDbPillar::ContentMemory.canonical_name(),
214            root,
215            "route-test-local",
216            "local-hash",
217            "local content",
218        )
219        .unwrap();
220        let local = route_handle(root, "route-test-local", false, false).unwrap();
221        assert_eq!(local.outcome, RouteHandleOutcome::Ok);
222        assert_eq!(local.content, "local content");
223        let missing = route_handle(root, "route-test-missing", false, false).unwrap_err();
224        assert_eq!(missing.outcome, RouteHandleOutcome::NotFound);
225        assert_eq!(
226            route_handle_exit_code(missing.outcome),
227            ClmExitCode::ContentMissing
228        );
229        db::handle_register_batch(
230            TriDbPillar::ContentMemory.canonical_name(),
231            root,
232            "route-test-remote",
233            "remote-hash",
234            "remote metadata placeholder",
235        )
236        .unwrap();
237        let stale_hash = crate::layer0::hash::compute_blake3(b"stale content");
238        db::handle_register_batch(
239            TriDbPillar::ContentMemory.canonical_name(),
240            root,
241            "route:remote-hash",
242            "route-metadata-hash",
243            &format!("medium: file\nuri: file:///path-that-does-not-exist-593\ncached_hash: {stale_hash}\n"),
244        )
245        .unwrap();
246        db::setter_card_batch(
247            TriDbPillar::ContentMemory.canonical_name(),
248            root,
249            &stale_hash,
250            "stale content",
251            "2026-11-08T00:00:00Z",
252        )
253        .unwrap();
254        let network = route_handle(root, "route-test-remote", false, false).unwrap_err();
255        assert_eq!(network.outcome, RouteHandleOutcome::NetworkError);
256        assert_eq!(
257            route_handle_exit_code(network.outcome),
258            ClmExitCode::GeneralError
259        );
260        let stale = route_handle(root, "route-test-remote", true, false).unwrap();
261        assert_eq!(stale.content, "stale content");
262        assert_eq!(stale.outcome, RouteHandleOutcome::StaleFallback);
263        assert_eq!(route_handle_exit_code(stale.outcome), ClmExitCode::Ok);
264        assert_eq!(sqlite_retry_curve(), [50, 100, 150, 200, 250]);
265        let next_hash = crate::layer0::hash::compute_blake3(b"route-test-local");
266        db::setter_card_batch(
267            TriDbPillar::ContentMemory.canonical_name(),
268            root,
269            &next_hash,
270            "route-test-local",
271            "2026-11-08T00:00:00Z",
272        )
273        .unwrap();
274        let conn = db::get_connection(TriDbPillar::ContentMemory.canonical_name(), root).unwrap();
275        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();
276        let fresh_hop = route_handle(root, "route-test-remote", true, false).unwrap();
277        assert_eq!(fresh_hop.outcome, RouteHandleOutcome::Ok);
278        assert_eq!(fresh_hop.content, "local content");
279        conn.execute(
280            "UPDATE card SET content = ?1 WHERE hash = ?2",
281            ("corrupted payload", &next_hash),
282        )
283        .unwrap();
284        let corrupted = route_handle(root, "route-test-remote", true, false).unwrap_err();
285        assert_eq!(corrupted.outcome, RouteHandleOutcome::NetworkError);
286    }
287
288    fn sqlite_retry_curve() -> [u32; 5] {
289        use crate::layer0::runtime_contract::sqlite_lock_retry_delay_ms;
290        [1, 2, 3, 4, 5].map(sqlite_lock_retry_delay_ms)
291    }
292}