nbreq 0.3.1

Runtime-independent cancellable HTTP client
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
use std::cell::Cell;
use std::marker::PhantomData;
use std::num::NonZeroUsize;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

#[cfg(feature = "resolver")]
use crate::Resolver;
use crate::backend::{self, Backend};
use crate::context::{ContextGuard, ContextKind};
use crate::dispatch::DispatcherOwner;
use crate::metrics::Metrics;
use crate::reactor::spawned_main_factory;
use crate::reactor::{ReactorCore, reactor_panicked, spawned_main};
use crate::registry::Shared;
use crate::waiter::sealed::Sealed;
use crate::{
    Client, DriveStatus, EngineConfig, EngineRequestBuilder, Error, ErrorKind, HttpBackend,
    Request, RunMode, ShutdownError, ShutdownOutcome, TcpConnector, WaiterTarget,
};

static NEXT_ENGINE_ID: AtomicU64 = AtomicU64::new(1);

enum RuntimeOwner {
    Spawned(Option<JoinHandle<Result<(), ShutdownError>>>),
    #[cfg_attr(not(feature = "native"), allow(dead_code))]
    Manual(Option<ReactorCore<dyn Backend + Send>>),
    Stopped,
}

/// Unique owner of one lifecycle, resource, and bulk-cancellation domain.
///
/// Engine is `Send`, deliberately non-cloneable, and deliberately not `Sync` in the initial
/// contract. [`Engine::client`] and [`Engine::tcp_connector`] issue cheap cloneable capability
/// tickets; the default-on `resolver` feature also provides `Engine::resolver`. Tickets neither own
/// nor extend Engine lifetime. Explicit shutdown consumes the Engine owner.
///
/// ```compile_fail
/// use nbreq::Engine;
/// fn require_sync<T: Sync>() {}
/// require_sync::<Engine>();
/// ```
pub struct Engine {
    shared: Arc<Shared>,
    config: EngineConfig,
    runtime: RuntimeOwner,
    dispatcher: Option<DispatcherOwner>,
    shutdown_failure: Option<Error>,
    driving: bool,
    _not_sync: PhantomData<Cell<()>>,
}

struct DrivingGuard<'flag> {
    driving: &'flag mut bool,
}

impl Drop for DrivingGuard<'_> {
    fn drop(&mut self) {
        *self.driving = false;
    }
}

fn validate_tls_backend(
    config: &EngineConfig,
    configured: Option<crate::TlsTrust>,
) -> Result<(), Error> {
    if (config.tls_trust() != crate::TlsTrust::Platform
        || !config.additional_tls_root_certificates().is_empty())
        && configured != Some(config.tls_trust())
    {
        return Err(Error::new(
            ErrorKind::Unsupported,
            "selected backend does not apply the configured TLS trust policy",
        ));
    }
    Ok(())
}

impl Engine {
    /// Creates one independent Engine from backend-neutral configuration.
    ///
    /// The default build uses NBReq's native HTTP implementation in spawned or manual mode. A
    /// build without the `native` feature returns [`ErrorKind::Unsupported`].
    pub fn new(config: EngineConfig) -> Result<Self, Error> {
        #[cfg(feature = "native")]
        {
            Self::with_native_backend(config)
        }
        #[cfg(not(feature = "native"))]
        {
            let _ = config;
            Err(unavailable_http_backend("native"))
        }
    }

    fn with_http_backend(config: EngineConfig, backend: HttpBackend) -> Result<Self, Error> {
        match backend {
            HttpBackend::Native => {
                #[cfg(feature = "native")]
                {
                    Self::with_native_backend(config)
                }
                #[cfg(not(feature = "native"))]
                {
                    let _ = config;
                    Err(unavailable_http_backend("native"))
                }
            }
        }
    }

    #[cfg(feature = "native")]
    fn with_native_backend(config: EngineConfig) -> Result<Self, Error> {
        match config.run_mode() {
            RunMode::Spawned => {
                let factory = backend::native_https_factory_with_system_dns(&config)?;
                Self::with_spawned_factory(config, factory)
            }
            RunMode::Manual => {
                let backend = backend::native_https_backend_with_system_dns(&config)?;
                Self::with_backend(config, backend)
            }
        }
    }

