geolith_tiles_builder/raster/
cache.rs1use std::fs;
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicU64, Ordering};
10
11use geolith::error::{GeolithError, Result};
12use geolith::geometry::mercator::TileCoord;
13
14static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
16
17#[derive(Debug, Clone)]
19pub struct TileCache {
20 root: PathBuf,
21}
22
23impl TileCache {
24 pub fn open(root: &Path) -> Result<Self> {
30 fs::create_dir_all(root)?;
31 Ok(Self {
32 root: root.to_owned(),
33 })
34 }
35
36 fn tile_path(&self, tile: TileCoord) -> PathBuf {
37 self.root
38 .join(tile.z.to_string())
39 .join(tile.x.to_string())
40 .join(format!("{}.bin", tile.y))
41 }
42
43 fn miss_path(&self, tile: TileCoord) -> PathBuf {
44 self.tile_path(tile).with_extension("miss")
45 }
46
47 #[must_use]
49 pub fn tile(&self, tile: TileCoord) -> Option<Vec<u8>> {
50 fs::read(self.tile_path(tile)).ok()
51 }
52
53 #[must_use]
55 pub fn is_missing(&self, tile: TileCoord) -> bool {
56 self.miss_path(tile).exists()
57 }
58
59 pub fn put(&self, tile: TileCoord, bytes: &[u8]) -> Result<()> {
65 self.write_atomic(&self.tile_path(tile), bytes)
66 }
67
68 pub fn mark_missing(&self, tile: TileCoord) -> Result<()> {
74 self.write_atomic(&self.miss_path(tile), &[])
75 }
76
77 fn write_atomic(&self, path: &Path, bytes: &[u8]) -> Result<()> {
78 let Some(parent) = path.parent() else {
79 return Err(GeolithError::RasterSource(format!(
80 "cache path {} has no parent directory",
81 path.display()
82 )));
83 };
84 fs::create_dir_all(parent)?;
85
86 let stem = path
90 .file_name()
91 .and_then(|name| name.to_str())
92 .unwrap_or("tile");
93 let unique = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
94 let tmp = parent.join(format!(".{stem}.{}.{unique}.tmp", std::process::id()));
95
96 crate::fsio::write_file(&tmp, bytes)?;
97 fs::rename(&tmp, path).map_err(|e| {
98 GeolithError::from(e).context(format!("moving {} to {}", tmp.display(), path.display()))
99 })?;
100 Ok(())
101 }
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107
108 fn cache() -> (tempfile::TempDir, TileCache) {
109 let dir = tempfile::tempdir().expect("tempdir");
110 let cache = TileCache::open(dir.path()).expect("open cache");
111 (dir, cache)
112 }
113
114 #[test]
115 fn a_path_without_a_parent_is_an_error() {
116 let (_dir, cache) = cache();
117 assert!(cache.write_atomic(Path::new(""), b"x").is_err());
118 }
119
120 #[test]
121 fn roundtrips_tile_bytes() {
122 let (_dir, cache) = cache();
123 let tile = TileCoord { z: 3, x: 5, y: 2 };
124 assert!(cache.tile(tile).is_none());
125 cache.put(tile, b"jpegbytes").expect("put");
126 assert_eq!(cache.tile(tile).as_deref(), Some(b"jpegbytes".as_slice()));
127 }
128
129 #[test]
130 fn distinguishes_missing_marker_from_uncached() {
131 let (_dir, cache) = cache();
132 let tile = TileCoord { z: 4, x: 1, y: 9 };
133 assert!(!cache.is_missing(tile));
134 cache.mark_missing(tile).expect("mark");
135 assert!(cache.is_missing(tile));
136 assert!(cache.tile(tile).is_none(), "a miss marker is not tile data");
137 }
138
139 #[test]
140 fn survives_reopen_for_resume() {
141 let (dir, cache) = cache();
142 let tile = TileCoord { z: 2, x: 3, y: 1 };
143 cache.put(tile, b"persisted").expect("put");
144 drop(cache);
145 let reopened = TileCache::open(dir.path()).expect("reopen");
146 assert_eq!(
147 reopened.tile(tile).as_deref(),
148 Some(b"persisted".as_slice())
149 );
150 }
151
152 #[test]
153 fn concurrent_writes_to_one_coordinate_never_corrupt_it() {
154 let (_dir, cache) = cache();
155 let payload = vec![0xAB_u8; 64 * 1024];
156
157 for round in 0..40 {
158 let tile = TileCoord {
159 z: 6,
160 x: round,
161 y: 3,
162 };
163 std::thread::scope(|scope| {
164 let c1 = &cache;
165 let c2 = &cache;
166 let p = &payload;
167 scope.spawn(move || c1.put(tile, p).expect("put"));
168 scope.spawn(move || c2.mark_missing(tile).expect("mark"));
169 });
170
171 if let Some(bytes) = cache.tile(tile) {
172 assert_eq!(
173 bytes.len(),
174 payload.len(),
175 "round {round}: a cached tile must be whole, never truncated by a \
176 colliding temp file"
177 );
178 }
179 }
180 }
181
182 #[test]
183 fn leaves_no_tmp_files_behind() {
184 let (dir, cache) = cache();
185 cache
186 .put(TileCoord { z: 1, x: 0, y: 0 }, b"x")
187 .expect("put");
188 cache
189 .mark_missing(TileCoord { z: 1, x: 1, y: 0 })
190 .expect("mark");
191 let mut stack = vec![dir.path().to_owned()];
192 while let Some(d) = stack.pop() {
193 for entry in fs::read_dir(&d).expect("read_dir") {
194 let entry = entry.expect("entry");
195 let path = entry.path();
196 if path.is_dir() {
197 stack.push(path);
198 } else {
199 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
200 assert!(
201 !name.ends_with(".tmp"),
202 "atomic writes must not leave temp files: {}",
203 path.display()
204 );
205 }
206 }
207 }
208 }
209}