open-net 0.3.4

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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
# Callback requests and completion handles

[HTTP guide](README.md) · [Library overview](../../README.md)

## Required features and example dependencies

Use Rust 1.89 or later and the `http-client` feature (it also enables `net-status`).
Create a consumer with `cargo new http-example` and add these dependencies.

```toml
[dependencies]
open-net = { version = "0.3.3", default-features = false, features = ["http-client"] }
rustls-openssl = { version = "=0.4.2", default-features = false, features = ["tls12"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
```

## Application TLS provider

open-net does not choose a cryptographic provider. Each complete program that
creates an HTTP client below initializes the example application's provider in
`main`; copy the program as written. Configuration-only examples need no provider
until a client is built. Client creation requires a provider even for plain HTTP
and otherwise returns `InvalidConfig` for `tls.provider`.

The examples use OpenSSL through `rustls-openssl`, an application dependency.
Another compatible rustls 0.23 provider can replace it. Install a process provider
once in the host application, or pass an explicit per-client provider. A library
using open-net should accept the host's choice rather than install its own global
provider. See [TLS providers](../tls.md) for build prerequisites, provider
precedence and complete examples of both approaches.

Each Rust block is an independent `src/main.rs`; `cargo check` compiles it.
Sending examples need a server at `http://127.0.0.1:8080` with the stated route.
Use `cargo run` only when that prerequisite is satisfied. Compilation is not a
network test. Construction and cleanup examples that send nothing need no server.

## Admission, ownership and completion

The four `send` methods consume a custom `HttpRequestTrait` implementation.
An `Ok(handle)` means the SDK accepted ownership. It does not mean the response
arrived or the callback ran. Accepted requests receive one terminal callback
under normal worker operation, including cancellation and shutdown. Worker
termination or callback panics are reflected by completion state.

An ordinary `Err(EnqueueError<R>)` preserves the original request, including any
owned application state. Rejected requests have no automatic callback. The
application may retry submission, discard the request, or invoke its handler
explicitly. Dropping a pending `send_wait*()` future drops its owned request;
there is no error value to recover and no callback. Configure an admission
timeout when you need ownership returned after a bounded wait.

`Send + 'static` allows the request to move to SDK worker threads and outlive the
submission stack. It need not be `Sync`, `Clone` or `Debug`. A request can own a
`FnOnce + Send` closure. `'static` does not mean “lives forever”; captured borrowed
stack data must be replaced with owned data or an appropriate shared owner.

## `HttpClient::send()`

Attempt immediate admission and obtain a completion handle.

### Required features

`http-client`.

### Function signature

```text
pub fn send<R>(
    &self, request: R,
) -> Result<HttpRequestHandle, EnqueueError<R>>
where
    R: HttpRequestTrait
```

### Steps

Implement HttpRequestTrait, start a server with /health, submit the request, then await handle.finished() and shut down externally.

### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| request | R: HttpRequestTrait | Yes | Owned custom request and its callback state. |

### Callback parameters

`deal_with_response(self: Box<Self>, result: HttpResponseResult)` consumes the request on the callback lane. `result` is the final buffered response or NetError. The optional header hook receives `&HeaderMap`. These are trait callbacks, not arguments to the send method.

### Return values

`Ok(HttpRequestHandle)` transfers ownership to the SDK. `Err(EnqueueError<R>)` returns the rejected request and its NetError. Neither return path is a buffered response.

### Errors and behavior

Does not wait for capacity. Capacity exhaustion (for example QueueFull), duplicate custom IDs, invalid options and closed admission return EnqueueError with the input preserved. The trait retry setting explicitly selects Inherit, Disabled, or Policy; Inherit uses the client default. retry_setting() runs before admission; a panic there unwinds on the submitting thread/future and is not an ownership-preserving returned error.

### Example

```rust
use open_net::api::http::{
    HttpClient, HttpClientConfig, HttpRequestTrait, HttpRequestMethod, HttpResponseResult
};

struct Health;

#[open_net::async_trait]
impl HttpRequestTrait for Health {
    fn get_path(&self) -> String { "/health".into() }
    fn get_method(&self) -> HttpRequestMethod { HttpRequestMethod::GET }
    async fn deal_with_response(self: Box<Self>, result: HttpResponseResult) {
        match result {
            Ok(response) => println!("HTTP status: {}", response.status()),
            Err(error) => eprintln!("Request failed: {error}"),
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), open_net::NetError> {
    rustls_openssl::default_provider()
        .install_default()
        .map_err(|_| open_net::NetError::from(open_net::error::ErrorKind::InvalidConfig))?;
    let client = HttpClient::new(
        HttpClientConfig::new("http://127.0.0.1:8080")?, "callback-example",
    )?;
    match client.send(Health) {
        Ok(handle) => {
            let completion = handle.finished().await;
            println!("Transport summary: {:?}", completion.response);
            if let Err(error) = completion.callback {
                eprintln!("Callback failed: {error}");
            }
        }
        Err(rejected) => {
            let (request, error) = rejected.into_parts();
            // This handler call is an explicit application decision.
            Box::new(request).deal_with_response(Err(error)).await;
        }
    }
    client.shutdown().await?;
    Ok(())
}
```

