1use 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) -> Result<Option<String>, String> {
61 let conn = db::get_connection(TriDbPillar::ContentMemory.canonical_name(), root).map_err(|e| e.to_string())?;
62 if let Some(hash) = route.cached_hash() {
63 return crate::layer2::record_store::read_text(&conn, hash).map_err(|e| e.to_string());
64 }
65 use rusqlite::OptionalExtension;
66 let hash: Option<String> = conn.query_row(
67 "SELECT previous_hash FROM handle_history WHERE handle = ?1 ORDER BY rowid DESC LIMIT 1",
68 [handle], |row| row.get(0)).optional().map_err(|e| e.to_string())?;
69 hash.map(|hash| crate::layer2::record_store::read_text(&conn, &hash).map_err(|e| e.to_string()))
70 .transpose().map(Option::flatten)
71}
72
73fn retrieve(root: &str, hash: &str, route: &RouteMetadata) -> Result<String, String> {
74 match route.medium {
75 RouteMedium::Local => {
76 db::get_card_content(TriDbPillar::ContentMemory.canonical_name(), root, hash)
77 .map_err(|error| error.to_string())?
78 .ok_or_else(|| "Content missing".to_string())
79 }
80 RouteMedium::File => {
81 let uri = &route.uri;
82 let location = uri.strip_prefix(uri_schemes::FILE).unwrap_or(uri);
83 let path = Path::new(location.strip_prefix("//").unwrap_or(location));
84 std::fs::read_to_string(if path.is_absolute() {
85 path.to_path_buf()
86 } else {
87 Path::new(root).join(path)
88 })
89 .map_err(|error| error.to_string())
90 }
91 RouteMedium::Http | RouteMedium::Https => {
92 let response = ureq::get(&route.uri)
93 .timeout(Duration::from_millis(u64::from(NETWORK_GATEWAY_TIMEOUT_MS)))
94 .call()
95 .map_err(|error| error.to_string())?;
96 response.into_string().map_err(|error| error.to_string())
97 }
98 ref medium => Err(format!("Unsupported route medium: {medium:?}")),
99 }
100}
101
102fn verify_cached_hash(root: &str, hash: &str, content: &str, route: &RouteMetadata) -> Result<(), String> {
103 let conn = db::get_connection(TriDbPillar::ContentMemory.canonical_name(), root).map_err(|e| e.to_string())?;
104 let record = crate::layer2::record_store::read_record(&conn, route.cached_hash().unwrap_or(hash))
105 .map_err(|e| e.to_string())?.ok_or_else(|| "route requires a declared stored content address".to_string())?;
106 if record.content != content.as_bytes() { return Err("Route content differs from declared stored bytes".into()); }
107 Ok(())
108}
109
110pub fn route_handle(
111 root: &str,
112 handle: &str,
113 stale_fallback: bool,
114 cache: bool,
115) -> Result<RouteHandleResult, RouteHandleError> {
116 let mut current = handle.to_string();
117 let mut visited = HashSet::new();
118 loop {
119 let mut outcome = RouteHandleOutcome::Ok;
120 if !visited.insert(current.clone()) {
121 return Err(failure(
122 "Circular reference detected",
123 RouteHandleOutcome::NetworkError,
124 ));
125 }
126 let hash =
127 db::resolve_handle_hash(TriDbPillar::ContentMemory.canonical_name(), root, ¤t)
128 .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?
129 .ok_or_else(|| {
130 failure(
131 format!("Handle not found: {current}"),
132 RouteHandleOutcome::NotFound,
133 )
134 })?;
135 let raw = db::resolve_handle_content(
136 TriDbPillar::ContentMemory.canonical_name(),
137 root,
138 &format!("route:{hash}"),
139 )
140 .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?;
141 let route = raw
142 .map(|text| serde_yaml::from_str::<RouteMetadata>(&text))
143 .transpose()
144 .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?
145 .unwrap_or_default();
146 let remote = route.medium != RouteMedium::Local;
147 let resolved = retrieve(root, &hash, &route).and_then(|content| {
148 if remote { verify_cached_hash(root, &hash, &content, &route)?; }
149 Ok(content)
150 });
151 let content = match resolved {
152 Ok(content) => content,
153 Err(error) => {
154 let fallback = if stale_fallback { cached(root, ¤t, &route)
155 .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))? } else { None };
156 if let Some(content) = fallback {
157 outcome = RouteHandleOutcome::StaleFallback;
158 content
159 } else {
160 return Err(failure(error, RouteHandleOutcome::NetworkError));
161 }
162 }
163 };
164 if remote && cache && outcome == RouteHandleOutcome::Ok {
165 let hash = crate::layer0::hash::compute_blake3(content.as_bytes());
166 db::setter_card_batch(
167 TriDbPillar::ContentMemory.canonical_name(),
168 root,
169 &hash,
170 &content,
171 &crate::layer0::gtime::stamp_g_time(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3, None, None, None),
172 )
173 .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?;
174 }
175 let next = content.trim();
176 if !next.is_empty()
177 && next
178 .chars()
179 .all(|char| char.is_ascii_alphanumeric() || "_:-".contains(char))
180 && db::resolve_handle_hash(TriDbPillar::ContentMemory.canonical_name(), root, next)
181 .map_err(|error| failure(error, RouteHandleOutcome::NetworkError))?
182 .is_some()
183 {
184 current = next.to_string();
185 continue;
186 }
187 return Ok(RouteHandleResult { content, outcome });
188 }
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194 use crate::layer0::runtime_contract::{route_handle_exit_code, ClmExitCode};
195
196 #[test]
197 fn route_handle_outcomes_cover_local_missing_network_and_stale() {
198 let root = tempfile::tempdir().unwrap();
199 let root = root.path().to_str().unwrap();
200 db::handle_register_batch(
201 TriDbPillar::ContentMemory.canonical_name(),
202 root,
203 "route-test-local",
204 &crate::hash::raw_hash_string("local content"),
205 "local content",
206 )
207 .unwrap();
208 let local = route_handle(root, "route-test-local", false, false).unwrap();
209 assert_eq!(local.outcome, RouteHandleOutcome::Ok);
210 assert_eq!(local.content, "local content");
211 let missing = route_handle(root, "route-test-missing", false, false).unwrap_err();
212 assert_eq!(missing.outcome, RouteHandleOutcome::NotFound);
213 assert_eq!(
214 route_handle_exit_code(missing.outcome),
215 ClmExitCode::ContentMissing
216 );
217 db::handle_register_batch(
218 TriDbPillar::ContentMemory.canonical_name(),
219 root,
220 "route-test-remote",
221 &crate::hash::raw_hash_string("remote metadata placeholder"),
222 "remote metadata placeholder",
223 )
224 .unwrap();
225 let stale_hash = crate::layer0::hash::compute_blake3(b"stale content");
226 db::handle_register_batch(
227 TriDbPillar::ContentMemory.canonical_name(),
228 root,
229 &format!("route:{}", crate::hash::raw_hash_string("remote metadata placeholder")),
230 &crate::hash::raw_hash_string(&format!("medium: file\nuri: file:///path-that-does-not-exist-593\ncached_hash: {stale_hash}\n")),
231 &format!("medium: file\nuri: file:///path-that-does-not-exist-593\ncached_hash: {stale_hash}\n"),
232 )
233 .unwrap();
234 db::setter_card_batch(
235 TriDbPillar::ContentMemory.canonical_name(),
236 root,
237 &stale_hash,
238 "stale content",
239 "blake3|2026-11-08T00:00:00Z|UTC",
240 )
241 .unwrap();
242 let network = route_handle(root, "route-test-remote", false, false).unwrap_err();
243 assert_eq!(network.outcome, RouteHandleOutcome::NetworkError);
244 assert_eq!(
245 route_handle_exit_code(network.outcome),
246 ClmExitCode::GeneralError
247 );
248 let stale = route_handle(root, "route-test-remote", true, false).unwrap();
249 assert_eq!(stale.content, "stale content");
250 assert_eq!(stale.outcome, RouteHandleOutcome::StaleFallback);
251 assert_eq!(route_handle_exit_code(stale.outcome), ClmExitCode::Ok);
252 assert_eq!(sqlite_retry_curve(), [50, 100, 150, 200, 250]);
253 let next_hash = crate::layer0::hash::compute_blake3(b"route-test-local");
254 db::setter_card_batch(
255 TriDbPillar::ContentMemory.canonical_name(),
256 root,
257 &next_hash,
258 "route-test-local",
259 "blake3|2026-11-08T00:00:00Z|UTC",
260 )
261 .unwrap();
262 let metadata = format!("medium: file\nuri: file:///path-that-does-not-exist-593\ncached_hash: {next_hash}\n");
263 db::handle_register_batch(TriDbPillar::ContentMemory.canonical_name(), root,
264 &format!("route:{}", crate::hash::raw_hash_string("remote metadata placeholder")),
265 &crate::hash::raw_hash_string(&metadata), &metadata).unwrap();
266 let fresh_hop = route_handle(root, "route-test-remote", true, false).unwrap();
267 assert_eq!(fresh_hop.outcome, RouteHandleOutcome::Ok);
268 assert_eq!(fresh_hop.content, "local content");
269 let conn = rusqlite::Connection::open(db::get_db_path(TriDbPillar::ContentMemory.canonical_name(), root)).unwrap();
270 conn.execute(
271 "UPDATE card SET content = ?1 WHERE hash = ?2",
272 ("corrupted payload", &next_hash),
273 )
274 .unwrap();
275 let corrupted = route_handle(root, "route-test-remote", true, false).unwrap_err();
276 assert_eq!(corrupted.outcome, RouteHandleOutcome::NetworkError);
277 }
278
279 fn sqlite_retry_curve() -> [u32; 5] {
280 use crate::layer0::runtime_contract::sqlite_lock_retry_delay_ms;
281 [1, 2, 3, 4, 5].map(sqlite_lock_retry_delay_ms)
282 }
283}