dataferry 0.1.0-beta.1

Data migration engine: move and reshape data from MongoDB and Postgres into Postgres, resumably, one committed partition at a time. The `dataferry` command line.
Documentation
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
//! `dataferry run`, `dataferry resume <run-id>` and `dataferry retry --failed
//! <run-id>` (S2): plan, then run every flow on A5's runner, then verify
//! (A8) and write the run report.
//!
//! - The flows, their sources and sinks come from the plan and the
//!   endpoints `validate` built through the registry, so nothing here
//!   knows a connector type.
//! - `runtime.yaml` becomes the runner's settings. The state store is the
//!   state connection's (`backend: <type>`, built with the sink so its
//!   flows commit `TxnWithState`) or a local directory (`backend: file`).
//! - Two observers watch every partition: the verifier's write-time
//!   checksums and the source-side aggregates of `expect:` (B8). Both keep
//!   their records in files under the work directory, so a run killed
//!   half-way is verified on resume with every attempt's records.
//! - A merge's co-partitioned joins are inputs of the runner; its staged
//!   joins read their sources themselves, in their share of
//!   `memory_budget`, spilling under `<work dir>/stage` (B6, 0002).
//! - After the run, each sink's flows are verified against that sink, with
//!   the run's totals scoped to them, and the report is written to
//!   `<work dir>/runs/<run id>/report.{json,md}`, or
//!   `report-<sink>.{json,md}` per sink when the run writes to several. A
//!   sink this binary can't read back is reported unverified (a warning),
//!   and what finalize couldn't restore on it still fails the run.
//! - Ctrl-C stops the run with exit 130 and releases the leases it held
//!   ([`leases`](crate::leases)), so `dataferry resume` doesn't wait for them
//!   to expire.
//!
//! `run` prints the run id before any partition is processed, so a run
//! that is killed can always be resumed.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use dataferry_dsl::expect::{Expectations, FileSourceLog, SourceLog};
use dataferry_dsl::plan::PlannedFlow;
use dataferry_registry::StateStore;
use dataferry_registry::state::{NewRun, RunId};
use dataferry_runtime::{Flow, RunError, RunReport, Runner, Settings};
use dataferry_state::{FileStateStore, ResumeError};
use dataferry_verify::{
    ChecksumObserver, FileWriteLog, Report, RunTiming, Status, Target, Verification, Verifier,
    WriteLog,
};

use crate::Ferry;
use crate::cli::Cli;
use crate::diagnostic::{Diagnostic, Printer, code};
use crate::exit::Exit;
use crate::leases::Tracked;
use crate::plan::{self, Planned};

/// The engine version a run is pinned to (A4).
pub(crate) const ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");

/// How long a lease lasts without a heartbeat. A run resumed after a crash
/// waits at most this long for the crashed process's partitions.
const LEASE_TTL: Duration = Duration::from_secs(30);
const HEARTBEAT: Duration = Duration::from_secs(10);

/// Overrides [`LEASE_TTL`], in milliseconds, with a heartbeat a third as
/// long: the chaos and conformance suites kill runs and resume them at once.
/// For tests only: a lease shorter than a slow commit or a stall expires
/// under a live worker, which loses its partition and its work.
const LEASE_TTL_ENV: &str = "FERRY_LEASE_TTL_MS";
/// The range [`LEASE_TTL_ENV`] may set. Under a second the heartbeat
/// (a third of it) is closer to a round trip than a renewal can count on;
/// over ten minutes it is no shorter than the default by any use.
const LEASE_TTL_MIN: Duration = Duration::from_secs(1);
const LEASE_TTL_MAX: Duration = Duration::from_secs(600);

/// Which command is running.
#[derive(Debug, Clone)]
pub(crate) enum Start {
    New,
    Resume(String),
    Retry(String),
}

