capsule_sdk/ffi/ops.rs
1//! Lifecycle ops from an app: one signed `delete` or `trash-restore` record, as the opaque
2//! canonical CBOR the workspace hands out, sent to its album's ops surface
3//! (`POST /v1/albums/{album_id}/ops`) through
4//! [`AlbumClient::apply_op`](crate::albums::AlbumClient::apply_op).
5//!
6//! # What crosses the boundary
7//!
8//! The record bytes come from foreign code, so they are judged before anything is sent
9//! ([`decode_op_record`](crate::ffi::ops::decode_op_record)): bounded in size, decoded as a
10//! [`ProvenanceRecord`](capsule_core::crypto::provenance::ProvenanceRecord), and refused
11//! unless they are that record's own canonical encoding, so the bytes the server hashes as the
12//! chain head are exactly the bytes the device signed. Only the actions that move no bytes and
13//! bind no metadata blob are accepted: a `delete` or a `trash-restore`.
14//!
15//! The server cannot verify a record's signatures, so a mis-signed record it accepted would
16//! become the asset's chain head and fail every reader's `verify_asset`. The bytes are therefore
17//! also judged against the workspace ([`judge_own_record`](crate::ffi::ops::judge_own_record)):
18//! the record's device signature verifies under the workspace's device directory, and it is a
19//! record of the chain the workspace holds for its asset. A delivery verifies every record of
20//! the stretch it sends the same way.
21//!
22//! # A delete is held until its create is indexed
23//!
24//! The server never sees a `delete` for an asset it has not indexed (Organization — Deletion
25//! State Machine). The evidence is the caller's sync feed: every verb here takes the head the
26//! feed lists for the asset (`server_head`, the latest entry's `manifest_cbor`), and `None`, an
27//! asset the feed does not list, sends nothing and answers
28//! [`FfiLifecycleOpOutcome::NotIndexed`]. Nothing is lost by holding: the record stays on the
29//! asset's chain in the workspace (the kept chain, after a purge), and a later delivery reads it
30//! from there again, also after a reopen.
31//!
32//! # A purge's re-issue goes with the stretch it chains onto
33//!
34//! An early purge appends a shorter-retention `delete` that chains onto the asset's previous
35//! head, usually the `delete` that moved it to the trash. When that delete never reached the
36//! server, the re-issue alone would be refused as a stale chain, so
37//! [`FfiSession::deliver_purge`] sends every record of the kept chain after the head the server
38//! holds, in chain order, each once the one before it was applied.
39//!
40//! # A live or trashed asset's held records go the same way
41//!
42//! A `delete` or `trash-restore` of an asset the workspace still holds is signed onto its chain
43//! and held there until the feed lists the asset. [`FfiSession::deliver_lifecycle_at_hash`]
44//! sends the stretch after the head the server holds, by the same rule as a purge and as the
45//! CLI ([`plan_delivery`](crate::albums::plan_delivery)): held while the asset is not indexed, and never a `trash-restore`
46//! that undoes a held `delete` whose window has closed, which answers
47//! [`FfiLifecycleOpOutcome::RestoreTooLate`].
48
49use std::sync::Arc;
50
51use capsule_core::crypto::hash::{Hash32, hash_bytes};
52use capsule_core::crypto::provenance::{Action, ProvenanceRecord};
53use capsule_core::crypto::verify_asset::verify_device_signature;
54use capsule_library::lifecycle::Workspace;
55use uuid::Uuid;
56
57use super::workspace::{parse_uuid, trash_error};
58use super::{FfiError, FfiSession, FfiWorkspace};
59use crate::albums::{
60 AlbumClient, AlbumTransport, AppliedOp, HeldDelivery, HoldReason, LifecycleOpError,
61 judging_clock, op_envelope, plan_delivery,
62};
63
64/// The largest record [`FfiSession::apply_lifecycle_op`] decodes. A lifecycle record is one
65/// signed manifest with its chain position, a few kilobytes even under hybrid signatures; this
66/// leaves an order of magnitude of room and refuses anything that could only be an attack on
67/// the decoder.
68pub const MAX_OP_RECORD_BYTES: usize = 64 * 1024;
69
70/// What became of one lifecycle op.
71#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
72pub enum FfiLifecycleOpOutcome {
73 /// The server applied the op, or had applied it already (`replayed`).
74 Applied {
75 /// The asset the op chained onto (UUID string).
76 asset_id: String,
77 /// The action the server applied (`delete`, `trash-restore`).
78 action: String,
79 /// The feed position the op occupies; on a replay, the one the first application took.
80 sync_seq: u64,
81 /// Whether the server had applied this record already: a resend whose answer was lost.
82 replayed: bool,
83 },
84 /// Nothing was sent: the feed does not list the asset, so its create is not indexed on the
85 /// server, and the server never sees a `delete` for an asset it has not indexed. The record
86 /// stays on the asset's chain; deliver it once a sync lists the asset.
87 NotIndexed,
88 /// Nothing was sent: a `trash-restore` in the stretch undoes a `delete` the server has not
89 /// seen, and that delete's window closed at `retention_until`. Sent, the server would apply
90 /// the delete, refuse the restore and purge an asset the user restored in time. Withheld
91 /// for good: the server keeps the asset live at the head it holds, the workspace keeps
92 /// every record, and nothing after the pair can be sent either, since the chain is
93 /// hash-linked. A later delivery judges it the same way, so it never needs retrying.
94 RestoreTooLate {
95 /// The withheld `delete`'s signed window (RFC 3339), which had closed.
96 retention_until: String,
97 },
98 /// The server refused the op, or could not be reached. `permanent` says whether sending
99 /// the same bytes again can only be refused again.
100 Failed {
101 /// A stable name for why, as the CLI's `--json` reports it: `retention_elapsed`,
102 /// `stale_revival`, `refused`, `forbidden`, `upgrade_required`, `unavailable` or
103 /// `malformed`.
104 kind: String,
105 /// The server's stable `error.*` code, when it gave one.
106 code: Option<String>,
107 /// Whether a resend can only be refused again: the server judged the op itself (a stale
108 /// chain, a closed retention window, a malformed op). Never retry a permanent failure.
109 permanent: bool,
110 /// On a stale chain, the head the server holds (hex SHA-256).
111 chain_head: Option<String>,
112 /// On a closed retention window, the signed floor the server judged (RFC 3339).
113 retention_until: Option<String>,
114 /// English detail (developer/log message).
115 detail: String,
116 },
117}
118
119impl FfiLifecycleOpOutcome {
120 fn applied(applied: AppliedOp) -> Self {
121 Self::Applied {
122 asset_id: applied.asset_id,
123 action: applied.action,
124 sync_seq: applied.sync_seq,
125 replayed: applied.replayed,
126 }
127 }
128}
129
130/// The outcome of a lifecycle op the server did not apply, or the [`FfiError::Auth`] a session
131/// it refused is, so the app signs in again rather than retrying.
132fn failed(error: LifecycleOpError) -> Result<FfiLifecycleOpOutcome, FfiError> {
133 let (chain_head, retention_until) = match &error {
134 LifecycleOpError::Refused {
135 status: 401, code, ..
136 } => {
137 return Err(FfiError::Auth {
138 code: Some(code.clone()),
139 detail: error.to_string(),
140 });
141 }
142 LifecycleOpError::Refused {
143 chain_head,
144 retention_until,
145 ..
146 } => (chain_head.clone(), retention_until.clone()),
147 _ => (None, None),
148 };
149 Ok(FfiLifecycleOpOutcome::Failed {
150 kind: error.kind().to_owned(),
151 code: error.error_code().map(str::to_owned),
152 permanent: error.is_permanent(),
153 chain_head,
154 retention_until,
155 detail: error.to_string(),
156 })
157}
158
159/// Judge foreign `bytes` as a lifecycle op record: at most [`MAX_OP_RECORD_BYTES`], a
160/// [`ProvenanceRecord`] whose canonical encoding they are exactly, of a `delete` or a
161/// `trash-restore` that binds no metadata blob.
162///
163/// # Errors
164///
165/// [`FfiError::InvalidArgument`] naming the first rule the bytes break.
166pub(super) fn decode_op_record(bytes: &[u8]) -> Result<ProvenanceRecord, FfiError> {
167 let invalid = |detail: String| {
168 tracing::warn!(len = bytes.len(), %detail, "ffi: a lifecycle op record was refused");
169 FfiError::InvalidArgument { detail }
170 };
171 if bytes.len() > MAX_OP_RECORD_BYTES {
172 return Err(invalid(format!(
173 "record: {} bytes is over the {MAX_OP_RECORD_BYTES}-byte bound",
174 bytes.len()
175 )));
176 }
177 let record: ProvenanceRecord = capsule_core::cbor::from_slice(bytes)
178 .map_err(|e| invalid(format!("record: not a provenance record ({e})")))?;
179 let canonical = capsule_core::cbor::to_canonical_vec(&record)
180 .map_err(|e| invalid(format!("record: does not re-encode ({e})")))?;
181 if canonical != bytes {
182 return Err(invalid(
183 "record: not in canonical CBOR, so its hash is not the one its chain names".to_owned(),
184 ));
185 }
186 let core = &record.manifest.core;
187 if !matches!(core.action, Action::Delete | Action::TrashRestore) {
188 return Err(invalid(format!(
189 "record: a {:?} is not a lifecycle op this verb sends; only a delete or a trash-restore",
190 core.action
191 )));
192 }
193 if core.metadata_blob_hash.is_some() {
194 return Err(invalid(
195 "record: binds a metadata blob, which a delete or a trash-restore never does"
196 .to_owned(),
197 ));
198 }
199 Ok(record)
200}
201
202/// Judge `record` against `ws`: its device signature verifies under the workspace's device
203/// directory ([`verify_device_signature`]), and it is a record of the chain the workspace holds
204/// for its asset, live, trashed or kept by a purge. The server cannot verify signatures, so
205/// this is the last place a mis-signed or foreign record is stopped before it would become the
206/// asset's chain head on the server.
207///
208/// # Errors
209///
210/// The first rule the record breaks, as an English detail.
211pub(super) fn judge_own_record(ws: &Workspace, record: &ProvenanceRecord) -> Result<(), String> {
212 let core = &record.manifest.core;
213 verify_device_signature(&record.manifest, ws.device_directory()).map_err(|reason| {
214 format!(
215 "record: its device signature does not verify under this workspace's device \
216 directory ({reason:?})"
217 )
218 })?;
219 let hash = record.record_hash();
220 let own = ws
221 .asset(&core.file_id)
222 .map(|asset| asset.chain.records())
223 .into_iter()
224 .chain(ws.purged_chain(&core.file_id))
225 .flatten()
226 .any(|held| held.record_hash() == hash);
227 if !own {
228 return Err(format!(
229 "record: not a record of this workspace's chain for asset {}",
230 core.file_id
231 ));
232 }
233 Ok(())
234}
235
236/// The generated request for `record`, whose canonical bytes are `canonical`: the server-visible
237/// projection of its manifest, every field verbatim, naming the original's ciphertext and no
238/// derivative, and no metadata blob.
239fn op_request(record: &ProvenanceRecord, canonical: &[u8]) -> crate::rest::types::OpRequest {
240 use base64::Engine as _;
241 crate::rest::types::OpRequest {
242 manifest_envelope: op_envelope(&record.manifest.core),
243 manifest_cbor: base64::engine::general_purpose::STANDARD.encode(canonical),
244 metadata_blob: crate::rest::Nullable::Absent,
245 }
246}
247
248/// The hash of the head the feed lists for an asset: `None` for an entry that carries no
249/// record, which names no position in any chain.
250fn listed_head(server_head: &[u8]) -> Option<Hash32> {
251 (!server_head.is_empty()).then(|| hash_bytes(server_head))
252}
253
254/// The head hash a caller kept for a listed asset: empty for an entry that carries no record,
255/// otherwise the 32-byte record hash.
256fn listed_hash(server_head_hash: &[u8]) -> Result<Option<Hash32>, FfiError> {
257 if server_head_hash.is_empty() {
258 return Ok(None);
259 }
260 <[u8; 32]>::try_from(server_head_hash)
261 .map(|bytes| Some(Hash32::from_bytes(bytes)))
262 .map_err(|_| FfiError::InvalidArgument {
263 detail: format!(
264 "server_head_hash: {} bytes, not an empty head or a 32-byte record hash",
265 server_head_hash.len()
266 ),
267 })
268}
269
270#[uniffi::export]
271impl FfiWorkspace {
272 /// Every asset this workspace has purged (UUID strings), whose kept chain
273 /// [`purged_record`](Self::purged_record) reads: the list a relaunch walks to deliver the
274 /// purges whose delivery failed or was held, with [`FfiSession::deliver_purge`]. A purge
275 /// the server already applied answers as a replay, so walking it again is safe.
276 pub fn purged_asset_ids(&self) -> Result<Vec<String>, FfiError> {
277 self.with(|ws| Ok(ws.tombstones().iter().map(ToString::to_string).collect()))
278 }
279}
280
281#[uniffi::export(async_runtime = "tokio")]
282impl FfiSession {
283 /// Apply one signed lifecycle op `record` — a `delete` or a `trash-restore`, as the opaque
284 /// canonical CBOR [`FfiWorkspace::provenance_head`],
285 /// [`FfiPurgeOutcome::reissue_record`](super::FfiPurgeOutcome::reissue_record) and
286 /// [`FfiWorkspace::purged_record`] carry — to its album's ops surface on `api_base_url`
287 /// (`http[s]://host:port`, the root `sync_pull` takes).
288 ///
289 /// The record must be one `workspace` holds: its device signature verifies under the
290 /// workspace's device directory, and it is a record of the workspace's chain for its asset
291 /// (live, trashed, or kept by a purge). The server cannot verify signatures, so a record
292 /// that is not this workspace's own is refused here rather than becoming the asset's chain
293 /// head there.
294 ///
295 /// `server_head` is the sync feed's evidence for the asset: the `manifest_cbor` of the
296 /// latest entry listing it (empty for an entry that carries none), or `None` when the feed
297 /// does not list it. With `None` nothing is sent and the answer is
298 /// [`FfiLifecycleOpOutcome::NotIndexed`]: the server never sees a lifecycle op for an asset
299 /// it has not indexed.
300 ///
301 /// Idempotent: a record the server already applied answers `Applied` with `replayed` set.
302 /// A refusal, or a server that could not be reached, is [`FfiLifecycleOpOutcome::Failed`];
303 /// a session the server did not accept is [`FfiError::Auth`].
304 ///
305 /// # Errors
306 ///
307 /// [`FfiError::InvalidArgument`] for bytes that are not a lifecycle op record (over the
308 /// bound, not canonical, not a `delete` or `trash-restore`, not signed by a device of the
309 /// workspace's directory, or not on the workspace's chain for its asset) or an
310 /// `api_base_url` that is not an http(s) URL, before anything is sent;
311 /// [`FfiError::Auth`] for a refused session.
312 pub async fn apply_lifecycle_op(
313 &self,
314 api_base_url: String,
315 workspace: Arc<FfiWorkspace>,
316 record: Vec<u8>,
317 server_head: Option<Vec<u8>>,
318 ) -> Result<FfiLifecycleOpOutcome, FfiError> {
319 let decoded = decode_op_record(&record)?;
320 workspace.with(|ws| {
321 judge_own_record(ws, &decoded).map_err(|detail| {
322 tracing::warn!(asset_id = %decoded.manifest.core.file_id, %detail, "ffi: a lifecycle op record was refused");
323 FfiError::InvalidArgument { detail }
324 })
325 })?;
326 let client = self.album_client(&api_base_url)?;
327 let core = &decoded.manifest.core;
328 tracing::info!(
329 asset_id = %core.file_id,
330 action = ?core.action,
331 indexed = server_head.is_some(),
332 "ffi: applying a lifecycle op"
333 );
334 if server_head.is_none() {
335 tracing::info!(asset_id = %core.file_id, "ffi: the feed does not list the asset; the op is held");
336 return Ok(FfiLifecycleOpOutcome::NotIndexed);
337 }
338 send(&client, &decoded, &record).await
339 }
340
341 /// Deliver a purged asset's `delete` to its album's ops surface: every record of the chain
342 /// the purge kept after the head the server holds, in chain order, each once the one
343 /// before it was applied. After an early purge that is the shorter-retention re-issue
344 /// ([`FfiPurgeOutcome::reissue_record`](super::FfiPurgeOutcome::reissue_record)) together
345 /// with any `delete` it chains onto that the server never saw.
346 ///
347 /// Everything is read from the workspace's kept chain, so a delivery that failed or was
348 /// held is retried by calling this again, also after the workspace was reopened
349 /// ([`FfiWorkspace::purged_asset_ids`] lists what to walk). The workspace lock is held only
350 /// while the chain is read, never across the network. Every record of the stretch is
351 /// judged as [`apply_lifecycle_op`](Self::apply_lifecycle_op) judges a foreign one before
352 /// any is sent, so a kept chain whose records no longer verify sends nothing.
353 ///
354 /// `server_head` is as [`apply_lifecycle_op`](Self::apply_lifecycle_op) takes it: `None`
355 /// sends nothing and answers [`FfiLifecycleOpOutcome::NotIndexed`]. The answer is the last
356 /// record's `Applied` — the purge reached the server — or the first record that was not
357 /// applied, whose `Failed` stops the stretch.
358 ///
359 /// The held rules are a live asset's
360 /// ([`deliver_lifecycle_at_hash`](Self::deliver_lifecycle_at_hash)), judged by this
361 /// device's clock: a kept chain whose stretch holds a `trash-restore` undoing a `delete` the server never saw, whose window has
362 /// closed, is withheld and answers [`FfiLifecycleOpOutcome::RestoreTooLate`].
363 ///
364 /// # Errors
365 ///
366 /// [`FfiError::Trash`] with [`FfiTrashRefusal::NotFound`](super::FfiTrashRefusal::NotFound)
367 /// for an asset this workspace has not purged; [`FfiError::InvalidArgument`] for a malformed
368 /// `asset_id` or `api_base_url`; [`FfiError::Workspace`] for a kept chain whose records do
369 /// not verify under the workspace's device directory; [`FfiError::Auth`] for a refused
370 /// session.
371 pub async fn deliver_purge(
372 &self,
373 api_base_url: String,
374 workspace: Arc<FfiWorkspace>,
375 asset_id: String,
376 server_head: Option<Vec<u8>>,
377 ) -> Result<FfiLifecycleOpOutcome, FfiError> {
378 let head = server_head.as_deref().map(listed_head);
379 self.deliver_chain(
380 &api_base_url,
381 &workspace,
382 &asset_id,
383 head,
384 ChainSource::Kept,
385 jiff::Timestamp::now(),
386 )
387 .await
388 }
389
390 /// [`deliver_purge`](Self::deliver_purge) with the head the feed lists given by its record
391 /// hash rather than its bytes: the SHA-256 of the latest entry's `manifest_cbor`, which is
392 /// the head record's hash, so a caller keeps 32 bytes per listed asset instead of the
393 /// record. `Some` of an empty vector is an entry that carries no record, and `None` an asset
394 /// the feed does not list, exactly as `deliver_purge` reads its `server_head`.
395 ///
396 /// # Errors
397 ///
398 /// As [`deliver_purge`](Self::deliver_purge), and [`FfiError::InvalidArgument`] for a
399 /// `server_head_hash` that is neither empty nor 32 bytes, before anything is sent.
400 pub async fn deliver_purge_at_hash(
401 &self,
402 api_base_url: String,
403 workspace: Arc<FfiWorkspace>,
404 asset_id: String,
405 server_head_hash: Option<Vec<u8>>,
406 ) -> Result<FfiLifecycleOpOutcome, FfiError> {
407 let head = server_head_hash.as_deref().map(listed_hash).transpose()?;
408 self.deliver_chain(
409 &api_base_url,
410 &workspace,
411 &asset_id,
412 head,
413 ChainSource::Kept,
414 jiff::Timestamp::now(),
415 )
416 .await
417 }
418
419 /// Deliver the held lifecycle records of an asset `workspace` still holds, live or in the
420 /// trash: every record of its chain after the head the server holds, in chain order, each
421 /// once the one before it was applied. That is a `delete` or `trash-restore` signed while
422 /// the server had not indexed the asset, or whose send failed, together with any it chains
423 /// onto that the server never saw. The rule is the CLI's and a purge's
424 /// ([`plan_delivery`]).
425 ///
426 /// `server_head_hash` is the feed's evidence for the asset, as
427 /// [`deliver_purge_at_hash`](Self::deliver_purge_at_hash) takes it: `None`, an asset the
428 /// feed does not list, sends nothing and answers [`FfiLifecycleOpOutcome::NotIndexed`].
429 ///
430 /// `latest_changed_at` is the latest `changed_at` (RFC 3339) the caller's feed drain saw,
431 /// on the server's clock, or `None` when it saw none. It floors this device's clock
432 /// ([`judging_clock`]), and a stretch in which a `trash-restore` undoes a `delete` whose
433 /// window had closed by that clock is withheld and answers
434 /// [`FfiLifecycleOpOutcome::RestoreTooLate`]: sent, the server would apply the delete and
435 /// refuse the restore.
436 ///
437 /// Everything is read from the workspace's chain, so a delivery that failed or was held is
438 /// retried by calling this again, also after the workspace was reopened. The workspace lock
439 /// is held only while the chain is read, never across the network, and every record of
440 /// the stretch is judged as [`apply_lifecycle_op`](Self::apply_lifecycle_op) judges a
441 /// foreign one before any is sent. A server level with the chain is sent its head alone,
442 /// which it answers as a replay; a caller that compares the listed head with
443 /// [`FfiWorkspace::provenance_head`] first sends nothing for it. The answer is the last
444 /// record's `Applied`, or the first record that was not applied, whose `Failed` stops the
445 /// stretch.
446 ///
447 /// # Errors
448 ///
449 /// [`FfiError::Trash`] with [`FfiTrashRefusal::NotFound`](super::FfiTrashRefusal::NotFound)
450 /// for an asset this workspace does not hold (a purged one goes through
451 /// [`deliver_purge_at_hash`](Self::deliver_purge_at_hash)); [`FfiError::InvalidArgument`]
452 /// for a malformed `asset_id` or `api_base_url`, a `server_head_hash` that is neither empty
453 /// nor 32 bytes, or a `latest_changed_at` that is not an RFC 3339 timestamp, before
454 /// anything is sent; [`FfiError::Workspace`] for a chain whose records do not verify under
455 /// the workspace's device directory; [`FfiError::Auth`] for a refused session.
456 pub async fn deliver_lifecycle_at_hash(
457 &self,
458 api_base_url: String,
459 workspace: Arc<FfiWorkspace>,
460 asset_id: String,
461 server_head_hash: Option<Vec<u8>>,
462 latest_changed_at: Option<String>,
463 ) -> Result<FfiLifecycleOpOutcome, FfiError> {
464 let head = server_head_hash.as_deref().map(listed_hash).transpose()?;
465 let seen = latest_changed_at
466 .as_deref()
467 .map(|at| {
468 at.parse::<jiff::Timestamp>()
469 .map_err(|e| FfiError::InvalidArgument {
470 detail: format!(
471 "latest_changed_at: {at:?} is not an RFC 3339 timestamp ({e})"
472 ),
473 })
474 })
475 .transpose()?;
476 let judge = judging_clock(jiff::Timestamp::now(), seen);
477 self.deliver_chain(
478 &api_base_url,
479 &workspace,
480 &asset_id,
481 head,
482 ChainSource::Held,
483 judge,
484 )
485 .await
486 }
487}
488
489/// Which of an asset's chains a delivery reads from the workspace.
490#[derive(Debug, Clone, Copy)]
491enum ChainSource {
492 /// The chain a purge kept ([`Workspace::purged_chain`]).
493 Kept,
494 /// The chain of an asset the workspace still holds, live or in the trash.
495 Held,
496}
497
498impl ChainSource {
499 /// `asset`'s chain of this kind in `ws`, or the `NotFound` refusal for an asset with none.
500 fn read<'a>(self, ws: &'a Workspace, asset: &Uuid) -> Result<&'a [ProvenanceRecord], FfiError> {
501 let (chain, what) = match self {
502 Self::Kept => (ws.purged_chain(asset), "purged asset"),
503 Self::Held => (ws.asset(asset).map(|held| held.chain.records()), "asset"),
504 };
505 chain.ok_or_else(|| {
506 trash_error(capsule_library::lifecycle::LifecycleError::NotFound(
507 format!("{what} {asset}"),
508 ))
509 })
510 }
511
512 /// What a log line or detail calls the chain.
513 fn name(self) -> &'static str {
514 match self {
515 Self::Kept => "the kept chain",
516 Self::Held => "the chain",
517 }
518 }
519}
520
521impl FfiSession {
522 /// The body of every delivery verb, given what the feed lists for the asset (`None` when it
523 /// does not list it, otherwise the hash of the head it holds, `None` for an entry that
524 /// carries no record), the chain to read, and the clock the held rules judge by.
525 async fn deliver_chain(
526 &self,
527 api_base_url: &str,
528 workspace: &FfiWorkspace,
529 asset_id: &str,
530 head: Option<Option<Hash32>>,
531 source: ChainSource,
532 judge: jiff::Timestamp,
533 ) -> Result<FfiLifecycleOpOutcome, FfiError> {
534 let asset = parse_uuid("asset_id", asset_id)?;
535 let client = self.album_client(api_base_url)?;
536 let chain_name = source.name();
537 let planned: Result<Vec<(ProvenanceRecord, Vec<u8>)>, FfiLifecycleOpOutcome> =
538 workspace.with(|ws| {
539 let chain = source.read(ws, &asset)?;
540 let stretch = match plan_delivery(chain, head, judge) {
541 HeldDelivery::Held {
542 reason: HoldReason::NotIndexed,
543 ..
544 } => return Ok(Err(FfiLifecycleOpOutcome::NotIndexed)),
545 HeldDelivery::Held {
546 reason: HoldReason::RestoreTooLate,
547 retention_until,
548 } => {
549 return Ok(Err(FfiLifecycleOpOutcome::RestoreTooLate {
550 retention_until: retention_until.unwrap_or_default(),
551 }));
552 }
553 HeldDelivery::Send(stretch) => stretch,
554 };
555 stretch
556 .iter()
557 .map(|record| {
558 judge_own_record(ws, record).map_err(|detail| {
559 tracing::error!(%asset, %detail, chain = chain_name, "ffi: a chain record does not verify; nothing is sent");
560 FfiError::Workspace {
561 detail: format!("{chain_name} of {asset}: {detail}"),
562 }
563 })?;
564 let bytes = capsule_core::cbor::to_canonical_vec(record).map_err(|e| {
565 FfiError::Workspace {
566 detail: format!("encoding {chain_name} of {asset}: {e}"),
567 }
568 })?;
569 Ok((record.clone(), bytes))
570 })
571 .collect::<Result<_, FfiError>>()
572 .map(Ok)
573 })?;
574 let stretch = match planned {
575 Ok(stretch) => stretch,
576 Err(held) => {
577 tracing::info!(%asset, chain = chain_name, outcome = ?held, %judge, "ffi: nothing of the asset's chain is sent; its records are held");
578 return Ok(held);
579 }
580 };
581 tracing::info!(%asset, chain = chain_name, records = stretch.len(), "ffi: delivering an asset's records to the album's ops surface");
582 let mut outcome = FfiLifecycleOpOutcome::NotIndexed;
583 for (record, bytes) in &stretch {
584 outcome = send(&client, record, bytes).await?;
585 if !matches!(outcome, FfiLifecycleOpOutcome::Applied { .. }) {
586 tracing::warn!(%asset, chain = chain_name, ?outcome, "ffi: the delivery stopped; the workspace still holds the records");
587 return Ok(outcome);
588 }
589 }
590 tracing::info!(%asset, chain = chain_name, "ffi: the asset's records reached the server");
591 Ok(outcome)
592 }
593}
594
595impl FfiSession {
596 /// An album client on `api_base_url`'s album surface, sending through the current path.
597 fn album_client(&self, api_base_url: &str) -> Result<AlbumClient, FfiError> {
598 let url = reqwest::Url::parse(api_base_url).map_err(|e| FfiError::InvalidArgument {
599 detail: format!("api_base_url: {api_base_url:?} is not a URL ({e})"),
600 })?;
601 if !matches!(url.scheme(), "http" | "https") {
602 return Err(FfiError::InvalidArgument {
603 detail: format!("api_base_url: {api_base_url:?} is not an http(s) URL"),
604 });
605 }
606 let endpoint = format!("{}/v1/albums", api_base_url.trim_end_matches('/'));
607 Ok(AlbumClient::new(AlbumTransport::with_session(
608 self.path_session(),
609 endpoint,
610 )))
611 }
612}
613
614/// Send one judged `record` (canonical bytes `bytes`) and say what became of it.
615async fn send(
616 client: &AlbumClient,
617 record: &ProvenanceRecord,
618 bytes: &[u8],
619) -> Result<FfiLifecycleOpOutcome, FfiError> {
620 match client.apply_op(&op_request(record, bytes)).await {
621 Ok(applied) => Ok(FfiLifecycleOpOutcome::applied(applied)),
622 Err(error) => failed(error),
623 }
624}
625
626#[cfg(test)]
627mod tests;