turnloop-http 0.1.0-alpha.2

Sans-I/O HTTP/1.1 and HTTP/2 client and server protocols
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
//! Host-driven fetch transport policy. DNS, environment, sockets and time are inputs.
//! JS body conversions, promise dispatch and abort reason objects remain in Perry.
use crate::{
    Error, Result,
    http1::{Head, Header},
};
use std::{
    net::IpAddr,
    time::{Duration, Instant},
};
use url::Url;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Protocol {
    Http1,
    Http2,
}
pub fn from_alpn(alpn: Option<&[u8]>) -> Result<Protocol> {
    match alpn {
        Some(b"h2") => Ok(Protocol::Http2),
        None | Some(b"http/1.1") => Ok(Protocol::Http1),
        _ => Err(Error::new("UND_ERR_NOT_SUPPORTED", "unsupported ALPN")),
    }
}
/// Resolver implementations enqueue host operations; they must not block here.
pub trait Resolver {
    type Token: Copy;
    fn resolve(&mut self, hostname: &str, port: u16) -> Result<Self::Token>;
    fn poll(&mut self, token: Self::Token, addresses: &mut Vec<IpAddr>) -> Option<Result<()>>;
    fn cancel(&mut self, token: Self::Token);
}
pub const DEFAULT_MAX_REDIRECTS: usize = 20;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RedirectMode {
    Follow,
    Manual,
    Error,
}
#[derive(Debug, Clone)]
pub struct Request {
    pub url: Url,
    pub method: String,
    pub headers: Vec<Header>,
    pub body: Vec<u8>,
    pub replayable: bool,
    pub redirects: usize,
}
impl Request {
    pub fn new(url: &str, method: &str) -> Result<Self> {
        let url = Url::parse(url).map_err(|_| Error::new("ERR_INVALID_URL", "invalid URL"))?;
        if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
            return Err(Error::new("ERR_INVALID_URL", "unsupported URL scheme"));
        }
        if !url.username().is_empty() || url.password().is_some() {
            return Err(Error::new(
                "UND_ERR_INVALID_ARG",
                "URL contains credentials",
            ));
        }
        http::Method::from_bytes(method.as_bytes())
            .map_err(|_| Error::new("UND_ERR_INVALID_ARG", "invalid method"))?;
        if ["CONNECT", "TRACE", "TRACK"]
            .iter()
            .any(|m| method.eq_ignore_ascii_case(m))
        {
            return Err(Error::new("UND_ERR_INVALID_ARG", "forbidden fetch method"));
        }
        let method = if ["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]
            .iter()
            .any(|m| method.eq_ignore_ascii_case(m))
        {
            method.to_ascii_uppercase()
        } else {
            method.into()
        };
        Ok(Self {
            url,
            method,
            headers: Vec::new(),
            body: Vec::new(),
            replayable: true,
            redirects: 0,
        })
    }
    pub fn head(&self, absolute_form: bool) -> Head {
        let mut url = self.url.clone();
        url.set_fragment(None);
        let target = if absolute_form {
            url.as_str().to_owned()
        } else {
            let mut target = url.path().to_string();
            if let Some(q) = url.query() {
                target.push('?');
                target.push_str(q);
            }
            target
        };
        let mut headers = self.headers.clone();
        headers.retain(|h| !h.name.eq_ignore_ascii_case("host"));
        headers.push(Header::new("host", authority(&url)));
        Head {
            method: self.method.clone(),
            target,
            status: 0,
            version: 1,
            headers,
            keep_alive: true,
        }
    }
    /// `true` means resend the modified request; `false` exposes the response as-is.
    pub fn redirect(
        &mut self,
        status: u16,
        location: Option<&str>,
        mode: RedirectMode,
        max: usize,
    ) -> Result<bool> {
        if !matches!(status, 301 | 302 | 303 | 307 | 308) {
            return Ok(false);
        }
        if mode == RedirectMode::Manual {
            return Ok(false);
        }
        if mode == RedirectMode::Error {
            return Err(Error::new("UND_ERR_REQ_RETRY", "redirect mode is error"));
        }
        let Some(location) = location else {
            return Ok(false);
        };
        if self.redirects >= max {
            return Err(Error::new("UND_ERR_REDIRECT", "redirect count exceeded"));
        }
        let next = self
            .url
            .join(location)
            .map_err(|_| Error::new("ERR_INVALID_URL", "invalid redirect URL"))?;
        if !matches!(next.scheme(), "http" | "https")
            || !next.username().is_empty()
            || next.password().is_some()
        {
            return Err(Error::new("UND_ERR_INVALID_ARG", "invalid redirect target"));
        }
        let rewrite = (matches!(status, 301 | 302) && self.method == "POST")
            || (status == 303 && self.method != "GET" && self.method != "HEAD");
        if !rewrite && !self.replayable {
            return Err(Error::new(
                "UND_ERR_REQ_RETRY",
                "streaming body cannot be replayed",
            ));
        }
        if self.url.origin() != next.origin() {
            self.headers.retain(|h| {
                ![
                    "authorization",
                    "proxy-authorization",
                    "cookie",
                    "cookie2",
                    "host",
                ]
                .iter()
                .any(|name| h.name.eq_ignore_ascii_case(name))
            });
        }
        if rewrite {
            self.method = "GET".into();
            self.body.clear();
            self.replayable = true;
            self.headers.retain(|h| {
                ![
                    "content-encoding",
                    "content-language",
                    "content-location",
                    "content-type",
                    "content-length",
                    "transfer-encoding",
                ]
                .iter()
                .any(|name| h.name.eq_ignore_ascii_case(name))
            });
        }
        self.url = next;
        self.redirects += 1;
        Ok(true)
    }
}
fn authority(url: &Url) -> String {
    let mut result = url.host_str().unwrap_or("").to_string();
    if let Some(port) = url.port() {
        result.push(':');
        result.push_str(&port.to_string());
    }
    result
}
#[derive(Debug, Default, Clone)]
pub struct ProxyEnvironment {
    pub http_proxy: Option<String>,
    pub https_proxy: Option<String>,
    pub no_proxy: String,
}
impl ProxyEnvironment {
    /// Values are supplied by the host from HTTP_PROXY/HTTPS_PROXY/NO_PROXY (or lowercase overrides).
    pub fn proxy_for(&self, url: &Url) -> Result<Option<Url>> {
        if bypass(url, &self.no_proxy) {
            return Ok(None);
        }
        let proxy = if url.scheme() == "https" {
            self.https_proxy.as_deref()
        } else {
            self.http_proxy.as_deref()
        };
        proxy
            .filter(|p| !p.is_empty())
            .map(|p| {
                let parsed =
                    Url::parse(p).map_err(|_| Error::new("ERR_INVALID_URL", "invalid proxy"))?;
                if parsed.scheme() != "http" || parsed.host_str().is_none() {
                    return Err(Error::new(
                        "UND_ERR_NOT_SUPPORTED",
                        "only HTTP proxies are supported",
                    ));
                }
                Ok(parsed)
            })
            .transpose()
    }
}
fn bypass(url: &Url, list: &str) -> bool {
    let host = url.host_str().unwrap_or("");
    list.split(',')
        .map(str::trim)
        .filter(|x| !x.is_empty())
        .any(|entry| {
            if entry == "*" {
                return true;
            }
            let (domain, port) = if let Some((h, p)) = entry.rsplit_once(':') {
                if let Ok(p) = p.parse::<u16>() {
                    (h, Some(p))
                } else {
                    (entry, None)
                }
            } else {
                (entry, None)
            };
            if port.is_some() && port != url.port_or_known_default() {
                return false;
            }
            let domain = domain.trim_start_matches("*.").trim_start_matches('.');
            host.eq_ignore_ascii_case(domain)
                || (host.len() > domain.len()
                    && host.as_bytes()[host.len() - domain.len() - 1] == b'.'
                    && host[host.len() - domain.len()..].eq_ignore_ascii_case(domain))
        })
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PoolKey {
    pub origin: String,
    pub proxy: Option<String>,
}
impl PoolKey {
    pub fn new(url: &Url, proxy: Option<&Url>) -> Self {
        Self {
            origin: url.origin().ascii_serialization(),
            proxy: proxy.map(ToString::to_string),
        }
    }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConnectionId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Acquire {
    Connect(ConnectionId),
    Reuse(ConnectionId),
    Wait,
}
struct Slot {
    id: ConnectionId,
    key: PoolKey,
    active: usize,
    capacity: usize,
    connecting: bool,
    deadline: Option<Instant>,
    closed: bool,
}
pub struct Pool {
    slots: Vec<Slot>,
    max_per_host: usize,
    idle: Duration,
    next: u64,
}
impl Pool {
    pub fn new(max_per_host: usize, idle: Duration) -> Self {
        Self {
            slots: Vec::new(),
            max_per_host,
            idle,
            next: 1,
        }
    }
    /// A Connect reservation counts immediately, so concurrent callers cannot overbook.
    pub fn acquire(&mut self, key: &PoolKey, now: Instant) -> Acquire {
        if let Some(s) = self.slots.iter_mut().find(|s| {
            !s.closed
                && s.key == *key
                && !s.connecting
                && s.active < s.capacity
                && s.deadline.is_none_or(|d| d > now)
        }) {
            s.active += 1;
            s.deadline = None;
            return Acquire::Reuse(s.id);
        }
        if self
            .slots
            .iter()
            .filter(|s| !s.closed && s.key == *key)
            .count()
            >= self.max_per_host
        {
            return Acquire::Wait;
        }
        let id = ConnectionId(self.next);
        self.next += 1;
        let slot = Slot {
            id,
            key: key.clone(),
            active: 1,
            capacity: 1,
            connecting: true,
            deadline: None,
            closed: false,
        };
        if let Some(s) = self.slots.iter_mut().find(|s| s.closed) {
            *s = slot;
        } else {
            self.slots.push(slot);
        }
        Acquire::Connect(id)
    }
    fn slot(&mut self, id: ConnectionId) -> Result<&mut Slot> {
        self.slots
            .iter_mut()
            .find(|s| s.id == id && !s.closed)
            .ok_or(Error::new("UND_ERR_CLOSED", "unknown connection"))
    }
    pub fn connected(
        &mut self,
        id: ConnectionId,
        protocol: Protocol,
        max_streams: usize,
    ) -> Result<()> {
        let s = self.slot(id)?;
        s.connecting = false;
        s.capacity = if protocol == Protocol::Http1 {
            1
        } else {
            max_streams
        };
        Ok(())
    }
    pub fn release(&mut self, id: ConnectionId, reusable: bool, now: Instant) -> Result<()> {
        let idle = self.idle;
        let s = self.slot(id)?;
        if s.active == 0 {
            return Err(Error::new("UND_ERR_INVALID_ARG", "duplicate pool release"));
        }
        s.active -= 1;
        if !reusable {
            s.capacity = 0;
        }
        if s.active == 0 {
            s.deadline = Some(if s.capacity == 0 { now } else { now + idle });
        }
        Ok(())
    }
    pub fn closed(&mut self, id: ConnectionId) -> Result<()> {
        self.slot(id)?.closed = true;
        Ok(())
    }
    pub fn next_timeout(&self) -> Option<Instant> {
        self.slots
            .iter()
            .filter(|s| !s.closed)
            .filter_map(|s| s.deadline)
            .min()
    }
    /// Repeatedly call to obtain all Close requests at this time. No clock or timer is owned.
    pub fn handle_timeout(&mut self, now: Instant) -> Option<ConnectionId> {
        let s = self
            .slots
            .iter_mut()
            .find(|s| !s.closed && s.deadline.is_some_and(|d| d <= now))?;
        s.closed = true;
        Some(s.id)
    }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Phase {
    Connect,
    Headers,
    Body,
    Done,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Completion {
    Success,
    Error(Error),
}
pub struct Lifecycle {
    phase: Phase,
    deadline: Option<Instant>,
    terminal: Option<Completion>,
    delivered: bool,
}
impl Default for Lifecycle {
    fn default() -> Self {
        Self {
            phase: Phase::Connect,
            deadline: None,
            terminal: None,
            delivered: false,
        }
    }
}
impl Lifecycle {
    pub fn transition(&mut self, phase: Phase, deadline: Option<Instant>) {
        if self.terminal.is_none() {
            self.phase = phase;
            self.deadline = deadline;
        }
    }
    pub fn next_timeout(&self) -> Option<Instant> {
        self.deadline
    }
    pub fn handle_timeout(&mut self, now: Instant) {
        if self.deadline.is_some_and(|d| d <= now) {
            let (code, message) = match self.phase {
                Phase::Connect => ("UND_ERR_CONNECT_TIMEOUT", "Connect Timeout Error"),
                Phase::Headers => ("UND_ERR_HEADERS_TIMEOUT", "Headers Timeout Error"),
                _ => ("UND_ERR_BODY_TIMEOUT", "Body Timeout Error"),
            };
            self.finish(Completion::Error(Error::new(code, message)));
        }
    }
    pub fn abort(&mut self) {
        self.finish(Completion::Error(Error::new(
            "UND_ERR_ABORTED",
            "Request aborted",
        )));
    }
    pub fn finish(&mut self, result: Completion) {
        if self.terminal.is_none() {
            self.terminal = Some(result);
            self.phase = Phase::Done;
            self.deadline = None;
        }
    }
    pub fn poll(&mut self) -> Option<Completion> {
        if self.delivered {
            return None;
        }
        let event = self.terminal?;
        self.delivered = true;
        Some(event)
    }
}
/// After a CONNECT 2xx upgrade, the host feeds remaining bytes into TLS.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransportRequest {
    Resolve { hostname: String, port: u16 },
    UpgradeTls { server_name: String },
    Ready(Protocol),
}
pub struct Route {
    target: Url,
    proxy: Option<Url>,
    tunnel: bool,
}
impl Route {
    pub fn new(target: Url, proxy: Option<Url>) -> Self {
        Self {
            target,
            proxy,
            tunnel: false,
        }
    }
    pub fn resolve(&self) -> TransportRequest {
        let peer = self.proxy.as_ref().unwrap_or(&self.target);
        TransportRequest::Resolve {
            hostname: peer.host_str().unwrap_or("").into(),
            port: peer.port_or_known_default().unwrap_or(80),
        }
    }
    pub fn connect_head(&self, authorization: Option<&[u8]>) -> Option<Head> {
        if self.proxy.is_none() || self.target.scheme() != "https" {
            return None;
        }
        let target = format!(
            "{}:{}",
            self.target.host_str().unwrap_or(""),
            self.target.port_or_known_default().unwrap_or(443)
        );
        let mut headers = vec![Header::new("host", &target)];
        if let Some(value) = authorization {
            headers.push(Header::new("proxy-authorization", value));
        } else if let Some(value) = self.proxy.as_ref().and_then(proxy_authorization) {
            headers.push(Header::new("proxy-authorization", value));
        }
        Some(Head {
            method: "CONNECT".into(),
            target,
            status: 0,
            version: 1,
            headers,
            keep_alive: true,
        })
    }
    /// Serialize origin-form for direct/tunnel traffic and absolute-form for HTTP proxies.
    /// Proxy credentials are never forwarded inside an HTTPS tunnel.
    pub fn request_head(&self, request: &Request, authorization: Option<&[u8]>) -> Head {
        let proxy_http = self.proxy.is_some() && self.target.scheme() == "http";
        let mut head = request.head(proxy_http);
        head.headers
            .retain(|h| !h.name.eq_ignore_ascii_case("proxy-authorization"));
        if proxy_http {
            if let Some(auth) = authorization {
                head.headers.push(Header::new("proxy-authorization", auth));
            } else if let Some(value) = self.proxy.as_ref().and_then(proxy_authorization) {
                head.headers.push(Header::new("proxy-authorization", value));
            }
        }
        head
    }
    pub fn tunnel_response(&mut self, status: u16) -> Result<TransportRequest> {
        if !(200..300).contains(&status) {
            return Err(Error::new("UND_ERR_PRX_TLS", "proxy CONNECT rejected"));
        }
        self.tunnel = true;
        Ok(TransportRequest::UpgradeTls {
            server_name: self.target.host_str().unwrap_or("").into(),
        })
    }
    pub fn connected(&self) -> Option<TransportRequest> {
        if self.target.scheme() == "https" {
            if self.proxy.is_some() && !self.tunnel {
                None
            } else {
                Some(TransportRequest::UpgradeTls {
                    server_name: self.target.host_str().unwrap_or("").into(),
                })
            }
        } else {
            Some(TransportRequest::Ready(Protocol::Http1))
        }
    }
}
pub fn transport_error(kind: std::io::ErrorKind) -> Error {
    match kind {
        std::io::ErrorKind::ConnectionRefused => Error::new("ECONNREFUSED", "connect ECONNREFUSED"),
        std::io::ErrorKind::ConnectionReset => Error::new("ECONNRESET", "read ECONNRESET"),
        std::io::ErrorKind::NotFound => Error::new("ENOTFOUND", "getaddrinfo ENOTFOUND"),
        std::io::ErrorKind::TimedOut => Error::new("ETIMEDOUT", "connect ETIMEDOUT"),
        _ => Error::new("UND_ERR_SOCKET", "socket error"),
    }
}

/// A single non-pipelined HTTP/1 client connection. All byte buffers are reused.
/// The host submits output, acknowledges completion, and supplies received bytes.
/// Do not mutate the connection while a completion-layer write borrows `output()`.
pub struct Http1Connection {
    decoder: crate::http1::Decoder,
    encoder: Option<crate::http1::Encoder>,
    output: Vec<u8>,
    output_pos: usize,
    lifecycle: Lifecycle,
    active: bool,
    used: bool,
    upload_finished: bool,
    close_requested: bool,
    expect_deadline: Option<Instant>,
    waiting_continue: bool,
}
impl Http1Connection {
    pub fn new(limits: crate::http1::Limits) -> Self {
        Self {
            decoder: crate::http1::Decoder::new(crate::http1::Mode::Response, limits),
            encoder: None,
            output: Vec::new(),
            output_pos: 0,
            lifecycle: Lifecycle::default(),
            active: false,
            used: false,
            upload_finished: false,
            close_requested: false,
            expect_deadline: None,
            waiting_continue: false,
        }
    }
    pub fn start(
        &mut self,
        head: &Head,
        length: crate::http1::BodyLength,
        headers_deadline: Option<Instant>,
        continue_deadline: Option<Instant>,
    ) -> Result<()> {
        if self.active || !self.output().is_empty() || self.used && !self.reusable() {
            return Err(Error::new(
                "UND_ERR_NOT_SUPPORTED",
                "HTTP/1 pipelining is disabled or connection closed",
            ));
        }
        let encoder = crate::http1::Encoder::start(head, length, &mut self.output)?;
        if self.used {
            self.decoder.reset()?;
        }
        self.decoder.response_to(&head.method);
        self.encoder = Some(encoder);
        self.active = true;
        self.used = true;
        self.upload_finished = false;
        self.close_requested = head.token("connection", "close");
        self.lifecycle = Lifecycle::default();
        self.lifecycle.transition(Phase::Headers, headers_deadline);
        self.waiting_continue = head.token("expect", "100-continue")
            && !matches!(
                length,
                crate::http1::BodyLength::Empty | crate::http1::BodyLength::Known(0)
            );
        self.expect_deadline = if self.waiting_continue {
            continue_deadline
        } else {
            None
        };
        Ok(())
    }
    pub fn can_send_body(&self) -> bool {
        self.active
            && !self.waiting_continue
            && !self.upload_finished
            && self.lifecycle.terminal.is_none()
    }
    pub fn send_body(&mut self, bytes: &[u8]) -> Result<()> {
        if !self.can_send_body() {
            return Err(Error::new(
                "UND_ERR_INVALID_ARG",
                "request body is not writable",
            ));
        }
        self.encoder.as_mut().unwrap().body(bytes, &mut self.output)
    }
    pub fn finish_body(&mut self, trailers: &[Header]) -> Result<()> {
        if !self.can_send_body() {
            return Err(Error::new(
                "UND_ERR_INVALID_ARG",
                "request body is not writable",
            ));
        }
        self.encoder
            .as_mut()
            .unwrap()
            .finish(trailers, &mut self.output)?;
        self.upload_finished = true;
        Ok(())
    }
    pub fn output(&self) -> &[u8] {
        &self.output[self.output_pos..]
    }
    pub fn consume_output(&mut self, n: usize) -> Result<()> {
        if n > self.output().len() {
            return Err(Error::new(
                "UND_ERR_INVALID_ARG",
                "write acknowledgement exceeds output",
            ));
        }
        self.output_pos += n;
        if self.output_pos == self.output.len() {
            self.output.clear();
            self.output_pos = 0;
        }
        Ok(())
    }
    pub fn receive<'a>(&mut self, input: &'a [u8]) -> Result<crate::http1::Step<'a>> {
        if !self.active || self.lifecycle.terminal.is_some() {
            return Err(Error::new("UND_ERR_CLOSED", "no active request"));
        }
        let step = match self.decoder.receive(input) {
            Ok(step) => step,
            Err(e) => {
                self.fail(e);
                return Err(e);
            }
        };
        match &step.event {
            Some(crate::http1::Event::Informational(h)) if h.status == 100 => {
                self.waiting_continue = false;
                self.expect_deadline = None;
            }
            Some(crate::http1::Event::Head(_)) => {
                self.expect_deadline = None;
                self.waiting_continue = false;
                if !self.upload_finished {
                    self.close_requested = true;
                    self.upload_finished = true;
                }
                self.lifecycle.transition(Phase::Body, None);
            }
            Some(crate::http1::Event::End | crate::http1::Event::Upgrade) => {
                self.lifecycle.finish(Completion::Success);
                self.active = false;
            }
            _ => {}
        }
        Ok(step)
    }
    /// Refresh body timeout on progress using host-supplied time.
    pub fn set_body_deadline(&mut self, deadline: Option<Instant>) {
        self.lifecycle.transition(Phase::Body, deadline);
    }
    pub fn eof(&mut self) -> Result<()> {
        match self.decoder.eof() {
            Ok(()) => Ok(()),
            Err(e) => {
                self.fail(e);
                Err(e)
            }
        }
    }
    pub fn next_timeout(&self) -> Option<Instant> {
        self.lifecycle
            .next_timeout()
            .into_iter()
            .chain(self.expect_deadline)
            .min()
    }
    pub fn handle_timeout(&mut self, now: Instant) {
        self.lifecycle.handle_timeout(now);
        if self.lifecycle.terminal.is_some() {
            self.active = false;
            self.close_requested = true;
            self.expect_deadline = None;
        } else if self.expect_deadline.is_some_and(|d| d <= now) {
            self.waiting_continue = false;
            self.expect_deadline = None;
        }
    }
    pub fn abort(&mut self) {
        self.lifecycle.abort();
        self.active = false;
        self.close_requested = true;
        self.expect_deadline = None;
    }
    pub fn fail(&mut self, error: Error) {
        self.lifecycle.finish(Completion::Error(error));
        self.active = false;
        self.close_requested = true;
        self.expect_deadline = None;
    }
    pub fn poll_completion(&mut self) -> Option<Completion> {
        self.lifecycle.poll()
    }
    pub fn reusable(&self) -> bool {
        !self.active && !self.close_requested && self.lifecycle.delivered && self.decoder.reusable()
    }
}

fn proxy_authorization(proxy: &Url) -> Option<String> {
    use base64::Engine;
    if proxy.username().is_empty() && proxy.password().is_none() {
        return None;
    }
    let mut credential =
        percent_encoding::percent_decode_str(proxy.username()).collect::<Vec<u8>>();
    credential.push(b':');
    credential.extend(percent_encoding::percent_decode_str(
        proxy.password().unwrap_or(""),
    ));
    Some(format!(
        "Basic {}",
        base64::engine::general_purpose::STANDARD.encode(credential)
    ))
}