Skip to main content

syncular_client/
native_transport.rs

1//! Shared native host transport for every Rust-backed Syncular binding.
2//!
3//! Two shapes behind one `HostTransport`:
4//!
5//! - `Null` (the dependency-lean default build): every network op fails loudly
6//!   with `transport.unavailable`. Client-local commands (create, subscribe,
7//!   mutate, readRows, conflicts, …) still run — enough for the C smoke test
8//!   and pure-logic tests, with zero HTTP/WS dependency compiled in.
9//! - `Native` (the `native-transport` feature): a real HTTP + WS client the
10//!   core drives itself, because a native app has no host loop to invert
11//!   transport into (unlike the conformance shim). `ureq` for blocking HTTP,
12//!   `tungstenite` for the WS socket; a reader thread buffers inbound frames.
13//!
14//! - `Local` (the `local-authority` feature, a `localAuthorityPath` config):
15//!   §12.4 routing over either shape above. Sync rounds reach the in-process
16//!   local authority until attach completes, then the remote transport.
17//!
18//! Inbound realtime frames land in a shared queue the host drains after each
19//! command. An optional wake callback lets mailbox-driven hosts react without
20//! polling. The queue is bounded by [`INBOUND_BUFFER_LIMIT_BYTES`]. The socket implementation is deliberately singular: fairness and
21//! wire fixes therefore reach FFI, Tauri, and future Rust hosts together.
22
23use std::sync::atomic::{AtomicU64, Ordering};
24use std::sync::{mpsc, Arc, Condvar, Mutex};
25use std::time::{Duration, SystemTime};
26
27use crate::{
28    BlobDownload, BlobUploadGrant, SegmentFetch, SegmentRequest, Transport, TransportError,
29};
30
31/// Redirect handling for native HTTP requests and the WebSocket handshake.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
33pub enum RedirectPolicy {
34    /// Never follow a 3xx. A redirected request would replay host
35    /// headers, URL userinfo, or a signed capability to an unverified
36    /// destination, so refusal is the default. A refused redirect surfaces
37    /// `transport.redirect`.
38    #[default]
39    Deny,
40    /// Follow a redirect for a request that carries neither host
41    /// headers, base-URL userinfo, nor a signed capability URL. A
42    /// credential-bearing request is still refused even under this policy,
43    /// because ureq forwards host headers and URL userinfo to the
44    /// redirect target, and tungstenite forwards host headers to a
45    /// WebSocket redirect target. A WebSocket handshake additionally may not
46    /// follow a redirect when its realtime URL carries userinfo or a query
47    /// (a signed capability). Enable only for a deployment whose
48    /// unauthenticated requests may safely move.
49    Follow,
50}
51
52/// Bounds and behavior for the native host transport. `Default` matches the
53/// reference HTTP binding: no deadline and no body cap, with redirects denied.
54#[derive(Debug, Clone, Default)]
55pub struct HostTransportPolicy {
56    /// End-to-end deadline for one request (DNS through response body).
57    pub request_timeout: Option<Duration>,
58    /// One monotonic deadline for a whole sync round: uploads, continuations,
59    /// the main request, and every segment fetch. Anchored once on the round's
60    /// first network call; a continuation never resets it. Independent of the
61    /// per-request deadline, which still bounds each individual call.
62    pub round_deadline: Option<Duration>,
63    /// Largest HTTP request body the transport will send. Checked before any
64    /// network I/O. Does not cap realtime socket buffers.
65    pub max_request_bytes: Option<u64>,
66    /// Largest decoded (post-decompression) HTTP response body the transport
67    /// will accept. Does not cap realtime socket buffers.
68    pub max_response_bytes: Option<u64>,
69    pub redirects: RedirectPolicy,
70    /// The server's §8.5 heartbeat interval; `None` is the suggested 30 s. An
71    /// established realtime socket that receives no frame for twice the
72    /// interval is lost.
73    pub realtime_heartbeat: Option<Duration>,
74}
75
76impl HostTransportPolicy {
77    /// Reject a bound the transport cannot honor: a zero or unrepresentable
78    /// duration, or a zero byte limit. Called on both the JSON and the
79    /// programmatic path, so `Follow`/`Deny` and every numeric field agree.
80    pub fn validate(&self) -> Result<(), String> {
81        let now = std::time::Instant::now();
82        if let Some(timeout) = self.request_timeout {
83            if timeout.is_zero() || now.checked_add(timeout).is_none() {
84                return Err(
85                    "sync.invalid_request: transport config requestTimeoutMs is out of range"
86                        .to_owned(),
87                );
88            }
89        }
90        if let Some(deadline) = self.round_deadline {
91            if deadline.is_zero() || now.checked_add(deadline).is_none() {
92                return Err(
93                    "sync.invalid_request: transport config roundDeadlineMs is out of range"
94                        .to_owned(),
95                );
96            }
97        }
98        if let Some(interval) = self.realtime_heartbeat {
99            if interval.is_zero()
100                || interval
101                    .checked_mul(2)
102                    .and_then(|silence| now.checked_add(silence))
103                    .is_none()
104            {
105                return Err(
106                    "sync.invalid_request: transport config realtimeHeartbeatMs is out of range"
107                        .to_owned(),
108                );
109            }
110        }
111        if self.max_request_bytes == Some(0) {
112            return Err(
113                "sync.invalid_request: transport config maxRequestBytes must be a positive integer"
114                    .to_owned(),
115            );
116        }
117        if self.max_response_bytes == Some(0) {
118            return Err("sync.invalid_request: transport config maxResponseBytes must be a positive integer".to_owned());
119        }
120        Ok(())
121    }
122
123    /// Parse the policy from the transport JSON config. Absent keys keep their
124    /// defaults; a wrong type or an out-of-range bound is rejected loudly.
125    pub fn from_config(config: &serde_json::Value) -> Result<Self, String> {
126        let bound = |key: &str, message: &'static str| -> Result<Option<u64>, String> {
127            match config.get(key) {
128                None | Some(serde_json::Value::Null) => Ok(None),
129                Some(value) => match value.as_u64() {
130                    Some(number) if number >= 1 => Ok(Some(number)),
131                    _ => Err(message.to_owned()),
132                },
133            }
134        };
135        let redirects = match config.get("redirects") {
136            None | Some(serde_json::Value::Null) => RedirectPolicy::Deny,
137            Some(serde_json::Value::String(value)) if value == "deny" => RedirectPolicy::Deny,
138            Some(serde_json::Value::String(value)) if value == "follow" => RedirectPolicy::Follow,
139            Some(_) => return Err(
140                "sync.invalid_request: transport config redirects must be \"deny\" or \"follow\""
141                    .to_owned(),
142            ),
143        };
144        let policy = Self {
145            request_timeout: bound(
146                "requestTimeoutMs",
147                "sync.invalid_request: transport config requestTimeoutMs must be a positive integer",
148            )?
149            .map(Duration::from_millis),
150            round_deadline: bound(
151                "roundDeadlineMs",
152                "sync.invalid_request: transport config roundDeadlineMs must be a positive integer",
153            )?
154            .map(Duration::from_millis),
155            max_request_bytes: bound(
156                "maxRequestBytes",
157                "sync.invalid_request: transport config maxRequestBytes must be a positive integer",
158            )?,
159            max_response_bytes: bound(
160                "maxResponseBytes",
161                "sync.invalid_request: transport config maxResponseBytes must be a positive integer",
162            )?,
163            redirects,
164            realtime_heartbeat: bound(
165                "realtimeHeartbeatMs",
166                "sync.invalid_request: transport config realtimeHeartbeatMs must be a positive integer",
167            )?
168            .map(Duration::from_millis),
169        };
170        policy.validate()?;
171        Ok(policy)
172    }
173}
174
175/// What a host-authenticated request is for, as a header source sees it.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
177pub enum HeaderTarget {
178    /// `POST /sync` and remote operations.
179    Sync,
180    /// `GET /segments/{id}`.
181    Segment,
182    /// The blob endpoints: upload, download and upload grant.
183    Blob,
184    /// The realtime WebSocket handshake.
185    Realtime,
186}
187
188impl HeaderTarget {
189    /// The wire name hosts receive: `sync`, `segment`, `blob`, `realtime`.
190    pub fn as_str(self) -> &'static str {
191        match self {
192            Self::Sync => "sync",
193            Self::Segment => "segment",
194            Self::Blob => "blob",
195            Self::Realtime => "realtime",
196        }
197    }
198}
199
200/// The request a header source answers for. `round` is the progress
201/// `attempt` of the sync round the request belongs to, and `None` outside a
202/// round (an app-initiated blob transfer, a realtime connect, a remote
203/// operation). `client_id` is empty before the client is created.
204#[derive(Debug, Clone, PartialEq, Eq, Hash)]
205pub struct HeaderContext {
206    pub client_id: String,
207    pub round: Option<u64>,
208    pub target: HeaderTarget,
209}
210
211type HeaderRead = dyn Fn(&HeaderContext, Option<&[(String, String)]>) -> Result<Vec<(String, String)>, TransportError>
212    + Send
213    + Sync;
214
215/// Where a Rust host transport reads its request headers (auth, actor and
216/// project ids, per-round trace headers). The transport calls it before every
217/// host-authenticated HTTP request and every realtime handshake; a signed URL
218/// never carries them. It receives the request's [`HeaderContext`] and `None`
219/// for an ordinary read, or the headers the server just answered 401 to for a
220/// refresh. A source that answers `None` has no headers to give, and the
221/// request fails with the retryable `sync.auth_required`
222/// (`causeKind: "header_source"`) before any network I/O.
223///
224/// Concurrent reads of one client and round share one in-flight call, with
225/// the first reader's context. Ordinary reads and refreshes fly separately,
226/// so a refresh never joins an ordinary read of the refused headers, and
227/// different rounds or clients never share a call. Clones share the flights.
228#[derive(Clone)]
229pub struct HeaderSource(Arc<HeaderFlights>);
230
231/// A flight key: client id, round, and whether the read is a refresh.
232type FlightKey = (String, Option<u64>, bool);
233
234struct HeaderFlights {
235    read: Box<HeaderRead>,
236    /// Running flights, and landed ones whose joined readers have yet to
237    /// collect the outcome.
238    state: Mutex<std::collections::HashMap<FlightKey, HeaderFlight>>,
239    landed: Condvar,
240}
241
242#[derive(Default)]
243struct HeaderFlight {
244    running: bool,
245    landings: u64,
246    /// Readers waiting for the running call to land.
247    joined: usize,
248    /// The outcome of the last call that landed.
249    outcome: Option<Result<Vec<(String, String)>, TransportError>>,
250}
251
252fn header_source_error() -> TransportError {
253    let mut error = TransportError::new(
254        "sync.auth_required",
255        "the host header source gave no headers",
256    );
257    error.details = Some(serde_json::json!({ "causeKind": "header_source" }));
258    error
259}
260
261impl std::fmt::Debug for HeaderSource {
262    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
263        f.write_str("HeaderSource")
264    }
265}
266
267impl HeaderSource {
268    pub fn new(
269        read: impl Fn(&HeaderContext, Option<&[(String, String)]>) -> Option<Vec<(String, String)>>
270            + Send
271            + Sync
272            + 'static,
273    ) -> Self {
274        Self::from_read(Box::new(move |context, rejected| {
275            read(context, rejected).ok_or_else(header_source_error)
276        }))
277    }
278
279    fn from_read(read: Box<HeaderRead>) -> Self {
280        Self(Arc::new(HeaderFlights {
281            read,
282            state: Mutex::default(),
283            landed: Condvar::new(),
284        }))
285    }
286
287    /// Read the headers for one request, joining the flight of the same
288    /// client, round and kind when one is in progress.
289    pub fn read(
290        &self,
291        context: &HeaderContext,
292        rejected: Option<&[(String, String)]>,
293    ) -> Result<Vec<(String, String)>, TransportError> {
294        let flights = &self.0;
295        let key = (context.client_id.clone(), context.round, rejected.is_some());
296        let mut state = flights.state.lock().expect("header source lock");
297        let flight = state.entry(key.clone()).or_default();
298        if flight.running {
299            let landing = flight.landings;
300            flight.joined += 1;
301            while state[&key].landings == landing {
302                state = flights.landed.wait(state).expect("header source wait");
303            }
304            let flight = state.get_mut(&key).expect("a joined flight stays");
305            flight.joined -= 1;
306            let outcome = flight
307                .outcome
308                .clone()
309                .expect("a landed flight has an outcome");
310            if flight.joined == 0 && !flight.running {
311                state.remove(&key);
312            }
313            return outcome;
314        }
315        flight.running = true;
316        drop(state);
317        // A panicking source still lands its flight, so joined readers wake
318        // before the panic resumes on this thread.
319        let read = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
320            (flights.read)(context, rejected)
321        }));
322        let outcome = match &read {
323            Ok(outcome) => outcome.clone(),
324            Err(_) => Err(header_source_error()),
325        };
326        let mut state = flights.state.lock().expect("header source lock");
327        let flight = state.get_mut(&key).expect("a running flight stays");
328        flight.running = false;
329        if flight.joined == 0 {
330            state.remove(&key);
331        } else {
332            flight.landings += 1;
333            flight.outcome = Some(outcome.clone());
334            flights.landed.notify_all();
335        }
336        drop(state);
337        if let Err(panic) = read {
338            std::panic::resume_unwind(panic);
339        }
340        outcome
341    }
342
343    /// Run one host-authenticated request with this source's headers. A
344    /// refusal carrying `details.httpStatus` 401 reads the source again, in
345    /// the same context, with the refused headers and resends once; a second
346    /// 401 surfaces.
347    pub fn authenticated<T>(
348        &self,
349        context: &HeaderContext,
350        mut send: impl FnMut(&[(String, String)]) -> Result<T, TransportError>,
351    ) -> Result<T, TransportError> {
352        let headers = self.read(context, None)?;
353        match send(&headers) {
354            Err(error)
355                if error
356                    .details
357                    .as_ref()
358                    .and_then(|details| details.get("httpStatus"))
359                    .and_then(serde_json::Value::as_u64)
360                    == Some(401) =>
361            {
362                send(&self.read(context, Some(&headers))?)
363            }
364            result => result,
365        }
366    }
367}
368
369/// How long a [`HeaderQuestions`] source waits for the host's answer. Past
370/// it the request fails with the retryable `sync.auth_required`
371/// (`causeKind: "header_source"`), and a late answer is ignored.
372pub const HEADER_ANSWER_WAIT_MS: i64 = 30_000;
373
374type HeaderAsk = dyn Fn(u64, &HeaderContext, Option<&[(String, String)]>) + Send + Sync;
375
376/// The header source of a host that answers over a pull channel (the FFI
377/// event queue, the conformance shim's stdio). Each read asks the host one
378/// question under a fresh request id and blocks until [`Self::provide`]
379/// answers it, [`HEADER_ANSWER_WAIT_MS`] pass on the clock, or
380/// [`Self::close`] runs. `clock` is monotonic milliseconds; a waiter
381/// re-checks it on every answer, every [`Self::recheck`], and at its
382/// deadline in real time.
383pub struct HeaderQuestions {
384    ask: Box<HeaderAsk>,
385    clock: Box<dyn Fn() -> i64 + Send + Sync>,
386    state: Mutex<QuestionState>,
387    answered: Condvar,
388}
389
390/// A host's answer: headers, or `None` when it has none.
391type HeaderAnswer = Option<Vec<(String, String)>>;
392
393#[derive(Default)]
394struct QuestionState {
395    next_id: u64,
396    /// Open questions by id: the deadline, and `Some` once answered
397    /// (`Some(None)`: the host has no headers).
398    open: std::collections::HashMap<u64, (i64, Option<HeaderAnswer>)>,
399    closed: bool,
400}
401
402impl HeaderQuestions {
403    pub fn new(
404        ask: impl Fn(u64, &HeaderContext, Option<&[(String, String)]>) + Send + Sync + 'static,
405        clock: impl Fn() -> i64 + Send + Sync + 'static,
406    ) -> Arc<Self> {
407        Arc::new(Self {
408            ask: Box::new(ask),
409            clock: Box::new(clock),
410            state: Mutex::default(),
411            answered: Condvar::new(),
412        })
413    }
414
415    /// The header source whose reads ask these questions.
416    pub fn source(self: &Arc<Self>) -> HeaderSource {
417        let questions = Arc::clone(self);
418        HeaderSource::from_read(Box::new(move |context, rejected| {
419            let mut state = questions.state.lock().expect("header questions lock");
420            if state.closed {
421                return Err(TransportError::new(
422                    "client.closed",
423                    "the client closed while the transport waited for headers",
424                ));
425            }
426            state.next_id += 1;
427            let id = state.next_id;
428            let deadline = (questions.clock)().saturating_add(HEADER_ANSWER_WAIT_MS);
429            state.open.insert(id, (deadline, None));
430            // Ask outside the lock: a host channel may call `is_open` while it
431            // holds its own lock, so this lock is never taken inside the ask.
432            drop(state);
433            (questions.ask)(id, context, rejected);
434            state = questions.state.lock().expect("header questions lock");
435            loop {
436                if state.closed {
437                    state.open.remove(&id);
438                    return Err(TransportError::new(
439                        "client.closed",
440                        "the client closed while the transport waited for headers",
441                    ));
442                }
443                if let Some((_, Some(_))) = state.open.get(&id) {
444                    let answer = state
445                        .open
446                        .remove(&id)
447                        .and_then(|(_, answer)| answer)
448                        .flatten();
449                    return answer.ok_or_else(header_source_error);
450                }
451                let now = (questions.clock)();
452                if now >= deadline {
453                    state.open.remove(&id);
454                    return Err(header_source_error());
455                }
456                state = questions
457                    .answered
458                    .wait_timeout(state, Duration::from_millis((deadline - now) as u64))
459                    .expect("header questions wait")
460                    .0;
461            }
462        }))
463    }
464
465    /// Answer question `id` with `headers`: an object of string values, or
466    /// `null` when the host cannot produce headers. An answer to an unknown
467    /// or expired id is ignored.
468    pub fn provide(&self, id: u64, headers: &serde_json::Value) -> Result<(), TransportError> {
469        let invalid = || {
470            TransportError::new(
471                "sync.invalid_request",
472                "provided headers must be an object of string values or null",
473            )
474        };
475        let headers = match headers {
476            serde_json::Value::Null => None,
477            serde_json::Value::Object(map) => Some(
478                map.iter()
479                    .map(|(name, value)| {
480                        value
481                            .as_str()
482                            .map(|value| (name.clone(), value.to_owned()))
483                            .ok_or_else(invalid)
484                    })
485                    .collect::<Result<Vec<_>, _>>()?,
486            ),
487            _ => return Err(invalid()),
488        };
489        let mut state = self.state.lock().expect("header questions lock");
490        if let Some((_, slot)) = state.open.get_mut(&id) {
491            *slot = Some(headers);
492            self.answered.notify_all();
493        }
494        Ok(())
495    }
496
497    /// Whether question `id` still waits for an answer: asked, unanswered,
498    /// and within its bound. A host channel skips a question that is not.
499    pub fn is_open(&self, id: u64) -> bool {
500        let now = (self.clock)();
501        let state = self.state.lock().expect("header questions lock");
502        matches!(state.open.get(&id), Some((deadline, None)) if now < *deadline)
503    }
504
505    /// Wake every waiter to re-check its deadline after the clock moved.
506    pub fn recheck(&self) {
507        let _state = self.state.lock().expect("header questions lock");
508        self.answered.notify_all();
509    }
510
511    /// Fail every open question and every later read with `client.closed`.
512    pub fn close(&self) {
513        self.state.lock().expect("header questions lock").closed = true;
514        self.answered.notify_all();
515    }
516}
517
518/// One inbound realtime frame buffered for the client's `on_realtime_*`.
519pub enum Inbound {
520    Text(String),
521    Binary(Vec<u8>),
522    /// The realtime connection ended without the host closing it (the peer closed an idle socket, a read or write failed, or a
523    /// send was abandoned). Pushed before any round or send waiter is woken, so the host drains it before it reconnects.
524    Disconnected(TransportError),
525}
526
527/// Metadata for one received WebSocket message. The byte count includes the
528/// Syncular channel tag for binary messages, but excludes WebSocket headers.
529#[derive(Debug, Clone, Copy, PartialEq, Eq)]
530pub struct RealtimeReceipt {
531    pub received_at: SystemTime,
532    pub bytes: usize,
533    pub kind: RealtimeReceiptKind,
534}
535
536#[derive(Debug, Clone, Copy, PartialEq, Eq)]
537pub enum RealtimeReceiptKind {
538    Text,
539    Delta,
540    Round,
541    OtherBinary,
542    Ping,
543    Pong,
544    Close,
545}
546
547/// Text and delta payload bytes the inbound buffer holds before the reader
548/// ends the connection (§8.8). Deltas are a latency path: the loss schedules a
549/// reconnect and a catch-up pull, so a host that drains late converges.
550pub const INBOUND_BUFFER_LIMIT_BYTES: usize = 16 * 1024 * 1024;
551
552/// Buffered inbound frames and their text/delta payload size.
553#[derive(Default)]
554struct InboundFrames {
555    list: Vec<Inbound>,
556    bytes: usize,
557}
558
559/// The shared inbound buffer the WS reader thread fills and the command path
560/// drains. The optional callback carries no data; it only wakes an owning
561/// mailbox so the host can drain the buffer promptly.
562pub struct InboundBuffer {
563    frames: Mutex<InboundFrames>,
564    notify: Option<Arc<dyn Fn() + Send + Sync>>,
565    receipts: Mutex<Option<mpsc::SyncSender<RealtimeReceipt>>>,
566    dropped_receipts: AtomicU64,
567}
568
569impl Default for InboundBuffer {
570    fn default() -> Self {
571        Self {
572            frames: Mutex::new(InboundFrames::default()),
573            notify: None,
574            receipts: Mutex::new(None),
575            dropped_receipts: AtomicU64::new(0),
576        }
577    }
578}
579
580impl InboundBuffer {
581    pub fn with_notify(notify: Arc<dyn Fn() + Send + Sync>) -> Self {
582        Self {
583            frames: Mutex::new(InboundFrames::default()),
584            notify: Some(notify),
585            receipts: Mutex::new(None),
586            dropped_receipts: AtomicU64::new(0),
587        }
588    }
589
590    pub fn push(&self, frame: Inbound) {
591        {
592            let mut frames = self.frames.lock().expect("inbound lock");
593            frames.bytes += match &frame {
594                Inbound::Text(text) => text.len(),
595                Inbound::Binary(bytes) => bytes.len(),
596                Inbound::Disconnected(_) => 0,
597            };
598            frames.list.push(frame);
599        }
600        if let Some(notify) = &self.notify {
601            notify();
602        }
603    }
604
605    fn take(&self) -> Vec<Inbound> {
606        std::mem::take(&mut *self.frames.lock().expect("inbound lock")).list
607    }
608
609    /// Whether the undrained frames exceed [`INBOUND_BUFFER_LIMIT_BYTES`].
610    #[cfg(feature = "native-transport")]
611    fn overflowed(&self) -> bool {
612        self.frames.lock().expect("inbound lock").bytes > INBOUND_BUFFER_LIMIT_BYTES
613    }
614
615    #[cfg(feature = "native-transport")]
616    fn observe(&self, kind: RealtimeReceiptKind, bytes: usize) {
617        if let Some(sender) = self.receipts.lock().expect("receipt lock").as_ref() {
618            let receipt = RealtimeReceipt {
619                received_at: SystemTime::now(),
620                bytes,
621                kind,
622            };
623            if sender.try_send(receipt).is_err() {
624                self.dropped_receipts.fetch_add(1, Ordering::Relaxed);
625            }
626        }
627    }
628}
629
630// One transport is held per host, so the native arm's size is not worth an
631// indirection; boxing it would change the public variant's payload type.
632#[allow(clippy::large_enum_variant)]
633pub enum HostTransport {
634    /// No network: client-local commands only (dependency-lean default).
635    Null {
636        signed_urls: bool,
637        inbound: Arc<InboundBuffer>,
638    },
639    #[cfg(feature = "native-transport")]
640    Native(native::NativeTransport),
641    /// §12 local authority in front of the `Null` or `Native` remote.
642    #[cfg(feature = "local-authority")]
643    Local(Box<LocalAuthorityTransport<HostTransport>>),
644}
645
646impl HostTransport {
647    /// Build the transport from the `new` config. `{}` (or no `baseUrl`) →
648    /// `Null`; a `baseUrl` under the `native-transport` feature → `Native`.
649    pub fn from_config(config: &serde_json::Value) -> Result<Self, String> {
650        Self::from_config_with_notify(config, None)
651    }
652
653    /// Build a transport whose realtime reader wakes a mailbox/event loop.
654    /// The callback is invoked after a frame is buffered and never carries
655    /// protocol data itself.
656    pub fn from_config_with_notify(
657        config: &serde_json::Value,
658        notify: Option<Arc<dyn Fn() + Send + Sync>>,
659    ) -> Result<Self, String> {
660        let policy = HostTransportPolicy::from_config(config)?;
661        Self::from_config_with_policy(config, policy, notify)
662    }
663
664    /// Build the transport with an explicit programmatic policy, ignoring any
665    /// policy keys the JSON config carries. `baseUrl` selection is unchanged;
666    /// a `localAuthorityPath` puts the §12 local authority in front of it.
667    pub fn from_config_with_policy(
668        config: &serde_json::Value,
669        policy: HostTransportPolicy,
670        notify: Option<Arc<dyn Fn() + Send + Sync>>,
671    ) -> Result<Self, String> {
672        // Static headers expire while the transport keeps sending them; the
673        // host answers the transport's header source instead.
674        if config.get("headers").is_some() {
675            return Err(
676                "sync.invalid_request: transport config headers is not supported; install a header source"
677                    .to_owned(),
678            );
679        }
680        let local_authority_path = match config.get("localAuthorityPath") {
681            None | Some(serde_json::Value::Null) => None,
682            Some(serde_json::Value::String(path)) if !path.is_empty() => Some(path.clone()),
683            Some(_) => return Err("localAuthorityPath must be a non-empty string".to_owned()),
684        };
685        #[cfg(not(feature = "local-authority"))]
686        if local_authority_path.is_some() {
687            return Err(format!(
688                "{}: this build has no local authority (rebuild with --features local-authority)",
689                crate::LOCAL_AUTHORITY_UNCONFIGURED_CODE
690            ));
691        }
692        let remote = match config.get("baseUrl").and_then(|v| v.as_str()) {
693            #[cfg(feature = "native-transport")]
694            Some(base_url) => HostTransport::Native(native::NativeTransport::with_policy(
695                base_url, config, policy, notify,
696            )?),
697            _ => {
698                #[cfg(not(feature = "native-transport"))]
699                {
700                    policy.validate()?;
701                    if config.get("baseUrl").is_some() {
702                        return Err(
703                            "this build has no native transport (rebuild with --features native-transport)"
704                                .to_owned(),
705                        );
706                    }
707                }
708                HostTransport::Null {
709                    signed_urls: false,
710                    inbound: Arc::new(match notify {
711                        Some(notify) => InboundBuffer::with_notify(notify),
712                        None => InboundBuffer::default(),
713                    }),
714                }
715            }
716        };
717        #[cfg(feature = "local-authority")]
718        if let Some(path) = local_authority_path {
719            let remote_configured = !matches!(remote, HostTransport::Null { .. });
720            return Ok(HostTransport::Local(Box::new(
721                LocalAuthorityTransport::new(path, remote, remote_configured),
722            )));
723        }
724        Ok(remote)
725    }
726
727    /// Network view for one I/O executor. The mutable owner keeps the reader
728    /// and inbound queue; no SQLite state or new socket is created.
729    pub fn fork_round(&self) -> Self {
730        match self {
731            Self::Null {
732                signed_urls,
733                inbound,
734            } => Self::Null {
735                signed_urls: *signed_urls,
736                inbound: inbound.clone(),
737            },
738            #[cfg(feature = "native-transport")]
739            Self::Native(t) => Self::Native(t.fork_round()),
740            #[cfg(feature = "local-authority")]
741            Self::Local(t) => Self::Local(Box::new(t.fork_round())),
742        }
743    }
744
745    pub fn set_signed_urls(&mut self, value: bool) {
746        match self {
747            HostTransport::Null { signed_urls, .. } => *signed_urls = value,
748            #[cfg(feature = "native-transport")]
749            HostTransport::Native(t) => t.signed_urls = value,
750            #[cfg(feature = "local-authority")]
751            HostTransport::Local(t) => t.remote.set_signed_urls(value),
752        }
753    }
754
755    /// Install the host's header source. Every later host-authenticated HTTP
756    /// request and realtime handshake reads it; round forks share it. A live
757    /// socket keeps the headers of its handshake.
758    pub fn set_header_source(&mut self, source: HeaderSource) {
759        match self {
760            HostTransport::Null { .. } => drop(source),
761            #[cfg(feature = "native-transport")]
762            HostTransport::Native(t) => t.headers = Some(source),
763            #[cfg(feature = "local-authority")]
764            HostTransport::Local(t) => t.remote.set_header_source(source),
765        }
766    }
767
768    /// Replace the transport's bounds for subsequent network calls. A round
769    /// past its first exchange keeps its anchored deadline; every other bound
770    /// takes effect on the next call. An invalid policy is rejected and the
771    /// current policy stays in force.
772    pub fn set_policy(&mut self, policy: HostTransportPolicy) -> Result<(), String> {
773        policy.validate()?;
774        match self {
775            HostTransport::Null { .. } => {}
776            #[cfg(feature = "native-transport")]
777            HostTransport::Native(t) => t.set_policy(policy)?,
778            #[cfg(feature = "local-authority")]
779            HostTransport::Local(t) => t.remote.set_policy(policy)?,
780        }
781        Ok(())
782    }
783
784    /// Drain the inbound realtime frames buffered since the last call.
785    pub fn take_inbound(&mut self) -> Vec<Inbound> {
786        match self {
787            HostTransport::Null { inbound, .. } => inbound.take(),
788            #[cfg(feature = "native-transport")]
789            HostTransport::Native(t) => t.inbound.take(),
790            #[cfg(feature = "local-authority")]
791            HostTransport::Local(t) => t.remote.take_inbound(),
792        }
793    }
794
795    /// Observe received WebSocket messages without blocking the socket reader.
796    /// Supply a bounded `sync_channel` and drain it on a separate thread. The
797    /// observer is shared by round forks and survives reconnects. Replacing it
798    /// resets the dropped-receipt count.
799    pub fn set_realtime_receipt_observer(
800        &mut self,
801        sender: Option<mpsc::SyncSender<RealtimeReceipt>>,
802    ) {
803        let inbound = match self {
804            HostTransport::Null { inbound, .. } => inbound,
805            #[cfg(feature = "native-transport")]
806            HostTransport::Native(t) => &t.inbound,
807            #[cfg(feature = "local-authority")]
808            HostTransport::Local(t) => {
809                t.remote.set_realtime_receipt_observer(sender);
810                return;
811            }
812        };
813        let mut current = inbound.receipts.lock().expect("receipt lock");
814        *current = sender;
815        inbound.dropped_receipts.store(0, Ordering::Relaxed);
816    }
817
818    /// Return and clear the number of receipts lost to a full or closed channel.
819    pub fn take_dropped_realtime_receipts(&mut self) -> u64 {
820        let inbound = match self {
821            HostTransport::Null { inbound, .. } => inbound,
822            #[cfg(feature = "native-transport")]
823            HostTransport::Native(t) => &t.inbound,
824            #[cfg(feature = "local-authority")]
825            HostTransport::Local(t) => return t.remote.take_dropped_realtime_receipts(),
826        };
827        inbound.dropped_receipts.swap(0, Ordering::Relaxed)
828    }
829
830    /// Release the socket/reader thread and close the local authority.
831    /// Idempotent.
832    pub fn shutdown(&mut self) {
833        match self {
834            HostTransport::Null { .. } => {}
835            #[cfg(feature = "native-transport")]
836            HostTransport::Native(t) => t.shutdown(),
837            #[cfg(feature = "local-authority")]
838            HostTransport::Local(t) => t.shutdown(),
839        }
840    }
841}
842
843fn unavailable(op: &str) -> TransportError {
844    TransportError::new(
845        "transport.unavailable",
846        format!("{op} needs the native transport (build with --features native-transport)"),
847    )
848}
849
850// Without the native transport the `Null` arm ignores every request payload;
851// the params are only consumed by the feature-gated `Native` arm.
852#[cfg_attr(not(feature = "native-transport"), allow(unused_variables))]
853impl Transport for HostTransport {
854    fn sync(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
855        match self {
856            HostTransport::Null { .. } => Err(unavailable("sync")),
857            #[cfg(feature = "native-transport")]
858            HostTransport::Native(t) => t.sync(request),
859            #[cfg(feature = "local-authority")]
860            HostTransport::Local(t) => t.sync(request),
861        }
862    }
863
864    fn remote_operation(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
865        match self {
866            HostTransport::Null { .. } => Err(unavailable("remoteOperation")),
867            #[cfg(feature = "native-transport")]
868            HostTransport::Native(t) => t.remote_operation(request),
869            #[cfg(feature = "local-authority")]
870            HostTransport::Local(t) => t.remote_operation(request),
871        }
872    }
873
874    fn realtime_sync(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
875        match self {
876            HostTransport::Null { .. } => Err(unavailable("realtimeSync")),
877            #[cfg(feature = "native-transport")]
878            HostTransport::Native(t) => t.realtime_sync(request),
879            #[cfg(feature = "local-authority")]
880            HostTransport::Local(t) => t.realtime_sync(request),
881        }
882    }
883
884    fn download_segment(
885        &mut self,
886        request: &SegmentRequest,
887        on_progress: &mut dyn FnMut(u64),
888    ) -> Result<Vec<u8>, TransportError> {
889        match self {
890            HostTransport::Null { .. } => Err(unavailable("downloadSegment")),
891            #[cfg(feature = "native-transport")]
892            HostTransport::Native(t) => t.download_segment(request, on_progress),
893            #[cfg(feature = "local-authority")]
894            HostTransport::Local(t) => t.download_segment(request, on_progress),
895        }
896    }
897
898    fn supports_url_fetch(&self) -> bool {
899        match self {
900            HostTransport::Null { signed_urls, .. } => *signed_urls,
901            #[cfg(feature = "native-transport")]
902            HostTransport::Native(t) => t.signed_urls,
903            #[cfg(feature = "local-authority")]
904            HostTransport::Local(t) => t.supports_url_fetch(),
905        }
906    }
907
908    fn download_segments(
909        &mut self,
910        fetches: &[SegmentFetch],
911        on_progress: &mut (dyn FnMut(usize, u64) + Send),
912    ) -> Vec<Result<Vec<u8>, TransportError>> {
913        match self {
914            HostTransport::Null { .. } => fetches
915                .first()
916                .map(|_| Err(unavailable("downloadSegments")))
917                .into_iter()
918                .collect(),
919            #[cfg(feature = "native-transport")]
920            HostTransport::Native(t) => t.download_segments(fetches, on_progress),
921            #[cfg(feature = "local-authority")]
922            HostTransport::Local(t) => t.download_segments(fetches, on_progress),
923        }
924    }
925
926    fn fetch_url(
927        &mut self,
928        url: &str,
929        byte_length: u64,
930        on_progress: &mut dyn FnMut(u64),
931    ) -> Result<Vec<u8>, TransportError> {
932        match self {
933            HostTransport::Null { .. } => Err(unavailable("fetchUrl")),
934            #[cfg(feature = "native-transport")]
935            HostTransport::Native(t) => t.fetch_url(url, byte_length, on_progress),
936            #[cfg(feature = "local-authority")]
937            HostTransport::Local(t) => t.fetch_url(url, byte_length, on_progress),
938        }
939    }
940
941    fn blob_upload(
942        &mut self,
943        blob_id: &str,
944        bytes: &[u8],
945        media_type: Option<&str>,
946    ) -> Result<(), TransportError> {
947        match self {
948            HostTransport::Null { .. } => Err(unavailable("blobUpload")),
949            #[cfg(feature = "native-transport")]
950            HostTransport::Native(t) => t.blob_upload(blob_id, bytes, media_type),
951            #[cfg(feature = "local-authority")]
952            HostTransport::Local(t) => t.blob_upload(blob_id, bytes, media_type),
953        }
954    }
955
956    fn blob_download(
957        &mut self,
958        blob_id: &str,
959        byte_length: Option<u64>,
960    ) -> Result<BlobDownload, TransportError> {
961        match self {
962            HostTransport::Null { .. } => Err(unavailable("blobDownload")),
963            #[cfg(feature = "native-transport")]
964            HostTransport::Native(t) => t.blob_download(blob_id, byte_length),
965            #[cfg(feature = "local-authority")]
966            HostTransport::Local(t) => t.blob_download(blob_id, byte_length),
967        }
968    }
969
970    fn fetch_blob_url(
971        &mut self,
972        url: &str,
973        byte_length: Option<u64>,
974    ) -> Result<Vec<u8>, TransportError> {
975        match self {
976            HostTransport::Null { .. } => Err(unavailable("fetchBlobUrl")),
977            #[cfg(feature = "native-transport")]
978            HostTransport::Native(t) => t.fetch_blob_url(url, byte_length),
979            #[cfg(feature = "local-authority")]
980            HostTransport::Local(t) => t.fetch_blob_url(url, byte_length),
981        }
982    }
983
984    fn blob_upload_grant(
985        &mut self,
986        blob_id: &str,
987        byte_length: u64,
988        media_type: Option<&str>,
989    ) -> Result<BlobUploadGrant, TransportError> {
990        match self {
991            // No grant available ⇒ the client streams through the direct
992            // upload endpoint (§5.9.3 capability, not fallback).
993            HostTransport::Null { .. } => Ok(BlobUploadGrant::None),
994            #[cfg(feature = "native-transport")]
995            HostTransport::Native(t) => t.blob_upload_grant(blob_id, byte_length, media_type),
996            #[cfg(feature = "local-authority")]
997            HostTransport::Local(t) => t.blob_upload_grant(blob_id, byte_length, media_type),
998        }
999    }
1000
1001    fn blob_put_url(
1002        &mut self,
1003        blob_id: &str,
1004        url: &str,
1005        bytes: &[u8],
1006        media_type: Option<&str>,
1007    ) -> Result<(), TransportError> {
1008        match self {
1009            HostTransport::Null { .. } => Err(unavailable("blobPutUrl")),
1010            #[cfg(feature = "native-transport")]
1011            HostTransport::Native(t) => t.blob_put_url(blob_id, url, bytes, media_type),
1012            #[cfg(feature = "local-authority")]
1013            HostTransport::Local(t) => t.blob_put_url(blob_id, url, bytes, media_type),
1014        }
1015    }
1016
1017    fn realtime_connect(&mut self, client_id: &str) -> Result<(), TransportError> {
1018        match self {
1019            HostTransport::Null { .. } => Err(unavailable("realtimeConnect")),
1020            #[cfg(feature = "native-transport")]
1021            HostTransport::Native(t) => t.realtime_connect(client_id),
1022            #[cfg(feature = "local-authority")]
1023            HostTransport::Local(t) => t.realtime_connect(client_id),
1024        }
1025    }
1026
1027    fn realtime_send(&mut self, text: &str) -> Result<(), TransportError> {
1028        match self {
1029            HostTransport::Null { .. } => Err(unavailable("realtimeSend")),
1030            #[cfg(feature = "native-transport")]
1031            HostTransport::Native(t) => t.realtime_send(text),
1032            #[cfg(feature = "local-authority")]
1033            HostTransport::Local(t) => t.realtime_send(text),
1034        }
1035    }
1036
1037    fn realtime_close(&mut self) -> Result<(), TransportError> {
1038        match self {
1039            HostTransport::Null { .. } => Ok(()),
1040            #[cfg(feature = "native-transport")]
1041            HostTransport::Native(t) => t.realtime_close(),
1042            #[cfg(feature = "local-authority")]
1043            HostTransport::Local(t) => t.realtime_close(),
1044        }
1045    }
1046
1047    fn round_deadline(&self) -> Option<std::time::Duration> {
1048        match self {
1049            HostTransport::Null { .. } => None,
1050            #[cfg(feature = "native-transport")]
1051            HostTransport::Native(t) => t.round_deadline(),
1052            #[cfg(feature = "local-authority")]
1053            HostTransport::Local(t) => t.round_deadline(),
1054        }
1055    }
1056
1057    fn set_round_deadline(&mut self, deadline: Option<std::time::Instant>) {
1058        match self {
1059            HostTransport::Null { .. } => {}
1060            #[cfg(feature = "native-transport")]
1061            HostTransport::Native(t) => t.set_round_deadline(deadline),
1062            #[cfg(feature = "local-authority")]
1063            HostTransport::Local(t) => t.set_round_deadline(deadline),
1064        }
1065    }
1066
1067    fn set_idle_bound(&mut self, bound: Option<std::time::Duration>) {
1068        match self {
1069            HostTransport::Null { .. } => {}
1070            #[cfg(feature = "native-transport")]
1071            HostTransport::Native(t) => t.set_idle_bound(bound),
1072            #[cfg(feature = "local-authority")]
1073            HostTransport::Local(t) => t.set_idle_bound(bound),
1074        }
1075    }
1076
1077    fn set_client_id(&mut self, client_id: &str) {
1078        match self {
1079            HostTransport::Null { .. } => {}
1080            #[cfg(feature = "native-transport")]
1081            HostTransport::Native(t) => t.set_client_id(client_id),
1082            #[cfg(feature = "local-authority")]
1083            HostTransport::Local(t) => t.set_client_id(client_id),
1084        }
1085    }
1086
1087    fn set_round(&mut self, attempt: Option<u64>) {
1088        match self {
1089            HostTransport::Null { .. } => {}
1090            #[cfg(feature = "native-transport")]
1091            HostTransport::Native(t) => t.set_round(attempt),
1092            #[cfg(feature = "local-authority")]
1093            HostTransport::Local(t) => t.set_round(attempt),
1094        }
1095    }
1096
1097    #[cfg(feature = "local-authority")]
1098    fn open_local_authority(
1099        &mut self,
1100        schema: &serde_json::Value,
1101        replica_path: Option<&str>,
1102    ) -> Result<(), TransportError> {
1103        match self {
1104            HostTransport::Local(t) => t.open_local_authority(schema, replica_path),
1105            _ => Ok(()),
1106        }
1107    }
1108
1109    #[cfg(feature = "local-authority")]
1110    fn local_authority_state(&self) -> Option<&'static str> {
1111        match self {
1112            HostTransport::Local(t) => t.local_authority_state(),
1113            _ => None,
1114        }
1115    }
1116
1117    #[cfg(feature = "local-authority")]
1118    fn attach_local_authority(&mut self) -> Result<(), TransportError> {
1119        match self {
1120            HostTransport::Local(t) => t.attach_local_authority(),
1121            _ => Err(local::unconfigured("this transport has no local authority")),
1122        }
1123    }
1124
1125    #[cfg(feature = "local-authority")]
1126    fn abandon_local_authority_attach(&mut self) -> Result<(), TransportError> {
1127        match self {
1128            HostTransport::Local(t) => t.abandon_local_authority_attach(),
1129            _ => Err(local::unconfigured("this transport has no local authority")),
1130        }
1131    }
1132}
1133
1134#[cfg(feature = "local-authority")]
1135pub use local::LocalAuthorityTransport;
1136
1137#[cfg(feature = "local-authority")]
1138mod local {
1139    //! §12.4 routing: sync rounds reach the in-process local authority until
1140    //! attach completes, then the remote transport. The replica rebinds to the
1141    //! remote server through the §2.1 log-epoch reset, so the client core adds
1142    //! no logic. While the authority serves the client there is no realtime
1143    //! channel and no segment endpoint: the authority delivers bootstrap rows
1144    //! inline (§5.7).
1145
1146    use std::sync::{Arc, Mutex};
1147
1148    use syncular_authority::{AuthorityError, AuthorityState, LocalAuthority};
1149
1150    use super::HostTransport;
1151    use crate::{
1152        BlobDownload, BlobUploadGrant, SegmentFetch, SegmentRequest, Transport, TransportError,
1153        LOCAL_AUTHORITY_UNCONFIGURED_CODE,
1154    };
1155
1156    pub(super) fn unconfigured(message: &'static str) -> TransportError {
1157        TransportError::new(LOCAL_AUTHORITY_UNCONFIGURED_CODE, message)
1158    }
1159
1160    fn transport_error(error: AuthorityError) -> TransportError {
1161        TransportError {
1162            code: error.code,
1163            message: error.message,
1164            details: error.details,
1165        }
1166    }
1167
1168    fn authority_error(error: TransportError) -> AuthorityError {
1169        AuthorityError {
1170            code: error.code,
1171            message: error.message,
1172            details: error.details,
1173        }
1174    }
1175
1176    fn refused(message: &'static str) -> TransportError {
1177        TransportError::new("sync.invalid_request", message)
1178    }
1179
1180    /// The §12 local authority in front of a remote transport `R`.
1181    pub struct LocalAuthorityTransport<R> {
1182        path: String,
1183        /// Opened by `create` with the client's schema. Every round view
1184        /// (`fork_round`) shares it, so attach and rounds serialize on it.
1185        authority: Arc<Mutex<Option<LocalAuthority>>>,
1186        pub(super) remote: R,
1187        /// A remote server is configured (`baseUrl`): attach and abandon
1188        /// need it.
1189        remote_configured: bool,
1190    }
1191
1192    impl<R> LocalAuthorityTransport<R> {
1193        /// `path` is the authority's own SQLite file (`":memory:"` for
1194        /// tests), never the replica's: the client's schema reset drops
1195        /// every replica table outside `_syncular_*`.
1196        pub fn new(path: impl Into<String>, remote: R, remote_configured: bool) -> Self {
1197            Self {
1198                path: path.into(),
1199                authority: Arc::new(Mutex::new(None)),
1200                remote,
1201                remote_configured,
1202            }
1203        }
1204
1205        fn local_active(&self) -> bool {
1206            self.authority
1207                .lock()
1208                .expect("local authority lock")
1209                .as_ref()
1210                .is_none_or(|authority| authority.state() != AuthorityState::Attached)
1211        }
1212    }
1213
1214    impl LocalAuthorityTransport<HostTransport> {
1215        pub(super) fn fork_round(&self) -> Self {
1216            Self {
1217                path: self.path.clone(),
1218                authority: self.authority.clone(),
1219                remote: self.remote.fork_round(),
1220                remote_configured: self.remote_configured,
1221            }
1222        }
1223
1224        pub(super) fn shutdown(&mut self) {
1225            self.remote.shutdown();
1226            *self.authority.lock().expect("local authority lock") = None;
1227        }
1228    }
1229
1230    impl<R: Transport> Transport for LocalAuthorityTransport<R> {
1231        fn sync(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
1232            let mut authority = self.authority.lock().expect("local authority lock");
1233            match authority.as_mut() {
1234                None => Err(unconfigured(
1235                    "the local authority opens with create; create a client first",
1236                )),
1237                Some(local) if local.state() != AuthorityState::Attached => {
1238                    local.sync(request).map_err(transport_error)
1239                }
1240                Some(_) => {
1241                    drop(authority);
1242                    self.remote.sync(request)
1243                }
1244            }
1245        }
1246
1247        fn remote_operation(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
1248            self.remote.remote_operation(request)
1249        }
1250
1251        fn realtime_sync(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
1252            if self.local_active() {
1253                return Err(refused("the local authority has no realtime channel"));
1254            }
1255            self.remote.realtime_sync(request)
1256        }
1257
1258        fn download_segment(
1259            &mut self,
1260            request: &SegmentRequest,
1261            on_progress: &mut dyn FnMut(u64),
1262        ) -> Result<Vec<u8>, TransportError> {
1263            if self.local_active() {
1264                return Err(refused("the local authority has no segment endpoint"));
1265            }
1266            self.remote.download_segment(request, on_progress)
1267        }
1268
1269        fn download_segments(
1270            &mut self,
1271            fetches: &[SegmentFetch],
1272            on_progress: &mut (dyn FnMut(usize, u64) + Send),
1273        ) -> Vec<Result<Vec<u8>, TransportError>> {
1274            if self.local_active() {
1275                return fetches
1276                    .first()
1277                    .map(|_| Err(refused("the local authority has no segment endpoint")))
1278                    .into_iter()
1279                    .collect();
1280            }
1281            self.remote.download_segments(fetches, on_progress)
1282        }
1283
1284        fn supports_url_fetch(&self) -> bool {
1285            self.remote.supports_url_fetch()
1286        }
1287
1288        fn fetch_url(
1289            &mut self,
1290            url: &str,
1291            byte_length: u64,
1292            on_progress: &mut dyn FnMut(u64),
1293        ) -> Result<Vec<u8>, TransportError> {
1294            if self.local_active() {
1295                return Err(refused("the local authority has no segment endpoint"));
1296            }
1297            self.remote.fetch_url(url, byte_length, on_progress)
1298        }
1299
1300        fn blob_upload(
1301            &mut self,
1302            blob_id: &str,
1303            bytes: &[u8],
1304            media_type: Option<&str>,
1305        ) -> Result<(), TransportError> {
1306            self.remote.blob_upload(blob_id, bytes, media_type)
1307        }
1308
1309        fn blob_download(
1310            &mut self,
1311            blob_id: &str,
1312            byte_length: Option<u64>,
1313        ) -> Result<BlobDownload, TransportError> {
1314            self.remote.blob_download(blob_id, byte_length)
1315        }
1316
1317        fn fetch_blob_url(
1318            &mut self,
1319            url: &str,
1320            byte_length: Option<u64>,
1321        ) -> Result<Vec<u8>, TransportError> {
1322            self.remote.fetch_blob_url(url, byte_length)
1323        }
1324
1325        fn blob_upload_grant(
1326            &mut self,
1327            blob_id: &str,
1328            byte_length: u64,
1329            media_type: Option<&str>,
1330        ) -> Result<BlobUploadGrant, TransportError> {
1331            self.remote
1332                .blob_upload_grant(blob_id, byte_length, media_type)
1333        }
1334
1335        fn blob_put_url(
1336            &mut self,
1337            blob_id: &str,
1338            url: &str,
1339            bytes: &[u8],
1340            media_type: Option<&str>,
1341        ) -> Result<(), TransportError> {
1342            self.remote.blob_put_url(blob_id, url, bytes, media_type)
1343        }
1344
1345        fn realtime_connect(&mut self, client_id: &str) -> Result<(), TransportError> {
1346            if self.local_active() {
1347                return Err(refused("the local authority has no realtime channel"));
1348            }
1349            self.remote.realtime_connect(client_id)
1350        }
1351
1352        fn round_deadline(&self) -> Option<std::time::Duration> {
1353            self.remote.round_deadline()
1354        }
1355
1356        fn set_round_deadline(&mut self, deadline: Option<std::time::Instant>) {
1357            self.remote.set_round_deadline(deadline);
1358        }
1359
1360        fn set_idle_bound(&mut self, bound: Option<std::time::Duration>) {
1361            self.remote.set_idle_bound(bound);
1362        }
1363
1364        fn set_client_id(&mut self, client_id: &str) {
1365            self.remote.set_client_id(client_id);
1366        }
1367
1368        fn set_round(&mut self, attempt: Option<u64>) {
1369            self.remote.set_round(attempt);
1370        }
1371
1372        fn realtime_send(&mut self, text: &str) -> Result<(), TransportError> {
1373            self.remote.realtime_send(text)
1374        }
1375
1376        fn realtime_close(&mut self) -> Result<(), TransportError> {
1377            self.remote.realtime_close()
1378        }
1379
1380        fn open_local_authority(
1381            &mut self,
1382            schema: &serde_json::Value,
1383            replica_path: Option<&str>,
1384        ) -> Result<(), TransportError> {
1385            if self.path != ":memory:" && replica_path == Some(self.path.as_str()) {
1386                return Err(TransportError::new(
1387                    "sync.invalid_request",
1388                    "localAuthorityPath must name a file other than the replica's dbPath",
1389                ));
1390            }
1391            let mut authority = self.authority.lock().expect("local authority lock");
1392            // Close the previous authority before reopening its file.
1393            *authority = None;
1394            *authority = Some(LocalAuthority::open(&self.path, schema).map_err(transport_error)?);
1395            Ok(())
1396        }
1397
1398        fn local_authority_state(&self) -> Option<&'static str> {
1399            self.authority
1400                .lock()
1401                .expect("local authority lock")
1402                .as_ref()
1403                .map(|authority| match authority.state() {
1404                    AuthorityState::Local => "local",
1405                    AuthorityState::Attaching => "attaching",
1406                    AuthorityState::Attached => "attached",
1407                })
1408        }
1409
1410        fn attach_local_authority(&mut self) -> Result<(), TransportError> {
1411            if !self.remote_configured {
1412                return Err(unconfigured(
1413                    "attachLocalAuthority needs a baseUrl for the remote server",
1414                ));
1415            }
1416            let remote = &mut self.remote;
1417            let mut authority = self.authority.lock().expect("local authority lock");
1418            authority
1419                .as_mut()
1420                .ok_or_else(|| {
1421                    unconfigured("the local authority opens with create; create a client first")
1422                })?
1423                .attach(&mut |request: &[u8]| remote.sync(request).map_err(authority_error))
1424                .map_err(transport_error)
1425        }
1426
1427        fn abandon_local_authority_attach(&mut self) -> Result<(), TransportError> {
1428            if !self.remote_configured {
1429                return Err(unconfigured(
1430                    "abandonLocalAuthorityAttach needs a baseUrl for the remote server",
1431                ));
1432            }
1433            let remote = &mut self.remote;
1434            let mut authority = self.authority.lock().expect("local authority lock");
1435            authority
1436                .as_mut()
1437                .ok_or_else(|| {
1438                    unconfigured("the local authority opens with create; create a client first")
1439                })?
1440                .abandon_attach(Some(&mut |request: &[u8]| {
1441                    remote.sync(request).map_err(authority_error)
1442                }))
1443                .map_err(transport_error)
1444        }
1445    }
1446}
1447
1448#[cfg(feature = "native-transport")]
1449mod native {
1450    //! The real native HTTP + WS transport. HTTP via `ureq` (blocking, no
1451    //! async runtime — matches the client's synchronous API); WS via
1452    //! `tungstenite`, with a reader thread pushing inbound frames into the
1453    //! shared `InboundBuffer`.
1454    //!
1455    //! Wire contract mirrors the reference HTTP+WS bindings (§1.1, §8.7):
1456    //! `POST {baseUrl}/sync` (application/vnd.syncular.sync.v2, `X-Syncular-Scopes`
1457    //! not needed here — the native app authenticates via its header source),
1458    //! `GET {baseUrl}/segments/{id}`, `PUT/GET {baseUrl}/blobs/{id}`, and the
1459    //! realtime socket at `{wsUrl}` (ws(s):// derived from baseUrl).
1460
1461    use std::io::{self, Read, Write};
1462    use std::net::{TcpStream, ToSocketAddrs};
1463    use std::sync::atomic::{AtomicBool, Ordering};
1464    use std::sync::{mpsc, Arc, Condvar, Mutex};
1465    use std::thread::JoinHandle;
1466    use std::time::{Duration, Instant};
1467
1468    use polling::{Event, Events, Poller};
1469    use tungstenite::stream::MaybeTlsStream;
1470    use tungstenite::Message;
1471    use ureq::unversioned::resolver::DefaultResolver;
1472    use ureq::unversioned::transport::{
1473        time::Duration as UreqDuration, ConnectionDetails, Connector, DefaultConnector,
1474        NextTimeout, Transport as UreqTransport,
1475    };
1476    use ureq::Timeout as UreqTimeout;
1477
1478    use super::{
1479        HeaderContext, HeaderSource, HeaderTarget, HostTransportPolicy, Inbound, InboundBuffer,
1480        RealtimeReceiptKind, RedirectPolicy,
1481    };
1482    use crate::{
1483        BlobDownload, BlobUploadGrant, RealtimeRound, RoundInbound, SegmentFetch, SegmentRequest,
1484        Transport, TransportError,
1485    };
1486
1487    // Unregister before the cloned socket handle is closed, including on unwind.
1488    struct SocketRegistration {
1489        poller: Arc<Poller>,
1490        stream: TcpStream,
1491    }
1492
1493    impl Drop for SocketRegistration {
1494        fn drop(&mut self) {
1495            let _ = self.poller.delete(&self.stream);
1496        }
1497    }
1498
1499    #[derive(Clone)]
1500    struct SocketSender {
1501        queue: mpsc::SyncSender<Outgoing>,
1502        poller: Arc<Poller>,
1503    }
1504
1505    struct Outgoing {
1506        message: Message,
1507        completed: mpsc::Sender<Result<(), TransportError>>,
1508    }
1509
1510    /// How long a socket round tolerates silence: no inbound byte of the
1511    /// response, or no outbound request chunk flushed, for this long fails the
1512    /// round (§1.8). The bound restarts on every chunk of progress, so a slow
1513    /// link that keeps delivering never trips it; the host's whole-round
1514    /// deadline is the only ceiling on total transfer time.
1515    const ROUND_IDLE_TIMEOUT: Duration = Duration::from_secs(30);
1516    /// Largest `0x01` chunk of a request. Each chunk's flush is one unit of
1517    /// outbound progress; chunk boundaries carry no meaning (§8.7).
1518    const REQUEST_CHUNK_BYTES: usize = 64 * 1024;
1519
1520    /// The bound that ends a socket round first.
1521    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1522    enum Expiry {
1523        /// The fixed socket silence bound (§1.8).
1524        Silence,
1525        /// The §7.8 drive bound, which also restarts on progress.
1526        Drive,
1527        /// The host's absolute whole-round deadline.
1528        Ceiling,
1529    }
1530
1531    /// When a round with `last_progress`, a silence bound `idle` and an
1532    /// optional drive bound expires, and which bound binds. The host's
1533    /// whole-round `ceiling` is absolute.
1534    fn round_expiry(
1535        last_progress: Instant,
1536        idle: Duration,
1537        drive: Option<Duration>,
1538        ceiling: Option<Instant>,
1539    ) -> (Instant, Expiry) {
1540        let mut expiry = (last_progress + idle, Expiry::Silence);
1541        if let Some(at) = drive.and_then(|drive| last_progress.checked_add(drive)) {
1542            if at < expiry.0 {
1543                expiry = (at, Expiry::Drive);
1544            }
1545        }
1546        match ceiling {
1547            Some(ceiling) if ceiling < expiry.0 => (ceiling, Expiry::Ceiling),
1548            _ => expiry,
1549        }
1550    }
1551    /// The §8.7 round rendezvous shared between the reader thread (which
1552    /// demuxes inbound `0x01` chunks into the round via [`RealtimeRound`]) and
1553    /// `realtime_sync` (which begins the round, sends the request, and blocks
1554    /// here for the reassembled response). The transport-agnostic framing
1555    /// logic lives in [`RealtimeRound`] (the lean client crate, shared with
1556    /// the Tauri plugin); this struct is just the thread rendezvous.
1557    #[derive(Default)]
1558    pub(super) struct RoundChannel {
1559        state: Mutex<RoundState>,
1560        ready: Condvar,
1561    }
1562
1563    #[derive(Default)]
1564    struct RoundState {
1565        round: RealtimeRound,
1566        /// When the round last moved: its request was framed, a request chunk
1567        /// flushed, or a response chunk arrived.
1568        last_progress: Option<Instant>,
1569        /// The connection ended; no round can ever complete on it.
1570        lost: bool,
1571        /// The completed round outcome, taken by `realtime_sync` once set.
1572        outcome: Option<Result<Vec<u8>, TransportError>>,
1573    }
1574
1575    impl RoundChannel {
1576        /// Begin a round: frame the request (`0x01` tag + envelope) for the
1577        /// socket and mark it in flight. Errors if one is already in flight
1578        /// (§8.7 one-in-flight, enforced client-side).
1579        fn begin(&self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
1580            let mut state = self.state.lock().expect("round lock");
1581            state.outcome = None;
1582            let framed = state.round.begin(request)?;
1583            state.last_progress = Some(Instant::now());
1584            Ok(framed)
1585        }
1586
1587        /// Record that a request chunk flushed.
1588        fn progressed(&self) {
1589            self.state.lock().expect("round lock").last_progress = Some(Instant::now());
1590        }
1591
1592        /// Whether the connection already ended. The reader thread publishes
1593        /// `Inbound::Disconnected` itself in that case.
1594        fn lost(&self) -> bool {
1595            self.state.lock().expect("round lock").lost
1596        }
1597
1598        /// Route one inbound binary frame from the reader thread. Returns the
1599        /// delta payload to enqueue on the inbound buffer, if any; a completed
1600        /// or failed round is stored and the waiting `realtime_sync` woken.
1601        fn route_binary(&self, frame: &[u8]) -> Option<Vec<u8>> {
1602            let mut state = self.state.lock().expect("round lock");
1603            match state.round.route_binary(frame) {
1604                Ok(RoundInbound::Delta(body)) => Some(body),
1605                Ok(RoundInbound::RoundProgress) => {
1606                    state.last_progress = Some(Instant::now());
1607                    None
1608                }
1609                Ok(RoundInbound::Ignored) => None,
1610                Ok(RoundInbound::RoundComplete(bytes)) => {
1611                    state.outcome = Some(Ok(bytes));
1612                    self.ready.notify_all();
1613                    None
1614                }
1615                Err(error) => {
1616                    state.outcome = Some(Err(error));
1617                    self.ready.notify_all();
1618                    None
1619                }
1620            }
1621        }
1622
1623        /// Fail any in-flight round (socket dropped) and wake the waiter.
1624        fn fail_in_flight(&self, error: TransportError) {
1625            let mut state = self.state.lock().expect("round lock");
1626            state.lost = true;
1627            if state.round.in_flight() && state.outcome.is_none() {
1628                state.round.abort();
1629                state.outcome = Some(Err(error));
1630                self.ready.notify_all();
1631            }
1632        }
1633
1634        /// Block until the round completes, fails, goes `idle` or the `drive`
1635        /// bound without progress, or reaches the host's whole-round `ceiling`.
1636        fn wait(
1637            &self,
1638            ceiling: Option<Instant>,
1639            idle: Duration,
1640            drive: Option<Duration>,
1641        ) -> Result<Vec<u8>, TransportError> {
1642            let mut state = self.state.lock().expect("round lock");
1643            while state.outcome.is_none() {
1644                let (deadline, expiry) = round_expiry(
1645                    state.last_progress.unwrap_or_else(Instant::now),
1646                    idle,
1647                    drive,
1648                    ceiling,
1649                );
1650                let now = Instant::now();
1651                if now >= deadline {
1652                    state.round.abort();
1653                    return Err(match expiry {
1654                        Expiry::Ceiling => {
1655                            timeout_error("sync round deadline exceeded", "round_deadline")
1656                        }
1657                        Expiry::Drive => {
1658                            timeout_error("realtime sync round made no progress", "drive")
1659                        }
1660                        Expiry::Silence => TransportError::new(
1661                            "sync.transport_failed",
1662                            "realtime sync round made no progress (§8.7)",
1663                        ),
1664                    });
1665                }
1666                let (guard, _timeout) = self
1667                    .ready
1668                    .wait_timeout(state, deadline - now)
1669                    .expect("round wait");
1670                state = guard;
1671            }
1672            state.outcome.take().expect("outcome present")
1673        }
1674    }
1675
1676    fn transfer_error(
1677        message: &'static str,
1678        cause_kind: &'static str,
1679        http_status: Option<u16>,
1680    ) -> TransportError {
1681        let mut details = serde_json::json!({ "causeKind": cause_kind });
1682        if let Some(status) = http_status {
1683            details["httpStatus"] = status.into();
1684        }
1685        let mut error = TransportError::new("transport.failed", message);
1686        error.details = Some(details);
1687        error
1688    }
1689
1690    /// A configured deadline elapsed. `cause_kind` distinguishes the
1691    /// per-request timeout from the whole-round deadline; `drive` is the §7.8
1692    /// drive bound, which fails the call with `sync.idle_timeout` (the round
1693    /// adds its details).
1694    fn timeout_error(message: &'static str, cause_kind: &'static str) -> TransportError {
1695        if cause_kind == "drive" {
1696            return TransportError::new("sync.idle_timeout", message);
1697        }
1698        let mut error = TransportError::new("transport.timeout", message);
1699        error.details = Some(serde_json::json!({ "causeKind": cause_kind }));
1700        error
1701    }
1702
1703    /// A 3xx was refused (either by policy or by exhausting the follow budget).
1704    fn redirect_error(message: &'static str, http_status: Option<u16>) -> TransportError {
1705        let mut details = serde_json::json!({ "causeKind": "redirect" });
1706        if let Some(status) = http_status {
1707            details["httpStatus"] = status.into();
1708        }
1709        let mut error = TransportError::new("transport.redirect", message);
1710        error.details = Some(details);
1711        error
1712    }
1713
1714    /// A 3xx that reached the caller means the redirect was refused (the
1715    /// request was credential bearing or the policy denies redirects). ureq
1716    /// returns such a response as-is when the ceiling is zero, so the refusal
1717    /// is detected here rather than in the error classifier.
1718    fn redirect_refused(resp: &ureq::http::Response<ureq::Body>) -> Result<(), TransportError> {
1719        let status = resp.status().as_u16();
1720        if (300..400).contains(&status) {
1721            return Err(redirect_error("redirect refused", Some(status)));
1722        }
1723        Ok(())
1724    }
1725
1726    /// The `causeKind` of a body-read timeout, or `None` for another error,
1727    /// classified through ureq's wrapping chain without formatting it:
1728    /// `Error::into_io` boxes a non-io ureq error as `io::Error::other`, and
1729    /// the gzip decoder re-wraps a plain io error as `Error::Decompress("gzip",
1730    /// e)`. Direct, nested, and plain shapes all count. Only the round
1731    /// deadline sets ureq's global timeout (`finish_request`), so a global
1732    /// timeout is the round deadline's (§1.8).
1733    /// Only the drive bound sets the per-read and per-write timeouts.
1734    fn timeout_cause(error: &std::io::Error) -> Option<&'static str> {
1735        let ureq_error = error
1736            .get_ref()
1737            .and_then(|inner| inner.downcast_ref::<ureq::Error>());
1738        match ureq_error {
1739            Some(ureq::Error::Timeout(ureq::Timeout::Global)) => Some("round_deadline"),
1740            Some(ureq::Error::Timeout(ureq::Timeout::PerRead | ureq::Timeout::PerWrite)) => {
1741                Some("drive")
1742            }
1743            Some(ureq::Error::Timeout(_)) => Some("timeout"),
1744            Some(ureq::Error::Io(nested) | ureq::Error::Decompress(_, nested)) => {
1745                timeout_cause(nested)
1746            }
1747            _ => (error.kind() == std::io::ErrorKind::TimedOut).then_some("timeout"),
1748        }
1749    }
1750
1751    fn http_err(message: &'static str, error: ureq::Error) -> TransportError {
1752        let (kind, status) = match error {
1753            ureq::Error::StatusCode(status) if (300..400).contains(&status) => {
1754                return redirect_error(message, Some(status))
1755            }
1756            ureq::Error::StatusCode(status) => ("status", Some(status)),
1757            ureq::Error::Timeout(ureq::Timeout::Global) => {
1758                return timeout_error(message, "round_deadline")
1759            }
1760            ureq::Error::Timeout(ureq::Timeout::PerRead | ureq::Timeout::PerWrite) => {
1761                return timeout_error(message, "drive")
1762            }
1763            ureq::Error::Timeout(_) => return timeout_error(message, "timeout"),
1764            ureq::Error::Io(error) => return io_err(message, error),
1765            ureq::Error::HostNotFound
1766            | ureq::Error::ConnectionFailed
1767            | ureq::Error::ConnectProxyFailed(_) => ("connect", None),
1768            ureq::Error::Tls(_)
1769            | ureq::Error::Rustls(_)
1770            | ureq::Error::Pem(_)
1771            | ureq::Error::TlsRequired => ("tls", None),
1772            ureq::Error::BadUri(_)
1773            | ureq::Error::Http(_)
1774            | ureq::Error::RequireHttpsOnly(_)
1775            | ureq::Error::InvalidProxyUrl => ("request", None),
1776            ureq::Error::Protocol(_) => ("protocol", None),
1777            ureq::Error::BodyExceedsLimit(_)
1778            | ureq::Error::BodyStalled
1779            | ureq::Error::Decompress(_, _) => ("body", None),
1780            ureq::Error::RedirectFailed | ureq::Error::TooManyRedirects => {
1781                return redirect_error(message, None)
1782            }
1783            _ => ("unknown", None),
1784        };
1785        transfer_error(message, kind, status)
1786    }
1787
1788    fn io_err(message: &'static str, error: std::io::Error) -> TransportError {
1789        if let Some(cause) = timeout_cause(&error) {
1790            return timeout_error(message, cause);
1791        }
1792        let kind = match error.kind() {
1793            std::io::ErrorKind::ConnectionRefused
1794            | std::io::ErrorKind::ConnectionAborted
1795            | std::io::ErrorKind::ConnectionReset
1796            | std::io::ErrorKind::NotConnected => "connect",
1797            _ => "io",
1798        };
1799        transfer_error(message, kind, None)
1800    }
1801
1802    fn ws_err(message: &'static str, error: tungstenite::Error) -> TransportError {
1803        match error {
1804            tungstenite::Error::Io(error) => io_err(message, error),
1805            tungstenite::Error::Tls(_) => transfer_error(message, "tls", None),
1806            // A 3xx that reached the caller was refused (the policy denies
1807            // redirects or the handshake request is credential bearing).
1808            tungstenite::Error::Http(response) if response.status().is_redirection() => {
1809                redirect_error(message, Some(response.status().as_u16()))
1810            }
1811            tungstenite::Error::Http(response) => {
1812                transfer_error(message, "status", Some(response.status().as_u16()))
1813            }
1814            tungstenite::Error::Url(_) | tungstenite::Error::HttpFormat(_) => {
1815                transfer_error(message, "request", None)
1816            }
1817            _ => transfer_error(message, "protocol", None),
1818        }
1819    }
1820
1821    const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
1822
1823    fn remaining(deadline: Instant) -> io::Result<Duration> {
1824        deadline
1825            .checked_duration_since(Instant::now())
1826            .filter(|left| !left.is_zero())
1827            .ok_or_else(|| {
1828                io::Error::new(
1829                    io::ErrorKind::TimedOut,
1830                    "websocket establishment deadline exceeded",
1831                )
1832            })
1833    }
1834
1835    struct EstablishingStream {
1836        socket: TcpStream,
1837        deadline: Option<Instant>,
1838    }
1839
1840    impl EstablishingStream {
1841        fn timeout(&self) -> io::Result<Option<Duration>> {
1842            self.deadline.map(remaining).transpose()
1843        }
1844        fn established(&mut self) -> io::Result<TcpStream> {
1845            self.deadline = None;
1846            self.socket.set_read_timeout(None)?;
1847            self.socket.set_write_timeout(None)?;
1848            self.socket.try_clone()
1849        }
1850    }
1851
1852    fn establishment_io<T>(result: io::Result<T>, establishing: bool) -> io::Result<T> {
1853        result.map_err(|error| {
1854            if establishing
1855                && matches!(
1856                    error.kind(),
1857                    io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
1858                )
1859            {
1860                io::Error::new(
1861                    io::ErrorKind::TimedOut,
1862                    "websocket establishment deadline exceeded",
1863                )
1864            } else {
1865                error
1866            }
1867        })
1868    }
1869
1870    impl Read for EstablishingStream {
1871        fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
1872            if self.deadline.is_some() {
1873                self.socket.set_read_timeout(self.timeout()?)?;
1874            }
1875            establishment_io(self.socket.read(bytes), self.deadline.is_some())
1876        }
1877    }
1878    impl Write for EstablishingStream {
1879        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1880            if self.deadline.is_some() {
1881                self.socket.set_write_timeout(self.timeout()?)?;
1882            }
1883            establishment_io(self.socket.write(bytes), self.deadline.is_some())
1884        }
1885        fn flush(&mut self) -> io::Result<()> {
1886            if self.deadline.is_some() {
1887                self.socket.set_write_timeout(self.timeout()?)?;
1888            }
1889            establishment_io(self.socket.flush(), self.deadline.is_some())
1890        }
1891    }
1892
1893    fn connect_websocket(
1894        request: tungstenite::handshake::client::Request,
1895        deadline: Instant,
1896    ) -> Result<tungstenite::WebSocket<MaybeTlsStream<EstablishingStream>>, TransportError> {
1897        let host = request
1898            .uri()
1899            .host()
1900            .ok_or_else(|| transfer_error("realtime URL invalid", "request", None))?;
1901        let host = host.trim_start_matches('[').trim_end_matches(']');
1902        let port = match request.uri().scheme_str() {
1903            Some("ws") => request.uri().port_u16().unwrap_or(80),
1904            Some("wss") => request.uri().port_u16().unwrap_or(443),
1905            _ => return Err(transfer_error("realtime URL invalid", "request", None)),
1906        };
1907        // System DNS has no cancellable deadline. Only resolution runs here:
1908        // a late result cannot open a socket or issue an authenticated request.
1909        let host = host.to_owned();
1910        let (resolved, addresses) = mpsc::sync_channel(1);
1911        std::thread::Builder::new()
1912            .name("syncular-dns".to_owned())
1913            .spawn(move || {
1914                let result = (host.as_str(), port)
1915                    .to_socket_addrs()
1916                    .map(|items| items.collect::<Vec<_>>());
1917                let _ = resolved.send(result);
1918            })
1919            .map_err(|e| io_err("realtime DNS failed", e))?;
1920        let addresses = addresses
1921            .recv_timeout(remaining(deadline).map_err(|e| io_err("realtime DNS failed", e))?)
1922            .map_err(|e| match e {
1923                mpsc::RecvTimeoutError::Timeout => {
1924                    timeout_error("realtime DNS timed out", "timeout")
1925                }
1926                mpsc::RecvTimeoutError::Disconnected => {
1927                    transfer_error("realtime DNS failed", "io", None)
1928                }
1929            })?
1930            .map_err(|e| io_err("realtime DNS failed", e))?;
1931        let mut last_error = io::Error::new(io::ErrorKind::NotFound, "DNS returned no addresses");
1932        let mut socket = None;
1933        for address in addresses {
1934            match TcpStream::connect_timeout(
1935                &address,
1936                remaining(deadline).map_err(|e| io_err("realtime TCP connect failed", e))?,
1937            ) {
1938                Ok(stream) => {
1939                    socket = Some(stream);
1940                    break;
1941                }
1942                Err(error) => last_error = error,
1943            }
1944        }
1945        let socket = socket.ok_or_else(|| io_err("realtime TCP connect failed", last_error))?;
1946        socket
1947            .set_nodelay(true)
1948            .map_err(|e| io_err("realtime TCP connect failed", e))?;
1949        let stream = EstablishingStream {
1950            socket,
1951            deadline: Some(deadline),
1952        };
1953        // Same pinned rustls / WebPKI connector, certificate and hostname checks.
1954        // Redirects are errors: credentials stay bound to the configured endpoint.
1955        let (ws, _) = tungstenite::client_tls_with_config(request, stream, None, None).map_err(
1956            |e| match e {
1957                tungstenite::HandshakeError::Failure(error) => {
1958                    ws_err("realtime connection failed", error)
1959                }
1960                // The establishment socket is blocking with a deadline, so the
1961                // handshake cannot report an interrupted (would-block) state.
1962                tungstenite::HandshakeError::Interrupted(_) => {
1963                    transfer_error("realtime connection failed", "protocol", None)
1964                }
1965            },
1966        )?;
1967        remaining(deadline).map_err(|e| io_err("realtime connection failed", e))?;
1968        Ok(ws)
1969    }
1970
1971    #[cfg(test)]
1972    mod establishment_tests {
1973        use super::*;
1974        use std::net::{Shutdown, TcpListener};
1975        use tungstenite::client::IntoClientRequest;
1976
1977        // A peer consumes the initial request/ClientHello, then withholds its
1978        // upgrade/TLS response until released. Cleanup also unblocks the old path.
1979        fn withheld_response(tls: bool, old: bool) {
1980            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1981            let url = format!(
1982                "{}://{}/realtime",
1983                if tls { "wss" } else { "ws" },
1984                listener.local_addr().unwrap()
1985            );
1986            let (accepted_tx, accepted_rx) = mpsc::channel();
1987            let (release_tx, release_rx) = mpsc::channel();
1988            let peer = std::thread::spawn(move || {
1989                let (mut stream, _) = listener.accept().unwrap();
1990                stream
1991                    .set_read_timeout(Some(Duration::from_secs(2)))
1992                    .unwrap();
1993                let mut bytes = [0; 4096];
1994                assert!(stream.read(&mut bytes).unwrap() > 0);
1995                accepted_tx.send(()).unwrap();
1996                release_rx.recv_timeout(Duration::from_secs(3)).unwrap();
1997                let _ = stream.shutdown(Shutdown::Both);
1998            });
1999            let (done_tx, done_rx) = mpsc::channel();
2000            let worker = std::thread::spawn(move || {
2001                let result = if old {
2002                    tungstenite::connect(url)
2003                        .map(|_| ())
2004                        .map_err(|e| e.to_string())
2005                } else {
2006                    connect_websocket(
2007                        url.into_client_request().unwrap(),
2008                        Instant::now() + Duration::from_millis(250),
2009                    )
2010                    .map(|_| ())
2011                    .map_err(|e| format!("{}: {}", e.code, e.message))
2012                };
2013                done_tx.send(result).unwrap();
2014            });
2015            accepted_rx.recv_timeout(Duration::from_secs(2)).unwrap();
2016            if old {
2017                assert!(
2018                    matches!(
2019                        done_rx.recv_timeout(Duration::from_millis(500)),
2020                        Err(mpsc::RecvTimeoutError::Timeout)
2021                    ),
2022                    "original connect unexpectedly had a deadline"
2023                );
2024                release_tx.send(()).unwrap();
2025                assert!(done_rx
2026                    .recv_timeout(Duration::from_secs(2))
2027                    .unwrap()
2028                    .is_err());
2029            } else {
2030                let error = done_rx
2031                    .recv_timeout(Duration::from_secs(2))
2032                    .expect("establishment remained blocked")
2033                    .unwrap_err();
2034                assert_eq!(error, "transport.timeout: realtime connection failed");
2035                eprintln!(
2036                    "withheld {} produces {error}",
2037                    if tls { "TLS" } else { "upgrade" }
2038                );
2039                release_tx.send(()).unwrap();
2040            }
2041            worker.join().unwrap();
2042            peer.join().unwrap();
2043        }
2044
2045        #[test]
2046        fn original_connect_blocks_on_withheld_upgrade_and_tls() {
2047            withheld_response(false, true);
2048            withheld_response(true, true);
2049        }
2050        #[test]
2051        fn establishment_deadline_errors_on_withheld_upgrade_and_tls() {
2052            withheld_response(false, false);
2053            withheld_response(true, false);
2054        }
2055
2056        #[test]
2057        fn slow_upgrade_bytes_cannot_renew_the_absolute_deadline() {
2058            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2059            let url = format!("ws://{}", listener.local_addr().unwrap());
2060            let peer = std::thread::spawn(move || {
2061                let (mut stream, _) = listener.accept().unwrap();
2062                let mut bytes = [0; 4096];
2063                let _ = stream.read(&mut bytes).unwrap();
2064                for byte in b"HTTP/1.1 101 Switching Protocols\r\n" {
2065                    if stream.write_all(&[*byte]).is_err() {
2066                        break;
2067                    }
2068                    std::thread::sleep(Duration::from_millis(40));
2069                }
2070            });
2071            let started = Instant::now();
2072            assert!(connect_websocket(
2073                url.into_client_request().unwrap(),
2074                started + Duration::from_millis(250)
2075            )
2076            .is_err());
2077            assert!(started.elapsed() < Duration::from_secs(1));
2078            peer.join().unwrap();
2079        }
2080
2081        #[test]
2082        fn saturated_tcp_accept_queue_returns_an_observable_error() {
2083            // Fill a loopback listener's kernel accept queue without accepting.
2084            // No unroutable external host or firewall mutation is needed.
2085            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2086            let address = listener.local_addr().unwrap();
2087            let mut queued = Vec::new();
2088            loop {
2089                match TcpStream::connect_timeout(&address, Duration::from_millis(50)) {
2090                    Ok(stream) => queued.push(stream),
2091                    Err(error) => {
2092                        assert!(
2093                            matches!(
2094                                error.kind(),
2095                                io::ErrorKind::TimedOut
2096                                    | io::ErrorKind::WouldBlock
2097                                    | io::ErrorKind::ConnectionRefused
2098                                    | io::ErrorKind::ConnectionReset
2099                            ),
2100                            "{error:?}"
2101                        );
2102                        break;
2103                    }
2104                }
2105                assert!(queued.len() < 4096, "listener queue did not saturate");
2106            }
2107            let started = Instant::now();
2108            let url = format!("ws://{address}");
2109            let error = match connect_websocket(
2110                url.into_client_request().unwrap(),
2111                started + Duration::from_millis(250),
2112            ) {
2113                Err(error) => error,
2114                Ok(_) => panic!("full accept queue unexpectedly connected"),
2115            };
2116            assert!(
2117                (error.code == "transport.timeout" || error.code == "transport.failed")
2118                    && (error.message == "realtime TCP connect failed"
2119                        || error.message == "realtime connection failed"),
2120                "{}: {}",
2121                error.code,
2122                error.message
2123            );
2124            assert!(started.elapsed() < Duration::from_secs(2));
2125        }
2126    }
2127
2128    /// Segment fetches keep their own generic surface (`sync.transport_failed`)
2129    /// but must not swallow a typed policy failure: a refused redirect or an
2130    /// exceeded deadline/byte budget survives to the caller.
2131    fn segment_error(mut error: TransportError) -> TransportError {
2132        if error.code == "transport.failed" {
2133            error.code = "sync.transport_failed".into();
2134            error.message = "segment transfer failed".into();
2135        }
2136        error
2137    }
2138
2139    /// Nonblocking I/O needs a readiness notification before it can continue.
2140    fn is_would_block(e: &tungstenite::Error) -> bool {
2141        matches!(
2142            e,
2143            tungstenite::Error::Io(io) if matches!(
2144                io.kind(),
2145                std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
2146            )
2147        )
2148    }
2149
2150    pub struct NativeTransport {
2151        base_url: String,
2152        ws_url: String,
2153        /// The host's header source; `None` sends no host headers.
2154        pub headers: Option<HeaderSource>,
2155        /// The served client's id and the progress attempt of the round in
2156        /// flight, named in each header source read.
2157        client_id: String,
2158        round_attempt: Option<u64>,
2159        /// The base URL carries `user:pass@`, which ureq turns into request
2160        /// credentials; a request to it is credential bearing even without
2161        /// host headers.
2162        base_url_has_userinfo: bool,
2163        agent: ureq::Agent,
2164        policy: HostTransportPolicy,
2165        /// Absolute whole-round deadline scoped by `set_round_deadline` for
2166        /// one exchange; `None` outside a round or when the policy sets no
2167        /// round budget.
2168        round_deadline_at: Option<std::time::Instant>,
2169        /// §7.8 drive bound scoped by `set_idle_bound` for one exchange: no
2170        /// call may wait longer for a byte to move. `None` outside a drive.
2171        drive_bound: Option<Duration>,
2172        pub signed_urls: bool,
2173        pub inbound: Arc<InboundBuffer>,
2174        /// One I/O thread owns the socket; callers wait for their write to flush.
2175        outgoing: Option<Box<SocketSender>>,
2176        reader: Option<JoinHandle<()>>,
2177        reader_stop: Arc<AtomicBool>,
2178        /// §8.7 round rendezvous, shared with the reader thread.
2179        round: Arc<RoundChannel>,
2180    }
2181
2182    /// Enforces `request_timeout` as a silence bound. ureq measures each
2183    /// request phase from its start, so a body that keeps arriving still
2184    /// expires; this connector caps every socket read and write at the bound
2185    /// instead, which restarts with each byte moved. The remaining phases
2186    /// (resolve, connect, request head, response head) keep ureq's own
2187    /// per-phase deadlines.
2188    #[derive(Debug)]
2189    struct IdleConnector(Option<Duration>);
2190
2191    impl Connector<Box<dyn UreqTransport>> for IdleConnector {
2192        type Out = Box<dyn UreqTransport>;
2193
2194        fn connect(
2195            &self,
2196            _: &ConnectionDetails,
2197            chained: Option<Box<dyn UreqTransport>>,
2198        ) -> Result<Option<Self::Out>, ureq::Error> {
2199            Ok(chained.map(|inner| match self.0 {
2200                Some(idle) => IdleTransport { inner, idle }.boxed(),
2201                None => inner,
2202            }))
2203        }
2204    }
2205
2206    #[derive(Debug)]
2207    struct IdleTransport {
2208        inner: Box<dyn UreqTransport>,
2209        idle: Duration,
2210    }
2211
2212    /// Cap a wait at `idle`: a wait with no deadline or a longer one becomes
2213    /// `idle`; a shorter ceiling (the round deadline) stays. The bound edits
2214    /// the wait in place, so ureq's other limits (per-read and per-write
2215    /// caps) pass through unchanged.
2216    fn idle_bound(mut timeout: NextTimeout, idle: Duration) -> NextTimeout {
2217        let idle = UreqDuration::Exact(idle);
2218        if timeout.after.is_not_happening() || timeout.after.as_nanos() > idle.as_nanos() {
2219            timeout.after = idle;
2220            timeout.reason = UreqTimeout::RecvBody;
2221        }
2222        timeout
2223    }
2224
2225    impl UreqTransport for IdleTransport {
2226        fn buffers(&mut self) -> &mut dyn ureq::unversioned::transport::Buffers {
2227            self.inner.buffers()
2228        }
2229        fn transmit_output(
2230            &mut self,
2231            amount: usize,
2232            timeout: NextTimeout,
2233        ) -> Result<(), ureq::Error> {
2234            self.inner
2235                .transmit_output(amount, idle_bound(timeout, self.idle))
2236        }
2237        fn await_input(&mut self, timeout: NextTimeout) -> Result<bool, ureq::Error> {
2238            self.inner.await_input(idle_bound(timeout, self.idle))
2239        }
2240        fn is_open(&mut self) -> bool {
2241            self.inner.is_open()
2242        }
2243        fn is_tls(&self) -> bool {
2244            self.inner.is_tls()
2245        }
2246    }
2247
2248    fn build_agent(policy: &HostTransportPolicy) -> ureq::Agent {
2249        let config = ureq::Agent::config_builder()
2250            .timeout_resolve(policy.request_timeout)
2251            .timeout_connect(policy.request_timeout)
2252            .timeout_send_request(policy.request_timeout)
2253            .timeout_recv_response(policy.request_timeout)
2254            .max_redirects(match policy.redirects {
2255                RedirectPolicy::Deny => 0,
2256                RedirectPolicy::Follow => 10,
2257            })
2258            .max_redirects_will_error(matches!(policy.redirects, RedirectPolicy::Follow))
2259            .redirect_auth_headers(ureq::config::RedirectAuthHeaders::Never)
2260            // A 4xx/5xx carries the server's §10.1 JSON error body. Read it so
2261            // the code, recommendedAction, details and HTTP status can reach
2262            // the caller; read_body turns a non-2xx response into a typed
2263            // TransportError before any payload is treated as data.
2264            .http_status_as_error(false)
2265            .build();
2266        ureq::Agent::with_parts(
2267            config,
2268            DefaultConnector::new().chain(IdleConnector(policy.request_timeout)),
2269            DefaultResolver::default(),
2270        )
2271    }
2272
2273    fn derive_ws_url(base_url: &str) -> String {
2274        // {scheme}://host/path → ws(s)://host/path/realtime — the reference
2275        // realtime endpoint sits alongside /sync under the mount (§8.7).
2276        let ws = if let Some(rest) = base_url.strip_prefix("https://") {
2277            format!("wss://{rest}")
2278        } else if let Some(rest) = base_url.strip_prefix("http://") {
2279            format!("ws://{rest}")
2280        } else {
2281            base_url.to_owned()
2282        };
2283        let trimmed = ws.trim_end_matches('/');
2284        format!("{trimmed}/realtime")
2285    }
2286
2287    impl NativeTransport {
2288        pub fn fork_round(&self) -> Self {
2289            Self {
2290                base_url: self.base_url.clone(),
2291                ws_url: self.ws_url.clone(),
2292                headers: self.headers.clone(),
2293                client_id: self.client_id.clone(),
2294                round_attempt: self.round_attempt,
2295                base_url_has_userinfo: self.base_url_has_userinfo,
2296                agent: self.agent.clone(),
2297                policy: self.policy.clone(),
2298                round_deadline_at: None,
2299                drive_bound: None,
2300                signed_urls: self.signed_urls,
2301                inbound: self.inbound.clone(),
2302                outgoing: self.outgoing.clone(),
2303                reader: None,
2304                reader_stop: self.reader_stop.clone(),
2305                round: self.round.clone(),
2306            }
2307        }
2308
2309        pub fn new(
2310            base_url: &str,
2311            config: &serde_json::Value,
2312            notify: Option<Arc<dyn Fn() + Send + Sync>>,
2313        ) -> Result<Self, String> {
2314            let policy = HostTransportPolicy::from_config(config)?;
2315            Self::with_policy(base_url, config, policy, notify)
2316        }
2317
2318        pub fn with_policy(
2319            base_url: &str,
2320            config: &serde_json::Value,
2321            policy: HostTransportPolicy,
2322            notify: Option<Arc<dyn Fn() + Send + Sync>>,
2323        ) -> Result<Self, String> {
2324            policy.validate()?;
2325            let ws_url = config
2326                .get("wsUrl")
2327                .and_then(|v| v.as_str())
2328                .map(str::to_owned)
2329                .unwrap_or_else(|| derive_ws_url(base_url));
2330            // ureq replays `user:pass@` as Basic auth, so a base URL with
2331            // userinfo is credential bearing even when no headers are set.
2332            let base_url_has_userinfo = url::Url::parse(base_url)
2333                .map(|url| !url.username().is_empty() || url.password().is_some())
2334                .unwrap_or(false);
2335            Ok(NativeTransport {
2336                base_url: base_url.trim_end_matches('/').to_owned(),
2337                ws_url,
2338                headers: None,
2339                client_id: String::new(),
2340                round_attempt: None,
2341                base_url_has_userinfo,
2342                agent: build_agent(&policy),
2343                policy,
2344                round_deadline_at: None,
2345                drive_bound: None,
2346                signed_urls: false,
2347                inbound: Arc::new(match notify {
2348                    Some(notify) => InboundBuffer::with_notify(notify),
2349                    None => InboundBuffer::default(),
2350                }),
2351                outgoing: None,
2352                reader: None,
2353                reader_stop: Arc::new(AtomicBool::new(false)),
2354                round: Arc::new(RoundChannel::default()),
2355            })
2356        }
2357
2358        /// Replace the policy for subsequent calls; an invalid policy is
2359        /// rejected and the current policy stays in force. The agent is
2360        /// rebuilt so the new redirect ceiling and timeout defaults apply.
2361        pub fn set_policy(&mut self, policy: HostTransportPolicy) -> Result<(), String> {
2362            policy.validate()?;
2363            self.agent = build_agent(&policy);
2364            self.policy = policy;
2365            Ok(())
2366        }
2367
2368        pub fn round_deadline(&self) -> Option<Duration> {
2369            self.policy.round_deadline
2370        }
2371
2372        pub fn set_round_deadline(&mut self, deadline: Option<std::time::Instant>) {
2373            self.round_deadline_at = deadline;
2374        }
2375
2376        /// What remains of the whole-round deadline, or `None` without one.
2377        /// Fails before any network I/O once the deadline has passed. The
2378        /// per-request bound is not part of this: it restarts on every byte
2379        /// (see [`IdleConnector`]).
2380        fn round_remaining(&self) -> Result<Option<Duration>, TransportError> {
2381            match self.round_deadline_at {
2382                Some(deadline) => deadline
2383                    .checked_duration_since(std::time::Instant::now())
2384                    .map(Some)
2385                    .ok_or_else(|| timeout_error("sync round deadline exceeded", "round_deadline")),
2386                None => Ok(None),
2387            }
2388        }
2389
2390        /// Run one host-authenticated request through the header source,
2391        /// in the context of this transport's client and round (one resend
2392        /// after a 401). Without a source the request carries no host
2393        /// headers and is not resent.
2394        fn authenticated<T>(
2395            &self,
2396            target: HeaderTarget,
2397            mut send: impl FnMut(&[(String, String)]) -> Result<T, TransportError>,
2398        ) -> Result<T, TransportError> {
2399            match &self.headers {
2400                Some(source) => source.authenticated(
2401                    &HeaderContext {
2402                        client_id: self.client_id.clone(),
2403                        round: self.round_attempt,
2404                        target,
2405                    },
2406                    send,
2407                ),
2408                None => send(&[]),
2409            }
2410        }
2411
2412        /// Attach host `headers` (`None` for a signed URL, which carries
2413        /// none) and apply the per-call bounds: the round's remaining time,
2414        /// the drive bound on every socket read and write (each restarts it),
2415        /// and a redirect ceiling of zero whenever the request is credential
2416        /// bearing or the policy denies redirects. Host headers, base-URL
2417        /// userinfo (ureq replays it as Basic auth) and a signed URL are each
2418        /// credentials, and a credential-bearing request is refused a redirect
2419        /// under every policy, because ureq forwards headers to the redirect
2420        /// target.
2421        fn finish_request<B>(
2422            &self,
2423            mut req: ureq::RequestBuilder<B>,
2424            headers: Option<&[(String, String)]>,
2425        ) -> Result<ureq::RequestBuilder<B>, TransportError> {
2426            let timeout = self.round_remaining()?;
2427            let credentialed = match headers {
2428                None => true,
2429                Some(headers) => !headers.is_empty() || self.base_url_has_userinfo,
2430            };
2431            for (name, value) in headers.unwrap_or_default() {
2432                req = req.header(name.as_str(), value.as_str());
2433            }
2434            let follow = self.policy.redirects == RedirectPolicy::Follow && !credentialed;
2435            Ok(req
2436                .config()
2437                .timeout_global(timeout)
2438                .timeout_per_read(self.drive_bound)
2439                .timeout_per_write(self.drive_bound)
2440                .max_redirects(if follow { 10 } else { 0 })
2441                .max_redirects_will_error(true)
2442                .build())
2443        }
2444
2445        /// Refuse an oversized request body before any network I/O.
2446        fn check_request_bytes(&self, len: u64) -> Result<(), TransportError> {
2447            match self.policy.max_request_bytes {
2448                Some(max) if len > max => {
2449                    let mut error = TransportError::new(
2450                        "transport.request_too_large",
2451                        "request body exceeds the configured transport limit",
2452                    );
2453                    error.details = Some(serde_json::json!({ "limit": max, "size": len }));
2454                    Err(error)
2455                }
2456                _ => Ok(()),
2457            }
2458        }
2459
2460        fn post_sync(&self, path: &str, body: &[u8]) -> Result<Vec<u8>, TransportError> {
2461            self.check_request_bytes(body.len() as u64)?;
2462            let url = format!("{}{}", self.base_url, path);
2463            self.authenticated(HeaderTarget::Sync, |headers| {
2464                // SSP2 requests carry their own media type (SPEC 1.1); a stock
2465                // server answers 415 to anything else.
2466                let req = self.finish_request(
2467                    self.agent
2468                        .post(&url)
2469                        .header("content-type", "application/vnd.syncular.sync.v2"),
2470                    Some(headers),
2471                )?;
2472                let resp = req
2473                    .send(body)
2474                    .map_err(|e| http_err("sync request failed", e))?;
2475                read_body(resp, None, self.policy.max_response_bytes, None)
2476            })
2477        }
2478
2479        fn post_operation(&self, body: &[u8]) -> Result<Vec<u8>, TransportError> {
2480            self.check_request_bytes(body.len() as u64)?;
2481            let url = format!("{}/operations", self.base_url);
2482            self.authenticated(HeaderTarget::Sync, |headers| {
2483                let req = self.finish_request(
2484                    self.agent.post(&url).header(
2485                        "content-type",
2486                        "application/vnd.syncular.operations.v1+json",
2487                    ),
2488                    Some(headers),
2489                )?;
2490                let response = req
2491                    .send(body)
2492                    .map_err(|error| http_err("remote operation request failed", error))?;
2493                read_body(response, None, self.policy.max_response_bytes, None)
2494            })
2495        }
2496
2497        pub fn shutdown(&mut self) {
2498            self.reader_stop.store(true, Ordering::SeqCst);
2499            // Wake any `realtime_sync` blocked on a round: the socket is going
2500            // away, so the round can never complete (§8.7 mid-round drop).
2501            self.round.fail_in_flight(TransportError::new(
2502                "sync.transport_failed",
2503                "realtime disconnected mid-round (§8.7)",
2504            ));
2505            if let Some(outgoing) = &self.outgoing {
2506                let _ = outgoing.poller.notify();
2507            }
2508            if let Some(handle) = self.reader.take() {
2509                let _ = handle.join();
2510            }
2511            self.outgoing = None;
2512        }
2513
2514        fn send_message(&mut self, message: Message) -> Result<(), TransportError> {
2515            // The whole-round deadline and the drive bound bound the write wait
2516            // too: intersect them with the socket's own ceiling and report the
2517            // bound that elapsed. The per-request HTTP deadline does not apply to a
2518            // socket send.
2519            let now = Instant::now();
2520            let (deadline, expiry) = round_expiry(
2521                now,
2522                ROUND_IDLE_TIMEOUT,
2523                self.drive_bound,
2524                self.round_deadline_at,
2525            );
2526            // The round is already spent: refuse before queuing the frame so a
2527            // later send cannot deliver it.
2528            if deadline <= now {
2529                return Err(timeout_error("realtime send timed out", "round_deadline"));
2530            }
2531            let wait = deadline - now;
2532            let result = (|| {
2533                let Some(outgoing) = &self.outgoing else {
2534                    return Err(TransportError::new(
2535                        "transport.failed",
2536                        "realtime not connected",
2537                    ));
2538                };
2539                let (completed, result) = mpsc::channel();
2540                outgoing
2541                    .queue
2542                    .try_send(Outgoing { message, completed })
2543                    .map_err(|_| {
2544                        TransportError::new("transport.failed", "realtime send queue unavailable")
2545                    })?;
2546                outgoing
2547                    .poller
2548                    .notify()
2549                    .map_err(|e| io_err("realtime wake failed", e))?;
2550                result.recv_timeout(wait).map_err(|_| match expiry {
2551                    Expiry::Ceiling => timeout_error("realtime send timed out", "round_deadline"),
2552                    Expiry::Drive => timeout_error("realtime send timed out", "drive"),
2553                    Expiry::Silence => {
2554                        TransportError::new("transport.failed", "realtime send did not complete")
2555                    }
2556                })?
2557            })();
2558            // A failed/timed-out write must not remain eligible for delivery
2559            // behind a later command on the same connection.
2560            if let Err(error) = &result {
2561                // Record the typed failure first: `shutdown` fails an
2562                // in-flight round with the generic mid-round loss, and the
2563                // first recorded outcome wins.
2564                self.round.fail_in_flight(error.clone());
2565                self.shutdown();
2566                // Some callers (delta acknowledgement) intentionally ignore a
2567                // send error. It still invalidates the connection for the host.
2568                self.inbound.push(Inbound::Disconnected(error.clone()));
2569            }
2570            result
2571        }
2572    }
2573
2574    /// A non-2xx response. Preserve the authenticated server catalog error
2575    /// body (§10.1) so callers see its code, recommendedAction, details and
2576    /// HTTP status; a non-JSON body keeps the transport classification.
2577    fn http_status_body_error(status: u16, body: &[u8]) -> TransportError {
2578        let mut error = TransportError::new("transport.failed", "HTTP request failed");
2579        let mut details = serde_json::Map::new();
2580        if let Ok(serde_json::Value::Object(parsed)) =
2581            serde_json::from_slice::<serde_json::Value>(body)
2582        {
2583            if let Some(code) = parsed.get("code").and_then(serde_json::Value::as_str) {
2584                if !code.is_empty() {
2585                    error.code = code.to_owned();
2586                }
2587            }
2588            if let Some(message) = parsed.get("message").and_then(serde_json::Value::as_str) {
2589                error.message = message.to_owned();
2590            }
2591            for key in ["category", "recommendedAction"] {
2592                if let Some(value) = parsed.get(key).and_then(serde_json::Value::as_str) {
2593                    details.insert(key.to_owned(), serde_json::Value::from(value));
2594                }
2595            }
2596            if let Some(retryable) = parsed.get("retryable").and_then(serde_json::Value::as_bool) {
2597                details.insert("retryable".to_owned(), serde_json::Value::from(retryable));
2598            }
2599            if let Some(serde_json::Value::Object(inner)) = parsed.get("details") {
2600                for (key, value) in inner {
2601                    details.insert(key.clone(), value.clone());
2602                }
2603            }
2604        }
2605        details.insert("causeKind".to_owned(), serde_json::Value::from("status"));
2606        details.insert("httpStatus".to_owned(), serde_json::Value::from(status));
2607        error.details = Some(serde_json::Value::Object(details));
2608        error
2609    }
2610
2611    /// Reads a response body. `max` is the transport limit, refused with
2612    /// `transport.response_too_large`; `stop` is a declared `byteLength`
2613    /// (§5.4): reading ends once the body exceeds it and the caller rejects
2614    /// the longer body.
2615    fn read_body(
2616        resp: ureq::http::Response<ureq::Body>,
2617        mut progress: Option<&mut dyn FnMut(u64)>,
2618        max: Option<u64>,
2619        stop: Option<u64>,
2620    ) -> Result<Vec<u8>, TransportError> {
2621        redirect_refused(&resp)?;
2622        use std::io::Read;
2623        let status = resp.status().as_u16();
2624        let mut reader = resp.into_body().into_with_config().reader();
2625        let mut bytes = Vec::new();
2626        let mut chunk = [0u8; 64 * 1024];
2627        let mut reported = 0;
2628        loop {
2629            let n = reader
2630                .read(&mut chunk)
2631                .map_err(|error| match timeout_cause(&error) {
2632                    Some(cause) => timeout_error("response body read times out", cause),
2633                    None => transfer_error("response body read failed", "body", Some(status)),
2634                })?;
2635            if n == 0 {
2636                break;
2637            }
2638            // The cap counts decoded bytes: ureq's reader decompresses before
2639            // this loop, so a gzip bomb hits the limit before the buffer grows.
2640            if let Some(max) = max {
2641                if bytes.len() as u64 + n as u64 > max {
2642                    return Err(response_too_large(max));
2643                }
2644            }
2645            bytes.extend_from_slice(&chunk[..n]);
2646            if stop.is_some_and(|stop| bytes.len() as u64 > stop) {
2647                break;
2648            }
2649            if bytes.len() - reported >= 64 * 1024 {
2650                if let Some(callback) = progress.as_mut() {
2651                    callback(bytes.len() as u64);
2652                }
2653                reported = bytes.len();
2654            }
2655        }
2656        if bytes.len() != reported {
2657            if let Some(callback) = progress {
2658                callback(bytes.len() as u64);
2659            }
2660        }
2661        if status >= 400 {
2662            return Err(http_status_body_error(status, &bytes));
2663        }
2664        Ok(bytes)
2665    }
2666
2667    fn response_too_large(max: u64) -> TransportError {
2668        let mut error = TransportError::new(
2669            "transport.response_too_large",
2670            "response body exceeds the configured transport limit",
2671        );
2672        error.details = Some(serde_json::json!({ "limit": max }));
2673        error
2674    }
2675
2676    impl Transport for NativeTransport {
2677        fn sync(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
2678            self.post_sync("/sync", request)
2679        }
2680
2681        fn remote_operation(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
2682            self.post_operation(request)
2683        }
2684
2685        fn realtime_sync(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
2686            // §8.7 socket round: send the request as a `0x01`-tagged chunk on
2687            // the connected socket and block for the reassembled response
2688            // stream (the reader thread demuxes `0x01` chunks to END, routing
2689            // any `0x00` delta / text that interleaves to the inbound queue).
2690            // When no socket is connected this is the client's "not connected"
2691            // path — the caller (client core) only calls `realtime_sync` while
2692            // `realtime_connected`, and connect established the socket; a
2693            // missing socket here means the round rides HTTP instead (same
2694            // rule as the TS client: `POST /sync` when the socket is absent).
2695            if self.outgoing.is_none() {
2696                return self.post_sync("/sync", request);
2697            }
2698            self.round_remaining()?;
2699            let framed = self.round.begin(request)?;
2700            let (tag, body) = framed.split_first().expect("framed request carries a tag");
2701            for chunk in body.chunks(REQUEST_CHUNK_BYTES) {
2702                let mut message = Vec::with_capacity(chunk.len() + 1);
2703                message.push(*tag);
2704                message.extend_from_slice(chunk);
2705                if let Err(error) = self.send_message(Message::Binary(message.into())) {
2706                    self.round.fail_in_flight(error);
2707                    break;
2708                }
2709                self.round.progressed();
2710            }
2711            let outcome =
2712                self.round
2713                    .wait(self.round_deadline_at, ROUND_IDLE_TIMEOUT, self.drive_bound);
2714            // A round that ends without its response END leaves the rest of
2715            // that response in flight on the socket, and the next round would
2716            // read it as its own (§8.7). Close the connection and report the
2717            // loss; the reader thread already did both when the peer ended it.
2718            if let Err(error) = &outcome {
2719                if !self.round.lost() {
2720                    self.shutdown();
2721                    self.inbound.push(Inbound::Disconnected(error.clone()));
2722                }
2723            }
2724            outcome
2725        }
2726
2727        fn download_segment(
2728            &mut self,
2729            request: &SegmentRequest,
2730            on_progress: &mut dyn FnMut(u64),
2731        ) -> Result<Vec<u8>, TransportError> {
2732            // The FULL content address (`sha256:<hex>`) is the path param —
2733            // the reference server keys its segment store by it (§5.1) and
2734            // answers `sync.not_found` to a bare hex id. The requested-scopes
2735            // header carries what the pull round granted; the server
2736            // re-authorizes the download against it (§5.5) and answers
2737            // `sync.forbidden` when it is missing.
2738            let url = format!("{}/segments/{}", self.base_url, request.segment_id);
2739            self.authenticated(HeaderTarget::Segment, |headers| {
2740                let req = self.finish_request(
2741                    self.agent
2742                        .get(&url)
2743                        .header("x-syncular-scopes", &request.requested_scopes_json),
2744                    Some(headers),
2745                )?;
2746                let resp = req
2747                    .call()
2748                    .map_err(|error| segment_error(http_err("segment request failed", error)))?;
2749                read_body(
2750                    resp,
2751                    Some(&mut *on_progress),
2752                    self.policy.max_response_bytes,
2753                    Some(request.byte_length),
2754                )
2755                .map_err(segment_error)
2756            })
2757        }
2758
2759        fn supports_url_fetch(&self) -> bool {
2760            self.signed_urls
2761        }
2762
2763        fn download_segments(
2764            &mut self,
2765            fetches: &[SegmentFetch],
2766            on_progress: &mut (dyn FnMut(usize, u64) + Send),
2767        ) -> Vec<Result<Vec<u8>, TransportError>> {
2768            // A segment GET is pure network I/O over immutable transport
2769            // state, so a page list downloads on a bounded pool instead of one
2770            // blocking request after the other: four pages of a paged
2771            // bootstrap overlap (§5.2). `fork_round` hands each worker the same
2772            // agent (a cheap clone) and header source; the round's anchored deadline
2773            // is copied over explicitly, because a fork starts without one.
2774            // Every fetch is attempted; the client stops consuming at the
2775            // first error in wire order.
2776            let workers = (0..fetches.len().min(4))
2777                .map(|_| {
2778                    let mut worker = self.fork_round();
2779                    worker.round_deadline_at = self.round_deadline_at;
2780                    worker.drive_bound = self.drive_bound;
2781                    worker
2782                })
2783                .collect::<Vec<_>>();
2784            let slots = fetches.iter().map(|_| Mutex::new(None)).collect::<Vec<_>>();
2785            let progress = Mutex::new(on_progress);
2786            let next = std::sync::atomic::AtomicUsize::new(0);
2787            std::thread::scope(|scope| {
2788                for worker in workers {
2789                    let (slots, progress, next) = (&slots, &progress, &next);
2790                    scope.spawn(move || {
2791                        let mut worker = worker;
2792                        loop {
2793                            let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2794                            let Some(fetch) = fetches.get(index) else {
2795                                break;
2796                            };
2797                            let mut report = |bytes: u64| {
2798                                (*progress.lock().expect("segment progress lock"))(index, bytes);
2799                            };
2800                            let result = match fetch {
2801                                SegmentFetch::Direct(request) => {
2802                                    worker.download_segment(request, &mut report)
2803                                }
2804                                SegmentFetch::Url { url, byte_length } => {
2805                                    worker.fetch_url(url, *byte_length, &mut report)
2806                                }
2807                            };
2808                            *slots[index].lock().expect("segment result slot") = Some(result);
2809                        }
2810                    });
2811                }
2812            });
2813            slots
2814                .into_iter()
2815                .map(|slot| slot.into_inner().expect("segment result slot"))
2816                .map(|result| result.expect("every fetch is attempted"))
2817                .collect()
2818        }
2819
2820        fn fetch_url(
2821            &mut self,
2822            url: &str,
2823            byte_length: u64,
2824            on_progress: &mut dyn FnMut(u64),
2825        ) -> Result<Vec<u8>, TransportError> {
2826            // §5.4: the URL is the entire grant — no host credentials attached.
2827            let req = self.finish_request(self.agent.get(url), None)?;
2828            let resp = req
2829                .call()
2830                .map_err(|error| segment_error(http_err("segment request failed", error)))?;
2831            read_body(
2832                resp,
2833                Some(on_progress),
2834                self.policy.max_response_bytes,
2835                Some(byte_length),
2836            )
2837            .map_err(segment_error)
2838        }
2839
2840        fn blob_upload(
2841            &mut self,
2842            blob_id: &str,
2843            bytes: &[u8],
2844            media_type: Option<&str>,
2845        ) -> Result<(), TransportError> {
2846            // Full `sha256:<hex>` id in the path — the reference server's
2847            // isBlobId check rejects a bare hex id (§5.9.1).
2848            self.check_request_bytes(bytes.len() as u64)?;
2849            let url = format!("{}/blobs/{}", self.base_url, blob_id);
2850            self.authenticated(HeaderTarget::Blob, |headers| {
2851                let req = self.finish_request(
2852                    self.agent.put(&url).header(
2853                        "content-type",
2854                        media_type.unwrap_or("application/octet-stream"),
2855                    ),
2856                    Some(headers),
2857                )?;
2858                let resp = req
2859                    .send(bytes)
2860                    .map_err(|e| http_err("blob upload failed", e))?;
2861                read_body(resp, None, self.policy.max_response_bytes, None)
2862            })?;
2863            Ok(())
2864        }
2865
2866        fn blob_download(
2867            &mut self,
2868            blob_id: &str,
2869            byte_length: Option<u64>,
2870        ) -> Result<BlobDownload, TransportError> {
2871            // Full `sha256:<hex>` id in the path — the reference server's
2872            // isBlobId check rejects a bare hex id (§5.9.1).
2873            let url = format!("{}/blobs/{}", self.base_url, blob_id);
2874            let (is_json, body) = self.authenticated(HeaderTarget::Blob, |headers| {
2875                let req = self.finish_request(self.agent.get(&url), Some(headers))?;
2876                let resp = req.call().map_err(|cause| {
2877                    let status = match &cause {
2878                        ureq::Error::StatusCode(status) => Some(*status),
2879                        _ => None,
2880                    };
2881                    let mut error = http_err("blob download failed", cause);
2882                    match status {
2883                        Some(404) => {
2884                            error.code = "blob.not_found".into();
2885                            error.message = "blob not found".into();
2886                        }
2887                        Some(403) => {
2888                            error.code = "blob.forbidden".into();
2889                            error.message = "blob download forbidden".into();
2890                        }
2891                        Some(401) => {
2892                            error.code = "sync.auth_required".into();
2893                            error.message = "host authentication required".into();
2894                        }
2895                        _ => {}
2896                    }
2897                    error
2898                })?;
2899                // §5.9.5 always-issue: a JSON body carries a presigned `url`; an
2900                // octet-stream body is inline bytes.
2901                let is_json = resp
2902                    .headers()
2903                    .get(ureq::http::header::CONTENT_TYPE)
2904                    .and_then(|value| value.to_str().ok())
2905                    .is_some_and(|value| value.contains("application/json"));
2906                // A JSON envelope is not the blob body, so the declared size caps
2907                // inline bytes only.
2908                let stop = byte_length.filter(|_| !is_json);
2909                let body = read_body(resp, None, self.policy.max_response_bytes, stop).map_err(
2910                    |mut error| {
2911                        // The blob endpoint keeps its status classification: an
2912                        // error body supplies details, but the HTTP status decides
2913                        // the code.
2914                        let status = error
2915                            .details
2916                            .as_ref()
2917                            .filter(|details| {
2918                                details.get("causeKind").and_then(serde_json::Value::as_str)
2919                                    == Some("status")
2920                            })
2921                            .and_then(|details| details.get("httpStatus"))
2922                            .and_then(serde_json::Value::as_u64);
2923                        match status {
2924                            Some(404) => {
2925                                error.code = "blob.not_found".into();
2926                                error.message = "blob not found".into();
2927                            }
2928                            Some(403) => {
2929                                error.code = "blob.forbidden".into();
2930                                error.message = "blob download forbidden".into();
2931                            }
2932                            Some(401) => {
2933                                error.code = "sync.auth_required".into();
2934                                error.message = "host authentication required".into();
2935                            }
2936                            Some(_) => {
2937                                error.code = "transport.failed".into();
2938                                error.message = "blob download failed".into();
2939                            }
2940                            None => {}
2941                        }
2942                        error
2943                    },
2944                )?;
2945                Ok((is_json, body))
2946            })?;
2947            if is_json {
2948                if let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&body) {
2949                    if let Some(u) = parsed.get("url").and_then(|v| v.as_str()) {
2950                        return Ok(BlobDownload::Url {
2951                            url: u.to_owned(),
2952                            url_expires_at_ms: parsed
2953                                .get("urlExpiresAtMs")
2954                                .and_then(|v| v.as_i64()),
2955                        });
2956                    }
2957                }
2958            }
2959            Ok(BlobDownload::Bytes(body))
2960        }
2961
2962        fn fetch_blob_url(
2963            &mut self,
2964            url: &str,
2965            byte_length: Option<u64>,
2966        ) -> Result<Vec<u8>, TransportError> {
2967            // §5.9.5: the URL is the entire grant — no host credentials, and
2968            // the URL capability makes the request credential bearing.
2969            let req = self.finish_request(self.agent.get(url), None)?;
2970            let resp = req.call().map_err(|e| http_err("URL fetch failed", e))?;
2971            read_body(resp, None, self.policy.max_response_bytes, byte_length)
2972        }
2973
2974        fn blob_upload_grant(
2975            &mut self,
2976            blob_id: &str,
2977            byte_length: u64,
2978            media_type: Option<&str>,
2979        ) -> Result<BlobUploadGrant, TransportError> {
2980            let url = format!("{}/blobs/{}/upload-grant", self.base_url, blob_id);
2981            let body = serde_json::json!({
2982                "byteLength": byte_length,
2983                "mediaType": media_type,
2984            })
2985            .to_string();
2986            self.check_request_bytes(body.len() as u64)?;
2987            let grant_body = self.authenticated(HeaderTarget::Blob, |headers| {
2988                let req = self.finish_request(
2989                    self.agent
2990                        .post(&url)
2991                        .header("content-type", "application/json"),
2992                    Some(headers),
2993                )?;
2994                let resp = req
2995                    .send(body.as_bytes())
2996                    .map_err(|e| http_err("blob upload grant request failed", e))?;
2997                read_body(resp, None, self.policy.max_response_bytes, None)
2998            })?;
2999            let parsed: serde_json::Value = serde_json::from_slice(&grant_body)
3000                .map_err(|_| transfer_error("blob upload grant decode failed", "decode", None))?;
3001            if let Some(u) = parsed.get("url").and_then(|v| v.as_str()) {
3002                return Ok(BlobUploadGrant::Url {
3003                    url: u.to_owned(),
3004                    url_expires_at_ms: parsed.get("urlExpiresAtMs").and_then(|v| v.as_i64()),
3005                });
3006            }
3007            if parsed.get("present").and_then(|v| v.as_bool()) == Some(true) {
3008                return Ok(BlobUploadGrant::Present);
3009            }
3010            Ok(BlobUploadGrant::None)
3011        }
3012
3013        fn blob_put_url(
3014            &mut self,
3015            blob_id: &str,
3016            url: &str,
3017            bytes: &[u8],
3018            media_type: Option<&str>,
3019        ) -> Result<(), TransportError> {
3020            // §5.9.3: the presigned URL is the entire grant — no host auth.
3021            // The grant signs content-length (ureq sets it from the body) and
3022            // the checksum, the blob id's digest, so the object store rejects
3023            // any other bytes without the client hashing the body again.
3024            let digest = blob_id
3025                .strip_prefix("sha256:")
3026                .filter(|hex| {
3027                    hex.len() == 64
3028                        && hex
3029                            .bytes()
3030                            .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
3031                })
3032                .map(|hex| {
3033                    (0..64)
3034                        .step_by(2)
3035                        .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).expect("hex digits"))
3036                        .collect::<Vec<u8>>()
3037                })
3038                .ok_or_else(|| {
3039                    TransportError::new(
3040                        "sync.invalid_request",
3041                        "the blob id is not a sha256 blob id (§5.9.1)",
3042                    )
3043                })?;
3044            self.check_request_bytes(bytes.len() as u64)?;
3045            let req = self.finish_request(
3046                self.agent
3047                    .put(url)
3048                    .header(
3049                        "content-type",
3050                        media_type.unwrap_or("application/octet-stream"),
3051                    )
3052                    .header("x-amz-checksum-sha256", ssp2::util::base64(&digest)),
3053                None,
3054            )?;
3055            let resp = req
3056                .send(bytes)
3057                .map_err(|e| http_err("signed blob upload failed", e))?;
3058            read_body(resp, None, self.policy.max_response_bytes, None)?;
3059            Ok(())
3060        }
3061
3062        fn realtime_connect(&mut self, client_id: &str) -> Result<(), TransportError> {
3063            if self.outgoing.is_some() {
3064                if self.reader_stop.load(Ordering::SeqCst)
3065                    || self
3066                        .reader
3067                        .as_ref()
3068                        .is_some_and(|reader| reader.is_finished())
3069                {
3070                    self.shutdown();
3071                } else {
3072                    return Ok(());
3073                }
3074            }
3075            // Build the client request VIA `IntoClientRequest` so tungstenite
3076            // fills the mandatory handshake headers (Host / Connection /
3077            // Upgrade / Sec-WebSocket-Version / Sec-WebSocket-Key); a
3078            // hand-built `http::Request` is taken as-is and would omit them.
3079            // Then layer the header source's auth/actor headers on top; a
3080            // handshake answered 401 reads the source again and retries once.
3081            use tungstenite::client::IntoClientRequest;
3082            let mut url = url::Url::parse(&self.ws_url)
3083                .map_err(|_| transfer_error("realtime URL invalid", "request", None))?;
3084            let retained_query: Vec<(String, String)> = url
3085                .query_pairs()
3086                .filter(|(key, _)| key != "clientId")
3087                .map(|(key, value)| (key.into_owned(), value.into_owned()))
3088                .collect();
3089            url.set_query(None);
3090            url.query_pairs_mut()
3091                .extend_pairs(retained_query)
3092                .append_pair("clientId", client_id);
3093            // The bounded establishment never follows a redirect, so a transport configured with
3094            // `RedirectPolicy::Follow` fails here instead of having the policy silently ignored.
3095            if self.policy.redirects == RedirectPolicy::Follow {
3096                return Err(redirect_error(
3097                    "realtime establishment does not follow redirects",
3098                    None,
3099                ));
3100            }
3101            let mut ws = self.authenticated(HeaderTarget::Realtime, |headers| {
3102                let mut request = url
3103                    .as_str()
3104                    .into_client_request()
3105                    .map_err(|error| ws_err("realtime request failed", error))?;
3106                let out = request.headers_mut();
3107                for (k, v) in headers {
3108                    if let (Ok(name), Ok(value)) = (
3109                        tungstenite::http::HeaderName::try_from(k.as_str()),
3110                        tungstenite::http::HeaderValue::try_from(v.as_str()),
3111                    ) {
3112                        out.insert(name, value);
3113                    }
3114                }
3115                connect_websocket(request, Instant::now() + CONNECT_TIMEOUT)
3116            })?;
3117            let stream = match ws.get_mut() {
3118                MaybeTlsStream::Plain(stream) => stream.established(),
3119                MaybeTlsStream::Rustls(stream) => stream.get_mut().established(),
3120                _ => {
3121                    return Err(TransportError::new(
3122                        "transport.failed",
3123                        "unsupported websocket stream",
3124                    ))
3125                }
3126            }
3127            .map_err(|e| io_err("realtime clone failed", e))?;
3128            stream
3129                .set_nonblocking(true)
3130                .map_err(|e| io_err("realtime nonblocking failed", e))?;
3131            let poller = Arc::new(Poller::new().map_err(|e| io_err("realtime poller failed", e))?);
3132            // SAFETY: SocketRegistration owns this handle and unregisters it before drop.
3133            unsafe { poller.add(&stream, Event::readable(0)) }
3134                .map_err(|e| io_err("realtime register failed", e))?;
3135            let registration = SocketRegistration {
3136                poller: Arc::clone(&poller),
3137                stream,
3138            };
3139            let (outgoing, queued) = mpsc::sync_channel::<Outgoing>(1);
3140            self.outgoing = Some(Box::new(SocketSender {
3141                queue: outgoing,
3142                poller,
3143            }));
3144            self.reader_stop = Arc::new(AtomicBool::new(false));
3145            self.round = Arc::new(RoundChannel::default());
3146            let inbound = Arc::clone(&self.inbound);
3147            let stop = Arc::clone(&self.reader_stop);
3148            let round = Arc::clone(&self.round);
3149            // §8.5: the connection's first heartbeat arms the watchdog; once
3150            // armed, any inbound frame proves the socket and twice the
3151            // heartbeat interval of silence loses it. A server that sends no
3152            // heartbeats never arms it.
3153            let silence = 2 * self
3154                .policy
3155                .realtime_heartbeat
3156                .unwrap_or(Duration::from_secs(30));
3157            self.reader = Some(std::thread::spawn(move || {
3158                let mut events = Events::new();
3159                let mut pending: Option<mpsc::Sender<Result<(), TransportError>>> = None;
3160                let mut heard: Option<Instant> = None;
3161                let failure = 'io: loop {
3162                    if stop.load(Ordering::SeqCst) {
3163                        let _ = ws.close(None);
3164                        let _ = ws.flush();
3165                        break TransportError::new(
3166                            "sync.transport_failed",
3167                            "realtime disconnected mid-round (§8.7)",
3168                        );
3169                    }
3170                    if pending.is_none() {
3171                        if let Ok(outgoing) = queued.try_recv() {
3172                            pending = Some(outgoing.completed);
3173                            // WouldBlock retains the frame in tungstenite's write buffer.
3174                            if let Err(error) = ws.write(outgoing.message) {
3175                                if !is_would_block(&error) {
3176                                    break ws_err("realtime write failed", error);
3177                                }
3178                            }
3179                        }
3180                    }
3181                    // Bound receive work so a continuously readable peer cannot starve sends.
3182                    let mut drained = false;
3183                    for _ in 0..64 {
3184                        let received = ws.read();
3185                        if let Ok(message) = &received {
3186                            let armed = heard.is_some()
3187                                || matches!(message, Message::Text(text)
3188                                    if serde_json::from_str::<serde_json::Value>(text)
3189                                        .is_ok_and(|event| event["event"] == "heartbeat"));
3190                            if armed {
3191                                heard = Some(Instant::now());
3192                            }
3193                            let kind = match message {
3194                                Message::Text(_) => Some(RealtimeReceiptKind::Text),
3195                                Message::Binary(bytes) => Some(match bytes.first() {
3196                                    Some(&crate::REALTIME_TAG_DELTA) => RealtimeReceiptKind::Delta,
3197                                    Some(&crate::REALTIME_TAG_ROUND) => RealtimeReceiptKind::Round,
3198                                    _ => RealtimeReceiptKind::OtherBinary,
3199                                }),
3200                                Message::Ping(_) => Some(RealtimeReceiptKind::Ping),
3201                                Message::Pong(_) => Some(RealtimeReceiptKind::Pong),
3202                                Message::Close(_) => Some(RealtimeReceiptKind::Close),
3203                                Message::Frame(_) => None,
3204                            };
3205                            if let Some(kind) = kind {
3206                                let bytes = match message {
3207                                    Message::Close(Some(close)) => 2 + close.reason.len(),
3208                                    _ => message.len(),
3209                                };
3210                                inbound.observe(kind, bytes);
3211                            }
3212                        }
3213                        match received {
3214                            Ok(Message::Text(text)) => {
3215                                inbound.push(Inbound::Text(text.to_string()))
3216                            }
3217                            Ok(Message::Binary(bytes)) => {
3218                                if let Some(delta) = round.route_binary(&bytes) {
3219                                    inbound.push(Inbound::Binary(delta));
3220                                }
3221                            }
3222                            Err(error) if is_would_block(&error) => {
3223                                drained = true;
3224                                break;
3225                            }
3226                            Ok(Message::Close(_)) => {
3227                                let _ = ws.flush();
3228                                break 'io TransportError::new(
3229                                    "sync.transport_failed",
3230                                    "realtime disconnected mid-round (§8.7)",
3231                                );
3232                            }
3233                            Err(_) => {
3234                                break 'io TransportError::new(
3235                                    "sync.transport_failed",
3236                                    "realtime disconnected mid-round (§8.7)",
3237                                );
3238                            }
3239                            Ok(_) => {}
3240                        }
3241                        // A host that does not drain loses the socket instead
3242                        // of growing the buffer (§8.8).
3243                        if inbound.overflowed() {
3244                            let _ = ws.close(None);
3245                            let _ = ws.flush();
3246                            let mut error = TransportError::new(
3247                                "transport.failed",
3248                                "realtime inbound buffer is full",
3249                            );
3250                            error.details = Some(serde_json::json!({
3251                                "causeKind": "inbound_overflow",
3252                                "limit": super::INBOUND_BUFFER_LIMIT_BYTES,
3253                            }));
3254                            break 'io error;
3255                        }
3256                    }
3257                    let interest = match ws.flush() {
3258                        Ok(()) => {
3259                            if let Some(completed) = pending.take() {
3260                                let _ = completed.send(Ok(()));
3261                            }
3262                            Event::readable(0)
3263                        }
3264                        Err(error) if is_would_block(&error) => Event::all(0),
3265                        Err(error) => break ws_err("realtime flush failed", error),
3266                    };
3267                    if !drained {
3268                        continue;
3269                    }
3270                    if let Err(error) = registration.poller.modify(&registration.stream, interest) {
3271                        break io_err("realtime rearm failed", error);
3272                    }
3273                    let wait = heard
3274                        .map(|heard| (heard + silence).saturating_duration_since(Instant::now()));
3275                    if wait.is_some_and(|wait| wait.is_zero()) {
3276                        break timeout_error("realtime heartbeat missed", "heartbeat");
3277                    }
3278                    events.clear();
3279                    if let Err(error) = registration.poller.wait(&mut events, wait) {
3280                        if error.kind() != std::io::ErrorKind::Interrupted {
3281                            break io_err("realtime wait failed", error);
3282                        }
3283                    }
3284                };
3285                // Publish before waking a round/send waiter: the host must
3286                // drain this old connection's event before it can reconnect.
3287                // An idle close has no round waiter at all. Explicit shutdown
3288                // is owned by its caller and must not leave a stale close.
3289                if !stop.load(Ordering::SeqCst) {
3290                    inbound.push(Inbound::Disconnected(failure.clone()));
3291                }
3292                if let Some(completed) = pending {
3293                    let _ = completed.send(Err(failure.clone()));
3294                }
3295                while let Ok(outgoing) = queued.try_recv() {
3296                    let _ = outgoing.completed.send(Err(failure.clone()));
3297                }
3298                round.fail_in_flight(failure);
3299            }));
3300            Ok(())
3301        }
3302
3303        fn realtime_send(&mut self, text: &str) -> Result<(), TransportError> {
3304            self.send_message(Message::Text(text.to_owned().into()))
3305        }
3306
3307        fn realtime_close(&mut self) -> Result<(), TransportError> {
3308            self.shutdown();
3309            Ok(())
3310        }
3311
3312        fn round_deadline(&self) -> Option<Duration> {
3313            NativeTransport::round_deadline(self)
3314        }
3315
3316        fn set_round_deadline(&mut self, deadline: Option<std::time::Instant>) {
3317            NativeTransport::set_round_deadline(self, deadline);
3318        }
3319
3320        fn set_idle_bound(&mut self, bound: Option<Duration>) {
3321            self.drive_bound = bound;
3322        }
3323
3324        fn set_client_id(&mut self, client_id: &str) {
3325            self.client_id = client_id.to_owned();
3326        }
3327
3328        fn set_round(&mut self, attempt: Option<u64>) {
3329            self.round_attempt = attempt;
3330        }
3331    }
3332    #[cfg(test)]
3333    mod transfer_tests {
3334        use super::*;
3335        use ureq::unversioned::resolver::DefaultResolver;
3336        use ureq::unversioned::transport::{ConnectionDetails, Connector};
3337
3338        const SECRET: &str = "https://user:password@cdn.example/secret-capability-path?secret-query=value#secret-fragment";
3339
3340        #[derive(Debug)]
3341        struct SecretError;
3342        impl std::fmt::Display for SecretError {
3343            fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3344                panic!("transport error must never be formatted")
3345            }
3346        }
3347        impl std::error::Error for SecretError {}
3348
3349        #[derive(Debug)]
3350        struct FailingConnector(&'static str);
3351        impl Connector for FailingConnector {
3352            type Out = ();
3353            fn connect(
3354                &self,
3355                _: &ConnectionDetails,
3356                _: Option<()>,
3357            ) -> Result<Option<()>, ureq::Error> {
3358                Err(match self.0 {
3359                    "io" => ureq::Error::Io(std::io::Error::new(
3360                        std::io::ErrorKind::ConnectionRefused,
3361                        format!("404 {SECRET}"),
3362                    )),
3363                    "tls" => ureq::Error::Tls(SECRET),
3364                    "request" => ureq::Error::BadUri(SECRET.into()),
3365                    "timeout" => ureq::Error::Timeout(ureq::Timeout::RecvResponse),
3366                    "round_deadline" => ureq::Error::Timeout(ureq::Timeout::Global),
3367                    "404" => ureq::Error::StatusCode(404),
3368                    "401" => ureq::Error::StatusCode(401),
3369                    "403" => ureq::Error::StatusCode(403),
3370                    "503" => ureq::Error::StatusCode(503),
3371                    _ => ureq::Error::Other(Box::new(SecretError)),
3372                })
3373            }
3374        }
3375
3376        #[test]
3377        fn injected_http_failures_never_expose_capabilities_or_format_the_cause() {
3378            for kind in [
3379                "io",
3380                "tls",
3381                "request",
3382                "timeout",
3383                "round_deadline",
3384                "unknown",
3385                "404",
3386                "401",
3387                "403",
3388                "503",
3389            ] {
3390                for operation in [
3391                    "sync",
3392                    "remote",
3393                    "segment",
3394                    "signed_segment",
3395                    "blob",
3396                    "signed_blob",
3397                    "upload",
3398                    "grant",
3399                    "signed_put",
3400                ] {
3401                    let mut transport =
3402                        NativeTransport::new("http://127.0.0.1", &serde_json::json!({}), None)
3403                            .unwrap();
3404                    transport.agent = ureq::Agent::with_parts(
3405                        ureq::Agent::config_builder().build(),
3406                        FailingConnector(kind),
3407                        DefaultResolver::default(),
3408                    );
3409                    let mut progress = |_| {};
3410                    let result = match operation {
3411                        "sync" => transport.sync(&[]).map(|_| ()),
3412                        "remote" => transport.remote_operation(&[]).map(|_| ()),
3413                        "segment" => transport.download_segment(&SegmentRequest { segment_id: "sha256:test".into(), table: "tasks".into(), requested_scopes_json: "{}".into(), byte_length: 1 << 20 }, &mut progress).map(|_| ()),
3414                        "signed_segment" => transport.fetch_url("http://127.0.0.1/secret-capability-path?secret-query=value#secret-fragment", 1 << 20, &mut progress).map(|_| ()),
3415                        "blob" => transport.blob_download("sha256:test", None).map(|_| ()),
3416                        "signed_blob" => transport.fetch_blob_url("http://127.0.0.1/secret-capability-path?secret-query=value#secret-fragment", None).map(|_| ()),
3417                        "upload" => transport.blob_upload("sha256:test", &[], None),
3418                        "grant" => transport.blob_upload_grant("sha256:test", 0, None).map(|_| ()),
3419                        _ => transport.blob_put_url(&format!("sha256:{}", "0".repeat(64)), "http://127.0.0.1/secret-capability-path?secret-query=value#secret-fragment", &[], None),
3420                    };
3421                    let error = result.unwrap_err();
3422                    let expected_code = match (operation, kind) {
3423                        (_, "timeout" | "round_deadline") => "transport.timeout",
3424                        ("segment" | "signed_segment", _) => "sync.transport_failed",
3425                        ("blob", "404") => "blob.not_found",
3426                        ("blob", "401") => "sync.auth_required",
3427                        ("blob", "403") => "blob.forbidden",
3428                        _ => "transport.failed",
3429                    };
3430                    assert_eq!(error.code, expected_code, "{operation} {kind}");
3431                    let details = error.details.unwrap();
3432                    assert_eq!(
3433                        details["causeKind"],
3434                        match kind {
3435                            "io" => "connect",
3436                            "404" | "401" | "403" | "503" => "status",
3437                            other => other,
3438                        }
3439                    );
3440                    assert_eq!(
3441                        details.get("httpStatus").and_then(|value| value.as_u64()),
3442                        kind.parse::<u64>().ok()
3443                    );
3444                    let rendered = format!("{}{}", error.message, details);
3445                    for secret in [
3446                        "http://",
3447                        "https://",
3448                        "password",
3449                        "secret-capability-path",
3450                        "secret-query",
3451                        "secret-fragment",
3452                    ] {
3453                        assert!(!rendered.contains(secret), "{operation} {kind}");
3454                    }
3455                    assert!(details.get("causeMessage").is_none());
3456                    assert!(details.get("path").is_none());
3457                }
3458            }
3459        }
3460
3461        #[test]
3462        fn injected_body_and_websocket_errors_do_not_expose_payloads_or_source_chains() {
3463            struct FailingRead;
3464            impl std::io::Read for FailingRead {
3465                fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
3466                    Err(std::io::Error::other(SECRET))
3467                }
3468            }
3469            let response = ureq::http::Response::builder()
3470                .status(200)
3471                .body(ureq::Body::builder().reader(FailingRead))
3472                .unwrap();
3473            let error = segment_error(read_body(response, None, None, None).unwrap_err());
3474            assert_eq!(error.code, "sync.transport_failed");
3475            assert_eq!(error.message, "segment transfer failed");
3476            assert_eq!(
3477                error.details,
3478                Some(serde_json::json!({ "causeKind": "body", "httpStatus": 200 }))
3479            );
3480            for cause in [
3481                tungstenite::Error::Io(std::io::Error::other(SecretError)),
3482                tungstenite::Error::Http(Box::new(
3483                    tungstenite::http::Response::builder()
3484                        .status(403)
3485                        .header("location", SECRET)
3486                        .body(Some(SECRET.as_bytes().to_vec()))
3487                        .unwrap(),
3488                )),
3489            ] {
3490                let error = ws_err("realtime connection failed", cause);
3491                assert_eq!(error.message, "realtime connection failed");
3492                let details = error.details.unwrap();
3493                assert!(details.get("path").is_none());
3494                assert!(details.get("causeMessage").is_none());
3495                assert!(!details.to_string().contains("secret"));
3496            }
3497        }
3498
3499        #[test]
3500        fn body_read_timeouts_are_classified_through_ureq_wrapping() {
3501            // Direct: Error::into_io boxes a non-io ureq error as io::Error::other.
3502            let direct = ureq::Error::Timeout(ureq::Timeout::RecvBody).into_io();
3503            assert_eq!(timeout_cause(&direct), Some("timeout"));
3504            // Compressed: gzip wraps the io error again as Error::Decompress.
3505            let wrapped = ureq::Error::Decompress(
3506                "gzip",
3507                ureq::Error::Timeout(ureq::Timeout::Global).into_io(),
3508            )
3509            .into_io();
3510            assert_eq!(timeout_cause(&wrapped), Some("round_deadline"));
3511            // Only the drive bound sets per-read and per-write timeouts.
3512            for reason in [ureq::Timeout::PerRead, ureq::Timeout::PerWrite] {
3513                assert_eq!(
3514                    timeout_cause(&ureq::Error::Timeout(reason).into_io()),
3515                    Some("drive")
3516                );
3517                let error = http_err("sync request failed", ureq::Error::Timeout(reason));
3518                assert_eq!(error.code, "sync.idle_timeout");
3519                assert_eq!(error.details, None, "the round adds the drive's details");
3520            }
3521            // A plain socket timeout and a non-timeout are handled too.
3522            assert_eq!(
3523                timeout_cause(&std::io::Error::new(std::io::ErrorKind::TimedOut, "plain")),
3524                Some("timeout")
3525            );
3526            assert_eq!(timeout_cause(&std::io::Error::other("other")), None);
3527            assert_eq!(timeout_cause(&ureq::Error::StatusCode(500).into_io()), None);
3528        }
3529
3530        #[test]
3531        fn body_read_wrapped_timeouts_surface_the_typed_code() {
3532            struct TimeoutRead(bool);
3533            impl std::io::Read for TimeoutRead {
3534                fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
3535                    Err(if self.0 {
3536                        ureq::Error::Timeout(ureq::Timeout::RecvBody).into_io()
3537                    } else {
3538                        ureq::Error::Decompress(
3539                            "gzip",
3540                            ureq::Error::Timeout(ureq::Timeout::RecvBody).into_io(),
3541                        )
3542                        .into_io()
3543                    })
3544                }
3545            }
3546            for compressed in [false, true] {
3547                let response = ureq::http::Response::builder()
3548                    .status(200)
3549                    .body(ureq::Body::builder().reader(TimeoutRead(compressed)))
3550                    .unwrap();
3551                let error = read_body(response, None, None, None).unwrap_err();
3552                assert_eq!(error.code, "transport.timeout", "{compressed}");
3553                assert_eq!(
3554                    error.details,
3555                    Some(serde_json::json!({ "causeKind": "timeout" }))
3556                );
3557            }
3558        }
3559
3560        #[test]
3561        fn policy_validation_rejects_zero_and_unrepresentable_bounds() {
3562            assert_eq!(
3563                HostTransportPolicy {
3564                    request_timeout: Some(Duration::ZERO),
3565                    ..Default::default()
3566                }
3567                .validate()
3568                .unwrap_err(),
3569                "sync.invalid_request: transport config requestTimeoutMs is out of range"
3570            );
3571            assert_eq!(
3572                HostTransportPolicy {
3573                    round_deadline: Some(Duration::MAX),
3574                    ..Default::default()
3575                }
3576                .validate()
3577                .unwrap_err(),
3578                "sync.invalid_request: transport config roundDeadlineMs is out of range"
3579            );
3580            for interval in [Duration::ZERO, Duration::MAX / 2 + Duration::from_secs(1)] {
3581                assert_eq!(
3582                    HostTransportPolicy {
3583                        realtime_heartbeat: Some(interval),
3584                        ..Default::default()
3585                    }
3586                    .validate()
3587                    .unwrap_err(),
3588                    "sync.invalid_request: transport config realtimeHeartbeatMs is out of range"
3589                );
3590            }
3591            assert!(HostTransportPolicy {
3592                max_request_bytes: Some(0),
3593                ..Default::default()
3594            }
3595            .validate()
3596            .is_err());
3597            assert!(HostTransportPolicy {
3598                max_response_bytes: Some(0),
3599                ..Default::default()
3600            }
3601            .validate()
3602            .is_err());
3603            // A programmatic zero or an unrepresentable duration matches the
3604            // JSON rejection instead of panicking at `Instant::now() + budget`.
3605            assert!(HostTransportPolicy::default().validate().is_ok());
3606            assert_eq!(
3607                HostTransportPolicy::from_config(&serde_json::json!({ "requestTimeoutMs": 0 }))
3608                    .unwrap_err(),
3609                "sync.invalid_request: transport config requestTimeoutMs must be a positive integer"
3610            );
3611        }
3612
3613        #[test]
3614        fn set_policy_rejects_invalid_and_preserves_the_current_policy() {
3615            let mut transport =
3616                NativeTransport::new("http://127.0.0.1", &serde_json::json!({}), None).unwrap();
3617            assert_eq!(transport.policy.max_response_bytes, None);
3618            let error = transport
3619                .set_policy(HostTransportPolicy {
3620                    max_response_bytes: Some(0),
3621                    ..Default::default()
3622                })
3623                .unwrap_err();
3624            assert_eq!(
3625                error,
3626                "sync.invalid_request: transport config maxResponseBytes must be a positive integer"
3627            );
3628            assert_eq!(transport.policy.max_response_bytes, None);
3629        }
3630
3631        #[test]
3632        fn an_expired_round_deadline_is_typed_and_cleared_for_the_next_round() {
3633            let mut transport =
3634                NativeTransport::new("http://127.0.0.1:9", &serde_json::json!({}), None).unwrap();
3635            transport.set_round_deadline(Some(std::time::Instant::now() - Duration::from_secs(1)));
3636            let error = transport.blob_download("sha256:test", None).unwrap_err();
3637            assert_eq!(error.code, "transport.timeout");
3638            assert_eq!(
3639                error.details,
3640                Some(serde_json::json!({ "causeKind": "round_deadline" }))
3641            );
3642            // Clearing the scope leaves no stale deadline for the next round.
3643            transport.set_round_deadline(None);
3644            assert!(transport.round_remaining().is_ok());
3645        }
3646
3647        #[test]
3648        fn an_expired_round_deadline_refuses_before_queuing_a_realtime_send() {
3649            let mut transport =
3650                NativeTransport::new("http://127.0.0.1:9", &serde_json::json!({}), None).unwrap();
3651            transport.set_round_deadline(Some(std::time::Instant::now() - Duration::from_secs(1)));
3652            // The refusal precedes the connection check, so a not-connected
3653            // transport reports the typed round timeout and leaves no frame
3654            // queued behind it for a later send.
3655            let error = transport.realtime_send("blocked").unwrap_err();
3656            assert_eq!(error.code, "transport.timeout");
3657            assert_eq!(
3658                error.details,
3659                Some(serde_json::json!({ "causeKind": "round_deadline" }))
3660            );
3661            // With the deadline cleared the same call reaches the connection
3662            // check instead.
3663            transport.set_round_deadline(None);
3664            let error = transport.realtime_send("blocked").unwrap_err();
3665            assert_eq!(error.code, "transport.failed");
3666        }
3667
3668        #[test]
3669        fn the_request_timeout_bounds_phases_and_the_round_deadline_bounds_the_call() {
3670            #[derive(Debug)]
3671            struct TimeoutRecording(Arc<Mutex<Vec<[Option<Duration>; 3]>>>);
3672            impl Connector for TimeoutRecording {
3673                type Out = ();
3674                fn connect(
3675                    &self,
3676                    details: &ConnectionDetails,
3677                    _: Option<()>,
3678                ) -> Result<Option<()>, ureq::Error> {
3679                    self.0.lock().unwrap().push([
3680                        details.config.timeouts().global,
3681                        details.config.timeout_per_read(),
3682                        details.config.timeout_per_write(),
3683                    ]);
3684                    Err(ureq::Error::ConnectionFailed)
3685                }
3686            }
3687            let mut transport =
3688                NativeTransport::new("http://127.0.0.1", &serde_json::json!({}), None).unwrap();
3689            transport
3690                .set_policy(HostTransportPolicy {
3691                    request_timeout: Some(Duration::from_millis(1234)),
3692                    ..Default::default()
3693                })
3694                .unwrap();
3695            let timeouts = transport.agent.config().timeouts();
3696            for phase in [
3697                timeouts.resolve,
3698                timeouts.connect,
3699                timeouts.send_request,
3700                timeouts.recv_response,
3701            ] {
3702                assert_eq!(phase, Some(Duration::from_millis(1234)));
3703            }
3704            assert_eq!(timeouts.global, None, "the request bound is not end to end");
3705            assert_eq!(timeouts.recv_body, None, "a body is bounded by silence");
3706            let seen = Arc::new(Mutex::new(Vec::new()));
3707            transport.agent = ureq::Agent::with_parts(
3708                ureq::Agent::config_builder().build(),
3709                TimeoutRecording(Arc::clone(&seen)),
3710                DefaultResolver::default(),
3711            );
3712            let _ = transport.blob_upload("sha256:test", &[0u8; 4], None);
3713            transport.set_round_deadline(Some(std::time::Instant::now() + Duration::from_secs(60)));
3714            let _ = transport.blob_upload("sha256:test", &[0u8; 4], None);
3715            // §7.8: the drive bound caps every read and write, which restarts it,
3716            // and leaves the host's absolute ceiling as it is.
3717            transport.set_idle_bound(Some(Duration::from_secs(60)));
3718            let _ = transport.sync(&[]);
3719            let seen = seen.lock().unwrap();
3720            assert_eq!(
3721                seen[0],
3722                [None, None, None],
3723                "no round deadline, no call ceiling"
3724            );
3725            assert!(seen[1][0].is_some_and(|ceiling| ceiling <= Duration::from_secs(60)));
3726            assert_eq!(seen[1][1..], [None, None]);
3727            assert!(seen[2][0].is_some_and(|ceiling| ceiling <= Duration::from_secs(60)));
3728            let drive = Some(Duration::from_secs(60));
3729            assert_eq!(seen[2][1..], [drive, drive]);
3730        }
3731
3732        #[test]
3733        fn the_idle_bound_replaces_an_unbounded_or_longer_wait_and_keeps_a_shorter_one() {
3734            let idle = Duration::from_secs(30);
3735            let unbounded = NextTimeout::default();
3736            assert_eq!(idle_bound(unbounded, idle).after, UreqDuration::Exact(idle));
3737            let longer = NextTimeout {
3738                after: UreqDuration::from_secs(90),
3739                per_read: Some(UreqDuration::from_secs(7)),
3740                ..NextTimeout::default()
3741            };
3742            let bounded = idle_bound(longer, idle);
3743            assert_eq!(bounded.after, UreqDuration::Exact(idle));
3744            assert_eq!(bounded.reason, UreqTimeout::RecvBody);
3745            assert_eq!(
3746                bounded.per_read, longer.per_read,
3747                "per-read cap passes through"
3748            );
3749            let shorter = NextTimeout {
3750                after: UreqDuration::from_secs(5),
3751                ..NextTimeout::default()
3752            };
3753            assert_eq!(idle_bound(shorter, idle), shorter);
3754        }
3755
3756        /// Arrival offsets of a response of `total` bytes in `chunk`-byte
3757        /// pieces over a link with a one-way `latency`, a `rate` in bytes per
3758        /// second, and `stalls` (start, length) windows in which nothing
3759        /// arrives. Virtual time: nothing sleeps.
3760        fn shaped_link(
3761            total: u64,
3762            chunk: u64,
3763            latency: Duration,
3764            rate: u64,
3765            stalls: &[(Duration, Duration)],
3766        ) -> Vec<Duration> {
3767            let mut at = latency;
3768            let mut arrivals = Vec::new();
3769            let mut left = total;
3770            while left > 0 {
3771                let piece = left.min(chunk);
3772                at += Duration::from_micros(piece * 1_000_000 / rate);
3773                for (start, length) in stalls {
3774                    if at > *start && at < *start + *length {
3775                        at = *start + *length;
3776                    }
3777                }
3778                arrivals.push(at);
3779                left -= piece;
3780            }
3781            arrivals
3782        }
3783
3784        /// Run `round_expiry` over a link: `Ok(finished_at)` when every chunk
3785        /// arrives before a bound, `Err((expired_at, expiry))` otherwise.
3786        fn round_over(
3787            arrivals: &[Duration],
3788            idle: Duration,
3789            drive: Option<Duration>,
3790            ceiling: Option<Duration>,
3791        ) -> Result<Duration, (Duration, Expiry)> {
3792            let base = Instant::now();
3793            let mut last = base;
3794            for arrival in arrivals {
3795                let (deadline, expiry) =
3796                    round_expiry(last, idle, drive, ceiling.map(|ceiling| base + ceiling));
3797                if base + *arrival > deadline {
3798                    return Err((deadline - base, expiry));
3799                }
3800                last = base + *arrival;
3801            }
3802            Ok(last - base)
3803        }
3804
3805        #[test]
3806        fn a_slow_link_that_keeps_delivering_never_trips_the_idle_bound() {
3807            // Nori's phone behind a relay: an 8.6 MB page at 100 KB/s, 80 ms.
3808            let link = shaped_link(
3809                8_600_000,
3810                64 * 1024,
3811                Duration::from_millis(80),
3812                100_000,
3813                &[],
3814            );
3815            let finished = round_over(&link, ROUND_IDLE_TIMEOUT, None, None).unwrap();
3816            assert!(
3817                finished > ROUND_IDLE_TIMEOUT * 2,
3818                "the transfer outlasts the old whole-transfer bound ({finished:?})"
3819            );
3820        }
3821
3822        #[test]
3823        fn a_stall_shorter_than_the_idle_bound_is_survived_and_a_longer_one_is_not() {
3824            let link = |length| {
3825                shaped_link(
3826                    4_000_000,
3827                    64 * 1024,
3828                    Duration::from_millis(80),
3829                    100_000,
3830                    &[(Duration::from_secs(10), length)],
3831                )
3832            };
3833            round_over(
3834                &link(Duration::from_secs(29)),
3835                ROUND_IDLE_TIMEOUT,
3836                None,
3837                None,
3838            )
3839            .unwrap();
3840            let (expired, expiry) = round_over(
3841                &link(Duration::from_secs(31)),
3842                ROUND_IDLE_TIMEOUT,
3843                None,
3844                None,
3845            )
3846            .unwrap_err();
3847            assert_eq!(expiry, Expiry::Silence);
3848            assert!(
3849                expired >= Duration::from_secs(30) && expired < Duration::from_secs(41),
3850                "the bound counts from the last chunk before the stall ({expired:?})"
3851            );
3852        }
3853
3854        #[test]
3855        fn the_host_ceiling_still_bounds_a_link_that_keeps_delivering() {
3856            let link = shaped_link(
3857                8_600_000,
3858                64 * 1024,
3859                Duration::from_millis(80),
3860                100_000,
3861                &[],
3862            );
3863            // The drive bound restarts with every chunk; the host ceiling does not.
3864            let (expired, expiry) = round_over(
3865                &link,
3866                ROUND_IDLE_TIMEOUT,
3867                Some(Duration::from_secs(60)),
3868                Some(Duration::from_secs(60)),
3869            )
3870            .unwrap_err();
3871            assert_eq!(expiry, Expiry::Ceiling);
3872            assert_eq!(expired, Duration::from_secs(60));
3873        }
3874
3875        #[test]
3876        fn keepalives_carry_a_round_through_a_server_build_under_the_drive_bound() {
3877            // §1.6: the server writes its header frames, then builds for 90 s
3878            // with a KEEPALIVE every 10 s, then writes the rest.
3879            let drive = Some(Duration::from_millis(
3880                crate::SyncClient::SYNC_IDLE_TIMEOUT_MS,
3881            ));
3882            let build = |keepalives: bool| {
3883                let mut arrivals = vec![Duration::from_millis(80)];
3884                if keepalives {
3885                    arrivals.extend((1..=8).map(|n| Duration::from_secs(10 * n)));
3886                }
3887                arrivals.push(Duration::from_secs(90));
3888                arrivals
3889            };
3890            assert_eq!(
3891                round_over(&build(true), ROUND_IDLE_TIMEOUT, drive, None).unwrap(),
3892                Duration::from_secs(90)
3893            );
3894            // Without keepalives the fixed 30 s socket silence bound ends it.
3895            let (expired, expiry) =
3896                round_over(&build(false), ROUND_IDLE_TIMEOUT, drive, None).unwrap_err();
3897            assert_eq!(expiry, Expiry::Silence);
3898            assert_eq!(expired, Duration::from_millis(30_080));
3899            // A drive bound under the silence bound ends a silent round first.
3900            let (expired, expiry) = round_over(
3901                &build(false),
3902                ROUND_IDLE_TIMEOUT,
3903                Some(Duration::from_secs(20)),
3904                None,
3905            )
3906            .unwrap_err();
3907            assert_eq!(expiry, Expiry::Drive);
3908            assert_eq!(expired, Duration::from_millis(20_080));
3909            // The host's absolute deadline ends a progressing round.
3910            let (expired, expiry) = round_over(
3911                &build(true),
3912                ROUND_IDLE_TIMEOUT,
3913                drive,
3914                Some(Duration::from_secs(45)),
3915            )
3916            .unwrap_err();
3917            assert_eq!(expiry, Expiry::Ceiling);
3918            assert_eq!(expired, Duration::from_secs(45));
3919        }
3920
3921        #[test]
3922        fn a_keepalive_chunk_restarts_the_socket_silence_bound() {
3923            let header = ssp2::Message {
3924                wire_version: ssp2::decode::WIRE_VERSION,
3925                msg_kind: ssp2::MsgKind::Response,
3926                frames: vec![ssp2::Frame::RespHeader {
3927                    required_schema_version: None,
3928                    latest_schema_version: None,
3929                    log_epoch: "epoch-1".to_owned(),
3930                    reset_required: false,
3931                }],
3932            };
3933            let mut message = header.clone();
3934            message.frames.push(ssp2::Frame::Keepalive);
3935            let response = ssp2::encode_message(&message);
3936            let header_len = ssp2::encode_message(&header).len() - 5;
3937            let channel = RoundChannel::default();
3938            channel.begin(&[0x00]).unwrap();
3939            let tagged = |bytes: &[u8]| [&[crate::REALTIME_TAG_ROUND][..], bytes].concat();
3940            let silent_since = Instant::now() - ROUND_IDLE_TIMEOUT;
3941            for chunk in [
3942                &response[..header_len],
3943                &response[header_len..header_len + 5],
3944            ] {
3945                // The previous chunk is a whole silence bound old.
3946                channel.state.lock().unwrap().last_progress = Some(silent_since);
3947                assert!(channel.route_binary(&tagged(chunk)).is_none());
3948                let last_progress = channel.state.lock().unwrap().last_progress.unwrap();
3949                assert!(
3950                    round_expiry(last_progress, ROUND_IDLE_TIMEOUT, None, None).0 > Instant::now(),
3951                    "the chunk restarted the silence bound"
3952                );
3953            }
3954            assert!(channel
3955                .route_binary(&tagged(&response[header_len + 5..]))
3956                .is_none());
3957            assert_eq!(
3958                channel.wait(None, ROUND_IDLE_TIMEOUT, None).unwrap(),
3959                response,
3960                "the round completes with the KEEPALIVE in its bytes"
3961            );
3962        }
3963
3964        #[test]
3965        fn an_expired_round_deadline_bounds_the_socket_wait() {
3966            let channel = RoundChannel::default();
3967            let error = channel
3968                .wait(
3969                    Some(std::time::Instant::now() - Duration::from_secs(1)),
3970                    ROUND_IDLE_TIMEOUT,
3971                    None,
3972                )
3973                .unwrap_err();
3974            assert_eq!(error.code, "transport.timeout");
3975            assert_eq!(
3976                error.details,
3977                Some(serde_json::json!({ "causeKind": "round_deadline" }))
3978            );
3979        }
3980    }
3981}
3982
3983#[cfg(all(test, feature = "native-transport"))]
3984mod tests {
3985    use super::*;
3986    use std::io::{BufRead, BufReader, Write};
3987
3988    #[test]
3989    fn an_undrained_inbound_buffer_past_its_limit_ends_the_connection() {
3990        const DELTA_BYTES: usize = 1024 * 1024;
3991        let deltas = INBOUND_BUFFER_LIMIT_BYTES / DELTA_BYTES + 1;
3992        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
3993        let base = format!("http://{}", listener.local_addr().unwrap());
3994        let server = std::thread::spawn(move || {
3995            let (socket, _) = listener.accept().unwrap();
3996            let mut socket = tungstenite::accept(socket).unwrap();
3997            for _ in 0..deltas {
3998                let mut frame = vec![crate::REALTIME_TAG_DELTA];
3999                frame.resize(DELTA_BYTES + 1, 7);
4000                socket
4001                    .send(tungstenite::Message::Binary(frame.into()))
4002                    .unwrap();
4003            }
4004            while !matches!(socket.read(), Ok(tungstenite::Message::Close(_)) | Err(_)) {}
4005        });
4006        let (woke, wakes) = mpsc::channel::<()>();
4007        let mut transport = HostTransport::from_config_with_notify(
4008            &serde_json::json!({"baseUrl": base}),
4009            Some(Arc::new(move || {
4010                let _ = woke.send(());
4011            })),
4012        )
4013        .unwrap();
4014        transport.realtime_connect("c1").unwrap();
4015        // One wake per buffered frame: every delta, then the loss.
4016        for _ in 0..=deltas {
4017            wakes.recv().unwrap();
4018        }
4019        let inbound = transport.take_inbound();
4020        assert_eq!(inbound.len(), deltas + 1);
4021        assert!(inbound[..deltas]
4022            .iter()
4023            .all(|frame| matches!(frame, Inbound::Binary(bytes) if bytes.len() == DELTA_BYTES)));
4024        assert!(matches!(
4025            &inbound[deltas],
4026            Inbound::Disconnected(error) if error.code == "transport.failed"
4027                && error.details.as_ref().and_then(|d| d.get("causeKind"))
4028                    == Some(&serde_json::json!("inbound_overflow"))
4029        ));
4030        transport.shutdown();
4031        server.join().unwrap();
4032    }
4033
4034    #[test]
4035    fn the_first_heartbeat_arms_silence_detection() {
4036        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4037        let base = format!("http://{}", listener.local_addr().unwrap());
4038        let (beat, heartbeat) = mpsc::channel::<()>();
4039        let server = std::thread::spawn(move || {
4040            let (socket, _) = listener.accept().unwrap();
4041            let mut socket = tungstenite::accept(socket).unwrap();
4042            socket
4043                .send(tungstenite::Message::Text("{\"event\":\"hello\"}".into()))
4044                .unwrap();
4045            heartbeat.recv().unwrap();
4046            socket
4047                .send(tungstenite::Message::Text(
4048                    "{\"event\":\"heartbeat\",\"data\":{\"timestamp\":1}}".into(),
4049                ))
4050                .unwrap();
4051            // Then silence until the client gives up on the socket.
4052            while socket.read().is_ok() {}
4053        });
4054        let (woke, wakes) = mpsc::channel::<()>();
4055        let mut transport = HostTransport::from_config_with_notify(
4056            &serde_json::json!({"baseUrl": base, "realtimeHeartbeatMs": 50}),
4057            Some(Arc::new(move || {
4058                let _ = woke.send(());
4059            })),
4060        )
4061        .unwrap();
4062        transport.realtime_connect("c1").unwrap();
4063        wakes.recv_timeout(Duration::from_secs(10)).unwrap();
4064        // §8.5: before the first heartbeat no silence bound applies, so five
4065        // intervals of silence keep the socket.
4066        assert!(wakes.recv_timeout(Duration::from_millis(250)).is_err());
4067        beat.send(()).unwrap();
4068        for _ in 0..2 {
4069            wakes.recv_timeout(Duration::from_secs(10)).unwrap();
4070        }
4071        let inbound = transport.take_inbound();
4072        assert_eq!(inbound.len(), 3);
4073        assert!(matches!(&inbound[0], Inbound::Text(_)));
4074        assert!(matches!(&inbound[1], Inbound::Text(text) if text.contains("heartbeat")));
4075        assert!(matches!(
4076            &inbound[2],
4077            Inbound::Disconnected(error) if error.code == "transport.timeout"
4078                && error.details == Some(serde_json::json!({ "causeKind": "heartbeat" }))
4079        ));
4080        transport.shutdown();
4081        server.join().unwrap();
4082    }
4083
4084    #[test]
4085    fn segment_and_blob_reads_stop_past_the_declared_byte_length() {
4086        for case in ["segment", "signed_segment", "blob", "signed_blob"] {
4087            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4088            let base = format!("http://{}", listener.local_addr().unwrap());
4089            let server = std::thread::spawn(move || {
4090                let (mut socket, _) = listener.accept().unwrap();
4091                let mut reader = BufReader::new(socket.try_clone().unwrap());
4092                loop {
4093                    let mut line = String::new();
4094                    reader.read_line(&mut line).unwrap();
4095                    if line == "\r\n" {
4096                        break;
4097                    }
4098                }
4099                let body = vec![7u8; 4 << 20];
4100                // The client stops reading, so the rest of the write may fail.
4101                let _ = write!(
4102                    socket,
4103                    "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
4104                    body.len()
4105                );
4106                let _ = socket.write_all(&body);
4107            });
4108            let mut transport =
4109                HostTransport::from_config(&serde_json::json!({ "baseUrl": base })).unwrap();
4110            let mut progress = |_| {};
4111            let bytes = match case {
4112                "segment" => transport.download_segment(
4113                    &SegmentRequest {
4114                        segment_id: "sha256:test".into(),
4115                        table: "tasks".into(),
4116                        requested_scopes_json: "{}".into(),
4117                        byte_length: 16,
4118                    },
4119                    &mut progress,
4120                ),
4121                "signed_segment" => {
4122                    transport.fetch_url(&format!("{base}/signed"), 16, &mut progress)
4123                }
4124                "blob" => transport
4125                    .blob_download("sha256:test", Some(16))
4126                    .map(|download| match download {
4127                        BlobDownload::Bytes(bytes) => bytes,
4128                        BlobDownload::Url { .. } => panic!("expected inline bytes"),
4129                    }),
4130                _ => transport.fetch_blob_url(&format!("{base}/signed"), Some(16)),
4131            }
4132            .unwrap();
4133            // §5.4: reading ends with the chunk that passes the cap; the
4134            // client rejects the longer body.
4135            assert!(
4136                bytes.len() > 16 && bytes.len() <= 16 + 64 * 1024,
4137                "{case} read {} bytes",
4138                bytes.len()
4139            );
4140            server.join().unwrap();
4141        }
4142    }
4143
4144    #[test]
4145    fn a_round_deadline_expiring_during_a_socket_send_is_the_typed_timeout() {
4146        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4147        let base = format!("http://{}", listener.local_addr().unwrap());
4148        let (release, released) = mpsc::channel::<()>();
4149        // The peer completes the upgrade and never reads, so the request's
4150        // send can only end at the round deadline.
4151        let server = std::thread::spawn(move || {
4152            let (socket, _) = listener.accept().unwrap();
4153            let _socket = tungstenite::accept(socket).unwrap();
4154            let _ = released.recv();
4155        });
4156        let mut transport =
4157            HostTransport::from_config(&serde_json::json!({"baseUrl": base})).unwrap();
4158        transport.realtime_connect("c1").unwrap();
4159        transport.set_round_deadline(Some(std::time::Instant::now() + Duration::from_millis(200)));
4160        let error = transport
4161            .realtime_sync(&vec![0u8; 32 * 1024 * 1024])
4162            .unwrap_err();
4163        assert_eq!(error.code, "transport.timeout");
4164        assert_eq!(
4165            error.details,
4166            Some(serde_json::json!({ "causeKind": "round_deadline" }))
4167        );
4168        assert!(matches!(
4169            &transport.take_inbound()[..],
4170            [Inbound::Disconnected(lost)] if lost.code == "transport.timeout"
4171        ));
4172        transport.shutdown();
4173        release.send(()).unwrap();
4174        server.join().unwrap();
4175    }
4176
4177    #[test]
4178    fn receipt_observer_covers_round_chunks_wakes_reconnect_and_overflow() {
4179        use ssp2::model::{Frame, Message, MsgKind};
4180        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4181        let base = format!("http://{}", listener.local_addr().unwrap());
4182        let response = ssp2::encode_message(&Message {
4183            wire_version: ssp2::decode::WIRE_VERSION,
4184            msg_kind: MsgKind::Response,
4185            frames: vec![Frame::RespHeader {
4186                required_schema_version: None,
4187                latest_schema_version: None,
4188                log_epoch: "epoch".into(),
4189                reset_required: false,
4190            }],
4191        });
4192        let server_response = response.clone();
4193        let server = std::thread::spawn(move || {
4194            for _ in 0..2 {
4195                let (socket, _) = listener.accept().unwrap();
4196                let mut socket = tungstenite::accept(socket).unwrap();
4197                assert!(matches!(
4198                    socket.read().unwrap(),
4199                    tungstenite::Message::Binary(_)
4200                ));
4201                socket
4202                    .send(tungstenite::Message::Binary(
4203                        vec![crate::REALTIME_TAG_DELTA, 7].into(),
4204                    ))
4205                    .unwrap();
4206                socket
4207                    .send(tungstenite::Message::Text("wake".into()))
4208                    .unwrap();
4209                let split = server_response.len() / 2;
4210                for part in [&server_response[..split], &server_response[split..]] {
4211                    let mut chunk = vec![crate::REALTIME_TAG_ROUND];
4212                    chunk.extend_from_slice(part);
4213                    socket
4214                        .send(tungstenite::Message::Binary(chunk.into()))
4215                        .unwrap();
4216                }
4217                assert!(matches!(
4218                    socket.read().unwrap(),
4219                    tungstenite::Message::Close(_)
4220                ));
4221            }
4222        });
4223        let mut transport =
4224            HostTransport::from_config(&serde_json::json!({"baseUrl": base})).unwrap();
4225        let (sender, receiver) = mpsc::sync_channel(4);
4226        let (small_sender, small_receiver) = mpsc::sync_channel(1);
4227        transport.set_realtime_receipt_observer(Some(sender));
4228        for round in 0..2 {
4229            transport.realtime_connect("c1").unwrap();
4230            let before = SystemTime::now();
4231            assert_eq!(transport.realtime_sync(b"request").unwrap(), response);
4232            let after = SystemTime::now();
4233            if round == 0 {
4234                let receipts = [
4235                    receiver.recv().unwrap(),
4236                    receiver.recv().unwrap(),
4237                    receiver.recv().unwrap(),
4238                    receiver.recv().unwrap(),
4239                ];
4240                assert_eq!(
4241                    receipts.map(|r| r.kind),
4242                    [
4243                        RealtimeReceiptKind::Delta,
4244                        RealtimeReceiptKind::Text,
4245                        RealtimeReceiptKind::Round,
4246                        RealtimeReceiptKind::Round
4247                    ]
4248                );
4249                assert_eq!(
4250                    receipts.map(|r| r.bytes),
4251                    [
4252                        2,
4253                        4,
4254                        1 + response.len() / 2,
4255                        1 + response.len() - response.len() / 2
4256                    ]
4257                );
4258                assert!(receipts
4259                    .iter()
4260                    .all(|r| r.received_at >= before && r.received_at <= after));
4261                assert!(
4262                    matches!(&transport.take_inbound()[..], [Inbound::Binary(bytes), Inbound::Text(text)] if bytes == &[7] && text == "wake")
4263                );
4264                assert_eq!(transport.take_dropped_realtime_receipts(), 0);
4265                // A capacity-one channel proves loss is visible without blocking
4266                // the reader or its round waiter.
4267                transport.set_realtime_receipt_observer(Some(small_sender.clone()));
4268            } else {
4269                assert_eq!(
4270                    small_receiver.recv().unwrap().kind,
4271                    RealtimeReceiptKind::Delta
4272                );
4273                assert_eq!(transport.take_dropped_realtime_receipts(), 3);
4274                assert_eq!(transport.take_dropped_realtime_receipts(), 0);
4275            }
4276            transport.shutdown();
4277        }
4278        server.join().unwrap();
4279    }
4280
4281    #[test]
4282    fn receipt_observer_reports_chunks_of_a_failed_round() {
4283        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4284        let base = format!("http://{}", listener.local_addr().unwrap());
4285        let server = std::thread::spawn(move || {
4286            let (socket, _) = listener.accept().unwrap();
4287            let mut socket = tungstenite::accept(socket).unwrap();
4288            assert!(matches!(
4289                socket.read().unwrap(),
4290                tungstenite::Message::Binary(_)
4291            ));
4292            socket
4293                .send(tungstenite::Message::Binary(
4294                    vec![crate::REALTIME_TAG_ROUND, b'S'].into(),
4295                ))
4296                .unwrap();
4297            socket
4298                .close(Some(tungstenite::protocol::CloseFrame {
4299                    code: tungstenite::protocol::frame::coding::CloseCode::Normal,
4300                    reason: "bye".into(),
4301                }))
4302                .unwrap();
4303        });
4304        let mut transport =
4305            HostTransport::from_config(&serde_json::json!({"baseUrl": base})).unwrap();
4306        let (sender, receiver) = mpsc::sync_channel(2);
4307        transport.set_realtime_receipt_observer(Some(sender));
4308        transport.realtime_connect("c1").unwrap();
4309        assert!(transport.realtime_sync(b"request").is_err());
4310        assert_eq!(receiver.recv().unwrap().kind, RealtimeReceiptKind::Round);
4311        let close = receiver.recv().unwrap();
4312        assert_eq!(close.kind, RealtimeReceiptKind::Close);
4313        assert_eq!(close.bytes, 5);
4314        assert_eq!(transport.take_dropped_realtime_receipts(), 0);
4315        transport.shutdown();
4316        server.join().unwrap();
4317    }
4318
4319    #[test]
4320    fn detached_round_uses_the_owned_socket_and_shutdown_releases_it() {
4321        use ssp2::model::{Frame, Message, MsgKind};
4322        use std::sync::mpsc::channel;
4323        for cancelled in [false, true] {
4324            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4325            let base = format!("http://{}", listener.local_addr().unwrap());
4326            let (entered_tx, entered_rx) = channel();
4327            let (release_tx, release_rx) = channel();
4328            let server = std::thread::spawn(move || {
4329                let (socket, _) = listener.accept().unwrap();
4330                let mut socket = tungstenite::accept(socket).unwrap();
4331                let request = socket.read().unwrap().into_data();
4332                assert_eq!(request[0], crate::REALTIME_TAG_ROUND);
4333                assert_eq!(
4334                    ssp2::decode_message(&request[1..]).unwrap().msg_kind,
4335                    MsgKind::Request
4336                );
4337                entered_tx.send(()).unwrap();
4338                release_rx.recv().unwrap();
4339                if !cancelled {
4340                    let response = ssp2::encode_message(&Message {
4341                        wire_version: ssp2::decode::WIRE_VERSION,
4342                        msg_kind: MsgKind::Response,
4343                        frames: vec![Frame::RespHeader {
4344                            required_schema_version: None,
4345                            latest_schema_version: None,
4346                            log_epoch: "epoch".into(),
4347                            reset_required: true,
4348                        }],
4349                    });
4350                    let mut chunk = vec![crate::REALTIME_TAG_ROUND];
4351                    chunk.extend(response);
4352                    socket
4353                        .send(tungstenite::Message::Binary(chunk.into()))
4354                        .unwrap();
4355                }
4356            });
4357            let mut owner =
4358                HostTransport::from_config(&serde_json::json!({"baseUrl":base})).unwrap();
4359            owner.realtime_connect("detached-round").unwrap();
4360            let mut detached = owner.fork_round();
4361            let network = std::thread::spawn(move || {
4362                let request = ssp2::encode_message(&Message {
4363                    wire_version: ssp2::decode::WIRE_VERSION,
4364                    msg_kind: MsgKind::Request,
4365                    frames: vec![
4366                        Frame::ReqHeader {
4367                            client_id: "detached-round".into(),
4368                            schema_version: 1,
4369                            log_epoch: None,
4370                            outbox_id: None,
4371                        },
4372                        Frame::PullHeader {
4373                            limit_commits: 0,
4374                            limit_snapshot_rows: 0,
4375                            max_snapshot_pages: 0,
4376                            accept: 3,
4377                            cursor: -1,
4378                            registration_digest: ssp2::registration::registration_digest([]),
4379                            echo_digest: None,
4380                        },
4381                    ],
4382                });
4383                detached.realtime_sync(&request)
4384            });
4385            entered_rx.recv().unwrap();
4386            owner.set_header_source(HeaderSource::new(|_, _| {
4387                Some(vec![("authorization".into(), "Bearer rotated".into())])
4388            }));
4389            assert!(owner.take_inbound().is_empty());
4390            if cancelled {
4391                owner.shutdown();
4392            }
4393            release_tx.send(()).unwrap();
4394            let response = network.join().unwrap();
4395            if cancelled {
4396                assert!(response.is_err());
4397            } else {
4398                assert_eq!(
4399                    ssp2::decode_message(&response.unwrap()).unwrap().msg_kind,
4400                    MsgKind::Response
4401                );
4402                owner.shutdown();
4403            }
4404            server.join().unwrap();
4405        }
4406    }
4407
4408    fn minimal_response() -> Vec<u8> {
4409        use ssp2::model::{Frame, Message, MsgKind};
4410        ssp2::encode_message(&Message {
4411            wire_version: ssp2::decode::WIRE_VERSION,
4412            msg_kind: MsgKind::Response,
4413            frames: vec![Frame::RespHeader {
4414                required_schema_version: None,
4415                latest_schema_version: None,
4416                log_epoch: "epoch".into(),
4417                reset_required: true,
4418            }],
4419        })
4420    }
4421
4422    #[test]
4423    fn a_presigned_blob_put_sends_the_blob_id_digest_without_hashing_the_body() {
4424        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4425        let base = format!("http://{}", listener.local_addr().unwrap());
4426        let server = std::thread::spawn(move || {
4427            let (mut socket, _) = listener.accept().unwrap();
4428            let mut reader = BufReader::new(socket.try_clone().unwrap());
4429            let mut head = Vec::new();
4430            loop {
4431                let mut line = String::new();
4432                reader.read_line(&mut line).unwrap();
4433                if line == "\r\n" {
4434                    break;
4435                }
4436                let (name, value) = line.trim_end().split_once(": ").unwrap_or((&line, ""));
4437                head.push(format!("{}: {value}", name.to_ascii_lowercase()));
4438            }
4439            socket
4440                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
4441                .unwrap();
4442            head
4443        });
4444        let mut transport =
4445            HostTransport::from_config(&serde_json::json!({"baseUrl": base})).unwrap();
4446        let url = format!("{base}/bucket/key?X-Amz-Signature=x");
4447        // A blob id that is not a sha256 id is refused before any request.
4448        let error = transport
4449            .blob_put_url("sha256:AB", &url, b"body", None)
4450            .unwrap_err();
4451        assert_eq!(error.code, "sync.invalid_request");
4452        // The digest of the blob id differs from SHA-256("body"): the header
4453        // carries the given digest, so no body hash ran.
4454        transport
4455            .blob_put_url(&format!("sha256:{}", "ab".repeat(32)), &url, b"body", None)
4456            .unwrap();
4457        let head = server.join().unwrap();
4458        assert!(head.contains(
4459            &"x-amz-checksum-sha256: q6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6s=".to_owned()
4460        ));
4461        assert!(head.contains(&"content-length: 4".to_owned()));
4462    }
4463
4464    #[test]
4465    fn a_stalled_response_body_times_out_on_silence() {
4466        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4467        let base = format!("http://{}", listener.local_addr().unwrap());
4468        let server = std::thread::spawn(move || {
4469            let (mut socket, _) = listener.accept().unwrap();
4470            let mut reader = BufReader::new(socket.try_clone().unwrap());
4471            loop {
4472                let mut line = String::new();
4473                reader.read_line(&mut line).unwrap();
4474                if line == "\r\n" {
4475                    break;
4476                }
4477            }
4478            socket
4479                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 1000\r\n\r\n0123456789")
4480                .unwrap();
4481            // Withhold the rest until the client gives up and closes.
4482            let mut rest = Vec::new();
4483            let _ = std::io::Read::read_to_end(&mut reader, &mut rest);
4484        });
4485        let mut transport = HostTransport::from_config(
4486            &serde_json::json!({"baseUrl": base, "requestTimeoutMs": 200}),
4487        )
4488        .unwrap();
4489        let mut received = 0;
4490        let error = transport
4491            .download_segment(
4492                &SegmentRequest {
4493                    segment_id: "sha256:test".into(),
4494                    table: "tasks".into(),
4495                    requested_scopes_json: "{}".into(),
4496                    byte_length: 1 << 20,
4497                },
4498                &mut |bytes| received = bytes,
4499            )
4500            .unwrap_err();
4501        assert_eq!(error.code, "transport.timeout");
4502        assert_eq!(
4503            error.details,
4504            Some(serde_json::json!({ "causeKind": "timeout" }))
4505        );
4506        server.join().unwrap();
4507    }
4508
4509    #[test]
4510    fn a_timed_out_socket_round_closes_the_socket_and_reports_the_loss() {
4511        use std::sync::mpsc::channel;
4512        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4513        let base = format!("http://{}", listener.local_addr().unwrap());
4514        let (closed_tx, closed_rx) = channel();
4515        let server = std::thread::spawn(move || {
4516            let (socket, _) = listener.accept().unwrap();
4517            let mut socket = tungstenite::accept(socket).unwrap();
4518            socket.read().unwrap();
4519            // The head of a response that never finishes.
4520            let response = minimal_response();
4521            let mut chunk = vec![crate::REALTIME_TAG_ROUND];
4522            chunk.extend_from_slice(&response[..response.len() / 2]);
4523            socket
4524                .send(tungstenite::Message::Binary(chunk.into()))
4525                .unwrap();
4526            // The client must close; the tail is never delivered to a round.
4527            while let Ok(message) = socket.read() {
4528                if matches!(message, tungstenite::Message::Close(_)) {
4529                    break;
4530                }
4531            }
4532            closed_tx.send(()).unwrap();
4533        });
4534        let mut transport =
4535            HostTransport::from_config(&serde_json::json!({"baseUrl": base})).unwrap();
4536        transport.realtime_connect("slow").unwrap();
4537        transport.set_round_deadline(Some(
4538            std::time::Instant::now() + std::time::Duration::from_millis(300),
4539        ));
4540        let error = transport.realtime_sync(b"request").unwrap_err();
4541        assert_eq!(error.code, "transport.timeout");
4542        closed_rx.recv().unwrap();
4543        let lost = transport
4544            .take_inbound()
4545            .into_iter()
4546            .filter(|inbound| matches!(inbound, Inbound::Disconnected(e) if e.code == "transport.timeout"))
4547            .count();
4548        assert_eq!(lost, 1, "the loss is reported once");
4549        server.join().unwrap();
4550    }
4551
4552    #[test]
4553    fn a_request_larger_than_a_chunk_rides_as_several_round_chunks() {
4554        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4555        let base = format!("http://{}", listener.local_addr().unwrap());
4556        let request: Vec<u8> = (0..3 * 64 * 1024 + 5).map(|i| (i % 251) as u8).collect();
4557        let expected = request.clone();
4558        let server = std::thread::spawn(move || {
4559            let (socket, _) = listener.accept().unwrap();
4560            let mut socket = tungstenite::accept(socket).unwrap();
4561            let mut body = Vec::new();
4562            let mut messages = 0;
4563            while body.len() < expected.len() {
4564                let message = socket.read().unwrap().into_data();
4565                assert_eq!(message[0], crate::REALTIME_TAG_ROUND);
4566                body.extend_from_slice(&message[1..]);
4567                messages += 1;
4568            }
4569            assert_eq!(body, expected);
4570            assert_eq!(messages, 4);
4571            let mut chunk = vec![crate::REALTIME_TAG_ROUND];
4572            chunk.extend(minimal_response());
4573            socket
4574                .send(tungstenite::Message::Binary(chunk.into()))
4575                .unwrap();
4576        });
4577        let mut transport =
4578            HostTransport::from_config(&serde_json::json!({"baseUrl": base})).unwrap();
4579        transport.realtime_connect("chunked").unwrap();
4580        let response = transport.realtime_sync(&request).unwrap();
4581        assert_eq!(response, minimal_response());
4582        transport.shutdown();
4583        server.join().unwrap();
4584    }
4585
4586    #[test]
4587    fn segment_http_failures_have_named_codes_and_safe_cause_details() {
4588        for signed in [false, true] {
4589            for body_failure in [false, true] {
4590                let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4591                let base = format!("http://{}", listener.local_addr().unwrap());
4592                let server = std::thread::spawn(move || {
4593                    let (mut socket, _) = listener.accept().unwrap();
4594                    let mut reader = BufReader::new(socket.try_clone().unwrap());
4595                    loop {
4596                        let mut line = String::new();
4597                        reader.read_line(&mut line).unwrap();
4598                        if line == "\r\n" {
4599                            break;
4600                        }
4601                        assert!(!line.is_empty());
4602                    }
4603                    socket.write_all(if body_failure {
4604                        b"HTTP/1.1 200 OK\r\nContent-Length: 999\r\nConnection: close\r\n\r\nshort"
4605                    } else {
4606                        b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
4607                    }).unwrap();
4608                });
4609                let mut transport =
4610                    HostTransport::from_config(&serde_json::json!({"baseUrl": base})).unwrap();
4611                let mut progress = |_| {};
4612                let error = if signed {
4613                    transport.fetch_url(
4614                        &format!("{base}/signed?signature=secret"),
4615                        1 << 20,
4616                        &mut progress,
4617                    )
4618                } else {
4619                    transport.download_segment(
4620                        &SegmentRequest {
4621                            segment_id: "sha256:test".into(),
4622                            table: "tasks".into(),
4623                            requested_scopes_json: "{}".into(),
4624                            byte_length: 1 << 20,
4625                        },
4626                        &mut progress,
4627                    )
4628                }
4629                .unwrap_err();
4630                assert_eq!(error.code, "sync.transport_failed");
4631                assert_eq!(error.message, "segment transfer failed");
4632                let details = error.details.unwrap();
4633                assert!(details.get("path").is_none());
4634                assert!(details.get("causeMessage").is_none());
4635                assert_eq!(
4636                    details["causeKind"],
4637                    if body_failure { "body" } else { "status" }
4638                );
4639                assert_eq!(details["httpStatus"], if body_failure { 200 } else { 403 });
4640                server.join().unwrap();
4641            }
4642        }
4643    }
4644
4645    #[test]
4646    fn blob_status_classification_uses_the_actual_http_response() {
4647        for (status, expected) in [
4648            (404, "blob.not_found"),
4649            (401, "sync.auth_required"),
4650            (403, "blob.forbidden"),
4651            (500, "transport.failed"),
4652        ] {
4653            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4654            let base = format!("http://{}", listener.local_addr().unwrap());
4655            let server = std::thread::spawn(move || {
4656                let (mut socket, _) = listener.accept().unwrap();
4657                let mut reader = BufReader::new(socket.try_clone().unwrap());
4658                loop {
4659                    let mut line = String::new();
4660                    reader.read_line(&mut line).unwrap();
4661                    if line == "\r\n" {
4662                        break;
4663                    }
4664                    assert!(!line.is_empty());
4665                }
4666                let body = r#"{"code":"blob.not_found","message":"https://host/secret-path?secret-query#secret-fragment","retryable":false}"#;
4667                write!(socket, "HTTP/1.1 {status} Error\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();
4668            });
4669            let mut transport =
4670                HostTransport::from_config(&serde_json::json!({"baseUrl":base})).unwrap();
4671            let error = transport.blob_download("sha256:test", None).unwrap_err();
4672            assert_eq!(error.code, expected);
4673            assert_eq!(
4674                error.details,
4675                Some(serde_json::json!({
4676                    "causeKind": "status",
4677                    "httpStatus": status,
4678                    "retryable": false
4679                }))
4680            );
4681            assert!(!error.message.contains("secret"));
4682            assert!(!error.message.contains("http"));
4683            server.join().unwrap();
4684        }
4685    }
4686
4687    #[test]
4688    fn refused_segment_connection_has_a_named_code_without_an_invented_status() {
4689        for signed in [false, true] {
4690            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4691            let base = format!("http://{}", listener.local_addr().unwrap());
4692            drop(listener);
4693            let mut transport =
4694                HostTransport::from_config(&serde_json::json!({"baseUrl": base})).unwrap();
4695            let mut progress = |_| {};
4696            let error = if signed {
4697                transport.fetch_url(
4698                    &format!("{base}/signed?signature=secret"),
4699                    1 << 20,
4700                    &mut progress,
4701                )
4702            } else {
4703                transport.download_segment(
4704                    &SegmentRequest {
4705                        segment_id: "sha256:test".into(),
4706                        table: "tasks".into(),
4707                        requested_scopes_json: "{}".into(),
4708                        byte_length: 1 << 20,
4709                    },
4710                    &mut progress,
4711                )
4712            }
4713            .unwrap_err();
4714            assert_eq!(error.code, "sync.transport_failed");
4715            assert!(error.details.as_ref().unwrap().get("httpStatus").is_none());
4716        }
4717    }
4718
4719    #[test]
4720    fn segment_http_reports_intermediate_bytes_for_direct_and_signed_urls() {
4721        for signed in [false, true] {
4722            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4723            let base = format!("http://{}", listener.local_addr().unwrap());
4724            let server = std::thread::spawn(move || {
4725                let (mut socket, _) = listener.accept().unwrap();
4726                let mut reader = BufReader::new(socket.try_clone().unwrap());
4727                let mut headers = String::new();
4728                loop {
4729                    let mut line = String::new();
4730                    reader.read_line(&mut line).unwrap();
4731                    if line == "\r\n" {
4732                        break;
4733                    }
4734                    assert!(!line.is_empty());
4735                    headers.push_str(&line.to_ascii_lowercase());
4736                }
4737                assert_eq!(headers.contains("authorization: bearer test"), !signed);
4738                assert_eq!(headers.contains("x-syncular-scopes:"), !signed);
4739                let bytes = vec![7; 128 * 1024 + 17];
4740                write!(
4741                    socket,
4742                    "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
4743                    bytes.len()
4744                )
4745                .unwrap();
4746                socket.write_all(&bytes).unwrap();
4747            });
4748            let mut transport =
4749                HostTransport::from_config(&serde_json::json!({ "baseUrl": base })).unwrap();
4750            transport.set_header_source(HeaderSource::new(|_, _| {
4751                Some(vec![("authorization".into(), "Bearer test".into())])
4752            }));
4753            let mut updates = Vec::new();
4754            let mut progress = |bytes| updates.push(bytes);
4755            let bytes = if signed {
4756                transport
4757                    .fetch_url(&format!("{base}/signed"), 1 << 20, &mut progress)
4758                    .unwrap()
4759            } else {
4760                transport
4761                    .download_segment(
4762                        &SegmentRequest {
4763                            segment_id: "sha256:test".into(),
4764                            table: "tasks".into(),
4765                            requested_scopes_json: "{}".into(),
4766                            byte_length: 1 << 20,
4767                        },
4768                        &mut progress,
4769                    )
4770                    .unwrap()
4771            };
4772            assert_eq!(bytes.len(), 128 * 1024 + 17);
4773            assert!(updates.iter().any(|n| *n > 0 && *n < bytes.len() as u64));
4774            assert_eq!(updates.last(), Some(&(bytes.len() as u64)));
4775            assert!(updates.windows(2).all(|pair| pair[0] < pair[1]));
4776            server.join().unwrap();
4777        }
4778    }
4779
4780    #[test]
4781    fn request_over_cap_is_refused_before_network() {
4782        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4783        listener.set_nonblocking(true).unwrap();
4784        let base = format!("http://{}", listener.local_addr().unwrap());
4785        let mut transport =
4786            HostTransport::from_config(&serde_json::json!({"baseUrl": base, "maxRequestBytes": 4}))
4787                .unwrap();
4788        let error = transport
4789            .blob_upload("sha256:test", &[0u8; 8], None)
4790            .unwrap_err();
4791        assert_eq!(error.code, "transport.request_too_large");
4792        assert_eq!(
4793            error.details,
4794            Some(serde_json::json!({ "limit": 4, "size": 8 }))
4795        );
4796        assert!(
4797            matches!(listener.accept(), Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock),
4798            "the request cap is checked before any connection"
4799        );
4800    }
4801
4802    #[test]
4803    fn credential_bearing_redirects_are_refused_without_contacting_the_destination() {
4804        for credentials in ["headers", "userinfo", "password"] {
4805            for redirects in ["deny", "follow"] {
4806                let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4807                destination.set_nonblocking(true).unwrap();
4808                let location = format!("http://{}/landed", destination.local_addr().unwrap());
4809                let origin = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4810                let host = origin.local_addr().unwrap();
4811                let base = match credentials {
4812                    "headers" => format!("http://{host}"),
4813                    "userinfo" => format!("http://user:secret@{host}"),
4814                    _ => format!("http://:secret@{host}"),
4815                };
4816                let server = std::thread::spawn(move || {
4817                    let (mut socket, _) = origin.accept().unwrap();
4818                    let mut reader = BufReader::new(socket.try_clone().unwrap());
4819                    loop {
4820                        let mut line = String::new();
4821                        reader.read_line(&mut line).unwrap();
4822                        if line == "\r\n" {
4823                            break;
4824                        }
4825                    }
4826                    let _ = write!(
4827                        socket,
4828                        "HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
4829                    );
4830                });
4831                let mut transport = HostTransport::from_config(&serde_json::json!({
4832                    "baseUrl": base,
4833                    "redirects": redirects,
4834                }))
4835                .unwrap();
4836                if credentials == "headers" {
4837                    transport.set_header_source(HeaderSource::new(|_, _| {
4838                        Some(vec![("authorization".into(), "Bearer secret".into())])
4839                    }));
4840                }
4841                let error = transport.blob_download("sha256:test", None).unwrap_err();
4842                assert_eq!(
4843                    error.code, "transport.redirect",
4844                    "{credentials} {redirects}"
4845                );
4846                let details = error.details.unwrap();
4847                assert_eq!(details["causeKind"], "redirect");
4848                assert_eq!(details["httpStatus"], 302);
4849                assert!(
4850                    matches!(destination.accept(), Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock),
4851                    "{credentials} {redirects}: the destination is never contacted"
4852                );
4853                server.join().unwrap();
4854            }
4855        }
4856    }
4857
4858    #[test]
4859    fn websocket_handshake_redirects_obey_the_redirect_policy() {
4860        // The handshake request carries the header source's headers and the realtime
4861        // URL's query, so a redirect response is an error and never replays
4862        // them to the Location. The Location points at a second listener so
4863        // the test can prove it was never contacted. A `follow` policy cannot
4864        // establish at all and fails before any connection (see
4865        // `tests/realtime_disconnect.rs`).
4866        for credential in ["headers", "userinfo", "query", "none"] {
4867            let redirects = "deny";
4868            let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4869            let destination_addr = destination.local_addr().unwrap();
4870            let location = format!("ws://{destination_addr}/realtime");
4871            // The redirect target answers every handshake with 400 and stops
4872            // on an explicit sentinel connection, so a leaked redirect fails
4873            // the assertions below instead of hanging the test.
4874            let landed = Arc::new(Mutex::new(Vec::new()));
4875            let landed_writer = Arc::clone(&landed);
4876            let destination_thread = std::thread::spawn(move || loop {
4877                let (mut socket, _) = destination.accept().unwrap();
4878                let mut reader = BufReader::new(socket.try_clone().unwrap());
4879                let mut head = String::new();
4880                loop {
4881                    let mut line = String::new();
4882                    reader.read_line(&mut line).unwrap();
4883                    if line == "\r\n" {
4884                        break;
4885                    }
4886                    head.push_str(&line);
4887                }
4888                let sentinel = head.starts_with("GET /sentinel");
4889                landed_writer.lock().unwrap().push(head);
4890                let _ = write!(
4891                    socket,
4892                    "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
4893                );
4894                if sentinel {
4895                    break;
4896                }
4897            });
4898            let origin = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4899            let origin_addr = origin.local_addr().unwrap();
4900            let ws_url = match credential {
4901                "userinfo" => Some(format!("ws://user:secret@{origin_addr}/realtime")),
4902                "query" => Some(format!("ws://{origin_addr}/realtime?token=secret")),
4903                _ => None,
4904            };
4905            let (head_tx, head_rx) = std::sync::mpsc::channel();
4906            let origin_thread = std::thread::spawn(move || {
4907                let (mut socket, _) = origin.accept().unwrap();
4908                let mut reader = BufReader::new(socket.try_clone().unwrap());
4909                let mut head = String::new();
4910                loop {
4911                    let mut line = String::new();
4912                    reader.read_line(&mut line).unwrap();
4913                    if line == "\r\n" {
4914                        break;
4915                    }
4916                    head.push_str(&line);
4917                }
4918                let _ = head_tx.send(head);
4919                let _ = write!(
4920                    socket,
4921                    "HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
4922                );
4923            });
4924            let mut config = serde_json::json!({
4925                "baseUrl": format!("http://{origin_addr}"),
4926                "redirects": redirects,
4927            });
4928            if let Some(ws_url) = &ws_url {
4929                config["wsUrl"] = serde_json::json!(ws_url);
4930            }
4931            let mut transport = HostTransport::from_config(&config).unwrap();
4932            if credential == "headers" {
4933                transport.set_header_source(HeaderSource::new(|_, _| {
4934                    Some(vec![("authorization".into(), "Bearer secret".into())])
4935                }));
4936            }
4937            let result = transport.realtime_connect("c1");
4938            // Stop the responder even when the redirect was refused; the
4939            // sentinel is the only connection it may have seen.
4940            let mut sentinel = std::net::TcpStream::connect(destination_addr).unwrap();
4941            let _ = write!(sentinel, "GET /sentinel HTTP/1.1\r\nHost: sentinel\r\n\r\n");
4942            destination_thread.join().unwrap();
4943            let landed = landed.lock().unwrap().clone();
4944            origin_thread.join().unwrap();
4945            let error = result.unwrap_err();
4946            assert_eq!(
4947                error.code, "transport.redirect",
4948                "{credential}: a refused handshake redirect surfaces the redirect code"
4949            );
4950            let details = error.details.unwrap();
4951            assert_eq!(details["causeKind"], "redirect");
4952            assert_eq!(details["httpStatus"], 302);
4953            assert_eq!(
4954                landed.len(),
4955                1,
4956                "{credential}: the redirect target is never contacted: {landed:?}"
4957            );
4958            assert!(landed[0].starts_with("GET /sentinel"), "{landed:?}");
4959            let head = head_rx.recv().unwrap();
4960            if credential == "userinfo" {
4961                assert!(
4962                    !head.contains("secret"),
4963                    "the handshake request line drops URL userinfo"
4964                );
4965            }
4966            if credential == "query" {
4967                assert!(
4968                    head.contains("token=secret"),
4969                    "the handshake request line carries the realtime query"
4970                );
4971            }
4972        }
4973    }
4974
4975    // 200000 decoded bytes in 548 compressed bytes: a decompression bomb the
4976    // decoded cap must stop before the buffer grows.
4977    const GZIP_BOMB: [u8; 548] = [
4978        0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xed, 0xc9, 0xb1, 0x11, 0x80,
4979        0x20, 0x10, 0x00, 0xb0, 0x59, 0x1c, 0x80, 0xa1, 0xfe, 0x90, 0xb3, 0x41, 0xf0, 0x7c, 0x2d,
4980        0xd8, 0xde, 0x09, 0xdc, 0x20, 0x69, 0x93, 0x6b, 0xd4, 0xb7, 0xc7, 0x5d, 0xb2, 0x1d, 0x67,
4981        0x1b, 0x4f, 0xb9, 0x62, 0xf5, 0x19, 0xfb, 0x96, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4982        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4983        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4984        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4985        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4986        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4987        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4988        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4989        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4990        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4991        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4992        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4993        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4994        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4995        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4996        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4997        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4998        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
4999        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5000        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5001        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5002        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5003        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5004        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5005        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5006        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5007        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5008        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5009        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5010        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5011        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5012        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08,
5013        0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0x10, 0x42, 0x08, 0x21, 0x84, 0xf8, 0x8b, 0x0f,
5014        0xdb, 0x82, 0xf4, 0xa9, 0x40, 0x0d, 0x03, 0x00,
5015    ];
5016
5017    #[test]
5018    fn decoded_response_cap_counts_decompressed_bytes() {
5019        for cap in [200000u64, 199999] {
5020            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
5021            let base = format!("http://{}", listener.local_addr().unwrap());
5022            let server = std::thread::spawn(move || {
5023                let (mut socket, _) = listener.accept().unwrap();
5024                let mut reader = BufReader::new(socket.try_clone().unwrap());
5025                loop {
5026                    let mut line = String::new();
5027                    reader.read_line(&mut line).unwrap();
5028                    if line == "\r\n" {
5029                        break;
5030                    }
5031                }
5032                let _ = write!(
5033                    socket,
5034                    "HTTP/1.1 200 OK\r\nContent-Encoding: gzip\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
5035                    GZIP_BOMB.len()
5036                );
5037                let _ = socket.write_all(&GZIP_BOMB);
5038            });
5039            let mut transport = HostTransport::from_config(
5040                &serde_json::json!({"baseUrl": base, "maxResponseBytes": cap}),
5041            )
5042            .unwrap();
5043            let result = transport.fetch_blob_url(&format!("{base}/signed"), None);
5044            if cap == 200000 {
5045                let body = result.expect("a cap equal to the decoded size admits the body");
5046                assert_eq!(body.len(), 200000);
5047            } else {
5048                let error = result.unwrap_err();
5049                assert_eq!(error.code, "transport.response_too_large");
5050                assert_eq!(error.details, Some(serde_json::json!({ "limit": cap })));
5051            }
5052            server.join().unwrap();
5053        }
5054    }
5055
5056    #[test]
5057    fn a_json_http_error_body_reaches_the_caller() {
5058        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
5059        let base = format!("http://{}", listener.local_addr().unwrap());
5060        let body = r#"{"code":"sync.invalid_client_id","category":"invalid-request","retryable":false,"recommendedAction":"resetClientId","message":"clientId is bound to a different actor in this partition (§1.5)","details":{"actorId":"actor-b"}}"#;
5061        let server = std::thread::spawn(move || {
5062            let (mut socket, _) = listener.accept().unwrap();
5063            let mut reader = BufReader::new(socket.try_clone().unwrap());
5064            loop {
5065                let mut line = String::new();
5066                reader.read_line(&mut line).unwrap();
5067                if line == "\r\n" {
5068                    break;
5069                }
5070            }
5071            let _ = write!(
5072                socket,
5073                "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
5074                body.len(),
5075                body
5076            );
5077        });
5078        let mut transport =
5079            HostTransport::from_config(&serde_json::json!({"baseUrl": base})).unwrap();
5080        let error = transport.sync(&[]).unwrap_err();
5081        assert_eq!(error.code, "sync.invalid_client_id");
5082        assert_eq!(
5083            error.message,
5084            "clientId is bound to a different actor in this partition (§1.5)"
5085        );
5086        let details = error.details.unwrap();
5087        assert_eq!(details["recommendedAction"], "resetClientId");
5088        assert_eq!(details["category"], "invalid-request");
5089        assert_eq!(details["retryable"], false);
5090        assert_eq!(details["httpStatus"], 400);
5091        assert_eq!(details["actorId"], "actor-b");
5092        server.join().unwrap();
5093    }
5094
5095    /// Answer one HTTP request per status, in order, and return each request
5096    /// head lowercased. A 401 carries the server's `sync.auth_required` body.
5097    fn answer(
5098        listener: std::net::TcpListener,
5099        statuses: Vec<u16>,
5100    ) -> std::thread::JoinHandle<Vec<String>> {
5101        std::thread::spawn(move || {
5102            statuses
5103                .into_iter()
5104                .map(|status| {
5105                    use std::io::Read;
5106                    let (mut socket, _) = listener.accept().unwrap();
5107                    let mut reader = BufReader::new(socket.try_clone().unwrap());
5108                    let mut head = String::new();
5109                    let mut length = 0;
5110                    loop {
5111                        let mut line = String::new();
5112                        reader.read_line(&mut line).unwrap();
5113                        if line == "\r\n" {
5114                            break;
5115                        }
5116                        let line = line.to_ascii_lowercase();
5117                        if let Some(value) = line.strip_prefix("content-length:") {
5118                            length = value.trim().parse().unwrap();
5119                        }
5120                        head.push_str(&line);
5121                    }
5122                    reader.read_exact(&mut vec![0; length]).unwrap();
5123                    let body = if status == 401 {
5124                        r#"{"code":"sync.auth_required","message":"host authentication required"}"#
5125                    } else {
5126                        "ok"
5127                    };
5128                    write!(
5129                        socket,
5130                        "HTTP/1.1 {status} Reply\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
5131                        body.len()
5132                    )
5133                    .unwrap();
5134                    head
5135                })
5136                .collect()
5137        })
5138    }
5139
5140    fn bearer(token: &str) -> Vec<(String, String)> {
5141        vec![("authorization".to_owned(), format!("Bearer {token}"))]
5142    }
5143
5144    #[test]
5145    fn transport_config_headers_are_refused() {
5146        let error = HostTransport::from_config(&serde_json::json!({
5147            "baseUrl": "http://127.0.0.1:1",
5148            "headers": { "authorization": "Bearer static" }
5149        }))
5150        .err()
5151        .unwrap();
5152        assert!(error.starts_with("sync.invalid_request:"), "{error}");
5153    }
5154
5155    #[test]
5156    fn each_host_request_reads_its_context_and_signed_urls_carry_no_host_headers() {
5157        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
5158        let base = format!("http://{}", listener.local_addr().unwrap());
5159        let server = answer(listener, vec![200; 7]);
5160        let contexts = Arc::new(Mutex::new(Vec::new()));
5161        let seen = contexts.clone();
5162        let mut transport =
5163            HostTransport::from_config(&serde_json::json!({ "baseUrl": base })).unwrap();
5164        transport.set_header_source(HeaderSource::new(move |context, rejected| {
5165            assert!(rejected.is_none());
5166            let mut seen = seen.lock().unwrap();
5167            seen.push(context.clone());
5168            let mut headers = bearer(&(seen.len() - 1).to_string());
5169            headers.push(("sentry-trace".into(), format!("trace-{}", seen.len() - 1)));
5170            Some(headers)
5171        }));
5172        transport.set_client_id("c1");
5173        transport.set_round(Some(7));
5174        transport.sync(b"sync").unwrap();
5175        transport
5176            .download_segment(
5177                &SegmentRequest {
5178                    segment_id: "sha256:test".into(),
5179                    table: "tasks".into(),
5180                    requested_scopes_json: "{}".into(),
5181                    byte_length: 1 << 20,
5182                },
5183                &mut |_| {},
5184            )
5185            .unwrap();
5186        transport.set_round(None);
5187        transport.remote_operation(b"operation").unwrap();
5188        transport.blob_upload("sha256:test", b"blob", None).unwrap();
5189        transport
5190            .fetch_url(&format!("{base}/signed-segment"), 1 << 20, &mut |_| {})
5191            .unwrap();
5192        transport
5193            .fetch_blob_url(&format!("{base}/signed-blob"), None)
5194            .unwrap();
5195        transport
5196            .blob_put_url(
5197                &format!("sha256:{}", "0".repeat(64)),
5198                &format!("{base}/signed-put"),
5199                b"blob",
5200                None,
5201            )
5202            .unwrap();
5203        let heads = server.join().unwrap();
5204        for (index, head) in heads[..4].iter().enumerate() {
5205            assert!(
5206                head.contains(&format!("authorization: bearer {index}")),
5207                "{head}"
5208            );
5209            assert!(
5210                head.contains(&format!("sentry-trace: trace-{index}")),
5211                "{head}"
5212            );
5213        }
5214        for head in &heads[4..] {
5215            assert!(!head.contains("authorization:"), "{head}");
5216            assert!(!head.contains("sentry-trace:"), "{head}");
5217        }
5218        let context = |round, target| HeaderContext {
5219            client_id: "c1".into(),
5220            round,
5221            target,
5222        };
5223        assert_eq!(
5224            *contexts.lock().unwrap(),
5225            vec![
5226                context(Some(7), HeaderTarget::Sync),
5227                context(Some(7), HeaderTarget::Segment),
5228                context(None, HeaderTarget::Sync),
5229                context(None, HeaderTarget::Blob),
5230            ]
5231        );
5232    }
5233
5234    #[test]
5235    fn a_source_without_headers_fails_before_the_network() {
5236        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
5237        listener.set_nonblocking(true).unwrap();
5238        let base = format!("http://{}", listener.local_addr().unwrap());
5239        let mut transport =
5240            HostTransport::from_config(&serde_json::json!({ "baseUrl": base })).unwrap();
5241        transport.set_header_source(HeaderSource::new(|_, _| None));
5242        for error in [
5243            transport.sync(b"sync").unwrap_err(),
5244            transport
5245                .blob_upload("sha256:test", b"blob", None)
5246                .unwrap_err(),
5247            transport.realtime_connect("c1").unwrap_err(),
5248        ] {
5249            assert_eq!(error.code, "sync.auth_required");
5250            assert_eq!(error.message, "the host header source gave no headers");
5251            assert_eq!(
5252                error.details,
5253                Some(serde_json::json!({ "causeKind": "header_source" }))
5254            );
5255        }
5256        assert!(
5257            matches!(listener.accept(), Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock),
5258            "no request reaches the server"
5259        );
5260    }
5261
5262    #[test]
5263    fn a_401_refreshes_the_header_source_and_retries_exactly_once() {
5264        // `stale`: the refresh returns the refused token again, so the server
5265        // sees exactly two requests and the second 401 surfaces.
5266        for stale in [false, true] {
5267            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
5268            let base = format!("http://{}", listener.local_addr().unwrap());
5269            let server = answer(listener, vec![401, if stale { 401 } else { 200 }]);
5270            let reads = Arc::new(Mutex::new(Vec::new()));
5271            let seen = reads.clone();
5272            let mut transport =
5273                HostTransport::from_config(&serde_json::json!({ "baseUrl": base })).unwrap();
5274            transport.set_header_source(HeaderSource::new(move |_, rejected| {
5275                seen.lock().unwrap().push(rejected.map(<[_]>::to_vec));
5276                Some(bearer(if rejected.is_none() || stale {
5277                    "stale"
5278                } else {
5279                    "fresh"
5280                }))
5281            }));
5282            let result = transport.sync(b"sync");
5283            let heads = server.join().unwrap();
5284            assert!(heads[0].contains("authorization: bearer stale"));
5285            assert_eq!(heads[1].contains("authorization: bearer fresh"), !stale);
5286            assert_eq!(*reads.lock().unwrap(), vec![None, Some(bearer("stale"))]);
5287            if stale {
5288                let error = result.unwrap_err();
5289                assert_eq!(error.code, "sync.auth_required");
5290                assert_eq!(error.details.unwrap()["httpStatus"], 401);
5291            } else {
5292                assert_eq!(result.unwrap(), b"ok");
5293            }
5294        }
5295    }
5296
5297    #[test]
5298    #[allow(clippy::result_large_err)]
5299    fn a_realtime_handshake_reads_the_header_source_and_retries_a_401_once() {
5300        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
5301        let base = format!("http://{}", listener.local_addr().unwrap());
5302        let server = std::thread::spawn(move || {
5303            let (mut refused, _) = listener.accept().unwrap();
5304            let mut reader = BufReader::new(refused.try_clone().unwrap());
5305            let mut head = String::new();
5306            loop {
5307                let mut line = String::new();
5308                reader.read_line(&mut line).unwrap();
5309                if line == "\r\n" {
5310                    break;
5311                }
5312                head.push_str(&line.to_ascii_lowercase());
5313            }
5314            assert!(head.contains("authorization: bearer stale"), "{head}");
5315            write!(
5316                refused,
5317                "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
5318            )
5319            .unwrap();
5320            let (accepted, _) = listener.accept().unwrap();
5321            let mut socket = tungstenite::accept_hdr(
5322                accepted,
5323                |request: &tungstenite::handshake::server::Request, response| {
5324                    assert_eq!(request.headers()["authorization"], "Bearer fresh");
5325                    Ok(response)
5326                },
5327            )
5328            .unwrap();
5329            while socket.read().is_ok() {}
5330        });
5331        let reads = Arc::new(Mutex::new(Vec::new()));
5332        let seen = reads.clone();
5333        let mut transport =
5334            HostTransport::from_config(&serde_json::json!({ "baseUrl": base })).unwrap();
5335        transport.set_header_source(HeaderSource::new(move |_, rejected| {
5336            seen.lock().unwrap().push(rejected.map(<[_]>::to_vec));
5337            Some(bearer(if rejected.is_none() { "stale" } else { "fresh" }))
5338        }));
5339        transport.realtime_connect("c1").unwrap();
5340        assert_eq!(*reads.lock().unwrap(), vec![None, Some(bearer("stale"))]);
5341        transport.shutdown();
5342        server.join().unwrap();
5343    }
5344
5345    #[test]
5346    fn reads_of_one_round_share_a_flight_and_other_rounds_and_replicas_fly_alone() {
5347        let (entered_tx, entered) = mpsc::channel();
5348        let (release, released) = mpsc::channel::<()>();
5349        let released = Mutex::new(released);
5350        let calls = Arc::new(AtomicU64::new(0));
5351        let counted = calls.clone();
5352        let source = HeaderSource::new(move |_, _| {
5353            let call = counted.fetch_add(1, Ordering::SeqCst);
5354            entered_tx.send(()).unwrap();
5355            released.lock().unwrap().recv().unwrap();
5356            Some(bearer(&call.to_string()))
5357        });
5358        let read = |client: &str, round: u64, target, rejected: Option<Vec<(String, String)>>| {
5359            let source = source.clone();
5360            let context = HeaderContext {
5361                client_id: client.into(),
5362                round: Some(round),
5363                target,
5364            };
5365            std::thread::spawn(move || source.read(&context, rejected.as_deref()).unwrap())
5366        };
5367        let first = read("c1", 1, HeaderTarget::Sync, None);
5368        entered.recv().unwrap();
5369        // The same round's segment reads join the sync read's flight.
5370        let joined = [
5371            read("c1", 1, HeaderTarget::Segment, None),
5372            read("c1", 1, HeaderTarget::Segment, None),
5373        ];
5374        // A refresh, another round and another replica each start a call.
5375        // Each starts only after the previous one entered, so the call numbers
5376        // follow this order.
5377        let others = [
5378            ("c1", 1, Some(bearer("0"))),
5379            ("c1", 2, None),
5380            ("c2", 1, None),
5381        ]
5382        .into_iter()
5383        .map(|(client, round, rejected)| {
5384            let reader = read(client, round, HeaderTarget::Sync, rejected);
5385            entered.recv().unwrap();
5386            reader
5387        })
5388        .collect::<Vec<_>>();
5389        let key = ("c1".to_owned(), Some(1), false);
5390        while source.0.state.lock().unwrap()[&key].joined < 2 {
5391            std::thread::yield_now();
5392        }
5393        for _ in 0..4 {
5394            release.send(()).unwrap();
5395        }
5396        assert_eq!(first.join().unwrap(), bearer("0"));
5397        for reader in joined {
5398            assert_eq!(reader.join().unwrap(), bearer("0"));
5399        }
5400        for (call, reader) in others.into_iter().enumerate() {
5401            assert_eq!(reader.join().unwrap(), bearer(&(call + 1).to_string()));
5402        }
5403        assert_eq!(calls.load(Ordering::SeqCst), 4);
5404        assert!(
5405            source.0.state.lock().unwrap().is_empty(),
5406            "landed flights are dropped"
5407        );
5408    }
5409}
5410
5411#[cfg(test)]
5412mod local_authority_tests {
5413    use super::HostTransport;
5414    use crate::Transport;
5415
5416    #[cfg(not(feature = "local-authority"))]
5417    #[test]
5418    fn a_local_authority_path_without_the_feature_fails_with_the_unconfigured_code() {
5419        let error = HostTransport::from_config(
5420            &serde_json::json!({ "localAuthorityPath": "authority.sqlite" }),
5421        )
5422        .err()
5423        .expect("a build without local-authority refuses localAuthorityPath");
5424        assert!(
5425            error.starts_with("client.local_authority_unconfigured:"),
5426            "{error}"
5427        );
5428    }
5429
5430    #[test]
5431    fn a_config_without_a_local_authority_reports_none() {
5432        let mut transport = HostTransport::from_config(&serde_json::json!({}))
5433            .ok()
5434            .unwrap();
5435        assert_eq!(transport.local_authority_state(), None);
5436        let error = transport.attach_local_authority().unwrap_err();
5437        assert_eq!(error.code, "client.local_authority_unconfigured");
5438        let error = transport.abandon_local_authority_attach().unwrap_err();
5439        assert_eq!(error.code, "client.local_authority_unconfigured");
5440    }
5441
5442    #[cfg(feature = "local-authority")]
5443    mod with_feature {
5444        use serde_json::{json, Map, Value};
5445        use syncular_authority::LocalAuthority;
5446
5447        use super::super::{HostTransport, LocalAuthorityTransport};
5448        use crate::{
5449            ClientLimits, Mutation, SegmentFetch, SegmentRequest, SyncClient, SyncOutcome,
5450            Transport, TransportError, UnitScopes,
5451        };
5452
5453        fn schema() -> Value {
5454            json!({
5455                "version": 1,
5456                "tables": [{
5457                    "name": "todos",
5458                    "columns": [
5459                        { "name": "id", "type": "string", "nullable": false },
5460                        { "name": "list_id", "type": "string", "nullable": false }
5461                    ],
5462                    "primaryKey": "id",
5463                    "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
5464                }]
5465            })
5466        }
5467
5468        /// The remote server: a second authority that serves the requests the
5469        /// first one's attach and the client's later rounds send it.
5470        struct AuthorityServer {
5471            server: LocalAuthority,
5472            syncs: usize,
5473        }
5474
5475        impl Transport for AuthorityServer {
5476            fn sync(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
5477                self.syncs += 1;
5478                self.server.sync(request).map_err(|error| TransportError {
5479                    code: error.code,
5480                    message: error.message,
5481                    details: error.details,
5482                })
5483            }
5484            fn realtime_sync(&mut self, _request: &[u8]) -> Result<Vec<u8>, TransportError> {
5485                Err(TransportError::new("sync.transport_failed", "no socket"))
5486            }
5487            fn download_segment(
5488                &mut self,
5489                _request: &SegmentRequest,
5490                _on_progress: &mut dyn FnMut(u64),
5491            ) -> Result<Vec<u8>, TransportError> {
5492                Err(TransportError::new("sync.transport_failed", "no segments"))
5493            }
5494            fn realtime_connect(&mut self, _client_id: &str) -> Result<(), TransportError> {
5495                Err(TransportError::new("sync.transport_failed", "no socket"))
5496            }
5497            fn realtime_send(&mut self, _text: &str) -> Result<(), TransportError> {
5498                Ok(())
5499            }
5500            fn realtime_close(&mut self) -> Result<(), TransportError> {
5501                Ok(())
5502            }
5503        }
5504
5505        #[test]
5506        fn a_configured_path_routes_to_the_authority_and_refuses_what_it_lacks() {
5507            let mut transport =
5508                HostTransport::from_config(&json!({ "localAuthorityPath": ":memory:" }))
5509                    .ok()
5510                    .unwrap();
5511            assert!(matches!(transport, HostTransport::Local(_)));
5512            // The authority opens with the client's schema at create.
5513            assert_eq!(transport.local_authority_state(), None);
5514            assert_eq!(
5515                transport.sync(b"").unwrap_err().code,
5516                "client.local_authority_unconfigured"
5517            );
5518            assert_eq!(
5519                transport.realtime_connect("device-1").unwrap_err().code,
5520                "sync.invalid_request"
5521            );
5522            let refused = transport.download_segments(
5523                &[SegmentFetch::Url {
5524                    url: "https://cdn.example.com/s1".to_owned(),
5525                    byte_length: 1 << 20,
5526                }],
5527                &mut |_, _| {},
5528            );
5529            assert_eq!(refused.len(), 1);
5530            assert_eq!(
5531                refused[0].as_ref().unwrap_err().code,
5532                "sync.invalid_request"
5533            );
5534            // Attach needs a remote server.
5535            let error = transport.attach_local_authority().unwrap_err();
5536            assert_eq!(error.code, "client.local_authority_unconfigured");
5537        }
5538
5539        /// The client's `crdt-yjs` feature gives the local authority its merger,
5540        /// so a crdt commit is accepted instead of `sync.crdt_merge_failed`.
5541        #[cfg(feature = "crdt-yjs")]
5542        #[test]
5543        fn a_crdt_commit_through_the_local_authority_is_merged() {
5544            let schema = json!({
5545                "version": 1,
5546                "tables": [{
5547                    "name": "notes",
5548                    "columns": [
5549                        { "name": "id", "type": "string", "nullable": false },
5550                        { "name": "list_id", "type": "string", "nullable": false },
5551                        { "name": "doc", "type": "crdt", "nullable": true, "crdtType": "yjs-doc" }
5552                    ],
5553                    "primaryKey": "id",
5554                    "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
5555                }]
5556            });
5557            let mut transport =
5558                HostTransport::from_config(&json!({ "localAuthorityPath": ":memory:" }))
5559                    .ok()
5560                    .unwrap();
5561            transport
5562                .open_local_authority(&schema, None)
5563                .expect("open the local authority");
5564            let mut client = SyncClient::new_with_identity(
5565                Some("device-1".to_owned()),
5566                &schema,
5567                ClientLimits::default(),
5568            )
5569            .expect("client");
5570            client
5571                .subscribe(UnitScopes::from([("list_id".to_owned(), "l1".to_owned())]))
5572                .expect("subscribe");
5573            client
5574                .mutate(vec![Mutation::Upsert {
5575                    table: "notes".to_owned(),
5576                    values: Map::from_iter([
5577                        ("id".to_owned(), json!("n1")),
5578                        ("list_id".to_owned(), json!("l1")),
5579                        ("doc".to_owned(), Value::Null),
5580                    ]),
5581                    base_version: None,
5582                }])
5583                .expect("mutate");
5584            client
5585                .crdt_insert_text("notes", "n1", "doc", "text", 0, "éa")
5586                .expect("crdt insert");
5587            let outcome = client.sync_until_idle(&mut transport, None);
5588            assert!(
5589                matches!(outcome, SyncOutcome::Ok(_)),
5590                "{:?}",
5591                outcome.to_json()
5592            );
5593            assert!(client.pending_commit_ids().is_empty());
5594            assert!(client.rejections().is_empty(), "{:?}", client.rejections());
5595            assert_eq!(
5596                client.crdt_text("notes", "n1", "doc", "text").unwrap(),
5597                "éa"
5598            );
5599        }
5600
5601        #[test]
5602        fn the_authority_path_must_differ_from_the_replica_and_be_a_string() {
5603            let mut transport =
5604                HostTransport::from_config(&json!({ "localAuthorityPath": "/data/app.sqlite" }))
5605                    .ok()
5606                    .unwrap();
5607            let error = transport
5608                .open_local_authority(&schema(), Some("/data/app.sqlite"))
5609                .unwrap_err();
5610            assert_eq!(error.code, "sync.invalid_request");
5611            for path in [json!(""), json!(7)] {
5612                assert!(
5613                    HostTransport::from_config(&json!({ "localAuthorityPath": path })).is_err()
5614                );
5615            }
5616        }
5617
5618        #[test]
5619        fn rounds_reach_the_authority_until_attach_then_the_remote_server() {
5620            let schema = schema();
5621            let remote = AuthorityServer {
5622                server: LocalAuthority::open(":memory:", &schema).expect("open the remote"),
5623                syncs: 0,
5624            };
5625            let mut transport = LocalAuthorityTransport::new(":memory:", remote, true);
5626            transport
5627                .open_local_authority(&schema, None)
5628                .expect("open the local authority");
5629            assert_eq!(transport.local_authority_state(), Some("local"));
5630
5631            let mut client = SyncClient::new_with_identity(
5632                Some("device-1".to_owned()),
5633                &schema,
5634                ClientLimits::default(),
5635            )
5636            .expect("client");
5637            client
5638                .subscribe(UnitScopes::from([("list_id".to_owned(), "l1".to_owned())]))
5639                .expect("subscribe");
5640            client
5641                .mutate(vec![Mutation::Upsert {
5642                    table: "todos".to_owned(),
5643                    values: Map::from_iter([
5644                        ("id".to_owned(), json!("t1")),
5645                        ("list_id".to_owned(), json!("l1")),
5646                    ]),
5647                    base_version: None,
5648                }])
5649                .expect("mutate");
5650            let outcome = client.sync_until_idle(&mut transport, None);
5651            assert!(
5652                matches!(outcome, SyncOutcome::Ok(_)),
5653                "{:?}",
5654                outcome.to_json()
5655            );
5656            assert!(client.pending_commit_ids().is_empty());
5657            assert_eq!(
5658                transport.remote.syncs, 0,
5659                "the local authority served the round"
5660            );
5661            let error = client.connect_realtime(&mut transport).unwrap_err();
5662            assert!(error.starts_with("sync.invalid_request:"), "{error}");
5663
5664            transport.attach_local_authority().expect("attach");
5665            assert_eq!(transport.local_authority_state(), Some("attached"));
5666            let uploads = transport.remote.syncs;
5667            assert!(uploads > 0, "attach uploaded through the remote transport");
5668
5669            // The remote server's log epoch differs, so the replica resets and
5670            // bootstraps the attached row from it.
5671            let outcome = client.sync_until_idle(&mut transport, None);
5672            assert!(
5673                matches!(outcome, SyncOutcome::Ok(_)),
5674                "{:?}",
5675                outcome.to_json()
5676            );
5677            assert!(transport.remote.syncs > uploads);
5678            let rows = client.read_rows("todos").expect("rows");
5679            assert_eq!(rows.len(), 1);
5680            assert_eq!(rows[0].row_id, "t1");
5681            assert!(rows[0].version >= 1);
5682        }
5683    }
5684}
5685
5686#[cfg(test)]
5687mod header_question_tests {
5688    use super::*;
5689    use std::sync::atomic::AtomicI64;
5690
5691    fn context() -> HeaderContext {
5692        HeaderContext {
5693            client_id: "c1".into(),
5694            round: None,
5695            target: HeaderTarget::Realtime,
5696        }
5697    }
5698
5699    #[test]
5700    fn an_unanswered_question_fails_once_the_clock_passes_the_bound() {
5701        let clock = Arc::new(AtomicI64::new(5_000));
5702        let now = clock.clone();
5703        let (asked_tx, asked) = mpsc::channel();
5704        let questions = HeaderQuestions::new(
5705            move |id, context: &HeaderContext, _| {
5706                assert_eq!(context.target, HeaderTarget::Realtime);
5707                asked_tx.send(id).unwrap()
5708            },
5709            move || now.load(Ordering::SeqCst),
5710        );
5711        let source = questions.source();
5712        let read = std::thread::spawn(move || source.read(&context(), None));
5713        assert_eq!(asked.recv().unwrap(), 1);
5714        assert!(questions.is_open(1));
5715        clock.store(5_000 + HEADER_ANSWER_WAIT_MS, Ordering::SeqCst);
5716        // Past the bound the question is closed even before its waiter wakes.
5717        assert!(!questions.is_open(1));
5718        questions.recheck();
5719        let error = read.join().unwrap().unwrap_err();
5720        assert_eq!(error.code, "sync.auth_required");
5721        assert_eq!(
5722            error.details,
5723            Some(serde_json::json!({ "causeKind": "header_source" }))
5724        );
5725        // The late answer is ignored; the next read asks again under a new id.
5726        questions.provide(1, &serde_json::json!({})).unwrap();
5727        let source = questions.source();
5728        let read = std::thread::spawn(move || source.read(&context(), None));
5729        assert_eq!(asked.recv().unwrap(), 2);
5730        assert_eq!(
5731            questions
5732                .provide(2, &serde_json::json!({ "x-actor": 7 }))
5733                .unwrap_err()
5734                .code,
5735            "sync.invalid_request"
5736        );
5737        questions
5738            .provide(2, &serde_json::json!({ "x-actor": "a1" }))
5739            .unwrap();
5740        assert_eq!(
5741            read.join().unwrap().unwrap(),
5742            vec![("x-actor".to_owned(), "a1".to_owned())]
5743        );
5744    }
5745
5746    #[test]
5747    fn close_fails_open_and_later_questions() {
5748        let (asked_tx, asked) = mpsc::channel();
5749        let questions = HeaderQuestions::new(move |id, _, _| asked_tx.send(id).unwrap(), || 0);
5750        let source = questions.source();
5751        let waiting = source.clone();
5752        let read = std::thread::spawn(move || waiting.read(&context(), None));
5753        asked.recv().unwrap();
5754        questions.close();
5755        assert_eq!(read.join().unwrap().unwrap_err().code, "client.closed");
5756        assert_eq!(
5757            source.read(&context(), None).unwrap_err().code,
5758            "client.closed"
5759        );
5760        assert!(asked.try_recv().is_err(), "a closed source asks nothing");
5761    }
5762}