Skip to main content

capsule_sdk/sync/
reannounce.rs

1//! Re-announcing held manifests after a sync epoch change (#781).
2//!
3//! When the feed answers a cursor with `409 error.sync.cursor_stale`
4//! ([`SyncError::is_stale_cursor`](super::SyncError::is_stale_cursor)), the server rebuilt this
5//! library's index and may have lost rows. The client resyncs from zero, and then every asset it
6//! holds that the resynced feed does not list is **re-announced**: its chain-head provenance
7//! record goes to `POST /v1/sync/reannounce`, manifests only, never bytes
8//! ([Server Filesystem § Sync Epoch and Client Re-Announce]).
9//!
10//! Two pieces, so the orchestration is testable without a server:
11//!
12//! - [`unlisted`] is the pure walk: the held assets the feed does not list, in the order held;
13//! - [`batches`] cuts them into requests the server accepts, by count and by size;
14//! - [`SyncConsumer::reannounce`] sends one batch through the generated operation.
15//!
16//! [`reannounce_unlisted`] is the three together. What the server answers is per manifest: a
17//! `missing_blobs` answer is the caller's cue to re-upload through the transfer protocol, which
18//! is the push path's to do, never this module's.
19//!
20//! [Server Filesystem § Sync Epoch and Client Re-Announce]: https://docs/design/filesystem/server/#sync-epoch-and-client-re-announce
21
22use std::collections::HashSet;
23
24use base64::Engine as _;
25use base64::engine::general_purpose::STANDARD as BASE64;
26use tracing::instrument;
27
28use super::{SyncConsumer, SyncError};
29use crate::rest;
30
31/// The most manifests one request carries: half the server's per-request ceiling, so a server
32/// that lowers it within reason still accepts a full batch.
33pub const MAX_BATCH_MANIFESTS: usize = 32;
34
35/// The most manifest bytes one request carries, before base64.
36///
37/// The route sits behind the server's bounded body cap (one mebibyte); base64 inflates by a
38/// third and JSON adds a little, so half of it keeps every batch well under the cap.
39pub const MAX_BATCH_BYTES: usize = 512 * 1024;
40
41/// One asset the client holds: its id and its chain head's provenance record, the exact bytes
42/// an upload sends as the `provenance` blob.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct HeldManifest {
45    /// The asset id, as the feed spells it.
46    pub asset_id: String,
47    /// The chain head's provenance record.
48    pub manifest: Vec<u8>,
49}
50
51/// What the server did with one re-announced manifest.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum ReannounceOutcome {
54    /// The server lacked the row and now holds it, published at `sync_seq`.
55    Restored {
56        /// The position the restored row was published at, when the server reported one.
57        sync_seq: Option<u64>,
58    },
59    /// The server already holds the row.
60    AlreadyIndexed,
61    /// The server's store lacks these blobs; re-upload them through the transfer protocol.
62    MissingBlobs(Vec<String>),
63    /// Refused, with the stable `error.sync.reannounce_*` code.
64    Refused {
65        /// The code the client localizes.
66        code: String,
67    },
68}
69
70/// One manifest's answer.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct ReannounceResult {
73    /// The asset the manifest names, when the server could read one.
74    pub asset_id: Option<String>,
75    /// What happened.
76    pub outcome: ReannounceOutcome,
77}
78
79/// The held assets `listed` does not name, in the order held: what to re-announce.
80#[must_use]
81pub fn unlisted<'a, S: std::hash::BuildHasher>(
82    held: &'a [HeldManifest],
83    listed: &HashSet<String, S>,
84) -> Vec<&'a HeldManifest> {
85    held.iter()
86        .filter(|manifest| !listed.contains(&manifest.asset_id))
87        .collect()
88}
89
90/// Cut `manifests` into requests of at most [`MAX_BATCH_MANIFESTS`] manifests and
91/// [`MAX_BATCH_BYTES`] bytes, in order.
92///
93/// A single manifest larger than the byte budget rides alone: the server answers it (it is far
94/// past any real manifest, so the answer is `malformed`), which is better than never sending it.
95#[must_use]
96pub fn batches<'a>(manifests: &[&'a HeldManifest]) -> Vec<Vec<&'a HeldManifest>> {
97    let mut out: Vec<Vec<&HeldManifest>> = Vec::new();
98    let mut current: Vec<&HeldManifest> = Vec::new();
99    let mut bytes = 0_usize;
100    for manifest in manifests {
101        let size = manifest.manifest.len();
102        if !current.is_empty()
103            && (current.len() == MAX_BATCH_MANIFESTS || bytes + size > MAX_BATCH_BYTES)
104        {
105            out.push(std::mem::take(&mut current));
106            bytes = 0;
107        }
108        bytes += size;
109        current.push(manifest);
110    }
111    if !current.is_empty() {
112        out.push(current);
113    }
114    out
115}
116
117impl SyncConsumer {
118    /// Re-announce one batch of manifests: `POST /v1/sync/reannounce`.
119    ///
120    /// One answer per manifest, in order. Refreshes once on a `401`, as a pull does.
121    ///
122    /// # Errors
123    ///
124    /// [`SyncError::Rejected`] with the server's code when it refused the request as a whole
125    /// (an empty or oversized batch, a collaborator that could not answer, the protocol gate),
126    /// [`SyncError::Transport`] when the request did not complete, and
127    /// [`SyncError::MalformedManifest`] when the server answered a different number of results
128    /// than manifests sent.
129    #[instrument(skip(self, manifests), fields(manifests = manifests.len()))]
130    pub async fn reannounce(
131        &self,
132        manifests: &[&HeldManifest],
133    ) -> Result<Vec<ReannounceResult>, SyncError> {
134        let body = rest::types::ReannounceRequest {
135            manifests: manifests
136                .iter()
137                .map(|held| BASE64.encode(&held.manifest))
138                .collect(),
139        };
140        let response = match self.call_reannounce(&body).await {
141            Ok(response) => response,
142            Err(error) if is_unauthenticated(&error) => match &self.auth {
143                super::SyncAuth::Session(session) => {
144                    tracing::info!("re-announce answered 401; refreshing once and retrying");
145                    session.refresh().await?;
146                    self.call_reannounce(&body).await.map_err(map_error)?
147                }
148                // A capability is refused here anyway (re-announce takes a session); its `401` is
149                // as final as a static token's.
150                super::SyncAuth::Static | super::SyncAuth::Signed { .. } => {
151                    return Err(map_error(error));
152                }
153            },
154            Err(error) => return Err(map_error(error)),
155        };
156        if response.results.len() != manifests.len() {
157            return Err(SyncError::MalformedManifest(format!(
158                "the server answered {} of {} re-announced manifests",
159                response.results.len(),
160                manifests.len()
161            )));
162        }
163        Ok(response.results.into_iter().map(decode_result).collect())
164    }
165
166    async fn call_reannounce(
167        &self,
168        body: &rest::types::ReannounceRequest,
169    ) -> Result<rest::types::ReannounceResponse, rest::Error<rest::ReannounceManifestsError>> {
170        Ok(self
171            .client
172            .reannounce_manifests(
173                rest::ReannounceManifestsParamsRequired {
174                    x_capsule_protocol: capsule_core::crypto::primitives::PROTOCOL_VERSION.into(),
175                },
176                body.clone(),
177            )
178            .await?
179            .into_inner())
180    }
181}
182
183/// Re-announce every held asset `listed` does not name, batch by batch, and return each answer
184/// paired with the asset the client sent it for.
185///
186/// # Errors
187///
188/// The first batch [`SyncConsumer::reannounce`] could not complete. Batches before it were
189/// answered and their restores stand; re-running re-announces what is still unlisted, and the
190/// server answers a restored asset `already_indexed`.
191#[instrument(skip(consumer, held, listed), fields(held = held.len(), listed = listed.len()))]
192pub async fn reannounce_unlisted<S: std::hash::BuildHasher>(
193    consumer: &SyncConsumer,
194    held: &[HeldManifest],
195    listed: &HashSet<String, S>,
196) -> Result<Vec<(String, ReannounceResult)>, SyncError> {
197    let pending = unlisted(held, listed);
198    tracing::info!(
199        unlisted = pending.len(),
200        "re-announcing what the feed no longer lists"
201    );
202    let mut answers = Vec::with_capacity(pending.len());
203    for batch in batches(&pending) {
204        let results = consumer.reannounce(&batch).await?;
205        answers.extend(batch.iter().map(|held| held.asset_id.clone()).zip(results));
206    }
207    Ok(answers)
208}
209
210/// Whether the route refused the credential.
211fn is_unauthenticated(error: &rest::Error<rest::ReannounceManifestsError>) -> bool {
212    matches!(
213        error,
214        rest::Error::Api(response)
215            if matches!(response.inner(), rest::ReannounceManifestsError::Status401(_))
216    )
217}
218
219/// Map the generated operation's error onto [`SyncError`], keeping the stable code.
220fn map_error(error: rest::Error<rest::ReannounceManifestsError>) -> SyncError {
221    use rest::ReannounceManifestsError as Refusal;
222    match error {
223        rest::Error::Api(response) => {
224            let (code, message) = match response.into_inner() {
225                Refusal::Status400(problem)
226                | Refusal::Status401(problem)
227                | Refusal::Status403(problem)
228                | Refusal::Status408(problem)
229                | Refusal::Status413(problem)
230                | Refusal::Status415(problem)
231                | Refusal::Status422(problem)
232                | Refusal::Status425(problem)
233                | Refusal::Status426(problem)
234                | Refusal::Status500(problem) => (
235                    Some(problem.code.clone()),
236                    problem.detail.clone().unwrap_or_default(),
237                ),
238            };
239            SyncError::Rejected { code, message }
240        }
241        other => SyncError::Transport(other.to_string()),
242    }
243}
244
245/// One wire answer, as the SDK speaks it.
246fn decode_result(result: rest::types::ReannounceResult) -> ReannounceResult {
247    let outcome = match result.outcome {
248        rest::types::ReannounceOutcome::Restored => ReannounceOutcome::Restored {
249            sync_seq: result.sync_seq.into_option(),
250        },
251        rest::types::ReannounceOutcome::AlreadyIndexed => ReannounceOutcome::AlreadyIndexed,
252        rest::types::ReannounceOutcome::MissingBlobs => {
253            ReannounceOutcome::MissingBlobs(result.missing.into_iter().flatten().collect())
254        }
255        rest::types::ReannounceOutcome::Refused => ReannounceOutcome::Refused {
256            code: result.code.into_option().unwrap_or_default(),
257        },
258    };
259    ReannounceResult {
260        asset_id: result.asset_id.into_option(),
261        outcome,
262    }
263}
264
265#[cfg(test)]
266mod tests;