open-net 0.3.5

A cross-platform async networking library for Rust with HTTP and WebSocket clients, network status monitoring, configurable retries, WebSocket reconnection and heartbeats, and managed client lifecycles. Reuse common networking infrastructure across applications to avoid repeated implementation and debugging, helping save development time and AI coding tokens.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
use crate::api::error::NetError;
#[cfg(feature = "http-client-cookies")]
use crate::api::http::cookies::CookieRequestContext;
#[cfg(feature = "http-client-codecs")]
use crate::api::http::multipart::Multipart;
#[cfg(feature = "http-client-codecs")]
use crate::api::http::request_codecs::{
    append_query, encode_form, encode_json, encode_query, ensure_body_slot,
    set_default_content_type, validate_multipart_header, BodyEncoding,
};
use crate::api::http::retry::HttpRetryPolicy;
use crate::api::http::{HttpAdmissionPolicy, HttpTimeouts};
use crate::api::retry::RetrySetting;
use bytes::Bytes;
use http::{HeaderMap, HeaderName, HeaderValue, Method};

#[derive(Clone)]
/// A concrete HTTP request accepted by [`crate::api::http::HttpClient`].
///
/// Requests own their method, relative path, headers, body, and retry policy.
/// Use [`HttpRequest::builder`] to validate the path and construct one without
/// relying on unchecked field combinations.
///
/// `Debug` reports diagnostic settings and sizes, omitting the path, header
/// names and values, and body contents in every HTTP feature combination.
/// The public fields retain the original values for explicit access.
///
/// Concrete requests return their responses through the Future API:
///
/// ```no_run
/// use open_net::api::error::NetError;
/// use open_net::api::http::{HttpClient, HttpRequest};
///
/// async fn fetch(client: &HttpClient) -> Result<(), NetError> {
///     let request = HttpRequest::builder().path("/status").build()?;
///     let response = client.request(request).await?;
///     let _ = response;
///     Ok(())
/// }
/// ```
///
/// A concrete request intentionally does not implement
/// [`crate::api::http::HttpRequestTrait`]. Callback entry points require a custom
/// request type that owns its response handler:
///
/// ```compile_fail
/// use open_net::api::error::NetError;
/// use open_net::api::http::{HttpClient, HttpRequest};
///
/// fn submit(client: &HttpClient) -> Result<(), NetError> {
///     let request = HttpRequest::builder().path("/status").build()?;
///     let _ = client.send(request);
///     Ok(())
/// }
/// ```
pub struct HttpRequest {
    /// HTTP method used for the request.
    pub method: Method,
    /// Relative path resolved against [`crate::api::http::HttpClientConfig::base_url`].
    pub path: String,
    /// Request headers merged over the client's common headers.
    pub headers: HeaderMap,
    /// Owned request body bytes.
    pub body: Bytes,
    /// SameSite context used when the configured Cookie store is queried.
    #[cfg(feature = "http-client-cookies")]
    pub(crate) cookie_context: CookieRequestContext,
    /// Whether this request inherits the client policy or carries an explicit override.
    pub(crate) retry_setting: RetrySetting<HttpRetryPolicy>,
    pub(crate) timeouts: HttpTimeouts,
    admission_policy: Option<HttpAdmissionPolicy>,
}

impl std::fmt::Debug for HttpRequest {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("HttpRequest")
            .field("method", &self.method)
            .field("path_bytes", &self.path.len())
            .field("header_count", &self.headers.len())
            .field("body_bytes", &self.body.len())
            .field("retry_setting", &self.retry_setting)
            .field("timeouts", &self.timeouts)
            .field("admission_policy", &self.admission_policy)
            .finish_non_exhaustive()
    }
}

/// Fluent builder for a validated [`HttpRequest`].
///
/// The builder starts with `GET`, an empty relative path, no headers, an empty
/// body, and inherited retry and admission settings. `build` rejects an empty path; the
/// client performs same-origin validation when the request is submitted.
pub struct HttpRequestBuilder {
    method: Result<Method, NetError>,
    path: String,
    headers: HeaderMap,
    body: Bytes,
    retry_setting: RetrySetting<HttpRetryPolicy>,
    timeouts: HttpTimeouts,
    admission_policy: Option<HttpAdmissionPolicy>,
    #[cfg(feature = "http-client-cookies")]
    cookie_context: CookieRequestContext,
    #[cfg(feature = "http-client-codecs")]
    body_configured: bool,
    #[cfg(feature = "http-client-codecs")]
    body_encoding: Option<BodyEncoding>,
    #[cfg(feature = "http-client-codecs")]
    body_conflict: bool,
    #[cfg(feature = "http-client-codecs")]
    multipart_content_type: Option<HeaderValue>,
    #[cfg(feature = "http-client-codecs")]
    query_parts: Vec<String>,
}

