1use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::Arc;
23use std::time::Duration;
24
25use serde_json::{json, Value};
26use sha2::{Digest, Sha256};
27
28use super::compact::{self, WindowEnd};
29pub use super::consol::{ByteRun, Map, Run, CONSOL};
30use crate::backend::storage::filestore::swap::{SwapBase, SwapOutcome, SwapPlan, SwapRename, SwapStamps};
31use crate::backend::storage::error::StoreError;
32use crate::backend::storage::filestore::{is_blank_line, FileMeta, FileOpts, FileStore};
33
34const SNAPSHOT: &str = "output.state.json";
36pub const NEXT: &str = "output.next";
38pub const NEXT_TSIDX: &str = "output.next.tsidx";
40
41#[derive(Debug, Clone)]
43pub struct Options {
44 pub window_bytes: i64,
47 pub max_window_bytes: i64,
48 pub quiet_after_bytes: i64,
51 pub max_tail: i64,
53 pub dry_run: bool,
55 pub pause: Duration,
57 pub swap_attempts: u32,
59 pub busy_ms: i64,
62 pub settle_ms: i64,
66}
67
68impl Default for Options {
69 fn default() -> Self {
70 Self {
71 window_bytes: 16 << 20,
72 max_window_bytes: 256 << 20,
73 quiet_after_bytes: 64 << 20,
74 max_tail: 8 << 20,
75 dry_run: false,
76 pause: Duration::from_millis(50),
77 swap_attempts: 5,
78 busy_ms: 10 * 60 * 1000,
79 settle_ms: 60 * 60 * 1000,
80 }
81 }
82}
83
84#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum Outcome {
87 Empty,
89 AlreadyCompact,
91 DryRun,
93 Swapped { new_gen: String },
95 Stale,
98 Failed(String),
100 Stopped,
102 Busy,
104}
105
106
107#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct Report {
110 pub zone: String,
111 pub outcome: Outcome,
112 pub bytes_before: i64,
113 pub bytes_after: i64,
114 pub lines_before: u64,
115 pub lines_after: u64,
116 pub windows: u32,
117 pub stats: compact::Stats,
118 pub created_next: bool,
120}
121
122impl Report {
123 fn new(zone: &str) -> Self {
124 Self {
125 zone: zone.to_string(),
126 outcome: Outcome::Empty,
127 bytes_before: 0,
128 bytes_after: 0,
129 lines_before: 0,
130 lines_after: 0,
131 windows: 0,
132 stats: compact::Stats::default(),
133 created_next: false,
134 }
135 }
136}
137
138
139fn stopped(stop: &AtomicBool) -> bool {
141 stop.load(Ordering::Relaxed)
142}
143
144fn old_state(fs: &FileStore, zone: &str) -> Result<Option<(i64, String)>, String> {
147 let file = fs.read_snapshot(|s| s.file(zone, "output")).map_err(|e| format!("read: {e}"))?;
148 Ok(file.map(|f| (f.size, f.gen.unwrap_or_default())))
149}
150
151fn read_old(fs: &FileStore, zone: &str, gen: &str, pos: i64, len: i64) -> Result<Option<Vec<u8>>, String> {
153 fs.read_snapshot(|s| {
154 let Some(file) = s.file(zone, "output")? else { return Ok(None) };
155 if file.gen.as_deref().unwrap_or("") != gen || file.size < pos + len {
156 return Ok(None);
157 }
158 s.bytes(zone, "output", pos, len)
159 })
160 .map_err(|e| format!("read: {e}"))
161}
162
163fn parse_stamps(raw: &[u8], from: i64) -> Vec<(i64, i64, i64)> {
167 let mut out: Vec<(i64, i64, i64)> = Vec::new();
168 let mut at = from;
169 for line in String::from_utf8_lossy(raw).split_inclusive('\n') {
170 if let Ok(v) = serde_json::from_str::<Value>(line.trim_end()) {
171 if let (Some(off), Some(ms)) = (v.get("off").and_then(Value::as_i64), v.get("ms").and_then(Value::as_i64)) {
172 out.push((off, ms, at));
173 }
174 }
175 at += line.len() as i64;
176 }
177 out
178}
179
180struct Build<'a> {
182 fs: &'a FileStore,
183 zone: &'a str,
184 opts: &'a Options,
185 gen: String,
186 pos: i64,
188 old_lines: u64,
190 new_size: i64,
192 new_lines: u64,
193 stamps: std::collections::VecDeque<(i64, i64, i64)>,
195 stamps_read_to: i64,
197 stamps_out: Vec<(i64, i64)>,
198 hash: Sha256,
199 runs: Vec<Run>,
200 byte_runs: Vec<ByteRun>,
201 report: Report,
202}
203
204impl Build<'_> {
205 fn pull_stamps(&mut self) {
208 let Ok(Some(state)) = self.fs.line_state(self.zone, "output.tsidx") else { return };
209 if state.size < self.stamps_read_to {
210 self.stamps.clear();
211 self.stamps_read_to = state.size;
212 return;
213 }
214 let Ok(raw) = self.fs.read_bytes_db(self.zone, "output.tsidx", self.stamps_read_to, state.size - self.stamps_read_to) else { return };
215 let whole = raw.iter().rposition(|c| *c == b'\n').map_or(0, |p| p + 1);
216 self.stamps.extend(parse_stamps(&raw[..whole], self.stamps_read_to));
217 self.stamps_read_to += whole as i64;
218 }
219
220 fn stamps_from(&self) -> i64 {
223 self.stamps.front().map_or(self.stamps_read_to, |s| s.2)
224 }
225
226 fn window(&mut self, chunk: &[u8], end: WindowEnd) -> Result<(), String> {
229 if let Ok(text) = std::str::from_utf8(chunk) {
230 return self.window_text(text, end);
231 }
232 let (mut at, mut from) = (0usize, 0usize);
236 for raw in chunk.split_inclusive(|c| *c == b'\n') {
237 let to = at + raw.len();
238 if std::str::from_utf8(raw).is_err() {
239 if from < at {
240 self.window_text(utf8(&chunk[from..at], self.pos)?, WindowEnd::Open)?;
241 }
242 self.window_raw(raw)?;
243 from = to;
244 }
245 at = to;
246 }
247 if from < chunk.len() {
248 self.window_text(utf8(&chunk[from..], self.pos)?, end)?;
249 }
250 Ok(())
251 }
252
253 fn window_raw(&mut self, raw: &[u8]) -> Result<(), String> {
256 self.pull_stamps();
257 let window_end = self.pos + raw.len() as i64;
258 while let Some(&(off, ms, _)) = self.stamps.front() {
259 if off >= window_end {
260 break;
261 }
262 self.stamps.pop_front();
263 match self.stamps_out.last_mut() {
264 Some(last) if last.0 == self.new_size => last.1 = ms,
265 _ => self.stamps_out.push((self.new_size, ms)),
266 }
267 }
268 self.hash.update(raw.strip_suffix(b"\n").unwrap_or(raw));
269 self.hash.update(b"\n");
270 if !self.opts.dry_run {
271 self.fs.append_lines(self.zone, NEXT, raw).map_err(|e| format!("write: {e}"))?;
272 if !self.stamps_out.is_empty() {
273 let stamps: String = self.stamps_out.iter().map(|(off, ms)| format!("{{\"off\":{off},\"ms\":{ms}}}\n")).collect();
274 self.fs.append_lines(self.zone, NEXT_TSIDX, stamps.as_bytes()).map_err(|e| format!("write: {e}"))?;
275 }
276 }
277 self.stamps_out.clear();
278 self.pos = window_end;
279 self.old_lines += 1;
280 self.new_size += raw.len() as i64;
281 self.new_lines += 1;
282 self.report.windows += 1;
283 self.report.stats.lines += 1;
284 self.report.stats.kept += 1;
285 Ok(())
286 }
287
288 fn window_text(&mut self, text: &str, end: WindowEnd) -> Result<(), String> {
290 let mut lines: Vec<&str> = Vec::new();
292 let mut starts: Vec<i64> = Vec::new();
293 let mut at = self.pos;
294 for raw in text.split_inclusive('\n') {
295 let line = raw.strip_suffix('\n').unwrap_or(raw);
296 if !is_blank_line(line.as_bytes()) {
297 lines.push(line);
298 starts.push(at);
299 }
300 at += raw.len() as i64;
301 }
302 self.pull_stamps();
305 let (new_lines, plan) = compact::compact_lines(&lines, end);
306 compact::verify(&lines, &new_lines).map_err(|f| format!("window at byte {}: check {f}", self.pos))?;
307 let mut new_starts: Vec<i64> = Vec::with_capacity(lines.len());
309 let mut cursor = self.new_size;
310 let mut synth = plan.synth.iter().peekable();
311 let mut run: Option<Run> = None;
312 for (i, line) in lines.iter().enumerate() {
313 new_starts.push(cursor);
314 if plan.actions[i] == compact::Action::Keep {
315 if let Some(r) = run.take() {
316 self.runs.push(r);
317 }
318 cursor += line.len() as i64 + 1;
319 } else {
320 let r = run.get_or_insert(Run { old_line: self.old_lines + i as u64, dropped: 0, synthesized: 0 });
321 r.dropped += 1;
322 }
323 while let Some(s) = synth.next_if(|s| s.after == i) {
324 cursor += s.line.len() as i64 + 1;
325 if let Some(r) = run.as_mut() {
326 r.synthesized += 1;
327 }
328 }
329 }
330 if let Some(r) = run.take() {
331 self.runs.push(r);
332 }
333 self.byte_runs.extend(byte_runs_of(&lines, &starts, self.pos, self.pos + text.len() as i64, &plan));
334 let window_end = at;
336 while let Some(&(off, ms, _)) = self.stamps.front() {
337 if off >= window_end {
338 break;
339 }
340 self.stamps.pop_front();
341 let idx = starts.partition_point(|s| *s <= off).saturating_sub(1);
342 let new_off = new_starts.get(idx).copied().unwrap_or(self.new_size);
343 match self.stamps_out.last_mut() {
344 Some(last) if last.0 == new_off => last.1 = ms,
346 _ => self.stamps_out.push((new_off, ms)),
347 }
348 }
349 let mut out = String::with_capacity(text.len());
351 for l in &new_lines {
352 out.push_str(l);
353 out.push('\n');
354 }
355 for (i, l) in lines.iter().enumerate() {
356 if plan.actions[i] == compact::Action::Keep {
357 self.hash.update(l.as_bytes());
358 self.hash.update(b"\n");
359 }
360 }
361 if !self.opts.dry_run && !out.is_empty() {
362 self.fs.append_lines(self.zone, NEXT, out.as_bytes()).map_err(|e| format!("write: {e}"))?;
363 if !self.stamps_out.is_empty() {
364 let raw: String = self.stamps_out.iter().map(|(off, ms)| format!("{{\"off\":{off},\"ms\":{ms}}}
365")).collect();
366 self.fs.append_lines(self.zone, NEXT_TSIDX, raw.as_bytes()).map_err(|e| format!("write: {e}"))?;
367 }
368 }
369 self.stamps_out.clear();
370 self.pos += text.len() as i64;
371 self.old_lines += lines.len() as u64;
372 self.new_size += out.len() as i64;
373 self.new_lines += new_lines.len() as u64;
374 self.report.windows += 1;
375 self.report.stats.absorb(&plan.stats);
376 Ok(())
377 }
378
379 fn record(&self, old: &SwapBase, new_gen: &str, old_size: i64, tail: &TailCopy) -> Vec<u8> {
382 let mut byte_runs = self.byte_runs.clone();
383 byte_runs.extend(tail.dropped.iter().copied());
384 let map = Map { gen_before: old.gen.clone(), gen_after: new_gen.to_string(), runs: self.runs.clone(), byte_runs }.to_json();
385 let done = json!({
386 "k": "done", "v": 1, "at": agentmux_common::time::now_ms(),
387 "gen_before": old.gen, "gen_after": new_gen,
388 "bytes_before": old_size, "bytes_after": self.new_size, "tail_bytes": tail.bytes,
389 "lines_before": self.old_lines, "lines_after": self.new_lines,
390 "dropped_fragments": self.report.stats.dropped_fragments,
391 "interrupted_lines": self.report.stats.interrupted_lines,
392 "unproven_fragments": self.report.stats.unproven_fragments,
393 "pending_fragments": self.report.stats.pending_fragments,
394 "orphan_fragments": self.report.stats.orphan_fragments,
395 "sequence_sha256": hex::encode(self.hash.clone().finalize()),
396 "ok": true,
397 });
398 format!("{map}\n{done}\n").into_bytes()
399 }
400}
401
402fn byte_runs_of(lines: &[&str], starts: &[i64], from: i64, to: i64, plan: &compact::Plan) -> Vec<ByteRun> {
405 let mut out = Vec::new();
406 let mut cur: Option<ByteRun> = None;
407 let mut at = from;
408 let mut synth = plan.synth.iter().peekable();
409 for (i, line) in lines.iter().enumerate() {
410 if starts[i] > at {
411 cur.get_or_insert(ByteRun { old_at: at, old_len: 0, new_len: 0 }).old_len += starts[i] - at;
412 }
413 let len = line.len() as i64 + 1;
414 if plan.actions[i] == compact::Action::Keep {
415 out.extend(cur.take());
416 } else {
417 cur.get_or_insert(ByteRun { old_at: starts[i], old_len: 0, new_len: 0 }).old_len += len;
418 }
419 while let Some(s) = synth.next_if(|s| s.after == i) {
420 cur.get_or_insert(ByteRun { old_at: starts[i] + len, old_len: 0, new_len: 0 }).new_len += s.line.len() as i64 + 1;
421 }
422 at = starts[i] + len;
423 }
424 if to > at {
425 cur.get_or_insert(ByteRun { old_at: at, old_len: 0, new_len: 0 }).old_len += to - at;
426 }
427 out.extend(cur);
428 out
429}
430
431fn last_done(fs: &FileStore, zone: &str) -> Option<Value> {
433 let size = fs.line_state(zone, CONSOL).ok()??.size;
434 let from = (size - 8192).max(0);
435 let raw = fs.read_bytes_db(zone, CONSOL, from, size - from).ok()?;
436 String::from_utf8_lossy(&raw)
437 .lines()
438 .rev()
439 .filter_map(|l| serde_json::from_str::<Value>(l).ok())
440 .find(|v| v.get("k").and_then(Value::as_str) == Some("done"))
441}
442
443fn already_compact(fs: &FileStore, zone: &str, gen: &str, size: i64) -> bool {
446 let Some(done) = last_done(fs, zone) else { return false };
447 if done.get("gen_after").and_then(Value::as_str) != Some(gen) || done.get("ok") != Some(&Value::Bool(true)) {
448 return false;
449 }
450 let covered = done.get("bytes_after").and_then(Value::as_i64).unwrap_or(-1);
453 if covered < 0 || covered > size || done.get("pending_fragments").and_then(Value::as_u64).unwrap_or(1) != 0 {
454 return false;
455 }
456 let tail = size - covered;
457 if tail == 0 {
458 return true;
459 }
460 if tail > 64 << 20 {
461 return false;
462 }
463 match fs.read_bytes_db(zone, "output", covered, tail) {
464 Ok(bytes) => !bytes.windows(14).any(|w| w == b"\"stream_event\""),
465 Err(_) => false,
466 }
467}
468
469fn discard(fs: &FileStore, zone: &str) {
471 if let Err(e) = fs.delete_files(zone, &[NEXT, NEXT_TSIDX]) {
472 tracing::warn!(zone = %zone, error = %e, "history migrate: could not remove the half-built file");
473 }
474}
475
476pub fn migrate_zone(fs: &Arc<FileStore>, zone: &str, opts: &Options, stop: &AtomicBool) -> Report {
478 let mut report = Report::new(zone);
479 report.outcome = match run_zone(fs, zone, opts, stop, &mut report) {
480 Ok(o) => o,
481 Err(e) => Outcome::Failed(e),
482 };
483 if report.created_next && !matches!(report.outcome, Outcome::Swapped { .. }) {
485 discard(fs, zone);
486 }
487 report
488}
489
490fn utf8(part: &[u8], pos: i64) -> Result<&str, String> {
492 std::str::from_utf8(part).map_err(|e| format!("window at byte {pos}: not UTF-8 ({e})"))
493}
494
495fn next_window(fs: &FileStore, zone: &str, gen: &str, pos: i64, remaining: i64, opts: &Options) -> Result<(Vec<u8>, bool), String> {
499 let mut want = opts.window_bytes.min(remaining);
500 loop {
501 if want == 0 {
502 return Ok((Vec::new(), false));
503 }
504 let bytes = read_old(fs, zone, gen, pos, want)?.ok_or("the file changed while it was read")?;
505 let whole = &bytes[..bytes.iter().rposition(|c| *c == b'\n').map_or(0, |p| p + 1)];
506 let (mut cut, mut at) = (None, 0usize);
508 for raw in whole.split_inclusive(|c| *c == b'\n') {
509 at += raw.len();
510 if std::str::from_utf8(raw).is_ok_and(|t| compact::is_turn_boundary(t.trim_end_matches('\n'))) {
511 cut = Some(at);
512 }
513 }
514 if let Some(cut) = cut {
515 return Ok((bytes[..cut].to_vec(), true));
516 }
517 if want >= remaining {
518 return Ok((whole.to_vec(), false));
519 }
520 if want >= opts.quiet_after_bytes {
521 if let Some(cut) = quiet_cut(whole) {
522 return Ok((bytes[..cut].to_vec(), true));
523 }
524 }
525 if want >= opts.max_window_bytes {
526 return Err(format!("no turn boundary and no quiet line within {want} bytes after byte {pos}"));
527 }
528 want = (want * 2).min(remaining).min(opts.max_window_bytes);
529 }
530}
531
532fn quiet_cut(whole: &[u8]) -> Option<usize> {
535 let mut lines: Vec<&str> = Vec::new();
536 let mut ends: Vec<usize> = Vec::new();
537 let mut at = 0usize;
538 for raw in whole.split_inclusive(|c| *c == b'\n') {
539 at += raw.len();
540 ends.push(at);
541 lines.push(std::str::from_utf8(raw).map_or("", |t| t.trim_end_matches('\n')));
542 }
543 compact::last_quiet_line(&lines).map(|i| ends[i])
544}
545
546fn run_zone(fs: &Arc<FileStore>, zone: &str, opts: &Options, stop: &AtomicBool, report: &mut Report) -> Result<Outcome, String> {
547 if !opts.dry_run && !fs.discard_unless_fresh(zone, &[NEXT, NEXT_TSIDX], opts.busy_ms).map_err(|e| format!("discard: {e}"))? {
550 return Ok(Outcome::Busy);
551 }
552 let Some(stat) = fs.stat(zone, "output").map_err(|e| format!("stat: {e}"))? else { return Ok(Outcome::Empty) };
553 if stat.size == 0 {
554 return Ok(Outcome::Empty);
555 }
556 if !opts.dry_run && !super::counting::ensure_counted(fs, zone, Duration::from_secs(30)) {
559 return Err("the file has no line count yet".to_string());
560 }
561 let Some((size0, gen)) = old_state(fs, zone)? else { return Err("the file has no line count".to_string()) };
562 if gen.is_empty() && !opts.dry_run {
563 return Err("the file has no line count".to_string());
564 }
565 report.bytes_before = size0;
566 if already_compact(fs, zone, &gen, size0) {
567 return Ok(Outcome::AlreadyCompact);
568 }
569 if !opts.dry_run {
570 match fs.make_file(zone, NEXT, FileMeta::new(), FileOpts::default()) {
572 Ok(()) => report.created_next = true,
573 Err(StoreError::AlreadyExists) => return Ok(Outcome::Busy),
574 Err(e) => return Err(format!("create: {e}")),
575 }
576 fs.make_file(zone, NEXT_TSIDX, FileMeta::new(), FileOpts::default()).map_err(|e| format!("create: {e}"))?;
577 }
578 let mut b = Build {
579 fs,
580 zone,
581 opts,
582 gen: gen.clone(),
583 pos: 0,
584 old_lines: 0,
585 new_size: 0,
586 new_lines: 0,
587 stamps: Default::default(),
588 stamps_read_to: 0,
589 stamps_out: Vec::new(),
590 hash: Sha256::new(),
591 runs: Vec::new(),
592 byte_runs: Vec::new(),
593 report: report.clone(),
594 };
595 let mut swaps = 0;
596 let out = loop {
597 if stopped(stop) {
598 break Outcome::Stopped;
599 }
600 let Some((size, now_gen)) = old_state(fs, zone)? else { break Outcome::Stale };
601 if now_gen != b.gen || size < b.pos {
602 break Outcome::Stale;
603 }
604 let remaining = size - b.pos;
605 let (chunk, has_boundary) = next_window(fs, zone, &b.gen, b.pos, remaining, opts)?;
606 if !has_boundary && remaining <= opts.max_tail {
607 if opts.dry_run {
609 break Outcome::DryRun;
610 }
611 let base = SwapBase { gen: b.gen.clone(), size: b.pos };
612 match swap_with_record(fs, zone, &base, &b, size, opts)? {
613 SwapOutcome::Swapped { new_gen, .. } => break Outcome::Swapped { new_gen },
614 SwapOutcome::Stale => break Outcome::Stale,
615 SwapOutcome::NotBuilt => return Err("the built file is not counted".to_string()),
616 SwapOutcome::Behind { .. } => {
617 swaps += 1;
618 if swaps >= opts.swap_attempts {
619 return Err("the file keeps growing under the swap".to_string());
620 }
621 std::thread::sleep(opts.pause);
622 continue;
623 }
624 }
625 }
626 if chunk.is_empty() {
627 return Err(format!("no whole line at byte {} (a line longer than the window, or an unterminated end)", b.pos));
628 }
629 b.window(&chunk, WindowEnd::Open)?;
630 if !opts.pause.is_zero() {
631 std::thread::sleep(opts.pause);
632 }
633 };
634 *report = b.report.clone();
635 report.bytes_after = b.new_size;
636 report.lines_before = b.old_lines;
637 report.lines_after = b.new_lines;
638 Ok(out)
640}
641
642struct TailCopy {
645 bytes: i64,
646 dropped: Vec<ByteRun>,
647}
648
649fn tail_copy(fs: &FileStore, zone: &str, base: &SwapBase, old_size: i64, opts: &Options) -> Result<TailCopy, String> {
653 let bytes = old_size - base.size;
654 let mut dropped = Vec::new();
655 if bytes > 0 && bytes <= opts.max_tail {
656 if let Some(tail) = read_old(fs, zone, &base.gen, base.size, bytes)? {
657 let mut at = base.size;
658 for raw in tail.split_inclusive(|b| *b == b'\n') {
659 if (raw.ends_with(b"\n") && is_blank_line(raw)) || !raw.ends_with(b"\n") {
660 dropped.push(ByteRun { old_at: at, old_len: raw.len() as i64, new_len: 0 });
663 }
664 at += raw.len() as i64;
665 }
666 }
667 }
668 Ok(TailCopy { bytes, dropped })
669}
670
671fn swap_with_record(fs: &FileStore, zone: &str, base: &SwapBase, b: &Build<'_>, old_size: i64, opts: &Options) -> Result<SwapOutcome, String> {
674 let new_gen = fs
675 .line_state(zone, NEXT)
676 .map_err(|e| format!("read: {e}"))?
677 .and_then(|s| s.counted)
678 .map(|c| c.gen)
679 .ok_or("the built file is not counted")?;
680 let tail = tail_copy(fs, zone, base, old_size, opts)?;
681 let map = Map { gen_before: base.gen.clone(), gen_after: new_gen.clone(), runs: b.runs.clone(), byte_runs: b.byte_runs.clone() };
683 let snapshot = move |bytes: &[u8]| -> Option<Vec<u8>> {
684 let mut v: Value = serde_json::from_slice(bytes).ok()?;
685 let hwm = v.get("highWaterMark")?.as_u64()?;
686 v["highWaterMark"] = json!(map.line(hwm));
687 serde_json::to_vec(&v).ok()
688 };
689 let plan = SwapPlan {
690 next: NEXT,
691 name: "output",
692 renames: vec![SwapRename { from: NEXT_TSIDX, to: "output.tsidx" }],
693 drop: vec!["output.idx"],
694 records: vec![(CONSOL, b.record(base, &new_gen, old_size, &tail))],
695 rewrite: vec![(SNAPSHOT, &snapshot)],
696 max_tail: opts.max_tail,
697 settle_ms: opts.settle_ms,
698 stamps: Some(SwapStamps { old: "output.tsidx", read_to: b.stamps_from() }),
699 };
700 fs.swap_in_next(zone, base, &plan).map_err(|e| format!("swap: {e}"))
701}
702
703pub fn migrate_all(fs: &Arc<FileStore>, prefix: &str, opts: &Options, stop: &AtomicBool) -> Vec<Report> {
706 let mut zones = fs.zone_ids_with_prefix(prefix).unwrap_or_default();
707 zones.sort();
708 let mut reports = Vec::new();
709 for zone in zones {
710 if stopped(stop) {
711 break;
712 }
713 if fs.stat(&zone, "output").ok().flatten().is_none() {
714 continue;
715 }
716 reports.push(migrate_zone(fs, &zone, opts, stop));
717 }
718 reports
719}
720
721#[cfg(test)]
722#[path = "migrate_tests.rs"]
723mod tests;