pub(crate) async fn run(ferry: &Ferry, cli: &Cli, printer: &mut Printer<'_>, start: Start) -> Exit {
    let lease = match lease_override(std::env::var(LEASE_TTL_ENV)) {
        Ok(None) => (LEASE_TTL, HEARTBEAT),
        Ok(Some(ttl)) => {
            // Shown even under `-q`: the run isn't safe outside a test.
            let d = Diagnostic::warning(
                code::LEASE_OVERRIDE,
                format!(
                    "{LEASE_TTL_ENV} is set: leases last {} ms instead of {} s. \
                     For tests only, not safe in production",
                    ttl.as_millis(),
                    LEASE_TTL.as_secs()
                ),
            );
            let _ = printer.diagnostics(&[d], &cli.config);
            (ttl, ttl / 3)
        }
        Err(d) => {
            let _ = printer.diagnostics(&[d], &cli.config);
            return Exit::Usage;
        }
    };
    let planned = plan::plan(
        ferry,
        &cli.config,
        &|name| std::env::var(name).ok(),
        &mut printer.redaction,
    )
    .await;
    let planned = match planned {
        Ok((planned, warnings)) => {
            let shown: Vec<Diagnostic> = warnings.into_iter().filter(|_| !cli.quiet).collect();
            let _ = printer.diagnostics(&shown, &cli.config);
            planned
        }
        Err(refused) => {
            let _ = printer.diagnostics(&refused.diagnostics, &cli.config);
            return refused.exit;
        }
    };
    match Execution::new(ferry, cli, &planned, lease) {
        Ok(execution) => execution.run(cli, printer, start).await,
        Err(d) => {
            let _ = printer.diagnostics(&[d], &cli.config);
            Exit::Internal
        }
    }
}

/// The lease [`LEASE_TTL_ENV`] asks for, `None` when it isn't set.
fn lease_override(var: Result<String, std::env::VarError>) -> Result<Option<Duration>, Diagnostic> {
    let ms = match var {
        Err(std::env::VarError::NotPresent) => return Ok(None),
        // Digits only: `parse` would take `+1000` too.
        ms => ms
            .ok()
            .filter(|ms| ms.bytes().all(|b| b.is_ascii_digit()))
            .and_then(|ms| ms.parse::<u64>().ok()),
    };
    let range = LEASE_TTL_MIN..=LEASE_TTL_MAX;
    match ms.map(Duration::from_millis) {
        Some(ttl) if range.contains(&ttl) => Ok(Some(ttl)),
        _ => Err(Diagnostic::error(
            code::RUN,
            format!(
                "{LEASE_TTL_ENV} must be a whole number of milliseconds from {} to {}",
                LEASE_TTL_MIN.as_millis(),
                LEASE_TTL_MAX.as_millis()
            ),
        )
        .help(format!(
            "it shortens leases for tests; unset it to use the default {} s",
            LEASE_TTL.as_secs()
        ))),
    }
}

/// Where `run` keeps what isn't in the state store: write-time records
/// and reports (and the state itself under `backend: file`). Default:
/// `.ferry` next to the config directory.
pub(crate) fn work_dir(cli: &Cli) -> PathBuf {
    match &cli.work_dir {
        Some(dir) => dir.clone(),
        None => cli
            .config
            .parent()
            .filter(|p| !p.as_os_str().is_empty())
            .unwrap_or(Path::new("."))
            .join(".ferry"),
    }
}

/// How one sink's flows are verified (A8).
struct Check {
    sink: String,
    /// The flows writing to it, by name.
    flows: Vec<String>,
    how: How,
}

enum How {
    /// Read back through `target`.
    Verified(Arc<dyn Target>),
    /// Not verified, and why: a warning, not a failure.
    Unverified(String),
}

impl Check {
    /// One check per sink the run writes to, in name order. `Err` when a
    /// sink's target can't be opened: the run must not start, since what
    /// it wrote could never be verified.
    fn of(
        ferry: &Ferry,
        summary: &crate::validate::Summary,
        flows: &[PlannedFlow],
    ) -> Result<Vec<Self>, String> {
        let mut by_sink: BTreeMap<&str, Vec<String>> = BTreeMap::new();
        for flow in flows {
            by_sink
                .entry(flow.sink.as_str())
                .or_default()
                .push(flow.name.clone());
        }
        let mut checks = Vec::new();
        for (sink, flows) in by_sink {
            let raw = summary
                .raw
                .get(sink)
                .ok_or_else(|| format!("connection `{sink}` was not built"))?;
            let how = match ferry.targets.get(&raw.r#type) {
                None => How::Unverified(format!(
                    "this binary can't read `{}` connections back, so `{sink}` isn't verified",
                    raw.r#type
                )),
                Some(factory) => How::Verified(
                    factory(raw)
                        .map_err(|e| format!("could not open `{sink}` to verify it: {e}"))?,
                ),
            };
            checks.push(Check {
                sink: sink.to_owned(),
                flows,
                how,
            });
        }
        Ok(checks)
    }
}

