Skip to main content

capsule_library/import/
executor.rs

1//! Phase 4 — execute an import plan onto the **signed lifecycle path**.
2//!
3//! Each `ImportDecision::Import` candidate is imported through
4//! [`Workspace::import_asset_with`](crate::lifecycle::Workspace::import_asset_with): every member
5//! becomes a signed [`SidecarV1`](capsule_core::sidecar::SidecarV1) + signed manifest +
6//! append-only provenance, self-verified through
7//! [`verify_asset`](capsule_core::crypto::verify_asset::verify_asset), and — when the still decodes —
8//! with a chromahash `lqip` in the sidecar and signed thumbnail derivatives on disk
9//! ([`capsule_core::media`]). A format with no
10//! codec in this build still imports, as a signed original with the gap recorded rather than
11//! hidden.
12//!
13//! This retired the legacy unsigned `AssetSidecar` write path from the executor; the production
14//! write path itself is now gone — no code writes unsigned sidecars anymore. Only the
15//! *read* path survives, for the recovery-first index rebuild
16//! ([`rebuild_index`](crate::library::rebuild_index)) that still ingests unsigned `.cbor`
17//! sidecars left by pre-signed-path libraries. The pure planner (`import::planner`) is unchanged:
18//! it still decides *what* to import; the executor decides *how* to commit it.
19
20use std::path::{Path, PathBuf};
21
22use capsule_core::domain::{ImportMode, MemberRole, StackType};
23use capsule_core::import::default_album::resolve_default_album;
24use capsule_core::import::scan::ImportCandidate;
25use capsule_core::sidecar::sidecar_v1::{StackMembership, StackRole};
26use uuid::Uuid;
27
28use crate::db::rows::{AssetStackRow, StackMemberRow};
29use crate::import::enrichment::{SourceMetadataIndex, sidecar_enrichment};
30use crate::import::executor_cancellation::CancellationToken;
31use crate::import::planner::{ImportActionPlan, ImportConfig, ImportDecision};
32use crate::import::progress::{ImportExecutionSummary, ImportOutcome, ImportProgressEvent};
33use crate::lifecycle::{LifecycleError, SidecarEnrichment, SignedImportOptions, Workspace};
34
35type ExecError = Box<dyn std::error::Error + Send + Sync>;
36
37/// Phase 4 — execute the import plan against `workspace`.
38///
39/// Every `ImportDecision::Import` candidate is committed through the signed lifecycle path; skip
40/// decisions are reported verbatim. Assets are written into the album resolved from
41/// `config.album` through [`resolve_default_album`] — the explicit pick, else the owner's
42/// `default_album_id` pointer, else the workspace's derived de facto album — which must already
43/// exist in the workspace.
44///
45/// This is a plain filesystem import: no exporter metadata is attached. A third-party import
46/// calls [`execute_with_source_metadata`] instead.
47pub fn execute(
48    plan: &ImportActionPlan,
49    workspace: &mut Workspace,
50    config: &ImportConfig,
51    on_event: impl Fn(ImportProgressEvent),
52    cancel: &CancellationToken,
53) -> Result<ImportExecutionSummary, ExecError> {
54    execute_with_source_metadata(
55        plan,
56        workspace,
57        config,
58        &SourceMetadataIndex::empty(),
59        on_event,
60        cancel,
61    )
62}
63
64/// [`execute`], with the folded metadata a third-party [source adapter] extracted attached to
65/// each file it covers.
66///
67/// The adapter resolved the [precedence rule] at extraction; the executor is what makes the
68/// result *durable* — each member's record is mapped onto sidecar fields by
69/// [`sidecar_enrichment`] and written inside the signed sidecar at import, rather than being
70/// discarded once the plan was built. A file the index does not cover imports exactly as it
71/// does through [`execute`].
72///
73/// **Catalog batching.** The plan runs in bounded batches (`IMPORT_BATCH_SIZE`, 64 entries),
74/// each one catalog transaction with every asset's index write a savepoint inside it. A
75/// `CandidateCompleted` event can therefore precede the commit that makes its rows visible
76/// to another connection; every batch has committed by the time this returns, which is
77/// before any caller can release a Move source.
78///
79/// [source adapter]: crate::import::SourceAdapter
80/// [precedence rule]: https://docs/design/import/pipeline/#third-party-importers
81pub fn execute_with_source_metadata(
82    plan: &ImportActionPlan,
83    workspace: &mut Workspace,
84    config: &ImportConfig,
85    source: &SourceMetadataIndex,
86    on_event: impl Fn(ImportProgressEvent),
87    cancel: &CancellationToken,
88) -> Result<ImportExecutionSummary, ExecError> {
89    execute_batched(
90        plan,
91        workspace,
92        config,
93        source,
94        on_event,
95        cancel,
96        IMPORT_BATCH_SIZE,
97    )
98}
99
100/// [`execute_with_source_metadata`] with the catalog batch size as a parameter, so tests can
101/// cross a batch boundary without importing [`IMPORT_BATCH_SIZE`] files.
102#[tracing::instrument(
103    skip_all,
104    fields(
105        candidates = plan.actions.len(),
106        mode = ?config.import_mode,
107        source_metadata = source.len(),
108        batch_size,
109    )
110)]
111pub(crate) fn execute_batched(
112    plan: &ImportActionPlan,
113    workspace: &mut Workspace,
114    config: &ImportConfig,
115    source: &SourceMetadataIndex,
116    on_event: impl Fn(ImportProgressEvent),
117    cancel: &CancellationToken,
118    batch_size: usize,
119) -> Result<ImportExecutionSummary, ExecError> {
120    // The library is the only authority on the derived de facto album (rule 3), so bind it
121    // here and run the *same* resolution the planner ran — one policy, never two. The plan's
122    // recorded `album` is the explainability trail; this is the authoritative destination.
123    let resolved = resolve_default_album(&config.album.with_derived(workspace.default_album_id()))
124        .map_err(|e| format!("cannot resolve a destination album: {e}"))?;
125    tracing::info!(
126        album_id = %resolved.album_id,
127        rule = resolved.rule.as_str(),
128        "import destination resolved"
129    );
130    let album_id = resolved.album_id;
131
132    let total = plan.actions.len() as u64;
133    let total_files: u64 = plan
134        .actions
135        .iter()
136        .filter(|(_, d)| matches!(d, ImportDecision::Import))
137        .map(|(c, _)| c.source_paths.len() as u64)
138        .sum();
139
140    on_event(ImportProgressEvent::ImportStarted {
141        total_candidates: total,
142        total_files,
143    });
144
145    let mut summary = ImportExecutionSummary::default();
146    let mut enriched_candidates = 0u64;
147    let batch_size = batch_size.max(1);
148
149    for (batch_no, batch) in plan.actions.chunks(batch_size).enumerate() {
150        if cancel.is_cancelled() {
151            break;
152        }
153        let base = batch_no * batch_size;
154        tracing::debug!(
155            batch = batch_no,
156            first_candidate = base,
157            candidates = batch.len(),
158            "import: catalog batch starting"
159        );
160        let cancelled = in_catalog_batch(workspace, |workspace| {
161            for (offset, (candidate, decision)) in batch.iter().enumerate() {
162                if cancel.is_cancelled() {
163                    return Ok(true);
164                }
165                let i = base + offset;
166
167                let primary_path = candidate.primary_path().clone();
168                on_event(ImportProgressEvent::CandidateStarted {
169                    index: i as u64,
170                    total,
171                    primary_path: primary_path.clone(),
172                });
173
174                let outcomes = match decision {
175                    ImportDecision::Import => {
176                        enriched_candidates +=
177                            u64::from(source.get(candidate.primary_path().as_path()).is_some());
178                        execute_candidate(candidate, workspace, config, album_id, source)?
179                    }
180                    ImportDecision::SkipDuplicate { existing_uuid } => {
181                        vec![(
182                            primary_path,
183                            ImportOutcome::DuplicateSkipped {
184                                existing_uuid: existing_uuid.clone(),
185                            },
186                        )]
187                    }
188                    ImportDecision::SkipError(msg) => {
189                        vec![(primary_path, ImportOutcome::CorruptUnreadable(msg.clone()))]
190                    }
191                };
192
193                on_event(ImportProgressEvent::CandidateCompleted {
194                    index: i as u64,
195                    outcomes: outcomes.clone(),
196                });
197                summary.outcomes.extend(outcomes);
198            }
199            Ok(false)
200        })?;
201        if cancelled {
202            break;
203        }
204    }
205
206    on_event(ImportProgressEvent::ImportCompleted {
207        summary: ImportExecutionSummary {
208            outcomes: summary.outcomes.clone(),
209        },
210    });
211
212    tracing::info!(
213        imported = summary.imported_count(),
214        duplicates = summary.duplicate_count(),
215        errors = summary.error_count(),
216        // Imported, but with no thumbnail/preview: the first is the expected no-codec gap,
217        // the second a genuine decode failure of a format we do support.
218        derivatives_deferred = summary.deferred_derivative_count(),
219        derivatives_decode_failed = summary.decode_failed_count(),
220        // How much of this run carried third-party exporter metadata into the signed sidecars; zero
221        // for a plain filesystem import.
222        enriched_candidates,
223        "import: execution complete"
224    );
225    Ok(summary)
226}
227
228// ── Catalog batching ─────────────────────────────────────────────────────────
229
230/// How many plan entries share one catalog transaction.
231///
232/// Without batching every imported file cost the catalog its own commits (the asset row, its
233/// tags and its original's cache entry), each a WAL append and sync. 64 amortises that to one
234/// commit per 64 entries while keeping both costs of a large batch small: the write
235/// transaction (and the WAL frames it pins) stays short-lived, and a crash before the commit
236/// leaves at most 64 durable bundles without index rows, which the next
237/// [`Workspace::open`] re-indexes from their sidecars.
238pub(crate) const IMPORT_BATCH_SIZE: usize = 64;
239
240/// Run `body` inside one catalog batch and commit it, **whether or not `body` succeeded**.
241///
242/// Every asset `body` imports is durable on disk before its index rows are written, and each
243/// asset's rows are their own savepoint (so a failed asset rolled back only itself). The
244/// rows that did land therefore belong to bundles that exist, and are committed even when
245/// `body` ends in an error — rolling them back would leave durable bundles unindexed until the
246/// next open. Nothing inside a batch deletes or releases a source: the bulk executor defers
247/// every Move release to its caller, which runs only after this commit returned.
248fn in_catalog_batch<T>(
249    workspace: &mut Workspace,
250    body: impl FnOnce(&mut Workspace) -> Result<T, ExecError>,
251) -> Result<T, ExecError> {
252    workspace.db().begin_batch()?;
253    let outcome = body(workspace);
254    if let Err(e) = workspace.db().commit_batch() {
255        // The bundles are durable; only their rows were lost with the batch, and the next
256        // `Workspace::open` reconciles them from their sidecars.
257        tracing::error!(
258            error = %e,
259            body_failed = outcome.is_err(),
260            "import: catalog batch commit failed; its assets are on disk and are re-indexed \
261             on the next open"
262        );
263        return Err(e.into());
264    }
265    outcome
266}
267
268// ── Per-member enrichment ────────────────────────────────────────────────────
269
270/// The signed-sidecar enrichment for one member path, with the fold decision logged.
271///
272/// The single place a [`SourceMetadataIndex`] is turned into a [`SidecarEnrichment`], shared by
273/// this executor and the [streaming window](crate::import::streaming) so a *streamed*
274/// third-party import writes exactly what a bulk one does. A path the index does not cover, or a record that folds to nothing, yields
275/// [`None`] — the untouched write path.
276pub(crate) fn member_enrichment(
277    source: &SourceMetadataIndex,
278    path: &Path,
279) -> Option<SidecarEnrichment> {
280    source.get(path).and_then(|folded| {
281        // The fold decision itself, per member, so a surprising capture time or location in
282        // a sidecar can be traced back to the side it came from. User content (the
283        // description text, the album titles) stays out: sizes and counts are enough.
284        tracing::debug!(
285            path = %path.display(),
286            taken_time = ?folded.taken_time,
287            taken_time_source = ?folded.taken_time_source,
288            gps_source = ?folded.gps_source,
289            description_bytes = folded.description.as_ref().map_or(0, String::len),
290            favorite = folded.favorite,
291            albums = folded.albums.len(),
292            "import: exporter metadata folded for member"
293        );
294        sidecar_enrichment(folded)
295    })
296}
297
298// ── Per-candidate execution ──────────────────────────────────────────────────
299
300/// Import every member of `candidate` through the signed path, then persist its stack grouping
301/// (if any). Move-mode source release and stack placement are handled inside the signed import.
302fn execute_candidate(
303    candidate: &ImportCandidate,
304    workspace: &mut Workspace,
305    config: &ImportConfig,
306    album_id: Uuid,
307    source: &SourceMetadataIndex,
308) -> Result<Vec<(PathBuf, ImportOutcome)>, ExecError> {
309    let move_source = matches!(config.import_mode, ImportMode::Move);
310    // One stack id per multi-file candidate; the primary member stays visible, the rest hidden.
311    let stack = candidate.stack_type.map(|st| (Uuid::now_v7(), st));
312
313    let mut outcomes = Vec::new();
314    let mut imported: Vec<(String, MemberRole)> = Vec::new();
315
316    for (seq, (path, role)) in candidate.members.iter().enumerate() {
317        let is_primary = *role == MemberRole::Primary || seq == 0;
318        let membership = stack_membership(stack, *role, is_primary, seq);
319        let enrichment = member_enrichment(source, path);
320        // A Move source is never deleted on the local commit: until the server holds the asset
321        // it may be the only other copy (invariant 7). The caller releases it through
322        // `Workspace::release_move_source` once the server's custody clears the gate, using the
323        // asset id each `Imported` outcome carries.
324        let opts = SignedImportOptions {
325            move_source,
326            defer_source_release: true,
327            stack: membership,
328            enrichment,
329        };
330
331        match workspace.import_asset_with(album_id, path, &opts) {
332            Ok(receipt) => {
333                imported.push((receipt.asset_id.to_string(), *role));
334                outcomes.push((
335                    path.clone(),
336                    ImportOutcome::Imported {
337                        asset_id: receipt.asset_id,
338                        derivatives: receipt.derivatives,
339                        deferred_formats: receipt.deferred_formats,
340                    },
341                ));
342            }
343            Err(e) => outcomes.push((path.clone(), import_error_outcome(&e))),
344        }
345    }
346
347    if let Some((stack_id, _)) = stack
348        && !imported.is_empty()
349    {
350        persist_stack(workspace, candidate, &stack_id.to_string(), &imported)?;
351    }
352
353    Ok(outcomes)
354}
355
356/// Persist the `asset_stacks` row + its members once the member assets exist in the index.
357/// Shared with the [streaming executor](crate::import::streaming), which groups multi-file
358/// candidates the same way.
359pub(crate) fn persist_stack(
360    workspace: &Workspace,
361    candidate: &ImportCandidate,
362    stack_id: &str,
363    imported: &[(String, MemberRole)],
364) -> Result<(), ExecError> {
365    let now = now_secs();
366    let primary_uuid = imported
367        .iter()
368        .find(|(_, r)| *r == MemberRole::Primary)
369        .or_else(|| imported.first())
370        .map(|(u, _)| u.clone())
371        .unwrap_or_default();
372
373    let stack_row = AssetStackRow {
374        id: stack_id.to_string(),
375        stack_type: candidate.stack_type.map_or_else(
376            || "custom".to_string(),
377            |st| format!("{st:?}").to_lowercase(),
378        ),
379        primary_asset_id: primary_uuid.clone(),
380        cover_asset_id: Some(primary_uuid),
381        is_collapsed: true,
382        is_auto_generated: true,
383        created_at: now,
384        modified_at: now,
385    };
386    // One scope: a stack row is never left without its members (or the reverse). Inside a
387    // bulk batch it is a savepoint, so a failure here rolls back only the stack, never the
388    // member rows already indexed.
389    let db = workspace.db();
390    db.with_transaction(|| {
391        db.insert_stack(&stack_row)?;
392        for (seq, (uuid, role)) in imported.iter().enumerate() {
393            let member_row = StackMemberRow {
394                id: format!("{stack_id}#{seq}"),
395                stack_id: stack_id.to_string(),
396                asset_id: uuid.clone(),
397                sequence_order: seq as i64,
398                member_role: role_str(*role).to_string(),
399                created_at: now,
400            };
401            db.insert_stack_member(&member_row)?;
402        }
403        Ok::<_, rusqlite::Error>(())
404    })?;
405    tracing::debug!(
406        stack_id,
407        members = imported.len(),
408        "import: stack rows written"
409    );
410    Ok(())
411}
412
413// ── Helpers ──────────────────────────────────────────────────────────────────
414
415/// Map a signed-import failure to a per-file outcome. Permission errors surface distinctly; the
416/// rest — including the "should never happen" self-verify failures — report as unreadable.
417fn import_error_outcome(e: &LifecycleError) -> ImportOutcome {
418    let msg = e.to_string();
419    if msg.contains("permission") {
420        ImportOutcome::PermissionDenied(msg)
421    } else {
422        ImportOutcome::CorruptUnreadable(msg)
423    }
424}
425
426/// The signed [`StackMembership`] one member of a multi-file candidate carries, or
427/// `None` for a standalone candidate.
428///
429/// `is_primary` is the executor's own rule (the declared primary, or the first member when none
430/// is declared), and it is what the index projection reads as "not stack-hidden" — so it wins
431/// over the declared [`MemberRole`], which is why the role mapping is applied only to the rest.
432pub(crate) fn stack_membership(
433    stack: Option<(Uuid, StackType)>,
434    role: MemberRole,
435    is_primary: bool,
436    seq: usize,
437) -> Option<StackMembership> {
438    let (stack_id, stack_type) = stack?;
439    Some(StackMembership {
440        stack_id,
441        stack_type,
442        role: if is_primary {
443            StackRole::Primary
444        } else {
445            stack_role(role)
446        },
447        member_index: Some(seq as u32),
448    })
449}
450
451/// Narrow the importer's [`MemberRole`] onto the sidecar's closed [`StackRole`]. The register
452/// records only what a *view* needs — which member represents the stack, and which are proxies
453/// — so every other role collapses to an ordinary member. The full role stays in the
454/// `stack_members` index row.
455fn stack_role(r: MemberRole) -> StackRole {
456    match r {
457        MemberRole::Primary => StackRole::Primary,
458        MemberRole::Proxy => StackRole::Proxy,
459        _ => StackRole::Member,
460    }
461}
462
463fn role_str(r: MemberRole) -> &'static str {
464    match r {
465        MemberRole::Primary => "primary",
466        MemberRole::Raw => "raw",
467        MemberRole::Video => "video",
468        MemberRole::Audio => "audio",
469        MemberRole::DepthMap => "depth_map",
470        MemberRole::Processed => "processed",
471        MemberRole::Source => "source",
472        MemberRole::Alternate => "alternate",
473        MemberRole::Sidecar => "sidecar",
474        MemberRole::Proxy => "proxy",
475        MemberRole::Master => "master",
476    }
477}
478
479fn now_secs() -> i64 {
480    std::time::SystemTime::now()
481        .duration_since(std::time::UNIX_EPOCH)
482        .unwrap_or_default()
483        .as_secs() as i64
484}
485
486// ── Tests ────────────────────────────────────────────────────────────────────
487
488#[cfg(test)]
489mod tests;