1
//! Simple HTTP client module for downloading resources (language packs, etc.)
2
//!
3
//! Uses ureq for simple, blocking HTTP requests. Designed to be exposed via C API.
4

            
5
use alloc::{format, string::String, vec::Vec};
6
use core::fmt;
7

            
8
use azul_css::{
9
    impl_option, impl_option_inner, impl_vec, impl_vec_clone, impl_vec_debug, impl_vec_mut,
10
    impl_vec_partialeq, AzString, U8Vec,
11
};
12

            
13
// ============================================================================
14
// Error types (C-compatible, single field per variant)
15
// ============================================================================
16

            
17
/// HTTP status error (4xx, 5xx responses)
18
#[derive(Debug, Clone, PartialEq, Eq)]
19
#[repr(C)]
20
pub struct HttpStatusError {
21
    /// HTTP status code
22
    pub status_code: u16,
23
    /// Status message
24
    pub message: AzString,
25
}
26

            
27
/// Response too large error
28
#[derive(Copy, Debug, Clone, PartialEq, Eq)]
29
#[repr(C)]
30
pub struct HttpResponseTooLargeError {
31
    /// Maximum allowed size in bytes
32
    pub max_size: u64,
33
    /// Actual size in bytes
34
    pub actual_size: u64,
35
}
36

            
37
/// HTTP error types (C-compatible)
38
#[derive(Debug, Clone, PartialEq, Eq)]
39
#[repr(C, u8)]
40
pub enum HttpError {
41
    /// Invalid URL format
42
    InvalidUrl(AzString),
43
    /// Connection failed
44
    ConnectionFailed(AzString),
45
    /// Request timed out
46
    Timeout,
47
    /// TLS/SSL error
48
    TlsError(AzString),
49
    /// HTTP error response (4xx, 5xx)
50
    HttpStatus(HttpStatusError),
51
    /// I/O error during request
52
    IoError(AzString),
53
    /// Response body too large
54
    ResponseTooLarge(HttpResponseTooLargeError),
55
    /// Other error
56
    Other(AzString),
57
}
58

            
59
impl HttpError {
60
    #[must_use]
61
11
    pub const fn invalid_url(url: AzString) -> Self {
62
11
        Self::InvalidUrl(url)
63
11
    }
64

            
65
    #[must_use]
66
6
    pub const fn connection_failed(msg: AzString) -> Self {
67
6
        Self::ConnectionFailed(msg)
68
6
    }
69

            
70
    #[must_use]
71
6
    pub const fn tls_error(msg: AzString) -> Self {
72
6
        Self::TlsError(msg)
73
6
    }
74

            
75
    #[must_use]
76
17
    pub const fn http_status(status_code: u16, message: AzString) -> Self {
77
17
        Self::HttpStatus(HttpStatusError {
78
17
            status_code,
79
17
            message,
80
17
        })
81
17
    }
82

            
83
    #[must_use]
84
6
    pub const fn io_error(msg: AzString) -> Self {
85
6
        Self::IoError(msg)
86
6
    }
87

            
88
    #[must_use]
89
12
    pub const fn response_too_large(max_size: u64, actual_size: u64) -> Self {
90
12
        Self::ResponseTooLarge(HttpResponseTooLargeError {
91
12
            max_size,
92
12
            actual_size,
93
12
        })
94
12
    }
95

            
96
    #[must_use]
97
35
    pub const fn other(msg: AzString) -> Self {
98
35
        Self::Other(msg)
99
35
    }
100
}
101

            
102
impl fmt::Display for HttpError {
103
36
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104
36
        match self {
105
2
            Self::InvalidUrl(url) => write!(f, "Invalid URL: {}", url.as_str()),
106
1
            Self::ConnectionFailed(msg) => write!(f, "Connection failed: {}", msg.as_str()),
107
2
            Self::Timeout => write!(f, "Request timed out"),
108
1
            Self::TlsError(msg) => write!(f, "TLS error: {}", msg.as_str()),
109
16
            Self::HttpStatus(e) => write!(f, "HTTP {} - {}", e.status_code, e.message.as_str()),
110
1
            Self::IoError(msg) => write!(f, "I/O error: {}", msg.as_str()),
111
11
            Self::ResponseTooLarge(e) => {
112
11
                write!(
113
11
                    f,
114
11
                    "Response too large: {} bytes (max: {})",
115
                    e.actual_size, e.max_size
116
                )
117
            }
118
2
            Self::Other(msg) => write!(f, "HTTP error: {}", msg.as_str()),
119
        }
120
36
    }
121
}
122

            
123
#[cfg(feature = "std")]
124
impl std::error::Error for HttpError {}
125

            
126
/// Result type for HTTP operations
127
pub type HttpResult<T> = Result<T, HttpError>;
128

            
129
// FFI-safe Result types for HTTP operations
130
use azul_css::{impl_result, impl_result_inner};
131

            
132
// Forward declaration - actual impl_result! calls are after HttpResponse definition
133

            
134
// ============================================================================
135
// Request configuration (C-compatible)
136
// ============================================================================
137

            
138
/// HTTP header key-value pair
139
#[derive(Debug, Clone, PartialEq, Eq)]
140
#[repr(C)]
141
pub struct HttpHeader {
142
    /// Header name
143
    pub name: AzString,
144
    /// Header value
145
    pub value: AzString,
146
}
147

            
148
impl HttpHeader {
149
113
    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
150
113
        Self {
151
113
            name: AzString::from(name.into()),
152
113
            value: AzString::from(value.into()),
153
113
        }
154
113
    }
155
}
156

            
157
impl_option!(
158
    HttpHeader,
159
    OptionHttpHeader,
160
    copy = false,
161
    [Debug, Clone, PartialEq, Eq]
162
);
163
impl_vec!(
164
    HttpHeader,
165
    HttpHeaderVec,
166
    HttpHeaderVecDestructor,
167
    HttpHeaderVecDestructorType,
168
    HttpHeaderVecSlice,
169
    OptionHttpHeader
170
);
171
impl_vec_clone!(HttpHeader, HttpHeaderVec, HttpHeaderVecDestructor);
172
impl_vec_debug!(HttpHeader, HttpHeaderVec);
173
impl_vec_partialeq!(HttpHeader, HttpHeaderVec);
174
impl_vec_mut!(HttpHeader, HttpHeaderVec);
175

            
176
/// HTTP request configuration (C-compatible)
177
#[derive(Debug, Clone)]
178
#[repr(C)]
179
pub struct HttpRequestConfig {
180
    /// Request timeout in seconds (default: 30)
181
    pub timeout_secs: u64,
182
    /// Maximum response size in bytes (default: 100MB, 0 = unlimited)
183
    pub max_response_size: u64,
184
    /// User-Agent header value
185
    pub user_agent: AzString,
186
    /// Additional headers
187
    pub headers: HttpHeaderVec,
188
    /// Disable TLS certificate verification (default: false).
189
    /// WARNING: This makes HTTPS connections vulnerable to MITM attacks.
190
    /// Use only for testing or when connecting to servers with self-signed
191
    /// or cross-signed certificates not in the Mozilla root store.
192
    pub disable_tls_cert_verification: bool,
193
    /// Connection pool to send the request through (default: none).
194
    ///
195
    /// `None` opens a fresh connection for this request and closes it after.
196
    /// `Some` reuses the client's idle connections, and TLS verification then
197
    /// follows the client's `HttpClientConfig`, not the field above.
198
    pub client: OptionHttpClient,
199
}
200

            
201
impl Default for HttpRequestConfig {
202
35
    fn default() -> Self {
203
35
        Self {
204
35
            timeout_secs: 30,
205
35
            max_response_size: 100 * 1024 * 1024, // 100 MB
206
35
            user_agent: AzString::from("azul-http/1.0".to_string()),
207
35
            headers: HttpHeaderVec::from_const_slice(&[]),
208
35
            disable_tls_cert_verification: false,
209
35
            client: OptionHttpClient::None,
210
35
        }
211
35
    }
212
}
213

            
214
/// Settings for an [`HttpClient`]'s connection pool (C-compatible).
215
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
216
#[repr(C)]
217
pub struct HttpClientConfig {
218
    /// Idle connections kept open across all hosts (default: 32).
219
    pub max_idle_connections: u32,
220
    /// Idle connections kept open to any one host (default: 8).
221
    pub max_idle_connections_per_host: u32,
222
    /// Seconds a host's DNS answer is reused (default: 0 = look it up for
223
    /// every request, like a request without a client does).
224
    ///
225
    /// Reusing a pooled connection does not skip the lookup: the address is
226
    /// resolved before the pool is asked for a connection. With a cache the
227
    /// lookup happens once per host per period. A host that moves to another
228
    /// address is only reached again once its entry expires.
229
    pub dns_cache_secs: u32,
230
    /// Disable TLS certificate verification for every request of this client
231
    /// (default: false). Same warning as on `HttpRequestConfig`.
232
    pub disable_tls_cert_verification: bool,
233
}
234

            
235
impl Default for HttpClientConfig {
236
    fn default() -> Self {
237
        Self {
238
            max_idle_connections: 32,
239
            max_idle_connections_per_host: 8,
240
            dns_cache_secs: 0,
241
            disable_tls_cert_verification: false,
242
        }
243
    }
244
}
245

            
246
impl HttpClientConfig {
247
    /// Create a new config with default values
248
    #[must_use]
249
    pub fn new() -> Self {
250
        Self::default()
251
    }
252

            
253
    /// Set how many idle connections the pool keeps across all hosts
254
    #[must_use]
255
    pub const fn with_max_idle_connections(mut self, n: u32) -> Self {
256
        self.max_idle_connections = n;
257
        self
258
    }
259

            
260
    /// Set how many idle connections the pool keeps to any one host
261
    #[must_use]
262
    pub const fn with_max_idle_connections_per_host(mut self, n: u32) -> Self {
263
        self.max_idle_connections_per_host = n;
264
        self
265
    }
266

            
267
    /// Reuse each host's DNS answer for `secs` seconds (0 = no cache)
268
    #[must_use]
269
    pub const fn with_dns_cache_secs(mut self, secs: u32) -> Self {
270
        self.dns_cache_secs = secs;
271
        self
272
    }
273
}
274

            
275
/// A connection pool that requests can share (C-compatible handle).
276
///
277
/// Created by the application, never by the framework: a request without a
278
/// client opens its own connection. Hand clones to
279
/// [`HttpRequestConfig::with_client`] or to a widget; all clones share one pool,
280
/// which closes its connections when the last clone is dropped.
281
#[repr(C)]
282
pub struct HttpClient {
283
    pub ptr: Box<alloc::sync::Arc<HttpClientInner>>,
284
    pub run_destructor: bool,
285
}
286

            
287
/// The shared state behind an [`HttpClient`] handle.
288
#[derive(Debug)]
289
#[allow(missing_copy_implementations)] // only Copy in builds without the `http` feature
290
pub struct HttpClientInner {
291
    pub config: HttpClientConfig,
292
    #[cfg(all(feature = "http", not(target_arch = "wasm32")))]
293
    agent: ureq::Agent,
294
}
295

            
296
impl HttpClient {
297
    /// Create a connection pool with the given settings
298
    #[must_use]
299
    pub fn create(config: HttpClientConfig) -> Self {
300
        Self {
301
            ptr: Box::new(alloc::sync::Arc::new(HttpClientInner {
302
                config,
303
                #[cfg(all(feature = "http", not(target_arch = "wasm32")))]
304
                agent: client_agent(
305
                    &config,
306
                    ureq::unversioned::resolver::DefaultResolver::default(),
307
                ),
308
            })),
309
            run_destructor: true,
310
        }
311
    }
312

            
313
    /// The settings this client was created with
314
    #[must_use]
315
    pub fn get_config(&self) -> HttpClientConfig {
316
        self.ptr.config
317
    }
318
}
319

            
320
impl Clone for HttpClient {
321
    fn clone(&self) -> Self {
322
        Self {
323
            ptr: self.ptr.clone(),
324
            run_destructor: true,
325
        }
326
    }
327
}
328

            
329
impl Drop for HttpClient {
330
    fn drop(&mut self) {
331
        self.run_destructor = false;
332
    }
333
}
334

            
335
impl fmt::Debug for HttpClient {
336
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337
        f.debug_struct("HttpClient")
338
            .field("config", &self.ptr.config)
339
            .finish_non_exhaustive()
340
    }