    #[cfg_attr(not(feature = "native"), allow(dead_code))]
    pub(crate) fn with_backend(
        config: EngineConfig,
        mut backend: Box<dyn Backend + Send>,
    ) -> Result<Self, Error> {
        validate_tls_backend(&config, backend.configured_tls_trust())?;
        let streaming_supported = backend.supports_streaming();
        let native_resolver_supported = backend.supports_native_resolver();
        let standalone_tcp_supported = backend.supports_standalone_tcp();
        let id = NEXT_ENGINE_ID.fetch_add(1, Ordering::Relaxed);
        if id == u64::MAX {
            return Err(Error::new(
                ErrorKind::Internal,
                "Engine identity space is exhausted",
            ));
        }

        let metrics = Arc::new(Metrics::default());
        if backend.connection_metrics_available() {
            metrics.enable_connection_metrics();
        }
        let dispatcher = DispatcherOwner::new(
            id,
            config.callback_queue_capacity().get(),
            config.callback_dispatch(),
            Arc::clone(&metrics),
        )?;
        let shared = Shared::new(
            id,
            &config,
            dispatcher.domain(),
            streaming_supported,
            Arc::clone(&metrics),
        );
        shared.set_native_resolver_supported(native_resolver_supported);
        shared.set_standalone_tcp_supported(standalone_tcp_supported);
        backend.attach_metrics(metrics);
        let runtime = match config.run_mode() {
            RunMode::Spawned => {
                let reactor_shared = Arc::clone(&shared);
                let reactor = ReactorCore::new(backend);
                let handle = thread::Builder::new()
                    .name(format!("nbreq-reactor-{id}"))
                    .spawn(move || spawned_main(reactor_shared, reactor))
                    .map_err(|error| {
                        shared.begin_shutdown();
                        dispatcher.seal();
                        Error::new(
                            ErrorKind::Internal,
                            format!("failed to spawn NBReq reactor: {error}"),
                        )
                    });
                let handle = match handle {
                    Ok(handle) => handle,
                    Err(error) => {
                        let _callback_result = dispatcher.finish();
                        return Err(error);
                    }
                };
                RuntimeOwner::Spawned(Some(handle))
            }
            RunMode::Manual => RuntimeOwner::Manual(Some(ReactorCore::new(backend))),
        };

        Ok(Self {
            shared,
            config,
            runtime,
            dispatcher: Some(dispatcher),
            shutdown_failure: None,
            driving: false,
            _not_sync: PhantomData,
        })
    }

    #[cfg_attr(not(feature = "native"), allow(dead_code))]
    pub(crate) fn with_spawned_factory(
        config: EngineConfig,
        factory: Box<dyn backend::BackendFactory>,
    ) -> Result<Self, Error> {
        validate_tls_backend(&config, factory.configured_tls_trust())?;
        if config.run_mode() != RunMode::Spawned {
            return Err(Error::new(
                ErrorKind::WrongMode,
                "a spawned backend factory requires spawned Engine mode",
            ));
        }
        let id = NEXT_ENGINE_ID.fetch_add(1, Ordering::Relaxed);
        if id == u64::MAX {
            return Err(Error::new(
                ErrorKind::Internal,
                "Engine identity space is exhausted",
            ));
        }
        let metrics = Arc::new(Metrics::default());
        if factory.connection_metrics_available() {
            metrics.enable_connection_metrics();
        }
        let dispatcher = DispatcherOwner::new(
            id,
            config.callback_queue_capacity().get(),
            config.callback_dispatch(),
            Arc::clone(&metrics),
        )?;
        let streaming_supported = factory.supports_streaming();
        let native_resolver_supported = factory.supports_native_resolver();
        let standalone_tcp_supported = factory.supports_standalone_tcp();
        let shared = Shared::new(
            id,
            &config,
            dispatcher.domain(),
            streaming_supported,
            metrics,
        );
        shared.set_native_resolver_supported(native_resolver_supported);
        shared.set_standalone_tcp_supported(standalone_tcp_supported);
        let reactor_shared = Arc::clone(&shared);
        let handle = thread::Builder::new()
            .name(format!("nbreq-reactor-{id}"))
            .spawn(move || spawned_main_factory(reactor_shared, factory))
            .map_err(|error| {
                shared.begin_shutdown();
                dispatcher.seal();
                Error::new(
                    ErrorKind::Internal,
                    format!("failed to spawn NBReq reactor factory: {error}"),
                )
            });
        let handle = match handle {
            Ok(handle) => handle,
            Err(error) => {
                let _callback_result = dispatcher.finish();
                return Err(error);
            }
        };

        Ok(Self {
            shared,
            config,
            runtime: RuntimeOwner::Spawned(Some(handle)),
            dispatcher: Some(dispatcher),
            shutdown_failure: None,
            driving: false,
            _not_sync: PhantomData,
        })
    }

    #[cfg(any(test, feature = "test-support"))]
    pub(crate) fn shared_for_testing(&self) -> Arc<Shared> {
        Arc::clone(&self.shared)
    }

    /// Starts a configuration builder in the convenient spawned mode.
    #[must_use]
    pub fn builder() -> EngineBuilder {
        EngineBuilder::spawned()
    }

    /// Returns whether this Engine is spawned or driven manually.
    #[must_use]
    pub fn run_mode(&self) -> RunMode {
        self.config.run_mode()
    }

    /// Issues a cheap cloneable command handle for this Engine.
    #[must_use]
    pub fn client(&self) -> Client {
        Client::new(Arc::clone(&self.shared))
    }

