Skip to main content

capsule_sdk/ffi/
culling.rs

1//! The **cull verbs** of the `capsule_sdk` uniffi namespace: flag an asset, flag a whole stack,
2//! read a stack's derived state, list the assets carrying a flag, list where each live asset
3//! sits in its stack, and the reject sweep — over
4//! `capsule-library`'s [`Workspace`] culling workflow ([Organization — Culling]).
5//!
6//! Every verb here is one call into the workspace under its lock. Flagging writes the trinary
7//! `cull` LWW register as a signed `metadata-update` and never touches bytes, so it is fully
8//! reversible; the sweep is the one destructive step, and it is a soft delete carrying the
9//! signed retention window like any [`FfiWorkspace::delete_asset`]. A stack has no stored flag:
10//! [`FfiWorkspace::stack_cull_state`] derives it from the members on every read.
11//!
12//! A separate `#[uniffi::export] impl` block on the same object, so the culling surface reads
13//! as one place rather than a fourth section of the workspace module.
14//!
15//! [`Workspace`]: capsule_library::lifecycle::Workspace
16//! [Organization — Culling]: https://docs/design/organization/#culling
17
18use capsule_core::culling::GroupCullState;
19use capsule_core::sidecar::sidecar_v1::{CullFlag, StackMembership, StackRole};
20
21use super::FfiError;
22use super::workspace::{FfiWorkspace, parse_uuid, trash_error};
23
24/// The trinary culling flag, mirrored from core's `CullFlag`. `Neutral` is the never-flagged
25/// state and what an unwritten register reads as.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
27pub enum FfiCullFlag {
28    /// A keeper.
29    Pick,
30    /// Not yet culled either way.
31    Neutral,
32    /// Marked for rejection: a candidate for the reject sweep.
33    Reject,
34}
35
36impl From<FfiCullFlag> for CullFlag {
37    fn from(flag: FfiCullFlag) -> Self {
38        match flag {
39            FfiCullFlag::Pick => Self::Pick,
40            FfiCullFlag::Neutral => Self::Neutral,
41            FfiCullFlag::Reject => Self::Reject,
42        }
43    }
44}
45
46impl From<CullFlag> for FfiCullFlag {
47    fn from(flag: CullFlag) -> Self {
48        match flag {
49            CullFlag::Pick => Self::Pick,
50            CullFlag::Neutral => Self::Neutral,
51            CullFlag::Reject => Self::Reject,
52        }
53    }
54}
55
56/// A stack's derived cull state, by the doc's precedence `all-rejected → any-pick → else mixed`.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
58pub enum FfiStackCullState {
59    /// Every member is rejected: the whole stack is a sweep candidate.
60    AllRejected,
61    /// At least one member is picked.
62    AnyPick,
63    /// Neither: undecided, or rejects mixed with neutrals.
64    Mixed,
65}
66
67impl From<GroupCullState> for FfiStackCullState {
68    fn from(state: GroupCullState) -> Self {
69        match state {
70            GroupCullState::AllRejected => Self::AllRejected,
71            GroupCullState::AnyPick => Self::AnyPick,
72            GroupCullState::Mixed => Self::Mixed,
73        }
74    }
75}
76
77/// Where one live asset sits in its stack, read from its signed `stack_membership` register.
78#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
79pub struct FfiStackMember {
80    /// The asset (UUID string).
81    pub asset_id: String,
82    /// The stack it belongs to (UUID string).
83    pub stack_id: String,
84    /// Whether it is the stack's cover: its `primary` member, the "best photo".
85    pub is_cover: bool,
86    /// Its position within the stack (burst sequence, chapter index), when one was recorded.
87    pub member_index: Option<u32>,
88}
89
90impl FfiStackMember {
91    fn new(asset_id: String, membership: &StackMembership) -> Self {
92        Self {
93            asset_id,
94            stack_id: membership.stack_id.to_string(),
95            is_cover: membership.role == StackRole::Primary,
96            member_index: membership.member_index,
97        }
98    }
99}
100
101#[uniffi::export]
102impl FfiWorkspace {
103    /// Flag one asset. `Neutral` clears a prior flag. Signs one `metadata-update`, stamped with
104    /// this device and now, so concurrent flags from two devices converge under LWW.
105    pub fn set_cull(&self, asset_id: String, flag: FfiCullFlag) -> Result<(), FfiError> {
106        let asset_id = parse_uuid("asset_id", &asset_id)?;
107        self.with(|ws| {
108            ws.set_cull(&asset_id, flag.into())?;
109            tracing::debug!(%asset_id, ?flag, "ffi: asset flagged");
110            Ok(())
111        })
112    }
113
114    /// The asset's current flag: `Neutral` when it was never flagged, and for an asset this
115    /// workspace does not hold.
116    pub fn cull_flag(&self, asset_id: String) -> Result<FfiCullFlag, FfiError> {
117        let asset_id = parse_uuid("asset_id", &asset_id)?;
118        self.with(|ws| Ok(ws.cull_flag(&asset_id).into()))
119    }
120
121    /// The managed, non-trashed assets currently carrying `flag`, sorted. `Neutral` includes
122    /// the never-flagged ones.
123    pub fn assets_by_cull(&self, flag: FfiCullFlag) -> Result<Vec<String>, FfiError> {
124        self.with(|ws| {
125            Ok(ws
126                .assets_by_cull(flag.into())
127                .iter()
128                .map(ToString::to_string)
129                .collect())
130        })
131    }
132
133    /// Every managed, non-trashed asset that belongs to a stack, with its stack, whether it is
134    /// the cover and its member index, sorted by asset id. An asset in no stack is absent, so a
135    /// cull pass reads it as a lone asset; a trashed member is absent too, matching the members
136    /// [`flag_stack`](Self::flag_stack) writes.
137    pub fn stack_memberships(&self) -> Result<Vec<FfiStackMember>, FfiError> {
138        self.with(|ws| {
139            let mut ids = ws.asset_ids();
140            ids.sort();
141            let members: Vec<FfiStackMember> = ids
142                .iter()
143                .filter(|id| !ws.is_trashed(id))
144                .filter_map(|id| {
145                    let membership = ws.asset(id)?.sidecar.stack_membership.get()?.as_ref()?;
146                    Some(FfiStackMember::new(id.to_string(), membership))
147                })
148                .collect();
149            tracing::debug!(members = members.len(), "ffi: stack memberships listed");
150            Ok(members)
151        })
152    }
153
154    /// Flag every non-trashed member of a stack, one `metadata-update` each — flagging a
155    /// collapsed stack flags its members, since a stack stores no flag of its own. Returns the
156    /// members flagged, sorted; empty for a stack with no members.
157    pub fn flag_stack(&self, stack_id: String, flag: FfiCullFlag) -> Result<Vec<String>, FfiError> {
158        let stack_id = parse_uuid("stack_id", &stack_id)?;
159        self.with(|ws| {
160            let members = ws.flag_stack(stack_id, flag.into())?;
161            tracing::debug!(%stack_id, ?flag, members = members.len(), "ffi: stack flagged");
162            Ok(members.iter().map(ToString::to_string).collect())
163        })
164    }
165
166    /// A stack's cull state, derived from its members on this read. `None` for a stack with no
167    /// non-trashed members.
168    pub fn stack_cull_state(
169        &self,
170        stack_id: String,
171    ) -> Result<Option<FfiStackCullState>, FfiError> {
172        let stack_id = parse_uuid("stack_id", &stack_id)?;
173        self.with(|ws| Ok(ws.group_cull_state(stack_id).map(Into::into)))
174    }
175
176    /// The reject sweep: move every rejected, not-yet-trashed asset to the trash with a
177    /// retention window of `retain_days` days, and return the swept ids, sorted. Each is a
178    /// signed `delete`, restorable from the trash until its window closes. A refusal partway
179    /// is [`FfiError::Trash`]; the assets swept before it stay in the trash, and a retried
180    /// sweep moves the rest.
181    pub fn reject_sweep(&self, retain_days: u32) -> Result<Vec<String>, FfiError> {
182        self.with(|ws| {
183            let swept = ws
184                .reject_sweep(i64::from(retain_days))
185                .map_err(trash_error)?;
186            tracing::info!(
187                swept = swept.len(),
188                retain_days,
189                "ffi: reject sweep moved assets to the trash"
190            );
191            Ok(swept.iter().map(ToString::to_string).collect())
192        })
193    }
194}
195
196#[cfg(test)]
197mod tests;