341
}
342

            
343
/// Two handles are equal when they share the same pool.
344
impl PartialEq for HttpClient {
345
    fn eq(&self, other: &Self) -> bool {
346
        alloc::sync::Arc::ptr_eq(&self.ptr, &other.ptr)
347
    }
348
}
349

            
350
impl_option!(
351
    HttpClient,
352
    OptionHttpClient,
353
    copy = false,
354
    [Debug, Clone, PartialEq]
355
);
356

            
357
/// The e2e mock store's answer for `url`, if the store is armed. `None` =
358
/// not an e2e run, perform the real transfer.
359
#[cfg(feature = "text_layout")]
360
16
fn mocked_http(url: &str) -> Option<ResultHttpResponseHttpError> {
361
    use crate::request::mock::{Answer, MockHttp};
362
16
    match crate::request::mock::take_http(url) {
363
16
        Answer::NotArmed => None,
364
        Answer::Mocked(MockHttp::Response(r)) => {
365
            let content_length = r.body.len() as u64;
366
            Some(ResultHttpResponseHttpError::Ok(HttpResponse {
367
                status_code: r.status,
368
                body: U8Vec::from_vec(r.body),
369
                content_type: r.content_type,
370
                content_length,
371
                headers: HttpHeaderVec::from_const_slice(&[]),
372
            }))
373
        }
374
        Answer::Mocked(MockHttp::Error(message)) => {
375
            Some(ResultHttpResponseHttpError::Err(HttpError::other(message)))
376
        }
377
        Answer::Unmocked => Some(ResultHttpResponseHttpError::Err(HttpError::other(
378
            AzString::from(format!("unmocked http request under e2e: {url}")),
379
        ))),
380
    }
381
16
}
382

            
383
/// [`mocked_http`] narrowed to the byte body: a non-2xx status is an
384
/// `HttpError::HttpStatus`, like `download_bytes_with_config`.
385
#[cfg(feature = "text_layout")]
386
6
fn mocked_download(url: &str) -> Option<ResultU8VecHttpError> {
387
6
    match mocked_http(url)? {
388
        ResultHttpResponseHttpError::Ok(response) => Some(if response.status_code >= 400 {
389
            ResultU8VecHttpError::Err(HttpError::http_status(
390
                response.status_code,
391
                AzString::from(format!("HTTP error {}", response.status_code)),
392
            ))
393
        } else {
394
            ResultU8VecHttpError::Ok(response.body)
395
        }),
396
        ResultHttpResponseHttpError::Err(e) => Some(ResultU8VecHttpError::Err(e)),
397
    }
398
6
}
399

            
400
impl HttpRequestConfig {
401
    /// Create a new config with default values
402
    #[must_use]
403
33
    pub fn new() -> Self {
404
33
        Self::default()
405
33
    }
406

            
407
    /// Set timeout in seconds
408
    #[must_use]
409
9
    pub const fn with_timeout(mut self, secs: u64) -> Self {
410
9
        self.timeout_secs = secs;
411
9
        self
412
9
    }
413

            
414
    /// Set maximum response size (0 = unlimited)
415
    #[must_use]
416
7
    pub const fn with_max_size(mut self, max_bytes: u64) -> Self {
417
7
        self.max_response_size = max_bytes;
418
7
        self
419
7
    }
420

            
421
    /// Send requests through a shared connection pool instead of opening a
422
    /// connection per request
423
    #[must_use]
424
    pub fn with_client(mut self, client: HttpClient) -> Self {
425
        self.client = OptionHttpClient::Some(client);
426
        self
427
    }
428

            
429
    /// Set User-Agent header
430
    #[must_use]
431
5
    pub fn with_user_agent(mut self, ua: impl Into<String>) -> Self {
432
5
        self.user_agent = AzString::from(ua.into());
433
5
        self
434
5
    }
435

            
436
    /// Add a header
437
    #[must_use]
438
104
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
439
104
        self.headers.push(HttpHeader::new(name, value));
440
104
        self
441
104
    }
442

            
443
    /// HTTP GET request using this configuration, resuming `on_result` with
444
    /// an [`HttpGetResult`].
445
    ///
446
    /// Never blocks the calling activation in an observable way: on desktop
447
    /// the request runs here (ureq is synchronous) and the callback runs
448
    /// right after the current activation returns; on web `fetch()` runs and
449
    /// the callback runs on a later task. `data` is handed back untouched.
450
    ///
451
    /// On web CORS applies and cannot be escaped: a target that does not
452
    /// send `Access-Control-Allow-Origin` fails with `HttpError::Other`
453
    /// naming CORS. Chromium 142+ additionally prompts for Local Network
454
    /// Access on loopback / LAN targets.
455
    #[cfg(feature = "text_layout")]
456
    #[must_use]
457
    pub fn http_get(
458
        &self,
459
        url: AzString,
460
        data: azul_core::refany::RefAny,
461
        on_result: crate::callbacks::ResumeCallback,
462
    ) -> azul_core::task::RequestId {
463
        let result = self.http_get_blocking(url);
464
        crate::request::complete(data, on_result, HttpGetResult { result })
465
    }
466

            
467
    /// The synchronous transport behind [`Self::http_get`]. Not part of the
468
    /// public API (it cannot exist on web); framework-internal callers that
469
    /// are already on a worker thread may use it.
470
    #[cfg(all(feature = "http", not(target_arch = "wasm32")))]
471
    #[must_use]
472
    pub fn http_get_blocking(&self, url: AzString) -> ResultHttpResponseHttpError {
473
        #[cfg(feature = "text_layout")]
474
        if let Some(mocked) = mocked_http(url.as_str()) {
475
            return mocked;
476
        }
477
        http_get_with_config(url.as_str(), self).into()
478
    }
479

            
480
    /// Stub: `http` feature disabled.
481
    #[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
482
    #[must_use]
483
6
    pub fn http_get_blocking(&self, url: AzString) -> ResultHttpResponseHttpError {
484
        #[cfg(feature = "text_layout")]
485
6
        if let Some(mocked) = mocked_http(url.as_str()) {
486
            return mocked;
487
6
        }
488
6
        ResultHttpResponseHttpError::Err(HttpError::other("http feature not enabled".into()))
489
6
    }
490

            
491
    /// HTTP request with an arbitrary verb and an optional body, using this
492
    /// configuration, resuming `on_result` with an [`HttpGetResult`]. An
493
    /// EMPTY `body` sends no body (GET/HEAD semantics); `content_type` is
494
    /// only applied when a body is present. Same contract as
495
    /// [`Self::http_get`].
496
    #[cfg(feature = "text_layout")]
497
    #[must_use]
498
    pub fn http_request(
499
        &self,
500
        method: HttpMethod,
501
        url: AzString,
502
        body: U8Vec,
503
        content_type: AzString,
504
        data: azul_core::refany::RefAny,
505
        on_result: crate::callbacks::ResumeCallback,
506
    ) -> azul_core::task::RequestId {
507
        let result = self.http_request_blocking(method, url, body, content_type);
508
        crate::request::complete(data, on_result, HttpGetResult { result })
509
    }
510

            
511
    /// The synchronous transport behind [`Self::http_request`]; see
512
    /// [`Self::http_get_blocking`].
513
    #[cfg(all(feature = "http", not(target_arch = "wasm32")))]
514
    #[must_use]
515
    pub fn http_request_blocking(
516
        &self,
517
        method: HttpMethod,
518
        url: AzString,
519
        body: U8Vec,
520
        content_type: AzString,
521
    ) -> ResultHttpResponseHttpError {
522
        #[cfg(feature = "text_layout")]
523
        if let Some(mocked) = mocked_http(url.as_str()) {
524
            return mocked;
525
        }
526
        let body_ref = body.as_ref();
527
        let body_opt = if body_ref.is_empty() {
528
            None
529
        } else {
530
            Some(body_ref)
531
        };
532
        http_request_with_config(method, url.as_str(), body_opt, content_type.as_str(), self).into()
533
    }
534

            
535
    /// Stub: `http` feature disabled.
536
    #[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
537
    #[must_use]