    /// Starts a simple Engine-bound GET request.
    ///
    /// The returned builder uses this Engine's existing [`Client`], backend, connection pool,
    /// limits, and lifecycle. It does not create or retain another Engine.
    ///
    /// ```no_run
    /// use nbreq::{Engine, EngineConfig};
    ///
    /// let engine = Engine::new(EngineConfig::spawned())?;
    /// let response = engine
    ///     .get("https://example.com/")
    ///     .header("Accept", "text/plain")
    ///     .call()?;
    /// assert!(response.status() >= 100);
    /// engine.shutdown()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn get(&self, url: impl Into<String>) -> EngineRequestBuilder {
        EngineRequestBuilder::new(self.client(), Request::get(url))
    }

    /// Starts a simple Engine-bound POST request.
    ///
    /// The buffered body may be supplied with [`EngineRequestBuilder::send`], or an empty POST may
    /// be executed with [`EngineRequestBuilder::call`] or [`EngineRequestBuilder::send_empty`].
    ///
    /// ```no_run
    /// use nbreq::{Engine, EngineConfig};
    ///
    /// let engine = Engine::new(EngineConfig::spawned())?;
    /// let response = engine
    ///     .post("https://example.com/items")
    ///     .header("Content-Type", "application/json")
    ///     .send(br#"{"name":"thing"}"#)?;
    /// assert!(response.status() >= 100);
    /// engine.shutdown()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn post(&self, url: impl Into<String>) -> EngineRequestBuilder {
        EngineRequestBuilder::new(self.client(), Request::post(url))
    }

    /// Issues a cheap cloneable hostname-resolution handle for this Engine.
    ///
    /// The ticket is always issued. Native Engines that own the private DNS service accept public
    /// resolutions. Engines without that service reject new work with
    /// [`ErrorKind::Unsupported`] before identity allocation, admission, callback reservation, or
    /// command queuing.
    ///
    /// ```no_run
    /// use nbreq::{Engine, EngineConfig, ResolveRequest};
    ///
    /// let engine = Engine::new(EngineConfig::spawned())?;
    /// let resolver = engine.resolver();
    /// let request = ResolveRequest::hostname("example.com")
    ///     .max_results(8)
    ///     .build()?;
    /// let _pending = resolver.submit(request);
    /// engine.shutdown()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    #[cfg(feature = "resolver")]
    pub fn resolver(&self) -> Resolver {
        Resolver::new(Arc::clone(&self.shared), self.config.max_resolve_results())
    }

    /// Issues a cheap cloneable cleartext TCP handle for this Engine.
    ///
    /// The ticket is always issued. Native Engines accept literal-address connects on their
    /// existing reactor owner. Hostname connects and Engines without that owner currently fail
    /// [`ErrorKind::Unsupported`] before identity allocation or admission.
    ///
    /// ```no_run
    /// use nbreq::{Engine, EngineConfig, TcpConnectRequest};
    ///
    /// let engine = Engine::new(EngineConfig::spawned())?;
    /// let tcp = engine.tcp_connector();
    /// let request = TcpConnectRequest::hostname("example.com", 1234)
    ///     .connect_timeout(std::time::Duration::from_secs(5))
    ///     .build()?;
    /// let _pending = tcp.submit(request);
    /// engine.shutdown()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn tcp_connector(&self) -> TcpConnector {
        TcpConnector::new(Arc::clone(&self.shared))
    }

    /// Returns a nonblocking, payload-free snapshot of this Engine's lifetime activity.
    ///
    /// Fields are loaded independently and may be cross-field inconsistent while work is moving.
    #[must_use]
    pub fn metrics(&self) -> crate::EngineMetrics {
        self.shared.metrics_snapshot()
    }

    /// Cancels HTTP requests, public resolutions when compiled, pending connects, and live
    /// standalone TCP accepted before the cancellation barrier while keeping the Engine alive.
    pub fn cancel_all(&self) {
        self.shared.cancel_all();
    }

    /// Performs one host-driven Engine pass up to `deadline`.
    pub fn drive(&mut self, deadline: Instant) -> Result<DriveStatus, Error> {
        if self.config.run_mode() != RunMode::Manual {
            return Err(Error::new(
                ErrorKind::WrongMode,
                "drive is available only for a manual Engine",
            ));
        }
        if self.driving {
            return Err(Error::new(
                ErrorKind::ReentrantDrive,
                "manual Engine drive is already active",
            ));
        }

        let (driving, runtime, dispatcher) =
            (&mut self.driving, &mut self.runtime, &self.dispatcher);
        *driving = true;
        let _driving = DrivingGuard { driving };
        let _context = ContextGuard::enter(self.shared.id, ContextKind::Drive);
        let result = match runtime {
            RuntimeOwner::Manual(Some(reactor)) => {
                let seen_generation = self.shared.queue.generation();
                let mut result = reactor.drive(&self.shared, deadline);
                if matches!(result, Ok(DriveStatus::Idle))
                    && reactor.transport_wait().is_none()
                    && Instant::now() < deadline
                {
                    if self.shared.queue.wait_for_signal_until(
                        seen_generation,
                        &self.shared.stopped,
                        deadline,
                    ) {
                        result = reactor.drive(&self.shared, deadline);
                    } else {
                        result = Ok(DriveStatus::DeadlineReached);
                    }
                }
                result
            }
            RuntimeOwner::Manual(None) | RuntimeOwner::Stopped => {
                Err(Error::new(ErrorKind::EngineStopped, "Engine has stopped"))
            }
            RuntimeOwner::Spawned(_) => Err(Error::new(
                ErrorKind::WrongMode,
                "drive is available only for a manual Engine",
            )),
        };
        if let Some(dispatcher) = dispatcher {
            dispatcher.drain_inline();
        }
        result
    }

    /// Drives a manual Engine until `pending` reaches its canonical terminal outcome.
    ///
    /// The existing HTTP call shape is unchanged: passing a [`PendingRequest`](crate::PendingRequest)
    /// still returns [`Completion`](crate::Completion). Public resolve and connect waiters return
    /// their own terminal types through the same method.
    pub fn drive_until<T: WaiterTarget>(&mut self, pending: T) -> Result<T::Output, Error> {
        if self.config.run_mode() != RunMode::Manual {
            return Err(Error::new(
                ErrorKind::WrongMode,
                "drive_until is available only for a manual Engine",
            ));
        }
        if Sealed::engine_id(&pending) != self.shared.id {
            return Err(Error::new(
                ErrorKind::WrongEngine,
                "the waiter belongs to another Engine",
            ));
        }
        loop {
            if let Some(output) = Sealed::try_output(&pending) {
                return Ok(output);
            }
            self.drive(Instant::now() + Duration::from_millis(10))?;
        }
    }

    /// Irreversibly stops network work and waits for callback dispatch to drain.
    pub fn shutdown(mut self) -> Result<(), ShutdownError> {
        if crate::context::is_callback(self.shared.id) {
            return match self.defer_cleanup() {
                Ok(()) => Err(reentrant_shutdown_error()),
                Err(error) => Err(error),
            };
        }
        let network = self.stop_network();
        let callbacks = self.finish_callbacks();
        network.and(callbacks)
    }

    /// Irreversibly stops network work, then waits up to `duration` for callback dispatch.
    pub fn shutdown_for(mut self, duration: Duration) -> Result<ShutdownOutcome, ShutdownError> {
        if crate::context::is_callback(self.shared.id) {
            return match self.defer_cleanup() {
                Ok(()) => Err(reentrant_shutdown_error()),
                Err(error) => Err(error),
            };
        }
        if let Err(error) = self.stop_network() {
            let _callback_result = self.finish_callbacks();
            return Err(error);
        }
        let Some(dispatcher) = self.dispatcher.take() else {
            return Ok(ShutdownOutcome::Complete);
        };
        match dispatcher.finish_for(duration)? {
            Some(detached) => Ok(ShutdownOutcome::CallbacksRemaining(detached)),
            None => Ok(ShutdownOutcome::Complete),
        }
    }

    fn stop_network(&mut self) -> Result<(), ShutdownError> {
        self.shared.begin_shutdown();
        if let Some(error) = &self.shutdown_failure {
            if let Some(dispatcher) = &self.dispatcher {
                dispatcher.seal();
            }
            return Err(ShutdownError::new(error.clone()));
        }
        let shutdown = match &mut self.runtime {
            RuntimeOwner::Spawned(handle) => match handle.take() {
                Some(handle) => handle.join().unwrap_or_else(|_| Err(reactor_panicked())),
                None => Ok(()),
            },
            RuntimeOwner::Manual(reactor) => match reactor.as_mut() {
                Some(reactor) => reactor.shutdown(&self.shared),
                None => Ok(()),
            },
            RuntimeOwner::Stopped => Ok(()),
        };

        self.shared.wait_for_callback_activations();
        if let Some(dispatcher) = &self.dispatcher {
            dispatcher.seal();
        }
        if let Err(error) = &shutdown {
            if matches!(self.runtime, RuntimeOwner::Spawned(None)) {
                self.shutdown_failure = Some(error.error().clone());
            }
        }
        if shutdown.is_ok() {
            self.runtime = RuntimeOwner::Stopped;
            self.shared.mark_stopped();
        }
        shutdown
    }

    fn finish_callbacks(&mut self) -> Result<(), ShutdownError> {
        match self.dispatcher.take() {
            Some(dispatcher) => dispatcher.finish(),
            None => Ok(()),
        }
    }

    fn defer_cleanup(&mut self) -> Result<(), ShutdownError> {
        self.shared.begin_shutdown();
        let runtime = std::mem::replace(&mut self.runtime, RuntimeOwner::Stopped);
        let dispatcher = self.dispatcher.take();
        let resources = Arc::new(std::sync::Mutex::new(Some((runtime, dispatcher))));
        let cleanup_resources = Arc::clone(&resources);
        let shared = Arc::clone(&self.shared);
        let cleanup = move || {
            let (runtime, dispatcher) = cleanup_resources
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .take()
                .expect("deferred cleanup resources must be present");
            let network = stop_owned_runtime(runtime, &shared);
            if network.is_ok() {
                shared.mark_stopped();
            }
            shared.wait_for_callback_activations();
            if let Some(dispatcher) = dispatcher {
                let _callback_result = dispatcher.finish();
            }
        };
        match thread::Builder::new()
            .name(format!("nbreq-deferred-shutdown-{}", self.shared.id))
            .spawn(cleanup)
        {
            Ok(_cleanup_thread) => Ok(()),
            Err(error) => {
                let (runtime, dispatcher) = resources
                    .lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner())
                    .take()
                    .expect("failed spawn must return deferred cleanup resources");
                self.runtime = runtime;
                self.dispatcher = dispatcher;
                Err(ShutdownError::new(Error::new(
                    ErrorKind::Internal,
                    format!("failed to spawn NBReq deferred cleanup worker: {error}"),
                )))
            }
        }
    }
}

