Skip to main content

syncular_client/
round.rs

1//! Owned round inputs and network results. SQLite never leaves its owner.
2use std::collections::BTreeMap;
3
4use ssp2::model::{Frame, MediaType, Message, MsgKind, SubStatus};
5use ssp2::{decode_message, encode_message};
6
7use crate::client::RequestMeta;
8use crate::{
9    BlobUploadGrant, ProgressObserver, ProgressPhase, SegmentFetch, SegmentRequest, SyncOutcome,
10    Transport, TransportError,
11};
12
13pub(crate) fn now_ms(fixed: Option<i64>) -> i64 {
14    fixed.unwrap_or_else(crate::wall_clock_ms)
15}
16
17pub(crate) struct PendingUpload {
18    pub id: String,
19    pub bytes: Result<Vec<u8>, TransportError>,
20    pub media_type: Option<String>,
21}
22
23/// One network operation of a prepared round.
24///
25/// A host that cannot block (a browser worker with `fetch`, a single-threaded
26/// runtime) drives a round with [`PreparedSyncRound::next_operation`],
27/// performs the operation with its own I/O, and returns the result with
28/// [`PreparedSyncRound::submit`]. A host with a blocking [`Transport`] calls
29/// [`PreparedSyncRound::exchange`], which runs the same operations in order.
30#[derive(Debug)]
31pub enum RoundOperation<'a> {
32    /// `POST <mount>/blobs/{blob_id}/upload-grant` (§5.9.3).
33    UploadGrant {
34        blob_id: &'a str,
35        byte_length: u64,
36        media_type: Option<&'a str>,
37    },
38    /// `PUT` the presigned upload url the grant returned. A failure falls back
39    /// to [`RoundOperation::Upload`] with the same body.
40    UploadPut {
41        blob_id: &'a str,
42        url: &'a str,
43        bytes: &'a [u8],
44        media_type: Option<&'a str>,
45    },
46    /// `PUT <mount>/blobs/{blob_id}` through the direct endpoint.
47    Upload {
48        blob_id: &'a str,
49        bytes: &'a [u8],
50        media_type: Option<&'a str>,
51    },
52    /// The combined push+pull message. `realtime` selects the socket path
53    /// (§8.7, [`Transport::realtime_sync`]) instead of `POST /sync` (§1.5).
54    Sync { request: &'a [u8], realtime: bool },
55    /// Every eligible segment body of the response, in wire order (§5.4 /
56    /// §5.5). Fetch them in parallel if the host can; the core consumes the
57    /// results in order and stops at the first failure.
58    Downloads(&'a [SegmentFetch]),
59}
60
61/// The host's answer to a [`RoundOperation`].
62#[derive(Debug)]
63pub enum RoundReply {
64    /// Answers [`RoundOperation::UploadGrant`] with the grant endpoint's body.
65    UploadGrant(Result<BlobUploadGrant, TransportError>),
66    /// Answers [`RoundOperation::UploadPut`] or [`RoundOperation::Upload`]. A
67    /// failed PUT makes `submit` ask for `Upload` next.
68    Upload(Result<(), TransportError>),
69    /// Answers [`RoundOperation::Sync`] with the assembled response bytes.
70    Sync(Result<Vec<u8>, TransportError>),
71    /// Answers [`RoundOperation::Downloads`] with one result per fetch, in
72    /// order.
73    Downloads(Vec<Result<Vec<u8>, TransportError>>),
74}
75
76/// The phase of a host-driven round. Every variant except `Downloads` names
77/// one network operation; `Downloads` carries the captured response while the
78/// host fetches its segment bodies.
79pub(crate) enum RoundPhase {
80    UploadGrant,
81    UploadPut {
82        url: String,
83    },
84    UploadDirect,
85    Sync,
86    Downloads {
87        planned: Vec<PlannedFetch>,
88        fetches: Vec<SegmentFetch>,
89        response: Message,
90        batch_started_at: i64,
91    },
92}
93
94/// Immutable request and blob bodies captured by the mutable client owner.
95/// Send this value to an I/O executor; it contains no SQLite connection.
96pub struct PreparedSyncRound {
97    pub(crate) id: uuid::Uuid,
98    pub(crate) started_at_ms: i64,
99    pub(crate) attempt: u64,
100    pub(crate) meta: RequestMeta,
101    pub(crate) message: Message,
102    pub(crate) realtime: bool,
103    pub(crate) uploads: std::collections::VecDeque<PendingUpload>,
104    pub(crate) scopes: BTreeMap<String, String>,
105    #[cfg(feature = "bench-internals")]
106    pub(crate) benchmark_phases: crate::bench::Recorder,
107    pub(crate) progress: ProgressObserver,
108    pub(crate) fixed_now: Option<i64>,
109    /// Absolute whole-round network deadline, anchored from the transport's
110    /// `round_deadline` budget on the round's first network call and carried
111    /// across `Continue`s. `exchange` scopes it onto the transport for the
112    /// duration of each network call.
113    pub(crate) round_deadline_at: Option<std::time::Instant>,
114    /// §7.8: the idle drive bound (`timeoutMs`, rounds the drive ran before
115    /// this one). `exchange` scopes it onto the transport as a bound on time
116    /// without progress: a network call that moves no byte for `timeoutMs`
117    /// fails with `sync.idle_timeout`.
118    pub(crate) idle_bound: Option<(u64, u32)>,
119    /// When the round's first network call started; the `elapsedMs` of a
120    /// `sync.idle_timeout` counts from it.
121    pub(crate) network_started_at: Option<std::time::Instant>,
122    /// The encoded round message, filled on the first request that needs it.
123    pub(crate) encoded: Option<Vec<u8>>,
124    pub(crate) phase: RoundPhase,
125    /// The phase that follows the completed upload exchange; consumed by the
126    /// next drive of a round whose apply returned `Continue`.
127    pub(crate) continuation: Option<RoundPhase>,
128    /// Set when the current exchange has nothing left to fetch. `finish`
129    /// returns it; `apply_sync_round` reads it.
130    pub(crate) completed: Option<ExchangeResult>,
131}
132
133/// Network results returned to the same mutable owner that prepared the round.
134pub struct CompletedSyncRound {
135    pub(crate) prepared: PreparedSyncRound,
136    pub(crate) exchange: ExchangeResult,
137}
138
139pub(crate) enum ExchangeResult {
140    Upload {
141        id: String,
142        result: Result<(), TransportError>,
143    },
144    Reply {
145        response: Result<Message, TransportError>,
146        transport_failed: bool,
147        downloads: DownloadResults,
148    },
149}
150
151/// A completed upload returns to the owner to persist its pin removal before
152/// any metadata push. A completed response returns its durable apply outcome.
153// The prepared round is the continuation and stays by value so a host keeps
154// one type for both outcomes.
155#[allow(clippy::large_enum_variant)]
156pub enum AppliedSyncRound {
157    Continue(PreparedSyncRound),
158    Complete {
159        outcome: SyncOutcome,
160        controls: Vec<String>,
161        /// The same continuation predicate used by `sync_until_idle`.
162        more: bool,
163        /// A bootstrap page advanced, renewing an unbounded idle run's budget.
164        bootstrap_advanced: bool,
165    },
166}
167
168impl PreparedSyncRound {
169    /// §7.8: bound this round by an idle drive's `timeout_ms`; `rounds` is
170    /// the count the drive ran before it. The bound restarts on every byte the
171    /// round's network calls move; the transport's own `round_deadline` stays
172    /// an absolute deadline beside it.
173    pub fn set_idle_deadline(&mut self, timeout_ms: u64, rounds: u32) {
174        self.idle_bound = Some((timeout_ms, rounds));
175    }
176
177    /// Scope the round deadline for one network call. The round anchors its
178    /// deadline on its first network call, so local work before that call does
179    /// not consume the network budget; the anchor is absolute from then on, and
180    /// a continuation reuses the carried anchor instead of refreshing it.
181    fn scope_round_deadline(
182        &mut self,
183        transport: &mut dyn Transport,
184    ) -> Result<(), TransportError> {
185        if self.network_started_at.is_none() && self.round_deadline_at.is_none() {
186            // No `Instant` to measure the drive bound with (see below).
187            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
188            {
189                self.idle_bound = None;
190            }
191            #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
192            {
193                self.network_started_at = Some(std::time::Instant::now());
194            }
195            if let Some(budget) = transport.round_deadline() {
196                // A wasm32-unknown-unknown host has no `Instant`, so there is
197                // nothing to anchor the budget to. Report that instead of
198                // panicking inside `Instant::now()`.
199                #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
200                {
201                    let _ = budget;
202                    return Err(TransportError::new(
203                        "sync.invalid_request",
204                        "transport round deadline is unsupported on wasm32-unknown-unknown",
205                    ));
206                }
207                #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
208                match std::time::Instant::now().checked_add(budget) {
209                    Some(deadline) => self.round_deadline_at = Some(deadline),
210                    // Reject an unrepresentable host budget before network I/O.
211                    None => {
212                        return Err(TransportError::new(
213                            "sync.invalid_request",
214                            "transport round deadline is out of range",
215                        ))
216                    }
217                }
218            }
219        }
220        transport.set_round_deadline(self.round_deadline_at);
221        transport.set_round(Some(self.attempt));
222        transport.set_idle_bound(
223            self.idle_bound
224                .map(|(ms, _)| std::time::Duration::from_millis(ms)),
225        );
226        Ok(())
227    }
228
229    /// Run network I/O without accessing client state. Download errors stay at
230    /// their descriptor's position so apply retains the same completed prefix.
231    ///
232    /// This drives the same [`RoundOperation`] sequence that a non-blocking
233    /// host drives itself, so both paths share every decision the client
234    /// makes about uploads, segment fetches, and deadline state.
235    pub fn exchange(mut self, transport: &mut dyn Transport) -> CompletedSyncRound {
236        let mut scoped = false;
237        while self.completed.is_none() {
238            let reply = {
239                let Some(operation) = self.next_operation_scoped(transport, &mut scoped) else {
240                    break;
241                };
242                match operation {
243                    RoundOperation::UploadGrant {
244                        blob_id,
245                        byte_length,
246                        media_type,
247                    } => RoundReply::UploadGrant(transport.blob_upload_grant(
248                        blob_id,
249                        byte_length,
250                        media_type,
251                    )),
252                    RoundOperation::UploadPut {
253                        blob_id,
254                        url,
255                        bytes,
256                        media_type,
257                    } => {
258                        RoundReply::Upload(transport.blob_put_url(blob_id, url, bytes, media_type))
259                    }
260                    RoundOperation::Upload {
261                        blob_id,
262                        bytes,
263                        media_type,
264                    } => RoundReply::Upload(transport.blob_upload(blob_id, bytes, media_type)),
265                    RoundOperation::Sync { request, realtime } => RoundReply::Sync(if realtime {
266                        transport.realtime_sync(request)
267                    } else {
268                        transport.sync(request)
269                    }),
270                    RoundOperation::Downloads(fetches) => {
271                        RoundReply::Downloads(transport.download_segments(fetches, &mut |_, _| {}))
272                    }
273                }
274            };
275            self.submit(reply)
276                .expect("the exchange answers its own operation");
277        }
278        transport.set_round_deadline(None);
279        transport.set_round(None);
280        transport.set_idle_bound(None);
281        self.finish().expect("the exchange completed the round")
282    }
283
284    /// The encoded round message (§1.5). Uploads listed by
285    /// [`RoundOperation::UploadGrant`] precede it; a host that drives the round
286    /// with `exchange` never needs this call.
287    pub fn request_bytes(&self) -> Vec<u8> {
288        self.encoded
289            .clone()
290            .unwrap_or_else(|| encode_message(&self.message))
291    }
292
293    /// The next network operation a host must perform, or `None` once every
294    /// operation of the current exchange is answered. Call
295    /// [`PreparedSyncRound::submit`] with its result, then repeat.
296    ///
297    /// After an upload operation completes, the round is complete for this
298    /// exchange: call [`PreparedSyncRound::finish`] and apply it, so the owner
299    /// persists the pin removal before the metadata request. The applied
300    /// round's `Continue` returns the prepared round for the next exchange.
301    pub fn next_operation(&mut self) -> Option<RoundOperation<'_>> {
302        let mut scoped = false;
303        self.next_operation_impl(None, &mut scoped)
304    }
305
306    /// Hand the result of the last [`PreparedSyncRound::next_operation`] back.
307    /// A reply of the wrong kind fails with `client.invalid_round_reply` and
308    /// leaves the round where it was.
309    pub fn submit(&mut self, reply: RoundReply) -> Result<(), TransportError> {
310        if self.completed.is_some() {
311            return Err(TransportError::new(
312                "client.invalid_round_reply",
313                "the exchange already has its reply",
314            ));
315        }
316        let phase = std::mem::replace(&mut self.phase, RoundPhase::Sync);
317        match (phase, reply) {
318            (RoundPhase::UploadGrant, RoundReply::UploadGrant(Err(error))) => {
319                let upload = self
320                    .uploads
321                    .pop_front()
322                    .expect("an upload phase owns an upload");
323                self.completed = Some(ExchangeResult::Upload {
324                    id: upload.id,
325                    result: Err(error),
326                });
327            }
328            (RoundPhase::UploadGrant, RoundReply::UploadGrant(Ok(grant))) => match grant {
329                BlobUploadGrant::Present => self.upload_complete(),
330                BlobUploadGrant::Url {
331                    url,
332                    url_expires_at_ms,
333                } => {
334                    // §5.9.3: an expiry the host clock already passed skips the
335                    // PUT; the direct endpoint still carries the body.
336                    if url_expires_at_ms.is_none_or(|expiry| expiry > now_ms(self.fixed_now)) {
337                        self.phase = RoundPhase::UploadPut { url };
338                    } else {
339                        self.phase = RoundPhase::UploadDirect;
340                    }
341                }
342                BlobUploadGrant::None => self.phase = RoundPhase::UploadDirect,
343            },
344            (RoundPhase::UploadPut { .. }, RoundReply::Upload(Ok(()))) => self.upload_complete(),
345            // A failed presigned PUT falls back to the direct endpoint with the
346            // same body, exactly like `upload_one`.
347            (RoundPhase::UploadPut { .. }, RoundReply::Upload(Err(_))) => {
348                self.phase = RoundPhase::UploadDirect;
349            }
350            (RoundPhase::UploadDirect, RoundReply::Upload(Ok(()))) => self.upload_complete(),
351            (RoundPhase::UploadDirect, RoundReply::Upload(Err(error))) => {
352                let upload = self
353                    .uploads
354                    .pop_front()
355                    .expect("an upload phase owns an upload");
356                self.completed = Some(ExchangeResult::Upload {
357                    id: upload.id,
358                    result: Err(error),
359                });
360            }
361            (RoundPhase::Sync, RoundReply::Sync(reply)) => {
362                let transport_failed = reply.is_err();
363                let response = reply.and_then(|bytes| {
364                    #[cfg(feature = "bench-internals")]
365                    let _decode_phase = self
366                        .benchmark_phases
367                        .start(crate::bench::Phase::ResponseDecode);
368                    let response = decode_message(&bytes)
369                        .map_err(|e| TransportError::new(e.code.as_str(), e.detail))?;
370                    if response.msg_kind != MsgKind::Response {
371                        return Err(TransportError::new(
372                            "sync.invalid_request",
373                            "expected a response message",
374                        ));
375                    }
376                    Ok(response)
377                });
378                let Ok(response) = response else {
379                    self.completed = Some(ExchangeResult::Reply {
380                        response,
381                        transport_failed,
382                        downloads: DownloadResults::default(),
383                    });
384                    return Ok(());
385                };
386                let mut planned: Vec<PlannedFetch> = Vec::new();
387                // A reset/floor/invalid header cannot authorize any segment
388                // fetch.
389                if matches!(response.frames.first(), Some(Frame::RespHeader { required_schema_version: None, reset_required: false, log_epoch: epoch, .. }) if self.message.frames.first().is_some_and(|f| matches!(f, Frame::ReqHeader { log_epoch, .. } if log_epoch.as_ref().map_or(self.message.frames.contains(&Frame::AdoptEpoch), |request_epoch| request_epoch == epoch))))
390                {
391                    let mut scope: Option<(&str, &str)> = None;
392                    // §7.7: the section's UNIT_EXTENT as (rowsTotal, rowsDone).
393                    let mut extent: Option<(u64, u64)> = None;
394                    // §5.4 / §5.5: collect every eligible descriptor first so
395                    // the host can overlap the fetches. One batch start is the
396                    // fetch start for the expiry rule.
397                    let batch_started_at = now_ms(self.fixed_now);
398                    let mut images = 0;
399                    for frame in &response.frames {
400                        match frame {
401                            Frame::SubStart {
402                                id,
403                                status: SubStatus::Active,
404                                ..
405                            } => {
406                                scope = self
407                                    .scopes
408                                    .get(id)
409                                    .map(|scopes| (id.as_str(), scopes.as_str()));
410                                extent = None;
411                            }
412                            Frame::SubStart { .. } | Frame::SubEnd { .. } => scope = None,
413                            Frame::UnitExtent {
414                                rows_total,
415                                rows_done,
416                            } => {
417                                extent = u64::try_from(*rows_total)
418                                    .ok()
419                                    .zip(u64::try_from(*rows_done).ok());
420                            }
421                            Frame::Error { .. } => break,
422                            Frame::SegmentRef {
423                                segment_id,
424                                table,
425                                media_type,
426                                url,
427                                url_expires_at_ms,
428                                byte_length,
429                                row_count,
430                                ..
431                            } => {
432                                let Some((id, scopes)) = scope else { continue };
433                                let advertised = match media_type {
434                                    MediaType::Rows => self.meta.accept & 3 != 0,
435                                    MediaType::Sqlite => self.meta.accept & 4 != 0,
436                                };
437                                if !advertised || (url.is_some() && self.meta.accept & 8 == 0) {
438                                    break;
439                                }
440                                // §5.6 applied-segment rule: a complete segment
441                                // is not downloaded again.
442                                if self
443                                    .meta
444                                    .applied
445                                    .get(id)
446                                    .and_then(|record| record.get(segment_id))
447                                    == Some(row_count)
448                                {
449                                    continue;
450                                }
451                                // §5.3 client memory: two image bodies per batch;
452                                // the unit's section stops before the next one.
453                                if *media_type == MediaType::Sqlite {
454                                    if images == 2 {
455                                        self.meta
456                                            .deferred
457                                            .insert((id.to_owned(), segment_id.clone()));
458                                        scope = None;
459                                        continue;
460                                    }
461                                    images += 1;
462                                }
463                                // A negative byteLength admits no body (§5.4).
464                                let cap = u64::try_from(*byte_length).unwrap_or(0);
465                                let expired = url.is_some()
466                                    && url_expires_at_ms
467                                        .is_some_and(|expiry| expiry <= batch_started_at);
468                                let (key, fetch) = match url {
469                                    Some(url) => (
470                                        DownloadKey::Url(url.clone()),
471                                        if expired {
472                                            None
473                                        } else {
474                                            Some(SegmentFetch::Url {
475                                                url: url.clone(),
476                                                byte_length: cap,
477                                            })
478                                        },
479                                    ),
480                                    None => (
481                                        DownloadKey::Segment(
482                                            segment_id.clone(),
483                                            table.clone(),
484                                            scopes.to_owned(),
485                                        ),
486                                        Some(SegmentFetch::Direct(SegmentRequest {
487                                            segment_id: segment_id.clone(),
488                                            table: table.clone(),
489                                            requested_scopes_json: scopes.to_owned(),
490                                            byte_length: cap,
491                                        })),
492                                    ),
493                                };
494                                planned.push(PlannedFetch {
495                                    key,
496                                    unit_id: id.to_owned(),
497                                    table: table.clone(),
498                                    segment_id: segment_id.clone(),
499                                    bytes_total: u64::try_from(*byte_length).ok(),
500                                    rows_total: u64::try_from(*row_count).ok(),
501                                    extent,
502                                    fetch,
503                                });
504                                if expired {
505                                    break;
506                                }
507                            }
508                            _ => {}
509                        }
510                    }
511                    if !planned.is_empty() {
512                        let progress = self.progress.clone();
513                        let on_progress = |index: usize, bytes: u64| {
514                            let Some(planned_fetch) = planned.get(index) else {
515                                return;
516                            };
517                            progress.update(|p| {
518                                p.phase = ProgressPhase::Download;
519                                p.unit_id = Some(planned_fetch.unit_id.clone());
520                                p.table = Some(planned_fetch.table.clone());
521                                p.segment_id = Some(planned_fetch.segment_id.clone());
522                                p.bytes_received = bytes;
523                                p.bytes_total = planned_fetch.bytes_total;
524                                p.rows_processed = 0;
525                                p.rows_total = planned_fetch.rows_total;
526                                p.unit_rows_total = planned_fetch.extent.map(|(total, _)| total);
527                                p.unit_rows_processed = planned_fetch.extent.map(|(_, done)| done);
528                            });
529                        };
530                        // Announce the download phase before the first byte lands.
531                        on_progress(0, 0);
532                        let fetches: Vec<SegmentFetch> = planned
533                            .iter()
534                            .filter_map(|planned_fetch| planned_fetch.fetch.clone())
535                            .collect();
536                        self.phase = RoundPhase::Downloads {
537                            planned,
538                            fetches,
539                            response,
540                            batch_started_at,
541                        };
542                        return Ok(());
543                    }
544                }
545                self.completed = Some(ExchangeResult::Reply {
546                    response: Ok(response),
547                    transport_failed,
548                    downloads: DownloadResults::default(),
549                });
550            }
551            (
552                RoundPhase::Downloads {
553                    planned,
554                    batch_started_at,
555                    response,
556                    ..
557                },
558                RoundReply::Downloads(results),
559            ) => {
560                let mut downloads = DownloadResults::default();
561                let progress = self.progress.clone();
562                let mut results = results.into_iter();
563                for planned_fetch in planned {
564                    let result = match planned_fetch.fetch {
565                        None => Err(TransportError::new(
566                            "sync.segment_expired",
567                            "signed segment URL expired before fetch",
568                        )),
569                        // A shorter result list means the batch stopped after an
570                        // earlier error, and apply aborts there.
571                        Some(_) => match results.next() {
572                            Some(result) => result,
573                            None => break,
574                        },
575                    };
576                    if let Ok(bytes) = &result {
577                        progress.update(|p| {
578                            p.phase = ProgressPhase::Download;
579                            p.unit_id = Some(planned_fetch.unit_id.clone());
580                            p.table = Some(planned_fetch.table.clone());
581                            p.segment_id = Some(planned_fetch.segment_id.clone());
582                            p.bytes_received = bytes.len() as u64;
583                            p.bytes_total = planned_fetch.bytes_total;
584                            p.rows_processed = 0;
585                            p.rows_total = planned_fetch.rows_total;
586                            p.unit_rows_total = planned_fetch.extent.map(|(total, _)| total);
587                            p.unit_rows_processed = planned_fetch.extent.map(|(_, done)| done);
588                        });
589                    }
590                    let failed = result.is_err();
591                    downloads
592                        .entries
593                        .push_back((planned_fetch.key, batch_started_at, result));
594                    if failed {
595                        break;
596                    }
597                }
598                self.completed = Some(ExchangeResult::Reply {
599                    response: Ok(response),
600                    transport_failed: false,
601                    downloads,
602                });
603            }
604            (phase, _) => {
605                self.phase = phase;
606                return Err(TransportError::new(
607                    "client.invalid_round_reply",
608                    "the reply does not answer the pending operation",
609                ));
610            }
611        }
612        Ok(())
613    }
614
615    /// The completed round once every operation is answered, ready for
616    /// `SyncClient::apply_sync_round`.
617    pub fn finish(mut self) -> Option<CompletedSyncRound> {
618        let mut exchange = self.completed.take()?;
619        // §7.8: the drive bound ended a network call; the round reports the
620        // drive's timeout, whichever call reached it.
621        if let Some((timeout_ms, rounds)) = self.idle_bound {
622            let elapsed_ms = self
623                .network_started_at
624                .map_or(0, |started| started.elapsed().as_millis() as u64);
625            let errors: Vec<&mut TransportError> = match &mut exchange {
626                ExchangeResult::Upload { result, .. } => {
627                    result.as_mut().err().into_iter().collect()
628                }
629                ExchangeResult::Reply {
630                    response,
631                    downloads,
632                    ..
633                } => response
634                    .as_mut()
635                    .err()
636                    .into_iter()
637                    .chain(
638                        downloads
639                            .entries
640                            .iter_mut()
641                            .filter_map(|(_, _, result)| result.as_mut().err()),
642                    )
643                    .collect(),
644            };
645            for error in errors {
646                if error.code == "sync.idle_timeout" {
647                    error.details = Some(serde_json::json!({
648                        "timeoutMs": timeout_ms,
649                        "rounds": rounds,
650                        "elapsedMs": elapsed_ms,
651                    }));
652                }
653            }
654        }
655        Some(CompletedSyncRound {
656            prepared: self,
657            exchange,
658        })
659    }
660
661    fn upload_complete(&mut self) {
662        let upload = self
663            .uploads
664            .pop_front()
665            .expect("an upload phase owns an upload");
666        self.completed = Some(ExchangeResult::Upload {
667            id: upload.id,
668            result: Ok(()),
669        });
670        self.continuation = Some(if self.uploads.is_empty() {
671            RoundPhase::Sync
672        } else {
673            RoundPhase::UploadGrant
674        });
675    }
676
677    fn ensure_encoded(&mut self) {
678        if self.encoded.is_none() {
679            #[cfg(feature = "bench-internals")]
680            let _phase = self
681                .benchmark_phases
682                .start(crate::bench::Phase::RequestEncode);
683            self.encoded = Some(encode_message(&self.message));
684        }
685    }
686
687    fn next_operation_scoped<'a>(
688        &'a mut self,
689        transport: &mut dyn Transport,
690        scoped: &mut bool,
691    ) -> Option<RoundOperation<'a>> {
692        self.next_operation_impl(Some(transport), scoped)
693    }
694
695    fn next_operation_impl<'a>(
696        &'a mut self,
697        mut scope: Option<&mut dyn Transport>,
698        scoped: &mut bool,
699    ) -> Option<RoundOperation<'a>> {
700        if self.completed.is_some() {
701            return None;
702        }
703        // The previous exchange ended with an upload; the owner has applied it.
704        if let Some(next) = self.continuation.take() {
705            self.phase = next;
706        }
707        if matches!(self.phase, RoundPhase::UploadGrant) && self.uploads.is_empty() {
708            self.phase = RoundPhase::Sync;
709        }
710        // A staged body that failed to read locally performs no network I/O,
711        // so it cannot be the round's first network call and must not anchor
712        // the round deadline either.
713        if matches!(self.phase, RoundPhase::UploadGrant)
714            && self
715                .uploads
716                .front()
717                .is_some_and(|upload| upload.bytes.is_err())
718        {
719            let upload = self
720                .uploads
721                .pop_front()
722                .expect("the failed upload is staged");
723            self.completed = Some(ExchangeResult::Upload {
724                id: upload.id,
725                result: Err(upload.bytes.unwrap_err()),
726            });
727            return None;
728        }
729        if matches!(self.phase, RoundPhase::Sync) {
730            self.ensure_encoded();
731        }
732        let needs_network = !matches!(self.phase, RoundPhase::Downloads { .. });
733        // The round's first network call anchors the deadline after the
734        // encode; a continuation reuses the carried anchor instead of
735        // refreshing it.
736        if needs_network && !*scoped {
737            *scoped = true;
738            if let Some(transport) = scope.as_mut() {
739                if let Err(error) = self.scope_round_deadline(&mut **transport) {
740                    if matches!(
741                        self.phase,
742                        RoundPhase::UploadGrant
743                            | RoundPhase::UploadPut { .. }
744                            | RoundPhase::UploadDirect
745                    ) {
746                        let upload = self
747                            .uploads
748                            .pop_front()
749                            .expect("an upload phase owns an upload");
750                        self.completed = Some(ExchangeResult::Upload {
751                            id: upload.id,
752                            result: Err(error),
753                        });
754                    } else {
755                        self.completed = Some(ExchangeResult::Reply {
756                            response: Err(error),
757                            transport_failed: false,
758                            downloads: DownloadResults::default(),
759                        });
760                    }
761                    return None;
762                }
763            }
764        }
765        match &self.phase {
766            RoundPhase::UploadGrant => {
767                let upload = self
768                    .uploads
769                    .front()
770                    .expect("an upload phase owns an upload");
771                let bytes = upload
772                    .bytes
773                    .as_ref()
774                    .expect("a staged body that failed to read has no operation");
775                Some(RoundOperation::UploadGrant {
776                    blob_id: &upload.id,
777                    byte_length: bytes.len() as u64,
778                    media_type: upload.media_type.as_deref(),
779                })
780            }
781            RoundPhase::UploadPut { url, .. } => {
782                let upload = self
783                    .uploads
784                    .front()
785                    .expect("an upload phase owns an upload");
786                let bytes = upload
787                    .bytes
788                    .as_ref()
789                    .expect("a staged body that failed to read has no operation");
790                Some(RoundOperation::UploadPut {
791                    blob_id: &upload.id,
792                    url,
793                    bytes,
794                    media_type: upload.media_type.as_deref(),
795                })
796            }
797            RoundPhase::UploadDirect => {
798                let upload = self
799                    .uploads
800                    .front()
801                    .expect("an upload phase owns an upload");
802                let bytes = upload
803                    .bytes
804                    .as_ref()
805                    .expect("a staged body that failed to read has no operation");
806                Some(RoundOperation::Upload {
807                    blob_id: &upload.id,
808                    bytes,
809                    media_type: upload.media_type.as_deref(),
810                })
811            }
812            RoundPhase::Sync => Some(RoundOperation::Sync {
813                request: self.encoded.as_deref().expect("the request is encoded"),
814                realtime: self.realtime,
815            }),
816            RoundPhase::Downloads { fetches, .. } => Some(RoundOperation::Downloads(fetches)),
817        }
818    }
819}
820
821#[derive(PartialEq)]
822enum DownloadKey {
823    Url(String),
824    Segment(String, String, String),
825}
826
827/// One eligible `SEGMENT_REF` of the response, collected before the batch
828/// fetch so `download_segments` sees the whole page list at once.
829pub(crate) struct PlannedFetch {
830    key: DownloadKey,
831    unit_id: String,
832    table: String,
833    segment_id: String,
834    bytes_total: Option<u64>,
835    rows_total: Option<u64>,
836    /// The unit section's `UNIT_EXTENT` (rowsTotal, rowsDone), §7.7.
837    extent: Option<(u64, u64)>,
838    /// `None` when the signed URL had already expired at the batch start: the
839    /// fetch is never attempted and its descriptor fails with
840    /// `sync.segment_expired`. Collection stops there, so only the last
841    /// collected fetch can be `None`.
842    fetch: Option<SegmentFetch>,
843}
844
845#[derive(Default)]
846pub(crate) struct DownloadResults {
847    entries: std::collections::VecDeque<(DownloadKey, i64, Result<Vec<u8>, TransportError>)>,
848    pub controls: Vec<String>,
849}
850
851impl DownloadResults {
852    fn take(&mut self, key: DownloadKey) -> Result<Vec<u8>, TransportError> {
853        let position = self
854            .entries
855            .iter()
856            .position(|(candidate, ..)| *candidate == key);
857        position
858            .and_then(|i| self.entries.remove(i))
859            .map(|(_, _, bytes)| bytes)
860            .unwrap_or_else(|| {
861                Err(TransportError::new(
862                    "client.round_download_missing",
863                    "round apply requested an uncaptured segment",
864                ))
865            })
866    }
867}
868
869impl Transport for DownloadResults {
870    fn sync(&mut self, _: &[u8]) -> Result<Vec<u8>, TransportError> {
871        Err(TransportError::new(
872            "client.round_network_on_owner",
873            "network requests must execute outside the client owner",
874        ))
875    }
876    fn realtime_sync(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
877        self.sync(request)
878    }
879    fn download_segment(
880        &mut self,
881        request: &SegmentRequest,
882        _: &mut dyn FnMut(u64),
883    ) -> Result<Vec<u8>, TransportError> {
884        self.take(DownloadKey::Segment(
885            request.segment_id.clone(),
886            request.table.clone(),
887            request.requested_scopes_json.clone(),
888        ))
889    }
890    fn fetch_url(
891        &mut self,
892        url: &str,
893        _: u64,
894        _: &mut dyn FnMut(u64),
895    ) -> Result<Vec<u8>, TransportError> {
896        self.take(DownloadKey::Url(url.to_owned()))
897    }
898    fn segment_fetch_started_at(&self, url: &str) -> Option<i64> {
899        self.entries
900            .iter()
901            .find_map(|(key, time, _)| (*key == DownloadKey::Url(url.to_owned())).then_some(*time))
902    }
903    fn realtime_connect(&mut self, _client_id: &str) -> Result<(), TransportError> {
904        Err(TransportError::new(
905            "client.round_network_on_owner",
906            "network connections must execute outside the client owner",
907        ))
908    }
909    fn realtime_send(&mut self, text: &str) -> Result<(), TransportError> {
910        self.controls.push(text.to_owned());
911        Ok(())
912    }
913    fn realtime_close(&mut self) -> Result<(), TransportError> {
914        Ok(())
915    }
916}
917
918#[cfg(test)]
919pub(crate) mod test_support {
920    use super::*;
921
922    /// Drive one exchange through the split API, answering every operation
923    /// with the blocking transport under test.
924    pub(crate) fn drive_round(
925        mut prepared: PreparedSyncRound,
926        transport: &mut dyn Transport,
927    ) -> CompletedSyncRound {
928        while let Some(operation) = prepared.next_operation() {
929            let reply = match operation {
930                RoundOperation::UploadGrant {
931                    blob_id,
932                    byte_length,
933                    media_type,
934                } => RoundReply::UploadGrant(transport.blob_upload_grant(
935                    blob_id,
936                    byte_length,
937                    media_type,
938                )),
939                RoundOperation::UploadPut {
940                    blob_id,
941                    url,
942                    bytes,
943                    media_type,
944                } => RoundReply::Upload(transport.blob_put_url(blob_id, url, bytes, media_type)),
945                RoundOperation::Upload {
946                    blob_id,
947                    bytes,
948                    media_type,
949                } => RoundReply::Upload(transport.blob_upload(blob_id, bytes, media_type)),
950                RoundOperation::Sync { request, realtime } => RoundReply::Sync(if realtime {
951                    transport.realtime_sync(request)
952                } else {
953                    transport.sync(request)
954                }),
955                RoundOperation::Downloads(fetches) => {
956                    RoundReply::Downloads(transport.download_segments(fetches, &mut |_, _| {}))
957                }
958            };
959            prepared
960                .submit(reply)
961                .expect("the driver answers the pending operation");
962        }
963        prepared.finish().expect("the round has no work left")
964    }
965}
966
967#[cfg(test)]
968mod tests {
969    use super::*;
970    use crate::{BlobUploadGrant, SegmentRequest, SyncClient, TransportError};
971
972    /// Every upload call fails with the same typed timeout, modelling a round
973    /// whose deadline was spent before the signed upload. The fallback to the
974    /// direct endpoint must not replace the typed code with a generic one.
975    struct SpentDeadline;
976
977    impl Transport for SpentDeadline {
978        fn sync(&mut self, _: &[u8]) -> Result<Vec<u8>, TransportError> {
979            unreachable!()
980        }
981        fn realtime_sync(&mut self, _: &[u8]) -> Result<Vec<u8>, TransportError> {
982            unreachable!()
983        }
984        fn download_segment(
985            &mut self,
986            _: &SegmentRequest,
987            _: &mut dyn FnMut(u64),
988        ) -> Result<Vec<u8>, TransportError> {
989            unreachable!()
990        }
991        fn blob_upload_grant(
992            &mut self,
993            _: &str,
994            _: u64,
995            _: Option<&str>,
996        ) -> Result<BlobUploadGrant, TransportError> {
997            Ok(BlobUploadGrant::Url {
998                url: "https://storage.example/signed".into(),
999                url_expires_at_ms: None,
1000            })
1001        }
1002        fn blob_put_url(
1003            &mut self,
1004            _: &str,
1005            _: &str,
1006            _: &[u8],
1007            _: Option<&str>,
1008        ) -> Result<(), TransportError> {
1009            Err(TransportError::new(
1010                "transport.timeout",
1011                "signed upload timed out",
1012            ))
1013        }
1014        fn blob_upload(
1015            &mut self,
1016            _: &str,
1017            _: &[u8],
1018            _: Option<&str>,
1019        ) -> Result<(), TransportError> {
1020            Err(TransportError::new(
1021                "transport.timeout",
1022                "direct upload timed out",
1023            ))
1024        }
1025        fn realtime_connect(&mut self, _client_id: &str) -> Result<(), TransportError> {
1026            Ok(())
1027        }
1028        fn realtime_send(&mut self, _: &str) -> Result<(), TransportError> {
1029            Ok(())
1030        }
1031        fn realtime_close(&mut self) -> Result<(), TransportError> {
1032            Ok(())
1033        }
1034    }
1035
1036    #[test]
1037    fn a_failed_presigned_put_falls_back_to_the_direct_endpoint() {
1038        let schema = serde_json::json!({"version":1,"tables":[{"name":"attachments","primaryKey":"id","columns":[
1039            {"name":"id","type":"string","nullable":false},
1040            {"name":"file","type":"blob_ref","nullable":true}],"scopes":[]}]});
1041        let mut client =
1042            SyncClient::new("spent-deadline".into(), &schema, Default::default()).unwrap();
1043        client
1044            .set_meta(crate::client::LOG_EPOCH_KEY, "epoch")
1045            .unwrap();
1046        client
1047            .upload_blob(b"body", Some("text/plain".into()), None)
1048            .unwrap();
1049        let mut prepared = client.prepare_sync_round(false).unwrap();
1050        let mut transport = SpentDeadline;
1051        let mut steps = Vec::new();
1052        while let Some(operation) = prepared.next_operation() {
1053            let reply = match operation {
1054                RoundOperation::UploadGrant {
1055                    blob_id,
1056                    byte_length,
1057                    media_type,
1058                } => {
1059                    steps.push("grant");
1060                    RoundReply::UploadGrant(transport.blob_upload_grant(
1061                        blob_id,
1062                        byte_length,
1063                        media_type,
1064                    ))
1065                }
1066                RoundOperation::UploadPut {
1067                    blob_id,
1068                    url,
1069                    bytes,
1070                    media_type,
1071                } => {
1072                    steps.push("put");
1073                    RoundReply::Upload(transport.blob_put_url(blob_id, url, bytes, media_type))
1074                }
1075                RoundOperation::Upload {
1076                    blob_id,
1077                    bytes,
1078                    media_type,
1079                } => {
1080                    steps.push("direct");
1081                    RoundReply::Upload(transport.blob_upload(blob_id, bytes, media_type))
1082                }
1083                _ => panic!("only upload operations precede the round message"),
1084            };
1085            prepared.submit(reply).unwrap();
1086        }
1087        assert_eq!(steps, ["grant", "put", "direct"]);
1088        let outcome = match client.apply_sync_round(prepared.finish().unwrap()) {
1089            AppliedSyncRound::Complete { outcome, .. } => outcome,
1090            AppliedSyncRound::Continue(_) => panic!("an upload failure does not continue"),
1091        };
1092        match outcome {
1093            SyncOutcome::Failed { error_code, .. } => {
1094                assert_eq!(error_code, "transport.timeout")
1095            }
1096            other => panic!("expected a typed upload failure, got {other:?}"),
1097        }
1098    }
1099
1100    /// Answers one response that references one segment and serves a body
1101    /// longer than the descriptor declares.
1102    struct OversizedSegment {
1103        unit_id: String,
1104        segment_id: String,
1105        body: Vec<u8>,
1106    }
1107
1108    impl Transport for OversizedSegment {
1109        fn sync(&mut self, _: &[u8]) -> Result<Vec<u8>, TransportError> {
1110            Ok(encode_message(&Message {
1111                wire_version: ssp2::decode::WIRE_VERSION,
1112                msg_kind: MsgKind::Response,
1113                frames: vec![
1114                    Frame::RespHeader {
1115                        required_schema_version: None,
1116                        latest_schema_version: None,
1117                        log_epoch: "epoch".into(),
1118                        reset_required: false,
1119                    },
1120                    Frame::SubStart {
1121                        id: self.unit_id.clone(),
1122                        status: SubStatus::Active,
1123                        reason_code: String::new(),
1124                        bootstrap: true,
1125                        fenced: Vec::new(),
1126                    },
1127                    Frame::SegmentRef {
1128                        segment_id: self.segment_id.clone(),
1129                        media_type: MediaType::Rows,
1130                        table: "tasks".into(),
1131                        byte_length: 4,
1132                        row_count: 1,
1133                        as_of_commit_seq: 1,
1134                        scope_digest: "digest".into(),
1135                        row_cursor: None,
1136                        next_row_cursor: None,
1137                        url: None,
1138                        url_expires_at_ms: None,
1139                    },
1140                    Frame::SubEnd {
1141                        next_cursor: 1,
1142                        bootstrap_state: None,
1143                    },
1144                ],
1145            }))
1146        }
1147        fn realtime_sync(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
1148            self.sync(request)
1149        }
1150        fn download_segment(
1151            &mut self,
1152            _: &SegmentRequest,
1153            _: &mut dyn FnMut(u64),
1154        ) -> Result<Vec<u8>, TransportError> {
1155            Ok(self.body.clone())
1156        }
1157        fn realtime_connect(&mut self, _client_id: &str) -> Result<(), TransportError> {
1158            Ok(())
1159        }
1160        fn realtime_send(&mut self, _: &str) -> Result<(), TransportError> {
1161            Ok(())
1162        }
1163        fn realtime_close(&mut self) -> Result<(), TransportError> {
1164            Ok(())
1165        }
1166    }
1167
1168    #[test]
1169    fn a_segment_body_longer_than_its_byte_length_fails_before_the_content_check() {
1170        use sha2::Digest;
1171        let schema = serde_json::json!({"version":1,"tables":[{"name":"tasks","primaryKey":"id","columns":[
1172            {"name":"id","type":"string","nullable":false},
1173            {"name":"project_id","type":"string","nullable":false}],
1174            "scopes":[{"pattern":"project:{project_id}"}]}]});
1175        let mut client = SyncClient::new("oversized".into(), &schema, Default::default()).unwrap();
1176        client
1177            .set_meta(crate::client::LOG_EPOCH_KEY, "epoch")
1178            .unwrap();
1179        let unit_id = client
1180            .subscribe(crate::UnitScopes::from([(
1181                "project_id".into(),
1182                "p1".into(),
1183            )]))
1184            .unwrap();
1185        // The body hashes to its content address, so only the §5.4 cap can
1186        // refuse it.
1187        let body = b"twelve bytes".to_vec();
1188        let segment_id = format!(
1189            "sha256:{}",
1190            sha2::Sha256::digest(&body)
1191                .iter()
1192                .map(|byte| format!("{byte:02x}"))
1193                .collect::<String>()
1194        );
1195        let mut transport = OversizedSegment {
1196            unit_id,
1197            segment_id,
1198            body,
1199        };
1200        match client.sync(&mut transport) {
1201            SyncOutcome::Failed {
1202                error_code,
1203                message,
1204                ..
1205            } => {
1206                assert_eq!(error_code, "sync.invalid_request");
1207                assert_eq!(message, "segment exceeds its byteLength");
1208            }
1209            other => panic!("expected the byteLength cap to fail the round, got {other:?}"),
1210        }
1211    }
1212
1213    /// Records the round each `set_round` scopes and the one `sync` runs in.
1214    #[derive(Default)]
1215    struct RoundRecorder {
1216        round: Option<u64>,
1217        scoped: Vec<Option<u64>>,
1218        sync_round: Option<Option<u64>>,
1219    }
1220
1221    impl Transport for RoundRecorder {
1222        fn sync(&mut self, _: &[u8]) -> Result<Vec<u8>, TransportError> {
1223            self.sync_round = Some(self.round);
1224            Err(TransportError::new("transport.failed", "recorded"))
1225        }
1226        fn realtime_sync(&mut self, _: &[u8]) -> Result<Vec<u8>, TransportError> {
1227            unreachable!()
1228        }
1229        fn download_segment(
1230            &mut self,
1231            _: &SegmentRequest,
1232            _: &mut dyn FnMut(u64),
1233        ) -> Result<Vec<u8>, TransportError> {
1234            unreachable!()
1235        }
1236        fn realtime_connect(&mut self, _client_id: &str) -> Result<(), TransportError> {
1237            Ok(())
1238        }
1239        fn realtime_send(&mut self, _: &str) -> Result<(), TransportError> {
1240            Ok(())
1241        }
1242        fn realtime_close(&mut self) -> Result<(), TransportError> {
1243            Ok(())
1244        }
1245        fn set_round(&mut self, attempt: Option<u64>) {
1246            self.round = attempt;
1247            self.scoped.push(attempt);
1248        }
1249    }
1250
1251    #[test]
1252    fn a_round_names_its_progress_attempt_to_the_transport_and_clears_it() {
1253        let schema = serde_json::json!({"version":1,"tables":[{"name":"tasks","primaryKey":"id","columns":[
1254            {"name":"id","type":"string","nullable":false},
1255            {"name":"project_id","type":"string","nullable":false}],
1256            "scopes":[{"pattern":"project:{project_id}"}]}]});
1257        let mut client =
1258            SyncClient::new("round-attempt".into(), &schema, Default::default()).unwrap();
1259        client
1260            .set_meta(crate::client::LOG_EPOCH_KEY, "epoch")
1261            .unwrap();
1262        client
1263            .subscribe(crate::UnitScopes::from([(
1264                "project_id".into(),
1265                "p1".into(),
1266            )]))
1267            .unwrap();
1268        let mut transport = RoundRecorder::default();
1269        for _ in 0..2 {
1270            client.sync(&mut transport);
1271            let attempt = client.progress().snapshot().unwrap().attempt;
1272            assert_eq!(transport.sync_round, Some(Some(attempt)));
1273            assert_eq!(transport.scoped.last(), Some(&None));
1274        }
1275        assert_ne!(
1276            transport.scoped[0],
1277            transport.scoped[transport.scoped.len() - 2]
1278        );
1279    }
1280
1281    /// Records each single fetch the default batch runs and fails the second.
1282    #[derive(Default)]
1283    struct CountingFetches {
1284        calls: Vec<String>,
1285    }
1286
1287    impl Transport for CountingFetches {
1288        fn sync(&mut self, _: &[u8]) -> Result<Vec<u8>, TransportError> {
1289            unreachable!()
1290        }
1291        fn realtime_sync(&mut self, _: &[u8]) -> Result<Vec<u8>, TransportError> {
1292            unreachable!()
1293        }
1294        fn download_segment(
1295            &mut self,
1296            request: &SegmentRequest,
1297            on_progress: &mut dyn FnMut(u64),
1298        ) -> Result<Vec<u8>, TransportError> {
1299            self.calls.push(request.segment_id.clone());
1300            on_progress(4);
1301            if request.segment_id == "sha256:b" {
1302                Err(TransportError::new(
1303                    "transport.timeout",
1304                    "second fetch failed",
1305                ))
1306            } else {
1307                Ok(request.segment_id.clone().into_bytes())
1308            }
1309        }
1310        fn realtime_connect(&mut self, _client_id: &str) -> Result<(), TransportError> {
1311            Ok(())
1312        }
1313        fn realtime_send(&mut self, _: &str) -> Result<(), TransportError> {
1314            Ok(())
1315        }
1316        fn realtime_close(&mut self) -> Result<(), TransportError> {
1317            Ok(())
1318        }
1319    }
1320
1321    #[test]
1322    fn the_default_batch_runs_the_single_fetches_in_order_and_stops_at_the_first_error() {
1323        let mut transport = CountingFetches::default();
1324        let fetches: Vec<SegmentFetch> = ["a", "b", "c"]
1325            .into_iter()
1326            .map(|id| {
1327                SegmentFetch::Direct(SegmentRequest {
1328                    segment_id: format!("sha256:{id}"),
1329                    table: "tasks".to_owned(),
1330                    requested_scopes_json: "{}".to_owned(),
1331                    byte_length: 4,
1332                })
1333            })
1334            .collect();
1335        let mut reported = Vec::new();
1336        let results = transport.download_segments(&fetches, &mut |index, bytes| {
1337            reported.push((index, bytes));
1338        });
1339        assert_eq!(
1340            transport.calls,
1341            vec!["sha256:a", "sha256:b"],
1342            "the third fetch was never attempted"
1343        );
1344        assert_eq!(results.len(), 2, "one result per attempted fetch");
1345        assert_eq!(results[0].as_ref().unwrap(), b"sha256:a");
1346        assert_eq!(results[1].as_ref().unwrap_err().code, "transport.timeout");
1347        assert_eq!(reported, vec![(0, 4), (1, 4)]);
1348    }
1349}