1use core::fmt;
4use std::fs;
5use std::path::{Path, PathBuf};
6
7use arcsec_core::ArcsecError;
8
9use crate::error::{Error, Result};
10use crate::index::{Existing, Freshness, freshness, index_files};
11use crate::registry::{
12 Archive, Entry, Purpose, REGISTRY, astap_file_count, expected_file_count, files_of,
13 installed_size, is_installed,
14};
15
16#[must_use]
20pub fn recommend(purpose: Purpose, fov_deg: f64) -> Option<&'static Entry> {
21 REGISTRY
22 .iter()
23 .filter(|e| e.purpose == purpose)
24 .filter(|e| matches!(e.fov, Some((lo, hi)) if fov_deg >= lo && fov_deg <= hi))
25 .min_by_key(|e| e.bytes)
26}
27
28#[must_use]
31pub fn download_disk(e: &Entry) -> u64 {
32 match e.archive {
33 Archive::Loose => e.bytes,
34 Archive::Zip | Archive::Deb => e.bytes.saturating_mul(2),
35 }
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct Removed {
41 pub files: usize,
43 pub bytes: u64,
45}
46
47pub fn remove(dir: &Path, e: &Entry) -> Result<Removed> {
58 let files = files_of(dir, e);
59 let mut freed = 0u64;
60 for p in &files {
61 freed += fs::metadata(p).map_or(0, |m| m.len());
62 fs::remove_file(p).map_err(Error::io(p))?;
63 }
64 Ok(Removed {
65 files: files.len(),
66 bytes: freed,
67 })
68}
69
70#[derive(Debug)]
72#[non_exhaustive]
73pub enum Problem {
74 Truncated(PathBuf),
77 Unreadable {
79 path: PathBuf,
81 error: std::io::Error,
83 },
84 FileCount {
87 expected: usize,
89 found: usize,
91 },
92}
93
94impl fmt::Display for Problem {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 match self {
97 Self::Truncated(p) => write!(f, "{} is truncated", p.display()),
98 Self::Unreadable { path, error } => write!(f, "{}: {error}", path.display()),
99 Self::FileCount { expected, found } => {
100 write!(f, "expected {expected} files, found {found}")
101 }
102 }
103 }
104}
105
106#[derive(Debug)]
108pub struct CatalogueCheck {
109 pub entry: &'static Entry,
111 pub files: usize,
113 pub bytes: u64,
115 pub problems: Vec<Problem>,
117}
118
119#[derive(Debug)]
121pub struct IndexCheck {
122 pub path: PathBuf,
124 pub health: IndexHealth,
126}
127
128#[derive(Debug)]
130#[non_exhaustive]
131pub enum IndexHealth {
132 Sound {
134 patterns: usize,
136 bytes: u64,
138 existing: Option<Existing>,
140 freshness: Option<Freshness>,
143 },
144 Stale {
147 source: String,
149 },
150 Broken(ArcsecError),
152}
153
154impl IndexHealth {
155 #[must_use]
157 pub const fn is_problem(&self) -> bool {
158 !matches!(self, Self::Sound { .. })
159 }
160}
161
162#[derive(Debug, Default)]
164pub struct Verification {
165 pub catalogues: Vec<CatalogueCheck>,
167 pub indexes: Vec<IndexCheck>,
169}
170
171impl Verification {
172 #[must_use]
175 pub fn problems(&self) -> usize {
176 self.catalogues
177 .iter()
178 .map(|c| c.problems.len())
179 .sum::<usize>()
180 + self
181 .indexes
182 .iter()
183 .filter(|i| i.health.is_problem())
184 .count()
185 }
186
187 #[must_use]
189 pub fn is_empty(&self) -> bool {
190 self.catalogues.is_empty() && self.indexes.is_empty()
191 }
192}
193
194#[must_use]
198pub fn verify(dir: &Path) -> Verification {
199 let mut v = Verification::default();
200 for e in REGISTRY {
201 if !is_installed(dir, e) {
202 continue;
203 }
204 let files = files_of(dir, e);
205 let mut problems = Vec::new();
206 for p in &files {
207 match fs::metadata(p) {
208 Ok(m) if m.len() < 120 => problems.push(Problem::Truncated(p.clone())),
209 Err(error) => problems.push(Problem::Unreadable {
210 path: p.clone(),
211 error,
212 }),
213 _ => {}
214 }
215 }
216 if let Some(want) = astap_file_count(dir, e).or_else(|| expected_file_count(e))
217 && files.len() != want
218 {
219 problems.push(Problem::FileCount {
220 expected: want,
221 found: files.len(),
222 });
223 }
224 v.catalogues.push(CatalogueCheck {
225 entry: e,
226 files: files.len(),
227 bytes: installed_size(dir, e),
228 problems,
229 });
230 }
231 for path in index_files(dir) {
232 let opened = arcsec_core::index::BlindIndex::open(&path).and_then(|ix| {
233 ix.validate()?;
234 Ok(ix)
235 });
236 let health = match opened {
237 Ok(ix) => {
238 let existing = Existing::open(&path);
239 let fresh = existing.as_ref().map(|ex| freshness(ex, dir));
240 if fresh == Some(Freshness::Changed) {
241 IndexHealth::Stale {
242 source: ix.source().to_string(),
243 }
244 } else {
245 IndexHealth::Sound {
246 patterns: ix.n_patterns(),
247 bytes: ix.file_size() as u64,
248 existing,
249 freshness: fresh,
250 }
251 }
252 }
253 Err(e) => IndexHealth::Broken(e),
254 };
255 v.indexes.push(IndexCheck { path, health });
256 }
257 v
258}
259
260#[cfg(test)]
261mod tests {
262 use super::*;
263 use crate::registry::find;
264 use crate::test_support::{TempDir, write_001_db};
265
266 #[test]
267 fn disk_needed_for_downloads_counts_archive_and_contents() {
268 let d80 = find("d80").unwrap();
269 assert_eq!(download_disk(d80), 2 * d80.bytes);
270 let anet = find("anet-4100").unwrap();
271 assert_eq!(download_disk(anet), anet.bytes);
272 }
273
274 #[test]
275 fn recommendations_are_the_smallest_covering_download() {
276 let id = |p, f| recommend(p, f).map(|e| e.id);
277 assert_eq!(id(Purpose::Solving, 1.5), Some("d05"));
278 assert_eq!(id(Purpose::Solving, 0.25), Some("d50"));
279 assert_eq!(id(Purpose::Solving, 10.0), Some("g05"));
280 assert_eq!(id(Purpose::Solving, 40.0), Some("w08"));
281 assert_eq!(id(Purpose::Solving, 0.1), None);
282 assert_eq!(id(Purpose::Photometry, 1.5), Some("v05"));
283 }
284
285 #[test]
286 fn verify_and_remove_a_tiny_database() {
287 let dir = TempDir::new("verify");
288 let d = dir.path();
289 assert!(verify(d).is_empty());
290 write_001_db(d, "w08", 50, 1);
291 let v = verify(d);
292 assert_eq!(v.catalogues.len(), 1);
293 assert_eq!(v.catalogues[0].entry.id, "w08");
294 assert_eq!(v.problems(), 0, "{v:?}");
295
296 std::fs::write(d.join("w08_0101.001"), b"short").unwrap();
298 std::fs::write(d.join("w08.arcsecix"), b"not an index").unwrap();
299 let v = verify(d);
300 assert!(matches!(
301 v.catalogues[0].problems[..],
302 [Problem::Truncated(_)]
303 ));
304 assert!(matches!(v.indexes[0].health, IndexHealth::Broken(_)));
305 assert_eq!(v.problems(), 2);
306
307 let r = remove(d, find("w08").unwrap()).unwrap();
308 assert_eq!(r, Removed { files: 1, bytes: 5 });
309 assert!(!is_installed(d, find("w08").unwrap()));
310 }
311}