capsule_library/lifecycle/organize/trash.rs
1//! The trash state machine (owner: [Organization — Deletion State Machine]): delete, restore,
2//! purge, and the trash listing, each judged against the `retention_until` signed into the
3//! asset's latest `delete` record rather than against an index column or a caller's clock
4//! arithmetic.
5//!
6//! Every transition is a signed provenance record, so it syncs and survives a
7//! [`rebuild_index`](crate::library::rebuild_index): the index row is a projection of the
8//! chain, never the place a deletion is decided.
9//!
10//! [Organization — Deletion State Machine]: https://docs/design/organization/#deletion-state-machine
11
12use std::collections::{BTreeMap, BTreeSet};
13use std::fs;
14use std::io::ErrorKind;
15use std::path::{Path, PathBuf};
16
17use capsule_core::crypto::hash::Hash32;
18use capsule_core::crypto::provenance::{Action, ProvenanceChain, ProvenanceRecord};
19use jiff::Timestamp;
20use uuid::Uuid;
21
22use super::super::{AssetState, LifecycleError, Result, Workspace, asset_is_deleted, media_dir};
23use crate::library::paths::{
24 ThumbnailSize, meta_cache_path, thumbnail_path, transcode_h264_path, transcode_live_path,
25};
26
27/// One asset in the trash, as its latest signed `delete` record describes it.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct TrashEntry {
30 /// The trashed asset.
31 pub asset_id: Uuid,
32 /// When the `delete` record was signed.
33 pub deleted_at: Timestamp,
34 /// The signed retention floor: a restore is refused at or after it, and a purge before it
35 /// must first re-issue a shorter one. `None` for a `delete` that carries no readable
36 /// window, which never expires and never refuses a restore, because a guessed deadline
37 /// could only ever lose data.
38 pub retention_until: Option<Timestamp>,
39}
40
41impl TrashEntry {
42 /// Whether a `trash-restore` is still accepted at `now`: strictly before `retention_until`.
43 pub fn is_restorable_at(&self, now: Timestamp) -> bool {
44 self.retention_until.is_none_or(|until| now < until)
45 }
46
47 /// Whether the retention window has closed at `now`, so a purge needs no re-issue.
48 pub fn is_expired_at(&self, now: Timestamp) -> bool {
49 self.retention_until.is_some_and(|until| now >= until)
50 }
51}
52
53/// A sync that drained the feed to its head: the evidence a retention sweep needs before it
54/// judges a deadline ([Peering — Sync]).
55///
56/// [Peering — Sync]: https://docs/design/peering/
57#[derive(Debug, Clone, PartialEq, Eq, Default)]
58pub struct FeedDrain {
59 /// The latest server `changed_at` the drain saw, or `None` for a drain that saw no entry.
60 pub latest_changed_at: Option<Timestamp>,
61 /// Every asset the drained feed lists (the assets the server has indexed), with the hash of
62 /// the head record its latest entry carries, or `None` for an entry that carries none (a
63 /// purged asset, or an older server). A record's hash is the SHA-256 of the entry's
64 /// `manifest_cbor`, which is that record's canonical CBOR.
65 ///
66 /// It must cover the whole feed: a drain from the feed's start, or heads the caller kept
67 /// across every cursored drain since one. A drain resumed from a cursor lists only what
68 /// changed after it, so an asset whose `delete` an earlier sync indexed would be missing,
69 /// judged held, and never expire.
70 pub server_heads: BTreeMap<Uuid, Option<Hash32>>,
71}
72
73impl FeedDrain {
74 /// The instant a deadline is judged at: the latest server `changed_at` the drain saw, and
75 /// never this device's clock. A device clock running ahead would purge early, and its
76 /// tombstone would then refuse a restore the server accepted in time; a late purge loses
77 /// nothing. `None` for a drain that saw no entry: there is no reading of the server's clock
78 /// to judge by, so nothing is judged expired.
79 pub fn judged_at(&self) -> Option<Timestamp> {
80 self.latest_changed_at
81 }
82
83 /// Whether the server has indexed the latest `delete` of `records` (an asset's chain, oldest
84 /// first): the feed lists the asset, and the head it carries is that `delete` or a record
85 /// after it. Anything else is a held delete, with no window running on the server: the
86 /// asset is not listed, its head precedes the delete, the entry carries no record, or the
87 /// head is one this chain does not hold.
88 fn indexes_delete_of(&self, asset_id: &Uuid, records: &[ProvenanceRecord]) -> bool {
89 let Some(delete) = records
90 .iter()
91 .rposition(|rec| rec.manifest.core.action == Action::Delete)
92 else {
93 return false;
94 };
95 let Some(Some(head)) = self.server_heads.get(asset_id) else {
96 return false;
97 };
98 records
99 .iter()
100 .position(|rec| rec.record_hash() == *head)
101 .is_some_and(|at| at >= delete)
102 }
103}
104
105/// What a [`purge`](Workspace::purge) did.
106#[derive(Debug, Clone)]
107pub struct PurgeOutcome {
108 /// The purged asset.
109 pub asset_id: Uuid,
110 /// The signed shorter-retention `delete` appended before an early purge, so the server may
111 /// purge too. `None` when the window had already closed. It is the asset's final chain
112 /// head and the record a client sends to the album's ops surface; a delivery that failed
113 /// resends it from [`Workspace::purge_record`].
114 pub reissue: Option<ProvenanceRecord>,
115 /// The files removed, for the caller's log.
116 pub removed_files: usize,
117}
118
119/// The trash entry `asset` is in, or `None` when its chain's lifecycle state is not deleted.
120fn entry_of(asset: &AssetState) -> Option<TrashEntry> {
121 if !asset_is_deleted(asset) {
122 return None;
123 }
124 let record = asset
125 .chain
126 .records()
127 .iter()
128 .rev()
129 .find(|rec| rec.manifest.core.action == Action::Delete)?;
130 let core = &record.manifest.core;
131 let retention_until = core
132 .retention_until
133 .as_deref()
134 .and_then(|until| match until.parse::<Timestamp>() {
135 Ok(until) => Some(until),
136 Err(error) => {
137 tracing::warn!(asset_id = %asset.asset_id, retention_until = %until, %error, "trash: unreadable retention_until; treating the window as open");
138 None
139 }
140 });
141 Some(TrashEntry {
142 asset_id: asset.asset_id,
143 deleted_at: core.timestamp.parse().unwrap_or(Timestamp::UNIX_EPOCH),
144 retention_until,
145 })
146}
147
148/// Remove `path` if it exists. A missing file is not an error: a purge that is retried after a
149/// partial one finds some files already gone.
150fn remove_if_present(path: &Path, removed: &mut usize) -> Result<()> {
151 match fs::remove_file(path) {
152 Ok(()) => {
153 *removed += 1;
154 tracing::trace!(path = %path.display(), "purge: removed");
155 Ok(())
156 }
157 Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
158 Err(error) => Err(LifecycleError::Io(format!(
159 "purge: removing {}: {error}",
160 path.display()
161 ))),
162 }
163}
164
165impl Workspace {
166 /// Soft-delete: emit a `delete` record carrying a signed retention window.
167 pub fn soft_delete(&mut self, asset_id: &Uuid, retain_days: i64) -> Result<()> {
168 // Timestamp arithmetic is absolute, so a retention "day" is exactly 24 h — the
169 // correct semantic for a UTC retention window.
170 let until = (Timestamp::now()
171 + jiff::SignedDuration::from_hours(retain_days.saturating_mul(24)))
172 .to_string();
173 self.append_lifecycle(asset_id, Action::Delete, Some(until), |_, _| {})
174 }
175
176 /// Restore a soft-deleted asset by this device's clock; see [`restore_at`](Self::restore_at).
177 pub fn restore(&mut self, asset_id: &Uuid) -> Result<()> {
178 self.restore_at(asset_id, Timestamp::now())
179 }
180
181 /// Restore a soft-deleted asset: emit a `trash-restore` record, judged at `now`.
182 ///
183 /// # Errors
184 ///
185 /// [`LifecycleError::NotFound`] for an unknown asset, [`LifecycleError::NotInTrash`] for one
186 /// that is not in the trash, and [`LifecycleError::RetentionElapsed`] at or after its signed
187 /// `retention_until`. A refusal signs nothing.
188 #[tracing::instrument(skip(self), fields(asset_id = %asset_id, now = %now))]
189 pub fn restore_at(&mut self, asset_id: &Uuid, now: Timestamp) -> Result<()> {
190 let entry = self.require_trashed(asset_id)?;
191 if !entry.is_restorable_at(now) {
192 let until = entry.retention_until.unwrap_or_default().to_string();
193 tracing::warn!(retention_until = %until, "trash: restore refused, the retention window has closed");
194 return Err(LifecycleError::RetentionElapsed {
195 asset_id: *asset_id,
196 retention_until: until,
197 });
198 }
199 self.append_lifecycle(asset_id, Action::TrashRestore, None, |_, _| {})?;
200 tracing::info!("trash: restored");
201 Ok(())
202 }
203
204 /// The trash entry `asset_id` is in, or `None` when it is unknown or not in the trash.
205 pub fn trash_entry(&self, asset_id: &Uuid) -> Option<TrashEntry> {
206 self.assets.get(asset_id).and_then(entry_of)
207 }
208
209 /// Every asset in the trash, most recently deleted first (ties by id, for determinism).
210 pub fn trash(&self) -> Vec<TrashEntry> {
211 let mut entries: Vec<TrashEntry> = self.assets.values().filter_map(entry_of).collect();
212 entries.sort_by(|a, b| {
213 b.deleted_at
214 .cmp(&a.deleted_at)
215 .then(a.asset_id.cmp(&b.asset_id))
216 });
217 entries
218 }
219
220 /// The trash entries whose signed retention window has closed at `now`: the retention
221 /// sweep's input. Judged by `retention_until` alone, never by how long ago the delete was.
222 pub fn expired_trash(&self, now: Timestamp) -> Vec<TrashEntry> {
223 self.trash()
224 .into_iter()
225 .filter(|entry| entry.is_expired_at(now))
226 .collect()
227 }
228
229 /// The retention sweep's input after a sync: [`expired_trash`](Self::expired_trash) judged
230 /// at the instant [`FeedDrain::judged_at`] gives, less every held delete. Nothing at all
231 /// when no sync drained the feed to its head (`drain` is `None`) or the drain saw no
232 /// entry, which leaves no reading of the server's clock to judge by.
233 ///
234 /// Waiting for the drain means a restore on a later feed page lands before any deadline is
235 /// judged, so the sweep never purges an asset that page restored. Judging by the server's
236 /// clock alone means a device clock running ahead never purges early. A held delete (one
237 /// the server has not indexed, [`FeedDrain::server_heads`]) never expires: the server has
238 /// no window running for it, so only the user's own [`purge`](Self::purge) removes it.
239 pub fn expired_trash_after_drain(&self, drain: Option<&FeedDrain>) -> Vec<TrashEntry> {
240 let Some(drain) = drain else {
241 tracing::debug!("trash: no drained feed; the retention sweep purges nothing");
242 return Vec::new();
243 };
244 let Some(now) = drain.judged_at() else {
245 tracing::debug!(
246 "trash: the drain saw no server clock reading; the retention sweep purges nothing"
247 );
248 return Vec::new();
249 };
250 let mut held = 0usize;
251 let expired: Vec<TrashEntry> = self
252 .expired_trash(now)
253 .into_iter()
254 .filter(|entry| {
255 let indexed = self.assets.get(&entry.asset_id).is_some_and(|asset| {
256 drain.indexes_delete_of(&entry.asset_id, asset.chain.records())
257 });
258 if !indexed {
259 held += 1;
260 tracing::debug!(asset_id = %entry.asset_id, retention_until = ?entry.retention_until, "trash: the server has not indexed this delete; held, so it never expires");
261 }
262 indexed
263 })
264 .collect();
265 tracing::debug!(%now, expired = expired.len(), held, "trash: retention sweep judged after a drain");
266 expired
267 }
268
269 /// Every asset this workspace has purged: the peering tombstones a backup import or a
270 /// peer ingest must never resurrect.
271 pub fn tombstones(&self) -> BTreeSet<Uuid> {
272 self.purged.keys().copied().collect()
273 }
274
275 /// The head of a purged asset's kept provenance chain: the `delete` that ended it. After
276 /// an early purge this is the shorter-retention re-issue, so a delivery that failed can be
277 /// retried from it after [`purge`](Self::purge) returned, and after a reopen. `None` for
278 /// an asset this workspace has not purged.
279 pub fn purge_record(&self, asset_id: &Uuid) -> Option<&ProvenanceRecord> {
280 self.purged
281 .get(asset_id)
282 .and_then(|chain| chain.records().last())
283 }
284
285 /// A purged asset's whole kept provenance chain, oldest first, headed by
286 /// [`purge_record`](Self::purge_record). A held delivery reads the stretch after the
287 /// server's head from it, so a `delete` the server never saw (and the shorter-retention
288 /// re-issue an early purge appended) is sent from the tombstone once another device's
289 /// upload of the create is indexed. `None` for an asset this workspace has not purged.
290 pub fn purged_chain(&self, asset_id: &Uuid) -> Option<&[ProvenanceRecord]> {
291 self.purged.get(asset_id).map(ProvenanceChain::records)
292 }
293
294 /// Purge a trashed asset by this device's clock; see [`purge_at`](Self::purge_at).
295 pub fn purge(&mut self, asset_id: &Uuid) -> Result<PurgeOutcome> {
296 self.purge_at(asset_id, Timestamp::now())
297 }
298
299 /// Hard-delete a trashed asset, judged at `now`.
300 ///
301 /// Before `retention_until` (an early purge, which the user asked for), a `delete` whose
302 /// `retention_until` is `now` is signed and appended first: the server refuses a purge
303 /// before the signed floor, so without the re-issue the server would keep the asset for the
304 /// rest of the old window.
305 ///
306 /// Then the original, every derivative, every local cache entry, the signed sidecar and the
307 /// sealed metadata blob are removed, and the asset leaves the index and this workspace. The
308 /// provenance chain stays on disk: it is the record that the asset was deleted, and without
309 /// it the purge could not be told from a lost file. The original goes first, so a failure
310 /// part-way leaves the asset in the trash for a retry rather than its bytes behind a
311 /// vanished row.
312 ///
313 /// # Errors
314 ///
315 /// [`LifecycleError::NotFound`] for an unknown asset, [`LifecycleError::NotInTrash`] for one
316 /// that is not in the trash (a purge never skips the trash), [`LifecycleError::Io`] when a
317 /// file cannot be removed, and [`LifecycleError::Db`] when the index cannot be updated.
318 #[tracing::instrument(skip(self), fields(asset_id = %asset_id, now = %now))]
319 pub fn purge_at(&mut self, asset_id: &Uuid, now: Timestamp) -> Result<PurgeOutcome> {
320 let entry = self.require_trashed(asset_id)?;
321 let reissue = if entry.is_expired_at(now) {
322 None
323 } else {
324 self.append_lifecycle(asset_id, Action::Delete, Some(now.to_string()), |_, _| {})?;
325 tracing::info!(previous = ?entry.retention_until, "trash: early purge; signed a shorter-retention delete");
326 self.assets[asset_id].chain.records().last().cloned()
327 };
328
329 let removed_files = self.remove_asset_files(asset_id)?;
330 let id = asset_id.to_string();
331 let db = &self.library.db;
332 db.purge_asset(&id)
333 .and_then(|()| db.delete_embeddings_for(&id))
334 .map_err(|e| LifecycleError::Db(e.to_string()))?;
335 if let Some(asset) = self.assets.remove(asset_id) {
336 // The peering tombstone: the kept chain, headed by its `delete`, which a reopen
337 // reads back from the provenance file.
338 self.purged.insert(*asset_id, asset.chain);
339 }
340 tracing::info!(
341 removed_files,
342 reissued = reissue.is_some(),
343 "trash: purged; provenance chain kept"
344 );
345 Ok(PurgeOutcome {
346 asset_id: *asset_id,
347 reissue,
348 removed_files,
349 })
350 }
351
352 /// The asset's trash entry, or why it has none.
353 fn require_trashed(&self, asset_id: &Uuid) -> Result<TrashEntry> {
354 let asset = self
355 .assets
356 .get(asset_id)
357 .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?;
358 entry_of(asset).ok_or(LifecycleError::NotInTrash(*asset_id))
359 }
360
361 /// Remove every file of `asset_id` but its provenance, receipt and attestation logs.
362 fn remove_asset_files(&self, asset_id: &Uuid) -> Result<usize> {
363 let asset = &self.assets[asset_id];
364 let mut removed = 0;
365 remove_if_present(&self.media_path(asset), &mut removed)?;
366
367 let stem = format!("{}.", asset_id.simple());
368 let derivatives = media_dir(&self.root, asset.capture_utc).join("derivatives");
369 match fs::read_dir(&derivatives) {
370 Ok(entries) => {
371 for entry in entries.filter_map(std::result::Result::ok) {
372 if entry.file_name().to_string_lossy().starts_with(&stem) {
373 remove_if_present(&entry.path(), &mut removed)?;
374 }
375 }
376 }
377 Err(error) if error.kind() == ErrorKind::NotFound => {}
378 Err(error) => {
379 return Err(LifecycleError::Io(format!(
380 "purge: listing {}: {error}",
381 derivatives.display()
382 )));
383 }
384 }
385
386 for path in self.cache_paths(asset_id)? {
387 remove_if_present(&path, &mut removed)?;
388 }
389
390 remove_if_present(&self.sidecar_path(asset), &mut removed)?;
391 remove_if_present(&self.metadata_blob_path(asset), &mut removed)?;
392 remove_if_present(&self.create_metadata_blob_path_of(asset), &mut removed)?;
393 Ok(removed)
394 }
395
396 /// Every local cache path `asset_id` may occupy: the `index/` tree's fixed layout and every
397 /// path the cache table recorded for it. A recorded path outside this library is skipped
398 /// rather than trusted, so a corrupt row cannot point a purge at someone else's file.
399 fn cache_paths(&self, asset_id: &Uuid) -> Result<Vec<PathBuf>> {
400 let mut paths = Vec::new();
401 for size in [
402 ThumbnailSize::Xs,
403 ThumbnailSize::S,
404 ThumbnailSize::M,
405 ThumbnailSize::L,
406 ThumbnailSize::Xl,
407 ThumbnailSize::O,
408 ] {
409 let base = thumbnail_path(&self.root, asset_id, size);
410 for ext in ["jxl", "webp"] {
411 paths.push(base.with_extension(ext));
412 }
413 }
414 paths.push(meta_cache_path(&self.root, asset_id));
415 paths.push(transcode_h264_path(&self.root, asset_id));
416 paths.push(transcode_live_path(&self.root, asset_id));
417
418 let rows = self
419 .library
420 .db
421 .representations_for(&asset_id.to_string())
422 .map_err(|e| LifecycleError::Db(e.to_string()))?;
423 for row in rows {
424 let recorded = Path::new(&row.path);
425 let path = self.root.join(recorded);
426 let climbs = recorded
427 .components()
428 .any(|c| matches!(c, std::path::Component::ParentDir));
429 if path.starts_with(&self.root) && !climbs {
430 paths.push(path);
431 } else {
432 tracing::warn!(path = %row.path, tier = %row.tier, "purge: cache row names a path outside the library; left alone");
433 }
434 }
435 Ok(paths)
436 }
437}
438
439#[cfg(test)]
440mod tests;