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