Skip to main content

FfiSession

Struct FfiSession 

Source
pub struct FfiSession { /* private fields */ }
Expand description

An authenticated session handle. Owns the SDK token store internally (auto pre-flight refresh, single-flight, 401-retry-once); no token ever crosses the FFI boundary. Every flow rides this handle.

Implementations§

Source§

impl FfiSession

Source

pub async fn apply_lifecycle_op( &self, api_base_url: String, workspace: Arc<FfiWorkspace>, record: Vec<u8>, server_head: Option<Vec<u8>>, ) -> Result<FfiLifecycleOpOutcome, FfiError>

Apply one signed lifecycle op record — a delete or a trash-restore, as the opaque canonical CBOR FfiWorkspace::provenance_head, FfiPurgeOutcome::reissue_record and FfiWorkspace::purged_record carry — to its album’s ops surface on api_base_url (http[s]://host:port, the root sync_pull takes).

The record must be one workspace holds: its device signature verifies under the workspace’s device directory, and it is a record of the workspace’s chain for its asset (live, trashed, or kept by a purge). The server cannot verify signatures, so a record that is not this workspace’s own is refused here rather than becoming the asset’s chain head there.

server_head is the sync feed’s evidence for the asset: the manifest_cbor of the latest entry listing it (empty for an entry that carries none), or None when the feed does not list it. With None nothing is sent and the answer is FfiLifecycleOpOutcome::NotIndexed: the server never sees a lifecycle op for an asset it has not indexed.

Idempotent: a record the server already applied answers Applied with replayed set. A refusal, or a server that could not be reached, is FfiLifecycleOpOutcome::Failed; a session the server did not accept is FfiError::Auth.

§Errors

FfiError::InvalidArgument for bytes that are not a lifecycle op record (over the bound, not canonical, not a delete or trash-restore, not signed by a device of the workspace’s directory, or not on the workspace’s chain for its asset) or an api_base_url that is not an http(s) URL, before anything is sent; FfiError::Auth for a refused session.

Source

pub async fn deliver_purge( &self, api_base_url: String, workspace: Arc<FfiWorkspace>, asset_id: String, server_head: Option<Vec<u8>>, ) -> Result<FfiLifecycleOpOutcome, FfiError>

Deliver a purged asset’s delete to its album’s ops surface: every record of the chain the purge kept after the head the server holds, in chain order, each once the one before it was applied. After an early purge that is the shorter-retention re-issue (FfiPurgeOutcome::reissue_record) together with any delete it chains onto that the server never saw.

Everything is read from the workspace’s kept chain, so a delivery that failed or was held is retried by calling this again, also after the workspace was reopened (FfiWorkspace::purged_asset_ids lists what to walk). The workspace lock is held only while the chain is read, never across the network. Every record of the stretch is judged as apply_lifecycle_op judges a foreign one before any is sent, so a kept chain whose records no longer verify sends nothing.

server_head is as apply_lifecycle_op takes it: None sends nothing and answers FfiLifecycleOpOutcome::NotIndexed. The answer is the last record’s Applied — the purge reached the server — or the first record that was not applied, whose Failed stops the stretch.

The held rules are a live asset’s (deliver_lifecycle_at_hash), judged by this device’s clock: a kept chain whose stretch holds a trash-restore undoing a delete the server never saw, whose window has closed, is withheld and answers FfiLifecycleOpOutcome::RestoreTooLate.

§Errors

FfiError::Trash with FfiTrashRefusal::NotFound for an asset this workspace has not purged; FfiError::InvalidArgument for a malformed asset_id or api_base_url; FfiError::Workspace for a kept chain whose records do not verify under the workspace’s device directory; FfiError::Auth for a refused session.

Source

pub async fn deliver_purge_at_hash( &self, api_base_url: String, workspace: Arc<FfiWorkspace>, asset_id: String, server_head_hash: Option<Vec<u8>>, ) -> Result<FfiLifecycleOpOutcome, FfiError>

deliver_purge with the head the feed lists given by its record hash rather than its bytes: the SHA-256 of the latest entry’s manifest_cbor, which is the head record’s hash, so a caller keeps 32 bytes per listed asset instead of the record. Some of an empty vector is an entry that carries no record, and None an asset the feed does not list, exactly as deliver_purge reads its server_head.

§Errors

As deliver_purge, and FfiError::InvalidArgument for a server_head_hash that is neither empty nor 32 bytes, before anything is sent.

Source

pub async fn deliver_lifecycle_at_hash( &self, api_base_url: String, workspace: Arc<FfiWorkspace>, asset_id: String, server_head_hash: Option<Vec<u8>>, latest_changed_at: Option<String>, ) -> Result<FfiLifecycleOpOutcome, FfiError>

Deliver the held lifecycle records of an asset workspace still holds, live or in the trash: every record of its chain after the head the server holds, in chain order, each once the one before it was applied. That is a delete or trash-restore signed while the server had not indexed the asset, or whose send failed, together with any it chains onto that the server never saw. The rule is the CLI’s and a purge’s (plan_delivery).

server_head_hash is the feed’s evidence for the asset, as deliver_purge_at_hash takes it: None, an asset the feed does not list, sends nothing and answers FfiLifecycleOpOutcome::NotIndexed.

latest_changed_at is the latest changed_at (RFC 3339) the caller’s feed drain saw, on the server’s clock, or None when it saw none. It floors this device’s clock (judging_clock), and a stretch in which a trash-restore undoes a delete whose window had closed by that clock is withheld and answers FfiLifecycleOpOutcome::RestoreTooLate: sent, the server would apply the delete and refuse the restore.

Everything is read from the workspace’s chain, so a delivery that failed or was held is retried by calling this again, also after the workspace was reopened. The workspace lock is held only while the chain is read, never across the network, and every record of the stretch is judged as apply_lifecycle_op judges a foreign one before any is sent. A server level with the chain is sent its head alone, which it answers as a replay; a caller that compares the listed head with FfiWorkspace::provenance_head first sends nothing for it. The answer is the last record’s Applied, or the first record that was not applied, whose Failed stops the stretch.

§Errors

FfiError::Trash with FfiTrashRefusal::NotFound for an asset this workspace does not hold (a purged one goes through deliver_purge_at_hash); FfiError::InvalidArgument for a malformed asset_id or api_base_url, a server_head_hash that is neither empty nor 32 bytes, or a latest_changed_at that is not an RFC 3339 timestamp, before anything is sent; FfiError::Workspace for a chain whose records do not verify under the workspace’s device directory; FfiError::Auth for a refused session.

Source§

impl FfiSession

Source

pub fn set_path(&self, snapshot: FfiPathSnapshot) -> u64

Report the path as the app’s OS listeners see it now, and return its path generation.

Call it whenever a listener fires. The generation advances only when reachability, the interface or the cost changes; it then drops this session’s pooled connections, forgets the resets and stalls seen on the old path, and cancels — within one scheduling tick — any push work the new path forbids, which re-plans and resumes. Power, thermal and background-deadline changes re-plan without a new generation.

Source

pub fn transfer_events(&self) -> Arc<FfiTransferSubscription> ⓘ

Subscribe to the step-by-step progress of every upload, push and fetch this session drives from now on, each event stamped with the milliseconds since this call on a monotonic clock.

Progress is advisory: a transfer never waits on its observer, so a subscriber that falls behind reads FfiTransferFeedItem::Lagged with the count it missed. The subscription ends once this session is dropped.

Source§

impl FfiSession

Source

pub async fn is_authenticated(&self) -> bool

Whether the session currently holds tokens (false after logout).

Source

pub async fn upload( &self, request: FfiUploadRequest, data: Vec<u8>, ) -> Result<FfiUploadOutcome, FfiError>

Upload a full ciphertext blob (data) under request, driving the adaptive, resumable protocol with the code-driven recovery matrix.

data crosses the boundary whole, so this is for blobs an app already holds in memory. To push a sealed asset, original included, use push_asset, which never holds the original whole.

Source

pub async fn upload_status( &self, session_id: String, ) -> Result<Option<FfiUploadStatus>, FfiError>

Query an upload session’s progress (HEAD /upload/{id}). None means the session is gone (discarded/expired/never-existent).

Source

pub async fn push_asset( &self, workspace: Arc<FfiWorkspace>, asset_id: String, ) -> Result<FfiPushReport, FfiError>

Push one sealed asset of workspace — every blob of its bundle, in ladder order (provenance and metadata, then derivative manifests and derivatives, then the original) — driving capsule_sdk::push::push_bundle inside the SDK.

The original never crosses the boundary: its ciphertext is re-derived from the plaintext on disk one upload chunk window at a time, so memory is bounded by the transfer window whatever the original’s size. The workspace lock is held only while the bundle is built, never across the network.

Every blob the reported path admits is driven (set_path); the tiers it holds back are counted in FfiPushReport::deferred and wait for the next push. A blob the server already holds answers duplicate_blob and comes back FfiUploadOutcome::AlreadyStored, so pushing twice is safe. The album must already be provisioned on the server.

A create the server refused is re-sealed and retried once (issue #822). When the album’s epoch moved past the one the asset was sealed under, the server refuses its create for good; if this device holds a newer epoch, the asset is re-sealed at it (Workspace::reseal_create) and pushed again, once. A second refusal fails the push. When this device holds no newer epoch the push fails with FfiError::Upload carrying the server’s code and a detail saying there is no newer epoch to re-seal at, and the asset stays local. That detail names no missing key: the refusal may have had nothing to do with the epoch (a revoked device, withdrawn write access), or another device rotated the album and its key has not reached this one yet.

To push several assets, use push_assets: one call here is one bundle on the server’s lane, so the lane never holds more than one session open.

Source

pub async fn push_assets( &self, workspace: Arc<FfiWorkspace>, asset_ids: Vec<String>, ) -> Vec<FfiPushAssetResult>

Push several sealed assets of workspace in one call, returning one FfiPushAssetResult per id, in the order of asset_ids.

Every asset is pushed exactly as push_asset pushes one — its original streamed in bounded windows, the tiers the reported path holds back counted in FfiPushReport::deferred, and a create the server refused re-sealed and retried once — but the assets share one run of the server’s lane: up to W of them have their sessions open at once, every range any of them sends reserves against one device-wide byte budget, and their retries spend from one lane budget. Calling push_asset concurrently instead gives each call its own budget, so the budgets add up rather than being shared.

The ids are pushed in batches of a bounded size, so a list of any length holds only one batch’s bundles in memory at a time. One asset’s failure is its own (FfiPushAssetResult::Failed, carrying the error push_asset would have returned for it): the others still push, and the call itself never fails. An id repeated in asset_ids pushes once, at its first occurrence; each later occurrence is FfiPushAssetResult::Failed with FfiError::InvalidArgument.

The adverse-link detector hears each batch’s outcomes when that batch’s run ends, so a link that degrades mid-batch re-plans the push from the next batch on.

Source

pub async fn fetch_blob_to_path( &self, blob_base_url: String, hash: String, size: u64, path: String, ) -> Result<(), FfiError>

Fetch the blob at content address hash (size bytes, as the sync feed’s FfiBlobRef declares) into the file at path, created or truncated.

The blob streams to disk in bounded Range windows, so memory is bounded by one window whatever the blob’s size, and its content address is checked as it lands. On any error the file is removed: a path this returns Ok for holds exactly the verified ciphertext. A session that cannot authorize the fetch is FfiError::Auth, so the app signs in again; every other failure is FfiError::Fetch.

blob_base_url is the root the blob route hangs off ({blob_base_url}/blob/{hash}), the server’s /v1 root.

Source

pub async fn fetch_metadata_blob( &self, blob_base_url: String, hash: String, ) -> Result<Vec<u8>, FfiError>

Fetch the metadata blob at content address hash, which a sync feed entry names by address only (its metadata_blob): the feed lists no size for it, so it is read in bounded Range windows until the server’s answer ends, and returned whole once it hashes to hash. This is the bytes FfiSyncHead::metadata_blob carries into FfiWorkspace::open_synced_original or FfiWorkspace::open_synced_history.

A sealed sidecar is a few KiB; a blob that grows past MAX_METADATA_BLOB_BYTES is refused rather than buffered without bound. On a delete in trash the server serves the asset’s live metadata blob to its readers until the retention window closes, so an asset first seen at its delete can be adopted and restored; where the entry names no metadata blob (an album page’s tombstone), synced_history_sources names its address.

blob_base_url is as for fetch_blob_to_path. A hash that is not a lowercase hex SHA-256 is FfiError::InvalidArgument and reaches no network; a session that cannot authorize the fetch is FfiError::Auth; a blob the server refuses, that does not hash to its address, or that runs past the bound is FfiError::Fetch.

Source

pub async fn fetch_provenance_history( &self, blob_base_url: String, manifest_cbor: Vec<u8>, ) -> Result<Vec<Vec<u8>>, FfiError>

Fetch the earlier provenance records of the asset whose latest record is manifest_cbor (a feed entry’s): each record the one after it names by prior_provenance_hash, back to the asset’s create, from the blob route the server serves an asset’s superseded records on. Returned oldest first, each the exact bytes the server holds, checked against its content address; empty for a create.

For an asset this workspace does not hold, first seen past its create — an entry FfiWorkspace::apply_sync_entry_from_file quarantines as Rejected.ForgedChain when the app’s catalog holds no head for it, or applies without adopting (FfiAssetFacts::adopted false) when it does — hand the records to FfiWorkspace::open_synced_history, which verifies them in order and holds the asset from its create. Nothing is verified here: the walk only follows links.

An asset first seen at its delete is fetched the same way while it is in trash: the server serves a trashed asset’s records, and its live metadata blob and original, to its readers until the retention window closes, so the adopted asset can be restored. An album page’s tombstone names neither blob; synced_history_sources names both from these records.

blob_base_url is as for fetch_blob_to_path. A record the server refuses (a deleted asset’s past its retention window, a purged asset’s, or one the caller may not read) or that does not hash to its address is FfiError::Fetch; a session that cannot authorize the fetch is FfiError::Auth; a record that does not decode, or a chain longer than MAX_HISTORY_RECORDS, is FfiError::Sync.

Source

pub async fn sync_pull( &self, api_base_url: String, cursor: Vec<u8>, page_size: u32, ) -> Result<FfiSyncPage, FfiError>

Pull one page of the key-free sync feed after cursor from api_base_url (http[s]://host:port). Pass an empty cursor for the first page; persist and pass back next_cursor to advance. The bearer rides the Authorization header (auto-refreshed); it never crosses the FFI boundary.

The parameter is the API base URL now, not a gRPC endpoint: the feed is GET /v1/sync on the same origin as every other call.

Source

pub async fn escrow_put( &self, api_base_url: String, blob: Vec<u8>, ) -> Result<FfiEscrowStored, FfiError>

Store or replace this account’s master-key escrow blob (PUT /v1/auth/escrow). blob is the opaque canonical CBOR FfiWorkspace::escrow_blob minted — the master key itself never crosses this boundary in either direction.

Single active escrow: the server replaces any prior blob in the same transaction, so the secret a rotation retired unwraps nothing.

api_base_url is the API root the session authenticates against (the per-call endpoint convention this surface already uses for sync_pull). A URL operation paths cannot hang off is FfiError::InvalidArgument; a refused credential is FfiError::Auth, so a caller re-authenticates rather than retrying; everything else is FfiError::Escrow with the server’s error.escrow.* code when it sent one.

The answer says what the store did: FfiEscrowStored::replaced separates “recovery set up” from “recovery key replaced” (the previous secret has stopped working).

Source

pub async fn escrow_get( &self, api_base_url: String, ) -> Result<Vec<u8>, FfiError>

Fetch this account’s escrow blob (GET /v1/auth/escrow) as opaque canonical CBOR — the bytes FfiWorkspace::verify_escrow_blob checks and a recovery flow unwraps.

No escrow enrolled yet is FfiError::Escrow carrying error.escrow.not_stored — the code that separates “set up a recovery key” from “we could not read the one you have”. A refused credential is FfiError::Auth.

Source

pub async fn publish_device_directory( &self, api_base_url: String, directory_cbor: Vec<u8>, user_ik: Vec<u8>, ) -> Result<u64, FfiError>

Publish this device’s signed device directory, returning the directory_version the server now stores. directory_cbor is the opaque document FfiWorkspace::signed_device_directory produced; it travels verbatim, because re-encoding it would detach it from the signature it carries. user_ik is the account’s user identity public key the document is signed under — the bytes FfiWorkspace::user_ik_public returns — which the server anchors on first publish and verifies every publish against.

Publish when the document changes (a device enrolled or revoked). The version must advance — republishing an unchanged document answers the version-conflict code.

Source

pub async fn fetch_device_directory( &self, api_base_url: String, user_id: String, pinned_user_ik: Vec<u8>, ) -> Result<Vec<u8>, FfiError>

Fetch a user’s signed device directory, verified under pinned_user_ik (the bytes FfiWorkspace::user_ik_public returns) before it is handed back. A document that does not verify is an error, never a return value.

Source

pub async fn logout(&self) -> Result<(), FfiError>

Revoke the session server-side and clear the local store (idempotent).

Trait Implementations§

Source§

impl<UT> LiftRef<UT> for FfiSession

Source§

impl<UT> LowerError<UT> for FfiSession

Source§

fn lower_error(obj: Self) -> RustBuffer

Lower this value for scaffolding function return Read more
Source§

impl<UT> LowerReturn<UT> for FfiSession

Source§

type ReturnType = <Arc<FfiSession> as LowerReturn<UniFfiTag>>::ReturnType

The type that should be returned by scaffolding functions for this type. Read more
Source§

fn lower_return(obj: Self) -> Result<Self::ReturnType, RustCallError>

Lower the return value from an scaffolding call Read more
§

fn handle_failed_lift( error: LiftArgsError, ) -> Result<Self::ReturnType, RustCallError>

Lower the return value for failed argument lifts Read more
Source§

impl<UT> TypeId<UT> for FfiSession

Source§

const TYPE_ID_META: MetadataBuffer

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T>
where T: Sized,

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T>

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the [Compat] adapter by mutable reference. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, UT> HandleAlloc<UT> for T
where T: Send + Sync,

§

fn new_handle(value: Arc<T>) -> Handle

Create a new handle for an Arc value Read more
§

unsafe fn clone_handle(handle: Handle) -> Handle

Clone a handle Read more
§

unsafe fn consume_handle(handle: Handle) -> Arc<T> ⓘ

Consume a handle, getting back the initial Arc<> Read more
§

unsafe fn get_arc(handle: Handle) -> Arc<Self> ⓘ

Get a clone of the Arc<> using a “borrowed” handle. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> MaybeSend for T
where T: Send + ?Sized,

Source§

impl<T> MaybeSync for T
where T: Sync + ?Sized,

§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more