capsule_sdk/albums/op_wire.rs
1//! The lifecycle op's client-side shape, shared by every client that sends one: the
2//! server-visible projection of a signed lifecycle manifest ([`op_envelope`]), which records
3//! of an asset's chain go to the server when it holds a given head ([`chain_after`],
4//! [`stretch_after`]), and whether they may go now ([`plan_delivery`]).
5//!
6//! # Held records
7//!
8//! The server never sees a lifecycle record of an asset it has not indexed (Organization —
9//! Deletion State Machine), so a stretch is sent only once the server's feed lists the asset,
10//! and until then it is **held** ([`HoldReason::NotIndexed`]).
11//!
12//! One stretch is never sent: a `trash-restore` that undoes a held `delete` whose window has
13//! closed. The server judges a restore by when it arrives, so it would apply the delete, refuse
14//! the restore and purge an asset the user restored in time. The pair is withheld instead
15//! ([`HoldReason::RestoreTooLate`]): the server keeps the asset live at the head it holds, and
16//! the library keeps every record. The chain is hash-linked, so nothing after the pair can be
17//! sent either.
18//!
19//! One copy, so the CLI and the FFI lane send the same envelope and the same stretch for the
20//! same chain; a second copy could drift and send a purge from one client that the other would
21//! have held or ordered differently.
22
23use capsule_core::crypto::hash::Hash32;
24use capsule_core::crypto::provenance::{Action, ManifestCore, ProvenanceRecord};
25use serde::Serialize;
26
27use crate::client::absent_unless;
28use crate::rest::Nullable;
29use crate::rest::types::ManifestEnvelope;
30
31/// The server-visible projection of a lifecycle manifest: every field verbatim, naming the
32/// original's ciphertext, and no derivative (the server refuses the pair on a lifecycle write).
33#[must_use]
34pub fn op_envelope(core: &ManifestCore) -> ManifestEnvelope {
35 let wire = |value: serde_json::Result<serde_json::Value>| {
36 value
37 .ok()
38 .and_then(|v| v.as_str().map(str::to_owned))
39 .unwrap_or_default()
40 };
41 ManifestEnvelope {
42 crypto_suite_id: core.crypto_suite_id,
43 protocol_version: core.protocol_version.clone(),
44 album_id: Nullable::Value(core.album_id.to_string()),
45 file_id: core.file_id.to_string(),
46 amk_version: core.amk_version.0,
47 ciphertext_hash: core.ciphertext_hash.to_hex(),
48 plaintext_size: core.plaintext_size,
49 chunk_size: core.chunk_size,
50 key_mode: wire(serde_json::to_value(core.key_mode)),
51 metadata_blob_hash: absent_unless(core.metadata_blob_hash.map(|h| h.to_hex())),
52 original_blob_hash: Nullable::Absent,
53 derivative_role: Nullable::Absent,
54 derivative_format: Nullable::Absent,
55 created_by_user: core.created_by_user.to_string(),
56 created_by_device: core.created_by_device.to_string(),
57 client_version: core.client_version.clone(),
58 timestamp: core.timestamp.clone(),
59 action: wire(serde_json::to_value(core.action)),
60 prior_provenance_hash: absent_unless(core.prior_provenance_hash.map(|h| h.to_hex())),
61 retention_until: absent_unless(core.retention_until.clone()),
62 }
63}
64
65/// The records of `records` (a chain, oldest first) the server lacks when it holds `head`: those
66/// after it, which is none when `head` already is the last; or the last record alone when
67/// `head` is unknown or not in the chain, which the server judges (a stale chain is refused,
68/// never applied).
69#[must_use]
70pub fn chain_after(records: &[ProvenanceRecord], head: Option<Hash32>) -> &[ProvenanceRecord] {
71 let start = head
72 .and_then(|head| records.iter().position(|r| r.record_hash() == head))
73 .map_or_else(|| records.len().saturating_sub(1), |at| at + 1);
74 records.get(start..).unwrap_or_default()
75}
76
77/// The stretch a delivery sends when the server holds `head`: [`chain_after`], except that a
78/// server level with the chain is sent the last record alone, which it answers as a replay (a
79/// send whose answer was lost). Empty only for an empty chain.
80#[must_use]
81pub fn stretch_after(records: &[ProvenanceRecord], head: Option<Hash32>) -> &[ProvenanceRecord] {
82 let after = chain_after(records, head);
83 if after.is_empty() {
84 records
85 .get(records.len().saturating_sub(1)..)
86 .unwrap_or_default()
87 } else {
88 after
89 }
90}
91
92/// Why an asset's records were not sent.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
94#[serde(rename_all = "snake_case")]
95pub enum HoldReason {
96 /// The server's feed does not list the asset: its create is not indexed there, so no
97 /// lifecycle record of it may be sent yet. Sent by the first delivery that finds it indexed.
98 NotIndexed,
99 /// A restore undoes a delete the server has not seen, and that delete's window has closed:
100 /// sent, the server would apply the delete and refuse the restore. Withheld for good; the
101 /// server keeps the asset live at the head it holds.
102 RestoreTooLate,
103}
104
105/// What a delivery does with one asset's chain ([`plan_delivery`]).
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub enum HeldDelivery<'a> {
108 /// Nothing is sent, for this reason; `retention_until` is the closed window (RFC 3339) of a
109 /// [`HoldReason::RestoreTooLate`].
110 Held {
111 /// Why nothing is sent.
112 reason: HoldReason,
113 /// The withheld `delete`'s signed window, for a [`HoldReason::RestoreTooLate`].
114 retention_until: Option<String>,
115 },
116 /// Send these records, in order, each once the one before it was applied.
117 Send(&'a [ProvenanceRecord]),
118}
119
120/// Decide what of `records` (an asset's chain, oldest first) goes to the server, given what its
121/// feed lists for the asset (`server`: `None` when it does not list it, otherwise the hash of
122/// the head it holds, `None` for an entry that carries no record) and the judging clock
123/// ([`judging_clock`]).
124///
125/// - Not listed: held ([`HoldReason::NotIndexed`]).
126/// - Listed: the [`stretch_after`] the server's head, unless a `trash-restore` in it undoes a
127/// `delete` of the same stretch whose `retention_until` is at or before `judge`, which holds
128/// it ([`HoldReason::RestoreTooLate`]).
129#[must_use]
130pub fn plan_delivery(
131 records: &[ProvenanceRecord],
132 server: Option<Option<Hash32>>,
133 judge: jiff::Timestamp,
134) -> HeldDelivery<'_> {
135 let Some(server_head) = server else {
136 return HeldDelivery::Held {
137 reason: HoldReason::NotIndexed,
138 retention_until: None,
139 };
140 };
141 let stretch = stretch_after(records, server_head);
142 if let Some(until) = restore_too_late(stretch, judge) {
143 return HeldDelivery::Held {
144 reason: HoldReason::RestoreTooLate,
145 retention_until: Some(until),
146 };
147 }
148 HeldDelivery::Send(stretch)
149}
150
151/// The clock a held stretch is judged by: this device's (`now`), floored by the latest
152/// `changed_at` a feed drain saw on the server's clock, so a restore is withheld whenever either
153/// clock says the server would refuse it. Only [`plan_delivery`] uses it: a retention sweep
154/// judges expiry by the server's `changed_at` alone, since a device clock running ahead would
155/// purge early.
156#[must_use]
157pub fn judging_clock(
158 now: jiff::Timestamp,
159 latest_changed_at: Option<jiff::Timestamp>,
160) -> jiff::Timestamp {
161 latest_changed_at.map_or(now, |seen| now.max(seen))
162}
163
164/// The closed window of a `delete` in `stretch` that a later `trash-restore` of the same
165/// stretch undoes, when there is one.
166fn restore_too_late(stretch: &[ProvenanceRecord], judge: jiff::Timestamp) -> Option<String> {
167 let mut undone: Option<&ProvenanceRecord> = None;
168 for record in stretch {
169 match record.manifest.core.action {
170 Action::Delete => undone = Some(record),
171 Action::TrashRestore => {
172 let closed = undone
173 .and_then(|delete| delete.manifest.core.retention_until.clone())
174 .filter(|until| {
175 until
176 .parse::<jiff::Timestamp>()
177 .is_ok_and(|until| judge >= until)
178 });
179 if closed.is_some() {
180 return closed;
181 }
182 undone = None;
183 }
184 _ => {}
185 }
186 }
187 None
188}
189
190#[cfg(test)]
191mod tests;