## `HttpClient::send_with_options()`

Attempt immediate admission and obtain a completion handle.

### Required features

`http-client`.

### Function signature

```text
pub fn send_with_options<R>(
    &self, request: R, options: HttpRequestOptions,
) -> Result<HttpRequestHandle, EnqueueError<R>>
where
    R: HttpRequestTrait
```

### Steps

Implement HttpRequestTrait, start a server with /health, submit the request, then await handle.finished() and shut down externally.

### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| request | R: HttpRequestTrait | Yes | Owned custom request and its callback state. |
| options | HttpRequestOptions | Yes | Authoritative retry, timeouts, request ID and replay settings. |

### Callback parameters

`deal_with_response(self: Box<Self>, result: HttpResponseResult)` consumes the request on the callback lane. `result` is the final buffered response or NetError. The optional header hook receives `&HeaderMap`. These are trait callbacks, not arguments to the send method.

### Return values

`Ok(HttpRequestHandle)` transfers ownership to the SDK. `Err(EnqueueError<R>)` returns the rejected request and its NetError. Neither return path is a buffered response.

### Errors and behavior

Does not wait for capacity. Capacity exhaustion (for example QueueFull), duplicate custom IDs, invalid options and closed admission return EnqueueError with the input preserved. Options override the trait policy. An inherited option uses the client default, even if the trait provides a positive policy.

### Example

```rust
use open_net::api::http::{
    HttpClient, HttpClientConfig, HttpRequestTrait, HttpRequestMethod, HttpResponseResult,
    HttpRequestOptions, HttpTimeouts
};
use open_net::api::retry::RetrySetting;

struct Health;

#[open_net::async_trait]
impl HttpRequestTrait for Health {
    fn get_path(&self) -> String { "/health".into() }
    fn get_method(&self) -> HttpRequestMethod { HttpRequestMethod::GET }
    async fn deal_with_response(self: Box<Self>, result: HttpResponseResult) {
        match result {
            Ok(response) => println!("HTTP status: {}", response.status()),
            Err(error) => eprintln!("Request failed: {error}"),
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), open_net::NetError> {
    rustls_openssl::default_provider()
        .install_default()
        .map_err(|_| open_net::NetError::from(open_net::error::ErrorKind::InvalidConfig))?;
    let client = HttpClient::new(
        HttpClientConfig::new("http://127.0.0.1:8080")?, "callback-example",
    )?;
    let options = HttpRequestOptions::new()
        .with_retry_setting(RetrySetting::Disabled)
        .with_timeouts(HttpTimeouts::new().with_admission_timeout(
            std::time::Duration::from_secs(2),
        ))?;
    match client.send_with_options(Health, options) {
        Ok(handle) => {
            let completion = handle.finished().await;
            println!("Transport summary: {:?}", completion.response);
            if let Err(error) = completion.callback {
                eprintln!("Callback failed: {error}");
            }
        }
        Err(rejected) => {
            let (request, error) = rejected.into_parts();
            // This handler call is an explicit application decision.
            Box::new(request).deal_with_response(Err(error)).await;
        }
    }
    client.shutdown().await?;
    Ok(())
}
```

## `HttpClient::send_wait()`

Wait for admission and obtain a completion handle.

### Required features

`http-client`.

### Function signature

```text
pub async fn send_wait<R>(
    &self, request: R,
) -> Result<HttpRequestHandle, EnqueueError<R>>
where
    R: HttpRequestTrait
```

### Steps

Implement HttpRequestTrait, start a server with /health, submit the request, then await handle.finished() and shut down externally.

### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| request | R: HttpRequestTrait | Yes | Owned custom request and its callback state. |

### Callback parameters

`deal_with_response(self: Box<Self>, result: HttpResponseResult)` consumes the request on the callback lane. `result` is the final buffered response or NetError. The optional header hook receives `&HeaderMap`. These are trait callbacks, not arguments to the send method.

### Return values

`Ok(HttpRequestHandle)` transfers ownership to the SDK. `Err(EnqueueError<R>)` returns the rejected request and its NetError. Neither return path is a buffered response.

### Errors and behavior

Waits for both in-flight capacity and a queue slot using one admission deadline from the first poll. The default admission budget is 30 seconds, independent of attempt timeouts. Timeout, shutdown and other returned errors retain the request; dropping the waiting future does not. The trait retry setting explicitly selects Inherit, Disabled, or Policy; Inherit uses the client default. retry_setting() runs before admission; a panic there unwinds on the submitting thread/future and is not an ownership-preserving returned error.

### Example

