Files
ianitor/crates/edge/src/fetch.rs
T

134 lines
4.4 KiB
Rust

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Small HTTP client on Pingora's connector, for forward-auth subrequests and health checks.
//!
//! - The whole exchange is bounded by one deadline (Pingora's connector ignores the peer's
//! read timeout, so the deadline is enforced here with `tokio::time::timeout`).
//! - Informational answers (100, 102, 103) are skipped; `101` is returned as the final head
//! without a body, for the caller to reject.
//! - Every resolved address is tried in order until one accepts the connection.
use std::net::SocketAddr;
use std::time::Duration;
use bytes::{Bytes, BytesMut};
use pingora::connectors::http::Connector;
use pingora::http::{RequestHeader, ResponseHeader};
use pingora::upstreams::peer::HttpPeer;
use pingora::{Error, ErrorType, Result};
use crate::runtime::UpstreamRt;
pub struct Fetched {
pub header: ResponseHeader,
pub body: Bytes,
}
/// Dial timeout, matching Caddy's reverse_proxy default.
pub const DIAL_TIMEOUT: Duration = Duration::from_secs(3);
/// More 1xx heads than this before a final answer is treated as a broken server. Go (and so
/// Caddy) has no count limit, only one on total header bytes; 1000 heads accepts anything a
/// real server sends, and the overall deadline bounds the rest.
const MAX_INFORMATIONAL: usize = 1000;
pub fn peer(addr: SocketAddr, u: &UpstreamRt) -> HttpPeer {
let mut p = HttpPeer::new(addr, u.tls, u.sni.clone());
p.options.connection_timeout = Some(DIAL_TIMEOUT);
p
}
/// Send `req` without a body; read the whole response, at most `max_body` bytes of body,
/// all within `timeout`.
pub async fn fetch(
connector: &Connector,
u: &UpstreamRt,
req: RequestHeader,
max_body: usize,
timeout: Duration,
) -> Result<Fetched> {
match tokio::time::timeout(timeout, exchange(connector, u, req, max_body, timeout)).await {
Ok(r) => r,
Err(_) => Error::e_explain(
ErrorType::ReadTimedout,
format!("no complete answer within {timeout:?}"),
),
}
}
async fn exchange(
connector: &Connector,
u: &UpstreamRt,
req: RequestHeader,
max_body: usize,
timeout: Duration,
) -> Result<Fetched> {
let addrs = u.resolve().await.map_err(|e| {
Error::explain(
ErrorType::ConnectNoRoute,
format!("cannot resolve {}: {e}", u.authority),
)
})?;
let mut last = None;
let mut session = None;
for addr in addrs {
let mut p = peer(addr, u);
p.options.total_connection_timeout = Some(timeout);
match connector.get_http_session(&p).await {
Ok((s, _reused)) => {
session = Some(s);
break;
}
Err(e) => last = Some(e),
}
}
let Some(mut http) = session else {
return Err(last.unwrap_or_else(|| {
Error::explain(ErrorType::ConnectError, "no address to connect to")
}));
};
http.set_read_timeout(Some(timeout));
http.set_write_timeout(Some(timeout));
http.write_request_header(Box::new(req)).await?;
http.finish_request_body().await?;
let mut header = None;
for _ in 0..=MAX_INFORMATIONAL {
http.read_response_header().await?;
let h = http
.response_header()
.cloned()
.ok_or_else(|| Error::explain(ErrorType::InvalidHTTPHeader, "no response header"))?;
let s = h.status.as_u16();
if (100..200).contains(&s) && s != 101 {
continue;
}
header = Some(h);
break;
}
let header = header.ok_or_else(|| {
Error::explain(ErrorType::InvalidHTTPHeader, "only informational answers")
})?;
if header.status.as_u16() == 101 {
// Switching protocols: there is no HTTP body to read.
return Ok(Fetched {
header,
body: Bytes::new(),
});
}
let mut body = BytesMut::new();
while let Some(chunk) = http.read_response_body().await? {
if body.len() + chunk.len() > max_body {
return Error::e_explain(ErrorType::InvalidHTTPHeader, "response body too large");
}
body.extend_from_slice(&chunk);
}
// Not returned to the pool: these calls are rare and a fresh connection is simplest.
Ok(Fetched {
header,
body: body.freeze(),
})
}