relay-knowledge 1.1.10

Graph-database-based knowledge graph project.
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
//! HTTP client and server runtime owned by the network boundary.
//!
//! This module owns validated HTTP configuration, outbound JSON client policy,
//! the bounded raw JSON POST helper, async Axum router serving, request body
//! limits, per-request timeouts, graceful shutdown, and QoS-gated listener
//! admission. Higher layers should use these APIs instead of constructing
//! sockets, listeners, HTTP clients, or HTTP server loops directly.

use std::{
    convert::Infallible,
    error::Error,
    fmt,
    future::{Future, IntoFuture, Ready, ready},
    io,
    net::IpAddr,
    pin::Pin,
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
    task::{Context, Poll},
    time::Duration,
};

use axum::{
    Router,
    extract::Request,
    http::StatusCode,
    response::{IntoResponse, Response},
    serve::{IncomingStream, Listener},
};
use serde_json::Value;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf};
use tower::Service;

use crate::{
    env::NetworkEnvOverrides,
    net::qos::{QosPermit, QosPolicy, QosRuntime, RejectReason},
};

pub const DEFAULT_HTTP_BIND: &str = "127.0.0.1:8791";
pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
pub const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10);
pub const DEFAULT_MAX_BODY_BYTES: u64 = 1_048_576;
pub const DEFAULT_SSL_VERIFY: bool = true;

/// Event-driven HTTP configuration for inbound and outbound adapters.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpConfig {
    pub bind_address: HttpBindAddress,
    pub request_timeout: Duration,
    pub graceful_shutdown_timeout: Duration,
    pub max_request_body_bytes: u64,
    pub proxy: HttpProxyConfig,
}

/// Validated HTTP bind address in `host:port` form.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpBindAddress {
    value: String,
    port: u16,
}

impl HttpBindAddress {
    /// Parses a host or IP literal with an explicit non-zero port.
    pub fn parse(value: &str) -> Result<Self, HttpConfigError> {
        let trimmed = value.trim();
        if trimmed.is_empty() {
            return Err(HttpConfigError::InvalidBindAddress {
                value: value.to_owned(),
            });
        }

        if let Ok(socket_addr) = trimmed.parse::<std::net::SocketAddr>() {
            return Self::from_parts(trimmed.to_owned(), socket_addr.port());
        }

        let Some((host, port)) = trimmed.rsplit_once(':') else {
            return Err(HttpConfigError::InvalidBindAddress {
                value: value.to_owned(),
            });
        };

        if host.is_empty() || host.contains('/') || host.contains(char::is_whitespace) {
            return Err(HttpConfigError::InvalidBindAddress {
                value: value.to_owned(),
            });
        }

        let port = port
            .parse::<u16>()
            .map_err(|_| HttpConfigError::InvalidBindAddress {
                value: value.to_owned(),
            })?;

        Self::from_parts(trimmed.to_owned(), port)
    }

    /// Returns the explicit TCP port.
    pub const fn port(&self) -> u16 {
        self.port
    }

    fn from_parts(value: String, port: u16) -> Result<Self, HttpConfigError> {
        if port == 0 {
            return Err(HttpConfigError::EphemeralPort);
        }

        Ok(Self { value, port })
    }
}

impl fmt::Display for HttpBindAddress {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.value)
    }
}

/// Returns whether a listener may accept non-local clients under the access policy.
pub fn remote_clients_allowed(config: &HttpConfig, allow_remote_clients: bool) -> bool {
    allow_remote_clients || is_local_bind(&config.bind_address.to_string())
}

/// Outbound HTTP proxy and TLS verification policy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpProxyConfig {
    pub proxy: Option<String>,
    pub no_proxy_rules: Vec<String>,
    pub ssl_verify: bool,
}

/// Builds an async outbound JSON client from validated network policy.
pub fn outbound_json_client(config: &HttpConfig) -> Result<reqwest::Client, OutboundClientError> {
    outbound_json_client_with_policy(config, None, None)
}

/// Builds an async outbound JSON client with request-scoped transport policy.
pub fn outbound_json_client_with_policy(
    config: &HttpConfig,
    ssl_verify: Option<bool>,
    connect_timeout: Option<Duration>,
) -> Result<reqwest::Client, OutboundClientError> {
    let mut builder = reqwest::Client::builder()
        .timeout(config.request_timeout)
        .danger_accept_invalid_certs(!ssl_verify.unwrap_or(config.proxy.ssl_verify));
    if let Some(timeout) = connect_timeout {
        builder = builder.connect_timeout(timeout);
    }
    if let Some(proxy_url) = &config.proxy.proxy {
        let no_proxy = reqwest::NoProxy::from_string(&config.proxy.no_proxy_rules.join(","));
        let proxy = reqwest::Proxy::all(proxy_url)
            .map_err(|error| OutboundClientError {
                message: error.to_string(),
            })?
            .no_proxy(no_proxy);
        builder = builder.proxy(proxy);
    }

    builder.build().map_err(|error| OutboundClientError {
        message: error.to_string(),
    })
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutboundClientError {
    pub message: String,
}
impl fmt::Display for OutboundClientError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.message.fmt(formatter)
    }
}

