Skip to main content

latexml_post/
resource_cache.rs

1//! The resource cache: the names the generated and copied resources of one destination directory take, kept across
2//! the split pages of a run and across runs into the same directory.
3//!
4//! Port of the part of Perl's document cache the resource names live in ([`crate::document::DocCache`], persisted as
5//! [`crate::document::CACHE_FILE`] in the destination directory): `generateResourcePathname`'s counter under
6//! `_max_<subdir>_<prefix>_counter_` (`Post.pm` L192-200) and Graphics' `key → "dest|w|h"` entries
7//! (`Post/Graphics.pm` L245-262, L331). A name's owner is its source (path relative to the destination directory,
8//! page, crop and turn, type; a size only where a vector render's root carries it, OD #1034), as a Perl key is: our
9//! entries `_owner_<name>`, `_name_<owner>` and `_source_<name>` keep it, and `_holds_<name>` the bytes the name was
10//! last written with, so an edited image is a new key (the content digest replaces Perl's timestamp check) written
11//! again into the name its source owns.
12//! `_content_<bytes>` lets a source with the same bytes share that file while its owner is named in the same run with
13//! them (the pages of one document); another document's file is never shared, as that document may write other bytes
14//! into it later, under a page this run does not rewrite. A copy keeping its path shares none (Perl L289-300).
15//! Divergences (OXIDIZED_DESIGN_DIVERGENCES #1157): an entry stores the name only (Perl's width and height let it skip
16//! a conversion, which the content-addressed `graphics_cache` serves here); a converted or generated name is kept
17//! across an edit (Perl generates a new `xN`); a kept name (a copy's relative path, a converted image's stem) another
18//! source owns falls back to a generated `xN`, where Perl overwrote it (issue 995); and a stored name is written only
19//! when the request could have been given it ([`Checks`]). Each [`resolve`] is one `IMMEDIATE` transaction, so
20//! processes naming into one folder at once through the file never hand out one name to two sources. A name new to the
21//! store is never given over a file in the folder the request may not write ([`Checks::on_disk`]): with the store on
22//! its file (a new one too, made where a cache was deleted) any file it does not own; in memory in place of its file
23//! (it could not be opened, or the transaction failed and runs again there) a file holding other bytes than the request
24//! writes, so a rerun takes its own files again. One that could not copy the file's entries does not know a file's
25//! owner: a file of another document holding the same bytes is taken as the request's own (OD #1157 (10)).
26
27use std::collections::HashMap;
28
29use rusqlite::Connection;
30
31use crate::document::{kv_get, kv_put};
32
33/// What a resource's name is first tried as.
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub enum Proposal {
36  /// A copy's path relative to the destination directory, kept when no other source owns it
37  /// (`Post/Graphics.pm` L292-300).
38  Kept(String),
39  /// A converted image's source stem (`plot` for `a/plot.pdf`), with the destination type appended: a readability
40  /// name Perl does not keep (it generates `xN` for every conversion, `Post/Graphics.pm` L318-319; witness
41  /// 2606.30620).
42  Stem(String),
43  /// A generated `<prefix>N` (`generateResourcePathname`).
44  Generated,
45}
46
47/// One resource to name.
48#[derive(Clone, Debug)]
49pub struct Request {
50  /// Perl's cache key (`ref($self):reldir/name.srctype.type|transform`) with the source's content digest.
51  pub key:      String,
52  /// What the destination file's bytes are made of (the source's bytes, page, type, crop and turn; a size only where
53  /// a vector render's root carries it): requests with the same bytes share one file.
54  pub bytes:    String,
55  /// Who owns the names the request is given: its source, transform and type, so an edited source keeps them.
56  pub owner:    String,
57  /// The source, relative to the destination directory, kept with the names it owns ([`Checks::vouch`]).
58  pub source:   String,
59  /// The source's content digest (hex), or its path when unreadable.
60  pub identity: String,
61  pub proposal: Proposal,
62  /// The destination's file type (extension), empty for none.
63  pub ext:      String,
64  /// A vector render `<name>.svg` may be written beside it, so that name is claimed too.
65  pub svg_alt:  bool,
66  /// A copy (named after the conversions of its page when it cannot keep its path) or a conversion.
67  pub copy:     bool,
68  /// What the destination file will hold ([`Checks::on_disk`]).
69  pub output:   Output,
70}
71
72/// What a resource's file will hold, so that a store in memory tells the file an earlier run wrote for it.
73#[derive(Clone, Debug, PartialEq, Eq)]
74pub enum Output {
75  /// The source's bytes (a copy).
76  Source,
77  /// The source's page (`None`: the default) rendered, as the graphics cache keeps it.
78  Render(Option<u32>),
79  /// Known only once made (a cropped or turned image).
80  Made,
81}
82
83/// A resource's destination, relative to the destination directory, and its vector render's when it may have one.
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct ResourceName {
86  pub dest: String,
87  pub alt:  Option<String>,
88}
89
90/// How a request was named.
91#[derive(Clone, Debug)]
92pub struct Resolved {
93  pub name:      ResourceName,
94  /// A name not stored under the request's key: a kept path, a stem, a generated one, or its source's earlier name.
95  pub allocated: bool,
96}
97
98/// Whether a file of the name exists in the destination directory that the request may not write ([`Checks::on_disk`]).
99pub type OnDisk<'a> = &'a dyn Fn(&Request, &ResourceName) -> bool;
100
101/// What the caller knows of the destination directory.
102pub struct Checks<'a> {
103  /// Perl's `resource_prefix` (`x` unless set).
104  pub prefix:  &'a str,
105  /// Whether a name may be written: a copy's kept path outside this run's site directory may not.
106  pub usable:  &'a dyn Fn(&ResourceName) -> bool,
107  /// Whether `name`, owned by the source at `source` (relative to the destination directory), is the name that source
108  /// takes and the source holds the request's bytes: another source's kept path or stem a request may share. Only a
109  /// relative path to a regular file is read.
110  pub vouch:   &'a dyn Fn(&Request, &ResourceName, &str) -> bool,
111  /// Whether a file of the name exists in the destination directory that the request may not write, asked of a name
112  /// the store does not know: the store may not know every file earlier runs wrote (a deleted cache, an unusable one).
113  /// `None` for a store in memory from the start (`--nocache`), whose names restart and overwrite as Perl's do.
114  pub on_disk: Option<OnDisk<'a>>,
115  /// The cache file a Warning names.
116  pub cache:   &'a str,
117  /// Report a Warning (`unexpected`, `cache`): the caller emits it once the transaction is done, as a transaction run
118  /// again in memory meets the same entries.
119  pub warn:    &'a dyn Fn(String),
120}
121
122/// The counter Perl's `generateResourcePathname` keeps for `prefix` (`Post.pm` L194-196; no `resource_directory`).
123pub fn counter_key(prefix: &str) -> String { format!("_max__{prefix}_counter_") }
124
125/// Name every request, page by page, on `conn` (in the caller's `IMMEDIATE` transaction): a name stored for its key,
126/// its source or its content, else, within a page, the copies that keep their path first, then the conversions, then
127/// the copies that take a generated name, each in node order (the order the page's names were handed out in before).
128pub fn resolve(
129  conn: &Connection,
130  checks: &Checks,
131  pages: &[Vec<Request>],
132) -> rusqlite::Result<Vec<Vec<Resolved>>> {
133  let counter = counter_key(checks.prefix);
134  // The sources this run names, with their bytes: only their files are shared, while they hold the same bytes.
135  let now: HashMap<&str, &str> = pages
136    .iter()
137    .flatten()
138    .map(|r| (r.owner.as_str(), r.bytes.as_str()))
139    .collect();
140  let mut out = Vec::with_capacity(pages.len());
141  for page in pages {
142    let mut names: Vec<Option<Resolved>> = vec![None; page.len()];
143    // Copies keeping their path.
144    for (i, r) in page.iter().enumerate() {
145      if let (true, Proposal::Kept(rel)) = (r.copy, &r.proposal) {
146        names[i] = place(conn, checks, &now, r, Some(name_of(rel, false)), true)?;
147      }
148    }
149    // Conversions, then the copies left.
150    for copies in [false, true] {
151      for (i, r) in page.iter().enumerate() {
152        if r.copy != copies || names[i].is_some() {
153          continue;
154        }
155        let proposed = match &r.proposal {
156          Proposal::Stem(stem) if !copies => Some(name_of(&with_ext(stem, &r.ext), r.svg_alt)),
157          _ => None,
158        };
159        // A copy whose kept path is taken looks its stored names up again (a copy since may share its bytes), its
160        // corrupt ones reported already.
161        let warn = !matches!((r.copy, &r.proposal), (true, Proposal::Kept(_)));
162        names[i] = match place(conn, checks, &now, r, proposed, warn)? {
163          Some(found) => Some(found),
164          None => Some(generate(conn, checks, r, &counter)?),
165        };
166      }
167    }
168    out.push(names.into_iter().flatten().collect());
169  }
170  Ok(out)
171}
172
173fn with_ext(stem: &str, ext: &str) -> String {
174  if ext.is_empty() {
175    stem.to_string()
176  } else {
177    format!("{stem}.{ext}")
178  }
179}
180
181/// `dest`, and the `.svg` of its stem when a vector render may be written beside it.
182fn name_of(dest: &str, svg_alt: bool) -> ResourceName {
183  let stem = dest.rsplit_once('.').map_or(dest, |(stem, _)| stem);
184  ResourceName {
185    dest: dest.to_string(),
186    alt:  svg_alt.then(|| format!("{stem}.svg")),
187  }
188}
189
190/// The name stored under the request's key, its source's or its content's, else `proposed` when no other source
191/// owns it, else `None`. A stored name no request could have is reported when `warn`.
192fn place(
193  conn: &Connection,
194  checks: &Checks,
195  now: &HashMap<&str, &str>,
196  r: &Request,
197  proposed: Option<ResourceName>,
198  warn: bool,
199) -> rusqlite::Result<Option<Resolved>> {
200  // A copy offered its kept path is that path or none: it shares no other source's file of the same bytes, as Perl
201  // copies each to its own path (`Post/Graphics.pm` L289-300).
202  let keeps = r.copy && matches!(r.proposal, Proposal::Kept(_)) && proposed.is_some();
203  // Perl's value, `dest|w|h`.
204  let by_key =
205    kv_get(conn, &r.key)?.map(|value| value.split('|').next().unwrap_or_default().to_string());
206  let by_owner = kv_get(conn, &format!("_name_{}", r.owner))?;
207  let by_content = if keeps {
208    None
209  } else {
210    kv_get(conn, &format!("_content_{}", r.bytes))?
211  };
212  // The first two are names this source was given: one no request could have is a corrupt or planted entry.
213  let mut tried: Vec<String> = Vec::new();
214  for (dest, given, keyed) in [
215    (by_key, true, true),
216    (by_owner, true, false),
217    (by_content, false, false),
218  ] {
219    let Some(dest) = dest.filter(|dest| !tried.contains(dest)) else {
220      continue;
221    };
222    tried.push(dest.clone());
223    let name = name_of(&dest, r.svg_alt);
224    let Some(own) = reusable(conn, checks, now, r, &name, warn && given, !keeps)? else {
225      continue;
226    };
227    if own {
228      take(conn, r, &name)?;
229    } else {
230      share(conn, r, &name)?;
231    }
232    return Ok(Some(Resolved { name, allocated: !keyed }));
233  }
234  let Some(name) = proposed else {
235    return Ok(None);
236  };
237  // A kept path or a stem the store does not know may be a file of another document's (issue 995 review: an unusable
238  // cache, and a second document's `figs/a.png` written over the first's).
239  let taken = claimed(conn, &name, Some(&r.owner))?
240    || checks.on_disk.is_some_and(|on_disk| on_disk(r, &name));
241  if taken {
242    return Ok(None);
243  }
244  take(conn, r, &name)?;
245  Ok(Some(Resolved { name, allocated: true }))
246}
247
248/// Whether a stored `name` serves `r`: `Some(true)` when `r`'s source owns it (or no source does and `r` could be
249/// given it), `Some(false)` when `r` may `share` and shares the file of another source of this run holding its bytes,
250/// `None` when it does not serve. A name no request of `r`'s type could have is reported when `warn` (a Warning) and
251/// never written.
252fn reusable(
253  conn: &Connection,
254  checks: &Checks,
255  now: &HashMap<&str, &str>,
256  r: &Request,
257  name: &ResourceName,
258  warn: bool,
259  share: bool,
260) -> rusqlite::Result<Option<bool>> {
261  let given = own_name(r, &name.dest) || generated_name(checks, r, &name.dest);
262  if !given && !shareable_name(r, &name.dest) {
263    if warn {
264      (checks.warn)(format!(
265        "The cache {} names {} for {}, a name no {} image is given; it is ignored",
266        checks.cache, name.dest, r.source, r.ext
267      ));
268    }
269    return Ok(None);
270  }
271  if !(checks.usable)(name) {
272    return Ok(None);
273  }
274  // A source owns only its kept path, its stem or a generated name.
275  let owner = kv_get(conn, &format!("_owner_{}", name.dest))?;
276  let Some(owner) = owner.filter(|owner| *owner != r.owner) else {
277    return Ok(given.then_some(true));
278  };
279  if !share {
280    return Ok(None);
281  }
282  // Another source's file, only while that source is named in this run with these bytes: a source of another
283  // document (or not in this run) may write other bytes into it later, under a page this run does not rewrite.
284  let holds = kv_get(conn, &format!("_holds_{}", name.dest))?;
285  if holds.as_deref() != Some(r.bytes.as_str())
286    || now.get(owner.as_str()) != Some(&r.bytes.as_str())
287  {
288    return Ok(None);
289  }
290  if given {
291    return Ok(Some(false));
292  }
293  let source = kv_get(conn, &format!("_source_{}", name.dest))?.unwrap_or_default();
294  Ok((checks.vouch)(r, name, &source).then_some(false))
295}
296
297/// Its kept path or its stem.
298fn own_name(r: &Request, dest: &str) -> bool {
299  match &r.proposal {
300    Proposal::Kept(rel) => dest == rel,
301    Proposal::Stem(stem) => dest == with_ext(stem, &r.ext),
302    Proposal::Generated => false,
303  }
304}
305
306/// A `<prefix>N` of its type.
307fn generated_name(checks: &Checks, r: &Request, dest: &str) -> bool {
308  let stem = if r.ext.is_empty() {
309    Some(dest)
310  } else {
311    dest.strip_suffix(&format!(".{}", r.ext))
312  };
313  stem
314    .and_then(|stem| stem.strip_prefix(checks.prefix))
315    .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
316}
317
318/// A name another source of the same bytes may have: of `r`'s type, no hidden file or directory on its path.
319fn shareable_name(r: &Request, dest: &str) -> bool {
320  let family = |ext: &str| match ext.to_ascii_lowercase().as_str() {
321    "jpeg" => "jpg".to_string(),
322    "tiff" => "tif".to_string(),
323    ext => ext.to_string(),
324  };
325  let ext = std::path::Path::new(dest)
326    .extension()
327    .map_or(String::new(), |e| e.to_string_lossy().into_owned());
328  !r.ext.is_empty()
329    && family(&ext) == family(&r.ext)
330    && dest
331      .split(['/', '\\'])
332      .all(|part| !part.is_empty() && (part == ".." || !part.starts_with('.')))
333}
334
335/// The next `<prefix>N` no source owns (Perl `generateResourcePathname`, which skips none) and whose file the request
336/// may write ([`Checks::on_disk`]). A counter that is no count, or has no next, is reported and counted again from 0.
337fn generate(
338  conn: &Connection,
339  checks: &Checks,
340  r: &Request,
341  counter: &str,
342) -> rusqlite::Result<Resolved> {
343  // A planted `u64::MAX` wrapped to `x0` (issue 995 review, round 7).
344  let unusable = |value: &str| {
345    (checks.warn)(format!(
346      "The cache {} holds {value} for {counter}, no count with a next one; names are counted again from {}1",
347      checks.cache, checks.prefix
348    ))
349  };
350  let stored = kv_get(conn, counter)?;
351  let mut n: u64 = match stored.as_deref().map(str::parse) {
352    None => 0,
353    Some(Ok(n)) => n,
354    Some(Err(_)) => {
355      unusable(stored.as_deref().unwrap_or_default());
356      0
357    },
358  };
359  let name = loop {
360    n = n.checked_add(1).unwrap_or_else(|| {
361      unusable(&n.to_string());
362      1
363    });
364    let name = name_of(
365      &with_ext(&format!("{}{n}", checks.prefix), &r.ext),
366      r.svg_alt,
367    );
368    if !claimed(conn, &name, None)? && !checks.on_disk.is_some_and(|on_disk| on_disk(r, &name)) {
369      break name;
370    }
371  };
372  kv_put(conn, counter, Some(&n.to_string()))?;
373  take(conn, r, &name)?;
374  Ok(Resolved { name, allocated: true })
375}
376
377/// Whether another source than `owner` (any, for `None`) owns one of `name`'s files.
378fn claimed(conn: &Connection, name: &ResourceName, owner: Option<&str>) -> rusqlite::Result<bool> {
379  for part in std::iter::once(&name.dest).chain(&name.alt) {
380    if let Some(found) = kv_get(conn, &format!("_owner_{part}"))?
381      && owner != Some(found.as_str())
382    {
383      return Ok(true);
384    }
385  }
386  Ok(false)
387}
388
389/// `r`'s source owns `name`, which holds `r`'s bytes.
390fn take(conn: &Connection, r: &Request, name: &ResourceName) -> rusqlite::Result<()> {
391  share(conn, r, name)?;
392  for part in std::iter::once(&name.dest).chain(&name.alt) {
393    kv_put(conn, &format!("_owner_{part}"), Some(&r.owner))?;
394  }
395  kv_put(conn, &format!("_holds_{}", name.dest), Some(&r.bytes))?;
396  kv_put(conn, &format!("_source_{}", name.dest), Some(&r.source))?;
397  kv_put(conn, &format!("_name_{}", r.owner), Some(&name.dest))
398}
399
400/// `r`'s key and content name `name`.
401fn share(conn: &Connection, r: &Request, name: &ResourceName) -> rusqlite::Result<()> {
402  kv_put(conn, &r.key, Some(&format!("{}||", name.dest)))?;
403  kv_put(conn, &format!("_content_{}", r.bytes), Some(&name.dest))
404}
405
406#[cfg(test)]
407mod tests {
408  use super::*;
409  use crate::document::{CACHE_FILE, DocCache};
410
411  fn checks<'a>(
412    vouch: &'a dyn Fn(&Request, &ResourceName, &str) -> bool,
413    on_disk: Option<OnDisk<'a>>,
414  ) -> Checks<'a> {
415    Checks {
416      prefix: "x",
417      usable: &|_| true,
418      vouch,
419      on_disk,
420      cache: CACHE_FILE,
421      warn: &|_| {},
422    }
423  }
424
425  /// Name `pages` in `cache`'s store of `dir`, in one transaction, every shared name vouched for.
426  fn resolve_in(cache: &DocCache, dir: Option<&str>, pages: &[Vec<Request>]) -> Vec<Vec<Resolved>> {
427    cache
428      .with_store(dir, |store| {
429        store.immediate(|tx, _| resolve(tx, &checks(&|_, _, _| true, None), pages))
430      })
431      .unwrap()
432  }
433
434  /// A copy of `source` holding `bytes`, proposing its kept path.
435  fn copy(source: &str, bytes: &str, kept: Option<&str>, ext: &str) -> Request {
436    Request {
437      key:      format!("c:{source}|{bytes}"),
438      bytes:    format!("copy|{bytes}"),
439      owner:    format!("copy|{source}"),
440      source:   source.to_string(),
441      identity: bytes.to_string(),
442      proposal: kept.map_or(Proposal::Generated, |k| Proposal::Kept(k.to_string())),
443      ext:      ext.to_string(),
444      svg_alt:  false,
445      copy:     true,
446      output:   Output::Source,
447    }
448  }
449
450  /// A conversion of `source` holding `bytes` to PNG, proposing its stem.
451  fn convert(source: &str, bytes: &str, stem: Option<&str>, svg_alt: bool) -> Request {
452    Request {
453      key: format!("v:{source}|{bytes}"),
454      bytes: format!("png|{bytes}"),
455      owner: format!("png|{source}"),
456      source: source.to_string(),
457      identity: bytes.to_string(),
458      proposal: stem.map_or(Proposal::Generated, |s| Proposal::Stem(s.to_string())),
459      ext: "png".to_string(),
460      svg_alt,
461      copy: false,
462      output: Output::Render(None),
463    }
464  }
465
466  fn dests(pages: &[Vec<Resolved>]) -> Vec<Vec<String>> {
467    pages
468      .iter()
469      .map(|page| page.iter().map(|r| r.name.dest.clone()).collect())
470      .collect()
471  }
472
473  /// Within a page the kept copies first, then the conversions, then the generated copies; a stem or path another
474  /// source owns takes the next `xN`; one content, one file; a key met again keeps its name.
475  #[test]
476  fn names_follow_the_page_order_and_never_clash() {
477    let cache = DocCache::new(false);
478    let pages = vec![
479      vec![
480        copy("../A.svg", "A", None, "svg"),
481        convert("a/plot.pdf", "a", Some("plot"), true),
482        copy("x1.png", "author", Some("x1.png"), "png"),
483      ],
484      vec![
485        convert("b/plot.pdf", "b", Some("plot"), false),
486        copy("plot.svg", "svg", Some("plot.svg"), "svg"),
487        copy("../A2.svg", "A", None, "svg"),
488      ],
489    ];
490    let first = resolve_in(&cache, None, &pages);
491    assert_eq!(dests(&first), [vec!["x1.svg", "plot.png", "x1.png"], vec![
492      "x2.png", "x3.svg", "x1.svg"
493    ]]);
494    assert_eq!(first[0][1].name.alt.as_deref(), Some("plot.svg"));
495    // A second run (or another document into the folder): the same keys keep their names, new content continues
496    // the counter.
497    let again = resolve_in(&cache, None, &[vec![
498      convert("b/plot.pdf", "b", Some("plot"), false),
499      convert("c/plot.pdf", "c", Some("plot"), false),
500    ]]);
501    assert_eq!(dests(&again), [vec!["x2.png", "x4.png"]]);
502    assert!(!again[0][0].allocated && again[0][1].allocated);
503  }
504
505  /// A name's owner is its source: an edited source is a new key written again into the names its source has, a kept
506  /// path, a stem and a generated name alike (issue 995 review B1: `x1.png`, `x2.png`... after an edit, the kept
507  /// file left with the old picture).
508  #[test]
509  fn an_edited_source_keeps_its_names() {
510    let cache = DocCache::new(false);
511    let run = |v: &str| {
512      dests(&resolve_in(&cache, None, &[vec![
513        copy("figs/a.png", v, Some("figs/a.png"), "png"),
514        convert("figs/p.eps", v, Some("p"), false),
515        convert("figs/r.png", &format!("turned {v}"), None, false),
516        copy("../o.svg", v, None, "svg"),
517      ]]))
518    };
519    let names = [vec!["figs/a.png", "p.png", "x1.png", "x2.svg"]];
520    assert_eq!(run("1"), names);
521    assert_eq!(run("2"), names);
522    assert_eq!(run("1"), names);
523  }
524
525  /// A source sharing another's file (same bytes) leaves it when its owner writes other bytes into it, whichever of
526  /// the two is named first; a name no source vouches for is not shared. A copy keeping its path shares none, also
527  /// where a cache of before stored the shared name (KEPTDEDUP: `figs/a.svg` and `figs/b.svg`, one SVG, both
528  /// `figs/a.svg`; Perl `Post/Graphics.pm` L289-300).
529  #[test]
530  fn a_shared_file_is_left_when_its_owner_changes() {
531    let cache = DocCache::new(false);
532    let first = resolve_in(&cache, None, &[vec![
533      copy("../a.png", "X", None, "png"),
534      copy("../b.png", "X", None, "png"),
535    ]]);
536    assert_eq!(dests(&first), [vec!["x1.png", "x1.png"]]);
537    let second = resolve_in(&cache, None, &[vec![
538      copy("../b.png", "X", None, "png"),
539      copy("../a.png", "Y", None, "png"),
540    ]]);
541    assert_eq!(dests(&second), [vec!["x2.png", "x1.png"]]);
542    let kept = [vec![
543      copy("a.png", "X", Some("a.png"), "png"),
544      copy("b.png", "X", Some("b.png"), "png"),
545      copy("c.png", "X", Some("c.png"), "png"),
546    ]];
547    let shared_before = DocCache::new(false);
548    shared_before.with_store(None, |store| {
549      store.immediate(|tx, _| {
550        kv_put(tx, "c:b.png|X", Some("a.png||"))?;
551        kv_put(tx, "_content_copy|X", Some("a.png"))?;
552        kv_put(tx, "_owner_a.png", Some("copy|a.png"))?;
553        kv_put(tx, "_holds_a.png", Some("copy|X"))
554      })
555    });
556    for cache in [DocCache::new(false), shared_before] {
557      for _run in 0..2 {
558        assert_eq!(dests(&resolve_in(&cache, None, &kept)), [vec![
559          "a.png", "b.png", "c.png"
560        ]]);
561      }
562    }
563    let unvouched = DocCache::new(false);
564    let pages = [vec![
565      convert("a/plot.pdf", "X", Some("plot"), false),
566      convert("b/fig.pdf", "X", Some("fig"), false),
567    ]];
568    let names = unvouched
569      .with_store(None, |store| {
570        store.immediate(|tx, _| resolve(tx, &checks(&|_, _, _| false, None), &pages))
571      })
572      .unwrap();
573    assert_eq!(dests(&names), [vec!["plot.png", "fig.png"]]);
574    // Vouched for, two conversions of one content share one file, as two copies with generated names do.
575    let vouched = resolve_in(&DocCache::new(false), None, &[pages[0].clone(), vec![
576      copy("../p.svg", "S", None, "svg"),
577      copy("../q.svg", "S", None, "svg"),
578    ]]);
579    assert_eq!(dests(&vouched), [vec!["plot.png", "plot.png"], vec![
580      "x1.svg", "x1.svg"
581    ]]);
582  }
583
584  /// A file is shared with another document's image of the same bytes never: that document may later write other
585  /// bytes into it, under a page this run does not rewrite (issue 995 review: `d1` and `d2` into one folder both on
586  /// `x1.png`; `d1`'s image edited and `d1` alone run again, `d2.html` showed `d1`'s new picture). The pages of one
587  /// run share it.
588  #[test]
589  fn another_documents_file_is_never_shared() {
590    let cache = DocCache::new(false);
591    let d1 = resolve_in(&cache, None, &[vec![copy("../c1/a.png", "X", None, "png")]]);
592    let d2 = resolve_in(&cache, None, &[vec![copy("../c2/b.png", "X", None, "png")]]);
593    let d1_edited = resolve_in(&cache, None, &[vec![copy("../c1/a.png", "Y", None, "png")]]);
594    let both = resolve_in(&cache, None, &[
595      vec![copy("../c3/c.png", "Z", None, "png")],
596      vec![copy("../c4/d.png", "Z", None, "png")],
597    ]);
598    let all = [dests(&d1), dests(&d2), dests(&d1_edited), dests(&both)].concat();
599    assert_eq!(all, [["x1.png"], ["x2.png"], ["x1.png"], ["x3.png"], [
600      "x3.png"
601    ]]);
602  }
603
604  /// A stored name no request could have been given (another type, a hidden path) is never written, nor a name a
605  /// source is recorded to own that is neither its kept path, its stem nor a generated one; a generated name of the
606  /// request's type no source owns is.
607  #[test]
608  fn a_planted_name_is_ignored() {
609    let cache = DocCache::new(false);
610    let pages = [vec![
611      copy("a.png", "A", Some("a.png"), "png"),
612      copy("../b.png", "B", None, "png"),
613      copy("../c.png", "C", None, "png"),
614      copy("../d.png", "D", None, "png"),
615    ]];
616    cache.with_store(None, |store| {
617      store.immediate(|tx, _| {
618        kv_put(tx, "c:a.png|A", Some("Ch1.html||"))?;
619        kv_put(tx, "c:../b.png|B", Some(".hidden/evil.png||"))?;
620        kv_put(tx, "c:../c.png|C", Some("x7.png||"))?;
621        kv_put(tx, "_name_copy|../d.png", Some("figs/other.png"))?;
622        kv_put(tx, "_owner_figs/other.png", Some("copy|../d.png"))
623      })
624    });
625    assert_eq!(dests(&resolve_in(&cache, None, &pages)), [vec![
626      "a.png", "x1.png", "x7.png", "x2.png"
627    ]]);
628  }
629
630  /// A store that fell back to memory skips a generated name, a stem or a kept path whose file holds other bytes, and
631  /// takes one holding the request's own: `x1.png` holds `a/plot.pdf`'s render, `plot.png`, `x2.png` and
632  /// `figs/k.png` other images (issue 995 review, round 7: a kept path was not asked, and a second document's
633  /// `figs/a.png` was written over the first's).
634  #[test]
635  fn a_store_in_memory_skips_files_on_disk() {
636    let on_disk = |r: &Request, name: &ResourceName| match name.dest.as_str() {
637      "x1.png" => r.identity != "a",
638      "plot.png" | "x2.png" | "figs/k.png" => true,
639      _ => false,
640    };
641    let pages = [vec![
642      convert("a/plot.pdf", "a", Some("plot"), false),
643      copy("../b.png", "b", None, "png"),
644      copy("figs/k.png", "k", Some("figs/k.png"), "png"),
645      copy("figs/m.png", "m", Some("figs/m.png"), "png"),
646    ]];
647    let names = DocCache::new(true)
648      .with_store(None, |store| {
649        store.immediate(|tx, _| resolve(tx, &checks(&|_, _, _| true, Some(&on_disk)), &pages))
650      })
651      .unwrap();
652    assert_eq!(dests(&names), [vec![
653      "x1.png",
654      "x3.png",
655      "x4.png",
656      "figs/m.png"
657    ]]);
658  }
659
660  /// A counter planted with no next count (`u64::MAX`, which wrapped to `x0`) or with none at all is reported and
661  /// counted again from `x1`, past the files the on-disk check finds (`x1.png` here).
662  #[test]
663  fn a_counter_with_no_next_counts_again() {
664    for planted in [u64::MAX.to_string(), "seven".to_string()] {
665      let warnings = std::cell::RefCell::new(Vec::new());
666      let warn = |w: String| warnings.borrow_mut().push(w);
667      let on_disk = |_: &Request, name: &ResourceName| name.dest == "x1.png";
668      let pages = [vec![copy("../b.png", "b", None, "png")]];
669      let names = DocCache::new(false)
670        .with_store(None, |store| {
671          store.immediate(|tx, _| {
672            kv_put(tx, &counter_key("x"), Some(&planted))?;
673            let checks = Checks {
674              warn: &warn,
675              ..checks(&|_, _, _| true, Some(&on_disk))
676            };
677            let names = resolve(tx, &checks, &pages)?;
678            Ok((names, kv_get(tx, &counter_key("x"))?))
679          })
680        })
681        .unwrap();
682      assert_eq!(
683        (dests(&names.0), names.1.as_deref(), warnings.into_inner()),
684        (vec![vec!["x2.png".to_string()]], Some("2"), vec![format!(
685          "The cache {CACHE_FILE} holds {planted} for _max__x_counter_, no count with a next one; names are \
686           counted again from x1"
687        )])
688      );
689    }
690  }
691
692  /// Two processes allocating into one cache file at once never hand out one name twice.
693  #[test]
694  fn concurrent_tables_on_one_file_never_share_a_name() {
695    let dir = tempfile::tempdir().unwrap();
696    let dir_str = dir.path().to_string_lossy().into_owned();
697    let names: Vec<Vec<String>> = std::thread::scope(|s| {
698      let handles: Vec<_> = (0..8)
699        .map(|t| {
700          let dir_str = dir_str.clone();
701          s.spawn(move || {
702            let cache = DocCache::new(false);
703            (0..20)
704              .map(|i| {
705                let r = copy(&format!("../k{t}_{i}"), &format!("c{t}_{i}"), None, "png");
706                resolve_in(&cache, Some(&dir_str), &[vec![r]])[0][0]
707                  .name
708                  .dest
709                  .clone()
710              })
711              .collect()
712          })
713        })
714        .collect();
715      handles.into_iter().map(|h| h.join().unwrap()).collect()
716    });
717    let mut all: Vec<String> = names.into_iter().flatten().collect();
718    all.sort();
719    let count = all.len();
720    all.dedup();
721    assert_eq!((all.len(), count), (160, 160));
722    assert!(dir.path().join(CACHE_FILE).exists());
723    assert!(!dir.path().join(format!("{CACHE_FILE}-wal")).exists());
724  }
725}