```rust
use open_net::api::http::{
    HttpClient, HttpClientConfig, HttpRequestTrait, HttpRequestMethod, HttpResponseResult
};

struct Health;

#[open_net::async_trait]
impl HttpRequestTrait for Health {
    fn get_path(&self) -> String { "/health".into() }
    fn get_method(&self) -> HttpRequestMethod { HttpRequestMethod::GET }
    async fn deal_with_response(self: Box<Self>, result: HttpResponseResult) {
        match result {
            Ok(response) => println!("HTTP status: {}", response.status()),
            Err(error) => eprintln!("Request failed: {error}"),
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), open_net::NetError> {
    rustls_openssl::default_provider()
        .install_default()
        .map_err(|_| open_net::NetError::from(open_net::error::ErrorKind::InvalidConfig))?;
    let client = HttpClient::new(
        HttpClientConfig::new("http://127.0.0.1:8080")?, "callback-example",
    )?;
    match client.send_wait(Health).await {
        Ok(handle) => {
            let completion = handle.finished().await;
            println!("Transport summary: {:?}", completion.response);
            if let Err(error) = completion.callback {
                eprintln!("Callback failed: {error}");
            }
        }
        Err(rejected) => {
            let (request, error) = rejected.into_parts();
            // This handler call is an explicit application decision.
            Box::new(request).deal_with_response(Err(error)).await;
        }
    }
    client.shutdown().await?;
    Ok(())
}
```

## `HttpClient::send_wait_with_options()`

Wait for admission and obtain a completion handle.

### Required features

`http-client`.

### Function signature

```text
pub async fn send_wait_with_options<R>(
    &self, request: R, options: HttpRequestOptions,
) -> Result<HttpRequestHandle, EnqueueError<R>>
where
    R: HttpRequestTrait
```

### Steps

Implement HttpRequestTrait, start a server with /health, submit the request, then await handle.finished() and shut down externally.

### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| request | R: HttpRequestTrait | Yes | Owned custom request and its callback state. |
| options | HttpRequestOptions | Yes | Authoritative retry, timeouts, request ID and replay settings. |

### Callback parameters

`deal_with_response(self: Box<Self>, result: HttpResponseResult)` consumes the request on the callback lane. `result` is the final buffered response or NetError. The optional header hook receives `&HeaderMap`. These are trait callbacks, not arguments to the send method.

### Return values

`Ok(HttpRequestHandle)` transfers ownership to the SDK. `Err(EnqueueError<R>)` returns the rejected request and its NetError. Neither return path is a buffered response.

### Errors and behavior

Waits for both in-flight capacity and a queue slot using one admission deadline from the first poll. The default admission budget is 30 seconds, independent of attempt timeouts. Timeout, shutdown and other returned errors retain the request; dropping the waiting future does not. Options override the trait policy. An inherited option uses the client default, even if the trait provides a positive policy.

### Example

```rust
use open_net::api::http::{
    HttpClient, HttpClientConfig, HttpRequestTrait, HttpRequestMethod, HttpResponseResult,
    HttpRequestOptions, HttpTimeouts
};
use open_net::api::retry::RetrySetting;

struct Health;

#[open_net::async_trait]
impl HttpRequestTrait for Health {
    fn get_path(&self) -> String { "/health".into() }
    fn get_method(&self) -> HttpRequestMethod { HttpRequestMethod::GET }
    async fn deal_with_response(self: Box<Self>, result: HttpResponseResult) {
        match result {
            Ok(response) => println!("HTTP status: {}", response.status()),
            Err(error) => eprintln!("Request failed: {error}"),
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), open_net::NetError> {
    rustls_openssl::default_provider()
        .install_default()
        .map_err(|_| open_net::NetError::from(open_net::error::ErrorKind::InvalidConfig))?;
    let client = HttpClient::new(
        HttpClientConfig::new("http://127.0.0.1:8080")?, "callback-example",
    )?;
    let options = HttpRequestOptions::new()
        .with_retry_setting(RetrySetting::Disabled)
        .with_timeouts(HttpTimeouts::new().with_admission_timeout(
            std::time::Duration::from_secs(2),
        ))?;
    match client.send_wait_with_options(Health, options).await {
        Ok(handle) => {
            let completion = handle.finished().await;
            println!("Transport summary: {:?}", completion.response);
            if let Err(error) = completion.callback {
                eprintln!("Callback failed: {error}");
            }
        }
        Err(rejected) => {
            let (request, error) = rejected.into_parts();
            // This handler call is an explicit application decision.
            Box::new(request).deal_with_response(Err(error)).await;
        }
    }
    client.shutdown().await?;
    Ok(())
}
```

## `HttpRequestTrait`

### Required features

`http-client`. Use the re-exported `#[open_net::async_trait]` attribute on the
implementation so the async consuming method matches the trait.

### Function signatures, parameters and defaults

```text
#[async_trait]
pub trait HttpRequestTrait: Send + 'static {
    fn get_path(&self) -> String;
    fn get_method(&self) -> HttpRequestMethod;
    fn get_req_data(&self) -> String;
    fn get_req_body(&self) -> Bytes;
    fn has_req_body(&self) -> bool;
    fn headers(&self) -> HeaderMap;
    fn retry_setting(&self) -> RetrySetting<HttpRetryPolicy>;
    fn on_response_headers(&self, headers: &HeaderMap);
    async fn deal_with_response(self: Box<Self>, result: HttpResponseResult);
}
```