impl Error for OutboundClientError {}

impl HttpProxyConfig {
    /// Validates proxy URL shape and no-proxy entries without exposing credentials.
    pub fn new(
        proxy: Option<String>,
        no_proxy_rules: Vec<String>,
        ssl_verify: bool,
    ) -> Result<Self, HttpConfigError> {
        if let Some(proxy_url) = proxy.as_deref() {
            validate_proxy_url(proxy_url)?;
        }

        for rule in &no_proxy_rules {
            if rule.trim().is_empty() {
                return Err(HttpConfigError::EmptyNoProxyRule);
            }
        }

        Ok(Self {
            proxy,
            no_proxy_rules,
            ssl_verify,
        })
    }

    /// Applies proxy, no-proxy, and TLS verification environment overrides.
    pub fn from_overrides(overrides: &NetworkEnvOverrides) -> Result<Self, HttpConfigError> {
        Self::new(
            overrides.proxy.clone(),
            parse_no_proxy_rules(overrides.no_proxy.as_deref())?,
            overrides.ssl_verify.unwrap_or(DEFAULT_SSL_VERIFY),
        )
    }

    /// Returns whether outbound HTTP should use a proxy.
    pub fn is_proxy_configured(&self) -> bool {
        self.proxy.is_some()
    }
}

impl HttpConfig {
    /// Builds HTTP config while enforcing bounded request and shutdown behavior.
    pub fn new(
        bind_address: HttpBindAddress,
        request_timeout: Duration,
        graceful_shutdown_timeout: Duration,
        max_request_body_bytes: u64,
        proxy: HttpProxyConfig,
    ) -> Result<Self, HttpConfigError> {
        if request_timeout.is_zero() {
            return Err(HttpConfigError::ZeroDuration {
                field: "request_timeout",
            });
        }

        if graceful_shutdown_timeout.is_zero() {
            return Err(HttpConfigError::ZeroDuration {
                field: "graceful_shutdown_timeout",
            });
        }

        if max_request_body_bytes == 0 {
            return Err(HttpConfigError::ZeroMaxBodyBytes);
        }

        Ok(Self {
            bind_address,
            request_timeout,
            graceful_shutdown_timeout,
            max_request_body_bytes,
            proxy,
        })
    }

    /// Applies environment overrides to the default local HTTP policy.
    pub fn from_overrides(overrides: &NetworkEnvOverrides) -> Result<Self, HttpConfigError> {
        let bind_value = overrides.http_bind.as_deref().unwrap_or(DEFAULT_HTTP_BIND);
        let bind_address = HttpBindAddress::parse(bind_value)?;
        let request_timeout = overrides
            .http_request_timeout_ms
            .map(Duration::from_millis)
            .unwrap_or(DEFAULT_REQUEST_TIMEOUT);
        let shutdown_timeout = overrides
            .http_shutdown_timeout_ms
            .map(Duration::from_millis)
            .unwrap_or(DEFAULT_SHUTDOWN_TIMEOUT);
        let max_body_bytes = overrides
            .http_max_body_bytes
            .unwrap_or(DEFAULT_MAX_BODY_BYTES);
        let proxy = HttpProxyConfig::from_overrides(overrides)?;

        Self::new(
            bind_address,
            request_timeout,
            shutdown_timeout,
            max_body_bytes,
            proxy,
        )
    }
}

/// HTTP configuration validation error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HttpConfigError {
    InvalidBindAddress { value: String },
    EphemeralPort,
    ZeroDuration { field: &'static str },
    ZeroMaxBodyBytes,
    InvalidProxyUrl,
    EmptyNoProxyRule,
}

impl fmt::Display for HttpConfigError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidBindAddress { value } => {
                write!(formatter, "bind address '{value}' is not host:port")
            }
            Self::EphemeralPort => write!(formatter, "bind address must use an explicit port"),
            Self::ZeroDuration { field } => write!(formatter, "{field} must be greater than zero"),
            Self::ZeroMaxBodyBytes => write!(
                formatter,
                "max request body bytes must be greater than zero"
            ),
            Self::InvalidProxyUrl => write!(
                formatter,
                "proxy must use http:// or https:// and include a host"
            ),
            Self::EmptyNoProxyRule => write!(formatter, "no-proxy entries must not be empty"),
        }
    }
}

