1use std::num::NonZeroUsize;
8use std::sync::Arc;
9use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering};
10use std::time::{Duration, Instant};
11
12use crate::error::{DimaError, Result};
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
16#[repr(u8)]
17pub enum Phase {
18 Opening = 0,
20 Counting = 1,
22 Finalising = 2,
24 Writing = 3,
26 Done = 4,
28}
29
30impl Phase {
31 pub const ALL: [Self; 5] = [
33 Self::Opening,
34 Self::Counting,
35 Self::Finalising,
36 Self::Writing,
37 Self::Done,
38 ];
39
40 const fn from_u8(v: u8) -> Self {
41 match v {
42 0 => Self::Opening,
43 1 => Self::Counting,
44 2 => Self::Finalising,
45 3 => Self::Writing,
46 _ => Self::Done,
47 }
48 }
49
50 #[must_use]
52 pub const fn as_str(self) -> &'static str {
53 match self {
54 Self::Opening => "opening",
55 Self::Counting => "counting",
56 Self::Finalising => "finalising",
57 Self::Writing => "writing",
58 Self::Done => "done",
59 }
60 }
61
62 #[must_use]
64 pub const fn label(self) -> &'static str {
65 match self {
66 Self::Opening => "opening",
67 Self::Counting => "counting k-mers",
68 Self::Finalising => "computing statistics",
69 Self::Writing => "writing",
70 Self::Done => "done",
71 }
72 }
73}
74
75#[derive(Debug)]
77pub struct Progress {
78 origin: Instant,
79 phase: AtomicU8,
80 phase_started: [AtomicU64; Phase::ALL.len()],
82 bytes_read: AtomicU64,
83 bytes_total: AtomicU64,
84 records: AtomicU64,
85 positions_done: AtomicU64,
86 positions_total: AtomicU64,
87 threads_started: AtomicUsize,
89}
90
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93pub struct ProgressSnapshot {
94 pub phase: Phase,
96 pub bytes_read: u64,
98 pub bytes_total: Option<u64>,
100 pub records: u64,
102 pub positions_done: u64,
104 pub positions_total: u64,
106}
107
108impl Default for Progress {
109 fn default() -> Self {
110 let p = Self {
111 origin: Instant::now(),
112 phase: AtomicU8::new(Phase::Opening as u8),
113 phase_started: Default::default(),
114 bytes_read: AtomicU64::new(0),
115 bytes_total: AtomicU64::new(0),
116 records: AtomicU64::new(0),
117 positions_done: AtomicU64::new(0),
118 positions_total: AtomicU64::new(0),
119 threads_started: AtomicUsize::new(0),
120 };
121 p.phase_started[Phase::Opening as usize].store(1, Ordering::Relaxed);
122 p
123 }
124}
125
126impl Progress {
127 #[must_use]
129 pub fn new() -> Self {
130 Self::default()
131 }
132
133 #[must_use]
135 pub fn elapsed(&self) -> Duration {
136 self.origin.elapsed()
137 }
138
139 #[must_use]
141 pub fn phase_started(&self, phase: Phase) -> Option<Duration> {
142 match self.phase_started[phase as usize].load(Ordering::Relaxed) {
143 0 => None,
144 n => Some(Duration::from_nanos(n - 1)),
145 }
146 }
147
148 pub fn set_phase(&self, phase: Phase) {
151 let nanos = u64::try_from(self.origin.elapsed().as_nanos()).unwrap_or(u64::MAX - 1);
152 let _ = self.phase_started[phase as usize].compare_exchange(
153 0,
154 nanos + 1,
155 Ordering::Relaxed,
156 Ordering::Relaxed,
157 );
158 self.phase.store(phase as u8, Ordering::Relaxed);
159 }
160
161 #[must_use]
163 pub fn snapshot(&self) -> ProgressSnapshot {
164 let total = self.bytes_total.load(Ordering::Relaxed);
165 ProgressSnapshot {
166 phase: Phase::from_u8(self.phase.load(Ordering::Relaxed)),
167 bytes_read: self.bytes_read.load(Ordering::Relaxed),
168 bytes_total: (total > 0).then_some(total),
169 records: self.records.load(Ordering::Relaxed),
170 positions_done: self.positions_done.load(Ordering::Relaxed),
171 positions_total: self.positions_total.load(Ordering::Relaxed),
172 }
173 }
174
175 #[must_use]
178 pub fn threads_started(&self) -> Option<usize> {
179 match self.threads_started.load(Ordering::Relaxed) {
180 0 => None,
181 n => Some(n),
182 }
183 }
184
185 pub(crate) fn set_threads_started(&self, n: usize) {
186 self.threads_started.store(n, Ordering::Relaxed);
187 }
188
189 pub(crate) fn add_bytes_read(&self, n: u64) {
190 self.bytes_read.fetch_add(n, Ordering::Relaxed);
191 }
192
193 pub(crate) fn set_bytes_total(&self, n: u64) {
194 self.bytes_total.store(n, Ordering::Relaxed);
195 }
196
197 pub(crate) fn add_records(&self, n: u64) {
198 self.records.fetch_add(n, Ordering::Relaxed);
199 }
200
201 pub(crate) fn set_positions_total(&self, n: u64) {
202 self.positions_total.store(n, Ordering::Relaxed);
203 }
204
205 pub(crate) fn add_positions_done(&self, n: u64) {
206 self.positions_done.fetch_add(n, Ordering::Relaxed);
207 }
208}
209
210#[derive(Clone)]
212pub struct Hook(Arc<dyn Fn() + Send + Sync>);
213
214impl Hook {
215 pub fn new(f: impl Fn() + Send + Sync + 'static) -> Self {
217 Self(Arc::new(f))
218 }
219
220 pub fn call(&self) {
222 (self.0)();
223 }
224}
225
226impl std::fmt::Debug for Hook {
227 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228 f.write_str("Hook")
229 }
230}
231
232#[derive(Clone, Debug, Default)]
234pub struct RunControl {
235 pub cancel: Arc<AtomicBool>,
237 pub progress: Arc<Progress>,
239 pub threads: Option<NonZeroUsize>,
241 pub batch_limits: crate::input::BatchLimits,
244 pub expected_probe: Option<ProbeFacts>,
249 pub thread_start: Option<Hook>,
252 pub threads_ready: Option<Hook>,
256}
257
258#[derive(Clone, Debug, Default, PartialEq, Eq)]
261pub struct ProbeFacts {
262 pub records: u64,
264 pub letters: crate::alphabet::LetterCounts,
266 pub alignment_length: usize,
268 pub header_fields: usize,
270}
271
272impl RunControl {
273 #[must_use]
275 pub fn new() -> Self {
276 Self::default()
277 }
278
279 #[must_use]
281 pub fn with_threads(mut self, threads: NonZeroUsize) -> Self {
282 self.threads = Some(threads);
283 self
284 }
285
286 #[must_use]
288 pub fn is_cancelled(&self) -> bool {
289 self.cancel.load(Ordering::Relaxed)
290 }
291
292 pub fn check(&self) -> Result<()> {
297 if self.is_cancelled() {
298 Err(DimaError::Cancelled)
299 } else {
300 Ok(())
301 }
302 }
303
304 #[must_use]
306 pub fn thread_count(&self) -> NonZeroUsize {
307 self.threads
308 .unwrap_or_else(|| std::thread::available_parallelism().unwrap_or(NonZeroUsize::MIN))
309 }
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 #[test]
317 fn progress_round_trip() {
318 let p = Progress::new();
319 assert_eq!(p.snapshot().phase, Phase::Opening);
320 assert_eq!(p.snapshot().bytes_total, None);
321 p.set_phase(Phase::Finalising);
322 p.add_bytes_read(10);
323 p.add_bytes_read(5);
324 p.set_bytes_total(100);
325 p.add_records(3);
326 p.set_positions_total(9);
327 p.add_positions_done(4);
328 let s = p.snapshot();
329 assert_eq!(s.phase, Phase::Finalising);
330 assert_eq!((s.bytes_read, s.bytes_total, s.records), (15, Some(100), 3));
331 assert_eq!((s.positions_done, s.positions_total), (4, 9));
332 assert_eq!(Phase::Counting.label(), "counting k-mers");
333 assert_eq!(p.phase_started(Phase::Opening), Some(Duration::ZERO));
334 assert!(p.phase_started(Phase::Finalising).is_some());
335 assert_eq!(
336 p.phase_started(Phase::Counting),
337 None,
338 "skipped phases have no start"
339 );
340 let first = p.phase_started(Phase::Finalising);
342 p.set_phase(Phase::Finalising);
343 assert_eq!(p.phase_started(Phase::Finalising), first);
344 }
345
346 #[test]
347 fn cancellation() {
348 let c = RunControl::new();
349 assert!(c.check().is_ok());
350 c.cancel.store(true, Ordering::Relaxed);
351 assert!(matches!(c.check(), Err(DimaError::Cancelled)));
352 assert!(c.thread_count().get() >= 1);
353 let c = RunControl::new().with_threads(NonZeroUsize::new(3).unwrap());
354 assert_eq!(c.thread_count().get(), 3);
355 }
356}