struct Execution<'a> {
    planned: &'a Planned,
    work: PathBuf,
    store: Arc<dyn StateStore>,
    /// `store`, remembering the leases the runner holds.
    leases: Arc<Tracked>,
    write_log: Arc<dyn WriteLog>,
    source_log: Arc<dyn SourceLog>,
    flows: Vec<Flow>,
    checks: Vec<Check>,
    runner: Runner,
}

impl<'a> Execution<'a> {
    fn new(
        ferry: &Ferry,
        cli: &Cli,
        planned: &'a Planned,
        (lease_ttl, heartbeat): (Duration, Duration),
    ) -> Result<Self, Diagnostic> {
        let Planned { summary, plan } = planned;
        let work = work_dir(cli);
        let inner: Arc<dyn StateStore> = match &summary.state_store {
            Some(store) => Arc::clone(store),
            None => {
                let path = summary
                    .state
                    .as_ref()
                    .and_then(|s| s.path.as_deref())
                    .map_or_else(|| work.join("state"), |p| cli.config.join(p));
                Arc::new(FileStateStore::new(path))
            }
        };
        let leases = Arc::new(Tracked::new(inner));
        let store: Arc<dyn StateStore> = leases.clone();
        let write_log: Arc<dyn WriteLog> = Arc::new(FileWriteLog::new(work.join("writes")));
        let source_log: Arc<dyn SourceLog> = Arc::new(FileSourceLog::new(work.join("sources")));

        let internal = |message: String| Diagnostic::error(code::RUN, message);
        let sources = |name: &str| summary.endpoints.get(name).and_then(|e| e.source.clone());
        let mut flows = Vec::new();
        for planned_flow in &plan.flows {
            let sink_endpoints = summary
                .endpoints
                .get(&planned_flow.sink)
                .ok_or_else(|| internal(format!("`{}` was not built", planned_flow.sink)))?;
            let sink = sink_endpoints
                .sink
                .clone()
                .ok_or_else(|| internal(format!("`{}` has no sink", planned_flow.sink)))?;
            let flow = planned_flow
                .runtime_flow(
                    &sources,
                    sink,
                    sink_endpoints.finalizer.clone(),
                    Some(work.join("stage")),
                )
                .map_err(|e| internal(format!("flow `{}`: {e}", planned_flow.name)))?;
            flows.push(flow);
        }
        let checks = Check::of(ferry, summary, &plan.flows)
            .map_err(|why| Diagnostic::error(code::VERIFY_FAILED, why).help("nothing was run"))?;

        let settings = Settings {
            lease_ttl,
            heartbeat,
            ..plan.settings(&summary.config)
        };
        let mut runner = Runner::new(Arc::clone(&store), flows.clone(), settings)
            .map_err(|e| internal(format!("the planned flows don't fit the runner: {e}")))?;
        // Every flow is recorded, so each sink's verification can take the
        // others' rows out of the run's totals; each is checksummed the way
        // its own sink is read back.
        let targets: BTreeMap<String, Arc<dyn Target>> = checks
            .iter()
            .filter_map(|c| match &c.how {
                How::Verified(target) => Some((c, target)),
                How::Unverified(_) => None,
            })
            .flat_map(|(c, target)| c.flows.iter().map(|f| (f.clone(), Arc::clone(target))))
            .collect();
        runner = runner.with_observer(Arc::new(ChecksumObserver::per_flow(
            Arc::clone(&write_log),
            targets,
        )));
        let expectations = Expectations::new(&plan.checked(), Arc::clone(&source_log));
        runner = runner.with_observer(expectations.observer());
        Ok(Self {
            planned,
            work,
            store,
            leases,
            write_log,
            source_log,
            flows,
            checks,
            runner,
        })
    }