| Function | Required implementation | Return value or callback parameters |
| --- | --- | --- |
| `get_path` | Yes | Relative request path; read on attempts. Unsafe paths fail after acceptance and reach the terminal callback. |
| `get_method` | Yes | Method for the request. |
| `get_req_data` | No | Legacy textual body; defaults to empty String. |
| `get_req_body` | No | Owned Bytes; default converts get_req_data(). If overridden, this is authoritative. Return equivalent data on each retry. |
| `has_req_body` | No | Defaults false. Nonempty bytes are detected automatically. Return true to explicitly frame an empty body. |
| `headers` | No | Owned per-request HeaderMap; empty by default. Invalid/transport-controlled headers fail at dispatch. |
| `retry_setting` | No | Defaults to Inherit. Disabled permits one attempt; Policy replaces the whole client policy. Explicit options are authoritative. |
| `on_response_headers` | No | Runs on the callback lane only for the final successfully buffered response, just before its consuming handler. No-op by default; headers are read-only. |
| `deal_with_response` | Yes | Consumes Box<Self> and the final HttpResponseResult, returns unit asynchronously. |

With `http-client-cookies`, the additional provider
`fn cookie_context(&self) -> CookieRequestContext` defaults to the default
SameSite context; see [cookies](cookies.md). `Box<T>` forwards the trait for
`T: HttpRequestTrait + ?Sized`, so a `Box<dyn HttpRequestTrait>` is accepted.
The complete examples above show the minimal implementation and cleanup.

### Callback errors and lifetime