538
    pub fn http_request_blocking(
539
        &self,
540
        _method: HttpMethod,
541
        url: AzString,
542
        _body: U8Vec,
543
        _content_type: AzString,
544
    ) -> ResultHttpResponseHttpError {
545
        #[cfg(feature = "text_layout")]
546
        if let Some(mocked) = mocked_http(url.as_str()) {
547
            return mocked;
548
        }
549
        ResultHttpResponseHttpError::Err(HttpError::other("http feature not enabled".into()))
550
    }
551

            
552
    /// HTTP POST with a body, using this configuration, resuming `on_result`
553
    /// with an [`HttpGetResult`]. Same contract as [`Self::http_get`].
554
    #[cfg(feature = "text_layout")]
555
    #[must_use]
556
    pub fn http_post(
557
        &self,
558
        url: AzString,
559
        body: U8Vec,
560
        content_type: AzString,
561
        data: azul_core::refany::RefAny,
562
        on_result: crate::callbacks::ResumeCallback,
563
    ) -> azul_core::task::RequestId {
564
        let result = self.http_post_blocking(url, body, content_type);
565
        crate::request::complete(data, on_result, HttpGetResult { result })
566
    }
567

            
568
    /// The synchronous transport behind [`Self::http_post`]; see
569
    /// [`Self::http_get_blocking`].
570
    #[cfg(all(feature = "http", not(target_arch = "wasm32")))]
571
    #[must_use]
572
    pub fn http_post_blocking(
573
        &self,
574
        url: AzString,
575
        body: U8Vec,
576
        content_type: AzString,
577
    ) -> ResultHttpResponseHttpError {
578
        #[cfg(feature = "text_layout")]
579
        if let Some(mocked) = mocked_http(url.as_str()) {
580
            return mocked;
581
        }
582
        http_post_with_config(url.as_str(), body.as_ref(), content_type.as_str(), self).into()
583
    }
584

            
585
    /// Stub: `http` feature disabled.
586
    #[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
587
    #[must_use]
588
    pub fn http_post_blocking(
589
        &self,
590
        url: AzString,
591
        _body: U8Vec,
592
        _content_type: AzString,
593
    ) -> ResultHttpResponseHttpError {
594
        #[cfg(feature = "text_layout")]
595
        if let Some(mocked) = mocked_http(url.as_str()) {
596
            return mocked;
597
        }
598
        ResultHttpResponseHttpError::Err(HttpError::other("http feature not enabled".into()))
599
    }
600

            
601
    /// Download a URL to bytes using this configuration, resuming
602
    /// `on_result` with an [`HttpBytesResult`] (a non-2xx status is an
603
    /// `HttpError::HttpStatus`). Same contract as [`Self::http_get`].
604
    #[cfg(feature = "text_layout")]
605
    #[must_use]
606
    pub fn download_bytes(
607
        &self,
608
        url: AzString,
609
        data: azul_core::refany::RefAny,
610
        on_result: crate::callbacks::ResumeCallback,
611
    ) -> azul_core::task::RequestId {
612
        let result = self.download_bytes_blocking(url);
613
        crate::request::complete(data, on_result, HttpBytesResult { result })
614
    }
615

            
616
    /// The synchronous transport behind [`Self::download_bytes`]; see
617
    /// [`Self::http_get_blocking`].
618
    #[cfg(all(feature = "http", not(target_arch = "wasm32")))]
619
    #[must_use]
620
    pub fn download_bytes_blocking(&self, url: AzString) -> ResultU8VecHttpError {
621
        #[cfg(feature = "text_layout")]
622
        if let Some(mocked) = mocked_download(url.as_str()) {
623
            return mocked;
624
        }
625
        download_bytes_with_config(url.as_str(), self).into()
626
    }
627

            
628
    /// Stub: `http` feature disabled.
629
    #[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
630
    #[must_use]
631
6
    pub fn download_bytes_blocking(&self, url: AzString) -> ResultU8VecHttpError {
632
        #[cfg(feature = "text_layout")]
633
6
        if let Some(mocked) = mocked_download(url.as_str()) {
634
            return mocked;
635
6
        }
636
6
        ResultU8VecHttpError::Err(HttpError::other("http feature not enabled".into()))
637
6
    }
638

            
639
    /// Check whether a URL is reachable (a HEAD request answered with a 2xx
640
    /// status), using this configuration's timeout and TLS settings, and
641
    /// resume `on_result` with an [`HttpReachableResult`]. Same contract as
642
    /// [`Self::http_get`].
643
    ///
644
    /// On web, opaque `no-cors` answers make "reachable" approximate: a
645
    /// server that answers at all counts as reachable even when its status
646
    /// cannot be read.
647
    #[cfg(feature = "text_layout")]
648
    #[must_use]
649
    pub fn is_url_reachable(
650
        &self,
651
        url: AzString,
652
        data: azul_core::refany::RefAny,
653
        on_result: crate::callbacks::ResumeCallback,
654
    ) -> azul_core::task::RequestId {
655
        let (reachable, error) = self.is_url_reachable_blocking(url);
656
        crate::request::complete(
657
            data,
658
            on_result,
659
            HttpReachableResult {
660
                reachable,
661
                error: error.into(),
662
            },
663
        )
664
    }
665

            
666
    /// The synchronous probe behind [`Self::is_url_reachable`]: `(reachable,
667
    /// transport error)`; see [`Self::http_get_blocking`].
668
    #[cfg(all(feature = "http", not(target_arch = "wasm32")))]
669
    #[must_use]
670
    pub fn is_url_reachable_blocking(&self, url: AzString) -> (bool, Option<AzString>) {
671
        #[cfg(feature = "text_layout")]
672
        if let Some(mocked) = mocked_http(url.as_str()) {
673
            return match mocked {
674
                ResultHttpResponseHttpError::Ok(response) => (response.is_success(), None),
675
                ResultHttpResponseHttpError::Err(e) => (false, Some(AzString::from(e.to_string()))),
676
            };
677
        }
678
        match http_request_with_config(HttpMethod::Head, url.as_str(), None, "", self) {
679
            Ok(response) => (response.is_success(), None),
680
            Err(e) => (false, Some(AzString::from(e.to_string()))),
681
        }
682
    }
683

            
684
    /// Stub: `http` feature disabled. The answer self-describes through the
685
    /// error instead of a bare `false` that reads exactly like "server down".
686
    #[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
687
    #[must_use]
688
4
    pub fn is_url_reachable_blocking(&self, url: AzString) -> (bool, Option<AzString>) {
689
        #[cfg(feature = "text_layout")]
690
4
        if let Some(mocked) = mocked_http(url.as_str()) {
691
            return match mocked {
692
                ResultHttpResponseHttpError::Ok(response) => (response.is_success(), None),
693
                ResultHttpResponseHttpError::Err(e) => (false, Some(AzString::from(e.to_string()))),
694
            };
695
4
        }
696
4
        (
697
4
            false,
698
4
            Some(AzString::from(
699
4
                "http feature not enabled: this build has no network transport (rebuild \
700
4
                 azul-layout with the `http` feature)",
701
4
            )),
702
4
        )
703
4
    }
