Skip to main content

capsule_core/import/
default_album.rs

1//! Default-album resolution — where an import lands when the user files it nowhere (SSoT:
2//! [Organization — The Default Album]).
3//!
4//! Capsule guarantees every owner a **default album**: a de facto, nameless container whose
5//! id is derived from the account master key, so a device can locate it from the master key
6//! alone. Which container is *currently* the default may be re-pointed by a non-secret
7//! `default_album_id` on the owner record, and an explicit pick at import time overrides
8//! both.
9//!
10//! [`resolve_default_album`] is the **one** place that order is encoded, and it records
11//! which rule fired ([`ResolutionRule`]) so a surprising destination is explainable after
12//! the fact. It **always** resolves to a container — a view can never be an import
13//! destination.
14//!
15//! **v1 scope.** The doc's full order interposes two settings-document rows —
16//! `scope_id` override, then per-[`SourceKind`](super::scope::SourceKind) default — between
17//! the explicit pick and the owner pointer. Those rows ship post-v1 with the
18//! library-settings document; v1 ships the base order below. The import's
19//! [`Scope`] is carried through and recorded now, so the two lookups slot in
20//! at the marked seam without changing this signature or any caller.
21//!
22//! [Organization — The Default Album]: https://docs/design/organization/#the-default-album
23
24use uuid::Uuid;
25
26use crate::crypto::hash::Hash32;
27use crate::import::scope::Scope;
28
29/// Which rule of the resolution order chose the destination album. Recorded on every
30/// resolution so a surprising destination is explainable after the fact.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32pub enum ResolutionRule {
33    /// Rule 1 — the user picked an album explicitly at import time.
34    ExplicitPick,
35    /// Rule 2 — the owner record's `default_album_id` pointer. (The post-v1 `scope_id`
36    /// override and per-source-kind default rows interpose *before* this one.)
37    OwnerPointer,
38    /// Rule 3 — the de facto album derived from the account master key. The terminal rule:
39    /// it exists for every owner from first-device enrollment, so import always has a home.
40    DerivedDeFacto,
41}
42
43impl ResolutionRule {
44    /// A stable, structured label for logs and diagnostics.
45    #[must_use]
46    pub fn as_str(self) -> &'static str {
47        match self {
48            ResolutionRule::ExplicitPick => "explicit_pick",
49            ResolutionRule::OwnerPointer => "owner_pointer",
50            ResolutionRule::DerivedDeFacto => "derived_de_facto",
51        }
52    }
53}
54
55/// Everything the resolution order reads. Each field is one rule's input, in priority
56/// order; [`scope`](DefaultAlbumContext::scope) is carried for traceability and for the
57/// post-v1 override rows.
58///
59/// A context whose three album fields are all `None` is **unbound** — no library has been
60/// attached to it yet. That is a caller-side gap, not a user-facing state: an owner always
61/// has a derived de facto album, so binding it (see
62/// [`with_derived`](DefaultAlbumContext::with_derived)) makes resolution total.
63#[derive(Debug, Clone, Default, PartialEq, Eq)]
64pub struct DefaultAlbumContext {
65    /// Rule 1 — the album the user picked explicitly for this import, if any.
66    pub explicit_pick: Option<Uuid>,
67    /// Rule 2 — the owner record's `default_album_id` pointer, if known to this device.
68    pub owner_default_album_id: Option<Uuid>,
69    /// Rule 3 — the de facto album derived from the account master key. Only the library
70    /// knows it, so callers bind it with [`with_derived`](Self::with_derived).
71    pub derived_de_facto_album_id: Option<Uuid>,
72    /// The import source this run came from. Not read by the v1 order; recorded on the
73    /// resolution, and the seam the post-v1 override rows key off.
74    pub scope: Option<Scope>,
75}
76
77impl DefaultAlbumContext {
78    /// A context bound to a library's derived de facto album (rule 3) and nothing else —
79    /// the "user filed it nowhere, no owner pointer known" baseline.
80    #[must_use]
81    pub fn derived(derived_de_facto_album_id: Uuid) -> Self {
82        Self {
83            derived_de_facto_album_id: Some(derived_de_facto_album_id),
84            ..Self::default()
85        }
86    }
87
88    /// This context with rule 3 bound to `derived` **if it is not already set**.
89    ///
90    /// The library is the only authority on the derived de facto album, so a caller that
91    /// assembled the context without one (an `ImportConfig` (`capsule-library`'s import planner) built
92    /// before a workspace was opened) completes it here. An already-bound context is
93    /// returned unchanged, so binding twice cannot change the answer.
94    #[must_use]
95    pub fn with_derived(&self, derived: Uuid) -> Self {
96        let mut bound = self.clone();
97        bound.derived_de_facto_album_id.get_or_insert(derived);
98        bound
99    }
100}
101
102/// The album an import will land in, and the rule that chose it.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct ResolvedAlbum {
105    /// The destination container album. Always a container — never a view.
106    pub album_id: Uuid,
107    /// Which rule of the order fired.
108    pub rule: ResolutionRule,
109    /// The [`scope_id`](Scope::scope_id) of the import source, when the context named a
110    /// scope. Recorded for explainability; the post-v1 override rows are keyed by it.
111    pub scope_id: Option<Hash32>,
112}
113
114/// Failure to resolve a destination album.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
116pub enum DefaultAlbumError {
117    /// The context named no album at any rule — it was never bound to a library. Every
118    /// owner has a derived de facto album from first-device enrollment onward, so this is a
119    /// caller that has not supplied it, never a legitimate "this user has nowhere to
120    /// import" state.
121    #[error(
122        "unbound default-album context: no explicit pick, no owner `default_album_id` \
123         pointer, and no derived de facto album"
124    )]
125    Unbound,
126}
127
128/// Resolve the destination album for an import, first match wins (SSoT:
129/// [Organization — The Default Album]).
130///
131/// 1. the explicit user pick at import time,
132/// 2. *(post-v1: the `scope_id` override row, then the per-source-kind default row)*,
133/// 3. the owner's `default_album_id` pointer,
134/// 4. the derived de facto album.
135///
136/// Deterministic by construction — a pure function of the context, with no clock, no I/O
137/// and no iteration order — and the fired [`ResolutionRule`] travels with the answer.
138///
139/// [Organization — The Default Album]: https://docs/design/organization/#the-default-album
140pub fn resolve_default_album(
141    context: &DefaultAlbumContext,
142) -> Result<ResolvedAlbum, DefaultAlbumError> {
143    let scope_id = context.scope.as_ref().map(Scope::scope_id);
144
145    // Rule 1 — explicit user pick.
146    // POST-V1 SEAM: the `scope_id` override row, then the per-`SourceKind` default row,
147    // interpose here once the library-settings document ships. Both key off `scope_id` /
148    // `context.scope`, which is why the scope is carried on the context today.
149    let (album_id, rule) = if let Some(pick) = context.explicit_pick {
150        (pick, ResolutionRule::ExplicitPick)
151    } else if let Some(pointer) = context.owner_default_album_id {
152        // Rule 2 — the owner record's pointer.
153        (pointer, ResolutionRule::OwnerPointer)
154    } else if let Some(derived) = context.derived_de_facto_album_id {
155        // Rule 3 — the terminal rule; import always has a home.
156        (derived, ResolutionRule::DerivedDeFacto)
157    } else {
158        tracing::warn!("default-album resolution refused: context is not bound to a library");
159        return Err(DefaultAlbumError::Unbound);
160    };
161
162    tracing::debug!(
163        %album_id,
164        rule = rule.as_str(),
165        scope = ?context.scope,
166        "resolved import destination album"
167    );
168    Ok(ResolvedAlbum {
169        album_id,
170        rule,
171        scope_id,
172    })
173}
174
175#[cfg(test)]
176mod tests;