Skip to main content

capsule_library/import/camera/
mod.rs

1//! The **camera source adapter**: import straight from a camera over PTP/IP.
2//!
3//! A camera is a source adapter on the same seam as the filesystem scanner and the
4//! [third-party importers](crate::import::importers): it feeds Scan & Extract, and planning,
5//! execution and upload are unchanged. It adds no pipeline stage and no server surface. The work
6//! splits in two:
7//!
8//! 1. [`CameraAdapter::receive`] copies every object off the camera into a local staging root,
9//!    hashing each one as its bytes arrive.
10//! 2. [`CameraAdapter::extract`](SourceAdapter::extract) hands the staged objects to the pipeline
11//!    exactly as a card reader's files would be: the scanner's grouping (RAW+JPEG stacks, Live
12//!    Photos) and the planner's content-hash dedup apply unchanged.
13//!
14//! The contract ([Import — Camera Import]):
15//!
16//! - **Deterministic enumeration** — storages by id, then objects by handle, then capture date.
17//! - **Dedup by content, not source.** The adapter keeps no "seen" state; re-importing a card the
18//!   library already holds is the planner's content-hash `SkipDuplicate`.
19//! - **Integrity.** PTP/IP carries no checksum, so each object is SHA-256-hashed on receipt and
20//!   its staged bytes are read back and re-hashed before it is accepted. A byte count that differs
21//!   from the camera's declared size, or a read-back that differs from the receipt hash, fails the
22//!   object at import, before anything is signed; the staged file the planner then hashes is the
23//!   one whose digest matched.
24//! - **Resumable per object.** A transfer cut off midway leaves a partial file; the next run
25//!   continues it with `GetPartialObject` where the camera supports that, and restarts it where
26//!   it does not. Finished objects are never fetched again.
27//! - **Read-only.** Nothing here mutates camera storage, and the [`CameraDevice`] port has no
28//!   operation that could.
29//!
30//! [`CameraDevice`] is the port; [`PtpCamera`] is its adapter over a `ptpip` session. Discovery
31//! (mDNS `_ptp._tcp` or a typed address) and pairing state are the caller's.
32//!
33//! [Import — Camera Import]: https://docs/design/import/camera-import/
34
35pub(crate) mod ptp_device;
36pub(crate) mod staging;
37
38use std::collections::HashMap;
39use std::ffi::OsString;
40use std::fs::{self, File, OpenOptions};
41use std::io::{self, BufWriter, Read, Seek, SeekFrom, Write};
42use std::path::{Path, PathBuf};
43use std::time::Instant;
44
45use capsule_core::crypto::hash::{Hash32, Sha256Hasher};
46use jiff::civil::DateTime;
47pub use ptp_device::PtpCamera;
48pub use staging::safe_file_name;
49use thiserror::Error;
50
51use crate::import::importers::{
52    AdapterError, ExtractedImport, ExtractedMetadata, ImportProvider, SourceAdapter, SourceEntry,
53};
54use crate::utils::hash_file;
55
56/// One object on the camera, as the [`CameraDevice`] port describes it.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct CameraObject {
59    /// The storage (card slot) holding it.
60    pub storage: u32,
61    /// Its object handle.
62    pub handle: u32,
63    /// The handle of the folder holding it; `0` for the storage root.
64    pub parent: u32,
65    /// The file name the camera stores it under.
66    pub filename: String,
67    /// Its size in bytes, where the camera states it (PTP cannot state 4 GiB or more).
68    pub size: Option<u64>,
69    /// The capture date from the camera's object record, as wall-clock time.
70    pub captured_at: Option<DateTime>,
71    /// Whether it is a folder rather than a file.
72    pub is_folder: bool,
73}
74
75/// What can go wrong talking to the camera or staging what it sends.
76#[derive(Debug, Error)]
77pub enum CameraError {
78    /// The connection to the camera is gone or no longer trustworthy. Ends the run.
79    #[error("camera connection lost: {0}")]
80    Disconnected(String),
81    /// The camera refused one operation. Fails that object only.
82    #[error("camera refused {operation}: {code}")]
83    Refused {
84        /// The operation, as the camera protocol names it.
85        operation: String,
86        /// The camera's response code.
87        code: String,
88    },
89    /// The object needs a partial read the camera cannot serve.
90    #[error("camera cannot resume object {handle:08x} at byte {offset}")]
91    ResumeUnsupported {
92        /// The object.
93        handle: u32,
94        /// The requested offset.
95        offset: u64,
96    },
97    /// A local write into the staging root failed. Ends the run.
98    #[error("staging {path}: {source}")]
99    Staging {
100        /// The path being written.
101        path: PathBuf,
102        /// The I/O failure.
103        source: io::Error,
104    },
105    /// The sink the camera's bytes were streamed into failed. Ends the run.
106    #[error("staging write: {0}")]
107    Sink(io::Error),
108    /// The camera delivered a byte count other than the size it declared. Fails that object.
109    #[error("object {handle:08x}: received {received} bytes, camera declared {declared}")]
110    SizeMismatch {
111        /// The object.
112        handle: u32,
113        /// The size the camera's object record declared.
114        declared: u64,
115        /// The bytes that arrived.
116        received: u64,
117    },
118    /// The staged bytes did not re-hash to the digest computed as they arrived. Fails that
119    /// object.
120    #[error("object {handle:08x}: staged bytes hash {staged}, received bytes hashed {received}")]
121    IntegrityMismatch {
122        /// The object.
123        handle: u32,
124        /// The receipt digest.
125        received: Hash32,
126        /// The read-back digest.
127        staged: Hash32,
128    },
129}
130
131impl CameraError {
132    /// Whether the run must stop: the connection or the local disk failed. Every other error
133    /// fails one object and the run moves on.
134    pub fn is_fatal(&self) -> bool {
135        matches!(
136            self,
137            Self::Disconnected(_) | Self::Staging { .. } | Self::Sink(_)
138        )
139    }
140}
141
142/// The camera the adapter reads from. Read-only by construction: enumeration and reads only.
143pub trait CameraDevice {
144    /// Whether [`read_object`](Self::read_object) accepts a non-zero offset.
145    fn supports_partial_reads(&self) -> bool;
146
147    /// The storages present.
148    fn storage_ids(&mut self) -> Result<Vec<u32>, CameraError>;
149
150    /// Every object handle on `storage`, folders included, at any depth.
151    fn object_handles(&mut self, storage: u32) -> Result<Vec<u32>, CameraError>;
152
153    /// One object's record.
154    fn object(&mut self, handle: u32) -> Result<CameraObject, CameraError>;
155
156    /// Stream `object`'s bytes from `offset` to its end into `sink`; returns the bytes written.
157    /// A non-zero `offset` is only asked of a device that
158    /// [supports partial reads](Self::supports_partial_reads), for an object of known size.
159    fn read_object(
160        &mut self,
161        object: &CameraObject,
162        offset: u64,
163        sink: &mut dyn Write,
164    ) -> Result<u64, CameraError>;
165}
166
167/// One object received and staged.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct ReceivedObject {
170    /// The camera's record of it.
171    pub object: CameraObject,
172    /// Where it is staged.
173    pub path: PathBuf,
174    /// Its size in bytes.
175    pub size: u64,
176    /// The SHA-256 of its bytes, computed as they arrived and confirmed by reading them back.
177    pub sha256: Hash32,
178    /// The byte offset this run continued from; `0` for a whole transfer.
179    pub resumed_from: u64,
180    /// Whether it was already staged by an earlier run and not fetched again.
181    pub already_staged: bool,
182}
183
184/// One object that could not be received.
185#[derive(Debug)]
186pub struct ObjectFailure {
187    /// The storage it is on.
188    pub storage: u32,
189    /// Its handle.
190    pub handle: u32,
191    /// Its file name, where its record was read.
192    pub filename: Option<String>,
193    /// Why it failed.
194    pub error: CameraError,
195}
196
197/// A storage, or the storage list itself, that the camera would not enumerate.
198#[derive(Debug)]
199pub struct StorageFailure {
200    /// The storage (card slot) whose object list was refused; `None` when the camera refused to
201    /// list its storages at all.
202    pub storage: Option<u32>,
203    /// Why it failed.
204    pub error: CameraError,
205}
206
207/// The outcome of [`CameraAdapter::receive`].
208#[derive(Debug)]
209pub struct CameraReceipt {
210    /// The root to hand to [`SourceAdapter::extract`].
211    pub objects_root: PathBuf,
212    /// Every object received, in enumeration order.
213    pub received: Vec<ReceivedObject>,
214    /// Every object that failed, in enumeration order. Never dropped silently.
215    pub failures: Vec<ObjectFailure>,
216    /// Every storage whose objects could not be listed, such as an empty or unavailable card
217    /// slot, in storage order. Its objects are neither received nor listed in `failures`.
218    pub storage_failures: Vec<StorageFailure>,
219}
220
221/// The camera import source adapter, staging into `staging_root`.
222#[derive(Debug, Clone)]
223pub struct CameraAdapter {
224    staging_root: PathBuf,
225}
226
227impl CameraAdapter {
228    /// An adapter staging under `staging_root`. Reuse the same root across runs so an
229    /// interrupted import resumes instead of starting over.
230    pub fn new(staging_root: impl Into<PathBuf>) -> Self {
231        Self {
232            staging_root: staging_root.into(),
233        }
234    }
235
236    /// The root [`SourceAdapter::extract`] scans.
237    pub fn objects_root(&self) -> PathBuf {
238        staging::objects_dir(&self.staging_root)
239    }
240
241    /// Copy every object off `device` into the staging root.
242    ///
243    /// Folders are skipped; every file is received whatever its format. A fatal error (the
244    /// connection or the local disk) returns `Err` and leaves what was staged in place for the
245    /// next run to resume. Any other error is recorded and the run moves on: a storage the camera
246    /// will not list in [`CameraReceipt::storage_failures`], an object in
247    /// [`CameraReceipt::failures`].
248    pub fn receive(&self, device: &mut dyn CameraDevice) -> Result<CameraReceipt, CameraError> {
249        let started = Instant::now();
250        let root = &self.staging_root;
251        tracing::info!(staging_root = %root.display(), "camera import: receive starts");
252        let mut failures = Vec::new();
253        let mut storage_failures = Vec::new();
254        let objects = enumerate(device, &mut failures, &mut storage_failures)?;
255        tracing::info!(
256            objects = objects.len(),
257            unreadable = failures.len(),
258            unlisted_storages = storage_failures.len(),
259            "camera import: enumerated"
260        );
261
262        let generations = match group_generations(root, &objects) {
263            Ok(generations) => generations,
264            Err(error) => {
265                tracing::error!(
266                    %error,
267                    "camera import: receive halted before any transfer; the staging tree is unreadable"
268                );
269                return Err(error);
270            }
271        };
272
273        let mut received = Vec::new();
274        for object in objects {
275            let start = generations
276                .get(&StemGroup::of(&object))
277                .copied()
278                .unwrap_or(0);
279            match receive_one(root, device, &object, start) {
280                Ok(done) => received.push(done),
281                Err(error) if !error.is_fatal() => {
282                    tracing::warn!(
283                        storage = format_args!("{:08x}", object.storage),
284                        handle = format_args!("{:08x}", object.handle),
285                        filename = %object.filename,
286                        %error,
287                        "camera import: object failed"
288                    );
289                    failures.push(ObjectFailure {
290                        storage: object.storage,
291                        handle: object.handle,
292                        filename: Some(object.filename.clone()),
293                        error,
294                    });
295                }
296                Err(error) => {
297                    tracing::error!(
298                        %error,
299                        received = received.len(),
300                        "camera import: receive halted; staged objects are kept for the next run"
301                    );
302                    return Err(error);
303                }
304            }
305        }
306
307        let bytes: u64 = received.iter().map(|r| r.size).sum();
308        tracing::info!(
309            received = received.len(),
310            already_staged = received.iter().filter(|r| r.already_staged).count(),
311            failed = failures.len(),
312            unlisted_storages = storage_failures.len(),
313            bytes,
314            elapsed_ms = started.elapsed().as_millis() as u64,
315            "camera import: receive complete"
316        );
317        Ok(CameraReceipt {
318            objects_root: self.objects_root(),
319            received,
320            failures,
321            storage_failures,
322        })
323    }
324}
325
326impl SourceAdapter for CameraAdapter {
327    fn provider(&self) -> ImportProvider {
328        ImportProvider::Camera
329    }
330
331    /// Scan staged object roots (normally [`CameraReceipt::objects_root`]) into entries, sorted by
332    /// primary path. A camera carries no out-of-band metadata: every entry's
333    /// [`ExtractedMetadata`] is empty and the files' own EXIF is authoritative.
334    fn extract(&self, parts: &[PathBuf]) -> Result<ExtractedImport, AdapterError> {
335        if parts.is_empty() {
336            return Err(AdapterError::NoParts);
337        }
338        for part in parts {
339            if !part.is_dir() {
340                return Err(AdapterError::Io {
341                    root: part.display().to_string(),
342                    reason: "not a directory".into(),
343                });
344            }
345        }
346        let scan = crate::import::scanner::scan(parts).map_err(|e| AdapterError::Io {
347            root: parts
348                .iter()
349                .map(|p| p.display().to_string())
350                .collect::<Vec<_>>()
351                .join(", "),
352            reason: e.to_string(),
353        })?;
354        let mut entries: Vec<SourceEntry> = scan
355            .candidates
356            .into_iter()
357            .map(|candidate| SourceEntry {
358                candidate,
359                metadata: ExtractedMetadata::default(),
360            })
361            .collect();
362        entries.sort_by(|a, b| a.primary_path().cmp(b.primary_path()));
363        Ok(ExtractedImport { entries })
364    }
365}
366
367/// Every file object on the camera, in the contract's order. An object whose record cannot be
368/// read is a failure, not an omission, and so is a storage the camera will not list: the other
369/// storages are still enumerated.
370fn enumerate(
371    device: &mut dyn CameraDevice,
372    failures: &mut Vec<ObjectFailure>,
373    storage_failures: &mut Vec<StorageFailure>,
374) -> Result<Vec<CameraObject>, CameraError> {
375    let mut storages = match device.storage_ids() {
376        Ok(storages) => storages,
377        Err(error) if !error.is_fatal() => {
378            tracing::warn!(%error, "camera import: storage list refused");
379            storage_failures.push(StorageFailure {
380                storage: None,
381                error,
382            });
383            return Ok(Vec::new());
384        }
385        Err(error) => return Err(error),
386    };
387    storages.sort_unstable();
388    storages.dedup();
389    let mut objects = Vec::new();
390    for storage in storages {
391        let mut handles = match device.object_handles(storage) {
392            Ok(handles) => handles,
393            Err(error) if !error.is_fatal() => {
394                tracing::warn!(
395                    storage = format_args!("{storage:08x}"),
396                    %error,
397                    "camera import: storage not listed; continuing with the others"
398                );
399                storage_failures.push(StorageFailure {
400                    storage: Some(storage),
401                    error,
402                });
403                continue;
404            }
405            Err(error) => return Err(error),
406        };
407        handles.sort_unstable();
408        handles.dedup();
409        tracing::debug!(
410            storage = format_args!("{storage:08x}"),
411            handles = handles.len(),
412            "camera import: storage listed"
413        );
414        for handle in handles {
415            match device.object(handle) {
416                Ok(object) if object.is_folder => {}
417                Ok(object) => objects.push(object),
418                Err(error) if !error.is_fatal() => failures.push(ObjectFailure {
419                    storage,
420                    handle,
421                    filename: None,
422                    error,
423                }),
424                Err(error) => return Err(error),
425            }
426        }
427    }
428    objects.sort_by(|a, b| {
429        (a.storage, a.handle, a.captured_at).cmp(&(b.storage, b.handle, b.captured_at))
430    });
431    Ok(objects)
432}
433
434/// A file sink that hashes and counts what passes through it.
435struct HashingSink<W> {
436    inner: W,
437    hasher: Sha256Hasher,
438    written: u64,
439}
440
441impl<W: Write> Write for HashingSink<W> {
442    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
443        let n = self.inner.write(buf)?;
444        self.hasher.update(&buf[..n]);
445        self.written += n as u64;
446        Ok(n)
447    }
448
449    fn flush(&mut self) -> io::Result<()> {
450        self.inner.flush()
451    }
452}
453
454fn staging_error(path: &Path) -> impl FnOnce(io::Error) -> CameraError + '_ {
455    move |source| CameraError::Staging {
456        path: path.to_path_buf(),
457        source,
458    }
459}
460
461/// Receive one object into its staged path, in folder generation `start` (its stem group's) or,
462/// where that is taken, the next free one.
463fn receive_one(
464    root: &Path,
465    device: &mut dyn CameraDevice,
466    object: &CameraObject,
467    start: u32,
468) -> Result<ReceivedObject, CameraError> {
469    let generation = match find_slot(root, object, start)? {
470        Slot::Staged(done) => return Ok(done),
471        Slot::Free { generation } => generation,
472    };
473    let final_path = staging::object_path(root, object, generation);
474
475    let partial = staging::partial_path(root, object);
476    let checkpoint = staging::checkpoint_path(&partial);
477    let parent = partial.parent().unwrap_or(root);
478    fs::create_dir_all(parent).map_err(staging_error(parent))?;
479
480    // Continue a partial file only where the camera can serve the rest, the size is known, and
481    // the prefix an earlier run made durable still hashes to its checkpoint.
482    let durable = match object.size {
483        Some(size) if device.supports_partial_reads() => {
484            durable_prefix(&partial, &checkpoint, size)
485        }
486        _ => None,
487    };
488    let (file, hasher, offset) = if let Some((offset, hasher)) = durable {
489        let file = reopen_partial(&partial, offset).map_err(staging_error(&partial))?;
490        tracing::debug!(
491            handle = format_args!("{:08x}", object.handle),
492            offset,
493            "camera import: resuming partial object"
494        );
495        (file, hasher, offset)
496    } else {
497        // A stale checkpoint could only ever match the very bytes it recorded; drop it anyway.
498        let _ = fs::remove_file(&checkpoint);
499        let file = File::create(&partial).map_err(staging_error(&partial))?;
500        (file, Sha256Hasher::new(), 0)
501    };
502
503    let mut sink = HashingSink {
504        inner: BufWriter::new(file),
505        hasher,
506        written: 0,
507    };
508    let delivered = match device.read_object(object, offset, &mut sink) {
509        Ok(delivered) => delivered,
510        Err(CameraError::Sink(source)) => {
511            return Err(CameraError::Staging {
512                path: partial,
513                source,
514            });
515        }
516        Err(error @ CameraError::Disconnected(_)) => {
517            // Keep the partial file only when the connection dropped, which is what resuming is
518            // for, and only once its bytes are synced and its checkpoint records them.
519            if let Err(source) = checkpoint_partial(sink, offset, &partial, &checkpoint) {
520                tracing::warn!(
521                    handle = format_args!("{:08x}", object.handle),
522                    path = %partial.display(),
523                    %source,
524                    "camera import: partial object not made durable; it will restart"
525                );
526                discard(&partial, &checkpoint);
527            }
528            return Err(error);
529        }
530        Err(error) => {
531            // A refusal says nothing about the bytes already written, so start over.
532            drop(sink);
533            discard(&partial, &checkpoint);
534            return Err(error);
535        }
536    };
537    let HashingSink {
538        inner,
539        hasher,
540        written,
541    } = sink;
542    let file = inner.into_inner().map_err(|e| CameraError::Staging {
543        path: partial.clone(),
544        source: e.into_error(),
545    })?;
546    file.sync_all().map_err(staging_error(&partial))?;
547    drop(file);
548
549    let size = offset + written;
550    if written != delivered {
551        tracing::warn!(
552            delivered,
553            written,
554            "camera import: device count and sink count differ; trusting the sink"
555        );
556    }
557    if let Some(declared) = object.size
558        && declared != size
559    {
560        discard(&partial, &checkpoint);
561        return Err(CameraError::SizeMismatch {
562            handle: object.handle,
563            declared,
564            received: size,
565        });
566    }
567
568    let received_hash = hasher.finalize();
569    let staged_hash = hash_file(&partial).map_err(staging_error(&partial))?;
570    if staged_hash != received_hash {
571        discard(&partial, &checkpoint);
572        return Err(CameraError::IntegrityMismatch {
573            handle: object.handle,
574            received: received_hash,
575            staged: staged_hash,
576        });
577    }
578
579    // Record which object this is before the file appears, so a staged file always has one.
580    let identity = staging::identity_path(root, object, generation);
581    let identity_parent = identity.parent().unwrap_or(root);
582    fs::create_dir_all(identity_parent).map_err(staging_error(identity_parent))?;
583    write_synced(&identity, staging::identity_key(object).as_bytes())
584        .map_err(staging_error(&identity))?;
585    let dir = final_path.parent().unwrap_or(root);
586    fs::create_dir_all(dir).map_err(staging_error(dir))?;
587    fs::rename(&partial, &final_path).map_err(staging_error(&final_path))?;
588    let _ = fs::remove_file(&checkpoint);
589    tracing::debug!(
590        handle = format_args!("{:08x}", object.handle),
591        path = %final_path.display(),
592        generation,
593        size,
594        resumed_from = offset,
595        sha256 = %received_hash,
596        "camera import: object received"
597    );
598    Ok(ReceivedObject {
599        object: object.clone(),
600        path: final_path,
601        size,
602        sha256: received_hash,
603        resumed_from: offset,
604        already_staged: false,
605    })
606}
607
608/// The most folder generations one staged path is probed through before the run gives up.
609const MAX_GENERATIONS: u32 = 1024;
610
611/// Where an object goes in the staging tree.
612enum Slot {
613    /// An earlier run already verified and staged this very object.
614    Staged(ReceivedObject),
615    /// The folder generation to stage it in: free, or holding a damaged copy of this object.
616    Free { generation: u32 },
617}
618
619/// The scanner's stacking key for a staged object: its storage, its camera folder, and the
620/// lowercase stem of its staged file name, as `group_by_stem` computes it. Members of one group
621/// stack only when they share a directory, so each group is staged in one folder generation.
622#[derive(Debug, Clone, PartialEq, Eq, Hash)]
623struct StemGroup {
624    storage: u32,
625    parent: u32,
626    stem: String,
627}
628
629impl StemGroup {
630    fn of(object: &CameraObject) -> Self {
631        Self {
632            storage: object.storage,
633            parent: object.parent,
634            stem: stem_of(&staged_name(object)),
635        }
636    }
637}
638
639/// The file name `object` is staged under, in whichever generation.
640fn staged_name(object: &CameraObject) -> OsString {
641    staging::object_path(Path::new(""), object, 0)
642        .file_name()
643        .map(OsString::from)
644        .unwrap_or_default()
645}
646
647/// The lowercase stem of a file name, as the scanner's stem grouping compares it.
648fn stem_of(name: &std::ffi::OsStr) -> String {
649    Path::new(name)
650        .file_stem()
651        .unwrap_or_default()
652        .to_string_lossy()
653        .to_lowercase()
654}
655
656/// The staged file names in one folder directory, by lowercase stem.
657type FolderListing = HashMap<String, Vec<OsString>>;
658
659/// List `dir` by stem; a directory not yet created is empty.
660fn list_folder(dir: &Path) -> Result<FolderListing, CameraError> {
661    let mut listing = FolderListing::new();
662    let entries = match fs::read_dir(dir) {
663        Ok(entries) => entries,
664        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(listing),
665        Err(error) => return Err(staging_error(dir)(error)),
666    };
667    for entry in entries {
668        let name = entry.map_err(staging_error(dir))?.file_name();
669        listing.entry(stem_of(&name)).or_default().push(name);
670    }
671    Ok(listing)
672}
673
674/// The folder generation each stem group among `objects` is staged in.
675///
676/// A group goes to the first generation whose directory either already holds one of its members
677/// (with that member's own identity) or holds no file of its stem at all, so a stack's members always land side by side
678/// and never beside an unrelated earlier object of the same stem (a reformatted card that
679/// restarted its counter, shot RAW-only before and RAW+JPEG now). Each folder directory is listed
680/// once.
681fn group_generations(
682    root: &Path,
683    objects: &[CameraObject],
684) -> Result<HashMap<StemGroup, u32>, CameraError> {
685    let mut groups: HashMap<StemGroup, Vec<&CameraObject>> = HashMap::new();
686    for object in objects {
687        groups
688            .entry(StemGroup::of(object))
689            .or_default()
690            .push(object);
691    }
692    let mut listings: HashMap<PathBuf, FolderListing> = HashMap::new();
693    let mut generations = HashMap::with_capacity(groups.len());
694    for (group, members) in groups {
695        let generation = group_generation(root, &group, &members, &mut listings)?;
696        if generation > 0 {
697            tracing::debug!(
698                storage = format_args!("{:08x}", group.storage),
699                parent = format_args!("{:08x}", group.parent),
700                stem = %group.stem,
701                members = members.len(),
702                generation,
703                "camera import: stem group staged in a later folder generation"
704            );
705        }
706        generations.insert(group, generation);
707    }
708    tracing::debug!(
709        groups = generations.len(),
710        moved = generations.values().filter(|g| **g > 0).count(),
711        folders_listed = listings.len(),
712        "camera import: folder generations chosen"
713    );
714    Ok(generations)
715}
716
717/// The first folder generation where a staged file of `group`'s stem is one of `members` holding
718/// its own identity record, or where no file of that stem is staged at all.
719fn group_generation(
720    root: &Path,
721    group: &StemGroup,
722    members: &[&CameraObject],
723    listings: &mut HashMap<PathBuf, FolderListing>,
724) -> Result<u32, CameraError> {
725    let first = members[0];
726    for generation in 0..MAX_GENERATIONS {
727        let path = staging::object_path(root, first, generation);
728        let dir = path.parent().unwrap_or(root).to_path_buf();
729        if !listings.contains_key(&dir) {
730            let listing = list_folder(&dir)?;
731            listings.insert(dir.clone(), listing);
732        }
733        let staged = listings[&dir]
734            .get(&group.stem)
735            .map_or(&[][..], Vec::as_slice);
736        let own = |name: &OsString| {
737            members.iter().any(|member| {
738                staged_name(member) == *name && holds_identity(root, member, generation)
739            })
740        };
741        // A member already staged here pins the group to this generation, even when the run
742        // lists only part of it (a member deleted in-camera or unreadable this time): the
743        // absent member's copy is the group's own, not an unrelated object of its stem.
744        if staged.iter().any(own) {
745            tracing::trace!(
746                dir = %dir.display(),
747                stem = %group.stem,
748                generation,
749                "camera import: stem group already staged in this folder generation"
750            );
751            return Ok(generation);
752        }
753        if staged.is_empty() {
754            return Ok(generation);
755        }
756        tracing::debug!(
757            dir = %dir.display(),
758            stem = %group.stem,
759            "camera import: folder holds another object of this stem; trying the next generation"
760        );
761    }
762    Err(CameraError::Staging {
763        path: staging::object_path(root, first, 0),
764        source: io::Error::other(format!(
765            "{MAX_GENERATIONS} staged folders already hold this file stem"
766        )),
767    })
768}
769
770/// Whether the identity recorded for `object`'s path in `generation` is `object`'s own.
771fn holds_identity(root: &Path, object: &CameraObject, generation: u32) -> bool {
772    fs::read_to_string(staging::identity_path(root, object, generation))
773        .is_ok_and(|recorded| recorded.trim() == staging::identity_key(object))
774}
775
776/// Find `object`'s place in the staging tree, from folder generation `start` (its stem group's)
777/// onwards.
778///
779/// A staged file is this object only when the identity recorded beside it is this object's
780/// identity key; a file without one, or with another object's, is left alone and the next folder
781/// generation is tried. That happens past `start` only where two objects of one run share a
782/// staged name. A staged copy of this object whose size differs from the camera's declared
783/// size is damaged and is received again in place. An accepted copy's bytes were verified before
784/// the rename that put them there.
785fn find_slot(root: &Path, object: &CameraObject, start: u32) -> Result<Slot, CameraError> {
786    let key = staging::identity_key(object);
787    for generation in start..MAX_GENERATIONS {
788        let path = staging::object_path(root, object, generation);
789        let Ok(metadata) = fs::metadata(&path) else {
790            return Ok(Slot::Free { generation });
791        };
792        let recorded = fs::read_to_string(staging::identity_path(root, object, generation)).ok();
793        if recorded.as_deref().map(str::trim) != Some(key.as_str()) {
794            tracing::debug!(
795                handle = format_args!("{:08x}", object.handle),
796                path = %path.display(),
797                "camera import: staged path holds another object; trying the next generation"
798            );
799            continue;
800        }
801        if object.size.is_some_and(|size| size != metadata.len()) {
802            tracing::warn!(
803                path = %path.display(),
804                staged = metadata.len(),
805                declared = ?object.size,
806                "camera import: staged file differs from the camera's object; fetching again"
807            );
808            return Ok(Slot::Free { generation });
809        }
810        let sha256 = hash_file(&path).map_err(staging_error(&path))?;
811        tracing::debug!(
812            handle = format_args!("{:08x}", object.handle),
813            path = %path.display(),
814            "camera import: already staged"
815        );
816        return Ok(Slot::Staged(ReceivedObject {
817            object: object.clone(),
818            path,
819            size: metadata.len(),
820            sha256,
821            resumed_from: 0,
822            already_staged: true,
823        }));
824    }
825    Err(CameraError::Staging {
826        path: staging::object_path(root, object, 0),
827        source: io::Error::other(format!(
828            "{MAX_GENERATIONS} staged objects already hold this path"
829        )),
830    })
831}
832
833/// The length of `partial`'s prefix that an earlier run made durable, and a hasher over it, if
834/// its checkpoint is readable and the prefix on disk still hashes to the recorded digest. A
835/// prefix a crash corrupted, or one never checkpointed, is not resumed.
836fn durable_prefix(partial: &Path, checkpoint: &Path, size: u64) -> Option<(u64, Sha256Hasher)> {
837    let recorded = fs::read_to_string(checkpoint).ok()?;
838    let (len, digest) = recorded.trim().split_once(' ')?;
839    let len: u64 = len.parse().ok()?;
840    let digest = Hash32::from_hex(digest).ok()?;
841    if len == 0 || len >= size {
842        return None;
843    }
844    let mut hasher = Sha256Hasher::new();
845    let read = File::open(partial)
846        .and_then(|file| hash_into(&mut file.take(len), &mut hasher))
847        .ok()?;
848    if read != len || hasher.clone().finalize() != digest {
849        tracing::warn!(
850            path = %partial.display(),
851            checkpoint = len,
852            on_disk = read,
853            "camera import: partial object no longer matches its checkpoint; restarting it"
854        );
855        return None;
856    }
857    Some((len, hasher))
858}
859
860/// Open `partial` to continue writing at `offset`, cutting off the bytes past it: they were never
861/// confirmed durable, so they are received again.
862///
863/// The handle is opened for writing and positioned at `offset`, not opened for append: on Windows
864/// an append-only handle lacks `FILE_WRITE_DATA`, so truncating through it is refused.
865fn reopen_partial(partial: &Path, offset: u64) -> io::Result<File> {
866    let mut file = OpenOptions::new().write(true).open(partial)?;
867    file.set_len(offset)?;
868    file.seek(SeekFrom::Start(offset))?;
869    Ok(file)
870}
871
872/// Sync what `sink` holds to disk, then record its length and digest in `checkpoint`.
873fn checkpoint_partial(
874    sink: HashingSink<BufWriter<File>>,
875    offset: u64,
876    partial: &Path,
877    checkpoint: &Path,
878) -> io::Result<()> {
879    let HashingSink {
880        inner,
881        hasher,
882        written,
883    } = sink;
884    let file = inner.into_inner().map_err(io::IntoInnerError::into_error)?;
885    file.sync_all()?;
886    drop(file);
887    let len = offset + written;
888    write_synced(
889        checkpoint,
890        format!("{len} {}\n", hasher.finalize().to_hex()).as_bytes(),
891    )?;
892    tracing::debug!(
893        path = %partial.display(),
894        len,
895        "camera import: partial object checkpointed"
896    );
897    Ok(())
898}
899
900/// Write `bytes` to a fresh file at `path` and sync it.
901fn write_synced(path: &Path, bytes: &[u8]) -> io::Result<()> {
902    let mut file = File::create(path)?;
903    file.write_all(bytes)?;
904    file.sync_all()
905}
906
907/// Remove a partial file and its checkpoint, so the object starts over next time.
908fn discard(partial: &Path, checkpoint: &Path) {
909    let _ = fs::remove_file(partial);
910    let _ = fs::remove_file(checkpoint);
911}
912
913/// Hash `reader` to its end into `hasher`; returns the bytes read.
914fn hash_into(reader: &mut dyn Read, hasher: &mut Sha256Hasher) -> io::Result<u64> {
915    let mut buf = vec![0u8; 64 * 1024];
916    let mut total = 0u64;
917    loop {
918        let n = reader.read(&mut buf)?;
919        if n == 0 {
920            return Ok(total);
921        }
922        hasher.update(&buf[..n]);
923        total += n as u64;
924    }
925}
926
927#[cfg(test)]
928mod tests;