use std::collections::HashSet;
use std::future::Future;
use std::sync::{OnceLock, RwLock};
use std::task::{Context as TaskContext, Poll};
use std::time::Duration;
use encore_sdk_core::telemetry::SpanContextExt;
use http::header::{
HeaderName, HeaderValue, AUTHORIZATION, CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_LENGTH,
CONTENT_LOCATION, CONTENT_TYPE, COOKIE, LOCATION, PROXY_AUTHORIZATION, WWW_AUTHENTICATE,
};
use http::{HeaderMap, Method, StatusCode};
use serde::Serialize;
use crate::opentelemetry::trace::TraceContextExt;
use crate::opentelemetry::Context;
pub use reqwest;
#[doc(hidden)]
pub mod clients;
pub use clients::{
BidiStreaming, CallError, ClientStreaming, ServerStreaming, Stream, Streaming, Unary,
UnlessNotFound,
};
pub fn base_url(service: &str) -> &'static str {
lookup(service).unwrap_or_else(|| panic!("{}", unknown_service(service)))
}
fn lookup(service: &str) -> Option<&'static str> {
let url = crate::runtime::core()
.runtime_config()
.services
.get(service)?
.trim_end_matches('/');
register(url);
Some(url)
}
pub(crate) fn unknown_service(service: &str) -> String {
format!("encore: no base URL configured for service {service:?}")
}
pub const fn client(service: &'static str) -> Client {
Client {
service,
base: OnceLock::new(),
}
}
#[derive(Debug)]
pub struct Client {
service: &'static str,
base: OnceLock<&'static str>,
}
impl Client {
pub fn base_url(&self) -> &'static str {
self.try_base_url()
.unwrap_or_else(|| panic!("{}", unknown_service(self.service)))
}
pub(crate) fn try_base_url(&self) -> Option<&'static str> {
if let Some(base) = self.base.get() {
return Some(base);
}
let base = lookup(self.service)?;
Some(self.base.get_or_init(|| base))
}
pub(crate) fn name(&self) -> &'static str {
self.service
}
pub fn get(&self, path: &str) -> RequestBuilder {
self.request(Method::GET, path)
}
pub fn post(&self, path: &str) -> RequestBuilder {
self.request(Method::POST, path)
}
pub fn put(&self, path: &str) -> RequestBuilder {
self.request(Method::PUT, path)
}
pub fn patch(&self, path: &str) -> RequestBuilder {
self.request(Method::PATCH, path)
}
pub fn delete(&self, path: &str) -> RequestBuilder {
self.request(Method::DELETE, path)
}
pub fn head(&self, path: &str) -> RequestBuilder {
self.request(Method::HEAD, path)
}
pub fn request(&self, method: Method, path: &str) -> RequestBuilder {
let base = self.base_url();
let url = if has_scheme(path) {
path.to_string()
} else {
format!("{base}/{}", path.trim_start_matches('/'))
};
request_to(method, url)
}
}
pub(crate) fn request_to(method: Method, url: String) -> RequestBuilder {
RequestBuilder {
inner: shared().request(method, url),
}
}
fn has_scheme(path: &str) -> bool {
let Some((scheme, _)) = path.split_once(':') else {
return false;
};
let mut chars = scheme.chars();
chars.next().is_some_and(|c| c.is_ascii_alphabetic())
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
}
#[derive(Debug)]
#[must_use = "a request is not sent until `.send()` is called"]
pub struct RequestBuilder {
inner: reqwest::RequestBuilder,
}
impl RequestBuilder {
pub fn header<K, V>(self, key: K, value: V) -> Self
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<http::Error>,
HeaderValue: TryFrom<V>,
<HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
{
self.map(|b| b.header(key, value))
}
pub fn headers(self, headers: HeaderMap) -> Self {
self.map(|b| b.headers(headers))
}
pub fn query<T: Serialize + ?Sized>(self, query: &T) -> Self {
self.map(|b| b.query(query))
}
pub fn json<T: Serialize + ?Sized>(self, json: &T) -> Self {
self.map(|b| b.json(json))
}
pub fn form<T: Serialize + ?Sized>(self, form: &T) -> Self {
self.map(|b| b.form(form))
}
pub fn body<T: Into<reqwest::Body>>(self, body: T) -> Self {
self.map(|b| b.body(body))
}
pub fn timeout(self, timeout: Duration) -> Self {
self.map(|b| b.timeout(timeout))
}
pub fn bearer_auth<T: std::fmt::Display>(self, token: T) -> Self {
self.map(|b| b.bearer_auth(token))
}
pub fn basic_auth<U: std::fmt::Display, P: std::fmt::Display>(
self,
username: U,
password: Option<P>,
) -> Self {
self.map(|b| b.basic_auth(username, password))
}
pub fn map(self, f: impl FnOnce(reqwest::RequestBuilder) -> reqwest::RequestBuilder) -> Self {
RequestBuilder {
inner: f(self.inner),
}
}
pub fn send(self) -> impl Future<Output = Result<reqwest::Response, reqwest::Error>> {
let called_in = Context::current();
let request = self.inner.build();
async move {
let polled_in = Context::current();
let cx = if carries_context(&polled_in) {
polled_in
} else {
called_in
};
follow_redirects(&cx, request?).await
}
}
}
const MAX_REDIRECTS: usize = 10;
const BODY_HEADERS: [HeaderName; 5] = [
CONTENT_TYPE,
CONTENT_LENGTH,
CONTENT_ENCODING,
CONTENT_LANGUAGE,
CONTENT_LOCATION,
];
const CREDENTIAL_HEADERS: [HeaderName; 4] =
[AUTHORIZATION, COOKIE, PROXY_AUTHORIZATION, WWW_AUTHENTICATE];
async fn follow_redirects(
cx: &Context,
mut request: reqwest::Request,
) -> Result<reqwest::Response, reqwest::Error> {
let client = shared();
let mut redirects = 0;
loop {
let origin = origin_of(request.url());
prepare(cx, origin.as_ref(), request.headers_mut());
let again = request.try_clone();
let method = request.method().clone();
let headers = request.headers().clone();
let timeout = request.timeout().copied();
let response = client.execute(request).await?;
let location = response
.headers()
.get(LOCATION)
.and_then(|l| l.to_str().ok())
.and_then(|l| response.url().join(l).ok());
let Some(location) = location else {
return Ok(response);
};
if redirects == MAX_REDIRECTS {
return Ok(response);
}
let to_get = match response.status() {
StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND => method == Method::POST,
StatusCode::SEE_OTHER => method != Method::GET && method != Method::HEAD,
StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT => false,
_ => return Ok(response),
};
let mut next = if to_get {
let mut next = reqwest::Request::new(Method::GET, location.clone());
*next.headers_mut() = headers;
*next.timeout_mut() = timeout;
for name in BODY_HEADERS {
next.headers_mut().remove(name);
}
next
} else {
match again {
Some(next) => next,
None => return Ok(response),
}
};
if origin_of(&location) != origin {
for name in CREDENTIAL_HEADERS {
next.headers_mut().remove(name);
}
}
*next.url_mut() = location;
request = next;
redirects += 1;
}
}
fn shared() -> &'static reqwest::Client {
static SHARED: OnceLock<reqwest::Client> = OnceLock::new();
SHARED.get_or_init(|| {
let core = crate::runtime::core();
let mut builder = reqwest::Client::builder()
.tls_backend_preconfigured(encore_sdk_core::tls::http_client_config())
.redirect(reqwest::redirect::Policy::none());
if core.system_test().is_some() {
builder = builder.pool_max_idle_per_host(0);
}
builder
.build()
.expect("encore: building the HTTP client for service calls")
})
}
#[derive(Debug, Clone, Copy, Default)]
pub struct PropagateLayer;
impl<S> tower_layer::Layer<S> for PropagateLayer {
type Service = Propagate<S>;
fn layer(&self, inner: S) -> Propagate<S> {
Propagate { inner }
}
}
#[derive(Debug, Clone)]
pub struct Propagate<S> {
inner: S,
}
impl<S, B> tower_service::Service<http::Request<B>> for Propagate<S>
where
S: tower_service::Service<http::Request<B>>,
{
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
fn poll_ready(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<(), S::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, mut request: http::Request<B>) -> S::Future {
let origin = origin_of_uri(request.uri());
prepare(&Context::current(), origin.as_ref(), request.headers_mut());
self.inner.call(request)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Origin {
scheme: String,
host: String,
port: Option<u16>,
}
fn origin_of(url: &reqwest::Url) -> Option<Origin> {
Some(Origin {
scheme: url.scheme().to_ascii_lowercase(),
host: url.host_str()?.to_ascii_lowercase(),
port: url.port_or_known_default(),
})
}
fn origin_of_uri(uri: &http::Uri) -> Option<Origin> {
let scheme = uri.scheme_str()?.to_ascii_lowercase();
let port = uri.port_u16().or(match scheme.as_str() {
"http" => Some(80),
"https" => Some(443),
_ => None,
});
Some(Origin {
host: uri.host()?.to_ascii_lowercase(),
scheme,
port,
})
}
static ORIGINS: RwLock<Option<HashSet<Origin>>> = RwLock::new(None);
fn register(base: &str) {
let Some(origin) = reqwest::Url::parse(base).ok().and_then(|u| origin_of(&u)) else {
return;
};
if is_service(Some(&origin)) {
return;
}
ORIGINS
.write()
.unwrap_or_else(|e| e.into_inner())
.get_or_insert_with(HashSet::new)
.insert(origin);
}
fn is_service(origin: Option<&Origin>) -> bool {
origin.is_some_and(|origin| {
ORIGINS
.read()
.unwrap_or_else(|e| e.into_inner())
.as_ref()
.is_some_and(|o| o.contains(origin))
})
}
pub(crate) fn carries_context(cx: &Context) -> bool {
cx.span().span_context().is_valid() || !encore_sdk_core::reqctx::Values::of(cx).is_empty()
}
const TRACEPARENT: HeaderName = HeaderName::from_static("traceparent");
const TRACESTATE: HeaderName = HeaderName::from_static("tracestate");
fn prepare(cx: &Context, origin: Option<&Origin>, headers: &mut HeaderMap) {
if !is_service(origin) {
let stale: Vec<HeaderName> = headers
.keys()
.filter(|name| encore_telemetry::propagation::is_context_header(name.as_str()))
.cloned()
.collect();
for name in stale {
headers.remove(name);
}
return;
}
let cx = &crate::testing::outgoing(cx);
crate::reqctx::inject(cx, headers);
if headers.contains_key(TRACEPARENT) {
return;
}
let span = cx.span();
let sc = span.span_context();
if !sc.is_valid() {
return;
}
if let Ok(value) = HeaderValue::from_str(&sc.to_traceparent()) {
headers.insert(TRACEPARENT, value);
}
headers.remove(TRACESTATE);
let state = sc.trace_state().header();
if !state.is_empty() {
if let Ok(value) = HeaderValue::from_str(&state) {
headers.insert(TRACESTATE, value);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn absolute_urls_are_told_from_paths() {
for url in ["http://x/y", "https://x", "h2c+x://y"] {
assert!(has_scheme(url), "{url}");
}
for path in ["/x", "x", "x/y:z", "", "1a:b", "/a:b"] {
assert!(!has_scheme(path), "{path}");
}
}
#[test]
fn origins_have_the_schemes_default_port() {
let url = |s: &str| origin_of(&reqwest::Url::parse(s).unwrap());
let uri = |s: &str| origin_of_uri(&s.parse().unwrap());
assert_eq!(url("http://LocalHost/x"), url("http://localhost:80/y"));
assert_eq!(url("https://egress"), uri("HTTPS://egress:443/a"));
assert_eq!(url("http://[::1]:9000/a"), uri("http://[::1]:9000"));
assert_ne!(url("http://localhost:4000"), url("http://localhost:4001"));
assert_eq!(uri("/package.Service/Method"), None);
}
}