`on_response_headers` is a completion hook, not an arrival notification. The SDK
finishes buffering the final body before invoking it. Intermediate redirect,
authentication replay and retry responses are not delivered to this hook. If
body collection fails (for example a size limit, timeout or transport error),
the handler receives `Err` and the header hook is skipped, even if headers had
already arrived. Inspect `error.http_response_head()` in the error branch for
the received status and headers of a buffered-body failure; explicit cancellation
does not carry that metadata. See [response-head diagnostics](requests_and_responses.md#neterrorhttp_response_head).
The hook cannot reject `Content-Length` before download;
use [streaming](streaming_and_sse.md) to inspect headers before consuming a body.
HTTP 4xx/5xx remain successful response values until the handler applies a status
policy. Callback panics are reported through completion, not returned by the
original send call. Keep handlers bounded: network timeouts do not interrupt
application callbacks. The handler must not await its own `finished()`, the same
client's `drain()`/`shutdown()`, or new work that requires capacity it still holds.
Use immediate `send()` or independent workers for reentrant submissions.

## `HttpRequestMethod`

Required feature: `http-client`. This enum has no callbacks and represents
`GET`, `POST`, `PUT`, `DELETE`, `HEAD`, `OPTIONS`, `CONNECT`, `PATCH`, `TRACE`,
`QUERY` and `Extension(String)`. `as_str(&self) -> &str` returns its method text.
Owned/borrowed conversions from `Method` are infallible. Conversions to `Method`
use `TryFrom`/`TryInto` and return `NetError` with `InvalidInput` at `RequestBuild`
for invalid extension tokens. Existing `Method::from(method)` / `method.into()`
calls in this direction must use `Method::try_from(method)?` / `method.try_into()?`.
Comparisons with Method work directly. Valid extension methods retain their exact
text; invalid methods are never replaced with GET or sent to the server. For trait
requests, validation happens after admission and the terminal callback receives the
input error. The concrete request builder reports it from `build()`.

```rust
use open_net::api::http::{HttpRequestMethod, Method};

fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let validated = Method::from_bytes(b"CUSTOM")?;
    let method = HttpRequestMethod::from(validated.clone());
    assert_eq!(method.as_str(), "CUSTOM");
    assert_eq!(Method::try_from(&method)?, validated);
    Ok(())
}
```

## `EnqueueError<R>`

This error lives at `open_net::EnqueueError` (also `open_net::error::EnqueueError`).
It does not require R to implement Debug. No constructor is public. There are
no callbacks on this type.

| Function signature | Return values and ownership |
| --- | --- |
| `error(&self) -> &NetError` | Inspect the admission failure while retaining the request. |
| `value(&self) -> &R` | Borrow the original request. |
| `into_parts(self) -> (R, NetError)` | Recover both owned values; demonstrated in every submission example. |
| `into_inner(self) -> R` | Recover only the request. |
| `into_error(self) -> NetError` | Keep the error and drop the owned request. |

## `HttpRequestId`, `HttpRequestHandle` and completion

An ID is `pub struct HttpRequestId(pub u64)`, supporting Copy, Clone, ordering,
hashing and equality. Automatic IDs increase without wrapping within one client;
IDs are local correlation values, not server-visible or persistent identifiers.
Custom IDs in HttpRequestOptions must be unique among active operations and may
be reused after cleanup. A handle remains bound to its original operation when
that ID is reused; `client.cancel(id)` instead looks up the currently registered ID.

| Function signature | Parameters | Return values and behavior |
| --- | --- | --- |
| `HttpRequestHandle::id(&self) -> HttpRequestId` | None | Operation correlation ID. |
| `HttpRequestHandle::cancel(&self) -> HttpCancelOutcome` | None | Requests local cancellation before callback dispatch. No server-side rollback. |
| `async HttpRequestHandle::finished(&self) -> HttpCompletion` | None | Wait for header hook, handler and SDK cleanup; cloned handles/repeated waits see cached completion. Detached application tasks are excluded. |

`HttpCancelOutcome` is `Requested` (first request), `AlreadyRequested` (already
cancelled before callback dispatch), or `TooLate` (dispatch started or operation
finished). A determined timeout remains a timeout even if cancellation is requested.

`HttpCompletion` has `request_id: HttpRequestId`,
`response: Result<HttpResponseSummary, NetError>` and
`callback: Result<(), NetError>`, and `retry_report: RetryReport`.
The report is also available through `retry_report()`, including zero-attempt
termination after acceptance. `HttpResponseSummary` has `status: StatusCode`
and `attempts: u32`. The response field describes the transport result delivered
to the callback. The callback field describes execution of both hook and handler,
not whether the application accepted the response. Successful completion keeps
metadata, not body bytes. Callback faults can include CallbackPanicked or runtime
failure; inspect the error instead of assuming an HTTP status failure.

Dropping a handle does not cancel its operation; handles do not retain the client,
request, response or admission capacity. Dropping a `finished()` future also does
not cancel the operation. Dropping the final worker owner initiates shutdown even
if a completion handle still exists. Explicit `cancel()` is a separate action.

This compile-ready helper is callable with any accepted handle. Its empty main
performs no network operation; the four submission programs demonstrate where
to obtain the handle.

```rust
use open_net::api::http::{HttpCancelOutcome, HttpRequestHandle};

async fn cancel_and_wait(handle: HttpRequestHandle) -> Result<(), open_net::NetError> {
    println!("Request ID: {:?}", handle.id());
    match handle.cancel() {
        HttpCancelOutcome::Requested => println!("Cancellation requested"),
        HttpCancelOutcome::AlreadyRequested => println!("Already requested"),
        HttpCancelOutcome::TooLate => println!("Callback started or completed"),
    }
    let completion = handle.finished().await;
    println!("Retry report: {:?}", completion.retry_report());
    completion.callback?;
    println!("{:?}", completion.response);
    Ok(())
}

fn main() {}
```

## Offline trait and rejection example

This program directly inspects the trait providers, then closes admission to
obtain recoverable rejection values without contacting a server. Direct hook and
handler invocation at the end is an explicit application decision for a locally
constructed response; the SDK never invokes callbacks for rejected submissions.

```rust
use open_net::api::http::{
    HttpClient, HttpClientConfig, HttpRequestId, HttpRequestMethod, HttpRequestTrait,
    HttpResponse, HttpResponseResult, HttpRetryPolicy,
};
use open_net::{Bytes, EnqueueError, HeaderMap, NetError, StatusCode};
use open_net::api::retry::RetrySetting;

struct Payload;

#[open_net::async_trait]
impl HttpRequestTrait for Payload {
    fn get_path(&self) -> String { "/echo".into() }
    fn get_method(&self) -> HttpRequestMethod { HttpRequestMethod::POST }
    fn get_req_data(&self) -> String { "demo".into() }
    fn get_req_body(&self) -> Bytes { Bytes::from(self.get_req_data()) }
    fn has_req_body(&self) -> bool { true }
    fn headers(&self) -> HeaderMap { HeaderMap::new() }
    fn retry_setting(&self) -> RetrySetting<HttpRetryPolicy> { RetrySetting::Disabled }
    fn on_response_headers(&self, headers: &HeaderMap) {
        println!("Final headers: {}", headers.len());
    }
    async fn deal_with_response(self: Box<Self>, result: HttpResponseResult) {
        println!("Application result: {:?}", result.map(|response| response.status()));
    }
}

fn reject(client: &HttpClient) -> Result<EnqueueError<Payload>, NetError> {
    match client.send(Payload) {
        Err(rejected) => Ok(rejected),
        Ok(_) => Err(NetError::protocol("admission should already be closed")),
    }
}

#[tokio::main]
async fn main() -> Result<(), NetError> {
    rustls_openssl::default_provider()
        .install_default()
        .map_err(|_| open_net::NetError::from(open_net::error::ErrorKind::InvalidConfig))?;
    let request = Payload;
    if request.get_path() != "/echo"
        || request.get_method() != HttpRequestMethod::POST
        || request.get_req_data() != "demo"
        || request.get_req_body().as_ref() != b"demo"
        || !request.has_req_body()
        || !request.headers().is_empty()
        || !matches!(request.retry_setting(), RetrySetting::Disabled)
    {
        return Err(NetError::protocol("unexpected request providers"));
    }
    let client = HttpClient::new(
        HttpClientConfig::new("http://127.0.0.1:8080")?, "rejected-request",
    )?;
    client.request_shutdown();
    let rejected = reject(&client)?;
    println!("{:?}: {}", rejected.error().kind(), rejected.value().get_path());
    let (_request, error) = rejected.into_parts();
    println!("Recovered error: {error}");
    let recovered = reject(&client)?.into_inner();
    if recovered.get_path() != "/echo" {
        return Err(NetError::protocol("rejected input was not preserved"));
    }
    println!("Error only: {}", reject(&client)?.into_error());
    client.shutdown().await?;
    let response = HttpResponse::new(
        StatusCode::OK, HeaderMap::new(), Bytes::new(), 0, HttpRequestId(0),
    );
    request.on_response_headers(response.headers());
    Box::new(request).deal_with_response(Ok(response)).await;
    Ok(())
}
```

## `HttpRequestTrait::get_path()`

### Required features

`http-client`; use `#[open_net::async_trait]` on the trait implementation.

### Function signature

```text
fn get_path(&self) -> String
```

### Steps

Implement this provider on a request type satisfying `Send + 'static`, then submit the request with a send method. The lifetime bound permits owned data and excludes temporary borrowed captures; it does not require the request value to live forever.

### Parameters

None beyond `&self`.

### Callback parameters

Not applicable.

### Return values

An owned request target.

### Errors and behavior

Required implementation. Return a safe relative path. The worker reads providers during attempts; invalid paths fail after admission through the terminal callback, not as a recoverable enqueue rejection.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) implements and directly calls this method; the submission programs above show SDK dispatch.