impl Drop for Engine {
    fn drop(&mut self) {
        if crate::context::is_callback(self.shared.id) {
            if !matches!(self.runtime, RuntimeOwner::Stopped) || self.dispatcher.is_some() {
                let _deferred_result = self.defer_cleanup();
            }
            return;
        }
        let _network_result = self.stop_network();
        let _callback_result = self.finish_callbacks();
    }
}

fn stop_owned_runtime(
    mut runtime: RuntimeOwner,
    shared: &Arc<Shared>,
) -> Result<(), ShutdownError> {
    match &mut runtime {
        RuntimeOwner::Spawned(handle) => match handle.take() {
            Some(handle) => handle.join().unwrap_or_else(|_| Err(reactor_panicked())),
            None => Ok(()),
        },
        RuntimeOwner::Manual(reactor) => match reactor.as_mut() {
            Some(reactor) => reactor.shutdown(shared),
            None => Ok(()),
        },
        RuntimeOwner::Stopped => Ok(()),
    }
}

fn reentrant_shutdown_error() -> ShutdownError {
    ShutdownError::new(Error::new(
        ErrorKind::ReentrantOperation,
        "Engine shutdown cannot synchronously join its own callback stack",
    ))
}

/// Builder for one independently owned Engine.
#[derive(Clone, Debug)]
pub struct EngineBuilder {
    config: EngineConfig,
    http_backend: Option<HttpBackend>,
}