    async fn run(self, cli: &Cli, printer: &mut Printer<'_>, start: Start) -> Exit {
        // Before the run id is printed: from then on Ctrl-C must stop the
        // run with 130 rather than kill the process.
        let mut interrupt = match Interrupt::listen() {
            Ok(interrupt) => interrupt,
            Err(e) => {
                let d = Diagnostic::error(code::RUN, format!("could not listen for Ctrl-C: {e}"));
                let _ = printer.diagnostics(&[d], &cli.config);
                return Exit::Internal;
            }
        };
        let plan = &self.planned.plan;
        let hash = plan.hash.as_str();
        let run = match &start {
            Start::New => {
                let new = NewRun {
                    config_hash: hash.to_owned(),
                    engine_version: ENGINE_VERSION.to_owned(),
                    connections: self
                        .planned
                        .summary
                        .connections
                        .iter()
                        .map(|(name, kind, ..)| (name.clone(), kind.clone()))
                        .collect(),
                };
                match self.runner.create(new).await {
                    Ok(run) => run,
                    Err(e) => return run_error(printer, cli, None, e),
                }
            }
            Start::Resume(id) | Start::Retry(id) => RunId(id.clone()),
        };
        let verb = match start {
            Start::New => "run",
            Start::Resume(_) => "resuming run",
            Start::Retry(_) => "retrying the failed partitions of run",
        };
        let _ = printer.output(&format!("{verb} {}\n", run.0));
        if !cli.quiet {
            let lines: String = plan
                .flows
                .iter()
                .map(|f| {
                    format!(
                        "  flow `{}`: {}{}\n",
                        f.name,
                        plan::strategy_name(f.strategy),
                        f.fallback
                            .as_ref()
                            .map_or(String::new(), |why| format!(" ({why})"))
                    )
                })
                .collect();
            let _ = printer.output(&lines);
        }

        let started = SystemTime::now();
        let execute = async {
            match &start {
                Start::New => self.runner.execute(&run).await,
                Start::Resume(_) => self.runner.resume(&run, hash, ENGINE_VERSION).await,
                Start::Retry(_) => self.runner.retry_failed(&run, hash, ENGINE_VERSION).await,
            }
        };
        let report = tokio::select! {
            report = execute => Some(report),
            _ = interrupt.wait() => None,
        };
        // The run future is dropped by now, and its workers with it.
        let Some(report) = report else {
            let released = self.leases.release().await;
            let d = Diagnostic::error(
                code::INTERRUPTED,
                format!(
                    "interrupted: in-flight partitions of run `{}` were abandoned, and {released} \
                     {} released",
                    run.0,
                    match released {
                        1 => "lease was",
                        _ => "leases were",
                    }
                ),
            )
            .help(format!("continue it with `dataferry resume {}`", run.0));
            let _ = printer.diagnostics(&[d], &cli.config);
            return Exit::Interrupted;
        };
        let report = match report {
            Ok(report) => report,
            Err(e) => return run_error(printer, cli, Some(&run), e),
        };
        let finished = SystemTime::now();
        let timing = RunTiming { started, finished };
        let _ = printer.output(&summary_line(&report));
        for f in &report.failures {
            let d = Diagnostic::error(
                code::PARTITION_FAILED,
                format!(
                    "flow `{}`: partition `{}` failed: {}",
                    f.flow, f.partition.0, f.error
                ),
            );
            let _ = printer.diagnostics(&[d], &cli.config);
        }
        for flow in &report.blocked {
            let d = Diagnostic::error(
                code::PARTITION_FAILED,
                format!("flow `{flow}` didn't start: a flow it waits for has failed partitions"),
            );
            let _ = printer.diagnostics(&[d], &cli.config);
        }

        // Verification reads every target back: Ctrl-C stops it too.
        let verified = tokio::select! {
            failed = self.check(cli, printer, &run, &report, timing) => Some(failed),
            _ = interrupt.wait() => None,
        };
        let Some(verification_failed) = verified else {
            let d = Diagnostic::error(
                code::INTERRUPTED,
                format!(
                    "interrupted while verifying run `{}`; its data is written",
                    run.0
                ),
            )
            .help(format!(
                "`dataferry resume {}` verifies it again once nothing is left to run",
                run.0
            ));
            let _ = printer.diagnostics(&[d], &cli.config);
            return Exit::Interrupted;
        };

        if report.counts.failed > 0 || !report.blocked.is_empty() {
            let _ = printer.note(&format!(
                "run `{0}` has failed partitions; `dataferry retry --failed {0}` re-runs them\n",
                run.0
            ));
            return Exit::RunFailed;
        }
        if !report.is_complete() {
            let _ = printer.note(&format!(
                "run `{0}` has unfinished partitions; `dataferry resume {0}` continues it\n",
                run.0
            ));
            return Exit::RunFailed;
        }
        match verification_failed {
            true => Exit::VerifyFailed,
            false => Exit::Success,
        }
    }

