Skip to main content

capsule_sdk/ffi/
events.rs

1//! The **transfer event stream** across the FFI boundary: the flattened mirror of
2//! [`crate::events`] and the subscription an app's real-time transfer view polls.
3//!
4//! # Shape
5//!
6//! A subscription is an object with one `async` method, [`FfiTransferSubscription::next`],
7//! rather than a foreign callback. The app pulls at its own pace, so a view that stops
8//! drawing stops pulling and nothing on the Rust side calls into foreign code from a transfer
9//! task; cancelling the foreign task that awaits `next` drops the future and ends the wait.
10//! The transfer itself never waits on the observer: the channel is the bounded broadcast
11//! [`TransferEvents`] already is, and a subscriber that falls behind reads
12//! [`FfiTransferFeedItem::Lagged`] with the count it missed.
13//!
14//! # Stamps
15//!
16//! Each event is stamped, as it is received, with the milliseconds since the subscription
17//! opened on a monotonic clock ([`std::time::Instant`]). The stamp is taken here so the fold
18//! that draws the stream (the apps' `TransferBoard`, the TUI's transfer view) never reads a
19//! clock, and a recorded stream replays into exactly the frames it drew live.
20//!
21//! Events describe the transfer, never its contents: offsets, sizes, content addresses and
22//! session ids, no plaintext and no key material.
23
24use std::sync::Arc;
25use std::time::{Duration, Instant};
26
27use tokio::sync::Mutex;
28use tokio::sync::broadcast::error::RecvError;
29use tokio::sync::broadcast::{self};
30
31use crate::events::{RetryReason, TransferEvent, TransferEvents, millis};
32
33/// Why an upload chunk is sent again. Mirrors [`RetryReason`] variant for variant.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
35pub enum FfiRetryReason {
36    /// The connection reset or the request was lost; the same chunk is re-sent after the wait.
37    TransportReset {
38        /// The backoff taken before the re-send, in milliseconds.
39        wait_ms: u64,
40    },
41    /// The server named a different offset; the transfer continues from it.
42    OffsetRealign {
43        /// The authoritative offset the transfer continues from.
44        to: u64,
45    },
46    /// The session was gone; a new one is created and the transfer continues from the offset
47    /// it reports.
48    SessionLost,
49    /// The server asked the client to wait; afterwards the transfer resumes from the offset
50    /// `HEAD` reports.
51    ServerWait {
52        /// The wait taken, in milliseconds.
53        wait_ms: u64,
54    },
55}
56
57impl From<RetryReason> for FfiRetryReason {
58    fn from(reason: RetryReason) -> Self {
59        match reason {
60            RetryReason::TransportReset { wait_ms } => Self::TransportReset { wait_ms },
61            RetryReason::OffsetRealign { to } => Self::OffsetRealign { to },
62            RetryReason::SessionLost => Self::SessionLost,
63            RetryReason::ServerWait { wait_ms } => Self::ServerWait { wait_ms },
64        }
65    }
66}
67
68/// One step of an upload, a custody check or a ranged fetch. Mirrors [`TransferEvent`]
69/// variant for variant and field for field; `blob` is the content address (lowercase hex) and
70/// offsets and lengths are bytes of ciphertext.
71#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
72pub enum FfiTransferEvent {
73    /// `POST /upload` opened a session; `resume_offset` is non-zero when the server returned an
74    /// existing session for the same blob.
75    SessionCreated {
76        /// The blob's content address.
77        blob: String,
78        /// The upload session id.
79        session_id: String,
80        /// The declared ciphertext size.
81        size: u64,
82        /// Bytes the server already holds.
83        resume_offset: u64,
84    },
85    /// An existing session resumed from the offset `HEAD` reported.
86    SessionResumed {
87        /// The blob's content address.
88        blob: String,
89        /// The upload session id.
90        session_id: String,
91        /// The declared ciphertext size.
92        size: u64,
93        /// The authoritative offset the transfer continues from.
94        offset: u64,
95    },
96    /// A chunk left the client.
97    ChunkSent {
98        /// The blob's content address.
99        blob: String,
100        /// The upload session id.
101        session_id: String,
102        /// The chunk's first byte.
103        offset: u64,
104        /// The chunk's length.
105        len: u64,
106    },
107    /// The server acknowledged a chunk; `acked_offset` is its new received-byte count.
108    ChunkAcked {
109        /// The blob's content address.
110        blob: String,
111        /// The upload session id.
112        session_id: String,
113        /// The chunk's first byte.
114        offset: u64,
115        /// The chunk's length.
116        len: u64,
117        /// The authoritative offset after the acknowledgement.
118        acked_offset: u64,
119    },
120    /// A chunk will be sent again, or the transfer moves to another offset or session.
121    ChunkRetried {
122        /// The blob's content address.
123        blob: String,
124        /// The upload session id the refused chunk was sent to.
125        session_id: String,
126        /// The refused chunk's first byte.
127        offset: u64,
128        /// The refused chunk's length.
129        len: u64,
130        /// Why.
131        reason: FfiRetryReason,
132    },
133    /// The server refused a chunk whose body did not match its checksum; it is re-sent.
134    ChecksumRejected {
135        /// The blob's content address.
136        blob: String,
137        /// The upload session id.
138        session_id: String,
139        /// The chunk's first byte.
140        offset: u64,
141        /// The chunk's length.
142        len: u64,
143    },
144    /// Every declared byte reached the server; it is finalizing the blob.
145    Finalize {
146        /// The blob's content address.
147        blob: String,
148        /// The session driven to completion.
149        session_id: String,
150        /// The blob's size.
151        size: u64,
152    },
153    /// The server already held the blob: resolved as a merge, nothing sent.
154    Merged {
155        /// The blob's content address.
156        blob: String,
157        /// The existing asset the reference merges onto.
158        asset_ref: String,
159    },
160    /// `POST /storage/verify` answered for an asset.
161    Verify {
162        /// The asset asked about.
163        asset_id: String,
164        /// The server's aggregate verdict.
165        durable: bool,
166        /// Blobs declared.
167        blobs: u64,
168        /// Declared blobs not stored, indexed and retrievable.
169        not_durable: u64,
170    },
171    /// A custody receipt for one blob verified under the pinned attestation keys.
172    Receipt {
173        /// The asset whose log held it.
174        asset_id: String,
175        /// The blob's content address.
176        blob: String,
177        /// The receipt's sequence number in the asset's log.
178        receipt_seq: u64,
179    },
180    /// A ranged request left the client; `max_len` is the bounded window, or `None` for the
181    /// open-ended remainder.
182    RangeRequested {
183        /// The blob's content address.
184        blob: String,
185        /// The first byte asked for.
186        offset: u64,
187        /// The most bytes asked for.
188        max_len: Option<u64>,
189    },
190    /// Bytes of a ranged request landed.
191    RangeReceived {
192        /// The blob's content address.
193        blob: String,
194        /// The first byte that landed.
195        offset: u64,
196        /// How many bytes landed.
197        len: u64,
198    },
199    /// A ranged request brought nothing; the fetch backs off and resumes from the same offset.
200    FetchRetried {
201        /// The blob's content address.
202        blob: String,
203        /// The offset the fetch resumes from.
204        offset: u64,
205        /// Whether the no-bytes stall cut tripped.
206        stalled: bool,
207        /// The backoff taken, in milliseconds.
208        wait_ms: u64,
209    },
210    /// The fetched bytes hashed to the requested content address.
211    FetchVerified {
212        /// The blob's content address.
213        blob: String,
214        /// The blob's size.
215        size: u64,
216    },
217    /// The fetched bytes did not hash to the requested content address and were discarded.
218    IntegrityRejected {
219        /// The requested content address.
220        blob: String,
221        /// How many bytes were fetched and discarded.
222        size: u64,
223    },
224}
225
226impl From<TransferEvent> for FfiTransferEvent {
227    fn from(event: TransferEvent) -> Self {
228        match event {
229            TransferEvent::SessionCreated {
230                blob,
231                session_id,
232                size,
233                resume_offset,
234            } => Self::SessionCreated {
235                blob,
236                session_id,
237                size,
238                resume_offset,
239            },
240            TransferEvent::SessionResumed {
241                blob,
242                session_id,
243                size,
244                offset,
245            } => Self::SessionResumed {
246                blob,
247                session_id,
248                size,
249                offset,
250            },
251            TransferEvent::ChunkSent {
252                blob,
253                session_id,
254                offset,
255                len,
256            } => Self::ChunkSent {
257                blob,
258                session_id,
259                offset,
260                len,
261            },
262            TransferEvent::ChunkAcked {
263                blob,
264                session_id,
265                offset,
266                len,
267                acked_offset,
268            } => Self::ChunkAcked {
269                blob,
270                session_id,
271                offset,
272                len,
273                acked_offset,
274            },
275            TransferEvent::ChunkRetried {
276                blob,
277                session_id,
278                offset,
279                len,
280                reason,
281            } => Self::ChunkRetried {
282                blob,
283                session_id,
284                offset,
285                len,
286                reason: reason.into(),
287            },
288            TransferEvent::ChecksumRejected {
289                blob,
290                session_id,
291                offset,
292                len,
293            } => Self::ChecksumRejected {
294                blob,
295                session_id,
296                offset,
297                len,
298            },
299            TransferEvent::Finalize {
300                blob,
301                session_id,
302                size,
303            } => Self::Finalize {
304                blob,
305                session_id,
306                size,
307            },
308            TransferEvent::Merged { blob, asset_ref } => Self::Merged { blob, asset_ref },
309            TransferEvent::Verify {
310                asset_id,
311                durable,
312                blobs,
313                not_durable,
314            } => Self::Verify {
315                asset_id,
316                durable,
317                blobs,
318                not_durable,
319            },
320            TransferEvent::Receipt {
321                asset_id,
322                blob,
323                receipt_seq,
324            } => Self::Receipt {
325                asset_id,
326                blob,
327                receipt_seq,
328            },
329            TransferEvent::RangeRequested {
330                blob,
331                offset,
332                max_len,
333            } => Self::RangeRequested {
334                blob,
335                offset,
336                max_len,
337            },
338            TransferEvent::RangeReceived { blob, offset, len } => {
339                Self::RangeReceived { blob, offset, len }
340            }
341            TransferEvent::FetchRetried {
342                blob,
343                offset,
344                stalled,
345                wait_ms,
346            } => Self::FetchRetried {
347                blob,
348                offset,
349                stalled,
350                wait_ms,
351            },
352            TransferEvent::FetchVerified { blob, size } => Self::FetchVerified { blob, size },
353            TransferEvent::IntegrityRejected { blob, size } => {
354                Self::IntegrityRejected { blob, size }
355            }
356        }
357    }
358}
359
360/// A transfer event and when it arrived: milliseconds since the subscription opened, on a
361/// monotonic clock.
362#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
363pub struct FfiStampedTransferEvent {
364    /// Milliseconds since the subscription opened.
365    pub at_ms: u64,
366    /// The event.
367    pub event: FfiTransferEvent,
368}
369
370/// What one pull of a subscription yields.
371#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
372pub enum FfiTransferFeedItem {
373    /// The next event.
374    Event {
375        /// The event and its stamp.
376        stamped: FfiStampedTransferEvent,
377    },
378    /// The subscriber fell behind and this many events never arrived. The transfers carried
379    /// on; only their progress went unseen.
380    Lagged {
381        /// How many events were missed.
382        missed: u64,
383    },
384}
385
386/// The time since a subscription opened, read when an event arrives.
387type Elapsed = Arc<dyn Fn() -> Duration + Send + Sync>;
388
389/// A live subscription to a session's transfer events: every step published after it opened.
390///
391/// Obtained from [`FfiSession::transfer_events`](crate::ffi::FfiSession::transfer_events).
392/// Pull with [`next`](Self::next) until it answers `None`, which it does once the session that
393/// publishes the events is gone.
394#[derive(uniffi::Object)]
395pub struct FfiTransferSubscription {
396    receiver: Mutex<Option<broadcast::Receiver<TransferEvent>>>,
397    elapsed: Elapsed,
398}
399
400impl FfiTransferSubscription {
401    /// Subscribe to `events`, stamping each event with the time since now.
402    pub(crate) fn open(events: &TransferEvents) -> Arc<Self> {
403        let opened = Instant::now();
404        Self::with_clock(events, Arc::new(move || opened.elapsed()))
405    }
406
407    /// Subscribe to `events`, stamping each event with what `elapsed` reads when it arrives.
408    /// The seam a deterministic test drives.
409    pub(crate) fn with_clock(events: &TransferEvents, elapsed: Elapsed) -> Arc<Self> {
410        let receiver = events.subscribe();
411        tracing::debug!(
412            observed = receiver.is_some(),
413            "ffi: transfer event subscription opened"
414        );
415        Arc::new(Self {
416            receiver: Mutex::new(receiver),
417            elapsed,
418        })
419    }
420}
421
422#[uniffi::export(async_runtime = "tokio")]
423impl FfiTransferSubscription {
424    /// The next event, or how many were missed since the last pull; `None` once the session
425    /// publishing them is gone, and from then on.
426    ///
427    /// Waits for an event when none is pending. Concurrent pulls take turns: each event is
428    /// delivered to exactly one of them.
429    pub async fn next(&self) -> Option<FfiTransferFeedItem> {
430        let mut guard = self.receiver.lock().await;
431        let receiver = guard.as_mut()?;
432        match receiver.recv().await {
433            Ok(event) => Some(FfiTransferFeedItem::Event {
434                stamped: FfiStampedTransferEvent {
435                    at_ms: millis((self.elapsed)()),
436                    event: event.into(),
437                },
438            }),
439            Err(RecvError::Lagged(missed)) => {
440                tracing::debug!(missed, "ffi: transfer event subscriber lagged");
441                Some(FfiTransferFeedItem::Lagged { missed })
442            }
443            Err(RecvError::Closed) => {
444                tracing::debug!("ffi: transfer event stream closed");
445                *guard = None;
446                None
447            }
448        }
449    }
450}
451
452#[cfg(test)]
453mod tests;