impl Error for HttpConfigError {}

/// Error raised while serving an event-driven HTTP adapter.
#[derive(Debug)]
pub enum HttpServeError {
    Bind(std::io::Error),
    Serve(std::io::Error),
    ShutdownTimeout,
}

impl fmt::Display for HttpServeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bind(error) => write!(formatter, "failed to bind HTTP listener: {error}"),
            Self::Serve(error) => write!(formatter, "HTTP server failed: {error}"),
            Self::ShutdownTimeout => write!(formatter, "HTTP graceful shutdown timed out"),
        }
    }
}

impl Error for HttpServeError {}

/// Error raised by bounded outbound JSON HTTP calls.
#[derive(Debug)]
pub enum HttpClientError {
    InvalidUrl(String),
    Io(io::Error),
    Timeout,
    InvalidResponse,
    ResponseStatus(u16),
    ResponseJson(serde_json::Error),
}

impl fmt::Display for HttpClientError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidUrl(value) => write!(formatter, "invalid HTTP worker URL: {value}"),
            Self::Io(error) => write!(formatter, "HTTP worker request failed: {error}"),
            Self::Timeout => write!(formatter, "HTTP worker request timed out"),
            Self::InvalidResponse => write!(formatter, "HTTP worker returned invalid response"),
            Self::ResponseStatus(status) => {
                write!(formatter, "HTTP worker returned status {status}")
            }
            Self::ResponseJson(error) => {
                write!(formatter, "HTTP worker returned invalid JSON: {error}")
            }
        }
    }
}

impl Error for HttpClientError {}

/// Posts a JSON payload through the network boundary using the configured timeout.
pub async fn post_json(
    config: &HttpConfig,
    url: &str,
    payload: &Value,
) -> Result<Value, HttpClientError> {
    let request = JsonHttpRequest::parse(url)?;
    let body = serde_json::to_vec(payload).map_err(HttpClientError::ResponseJson)?;
    let response = tokio::time::timeout(config.request_timeout, send_json_request(request, body))
        .await
        .map_err(|_| HttpClientError::Timeout)??;

    serde_json::from_slice(&response).map_err(HttpClientError::ResponseJson)
}

struct JsonHttpRequest {
    host: String,
    port: u16,
    path: String,
}

impl JsonHttpRequest {
    fn parse(value: &str) -> Result<Self, HttpClientError> {
        let remainder = value
            .strip_prefix("http://")
            .ok_or_else(|| HttpClientError::InvalidUrl(value.to_owned()))?;
        let (authority, path) = remainder
            .split_once('/')
            .map_or((remainder, "/"), |(authority, path)| {
                (authority, path.trim_start_matches('/'))
            });
        if authority.is_empty() {
            return Err(HttpClientError::InvalidUrl(value.to_owned()));
        }
        let (host, port) = authority
            .rsplit_once(':')
            .map(|(host, port)| {
                let parsed_port = port
                    .parse::<u16>()
                    .map_err(|_| HttpClientError::InvalidUrl(value.to_owned()))?;
                Ok((host.to_owned(), parsed_port))
            })
            .unwrap_or_else(|| Ok((authority.to_owned(), 80)))?;
        if host.is_empty() || port == 0 {
            return Err(HttpClientError::InvalidUrl(value.to_owned()));
        }
        let path = if path.is_empty() {
            "/".to_owned()
        } else {
            format!("/{path}")
        };

        Ok(Self { host, port, path })
    }
}

async fn send_json_request(
    request: JsonHttpRequest,
    body: Vec<u8>,
) -> Result<Vec<u8>, HttpClientError> {
    let mut stream = tokio::net::TcpStream::connect((request.host.as_str(), request.port))
        .await
        .map_err(HttpClientError::Io)?;
    let head = format!(
        "POST {} HTTP/1.1\r\nHost: {}\r\nContent-Type: application/json\r\nAccept: application/json\r\nConnection: close\r\nContent-Length: {}\r\n\r\n",
        request.path,
        request.host,
        body.len()
    );
    stream
        .write_all(head.as_bytes())
        .await
        .map_err(HttpClientError::Io)?;
    stream.write_all(&body).await.map_err(HttpClientError::Io)?;
    stream.shutdown().await.map_err(HttpClientError::Io)?;
    let mut response = Vec::new();
    stream
        .read_to_end(&mut response)
        .await
        .map_err(HttpClientError::Io)?;
    parse_http_response(response)
}

