lean_ctx/server/
reference_store.rs1use std::collections::HashMap;
2use std::sync::{Arc, Mutex, OnceLock};
3use std::time::{Duration, Instant};
4
5use crate::core::archive::authority::ArchiveAuthority;
6use crate::core::policy::{content, runtime};
7
8#[derive(Clone)]
9struct RefEntry {
10 content: Arc<str>,
11 authority: Option<ArchiveAuthority>,
12 created_at: Instant,
13}
14
15const MAX_ENTRIES: usize = 200;
16const MAX_STORE_BYTES: usize = 64 * 1024 * 1024;
17const TTL: Duration = Duration::from_mins(5);
18
19fn store_lock() -> &'static Mutex<HashMap<String, RefEntry>> {
20 static STORE: OnceLock<Mutex<HashMap<String, RefEntry>>> = OnceLock::new();
21 STORE.get_or_init(|| Mutex::new(HashMap::new()))
22}
23
24const RESOLVE_LOCK_WAIT: Duration = Duration::from_millis(50);
25
26fn lock_briefly() -> Option<std::sync::MutexGuard<'static, HashMap<String, RefEntry>>> {
27 let deadline = Instant::now() + RESOLVE_LOCK_WAIT;
28 loop {
29 match store_lock().try_lock() {
30 Ok(map) => return Some(map),
31 Err(std::sync::TryLockError::Poisoned(poisoned)) => return Some(poisoned.into_inner()),
32 Err(std::sync::TryLockError::WouldBlock) if Instant::now() < deadline => {
33 std::thread::sleep(Duration::from_micros(200));
34 }
35 Err(std::sync::TryLockError::WouldBlock) => return None,
36 }
37 }
38}
39
40pub fn store(content: &str) -> Option<String> {
42 store_with_authority(content, None)
43}
44
45pub(crate) fn store_with_authority(
46 text: &str,
47 authority: Option<&ArchiveAuthority>,
48) -> Option<String> {
49 runtime::with_source_view(|| {
50 if text.len() > entry_budget()
51 || (runtime::is_active() && authority.is_none())
52 || authority.is_some_and(|origin| !origin.admitted())
53 {
54 return None;
55 }
56 let text = content::protect_active(text).ok()?;
57 let text = crate::core::context_admission::recovery::admit_for_storage(&text)?;
60 if text.len() > entry_budget() {
61 return None;
62 }
63 let id = reference_id(&text, authority)?;
64 let mut map = store_lock().try_lock().ok()?;
66 map.retain(|_, entry| entry.created_at.elapsed() < TTL);
67 let mut bytes: usize = map.values().map(|entry| entry.content.len()).sum();
68 if let Some(previous) = map.remove(&id) {
69 bytes -= previous.content.len();
70 }
71 while map.len() >= MAX_ENTRIES || bytes.saturating_add(text.len()) > MAX_STORE_BYTES {
72 let oldest = map
73 .iter()
74 .min_by_key(|(_, entry)| entry.created_at)
75 .map(|(key, _)| key.clone())?;
76 bytes -= map.remove(&oldest)?.content.len();
77 }
78 map.insert(
79 id.clone(),
80 RefEntry {
81 content: Arc::from(text.as_str()),
82 authority: authority.cloned(),
83 created_at: Instant::now(),
84 },
85 );
86 Some(id)
87 })
88 .ok()
89 .flatten()
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub(crate) enum ReferenceResolveError {
94 Malformed,
95 Missing,
96 Expired,
97 Refused(&'static str),
100}
101
102pub(crate) fn resolve_checked(id: &str) -> Result<String, ReferenceResolveError> {
106 let Some(digest) = id.strip_prefix("ref_") else {
107 return Err(ReferenceResolveError::Malformed);
108 };
109 if digest.is_empty() || !digest.bytes().all(|b| b.is_ascii_hexdigit()) {
110 return Err(ReferenceResolveError::Malformed);
111 }
112 let entry = {
113 let Some(mut map) = lock_briefly() else {
116 return Err(ReferenceResolveError::Missing);
117 };
118 let Some(entry) = map.get(id) else {
119 return Err(ReferenceResolveError::Missing);
120 };
121 if entry.created_at.elapsed() >= TTL {
122 map.remove(id);
123 return Err(ReferenceResolveError::Expired);
124 }
125 entry.clone()
126 };
127 if entry.authority.is_some()
129 && !runtime::REQUEST_PROJECT
130 .try_with(|project| project.borrow().is_some())
131 .unwrap_or(false)
132 {
133 return Err(ReferenceResolveError::Refused(
134 "reference is bound to a project this request does not name",
135 ));
136 }
137 runtime::with_source_view(|| {
138 if runtime::is_active() && entry.authority.is_none() {
139 return Err(ReferenceResolveError::Refused(
140 "stored output has no source authority under the active policy",
141 ));
142 }
143 if entry
144 .authority
145 .as_ref()
146 .is_some_and(|origin| !origin.admitted())
147 || reference_id(&entry.content, entry.authority.as_ref()).as_deref() != Some(id)
148 {
149 return Err(ReferenceResolveError::Refused(
150 "the reference's source is no longer admitted",
151 ));
152 }
153 content::protect_active(&entry.content)
154 .map(std::borrow::Cow::into_owned)
155 .map_err(|_| {
156 ReferenceResolveError::Refused("stored output is withheld by current content rules")
157 })
158 })
159 .unwrap_or(Err(ReferenceResolveError::Refused(
160 "current policy cannot be verified",
161 )))
162}
163
164pub fn resolve(id: &str) -> Option<String> {
166 resolve_checked(id).ok()
167}
168
169#[cfg(test)]
170pub(crate) fn expire_for_test(id: &str) {
171 if let Some(entry) = store_lock()
172 .lock()
173 .unwrap_or_else(std::sync::PoisonError::into_inner)
174 .get_mut(id)
175 {
176 entry.created_at = Instant::now()
177 .checked_sub(TTL + Duration::from_secs(1))
178 .expect("test timestamp supports TTL subtraction");
179 }
180}
181
182pub fn stats() -> (usize, usize) {
183 let Ok(map) = store_lock().try_lock() else {
184 return (0, 0);
185 };
186 let live = map
187 .values()
188 .filter(|entry| entry.created_at.elapsed() < TTL);
189 live.fold((0, 0), |(count, bytes), entry| {
190 (count + 1, bytes + entry.content.len())
191 })
192}
193
194fn entry_budget() -> usize {
195 crate::core::limits::max_read_bytes().min(content::MAX_PROTECTED_CONTENT_BYTES)
196}
197
198fn reference_id(text: &str, authority: Option<&ArchiveAuthority>) -> Option<String> {
199 let digest = if let Some(origin) = authority {
200 origin.id(text)?
201 } else {
202 let mut hash = blake3::Hasher::new();
203 hash.update(b"leanctx-public-reference-v1\0");
204 hash.update(text.as_bytes());
205 hash.finalize().to_hex().to_string()
206 };
207 Some(format!("ref_{digest}"))
208}
209
210#[cfg(test)]
211mod tests;