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