704
}
705

            
706
// ============================================================================
707
// Response (C-compatible)
708
// ============================================================================
709

            
710
/// HTTP response with status code, headers, and body
711
#[derive(Debug, Clone, PartialEq)]
712
#[repr(C)]
713
pub struct HttpResponse {
714
    /// HTTP status code (200, 404, etc.)
715
    pub status_code: u16,
716
    /// Response body as bytes
717
    pub body: U8Vec,
718
    /// Content-Type header value
719
    pub content_type: AzString,
720
    /// Content-Length header value (0 if unknown)
721
    pub content_length: u64,
722
    /// Response headers
723
    pub headers: HttpHeaderVec,
724
}
725

            
726
impl HttpResponse {
727
    /// Check if the response was successful (2xx status)
728
    #[must_use]
729
65553
    pub const fn is_success(&self) -> bool {
730
65553
        self.status_code >= 200 && self.status_code < 300
731
65553
    }
732

            
733
    /// Check if the response is a redirect (3xx status)
734
    #[must_use]
735
65552
    pub const fn is_redirect(&self) -> bool {
736
65552
        self.status_code >= 300 && self.status_code < 400
737
65552
    }
738

            
739
    /// Check if the response is a client error (4xx status)
740
    #[must_use]
741
65553
    pub const fn is_client_error(&self) -> bool {
742
65553
        self.status_code >= 400 && self.status_code < 500
743
65553
    }
744

            
745
    /// Check if the response is a server error (5xx status)
746
    #[must_use]
747
65553
    pub const fn is_server_error(&self) -> bool {
748
65553
        self.status_code >= 500 && self.status_code < 600
749
65553
    }
750

            
751
    /// Try to convert the body to a UTF-8 string
752
    #[must_use]
753
18
    pub fn body_as_string(&self) -> Option<AzString> {
754
18
        core::str::from_utf8(self.body.as_slice())
755
18
            .ok()
756
18
            .map(|s| AzString::from(s.to_string()))
757
18
    }
758
}
759

            
760
// FFI-safe Result types for HTTP operations (must be after HttpResponse definition)
761
impl_result!(
762
    HttpResponse,
763
    HttpError,
764
    ResultHttpResponseHttpError,
765
    copy = false,
766
    clone = false,
767
    [Debug, Clone, PartialEq]
768
);
769

            
770
impl_result!(
771
    U8Vec,
772
    HttpError,
773
    ResultU8VecHttpError,
774
    copy = false,
775
    clone = false,
776
    [Debug, Clone, PartialEq, Eq]
777
);
778

            
779
// ============================================================================
780
// Resumable request results
781
// ============================================================================
782
//
783
// `HttpRequestConfig::http_get` / `http_post` / `http_request` /
784
// `download_bytes` / `is_url_reachable` are request functions (see
785
// `crate::request`): they return a `RequestId` and resume the caller's
786
// `ResumeCallback` with one of these structs, type-erased into a `RefAny`.
787

            
788
/// Result of [`HttpRequestConfig::http_get`], [`HttpRequestConfig::http_post`]
789
/// and [`HttpRequestConfig::http_request`].
790
#[derive(Debug, Clone)]
791
#[repr(C)]
792
pub struct HttpGetResult {
793
    pub result: ResultHttpResponseHttpError,
794
}
795

            
796
impl_option!(
797
    HttpGetResult,
798
    OptionHttpGetResult,
799
    copy = false,
800
    [Debug, Clone]
801
);
802

            
803
impl HttpGetResult {
804
    /// Downcast the `result` `RefAny` delivered to a `ResumeCallback`.
805
    #[must_use]
806
    pub fn downcast(mut result: azul_core::refany::RefAny) -> OptionHttpGetResult {
807
        result.downcast_ref::<Self>().map(|r| r.clone()).into()
808
    }
809
}
810

            
811
/// Result of [`HttpRequestConfig::download_bytes`].
812
#[derive(Debug, Clone)]
813
#[repr(C)]
814
pub struct HttpBytesResult {
815
    pub result: ResultU8VecHttpError,
816
}
817

            
818
impl_option!(
819
    HttpBytesResult,
820
    OptionHttpBytesResult,
821
    copy = false,
822
    [Debug, Clone]
823
);
824

            
825
impl HttpBytesResult {
826
    /// Downcast the `result` `RefAny` delivered to a `ResumeCallback`.
827
    #[must_use]
828
    pub fn downcast(mut result: azul_core::refany::RefAny) -> OptionHttpBytesResult {
829
        result.downcast_ref::<Self>().map(|r| r.clone()).into()
830
    }
831
}
832

            
833
/// Result of [`HttpRequestConfig::is_url_reachable`]. `reachable` is `true`
834
/// for a 2xx answer to a HEAD request; `error` carries the transport error
835
/// when the request could not be made at all (`None` for a plain non-2xx
836
/// status).
837
#[derive(Debug, Clone, PartialEq, Eq)]
838
#[repr(C)]
839
pub struct HttpReachableResult {
840
    pub reachable: bool,
841
    pub error: azul_css::corety::OptionString,
842
}
843

            
844
impl_option!(
845
    HttpReachableResult,
846
    OptionHttpReachableResult,
847
    copy = false,
848
    [Debug, Clone, PartialEq, Eq]
849
);
850

            
851
impl HttpReachableResult {
852
    /// Downcast the `result` `RefAny` delivered to a `ResumeCallback`.
853
    #[must_use]
854
    pub fn downcast(mut result: azul_core::refany::RefAny) -> OptionHttpReachableResult {
855
        result.downcast_ref::<Self>().map(|r| r.clone()).into()
856
    }
857
}
858

            
859
/// Simple HTTP GET request
860
///
861
/// # Arguments
862
/// * `url` - The URL to request
863
///
864
/// # Returns
865
/// * `HttpResult<HttpResponse>` - The response or an error
866
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
867
pub fn http_get(url: &str) -> HttpResult<HttpResponse> {
868
    http_get_with_config(url, &HttpRequestConfig::default())
869
}
870

            
871
/// Stub: `http` feature disabled.
872
#[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
873
/// # Errors
874
///
875
/// Returns an `HttpError` if the request fails (network/status error, or the networking feature is
876
/// disabled).
877
4
pub fn http_get(_url: &str) -> HttpResult<HttpResponse> {
878
4
    Err(HttpError::other("http feature not enabled".into()))
879
4
}
880

            
881
/// HTTP GET request with custom configuration
882
///
883
/// # Arguments
884
/// * `url` - The URL to request
885
/// * `config` - Request configuration
886
///
887
/// # Returns
888
/// * `HttpResult<HttpResponse>` - The response or an error
889
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
890
fn make_agent(timeout_secs: u64, disable_tls_cert_verification: bool) -> ureq::Agent {
891
    use std::time::Duration;
892

            
893
    agent_config(disable_tls_cert_verification)
894
        .timeout_global(Some(Duration::from_secs(timeout_secs)))
895
        .build()
896
        .new_agent()
897
}
898

            
899
/// The agent settings every request shares, whether its agent is built for one
900
/// request ([`make_agent`]) or kept in an [`HttpClient`].
901
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
902
fn agent_config(
903
    disable_tls_cert_verification: bool,
904
) -> ureq::config::ConfigBuilder<ureq::typestate::AgentScope> {
905
    let mut tls_builder = ureq::tls::TlsConfig::builder()
906
        .provider(ureq::tls::TlsProvider::Rustls)
907
        .unversioned_rustls_crypto_provider(std::sync::Arc::new(rustls_rustcrypto::provider()));
908

            
909
    if disable_tls_cert_verification {
910
        tls_builder = tls_builder.disable_verification(true);
911
    } else {
912
        tls_builder = tls_builder.root_certs(ureq::tls::RootCerts::WebPki);
913
    }
914

            
915
    let tls_config = tls_builder.build();
916

            
917
    ureq::Agent::config_builder()
918
        .tls_config(tls_config)
919
        .http_status_as_error(false)
920
}
921

            
922
/// The agent behind an [`HttpClient`]: pooled per `config`, and resolving hosts
923
/// through `resolver`, cached when `config.dns_cache_secs` asks for it.
924
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
925
fn client_agent(
926
    config: &HttpClientConfig,
927
    resolver: impl ureq::unversioned::resolver::Resolver,
928
) -> ureq::Agent {
929
    let agent_config = agent_config(config.disable_tls_cert_verification)
930
        .max_idle_connections(config.max_idle_connections as usize)
931
        .max_idle_connections_per_host(config.max_idle_connections_per_host as usize)
932
        .build();
933
    let connector = ureq::unversioned::transport::DefaultConnector::default();
934
    if config.dns_cache_secs == 0 {
935
        ureq::Agent::with_parts(agent_config, connector, resolver)
936
    } else {
937
        ureq::Agent::with_parts(
938
            agent_config,
939
            connector,
940
            CachingResolver::new(
941
                resolver,
942
                std::time::Duration::from_secs(u64::from(config.dns_cache_secs)),
943
            ),
944
        )
945
    }
946
}
947

            
948
/// A resolver that answers each `host:port` from memory for `ttl` after asking
949
/// `inner` once.
950
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
951
#[derive(Debug)]
952
struct CachingResolver<R> {
953
    inner: R,
954
    ttl: std::time::Duration,
955
    answers: std::sync::Mutex<
956
        std::collections::HashMap<String, (std::time::Instant, Vec<std::net::SocketAddr>)>,
957
    >,
958
}
959

            
960
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
961
impl<R> CachingResolver<R> {
962
    fn new(inner: R, ttl: std::time::Duration) -> Self {
963
        Self {
964
            inner,
965
            ttl,
966
            answers: std::sync::Mutex::new(std::collections::HashMap::new()),
967
        }
968
    }
969
}
970

            
971
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
972
impl<R: ureq::unversioned::resolver::Resolver> ureq::unversioned::resolver::Resolver
973
    for CachingResolver<R>