impl HttpRequest {
    /// Start constructing a request with safe defaults.
    pub fn builder() -> HttpRequestBuilder {
        HttpRequestBuilder {
            method: Ok(Method::GET),
            path: String::new(),
            headers: HeaderMap::new(),
            body: Bytes::new(),
            retry_setting: RetrySetting::Inherit,
            timeouts: HttpTimeouts::new(),
            admission_policy: None,
            #[cfg(feature = "http-client-cookies")]
            cookie_context: CookieRequestContext::default(),
            #[cfg(feature = "http-client-codecs")]
            body_configured: false,
            #[cfg(feature = "http-client-codecs")]
            body_encoding: None,
            #[cfg(feature = "http-client-codecs")]
            body_conflict: false,
            #[cfg(feature = "http-client-codecs")]
            multipart_content_type: None,
            #[cfg(feature = "http-client-codecs")]
            query_parts: Vec::new(),
        }
    }

    /// Return the explicit overrides installed when this request was built.
    pub fn timeouts(&self) -> &HttpTimeouts {
        &self.timeouts
    }

    /// Return this request's capacity policy override, or `None` to inherit the client.
    pub fn admission_policy_override(&self) -> Option<HttpAdmissionPolicy> {
        self.admission_policy
    }

    pub fn retry_setting(&self) -> RetrySetting<HttpRetryPolicy> {
        self.retry_setting.clone()
    }
}

impl HttpRequestBuilder {
    /// Override the client's capacity policy for this response-returning request.
    ///
    /// The policy and timeout budgets are resolved when the response Future is
    /// first polled, before middleware runs. Middleware cannot alter the admission
    /// policy of an operation that has already been accepted.
    pub fn admission_policy(mut self, policy: HttpAdmissionPolicy) -> Self {
        self.admission_policy = Some(policy);
        self
    }

    /// Replace all timeout overrides for this request; `build` validates durations.
    pub fn timeouts(mut self, timeouts: HttpTimeouts) -> Self {
        self.timeouts = timeouts;
        self
    }