## `HttpRequestTrait::get_method()`

### Required features

`http-client`; use `#[open_net::async_trait]` on the trait implementation.

### Function signature

```text
fn get_method(&self) -> HttpRequestMethod
```

### Steps

Implement this provider on a request type satisfying `Send + 'static`, then submit the request with a send method. The lifetime bound permits owned data and excludes temporary borrowed captures; it does not require the request value to live forever.

### Parameters

None beyond `&self`.

### Callback parameters

Not applicable.

### Return values

An owned method value.

### Errors and behavior

Required implementation. The method participates in replay safety. Validate custom method text before creating an Extension value.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) implements and directly calls this method; the submission programs above show SDK dispatch.

## `HttpRequestTrait::get_req_data()`

### Required features

`http-client`; use `#[open_net::async_trait]` on the trait implementation.

### Function signature

```text
fn get_req_data(&self) -> String
```

### Steps

Implement this provider on a request type satisfying `Send + 'static`, then submit the request with a send method. The lifetime bound permits owned data and excludes temporary borrowed captures; it does not require the request value to live forever.

### Parameters

None beyond `&self`.

### Callback parameters

Not applicable.

### Return values

An owned textual body; empty by default.

### Errors and behavior

Legacy body provider. Default get_req_body converts this string into bytes. If get_req_body is overridden, that byte provider is authoritative.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) implements and directly calls this method; the submission programs above show SDK dispatch.

## `HttpRequestTrait::get_req_body()`

### Required features

`http-client`; use `#[open_net::async_trait]` on the trait implementation.

### Function signature

```text
fn get_req_body(&self) -> Bytes
```

### Steps

Implement this provider on a request type satisfying `Send + 'static`, then submit the request with a send method. The lifetime bound permits owned data and excludes temporary borrowed captures; it does not require the request value to live forever.

### Parameters

None beyond `&self`.

### Callback parameters

Not applicable.

### Return values

Owned buffered request bytes.

### Errors and behavior

By default converts get_req_data. Providers can be called again on retries; return equivalent replayable bytes. A nonempty byte buffer is detected as a body automatically.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) implements and directly calls this method; the submission programs above show SDK dispatch.

## `HttpRequestTrait::has_req_body()`

### Required features

`http-client`; use `#[open_net::async_trait]` on the trait implementation.

### Function signature

```text
fn has_req_body(&self) -> bool
```

### Steps

Implement this provider on a request type satisfying `Send + 'static`, then submit the request with a send method. The lifetime bound permits owned data and excludes temporary borrowed captures; it does not require the request value to live forever.

### Parameters

None beyond `&self`.

### Callback parameters

Not applicable.

### Return values

True to explicitly frame a body even when its byte representation is empty; false by default.

### Errors and behavior

The default does not invoke body providers. Nonempty get_req_body bytes already imply a body; override this for an intentional empty body needing framing.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) implements and directly calls this method; the submission programs above show SDK dispatch.

## `HttpRequestTrait::headers()`

### Required features

`http-client`; use `#[open_net::async_trait]` on the trait implementation.

### Function signature

```text
fn headers(&self) -> HeaderMap
```

### Steps

Implement this provider on a request type satisfying `Send + 'static`, then submit the request with a send method. The lifetime bound permits owned data and excludes temporary borrowed captures; it does not require the request value to live forever.

### Parameters

None beyond `&self`.

### Callback parameters

Not applicable.

### Return values

Owned per-request headers; empty by default.

### Errors and behavior