974
{
975
    fn resolve(
976
        &self,
977
        uri: &ureq::http::Uri,
978
        config: &ureq::config::Config,
979
        timeout: ureq::unversioned::transport::NextTimeout,
980
    ) -> Result<ureq::unversioned::resolver::ResolvedSocketAddrs, ureq::Error> {
981
        let key = uri
982
            .scheme()
983
            .zip(uri.authority())
984
            .and_then(|(scheme, authority)| {
985
                ureq::unversioned::resolver::DefaultResolver::host_and_port(scheme, authority)
986
            });
987
        let Some(key) = key else {
988
            return self.inner.resolve(uri, config, timeout); // let it report the bad URL
989
        };
990
        let cached = self.answers.lock().ok().and_then(|answers| {
991
            answers
992
                .get(&key)
993
                .filter(|(at, _)| at.elapsed() < self.ttl)
994
                .map(|(_, addrs)| addrs.clone())
995
        });
996
        if let Some(addrs) = cached {
997
            let mut out = self.inner.empty();
998
            for addr in addrs {
999
                out.push(addr);
            }
            return Ok(out);
        }
        // Failures are not cached: the next request asks again.
        let resolved = self.inner.resolve(uri, config, timeout)?;
        if let Ok(mut answers) = self.answers.lock() {
            answers.insert(
                key,
                (
                    std::time::Instant::now(),
                    resolved.iter().copied().collect(),
                ),
            );
        }
        Ok(resolved)
    }
    fn empty(&self) -> ureq::unversioned::resolver::ResolvedSocketAddrs {
        self.inner.empty()
    }
}
/// HTTP verb for [`http_request_with_config`].
///
/// Rust-side only — this type deliberately has no C-ABI mirror in `api.json`;
/// the C bindings keep the pre-existing `HttpRequestConfig::http_get` /
/// `download_bytes` entry points.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[repr(C)]
pub enum HttpMethod {
    Get,
    Head,
    Post,
    Put,
    Patch,
    Delete,
}
impl HttpMethod {
    /// The uppercase wire name of the verb.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Get => "GET",
            Self::Head => "HEAD",
            Self::Post => "POST",
            Self::Put => "PUT",
            Self::Patch => "PATCH",
            Self::Delete => "DELETE",
        }
    }
    /// Whether this verb carries a request body.
    ///
    /// Mirrors ureq's request typestate split: `POST`/`PUT`/`PATCH` build a
    /// `WithBody` request terminated by `send()`, while `GET`/`HEAD`/`DELETE`
    /// build a `WithoutBody` one terminated by `call()`.
    #[must_use]
    pub const fn takes_body(self) -> bool {
        matches!(self, Self::Post | Self::Put | Self::Patch)
    }
}
impl fmt::Display for HttpMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}
/// Maps a ureq transport error onto the C-ABI-safe [`HttpError`].
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
fn map_ureq_error(url: &str, e: &ureq::Error) -> HttpError {
    match e {
        ureq::Error::Timeout(_) => HttpError::Timeout,
        ureq::Error::HostNotFound => {
            HttpError::connection_failed(format!("DNS resolution failed for {url}").into())
        }
        ureq::Error::ConnectionFailed => {
            HttpError::connection_failed(format!("Connection failed: {url}").into())
        }
        ureq::Error::Io(io_err) => HttpError::io_error(format!("{io_err}").into()),
        ureq::Error::BadUri(msg) => HttpError::invalid_url(format!("{url}: {msg}").into()),
        ureq::Error::Tls(msg) => HttpError::tls_error(format!("TLS error: {msg}").into()),
        // Catch-all for feature-gated variants (Rustls, Pem, etc.)
        _ => {
            let msg = e.to_string();
            if msg.starts_with("rustls:") || msg.contains("TLS") || msg.contains("certificate") {
                HttpError::tls_error(msg.into())
            } else {
                HttpError::other(msg.into())
            }
        }
    }
}
/// Turns a ureq response into the C-ABI [`HttpResponse`], enforcing
/// `config.max_response_size` both on the advertised `Content-Length` and on
/// the actual number of bytes read.
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
fn decode_response(
    response: ureq::http::Response<ureq::Body>,
    config: &HttpRequestConfig,
) -> HttpResult<HttpResponse> {
    use std::io::Read;
    let status_code = response.status().as_u16();
    let content_type = AzString::from(
        response
            .headers()
            .get("Content-Type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("application/octet-stream")
            .to_string(),
    );
    let content_length = response
        .headers()
        .get("Content-Length")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse::<u64>().ok())
        .unwrap_or(0);
    // Collect response headers
    let mut headers = Vec::new();
    for (name, value) in response.headers() {
        if let Ok(v) = value.to_str() {
            headers.push(HttpHeader::new(name.to_string(), v.to_string()));
        }
    }
    // Check response size limit
    if config.max_response_size > 0 && content_length > config.max_response_size {
        return Err(HttpError::response_too_large(
            config.max_response_size,
            content_length,
        ));
    }
    // Read body with size limit
    let mut body = Vec::new();
    let limit = if config.max_response_size > 0 {
        config.max_response_size as usize
    } else {
        usize::MAX
    };
    let mut body_reader = response.into_body();
    let mut reader = body_reader.as_reader().take(limit as u64);
    reader
        .read_to_end(&mut body)
        .map_err(|e| HttpError::io_error(e.to_string().into()))?;
    Ok(HttpResponse {
        status_code,
        body: U8Vec::from(body),
        content_type,
        content_length,
        headers: HttpHeaderVec::from_vec(headers),
    })
}
/// Generic HTTP request with an optional body — the single code path every
/// verb-specific helper in this module funnels through.
///
/// `content_type` is applied only when a body is present; explicit entries in
/// `config.headers` are applied afterwards and therefore win. To gzip a
/// request body, compress it yourself and pass
/// `HttpRequestConfig::with_header("Content-Encoding", "gzip")`.
///
/// Note that 4xx/5xx are returned as an `Ok(HttpResponse)` with the status
/// code set (the agent is built with `http_status_as_error(false)`); only
/// transport failures produce an `Err`.
///
/// # Errors
///
/// Returns an `HttpError` on DNS/connect/TLS/IO failure, on timeout, if the
/// response exceeds `config.max_response_size`, or if the `http` feature is
/// disabled.
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
pub fn http_request_with_config(
    method: HttpMethod,
    url: &str,
    body: Option<&[u8]>,
    content_type: &str,
    config: &HttpRequestConfig,
) -> HttpResult<HttpResponse> {
    // A pooled agent was built without this request's timeout, so every request
    // below sets it on itself; for a one-off agent that restates the same value.
    let agent = match &config.client {
        OptionHttpClient::Some(client) => client.ptr.agent.clone(),
        OptionHttpClient::None => {
            make_agent(config.timeout_secs, config.disable_tls_cert_verification)
        }
    };
    let timeout = Some(std::time::Duration::from_secs(config.timeout_secs));
    // ureq 3.x splits the request builder by typestate: `WithoutBody` for
    // GET/HEAD/DELETE (terminated by `.call()`) and `WithBody` for
    // POST/PUT/PATCH (terminated by `.send()`). The two are different types,
    // so the header application is written out per branch.
    let response = if method.takes_body() {
        let mut request = match method {
            HttpMethod::Put => agent.put(url),
            HttpMethod::Patch => agent.patch(url),
            // `takes_body()` admits only POST/PUT/PATCH here.
            _ => agent.post(url),
        };
        if !config.user_agent.as_str().is_empty() {
            request = request.header("User-Agent", config.user_agent.as_str());
        }
        if !content_type.is_empty() {
            request = request.header("Content-Type", content_type);
        }
        for header in config.headers.as_slice() {
            request = request.header(header.name.as_str(), header.value.as_str());
        }
        request
            .config()
            .timeout_global(timeout)
            .build()
            .send(body.unwrap_or(&[]))
            .map_err(|e| map_ureq_error(url, &e))?
    } else {
        let mut request = match method {
            HttpMethod::Head => agent.head(url),
            HttpMethod::Delete => agent.delete(url),
            // `takes_body()` admits only GET/HEAD/DELETE here.
            _ => agent.get(url),
        };
        if !config.user_agent.as_str().is_empty() {
            request = request.header("User-Agent", config.user_agent.as_str());
        }
        for header in config.headers.as_slice() {
            request = request.header(header.name.as_str(), header.value.as_str());
        }
        request
            .config()
            .timeout_global(timeout)
            .build()
            .call()
            .map_err(|e| map_ureq_error(url, &e))?
    };
    decode_response(response, config)
}
/// Stub: `http` feature disabled.
///
/// # Errors
///
/// Always returns an `HttpError` — the networking feature is disabled.
#[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
pub fn http_request_with_config(
    _method: HttpMethod,
    _url: &str,
    _body: Option<&[u8]>,
    _content_type: &str,
    _config: &HttpRequestConfig,
) -> HttpResult<HttpResponse> {
    Err(HttpError::other("http feature not enabled".into()))
}
/// HTTP GET request with custom configuration.
///
/// # Errors
///
/// See [`http_request_with_config`].
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
pub fn http_get_with_config(url: &str, config: &HttpRequestConfig) -> HttpResult<HttpResponse> {
    http_request_with_config(HttpMethod::Get, url, None, "", config)
}
/// Stub: `http` feature disabled.
#[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
/// # Errors
///
/// Returns an `HttpError` if the request fails (network/status error, or the networking feature is
/// disabled).
4
pub fn http_get_with_config(_url: &str, _config: &HttpRequestConfig) -> HttpResult<HttpResponse> {
4
    Err(HttpError::other("http feature not enabled".into()))
4
}
/// HTTP POST with the default configuration.
///
/// # Errors
///
/// See [`http_request_with_config`].
pub fn http_post(url: &str, body: &[u8], content_type: &str) -> HttpResult<HttpResponse> {
    http_post_with_config(url, body, content_type, &HttpRequestConfig::default())
}
/// HTTP POST with custom configuration.
///
/// This is the transport under the telemetry uploader (OTLP/HTTP JSON), crash
/// bundle upload and the update-manifest fetch.
///
/// # Errors
///
/// See [`http_request_with_config`].
pub fn http_post_with_config(
    url: &str,
    body: &[u8],
    content_type: &str,
    config: &HttpRequestConfig,
) -> HttpResult<HttpResponse> {
    http_request_with_config(HttpMethod::Post, url, Some(body), content_type, config)
}
/// HTTP PUT with custom configuration.
///
/// # Errors
///
/// See [`http_request_with_config`].
pub fn http_put_with_config(
    url: &str,
    body: &[u8],
    content_type: &str,
    config: &HttpRequestConfig,
) -> HttpResult<HttpResponse> {
    http_request_with_config(HttpMethod::Put, url, Some(body), content_type, config)
}
/// Download a URL to bytes (convenience wrapper with default config)
///
/// # Arguments
/// * `url` - The URL to download
///
/// # Returns
/// * `HttpResult<U8Vec>` - The response body or an error
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
pub fn download_bytes(url: &str) -> HttpResult<U8Vec> {
    download_bytes_with_config(url, &HttpRequestConfig::default())
}
/// Stub: `http` feature disabled.
#[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
/// # Errors
///
/// Returns an `HttpError` if the request fails (network/status error, or the networking feature is
/// disabled).
4
pub fn download_bytes(_url: &str) -> HttpResult<U8Vec> {
4
    Err(HttpError::other("http feature not enabled".into()))
4
}
/// Download a URL to bytes with custom configuration
///
/// # Arguments
/// * `url` - The URL to download
/// * `config` - Request configuration (timeout, max size, etc.)
///
/// # Returns
/// * `HttpResult<U8Vec>` - The response body or an error
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
pub fn download_bytes_with_config(url: &str, config: &HttpRequestConfig) -> HttpResult<U8Vec> {
    let response = http_get_with_config(url, config)?;
    // Check for successful status
    if response.status_code >= 400 {
        return Err(HttpError::http_status(
            response.status_code,
            format!("HTTP error {}", response.status_code).into(),
        ));
    }
    Ok(response.body)
}
/// Stub: `http` feature disabled.
#[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
/// # Errors
///
/// Returns an `HttpError` if the request fails (network/status error, or the networking feature is
/// disabled).
4
pub fn download_bytes_with_config(_url: &str, _config: &HttpRequestConfig) -> HttpResult<U8Vec> {
4
    Err(HttpError::other("http feature not enabled".into()))
4
}
/// Check if a URL is reachable (HEAD request)
///
/// # Arguments
/// * `url` - The URL to check
///
/// # Returns
/// * `bool` - True if reachable (2xx status)
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
#[must_use]
pub fn is_url_reachable(url: &str) -> bool {
    const REACHABILITY_TIMEOUT_SECS: u64 = 10;
    let agent = make_agent(REACHABILITY_TIMEOUT_SECS, false);
    match agent.head(url).call() {
        Ok(resp) => {
            let code = resp.status().as_u16();
            (200..300).contains(&code)
        }
        Err(_) => false,
    }
}
/// Stub: `http` feature disabled.
#[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
#[must_use]
4
pub const fn is_url_reachable(_url: &str) -> bool {
4
    false
4
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
1
    fn test_http_request_config_default() {
1
        let config = HttpRequestConfig::default();
1
        assert_eq!(config.timeout_secs, 30);
1
        assert_eq!(config.max_response_size, 100 * 1024 * 1024);
1
        assert!(!config.user_agent.as_str().is_empty());
1
    }
    #[test]
1
    fn test_http_response_status_checks() {
1
        let response = HttpResponse {
1
            status_code: 200,
1
            body: U8Vec::from(Vec::new()),
1
            content_type: AzString::from(String::new()),
1
            content_length: 0,
1
            headers: HttpHeaderVec::from_const_slice(&[]),
1
        };
1
        assert!(response.is_success());
1
        assert!(!response.is_redirect());
1
        assert!(!response.is_client_error());
1
        assert!(!response.is_server_error());
1
    }
    #[test]
1
    fn test_http_error_constructors() {
1
        let err = HttpError::http_status(404, "Not Found".into());
1
        assert!(err.to_string().contains("404"));
1
        let err2 = HttpError::response_too_large(100, 200);
1
        assert!(err2.to_string().contains("200"));
1
    }
}
#[cfg(test)]
mod autotest_generated {
    use super::*;
    // =========================================================================
    // Shared fixtures
    //
    // Everything below is offline: the `http`-gated tests only touch URIs that
    // fail during URI parsing (no DNS lookup, no socket) or construct a ureq
    // agent without ever calling it.
    // =========================================================================
    /// 256 KiB of ASCII — used to check the constructors don't choke on big payloads.
    fn huge_ascii() -> String {
        "A".repeat(256 * 1024)
    }
    /// A string designed to break naive formatting / escaping.
    const NASTY: &str = "\u{0}\r\n\t\"{}{{}}%s%n\u{7f}héllo·🦀·\u{202e}\u{feff}";
    fn response_with_status(status_code: u16) -> HttpResponse {
        HttpResponse {
            status_code,
            body: U8Vec::from(Vec::new()),
            content_type: AzString::from("application/octet-stream"),
            content_length: 0,
            headers: HttpHeaderVec::from_const_slice(&[]),
        }
    }
    fn response_with_body(body: Vec<u8>) -> HttpResponse {
        HttpResponse {
            status_code: 200,
            body: U8Vec::from(body),
            content_type: AzString::from("text/plain"),
            content_length: 0,
            headers: HttpHeaderVec::from_const_slice(&[]),
        }
    }
    // =========================================================================
    // HttpError constructors (`other` category) — extreme AzString payloads
    // =========================================================================
    #[test]
    fn http_error_string_constructors_store_payload_verbatim() {
        for payload in ["", "http://example.com", NASTY, huge_ascii().as_str()] {
            let s = AzString::from(payload);
            assert_eq!(
                HttpError::invalid_url(s.clone()),
                HttpError::InvalidUrl(s.clone())
            );
            assert_eq!(
                HttpError::connection_failed(s.clone()),
                HttpError::ConnectionFailed(s.clone())
            );
            assert_eq!(
                HttpError::tls_error(s.clone()),
                HttpError::TlsError(s.clone())
            );
            assert_eq!(
                HttpError::io_error(s.clone()),
                HttpError::IoError(s.clone())
            );
            assert_eq!(HttpError::other(s.clone()), HttpError::Other(s.clone()));
            // The payload survives the round-trip through the enum untouched:
            // no truncation at NUL, no escaping, no normalization.
            match HttpError::invalid_url(s.clone()) {
                HttpError::InvalidUrl(inner) => assert_eq!(inner.as_str(), payload),
                other => panic!("wrong variant: {other:?}"),
            }
        }
    }
    #[test]
    fn http_error_variants_are_not_conflated() {
        let s = AzString::from("x");
        assert_ne!(
            HttpError::invalid_url(s.clone()),
            HttpError::other(s.clone())
        );
        assert_ne!(
            HttpError::tls_error(s.clone()),
            HttpError::io_error(s.clone())
        );
        assert_ne!(HttpError::connection_failed(s.clone()), HttpError::Timeout);
    }
    // =========================================================================
    // HttpError::http_status / response_too_large (`numeric` category)
    // =========================================================================
    #[test]
    fn http_status_accepts_full_u16_range_without_clamping() {
        // 0 and u16::MAX are not valid HTTP status codes, but the constructor is
        // a plain data carrier: it must store them as-is rather than clamp/panic.
        for code in [0_u16, 1, 99, 100, 200, 299, 400, 599, 600, 999, u16::MAX] {
            let err = HttpError::http_status(code, AzString::from("msg"));
            match err {
                HttpError::HttpStatus(ref e) => {
                    assert_eq!(e.status_code, code);
                    assert_eq!(e.message.as_str(), "msg");
                }
                ref other => panic!("wrong variant: {other:?}"),
            }
            // Display must render the raw number, never a saturated stand-in.
            assert!(err.to_string().contains(&code.to_string()));
        }
    }
    #[test]
    fn http_status_with_empty_and_huge_message() {
        let empty = HttpError::http_status(u16::MAX, AzString::from(""));
        assert_eq!(empty.to_string(), "HTTP 65535 - ");
        let big = huge_ascii();
        let huge = HttpError::http_status(0, AzString::from(big.as_str()));
        assert_eq!(huge.to_string().len(), "HTTP 0 - ".len() + big.len());
    }
    #[test]
    fn response_too_large_stores_both_sizes_at_u64_limits() {
        // Includes the nonsensical actual < max ordering: the constructor performs
        // no validation and no arithmetic, so nothing can overflow here.
        for (max, actual) in [
            (0_u64, 0_u64),
            (0, u64::MAX),
            (u64::MAX, 0),
            (u64::MAX, u64::MAX),
            (1, 1),
            (100, 200),
            (u64::MAX, u64::MAX - 1),
        ] {
            let err = HttpError::response_too_large(max, actual);
            match err {
                HttpError::ResponseTooLarge(ref e) => {
                    assert_eq!(e.max_size, max);
                    assert_eq!(e.actual_size, actual);
                }
                ref other => panic!("wrong variant: {other:?}"),
            }
            let msg = err.to_string();
            assert!(msg.contains(&actual.to_string()));
            assert!(msg.contains(&max.to_string()));
        }
    }
    // =========================================================================
    // Display impl (`serializer` category)
    // =========================================================================
    #[test]
    fn display_is_non_empty_for_every_variant() {
        let variants = [
            HttpError::invalid_url(AzString::from("u")),
            HttpError::connection_failed(AzString::from("c")),
            HttpError::Timeout,
            HttpError::tls_error(AzString::from("t")),
            HttpError::http_status(500, AzString::from("s")),
            HttpError::io_error(AzString::from("i")),
            HttpError::response_too_large(1, 2),
            HttpError::other(AzString::from("o")),
        ];
        for v in &variants {
            let s = v.to_string();
            assert!(!s.is_empty(), "empty Display for {v:?}");
        }
        assert_eq!(HttpError::Timeout.to_string(), "Request timed out");
    }
    #[test]
    fn display_does_not_interpret_the_payload_as_a_format_string() {
        // A payload full of `{}` / `%s` must be echoed literally — a Display impl
        // that re-formatted its own output would either panic or eat the braces.
        let err = HttpError::other(AzString::from("{} {0} {{}} %s %n"));
        assert_eq!(err.to_string(), "HTTP error: {} {0} {{}} %s %n");
    }
    #[test]
    fn display_preserves_nul_newlines_and_unicode() {
        let err = HttpError::invalid_url(AzString::from(NASTY));
        let s = err.to_string();
        assert!(s.starts_with("Invalid URL: "));
        assert!(s.ends_with(NASTY));
        assert!(s.contains('\u{0}'));
        assert!(s.contains('🦀'));
    }
    #[test]
    fn display_of_edge_numeric_values_does_not_panic() {
        assert_eq!(
            HttpError::http_status(u16::MAX, AzString::from("x")).to_string(),
            "HTTP 65535 - x"
        );
        assert_eq!(
            HttpError::response_too_large(u64::MAX, u64::MAX).to_string(),
            format!("Response too large: {} bytes (max: {})", u64::MAX, u64::MAX)
        );
        assert_eq!(
            HttpError::response_too_large(0, 0).to_string(),
            "Response too large: 0 bytes (max: 0)"
        );
    }
    // =========================================================================
    // HttpHeader::new (`constructor` category)
    // =========================================================================
    #[test]
    fn http_header_new_keeps_fields_exactly_as_given() {
        for (name, value) in [
            ("", ""),
            ("Content-Type", "text/html; charset=utf-8"),
            (NASTY, NASTY),
            (huge_ascii().as_str(), ""),
            ("", huge_ascii().as_str()),
        ] {
            let h = HttpHeader::new(name, value);
            assert_eq!(h.name.as_str(), name);
            assert_eq!(h.value.as_str(), value);
        }
    }
    #[test]
    fn http_header_new_does_not_sanitize_crlf() {
        // Documented behaviour, not an endorsement: HttpHeader is a dumb pair, so a
        // CRLF-bearing name is stored verbatim. Rejecting it is the transport's job
        // (ureq validates at request time) — assert the value is at least not
        // silently truncated at the newline, which would hide the injection attempt.
        let h = HttpHeader::new("X-Evil\r\nInjected: 1", "v\r\nSet-Cookie: pwned=1");
        assert_eq!(h.name.as_str(), "X-Evil\r\nInjected: 1");
        assert_eq!(h.value.as_str(), "v\r\nSet-Cookie: pwned=1");
    }
    #[test]
    fn http_header_new_accepts_string_and_str() {
        let from_str = HttpHeader::new("a", "b");
        let from_string = HttpHeader::new(String::from("a"), String::from("b"));
        assert_eq!(from_str, from_string);
    }
    // =========================================================================
    // HttpRequestConfig builders (`constructor` category)
    // =========================================================================
    #[test]
    fn config_new_matches_default_and_documented_values() {
        let a = HttpRequestConfig::new();
        let b = HttpRequestConfig::default();
        assert_eq!(a.timeout_secs, b.timeout_secs);
        assert_eq!(a.max_response_size, b.max_response_size);
        assert_eq!(a.user_agent.as_str(), b.user_agent.as_str());
        assert_eq!(a.headers.len(), b.headers.len());
        assert_eq!(
            a.disable_tls_cert_verification,
            b.disable_tls_cert_verification
        );
        assert_eq!(a.timeout_secs, 30);
        assert_eq!(a.max_response_size, 100 * 1024 * 1024);
        assert!(a.headers.is_empty());
        // Secure by default: certificate verification must be ON unless opted out.
        assert!(!a.disable_tls_cert_verification);
    }
    #[test]
    fn with_timeout_stores_extremes_verbatim() {
        for secs in [0_u64, 1, 30, u64::MAX / 2, u64::MAX - 1, u64::MAX] {
            let cfg = HttpRequestConfig::new().with_timeout(secs);
            assert_eq!(cfg.timeout_secs, secs);
            // Nothing else may be disturbed by the setter.
            assert_eq!(cfg.max_response_size, 100 * 1024 * 1024);
            assert!(cfg.headers.is_empty());
        }
    }
    #[test]
    fn with_max_size_stores_extremes_verbatim() {
        for max in [0_u64, 1, u64::MAX] {
            let cfg = HttpRequestConfig::new().with_max_size(max);
            assert_eq!(cfg.max_response_size, max);
            assert_eq!(cfg.timeout_secs, 30);
        }
        // 0 is the documented "unlimited" sentinel, not a "reject everything" limit.
        assert_eq!(
            HttpRequestConfig::new().with_max_size(0).max_response_size,
            0
        );
    }
    #[test]
    fn builder_setters_are_last_write_wins_and_independent() {
        let cfg = HttpRequestConfig::new()
            .with_timeout(1)
            .with_timeout(u64::MAX)
            .with_max_size(5)
            .with_max_size(0)
            .with_user_agent("first")
            .with_user_agent("second");
        assert_eq!(cfg.timeout_secs, u64::MAX);
        assert_eq!(cfg.max_response_size, 0);
        assert_eq!(cfg.user_agent.as_str(), "second");
    }
    #[test]
    fn with_user_agent_accepts_empty_and_extreme_values() {
        let empty = HttpRequestConfig::new().with_user_agent("");
        // Empty UA is meaningful: http_get_with_config skips the header entirely.
        assert!(empty.user_agent.as_str().is_empty());
        let unicode = HttpRequestConfig::new().with_user_agent(NASTY);
        assert_eq!(unicode.user_agent.as_str(), NASTY);
        let big = huge_ascii();
        let huge = HttpRequestConfig::new().with_user_agent(big.clone());
        assert_eq!(huge.user_agent.as_str().len(), big.len());
    }
    #[test]
    fn with_header_appends_in_order_and_keeps_duplicates() {
        let mut cfg = HttpRequestConfig::new();
        assert!(cfg.headers.is_empty());
        for i in 0..100_usize {
            cfg = cfg.with_header(format!("H{i}"), format!("v{i}"));
        }
        // Duplicate names are kept, not deduplicated or overwritten.
        cfg = cfg.with_header("H0", "second-value");
        assert_eq!(cfg.headers.len(), 101);
        let slice = cfg.headers.as_slice();
        for (i, h) in slice.iter().take(100).enumerate() {
            assert_eq!(h.name.as_str(), format!("H{i}"));
            assert_eq!(h.value.as_str(), format!("v{i}"));
        }
        assert_eq!(slice[100].name.as_str(), "H0");
        assert_eq!(slice[100].value.as_str(), "second-value");
    }
    #[test]
    fn with_header_accepts_empty_name_and_value() {
        let cfg = HttpRequestConfig::new().with_header("", "");
        assert_eq!(cfg.headers.len(), 1);
        assert!(cfg.headers.as_slice()[0].name.as_str().is_empty());
        assert!(cfg.headers.as_slice()[0].value.as_str().is_empty());
    }
    #[test]
    fn cloning_a_config_gives_an_independent_header_vec() {
        // The header vec is an FFI vec with a destructor field; a shallow clone that
        // aliased the original's buffer would show up here (and later double-free).
        let base = HttpRequestConfig::new().with_header("A", "1");
        let cloned = base.clone().with_header("B", "2");
        assert_eq!(base.headers.len(), 1);
        assert_eq!(cloned.headers.len(), 2);
        assert_eq!(base.headers.as_slice()[0].name.as_str(), "A");
        assert_eq!(cloned.headers.as_slice()[0].name.as_str(), "A");
        assert_eq!(cloned.headers.as_slice()[1].name.as_str(), "B");
        drop(cloned);
        // `base` must still be readable after the clone is dropped.
        assert_eq!(base.headers.as_slice()[0].value.as_str(), "1");
    }
    // =========================================================================
    // HttpResponse predicates (`predicate` category)
    // =========================================================================
    #[test]
    fn status_predicates_at_class_boundaries() {
        let cases: &[(u16, bool, bool, bool, bool)] = &[
            // status, success, redirect, client_err, server_err
            (0, false, false, false, false),
            (100, false, false, false, false),
            (199, false, false, false, false),
            (200, true, false, false, false),
            (204, true, false, false, false),
            (299, true, false, false, false),
            (300, false, true, false, false),
            (399, false, true, false, false),
            (400, false, false, true, false),
            (499, false, false, true, false),
            (500, false, false, false, true),
            (599, false, false, false, true),
            (600, false, false, false, false),
            (999, false, false, false, false),
            (u16::MAX, false, false, false, false),
        ];
        for &(status, success, redirect, client, server) in cases {
            let r = response_with_status(status);
            assert_eq!(r.is_success(), success, "is_success({status})");
            assert_eq!(r.is_redirect(), redirect, "is_redirect({status})");
            assert_eq!(r.is_client_error(), client, "is_client_error({status})");
            assert_eq!(r.is_server_error(), server, "is_server_error({status})");
        }
    }
    #[test]
    fn status_predicates_are_mutually_exclusive_over_the_whole_u16_range() {
        let mut r = response_with_status(0);
        for status in 0..=u16::MAX {
            r.status_code = status;
            let hits = u8::from(r.is_success())
                + u8::from(r.is_redirect())
                + u8::from(r.is_client_error())
                + u8::from(r.is_server_error());
            assert!(hits <= 1, "status {status} matched {hits} classes");
            // Exactly one class must match inside 200..=599, and none outside it.
            let expected = u8::from((200_u16..600_u16).contains(&status));
            assert_eq!(hits, expected, "status {status}");
        }
    }
    #[test]
    fn status_predicates_ignore_body_and_headers() {
        let mut r = response_with_body(vec![0xFF; 1024]);
        r.status_code = 503;
        r.content_length = u64::MAX;
        r.headers = HttpHeaderVec::from_vec(vec![HttpHeader::new("X", "Y")]);
        assert!(r.is_server_error());
        assert!(!r.is_success());
    }
    // =========================================================================
    // HttpResponse::body_as_string (`getter` category)
    // =========================================================================
    #[test]
    fn body_as_string_on_empty_body_is_some_empty_string() {
        let r = response_with_body(Vec::new());
        let s = r.body_as_string().expect("empty body is valid UTF-8");
        assert_eq!(s.as_str(), "");
    }
    #[test]
    fn body_as_string_round_trips_valid_utf8() {
        for text in ["hello", NASTY, "🦀🦀🦀", "a\u{0}b"] {
            let r = response_with_body(text.as_bytes().to_vec());
            let s = r.body_as_string().expect("valid UTF-8 must decode");
            assert_eq!(s.as_str(), text);
            assert_eq!(s.as_str().len(), text.len());
        }
    }
    #[test]
    fn body_as_string_returns_none_for_invalid_utf8() {
        let invalid: &[&[u8]] = &[
            &[0xFF],                   // never valid
            &[0x80],                   // lone continuation byte
            &[0xC3],                   // truncated 2-byte sequence
            &[0xE2, 0x82],             // truncated 3-byte sequence
            &[0xED, 0xA0, 0x80],       // UTF-16 surrogate half (CESU-8)
            &[0xF4, 0x90, 0x80, 0x80], // above U+10FFFF
            &[0xC0, 0x80],             // overlong NUL
            &[b'o', b'k', 0xFE, b'!'], // valid prefix, invalid tail
        ];
        for bytes in invalid {
            let r = response_with_body(bytes.to_vec());
            assert!(
                r.body_as_string().is_none(),
                "expected None for {bytes:02X?}"
            );
        }
    }
    #[test]
    fn body_as_string_is_pure_and_repeatable() {
        let r = response_with_body(b"payload".to_vec());
        let first = r.body_as_string();
        let second = r.body_as_string();
        assert_eq!(first, second);
        // The getter must not consume or mutate the body.
        assert_eq!(r.body.as_slice(), &b"payload"[..]);
    }
    #[test]
    fn body_as_string_ignores_a_lying_content_length() {
        // content_length is untrusted server metadata and is not an invariant of
        // `body`; the decoder must go by the actual byte slice.
        let mut r = response_with_body(b"1234".to_vec());
        r.content_length = u64::MAX;
        assert_eq!(r.body_as_string().expect("valid").as_str(), "1234");
        r.content_length = 0;
        assert_eq!(r.body_as_string().expect("valid").as_str(), "1234");
    }
    #[test]
    fn body_as_string_handles_a_large_body() {
        let big = huge_ascii();
        let r = response_with_body(big.clone().into_bytes());
        let s = r.body_as_string().expect("ASCII is valid UTF-8");
        assert_eq!(s.as_str().len(), big.len());
    }
    // =========================================================================
    // FFI result round-trips (encode == decode)
    // =========================================================================
    #[test]
    fn result_http_response_round_trips_through_the_ffi_enum() {
        let ok: Result<HttpResponse, HttpError> = Ok(response_with_status(200));
        let ffi: ResultHttpResponseHttpError = ok.clone().into();
        assert!(ffi.is_ok());
        assert!(!ffi.is_err());
        assert_eq!(ffi.into_result(), ok);
        let err: Result<HttpResponse, HttpError> =
            Err(HttpError::http_status(u16::MAX, AzString::from(NASTY)));
        let ffi: ResultHttpResponseHttpError = err.clone().into();
        assert!(ffi.is_err());
        assert!(!ffi.is_ok());
        assert_eq!(ffi.into_result(), err);
    }
    #[test]
    fn result_u8vec_round_trips_through_the_ffi_enum() {
        let ok: Result<U8Vec, HttpError> = Ok(U8Vec::from(vec![0u8, 0xFF, 0x7F]));
        let ffi: ResultU8VecHttpError = ok.clone().into();
        assert!(ffi.is_ok());
        assert_eq!(ffi.into_result(), ok);
        let err: Result<U8Vec, HttpError> = Err(HttpError::response_too_large(0, u64::MAX));
        let ffi: ResultU8VecHttpError = err.clone().into();
        assert!(ffi.is_err());
        assert_eq!(ffi.into_result(), err);
        // An empty Ok payload must stay Ok — not collapse into Err.
        let empty: ResultU8VecHttpError = Ok(U8Vec::from(Vec::new())).into();
        assert!(empty.is_ok());
        assert_eq!(empty.as_result().map(|v| v.len()), Ok(0));
    }
    #[test]
    fn ffi_result_as_result_agrees_with_is_ok() {
        let ffi: ResultHttpResponseHttpError = Ok(response_with_status(404)).into();
        assert_eq!(ffi.is_ok(), ffi.as_result().is_ok());
        assert_eq!(ffi.as_result().map(HttpResponse::is_client_error), Ok(true));
    }
    // =========================================================================
    // `http` feature DISABLED — the stubs must fail closed
    // =========================================================================
    #[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
    #[test]
    fn stub_free_functions_return_err_for_any_url() {
        for url in ["", "https://example.com", NASTY, huge_ascii().as_str()] {
            let cfg = HttpRequestConfig::new();
            assert!(matches!(http_get(url), Err(HttpError::Other(_))));
            assert!(matches!(
                http_get_with_config(url, &cfg),
                Err(HttpError::Other(_))
            ));
            assert!(matches!(download_bytes(url), Err(HttpError::Other(_))));
            assert!(matches!(
                download_bytes_with_config(url, &cfg),
                Err(HttpError::Other(_))
            ));
        }
    }
    #[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
    #[test]
    fn stub_is_url_reachable_is_always_false() {
        // Fails closed: a disabled HTTP stack must never claim a URL is reachable.
        for url in ["", "https://example.com", NASTY, huge_ascii().as_str()] {
            assert!(!is_url_reachable(url));
            let (reachable, error) =
                HttpRequestConfig::new().is_url_reachable_blocking(AzString::from(url));
            assert!(!reachable);
            assert!(error.is_some(), "the stub must say why it answered false");
        }
    }
    #[cfg(any(not(feature = "http"), target_arch = "wasm32"))]
    #[test]
    fn stub_config_methods_return_err_results() {
        let cfg = HttpRequestConfig::new()
            .with_timeout(u64::MAX)
            .with_max_size(0);
        for url in ["", "https://example.com", NASTY] {
            let u = AzString::from(url);
            assert!(HttpRequestConfig::new()
                .http_get_blocking(u.clone())
                .is_err());
            assert!(cfg.http_get_blocking(u.clone()).is_err());
            assert!(HttpRequestConfig::new()
                .download_bytes_blocking(u.clone())
                .is_err());
            assert!(cfg.download_bytes_blocking(u.clone()).is_err());
        }
    }
    // =========================================================================
    // `http` feature ENABLED — offline-only checks
    // =========================================================================
    #[cfg(all(feature = "http", not(target_arch = "wasm32")))]
    #[test]
    fn make_agent_builds_at_timeout_extremes() {
        // Duration::from_secs(u64::MAX) is representable, so agent construction must
        // not panic at either end of the range (the agent is never called here).
        for secs in [0_u64, 1, 30, u64::MAX] {
            for disable_tls in [false, true] {
                let _agent = make_agent(secs, disable_tls);
            }
        }
    }
    #[cfg(all(feature = "http", not(target_arch = "wasm32")))]
    #[test]
    fn malformed_urls_are_rejected_without_touching_the_network() {
        // Each of these fails in ureq's URI parser: no DNS resolution, no socket.
        let cfg = HttpRequestConfig::new().with_timeout(1);
        for url in ["", "not a url", "://no-scheme", "ht tp://spaces"] {
            assert!(http_get(url).is_err(), "expected Err for {url:?}");
            assert!(
                http_get_with_config(url, &cfg).is_err(),
                "expected Err for {url:?}"
            );
            assert!(download_bytes(url).is_err(), "expected Err for {url:?}");
            assert!(!is_url_reachable(url), "expected false for {url:?}");
        }
    }
    #[cfg(all(feature = "http", not(target_arch = "wasm32")))]
    #[test]
    fn malformed_urls_are_rejected_through_the_ffi_wrappers() {
        let cfg = HttpRequestConfig::new().with_timeout(1);
        for url in ["", "not a url"] {
            let u = AzString::from(url);
            assert!(HttpRequestConfig::new()
                .http_get_blocking(u.clone())
                .is_err());
            assert!(cfg.http_get_blocking(u.clone()).is_err());
            assert!(HttpRequestConfig::new()
                .download_bytes_blocking(u.clone())
                .is_err());
            assert!(cfg.download_bytes_blocking(u.clone()).is_err());
            let (reachable, error) = cfg.is_url_reachable_blocking(u.clone());
            assert!(!reachable);
            assert!(error.is_some());
        }
    }
    // The resumable form parks the answer in the runtime queue instead of
    // returning it: the request id is valid and exactly one completion
    // carrying the typed result struct is waiting to be delivered.
    #[cfg(all(feature = "http", not(target_arch = "wasm32"), feature = "text_layout"))]
    #[test]
    fn resumable_requests_park_their_result_in_the_queue() {
        use azul_core::refany::RefAny;
        extern "C" fn noop(
            _: RefAny,
            _: crate::callbacks::CallbackInfo,
            _: RefAny,
        ) -> azul_core::callbacks::Update {
            azul_core::callbacks::Update::DoNothing
        }
        let _ = crate::request::take_completed();
        let cfg = HttpRequestConfig::new().with_timeout(1);
        let id = cfg.http_get(
            AzString::from("not a url"),
            RefAny::new(()),
            crate::callbacks::ResumeCallback::create(noop),
        );
        assert!(id.is_valid());
        let mut completed = crate::request::take_completed();
        assert_eq!(completed.len(), 1);
        let entry = completed.remove(0);
        assert_eq!(entry.request_id, id);
        let answer = HttpGetResult::downcast(entry.result)
            .into_option()
            .expect("an HttpGetResult");
        assert!(answer.result.is_err());
    }
}
#[cfg(all(test, feature = "http", not(target_arch = "wasm32")))]
mod client_pool_tests {
    use std::{
        io::{BufRead, BufReader, Write},
        net::TcpListener,
        sync::{
            atomic::{AtomicUsize, Ordering},
            Arc,
        },
    };
    use super::*;
    /// A keep-alive HTTP/1.1 server on localhost that counts the connections it
    /// accepts. It serves one connection at a time until the client closes it.
    fn serve() -> (String, Arc<AtomicUsize>) {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
        let url = format!("http://{}/", listener.local_addr().expect("addr"));
        let accepted = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&accepted);
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(mut stream) = stream else { return };
                counter.fetch_add(1, Ordering::SeqCst);
                let mut reader = BufReader::new(stream.try_clone().expect("clone"));
                while read_request_head(&mut reader) {
                    let reply = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nContent-Type: text/plain\r\n\r\nok";
                    if stream.write_all(reply).is_err() {
                        break;
                    }
                }
            }
        });
        (url, accepted)
    }
    /// Consume one request head; false once the client has closed the connection.
    fn read_request_head(reader: &mut impl BufRead) -> bool {
        let mut line = String::new();
        loop {
            line.clear();
            match reader.read_line(&mut line) {
                Ok(0) | Err(_) => return false,
                Ok(_) if line == "\r\n" => return true,
                Ok(_) => {}
            }
        }
    }
    fn get_three_times(url: &str, config: &HttpRequestConfig) {
        for _ in 0..3 {
            let response = http_get_with_config(url, config).expect("GET");
            assert_eq!(response.status_code, 200);
            assert_eq!(response.body.as_ref(), b"ok");
        }
    }
    #[test]
    fn requests_through_a_client_reuse_one_connection() {
        let (url, accepted) = serve();
        let client = HttpClient::create(HttpClientConfig::default());
        get_three_times(
            &url,
            &HttpRequestConfig::default()
                .with_timeout(5)
                .with_client(client),
        );
        assert_eq!(accepted.load(Ordering::SeqCst), 1);
    }
    /// Answers every host with 127.0.0.1:`port`, counting how often it is asked.
    #[derive(Debug)]
    struct CountingResolver {
        port: u16,
        calls: Arc<AtomicUsize>,
    }
    impl ureq::unversioned::resolver::Resolver for CountingResolver {
        fn resolve(
            &self,
            _uri: &ureq::http::Uri,
            _config: &ureq::config::Config,
            _timeout: ureq::unversioned::transport::NextTimeout,
        ) -> Result<ureq::unversioned::resolver::ResolvedSocketAddrs, ureq::Error> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            let mut out = self.empty();
            out.push(std::net::SocketAddr::from(([127, 0, 0, 1], self.port)));
            Ok(out)
        }
    }
    /// A client for a host name only `CountingResolver` knows, so every lookup
    /// the client makes is counted.
    fn counted_client(
        agent: impl FnOnce(CountingResolver) -> ureq::Agent,
    ) -> (String, Arc<AtomicUsize>) {
        let (url, _) = serve();
        let port: u16 = url
            .trim_end_matches('/')
            .rsplit(':')
            .next()
            .and_then(|p| p.parse().ok())
            .expect("port");
        let calls = Arc::new(AtomicUsize::new(0));
        let client = HttpClient {
            ptr: Box::new(Arc::new(HttpClientInner {
                config: HttpClientConfig::default(),
                agent: agent(CountingResolver {
                    port,
                    calls: Arc::clone(&calls),
                }),
            })),
            run_destructor: true,
        };
        let config = HttpRequestConfig::default()
            .with_timeout(5)
            .with_client(client);
        get_three_times(&format!("http://tiles.azul.invalid:{port}/"), &config);
        (url, calls)
    }
    #[test]
    fn a_client_without_a_dns_cache_looks_the_host_up_for_every_request() {
        let config = HttpClientConfig::default();
        let (_, calls) = counted_client(|resolver| client_agent(&config, resolver));
        assert_eq!(calls.load(Ordering::SeqCst), 3);
    }
    #[test]
    fn a_client_with_a_dns_cache_looks_the_host_up_once() {
        let config = HttpClientConfig::default().with_dns_cache_secs(60);
        let (_, calls) = counted_client(|resolver| client_agent(&config, resolver));
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }
    #[test]
    fn an_expired_dns_answer_is_looked_up_again() {
        let (_, calls) = counted_client(|resolver| {
            ureq::Agent::with_parts(
                agent_config(false).build(),
                ureq::unversioned::transport::DefaultConnector::default(),
                CachingResolver::new(resolver, std::time::Duration::ZERO),
            )
        });
        assert_eq!(calls.load(Ordering::SeqCst), 3);
    }
    #[test]
    fn requests_without_a_client_each_open_a_connection() {
        let (url, accepted) = serve();
        get_three_times(&url, &HttpRequestConfig::default().with_timeout(5));
        assert_eq!(accepted.load(Ordering::SeqCst), 3);
    }
}