1use std::collections::HashMap;
28
29use rusqlite::Connection;
30
31use crate::document::{kv_get, kv_put};
32
33#[derive(Clone, Debug, PartialEq, Eq)]
35pub enum Proposal {
36 Kept(String),
39 Stem(String),
43 Generated,
45}
46
47#[derive(Clone, Debug)]
49pub struct Request {
50 pub key: String,
52 pub bytes: String,
55 pub owner: String,
57 pub source: String,
59 pub identity: String,
61 pub proposal: Proposal,
62 pub ext: String,
64 pub svg_alt: bool,
66 pub copy: bool,
68 pub output: Output,
70}
71
72#[derive(Clone, Debug, PartialEq, Eq)]
74pub enum Output {
75 Source,
77 Render(Option<u32>),
79 Made,
81}
82
83#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct ResourceName {
86 pub dest: String,
87 pub alt: Option<String>,
88}
89
90#[derive(Clone, Debug)]
92pub struct Resolved {
93 pub name: ResourceName,
94 pub allocated: bool,
96}
97
98pub type OnDisk<'a> = &'a dyn Fn(&Request, &ResourceName) -> bool;
100
101pub struct Checks<'a> {
103 pub prefix: &'a str,
105 pub usable: &'a dyn Fn(&ResourceName) -> bool,
107 pub vouch: &'a dyn Fn(&Request, &ResourceName, &str) -> bool,
111 pub on_disk: Option<OnDisk<'a>>,
115 pub cache: &'a str,
117 pub warn: &'a dyn Fn(String),
120}
121
122pub fn counter_key(prefix: &str) -> String { format!("_max__{prefix}_counter_") }
124
125pub 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 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 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 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 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
181fn 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
190fn 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 let keeps = r.copy && matches!(r.proposal, Proposal::Kept(_)) && proposed.is_some();
203 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 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 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
248fn 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 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 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
297fn 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
306fn 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
318fn 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
335fn generate(
338 conn: &Connection,
339 checks: &Checks,
340 r: &Request,
341 counter: &str,
342) -> rusqlite::Result<Resolved> {
343 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
377fn 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
389fn 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
400fn 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 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 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 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 #[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 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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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}