1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
//! Cooperative cancellation and progress reporting for long scans.
//!
//! Project files run the walker over tens of megabytes of `Global/Latest`
//! and every `Partitions/*` stream; a caller driving a UI or a batch job
//! needs to stop that early and to see that it is still moving. Both hooks
//! are opt-in and additive: the `*_with_limits` entry points keep their
//! signatures and behave as before, and the `*_with_control` variants take
//! a [`WalkerControl`] carrying an optional [`CancelToken`] and an optional
//! progress callback.
//!
//! Cancellation is cooperative — checked at the start of every
//! [`PROGRESS_BYTE_INTERVAL`] of scanned bytes, every 256 decoded
//! candidates, before each partition stream, and once after each loop —
//! and it returns [`Error::Cancelled`]; nothing partial is yielded.
use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::error::{Error, Result};
/// Bytes of input between cancellation checks / progress reports in the
/// candidate scan (1 MiB). Power of two so the check is a mask.
pub const PROGRESS_BYTE_INTERVAL: usize = 1 << 20;
/// Shared cancellation flag. Clone it into a UI thread or a signal handler
/// and call [`CancelToken::cancel`]; the scan observes it at its next
/// checkpoint. Once cancelled it stays cancelled.
#[derive(Debug, Clone, Default)]
pub struct CancelToken {
flag: Arc<AtomicBool>,
}
impl CancelToken {
pub fn new() -> Self {
Self::default()
}
/// Request cancellation. Idempotent.
pub fn cancel(&self) {
self.flag.store(true, Ordering::SeqCst);
}
pub fn is_cancelled(&self) -> bool {
self.flag.load(Ordering::SeqCst)
}
/// `Err(Error::Cancelled)` once [`cancel`](Self::cancel) has been called.
pub fn check(&self) -> Result<()> {
if self.is_cancelled() {
Err(Error::Cancelled)
} else {
Ok(())
}
}
}
/// Which phase of a scan a [`ProgressEvent`] describes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Stage {
/// `Formats/Latest` decompress + schema parse (reported as 0 then 1/1).
SchemaParse,
/// Class-tag scan over `Global/Latest`; `done`/`total` are bytes.
CandidateScan,
/// Typed / generic decode of scan candidates; `done`/`total` are candidates.
ElementDecode,
/// Partition-stream passes; `done`/`total` are streams where known,
/// otherwise 0 then 1/1 around the merged partition recoveries.
PartitionScan,
}
impl Stage {
pub fn as_str(self) -> &'static str {
match self {
Self::SchemaParse => "schema-parse",
Self::CandidateScan => "candidate-scan",
Self::ElementDecode => "element-decode",
Self::PartitionScan => "partition-scan",
}
}
}
/// One progress report. `total` is `None` when the stage has no known
/// denominator yet.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProgressEvent {
pub stage: Stage,
pub done: u64,
pub total: Option<u64>,
}
/// Progress callback. Called from the scanning thread; keep it cheap.
pub type ProgressCallback = Arc<dyn Fn(ProgressEvent) + Send + Sync>;
/// Optional cancellation token + optional progress callback handed to the
/// `*_with_control` walker entry points. The default is a no-op that can
/// never cancel, which is what the `*_with_limits` variants use.
#[derive(Clone, Default)]
pub struct WalkerControl {
cancel: Option<CancelToken>,
progress: Option<ProgressCallback>,
}
impl fmt::Debug for WalkerControl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WalkerControl")
.field("cancel", &self.cancel)
.field("progress", &self.progress.as_ref().map(|_| "callback"))
.finish()
}
}
impl WalkerControl {
pub fn new() -> Self {
Self::default()
}
pub fn with_cancel(mut self, token: CancelToken) -> Self {
self.cancel = Some(token);
self
}
pub fn with_progress<F>(mut self, callback: F) -> Self
where
F: Fn(ProgressEvent) + Send + Sync + 'static,
{
self.progress = Some(Arc::new(callback));
self
}
/// The token, if one was attached (so callers can cancel from elsewhere).
pub fn cancel_token(&self) -> Option<&CancelToken> {
self.cancel.as_ref()
}
/// `Err(Error::Cancelled)` if a token is attached and cancelled.
pub fn check(&self) -> Result<()> {
match &self.cancel {
Some(token) => token.check(),
None => Ok(()),
}
}
/// Emit a progress event if a callback is attached.
pub fn report(&self, stage: Stage, done: u64, total: Option<u64>) {
if let Some(progress) = &self.progress {
progress(ProgressEvent { stage, done, total });
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
#[test]
fn token_starts_clear_and_stays_cancelled() {
let token = CancelToken::new();
assert!(!token.is_cancelled());
assert!(token.check().is_ok());
token.cancel();
token.cancel();
assert!(token.is_cancelled());
assert!(matches!(token.check(), Err(Error::Cancelled)));
let clone = token.clone();
assert!(clone.is_cancelled(), "clones share the flag");
}
#[test]
fn default_control_never_cancels_and_never_reports() {
let control = WalkerControl::default();
assert!(control.check().is_ok());
control.report(Stage::CandidateScan, 1, Some(2));
assert!(control.cancel_token().is_none());
}
#[test]
fn control_forwards_cancel_and_progress() {
let token = CancelToken::new();
let seen = Arc::new(Mutex::new(Vec::new()));
let sink = Arc::clone(&seen);
let control = WalkerControl::new()
.with_cancel(token.clone())
.with_progress(move |event| sink.lock().unwrap().push(event));
control.report(Stage::SchemaParse, 0, None);
control.report(Stage::ElementDecode, 3, Some(7));
assert_eq!(
*seen.lock().unwrap(),
vec![
ProgressEvent {
stage: Stage::SchemaParse,
done: 0,
total: None
},
ProgressEvent {
stage: Stage::ElementDecode,
done: 3,
total: Some(7)
},
]
);
assert!(control.check().is_ok());
token.cancel();
assert!(matches!(control.check(), Err(Error::Cancelled)));
}
#[test]
fn interval_is_a_power_of_two() {
assert!(PROGRESS_BYTE_INTERVAL.is_power_of_two());
}
}