1use super::*;
17use super::readonly::ReadonlyRefgetStore;
18
19use std::collections::BTreeMap;
20use std::sync::atomic::{AtomicUsize, Ordering};
21
22use anyhow::{anyhow, Result};
23use serde::Serialize;
24
25use crate::digest::{AlphabetType, SequenceHasher};
26use crate::hashkeyable::{key_to_digest_string, HashKeyable};
27
28const PROGRESS_INTERVAL: usize = 10_000;
31
32const VERIFY_READ_BUF_SIZE: usize = 1024 * 1024;
34
35#[derive(Debug, Clone)]
41pub struct VerifyOptions {
42 pub jobs: usize,
45 pub check_md5: bool,
47}
48
49impl Default for VerifyOptions {
50 fn default() -> Self {
51 Self {
52 jobs: 0,
53 check_md5: true,
54 }
55 }
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
68pub enum VerifyFailureKind {
69 DigestMismatch,
71 Md5Mismatch,
73 LengthMismatch,
75 ReadError,
77}
78
79impl VerifyFailureKind {
80 pub fn as_str(&self) -> &'static str {
82 match self {
83 VerifyFailureKind::DigestMismatch => "digest_mismatch",
84 VerifyFailureKind::Md5Mismatch => "md5_mismatch",
85 VerifyFailureKind::LengthMismatch => "length_mismatch",
86 VerifyFailureKind::ReadError => "read_error",
87 }
88 }
89}
90
91impl std::fmt::Display for VerifyFailureKind {
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 write!(f, "{}", self.as_str())
94 }
95}
96
97#[derive(Debug, Clone, Serialize)]
99pub struct VerifyFailure {
100 pub digest: String,
102 pub name: String,
104 pub alphabet: AlphabetType,
105 pub length: usize,
107 pub kind: VerifyFailureKind,
108 pub bases_read: u64,
109 pub computed_sha512t24u: Option<String>,
111 pub stored_md5: String,
112 pub computed_md5: Option<String>,
114 pub error: Option<String>,
116}
117
118#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
120pub struct AlphabetVerifyCounts {
121 pub checked: usize,
122 pub failed: usize,
123}
124
125#[derive(Debug, Clone, Default, Serialize)]
128pub struct VerifyReport {
129 pub n_checked: usize,
130 pub n_ok: usize,
131 pub n_failed: usize,
132 pub by_alphabet: BTreeMap<String, AlphabetVerifyCounts>,
134 pub failures: Vec<VerifyFailure>,
136}
137
138impl VerifyReport {
139 pub fn is_ok(&self) -> bool {
141 self.n_failed == 0
142 }
143}
144
145impl ReadonlyRefgetStore {
150 pub fn verify_sequence(&self, digest: &str, check_md5: bool) -> Result<Option<VerifyFailure>> {
158 let meta = self
160 .get_sequence_metadata(digest)
161 .ok_or_else(|| anyhow!("Sequence not found: {}", digest))?;
162
163 let want_md5 = check_md5 && !meta.md5.is_empty();
164
165 let mut reader = match self.stream_sequence(&meta.sha512t24u, None, None) {
166 Ok(r) => r,
167 Err(e) => {
168 return Ok(Some(VerifyFailure {
169 digest: meta.sha512t24u.clone(),
170 name: meta.name.clone(),
171 alphabet: meta.alphabet,
172 length: meta.length,
173 kind: VerifyFailureKind::ReadError,
174 bases_read: 0,
175 computed_sha512t24u: None,
176 stored_md5: meta.md5.clone(),
177 computed_md5: None,
178 error: Some(e.to_string()),
179 }));
180 }
181 };
182
183 let mut hasher = SequenceHasher::new(want_md5);
184 let mut buf = vec![0u8; VERIFY_READ_BUF_SIZE];
185 let mut bases_read: u64 = 0;
186 loop {
187 match reader.read(&mut buf) {
188 Ok(0) => break,
189 Ok(n) => {
190 hasher.update(&buf[..n]);
191 bases_read += n as u64;
192 }
193 Err(e) => {
194 let (computed_sha512t24u, computed_md5, _) = hasher.finalize();
195 return Ok(Some(VerifyFailure {
196 digest: meta.sha512t24u.clone(),
197 name: meta.name.clone(),
198 alphabet: meta.alphabet,
199 length: meta.length,
200 kind: VerifyFailureKind::ReadError,
201 bases_read,
202 computed_sha512t24u: Some(computed_sha512t24u),
203 stored_md5: meta.md5.clone(),
204 computed_md5,
205 error: Some(e.to_string()),
206 }));
207 }
208 }
209 }
210
211 let (computed_sha512t24u, computed_md5, hashed_len) = hasher.finalize();
212
213 if hashed_len != meta.length as u64 {
214 return Ok(Some(VerifyFailure {
215 digest: meta.sha512t24u.clone(),
216 name: meta.name.clone(),
217 alphabet: meta.alphabet,
218 length: meta.length,
219 kind: VerifyFailureKind::LengthMismatch,
220 bases_read: hashed_len,
221 computed_sha512t24u: Some(computed_sha512t24u),
222 stored_md5: meta.md5.clone(),
223 computed_md5,
224 error: None,
225 }));
226 }
227
228 if computed_sha512t24u != meta.sha512t24u {
229 return Ok(Some(VerifyFailure {
230 digest: meta.sha512t24u.clone(),
231 name: meta.name.clone(),
232 alphabet: meta.alphabet,
233 length: meta.length,
234 kind: VerifyFailureKind::DigestMismatch,
235 bases_read: hashed_len,
236 computed_sha512t24u: Some(computed_sha512t24u),
237 stored_md5: meta.md5.clone(),
238 computed_md5,
239 error: None,
240 }));
241 }
242
243 if want_md5
244 && let Some(cm) = computed_md5.as_ref()
245 && *cm != meta.md5
246 {
247 return Ok(Some(VerifyFailure {
248 digest: meta.sha512t24u.clone(),
249 name: meta.name.clone(),
250 alphabet: meta.alphabet,
251 length: meta.length,
252 kind: VerifyFailureKind::Md5Mismatch,
253 bases_read: hashed_len,
254 computed_sha512t24u: Some(computed_sha512t24u),
255 stored_md5: meta.md5.clone(),
256 computed_md5,
257 error: None,
258 }));
259 }
260
261 Ok(None)
262 }
263
264 pub fn verify_sequences(
272 &self,
273 digests: Option<&[String]>,
274 opts: &VerifyOptions,
275 ) -> Result<VerifyReport> {
276 fn _assert_sync<T: Sync>() {}
280 _assert_sync::<ReadonlyRefgetStore>();
281
282 let mut work: Vec<DigestKey> = match digests {
284 None => self.sequence_digests().collect(),
285 Some(requested) => {
286 let mut keys = Vec::with_capacity(requested.len());
287 let mut unknown = Vec::new();
288 for d in requested {
289 if let Some(v) = self.sequence_view(d) {
290 keys.push(v.sha512t24u().to_key());
291 } else {
292 unknown.push(d.clone());
293 }
294 }
295 if !unknown.is_empty() {
296 return Err(anyhow!(
297 "Unknown sequence digest(s): {}",
298 unknown.join(", ")
299 ));
300 }
301 keys
302 }
303 };
304 work.sort();
305 work.dedup();
306 let total = work.len();
307
308 let jobs = match opts.jobs {
310 0 => std::thread::available_parallelism()
311 .map(|n| n.get())
312 .unwrap_or(1),
313 n => n,
314 };
315 let jobs = jobs.min(total.max(1)).max(1);
316
317 let quiet = self.is_quiet();
318 let done = AtomicUsize::new(0);
319 let failed_count = AtomicUsize::new(0);
320
321 let maybe_report_progress = |n: usize| {
322 if !quiet && n.is_multiple_of(PROGRESS_INTERVAL) {
323 eprintln!(
324 "Verified {} / {} sequences ({} failures so far)",
325 n,
326 total,
327 failed_count.load(Ordering::Relaxed)
328 );
329 }
330 };
331
332 let mut all_failures: Vec<VerifyFailure> = Vec::new();
333 let mut by_alphabet: BTreeMap<String, AlphabetVerifyCounts> = BTreeMap::new();
334
335 let record_one = |key: &DigestKey,
336 failures: &mut Vec<VerifyFailure>,
337 counts: &mut BTreeMap<String, AlphabetVerifyCounts>|
338 -> Result<()> {
339 let digest_str = key_to_digest_string(key);
340 let alphabet = self.sequence_view(&digest_str).map(|v| v.alphabet());
341 let outcome = self.verify_sequence(&digest_str, opts.check_md5)?;
342 if let Some(alphabet) = alphabet {
343 let entry = counts.entry(alphabet.to_string()).or_default();
344 entry.checked += 1;
345 if outcome.is_some() {
346 entry.failed += 1;
347 }
348 }
349 if let Some(failure) = outcome {
350 failed_count.fetch_add(1, Ordering::Relaxed);
351 failures.push(failure);
352 }
353 let n = done.fetch_add(1, Ordering::Relaxed) + 1;
354 maybe_report_progress(n);
355 Ok(())
356 };
357
358 if jobs <= 1 {
359 for key in &work {
360 record_one(key, &mut all_failures, &mut by_alphabet)?;
361 }
362 } else {
363 let index = AtomicUsize::new(0);
364 let work_ref = &work;
365 std::thread::scope(|scope| -> Result<()> {
366 let mut handles = Vec::with_capacity(jobs);
367 for _ in 0..jobs {
368 let index = &index;
369 let record_one = &record_one;
370 handles.push(scope.spawn(move || -> Result<(Vec<VerifyFailure>, BTreeMap<String, AlphabetVerifyCounts>)> {
371 let mut local_failures = Vec::new();
372 let mut local_counts: BTreeMap<String, AlphabetVerifyCounts> = BTreeMap::new();
373 loop {
374 let i = index.fetch_add(1, Ordering::Relaxed);
375 if i >= work_ref.len() {
376 break;
377 }
378 record_one(&work_ref[i], &mut local_failures, &mut local_counts)?;
379 }
380 Ok((local_failures, local_counts))
381 }));
382 }
383 for handle in handles {
384 let (failures, counts) = handle
385 .join()
386 .map_err(|_| anyhow!("verify worker thread panicked"))??;
387 all_failures.extend(failures);
388 for (alphabet, c) in counts {
389 let entry = by_alphabet.entry(alphabet).or_default();
390 entry.checked += c.checked;
391 entry.failed += c.failed;
392 }
393 }
394 Ok(())
395 })?;
396 }
397
398 all_failures.sort_by(|a, b| a.digest.cmp(&b.digest));
399 let n_failed = all_failures.len();
400
401 if !quiet {
402 eprintln!(
403 "Verified {} / {} sequences: {} failures",
404 total, total, n_failed
405 );
406 }
407
408 Ok(VerifyReport {
409 n_checked: total,
410 n_ok: total - n_failed,
411 n_failed,
412 by_alphabet,
413 failures: all_failures,
414 })
415 }
416}