fn parse_http_response(response: Vec<u8>) -> Result<Vec<u8>, HttpClientError> {
    let Some(header_end) = response.windows(4).position(|window| window == b"\r\n\r\n") else {
        return Err(HttpClientError::InvalidResponse);
    };
    let headers = std::str::from_utf8(&response[..header_end])
        .map_err(|_| HttpClientError::InvalidResponse)?;
    let status = headers
        .lines()
        .next()
        .and_then(|line| line.split_whitespace().nth(1))
        .and_then(|value| value.parse::<u16>().ok())
        .ok_or(HttpClientError::InvalidResponse)?;
    if !(200..300).contains(&status) {
        return Err(HttpClientError::ResponseStatus(status));
    }

    Ok(response[header_end + 4..].to_vec())
}

/// Stable identifier assigned to an accepted HTTP connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HttpConnectionId(u64);

impl HttpConnectionId {
    /// Returns the numeric connection identifier for request correlation.
    pub const fn get(self) -> u64 {
        self.0
    }
}

/// Starts an async HTTP server with graceful shutdown under the network boundary.
pub async fn serve_router(
    router: Router,
    config: HttpConfig,
    shutdown: impl Future<Output = ()> + Send + 'static,
) -> Result<(), HttpServeError> {
    let listener = tokio::net::TcpListener::bind(config.bind_address.to_string())
        .await
        .map_err(HttpServeError::Bind)?;

    serve_listener(listener, router, config, shutdown).await
}

/// Starts an async HTTP server whose accepted connections consume QoS permits.
pub async fn serve_router_with_qos(
    router: Router,
    config: HttpConfig,
    qos: QosRuntime,
    policy: QosPolicy,
    shutdown: impl Future<Output = ()> + Send + 'static,
) -> Result<(), HttpServeError> {
    let listener = tokio::net::TcpListener::bind(config.bind_address.to_string())
        .await
        .map_err(HttpServeError::Bind)?;
    let listener = QosTcpListener::new(listener, qos, policy);

    serve_listener(listener, router, config, shutdown).await
}

async fn serve_listener<L>(
    listener: L,
    router: Router,
    config: HttpConfig,
    shutdown: impl Future<Output = ()> + Send + 'static,
) -> Result<(), HttpServeError>
where
    L: Listener,
    L::Addr: fmt::Debug,
{
    let (shutdown_started, mut shutdown_observed) = tokio::sync::watch::channel(false);
    let graceful_shutdown = async move {
        shutdown.await;
        let _ = shutdown_started.send(true);
    };
    let server = axum::serve(
        listener,
        HttpMakeService::new(router, config.request_timeout),
    )
    .with_graceful_shutdown(graceful_shutdown)
    .into_future();

    tokio::pin!(server);
    tokio::select! {
        result = &mut server => result.map_err(HttpServeError::Serve),
        changed = shutdown_observed.changed() => {
            let _ = changed;
            match tokio::time::timeout(config.graceful_shutdown_timeout, &mut server).await {
                Ok(result) => result.map_err(HttpServeError::Serve),
                Err(_) => Err(HttpServeError::ShutdownTimeout),
            }
        }
    }
}

struct HttpMakeService {
    router: Router,
    request_timeout: Duration,
    next_connection_id: Arc<AtomicU64>,
}

impl HttpMakeService {
    fn new(router: Router, request_timeout: Duration) -> Self {
        Self {
            router,
            request_timeout,
            next_connection_id: Arc::new(AtomicU64::new(1)),
        }
    }
}

impl<'a, L> Service<IncomingStream<'a, L>> for HttpMakeService
where
    L: Listener,
{
    type Response = HttpConnectionService<Router>;
    type Error = Infallible;
    type Future = Ready<Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, _context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, _target: IncomingStream<'a, L>) -> Self::Future {
        let connection_id =
            HttpConnectionId(self.next_connection_id.fetch_add(1, Ordering::Relaxed));
        ready(Ok(HttpConnectionService::new(
            self.router.clone(),
            connection_id,
            self.request_timeout,
        )))
    }
}

struct HttpConnectionService<S> {
    inner: S,
    connection_id: HttpConnectionId,
    request_timeout: Duration,
}

impl<S> HttpConnectionService<S> {
    fn new(inner: S, connection_id: HttpConnectionId, request_timeout: Duration) -> Self {
        Self {
            inner,
            connection_id,
            request_timeout,
        }
    }
}