    /// Set the HTTP method.
    ///
    /// Invalid methods are reported by [`Self::build`] as input errors. A later
    /// call replaces the previous method, including any conversion error.
    pub fn method(mut self, method: impl TryInto<Method>) -> Self {
        self.method = method
            .try_into()
            .map_err(|_| NetError::input("method", "invalid HTTP method token"));
        self
    }
    /// Set the relative request path.
    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.path = path.into();
        #[cfg(feature = "http-client-codecs")]
        for query in &self.query_parts {
            append_query(&mut self.path, query);
        }
        self
    }
    /// Replace all request-specific headers.
    pub fn headers(mut self, headers: HeaderMap) -> Self {
        self.headers = headers;
        self
    }
    /// Set the owned request body.
    pub fn body(mut self, body: Bytes) -> Self {
        #[cfg(feature = "http-client-codecs")]
        {
            if self
                .body_encoding
                .is_some_and(|encoding| encoding != BodyEncoding::Raw)
            {
                self.body_conflict = true;
            }
            self.body_encoding = Some(BodyEncoding::Raw);
            self.body_configured = true;
            self.multipart_content_type = None;
        }
        self.body = body;
        self
    }

    #[cfg(feature = "http-client-codecs")]
    /// Append a serde value to the request target query string.
    pub fn query<T: serde::Serialize>(mut self, value: &T) -> Result<Self, NetError> {
        let encoded = encode_query(value)?;
        append_query(&mut self.path, &encoded);
        if !encoded.is_empty() {
            self.query_parts.push(encoded);
        }
        Ok(self)
    }

    #[cfg(feature = "http-client-codecs")]
    /// Serialize a value as a JSON request body.
    pub fn json<T: serde::Serialize>(mut self, value: &T) -> Result<Self, NetError> {
        ensure_body_slot(self.body_encoding, BodyEncoding::Json)?;
        if self.body_configured {
            return Err(crate::api::error::NetError::input(
                "body",
                "a request body is already configured",
            ));
        }
        self.body = Bytes::from(encode_json(value)?);
        set_default_content_type(&mut self.headers, "application/json")?;
        self.body_configured = true;
        self.body_encoding = Some(BodyEncoding::Json);
        Ok(self)
    }

    #[cfg(feature = "http-client-codecs")]
    /// Serialize a value as an `application/x-www-form-urlencoded` body.
    pub fn form<T: serde::Serialize>(mut self, value: &T) -> Result<Self, NetError> {
        ensure_body_slot(self.body_encoding, BodyEncoding::Form)?;
        if self.body_configured {
            return Err(crate::api::error::NetError::input(
                "body",
                "a request body is already configured",
            ));
        }
        self.body = Bytes::from(encode_form(value)?);
        set_default_content_type(&mut self.headers, "application/x-www-form-urlencoded")?;
        self.body_configured = true;
        self.body_encoding = Some(BodyEncoding::Form);
        Ok(self)
    }

    #[cfg(feature = "http-client-codecs")]
    /// Encode a buffered multipart form body with an SDK-owned boundary.
    pub fn multipart(mut self, value: Multipart) -> Result<Self, NetError> {
        ensure_body_slot(self.body_encoding, BodyEncoding::Multipart)?;
        if self.body_configured || self.headers.contains_key(http::header::CONTENT_TYPE) {
            return Err(crate::api::error::NetError::input(
                "body",
                "multipart requires an unused body and SDK-owned content-type",
            ));
        }
        let (body, content_type) = value.encode()?;
        validate_multipart_header(&self.headers, &content_type)?;
        self.body = body;
        self.headers
            .insert(http::header::CONTENT_TYPE, content_type.clone());
        self.body_configured = true;
        self.body_encoding = Some(BodyEncoding::Multipart);
        self.multipart_content_type = Some(content_type);
        Ok(self)
    }
    /// Set the retry policy carried by the request.
    /// Inherit, disable, or replace the client retry policy for this request.
    pub fn retry_setting(mut self, setting: RetrySetting<HttpRetryPolicy>) -> Self {
        self.retry_setting = setting;
        self
    }

    #[cfg(feature = "http-client-cookies")]
    pub fn cookie_context(mut self, context: CookieRequestContext) -> Self {
        self.cookie_context = context;
        self
    }

    /// Insert or replace one request header.
    ///
    /// Header names and values are validated by the `http` crate. This method
    /// returns an input error without consuming the partially built request
    /// when conversion fails.
    pub fn header(
        mut self,
        name: impl TryInto<HeaderName>,
        value: impl TryInto<HeaderValue>,
    ) -> Result<Self, NetError> {
        let name = name
            .try_into()
            .map_err(|_| NetError::input("header", "invalid name"))?;
        let value = value
            .try_into()
            .map_err(|_| NetError::input("header", "invalid value"))?;
        #[cfg(feature = "http-client-codecs")]
        if name == http::header::CONTENT_TYPE {
            if let Some(expected) = &self.multipart_content_type {
                if value != expected {
                    return Err(NetError::input(
                        "content-type",
                        "multipart content-type is managed by the SDK",
                    ));
                }
            }
        }
        self.headers.insert(name, value);
        Ok(self)
    }

    /// Validate the method and path and produce an owned request value.
    ///
    /// Method tokens, timeout durations and the nonempty path are checked here;
    /// the client later rejects absolute, cross-origin, or otherwise unsafe paths.
    pub fn build(self) -> Result<HttpRequest, NetError> {
        let method = self.method?;
        self.timeouts.validate_request()?;
        if self.path.is_empty() {
            return Err(NetError::input("path", "path must not be empty"));
        }
        #[cfg(feature = "http-client-codecs")]
        {
            if self.body_conflict {
                return Err(NetError::input(
                    "body",
                    "raw body and a typed body codec cannot be combined",
                ));
            }
            if let Some(expected) = &self.multipart_content_type {
                if self.headers.get(http::header::CONTENT_TYPE) != Some(expected) {
                    return Err(NetError::input(
                        "content-type",
                        "multipart content-type is managed by the SDK",
                    ));
                }
            }
        }
        Ok(HttpRequest {
            method,
            path: self.path,
            headers: self.headers,
            body: self.body,
            retry_setting: self.retry_setting,
            timeouts: self.timeouts,
            admission_policy: self.admission_policy,
            #[cfg(feature = "http-client-cookies")]
            cookie_context: self.cookie_context,
        })
    }
}

#[cfg(test)]
mod method_builder_tests {
    use super::*;
    use crate::api::error::{ErrorKind, ErrorStage};
    use crate::api::http::HttpRequestMethod;

    #[test]
    fn builder_rejects_invalid_methods_without_panicking_or_exposing_input() {
        for token in ["", "BAD METHOD", "GET\r\nsecret", "GÉT", "GET/", "GET\0"] {
            let method = HttpRequestMethod::Extension(token.to_owned());
            for result in [
                HttpRequest::builder().method(&method).path("/").build(),
                HttpRequest::builder().method(method).path("/").build(),
                HttpRequest::builder().method(token).path("/").build(),
            ] {
                let error = result.expect_err("invalid methods cannot build a request");
                assert_eq!(error.kind(), ErrorKind::InvalidInput);
                assert_eq!(error.context().stage, Some(ErrorStage::RequestBuild));
                let detail = error.config_error().expect("method error details");
                assert_eq!(detail.field(), "method");
                assert_eq!(detail.reason(), "invalid HTTP method token");
                assert!(!format!("{error} {error:?}").contains("secret"));
            }
        }
    }

