Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / fingerprint.rs

fingerprint.rs142 lines · 5.7 KiBRaw
1//! Content fingerprints of input files: what a tool may key a cache guard or a build id on.
2//!
3//! Never a path, an mtime, an inode, a host or a user: two copies of the same bytes anywhere, made
4//! at any time, fingerprint the same, and the archives built from them come out byte-identical.
5//! (The blob-kinds sidecar used to carry the input's mtime, and the archive's build id hashed the
6//! input's absolute path and mtime, so the same planet built on two machines differed.)
7//!
8//! A fingerprint is FNV-1a 64 over the file's length, its first [`SAMPLE_BYTES`] and its last
9//! [`SAMPLE_BYTES`] (the whole file when it is no longer than twice that). That is a few MB of
10//! reads per input, however large the input. It is a change detector, not a proof of identity:
11//! callers that need more mix in what they already know about the content (a `.pbf`'s blob
12//! index, the archive's own tile digest).
13
14use std::io::{Read, Seek, SeekFrom};
15use std::path::Path;
16
17/// Bytes sampled from each end of a file.
18pub const SAMPLE_BYTES: u64 = 4 << 20;
19
20/// FNV-1a 64, the same hash the archive writer uses for its dedup keys: stable, dependency-free,
21/// and defined byte by byte so it cannot depend on platform or word size.
22#[derive(Debug, Clone, Copy)]
23pub struct Fnv(pub u64);
24
25impl Default for Fnv {
26 fn default() -> Self {
27 Fnv(0xcbf2_9ce4_8422_2325)
28 }
29}
30
31impl Fnv {
32 pub fn eat(&mut self, bytes: &[u8]) {
33 for &b in bytes {
34 self.0 ^= b as u64;
35 self.0 = self.0.wrapping_mul(0x100_0000_01b3);
36 }
37 }
38
39 pub fn eat_u64(&mut self, v: u64) {
40 self.eat(&v.to_le_bytes());
41 }
42
43 pub fn finish(&self) -> u64 {
44 self.0
45 }
46}
47
48/// The content fingerprint of one file (see the module docs).
49pub fn file_fingerprint(path: &Path) -> std::io::Result<u64> {
50 let mut file = std::fs::File::open(path)?;
51 let len = file.metadata()?.len();
52 let mut h = Fnv::default();
53 h.eat(b"file/1");
54 h.eat_u64(len);
55 let mut buf = Vec::new();
56 if len <= 2 * SAMPLE_BYTES {
57 file.read_to_end(&mut buf)?;
58 h.eat(&buf);
59 } else {
60 buf.resize(SAMPLE_BYTES as usize, 0);
61 file.read_exact(&mut buf)?;
62 h.eat(&buf);
63 file.seek(SeekFrom::Start(len - SAMPLE_BYTES))?;
64 file.read_exact(&mut buf)?;
65 h.eat(&buf);
66 }
67 Ok(h.finish())
68}
69
70/// The fingerprint of a directory's regular files: each file's name (relative, so the directory's
71/// own location never counts) and [`file_fingerprint`], in name order. Dot-files are skipped:
72/// `planet_build.sh` touches `.ready` in the graph dir as a signal, which is not content.
73pub fn dir_fingerprint(dir: &Path) -> std::io::Result<u64> {
74 let mut names: Vec<std::ffi::OsString> = Vec::new();
75 for entry in std::fs::read_dir(dir)? {
76 let entry = entry?;
77 let name = entry.file_name();
78 if name.to_string_lossy().starts_with('.') || !entry.file_type()?.is_file() {
79 continue;
80 }
81 names.push(name);
82 }
83 names.sort();
84 let mut h = Fnv::default();
85 h.eat(b"dir/1");
86 for name in names {
87 h.eat(name.to_string_lossy().as_bytes());
88 h.eat(&[0]);
89 h.eat_u64(file_fingerprint(&dir.join(&name))?);
90 }
91 Ok(h.finish())
92}
93
94#[cfg(test)]
95mod tests {
96 use super::*;
97
98 fn scratch(name: &str) -> std::path::PathBuf {
99 let d = std::env::temp_dir().join(format!("osm_fp_{}_{name}", std::process::id()));
100 let _ = std::fs::remove_dir_all(&d);
101 std::fs::create_dir_all(&d).unwrap();
102 d
103 }
104
105 /// The same bytes fingerprint the same at another path with another mtime; a change at the
106 /// head, the tail or the length moves it; small files are hashed whole.
107 #[test]
108 fn fingerprints_follow_content_not_place_or_time() {
109 let a = scratch("a");
110 let b = scratch("b");
111 let big: Vec<u8> = (0..(SAMPLE_BYTES as usize * 3)).map(|i| (i * 31 % 251) as u8).collect();
112 std::fs::write(a.join("x.bin"), &big).unwrap();
113 std::thread::sleep(std::time::Duration::from_millis(20));
114 std::fs::write(b.join("x.bin"), &big).unwrap();
115 let fa = file_fingerprint(&a.join("x.bin")).unwrap();
116 assert_eq!(fa, file_fingerprint(&b.join("x.bin")).unwrap());
117 assert_eq!(dir_fingerprint(&a).unwrap(), dir_fingerprint(&b).unwrap());
118 // Signals are not content.
119 std::fs::write(b.join(".ready"), b"").unwrap();
120 assert_eq!(dir_fingerprint(&a).unwrap(), dir_fingerprint(&b).unwrap());
121 for (at, what) in [(0usize, "head"), (big.len() - 1, "tail")] {
122 let mut changed = big.clone();
123 changed[at] ^= 1;
124 std::fs::write(b.join("x.bin"), &changed).unwrap();
125 assert_ne!(fa, file_fingerprint(&b.join("x.bin")).unwrap(), "{what} change missed");
126 assert_ne!(dir_fingerprint(&a).unwrap(), dir_fingerprint(&b).unwrap());
127 }
128 std::fs::write(b.join("x.bin"), &big[1..]).unwrap();
129 assert_ne!(fa, file_fingerprint(&b.join("x.bin")).unwrap(), "length change missed");
130 // A small file is hashed whole: a change anywhere moves it.
131 std::fs::write(a.join("s.bin"), b"0123456789").unwrap();
132 let fs = file_fingerprint(&a.join("s.bin")).unwrap();
133 std::fs::write(a.join("s.bin"), b"0123x56789").unwrap();
134 assert_ne!(fs, file_fingerprint(&a.join("s.bin")).unwrap());
135 // A renamed file inside a directory is a different directory.
136 std::fs::write(b.join("x.bin"), &big).unwrap();
137 std::fs::rename(b.join("x.bin"), b.join("y.bin")).unwrap();
138 assert_ne!(dir_fingerprint(&a).unwrap(), dir_fingerprint(&b).unwrap());
139 let _ = std::fs::remove_dir_all(&a);
140 let _ = std::fs::remove_dir_all(&b);
141 }
142}