ifc_lite_processing/result_cache/
mod.rs1mod config;
37mod envelope;
38mod fs_private;
39mod key;
40mod mesh_codec;
41mod meta_codec;
42mod store;
43mod wire;
44mod report;
45#[cfg(test)]
46#[path = "codec_tests.rs"]
47mod codec_tests;
48#[cfg(test)]
49#[path = "store_tests.rs"]
50mod store_tests;
51
52pub use config::{default_directory, CacheMode, PassHook, ResultCacheConfig};
53pub use report::{BypassReason, CacheOutcome, CacheReport, CacheWork, MissReason, PublishOutcome};
54use config::HookSink;
55
56use crate::{ProcessingRequest, ProcessingResult};
57use envelope::EntryIdentity;
58use std::time::Instant;
59use store::{ReadEntry, ReadError, Store};
60
61pub struct CachedProcessing {
63 pub result: ProcessingResult,
64 pub report: CacheReport,
65}
66
67#[derive(Debug, Clone, Default)]
69pub struct ResultCache {
70 config: ResultCacheConfig,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
75pub(crate) enum CodecError {
76 Truncated,
77 Overflow,
78 BadMagic,
79 Unsupported(u32),
80 Layout(&'static str),
81 IdentityMismatch,
82 Checksum(&'static str),
83 Malformed(&'static str, &'static str),
84 Invariant(&'static str),
85}
86
87impl std::fmt::Display for CodecError {
88 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89 match self {
90 Self::Truncated => f.write_str("truncated"),
91 Self::Overflow => f.write_str("length or count overflows"),
92 Self::BadMagic => f.write_str("not a result-cache entry"),
93 Self::Unsupported(v) => write!(f, "unsupported entry format version {v}"),
94 Self::Layout(what) => write!(f, "bad layout: {what}"),
95 Self::IdentityMismatch => f.write_str("entry identity does not match its key"),
96 Self::Checksum(section) => write!(f, "{section} checksum mismatch"),
97 Self::Malformed(section, what) => write!(f, "malformed {section}: {what}"),
98 Self::Invariant(what) => write!(f, "invariant: {what}"),
99 }
100 }
101}
102
103impl ResultCache {
104 pub fn new(config: ResultCacheConfig) -> Self {
105 Self { config }
106 }
107
108 pub fn config(&self) -> &ResultCacheConfig {
109 &self.config
110 }
111
112 pub fn process(&self, content: &[u8], request: &ProcessingRequest) -> CachedProcessing {
115 let mut report = CacheReport::new(CacheOutcome::Off);
116 if self.config.mode == CacheMode::Off {
117 return self.run_live(content, request, report, None);
118 }
119 let request_digest = match key::request_digest(request) {
120 Ok(digest) => digest,
121 Err(reason) => {
122 report.outcome = CacheOutcome::Bypass(reason);
123 return self.run_live(content, request, report, None);
124 }
125 };
126 if ifc_lite_geometry::resource::ambient_scope_active() {
131 report.outcome = CacheOutcome::Bypass(BypassReason::AmbientResourceScope);
132 return self.run_live(content, request, report, None);
133 }
134 let writable = self.config.mode == CacheMode::ReadWrite;
135 let Some(root) = self.config.directory.clone().or_else(default_directory) else {
136 report.outcome = CacheOutcome::Bypass(BypassReason::Unavailable("no cache directory".into()));
137 return self.run_live(content, request, report, None);
138 };
139 let store = match Store::open(&root, writable, self.config.max_bytes, self.config.max_entry_bytes)
140 .map(|store| store.with_min_free(self.config.min_free_bytes)) {
141 Ok(store) => Some(store),
142 Err(e) if !writable && e.kind() == std::io::ErrorKind::NotFound => None,
143 Err(e) => {
144 report.warn(format!("result cache unavailable at {}: {e}", root.display()));
145 report.outcome = CacheOutcome::Bypass(BypassReason::Unavailable(e.to_string()));
146 return self.run_live(content, request, report, None);
147 }
148 };
149
150 let Some(engine) = key::EngineIdentity::current(&self.config.engine_salt) else {
153 report.warn("result cache: executable identity unreadable".into());
154 report.outcome = CacheOutcome::Bypass(BypassReason::Unavailable("no engine identity".into()));
155 return self.run_live(content, request, report, None);
156 };
157 let started = Instant::now();
158 let source_sha256 = key::source_digest(content);
159 report.work.hash = started.elapsed();
160 report.work.bytes_hashed = content.len() as u64;
161 let engine_digest = engine.digest();
162 let source_len = content.len() as u64;
163 let id = EntryIdentity {
164 key: key::cache_key(&source_sha256, source_len, &request_digest, &engine_digest),
165 source_sha256,
166 source_len,
167 request_digest,
168 engine_digest,
169 };
170 let key_hex = key::hex(&id.key);
171 report.key = Some(key_hex.clone());
172 let Some(store) = store else {
173 report.outcome = CacheOutcome::Miss(MissReason::Absent);
174 return self.run_live(content, request, report, None);
175 };
176 match lookup(&store, &key_hex, &id, self.config.max_entry_bytes, &mut report) {
177 Ok(_) if engine.policy_changed() => {
178 report.outcome = CacheOutcome::Miss(MissReason::PolicyChangedDuringLookup);
182 let publish = writable.then_some(Publish { store: &store, id: &id, key_hex: &key_hex, engine: &engine });
183 self.run_live(content, request, report, publish)
184 }
185 Ok((mut result, entry)) => {
186 if writable {
187 store.touch(&entry);
188 }
189 result.stats.from_cache = true;
190 report.outcome = CacheOutcome::Hit;
191 CachedProcessing { result, report }
192 }
193 Err((reason, entry)) => {
194 if let (true, Some(entry)) = (writable, entry.as_ref()) {
195 store.remove_if_same(&key_hex, entry);
196 }
197 report.outcome = CacheOutcome::Miss(reason);
198 let publish = writable.then_some(Publish { store: &store, id: &id, key_hex: &key_hex, engine: &engine });
199 self.run_live(content, request, report, publish)
200 }
201 }
202 }
203
204 fn run_live(
206 &self,
207 content: &[u8],
208 request: &ProcessingRequest,
209 mut report: CacheReport,
210 publish: Option<Publish<'_>>,
211 ) -> CachedProcessing {
212 let started = Instant::now();
213 let (result, observed) = match &self.config.pass_hook {
214 Some(hook) => crate::processor::process_observed(content, request, &mut HookSink(hook, 0)),
215 None => crate::processor::process_observed(content, request, &mut ()),
216 };
217 report.work.process = started.elapsed();
218 if let Some(Publish { engine, .. }) = &publish {
219 let skip = if engine.policy_changed() {
226 Some(PublishOutcome::SkippedPolicyChanged)
227 } else if observed.foreign_resource_scope || engine.resource_stopped() {
228 Some(PublishOutcome::SkippedResourceStop)
229 } else if engine.refusal_reported() {
230 Some(PublishOutcome::SkippedRefusalReported)
231 } else {
232 None
233 };
234 if let Some(skip) = skip {
235 report.publish = skip;
236 return CachedProcessing { result, report };
237 }
238 }
239 if let Some(Publish { store, id, key_hex, .. }) = publish {
240 let limit = self.config.max_entry_bytes.min(self.config.max_bytes);
241 let at_least = envelope::payload_lower_bound(&result);
242 if at_least > limit {
243 report.publish = PublishOutcome::SkippedOversized { bytes: at_least, limit };
245 return CachedProcessing { result, report };
246 }
247 let started = Instant::now();
248 let encoded = envelope::encode_parts(&result, id);
249 report.work.encode = started.elapsed();
250 report.publish = match encoded {
251 Ok(entry) => {
252 let started = Instant::now();
253 let outcome = store.publish_parts(key_hex, &entry.parts());
254 report.work.write = started.elapsed();
255 if matches!(outcome, PublishOutcome::Published { .. }) {
256 report.work.entry_bytes_written = entry.len() as u64;
257 }
258 outcome
259 }
260 Err(e) => PublishOutcome::Unencodable(e.to_string()),
261 };
262 if let PublishOutcome::Failed(why) | PublishOutcome::Unencodable(why) = &report.publish {
263 report.warn(format!("result cache: not stored: {why}"));
264 }
265 }
266 CachedProcessing { result, report }
267 }
268}
269
270struct Publish<'a> {
272 store: &'a Store,
273 id: &'a EntryIdentity,
274 key_hex: &'a str,
275 engine: &'a key::EngineIdentity,
276}
277
278type Lookup = Result<(ProcessingResult, ReadEntry), (MissReason, Option<ReadEntry>)>;
279
280fn lookup(store: &Store, key_hex: &str, id: &EntryIdentity, limit: u64, report: &mut CacheReport) -> Lookup {
282 let started = Instant::now();
283 let read = store.read(key_hex);
284 report.work.read = started.elapsed();
285 let entry = match read {
286 Ok(Some(entry)) => entry,
287 Ok(None) => return Err((MissReason::Absent, None)),
288 Err(ReadError::Oversized(bytes)) => {
289 report.warn(format!("result cache: entry {key_hex} is {bytes} bytes, over the per-entry limit"));
290 return Err((MissReason::Oversized { bytes, limit }, None));
291 }
292 Err(ReadError::Io(e)) => {
293 report.warn(format!("result cache: could not read entry {key_hex}: {e}"));
294 return Err((MissReason::ReadFailed(e.to_string()), None));
295 }
296 };
297 report.work.entry_bytes_read = entry.bytes.len() as u64;
298 let started = Instant::now();
299 let layout = envelope::validate_entry(&entry.bytes, id);
300 report.work.validate = started.elapsed();
301 let decoded = layout.and_then(|layout| {
302 let started = Instant::now();
303 let decoded = envelope::decode_entry(&entry.bytes, &layout);
304 report.work.decode = started.elapsed();
305 decoded
306 });
307 match decoded {
308 Ok(result) => {
309 report.work.bytes_decoded = (entry.bytes.len() - envelope::BODY_START) as u64;
310 Ok((result, entry))
311 }
312 Err(e) => {
313 report.warn(format!("result cache: rejected entry {key_hex}: {e}"));
314 let reason = match e {
315 CodecError::Unsupported(version) => MissReason::Unsupported(version),
316 CodecError::IdentityMismatch => MissReason::IdentityMismatch,
317 other => MissReason::Corrupt(other.to_string()),
318 };
319 Err((reason, Some(entry)))
320 }
321 }
322}