    #[test]
    fn builder_preserves_valid_method_and_allows_replacing_invalid_method() -> Result<(), NetError>
    {
        for token in [
            "GET",
            "POST",
            "QUERY",
            "CUSTOM",
            "custom",
            "CuStOm",
            "X!#$%&'*+-.^_`|~",
        ] {
            let method = HttpRequestMethod::Extension(token.to_owned());
            let request = HttpRequest::builder().method(method).path("/").build()?;
            assert_eq!(request.method.as_str(), token);
        }
        let request = HttpRequest::builder()
            .method(HttpRequestMethod::Extension("BAD METHOD".to_owned()))
            .method(HttpRequestMethod::PATCH)
            .path("/")
            .build()?;
        assert_eq!(request.method, Method::PATCH);
        Ok(())
    }
}

#[cfg(test)]
mod admission_tests {
    use super::*;
    use crate::api::http::HttpAdmissionPolicy;

    type TestResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;

    fn check(condition: bool, message: &str) -> TestResult {
        if condition {
            Ok(())
        } else {
            Err(std::io::Error::other(message).into())
        }
    }

    #[test]
    fn request_admission_defaults_to_client_inheritance() -> TestResult {
        let request = HttpRequest::builder().path("/").build()?;
        check(
            request.admission_policy_override().is_none(),
            "new requests must inherit their client's admission policy",
        )
    }

    #[test]
    fn request_admission_override_survives_build_clone_and_debug() -> TestResult {
        for policy in [HttpAdmissionPolicy::Wait, HttpAdmissionPolicy::FailFast] {
            let request = HttpRequest::builder()
                .path("/")
                .admission_policy(policy)
                .build()?;
            let cloned = request.clone();
            check(
                request.admission_policy_override() == Some(policy)
                    && cloned.admission_policy_override() == Some(policy),
                "build and clone must retain explicit admission policy overrides",
            )?;
            let debug = format!("{cloned:?}");
            check(
                debug.contains("admission_policy") && debug.contains(&format!("{policy:?}")),
                "request debug must include its non-sensitive admission configuration",
            )?;
        }
        Ok(())
    }

    #[test]
    fn last_request_admission_override_wins() -> TestResult {
        let request = HttpRequest::builder()
            .path("/")
            .admission_policy(HttpAdmissionPolicy::FailFast)
            .admission_policy(HttpAdmissionPolicy::Wait)
            .build()?;
        check(
            request.admission_policy_override() == Some(HttpAdmissionPolicy::Wait),
            "the last explicit request admission policy must win",
        )
    }
}

#[cfg(test)]
#[cfg(feature = "http-client-codecs")]
mod codec_builder_tests {
    use super::*;
    use bytes::Bytes;
    use serde::Serialize;

    #[derive(Serialize)]
    struct QueryPart {
        key: &'static str,
    }

    #[derive(Serialize)]
    struct FormValue {
        value: &'static str,
    }

    #[test]
    fn repeated_query_values_survive_path_reset() {
        let request = HttpRequest::builder()
            .path("/first?fixed=1")
            .query(&QueryPart { key: "one" })
            .unwrap()
            .query(&QueryPart { key: "two" })
            .unwrap()
            .path("/second?reset=1")
            .build()
            .unwrap();

        assert_eq!(
            request.path, "/second?reset=1&key=one&key=two",
            "path() must preserve previously appended query parts"
        );
    }

    #[test]
    fn form_keeps_a_caller_supplied_content_type() {
        let request = HttpRequest::builder()
            .path("/form")
            .header("content-type", "application/vnd.example.form")
            .unwrap()
            .form(&FormValue { value: "demo" })
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(
            request.headers.get(http::header::CONTENT_TYPE).unwrap(),
            "application/vnd.example.form"
        );
    }

    #[test]
    fn reverse_raw_and_typed_body_combinations_are_rejected_at_build() {
        let json_then_raw = HttpRequest::builder()
            .path("/body")
            .json(&serde_json::json!({"ok": true}))
            .unwrap()
            .body(Bytes::from_static(b"raw"))
            .build();
        assert!(json_then_raw.is_err());

        let raw_then_json = HttpRequest::builder()
            .path("/body")
            .body(Bytes::from_static(b"raw"))
            .json(&serde_json::json!({"ok": true}));
        assert!(raw_then_json.is_err());

        let multipart_then_header = HttpRequest::builder()
            .path("/multipart")
            .multipart(
                crate::api::http::Multipart::new()
                    .text("field", "value")
                    .unwrap(),
            )
            .unwrap()
            .header("content-type", "multipart/form-data; boundary=user")
            .and_then(|builder| builder.build());
        assert!(multipart_then_header.is_err());
    }
}