capsule_library/import/planner.rs
1use std::path::Path;
2
3use capsule_core::domain::ImportMode;
4use capsule_core::import::default_album::{
5 DefaultAlbumContext, ResolvedAlbum, resolve_default_album,
6};
7use capsule_core::import::scan::{ImportCandidate, ScanResult};
8use capsule_core::import::upload::{
9 StagedStreamingConflict, UploadPolicy, ensure_streaming_compatible,
10};
11
12use crate::db::DatabaseDriver;
13use crate::library::{LibraryError, available_bytes};
14
15/// Configuration for an import run.
16#[derive(Debug, Clone)]
17pub struct ImportConfig {
18 pub import_mode: ImportMode,
19 /// Where this import should land, as the **inputs to the resolution order** rather than
20 /// a raw destination id (SSoT: organization § The Default Album). The planner runs
21 /// [`resolve_default_album`] over it and records the fired rule on the plan; the
22 /// executor binds the library's derived de facto album (rule 3) before running the same
23 /// single resolution. Default is unbound — "the user filed this nowhere".
24 pub album: DefaultAlbumContext,
25 /// If true, import even if a file with the same SHA-256 hash already exists.
26 pub force_reimport_duplicates: bool,
27 /// The per-device upload policy (staged uploads). `Full` (the
28 /// default) opens every bundle session eagerly; `Staged` opens them in tier
29 /// order gated by the connection class, and is **mutually exclusive** with a
30 /// streaming import — the planner rejects the combination at confirmation
31 /// ([`ImportActionPlan::confirm_upload_policy`]) and the streaming executor
32 /// refuses it by construction.
33 pub upload_policy: UploadPolicy,
34}
35
36impl Default for ImportConfig {
37 fn default() -> Self {
38 Self {
39 import_mode: ImportMode::Copy,
40 album: DefaultAlbumContext::default(),
41 force_reimport_duplicates: false,
42 upload_policy: UploadPolicy::Full,
43 }
44 }
45}
46
47/// Decision for a single candidate.
48#[derive(Debug, Clone)]
49pub enum ImportDecision {
50 Import,
51 SkipDuplicate { existing_uuid: String },
52 SkipError(String),
53}
54
55/// What the plan decided, counted. There is no "unsupported" bucket, by design: a file is
56/// imported, already held, or could not be read. Neither its format nor whether this build has
57/// a codec for it can keep it out of the library (issue #695).
58#[derive(Debug, Default, Clone)]
59pub struct PlanCounts {
60 pub to_import: usize,
61 pub duplicates: usize,
62 pub errors: usize,
63 /// Total bytes the plan will bring into the library: the summed on-disk size of every
64 /// source file of every `Import` candidate (skips contribute nothing). This is the
65 /// `total_size` the confirmation UI shows and the free-space probe compares against to set
66 /// [`ImportActionPlan::streaming_recommended`]. Missing/unreadable sizes count as zero — the
67 /// same file already reports as a `SkipError`, so it is not double-charged as import bytes.
68 pub total_size: u64,
69}
70
71/// Output of Phase 2 (plan).
72#[derive(Debug)]
73pub struct ImportActionPlan {
74 pub actions: Vec<(ImportCandidate, ImportDecision)>,
75 pub counts: PlanCounts,
76 /// The free-space probe's streaming recommendation, attached **at confirmation** by
77 /// [`attach_streaming_recommendation`](Self::attach_streaming_recommendation) — never by the
78 /// pure planner (the probe is I/O). `None` until attached; `Some(true)` means the library
79 /// volume is near/over full for this plan's `total_size` and the user should confirm a
80 /// [streaming import](crate::import::execute_streaming). Recording it on the plan (like the resolved
81 /// destination `album_id`) keeps the planner deterministic.
82 pub streaming_recommended: Option<bool>,
83 /// The destination album and **which resolution rule chose it** (SSoT: organization
84 /// § The Default Album), so a surprising destination is explainable after the fact.
85 ///
86 /// `None` when [`ImportConfig::album`] was still unbound at plan time — the library's
87 /// derived de facto album (rule 3) is the workspace's to supply, and the executor binds
88 /// it and runs the same [`resolve_default_album`] before writing anything. There is one
89 /// resolution policy, never two.
90 pub album: Option<ResolvedAlbum>,
91}
92
93impl ImportActionPlan {
94 /// Per-`Import`-candidate source-byte sizes, largest first — the input to the streaming
95 /// minimum-headroom check (the largest single asset must fully materialize locally). Skip
96 /// decisions contribute nothing.
97 pub fn import_candidate_sizes(&self) -> Vec<u64> {
98 let mut sizes: Vec<u64> = self
99 .actions
100 .iter()
101 .filter(|(_, d)| matches!(d, ImportDecision::Import))
102 .map(|(c, _)| candidate_size(c))
103 .collect();
104 sizes.sort_unstable_by(|a, b| b.cmp(a));
105 sizes
106 }
107
108 /// The largest single `Import` candidate's size, or `0` when nothing will be imported.
109 pub fn largest_import_size(&self) -> u64 {
110 self.import_candidate_sizes().into_iter().max().unwrap_or(0)
111 }
112
113 /// Attach the free-space probe's streaming recommendation **at confirmation**: probe
114 /// `library_root`'s available bytes (I/O — never inside the pure planner) and set
115 /// [`streaming_recommended`](Self::streaming_recommended) from the pure
116 /// [`streaming_recommended`](crate::library::streaming_recommended) predicate over this
117 /// plan's `total_size`. Returns the attached verdict.
118 #[tracing::instrument(skip_all, fields(total_size = self.counts.total_size))]
119 pub fn attach_streaming_recommendation(
120 &mut self,
121 library_root: &Path,
122 headroom_margin: u64,
123 ) -> Result<bool, LibraryError> {
124 let available = available_bytes(library_root)?;
125 Ok(self.set_streaming_recommendation(available, headroom_margin))
126 }
127
128 /// The pure half of [`attach_streaming_recommendation`](Self::attach_streaming_recommendation),
129 /// taking an already-probed `available` so the auto-detect verdict is unit-testable without
130 /// touching a real volume. Sets and returns [`streaming_recommended`](Self::streaming_recommended).
131 pub fn set_streaming_recommendation(&mut self, available: u64, headroom_margin: u64) -> bool {
132 let recommended = crate::library::streaming_recommended(
133 self.counts.total_size,
134 available,
135 headroom_margin,
136 );
137 self.streaming_recommended = Some(recommended);
138 recommended
139 }
140
141 /// **Confirmation-time upload-policy gate** (staged uploads).
142 ///
143 /// A [`UploadPolicy::Staged`] run and a streaming import are mutually exclusive
144 /// per import (transfer upload doc): streaming exists to release local bytes
145 /// quickly, staged defers exactly the T2 upload release depends on. This is the
146 /// planner's single rejection point — call it at confirmation with the run's
147 /// `policy` and whether a streaming import was chosen (`use_streaming`); a
148 /// conflicting combination returns [`StagedStreamingConflict`] instead of ever
149 /// entering the executor. Delegates to the pure [`ensure_streaming_compatible`]
150 /// invariant so the rule lives in one place.
151 pub fn confirm_upload_policy(
152 &self,
153 policy: UploadPolicy,
154 use_streaming: bool,
155 ) -> Result<(), StagedStreamingConflict> {
156 ensure_streaming_compatible(policy, use_streaming)
157 }
158}
159
160/// Phase 2 — decide what to do with each candidate from the scan.
161///
162/// SHA-256-hashes the primary member of each candidate and checks the DB for
163/// duplicates. Returns an `ImportActionPlan` with per-candidate decisions.
164pub fn plan(
165 scan: &ScanResult,
166 db: &DatabaseDriver,
167 config: &ImportConfig,
168) -> Result<ImportActionPlan, Box<dyn std::error::Error + Send + Sync>> {
169 // Resolve the destination album before hashing anything, so a surprising destination is
170 // explainable from the plan alone. An unbound context is not an error here: the executor
171 // binds the library's derived de facto album and runs the same resolution.
172 let album = resolve_default_album(&config.album).ok();
173
174 let mut actions = Vec::new();
175 let mut counts = PlanCounts::default();
176
177 for candidate in &scan.candidates {
178 let decision = decide(candidate, db, config)?;
179 match &decision {
180 ImportDecision::Import => {
181 counts.to_import += 1;
182 // total_size accumulates only what will actually be imported.
183 counts.total_size = counts.total_size.saturating_add(candidate_size(candidate));
184 }
185 ImportDecision::SkipDuplicate { .. } => counts.duplicates += 1,
186 ImportDecision::SkipError(_) => counts.errors += 1,
187 }
188 actions.push((candidate.clone(), decision));
189 }
190
191 Ok(ImportActionPlan {
192 actions,
193 counts,
194 streaming_recommended: None,
195 album,
196 })
197}
198
199/// The summed on-disk size of every source file in `candidate`. A file whose metadata cannot be
200/// read counts as zero — an unreadable file is already surfaced as a `SkipError`, so it never
201/// inflates the import byte total. Shared with the [streaming executor](crate::import::streaming),
202/// which names the largest candidate for the minimum-headroom error.
203pub(crate) fn candidate_size(candidate: &ImportCandidate) -> u64 {
204 candidate
205 .source_paths
206 .iter()
207 .map(|p| std::fs::metadata(p).map_or(0, |m| m.len()))
208 .sum()
209}
210
211fn decide(
212 candidate: &ImportCandidate,
213 db: &DatabaseDriver,
214 config: &ImportConfig,
215) -> Result<ImportDecision, Box<dyn std::error::Error + Send + Sync>> {
216 // Hash the primary file (first member with Primary role, or source_paths[0])
217 let primary_path = candidate.primary_path();
218
219 let hash = match hash_file(primary_path) {
220 Ok(h) => h,
221 Err(e) => {
222 return Ok(ImportDecision::SkipError(format!(
223 "failed to hash {}: {e}",
224 primary_path.display()
225 )));
226 }
227 };
228
229 if !config.force_reimport_duplicates
230 && let Some(existing) = db.find_by_hash(&hash)?
231 {
232 return Ok(ImportDecision::SkipDuplicate {
233 existing_uuid: existing.uuid,
234 });
235 }
236
237 Ok(ImportDecision::Import)
238}
239
240fn hash_file(path: &Path) -> Result<String, std::io::Error> {
241 Ok(crate::utils::hash_file(path)?.to_hex())
242}
243
244// ── Tests ────────────────────────────────────────────────────────────────────
245
246#[cfg(test)]
247mod tests;