1use 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
43pub struct CachedPlan {
45 pub plan: Plan,
46 pub(crate) inputs: PlanInputs,
47}
48
49impl CachedPlan {
50 pub fn desired(&self) -> &DesiredState {
53 &self.inputs.desired
54 }
55
56 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
70pub type OpenStore<'a> = dyn for<'f> Fn(&'f dyn Fs) -> Result<Option<Store<'f>>, CoreError> + 'a;
73
74#[derive(Default)]
76pub struct PlanCache {
77 state: Mutex<State>,
78 computing: Mutex<()>,
80 probes: ProbeCache,
82}
83
84#[derive(Default)]
85struct State {
86 generation: u64,
88 finished: u64,
91 entry: Option<Entry>,
92}
93
94struct Entry {
95 plan: Arc<CachedPlan>,
96 generation: u64,
97 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 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 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 pub fn probes(&self) -> &ProbeCache {
136 &self.probes
137 }
138
139 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 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 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#[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#[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 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
284struct 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 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 fn write_probe(&self) -> Option<crate::access::WriteProbe> {
427 self.inner.write_probe()
428 }
429}