impl EngineBuilder {
    /// Starts a spawned Engine configuration.
    #[must_use]
    pub fn spawned() -> Self {
        Self {
            config: EngineConfig::spawned(),
            http_backend: None,
        }
    }

    /// Starts a manual Engine configuration.
    #[must_use]
    pub fn manual() -> Self {
        Self {
            config: EngineConfig::manual(),
            http_backend: None,
        }
    }

    /// Replaces the backend-neutral configuration.
    #[must_use]
    pub fn config(mut self, config: EngineConfig) -> Self {
        self.config = config;
        self
    }

    /// Explicitly selects an HTTP implementation.
    ///
    /// Cargo features control whether the selected implementation is available. They never alter
    /// an explicit selection. Omitting this call uses [`Engine::new`], which selects native when
    /// compiled and otherwise fails with [`ErrorKind::Unsupported`].
    #[must_use]
    pub fn http_backend(mut self, backend: HttpBackend) -> Self {
        self.http_backend = Some(backend);
        self
    }

    /// Selects the Engine-owned callback worker count.
    #[must_use]
    pub fn callback_workers(mut self, workers: NonZeroUsize) -> Self {
        self.config = self.config.with_callback_workers(workers);
        self
    }

    /// Selects the accepted/inflight request bound.
    #[must_use]
    pub fn max_inflight_requests(mut self, requests: NonZeroUsize) -> Self {
        self.config = self.config.with_max_inflight_requests(requests);
        self
    }

    /// Selects the bounded command queue capacity.
    #[must_use]
    pub fn command_queue_capacity(mut self, capacity: NonZeroUsize) -> Self {
        self.config = self.config.with_command_queue_capacity(capacity);
        self
    }

    /// Selects the bounded callback event and callback-bearing request capacity.
    #[must_use]
    pub fn callback_queue_capacity(mut self, capacity: NonZeroUsize) -> Self {
        self.config = self.config.with_callback_queue_capacity(capacity);
        self
    }

    /// Selects the maximum buffered request-body size.
    #[must_use]
    pub fn max_request_body_bytes(mut self, bytes: usize) -> Self {
        self.config = self.config.with_max_request_body_bytes(bytes);
        self
    }

    /// Selects the maximum buffered response-body size.
    #[must_use]
    pub fn max_response_body_bytes(mut self, bytes: usize) -> Self {
        self.config = self.config.with_max_response_body_bytes(bytes);
        self
    }

