Skip to main content

day_part_http/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-part-http: headless cross-platform HTTP(S), by default through native networking
5//! stack (docs/http.md). No UI; any Rust code can depend on this crate.
6//!
7//! [signal-setter]: https://docs.rs/day-reactive/latest/day_reactive/struct.Signal.html#method.setter
8//!
9//! ```no_run
10//! let resp = day_part_http::fetch(&day_part_http::Request::get("https://example.com"))?;
11//! println!("{} {} bytes", resp.status, resp.body.len());
12//! # Ok::<(), day_part_http::HttpError>(())
13//! ```
14//!
15//! Why native stacks instead of a Rust HTTP crate: the request inherits the system configuration
16//! (proxies + PAC, per-network VPN routing, Low Data Mode via [`Request::allow_constrained`],
17//! enterprise/MDM certificate stores), and the binary carries no TLS library of its own. macOS
18//! and iOS use `URLSession`, Android OkHttp through a Java bridge arm, Windows WinHTTP, Linux the
19//! system's libcurl (opened at run time), HarmonyOS the Network Kit through an ArkTS arm, and the
20//! web the browser's `fetch` and `WebSocket` through a JavaScript arm, where only the asynchronous
21//! entry points exist and the blocking calls return [`HttpError::Unsupported`]. [`tier`] reports
22//! whether a stack is present.
23//!
24//! **Two doors.** The functions at the crate root ([`fetch`], [`fetch_async`], [`fetch_future`],
25//! [`fetch_streamed`]) send one request with no state kept between requests. A [`Client`] adds
26//! the rest of a modern HTTP surface on the same stacks: bodies streamed in chunks with
27//! backpressure, uploads from files, streams and multipart forms, redirect and authentication
28//! callbacks, public-key pins and server trust decisions, client identities, cookies, caches,
29//! transfer metrics and WebSockets. [`capabilities`] reports what the platform offers.
30//!
31//! **Threading.** [`fetch`] blocks the calling thread; run it on your own thread, never the UI
32//! thread. [`fetch_async`]'s completion runs on the transport's own thread (`URLSession`'s delegate
33//! queue, OkHttp's reader pool, the libcurl driver, WinHTTP's callbacks, the HarmonyOS JS thread,
34//! or the browser's only thread); deliver results into the UI by capturing
35//! a [`day_reactive::Signal::setter`](https://docs.rs/day-reactive/latest/day_reactive/struct.Signal.html#method.setter)-style
36//! setter in the callback; setters hop to the UI thread
37//! themselves and silently no-op after disposal, so late completions are harmless (DESIGN §4.5):
38//!
39//! ```ignore
40//! let done = body_signal.setter();
41//! day_part_http::fetch_async(Request::get(url), move |result| {
42//!     if let Ok(resp) = result { done.set(Some(Arc::new(resp.body))); }
43//! });
44//! ```
45//!
46//! Or await it: [`fetch_future`] wraps the same completion as a `Future` whose drop cancels the
47//! request where the platform can (docs/http.md's cancel matrix); under `day::task` the
48//! continuation runs on the UI thread, so results are plain signal writes (docs/async.md).
49//!
50//! Every option is **best-effort per platform** (docs/http.md has the matrix):
51//! `allow_expensive`/`allow_constrained` are native on Apple and advisory elsewhere; HTTP 4xx/5xx
52//! are `Ok` responses (check [`Response::status`]), not errors.
53
54use std::borrow::Cow;
55use std::future::Future;
56use std::path::{Path, PathBuf};
57use std::sync::{Arc, Mutex};
58use std::time::Duration;
59
60mod client;
61#[cfg(all(feature = "reqwest", not(target_arch = "wasm32")))]
62mod reqwest_provider;
63mod session;
64pub mod simulation;
65mod statistics;
66mod validators;
67pub use session::{Provider, Session};
68pub use statistics::{Statistics, TransferStatistics};
69pub use validators::CacheValidators;
70
71#[cfg(not(target_arch = "wasm32"))]
72pub mod testing;
73
74pub use client::{
75    Body, Cache, CachePolicy, Capabilities, Challenge, ChallengeReply, Client, ClientBuilder,
76    Collecting, Connecting, Cookie, CookieJar, Cookies, Fetching, Form, Head, Hop, Identity,
77    InFlight, Message, Metrics, NextChunk, NextMessage, RedirectReply, Redirects, Scheme, Sending,
78    ServerTrust, Streaming, Trust, TrustReply, WebSocket, WsSender,
79};
80pub(crate) use client::{Payload, ProgressFn};
81
82/// The contract a backend implements (docs/http.md "Transports"). Apps reach for it to install
83/// a test double with [`ClientBuilder::transport`], or to route a client through their own stack.
84pub mod transport {
85    pub use crate::client::{
86        Answer, AuthQuestion, Completion, Event, Events, Prepared, PreparedBody, Question,
87        QuestionId, SharedReader, Socket, Transfer, Transport, TransportConfig, WsEvent, WsEvents,
88    };
89}
90
91/// An HTTP request method.
92#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93pub enum Method {
94    Get,
95    Post,
96    Put,
97    Delete,
98    Patch,
99    Head,
100    Options,
101    Propfind,
102    Proppatch,
103    Mkcol,
104    Copy,
105    Move,
106    Lock,
107    Unlock,
108    Report,
109}
110
111impl Method {
112    /// The RFC 9110 token (`"GET"`, …).
113    #[must_use]
114    pub fn as_str(self) -> &'static str {
115        match self {
116            Method::Get => "GET",
117            Method::Post => "POST",
118            Method::Put => "PUT",
119            Method::Delete => "DELETE",
120            Method::Patch => "PATCH",
121            Method::Head => "HEAD",
122            Method::Options => "OPTIONS",
123            Method::Propfind => "PROPFIND",
124            Method::Proppatch => "PROPPATCH",
125            Method::Mkcol => "MKCOL",
126            Method::Copy => "COPY",
127            Method::Move => "MOVE",
128            Method::Lock => "LOCK",
129            Method::Unlock => "UNLOCK",
130            Method::Report => "REPORT",
131        }
132    }
133
134    /// The method a token names, ASCII case-insensitive.
135    #[must_use]
136    pub fn parse(token: &str) -> Option<Method> {
137        [
138            Method::Get,
139            Method::Post,
140            Method::Put,
141            Method::Delete,
142            Method::Patch,
143            Method::Head,
144            Method::Options,
145            Method::Propfind,
146            Method::Proppatch,
147            Method::Mkcol,
148            Method::Copy,
149            Method::Move,
150            Method::Lock,
151            Method::Unlock,
152            Method::Report,
153        ]
154        .into_iter()
155        .find(|m| m.as_str().eq_ignore_ascii_case(token))
156    }
157}
158
159/// A request under construction. Build with [`Request::get`] (and friends), then [`fetch`] or a
160/// [`Client`].
161#[derive(Clone, Debug)]
162#[must_use]
163pub struct Request {
164    pub(crate) method: Method,
165    pub(crate) url: String,
166    pub(crate) headers: Vec<(String, String)>,
167    pub(crate) payload: Payload,
168    pub(crate) timeout: Option<Duration>,
169    pub(crate) timeout_total: Option<Duration>,
170    pub(crate) allow_expensive: bool,
171    pub(crate) allow_constrained: bool,
172    pub(crate) cache: CachePolicy,
173    pub(crate) priority: Option<f32>,
174    pub(crate) protocols: Vec<String>,
175    pub(crate) upload_progress: Option<ProgressFn>,
176}
177
178impl Request {
179    /// A request with this method.
180    pub fn new(method: Method, url: impl Into<String>) -> Request {
181        Request {
182            method,
183            url: url.into(),
184            headers: Vec::new(),
185            payload: Payload::Empty,
186            timeout: None,
187            timeout_total: None,
188            allow_expensive: true,
189            allow_constrained: true,
190            cache: CachePolicy::Default,
191            priority: None,
192            protocols: Vec::new(),
193            upload_progress: None,
194        }
195    }
196
197    pub fn get(url: impl Into<String>) -> Request {
198        Self::new(Method::Get, url)
199    }
200    pub fn post(url: impl Into<String>, body: Vec<u8>) -> Request {
201        Self::new(Method::Post, url).body(body)
202    }
203    pub fn put(url: impl Into<String>, body: Vec<u8>) -> Request {
204        Self::new(Method::Put, url).body(body)
205    }
206    pub fn delete(url: impl Into<String>) -> Request {
207        Self::new(Method::Delete, url)
208    }
209    pub fn patch(url: impl Into<String>, body: Vec<u8>) -> Request {
210        Self::new(Method::Patch, url).body(body)
211    }
212    pub fn head(url: impl Into<String>) -> Request {
213        Self::new(Method::Head, url)
214    }
215
216    /// The method.
217    #[must_use]
218    pub fn method(&self) -> Method {
219        self.method
220    }
221
222    /// The URL, as given.
223    #[must_use]
224    pub fn url(&self) -> &str {
225        &self.url
226    }
227
228    /// The request headers, in the order they were added.
229    #[must_use]
230    pub fn headers(&self) -> &[(String, String)] {
231        &self.headers
232    }
233
234    /// Append a request header (duplicates allowed, sent in order).
235    pub fn header(mut self, name: &str, value: &str) -> Self {
236        self.headers.push((name.to_string(), value.to_string()));
237        self
238    }
239
240    /// `Authorization: Bearer <token>`, sent up front.
241    pub fn bearer(self, token: &str) -> Self {
242        self.header("Authorization", &format!("Bearer {token}"))
243    }
244
245    /// `Authorization: Basic …`, sent up front instead of waiting for a challenge.
246    pub fn basic_auth(self, user: &str, password: &str) -> Self {
247        let value = client::basic_authorization(user, password);
248        self.header("Authorization", &value)
249    }
250
251    /// The request body (also settable via the [`Request::post`]/[`Request::put`]/[`Request::patch`]
252    /// constructors).
253    pub fn body(mut self, bytes: Vec<u8>) -> Self {
254        self.payload = Payload::Bytes(Arc::new(bytes));
255        self
256    }
257
258    /// Send a file as the body, read while it is sent. A [`Client`] only.
259    pub fn body_file(mut self, path: impl Into<PathBuf>) -> Self {
260        self.payload = Payload::File(path.into());
261        self
262    }
263
264    /// Send what `reader` yields as the body, read while it is sent. `len` becomes
265    /// `Content-Length`; without it the body goes out chunked where the platform allows. A
266    /// stream can be sent once, so a redirect or challenge that needs the body again fails the
267    /// request. A [`Client`] only.
268    pub fn body_stream(
269        mut self,
270        reader: impl std::io::Read + Send + 'static,
271        len: Option<u64>,
272    ) -> Self {
273        self.payload = Payload::Stream(transport::SharedReader::new(reader), len);
274        self
275    }
276
277    /// Send a `multipart/form-data` body; its `Content-Type` is set unless the request sets one.
278    /// A [`Client`] only.
279    pub fn form(mut self, form: Form) -> Self {
280        self.payload = Payload::Form(form);
281        self
282    }
283
284    /// How long the request may sit without progress. Default **30 s**. This bounds connecting,
285    /// awaiting the response head, and idle gaps in the body, not the total transfer time, so a
286    /// long download that keeps moving is never cut off (per-platform mapping: docs/http.md).
287    pub fn timeout(mut self, d: Duration) -> Self {
288        self.timeout = Some(d);
289        self
290    }
291
292    /// How long the whole request may take, redirects, challenges and body included. A
293    /// [`Client`] only; it overrides [`ClientBuilder::timeout_total`].
294    pub fn timeout_total(mut self, d: Duration) -> Self {
295        self.timeout_total = Some(d);
296        self
297    }
298
299    /// Whether the request may use "expensive" paths (cellular / personal hotspot). Default
300    /// `true`. Native on Apple (`allowsExpensiveNetworkAccess`); advisory elsewhere; combine
301    /// with `day_part_connectivity::status().expensive` for app-side policy.
302    pub fn allow_expensive(mut self, allowed: bool) -> Self {
303        self.allow_expensive = allowed;
304        self
305    }
306
307    /// Whether the request may run under Low Data Mode. Default `true`. Native on Apple
308    /// (`allowsConstrainedNetworkAccess`); advisory elsewhere.
309    pub fn allow_constrained(mut self, allowed: bool) -> Self {
310        self.allow_constrained = allowed;
311        self
312    }
313
314    /// How the request may use the client's cache. Default [`CachePolicy::Default`].
315    pub fn cache(mut self, policy: CachePolicy) -> Self {
316        self.cache = policy;
317        self
318    }
319
320    /// A scheduling hint from 0.0 (lowest) to 1.0 (highest), where the platform takes one.
321    pub fn priority(mut self, priority: f32) -> Self {
322        self.priority = Some(priority.clamp(0.0, 1.0));
323        self
324    }
325
326    /// WebSocket subprotocols to offer, in preference order.
327    pub fn protocols<S: Into<String>>(mut self, protocols: impl IntoIterator<Item = S>) -> Self {
328        self.protocols = protocols.into_iter().map(Into::into).collect();
329        self
330    }
331
332    /// Observe the body going out: `(bytes sent, total)`, on the thread the platform reports on.
333    /// Needs [`Capabilities::upload_progress`]. A [`Client`] only.
334    pub fn upload_progress(
335        mut self,
336        observe: impl Fn(u64, Option<u64>) + Send + Sync + 'static,
337    ) -> Self {
338        self.upload_progress = Some(ProgressFn(Arc::new(observe)));
339        self
340    }
341}
342
343/// A complete HTTP response, body buffered in memory. For large downloads use [`fetch_to_file`],
344/// which streams to disk instead, or read a [`Client`]'s [`Body`] in chunks.
345#[derive(Clone, Debug)]
346pub struct Response {
347    /// The HTTP status code. **4xx/5xx are delivered here, not as [`HttpError`]**; only
348    /// transport-level failures error.
349    pub status: u16,
350    /// Response headers in arrival order (duplicates preserved).
351    pub headers: Vec<(String, String)>,
352    pub body: Vec<u8>,
353    /// The URL that answered, after redirects; empty where the platform does not report it.
354    pub url: String,
355    /// Transfer metrics, where the platform reports them.
356    pub metrics: Option<Metrics>,
357}
358
359impl Response {
360    /// A response from its parts, with no URL and no metrics.
361    #[must_use]
362    pub fn new(status: u16, headers: Vec<(String, String)>, body: Vec<u8>) -> Response {
363        Response {
364            status,
365            headers,
366            body,
367            url: String::new(),
368            metrics: None,
369        }
370    }
371
372    pub(crate) fn assemble(head: Head, body: Vec<u8>, metrics: Option<Metrics>) -> Response {
373        Response {
374            status: head.status,
375            headers: head.headers,
376            body,
377            url: head.url,
378            metrics,
379        }
380    }
381
382    /// The body as (lossily-decoded) UTF-8 text.
383    #[must_use]
384    pub fn text(&self) -> Cow<'_, str> {
385        String::from_utf8_lossy(&self.body)
386    }
387
388    /// The first header with this name (ASCII case-insensitive).
389    #[must_use]
390    pub fn header(&self, name: &str) -> Option<&str> {
391        self.headers
392            .iter()
393            .find(|(k, _)| k.eq_ignore_ascii_case(name))
394            .map(|(_, v)| v.as_str())
395    }
396}
397
398/// The result of a [`fetch_to_file`] download (the body went to disk, not memory).
399#[derive(Clone, Debug)]
400pub struct Download {
401    pub status: u16,
402    pub headers: Vec<(String, String)>,
403    pub bytes_written: u64,
404}
405
406/// A transport-level failure. HTTP error statuses (4xx/5xx) are not here; they arrive as
407/// [`Response::status`]. The portable core maps from each platform's taxonomy (docs/http.md).
408#[non_exhaustive]
409#[derive(Clone, Debug, PartialEq, Eq)]
410pub enum HttpError {
411    /// The URL failed to parse (or uses an unsupported scheme).
412    BadUrl(String),
413    /// The request exceeded [`Request::timeout`] or its total limit.
414    Timeout,
415    /// Host name resolution failed.
416    Dns,
417    /// The connection could not be established (refused, unreachable, reset mid-handshake).
418    Connect,
419    /// TLS handshake / certificate failure, including a server a pin or a trust handler refused.
420    Tls(String),
421    /// Everything else the platform reported (message passed through).
422    Io(String),
423    /// The request was cancelled: its [`FetchFuture`] dropped, or a platform-side cancel.
424    Cancelled,
425    /// No HTTP capability on this platform ([`Tier::Unavailable`]), or an entry point or option
426    /// that cannot exist on it (the blocking calls on the web's single thread, see docs/http.md).
427    Unsupported,
428    /// More redirects than [`Redirects::Follow`] allows.
429    TooManyRedirects,
430    /// A status the caller could not accept, such as a download manager's unexpected `416`.
431    Status(u16),
432    /// The response exceeded the caller's explicit buffered-body limit.
433    BodyTooLarge { limit: usize },
434}
435
436impl std::fmt::Display for HttpError {
437    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
438        match self {
439            HttpError::BadUrl(u) => write!(f, "bad url: {u}"),
440            HttpError::Timeout => write!(f, "request timed out"),
441            HttpError::Dns => write!(f, "host name resolution failed"),
442            HttpError::Connect => write!(f, "connection failed"),
443            HttpError::Tls(m) => write!(f, "TLS failure: {m}"),
444            HttpError::Io(m) => write!(f, "{m}"),
445            HttpError::Cancelled => write!(f, "request cancelled"),
446            HttpError::Unsupported => write!(f, "not supported on this platform"),
447            HttpError::TooManyRedirects => write!(f, "too many redirects"),
448            HttpError::Status(s) => write!(f, "unexpected status {s}"),
449            HttpError::BodyTooLarge { limit } => write!(f, "response exceeds {limit} bytes"),
450        }
451    }
452}
453
454impl std::error::Error for HttpError {}
455
456/// How requests are realized on the compiled target.
457#[derive(Clone, Copy, Debug, PartialEq, Eq)]
458pub enum Tier {
459    /// The platform's own networking stack (`URLSession`, OkHttp, WinHTTP, libcurl, the Network
460    /// Kit, the browser's fetch): system proxy + PAC, VPN routing, platform TLS + certificate
461    /// stores. On the web this tier is async-only; the blocking entry points return
462    /// [`HttpError::Unsupported`] (docs/http.md).
463    NativeStack,
464    /// No HTTP capability (no libcurl on Linux, a HarmonyOS build without its staged arm, an
465    /// unknown target); every call returns [`HttpError::Unsupported`].
466    Unavailable,
467}
468
469impl Tier {
470    /// A short display label (`"native"` / `"unavailable"`).
471    #[must_use]
472    pub fn label(self) -> &'static str {
473        match self {
474            Tier::NativeStack => "native",
475            Tier::Unavailable => "unavailable",
476        }
477    }
478}
479
480/// How this target realizes requests (fixed at compile time).
481#[must_use]
482pub fn tier() -> Tier {
483    // libcurl loads at run time, so Linux knows its tier only then.
484    #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
485    {
486        imp::tier()
487    }
488    #[cfg(not(all(target_os = "linux", not(target_env = "ohos"))))]
489    {
490        imp::TIER
491    }
492}
493
494/// What a [`Client`] on this platform can do.
495#[must_use]
496pub fn capabilities() -> Capabilities {
497    platform_capabilities()
498}
499
500/// The platform transport's capabilities, before any client exists.
501pub(crate) fn platform_capabilities() -> Capabilities {
502    imp::capabilities()
503}
504
505/// The platform transport, configured for one client.
506pub(crate) fn platform_transport(
507    config: &transport::TransportConfig,
508) -> Arc<dyn transport::Transport> {
509    imp::transport(config)
510}
511
512/// The client the crate-root functions share: no cookies and no cache, so each call stands alone
513/// as it always has.
514fn stateless() -> &'static Client {
515    static CLIENT: std::sync::OnceLock<Client> = std::sync::OnceLock::new();
516    CLIENT.get_or_init(|| {
517        Client::builder()
518            .cookies(Cookies::Off)
519            .cache(Cache::Off)
520            .build()
521    })
522}
523
524/// Fetch through the shared stateless client with a strict limit on buffered response bytes.
525/// Checks both Content-Length and streamed chunks; exceeding the limit cancels the transfer.
526/// The returned future also cancels on drop. Available on every backend, including the web.
527///
528/// # Errors
529///
530/// [`HttpError::BodyTooLarge`] when the advertised or received body exceeds `max_bytes`, and
531/// otherwise the [`HttpError`] the request or its body stream fails with.
532pub async fn fetch_limited_future(req: Request, max_bytes: usize) -> Result<Response, HttpError> {
533    stateless().fetch_limited_future(req, max_bytes).await
534}
535
536/// Shared-client bounded download with progress on the future's polling thread.
537/// See [`Client::fetch_limited_with_progress_future`].
538///
539/// # Errors
540///
541/// [`HttpError::BodyTooLarge`] when the advertised or received body exceeds `max_bytes`, and
542/// otherwise the [`HttpError`] the request or its body stream fails with.
543pub async fn fetch_limited_with_progress_future(
544    req: Request,
545    max_bytes: usize,
546    progress: impl FnMut(u64, Option<u64>),
547) -> Result<Response, HttpError> {
548    stateless()
549        .fetch_limited_with_progress_future(req, max_bytes, progress)
550        .await
551}
552
553/// Stream `req` through `client` into `sink`, waiting on this thread.
554#[cfg(not(target_arch = "wasm32"))]
555fn streamed_through(
556    client: &Client,
557    req: &Request,
558    sink: &mut dyn StreamSink,
559) -> Result<Download, HttpError> {
560    // On HarmonyOS the JS thread is the loop that delivers the answer: waiting there would starve it.
561    #[cfg(all(target_os = "linux", target_env = "ohos"))]
562    if day_bridge::arkts::on_js_thread() {
563        return Err(HttpError::Unsupported);
564    }
565    let streaming = client::wait(client.send_future(req.clone()))?;
566    let (status, headers) = (streaming.status(), streaming.headers().to_vec());
567    if !sink.head(status, &headers) {
568        return Err(HttpError::Io("aborted".into()));
569    }
570    let mut body = streaming.into_body();
571    let mut bytes_written = 0u64;
572    while let Some(chunk) = body.next_blocking() {
573        let chunk = chunk?;
574        sink.chunk(&chunk)?;
575        bytes_written += chunk.len() as u64;
576    }
577    Ok(Download {
578        status,
579        headers,
580        bytes_written,
581    })
582}
583
584/// Perform the request, blocking the calling thread until the response (or [`Request::timeout`]).
585/// Run it on your own thread; calling this on the UI thread stalls the app (docs/http.md).
586/// On the web (web-dom) blocking is impossible on the single browser thread: this returns
587/// [`HttpError::Unsupported`] there; use [`fetch_async`] or [`fetch_future`].
588///
589/// # Errors
590///
591/// The [`HttpError`] the request fails with, or [`HttpError::Unsupported`] where the calling
592/// thread cannot block: the web, and the JS thread on HarmonyOS.
593pub fn fetch(req: &Request) -> Result<Response, HttpError> {
594    // The browser has one thread and no blocking waits.
595    #[cfg(target_arch = "wasm32")]
596    {
597        let _ = req;
598        Err(HttpError::Unsupported)
599    }
600    #[cfg(not(target_arch = "wasm32"))]
601    {
602        // On HarmonyOS the JS thread is the loop that delivers the answer: waiting there would
603        // starve it.
604        #[cfg(all(target_os = "linux", target_env = "ohos"))]
605        if day_bridge::arkts::on_js_thread() {
606            return Err(HttpError::Unsupported);
607        }
608        client::wait(stateless().fetch_future(req.clone()))
609    }
610}
611
612/// Perform the request without blocking; `on_done` runs on an unspecified background thread
613/// (capture a reactive `Setter` to deliver into UI state; see the crate docs). On the web
614/// the completion runs on the browser thread, the only one, which the Setter idiom absorbs
615/// unchanged.
616pub fn fetch_async(
617    req: Request,
618    on_done: impl FnOnce(Result<Response, HttpError>) + Send + 'static,
619) {
620    drop(start_cancellable(req, Box::new(on_done)));
621}
622
623/// Download the response body straight to `dest` (create/truncate), never buffering it in memory.
624/// Blocking, like [`fetch`]. On error a partial `dest` is removed best-effort; atomicity is not
625/// promised.
626///
627/// # Errors
628///
629/// [`HttpError::Io`] when `dest` cannot be created or written, [`HttpError::Unsupported`] on the
630/// web, and otherwise the [`HttpError`] the request fails with.
631pub fn fetch_to_file(req: &Request, dest: &Path) -> Result<Download, HttpError> {
632    // The browser has one thread and no filesystem for this.
633    #[cfg(target_arch = "wasm32")]
634    let out = {
635        let _ = req;
636        Err(HttpError::Unsupported)
637    };
638    #[cfg(not(target_arch = "wasm32"))]
639    let out = {
640        struct FileSink(std::fs::File);
641        impl StreamSink for FileSink {
642            fn chunk(&mut self, data: &[u8]) -> Result<(), HttpError> {
643                use std::io::Write;
644                self.0
645                    .write_all(data)
646                    .map_err(|e| HttpError::Io(e.to_string()))
647            }
648        }
649        std::fs::File::create(dest)
650            .map_err(|e| HttpError::Io(e.to_string()))
651            .and_then(|file| streamed_through(stateless(), req, &mut FileSink(file)))
652    };
653    if out.is_err() {
654        let _ = std::fs::remove_file(dest);
655    }
656    out
657}
658
659/// Start the request immediately and await the result. The future is the cancellation grip:
660/// **dropping it cancels the request** where the platform supports it (docs/http.md's cancel
661/// matrix): Apple `NSURLSessionTask.cancel`, Android OkHttp `Call.cancel`, the web the
662/// fetch's `AbortController`; Windows closes the WinHTTP
663/// request handle.
664/// A cancelled request that still completes resolves nothing; a platform-side cancel that beats
665/// the drop surfaces as [`HttpError::Cancelled`].
666///
667/// Await it inside `day::task` (or any executor; the future is `Send`-agnostic plumbing over
668/// [`fetch_async`]'s completion): `day::task(async move { let r = fetch_future(req).await; … })`.
669#[must_use]
670pub fn fetch_future(req: Request) -> FetchFuture {
671    let shared = Arc::new(Mutex::new(FutureState {
672        result: None,
673        waker: None,
674        cancelled: false,
675    }));
676    let deliver = shared.clone();
677    let cancel = start_cancellable(
678        req,
679        Box::new(move |result| deliver_future(&deliver, result)),
680    );
681    FetchFuture {
682        shared,
683        cancel: Some(cancel),
684        done: false,
685    }
686}
687
688/// Shared state between a [`FetchFuture`] and its completion callback.
689///
690/// Locking protocol (the mutex is a leaf lock; no platform or user code runs under it):
691/// - `poll` checks `result` and stores the waker under one lock acquisition, closing the
692///   lost-wakeup race (a completion between a check and a separate store would be missed).
693/// - the completion stores `result`, takes the waker, unlocks, then wakes; an inline waker
694///   (tests) re-polls synchronously, which re-takes the lock.
695/// - `Drop` sets `cancelled`, clears the waker, unlocks, then runs the platform cancel, because
696///   Apple's `task.cancel()` can schedule the completion synchronously on the delegate queue,
697///   which takes this lock. Nobody wakes on cancel: Drop is terminal (the future can never be
698///   polled again); a late completion finds no waker and its stored result is never read.
699struct FutureState {
700    result: Option<Result<Response, HttpError>>,
701    waker: Option<std::task::Waker>,
702    cancelled: bool,
703}
704
705/// An in-flight [`fetch_future`] request; dropping it cancels (see the cancel matrix).
706pub struct FetchFuture {
707    shared: Arc<Mutex<FutureState>>,
708    cancel: Option<Box<dyn FnOnce() + Send>>,
709    done: bool,
710}
711
712/// Lock, riding out poisoning: a panic while holding the lock leaves plain data (no broken
713/// invariants), so the poisoned value is still the truth.
714fn lock(m: &Mutex<FutureState>) -> std::sync::MutexGuard<'_, FutureState> {
715    match m.lock() {
716        Ok(g) => g,
717        Err(poisoned) => poisoned.into_inner(),
718    }
719}
720
721impl Future for FetchFuture {
722    type Output = Result<Response, HttpError>;
723
724    fn poll(
725        mut self: std::pin::Pin<&mut Self>,
726        cx: &mut std::task::Context<'_>,
727    ) -> std::task::Poll<Self::Output> {
728        let mut st = lock(&self.shared);
729        if let Some(r) = st.result.take() {
730            drop(st);
731            self.done = true;
732            return std::task::Poll::Ready(r);
733        }
734        st.waker = Some(cx.waker().clone());
735        std::task::Poll::Pending
736    }
737}
738
739impl Drop for FetchFuture {
740    fn drop(&mut self) {
741        if self.done {
742            return;
743        }
744        {
745            let mut st = lock(&self.shared);
746            st.cancelled = true;
747            st.waker = None;
748        }
749        if let Some(cancel) = self.cancel.take() {
750            cancel();
751        }
752    }
753}
754
755/// Store a completion result and wake the future (see [`FutureState`]'s locking protocol).
756fn deliver_future(shared: &Arc<Mutex<FutureState>>, result: Result<Response, HttpError>) {
757    let waker = {
758        let mut st = lock(shared);
759        if st.cancelled {
760            return;
761        }
762        st.result = Some(result);
763        st.waker.take()
764    };
765    if let Some(w) = waker {
766        w.wake();
767    }
768}
769
770type Completion = Box<dyn FnOnce(Result<Response, HttpError>) + Send>;
771type CancelFn = Box<dyn FnOnce() + Send>;
772
773/// Start the request through the shared stateless client; returns the closure that cancels it. The
774/// completion runs on the thread the platform reports on.
775fn start_cancellable(req: Request, on_done: Completion) -> CancelFn {
776    stateless().fetch_cancellable(req, on_done)
777}
778
779/// [`fetch_to_file`] without blocking; `on_done` runs on an unspecified background thread.
780pub fn fetch_to_file_async(
781    req: Request,
782    dest: PathBuf,
783    on_done: impl FnOnce(Result<Download, HttpError>) + Send + 'static,
784) {
785    #[cfg(target_arch = "wasm32")]
786    {
787        // No filesystem in the browser sandbox: the Unsupported answer is immediate, so
788        // complete inline (wasm32 has no threads to defer to).
789        on_done(fetch_to_file(&req, &dest));
790    }
791    #[cfg(not(target_arch = "wasm32"))]
792    std::thread::spawn(move || on_done(fetch_to_file(&req, &dest)));
793}
794
795/// Receives a streamed response: the head first, then each body chunk as it arrives. Implement
796/// this for progress reporting, cancellation, incremental hashing, or anything that must observe a
797/// large body without buffering it (an app store streaming an APK to disk, docs/http.md).
798pub trait StreamSink {
799    /// The status + headers, before any body. Return `false` to abort the transfer (e.g. an
800    /// unexpected status for a `Range` resume); [`fetch_streamed`] then returns
801    /// [`HttpError::Io`]`("aborted")`.
802    fn head(&mut self, _status: u16, _headers: &[(String, String)]) -> bool {
803        true
804    }
805    /// One body chunk, in arrival order. Returning `Err` aborts the transfer and becomes
806    /// [`fetch_streamed`]'s result (return `Io("cancelled")` for user cancellation).
807    ///
808    /// # Errors
809    ///
810    /// Whatever [`HttpError`] the sink chooses to stop the transfer with.
811    fn chunk(&mut self, data: &[u8]) -> Result<(), HttpError>;
812}
813
814/// Perform the request, streaming the body into `sink` chunk by chunk; nothing is buffered
815/// beyond one chunk. Blocking, like [`fetch`]. `bytes_written` counts the bytes handed to the
816/// sink.
817///
818/// # Errors
819///
820/// The [`HttpError`] the request fails with, the error `sink` returned from
821/// [`StreamSink::chunk`], [`HttpError::Io`]`("aborted")` when [`StreamSink::head`] returned
822/// `false`, or [`HttpError::Unsupported`] where the calling thread cannot block.
823pub fn fetch_streamed(req: &Request, sink: &mut dyn StreamSink) -> Result<Download, HttpError> {
824    // The browser has one thread and no blocking waits.
825    #[cfg(target_arch = "wasm32")]
826    {
827        let _ = (req, sink);
828        Err(HttpError::Unsupported)
829    }
830    #[cfg(not(target_arch = "wasm32"))]
831    {
832        streamed_through(stateless(), req, sink)
833    }
834}
835
836// ---------------------------------------------------------------------------
837// Per-OS implementations. Each exposes `TIER` (Linux: `tier()`), `capabilities()` and
838// `transport()`, the platform transport beneath every `Client`.
839// ---------------------------------------------------------------------------
840
841// The bridged arms (docs/bridge.md "Streams"): Android, HarmonyOS and the web. The declarations and
842// their fallback compile everywhere; only those targets reach an arm.
843mod bridge;
844
845// macOS + iOS share one NSURLSession impl.
846#[cfg(any(target_os = "macos", target_os = "ios"))]
847#[path = "apple.rs"]
848mod imp;
849
850#[cfg(target_os = "windows")]
851#[path = "windows.rs"]
852mod imp;
853
854// Desktop Linux: the system's libcurl, loaded at run time.
855#[cfg(all(target_os = "linux", not(target_env = "ohos")))]
856#[path = "linux.rs"]
857mod imp;
858
859// The same libcurl transport, tested on macOS against the system's libcurl.
860#[cfg(all(test, target_os = "macos"))]
861#[path = "linux.rs"]
862#[allow(dead_code)]
863mod curl;
864
865// Android, HarmonyOS and the web: the bridged arms over one frame protocol (src/bridge.rs).
866#[cfg(any(
867    target_os = "android",
868    all(target_os = "linux", target_env = "ohos"),
869    target_arch = "wasm32"
870))]
871#[path = "bridged.rs"]
872mod imp;
873
874// Any other platform: no HTTP capability.
875#[cfg(not(any(
876    target_os = "macos",
877    target_os = "ios",
878    target_os = "windows",
879    target_os = "linux",
880    target_os = "android",
881    target_arch = "wasm32"
882)))]
883mod imp {
884    use std::sync::Arc;
885
886    use super::{HttpError, Tier};
887    use crate::client::{
888        Answer, Capabilities, Event, Events, Prepared, QuestionId, Transfer, Transport,
889        TransportConfig,
890    };
891
892    pub const TIER: Tier = Tier::Unavailable;
893
894    pub(crate) fn capabilities() -> Capabilities {
895        Capabilities::default()
896    }
897
898    pub(crate) fn transport(_config: &TransportConfig) -> Arc<dyn Transport> {
899        Arc::new(Unavailable)
900    }
901
902    /// Every exchange fails with `Unsupported`.
903    struct Unavailable;
904
905    impl Transport for Unavailable {
906        fn capabilities(&self) -> Capabilities {
907            capabilities()
908        }
909
910        fn start(&self, _request: Prepared, events: Events) -> Arc<dyn Transfer> {
911            events(Event::Failed(HttpError::Unsupported));
912            Arc::new(Unavailable)
913        }
914    }
915
916    impl Transfer for Unavailable {
917        fn demand(&self, _chunks: u32) {}
918        fn answer(&self, _id: QuestionId, _answer: Answer) {}
919        fn cancel(&self) {}
920    }
921}