Skip to main content

toolkit_contract/runtime/
client.rs

1//! Per-call helpers used by the generated REST client.
2//!
3//! The macro keeps emitted code small by funnelling the common
4//! "send unary request and decode the response" path through
5//! [`send_unary`], and the streaming path through
6//! [`send_streaming`].
7
8use std::pin::Pin;
9use std::time::Duration;
10
11use futures_core::Stream;
12use serde::Serialize;
13use serde::de::DeserializeOwned;
14use toolkit_http::RequestBuilder;
15
16use crate::ir::binding::StreamFraming;
17use crate::runtime::breaker::AttemptStart;
18use crate::runtime::config::{ClientConfig, ReconnectConfig};
19use crate::runtime::http::{
20    body_to_byte_stream, map_http_error, parse_retry_after, read_error_body_prefix,
21};
22use crate::runtime::multipart::{
23    MultipartStream, boundary_from_content_type, parse_multipart_stream,
24};
25use crate::runtime::sse::{LastEventId, SseStream, StreamActivity, parse_sse_stream_with_id};
26use crate::runtime::transport_error::TransportError;
27
28/// Boxed byte stream produced from an HTTP response body for framing parsers.
29type BoxByteStream = Pin<
30    Box<
31        dyn Stream<Item = Result<bytes::Bytes, Box<dyn std::error::Error + Send + Sync + 'static>>>
32            + Send,
33    >,
34>;
35
36/// Send a unary request and decode the JSON response.
37///
38/// `build` is a closure returning a `RequestBuilder` configured with method,
39/// URL, headers, and any auth state. It is invoked once per attempt.
40///
41/// `timeout` bounds the **whole** attempt — connection, response headers, and
42/// reading the response body — as a per-attempt deadline (mirroring the
43/// streaming path). It runs from the moment the attempt reaches the transport,
44/// after auth and the client's queue, so time spent there is not taken from
45/// the backend. Elapse maps to [`TransportError::Timeout`], which is
46/// transient, so a `#[retryable]` method retries a timed-out attempt. `None`
47/// leaves the deadline to the underlying transport.
48///
49/// # Errors
50/// Returns [`TransportError`] when the builder closure fails, the deadline elapses,
51/// the network call fails, the response body cannot be read, JSON deserialization of a
52/// success body fails, or the server returns a non-success HTTP status (mapped via
53/// [`map_http_error`]).
54pub async fn send_unary<F, R>(build: F, timeout: Option<Duration>) -> Result<R, TransportError>
55where
56    F: FnOnce() -> Result<RequestBuilder, TransportError>,
57    R: DeserializeOwned,
58{
59    let attempt = AttemptStart::default();
60    let builder = build()?.extension(attempt.clone());
61    let started = tokio::time::Instant::now();
62    let op = async move {
63        let response = builder.send().await.map_err(map_send_error)?;
64        let status = response.status();
65        if status.is_success() {
66            // `HttpResponse::bytes` does NOT enforce status check; we already did.
67            // Avoiding `.json()` here because it would re-check status and
68            // duplicate work on the success path.
69            let bytes = response.bytes().await.map_err(TransportError::network)?;
70            // A `204 No Content` (or any 2xx with an empty body) is valid for
71            // methods returning `Result<(), _>` and other unit-like `Ok` types.
72            // `serde_json::from_slice::<()>(b"")` would fail with an EOF error
73            // (and `()` deserializes only from JSON `null`), so map an empty
74            // success body to JSON `null` before decoding — `null` deserializes
75            // into `()` and `Option::None`, while any non-unit `R` still errors.
76            let bytes: &[u8] = if bytes.is_empty() { b"null" } else { &bytes };
77            serde_json::from_slice::<R>(bytes).map_err(TransportError::serialization)
78        } else {
79            let retry_after = parse_retry_after(response.headers());
80            let bytes = response.bytes().await.map_err(TransportError::network)?;
81            let body = String::from_utf8_lossy(&bytes).into_owned();
82            Err(map_http_error(status.as_u16(), body, retry_after))
83        }
84    };
85    // The transport's own timeout, set to the same length, bounds the wait
86    // for response headers, so a timed-out attempt reaches the circuit
87    // breaker's attempt layer as a timeout. This timer, which also bounds the
88    // body, runs from the same start plus a grace, so it never fires first;
89    // if it did, the breaker would see only a dropped call.
90    match timeout {
91        Some(d) => attempt
92            .bound(started, d + HEADER_DEADLINE_GRACE, op)
93            .await
94            .ok_or(TransportError::Timeout(d))?,
95        None => op.await,
96    }
97}
98
99/// Slack the outer per-attempt timer gives the transport's timeout layer, so
100/// the transport reports a timed-out attempt first. See [`send_unary`].
101const HEADER_DEADLINE_GRACE: Duration = Duration::from_millis(50);
102
103/// Shared transport-construction chain for both cfg variants of
104/// [`build_default_http_client`] — in one place so a knob can't be added to one
105/// arm and forgotten in the other.
106///
107/// Reads only transport-construction fields; call-time fields (`retry`,
108/// streaming, `internal_token_provider`) are applied per call and must not be
109/// wired here. `timeout` is wired on purpose: the SDK also enforces it per call,
110/// and matching the transport's `TimeoutLayer` to it stops a `config.timeout`
111/// above toolkit-http's 30s default being silently capped at 30s.
112fn transport_builder(config: &ClientConfig) -> toolkit_http::HttpClientBuilder {
113    let builder = toolkit_http::HttpClient::builder()
114        .retry(None)
115        .transport(transport_security(config.require_tls))
116        .timeout(config.timeout)
117        .pool_max_idle_per_host(config.pool_max_idle_per_host)
118        .pool_idle_timeout(config.pool_idle_timeout)
119        .concurrency_limit(
120            config
121                .max_concurrent_requests
122                .map(|max_concurrent_requests| toolkit_http::RateLimitConfig {
123                    max_concurrent_requests,
124                }),
125        );
126    crate::runtime::breaker::install_http_breaker(builder, config)
127}
128
129/// Build the default `toolkit-http` client used by macro-generated REST clients.
130///
131/// Transport-layer retry is **disabled** — the SDK runs its own retry loop in
132/// [`retry_with_backoff`](crate::runtime::retry::retry_with_backoff).
133///
134/// Only the *transport-construction* fields of `config` are read — TLS mode,
135/// the connection-pool and concurrency knobs, and the per-attempt `timeout`;
136/// call-time fields (`retry`, the streaming knobs, `internal_token_provider`)
137/// are applied per call by the generated client, not on the transport. In
138/// particular `config.require_tls` selects the transport security mode: `false`
139/// (the default via
140/// [`ClientConfig::new`](crate::runtime::config::ClientConfig::new), except in
141/// FIPS builds where the default is `true`) allows plaintext `http://`,
142/// preserving the platform's existing in-mesh service-to-service convention;
143/// `true`
144/// ([`ClientConfig::with_require_tls`](crate::runtime::config::ClientConfig::with_require_tls))
145/// switches to `toolkit_http::TransportSecurity::TlsOnly`, rejecting
146/// plaintext. This matters because the tenant bearer token is forwarded via
147/// `Authorization` on whatever scheme the resolved endpoint uses — set
148/// `require_tls` when a client may talk to an endpoint outside a trusted
149/// network boundary.
150///
151/// `.with_otel()` is called in BOTH cfg variants below — it always installs
152/// `toolkit-http`'s `OtelLayer`, but the layer's actual W3C `traceparent`
153/// injection is itself `#[cfg(feature = "otel")]` **inside `toolkit-http`**
154/// (a no-op otherwise). Because Cargo unifies features workspace-wide, that
155/// gate tracks whether *anything* in the final binary enables
156/// `toolkit-http/otel` — which may not be this crate's own `otel` feature.
157/// The one thing genuinely gated by *this* crate's `otel` feature (which
158/// forwards `toolkit-http/otel`) is `.with_metrics(client_type)` below, since
159/// that builder method only exists when the dependency is compiled with the
160/// feature on. The generated method's per-method `tracing` span is always
161/// opened either way, independent of any of this.
162///
163/// # Errors
164/// [`toolkit_http::HttpError::InvalidScheme`] when `config.require_tls` is set
165/// and `config.base_url` is not `https://`. Otherwise propagates
166/// [`toolkit_http::HttpError`] from the underlying builder (e.g. a TLS backend
167/// that cannot be constructed under FIPS).
168#[cfg(feature = "otel")]
169pub fn build_default_http_client(
170    client_type: &str,
171    config: &ClientConfig,
172) -> Result<toolkit_http::HttpClient, toolkit_http::HttpError> {
173    reject_plaintext_if_tls_required(config)?;
174    transport_builder(config)
175        .with_otel()
176        .with_metrics(client_type)
177        .build()
178}
179
180/// Non-`otel` build of [`build_default_http_client`]: RED metrics
181/// (`.with_metrics`) are NOT compiled in — that builder method only exists
182/// under `toolkit-http/otel`. `client_type` is unused in this configuration.
183/// `.with_otel()` is still called (see the doc on the `otel`-cfg sibling
184/// above): whether it actually propagates `traceparent` depends on whether
185/// `toolkit-http/otel` ends up enabled by *some* crate in the build, not on
186/// this crate's own `otel` feature.
187///
188/// # Errors
189/// [`toolkit_http::HttpError::InvalidScheme`] when `config.require_tls` is set
190/// and `config.base_url` is not `https://`. Otherwise propagates
191/// [`toolkit_http::HttpError`] from the underlying builder (e.g. a TLS backend
192/// that cannot be constructed under FIPS).
193#[cfg(not(feature = "otel"))]
194pub fn build_default_http_client(
195    _client_type: &str,
196    config: &ClientConfig,
197) -> Result<toolkit_http::HttpClient, toolkit_http::HttpError> {
198    reject_plaintext_if_tls_required(config)?;
199    transport_builder(config).with_otel().build()
200}
201
202/// Fail at construction, not on every call, when TLS is required but the
203/// endpoint is `http://`: the per-call `InvalidScheme` maps to a transient
204/// network error and would be retried.
205fn reject_plaintext_if_tls_required(config: &ClientConfig) -> Result<(), toolkit_http::HttpError> {
206    match config.tls_scheme_violation() {
207        Some(reason) => Err(toolkit_http::HttpError::InvalidScheme {
208            scheme: config
209                .base_url
210                .split_once("://")
211                .map_or_else(String::new, |(scheme, _)| scheme.to_owned()),
212            reason,
213        }),
214        None => Ok(()),
215    }
216}
217
218fn transport_security(require_tls: bool) -> toolkit_http::TransportSecurity {
219    if require_tls {
220        toolkit_http::TransportSecurity::TlsOnly
221    } else {
222        toolkit_http::TransportSecurity::AllowInsecureHttp
223    }
224}
225
226/// Map a `toolkit-http` send error to a [`TransportError`]. Two kinds get a
227/// dedicated variant instead of the generic [`TransportError::Network`]:
228///
229/// - `Overloaded`: the concurrency limiter shed the request before it was sent
230///   → [`TransportError::Overloaded`] (non-transient), so the retry loop can
231///   tell a locally-shed request from a network failure.
232/// - A circuit-breaker rejection from the attempt layer →
233///   [`TransportError::CircuitOpen`] (non-transient).
234/// - `Timeout` / `DeadlineExceeded`: the transport timeout layer fired. It is
235///   set to `config.timeout`, which the SDK also enforces per call, so either
236///   timer can win; both map to [`TransportError::Timeout`] to keep the
237///   classification stable.
238fn map_send_error(err: toolkit_http::HttpError) -> TransportError {
239    match err {
240        toolkit_http::HttpError::Overloaded => TransportError::Overloaded,
241        toolkit_http::HttpError::Timeout(d) | toolkit_http::HttpError::DeadlineExceeded(d) => {
242            TransportError::Timeout(d)
243        }
244        toolkit_http::HttpError::Transport(err) => {
245            match crate::runtime::breaker::find_rejected(err.as_ref()) {
246                Some(rejected) => TransportError::CircuitOpen {
247                    retry_after: rejected.retry_after(),
248                },
249                None => TransportError::network(toolkit_http::HttpError::Transport(err)),
250            }
251        }
252        other => TransportError::network(other),
253    }
254}
255
256/// Add a JSON body to a request builder. Wraps `toolkit_http`'s fallible
257/// `.json()` (which can fail to serialize) in our [`TransportError`] surface
258/// so the macro emit path can `?` uniformly.
259///
260/// # Errors
261/// Returns [`TransportError::Serialization`] when `body` cannot be serialized to JSON.
262pub fn with_json_body<T: Serialize>(
263    builder: RequestBuilder,
264    body: &T,
265) -> Result<RequestBuilder, TransportError> {
266    builder.json(body).map_err(TransportError::serialization)
267}
268
269/// Builder for a streaming request that can be re-issued on reconnect.
270///
271/// `build` receives the latest seen `Last-Event-ID` (or `None` on the first
272/// attempt) and must return a fresh, configured `RequestBuilder`.
273/// Implementations should set the `Last-Event-ID` header from the parameter
274/// when present.
275///
276/// The parameter is permanently `None` under any framing other than SSE:
277/// `Last-Event-ID` is an SSE mechanism and no other framing has a resume
278/// token, so the signature stays framing-free rather than growing a resume-token
279/// abstraction with exactly one inhabitant.
280pub trait StreamRequestFactory: Send + 'static {
281    /// Construct a `RequestBuilder` for the next stream attempt.
282    ///
283    /// # Errors
284    /// Returns [`TransportError`] when the factory cannot produce a builder
285    /// (e.g. URL composition or auth header attachment fails).
286    fn build(&self, last_event_id: Option<&str>) -> Result<RequestBuilder, TransportError>;
287}
288
289impl<F> StreamRequestFactory for F
290where
291    F: Fn(Option<&str>) -> Result<RequestBuilder, TransportError> + Send + 'static,
292{
293    fn build(&self, last: Option<&str>) -> Result<RequestBuilder, TransportError> {
294        (self)(last)
295    }
296}
297
298/// A configured streaming request, ready to be opened.
299///
300/// Replaces what was a positional argument list on [`send_streaming`]. The
301/// knobs are independent and all but the factory have a meaningful default, so
302/// a builder keeps call sites readable as more of them arrive.
303///
304/// Defaults: [`StreamFraming::ServerSentEvents`], no reconnect
305/// ([`ReconnectConfig::disabled`]), no open deadline and no idle deadline.
306///
307/// # Stability
308/// **Not settled surface.** This exists to be driven by generated code; it has
309/// no hand-written consumer yet. Expect it to change until a real consumer has
310/// exercised it.
311pub struct StreamRequest<F> {
312    factory: F,
313    framing: StreamFraming,
314    reconnect: ReconnectConfig,
315    open_timeout: Option<Duration>,
316    idle_timeout: Option<Duration>,
317}
318
319impl<F: StreamRequestFactory> StreamRequest<F> {
320    /// Start from a request factory, with SSE framing, reconnect disabled and
321    /// no open or idle deadline.
322    #[must_use]
323    pub fn new(factory: F) -> Self {
324        Self {
325            factory,
326            framing: StreamFraming::default(),
327            reconnect: ReconnectConfig::disabled(),
328            open_timeout: None,
329            idle_timeout: None,
330        }
331    }
332
333    /// Select the wire framing the response body is parsed as.
334    ///
335    /// This does **not** set the request's `Accept` header — the factory owns
336    /// the request, so advertising the matching media type is its job. The two
337    /// come from one declaration in generated code.
338    #[must_use]
339    pub fn framing(mut self, framing: StreamFraming) -> Self {
340        self.framing = framing;
341        self
342    }
343
344    /// Set the reconnect policy applied to transient open and stream failures.
345    #[must_use]
346    pub fn reconnect(mut self, reconnect: ReconnectConfig) -> Self {
347        self.reconnect = reconnect;
348        self
349    }
350
351    /// Set the deadline for **opening** the stream: the connect, the response
352    /// headers, and (on a non-success status) the error-body read. This is a
353    /// bound on the open handshake only, distinct from
354    /// [`idle_timeout`](Self::idle_timeout), which bounds the gap between items
355    /// once the stream is live. Without it, a peer that accepts the socket and
356    /// never answers hangs the open forever. Generated code defaults this from
357    /// the client's unary [`timeout`](crate::runtime::config::ClientConfig::timeout).
358    #[must_use]
359    pub fn open_timeout(mut self, open_timeout: Duration) -> Self {
360        self.open_timeout = Some(open_timeout);
361        self
362    }
363
364    /// Set the per-item idle deadline. This is *idle*, not total: any wire
365    /// chunk resets it, including ones that dispatch no item.
366    #[must_use]
367    pub fn idle_timeout(mut self, idle_timeout: Duration) -> Self {
368        self.idle_timeout = Some(idle_timeout);
369        self
370    }
371}
372
373/// Why one open attempt failed, and whether the reconnect budget applies.
374///
375/// The distinction is not derivable from [`TransportError::is_transient`]: a
376/// request-shape failure is a configuration bug that will fail identically on
377/// every attempt, so it is fatal regardless of how its error class is
378/// otherwise classified.
379enum OpenFailure {
380    /// Request-shape failure (URL composition, auth attach), or an error-body
381    /// read that itself failed. Never retried.
382    Fatal(TransportError),
383    /// Connect, send, or non-success status. Retried when the error is
384    /// transient and budget remains.
385    Retryable(TransportError),
386}
387
388/// Send one request and await response headers, bounded by `timeout`.
389// cancel-safe: holds only the in-flight send; being dropped (the `timeout`
390// below wraps `send`, so this is the future cancelled on elapse) abandons the
391// attempt with nothing committed and no buffered state to lose.
392async fn send_open_request(
393    builder: RequestBuilder,
394    timeout: Option<Duration>,
395) -> Result<toolkit_http::HttpResponse, OpenFailure> {
396    let attempt = AttemptStart::default();
397    let started = tokio::time::Instant::now();
398    let send_fut = builder.extension(attempt.clone()).send();
399    // Timed from the attempt's arrival at the transport, plus a grace, so the
400    // transport's timer reports the timeout to the circuit breaker first, as
401    // in `send_unary`.
402    let sent = match timeout {
403        Some(d) => match attempt
404            .bound(started, d + HEADER_DEADLINE_GRACE, send_fut)
405            .await
406        {
407            Some(r) => r,
408            None => return Err(OpenFailure::Retryable(TransportError::Timeout(d))),
409        },
410        None => send_fut.await,
411    };
412    // Pre-flight failures are reconnect-eligible, except a concurrency-limiter
413    // shed (`Overloaded`), which is fail-fast: bubble it up as `Fatal`.
414    sent.map_err(|e| match map_send_error(e) {
415        overloaded @ TransportError::Overloaded => OpenFailure::Fatal(overloaded),
416        other => OpenFailure::Retryable(other),
417    })
418}
419
420/// Read and classify a non-success open response.
421// cancel-safe: reads and discards the error body only to build a message;
422// dropping it abandons that read with nothing committed. Awaited to completion
423// inside `open`.
424async fn open_status_failure(
425    response: toolkit_http::HttpResponse,
426    timeout: Option<Duration>,
427) -> OpenFailure {
428    let status_code = response.status().as_u16();
429    let retry_after = parse_retry_after(response.headers());
430    // Bound the error-body read two ways. In *time*, by the same per-attempt
431    // deadline as the initial send — otherwise a slow error body on the
432    // pre-stream path could stall the attempt indefinitely, defeating the
433    // timeout guarantee. In *size*, by reading only a bounded prefix rather
434    // than `response.bytes()` (which buffers up to the client's `max_body_size`,
435    // megabytes by default) — the body only feeds a diagnostic, so a large or
436    // hostile error body cannot force an outsized allocation here.
437    let body_fut = read_error_body_prefix(response.into_body());
438    let bytes_result = match timeout {
439        Some(d) => match tokio::time::timeout(d, body_fut).await {
440            Ok(r) => r,
441            Err(_) => return OpenFailure::Retryable(TransportError::Timeout(d)),
442        },
443        None => body_fut.await,
444    };
445    let bytes = match bytes_result {
446        Ok(b) => b,
447        // A failed error-body read ends the stream rather than consuming a
448        // reconnect attempt: we no longer know what the peer said, so
449        // re-issuing would be guessing.
450        Err(e) => return OpenFailure::Fatal(TransportError::network(e)),
451    };
452    let body = String::from_utf8_lossy(&bytes).into_owned();
453    // A transient status (e.g. 503 during a rolling deploy) is
454    // reconnect-eligible, consistent with the pre-flight failure branch; other
455    // statuses are domain errors and bubble straight through.
456    OpenFailure::Retryable(map_http_error(status_code, body, retry_after))
457}
458
459/// One open attempt against an already-built request: send it and check the
460/// status.
461///
462/// Steps 1-3 of the streaming lifecycle, shared by [`send_streaming`] and
463/// [`open_streaming`]. Performs no retry of its own.
464///
465/// Takes the built `RequestBuilder` rather than the factory deliberately: an
466/// `async fn` holding a `&F` would put that reference in the returned future,
467/// which is `Send` only if `F: Sync` — a bound [`StreamRequestFactory`] does
468/// not require and should not have to.
469async fn attempt_open(
470    builder: RequestBuilder,
471    timeout: Option<Duration>,
472) -> Result<toolkit_http::HttpResponse, OpenFailure> {
473    let response = send_open_request(builder, timeout).await?;
474    if response.status().is_success() {
475        return Ok(response);
476    }
477    Err(open_status_failure(response, timeout).await)
478}
479
480/// A successfully opened streaming response, together with whatever
481/// framing-specific setup its body needs before it can be parsed.
482///
483/// An enum rather than a struct carrying an `Option<String>` boundary, so
484/// "multipart with no boundary" is not a representable state. The multipart arm
485/// is why this type exists at all: its boundary lives in the response's
486/// `Content-Type`, so a multipart open can still fail *after* a `200` — and
487/// resolving it here, at open time, is what makes that failure an `Err` from
488/// [`open_streaming`] rather than the returned stream's first item.
489enum OpenedResponse {
490    /// SSE needs no setup beyond the body itself.
491    ServerSentEvents(toolkit_http::HttpResponse),
492    /// `multipart/mixed`, with the boundary read from the response's
493    /// `Content-Type`.
494    MultipartMixed {
495        response: toolkit_http::HttpResponse,
496        boundary: String,
497    },
498}
499
500/// Perform the framing-specific setup a success response needs.
501///
502/// # Errors
503/// [`TransportError::Framing`] when a `multipart/mixed` response carries no
504/// `Content-Type`, or one from which no boundary can be read.
505fn open_response(
506    framing: StreamFraming,
507    response: toolkit_http::HttpResponse,
508) -> Result<OpenedResponse, TransportError> {
509    match framing {
510        StreamFraming::ServerSentEvents => Ok(OpenedResponse::ServerSentEvents(response)),
511        StreamFraming::MultipartMixed => {
512            let content_type = response
513                .headers()
514                .get(http::header::CONTENT_TYPE)
515                .and_then(|v| v.to_str().ok())
516                .ok_or_else(|| {
517                    TransportError::framing(
518                        StreamFraming::MultipartMixed,
519                        "success response carries no readable `Content-Type` header",
520                    )
521                })?;
522            let boundary = boundary_from_content_type(content_type)?;
523            Ok(OpenedResponse::MultipartMixed { response, boundary })
524        }
525    }
526}
527
528/// Owns everything that persists across open attempts: the request factory,
529/// the reconnect budget, and the `Last-Event-ID` cell the SSE parser advances.
530///
531/// Exists so the retry loop can be written once and shared by the eager and
532/// lazy entry points. Its methods take `&mut self` rather than `&F` — `&mut T`
533/// is `Send` when `T: Send`, so this keeps the futures `Send` without
534/// demanding `F: Sync`.
535struct StreamOpener<F> {
536    factory: F,
537    framing: StreamFraming,
538    reconnect: ReconnectConfig,
539    /// Deadline for the open handshake (connect, headers, error-body read),
540    /// applied per attempt. Distinct from `idle_timeout`, which bounds only the
541    /// item loop once the stream is live.
542    open_timeout: Option<Duration>,
543    idle_timeout: Option<Duration>,
544    last_id: LastEventId,
545    /// Reconnect attempts consumed so far. Shared by the open and the stream
546    /// so a burst of failures with no delivered item is capped as one budget
547    /// rather than one per phase. Reset by a healthy connection.
548    attempt: u32,
549    /// Reopens performed over the whole lifetime of this stream, never reset.
550    /// Bounds a peer that keeps resetting the burst budget from reopening
551    /// forever (#4740), against `reconnect.max_total_reopens`.
552    total_reopens: u32,
553}
554
555impl<F: StreamRequestFactory> StreamOpener<F> {
556    fn new(request: StreamRequest<F>) -> Self {
557        Self {
558            factory: request.factory,
559            framing: request.framing,
560            reconnect: request.reconnect,
561            open_timeout: request.open_timeout,
562            idle_timeout: request.idle_timeout,
563            last_id: LastEventId::empty(),
564            attempt: 0,
565            total_reopens: 0,
566        }
567    }
568
569    /// Open the stream, retrying transient failures against the budget.
570    // cancel-safe: the only carried state is the budget counters in `self`,
571    // which are monotonic, so a drop mid-attempt at worst counts an attempt
572    // that wasn't retried (conservative) — never a double-open or a lost item.
573    // The driver awaits it to completion rather than racing it under a timeout.
574    async fn open(&mut self) -> Result<OpenedResponse, TransportError> {
575        loop {
576            let snapshot = match self.framing {
577                // Re-read per attempt: a reconnect replays the most recently
578                // observed `id:` field, which the parser may have advanced
579                // since the previous open.
580                StreamFraming::ServerSentEvents => self.last_id.current(),
581                // `Last-Event-ID` is an SSE mechanism and `multipart/mixed`
582                // has no resume token of its own, so the factory is handed
583                // `None` on every attempt. Stated as a branch rather than left
584                // to the cell simply never being advanced, so the reason is
585                // visible at the one place it decides anything: resuming a
586                // multipart stream is the caller's own reopen loop, not the
587                // transport's.
588                StreamFraming::MultipartMixed => None,
589            };
590            // URL-build / serialization failure on the request side — not
591            // eligible for reconnect (config-shape error).
592            let built = self.factory.build(snapshot.as_deref());
593            let attempted = match built {
594                Ok(builder) => attempt_open(builder, self.open_timeout).await,
595                Err(e) => Err(OpenFailure::Fatal(e)),
596            };
597            match attempted {
598                // A framing-setup failure (a `200` whose `Content-Type` names
599                // no usable boundary) is not retried: it is a response-shape
600                // error that repeats identically, the same argument as the
601                // request-shape branch above. Returning it from here is also
602                // what makes it an `Err` from `open_streaming` rather than the
603                // stream's first item.
604                Ok(response) => return open_response(self.framing, response),
605                Err(OpenFailure::Fatal(e)) => return Err(e),
606                Err(OpenFailure::Retryable(err)) => {
607                    if !self.consume_attempt(&err).await {
608                        return Err(err);
609                    }
610                }
611            }
612        }
613    }
614
615    /// Consume one reconnect attempt for `err`, backing off before returning
616    /// `true`. Returns `false` when the budget is spent or the error class is
617    /// not retryable, meaning the caller must surface `err`.
618    // cancel-safe: the counter increments precede the backoff `sleep`, so a drop
619    // during the sleep leaves the budget consistently decremented (conservative)
620    // rather than in a half-updated state. No wire data flows through here.
621    async fn consume_attempt(&mut self, err: &TransportError) -> bool {
622        // Absolute lifetime ceiling, checked before the burst budget so it also
623        // stops a peer that keeps resetting that budget. It survives
624        // `reset_budget` (which only clears `attempt`), so it is the one bound a
625        // healthy-looking flapping peer cannot escape.
626        if self.total_reopens >= self.reconnect.max_total_reopens {
627            tracing::warn!(
628                total_reopens = self.total_reopens,
629                max_total_reopens = self.reconnect.max_total_reopens,
630                framing = ?self.framing,
631                error = %err,
632                "stream lifetime reopen cap reached; surfacing error",
633            );
634            return false;
635        }
636        if self.attempt < self.reconnect.max_attempts && err.is_transient() {
637            self.attempt += 1;
638            self.total_reopens += 1;
639            // A server-advised `Retry-After` (from a 429/503 open failure) wins
640            // over computed backoff, clamped to `max_delay` so a hostile or
641            // misconfigured peer cannot stall the reopen indefinitely — the same
642            // preference the unary retry loop applies in `retry::next_delay`.
643            let delay = match err.retry_after() {
644                Some(advised) => advised.min(self.reconnect.max_delay),
645                None => backoff_delay(&self.reconnect, self.attempt),
646            };
647            // The single choke point for every reconnect: an operator otherwise
648            // sees only the final error and nothing when a reopen succeeds.
649            tracing::warn!(
650                attempt = self.attempt,
651                max_attempts = self.reconnect.max_attempts,
652                delay_ms = u64::try_from(delay.as_millis()).unwrap_or(u64::MAX),
653                framing = ?self.framing,
654                error = %err,
655                "stream failed; reconnecting after backoff",
656            );
657            tokio::time::sleep(delay).await;
658            true
659        } else {
660            // A non-transient error, or the budget is spent: no more reopens.
661            if self.attempt >= self.reconnect.max_attempts && err.is_transient() {
662                tracing::warn!(
663                    attempt = self.attempt,
664                    max_attempts = self.reconnect.max_attempts,
665                    framing = ?self.framing,
666                    error = %err,
667                    "stream reconnect budget exhausted; surfacing error",
668                );
669            }
670            false
671        }
672    }
673
674    /// Reset the budget after a connection that delivered items.
675    fn reset_budget(&mut self) {
676        self.attempt = 0;
677    }
678}
679
680/// The framing parser driving one opened response body, behind the single
681/// surface [`drive`] needs.
682///
683/// A `dyn` decoder trait is not available here — decoding is generic in `T`, so
684/// the trait could not be object-safe — and the two framings genuinely differ
685/// in only three places, so an enum keeps each difference visible at the point
686/// it is decided rather than dispersing it behind a vtable.
687enum FramedItems<T> {
688    Sse(SseStream<T, BoxByteStream>),
689    Multipart(MultipartStream<T, BoxByteStream>),
690}
691
692impl<T> FramedItems<T>
693where
694    T: DeserializeOwned + 'static,
695{
696    /// Build the parser for an opened response.
697    ///
698    /// `last_id` is consumed **only** by the SSE arm: the cell is
699    /// SSE-parser-owned and multipart never reads or writes it.
700    fn new(opened: OpenedResponse, last_id: LastEventId) -> Self {
701        match opened {
702            OpenedResponse::ServerSentEvents(response) => {
703                // The parsers need `Unpin + 'static`; pinning on the stack with
704                // `pin_mut!` would borrow the byte stream for less than
705                // `'static`, so move ownership behind `Box::pin` and hand the
706                // boxed stream over.
707                let byte_stream: BoxByteStream =
708                    Box::pin(body_to_byte_stream(response.into_body()));
709                Self::Sse(parse_sse_stream_with_id::<T, _, _>(byte_stream, last_id))
710            }
711            OpenedResponse::MultipartMixed { response, boundary } => {
712                ::std::mem::drop(last_id);
713                let byte_stream: BoxByteStream =
714                    Box::pin(body_to_byte_stream(response.into_body()));
715                Self::Multipart(parse_multipart_stream::<T, _, _>(byte_stream, &boundary))
716            }
717        }
718    }
719
720    /// Wire-activity counter, so the idle deadline stays *idle* rather than
721    /// merely *quiet* under either framing.
722    fn activity_handle(&self) -> StreamActivity {
723        match self {
724            Self::Sse(s) => s.activity_handle(),
725            Self::Multipart(s) => s.activity_handle(),
726        }
727    }
728
729    // cancel-safe: the parser state (buffered wire bytes, partial frame) lives
730    // in `self`, not this future — `drive` drops and re-creates this future
731    // around its idle `timeout` on every quiet window, and resumes without
732    // losing bytes. Both arms delegate to a `Stream::next` that only reads into
733    // the stream's own buffer. This is the load-bearing one: if it regressed to
734    // holding partial state in the future, every idle elapse would drop bytes.
735    async fn next(&mut self) -> Option<Result<T, TransportError>> {
736        use futures_util::StreamExt;
737        match self {
738            Self::Sse(s) => s.next().await,
739            Self::Multipart(s) => s.next().await,
740        }
741    }
742
743    /// What a **graceful** end of the underlying byte stream means for this
744    /// framing. `None` is a clean end; `Some` ends the stream with that error,
745    /// which is transient and so reconnect-eligible.
746    ///
747    /// This is the one place the two framings disagree about success, and
748    /// getting it backwards is silent in both directions — every completed
749    /// multipart stream would become an error, or every truncated SSE stream a
750    /// success.
751    fn end_of_stream_error(&self) -> Option<TransportError> {
752        match self {
753            // SSE has no application-level terminator, so the transport must
754            // supply one: an `event: done` frame and a bare connection close
755            // both surface as an end of stream. Treat a close WITHOUT an
756            // explicit `done` as an anomaly rather than silently reporting
757            // success — otherwise a server restart / LB idle-timeout / rolling
758            // deploy that closes the connection mid-stream would look identical
759            // to a fully-delivered stream.
760            Self::Sse(s) => (!s.saw_done_event()).then(|| {
761                TransportError::framing(
762                    StreamFraming::ServerSentEvents,
763                    "SSE stream ended without a terminal `done` event",
764                )
765            }),
766            // A complete multipart body ends with the `--<boundary>--` close
767            // delimiter (RFC 2046). A graceful EOF that did NOT see it is a
768            // truncation — a proxy idle-timeout, an LB half-close, a rolling
769            // deploy closing the connection mid-body — so report it, mirroring
770            // the SSE arm (#4740). On the public path the caller has no other
771            // way to tell truncation from completion: `send_streaming` /
772            // `open_streaming` hand back a boxed stream that erases
773            // `MultipartStream::saw_close_delimiter`, and a generic item type
774            // carries no terminal marker of its own. An *aborted* body is a
775            // different thing and still arrives as a `Network` error item, not
776            // as an end of stream.
777            Self::Multipart(s) => (!s.saw_close_delimiter()).then(|| {
778                TransportError::framing(
779                    StreamFraming::MultipartMixed,
780                    "multipart body ended without a closing `--<boundary>--` delimiter",
781                )
782            }),
783        }
784    }
785}
786
787/// Parse one already-opened response body and yield its items.
788///
789/// Steps 4-5 of the streaming lifecycle. Ends after yielding at most one
790/// `Err`; a clean end yields nothing further. Reconnect is the caller's
791/// concern.
792fn drive<T>(
793    opened: OpenedResponse,
794    last_id: LastEventId,
795    idle_timeout: Option<Duration>,
796) -> impl Stream<Item = Result<T, TransportError>> + Send
797where
798    T: DeserializeOwned + Send + 'static,
799{
800    async_stream::stream! {
801        let mut inner = FramedItems::<T>::new(opened, last_id);
802        let activity = inner.activity_handle();
803        loop {
804            // Idle timeout is *idle*: keepalive comments (and any other wire
805            // chunk that dispatches no item) still count as activity, so a
806            // quiet-but-alive stream is not torn down. On elapse we only
807            // error if no chunk arrived while we waited.
808            let item = match idle_timeout {
809                Some(d) => loop {
810                    let before = activity.generation();
811                    match tokio::time::timeout(d, inner.next()).await {
812                        Ok(v) => break v,
813                        // Activity advanced since the wait started (e.g. a
814                        // keepalive comment) — loop again rather than
815                        // treating this as a genuine idle timeout. Falling
816                        // off this arm already re-enters the loop; an
817                        // explicit `continue` here is redundant.
818                        Err(_) if activity.generation() != before => {}
819                        Err(_) => {
820                            yield Err(TransportError::Timeout(d));
821                            return;
822                        }
823                    }
824                },
825                None => inner.next().await,
826            };
827            match item {
828                Some(Ok(v)) => yield Ok(v),
829                Some(Err(e)) => {
830                    yield Err(e);
831                    return;
832                }
833                None => {
834                    // The underlying byte stream ended with no error. Whether
835                    // that is success depends on the framing — see
836                    // `FramedItems::end_of_stream_error`.
837                    if let Some(e) = inner.end_of_stream_error() {
838                        yield Err(e);
839                    }
840                    return;
841                }
842            }
843        }
844    }
845}
846
847/// Drive an opened response to completion, re-opening on transient failures.
848///
849/// `first` is the already-opened response; subsequent attempts re-open through
850/// [`StreamOpener::open`].
851fn drive_with_reconnect<F, T>(
852    mut opener: StreamOpener<F>,
853    first: OpenedResponse,
854) -> impl Stream<Item = Result<T, TransportError>> + Send
855where
856    F: StreamRequestFactory,
857    T: DeserializeOwned + Send + 'static,
858{
859    use futures_util::StreamExt;
860
861    async_stream::try_stream! {
862        let mut pending = Some(first);
863        loop {
864            let response = match pending.take() {
865                Some(r) => r,
866                // Only reached on a reopen (`pending` is `Some` on the first
867                // iteration), so a success here is a recovered reconnect.
868                None => match opener.open().await {
869                    Ok(r) => {
870                        tracing::debug!(
871                            attempt = opener.attempt,
872                            framing = ?opener.framing,
873                            "stream reconnect succeeded",
874                        );
875                        r
876                    }
877                    Err(e) => {
878                        Err(e)?;
879                        return;
880                    }
881                },
882            };
883
884            // Measured from the moment the connection is live (its response is
885            // open) to when its byte stream ends, so a one-item-then-drop peer
886            // registers a near-zero uptime.
887            let connection_started = tokio::time::Instant::now();
888            let mut inner = Box::pin(
889                drive::<T>(response, opener.last_id.clone(), opener.idle_timeout),
890            );
891            let mut stream_err: Option<TransportError> = None;
892            // Whether this connection ever delivered an event. Necessary but not
893            // sufficient for "healthy" — see the reset gate below.
894            let mut delivered_an_event = false;
895            while let Some(item) = inner.next().await {
896                match item {
897                    Ok(v) => {
898                        delivered_an_event = true;
899                        yield v;
900                    }
901                    Err(e) => {
902                        stream_err = Some(e);
903                        break;
904                    }
905                }
906            }
907            let uptime = connection_started.elapsed();
908            // Drop the parser before re-opening: it owns the previous
909            // connection's body, and the next attempt gets a fresh one.
910            ::std::mem::drop(inner);
911
912            // A *healthy* connection resets the burst budget so `max_attempts`
913            // is a burst cap, not a lifetime cap: a long-lived subscription that
914            // survives N unrelated blips over days should not die on the N+1st.
915            // "Healthy" needs both a delivered item AND a minimum uptime —
916            // delivering one item then dropping immediately is the #4740 peer
917            // that would otherwise reset the budget forever and reopen at
918            // `base_delay` indefinitely, re-sending the auth token each time. A
919            // too-brief connection instead counts against the budget, and the
920            // absolute `max_total_reopens` cap (in `consume_attempt`) backstops
921            // a peer that games the uptime threshold.
922            if delivered_an_event && uptime >= opener.reconnect.min_healthy_uptime {
923                opener.reset_budget();
924            }
925
926            match stream_err {
927                // Stream ended cleanly, by whatever its framing calls clean.
928                None => return,
929                Some(e) => {
930                    if !opener.consume_attempt(&e).await {
931                        Err(e)?;
932                        return;
933                    }
934                    // Budget consumed and backoff applied — fall through to
935                    // the next iteration, which re-opens.
936                }
937            }
938        }
939    }
940}
941
942/// Open a stream **eagerly**: connect, check the response status, and perform
943/// the framing's own setup before returning, so an open-time failure is an
944/// `Err` from this call rather than the returned stream's first item.
945///
946/// This is the entry point for a contract method declared
947/// `#[streaming] async fn` — a stream whose open is a distinct, fallible
948/// operation. Open-time failures (a `404`, a `409` carrying a domain
949/// `Problem`, a `410`) reach the caller before any item exists, where its
950/// open-time error handling can act on them.
951///
952/// The request's reconnect policy governs the *open* as well as the stream:
953/// with [`ReconnectConfig::disabled`] (the [`StreamRequest::new`] default, and
954/// what generated code passes for a fallible open per D6) exactly one open
955/// attempt is made.
956///
957/// # Errors
958/// Returns [`TransportError`] when the request cannot be built, the connect
959/// fails or times out, the response status is not a success, or the framing's
960/// setup fails — for [`StreamFraming::MultipartMixed`] that last case is a
961/// `200` whose `Content-Type` names no usable boundary, which is why a
962/// multipart open can fail after a success status. Failures after a successful
963/// open arrive as items of the returned stream.
964///
965/// # Stability
966/// **Not settled surface** — see [`StreamRequest`].
967pub async fn open_streaming<F, T>(
968    request: StreamRequest<F>,
969) -> Result<Pin<Box<dyn Stream<Item = Result<T, TransportError>> + Send>>, TransportError>
970where
971    F: StreamRequestFactory,
972    T: DeserializeOwned + Send + 'static,
973{
974    let mut opener = StreamOpener::new(request);
975    let response = opener.open().await?;
976    Ok(Box::pin(drive_with_reconnect(opener, response)))
977}
978
979/// Send a streaming request and adapt the response into a typed stream, with
980/// the open deferred until the stream is first polled.
981///
982/// The returned stream yields `Result<T, TransportError>` items, one per SSE
983/// event or per `multipart/mixed` part. With `reconnect.max_attempts == 0` (the
984/// default), a transient transport failure ends the stream immediately. With a
985/// non-zero limit, the client re-issues the request up to `max_attempts` times,
986/// applying exponential backoff between attempts — replaying `Last-Event-ID`
987/// under SSE framing, and with no resume token under any other. A
988/// `multipart/mixed` reopen therefore replays the body from its first part,
989/// redelivering any items already yielded (at-least-once); see
990/// [`ClientConfig::stream_reconnect`](crate::runtime::config::ClientConfig::stream_reconnect).
991///
992/// The open is **lazy**: nothing is sent until the returned stream is first
993/// polled, so a connect failure, a non-success status or a framing-setup
994/// failure arrives as the stream's first item. That is the shape a
995/// `#[streaming] fn` method needs, since it has nowhere else to put an error.
996/// Use [`open_streaming`] when the open must be able to fail on its own.
997///
998/// # Stability
999/// The [`StreamRequest`] parameter is **not settled surface** — see
1000/// [`StreamRequest`]. This entry point took a positional argument list before
1001/// a framing selector existed.
1002pub fn send_streaming<F, T>(
1003    request: StreamRequest<F>,
1004) -> Pin<Box<dyn Stream<Item = Result<T, TransportError>> + Send>>
1005where
1006    F: StreamRequestFactory,
1007    T: DeserializeOwned + Send + 'static,
1008{
1009    use futures_util::StreamExt;
1010
1011    Box::pin(async_stream::try_stream! {
1012        // Deferred into the stream so this entry point stays lazy.
1013        let mut inner = match open_streaming::<F, T>(request).await {
1014            Ok(s) => s,
1015            Err(e) => {
1016                Err(e)?;
1017                return;
1018            }
1019        };
1020        while let Some(item) = inner.next().await {
1021            yield item?;
1022        }
1023    })
1024}
1025
1026/// Compute the (jittered) backoff delay for reconnect attempt #N (1-indexed).
1027/// Doubles the base delay each attempt, capped at `max_delay`, then multiplies
1028/// by a ±25% jitter factor — fleet-wide reconnect synchronization (many clients
1029/// reconnecting in lockstep after a shared upstream blip) is the real concern.
1030///
1031/// Pure so the caller can both log the chosen delay and sleep the same value —
1032/// the jitter is random, so it must be drawn exactly once.
1033fn backoff_delay(config: &ReconnectConfig, attempt: u32) -> Duration {
1034    use rand::RngExt;
1035    let exp = attempt.saturating_sub(1);
1036    let multiplier = 2u32.saturating_pow(exp);
1037    let base = config
1038        .base_delay
1039        .saturating_mul(multiplier)
1040        .min(config.max_delay);
1041    let jitter: f64 = rand::rng().random_range(0.75..=1.25);
1042    let secs = base.as_secs_f64() * jitter;
1043    if secs.is_finite() && secs >= 0.0 {
1044        Duration::from_secs_f64(secs).min(config.max_delay)
1045    } else {
1046        base
1047    }
1048}
1049
1050// `with_json_body` and the streaming path are exercised end-to-end (real
1051// serialized body observed by a real server) by the integration tests in
1052// `tests/rest_client_codegen.rs` (`unary_post_round_trip` et al.) — a local
1053// unit test here could only check "builds without panicking" without
1054// access to `toolkit_http::RequestBuilder`'s private fields, which is
1055// strictly weaker than the existing round-trip coverage.