capsule_sdk/ffi.rs
1//! uniffi bindings: an async-capable wrapper over the SDK's user-flow primitives, so iOS/macOS
2//! (Swift), Android (Kotlin), and Linux consumers call
3//! one SDK instead of reimplementing login/upload/sync flows.
4//!
5//! # Surface
6//!
7//! [`FfiCapsuleClient`] is the unauthenticated entry point (auth + upload endpoints
8//! and the protocol pin). [`FfiCapsuleClient::login`]/[`register`](crate::ffi::FfiCapsuleClient::register)
9//! return an [`FfiSession`] **handle** — an opaque object that owns the token store
10//! internally. Every subsequent call ([`upload`](crate::ffi::FfiSession::upload),
11//! [`push_asset`](crate::ffi::FfiSession::push_asset),
12//! [`push_assets`](crate::ffi::FfiSession::push_assets),
13//! [`upload_status`](crate::ffi::FfiSession::upload_status),
14//! [`fetch_blob_to_path`](crate::ffi::FfiSession::fetch_blob_to_path),
15//! [`apply_lifecycle_op`](crate::ffi::FfiSession::apply_lifecycle_op),
16//! [`deliver_purge`](crate::ffi::FfiSession::deliver_purge),
17//! [`deliver_lifecycle_at_hash`](crate::ffi::FfiSession::deliver_lifecycle_at_hash),
18//! [`sync_pull`](crate::ffi::FfiSession::sync_pull),
19//! [`logout`](crate::ffi::FfiSession::logout)) rides that handle, and
20//! [`transfer_events`](crate::ffi::FfiSession::transfer_events) subscribes to the step-by-step
21//! progress of the uploads and fetches it drives. **Tokens never cross the FFI
22//! boundary raw**: the SDK session store injects and auto-refreshes the bearer
23//! behind the handle, so foreign code never sees access/refresh token material.
24//!
25//! [`FfiCapsuleClient`]: crate::ffi::FfiCapsuleClient
26//! [`FfiCapsuleClient::login`]: crate::ffi::FfiCapsuleClient::login
27//! [`FfiSession`]: crate::ffi::FfiSession
28//!
29//! # Async
30//!
31//! The flows are inherently networked, so the exported methods are `async fn` under
32//! `#[uniffi::export(async_runtime = "tokio")]`: uniffi drives the returned future on
33//! the tokio runtime `reqwest`/`tonic` require, and foreign callers see idiomatic
34//! `suspend` (Kotlin) / `async` (Swift) functions. The Rust methods stay plain
35//! `async fn`, so the in-crate smoke exercises them with a direct `.await`.
36//!
37//! # Types
38//!
39//! Following `capsule-core`'s FFI philosophy, the surface is deliberately minimal:
40//! ids/hashes/paths cross as `String`, blobs/manifests/cursors as `bytes`, and the
41//! rich SDK enums/records are flattened into `Ffi*` mirrors so the Rust API stays
42//! free to evolve behind the boundary. Errors carry the stable `error.*` catalog
43//! `code` (which clients localize) plus the English `detail` (which stays
44//! English) — mirroring the server's `{ error, code }` contract. The field is `detail`, not
45//! `message`, because uniffi turns each variant into a Kotlin `Throwable` subclass whose own
46//! `message` property a `val message` field would clash with.
47
48use std::collections::HashSet;
49use std::path::{Path, PathBuf};
50use std::sync::Arc;
51
52use capsule_library::import::UploadPolicy;
53use capsule_library::lifecycle::{LifecycleError, UploadBundle};
54use secrecy::{ExposeSecret as _, SecretString};
55
56use crate::auth::{AuthClient, AuthError, LoginOutcome, Session};
57use crate::directory::{DirectoryClient, DirectoryError};
58use crate::events::TransferEvents;
59use crate::fetch::{FetchError, HttpBlobSource, RangedFetcher};
60use crate::net::ConnectionClass;
61use crate::net::path::{GenerationPool, PathMonitor, PathSample};
62use crate::push::{
63 AssetPushReport, LaneBundle, LanePush, PUSH_BATCH_BUNDLES, PUSH_BYTE_BUDGET, PushError,
64 PushedBlob, push_lanes,
65};
66use crate::recovery::{EscrowStored, RecoveryClient, RecoveryError};
67use crate::staged::{TierSessionOutcome, run_under_path};
68use crate::sync::{
69 BlobManifest, BlobRef, ChangeKind, FeedEntry, SyncConsumer, SyncCursor, SyncError, SyncPage,
70};
71use crate::upload::queue::{LaneWindows, ServerKey};
72use crate::upload::{
73 BlobRole, CreateUploadRequest, HeadInfo, ManifestEnvelope, UploadClient, UploadError,
74 UploadOutcome, UploadTransport,
75};
76
77/// The `capsule-core`-facing workspace verbs: enroll/open, albums, seal + import,
78/// verify, sync-apply, escrow minting, the signed device directory, and labels and regions. Separated from the
79/// networked client/session surface below because it is the half that touches no transport.
80mod workspace;
81
82pub use workspace::{
83 FfiAlbum, FfiAssetFacts, FfiAssetMetadata, FfiClientBuild, FfiDeviceTier, FfiFeedDrain,
84 FfiHardwareKeyAgreement, FfiHardwareSigner, FfiHardwareSignerError, FfiLabelRefusal,
85 FfiLabelTarget, FfiOpenedOriginal, FfiPurgeOutcome, FfiRegion, FfiRegionShape,
86 FfiSyncApplyOutcome, FfiSyncEntry, FfiSyncHead, FfiTrashEntry, FfiTrashRefusal, FfiUploadBlob,
87 FfiVerifyOutcome, FfiWorkspace, p256_hardware_dek_round_trip,
88};
89
90/// The cull verbs on [`FfiWorkspace`]: flag an asset or a stack, read a stack's derived state,
91/// list by flag, list stack membership, and the reject sweep. Its own module because culling is one workflow with one
92/// destructive step, and reads better as a unit than as another section of `workspace`.
93mod culling;
94
95pub use culling::{FfiCullFlag, FfiStackCullState, FfiStackMember};
96
97/// The transfer event stream: the flattened mirror of `crate::events` and the subscription a
98/// real-time transfer view polls. Separated because it is the one surface that is a stream
99/// rather than a call.
100mod events;
101
102pub use events::{
103 FfiRetryReason, FfiStampedTransferEvent, FfiTransferEvent, FfiTransferFeedItem,
104 FfiTransferSubscription,
105};
106
107/// The local-alert surface: the shared `capsule_core::notify` predicate, flattened.
108/// Separated from both blocks above because it touches neither a transport nor a workspace —
109/// it is a pure function of caller-supplied device state, and the two free exports say so.
110mod notify;
111
112pub use notify::{
113 FfiAlert, FfiAlertClass, FfiAlertSeverity, FfiClassDeadline, FfiNotifyInput, FfiQuotaAdvisory,
114 evaluate_alerts, next_alert_deadline, pre_arm_deadlines,
115};
116
117/// The path snapshot an app's OS listeners report, flattened, and what a finished push tells
118/// the adverse detector. Separated because it is the session's one input that is device state
119/// rather than a request.
120mod path;
121
122pub use path::{FfiPathCost, FfiPathInterface, FfiPathSnapshot, FfiPowerState, FfiThermalState};
123
124/// The render ladder: the one order every app renders by, and the embedded-preview read that
125/// feeds it. Separated for the reason `notify` is: pure functions of caller-supplied state.
126mod ladder;
127
128pub use ladder::{
129 FfiEmbeddedPreview, FfiLocalHoldings, FfiNextStep, FfiRenderRequest, FfiRenderStep,
130 FfiRendition, FfiRepresentation, FfiRungSource, embedded_preview, render_step,
131};
132
133/// Lifecycle ops from an app: a signed `delete` or `trash-restore` record, judged at the
134/// boundary and sent to its album's ops surface, and a purge's delivery from the chain the
135/// workspace kept. Separated because it is the one surface where a workspace record meets the
136/// network, and where the rule that holds a delete until its create is indexed lives.
137mod ops;
138
139pub use ops::{FfiLifecycleOpOutcome, MAX_OP_RECORD_BYTES};
140
141// ─── Errors ──────────────────────────────────────────────────────────────────
142
143/// Every failure the FFI flows can surface, flattened by originating layer. Each
144/// variant carries the stable `error.*` catalog `code` (when one applies — clients
145/// localize it) and the English `detail` (stays English), mirroring the
146/// SDK's `{ error, code }` contract so foreign apps switch on the code, never a
147/// bare HTTP status.
148#[derive(Debug, thiserror::Error, uniffi::Error)]
149pub enum FfiError {
150 /// An authentication flow (login/register/refresh/logout) failed.
151 #[error("authentication failed ({code:?}): {detail}")]
152 Auth {
153 /// Stable `error.*` catalog code, when the SDK mapped one.
154 code: Option<String>,
155 /// English detail (developer/log message).
156 detail: String,
157 },
158 /// An upload flow (create/transfer/status) failed.
159 #[error("upload failed ({code:?}): {detail}")]
160 Upload {
161 /// Stable `error.*` catalog code, when the server supplied one.
162 code: Option<String>,
163 /// English detail (developer/log message).
164 detail: String,
165 },
166 /// A sync flow (pull/reconcile) failed.
167 #[error("sync failed ({code:?}): {detail}")]
168 Sync {
169 /// Stable `error.*` catalog code, when one applies.
170 code: Option<String>,
171 /// English detail (developer/log message).
172 detail: String,
173 },
174 /// A local workspace operation failed — opening the library, sealing an asset, reading a
175 /// managed asset. This is the *workspace* failing, never an entry being refused: a refused
176 /// sync entry is a [`FfiSyncApplyOutcome::Quarantined`] verdict, not an error.
177 #[error("workspace error: {detail}")]
178 Workspace {
179 /// English detail (developer/log message).
180 detail: String,
181 },
182 /// A label or region edit was refused before anything was written: its target does not
183 /// exist, the label rule refused the label, or the shape broke the normalized-coordinate
184 /// contract. `refusal` says which, so an editor shows the reason rather than parsing
185 /// `detail`.
186 #[error("label edit refused ({refusal:?}): {detail}")]
187 Label {
188 /// Why the edit was refused.
189 refusal: FfiLabelRefusal,
190 /// English detail (developer/log message).
191 detail: String,
192 },
193 /// A trash verb (delete, restore, purge) was refused before anything was written: the asset
194 /// is unknown, not in the trash, or past its signed retention window. `refusal` says which.
195 #[error("trash verb refused ({refusal:?}): {detail}")]
196 Trash {
197 /// Why the verb was refused.
198 refusal: FfiTrashRefusal,
199 /// Stable `error.*` catalog code, when one applies: `error.upload.retention_elapsed`
200 /// for [`FfiTrashRefusal::RetentionElapsed`], the code the server answers the same
201 /// refusal with.
202 code: Option<String>,
203 /// The signed retention floor (RFC 3339) a refused restore came too late for.
204 retention_until: Option<String>,
205 /// English detail (developer/log message).
206 detail: String,
207 },
208 /// A master-key escrow flow (store/fetch) failed.
209 #[error("escrow failed ({code:?}): {detail}")]
210 Escrow {
211 /// Stable `error.*` catalog code, when the server supplied one — `error.escrow.*`
212 /// separates "you have no recovery backup" (a setup prompt) from "we could not read
213 /// it" (a retry), which is the whole reason the catalog distinguishes them.
214 code: Option<String>,
215 /// English detail (developer/log message).
216 detail: String,
217 },
218 /// A device-directory flow (publish/fetch) failed.
219 #[error("device directory failed ({code:?}): {detail}")]
220 Directory {
221 /// Stable `error.*` catalog code, when one applies.
222 code: Option<String>,
223 /// English detail (developer/log message).
224 detail: String,
225 },
226 /// A blob fetch ([`FfiSession::fetch_blob_to_path`]) failed: the blob is gone, still
227 /// awaiting its original, refused, did not hash to its content address, or could not be
228 /// written locally. Nothing is left at the destination path.
229 #[error("blob fetch failed ({code:?}): {detail}")]
230 Fetch {
231 /// Stable `error.*` catalog code, when one applies (e.g. `error.blob.pending_upload`;
232 /// `error.blob.gone` for a blob or record the server will never serve again: a `410`
233 /// past a retention window or under a takedown, or a `404`).
234 code: Option<String>,
235 /// English detail (developer/log message).
236 detail: String,
237 },
238 /// A foreign argument was structurally invalid (e.g. an un-parseable URL) before
239 /// any network call.
240 #[error("invalid argument: {detail}")]
241 InvalidArgument {
242 /// What was wrong with the argument.
243 detail: String,
244 },
245}
246
247impl From<LifecycleError> for FfiError {
248 fn from(err: LifecycleError) -> Self {
249 Self::Workspace {
250 detail: err.to_string(),
251 }
252 }
253}
254
255impl From<RecoveryError> for FfiError {
256 fn from(err: RecoveryError) -> Self {
257 // A refused credential under an escrow call keeps its auth identity so callers can
258 // trigger interactive re-authentication, exactly as the upload mapping does. Before
259 // the escrow calls moved onto the generated client this arrived as
260 // `RecoveryError::Auth`; routing `Unauthorized` here is what stops the move from
261 // silently downgrading "sign in again" into "escrow failed".
262 if let RecoveryError::Unauthorized { code, detail } = err {
263 return Self::Auth { code, detail };
264 }
265 // A malformed argument is the caller's, not the escrow surface's.
266 if let RecoveryError::InvalidBaseUrl { .. } = err {
267 return Self::InvalidArgument {
268 detail: err.to_string(),
269 };
270 }
271 Self::Escrow {
272 code: err.error_code().map(str::to_owned),
273 detail: err.to_string(),
274 }
275 }
276}
277
278impl From<DirectoryError> for FfiError {
279 fn from(err: DirectoryError) -> Self {
280 if let DirectoryError::Auth(auth) = err {
281 return auth.into();
282 }
283 Self::Directory {
284 code: err.error_code().map(str::to_string),
285 detail: err.to_string(),
286 }
287 }
288}
289
290impl From<AuthError> for FfiError {
291 fn from(err: AuthError) -> Self {
292 let code = err.error_code().map(str::to_string);
293 match &err {
294 AuthError::InvalidBaseUrl { .. } => Self::InvalidArgument {
295 detail: err.to_string(),
296 },
297 _ => Self::Auth {
298 code,
299 detail: err.to_string(),
300 },
301 }
302 }
303}
304
305impl From<UploadError> for FfiError {
306 fn from(err: UploadError) -> Self {
307 // Auth failures under an upload keep their auth identity so callers can
308 // trigger interactive re-authentication.
309 if let UploadError::Auth(auth) = err {
310 return auth.into();
311 }
312 let code = match &err {
313 UploadError::UpgradeRequired { .. } => {
314 Some(capsule_i18n::error_codes::PROTOCOL_VERSION_UNSUPPORTED.to_owned())
315 }
316 _ => err.error_code().map(str::to_owned),
317 };
318 Self::Upload {
319 code,
320 detail: err.to_string(),
321 }
322 }
323}
324
325impl From<PushError> for FfiError {
326 fn from(err: PushError) -> Self {
327 // A transfer failure keeps the upload mapping (and with it the auth identity of a
328 // refused credential); everything else a push can say is an upload-flow failure.
329 match err {
330 PushError::Upload(upload) => return upload.into(),
331 PushError::CreateRefused { source, .. } => return (*source).into(),
332 _ => {}
333 }
334 Self::Upload {
335 code: err.error_code().map(str::to_string),
336 detail: err.to_string(),
337 }
338 }
339}
340
341impl From<FetchError> for FfiError {
342 fn from(err: FetchError) -> Self {
343 // A fetch the session could not authorize keeps its auth identity, as the upload and
344 // sync mappings do, so the app re-authenticates rather than retrying.
345 if let FetchError::Unauthenticated { code, message } = err {
346 return Self::Auth {
347 code,
348 detail: message,
349 };
350 }
351 Self::Fetch {
352 code: err.error_code().map(str::to_string),
353 detail: err.to_string(),
354 }
355 }
356}
357
358impl From<crate::sync::HistoryError> for FfiError {
359 fn from(err: crate::sync::HistoryError) -> Self {
360 match err {
361 // The fetch's own mapping, so a refused refresh stays an auth error, with the link
362 // that could not be followed named.
363 crate::sync::HistoryError::Fetch { hash, source } => match Self::from(source) {
364 Self::Fetch { code, detail } => Self::Fetch {
365 code,
366 detail: format!("provenance record {hash}: {detail}"),
367 },
368 other => other,
369 },
370 other => Self::Sync {
371 code: None,
372 detail: other.to_string(),
373 },
374 }
375 }
376}
377
378impl From<SyncError> for FfiError {
379 fn from(err: SyncError) -> Self {
380 if let SyncError::Auth(auth) = err {
381 return auth.into();
382 }
383 let code = err.error_code().map(str::to_string);
384 Self::Sync {
385 code,
386 detail: err.to_string(),
387 }
388 }
389}
390
391// ─── Upload request mirrors ──────────────────────────────────────────────────
392
393/// FFI mirror of [`BlobRole`] (snake_case on the wire, closed enum).
394#[derive(uniffi::Enum)]
395pub enum FfiBlobRole {
396 /// The source asset.
397 Original,
398 /// A client-generated thumbnail/preview.
399 Derivative,
400 /// The CBOR metadata document.
401 Metadata,
402 /// Append-only provenance.
403 Provenance,
404 /// A library backup artifact.
405 Backup,
406 /// A derivative tier's signed manifest.
407 DerivativeManifest,
408}
409
410impl From<FfiBlobRole> for BlobRole {
411 fn from(role: FfiBlobRole) -> Self {
412 match role {
413 FfiBlobRole::Original => Self::Original,
414 FfiBlobRole::Derivative => Self::Derivative,
415 FfiBlobRole::Metadata => Self::Metadata,
416 FfiBlobRole::Provenance => Self::Provenance,
417 FfiBlobRole::Backup => Self::Backup,
418 FfiBlobRole::DerivativeManifest => Self::DerivativeManifest,
419 }
420 }
421}
422
423impl From<BlobRole> for FfiBlobRole {
424 fn from(role: BlobRole) -> Self {
425 match role {
426 BlobRole::Original => Self::Original,
427 BlobRole::Derivative => Self::Derivative,
428 BlobRole::Metadata => Self::Metadata,
429 BlobRole::Provenance => Self::Provenance,
430 BlobRole::Backup => Self::Backup,
431 BlobRole::DerivativeManifest => Self::DerivativeManifest,
432 }
433 }
434}
435
436/// FFI mirror of [`ManifestEnvelope`] — the server-visible envelope fields the
437/// import pipeline builds and signs; opaque to this layer, carried verbatim.
438#[derive(uniffi::Record)]
439pub struct FfiManifestEnvelope {
440 /// Crypto suite the blob is sealed under.
441 pub crypto_suite_id: u16,
442 /// Protocol date (`YYYY-MM-DD`).
443 pub protocol_version: String,
444 /// Optional album this blob belongs to.
445 pub album_id: Option<String>,
446 /// The asset id this blob belongs to (UUIDv7).
447 pub file_id: String,
448 /// AMK epoch the blob is sealed under.
449 pub amk_version: u32,
450 /// Ciphertext content hash, lowercase hex.
451 pub ciphertext_hash: String,
452 /// Plaintext size in bytes.
453 pub plaintext_size: u64,
454 /// STREAM plaintext chunk size.
455 pub chunk_size: u32,
456 /// `derived | wrapped`.
457 pub key_mode: String,
458 /// Hash of the bundle's metadata blob, when known.
459 pub metadata_blob_hash: Option<String>,
460 /// A derivative blob's role (`thumbnail | preview | embedding`); `None` for every other
461 /// blob.
462 pub derivative_role: Option<String>,
463 /// A derivative blob's format, e.g. `image/jxl`; set exactly when `derivative_role` is.
464 pub derivative_format: Option<String>,
465 /// The authoring user.
466 pub created_by_user: String,
467 /// The authoring device.
468 pub created_by_device: String,
469 /// The exact client build.
470 pub client_version: String,
471 /// RFC 3339 authoring timestamp.
472 pub timestamp: String,
473 /// Lifecycle action (`create` for a fresh bundle).
474 pub action: String,
475 /// Prior provenance hash, for append-only chains.
476 pub prior_provenance_hash: Option<String>,
477 /// Optional retention floor.
478 pub retention_until: Option<String>,
479}
480
481impl From<FfiManifestEnvelope> for ManifestEnvelope {
482 fn from(env: FfiManifestEnvelope) -> Self {
483 Self {
484 crypto_suite_id: env.crypto_suite_id,
485 protocol_version: env.protocol_version,
486 album_id: env.album_id,
487 file_id: env.file_id,
488 amk_version: env.amk_version,
489 ciphertext_hash: env.ciphertext_hash,
490 plaintext_size: env.plaintext_size,
491 chunk_size: env.chunk_size,
492 key_mode: env.key_mode,
493 metadata_blob_hash: env.metadata_blob_hash,
494 derivative_role: env.derivative_role,
495 derivative_format: env.derivative_format,
496 created_by_user: env.created_by_user,
497 created_by_device: env.created_by_device,
498 client_version: env.client_version,
499 timestamp: env.timestamp,
500 action: env.action,
501 prior_provenance_hash: env.prior_provenance_hash,
502 retention_until: env.retention_until,
503 }
504 }
505}
506
507impl From<ManifestEnvelope> for FfiManifestEnvelope {
508 fn from(env: ManifestEnvelope) -> Self {
509 Self {
510 crypto_suite_id: env.crypto_suite_id,
511 protocol_version: env.protocol_version,
512 album_id: env.album_id,
513 file_id: env.file_id,
514 amk_version: env.amk_version,
515 ciphertext_hash: env.ciphertext_hash,
516 plaintext_size: env.plaintext_size,
517 chunk_size: env.chunk_size,
518 key_mode: env.key_mode,
519 metadata_blob_hash: env.metadata_blob_hash,
520 derivative_role: env.derivative_role,
521 derivative_format: env.derivative_format,
522 created_by_user: env.created_by_user,
523 created_by_device: env.created_by_device,
524 client_version: env.client_version,
525 timestamp: env.timestamp,
526 action: env.action,
527 prior_provenance_hash: env.prior_provenance_hash,
528 retention_until: env.retention_until,
529 }
530 }
531}
532
533/// FFI mirror of [`CreateUploadRequest`] — the `POST /upload` body.
534#[derive(uniffi::Record)]
535pub struct FfiUploadRequest {
536 /// Ciphertext size in bytes.
537 pub size: u64,
538 /// Ciphertext content hash, lowercase hex.
539 pub hash: String,
540 /// MIME type (closed enum per protocol version).
541 pub content_type: String,
542 /// Crypto suite the blob is sealed under.
543 pub crypto_suite_id: u16,
544 /// Protocol date (`YYYY-MM-DD`) this client speaks.
545 pub protocol_version: String,
546 /// This blob's role in its bundle.
547 pub blob_role: FfiBlobRole,
548 /// The unencrypted manifest fields the server validates.
549 pub manifest_envelope: FfiManifestEnvelope,
550 /// Optional album to add the asset to.
551 pub album_id: Option<String>,
552 /// Optional owner id (defaults to the authenticated uploader).
553 pub owner_id: Option<String>,
554 /// Album-upgrade intent id (album upgrade ceremony only).
555 pub intent_id: Option<String>,
556}
557
558impl From<FfiUploadRequest> for CreateUploadRequest {
559 fn from(req: FfiUploadRequest) -> Self {
560 Self {
561 size: req.size,
562 hash: req.hash,
563 content_type: req.content_type,
564 crypto_suite_id: req.crypto_suite_id,
565 protocol_version: req.protocol_version,
566 blob_role: req.blob_role.into(),
567 manifest_envelope: req.manifest_envelope.into(),
568 album_id: req.album_id,
569 owner_id: req.owner_id,
570 intent_id: req.intent_id,
571 }
572 }
573}
574
575/// The reverse mapping, so [`FfiWorkspace::upload_blobs`] can hand back exactly what
576/// [`FfiSession::upload`] takes. It reuses `capsule_sdk::push`'s envelope projection wholesale
577/// — the invariant-15 per-blob `ciphertext_hash` rule has one implementation, in `push`, and
578/// this is a shape conversion over its output.
579impl From<CreateUploadRequest> for FfiUploadRequest {
580 fn from(req: CreateUploadRequest) -> Self {
581 Self {
582 size: req.size,
583 hash: req.hash,
584 content_type: req.content_type,
585 crypto_suite_id: req.crypto_suite_id,
586 protocol_version: req.protocol_version,
587 blob_role: req.blob_role.into(),
588 manifest_envelope: req.manifest_envelope.into(),
589 album_id: req.album_id,
590 owner_id: req.owner_id,
591 intent_id: req.intent_id,
592 }
593 }
594}
595
596// ─── Upload outcome / status mirrors ─────────────────────────────────────────
597
598/// FFI mirror of [`UploadOutcome`] — how a full upload resolved.
599#[derive(uniffi::Enum)]
600pub enum FfiUploadOutcome {
601 /// Every declared byte transferred; the server has begun finalization.
602 Completed {
603 /// The session driven to completion.
604 session_id: String,
605 },
606 /// The blob was already stored server-side (the `duplicate_blob` → merge path).
607 AlreadyStored {
608 /// The existing asset the caller merges onto.
609 asset_ref: String,
610 },
611}
612
613impl From<UploadOutcome> for FfiUploadOutcome {
614 fn from(outcome: UploadOutcome) -> Self {
615 match outcome {
616 UploadOutcome::Completed { session_id } => Self::Completed { session_id },
617 UploadOutcome::AlreadyStored { asset_ref } => Self::AlreadyStored { asset_ref },
618 }
619 }
620}
621
622/// FFI mirror of [`HeadInfo`] — the `HEAD /upload/{id}` resumption/status primitive.
623#[derive(uniffi::Record)]
624pub struct FfiUploadStatus {
625 /// Next expected byte (authoritative received-byte count).
626 pub offset: u64,
627 /// Declared total size, when known.
628 pub total_size: Option<u64>,
629 /// Session state (`X-Capsule-Upload-Status`).
630 pub status: String,
631}
632
633impl From<HeadInfo> for FfiUploadStatus {
634 fn from(info: HeadInfo) -> Self {
635 Self {
636 offset: info.offset,
637 total_size: info.total_size,
638 status: info.status,
639 }
640 }
641}
642
643// ─── Push report mirrors ─────────────────────────────────────────────────────
644
645/// How one blob of a pushed asset resolved — FFI mirror of [`PushedBlob`].
646#[derive(uniffi::Record)]
647pub struct FfiPushedBlob {
648 /// The ladder tier the blob occupies (`index` / `preview` / `original`), the vocabulary
649 /// [`FfiUploadBlob::tier`] uses.
650 pub tier: String,
651 /// The blob's content address (lowercase hex).
652 pub hash: String,
653 /// Whether it transferred or merged onto a blob the server already held.
654 pub outcome: FfiUploadOutcome,
655}
656
657impl From<PushedBlob> for FfiPushedBlob {
658 fn from(blob: PushedBlob) -> Self {
659 Self {
660 tier: workspace::tier_name(blob.tier),
661 hash: blob.hash,
662 outcome: match blob.outcome {
663 TierSessionOutcome::Uploaded { session_id } => {
664 FfiUploadOutcome::Completed { session_id }
665 }
666 TierSessionOutcome::AlreadyStored { asset_ref } => {
667 FfiUploadOutcome::AlreadyStored { asset_ref }
668 }
669 },
670 }
671 }
672}
673
674/// What [`FfiSession::push_asset`] did — FFI mirror of [`AssetPushReport`].
675#[derive(uniffi::Record)]
676pub struct FfiPushReport {
677 /// The asset id (UUID string).
678 pub asset_id: String,
679 /// Every blob whose session was opened, in ladder order.
680 pub pushed: Vec<FfiPushedBlob>,
681 /// Total bytes handed to the upload client, the original included.
682 pub bytes: u64,
683 /// Blobs the reported path held back ([`FfiSession::set_path`]): push the asset again once
684 /// the path allows them. Zero when the whole ladder ran.
685 pub deferred: u32,
686}
687
688impl From<AssetPushReport> for FfiPushReport {
689 fn from(report: AssetPushReport) -> Self {
690 Self {
691 asset_id: report.asset_id,
692 pushed: report.pushed.into_iter().map(FfiPushedBlob::from).collect(),
693 bytes: report.bytes,
694 deferred: u32::try_from(report.deferred).unwrap_or(u32::MAX),
695 }
696 }
697}
698
699/// How one asset of an [`FfiSession::push_assets`] call ended.
700#[derive(uniffi::Enum)]
701pub enum FfiPushAssetResult {
702 /// The asset's admitted ladder ran: what [`FfiSession::push_asset`] would have returned.
703 Pushed {
704 /// What the push did, the asset id included.
705 report: FfiPushReport,
706 },
707 /// The asset did not push: the error [`FfiSession::push_asset`] would have failed with.
708 /// It stays local, and pushing it again is safe.
709 Failed {
710 /// The asset id, as the caller passed it.
711 asset_id: String,
712 /// Why the asset did not push.
713 error: FfiError,
714 },
715}
716
717// ─── Sync mirrors ────────────────────────────────────────────────────────────
718
719/// FFI mirror of [`ChangeKind`].
720#[derive(uniffi::Enum)]
721pub enum FfiChangeKind {
722 /// A new asset became visible in the album.
723 Created,
724 /// An existing asset advanced — new metadata, new bytes, or a restore.
725 Updated,
726 /// The asset was tombstoned.
727 Deleted,
728}
729
730impl From<ChangeKind> for FfiChangeKind {
731 fn from(kind: ChangeKind) -> Self {
732 match kind {
733 ChangeKind::Created => Self::Created,
734 ChangeKind::Updated => Self::Updated,
735 ChangeKind::Deleted => Self::Deleted,
736 }
737 }
738}
739
740/// FFI mirror of [`BlobRef`] — a blob's content address and role.
741#[derive(uniffi::Record)]
742pub struct FfiBlobRef {
743 /// Ciphertext content address (lowercase hex).
744 pub ciphertext_hash: String,
745 /// `original | metadata | derivative | provenance`.
746 pub role: String,
747 /// Ciphertext size in bytes.
748 pub size: u64,
749}
750
751impl From<BlobRef> for FfiBlobRef {
752 fn from(blob: BlobRef) -> Self {
753 Self {
754 ciphertext_hash: blob.ciphertext_hash,
755 role: blob.role,
756 size: blob.size,
757 }
758 }
759}
760
761/// FFI mirror of [`BlobManifest`] — an asset's blobs by role.
762#[derive(uniffi::Record)]
763pub struct FfiBlobManifest {
764 /// The original ciphertext blob, when this entry carries one.
765 pub original: Option<FfiBlobRef>,
766 /// Derivative / metadata / provenance blobs.
767 pub derivatives: Vec<FfiBlobRef>,
768}
769
770impl From<BlobManifest> for FfiBlobManifest {
771 fn from(manifest: BlobManifest) -> Self {
772 Self {
773 original: manifest.original.map(FfiBlobRef::from),
774 derivatives: manifest
775 .derivatives
776 .into_iter()
777 .map(FfiBlobRef::from)
778 .collect(),
779 }
780 }
781}
782
783/// FFI mirror of [`HistorySources`](crate::sync::HistorySources): the blobs adopting an asset
784/// from its fetched history needs beyond its records.
785#[derive(uniffi::Record)]
786pub struct FfiHistorySources {
787 /// The asset's live metadata blob's content address (lowercase hex), for
788 /// [`FfiSession::fetch_metadata_blob`]; its bytes are the [`FfiSyncHead::metadata_blob`]
789 /// [`FfiWorkspace::open_synced_history`] takes.
790 pub metadata_blob_hash: String,
791 /// The original the head commits to, role `original`, sized for
792 /// [`FfiSession::fetch_blob_to_path`]; that file is the `ciphertext_path`
793 /// [`FfiWorkspace::open_synced_history`] takes.
794 pub original: FfiBlobRef,
795}
796
797impl From<crate::sync::HistorySources> for FfiHistorySources {
798 fn from(sources: crate::sync::HistorySources) -> Self {
799 Self {
800 metadata_blob_hash: sources.metadata_blob_hash.to_hex(),
801 original: FfiBlobRef {
802 ciphertext_hash: sources.original_hash.to_hex(),
803 role: "original".to_owned(),
804 size: sources.original_size,
805 },
806 }
807 }
808}
809
810/// **Name what adopting an asset from its history fetches**: the live metadata blob and the
811/// original, read off the asset's latest record `manifest_cbor` (a feed entry's) and `history`,
812/// the records before it that [`FfiSession::fetch_provenance_history`] returned.
813///
814/// An album page — the one a writer member's device reads — serves a `delete` with no metadata
815/// blob and no blob, so a device that first sees the asset there has only its records. The live
816/// metadata blob is the newest record that binds one, and the delete commits to the original;
817/// the server serves both to the asset's readers until its retention window closes. Fetch them
818/// with [`FfiSession::fetch_metadata_blob`] and [`FfiSession::fetch_blob_to_path`], set the
819/// entry's `metadata_blob` to the first, and hand the second to
820/// [`FfiWorkspace::open_synced_history`]: the asset is held in this device's trash and its
821/// `trash-restore` can be signed. An entry that names its metadata blob (the owner's own feed)
822/// agrees with this answer.
823///
824/// Pure and offline. Nothing is trusted for being named: the adoption binds the metadata blob and
825/// the original to the records, and refuses what does not.
826///
827/// # Errors
828///
829/// [`FfiError::Sync`] when a record does not decode or none binds a metadata blob.
830#[uniffi::export]
831pub fn synced_history_sources(
832 manifest_cbor: Vec<u8>,
833 history: Vec<Vec<u8>>,
834) -> Result<FfiHistorySources, FfiError> {
835 Ok(crate::sync::history_sources(&manifest_cbor, &history)?.into())
836}
837
838/// **Whether a tombstone's retention window had closed** at `changed_at` (RFC 3339, a feed
839/// entry's own): `manifest_cbor` is a `delete` record and `changed_at` is at or after the
840/// `retention_until` signed into it.
841///
842/// A device that first sees an asset at an album page's tombstone reads this before it calls
843/// [`FfiSession::fetch_provenance_history`]: once the window has closed the server refuses the
844/// asset's records and bytes to its readers, so there is nothing left to adopt, and passing the
845/// entry loses nothing. A record that is not a `delete`, or a `delete` whose window is absent or
846/// unreadable, answers `false`.
847///
848/// Pure and offline.
849///
850/// # Errors
851///
852/// [`FfiError::InvalidArgument`] when `changed_at` is not an RFC 3339 instant;
853/// [`FfiError::Sync`] when `manifest_cbor` does not decode.
854#[uniffi::export]
855pub fn synced_retention_closed(
856 manifest_cbor: Vec<u8>,
857 changed_at: String,
858) -> Result<bool, FfiError> {
859 let at = changed_at
860 .parse::<jiff::Timestamp>()
861 .map_err(|error| FfiError::InvalidArgument {
862 detail: format!("changed_at {changed_at:?} is not an RFC 3339 instant: {error}"),
863 })?;
864 Ok(crate::sync::retention_closed(&manifest_cbor, at)?)
865}
866
867/// FFI mirror of [`FeedEntry`] — one decoded sync feed entry. Ids/manifest/metadata
868/// cross as opaque bytes.
869#[derive(uniffi::Record)]
870pub struct FfiFeedEntry {
871 /// The album this entry belongs to.
872 pub album_id: Vec<u8>,
873 /// Per-album, strictly-increasing anti-rewind high-water mark.
874 pub sync_seq: u64,
875 /// The album protocol pin (`YYYY-MM-DD`).
876 pub protocol_version: String,
877 /// What changed.
878 pub kind: FfiChangeKind,
879 /// The asset id.
880 pub asset_id: Vec<u8>,
881 /// The signed `AssetManifest` as opaque canonical CBOR.
882 pub manifest_cbor: Vec<u8>,
883 /// The encrypted metadata blob's content address, as UTF-8 bytes. On a delete in trash, the
884 /// asset's live metadata blob, which a restore needs; empty for a purged delete.
885 pub metadata_blob: Vec<u8>,
886 /// Content addresses of the asset's blobs by role. On a delete in trash, only its original;
887 /// none for a purged delete.
888 pub blobs: FfiBlobManifest,
889 /// Whether the original blob is finalized server-side.
890 pub original_held: bool,
891 /// When the change happened, RFC 3339, on the server's clock.
892 pub changed_at: String,
893}
894
895impl From<FeedEntry> for FfiFeedEntry {
896 fn from(entry: FeedEntry) -> Self {
897 Self {
898 album_id: entry.album_id,
899 sync_seq: entry.sync_seq,
900 protocol_version: entry.protocol_version,
901 kind: entry.kind.into(),
902 asset_id: entry.asset_id,
903 manifest_cbor: entry.manifest_cbor,
904 metadata_blob: entry.metadata_blob,
905 blobs: entry.blobs.into(),
906 original_held: entry.original_held,
907 changed_at: entry.changed_at,
908 }
909 }
910}
911
912/// FFI mirror of [`SyncPage`] — a decoded page plus the opaque cursor for the next
913/// pull (the client persists `next_cursor` and passes it back to advance).
914#[derive(uniffi::Record)]
915pub struct FfiSyncPage {
916 /// The changes in this page, in strictly-increasing per-album `sync_seq` order.
917 pub entries: Vec<FfiFeedEntry>,
918 /// The opaque cursor to pass to the next [`FfiSession::sync_pull`].
919 pub next_cursor: Vec<u8>,
920 /// Whether the server holds changes beyond this page.
921 pub has_more: bool,
922}
923
924impl From<SyncPage> for FfiSyncPage {
925 fn from(page: SyncPage) -> Self {
926 Self {
927 entries: page.entries.into_iter().map(FfiFeedEntry::from).collect(),
928 next_cursor: page.next_cursor.as_bytes().to_vec(),
929 has_more: page.has_more,
930 }
931 }
932}
933
934/// FFI mirror of [`EscrowStored`] — what [`FfiSession::escrow_put`] did.
935#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
936pub struct FfiEscrowStored {
937 /// When the server accepted the blob, RFC 3339, on the server's clock.
938 pub stored_at: String,
939 /// Whether this displaced an earlier escrow: `false` is a first enrollment (recovery set
940 /// up), `true` a replacement (the previous recovery secret has stopped working).
941 pub replaced: bool,
942}
943
944impl From<EscrowStored> for FfiEscrowStored {
945 fn from(stored: EscrowStored) -> Self {
946 Self {
947 stored_at: stored.stored_at.to_string(),
948 replaced: stored.replaced,
949 }
950 }
951}
952
953// ─── Client (entry point) ────────────────────────────────────────────────────
954
955/// The unauthenticated entry point over the SDK's auth + upload endpoints. Turns
956/// credentials into an [`FfiSession`] handle; the protocol pin and endpoints are
957/// captured once here and reused by every session this client mints.
958#[derive(uniffi::Object)]
959pub struct FfiCapsuleClient {
960 auth: AuthClient,
961 upload_base_url: String,
962 protocol_version: String,
963}
964
965#[uniffi::export]
966impl FfiCapsuleClient {
967 /// Build a client.
968 ///
969 /// - `auth_base_url` is the auth endpoint root (e.g. `https://api.example.com/auth`).
970 /// - `upload_base_url` is the upload endpoint root (`POST` target; chunk/HEAD hang
971 /// under `{upload_base_url}/{id}`).
972 /// - `protocol_version` is the pinned protocol date (`YYYY-MM-DD`).
973 /// - `cohort_hash` is the optional advisory device-cohort digest; `None`
974 /// sends nothing (the server behaves identically).
975 #[uniffi::constructor]
976 pub fn new(
977 auth_base_url: String,
978 upload_base_url: String,
979 protocol_version: String,
980 cohort_hash: Option<String>,
981 ) -> Result<Arc<Self>, FfiError> {
982 let mut auth = AuthClient::new(&auth_base_url)?;
983 if let Some(cohort) = cohort_hash {
984 auth = auth.with_cohort_hash(cohort);
985 }
986 Ok(Arc::new(Self {
987 auth,
988 upload_base_url: upload_base_url.trim_end_matches('/').to_string(),
989 protocol_version,
990 }))
991 }
992}
993
994/// What a password login answered with, across the FFI.
995///
996/// An enum rather than an optional session handle: "signed in" and "needs a code" are different
997/// states an app renders differently, and a `null` handle beside a `mfaToken` string would let a
998/// caller read one while acting on the other.
999#[derive(uniffi::Enum)]
1000pub enum FfiLoginOutcome {
1001 /// The account has no second factor, and this is its session.
1002 Session {
1003 /// The authenticated session handle.
1004 session: Arc<FfiSession>,
1005 },
1006 /// The password verified and a code is still needed.
1007 SecondFactorRequired {
1008 /// The challenge to hand to `verifySecondFactor`.
1009 mfa_token: String,
1010 /// The absolute Unix-seconds instant the challenge stops being honoured.
1011 expires_by: u64,
1012 },
1013}
1014
1015#[uniffi::export(async_runtime = "tokio")]
1016impl FfiCapsuleClient {
1017 /// Authenticate with email + password, returning an authenticated session handle.
1018 pub async fn login(
1019 &self,
1020 email: String,
1021 password: String,
1022 ) -> Result<FfiLoginOutcome, FfiError> {
1023 match self.auth.login(&email, &password).await? {
1024 LoginOutcome::Session(session) => Ok(FfiLoginOutcome::Session {
1025 session: self.session_handle(session),
1026 }),
1027 // The password verified and the sign-in is not finished. No session
1028 // handle is produced, because there is no session — an app that got one here would
1029 // hold a handle to a half-authentication.
1030 LoginOutcome::SecondFactorRequired {
1031 mfa_token,
1032 expires_by,
1033 } => Ok(FfiLoginOutcome::SecondFactorRequired {
1034 mfa_token: mfa_token.expose_secret().to_owned(),
1035 expires_by,
1036 }),
1037 }
1038 }
1039
1040 /// Complete a sign-in with the code an authenticator app is showing.
1041 ///
1042 /// `mfa_token` is what [`FfiLoginOutcome::SecondFactorRequired`] carried. It is good once
1043 /// and for five minutes.
1044 pub async fn verify_second_factor(
1045 &self,
1046 mfa_token: String,
1047 totp_code: String,
1048 ) -> Result<Arc<FfiSession>, FfiError> {
1049 let session = self
1050 .auth
1051 .verify_second_factor(&SecretString::from(mfa_token), &totp_code)
1052 .await?;
1053 Ok(self.session_handle(session))
1054 }
1055
1056 /// Create an account and return an authenticated session handle (the server
1057 /// issues tokens on registration).
1058 /// An address and a password, and nothing else: the server takes nothing else.
1059 /// A display name is a fact about a person, and the profile surface that would hold one is
1060 /// owed rather than assumed.
1061 pub async fn register(
1062 &self,
1063 email: String,
1064 password: String,
1065 ) -> Result<Arc<FfiSession>, FfiError> {
1066 let session = self.auth.register(&email, &password).await?;
1067 Ok(self.session_handle(session))
1068 }
1069}
1070
1071impl FfiCapsuleClient {
1072 fn session_handle(&self, session: Session) -> Arc<FfiSession> {
1073 Arc::new(FfiSession {
1074 session,
1075 upload_base_url: self.upload_base_url.clone(),
1076 protocol_version: self.protocol_version.clone(),
1077 events: TransferEvents::default_channel(),
1078 path: PathMonitor::new(PathSample::desktop(), LaneWindows::default()),
1079 pool: GenerationPool::sdk(),
1080 })
1081 }
1082}
1083
1084// ─── Session (authenticated handle) ──────────────────────────────────────────
1085
1086/// An authenticated session handle. Owns the SDK token store internally (auto
1087/// pre-flight refresh, single-flight, `401`-retry-once); **no token ever crosses
1088/// the FFI boundary**. Every flow rides this handle.
1089#[derive(uniffi::Object)]
1090pub struct FfiSession {
1091 session: Session,
1092 upload_base_url: String,
1093 protocol_version: String,
1094 /// Where every upload, push and fetch this session drives publishes its steps. Nothing is
1095 /// built while nobody is subscribed.
1096 events: TransferEvents,
1097 /// The path the app last reported and the link behaviour seen on it: every push and fetch
1098 /// plans from it. Until the app reports one, the desktop default — reachable, unmetered,
1099 /// foreground.
1100 path: PathMonitor,
1101 /// The HTTP client uploads ride, rebuilt on each new path generation so no pooled
1102 /// connection outlives its path.
1103 pool: GenerationPool,
1104}
1105
1106#[uniffi::export]
1107impl FfiSession {
1108 /// Report the path as the app's OS listeners see it now, and return its path generation.
1109 ///
1110 /// Call it whenever a listener fires. The generation advances only when reachability, the
1111 /// interface or the cost changes; it then drops this session's pooled connections, forgets
1112 /// the resets and stalls seen on the old path, and cancels — within one scheduling tick —
1113 /// any push work the new path forbids, which re-plans and resumes. Power, thermal and
1114 /// background-deadline changes re-plan without a new generation.
1115 pub fn set_path(&self, snapshot: FfiPathSnapshot) -> u64 {
1116 let update = self.path.observe(snapshot.into());
1117 update.plan().generation.0
1118 }
1119
1120 /// Subscribe to the step-by-step progress of every upload, push and fetch this session
1121 /// drives from now on, each event stamped with the milliseconds since this call on a
1122 /// monotonic clock.
1123 ///
1124 /// Progress is advisory: a transfer never waits on its observer, so a subscriber that
1125 /// falls behind reads [`FfiTransferFeedItem::Lagged`] with the count it missed. The
1126 /// subscription ends once this session is dropped.
1127 pub fn transfer_events(&self) -> Arc<FfiTransferSubscription> {
1128 FfiTransferSubscription::open(&self.events)
1129 }
1130}
1131
1132#[uniffi::export(async_runtime = "tokio")]
1133impl FfiSession {
1134 /// Whether the session currently holds tokens (`false` after logout).
1135 pub async fn is_authenticated(&self) -> bool {
1136 self.session.is_authenticated().await
1137 }
1138
1139 /// Upload a full ciphertext blob (`data`) under `request`, driving the adaptive,
1140 /// resumable protocol with the code-driven recovery matrix.
1141 ///
1142 /// `data` crosses the boundary whole, so this is for blobs an app already holds in memory.
1143 /// To push a sealed asset, original included, use [`push_asset`](Self::push_asset), which
1144 /// never holds the original whole.
1145 pub async fn upload(
1146 &self,
1147 request: FfiUploadRequest,
1148 data: Vec<u8>,
1149 ) -> Result<FfiUploadOutcome, FfiError> {
1150 let request: CreateUploadRequest = request.into();
1151 let outcome = self.upload_client().upload(&request, &data).await?;
1152 Ok(outcome.into())
1153 }
1154
1155 /// Query an upload session's progress (`HEAD /upload/{id}`). `None` means the
1156 /// session is gone (discarded/expired/never-existent).
1157 pub async fn upload_status(
1158 &self,
1159 session_id: String,
1160 ) -> Result<Option<FfiUploadStatus>, FfiError> {
1161 let info = self.upload_client().head(&session_id).await?;
1162 Ok(info.map(FfiUploadStatus::from))
1163 }
1164
1165 /// **Push** one sealed asset of `workspace` — every blob of its bundle, in ladder order
1166 /// (provenance and metadata, then derivative manifests and derivatives, then the
1167 /// original) — driving `capsule_sdk::push::push_bundle` inside the SDK.
1168 ///
1169 /// The original never crosses the boundary: its ciphertext is re-derived from the
1170 /// plaintext on disk one upload chunk window at a time, so memory is bounded by the
1171 /// transfer window whatever the original's size. The workspace lock is held only while the
1172 /// bundle is built, never across the network.
1173 ///
1174 /// Every blob the reported path admits is driven ([`set_path`](Self::set_path)); the tiers
1175 /// it holds back are counted in [`FfiPushReport::deferred`] and wait for the next push. A
1176 /// blob the server already holds answers `duplicate_blob` and comes back
1177 /// [`FfiUploadOutcome::AlreadyStored`], so pushing twice is safe. The album must already be
1178 /// provisioned on the server.
1179 ///
1180 /// **A create the server refused is re-sealed and retried once** (issue #822). When the
1181 /// album's epoch moved past the one the asset was sealed under, the server refuses its
1182 /// create for good; if this device holds a newer epoch, the asset is re-sealed at it
1183 /// (`Workspace::reseal_create`) and pushed again, once. A second refusal fails the push.
1184 /// When this device holds no newer epoch the push fails with [`FfiError::Upload`] carrying
1185 /// the server's code and a detail saying there is no newer epoch to re-seal at, and the
1186 /// asset stays local. That detail names no missing key: the refusal may have had nothing to
1187 /// do with the epoch (a revoked device, withdrawn write access), or another device rotated
1188 /// the album and its key has not reached this one yet.
1189 ///
1190 /// To push several assets, use [`push_assets`](Self::push_assets): one call here is one
1191 /// bundle on the server's lane, so the lane never holds more than one session open.
1192 pub async fn push_asset(
1193 &self,
1194 workspace: Arc<FfiWorkspace>,
1195 asset_id: String,
1196 ) -> Result<FfiPushReport, FfiError> {
1197 let report = self
1198 .push_batch(&workspace, std::slice::from_ref(&asset_id))
1199 .await
1200 .into_iter()
1201 .next()
1202 .expect("push_batch returns one result per asset id")?;
1203 Ok(report.into())
1204 }
1205
1206 /// **Push** several sealed assets of `workspace` in one call, returning one
1207 /// [`FfiPushAssetResult`] per id, in the order of `asset_ids`.
1208 ///
1209 /// Every asset is pushed exactly as [`push_asset`](Self::push_asset) pushes one — its
1210 /// original streamed in bounded windows, the tiers the reported path holds back counted in
1211 /// [`FfiPushReport::deferred`], and a create the server refused re-sealed and retried once —
1212 /// but the assets share one run of the server's lane: up to W of them have their sessions
1213 /// open at once, every range any of them sends reserves against one device-wide byte
1214 /// budget, and their retries spend from one lane budget. Calling `push_asset` concurrently
1215 /// instead gives each call its own budget, so the budgets add up rather than being shared.
1216 ///
1217 /// The ids are pushed in batches of a bounded size, so a list of any length holds only one
1218 /// batch's bundles in memory at a time. One asset's failure is its own
1219 /// ([`FfiPushAssetResult::Failed`], carrying the error `push_asset` would have returned for
1220 /// it): the others still push, and the call itself never fails. An id repeated in
1221 /// `asset_ids` pushes once, at its first occurrence; each later occurrence is
1222 /// [`FfiPushAssetResult::Failed`] with [`FfiError::InvalidArgument`].
1223 ///
1224 /// The adverse-link detector hears each batch's outcomes when that batch's run ends, so a
1225 /// link that degrades mid-batch re-plans the push from the next batch on.
1226 pub async fn push_assets(
1227 &self,
1228 workspace: Arc<FfiWorkspace>,
1229 asset_ids: Vec<String>,
1230 ) -> Vec<FfiPushAssetResult> {
1231 self.push_assets_in(&workspace, &asset_ids, PUSH_BATCH_BUNDLES)
1232 .await
1233 }
1234
1235 /// **Fetch** the blob at content address `hash` (`size` bytes, as the sync feed's
1236 /// [`FfiBlobRef`] declares) into the file at `path`, created or truncated.
1237 ///
1238 /// The blob streams to disk in bounded `Range` windows, so memory is bounded by one window
1239 /// whatever the blob's size, and its content address is checked as it lands. On any error
1240 /// the file is removed: a path this returns `Ok` for holds exactly the verified ciphertext.
1241 /// A session that cannot authorize the fetch is [`FfiError::Auth`], so the app signs in
1242 /// again; every other failure is [`FfiError::Fetch`].
1243 ///
1244 /// `blob_base_url` is the root the blob route hangs off (`{blob_base_url}/blob/{hash}`),
1245 /// the server's `/v1` root.
1246 pub async fn fetch_blob_to_path(
1247 &self,
1248 blob_base_url: String,
1249 hash: String,
1250 size: u64,
1251 path: String,
1252 ) -> Result<(), FfiError> {
1253 check_content_address(&hash)?;
1254 let path = PathBuf::from(path);
1255 tracing::info!(%hash, size, path = %path.display(), "ffi: fetching a blob to disk");
1256 let source = HttpBlobSource::new(self.path_session(), blob_base_url);
1257 // A fetch is a request the user is waiting on: the path sizes its range windows (bounded
1258 // under `adverse`) but never holds it back.
1259 let class = self.path.plan().class;
1260 let result = fetch_to_file(&source, &hash, size, &path, class, &self.events).await;
1261 if let Err(error) = &result {
1262 tracing::warn!(%hash, %error, "ffi: blob fetch failed; removing the partial file");
1263 // Best effort: the file may never have been created.
1264 let _ = std::fs::remove_file(&path);
1265 }
1266 result
1267 }
1268
1269 /// **Fetch the metadata blob** at content address `hash`, which a sync feed entry names by
1270 /// address only (its `metadata_blob`): the feed lists no size for it, so it is read in
1271 /// bounded `Range` windows until the server's answer ends, and returned whole once it hashes
1272 /// to `hash`. This is the bytes [`FfiSyncHead::metadata_blob`] carries into
1273 /// [`FfiWorkspace::open_synced_original`] or [`FfiWorkspace::open_synced_history`].
1274 ///
1275 /// A sealed sidecar is a few KiB; a blob that grows past [`MAX_METADATA_BLOB_BYTES`] is
1276 /// refused rather than buffered without bound. On a `delete` in trash the server serves the
1277 /// asset's live metadata blob to its readers until the retention window closes, so an asset
1278 /// first seen at its delete can be adopted and restored; where the entry names no metadata
1279 /// blob (an album page's tombstone), [`synced_history_sources`] names its address.
1280 ///
1281 /// `blob_base_url` is as for [`fetch_blob_to_path`](Self::fetch_blob_to_path). A `hash` that
1282 /// is not a lowercase hex SHA-256 is [`FfiError::InvalidArgument`] and reaches no network; a
1283 /// session that cannot authorize the fetch is [`FfiError::Auth`]; a blob the server refuses,
1284 /// that does not hash to its address, or that runs past the bound is [`FfiError::Fetch`].
1285 pub async fn fetch_metadata_blob(
1286 &self,
1287 blob_base_url: String,
1288 hash: String,
1289 ) -> Result<Vec<u8>, FfiError> {
1290 check_content_address(&hash)?;
1291 tracing::info!(%hash, "ffi: fetching a metadata blob of unlisted size");
1292 let source = HttpBlobSource::new(self.path_session(), blob_base_url);
1293 let fetcher = RangedFetcher::new(self.path.plan().class).with_events(self.events.clone());
1294 let fetched = fetcher
1295 .fetch_unsized(&source, &hash, MAX_METADATA_BLOB_BYTES)
1296 .await;
1297 match &fetched {
1298 Ok(bytes) => tracing::debug!(%hash, bytes = bytes.len(), "ffi: metadata blob fetched"),
1299 Err(error) => tracing::warn!(%hash, %error, "ffi: metadata blob fetch failed"),
1300 }
1301 Ok(fetched?)
1302 }
1303
1304 /// **Fetch the earlier provenance records** of the asset whose latest record is
1305 /// `manifest_cbor` (a feed entry's): each record the one after it names by
1306 /// `prior_provenance_hash`, back to the asset's `create`, from the blob route the server
1307 /// serves an asset's superseded records on. Returned oldest first, each the exact bytes the
1308 /// server holds, checked against its content address; empty for a `create`.
1309 ///
1310 /// For an asset this workspace does not hold, first seen past its create — an entry
1311 /// [`FfiWorkspace::apply_sync_entry_from_file`] quarantines as `Rejected.ForgedChain` when
1312 /// the app's catalog holds no head for it, or applies without adopting
1313 /// ([`FfiAssetFacts::adopted`] `false`) when it does — hand the records to
1314 /// [`FfiWorkspace::open_synced_history`], which verifies them in order and holds the asset
1315 /// from its create. Nothing is verified here: the walk only follows links.
1316 ///
1317 /// An asset first seen at its `delete` is fetched the same way while it is in trash: the
1318 /// server serves a trashed asset's records, and its live metadata blob and original, to
1319 /// its readers until the retention window closes, so the adopted asset can be restored. An
1320 /// album page's tombstone names neither blob; [`synced_history_sources`] names both from
1321 /// these records.
1322 ///
1323 /// `blob_base_url` is as for [`fetch_blob_to_path`](Self::fetch_blob_to_path). A record the
1324 /// server refuses (a deleted asset's past its retention window, a purged asset's, or one the
1325 /// caller may not read) or that does not hash
1326 /// to its address is [`FfiError::Fetch`]; a session that cannot authorize the fetch is
1327 /// [`FfiError::Auth`]; a record that does not decode, or a chain longer than
1328 /// [`MAX_HISTORY_RECORDS`](crate::sync::MAX_HISTORY_RECORDS), is [`FfiError::Sync`].
1329 pub async fn fetch_provenance_history(
1330 &self,
1331 blob_base_url: String,
1332 manifest_cbor: Vec<u8>,
1333 ) -> Result<Vec<Vec<u8>>, FfiError> {
1334 let source = HttpBlobSource::new(self.path_session(), blob_base_url);
1335 let fetcher = RangedFetcher::new(self.path.plan().class).with_events(self.events.clone());
1336 crate::sync::fetch_history(&fetcher, &source, &manifest_cbor)
1337 .await
1338 .map_err(FfiError::from)
1339 }
1340
1341 /// Pull one page of the key-free sync feed after `cursor` from `api_base_url`
1342 /// (`http[s]://host:port`). Pass an empty `cursor` for the first page; persist and pass
1343 /// back `next_cursor` to advance. The bearer rides the `Authorization` header
1344 /// (auto-refreshed); it never crosses the FFI boundary.
1345 ///
1346 /// The parameter is the **API base URL** now, not a gRPC endpoint: the feed is
1347 /// `GET /v1/sync` on the same origin as every other call.
1348 pub async fn sync_pull(
1349 &self,
1350 api_base_url: String,
1351 cursor: Vec<u8>,
1352 page_size: u32,
1353 ) -> Result<FfiSyncPage, FfiError> {
1354 let consumer = SyncConsumer::with_session(&api_base_url, self.session.clone())?;
1355 let cursor = SyncCursor::from_bytes(cursor);
1356 let page = consumer.pull(&cursor, page_size).await?;
1357 Ok(page.into())
1358 }
1359
1360 /// Store or replace this account's **master-key escrow blob** (`PUT /v1/auth/escrow`).
1361 /// `blob` is the opaque canonical CBOR
1362 /// [`FfiWorkspace::escrow_blob`](FfiWorkspace::escrow_blob) minted — the master key itself
1363 /// never crosses this boundary in either direction.
1364 ///
1365 /// Single active escrow: the server replaces any prior blob in the same transaction, so the
1366 /// secret a rotation retired unwraps nothing.
1367 ///
1368 /// `api_base_url` is the API root the session authenticates against (the per-call endpoint
1369 /// convention this surface already uses for `sync_pull`). A URL operation paths cannot hang
1370 /// off is [`FfiError::InvalidArgument`]; a refused credential is [`FfiError::Auth`], so a
1371 /// caller re-authenticates rather than retrying; everything else is
1372 /// [`FfiError::Escrow`] with the server's `error.escrow.*` code when it sent one.
1373 ///
1374 /// The answer says what the store did: [`FfiEscrowStored::replaced`] separates "recovery
1375 /// set up" from "recovery key replaced" (the previous secret has stopped working).
1376 pub async fn escrow_put(
1377 &self,
1378 api_base_url: String,
1379 blob: Vec<u8>,
1380 ) -> Result<FfiEscrowStored, FfiError> {
1381 let blob =
1382 capsule_core::cbor::from_slice(&blob).map_err(|e| FfiError::InvalidArgument {
1383 detail: format!("escrow blob is not a canonical WrappedSecret: {e}"),
1384 })?;
1385 let stored = RecoveryClient::new(self.session.clone(), &api_base_url)?
1386 .store_escrow(&blob)
1387 .await?;
1388 Ok(stored.into())
1389 }
1390
1391 /// Fetch this account's escrow blob (`GET /v1/auth/escrow`) as opaque canonical CBOR — the
1392 /// bytes [`FfiWorkspace::verify_escrow_blob`](FfiWorkspace::verify_escrow_blob) checks and
1393 /// a recovery flow unwraps.
1394 ///
1395 /// No escrow enrolled yet is [`FfiError::Escrow`] carrying `error.escrow.not_stored` — the
1396 /// code that separates "set up a recovery key" from "we could not read the one you have".
1397 /// A refused credential is [`FfiError::Auth`].
1398 pub async fn escrow_get(&self, api_base_url: String) -> Result<Vec<u8>, FfiError> {
1399 let cache = RecoveryClient::new(self.session.clone(), &api_base_url)?
1400 .fetch_escrow()
1401 .await?;
1402 capsule_core::cbor::to_canonical_vec(cache.blob()).map_err(|e| FfiError::Escrow {
1403 // A local encode failure is ours, not the server's: no catalog code applies.
1404 code: None,
1405 detail: format!("encoding the fetched escrow blob failed: {e}"),
1406 })
1407 }
1408
1409 /// Publish this device's **signed device directory**, returning the `directory_version` the
1410 /// server now stores. `directory_cbor` is the opaque document
1411 /// [`FfiWorkspace::signed_device_directory`](FfiWorkspace::signed_device_directory)
1412 /// produced; it travels verbatim, because re-encoding it would detach it from the signature
1413 /// it carries. `user_ik` is the account's user identity **public** key the document is
1414 /// signed under — the bytes [`FfiWorkspace::user_ik_public`](FfiWorkspace::user_ik_public)
1415 /// returns — which the server anchors on first publish and verifies every publish against.
1416 ///
1417 /// Publish when the document changes (a device enrolled or revoked). The version must
1418 /// advance — republishing an unchanged document answers the version-conflict code.
1419 pub async fn publish_device_directory(
1420 &self,
1421 api_base_url: String,
1422 directory_cbor: Vec<u8>,
1423 user_ik: Vec<u8>,
1424 ) -> Result<u64, FfiError> {
1425 let directory = capsule_core::cbor::from_slice(&directory_cbor).map_err(|e| {
1426 FfiError::InvalidArgument {
1427 detail: format!("not a canonical DeviceDirectory: {e}"),
1428 }
1429 })?;
1430 let identity_key = capsule_core::crypto::keys::HybridVerifyingKey::from_bytes(&user_ik)
1431 .map_err(|e| FfiError::InvalidArgument {
1432 detail: format!("user_ik is not a hybrid verifying key: {e}"),
1433 })?;
1434 let version = DirectoryClient::new(self.session.clone(), &api_base_url)
1435 .publish(&directory, &identity_key)
1436 .await?;
1437 Ok(version)
1438 }
1439
1440 /// Fetch a user's signed device directory, **verified under `pinned_user_ik`** (the bytes
1441 /// [`FfiWorkspace::user_ik_public`](FfiWorkspace::user_ik_public) returns) before it is
1442 /// handed back. A document that does not verify is an error, never a return value.
1443 pub async fn fetch_device_directory(
1444 &self,
1445 api_base_url: String,
1446 user_id: String,
1447 pinned_user_ik: Vec<u8>,
1448 ) -> Result<Vec<u8>, FfiError> {
1449 let user_id = uuid::Uuid::parse_str(&user_id).map_err(|e| FfiError::InvalidArgument {
1450 detail: format!("user_id: {user_id:?} is not a UUID ({e})"),
1451 })?;
1452 let pinned = capsule_core::crypto::keys::HybridVerifyingKey::from_bytes(&pinned_user_ik)
1453 .map_err(|e| FfiError::InvalidArgument {
1454 detail: format!("pinned_user_ik is not a hybrid verifying key: {e}"),
1455 })?;
1456 let directory = DirectoryClient::new(self.session.clone(), &api_base_url)
1457 .fetch(user_id, &pinned)
1458 .await?;
1459 capsule_core::cbor::to_canonical_vec(&directory).map_err(|e| FfiError::Directory {
1460 code: None,
1461 detail: format!("re-encoding the verified directory failed: {e}"),
1462 })
1463 }
1464
1465 /// Revoke the session server-side and clear the local store (idempotent).
1466 pub async fn logout(&self) -> Result<(), FfiError> {
1467 self.session.logout().await?;
1468 Ok(())
1469 }
1470}
1471
1472impl FfiSession {
1473 /// The session, sending through the current path generation's pooled connections.
1474 fn path_session(&self) -> Session {
1475 let generation = self.path.snapshot().generation;
1476 // Requests routed through the HTTP/3 transport start on the same network.
1477 #[cfg(feature = "http3")]
1478 crate::net::h3::route::observe_generation(generation);
1479 match self.pool.client(generation) {
1480 Ok(http) => self.session.with_http_client(http),
1481 Err(error) => {
1482 // Building a client fails only where the platform lacks something the builder
1483 // needs; the session's own client still sends, on the pool it already has.
1484 tracing::warn!(%error, generation = generation.0, "ffi: no client for the new path; sending on the session's own");
1485 self.session.clone()
1486 }
1487 }
1488 }
1489
1490 /// An upload client on the current path's pooled connections, sizing its chunks to the
1491 /// current plan's class: under `adverse` each chunk request targets the shorter duration.
1492 fn upload_client(&self) -> UploadClient {
1493 let transport = UploadTransport::with_session(
1494 self.path_session(),
1495 self.upload_base_url.clone(),
1496 self.protocol_version.clone(),
1497 );
1498 UploadClient::new(transport)
1499 .with_events(self.events.clone())
1500 .with_connection_class(self.path.plan().class)
1501 }
1502
1503 /// [`push_assets`](Self::push_assets) in batches of at most `batch_size` distinct ids, so
1504 /// tests reach more than one batch without sealing [`PUSH_BATCH_BUNDLES`] assets.
1505 async fn push_assets_in(
1506 &self,
1507 workspace: &FfiWorkspace,
1508 asset_ids: &[String],
1509 batch_size: usize,
1510 ) -> Vec<FfiPushAssetResult> {
1511 tracing::info!(
1512 assets = asset_ids.len(),
1513 batch = batch_size,
1514 "ffi: pushing several sealed assets through one lane"
1515 );
1516 // A repeated id is refused in its own slot: pushing it twice would open two sessions
1517 // for one asset in one lane. Its first occurrence pushes as usual.
1518 let mut seen = HashSet::with_capacity(asset_ids.len());
1519 let mut slots: Vec<Option<FfiPushAssetResult>> = Vec::with_capacity(asset_ids.len());
1520 let mut distinct = Vec::with_capacity(asset_ids.len());
1521 for (at, asset_id) in asset_ids.iter().enumerate() {
1522 if seen.insert(asset_id.as_str()) {
1523 distinct.push(at);
1524 slots.push(None);
1525 } else {
1526 tracing::warn!(%asset_id, "ffi: the asset id is repeated; refusing the repeat");
1527 slots.push(Some(FfiPushAssetResult::Failed {
1528 asset_id: asset_id.clone(),
1529 error: FfiError::InvalidArgument {
1530 detail: format!(
1531 "asset_ids: {asset_id:?} is repeated; it is pushed once, at its first occurrence"
1532 ),
1533 },
1534 }));
1535 }
1536 }
1537 for batch in distinct.chunks(batch_size.max(1)) {
1538 let ids: Vec<String> = batch.iter().map(|&at| asset_ids[at].clone()).collect();
1539 let pushed = self.push_batch(workspace, &ids).await;
1540 for ((&at, asset_id), pushed) in batch.iter().zip(ids).zip(pushed) {
1541 slots[at] = Some(match pushed {
1542 Ok(report) => FfiPushAssetResult::Pushed {
1543 report: report.into(),
1544 },
1545 Err(error) => FfiPushAssetResult::Failed { asset_id, error },
1546 });
1547 }
1548 }
1549 let results: Vec<FfiPushAssetResult> = slots
1550 .into_iter()
1551 .map(|slot| slot.expect("every requested id ended exactly once"))
1552 .collect();
1553 let failed = results
1554 .iter()
1555 .filter(|result| matches!(result, FfiPushAssetResult::Failed { .. }))
1556 .count();
1557 tracing::info!(
1558 assets = results.len(),
1559 failed,
1560 "ffi: pushed several sealed assets"
1561 );
1562 results
1563 }
1564
1565 /// Push the assets `asset_ids` names — at most one batch — and return how each ended, in
1566 /// the order of `asset_ids`. The workspace lock is held only while a bundle is built or
1567 /// re-sealed, or its upload guard released, never across the network.
1568 ///
1569 /// A bundle whose push ends with every blob `Completed` or already held, and no tier
1570 /// deferred, has its original's upload source guard released.
1571 ///
1572 /// Every bundle that builds goes through one [`push_bundles`](Self::push_bundles) run. A
1573 /// create the server refused for good is re-sealed at the album's current epoch (issue
1574 /// #822), and every re-sealed bundle goes through one more run, once: a second refusal
1575 /// fails its asset.
1576 async fn push_batch(
1577 &self,
1578 workspace: &FfiWorkspace,
1579 asset_ids: &[String],
1580 ) -> Vec<Result<AssetPushReport, FfiError>> {
1581 let mut outcomes: Vec<Option<Result<AssetPushReport, FfiError>>> =
1582 Vec::with_capacity(asset_ids.len());
1583 let mut bundles = Vec::with_capacity(asset_ids.len());
1584 let mut bundled_at = Vec::with_capacity(asset_ids.len());
1585 for (at, asset_id) in asset_ids.iter().enumerate() {
1586 match workspace.bundle(asset_id) {
1587 Ok(bundle) => {
1588 bundles.push(bundle);
1589 bundled_at.push(at);
1590 outcomes.push(None);
1591 }
1592 Err(error) => {
1593 tracing::warn!(%asset_id, %error, "ffi: the asset's bundle could not be built");
1594 outcomes.push(Some(Err(error)));
1595 }
1596 }
1597 }
1598
1599 let pushed = self.push_bundles(&bundles).await;
1600 let mut resealed = Vec::new();
1601 let mut resealed_at = Vec::new();
1602 // The first run's bundles are consumed one by one, each dropped before its re-sealed
1603 // replacement is built, so the batch never holds both at once.
1604 for ((bundle, at), pushed) in bundles.into_iter().zip(bundled_at).zip(pushed) {
1605 let refused = match pushed {
1606 Err(PushError::CreateRefused { source, .. }) => source,
1607 other => {
1608 release_if_complete(workspace, &bundle, &other);
1609 outcomes[at] = Some(other.map_err(FfiError::from));
1610 continue;
1611 }
1612 };
1613 tracing::warn!(
1614 asset_id = %bundle.asset_id,
1615 amk_version = bundle.amk_version,
1616 "ffi: the server refused this create; re-sealing it at the album's current epoch"
1617 );
1618 let asset_id = bundle.asset_id;
1619 drop(bundle);
1620 match workspace
1621 .reseal(&asset_id, &refused)
1622 .and_then(|()| workspace.bundle(&asset_ids[at]))
1623 {
1624 Ok(bundle) => {
1625 resealed.push(bundle);
1626 resealed_at.push(at);
1627 }
1628 Err(error) => outcomes[at] = Some(Err(error)),
1629 }
1630 }
1631 if !resealed.is_empty() {
1632 tracing::info!(
1633 resealed = resealed.len(),
1634 "ffi: pushing the re-sealed creates again, once"
1635 );
1636 let retried = self.push_bundles(&resealed).await;
1637 for ((bundle, at), pushed) in resealed.iter().zip(resealed_at).zip(retried) {
1638 release_if_complete(workspace, bundle, &pushed);
1639 outcomes[at] = Some(pushed.map_err(FfiError::from));
1640 }
1641 }
1642 outcomes
1643 .into_iter()
1644 .map(|outcome| outcome.expect("every asset of the batch ended exactly once"))
1645 .collect()
1646 }
1647
1648 /// Drive `bundles` through one run of this server's lane, returning each bundle's result
1649 /// in their order. The workspace lock is not held: the bundles are owned.
1650 ///
1651 /// The bundles are the jobs of this server's lane in [`push_lanes`], so up to W of them
1652 /// have sessions open at once, their ranges reserve against the one push byte budget, the
1653 /// server's advice narrows the lane's windows, and their retries spend from the lane's
1654 /// budget. The run happens under the reported path ([`run_under_path`]): a path change that
1655 /// closes a running tier cancels and re-plans it. Each outcome observed on the path the run
1656 /// started on feeds the adverse detector.
1657 async fn push_bundles(
1658 &self,
1659 bundles: &[UploadBundle],
1660 ) -> Vec<Result<AssetPushReport, PushError>> {
1661 if bundles.is_empty() {
1662 return Vec::new();
1663 }
1664 for bundle in bundles {
1665 tracing::info!(
1666 asset_id = %bundle.asset_id,
1667 amk_version = bundle.amk_version,
1668 original_bytes = bundle.original.size(),
1669 "ffi: pushing a sealed asset"
1670 );
1671 }
1672 // Full ordering where the path allows it; the plan stages the push where it holds bulk
1673 // back, and a path change that closes a running tier cancels and re-plans the push.
1674 let held = HashSet::<String>::new();
1675 let started_on = self.path.snapshot().generation;
1676 let pushed = run_under_path(&self.path, UploadPolicy::Full, false, |scheduler| {
1677 let client = self.upload_client();
1678 let held = &held;
1679 async move {
1680 let lanes = [LanePush {
1681 server: ServerKey::new(self.upload_base_url.clone()),
1682 client: &client,
1683 bundles: bundles
1684 .iter()
1685 .map(|bundle| LaneBundle { bundle, held })
1686 .collect(),
1687 // The server publishes no live-session cap; its advice narrows W instead.
1688 session_cap: None,
1689 }];
1690 push_lanes(
1691 &scheduler,
1692 &lanes,
1693 false,
1694 PUSH_BYTE_BUDGET,
1695 LaneWindows::default(),
1696 )
1697 .await
1698 .into_iter()
1699 .flatten()
1700 .collect::<Vec<_>>()
1701 }
1702 })
1703 .await;
1704 debug_assert_eq!(
1705 pushed.len(),
1706 bundles.len(),
1707 "push_lanes returns one result per queued bundle"
1708 );
1709 // Only outcomes on the path the push started on: if the path changed under it, the
1710 // detector was reset for a link these outcomes never measured.
1711 for result in &pushed {
1712 if let Some(signal) = path::link_signal(result)
1713 && let Some(plan) = self.path.record_on(started_on, signal)
1714 {
1715 tracing::debug!(?signal, class = ?plan.class, "ffi: the push's outcome fed the adverse detector");
1716 }
1717 }
1718 pushed
1719 }
1720}
1721
1722/// Release `bundle`'s upload source guard once `pushed` shows every blob of it `Completed` or
1723/// already held. A deferred tier keeps it, since the original is still to be sent under its
1724/// nonces, and so does a failed push, which a retry resumes under the same ones.
1725fn release_if_complete(
1726 workspace: &FfiWorkspace,
1727 bundle: &UploadBundle,
1728 pushed: &Result<AssetPushReport, PushError>,
1729) {
1730 if let Ok(report) = pushed
1731 && report.deferred == 0
1732 {
1733 workspace.release_upload_guard(&bundle.asset_id);
1734 }
1735}
1736
1737/// The most [`FfiSession::fetch_metadata_blob`] reads of a metadata blob whose size the feed
1738/// does not list (16 MiB, the upload protocol's largest chunk), the bound the CLI's restore
1739/// reads one under. A sealed sidecar is a few KiB; the cap only stops a server that keeps
1740/// answering full windows from growing the buffer without bound.
1741pub const MAX_METADATA_BLOB_BYTES: u64 = crate::upload::PROTOCOL_MAX_CHUNK;
1742
1743/// Refuse a `hash` that is not a lowercase hex SHA-256 before it reaches a blob route.
1744fn check_content_address(hash: &str) -> Result<(), FfiError> {
1745 if hash.len() != 64 || !hash.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
1746 return Err(FfiError::InvalidArgument {
1747 detail: format!("hash: {hash:?} is not a lowercase hex SHA-256"),
1748 });
1749 }
1750 Ok(())
1751}
1752
1753/// Stream the blob at `hash` from `source` into a fresh file at `path`, synced to disk once
1754/// its content address has checked out. Leaves cleanup of a failed fetch to the caller.
1755async fn fetch_to_file<B: crate::fetch::BlobSource>(
1756 source: &B,
1757 hash: &str,
1758 size: u64,
1759 path: &Path,
1760 class: ConnectionClass,
1761 events: &TransferEvents,
1762) -> Result<(), FfiError> {
1763 let local = |action: &str, e: std::io::Error| FfiError::Fetch {
1764 code: None,
1765 detail: format!("{action} {}: {e}", path.display()),
1766 };
1767 let file = std::fs::File::create(path).map_err(|e| local("creating", e))?;
1768 let mut sink = std::io::BufWriter::new(file);
1769 RangedFetcher::new(class)
1770 .with_events(events.clone())
1771 .fetch_into(source, hash, size, &mut sink)
1772 .await?;
1773 sink.into_inner()
1774 .map_err(|e| local("flushing", e.into_error()))?
1775 .sync_all()
1776 .map_err(|e| local("syncing", e))
1777}
1778
1779#[cfg(test)]
1780mod tests;