    /// Caps aggregate retained buffered HTTP body capacity; disabled by default.
    #[must_use]
    pub fn max_buffered_body_bytes(mut self, bytes: usize) -> Self {
        self.config = self.config.with_max_buffered_body_bytes(bytes);
        self
    }

    /// Selects the maximum per-request streaming upload or response queue window.
    #[must_use]
    pub fn max_stream_queue_bytes_per_request(mut self, bytes: usize) -> Self {
        self.config = self.config.with_max_stream_queue_bytes_per_request(bytes);
        self
    }

    /// Selects the Engine-wide reserved streaming queue budget.
    #[must_use]
    pub fn max_stream_queued_bytes(mut self, bytes: usize) -> Self {
        self.config = self.config.with_max_stream_queued_bytes(bytes);
        self
    }

    /// Selects the Engine-wide queue budget shared by HTTP streams and standalone TCP.
    #[must_use]
    pub fn max_queued_bytes(mut self, bytes: usize) -> Self {
        self.config = self.config.with_max_queued_bytes(bytes);
        self
    }

    /// Selects the maximum cumulative request/response header bytes.
    #[must_use]
    pub fn max_header_bytes(mut self, bytes: usize) -> Self {
        self.config = self.config.with_max_header_bytes(bytes);
        self
    }

    /// Selects the maximum request/response header field count.
    #[must_use]
    pub fn max_header_count(mut self, count: usize) -> Self {
        self.config = self.config.with_max_header_count(count);
        self
    }

    /// Selects the Engine-wide connecting, leased, and idle connection limit.
    #[must_use]
    pub fn max_connections(mut self, connections: NonZeroUsize) -> Self {
        self.config = self.config.with_max_connections(connections);
        self
    }

    /// Selects the per-origin connecting, leased, and idle connection limit.
    #[must_use]
    pub fn max_connections_per_origin(mut self, connections: NonZeroUsize) -> Self {
        self.config = self.config.with_max_connections_per_origin(connections);
        self
    }

    /// Selects the Engine-wide idle connection limit. Zero disables idle reuse.
    #[must_use]
    pub fn max_idle_connections(mut self, connections: usize) -> Self {
        self.config = self.config.with_max_idle_connections(connections);
        self
    }

    /// Selects the per-origin idle connection limit. Zero disables idle reuse.
    #[must_use]
    pub fn max_idle_connections_per_origin(mut self, connections: usize) -> Self {
        self.config = self
            .config
            .with_max_idle_connections_per_origin(connections);
        self
    }

    /// Selects how long an unused persistent connection may remain pooled.
    #[must_use]
    pub fn idle_connection_timeout(mut self, timeout: Duration) -> Self {
        self.config = self.config.with_idle_connection_timeout(timeout);
        self
    }

    /// Selects the DNS inflight budget shared by public Resolver operations (when compiled) and
    /// hostname TCP connects.
    #[must_use]
    pub fn max_inflight_resolutions(mut self, resolutions: NonZeroUsize) -> Self {
        self.config = self.config.with_max_inflight_resolutions(resolutions);
        self
    }

    /// Selects the standalone TCP connect/live-connection budget.
    #[must_use]
    pub fn max_standalone_tcp_connections(mut self, connections: NonZeroUsize) -> Self {
        self.config = self.config.with_max_standalone_tcp_connections(connections);
        self
    }

    /// Selects the Engine ceiling for addresses retained by one DNS result or hostname-connect
    /// attempt.
    #[must_use]
    pub fn max_resolve_results(mut self, results: NonZeroUsize) -> Self {
        self.config = self.config.with_max_resolve_results(results);
        self
    }

    /// Selects the maximum send or unread-receive queue window for one standalone TCP connection.
    #[must_use]
    pub fn max_tcp_queue_bytes_per_connection(mut self, bytes: usize) -> Self {
        self.config = self.config.with_max_tcp_queue_bytes_per_connection(bytes);
        self
    }

    /// Builds one independent Engine.
    pub fn build(self) -> Result<Engine, Error> {
        match self.http_backend {
            Some(backend) => Engine::with_http_backend(self.config, backend),
            None => Engine::new(self.config),
        }
    }
}

#[cfg_attr(feature = "native", allow(dead_code))]
fn unavailable_http_backend(backend: &str) -> Error {
    Error::new(
        ErrorKind::Unsupported,
        format!("the {backend} HTTP backend is not compiled into this NBReq build"),
    )
}

#[cfg(test)]
mod tests {
    use std::panic::{AssertUnwindSafe, catch_unwind};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[cfg(feature = "native")]
    use crate::CallbackDispatch;
    use crate::backend::BackendCompletion;
    use crate::stream::ResponseSink;
    use crate::{Completion, Request, RequestId, StreamError, StreamRequest};

    use super::*;

    struct FailOnceBackend {
        shutdown_attempts: Arc<AtomicUsize>,
    }

