capsule_library/import/enrichment.rs
1//! Folding a third-party adapter's [`ExtractedMetadata`] into the **signed sidecar** at import.
2//!
3//! A [source adapter](crate::import::importers) already resolves the [precedence rule] at
4//! extraction — embedded EXIF wins over the exporter's records, **except** for constructs the
5//! exporter is authoritative for (album membership, favorites/rating, user-typed descriptions).
6//! This module is the other half: it maps that folded record onto the fields the signed
7//! [`SidecarV1`](capsule_core::sidecar::SidecarV1) actually has, and indexes it by source
8//! path so the [executor](crate::import::executor) can attach it to the member it is importing.
9//!
10//! The mapping, one row per [Takeout mapping-table] rule:
11//!
12//! | Folded field | Sidecar destination | Rule |
13//! | --- | --- | --- |
14//! | `taken_time` | `capture_timestamp` | fallback — the file's own EXIF wins at the write site |
15//! | `gps` | `gps` (as [`GpsSource::Manual`]) | fallback — the file's own EXIF GPS wins |
16//! | `description` | `caption` LWW register | exporter-authoritative |
17//! | `favorite` | `rating` LWW register = [`FAVORITE_RATING`] | exporter-authoritative |
18//! | `albums` | `tags_user` OR-set | exporter-authoritative |
19//!
20//! Two of those mappings are **not** stated by the design docs and are recorded here as the
21//! decision this change took, so a later change can revisit them deliberately:
22//!
23//! - **Favorites.** Capsule models no "favorite" flag. The two candidate registers are the
24//! numeric star `rating` and the trinary `cull` flag, and [Organization — Culling] keeps them
25//! deliberately orthogonal: `cull` is a *review-pass* state (`pick` means "kept in a cull"),
26//! while `rating` is the user's expressed regard for a photo. A Google Photos favorite is the
27//! latter, so it lands as the maximum star value; `cull` is left untouched (a favorite is not
28//! a culling decision, and writing one would fabricate a review the user never made).
29//! - **Album membership.** An asset belongs to exactly one [container album], which the plan
30//! resolves once for the whole import; the sidecar has no per-asset album field, and
31//! [Organization — The Default Album] forbids an automated import from inventing destinations.
32//! So the exporter's album titles are preserved as `tags_user` entries, normalized by the
33//! label rule at the write site (a title the rule refuses is dropped) — the only
34//! multi-valued user-content set in the sidecar, and a [smart-album] queryable field, so a
35//! Google Photos album can be reconstructed later as a view over `tags_user contains "…"`
36//! without re-encrypting or moving anything.
37//!
38//! [precedence rule]: https://docs/design/import/pipeline/#third-party-importers
39//! [Takeout mapping-table]: https://docs/design/import/pipeline/#third-party-importers
40//! [Organization — Culling]: https://docs/design/organization/#culling
41//! [container album]: https://docs/design/organization/#container-albums
42//! [Organization — The Default Album]: https://docs/design/organization/#the-default-album
43//! [smart-album]: https://docs/design/organization/#smart-album-definition-schema
44//!
45//! ## Test contract
46//!
47//! - `no_exporter_record_yields_no_enrichment` — a default [`ExtractedMetadata`] maps to
48//! [`None`], so the executor attaches nothing and the write path is untouched (the
49//! byte-stability floor).
50//! - `taken_time_and_gps_carry_across_as_fallbacks` — folded values reach the enrichment, GPS
51//! tagged [`GpsSource::Manual`] in the WGS-84 datum Takeout publishes.
52//! - `a_favorite_maps_to_the_max_star_rating` / `a_non_favorite_leaves_the_rating_unwritten`.
53//! - `a_description_maps_to_the_caption` and `an_oversize_description_is_bounded_on_a_char_boundary`.
54//! - `album_membership_maps_to_user_tags`.
55//! - `the_index_resolves_every_member_of_a_stacked_entry` / `the_index_misses_an_unknown_path`.
56
57use std::collections::BTreeMap;
58use std::path::{Path, PathBuf};
59
60use capsule_core::domain::GpsDatum;
61use capsule_core::sidecar::sidecar_v1::{Gps, GpsSource};
62
63use crate::import::importers::{ExtractedImport, ExtractedMetadata};
64use crate::lifecycle::SidecarEnrichment;
65
66/// The star rating an exporter-side "favorite" maps to — the top of the 0–5 scale.
67pub const FAVORITE_RATING: u8 = 5;
68
69/// The caption bound the [metadata schema] fixes (`caption_lww.value` ≤ 4096 bytes). A longer
70/// exporter description is truncated on a character boundary rather than dropped: the sidecar
71/// is a copy, and the exporter's own JSON remains the untruncated record.
72///
73/// [metadata schema]: https://docs/design/metadata/#sidecar-schema-v1
74pub const CAPTION_MAX_BYTES: usize = 4096;
75
76/// The folded exporter metadata of a whole export, keyed by **every** source path it covers.
77///
78/// An [`ExtractedImport`] is keyed by each entry's *primary* path, but the executor imports one
79/// member at a time (an edited rendition is its own signed asset), so the index maps every
80/// member of an entry to that entry's record: the exporter describes the photograph, and each
81/// member is a rendition of it.
82#[derive(Debug, Default, Clone)]
83pub struct SourceMetadataIndex {
84 by_path: BTreeMap<PathBuf, ExtractedMetadata>,
85}
86
87impl SourceMetadataIndex {
88 /// An index covering nothing — what a plain filesystem import attaches.
89 #[must_use]
90 pub fn empty() -> Self {
91 Self::default()
92 }
93
94 /// Index an adapter's extraction by every member path of every entry.
95 #[must_use]
96 pub fn from_extracted(extracted: &ExtractedImport) -> Self {
97 let mut by_path = BTreeMap::new();
98 for entry in &extracted.entries {
99 for (path, _role) in &entry.candidate.members {
100 by_path.insert(path.clone(), entry.metadata.clone());
101 }
102 }
103 Self { by_path }
104 }
105
106 /// The folded record for a source file, if the export carried one.
107 #[must_use]
108 pub fn get(&self, path: &Path) -> Option<&ExtractedMetadata> {
109 self.by_path.get(path)
110 }
111
112 /// How many source files the index covers.
113 #[must_use]
114 pub fn len(&self) -> usize {
115 self.by_path.len()
116 }
117
118 /// Whether the index covers nothing.
119 #[must_use]
120 pub fn is_empty(&self) -> bool {
121 self.by_path.is_empty()
122 }
123}
124
125/// Map one folded exporter record onto the sidecar fields it enriches, or [`None`] when the
126/// record carries nothing to write.
127///
128/// The [`None`] case is load-bearing: an entry whose export supplied no metadata must reach the
129/// signed write path with no enrichment at all, so its sidecar encodes byte-identically to a
130/// plain filesystem import's.
131#[must_use]
132pub fn sidecar_enrichment(metadata: &ExtractedMetadata) -> Option<SidecarEnrichment> {
133 let enrichment = SidecarEnrichment {
134 capture_time: metadata.taken_time,
135 // Takeout publishes WGS-84 coordinates, so the datum stays the wire-absent default. The
136 // fix is *not* tagged `Exif`: it was read out of the exporter's record, not out of these
137 // file bytes, and the sidecar is signed — `Manual` is the honest provenance for a
138 // service-held, user-editable location.
139 gps: metadata.gps.map(|p| Gps {
140 lat: p.lat,
141 lon: p.lon,
142 source: GpsSource::Manual,
143 datum: GpsDatum::Wgs84,
144 }),
145 caption: metadata.description.as_deref().map(bounded_caption),
146 rating: metadata.favorite.then_some(FAVORITE_RATING),
147 tags: metadata.albums.clone(),
148 };
149 (enrichment != SidecarEnrichment::default()).then_some(enrichment)
150}
151
152/// Truncate a description to [`CAPTION_MAX_BYTES`] on a character boundary.
153fn bounded_caption(text: &str) -> String {
154 if text.len() <= CAPTION_MAX_BYTES {
155 return text.to_string();
156 }
157 let mut end = CAPTION_MAX_BYTES;
158 while !text.is_char_boundary(end) {
159 end -= 1;
160 }
161 tracing::warn!(
162 source_bytes = text.len(),
163 kept_bytes = end,
164 "import: exporter description exceeds the sidecar caption bound; truncated"
165 );
166 text[..end].to_string()
167}
168
169// ── Tests ────────────────────────────────────────────────────────────────────
170
171#[cfg(test)]
172mod tests;
173
174// ── Archive-level tests: the mapping table, at the signed sidecar ────────────
175//
176// The unit tests above pin the mapping; these pin the *deliverable* — that a Takeout import
177// actually lands the exporter's metadata inside the signed sidecar, under the precedence rule,
178// and that an import carrying no exporter record is byte-identical to a plain one.
179//
180// Test contract:
181//
182// - `embedded_exif_beats_the_exporter_and_the_exporter_authoritative_fields_land` — one archive
183// entry whose EXIF and JSON sidecar disagree on **both** capture time and GPS: EXIF wins both,
184// while the description, favorite, and album membership are written from the exporter.
185// - `the_exporter_fills_capture_and_gps_when_the_bytes_carry_none` — the other arm of the rule.
186// - `re_running_the_enriched_import_skips_completed_work` — determinism/resume is unchanged by
187// the enrichment path.
188// - `an_import_with_no_exporter_metadata_is_byte_stable` — a default enrichment reaching the
189// write path encodes to the same canonical bytes as no enrichment at all.
190#[cfg(test)]
191mod archive_tests;