Skip to main content

encore/
services.rs

1//! Calling other services in the application.
2//!
3//! A [`Client`] targets a single service. Because [`client`] is `const`, you
4//! can declare clients as module-level `static`s:
5//!
6//! ```ignore
7//! use encore::services;
8//!
9//! static BILLING: services::Client = services::client("billing");
10//!
11//! async fn invoices() -> anyhow::Result<Vec<Invoice>> {
12//!     Ok(BILLING.get("/invoices").send().await?.error_for_status()?.json().await?)
13//! }
14//! ```
15//!
16//! Outgoing requests to application services automatically propagate the active
17//! trace context and Request Context ([`crate::reqctx`]), so downstream
18//! services continue the same trace and request metadata. Requests to external
19//! origins never include Request Context headers. All [`Client`] instances
20//! share a single connection pool, so creating a client on demand is as cheap
21//! as using a `static`.
22//!
23//! For Tower-based HTTP clients (such as `hyper-util` or a `tonic` channel),
24//! use [`PropagateLayer`] for the same propagation behavior.
25//!
26//! Calling [`base_url`] or [`client`] declares a dependency on the target
27//! service. Because Encore parses dependencies statically from source code,
28//! pass the service name as a string literal, call the function directly
29//! (rather than through a function pointer), and make the call inside a
30//! service.
31//!
32//! # Generated clients
33//!
34//! When a service lists another service under `clients` in its
35//! `encore.service.json`, Encore generates typed clients in
36//! `encore_gen::clients` — one module per service, containing one module per
37//! declared API. Each operation is a top-level function returning a call builder
38//! that executes when `.await`ed:
39//!
40//! ```ignore
41//! mod encore_gen;
42//! use encore_gen::clients::catalog;
43//!
44//! let product = catalog::openapi::get_product("xyz").await?;
45//! let users = catalog::openapi::list_users().limit(10).await?;
46//! ```
47//!
48//! Failed calls return [`CallError`] regardless of API protocol, and `?`
49//! converts it into an [`encore::Error`](crate::Error) with the same error
50//! code:
51//!
52//! ```ignore
53//! let product = match catalog::openapi::get_product("xyz").await {
54//!     Ok(product) => Some(product),
55//!     Err(err) if err.code == encore::ErrCode::NotFound => None,
56//!     Err(err) => return Err(err.into()),
57//! };
58//! ```
59//!
60//! Use [`UnlessNotFound`] to turn a `NotFound` error into `Ok(None)`:
61//!
62//! ```ignore
63//! use encore::services::UnlessNotFound;
64//!
65//! let product = catalog::openapi::get_product("xyz").await.unless_not_found()?;
66//! ```
67//!
68//! For APIs that require a `Future` directly (such as `tokio::spawn` or
69//! `join_all`), call `.into_future()`. The resulting future captures the
70//! caller's trace and Request Context just like an awaited call:
71//!
72//! ```ignore
73//! use std::future::IntoFuture;
74//!
75//! let product = tokio::spawn(catalog::openapi::get_product("xyz").into_future());
76//! ```
77//!
78//! Individual calls can override timeouts and headers, and each API module
79//! provides a `Client` for sharing default settings across calls:
80//!
81//! ```ignore
82//! let product = catalog::openapi::get_product("xyz")
83//!     .timeout(Duration::from_secs(2))
84//!     .await?;
85//! let storefront = catalog::storefront::Client::new().header("x-tenant", "a");
86//! ```
87//!
88//! Generated HTTP/OpenAPI/GraphQL clients use the same shared connection pool
89//! and context propagation as [`Client`]. Generated gRPC clients ([`Unary`],
90//! [`ServerStreaming`], [`ClientStreaming`], and [`BidiStreaming`]) speak gRPC
91//! over HTTP/2 via `tonic`, sharing one channel per base URL — using cleartext
92//! HTTP/2 (`h2c`) for `http://` URLs and TLS (trusting system roots or
93//! `SSL_CERT_FILE`) for `https://` URLs.
94//!
95//! For gRPC calls, a timeout acts as an end-to-end deadline covering
96//! connecting and every message on a stream. Bidirectional streams resolve
97//! immediately without waiting for server headers so the server can read an
98//! initial client message first. Decoded protobuf messages preserve unknown
99//! fields from newer schemas when re-encoded, and gRPC error details are
100//! exposed on [`CallError::grpc_details`]. Because a generated `Client` only
101//! holds settings, constructing one per call is free and requires no cleanup.
102//!
103//! # Tests
104//!
105//! In unit tests under `encore test`, peer services are not started. Every
106//! service still has a placeholder base URL so clients can be constructed, but
107//! calls return `501 Not Implemented` identifying the service and path; mock
108//! downstream calls in unit tests (or use [system tests](crate::testing::system)).
109
110use std::collections::HashSet;
111use std::future::Future;
112use std::sync::{OnceLock, RwLock};
113use std::task::{Context as TaskContext, Poll};
114use std::time::Duration;
115
116use encore_sdk_core::telemetry::SpanContextExt;
117use http::header::{
118    HeaderName, HeaderValue, AUTHORIZATION, CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_LENGTH,
119    CONTENT_LOCATION, CONTENT_TYPE, COOKIE, LOCATION, PROXY_AUTHORIZATION, WWW_AUTHENTICATE,
120};
121use http::{HeaderMap, Method, StatusCode};
122use serde::Serialize;
123
124use crate::opentelemetry::trace::TraceContextExt;
125use crate::opentelemetry::Context;
126
127/// Re-export of `reqwest` for working with [`Client`] request and response types.
128pub use reqwest;
129
130#[doc(hidden)]
131pub mod clients;
132
133pub use clients::{
134    BidiStreaming, CallError, ClientStreaming, ServerStreaming, Stream, Streaming, Unary,
135    UnlessNotFound,
136};
137
138/// Returns the base URL for calling `service`, without a trailing slash (so
139/// paths can be appended directly, e.g. `{base}/users/42`).
140///
141/// # Panics
142///
143/// Panics if the runtime has no base URL configured for `service` — either
144/// because no service with that name exists or because the process was started
145/// without Encore service discovery (such as a plain `cargo test`).
146pub fn base_url(service: &str) -> &'static str {
147    lookup(service).unwrap_or_else(|| panic!("{}", unknown_service(service)))
148}
149
150/// The base URL of `service`, as [`base_url`] returns it, and `None` where
151/// that panics.
152fn lookup(service: &str) -> Option<&'static str> {
153    let url = crate::runtime::core()
154        .runtime_config()
155        .services
156        .get(service)?
157        .trim_end_matches('/');
158    register(url);
159    Some(url)
160}
161
162/// Formats the error message for an unknown or unconfigured service.
163pub(crate) fn unknown_service(service: &str) -> String {
164    format!("encore: no base URL configured for service {service:?}")
165}
166
167/// Creates a [`Client`] for calling `service`.
168///
169/// Requests accept paths relative to the service's base URL and automatically
170/// propagate the active trace and Request Context. This function is `const` so
171/// it can initialize a module-level `static`; the service URL is resolved on
172/// first use.
173///
174/// Like [`base_url`], calling `client` records a static dependency on
175/// `service`, so pass the service name as a string literal and call `client`
176/// directly inside a service.
177///
178/// ```ignore
179/// static ORDERS: encore::services::Client = encore::services::client("orders");
180/// ```
181pub const fn client(service: &'static str) -> Client {
182    Client {
183        service,
184        base: OnceLock::new(),
185    }
186}
187
188/// HTTP client for calling another service in the application, created with
189/// [`client`].
190#[derive(Debug)]
191pub struct Client {
192    service: &'static str,
193    base: OnceLock<&'static str>,
194}
195
196impl Client {
197    /// Returns the service's base URL without a trailing slash.
198    ///
199    /// # Panics
200    ///
201    /// Panics under the same conditions as [`base_url`].
202    pub fn base_url(&self) -> &'static str {
203        self.try_base_url()
204            .unwrap_or_else(|| panic!("{}", unknown_service(self.service)))
205    }
206
207    /// The service's base URL, as [`Client::base_url`] returns it, and `None`
208    /// where that panics.
209    pub(crate) fn try_base_url(&self) -> Option<&'static str> {
210        if let Some(base) = self.base.get() {
211            return Some(base);
212        }
213        let base = lookup(self.service)?;
214        Some(self.base.get_or_init(|| base))
215    }
216
217    /// The service's name.
218    pub(crate) fn name(&self) -> &'static str {
219        self.service
220    }
221
222    /// A `GET` request for `path`. See [`Client::request`].
223    pub fn get(&self, path: &str) -> RequestBuilder {
224        self.request(Method::GET, path)
225    }
226
227    /// A `POST` request for `path`. See [`Client::request`].
228    pub fn post(&self, path: &str) -> RequestBuilder {
229        self.request(Method::POST, path)
230    }
231
232    /// A `PUT` request for `path`. See [`Client::request`].
233    pub fn put(&self, path: &str) -> RequestBuilder {
234        self.request(Method::PUT, path)
235    }
236
237    /// A `PATCH` request for `path`. See [`Client::request`].
238    pub fn patch(&self, path: &str) -> RequestBuilder {
239        self.request(Method::PATCH, path)
240    }
241
242    /// A `DELETE` request for `path`. See [`Client::request`].
243    pub fn delete(&self, path: &str) -> RequestBuilder {
244        self.request(Method::DELETE, path)
245    }
246
247    /// A `HEAD` request for `path`. See [`Client::request`].
248    pub fn head(&self, path: &str) -> RequestBuilder {
249        self.request(Method::HEAD, path)
250    }
251
252    /// Starts a request with `method` and `path`.
253    ///
254    /// Relative paths are joined to the service's base URL with a single `/`
255    /// (so `/invoices` and `invoices` are equivalent). Absolute URLs with a
256    /// scheme are used as-is.
257    ///
258    /// # Panics
259    ///
260    /// Panics under the same conditions as [`base_url`].
261    pub fn request(&self, method: Method, path: &str) -> RequestBuilder {
262        // Looked up for an absolute URL too: the lookup is what records the
263        // service's origin, and what fails for an unknown service.
264        let base = self.base_url();
265        let url = if has_scheme(path) {
266            path.to_string()
267        } else {
268            format!("{base}/{}", path.trim_start_matches('/'))
269        };
270        request_to(method, url)
271    }
272}
273
274/// A request for absolute `url`, sent as a [`Client`]'s are, for one that
275/// has looked its service up already, or tried to.
276pub(crate) fn request_to(method: Method, url: String) -> RequestBuilder {
277    RequestBuilder {
278        inner: shared().request(method, url),
279    }
280}
281
282/// Whether `path` is an absolute URL: it starts with a scheme.
283fn has_scheme(path: &str) -> bool {
284    let Some((scheme, _)) = path.split_once(':') else {
285        return false;
286    };
287    let mut chars = scheme.chars();
288    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
289        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
290}
291
292/// Builder for an HTTP request sent by [`Client`], wrapping
293/// [`reqwest::RequestBuilder`] with Encore context propagation.
294#[derive(Debug)]
295#[must_use = "a request is not sent until `.send()` is called"]
296pub struct RequestBuilder {
297    inner: reqwest::RequestBuilder,
298}
299
300impl RequestBuilder {
301    /// Adds a header.
302    pub fn header<K, V>(self, key: K, value: V) -> Self
303    where
304        HeaderName: TryFrom<K>,
305        <HeaderName as TryFrom<K>>::Error: Into<http::Error>,
306        HeaderValue: TryFrom<V>,
307        <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
308    {
309        self.map(|b| b.header(key, value))
310    }
311
312    /// Adds headers.
313    pub fn headers(self, headers: HeaderMap) -> Self {
314        self.map(|b| b.headers(headers))
315    }
316
317    /// Adds query parameters, as reqwest's
318    /// [`query`](reqwest::RequestBuilder::query) does.
319    pub fn query<T: Serialize + ?Sized>(self, query: &T) -> Self {
320        self.map(|b| b.query(query))
321    }
322
323    /// Sends `json` as the body, as JSON.
324    pub fn json<T: Serialize + ?Sized>(self, json: &T) -> Self {
325        self.map(|b| b.json(json))
326    }
327
328    /// Sends `form` as the body, URL-encoded.
329    pub fn form<T: Serialize + ?Sized>(self, form: &T) -> Self {
330        self.map(|b| b.form(form))
331    }
332
333    /// Sends `body` as the body.
334    pub fn body<T: Into<reqwest::Body>>(self, body: T) -> Self {
335        self.map(|b| b.body(body))
336    }
337
338    /// Sets a per-request timeout applied to the initial request and each
339    /// redirect.
340    pub fn timeout(self, timeout: Duration) -> Self {
341        self.map(|b| b.timeout(timeout))
342    }
343
344    /// Adds a bearer token `Authorization` header.
345    pub fn bearer_auth<T: std::fmt::Display>(self, token: T) -> Self {
346        self.map(|b| b.bearer_auth(token))
347    }
348
349    /// Adds a basic `Authorization` header.
350    pub fn basic_auth<U: std::fmt::Display, P: std::fmt::Display>(
351        self,
352        username: U,
353        password: Option<P>,
354    ) -> Self {
355        self.map(|b| b.basic_auth(username, password))
356    }
357
358    /// Applies a custom transformation to the underlying
359    /// [`reqwest::RequestBuilder`] for options not directly exposed here.
360    pub fn map(self, f: impl FnOnce(reqwest::RequestBuilder) -> reqwest::RequestBuilder) -> Self {
361        RequestBuilder {
362            inner: f(self.inner),
363        }
364    }
365
366    /// Sends the request, propagating the active trace and Request Context
367    /// when targeting an application service (and stripping Request Context
368    /// headers otherwise).
369    ///
370    /// Context is taken from the polling context (such as via
371    /// `.send().with_context(cx)`) if it contains a trace or Request Context;
372    /// otherwise it falls back to the context active when `send` was called so
373    /// spawned futures preserve the caller's context.
374    ///
375    /// Follows up to 10 redirects, re-evaluating context propagation for each
376    /// hop so redirects to external origins never receive Request Context
377    /// headers. Following the Fetch specification, 301/302 converts `POST` to
378    /// `GET`, 303 converts any method other than `GET`/`HEAD` to `GET`, and
379    /// 307/308 preserves the method and body. After 10 redirects, or if a
380    /// redirect requires re-sending a streamed body, the redirect response is
381    /// returned as-is.
382    pub fn send(self) -> impl Future<Output = Result<reqwest::Response, reqwest::Error>> {
383        let called_in = Context::current();
384        let request = self.inner.build();
385        async move {
386            let polled_in = Context::current();
387            let cx = if carries_context(&polled_in) {
388                polled_in
389            } else {
390                called_in
391            };
392            follow_redirects(&cx, request?).await
393        }
394    }
395}
396
397/// How many redirects a request follows, as reqwest's default policy.
398const MAX_REDIRECTS: usize = 10;
399
400/// The headers that describe a body, which a redirect dropping it drops too,
401/// as fetch does.
402const BODY_HEADERS: [HeaderName; 5] = [
403    CONTENT_TYPE,
404    CONTENT_LENGTH,
405    CONTENT_ENCODING,
406    CONTENT_LANGUAGE,
407    CONTENT_LOCATION,
408];
409
410/// The headers a redirect to another origin drops, as reqwest's does.
411const CREDENTIAL_HEADERS: [HeaderName; 4] =
412    [AUTHORIZATION, COOKIE, PROXY_AUTHORIZATION, WWW_AUTHENTICATE];
413
414/// Sends `request`, and the requests the redirects it is answered with ask
415/// for, each prepared for its own URL in `cx`.
416async fn follow_redirects(
417    cx: &Context,
418    mut request: reqwest::Request,
419) -> Result<reqwest::Response, reqwest::Error> {
420    let client = shared();
421    let mut redirects = 0;
422    loop {
423        let origin = origin_of(request.url());
424        prepare(cx, origin.as_ref(), request.headers_mut());
425        let again = request.try_clone();
426        let method = request.method().clone();
427        let headers = request.headers().clone();
428        let timeout = request.timeout().copied();
429        let response = client.execute(request).await?;
430        let location = response
431            .headers()
432            .get(LOCATION)
433            .and_then(|l| l.to_str().ok())
434            .and_then(|l| response.url().join(l).ok());
435        let Some(location) = location else {
436            return Ok(response);
437        };
438        if redirects == MAX_REDIRECTS {
439            return Ok(response);
440        }
441        // As fetch does: a 301 or 302 turns only a POST into a GET, and a
442        // 303 anything but a HEAD; the others keep the method and body.
443        let to_get = match response.status() {
444            StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND => method == Method::POST,
445            StatusCode::SEE_OTHER => method != Method::GET && method != Method::HEAD,
446            StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT => false,
447            _ => return Ok(response),
448        };
449        let mut next = if to_get {
450            // Without the body, so a streamed one is no obstacle.
451            let mut next = reqwest::Request::new(Method::GET, location.clone());
452            *next.headers_mut() = headers;
453            *next.timeout_mut() = timeout;
454            for name in BODY_HEADERS {
455                next.headers_mut().remove(name);
456            }
457            next
458        } else {
459            match again {
460                Some(next) => next,
461                // A streamed body cannot be sent again.
462                None => return Ok(response),
463            }
464        };
465        if origin_of(&location) != origin {
466            for name in CREDENTIAL_HEADERS {
467                next.headers_mut().remove(name);
468            }
469        }
470        *next.url_mut() = location;
471        request = next;
472        redirects += 1;
473    }
474}
475
476/// The reqwest client every [`Client`] sends with: one, so they share its
477/// connections. It follows no redirects itself: [`follow_redirects`] does,
478/// preparing each.
479fn shared() -> &'static reqwest::Client {
480    static SHARED: OnceLock<reqwest::Client> = OnceLock::new();
481    SHARED.get_or_init(|| {
482        // The core installs the process's TLS provider, which the client uses.
483        let core = crate::runtime::core();
484        let mut builder = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none());
485        // A system test's process has a Tokio runtime for each test, and one
486        // for each fixture it builds, which ends with it. A connection is
487        // driven by the runtime it was opened in, so one kept for the next
488        // call would be dead by the time another test took it up: there
489        // none is kept.
490        if core.system_test().is_some() {
491            builder = builder.pool_max_idle_per_host(0);
492        }
493        builder
494            .build()
495            .expect("encore: building the HTTP client for service calls")
496    })
497}
498
499/// Tower [`Layer`](tower_layer::Layer) that propagates the active trace and
500/// Request Context on outgoing requests to application services (and strips
501/// Request Context headers for all other origins).
502///
503/// Use this with `hyper-util`, `tonic` channels, or any Tower HTTP client:
504///
505/// ```ignore
506/// use encore::services;
507///
508/// let base = services::base_url("search");
509/// let channel = tonic::transport::Endpoint::from_static(base).connect_lazy();
510/// let search = SearchClient::with_origin(
511///     tower::ServiceBuilder::new().layer(services::PropagateLayer).service(channel),
512///     base.parse()?,
513/// );
514/// ```
515///
516/// A request is treated as targeting an application service if its URI matches
517/// the origin of a URL returned by [`base_url`] (requests without an explicit
518/// origin, such as a `tonic` client not constructed with `with_origin`, are
519/// not). This layer does not follow redirects itself; place redirect middleware
520/// outside it so each redirected request is prepared individually.
521#[derive(Debug, Clone, Copy, Default)]
522pub struct PropagateLayer;
523
524impl<S> tower_layer::Layer<S> for PropagateLayer {
525    type Service = Propagate<S>;
526
527    fn layer(&self, inner: S) -> Propagate<S> {
528        Propagate { inner }
529    }
530}
531
532/// Tower service produced by [`PropagateLayer`].
533#[derive(Debug, Clone)]
534pub struct Propagate<S> {
535    inner: S,
536}
537
538impl<S, B> tower_service::Service<http::Request<B>> for Propagate<S>
539where
540    S: tower_service::Service<http::Request<B>>,
541{
542    type Response = S::Response;
543    type Error = S::Error;
544    type Future = S::Future;
545
546    fn poll_ready(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<(), S::Error>> {
547        self.inner.poll_ready(cx)
548    }
549
550    fn call(&mut self, mut request: http::Request<B>) -> S::Future {
551        let origin = origin_of_uri(request.uri());
552        prepare(&Context::current(), origin.as_ref(), request.headers_mut());
553        self.inner.call(request)
554    }
555}
556
557/// A URL's scheme, host and port, with the scheme's default port when it
558/// has none.
559#[derive(Debug, Clone, PartialEq, Eq, Hash)]
560struct Origin {
561    scheme: String,
562    host: String,
563    port: Option<u16>,
564}
565
566fn origin_of(url: &reqwest::Url) -> Option<Origin> {
567    Some(Origin {
568        scheme: url.scheme().to_ascii_lowercase(),
569        host: url.host_str()?.to_ascii_lowercase(),
570        port: url.port_or_known_default(),
571    })
572}
573
574fn origin_of_uri(uri: &http::Uri) -> Option<Origin> {
575    let scheme = uri.scheme_str()?.to_ascii_lowercase();
576    let port = uri.port_u16().or(match scheme.as_str() {
577        "http" => Some(80),
578        "https" => Some(443),
579        _ => None,
580    });
581    Some(Origin {
582        host: uri.host()?.to_ascii_lowercase(),
583        scheme,
584        port,
585    })
586}
587
588/// The origins of the base URLs [`base_url`] has returned: where the app's
589/// services are reached. Every service URL is the egress endpoint's, or
590/// locally the run proxy's, plus the service's path; nothing else is served
591/// at either.
592static ORIGINS: RwLock<Option<HashSet<Origin>>> = RwLock::new(None);
593
594/// Records the origin of `base`, a service's base URL.
595fn register(base: &str) {
596    let Some(origin) = reqwest::Url::parse(base).ok().and_then(|u| origin_of(&u)) else {
597        return;
598    };
599    if is_service(Some(&origin)) {
600        return;
601    }
602    ORIGINS
603        .write()
604        .unwrap_or_else(|e| e.into_inner())
605        .get_or_insert_with(HashSet::new)
606        .insert(origin);
607}
608
609/// Whether `origin` is one of the app's services'.
610fn is_service(origin: Option<&Origin>) -> bool {
611    origin.is_some_and(|origin| {
612        ORIGINS
613            .read()
614            .unwrap_or_else(|e| e.into_inner())
615            .as_ref()
616            .is_some_and(|o| o.contains(origin))
617    })
618}
619
620/// Whether `cx` holds a trace or Request Context to send.
621pub(crate) fn carries_context(cx: &Context) -> bool {
622    cx.span().span_context().is_valid() || !encore_sdk_core::reqctx::Values::of(cx).is_empty()
623}
624
625const TRACEPARENT: HeaderName = HeaderName::from_static("traceparent");
626const TRACESTATE: HeaderName = HeaderName::from_static("tracestate");
627
628/// Sets the trace and Request Context of `cx` on a request to `origin`:
629/// drops the Request Context headers it carried, then, when it is for one of
630/// the app's services, sets the context's fields and, unless it carries one,
631/// the W3C trace context of its span, whose `tracestate` carries Encore's
632/// mark. Encore's egress records the call's span.
633fn prepare(cx: &Context, origin: Option<&Origin>, headers: &mut HeaderMap) {
634    if !is_service(origin) {
635        let stale: Vec<HeaderName> = headers
636            .keys()
637            .filter(|name| encore_telemetry::propagation::is_context_header(name.as_str()))
638            .cloned()
639            .collect();
640        for name in stale {
641            headers.remove(name);
642        }
643        return;
644    }
645    // In a system test a call carries the test, where `cx` does not. One
646    // whose test cannot be told panics, rather than go out as no test's.
647    let cx = &crate::testing::outgoing(cx);
648    crate::reqctx::inject(cx, headers);
649    if headers.contains_key(TRACEPARENT) {
650        return;
651    }
652    let span = cx.span();
653    let sc = span.span_context();
654    if !sc.is_valid() {
655        return;
656    }
657    if let Ok(value) = HeaderValue::from_str(&sc.to_traceparent()) {
658        headers.insert(TRACEPARENT, value);
659    }
660    // A tracestate the request carried belongs to another trace's
661    // traceparent: the span's own, with Encore's mark, replaces it.
662    headers.remove(TRACESTATE);
663    let state = sc.trace_state().header();
664    if !state.is_empty() {
665        if let Ok(value) = HeaderValue::from_str(&state) {
666            headers.insert(TRACESTATE, value);
667        }
668    }
669}
670
671#[cfg(test)]
672mod tests {
673    use super::*;
674
675    #[test]
676    fn absolute_urls_are_told_from_paths() {
677        for url in ["http://x/y", "https://x", "h2c+x://y"] {
678            assert!(has_scheme(url), "{url}");
679        }
680        for path in ["/x", "x", "x/y:z", "", "1a:b", "/a:b"] {
681            assert!(!has_scheme(path), "{path}");
682        }
683    }
684
685    #[test]
686    fn origins_have_the_schemes_default_port() {
687        let url = |s: &str| origin_of(&reqwest::Url::parse(s).unwrap());
688        let uri = |s: &str| origin_of_uri(&s.parse().unwrap());
689        assert_eq!(url("http://LocalHost/x"), url("http://localhost:80/y"));
690        assert_eq!(url("https://egress"), uri("HTTPS://egress:443/a"));
691        assert_eq!(url("http://[::1]:9000/a"), uri("http://[::1]:9000"));
692        assert_ne!(url("http://localhost:4000"), url("http://localhost:4001"));
693        assert_eq!(uri("/package.Service/Method"), None);
694    }
695}