Skip to main content

capsule_library/import/
streaming.rs

1//! Streaming import — the storage-constrained drive mode over the signed executor (SSoT:
2//! [Import — Pipeline: Import-Upload Streaming Mode](https://docs/design/import/pipeline/#import-upload-streaming-mode)).
3//!
4//! The default [`execute`](crate::import::execute) imports every file into the local
5//! library *before* upload, so the device temporarily holds the whole import on disk — impossible
6//! on a storage-constrained device. Streaming mode removes that requirement by running a bounded
7//! **sliding window** of one asset at a time:
8//!
9//! 1. Import the next file onto the signed path — with source release *deferred*
10//!    ([`Workspace::import_asset_streaming`](crate::lifecycle::Workspace::import_asset_streaming)).
11//! 2. Upload its bundle via the injected [`AssetUploader`] seam.
12//! 3. Confirm durability + custody through the [`ReleaseGate`] over the injected
13//!    [`StorageVerifier`] seam.
14//! 4. **Release** the local original (and delete the Move-mode source) *only* on the `durable`
15//!    verdict, so the device never drops the only copy of bytes the server has not confirmed.
16//! 5. Advance the window.
17//!
18//! Peak local disk is therefore bounded to the in-flight asset, not the whole import. The two
19//! network touch-points — upload and verify — are **injected trait seams**, so this executor,
20//! and its release gating, run with no network at all; `capsule-sdk`/CLI supply the real ones
21//! (the SDK's upload client + `POST /storage/verify` coordinator), tests supply deterministic
22//! mocks. `capsule-core` stays network-free.
23
24use std::path::PathBuf;
25
26use capsule_core::crypto::verify_asset::VerifyOutcome;
27use capsule_core::domain::{ImportMode, MemberRole};
28use capsule_core::import::scan::ImportCandidate;
29use uuid::Uuid;
30
31use crate::import::enrichment::SourceMetadataIndex;
32use crate::import::executor_cancellation::CancellationToken;
33use crate::import::planner::{ImportActionPlan, ImportConfig, ImportDecision};
34use crate::library::{
35    ReleaseDecision, ReleaseGate, RetainReason, StorageVerifier, available_bytes,
36};
37use crate::lifecycle::{StreamedImport, Workspace};
38
39// ── The injected network seam ─────────────────────────────────────────────────
40
41/// The network seam the streaming window drives to hand one just-imported asset's bundle
42/// (original + derivatives + metadata) to the [upload protocol](https://docs/design/transfer/upload/).
43/// Implemented by `capsule-sdk`/CLI over the real upload client; tests supply a deterministic
44/// mock. Kept in `capsule-core` as a trait so the streaming loop — and its release gating — is
45/// exercised without any network. Synchronous by construction: the offline data plane calls it;
46/// async callers resolve their futures before returning.
47pub trait AssetUploader {
48    /// Upload the imported asset identified by `imported.asset_id`, whose declared blob
49    /// content-addresses are `imported.blob_hashes`. Returns `Ok` when the upload session(s)
50    /// completed (or the server already held the bytes), or an [`UploadHalt`] when the window
51    /// must **pause** rather than admit the next source file.
52    fn upload(&self, imported: &StreamedImport) -> Result<(), UploadHalt>;
53}
54
55/// Why the streaming window must pause. A halt stops the loop from admitting further source files
56/// into the library — continuing would refill the very disk streaming exists to spare. The
57/// already-imported in-flight asset is retained locally; its upload resumes via the protocol's
58/// `HEAD` resumption on reconnect, and the deterministic planner re-derives the not-yet-admitted
59/// work on the next run.
60#[derive(Debug, Clone)]
61pub enum UploadHalt {
62    /// The connection to the server dropped mid-stream.
63    Disconnected(String),
64    /// Server quota was exhausted at session creation; the next session would be refused.
65    QuotaExhausted,
66    /// A transport error the driver classifies as pause-worthy.
67    Transport(String),
68}
69
70// ── Errors ────────────────────────────────────────────────────────────────────
71
72/// A streaming import that cannot start or cannot make progress. Per-asset upload pauses and
73/// per-asset retain decisions are *not* errors — they are outcomes in the [`StreamingReport`];
74/// these variants are the hard stops.
75#[derive(Debug, thiserror::Error)]
76pub enum StreamingError {
77    /// The minimum-headroom check failed: the largest single asset cannot fully materialize
78    /// locally even within the one-asset window. Surfaced *before* any file is imported — the
79    /// "cannot import *X* without freeing *Y*" confirmation-time error.
80    #[error(
81        "cannot stream-import {path}: its {asset_bytes} bytes exceed the {available} available \
82         (free {need_to_free} more bytes)"
83    )]
84    InsufficientHeadroom {
85        /// The offending asset's primary source path.
86        path: PathBuf,
87        /// The largest asset's size in bytes.
88        asset_bytes: u64,
89        /// Bytes available to an unprivileged process on the library volume.
90        available: u64,
91        /// Bytes that must be freed for the largest asset (plus headroom) to fit.
92        need_to_free: u64,
93    },
94
95    /// The free-space probe failed.
96    #[error("free-space probe: {0}")]
97    Probe(#[from] crate::library::LibraryError),
98
99    /// The run was configured with a [`UploadPolicy::Staged`](crate::import::UploadPolicy)
100    /// policy, which is mutually exclusive with streaming import. Streaming releases local
101    /// bytes quickly; staged defers exactly the T2 upload release depends on — so a staged
102    /// policy can never enter the streaming window. Surfaced *before* any file is imported, mirroring the
103    /// planner's confirmation-time rejection.
104    #[error(transparent)]
105    StagedPolicyConflict(#[from] capsule_core::import::upload::StagedStreamingConflict),
106
107    /// A signed-path import failed hard enough to abort the run (not a per-file skip).
108    #[error("streamed import: {0}")]
109    Import(String),
110
111    /// A library-index write (dropping a released owned-original row) failed.
112    #[error("index write: {0}")]
113    Db(String),
114}
115
116// ── Report ────────────────────────────────────────────────────────────────────
117
118/// The per-asset result of one window step, in window order.
119#[derive(Debug)]
120pub struct StreamedOutcome {
121    /// The imported asset's id, when it reached the library (absent for skips / import failures).
122    pub asset_id: Option<Uuid>,
123    /// The source file this outcome is for.
124    pub source_path: PathBuf,
125    /// What became of it.
126    pub state: StreamedState,
127}
128
129/// What became of one file in the streaming window.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum StreamedState {
132    /// Imported, uploaded, verified `durable` + custody receipt, local original (and any
133    /// Move-mode source) released — the asset is now a server-only, re-fetchable representation.
134    Released,
135    /// Imported + uploaded, but the release gate **retained** the local copy (verdict not
136    /// `durable`, receipt missing/unverified, or a transport failure). The bytes stay on disk;
137    /// a later attempt re-drives the gate.
138    Retained(RetainReason),
139    /// The upload paused the window on this asset. Its bytes were imported and are retained
140    /// locally; its upload resumes via `HEAD` on reconnect.
141    UploadHalted,
142    /// A planner skip decision — never imported.
143    Skipped,
144    /// The signed-path import of this member failed.
145    ImportFailed(String),
146}
147
148/// Why the window halted before draining the plan.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub enum StreamHalt {
151    /// The server connection dropped mid-stream.
152    Disconnected(String),
153    /// Server quota was exhausted.
154    QuotaExhausted,
155    /// A pause-worthy transport error.
156    Transport(String),
157    /// The caller's cancel token fired at a window boundary.
158    Cancelled,
159}
160
161impl From<UploadHalt> for StreamHalt {
162    fn from(h: UploadHalt) -> Self {
163        match h {
164            UploadHalt::Disconnected(m) => StreamHalt::Disconnected(m),
165            UploadHalt::QuotaExhausted => StreamHalt::QuotaExhausted,
166            UploadHalt::Transport(m) => StreamHalt::Transport(m),
167        }
168    }
169}
170
171/// The outcome of a streaming import run.
172#[derive(Debug, Default)]
173pub struct StreamingReport {
174    /// Per-file outcomes in window order.
175    pub outcomes: Vec<StreamedOutcome>,
176    /// Set when the window halted before draining the plan; `None` on a clean drain.
177    pub halted: Option<StreamHalt>,
178}
179
180impl StreamingReport {
181    /// How many local originals were released after a durable verdict.
182    pub fn released_count(&self) -> usize {
183        self.count(|s| *s == StreamedState::Released)
184    }
185
186    /// How many imports were kept local (gate retained + the in-flight halted asset).
187    pub fn retained_count(&self) -> usize {
188        self.count(|s| matches!(s, StreamedState::Retained(_) | StreamedState::UploadHalted))
189    }
190
191    /// Whether the window halted before completing the plan.
192    pub fn is_halted(&self) -> bool {
193        self.halted.is_some()
194    }
195
196    fn count(&self, pred: impl Fn(&StreamedState) -> bool) -> usize {
197        self.outcomes.iter().filter(|o| pred(&o.state)).count()
198    }
199}
200
201/// Progress events for traceability / UI. The window is per-asset, so every state transition is
202/// observable.
203#[derive(Debug, Clone)]
204pub enum StreamingEvent {
205    /// The pre-flight probe result, emitted once before the first import.
206    Preflight {
207        /// The plan's total import size.
208        total_size: u64,
209        /// Bytes available on the library volume.
210        available: u64,
211        /// The largest single asset's size (the headroom-bound).
212        largest_asset: u64,
213    },
214    /// An asset landed in the library (import complete, upload not yet started).
215    Imported { asset_id: Uuid, source: PathBuf },
216    /// An asset's local original was released after a durable verdict.
217    Released { asset_id: Uuid },
218    /// An asset's local copy was retained (gate refused release).
219    Retained {
220        asset_id: Uuid,
221        reason: RetainReason,
222    },
223    /// The window halted; no further source files are admitted.
224    Halted { reason: StreamHalt },
225}
226
227// ── The window executor ────────────────────────────────────────────────────────
228
229/// Everything the streaming window needs beyond the plan, the workspace, and the event sink.
230///
231/// One struct rather than six positionals: the two entry points this replaced differed only in
232/// `source` and carried eight and nine arguments respectively, both behind a
233/// `#[allow(clippy::too_many_arguments)]`. A caller that wants no source-adapter enrichment
234/// passes `&SourceMetadataIndex::empty()`, which is exactly what the thinner of the two
235/// entry points did for it.
236pub struct StreamingOptions<'a, U: AssetUploader, V: StorageVerifier> {
237    /// The planner configuration the run was confirmed against.
238    pub config: &'a ImportConfig,
239    /// Folded metadata a third-party [source adapter](crate::import::SourceAdapter) extracted,
240    /// attached to each file it covers. [`SourceMetadataIndex::empty`] for a plain filesystem
241    /// drive; files the index does not cover import identically either way.
242    pub source: &'a SourceMetadataIndex,
243    /// The injected upload seam. `capsule-core` performs no network I/O of its own.
244    pub uploader: &'a U,
245    /// The injected durability/custody seam behind the release gate.
246    pub verifier: &'a V,
247    /// The free-space cushion the minimum-headroom check and the implicit recommendation apply.
248    pub headroom_margin: u64,
249    /// Honored at every window boundary.
250    pub cancel: &'a CancellationToken,
251}
252
253/// Drive a streaming import: the bounded per-asset import → upload → verify → release window over
254/// `plan`, under `opts`.
255///
256/// The enrichment in [`StreamingOptions::source`] is written *inside the signed sidecar*, at the
257/// same single write path the bulk executor drives, so the drive mode a user picks never changes
258/// what a migrated library keeps: a storage-constrained device streaming a Takeout export lands
259/// the exporter's capture time, GPS, caption, favorite, and album membership exactly as an
260/// unconstrained one does. This is the streaming twin of
261/// [`execute_with_source_metadata`](crate::import::execute_with_source_metadata).
262///
263/// Returns a [`StreamingReport`]; a hard failure to *start* (insufficient headroom, a failed
264/// probe) is a [`StreamingError`]. Per-asset upload pauses and gate retentions are outcomes, not
265/// errors: on a pause the window halts (`report.halted` set) with no further files admitted, and
266/// the run can be re-invoked after reconnect — the deterministic planner re-derives the remaining
267/// work and skips already-completed assets.
268#[tracing::instrument(
269    skip_all,
270    fields(
271        candidates = plan.actions.len(),
272        mode = ?opts.config.import_mode,
273        headroom = opts.headroom_margin,
274        source_metadata = opts.source.len(),
275    )
276)]
277pub fn execute_streaming<U, V>(
278    plan: &ImportActionPlan,
279    workspace: &mut Workspace,
280    opts: StreamingOptions<'_, U, V>,
281    on_event: impl Fn(StreamingEvent),
282) -> Result<StreamingReport, StreamingError>
283where
284    U: AssetUploader,
285    V: StorageVerifier,
286{
287    // Every field is a shared reference or a `u64`, so this copies out of `opts` rather than
288    // moving it; the struct is handed to `stream_candidate` whole below.
289    let StreamingOptions {
290        config,
291        headroom_margin,
292        cancel,
293        ..
294    } = opts;
295    // ── Exclusion: a staged upload policy can never enter the streaming window ───
296    // Streaming exists to release local bytes as fast as possible; staged uploads
297    // defer exactly the T2 (original) upload that release depends on. The planner
298    // rejects the combination at confirmation; this is the by-construction backstop
299    // so a staged policy cannot reach `execute_streaming` even if a caller skips
300    // confirmation. Surfaces before any file is imported (staged uploads).
301    crate::import::ensure_streaming_compatible(config.upload_policy, true)?;
302
303    // Same single resolution the executor runs: bind the library's derived de facto album
304    // (rule 3), then apply the order (SSoT: organization § The Default Album).
305    let resolved = capsule_core::import::default_album::resolve_default_album(
306        &config.album.with_derived(workspace.default_album_id()),
307    )
308    .map_err(|e| StreamingError::Import(format!("cannot resolve a destination album: {e}")))?;
309    tracing::info!(
310        album_id = %resolved.album_id,
311        rule = resolved.rule.as_str(),
312        "streaming import destination resolved"
313    );
314    let album_id = resolved.album_id;
315
316    // ── Pre-flight: minimum-headroom hard error ─────────────────────────────────
317    // Streaming bounds peak disk to the window, but the largest single asset must still fully
318    // materialize locally before its upload and release. Probe once, up front, so the failure
319    // surfaces at confirmation rather than mid-stream.
320    let available = available_bytes(workspace.root())?;
321    let largest = plan.largest_import_size();
322    on_event(StreamingEvent::Preflight {
323        total_size: plan.counts.total_size,
324        available,
325        largest_asset: largest,
326    });
327    if !crate::library::largest_asset_fits(largest, available, headroom_margin) {
328        let (path, asset_bytes) = largest_candidate(plan);
329        let need_to_free = asset_bytes
330            .saturating_add(headroom_margin)
331            .saturating_sub(available);
332        tracing::warn!(
333            %need_to_free, asset_bytes, available,
334            "streaming import blocked: largest asset does not fit"
335        );
336        return Err(StreamingError::InsufficientHeadroom {
337            path,
338            asset_bytes,
339            available,
340            need_to_free,
341        });
342    }
343
344    // ── The window ──────────────────────────────────────────────────────────────
345    let mut report = StreamingReport::default();
346    for (candidate, decision) in &plan.actions {
347        if cancel.is_cancelled() {
348            report.halted = Some(StreamHalt::Cancelled);
349            on_event(StreamingEvent::Halted {
350                reason: StreamHalt::Cancelled,
351            });
352            break;
353        }
354        match decision {
355            ImportDecision::Import => {
356                match stream_candidate(workspace, album_id, candidate, &opts, &on_event)? {
357                    CandidateFlow::Done(outs) => report.outcomes.extend(outs),
358                    CandidateFlow::Halt(reason, outs) => {
359                        report.outcomes.extend(outs);
360                        on_event(StreamingEvent::Halted {
361                            reason: reason.clone(),
362                        });
363                        report.halted = Some(reason);
364                        break;
365                    }
366                }
367            }
368            ImportDecision::SkipDuplicate { .. } | ImportDecision::SkipError(_) => {
369                report.outcomes.push(StreamedOutcome {
370                    asset_id: None,
371                    source_path: candidate.primary_path().clone(),
372                    state: StreamedState::Skipped,
373                });
374            }
375        }
376    }
377
378    tracing::info!(
379        released = report.released_count(),
380        retained = report.retained_count(),
381        halted = report.is_halted(),
382        "streaming import: run complete"
383    );
384    Ok(report)
385}
386
387// ── Per-candidate window step ──────────────────────────────────────────────────
388
389/// The control flow of one candidate's window step.
390enum CandidateFlow {
391    /// Every member handled; the outcomes to record.
392    Done(Vec<StreamedOutcome>),
393    /// The window must halt: the reason + the outcomes gathered so far (including the in-flight
394    /// retained asset that triggered the pause).
395    Halt(StreamHalt, Vec<StreamedOutcome>),
396}
397
398/// Import → upload → verify → release each member of `candidate` in turn. A multi-file candidate
399/// (RAW+JPEG, Live Photo) mints one stack id and hides its non-primary members, exactly as the
400/// bulk executor does; the stack row is persisted once its members exist in the index — released
401/// originals keep their queryable asset rows, so grouping survives release.
402fn stream_candidate<U, V>(
403    workspace: &mut Workspace,
404    album_id: Uuid,
405    candidate: &ImportCandidate,
406    opts: &StreamingOptions<'_, U, V>,
407    on_event: &impl Fn(StreamingEvent),
408) -> Result<CandidateFlow, StreamingError>
409where
410    U: AssetUploader,
411    V: StorageVerifier,
412{
413    let StreamingOptions {
414        config,
415        source,
416        uploader,
417        verifier,
418        ..
419    } = *opts;
420    let move_source = matches!(config.import_mode, ImportMode::Move);
421    let stack = candidate.stack_type.map(|st| (Uuid::now_v7(), st));
422
423    let mut outcomes = Vec::new();
424    let mut imported_members: Vec<(String, MemberRole)> = Vec::new();
425
426    for (seq, (path, role)) in candidate.members.iter().enumerate() {
427        let is_primary = *role == MemberRole::Primary || seq == 0;
428        let membership = crate::import::executor::stack_membership(stack, *role, is_primary, seq);
429
430        // 1. Import onto the signed path with deferred release, carrying whatever the source
431        //    adapter folded for this member. Resolved through the *same* helper the
432        //    bulk executor uses, so the two drive modes cannot drift apart.
433        let enrichment = crate::import::executor::member_enrichment(source, path);
434        let imported = match workspace.import_asset_streaming(
435            album_id,
436            path,
437            move_source,
438            membership,
439            enrichment,
440        ) {
441            Ok(i) => i,
442            Err(e) => {
443                outcomes.push(StreamedOutcome {
444                    asset_id: None,
445                    source_path: path.clone(),
446                    state: StreamedState::ImportFailed(e.to_string()),
447                });
448                continue;
449            }
450        };
451        on_event(StreamingEvent::Imported {
452            asset_id: imported.asset_id,
453            source: path.clone(),
454        });
455        imported_members.push((imported.asset_id.to_string(), *role));
456
457        // 2. Upload the bundle. A halt pauses the window: the imported bytes stay local and no
458        //    further source files are admitted.
459        if let Err(halt) = uploader.upload(&imported) {
460            tracing::warn!(asset = %imported.asset_id, ?halt, "streaming upload paused the window");
461            outcomes.push(StreamedOutcome {
462                asset_id: Some(imported.asset_id),
463                source_path: path.clone(),
464                state: StreamedState::UploadHalted,
465            });
466            return Ok(CandidateFlow::Halt(halt.into(), outcomes));
467        }
468
469        // 3–4. Gate on durability + custody, then release the local original (and Move source)
470        //       only on a Release decision — the verify-before-destroy rule per asset.
471        let state = release_after_verify(workspace, verifier, &imported, on_event)?;
472        outcomes.push(StreamedOutcome {
473            asset_id: Some(imported.asset_id),
474            source_path: path.clone(),
475            state,
476        });
477    }
478
479    // Persist the stack grouping once its members exist in the index.
480    if let Some((stack_id, _)) = stack
481        && !imported_members.is_empty()
482    {
483        crate::import::executor::persist_stack(
484            workspace,
485            candidate,
486            &stack_id.to_string(),
487            &imported_members,
488        )
489        .map_err(|e| StreamingError::Db(e.to_string()))?;
490    }
491
492    Ok(CandidateFlow::Done(outcomes))
493}
494
495/// Run the release gate for a just-uploaded asset and act on it: on `Release`, delete the local
496/// original + drop its owned-original representation row (it becomes a server-only asset); on
497/// `Retain`, leave every local byte in place. A Move-mode source is released through
498/// [`Workspace::release_move_source`], which reads it and the local original back against the
499/// signed hash before the gate, so its decision is the one acted on here.
500fn release_after_verify<V: StorageVerifier>(
501    workspace: &mut Workspace,
502    verifier: &V,
503    imported: &StreamedImport,
504    on_event: &impl Fn(StreamingEvent),
505) -> Result<StreamedState, StreamingError> {
506    // A Move source goes through the one Move-release path, before the local original is
507    // touched: both copies are read back against the signed hash, then the gate decides, and
508    // the source is deleted only on `Release`. A source that fails the read-back keeps the
509    // local original too — it is then the one copy known to be intact.
510    let decision = if let Some(src) = &imported.move_source {
511        workspace
512            .release_move_source(verifier, imported.asset_id, src)
513            .map_err(|e| StreamingError::Import(e.to_string()))?
514    } else {
515        // The crypto half of the gate: the asset self-verified on import, but re-check freshly.
516        let verify_asset_accepted = workspace
517            .verify(&imported.asset_id)
518            .is_ok_and(|o| o == VerifyOutcome::Accept);
519        ReleaseGate::new(verifier).may_release(
520            imported.asset_id,
521            &imported.blob_hashes,
522            verify_asset_accepted,
523        )
524    };
525
526    match decision {
527        ReleaseDecision::Release => {
528            let _ = std::fs::remove_file(&imported.local_original);
529            // The owned-original representation row is keyed by the hyphenated UUID, matching
530            // `Workspace::index_original_representation` (the writer).
531            workspace
532                .db()
533                .remove_representation(&imported.asset_id.to_string(), "original")
534                .map_err(|e| StreamingError::Db(e.to_string()))?;
535            on_event(StreamingEvent::Released {
536                asset_id: imported.asset_id,
537            });
538            Ok(StreamedState::Released)
539        }
540        ReleaseDecision::Retain(reason) => {
541            on_event(StreamingEvent::Retained {
542                asset_id: imported.asset_id,
543                reason: reason.clone(),
544            });
545            Ok(StreamedState::Retained(reason))
546        }
547    }
548}
549
550/// The largest `Import` candidate's `(primary_path, size)` — the offending asset for the
551/// insufficient-headroom error.
552fn largest_candidate(plan: &ImportActionPlan) -> (PathBuf, u64) {
553    plan.actions
554        .iter()
555        .filter(|(_, d)| matches!(d, ImportDecision::Import))
556        .map(|(c, _)| {
557            (
558                c.primary_path().clone(),
559                crate::import::planner::candidate_size(c),
560            )
561        })
562        .max_by_key(|(_, b)| *b)
563        .unwrap_or_default()
564}
565
566// ── Tests ──────────────────────────────────────────────────────────────────────
567
568#[cfg(test)]
569mod tests;