    /// Verifies each sink's flows, writes their reports and prints the
    /// outcome. `true` if any verification failed.
    async fn check(
        &self,
        cli: &Cli,
        printer: &mut Printer<'_>,
        run: &RunId,
        report: &RunReport,
        timing: RunTiming,
    ) -> bool {
        let dir = self.report_dir(run);
        let several = self.checks.len() > 1;
        let mut failed = false;
        for check in &self.checks {
            let target = match &check.how {
                How::Verified(target) => target,
                How::Unverified(why) => {
                    let d = Diagnostic::warning(code::UNVERIFIED, format!("not verified: {why}"));
                    let _ = printer.diagnostics(&[d], &cli.config);
                    // Without the verifier, what finalize couldn't restore
                    // is still a failed load.
                    let problems: Vec<Diagnostic> = report
                        .finalize_problems()
                        .filter(|(flow, _)| check.flows.iter().any(|f| f == flow))
                        .map(|(flow, p)| {
                            Diagnostic::error(
                                code::VERIFY_FAILED,
                                format!("flow `{flow}`: finalize couldn't restore {p}"),
                            )
                        })
                        .collect();
                    let _ = printer.diagnostics(&problems, &cli.config);
                    failed |= !problems.is_empty();
                    continue;
                }
            };
            let name = match several {
                true => format!("report-{}", check.sink),
                false => "report".to_owned(),
            };
            let sink = &check.sink;
            match self
                .verify(
                    check,
                    Arc::clone(target),
                    run,
                    report,
                    timing,
                    &dir,
                    &name,
                    printer,
                )
                .await
            {
                Ok(v) => {
                    let text = match v.status {
                        Status::Passed => "passed".to_owned(),
                        Status::Failed => format!("failed ({} problems)", v.problems.len()),
                        Status::Incomplete => "incomplete: the run isn't finished".to_owned(),
                    };
                    let _ = printer.output(&format!(
                        "verification of `{sink}` {text}; report: {}\n",
                        dir.join(format!("{name}.md")).display()
                    ));
                    let diagnostics: Vec<Diagnostic> = match v.status {
                        Status::Failed => v
                            .problems
                            .iter()
                            .map(|p| Diagnostic::error(code::VERIFY_FAILED, p.clone()))
                            .collect(),
                        _ => Vec::new(),
                    };
                    let _ = printer.diagnostics(&diagnostics, &cli.config);
                    failed |= v.status == Status::Failed;
                }
                Err(e) => {
                    let d = Diagnostic::error(
                        code::VERIFY_FAILED,
                        format!("could not verify the flows writing to `{sink}`: {e}"),
                    );
                    let _ = printer.diagnostics(&[d], &cli.config);
                    failed = true;
                }
            }
        }
        failed
    }

    fn report_dir(&self, run: &RunId) -> PathBuf {
        let safe = run
            .0
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
        let name = match safe {
            true => run.0.clone(),
            false => run.0.bytes().map(|b| format!("{b:02x}")).collect(),
        };
        self.work.join("runs").join(name)
    }

    /// Verifies `check`'s flows against `target`, and writes
    /// `<name>.json` and `<name>.md` into `dir`.
    #[allow(clippy::too_many_arguments)]
    async fn verify(
        &self,
        check: &Check,
        target: Arc<dyn Target>,
        run: &RunId,
        report: &RunReport,
        timing: RunTiming,
        dir: &Path,
        name: &str,
        printer: &Printer<'_>,
    ) -> dataferry_core::Result<Verification> {
        let ours = |flow: &str| check.flows.iter().any(|f| f == flow);
        let flows: Vec<Flow> = self
            .flows
            .iter()
            .filter(|f| ours(&f.name))
            .cloned()
            .collect();
        let verifier = Verifier::new(
            Arc::clone(&self.store),
            Arc::clone(&self.write_log),
            target,
            &flows,
        )
        .in_run(&self.flows)
        .with_finalized(report);
        let checked: Vec<_> = self
            .planned
            .plan
            .checked()
            .into_iter()
            .filter(|c| ours(&c.name))
            .collect();
        let verifier = Expectations::new(&checked, Arc::clone(&self.source_log)).verifier(verifier);
        let verification = verifier.verify(run).await?;
        let written = Report::new(&verification).with_run_timing(timing);
        std::fs::create_dir_all(dir).map_err(|e| io_error(dir, e))?;
        // Each value is redacted before it is escaped for Markdown, which
        // could otherwise split a secret; the whole text is redacted after.
        let markdown = written.to_markdown_redacted(&|text| printer.redaction.apply(text));
        for (file, text) in [
            (format!("{name}.json"), written.to_json()),
            (format!("{name}.md"), markdown),
        ] {
            let path = dir.join(file);
            std::fs::write(&path, printer.redaction.apply(&text))
                .map_err(|e| io_error(&path, e))?;
        }
        Ok(verification)
    }
}