Request headers override common client headers. Invalid or transport-controlled headers fail at dispatch. Return stable values when the request is replayable.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) implements and directly calls this method; the submission programs above show SDK dispatch.

## `HttpRequestTrait::retry_setting()`

### Required features

`http-client`; use `#[open_net::async_trait]` on the trait implementation.

### Function signature

```text
fn retry_setting(&self) -> RetrySetting<HttpRetryPolicy>
```

### Steps

Implement this provider on a request type satisfying `Send + 'static`, then submit the request with a send method. The lifetime bound permits owned data and excludes temporary borrowed captures; it does not require the request value to live forever.

### Parameters

None beyond `&self`.

### Callback parameters

Not applicable.

### Return values

The request retry setting; Inherit by default.

### Errors and behavior

send/send_wait consult this provider on the caller before admission. Inherit uses the client default; Disabled permits one attempt; Policy replaces the whole policy. Explicit options are authoritative and their Inherit also uses the client default. Provider panics unwind on the caller; ownership recovery applies to returned errors, not panics.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) implements and directly calls this method; the submission programs above show SDK dispatch.

## `HttpRequestTrait::on_response_headers()`

### Required features

`http-client`.

### Function signature

```text
fn on_response_headers(&self, headers: &HeaderMap)
```

### Steps

Optionally override this synchronous hook to inspect final headers immediately before the consuming callback.

### Parameters

`&self` borrows the request and `headers: &HeaderMap` borrows final response headers.

### Callback parameters

`headers: &HeaderMap` contains the final response headers, borrowed only for this call. The callback returns synchronously; retain a clone if needed later.

### Return values

Unit; the default implementation is a no-op.

### Errors and behavior

Runs on the callback lane only after the complete final buffered response succeeds. There are no intermediate redirect/retry/authentication-response notifications. Body read errors, limits and timeouts skip the hook. It cannot reject headers before download or replace the result; use stream() for pre-body inspection. A panic is reflected in handle completion.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) implements and directly calls this method; the submission programs above show SDK dispatch.

## `HttpRequestTrait::deal_with_response()`

### Required features

`http-client`; use `#[open_net::async_trait]` on the implementation, which must satisfy `Send + 'static`.

### Function signature

```text
async fn deal_with_response(self: Box<Self>, result: HttpResponseResult)
```

### Steps

Implement the owned terminal callback, handle both response and transport failure, and let it finish to release operation capacity.

### Parameters

`self: Box<Self>` consumes the request and its application state; `result: HttpResponseResult` is required and moved into the callback.

### Callback parameters

`result` is `Result<HttpResponse, NetError>`: Ok owns a fully buffered final response; Err owns the failure. Application state is recovered through owned self.

### Return values

Unit after the callback future completes; application success is not inferred from the return type.

### Errors and behavior

Accepted submissions receive one terminal callback under normal SDK dispatch, including failure/cancellation. Rejected submissions receive none. HTTP 4xx/5xx remain Ok responses unless checked. The callback runs on the SDK callback lane, must not wait for its own completion or client cleanup, and is not interrupted by network timeout budgets. After a terminal network result, neither its callback queue wait nor callback execution counts toward total_timeout or retry-report elapsed. Completion reports callback panic or abnormal execution.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) implements and directly calls this method; the submission programs above show SDK dispatch.

## `HttpRequestMethod::as_str()`

### Required features

`http-client`.

### Function signature

```text
pub fn as_str(&self) -> &str
```

### Steps

Inspect the textual method while retaining the enum.

### Parameters

None beyond `&self`.

### Callback parameters

Not applicable.

### Return values

A borrowed method string.

### Errors and behavior

Known variants return their method text; Extension returns its stored text without validation. Converting an invalid Extension with `Method::try_from` returns an `InvalidInput` error. Conversion errors do not include the supplied method text.

### Example

[HttpRequestMethod example](#httprequestmethod) validates CUSTOM and calls as_str in a complete offline program.

## `EnqueueError::error()`

### Required features

`http-client`.

### Function signature

```text
pub fn error(&self) -> &NetError
```

### Steps

Handle the Err branch of send/send_wait and choose whether to inspect or recover the rejected request.

### Parameters

None beyond `&self` or consumed `self`, as shown in the signature. R has no extra Clone, Sync or Debug requirement.

### Callback parameters

Not applicable.

### Return values

A borrowed admission error.

### Errors and behavior

Keeps the original rejected request owned by EnqueueError. No callback is scheduled by inspection.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) exercises all five accessors against explicitly closed admission.

## `EnqueueError::value()`

### Required features

`http-client`.

### Function signature

```text
pub fn value(&self) -> &R
```

### Steps

Handle the Err branch of send/send_wait and choose whether to inspect or recover the rejected request.

### Parameters

None beyond `&self` or consumed `self`, as shown in the signature. R has no extra Clone, Sync or Debug requirement.

### Callback parameters

Not applicable.

### Return values

A borrowed original rejected request.

### Errors and behavior

