capsule_sdk/sync/
reannounce.rs1use 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
31pub const MAX_BATCH_MANIFESTS: usize = 32;
34
35pub const MAX_BATCH_BYTES: usize = 512 * 1024;
40
41#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct HeldManifest {
45 pub asset_id: String,
47 pub manifest: Vec<u8>,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum ReannounceOutcome {
54 Restored {
56 sync_seq: Option<u64>,
58 },
59 AlreadyIndexed,
61 MissingBlobs(Vec<String>),
63 Refused {
65 code: String,
67 },
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct ReannounceResult {
73 pub asset_id: Option<String>,
75 pub outcome: ReannounceOutcome,
77}
78
79#[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#[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 #[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 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#[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
210fn 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
219fn 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
245fn 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;