pigeon-cli 0.4.1

Pigeon: authenticate, sink, and transform personal data from external services.
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
//! Orchestrates `transform`'s three phases (ADR-0112 Decision §2): Phase A
//! pulls via `rclone copy`, Phase B transcodes/places locally, Phase C
//! pushes via `rclone copy`. Phase B's per-file pipeline (transcode/copy-
//! through -> place -> checkpoint) runs concurrently, bounded by
//! `--concurrency`; a single transcode failure stops dispatching further
//! work (but lets already-dispatched work drain) and skips Phase C
//! entirely -- the whole run aborts, while every file placed before the
//! failure stays checkpointed (Decision §7).

use std::path::{Path, PathBuf};

use tokio::task::JoinSet;

use super::format::InputFileType;
use super::manifest::{self, PendingFile};
use super::{media, placement};
use crate::commands::job::rclone_transfer;

pub(crate) struct TransformPlan {
    pub source_path: String,
    pub destination_path: String,
    pub local_output: PathBuf,
    pub input_file_type: InputFileType,
    pub transfers: usize,
    pub checkers: usize,
    pub tpslimit: Option<usize>,
    pub run_id: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Outcome {
    Transcoded,
    CopiedThrough,
    Failed,
}

impl Outcome {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Outcome::Transcoded => "transcoded",
            Outcome::CopiedThrough => "copied_through",
            Outcome::Failed => "failed",
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct FileOutcome {
    pub relative_path: String,
    pub destination_filename: Option<String>,
    pub outcome: Outcome,
    pub detail: String,
}

/// `Job::Summary`. `failed` is `true` exactly when Phase B hit a transcode
/// failure -- in that case Phase C never ran at all (`pushed` is always `0`),
/// and the wizard treats this as the run's overall failure (ADR-0112
/// Decision §7), even though this is returned as `Ok` rather than `Err` so
/// every already-succeeded file's outcome survives to be reported.
#[derive(Debug, Default)]
pub(crate) struct TransformSummary {
    pub outcomes: Vec<FileOutcome>,
    pub pulled: u64,
    pub pushed: u64,
    pub failed: bool,
}

fn source_dir(local_output: &Path) -> PathBuf {
    local_output.join("source")
}

fn staging_dir(local_output: &Path) -> PathBuf {
    local_output.join(".staging")
}

fn scratch_dir(local_output: &Path) -> PathBuf {
    staging_dir(local_output).join("scratch")
}

fn result_dir(local_output: &Path) -> PathBuf {
    local_output.join("result")
}

/// One file's full Phase B pipeline: transcode (png/heic) or copy-through
/// (jpeg) into a scratch path, then place it under `result_dir` at its
/// deterministic, collision-free name. Returns the final path on success so
/// the caller can report it and append the checkpoint -- checkpoint writes
/// deliberately happen in the single-threaded dispatch loop below, not here,
/// so concurrent tasks never need to coordinate a shared file write.
async fn process_one(
    pending_file: &PendingFile,
    input_file_type: InputFileType,
    source_path: &str,
    result_dir: &Path,
    scratch_dir: &Path,
) -> Result<PathBuf, String> {
    let scratch_path = scratch_dir.join(format!(
        "{}.scratch",
        placement::compute_destination_name(source_path, &pending_file.relative_path)
    ));
    std::fs::create_dir_all(scratch_dir)
        .map_err(|err| format!("failed to create {}: {err}", scratch_dir.display()))?;

    match input_file_type {
        InputFileType::Jpeg => media::copy_through(&pending_file.absolute_path, &scratch_path)?,
        InputFileType::Png | InputFileType::Heic => {
            media::transcode_to_jpg(&pending_file.absolute_path, &scratch_path).await?
        }
    }

    placement::place_one(
        result_dir,
        &scratch_path,
        source_path,
        &pending_file.relative_path,
    )
}

fn outcome_for(input_file_type: InputFileType) -> Outcome {
    match input_file_type {
        InputFileType::Jpeg => Outcome::CopiedThrough,
        InputFileType::Png | InputFileType::Heic => Outcome::Transcoded,
    }
}

/// Runs Phase B's concurrent, `concurrency`-bounded per-file pipeline.
/// Dispatches up to `concurrency` files at once; on the first failure, stops
/// dispatching new work but lets already-in-flight tasks drain to
/// completion (any of which may still succeed and get checkpointed) before
/// returning. Every successful file's checkpoint append happens here,
/// single-threaded, immediately after that file's `process_one` future
/// resolves -- never inside the concurrent task itself.
async fn run_phase_b(
    pending: Vec<PendingFile>,
    input_file_type: InputFileType,
    source_path: String,
    local_output: &Path,
    concurrency: usize,
) -> (Vec<FileOutcome>, bool) {
    let result_dir = result_dir(local_output);
    let scratch_dir = scratch_dir(local_output);
    let staging_dir = staging_dir(local_output);

    let mut outcomes = Vec::new();
    let mut aborted = false;
    let mut pending_iter = pending.into_iter();
    let mut in_flight: JoinSet<(String, Result<PathBuf, String>)> = JoinSet::new();

    loop {
        while !aborted && in_flight.len() < concurrency.max(1) {
            let Some(pending_file) = pending_iter.next() else {
                break;
            };
            let relative_path = pending_file.relative_path.clone();
            let source_path = source_path.clone();
            let result_dir = result_dir.clone();
            let scratch_dir = scratch_dir.clone();
            in_flight.spawn(async move {
                let outcome = process_one(
                    &pending_file,
                    input_file_type,
                    &source_path,
                    &result_dir,
                    &scratch_dir,
                )
                .await;
                (relative_path, outcome)
            });
        }

        if in_flight.is_empty() {
            break;
        }

        let Some(joined) = in_flight.join_next().await else {
            break;
        };
        let (relative_path, result) = joined.expect("transform phase B task panicked");

        match result {
            Ok(final_path) => {
                if let Err(err) = manifest::append_checkpoint(&staging_dir, &relative_path) {
                    aborted = true;
                    outcomes.push(FileOutcome {
                        relative_path,
                        destination_filename: None,
                        outcome: Outcome::Failed,
                        detail: err,
                    });
                    continue;
                }
                outcomes.push(FileOutcome {
                    relative_path,
                    destination_filename: final_path
                        .file_name()
                        .and_then(|name| name.to_str())
                        .map(str::to_string),
                    outcome: outcome_for(input_file_type),
                    detail: String::new(),
                });
            }
            Err(err) => {
                aborted = true;
                outcomes.push(FileOutcome {
                    relative_path,
                    destination_filename: None,
                    outcome: Outcome::Failed,
                    detail: err,
                });
            }
        }
    }

    (outcomes, aborted)
}

/// Runs all three phases. `Err` is reserved for infrastructure-level
/// failures (an `rclone` invocation itself failing, a directory that
/// couldn't be created) -- a per-file transcode failure is captured in the
/// returned `TransformSummary` instead (`failed: true`), so every
/// already-succeeded file's outcome survives for the report.
pub(crate) async fn run_transform_job(
    plan: &TransformPlan,
    concurrency: usize,
) -> Result<TransformSummary, String> {
    let source_dir = source_dir(&plan.local_output);

    crate::observability::metrics::set_macro_phase("transform", false);

    let pull_log_path = plan
        .local_output
        .join(format!("rclone-pull-{}.jsonl", plan.run_id));
    let pull_summary = rclone_transfer::run_rclone_copy(
        &plan.source_path,
        &source_dir.display().to_string(),
        Some(plan.input_file_type.extension()),
        &pull_log_path,
        plan.transfers,
        plan.checkers,
        plan.tpslimit,
        "transform",
        "pull",
        false,
    )
    .await?;

    let pending = manifest::gather_pending(
        &source_dir,
        &staging_dir(&plan.local_output),
        plan.input_file_type,
    )?;

    let (outcomes, aborted) = run_phase_b(
        pending,
        plan.input_file_type,
        plan.source_path.clone(),
        &plan.local_output,
        concurrency,
    )
    .await;

    if aborted {
        return Ok(TransformSummary {
            outcomes,
            pulled: pull_summary.transferred,
            pushed: 0,
            failed: true,
        });
    }

    crate::observability::metrics::set_macro_phase("transform", true);

    let push_log_path = plan
        .local_output
        .join(format!("rclone-push-{}.jsonl", plan.run_id));
    let push_summary = rclone_transfer::run_rclone_copy(
        &result_dir(&plan.local_output).display().to_string(),
        &plan.destination_path,
        None,
        &push_log_path,
        plan.transfers,
        plan.checkers,
        plan.tpslimit,
        "transform",
        "push",
        true,
    )
    .await?;

    Ok(TransformSummary {
        outcomes,
        pulled: pull_summary.transferred,
        pushed: push_summary.transferred,
        failed: false,
    })
}

/// Bespoke, tab-separated `<local_output>/transform-report.txt` (ADR-0112
/// Decision §8) -- not the generic `Debug`-based report
/// `report_upload::write_summary_report` writes for jobs without a bespoke
/// one, mirroring `deduplicate-report.txt`'s precedent. Written at
/// `local_output`'s top level, sibling of `.staging/`/`result/`, so it is
/// never swept into Phase C's push by `core::data::collect_files`.
pub(crate) fn write_report(
    local_output: &Path,
    summary: &TransformSummary,
) -> Result<PathBuf, String> {
    use std::fmt::Write as _;

    let mut body = String::from("source_relative_path\toutcome\tdestination_filename\tdetail\n");
    let mut transcoded = 0;
    let mut copied_through = 0;
    let mut failed = 0;
    for outcome in &summary.outcomes {
        match outcome.outcome {
            Outcome::Transcoded => transcoded += 1,
            Outcome::CopiedThrough => copied_through += 1,
            Outcome::Failed => failed += 1,
        }
        let _ = writeln!(
            body,
            "{}\t{}\t{}\t{}",
            outcome.relative_path,
            outcome.outcome.as_str(),
            outcome.destination_filename.as_deref().unwrap_or(""),
            outcome.detail,
        );
    }
    let _ = writeln!(
        body,
        "\n{transcoded} transcoded, {copied_through} copied through, {failed} failed."
    );

    let path = local_output.join("transform-report.txt");
    std::fs::write(&path, body)
        .map_err(|err| format!("failed to write {}: {err}", path.display()))?;
    Ok(path)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn run_phase_b_transcodes_and_checkpoints_every_pending_file() {
        if media::check_ffmpeg_available().await.is_err() {
            eprintln!("skipping: ffmpeg/ffprobe not found on PATH");
            return;
        }

        let dir = tempfile::tempdir().unwrap();
        let local_output = dir.path().to_path_buf();
        let source_dir = source_dir(&local_output);
        std::fs::create_dir_all(&source_dir).unwrap();
        std::fs::write(source_dir.join("a.jpeg"), b"jpeg bytes").unwrap();
        std::fs::write(source_dir.join("b.jpeg"), b"other jpeg bytes").unwrap();

        let pending = manifest::gather_pending(
            &source_dir,
            &staging_dir(&local_output),
            InputFileType::Jpeg,
        )
        .unwrap();
        assert_eq!(pending.len(), 2);

        let (outcomes, aborted) = run_phase_b(
            pending,
            InputFileType::Jpeg,
            "source:jpeg/".to_string(),
            &local_output,
            2,
        )
        .await;

        assert!(!aborted);
        assert_eq!(outcomes.len(), 2);
        assert!(
            outcomes
                .iter()
                .all(|outcome| outcome.outcome == Outcome::CopiedThrough)
        );

        let checkpoint = manifest::load_checkpoint(&staging_dir(&local_output)).unwrap();
        assert!(checkpoint.contains("a.jpeg"));
        assert!(checkpoint.contains("b.jpeg"));

        // A rerun of gather_pending must now find nothing left to do.
        let rerun_pending = manifest::gather_pending(
            &source_dir,
            &staging_dir(&local_output),
            InputFileType::Jpeg,
        )
        .unwrap();
        assert!(rerun_pending.is_empty());
    }

    /// The key regression test for the fail-fast + checkpoint design
    /// (ADR-0112 Decision §7): a mixed valid/one-corrupt-file batch stops
    /// dispatching further work on the first failure, but every file that
    /// completed first stays checkpointed, and a rerun resumes from exactly
    /// where it stopped.
    #[tokio::test]
    async fn run_phase_b_stops_on_failure_but_checkpoints_prior_successes() {
        if media::check_ffmpeg_available().await.is_err() {
            eprintln!("skipping: ffmpeg/ffprobe not found on PATH");
            return;
        }

        let dir = tempfile::tempdir().unwrap();
        let local_output = dir.path().to_path_buf();
        let source_dir = source_dir(&local_output);
        std::fs::create_dir_all(&source_dir).unwrap();
        std::fs::write(source_dir.join("good.heic"), b"not a real heic file").unwrap();

        let pending = manifest::gather_pending(
            &source_dir,
            &staging_dir(&local_output),
            InputFileType::Heic,
        )
        .unwrap();
        assert_eq!(pending.len(), 1);

        let (outcomes, aborted) = run_phase_b(
            pending,
            InputFileType::Heic,
            "source:heic/".to_string(),
            &local_output,
            1,
        )
        .await;

        assert!(aborted);
        assert_eq!(outcomes.len(), 1);
        assert_eq!(outcomes[0].outcome, Outcome::Failed);
        assert!(!outcomes[0].detail.is_empty());

        let checkpoint = manifest::load_checkpoint(&staging_dir(&local_output)).unwrap();
        assert!(checkpoint.is_empty());
    }

    #[test]
    fn outcome_for_maps_jpeg_to_copied_through_and_others_to_transcoded() {
        assert_eq!(outcome_for(InputFileType::Jpeg), Outcome::CopiedThrough);
        assert_eq!(outcome_for(InputFileType::Png), Outcome::Transcoded);
        assert_eq!(outcome_for(InputFileType::Heic), Outcome::Transcoded);
    }

    #[test]
    fn write_report_lists_every_outcome_and_a_trailing_summary_line() {
        let dir = tempfile::tempdir().unwrap();
        let summary = TransformSummary {
            outcomes: vec![
                FileOutcome {
                    relative_path: "a.png".to_string(),
                    destination_filename: Some("a-abc123.jpg".to_string()),
                    outcome: Outcome::Transcoded,
                    detail: String::new(),
                },
                FileOutcome {
                    relative_path: "bad.heic".to_string(),
                    destination_filename: None,
                    outcome: Outcome::Failed,
                    detail: "ffmpeg: boom".to_string(),
                },
            ],
            pulled: 2,
            pushed: 1,
            failed: true,
        };

        let path = write_report(dir.path(), &summary).unwrap();
        let contents = std::fs::read_to_string(&path).unwrap();

        assert!(contents.contains("a.png\ttranscoded\ta-abc123.jpg\t"));
        assert!(contents.contains("bad.heic\tfailed\t\tffmpeg: boom"));
        assert!(contents.contains("1 transcoded, 0 copied through, 1 failed."));
        assert_eq!(path.file_name().unwrap(), "transform-report.txt");
    }
}