Neither transfers nor clones the request. Use an owning accessor when retrying submission.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) exercises all five accessors against explicitly closed admission.

## `EnqueueError::into_parts()`

### Required features

`http-client`.

### Function signature

```text
pub fn into_parts(self) -> (R, NetError)
```

### Steps

Handle the Err branch of send/send_wait and choose whether to inspect or recover the rejected request.

### Parameters

None beyond `&self` or consumed `self`, as shown in the signature. R has no extra Clone, Sync or Debug requirement.

### Callback parameters

Not applicable.

### Return values

The original request and admission error as owned values.

### Errors and behavior

Consumes the wrapper. The application can retry, retain, or manually handle the request; no SDK callback has been scheduled.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) exercises all five accessors against explicitly closed admission.

## `EnqueueError::into_inner()`

### Required features

`http-client`.

### Function signature

```text
pub fn into_inner(self) -> R
```

### Steps

Handle the Err branch of send/send_wait and choose whether to inspect or recover the rejected request.

### Parameters

None beyond `&self` or consumed `self`, as shown in the signature. R has no extra Clone, Sync or Debug requirement.

### Callback parameters

Not applicable.

### Return values

The original owned request.

### Errors and behavior

Consumes the wrapper and discards its error. This performs no retry automatically.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) exercises all five accessors against explicitly closed admission.

## `EnqueueError::into_error()`

### Required features

`http-client`.

### Function signature

```text
pub fn into_error(self) -> NetError
```

### Steps

Handle the Err branch of send/send_wait and choose whether to inspect or recover the rejected request.

### Parameters

None beyond `&self` or consumed `self`, as shown in the signature. R has no extra Clone, Sync or Debug requirement.

### Callback parameters

Not applicable.

### Return values

The owned admission error.

### Errors and behavior

Consumes the wrapper and drops its original request, including owned callback/application state. No callback is invoked.

### Example

[Offline trait and rejection example](#offline-trait-and-rejection-example) exercises all five accessors against explicitly closed admission.

## `HttpRequestHandle::id()`

### Required features

`http-client`.

### Function signature

```text
pub fn id(&self) -> HttpRequestId
```

### Steps

Retain the accepted operation handle and read its correlation ID.

### Parameters

None beyond `&self`.

### Callback parameters

Not applicable.

### Return values

The operation ID by value.

### Errors and behavior

The handle remains bound to its original operation even if that numeric ID is later reused. This accessor does not schedule cancellation or retain request capacity.

### Example

[Handle example](#httprequestid-httprequesthandle-and-completion) provides the complete cancel_and_wait helper calling this method; the send programs supply accepted handles.

## `HttpRequestHandle::cancel()`

### Required features

`http-client`.

### Function signature

```text
pub fn cancel(&self) -> HttpCancelOutcome
```

### Steps

Request local cancellation and await finished separately if cleanup must be observed.

### Parameters

None beyond `&self`.

### Callback parameters

Not applicable.

### Return values

Requested on the first cancellation request, AlreadyRequested if previously requested, or TooLate once callback dispatch begins or the operation finishes.

### Errors and behavior

Cancellation cannot roll back server-side processing or interrupt an executing callback. An already determined timeout remains a timeout. Dropping the handle alone does not request cancellation.

### Example

[Handle example](#httprequestid-httprequesthandle-and-completion) provides the complete cancel_and_wait helper calling this method; the send programs supply accepted handles.

## `HttpRequestHandle::finished()`

### Required features

`http-client`.

### Function signature

```text
pub async fn finished(&self) -> HttpCompletion
```

### Steps

Await completion outside the operation callback, then inspect response and callback fields separately.

### Parameters

None beyond `&self`.

### Callback parameters

Not applicable.

### Return values

A cached HttpCompletion containing request ID, transport summary/error and callback execution result.

### Errors and behavior

Waits for the header hook, consuming handler and SDK operation-resource cleanup. Repeated waits and cloned handles observe the same result. Dropping this waiting future does not cancel the operation. Detached callback tasks are outside the boundary; a callback that never returns can prevent completion. A callback must not await its own handle.

### Example

[Handle example](#httprequestid-httprequesthandle-and-completion) provides the complete cancel_and_wait helper calling this method; the send programs supply accepted handles.

## `HttpCompletion::retry_report()`

### Required features

`http-client`.

### Function signature

```text
HttpCompletion::retry_report(&self) -> &RetryReport
```

### Steps

Await `handle.finished()`, inspect the final report, then consume completion fields.

### Parameters

None.

### Callback parameters

None.

### Return values

The accepted operation's final common retry report; it is always present.

### Errors and behavior

Includes zero attempts when accepted work terminates before an attempt starts.
The report describes network scheduling; `callback` separately reports callback
execution. Once the network operation has a terminal result, both final callback
queueing and execution are excluded from `total_timeout` and report `elapsed`.
The queued result does not become a timeout merely because callback dispatch is
slow. `finished()` waits for that callback and SDK resource cleanup.

### Example

See the complete [cancel-and-wait helper](#httprequestid-httprequesthandle-and-completion).