Skip to main content

turnloop_http/
client.rs

1//! Host-driven fetch transport policy. DNS, environment, sockets and time are inputs.
2//! JS body conversions, promise dispatch and abort reason objects remain in Perry.
3use crate::{
4    Error, Result,
5    http1::{Head, Header},
6};
7use std::{
8    net::IpAddr,
9    time::{Duration, Instant},
10};
11use url::Url;
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Protocol {
14    Http1,
15    Http2,
16}
17pub fn from_alpn(alpn: Option<&[u8]>) -> Result<Protocol> {
18    match alpn {
19        Some(b"h2") => Ok(Protocol::Http2),
20        None | Some(b"http/1.1") => Ok(Protocol::Http1),
21        _ => Err(Error::new("UND_ERR_NOT_SUPPORTED", "unsupported ALPN")),
22    }
23}
24/// Resolver implementations enqueue host operations; they must not block here.
25pub trait Resolver {
26    type Token: Copy;
27    fn resolve(&mut self, hostname: &str, port: u16) -> Result<Self::Token>;
28    fn poll(&mut self, token: Self::Token, addresses: &mut Vec<IpAddr>) -> Option<Result<()>>;
29    fn cancel(&mut self, token: Self::Token);
30}
31pub const DEFAULT_MAX_REDIRECTS: usize = 20;
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum RedirectMode {
34    Follow,
35    Manual,
36    Error,
37}
38#[derive(Debug, Clone)]
39pub struct Request {
40    pub url: Url,
41    pub method: String,
42    pub headers: Vec<Header>,
43    pub body: Vec<u8>,
44    pub replayable: bool,
45    pub redirects: usize,
46}
47impl Request {
48    pub fn new(url: &str, method: &str) -> Result<Self> {
49        let url = Url::parse(url).map_err(|_| Error::new("ERR_INVALID_URL", "invalid URL"))?;
50        if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
51            return Err(Error::new("ERR_INVALID_URL", "unsupported URL scheme"));
52        }
53        if !url.username().is_empty() || url.password().is_some() {
54            return Err(Error::new(
55                "UND_ERR_INVALID_ARG",
56                "URL contains credentials",
57            ));
58        }
59        http::Method::from_bytes(method.as_bytes())
60            .map_err(|_| Error::new("UND_ERR_INVALID_ARG", "invalid method"))?;
61        if ["CONNECT", "TRACE", "TRACK"]
62            .iter()
63            .any(|m| method.eq_ignore_ascii_case(m))
64        {
65            return Err(Error::new("UND_ERR_INVALID_ARG", "forbidden fetch method"));
66        }
67        let method = if ["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]
68            .iter()
69            .any(|m| method.eq_ignore_ascii_case(m))
70        {
71            method.to_ascii_uppercase()
72        } else {
73            method.into()
74        };
75        Ok(Self {
76            url,
77            method,
78            headers: Vec::new(),
79            body: Vec::new(),
80            replayable: true,
81            redirects: 0,
82        })
83    }
84    pub fn head(&self, absolute_form: bool) -> Head {
85        let mut url = self.url.clone();
86        url.set_fragment(None);
87        let target = if absolute_form {
88            url.as_str().to_owned()
89        } else {
90            let mut target = url.path().to_string();
91            if let Some(q) = url.query() {
92                target.push('?');
93                target.push_str(q);
94            }
95            target
96        };
97        let mut headers = self.headers.clone();
98        headers.retain(|h| !h.name.eq_ignore_ascii_case("host"));
99        headers.push(Header::new("host", authority(&url)));
100        Head {
101            method: self.method.clone(),
102            target,
103            status: 0,
104            version: 1,
105            headers,
106            keep_alive: true,
107        }
108    }
109    /// `true` means resend the modified request; `false` exposes the response as-is.
110    pub fn redirect(
111        &mut self,
112        status: u16,
113        location: Option<&str>,
114        mode: RedirectMode,
115        max: usize,
116    ) -> Result<bool> {
117        if !matches!(status, 301 | 302 | 303 | 307 | 308) {
118            return Ok(false);
119        }
120        if mode == RedirectMode::Manual {
121            return Ok(false);
122        }
123        if mode == RedirectMode::Error {
124            return Err(Error::new("UND_ERR_REQ_RETRY", "redirect mode is error"));
125        }
126        let Some(location) = location else {
127            return Ok(false);
128        };
129        if self.redirects >= max {
130            return Err(Error::new("UND_ERR_REDIRECT", "redirect count exceeded"));
131        }
132        let next = self
133            .url
134            .join(location)
135            .map_err(|_| Error::new("ERR_INVALID_URL", "invalid redirect URL"))?;
136        if !matches!(next.scheme(), "http" | "https")
137            || !next.username().is_empty()
138            || next.password().is_some()
139        {
140            return Err(Error::new("UND_ERR_INVALID_ARG", "invalid redirect target"));
141        }
142        let rewrite = (matches!(status, 301 | 302) && self.method == "POST")
143            || (status == 303 && self.method != "GET" && self.method != "HEAD");
144        if !rewrite && !self.replayable {
145            return Err(Error::new(
146                "UND_ERR_REQ_RETRY",
147                "streaming body cannot be replayed",
148            ));
149        }
150        if self.url.origin() != next.origin() {
151            self.headers.retain(|h| {
152                ![
153                    "authorization",
154                    "proxy-authorization",
155                    "cookie",
156                    "cookie2",
157                    "host",
158                ]
159                .iter()
160                .any(|name| h.name.eq_ignore_ascii_case(name))
161            });
162        }
163        if rewrite {
164            self.method = "GET".into();
165            self.body.clear();
166            self.replayable = true;
167            self.headers.retain(|h| {
168                ![
169                    "content-encoding",
170                    "content-language",
171                    "content-location",
172                    "content-type",
173                    "content-length",
174                    "transfer-encoding",
175                ]
176                .iter()
177                .any(|name| h.name.eq_ignore_ascii_case(name))
178            });
179        }
180        self.url = next;
181        self.redirects += 1;
182        Ok(true)
183    }
184}
185fn authority(url: &Url) -> String {
186    let mut result = url.host_str().unwrap_or("").to_string();
187    if let Some(port) = url.port() {
188        result.push(':');
189        result.push_str(&port.to_string());
190    }
191    result
192}
193#[derive(Debug, Default, Clone)]
194pub struct ProxyEnvironment {
195    pub http_proxy: Option<String>,
196    pub https_proxy: Option<String>,
197    pub no_proxy: String,
198}
199impl ProxyEnvironment {
200    /// Values are supplied by the host from HTTP_PROXY/HTTPS_PROXY/NO_PROXY (or lowercase overrides).
201    pub fn proxy_for(&self, url: &Url) -> Result<Option<Url>> {
202        if bypass(url, &self.no_proxy) {
203            return Ok(None);
204        }
205        let proxy = if url.scheme() == "https" {
206            self.https_proxy.as_deref()
207        } else {
208            self.http_proxy.as_deref()
209        };
210        proxy
211            .filter(|p| !p.is_empty())
212            .map(|p| {
213                let parsed =
214                    Url::parse(p).map_err(|_| Error::new("ERR_INVALID_URL", "invalid proxy"))?;
215                if parsed.scheme() != "http" || parsed.host_str().is_none() {
216                    return Err(Error::new(
217                        "UND_ERR_NOT_SUPPORTED",
218                        "only HTTP proxies are supported",
219                    ));
220                }
221                Ok(parsed)
222            })
223            .transpose()
224    }
225}
226fn bypass(url: &Url, list: &str) -> bool {
227    let host = url.host_str().unwrap_or("");
228    list.split(',')
229        .map(str::trim)
230        .filter(|x| !x.is_empty())
231        .any(|entry| {
232            if entry == "*" {
233                return true;
234            }
235            let (domain, port) = if let Some((h, p)) = entry.rsplit_once(':') {
236                if let Ok(p) = p.parse::<u16>() {
237                    (h, Some(p))
238                } else {
239                    (entry, None)
240                }
241            } else {
242                (entry, None)
243            };
244            if port.is_some() && port != url.port_or_known_default() {
245                return false;
246            }
247            let domain = domain.trim_start_matches("*.").trim_start_matches('.');
248            host.eq_ignore_ascii_case(domain)
249                || (host.len() > domain.len()
250                    && host.as_bytes()[host.len() - domain.len() - 1] == b'.'
251                    && host[host.len() - domain.len()..].eq_ignore_ascii_case(domain))
252        })
253}
254#[derive(Debug, Clone, PartialEq, Eq)]
255pub struct PoolKey {
256    pub origin: String,
257    pub proxy: Option<String>,
258}
259impl PoolKey {
260    pub fn new(url: &Url, proxy: Option<&Url>) -> Self {
261        Self {
262            origin: url.origin().ascii_serialization(),
263            proxy: proxy.map(ToString::to_string),
264        }
265    }
266}
267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
268pub struct ConnectionId(pub u64);
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
270pub enum Acquire {
271    Connect(ConnectionId),
272    Reuse(ConnectionId),
273    Wait,
274}
275struct Slot {
276    id: ConnectionId,
277    key: PoolKey,
278    active: usize,
279    capacity: usize,
280    connecting: bool,
281    deadline: Option<Instant>,
282    closed: bool,
283}
284pub struct Pool {
285    slots: Vec<Slot>,
286    max_per_host: usize,
287    idle: Duration,
288    next: u64,
289}
290impl Pool {
291    pub fn new(max_per_host: usize, idle: Duration) -> Self {
292        Self {
293            slots: Vec::new(),
294            max_per_host,
295            idle,
296            next: 1,
297        }
298    }
299    /// A Connect reservation counts immediately, so concurrent callers cannot overbook.
300    pub fn acquire(&mut self, key: &PoolKey, now: Instant) -> Acquire {
301        if let Some(s) = self.slots.iter_mut().find(|s| {
302            !s.closed
303                && s.key == *key
304                && !s.connecting
305                && s.active < s.capacity
306                && s.deadline.is_none_or(|d| d > now)
307        }) {
308            s.active += 1;
309            s.deadline = None;
310            return Acquire::Reuse(s.id);
311        }
312        if self
313            .slots
314            .iter()
315            .filter(|s| !s.closed && s.key == *key)
316            .count()
317            >= self.max_per_host
318        {
319            return Acquire::Wait;
320        }
321        let id = ConnectionId(self.next);
322        self.next += 1;
323        let slot = Slot {
324            id,
325            key: key.clone(),
326            active: 1,
327            capacity: 1,
328            connecting: true,
329            deadline: None,
330            closed: false,
331        };
332        if let Some(s) = self.slots.iter_mut().find(|s| s.closed) {
333            *s = slot;
334        } else {
335            self.slots.push(slot);
336        }
337        Acquire::Connect(id)
338    }
339    fn slot(&mut self, id: ConnectionId) -> Result<&mut Slot> {
340        self.slots
341            .iter_mut()
342            .find(|s| s.id == id && !s.closed)
343            .ok_or(Error::new("UND_ERR_CLOSED", "unknown connection"))
344    }
345    pub fn connected(
346        &mut self,
347        id: ConnectionId,
348        protocol: Protocol,
349        max_streams: usize,
350    ) -> Result<()> {
351        let s = self.slot(id)?;
352        s.connecting = false;
353        s.capacity = if protocol == Protocol::Http1 {
354            1
355        } else {
356            max_streams
357        };
358        Ok(())
359    }
360    pub fn release(&mut self, id: ConnectionId, reusable: bool, now: Instant) -> Result<()> {
361        let idle = self.idle;
362        let s = self.slot(id)?;
363        if s.active == 0 {
364            return Err(Error::new("UND_ERR_INVALID_ARG", "duplicate pool release"));
365        }
366        s.active -= 1;
367        if !reusable {
368            s.capacity = 0;
369        }
370        if s.active == 0 {
371            s.deadline = Some(if s.capacity == 0 { now } else { now + idle });
372        }
373        Ok(())
374    }
375    pub fn closed(&mut self, id: ConnectionId) -> Result<()> {
376        self.slot(id)?.closed = true;
377        Ok(())
378    }
379    pub fn next_timeout(&self) -> Option<Instant> {
380        self.slots
381            .iter()
382            .filter(|s| !s.closed)
383            .filter_map(|s| s.deadline)
384            .min()
385    }
386    /// Repeatedly call to obtain all Close requests at this time. No clock or timer is owned.
387    pub fn handle_timeout(&mut self, now: Instant) -> Option<ConnectionId> {
388        let s = self
389            .slots
390            .iter_mut()
391            .find(|s| !s.closed && s.deadline.is_some_and(|d| d <= now))?;
392        s.closed = true;
393        Some(s.id)
394    }
395}
396#[derive(Debug, Clone, Copy, PartialEq, Eq)]
397pub enum Phase {
398    Connect,
399    Headers,
400    Body,
401    Done,
402}
403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
404pub enum Completion {
405    Success,
406    Error(Error),
407}
408pub struct Lifecycle {
409    phase: Phase,
410    deadline: Option<Instant>,
411    terminal: Option<Completion>,
412    delivered: bool,
413}
414impl Default for Lifecycle {
415    fn default() -> Self {
416        Self {
417            phase: Phase::Connect,
418            deadline: None,
419            terminal: None,
420            delivered: false,
421        }
422    }
423}
424impl Lifecycle {
425    pub fn transition(&mut self, phase: Phase, deadline: Option<Instant>) {
426        if self.terminal.is_none() {
427            self.phase = phase;
428            self.deadline = deadline;
429        }
430    }
431    pub fn next_timeout(&self) -> Option<Instant> {
432        self.deadline
433    }
434    pub fn handle_timeout(&mut self, now: Instant) {
435        if self.deadline.is_some_and(|d| d <= now) {
436            let (code, message) = match self.phase {
437                Phase::Connect => ("UND_ERR_CONNECT_TIMEOUT", "Connect Timeout Error"),
438                Phase::Headers => ("UND_ERR_HEADERS_TIMEOUT", "Headers Timeout Error"),
439                _ => ("UND_ERR_BODY_TIMEOUT", "Body Timeout Error"),
440            };
441            self.finish(Completion::Error(Error::new(code, message)));
442        }
443    }
444    pub fn abort(&mut self) {
445        self.finish(Completion::Error(Error::new(
446            "UND_ERR_ABORTED",
447            "Request aborted",
448        )));
449    }
450    pub fn finish(&mut self, result: Completion) {
451        if self.terminal.is_none() {
452            self.terminal = Some(result);
453            self.phase = Phase::Done;
454            self.deadline = None;
455        }
456    }
457    pub fn poll(&mut self) -> Option<Completion> {
458        if self.delivered {
459            return None;
460        }
461        let event = self.terminal?;
462        self.delivered = true;
463        Some(event)
464    }
465}
466/// After a CONNECT 2xx upgrade, the host feeds remaining bytes into TLS.
467#[derive(Debug, Clone, PartialEq, Eq)]
468pub enum TransportRequest {
469    Resolve { hostname: String, port: u16 },
470    UpgradeTls { server_name: String },
471    Ready(Protocol),
472}
473pub struct Route {
474    target: Url,
475    proxy: Option<Url>,
476    tunnel: bool,
477}
478impl Route {
479    pub fn new(target: Url, proxy: Option<Url>) -> Self {
480        Self {
481            target,
482            proxy,
483            tunnel: false,
484        }
485    }
486    pub fn resolve(&self) -> TransportRequest {
487        let peer = self.proxy.as_ref().unwrap_or(&self.target);
488        TransportRequest::Resolve {
489            hostname: peer.host_str().unwrap_or("").into(),
490            port: peer.port_or_known_default().unwrap_or(80),
491        }
492    }
493    pub fn connect_head(&self, authorization: Option<&[u8]>) -> Option<Head> {
494        if self.proxy.is_none() || self.target.scheme() != "https" {
495            return None;
496        }
497        let target = format!(
498            "{}:{}",
499            self.target.host_str().unwrap_or(""),
500            self.target.port_or_known_default().unwrap_or(443)
501        );
502        let mut headers = vec![Header::new("host", &target)];
503        if let Some(value) = authorization {
504            headers.push(Header::new("proxy-authorization", value));
505        } else if let Some(value) = self.proxy.as_ref().and_then(proxy_authorization) {
506            headers.push(Header::new("proxy-authorization", value));
507        }
508        Some(Head {
509            method: "CONNECT".into(),
510            target,
511            status: 0,
512            version: 1,
513            headers,
514            keep_alive: true,
515        })
516    }
517    /// Serialize origin-form for direct/tunnel traffic and absolute-form for HTTP proxies.
518    /// Proxy credentials are never forwarded inside an HTTPS tunnel.
519    pub fn request_head(&self, request: &Request, authorization: Option<&[u8]>) -> Head {
520        let proxy_http = self.proxy.is_some() && self.target.scheme() == "http";
521        let mut head = request.head(proxy_http);
522        head.headers
523            .retain(|h| !h.name.eq_ignore_ascii_case("proxy-authorization"));
524        if proxy_http {
525            if let Some(auth) = authorization {
526                head.headers.push(Header::new("proxy-authorization", auth));
527            } else if let Some(value) = self.proxy.as_ref().and_then(proxy_authorization) {
528                head.headers.push(Header::new("proxy-authorization", value));
529            }
530        }
531        head
532    }
533    pub fn tunnel_response(&mut self, status: u16) -> Result<TransportRequest> {
534        if !(200..300).contains(&status) {
535            return Err(Error::new("UND_ERR_PRX_TLS", "proxy CONNECT rejected"));
536        }
537        self.tunnel = true;
538        Ok(TransportRequest::UpgradeTls {
539            server_name: self.target.host_str().unwrap_or("").into(),
540        })
541    }
542    pub fn connected(&self) -> Option<TransportRequest> {
543        if self.target.scheme() == "https" {
544            if self.proxy.is_some() && !self.tunnel {
545                None
546            } else {
547                Some(TransportRequest::UpgradeTls {
548                    server_name: self.target.host_str().unwrap_or("").into(),
549                })
550            }
551        } else {
552            Some(TransportRequest::Ready(Protocol::Http1))
553        }
554    }
555}
556pub fn transport_error(kind: std::io::ErrorKind) -> Error {
557    match kind {
558        std::io::ErrorKind::ConnectionRefused => Error::new("ECONNREFUSED", "connect ECONNREFUSED"),
559        std::io::ErrorKind::ConnectionReset => Error::new("ECONNRESET", "read ECONNRESET"),
560        std::io::ErrorKind::NotFound => Error::new("ENOTFOUND", "getaddrinfo ENOTFOUND"),
561        std::io::ErrorKind::TimedOut => Error::new("ETIMEDOUT", "connect ETIMEDOUT"),
562        _ => Error::new("UND_ERR_SOCKET", "socket error"),
563    }
564}
565
566/// A single non-pipelined HTTP/1 client connection. All byte buffers are reused.
567/// The host submits output, acknowledges completion, and supplies received bytes.
568/// Do not mutate the connection while a completion-layer write borrows `output()`.
569pub struct Http1Connection {
570    decoder: crate::http1::Decoder,
571    encoder: Option<crate::http1::Encoder>,
572    output: Vec<u8>,
573    output_pos: usize,
574    lifecycle: Lifecycle,
575    active: bool,
576    used: bool,
577    upload_finished: bool,
578    close_requested: bool,
579    expect_deadline: Option<Instant>,
580    waiting_continue: bool,
581}
582impl Http1Connection {
583    pub fn new(limits: crate::http1::Limits) -> Self {
584        Self {
585            decoder: crate::http1::Decoder::new(crate::http1::Mode::Response, limits),
586            encoder: None,
587            output: Vec::new(),
588            output_pos: 0,
589            lifecycle: Lifecycle::default(),
590            active: false,
591            used: false,
592            upload_finished: false,
593            close_requested: false,
594            expect_deadline: None,
595            waiting_continue: false,
596        }
597    }
598    pub fn start(
599        &mut self,
600        head: &Head,
601        length: crate::http1::BodyLength,
602        headers_deadline: Option<Instant>,
603        continue_deadline: Option<Instant>,
604    ) -> Result<()> {
605        if self.active || !self.output().is_empty() || self.used && !self.reusable() {
606            return Err(Error::new(
607                "UND_ERR_NOT_SUPPORTED",
608                "HTTP/1 pipelining is disabled or connection closed",
609            ));
610        }
611        let encoder = crate::http1::Encoder::start(head, length, &mut self.output)?;
612        if self.used {
613            self.decoder.reset()?;
614        }
615        self.decoder.response_to(&head.method);
616        self.encoder = Some(encoder);
617        self.active = true;
618        self.used = true;
619        self.upload_finished = false;
620        self.close_requested = head.token("connection", "close");
621        self.lifecycle = Lifecycle::default();
622        self.lifecycle.transition(Phase::Headers, headers_deadline);
623        self.waiting_continue = head.token("expect", "100-continue")
624            && !matches!(
625                length,
626                crate::http1::BodyLength::Empty | crate::http1::BodyLength::Known(0)
627            );
628        self.expect_deadline = if self.waiting_continue {
629            continue_deadline
630        } else {
631            None
632        };
633        Ok(())
634    }
635    pub fn can_send_body(&self) -> bool {
636        self.active
637            && !self.waiting_continue
638            && !self.upload_finished
639            && self.lifecycle.terminal.is_none()
640    }
641    pub fn send_body(&mut self, bytes: &[u8]) -> Result<()> {
642        if !self.can_send_body() {
643            return Err(Error::new(
644                "UND_ERR_INVALID_ARG",
645                "request body is not writable",
646            ));
647        }
648        self.encoder.as_mut().unwrap().body(bytes, &mut self.output)
649    }
650    pub fn finish_body(&mut self, trailers: &[Header]) -> Result<()> {
651        if !self.can_send_body() {
652            return Err(Error::new(
653                "UND_ERR_INVALID_ARG",
654                "request body is not writable",
655            ));
656        }
657        self.encoder
658            .as_mut()
659            .unwrap()
660            .finish(trailers, &mut self.output)?;
661        self.upload_finished = true;
662        Ok(())
663    }
664    pub fn output(&self) -> &[u8] {
665        &self.output[self.output_pos..]
666    }
667    pub fn consume_output(&mut self, n: usize) -> Result<()> {
668        if n > self.output().len() {
669            return Err(Error::new(
670                "UND_ERR_INVALID_ARG",
671                "write acknowledgement exceeds output",
672            ));
673        }
674        self.output_pos += n;
675        if self.output_pos == self.output.len() {
676            self.output.clear();
677            self.output_pos = 0;
678        }
679        Ok(())
680    }
681    pub fn receive<'a>(&mut self, input: &'a [u8]) -> Result<crate::http1::Step<'a>> {
682        if !self.active || self.lifecycle.terminal.is_some() {
683            return Err(Error::new("UND_ERR_CLOSED", "no active request"));
684        }
685        let step = match self.decoder.receive(input) {
686            Ok(step) => step,
687            Err(e) => {
688                self.fail(e);
689                return Err(e);
690            }
691        };
692        match &step.event {
693            Some(crate::http1::Event::Informational(h)) if h.status == 100 => {
694                self.waiting_continue = false;
695                self.expect_deadline = None;
696            }
697            Some(crate::http1::Event::Head(_)) => {
698                self.expect_deadline = None;
699                self.waiting_continue = false;
700                if !self.upload_finished {
701                    self.close_requested = true;
702                    self.upload_finished = true;
703                }
704                self.lifecycle.transition(Phase::Body, None);
705            }
706            Some(crate::http1::Event::End | crate::http1::Event::Upgrade) => {
707                self.lifecycle.finish(Completion::Success);
708                self.active = false;
709            }
710            _ => {}
711        }
712        Ok(step)
713    }
714    /// Refresh body timeout on progress using host-supplied time.
715    pub fn set_body_deadline(&mut self, deadline: Option<Instant>) {
716        self.lifecycle.transition(Phase::Body, deadline);
717    }
718    pub fn eof(&mut self) -> Result<()> {
719        match self.decoder.eof() {
720            Ok(()) => Ok(()),
721            Err(e) => {
722                self.fail(e);
723                Err(e)
724            }
725        }
726    }
727    pub fn next_timeout(&self) -> Option<Instant> {
728        self.lifecycle
729            .next_timeout()
730            .into_iter()
731            .chain(self.expect_deadline)
732            .min()
733    }
734    pub fn handle_timeout(&mut self, now: Instant) {
735        self.lifecycle.handle_timeout(now);
736        if self.lifecycle.terminal.is_some() {
737            self.active = false;
738            self.close_requested = true;
739            self.expect_deadline = None;
740        } else if self.expect_deadline.is_some_and(|d| d <= now) {
741            self.waiting_continue = false;
742            self.expect_deadline = None;
743        }
744    }
745    pub fn abort(&mut self) {
746        self.lifecycle.abort();
747        self.active = false;
748        self.close_requested = true;
749        self.expect_deadline = None;
750    }
751    pub fn fail(&mut self, error: Error) {
752        self.lifecycle.finish(Completion::Error(error));
753        self.active = false;
754        self.close_requested = true;
755        self.expect_deadline = None;
756    }
757    pub fn poll_completion(&mut self) -> Option<Completion> {
758        self.lifecycle.poll()
759    }
760    pub fn reusable(&self) -> bool {
761        !self.active && !self.close_requested && self.lifecycle.delivered && self.decoder.reusable()
762    }
763}
764
765fn proxy_authorization(proxy: &Url) -> Option<String> {
766    use base64::Engine;
767    if proxy.username().is_empty() && proxy.password().is_none() {
768        return None;
769    }
770    let mut credential =
771        percent_encoding::percent_decode_str(proxy.username()).collect::<Vec<u8>>();
772    credential.push(b':');
773    credential.extend(percent_encoding::percent_decode_str(
774        proxy.password().unwrap_or(""),
775    ));
776    Some(format!(
777        "Basic {}",
778        base64::engine::general_purpose::STANDARD.encode(credential)
779    ))
780}