    impl Backend for FailOnceBackend {
        fn submit(
            &mut self,
            _id: RequestId,
            _request: Request,
            _accepted_at: Instant,
        ) -> Option<Completion> {
            None
        }

        fn cancel(&mut self, _id: RequestId) {}

        fn poll(&mut self, _deadline: Instant) -> Result<Vec<BackendCompletion>, Error> {
            Ok(Vec::new())
        }

        fn shutdown(&mut self) -> Result<(), ShutdownError> {
            if self.shutdown_attempts.fetch_add(1, Ordering::Relaxed) == 0 {
                Err(ShutdownError::new(Error::new(
                    ErrorKind::Internal,
                    "deliberate first shutdown failure",
                )))
            } else {
                Ok(())
            }
        }
    }

    struct PanicOnceBackend {
        should_panic: bool,
    }

    struct PanicOnSubmitBackend;

    struct PanicOnStreamSubmitBackend {
        response: Option<ResponseSink>,
    }

    impl Backend for PanicOnSubmitBackend {
        fn submit(
            &mut self,
            _id: RequestId,
            _request: Request,
            _accepted_at: Instant,
        ) -> Option<Completion> {
            panic!("deliberate spawned reactor panic");
        }

        fn cancel(&mut self, _id: RequestId) {}

        fn poll(&mut self, _deadline: Instant) -> Result<Vec<BackendCompletion>, Error> {
            Ok(Vec::new())
        }

        fn shutdown(&mut self) -> Result<(), ShutdownError> {
            Ok(())
        }
    }

    impl Backend for PanicOnStreamSubmitBackend {
        fn submit(
            &mut self,
            _id: RequestId,
            _request: Request,
            _accepted_at: Instant,
        ) -> Option<Completion> {
            None
        }

        fn submit_stream(
            &mut self,
            _id: RequestId,
            _request: StreamRequest,
            response: ResponseSink,
            _accepted_at: Instant,
        ) {
            self.response = Some(response);
            panic!("deliberate spawned stream reactor panic");
        }

        fn cancel(&mut self, _id: RequestId) {}

        fn poll(&mut self, _deadline: Instant) -> Result<Vec<BackendCompletion>, Error> {
            Ok(Vec::new())
        }

        fn shutdown(&mut self) -> Result<(), ShutdownError> {
            Ok(())
        }

        fn supports_streaming(&self) -> bool {
            true
        }
    }

    impl Backend for PanicOnceBackend {
        fn submit(
            &mut self,
            _id: RequestId,
            _request: Request,
            _accepted_at: Instant,
        ) -> Option<Completion> {
            None
        }

        fn cancel(&mut self, _id: RequestId) {}

        fn poll(&mut self, _deadline: Instant) -> Result<Vec<BackendCompletion>, Error> {
            if self.should_panic {
                self.should_panic = false;
                panic!("deliberate drive panic");
            }
            Ok(Vec::new())
        }

        fn shutdown(&mut self) -> Result<(), ShutdownError> {
            Ok(())
        }
    }

    #[test]
    fn failed_backend_shutdown_seals_and_remains_retryable() {
        let attempts = Arc::new(AtomicUsize::new(0));
        let mut engine = Engine::with_backend(
            EngineConfig::manual(),
            Box::new(FailOnceBackend {
                shutdown_attempts: Arc::clone(&attempts),
            }),
        )
        .expect("Engine must construct");

        assert!(engine.stop_network().is_err());
        assert!(engine.shared.stopped.load(Ordering::Acquire));
        assert!(
            engine
                .dispatcher
                .as_ref()
                .is_some_and(|owner| owner.is_sealed())
        );

        engine
            .stop_network()
            .expect("a second teardown attempt must reach the backend");
        assert_eq!(attempts.load(Ordering::Relaxed), 2);
    }

    #[test]
    fn consuming_shutdown_drop_retries_failed_backend_teardown() {
        let attempts = Arc::new(AtomicUsize::new(0));
        let engine = Engine::with_backend(
            EngineConfig::manual(),
            Box::new(FailOnceBackend {
                shutdown_attempts: Arc::clone(&attempts),
            }),
        )
        .expect("Engine must construct");

        assert!(engine.shutdown().is_err());
        assert_eq!(attempts.load(Ordering::Relaxed), 2);
    }