impl<S> Clone for HttpConnectionService<S>
where
    S: Clone,
{
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            connection_id: self.connection_id,
            request_timeout: self.request_timeout,
        }
    }
}

impl<S> Service<Request> for HttpConnectionService<S>
where
    S: Service<Request, Response = Response, Error = Infallible> + Send,
    S::Future: Send + 'static,
{
    type Response = Response;
    type Error = Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(context)
    }

    fn call(&mut self, mut request: Request) -> Self::Future {
        request.extensions_mut().insert(self.connection_id);
        let future = self.inner.call(request);
        let request_timeout = self.request_timeout;
        Box::pin(async move {
            match tokio::time::timeout(request_timeout, future).await {
                Ok(result) => result,
                Err(_) => Ok((StatusCode::REQUEST_TIMEOUT, "request timed out").into_response()),
            }
        })
    }
}

struct QosTcpListener {
    inner: tokio::net::TcpListener,
    qos: QosRuntime,
    policy: QosPolicy,
}

impl QosTcpListener {
    fn new(inner: tokio::net::TcpListener, qos: QosRuntime, policy: QosPolicy) -> Self {
        Self { inner, qos, policy }
    }
}

impl Listener for QosTcpListener {
    type Io = QosTcpStream;
    type Addr = std::net::SocketAddr;

    async fn accept(&mut self) -> (Self::Io, Self::Addr) {
        loop {
            match self.inner.accept().await {
                Ok((stream, address)) => match self.qos.admit_connection(&self.policy) {
                    Ok(permit) => {
                        return (
                            QosTcpStream {
                                inner: stream,
                                _permit: permit,
                            },
                            address,
                        );
                    }
                    Err(RejectReason::ConnectionBudgetExceeded) => drop(stream),
                    Err(_) => drop(stream),
                },
                Err(_) => tokio::time::sleep(Duration::from_secs(1)).await,
            }
        }
    }

    fn local_addr(&self) -> io::Result<Self::Addr> {
        self.inner.local_addr()
    }
}

struct QosTcpStream {
    inner: tokio::net::TcpStream,
    _permit: QosPermit,
}

impl AsyncRead for QosTcpStream {
    fn poll_read(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        buffer: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        Pin::new(&mut self.inner).poll_read(context, buffer)
    }
}

impl AsyncWrite for QosTcpStream {
    fn poll_write(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        buffer: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.inner).poll_write(context, buffer)
    }

    fn poll_flush(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.inner).poll_flush(context)
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.inner).poll_shutdown(context)
    }
}

fn validate_proxy_url(value: &str) -> Result<(), HttpConfigError> {
    let Some((scheme, remainder)) = value.split_once("://") else {
        return Err(HttpConfigError::InvalidProxyUrl);
    };

    if !matches!(scheme, "http" | "https") {
        return Err(HttpConfigError::InvalidProxyUrl);
    }

    let authority = remainder.split('/').next().unwrap_or_default();
    if authority.is_empty() || authority.starts_with('@') {
        return Err(HttpConfigError::InvalidProxyUrl);
    }
    let host_port = authority
        .rsplit_once('@')
        .map_or(authority, |(_, host)| host);
    let host = if let Some(remainder) = host_port.strip_prefix('[') {
        remainder.split_once(']').map_or("", |(host, _)| host)
    } else {
        host_port.split(':').next().unwrap_or_default()
    };
    if host.is_empty() {
        return Err(HttpConfigError::InvalidProxyUrl);
    }

    Ok(())
}

fn parse_no_proxy_rules(value: Option<&str>) -> Result<Vec<String>, HttpConfigError> {
    value
        .map(|rules| {
            rules
                .split(',')
                .map(str::trim)
                .map(|rule| {
                    if rule.is_empty() {
                        Err(HttpConfigError::EmptyNoProxyRule)
                    } else {
                        Ok(rule.to_owned())
                    }
                })
                .collect()
        })
        .unwrap_or_else(|| Ok(Vec::new()))
}

fn is_local_bind(bind: &str) -> bool {
    is_loopback_host(authority_host(bind))
}

fn authority_host(authority: &str) -> &str {
    if let Some(remainder) = authority.strip_prefix('[') {
        return remainder
            .find(']')
            .map_or(authority, |index| &remainder[..index]);
    }

    authority
        .rsplit_once(':')
        .map_or(authority, |(host, _)| host)
}

fn is_loopback_host(host: &str) -> bool {
    host.eq_ignore_ascii_case("localhost")
        || host
            .parse::<IpAddr>()
            .is_ok_and(|address| address.is_loopback())
}

#[cfg(test)]
#[path = "http_tests.rs"]
mod tests;