Skip to main content

surjection_core/apply/
cache.rs

1//! The pending-plan cache (#15): one full plan ([`PlanOptions::default`])
2//! and the desired state it was planned from, reused while nothing it was
3//! planned from changed.
4//!
5//! A plan reads the store's working tree, `state/` (ledger, trust, machine),
6//! every client file it plans and the folders detection probes, all through
7//! the [`Fs`]. While a plan is computed, a recording view of the file system
8//! notes each of these reads with what it saw (existence, content hash,
9//! folder listing). The cached plan is served only after every noted read
10//! gives the same answer again, so a store commit, a trust change, a client
11//! file edited by its client, an apply from the CLI or a new project
12//! manifest each make the next request plan again. The project repository
13//! state that git2 reads directly is noted through [`Fs::note_dependency`].
14//!
15//! What the file system does not show:
16//! - [`PlanCache::invalidate`] drops the plan (the app calls it on the drift
17//!   watcher's event);
18//! - a plan that read secret values (a keyring entry, an inline value) is
19//!   *volatile*: it is shared with the requests that waited for it, never
20//!   kept for later ones, because a secret store can change without any
21//!   file changing.
22//!
23//! Requests that arrive while a plan is computed wait for it instead of
24//! planning in parallel (one focus refetch asks for the plan two or three
25//! times at once).
26
27use std::collections::HashMap;
28use std::hash::{DefaultHasher, Hash, Hasher};
29use std::io;
30use std::path::{Path, PathBuf};
31use std::sync::{Arc, Mutex, MutexGuard};
32
33use crate::access::ProbeCache;
34use crate::apply::ApplyEnv;
35use crate::apply::exec::PlanInputs;
36use crate::apply::plan::{self, Plan, PlanOptions};
37use crate::apply::render::DesiredState;
38use crate::error::CoreError;
39use crate::fs::Fs;
40use crate::secrets::scanner::SecretMemory;
41use crate::store::Store;
42
43/// A full plan and what it was planned from.
44pub struct CachedPlan {
45    pub plan: Plan,
46    pub(crate) inputs: PlanInputs,
47}
48
49impl CachedPlan {
50    /// The desired state of the store's working tree (empty without a
51    /// store).
52    pub fn desired(&self) -> &DesiredState {
53        &self.inputs.desired
54    }
55
56    /// The secret memory the plan rendered with.
57    pub fn memory(&self) -> Arc<SecretMemory> {
58        self.inputs.memory.clone()
59    }
60}
61
62impl std::fmt::Debug for CachedPlan {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        f.debug_struct("CachedPlan")
65            .field("plan", &self.plan)
66            .finish_non_exhaustive()
67    }
68}
69
70/// Opens the store (`None` when there is none yet) over the file system it
71/// is given.
72pub type OpenStore<'a> = dyn for<'f> Fn(&'f dyn Fs) -> Result<Option<Store<'f>>, CoreError> + 'a;
73
74/// See the module documentation. One per process (the app's `Core`).
75#[derive(Default)]
76pub struct PlanCache {
77    state: Mutex<State>,
78    /// Held while a plan is computed, so concurrent requests wait for it.
79    computing: Mutex<()>,
80    /// Write probes of the target files, per file fingerprint (#4).
81    probes: ProbeCache,
82}
83
84#[derive(Default)]
85struct State {
86    /// Bumped by [`PlanCache::invalidate`].
87    generation: u64,
88    /// Plans computed so far; a request may share a volatile plan only if
89    /// it finished after the request arrived.
90    finished: u64,
91    entry: Option<Entry>,
92}
93
94struct Entry {
95    plan: Arc<CachedPlan>,
96    generation: u64,
97    /// The value of [`State::finished`] this plan was stored under.
98    finished: u64,
99    volatile: bool,
100    reads: Vec<(Read, Seen)>,
101}
102
103impl std::fmt::Debug for PlanCache {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        f.debug_struct("PlanCache").finish_non_exhaustive()
106    }
107}
108
109impl PlanCache {
110    pub fn new() -> Self {
111        Self::default()
112    }
113
114    /// A cache whose planner runs wait `budget` for their write probes
115    /// (default [`crate::access::PROBE_BUDGET`]).
116    pub fn with_probe_budget(budget: std::time::Duration) -> Self {
117        Self {
118            probes: ProbeCache::with_budget(budget),
119            ..Self::default()
120        }
121    }
122
123    /// Drops the cached plan; the next request plans again. A plan being
124    /// computed now is returned to its requests but not kept.
125    pub fn invalidate(&self) {
126        let mut state = self.lock();
127        state.generation += 1;
128        state.entry = None;
129        self.probes.clear();
130    }
131
132    /// The write probes of client files, kept per file fingerprint; the
133    /// app's views probe files outside the plan (manifests, skill folders)
134    /// through it too.
135    pub fn probes(&self) -> &ProbeCache {
136        &self.probes
137    }
138
139    /// The full plan of this machine: the cached one when everything it was
140    /// planned from reads the same, else a new one. `open` opens the store
141    /// (or returns `None` when there is none yet) over the file system it
142    /// is given, so the store's reads are noted too.
143    pub fn plan(
144        &self,
145        ax: &ApplyEnv<'_>,
146        open: &OpenStore<'_>,
147    ) -> Result<Arc<CachedPlan>, CoreError> {
148        let arrived = self.lock().finished;
149        if let Some(plan) = self.reusable(ax.fs, arrived, false) {
150            return Ok(plan);
151        }
152        let _computing = self
153            .computing
154            .lock()
155            .unwrap_or_else(std::sync::PoisonError::into_inner);
156        // Another request may have planned while this one waited.
157        if let Some(plan) = self.reusable(ax.fs, arrived, true) {
158            return Ok(plan);
159        }
160        let generation = self.lock().generation;
161        let recorder = Recorder {
162            inner: ax.fs,
163            reads: Mutex::new(HashMap::new()),
164            order: Mutex::new(Vec::new()),
165        };
166        let provider_reads = ax.delivery.provider_reads();
167        let recorded = ApplyEnv {
168            fs: &recorder,
169            ..*ax
170        };
171        let store = open(&recorder)?;
172        let inputs = PlanInputs::load(store.as_ref(), &recorded)?;
173        let mut cx = recorded.render_cx(inputs.memory.clone());
174        cx.probes = Some(&self.probes);
175        let plan = plan::plan(
176            &cx,
177            &inputs.desired,
178            &inputs.ledger,
179            &inputs.key,
180            &PlanOptions::default(),
181        )?;
182        drop(store);
183        let volatile = ax.delivery.provider_reads() != provider_reads;
184        let cached = Arc::new(CachedPlan { plan, inputs });
185        let reads = recorder.into_reads();
186        let mut state = self.lock();
187        state.finished += 1;
188        if state.generation == generation {
189            state.entry = Some(Entry {
190                plan: cached.clone(),
191                generation,
192                finished: state.finished,
193                volatile,
194                reads,
195            });
196        }
197        Ok(cached)
198    }
199
200    /// The cached plan if it may serve a request that arrived when
201    /// [`State::finished`] was `arrived`: only when every read it noted
202    /// gives the same answer now (a plan that started before a store commit
203    /// read the store as it was, so it fails this even when it finished
204    /// after the request arrived), and for a volatile plan only when it
205    /// also finished after the request arrived and the request `waited`.
206    fn reusable(&self, fs: &dyn Fs, arrived: u64, waited: bool) -> Option<Arc<CachedPlan>> {
207        let (plan, reads) = {
208            let state = self.lock();
209            let entry = state.entry.as_ref()?;
210            if entry.generation != state.generation {
211                return None;
212            }
213            if entry.volatile && !(waited && entry.finished > arrived) {
214                return None;
215            }
216            (entry.plan.clone(), entry.reads.clone())
217        };
218        reads
219            .iter()
220            .all(|(read, seen)| read.observe(fs) == *seen)
221            .then_some(plan)
222    }
223
224    fn lock(&self) -> MutexGuard<'_, State> {
225        self.state
226            .lock()
227            .unwrap_or_else(std::sync::PoisonError::into_inner)
228    }
229}
230
231/// One read a plan made.
232#[derive(Debug, Clone, PartialEq, Eq, Hash)]
233enum Read {
234    Exists(PathBuf),
235    IsDir(PathBuf),
236    Bytes(PathBuf),
237    Text(PathBuf),
238    Dir(PathBuf),
239    Canonical(PathBuf),
240}
241
242/// What a read saw: a flag, a content hash, a path, or an error kind.
243#[derive(Debug, Clone, PartialEq, Eq)]
244enum Seen {
245    Flag(bool),
246    Hash(u64),
247    Path(PathBuf),
248    Failed(io::ErrorKind),
249}
250
251fn hash_of(bytes: &[u8]) -> u64 {
252    let mut hasher = DefaultHasher::new();
253    bytes.hash(&mut hasher);
254    hasher.finish()
255}
256
257fn seen<T>(result: &io::Result<T>, ok: impl FnOnce(&T) -> Seen) -> Seen {
258    match result {
259        Ok(value) => ok(value),
260        Err(err) => Seen::Failed(err.kind()),
261    }
262}
263
264impl Read {
265    /// What this read gives now.
266    fn observe(&self, fs: &dyn Fs) -> Seen {
267        match self {
268            Read::Exists(path) => Seen::Flag(fs.exists(path)),
269            Read::IsDir(path) => Seen::Flag(fs.is_dir(path)),
270            Read::Bytes(path) => seen(&fs.read(path), |bytes| Seen::Hash(hash_of(bytes))),
271            Read::Text(path) => seen(&fs.read_to_string(path), |text| {
272                Seen::Hash(hash_of(text.as_bytes()))
273            }),
274            Read::Dir(path) => seen(&fs.read_dir(path), |entries| {
275                let mut hasher = DefaultHasher::new();
276                entries.hash(&mut hasher);
277                Seen::Hash(hasher.finish())
278            }),
279            Read::Canonical(path) => seen(&fs.canonicalize(path), |path| Seen::Path(path.clone())),
280        }
281    }
282}
283
284/// The file system as a plan sees it, noting every read and its answer
285/// (the first one, when a path is read twice).
286struct Recorder<'a> {
287    inner: &'a dyn Fs,
288    reads: Mutex<HashMap<Read, Seen>>,
289    order: Mutex<Vec<Read>>,
290}
291
292impl Recorder<'_> {
293    fn note(&self, read: Read, seen: Seen) {
294        let mut reads = self
295            .reads
296            .lock()
297            .unwrap_or_else(std::sync::PoisonError::into_inner);
298        if !reads.contains_key(&read) {
299            reads.insert(read.clone(), seen);
300            self.order
301                .lock()
302                .unwrap_or_else(std::sync::PoisonError::into_inner)
303                .push(read);
304        }
305    }
306
307    /// The reads in the order they were made, so a check stops at the
308    /// first that differs.
309    fn into_reads(self) -> Vec<(Read, Seen)> {
310        let mut reads = self
311            .reads
312            .into_inner()
313            .unwrap_or_else(std::sync::PoisonError::into_inner);
314        self.order
315            .into_inner()
316            .unwrap_or_else(std::sync::PoisonError::into_inner)
317            .into_iter()
318            .filter_map(|read| {
319                let seen = reads.remove(&read)?;
320                Some((read, seen))
321            })
322            .collect()
323    }
324}
325
326impl Fs for Recorder<'_> {
327    fn root(&self) -> Option<&Path> {
328        self.inner.root()
329    }
330
331    fn exists(&self, path: &Path) -> bool {
332        let found = self.inner.exists(path);
333        self.note(Read::Exists(path.to_path_buf()), Seen::Flag(found));
334        found
335    }
336
337    fn is_dir(&self, path: &Path) -> bool {
338        let found = self.inner.is_dir(path);
339        self.note(Read::IsDir(path.to_path_buf()), Seen::Flag(found));
340        found
341    }
342
343    fn read_to_string(&self, path: &Path) -> io::Result<String> {
344        let result = self.inner.read_to_string(path);
345        let seen = seen(&result, |text| Seen::Hash(hash_of(text.as_bytes())));
346        self.note(Read::Text(path.to_path_buf()), seen);
347        result
348    }
349
350    fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
351        let result = self.inner.read(path);
352        let seen = seen(&result, |bytes| Seen::Hash(hash_of(bytes)));
353        self.note(Read::Bytes(path.to_path_buf()), seen);
354        result
355    }
356
357    fn write(&self, path: &Path, contents: &[u8]) -> io::Result<()> {
358        self.inner.write(path, contents)
359    }
360
361    fn write_new(&self, path: &Path, contents: &[u8], like: Option<&Path>) -> io::Result<()> {
362        self.inner.write_new(path, contents, like)
363    }
364
365    fn replace(&self, from: &Path, to: &Path) -> io::Result<()> {
366        self.inner.replace(from, to)
367    }
368
369    fn write_private(&self, path: &Path, contents: &[u8]) -> io::Result<()> {
370        self.inner.write_private(path, contents)
371    }
372
373    fn create_dir_all(&self, path: &Path) -> io::Result<()> {
374        self.inner.create_dir_all(path)
375    }
376
377    fn create_private_dir_all(&self, path: &Path) -> io::Result<()> {
378        self.inner.create_private_dir_all(path)
379    }
380
381    fn remove_file(&self, path: &Path) -> io::Result<()> {
382        self.inner.remove_file(path)
383    }
384
385    fn is_regular_file(&self, path: &Path) -> bool {
386        self.inner.is_regular_file(path)
387    }
388
389    fn overwrite_with_zeros(&self, path: &Path) -> io::Result<()> {
390        self.inner.overwrite_with_zeros(path)
391    }
392
393    fn remove_dir_all(&self, path: &Path) -> io::Result<()> {
394        self.inner.remove_dir_all(path)
395    }
396
397    fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
398        let result = self.inner.read_dir(path);
399        let seen = seen(&result, |entries| {
400            let mut hasher = DefaultHasher::new();
401            entries.hash(&mut hasher);
402            Seen::Hash(hasher.finish())
403        });
404        self.note(Read::Dir(path.to_path_buf()), seen);
405        result
406    }
407
408    fn open_lock_file(&self, path: &Path) -> io::Result<std::fs::File> {
409        self.inner.open_lock_file(path)
410    }
411
412    fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
413        let result = self.inner.canonicalize(path);
414        let seen = seen(&result, |path| Seen::Path(path.clone()));
415        self.note(Read::Canonical(path.to_path_buf()), seen);
416        result
417    }
418
419    fn note_dependency(&self, path: &Path) {
420        let seen = seen(&self.inner.read(path), |bytes| Seen::Hash(hash_of(bytes)));
421        self.note(Read::Bytes(path.to_path_buf()), seen);
422    }
423
424    /// Not a read the plan is checked against: probe results are kept per
425    /// file fingerprint in the cache's [`ProbeCache`] instead.
426    fn write_probe(&self) -> Option<crate::access::WriteProbe> {
427        self.inner.write_probe()
428    }
429}