    #[test]
    fn spawned_shutdown_failure_is_remembered_after_join_handle_is_consumed() {
        let attempts = Arc::new(AtomicUsize::new(0));
        let mut engine = Engine::with_backend(
            EngineConfig::spawned(),
            Box::new(FailOnceBackend {
                shutdown_attempts: Arc::clone(&attempts),
            }),
        )
        .expect("Engine must construct");

        assert!(engine.stop_network().is_err());
        assert!(engine.stop_network().is_err());
        assert_eq!(attempts.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn drive_guard_clears_reentrancy_flag_during_unwind() {
        let mut engine = Engine::with_backend(
            EngineConfig::manual(),
            Box::new(PanicOnceBackend { should_panic: true }),
        )
        .expect("Engine must construct");

        let panic = catch_unwind(AssertUnwindSafe(|| engine.drive(Instant::now())));
        assert!(panic.is_err());

        let status = engine
            .drive(Instant::now())
            .expect("drive must be usable after a contained backend panic");
        assert_eq!(status, DriveStatus::DeadlineReached);
    }

    #[test]
    fn spawned_reactor_panic_fails_accepted_waiters_instead_of_stranding_them() {
        let engine = Engine::with_backend(EngineConfig::spawned(), Box::new(PanicOnSubmitBackend))
            .expect("Engine must construct");
        let pending = engine
            .client()
            .submit(
                Request::get("https://example.invalid/")
                    .build()
                    .expect("request must build"),
            )
            .expect("request must be accepted before the reactor panic");

        match pending.wait_for(Duration::from_secs(1)) {
            crate::WaitOutcome::Completed(Completion::Failed(error)) => {
                assert_eq!(error.kind(), ErrorKind::Internal);
                assert_eq!(error.message(), "NBReq reactor thread panicked");
            }
            other => panic!("reactor panic stranded or miscompleted the waiter: {other:?}"),
        }
        let shutdown = engine
            .shutdown()
            .expect_err("the contained reactor panic must remain observable at shutdown");
        assert_eq!(shutdown.error().kind(), ErrorKind::Internal);
    }

    #[test]
    fn spawned_reactor_panic_beats_backend_sink_drop_for_stream_readers() {
        let engine = Engine::with_backend(
            EngineConfig::spawned(),
            Box::new(PanicOnStreamSubmitBackend { response: None }),
        )
        .expect("Engine must construct");
        let mut reader = engine
            .client()
            .submit_stream(
                StreamRequest::get("http://example.test/")
                    .build()
                    .expect("stream request must build"),
            )
            .expect("stream request must be accepted before the reactor panic");

        match reader.wait_head() {
            Err(StreamError::Failed(error)) => {
                assert_eq!(error.kind(), ErrorKind::Internal);
                assert_eq!(error.message(), "NBReq reactor thread panicked");
            }
            other => panic!("reactor panic did not win the stream terminal race: {other:?}"),
        }
        let shutdown = engine
            .shutdown()
            .expect_err("the contained stream reactor panic must remain observable at shutdown");
        assert_eq!(shutdown.error().kind(), ErrorKind::Internal);
    }

    #[test]
    #[cfg(feature = "native")]
    fn builder_sets_engine_configuration() {
        let workers = NonZeroUsize::new(3).expect("three is non-zero");
        let command_capacity = NonZeroUsize::new(7).expect("seven is non-zero");
        let callback_capacity = NonZeroUsize::new(9).expect("nine is non-zero");
        let connection_capacity = NonZeroUsize::new(11).expect("eleven is non-zero");
        let origin_capacity = NonZeroUsize::new(5).expect("five is non-zero");
        let idle_timeout = Duration::from_secs(17);
        let engine = EngineBuilder::spawned()
            .callback_workers(workers)
            .max_inflight_requests(command_capacity)
            .command_queue_capacity(command_capacity)
            .callback_queue_capacity(callback_capacity)
            .max_connections(connection_capacity)
            .max_connections_per_origin(origin_capacity)
            .max_idle_connections(6)
            .max_idle_connections_per_origin(2)
            .idle_connection_timeout(idle_timeout)
            .max_inflight_resolutions(command_capacity)
            .max_standalone_tcp_connections(origin_capacity)
            .max_resolve_results(origin_capacity)
            .max_tcp_queue_bytes_per_connection(6)
            .max_queued_bytes(12)
            .build()
            .expect("Engine must construct");
        assert_eq!(
            engine.config.callback_dispatch(),
            CallbackDispatch::Workers(workers)
        );
        assert_eq!(engine.config.max_inflight_requests(), command_capacity);
        assert_eq!(engine.config.command_queue_capacity(), command_capacity);
        assert_eq!(engine.config.callback_queue_capacity(), callback_capacity);
        assert_eq!(engine.config.max_connections(), connection_capacity);
        assert_eq!(engine.config.max_connections_per_origin(), origin_capacity);
        assert_eq!(engine.config.max_idle_connections(), 6);
        assert_eq!(engine.config.max_idle_connections_per_origin(), 2);
        assert_eq!(engine.config.idle_connection_timeout(), idle_timeout);
        assert_eq!(engine.config.max_inflight_resolutions(), command_capacity);
        assert_eq!(
            engine.config.max_standalone_tcp_connections(),
            origin_capacity
        );
        assert_eq!(engine.config.max_resolve_results(), origin_capacity);
        assert_eq!(engine.config.max_tcp_queue_bytes_per_connection(), 6);
        assert_eq!(engine.config.max_queued_bytes(), 12);
    }
}