fn io_error(path: &Path, e: std::io::Error) -> dataferry_core::FerryError {
    dataferry_core::FerryError::Connector {
        connector: "report".into(),
        message: format!("{}: {e}", path.display()),
    }
}

fn summary_line(report: &RunReport) -> String {
    let c = &report.counts;
    let t = &report.totals;
    let state = match report.is_complete() {
        true => "complete".to_owned(),
        false => format!(
            "not complete ({} done, {} failed, {} pending, {} leased)",
            c.done, c.failed, c.pending, c.leased
        ),
    };
    // Dead letters are counted on their own.
    let written: Vec<String> = t
        .written
        .iter()
        .filter(|(table, _)| *table != dataferry_runtime::DLQ_TABLE)
        .map(|(table, rows)| format!("{table} {rows}"))
        .collect();
    format!(
        "run {}: {state}; {} partitions; read {}, dead-lettered {}; wrote {}\n",
        report.run.0,
        c.done + c.failed + c.pending + c.leased,
        t.read,
        t.dead_lettered,
        match written.is_empty() {
            true => "nothing".to_owned(),
            false => written.join(", "),
        }
    )
}

/// Prints why the run couldn't run at all, and picks the exit code.
fn run_error(printer: &mut Printer<'_>, cli: &Cli, run: Option<&RunId>, e: RunError) -> Exit {
    let (exit, code, help) = match &e {
        RunError::Resume(ResumeError::NotFound(_)) => (
            Exit::Usage,
            code::RESUME_REFUSED,
            Some("the run id is the one `dataferry run` printed first".to_owned()),
        ),
        RunError::Resume(ResumeError::ConfigChanged { .. } | ResumeError::EngineChanged { .. }) => {
            (Exit::ResumeRefused, code::RESUME_REFUSED, None)
        }
        RunError::Resume(ResumeError::Store(_)) | RunError::Store(_) => {
            (Exit::Connect, code::CONNECT, None)
        }
        RunError::NoStrategy { .. } => (Exit::PlanRefused, code::RUN, None),
        RunError::Flow { .. } => (
            Exit::RunFailed,
            code::RUN,
            run.map(|r| format!("fix the cause, then `dataferry resume {}`", r.0)),
        ),
        RunError::Invalid(_) | RunError::Worker(_) => (Exit::Internal, code::RUN, None),
    };
    let mut d = Diagnostic::error(code, e.to_string());
    if let Some(help) = help {
        d = d.help(help);
    }
    let _ = printer.diagnostics(&[d], &cli.config);
    exit
}

/// Ctrl-C, caught from the moment `listen` returns.
struct Interrupt {
    #[cfg(unix)]
    signal: tokio::signal::unix::Signal,
}

impl Interrupt {
    fn listen() -> std::io::Result<Self> {
        Ok(Self {
            #[cfg(unix)]
            signal: tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt())?,
        })
    }

    async fn wait(&mut self) {
        #[cfg(unix)]
        self.signal.recv().await;
        #[cfg(not(unix))]
        let _ = tokio::signal::ctrl_c().await;
    }
}

#[cfg(test)]
mod tests {
    use std::env::VarError;

    use super::*;

    fn lease(ms: &str) -> Result<Option<Duration>, String> {
        lease_override(Ok(ms.to_owned())).map_err(|d| d.message)
    }

    #[test]
    fn the_lease_override_takes_exactly_one_second_to_ten_minutes() {
        assert_eq!(lease_override(Err(VarError::NotPresent)).unwrap(), None);
        assert_eq!(lease("1000"), Ok(Some(Duration::from_secs(1))));
        assert_eq!(lease("1500"), Ok(Some(Duration::from_millis(1_500))));
        assert_eq!(lease("600000"), Ok(Some(Duration::from_secs(600))));
        for bad in [
            "999",
            "600001",
            "0",
            "18446744073709551615",
            " 1000",
            "1e3",
            "+1000",
        ] {
            let e = lease(bad).expect_err(bad);
            assert_eq!(
                e, "FERRY_LEASE_TTL_MS must be a whole number of milliseconds from 1000 to 600000",
                "{bad:?}"
            );
        }
        let e = lease_override(Err(VarError::NotUnicode("\u{fffd}".into()))).unwrap_err();
        assert_eq!(e.code, code::RUN);
    }

    #[test]
    fn the_conformance_suite_asks_for_the_leases_ferry_takes() {
        assert_eq!(
            LEASE_TTL_MIN..=LEASE_TTL_MAX,
            dataferry_runtime::testkit::conformance::LEASE_TTL_RANGE
        );
    }
}