Skip to main content

capsule_sdk/
events.rs

1//! The typed **transfer event stream**: what an upload, a push or a fetch is doing, as it does
2//! it, for a caller that renders progress (the TUI's transfer view, a mobile progress bar).
3//!
4//! Progress used to exist only as `tracing` lines, which a UI cannot consume. A
5//! [`TransferEvents`] handle is attached to the clients that move bytes —
6//! [`UploadClient::with_events`](crate::upload::UploadClient::with_events) (which
7//! [`push_bundle`](crate::push::push_bundle) drives),
8//! [`verify_custody_with_events`](crate::push::verify_custody_with_events) and
9//! [`RangedFetcher::with_events`](crate::fetch::RangedFetcher::with_events) — and every
10//! subscriber receives each [`TransferEvent`] in the order the client took the step.
11//!
12//! # Contract
13//!
14//! - **Zero cost when nobody listens.** A client built without a handle, or one whose handle has
15//!   no live subscriber, never constructs an event: [`TransferEvents::emit`] takes a closure and
16//!   calls it only when a receiver exists. The disabled path is one branch.
17//! - **A transfer never waits on its observer.** The channel is a bounded
18//!   [`tokio::sync::broadcast`]: a subscriber that falls more than `capacity` events behind
19//!   reads [`RecvError::Lagged`](tokio::sync::broadcast::error::RecvError::Lagged) with the count
20//!   it missed, and the transfer carries on. Progress is advisory; the transfer's result is the
21//!   value its call returns.
22//! - **Deterministic order.** One transfer's events arrive in the order its state machine took
23//!   the steps, so a scripted fault schedule produces the same sequence every run. Events carry
24//!   the blob's content address, so a subscriber watching several concurrent transfers through
25//!   one handle can tell them apart.
26//!
27//! - **Replayable.** An event serializes to one JSON object and parses back to the same value,
28//!   so a recorded stream replays into a progress UI exactly as it was published.
29//!
30//! Events describe the transfer, never its contents: offsets, sizes, content addresses and
31//! session ids, no plaintext and no key material.
32
33use std::time::Duration;
34
35use serde::{Deserialize, Serialize};
36use tokio::sync::broadcast;
37
38/// The capacity [`TransferEvents::default_channel`] uses: room for a few seconds of chunk
39/// traffic on a fast link before a stalled subscriber starts lagging.
40pub const DEFAULT_CAPACITY: usize = 1024;
41
42/// Why a chunk is being sent again, or from a different offset than the last acknowledgement.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(tag = "reason", rename_all = "snake_case")]
45pub enum RetryReason {
46    /// The connection reset or the request was lost; the same chunk is re-sent after `wait`.
47    TransportReset {
48        /// The backoff taken before the re-send, in milliseconds.
49        wait_ms: u64,
50    },
51    /// The server named a different offset (`offset_mismatch`); the transfer continues from it.
52    OffsetRealign {
53        /// The authoritative offset the transfer continues from.
54        to: u64,
55    },
56    /// The session was gone (`session_not_found`, or a `HEAD` answering `404`); a new one is
57    /// created and the transfer continues from the offset it reports.
58    SessionLost,
59    /// The server asked the client to wait (`rate_limited`, `unavailable`, `storage_full`);
60    /// after `wait_ms` the transfer resumes from the offset `HEAD` reports.
61    ServerWait {
62        /// The wait taken, in milliseconds.
63        wait_ms: u64,
64    },
65}
66
67/// One step of a transfer.
68///
69/// `blob` is always the blob's content address (lowercase hex). Offsets and lengths are bytes of
70/// ciphertext.
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72#[serde(tag = "event", rename_all = "snake_case")]
73pub enum TransferEvent {
74    // ── Upload ──────────────────────────────────────────────────────────────
75    /// `POST /upload` opened a session. `resume_offset` is non-zero when the server returned an
76    /// existing active session for the same blob (the idempotent re-create).
77    SessionCreated {
78        /// The blob's content address.
79        blob: String,
80        /// The upload session id.
81        session_id: String,
82        /// The declared ciphertext size.
83        size: u64,
84        /// Where the transfer starts: bytes the server already holds.
85        resume_offset: u64,
86    },
87    /// An existing session was resumed from the offset `HEAD` reported.
88    SessionResumed {
89        /// The blob's content address.
90        blob: String,
91        /// The upload session id.
92        session_id: String,
93        /// The declared ciphertext size, so an observer that never saw the session's create
94        /// (a resume in a later run) still knows how far the transfer has to go.
95        size: u64,
96        /// The authoritative offset the transfer continues from.
97        offset: u64,
98    },
99    /// A chunk left the client (`PATCH /upload/{id}`).
100    ChunkSent {
101        /// The blob's content address.
102        blob: String,
103        /// The upload session id.
104        session_id: String,
105        /// The chunk's first byte.
106        offset: u64,
107        /// The chunk's length.
108        len: u64,
109    },
110    /// The server acknowledged a chunk. `acked_offset` is the server's new received-byte count,
111    /// which is `offset + len` unless the server kept less (a short write).
112    ChunkAcked {
113        /// The blob's content address.
114        blob: String,
115        /// The upload session id.
116        session_id: String,
117        /// The chunk's first byte.
118        offset: u64,
119        /// The chunk's length.
120        len: u64,
121        /// The authoritative offset after the acknowledgement.
122        acked_offset: u64,
123    },
124    /// A chunk will be sent again, or the transfer moves to another offset or session.
125    ChunkRetried {
126        /// The blob's content address.
127        blob: String,
128        /// The upload session id the refused chunk was sent to.
129        session_id: String,
130        /// The refused chunk's first byte.
131        offset: u64,
132        /// The refused chunk's length.
133        len: u64,
134        /// Why.
135        #[serde(flatten)]
136        reason: RetryReason,
137    },
138    /// The server refused a chunk whose body did not match its `X-Capsule-Checksum`
139    /// (`checksum_mismatch`); nothing was persisted and the same chunk is re-sent.
140    ChecksumRejected {
141        /// The blob's content address.
142        blob: String,
143        /// The upload session id.
144        session_id: String,
145        /// The chunk's first byte.
146        offset: u64,
147        /// The chunk's length.
148        len: u64,
149    },
150    /// Every declared byte reached the server; it is finalizing the blob.
151    Finalize {
152        /// The blob's content address.
153        blob: String,
154        /// The session driven to completion.
155        session_id: String,
156        /// The blob's size.
157        size: u64,
158    },
159    /// The server already held this blob (`duplicate_blob`): resolved as a merge, nothing sent.
160    Merged {
161        /// The blob's content address.
162        blob: String,
163        /// The existing asset the reference merges onto.
164        asset_ref: String,
165    },
166
167    // ── Custody ─────────────────────────────────────────────────────────────
168    /// `POST /storage/verify` answered for an asset.
169    Verify {
170        /// The asset asked about.
171        asset_id: String,
172        /// The server's aggregate verdict.
173        durable: bool,
174        /// Blobs declared.
175        blobs: u64,
176        /// Declared blobs not stored ∧ indexed ∧ retrievable.
177        not_durable: u64,
178    },
179    /// A custody receipt for one blob verified under the pinned attestation keys.
180    Receipt {
181        /// The asset whose log held it.
182        asset_id: String,
183        /// The blob's content address.
184        blob: String,
185        /// The receipt's sequence number in the asset's log.
186        receipt_seq: u64,
187    },
188
189    // ── Fetch ───────────────────────────────────────────────────────────────
190    /// A ranged request for a blob left the client. `max_len` is the bounded window, or `None`
191    /// for the open-ended remainder.
192    RangeRequested {
193        /// The blob's content address.
194        blob: String,
195        /// The first byte asked for.
196        offset: u64,
197        /// The most bytes asked for.
198        max_len: Option<u64>,
199    },
200    /// Bytes of a ranged request landed.
201    RangeReceived {
202        /// The blob's content address.
203        blob: String,
204        /// The first byte that landed.
205        offset: u64,
206        /// How many bytes landed.
207        len: u64,
208    },
209    /// A ranged request brought nothing; the fetch backs off and resumes from the same offset.
210    /// `stalled` is set when no bytes arrived for the stall bound.
211    FetchRetried {
212        /// The blob's content address.
213        blob: String,
214        /// The offset the fetch resumes from.
215        offset: u64,
216        /// Whether the no-bytes-for-T stall cut tripped.
217        stalled: bool,
218        /// The backoff taken, in milliseconds.
219        wait_ms: u64,
220    },
221    /// The fetched bytes hashed to the requested content address.
222    FetchVerified {
223        /// The blob's content address.
224        blob: String,
225        /// The blob's size.
226        size: u64,
227    },
228    /// The fetched bytes did not hash to the requested content address; they are discarded.
229    IntegrityRejected {
230        /// The requested content address.
231        blob: String,
232        /// How many bytes were fetched and discarded.
233        size: u64,
234    },
235}
236
237/// The handle a transfer publishes its [`TransferEvent`]s through.
238///
239/// [`TransferEvents::disabled`] (the [`Default`]) publishes nothing and costs one branch per
240/// step. [`TransferEvents::channel`] publishes to every [`subscribe`](Self::subscribe)r. Cloning
241/// the handle shares the channel, so one handle can be attached to several clients.
242#[derive(Debug, Clone, Default)]
243pub struct TransferEvents {
244    sender: Option<broadcast::Sender<TransferEvent>>,
245}
246
247impl TransferEvents {
248    /// A handle that publishes nothing.
249    #[must_use]
250    pub fn disabled() -> Self {
251        Self { sender: None }
252    }
253
254    /// A handle over a fresh channel that holds up to `capacity` events per subscriber before a
255    /// slow one lags. `capacity` is raised to 1 when zero.
256    #[must_use]
257    pub fn channel(capacity: usize) -> Self {
258        let (sender, _) = broadcast::channel(capacity.max(1));
259        Self {
260            sender: Some(sender),
261        }
262    }
263
264    /// [`channel`](Self::channel) at [`DEFAULT_CAPACITY`].
265    #[must_use]
266    pub fn default_channel() -> Self {
267        Self::channel(DEFAULT_CAPACITY)
268    }
269
270    /// A receiver of every event published from now on, or `None` on a disabled handle.
271    #[must_use]
272    pub fn subscribe(&self) -> Option<broadcast::Receiver<TransferEvent>> {
273        self.sender.as_ref().map(broadcast::Sender::subscribe)
274    }
275
276    /// Whether an event published now would reach anyone.
277    #[must_use]
278    pub fn is_observed(&self) -> bool {
279        self.sender
280            .as_ref()
281            .is_some_and(|sender| sender.receiver_count() > 0)
282    }
283
284    /// Publish the event `build` makes, calling it only when someone is subscribed.
285    pub fn emit(&self, build: impl FnOnce() -> TransferEvent) {
286        let Some(sender) = &self.sender else {
287            return;
288        };
289        if sender.receiver_count() == 0 {
290            return;
291        }
292        let event = build();
293        tracing::trace!(?event, "transfer event");
294        // A send fails only when every receiver dropped between the count and the send: there
295        // is nobody left to tell, which is the case the count already skips.
296        let _ = sender.send(event);
297    }
298}
299
300/// A [`Duration`] as whole milliseconds, saturating — the unit events carry waits in.
301pub(crate) fn millis(duration: Duration) -> u64 {
302    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
303}
304
305#[cfg(test)]
306mod tests;