Skip to main content

encore/
services.rs

1//! Calling the app's other services.
2//!
3//! A [`Client`] calls one service. It is `const`, so it can be a `static`:
4//!
5//! ```ignore
6//! use encore::services;
7//!
8//! static BILLING: services::Client = services::client("billing");
9//!
10//! async fn invoices() -> anyhow::Result<Vec<Invoice>> {
11//!     Ok(BILLING.get("/invoices").send().await?.error_for_status()?.json().await?)
12//! }
13//! ```
14//!
15//! Its calls carry the trace and Request Context ([`crate::reqctx`]) of the
16//! context they are sent in to the app's services, so the services they reach
17//! continue the request they are made for. A request to anything else carries
18//! no Request Context: who a request is made for is no business of a third
19//! party's. Every client shares the same connections, so making one where it
20//! is needed costs no more than a `static`.
21//!
22//! A tower client, as hyper-util's or a tonic channel, does the same through
23//! [`PropagateLayer`].
24//!
25//! Looking up a service's URL, or making a client for it, makes the calling
26//! service depend on it. Encore reads the dependency from the code, as it
27//! reads which resources a service uses: so the name must be a string
28//! literal, the function must be called directly rather than passed around,
29//! and the call must be in a service.
30//!
31//! # Generated clients
32//!
33//! A service that lists another in its `encore.service.json` `clients` gets
34//! clients for calling it in `encore_gen::clients`: a module per service,
35//! with a module per API the service declares. Each operation is a function
36//! of its module, returning the call, which `.await` sends, so there is no
37//! client to make first:
38//!
39//! ```ignore
40//! mod encore_gen;
41//! use encore_gen::clients::catalog;
42//!
43//! let product = catalog::openapi::get_product("xyz").await?;
44//! let users = catalog::openapi::list_users().limit(10).await?;
45//! ```
46//!
47//! A call that fails is a [`CallError`], whatever kind of API it calls, and
48//! `?` turns it into an [`encore::Error`](crate::Error) with the same code:
49//!
50//! ```ignore
51//! let product = match catalog::openapi::get_product("xyz").await {
52//!     Ok(product) => Some(product),
53//!     Err(err) if err.code == encore::ErrCode::NotFound => None,
54//!     Err(err) => return Err(err.into()),
55//! };
56//! ```
57//!
58//! [`UnlessNotFound`] makes a `NotFound` failure `None`, for a call for
59//! something that may not be there:
60//!
61//! ```ignore
62//! use encore::services::UnlessNotFound;
63//!
64//! let product = catalog::openapi::get_product("xyz").await.unless_not_found()?;
65//! ```
66//!
67//! A call is a `Future` once `into_future` makes it one, for what takes a
68//! future rather than something to await, as `tokio::spawn` and `join_all`
69//! do. It carries the context of the code that made it, as an awaited call
70//! does:
71//!
72//! ```ignore
73//! use std::future::IntoFuture;
74//!
75//! let product = tokio::spawn(catalog::openapi::get_product("xyz").into_future());
76//! ```
77//!
78//! Every call also takes a timeout and headers of its own, which go over its
79//! client's, and a module's `Client` holds settings for every call made with
80//! it:
81//!
82//! ```ignore
83//! let product = catalog::openapi::get_product("xyz")
84//!     .timeout(Duration::from_secs(2))
85//!     .await?;
86//! let storefront = catalog::storefront::Client::new().header("x-tenant", "a");
87//! ```
88//!
89//! The clients send as a [`Client`] does, so their calls carry the trace and
90//! Request Context of the context they are made in, and share its
91//! connections; a gRPC API's calls, which are [`Unary`], [`ServerStreaming`],
92//! [`ClientStreaming`] and [`BidiStreaming`], share one connection per base
93//! URL. They speak gRPC over HTTP/2, through tonic, as every language's
94//! generated clients do: in the clear (h2c) to an `http://` base URL, and
95//! with TLS to an `https://` one, trusting the system's roots, or those of
96//! `SSL_CERT_FILE`. A gRPC call's timeout is its deadline, which holds for
97//! the whole call, connecting and each message of a stream too. A
98//! bidirectional call is ready before the service answers, as a service may
99//! wait for a message first. A gRPC message keeps the fields its schema
100//! lacks, as a newer schema's, and sends them on; a failed call keeps its
101//! status's details, in [`CallError::grpc_details`]. A client holds only its
102//! settings, so one made for a single call costs nothing to make, and there
103//! is nothing to close.
104//!
105//! # Tests
106//!
107//! No service runs under `encore test`. Every service still has a base URL
108//! there, so a client can be made as usual, but a call to it is answered with
109//! `501 Not Implemented` and an error saying which service and path the test
110//! called: mock the call in the test instead.
111
112use std::collections::HashSet;
113use std::future::Future;
114use std::sync::{OnceLock, RwLock};
115use std::task::{Context as TaskContext, Poll};
116use std::time::Duration;
117
118use encore_sdk_core::telemetry::SpanContextExt;
119use http::header::{
120    HeaderName, HeaderValue, AUTHORIZATION, CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_LENGTH,
121    CONTENT_LOCATION, CONTENT_TYPE, COOKIE, LOCATION, PROXY_AUTHORIZATION, WWW_AUTHENTICATE,
122};
123use http::{HeaderMap, Method, StatusCode};
124use serde::Serialize;
125
126use crate::opentelemetry::trace::TraceContextExt;
127use crate::opentelemetry::Context;
128
129/// The reqwest a [`Client`] is made with, for the types its requests take
130/// and its responses are.
131pub use reqwest;
132
133#[doc(hidden)]
134pub mod clients;
135
136pub use clients::{
137    BidiStreaming, CallError, ClientStreaming, ServerStreaming, Stream, Streaming, Unary,
138    UnlessNotFound,
139};
140
141/// The base URL the calling service reaches `service` at, for
142/// service-to-service calls, without a trailing slash: a call's path goes
143/// after it, `{base}/users/42`.
144///
145/// # Panics
146///
147/// If the runtime has no address for `service`: the app has no service of
148/// that name, which Encore's parser reports, or this process was started
149/// without the app's service discovery, as a plain `cargo test` is.
150pub fn base_url(service: &str) -> &'static str {
151    lookup(service).unwrap_or_else(|| panic!("{}", unknown_service(service)))
152}
153
154/// The base URL of `service`, as [`base_url`] returns it, and `None` where
155/// that panics.
156fn lookup(service: &str) -> Option<&'static str> {
157    let url = crate::runtime::core()
158        .runtime_config()
159        .services
160        .get(service)?
161        .trim_end_matches('/');
162    register(url);
163    Some(url)
164}
165
166/// What a lookup of a service the runtime knows no address for says.
167pub(crate) fn unknown_service(service: &str) -> String {
168    format!("encore: no base URL is known for service {service:?}")
169}
170
171/// A client for `service`, for service-to-service calls: its requests take
172/// the service's paths, and carry the trace and Request Context of the
173/// context they are sent in.
174///
175/// It is `const`, so it can be a `static`, and looks the service up when it
176/// is first used. Like [`base_url`], it makes the calling service depend on
177/// `service`, so the name must be a string literal and the call made
178/// directly, in a service.
179///
180/// ```ignore
181/// static ORDERS: encore::services::Client = encore::services::client("orders");
182/// ```
183pub const fn client(service: &'static str) -> Client {
184    Client {
185        service,
186        base: OnceLock::new(),
187    }
188}
189
190/// A client for one of the app's services, made with [`client`].
191#[derive(Debug)]
192pub struct Client {
193    service: &'static str,
194    base: OnceLock<&'static str>,
195}
196
197impl Client {
198    /// The service's base URL, without a trailing slash, as [`base_url`]
199    /// returns it.
200    ///
201    /// # Panics
202    ///
203    /// As [`base_url`] does.
204    pub fn base_url(&self) -> &'static str {
205        self.try_base_url()
206            .unwrap_or_else(|| panic!("{}", unknown_service(self.service)))
207    }
208
209    /// The service's base URL, as [`Client::base_url`] returns it, and `None`
210    /// where that panics.
211    pub(crate) fn try_base_url(&self) -> Option<&'static str> {
212        if let Some(base) = self.base.get() {
213            return Some(base);
214        }
215        let base = lookup(self.service)?;
216        Some(self.base.get_or_init(|| base))
217    }
218
219    /// The service's name.
220    pub(crate) fn name(&self) -> &'static str {
221        self.service
222    }
223
224    /// A `GET` request for `path`. See [`Client::request`].
225    pub fn get(&self, path: &str) -> RequestBuilder {
226        self.request(Method::GET, path)
227    }
228
229    /// A `POST` request for `path`. See [`Client::request`].
230    pub fn post(&self, path: &str) -> RequestBuilder {
231        self.request(Method::POST, path)
232    }
233
234    /// A `PUT` request for `path`. See [`Client::request`].
235    pub fn put(&self, path: &str) -> RequestBuilder {
236        self.request(Method::PUT, path)
237    }
238
239    /// A `PATCH` request for `path`. See [`Client::request`].
240    pub fn patch(&self, path: &str) -> RequestBuilder {
241        self.request(Method::PATCH, path)
242    }
243
244    /// A `DELETE` request for `path`. See [`Client::request`].
245    pub fn delete(&self, path: &str) -> RequestBuilder {
246        self.request(Method::DELETE, path)
247    }
248
249    /// A `HEAD` request for `path`. See [`Client::request`].
250    pub fn head(&self, path: &str) -> RequestBuilder {
251        self.request(Method::HEAD, path)
252    }
253
254    /// A request for `path`, which is the service's: it is joined to the base
255    /// URL with a single `/`, so `/invoices` and `invoices` are the same
256    /// request. An absolute URL is used as it is.
257    ///
258    /// # Panics
259    ///
260    /// As [`base_url`] does.
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/// A request a [`Client`] sends: reqwest's builder, whose
293/// [`send`](RequestBuilder::send) carries the call's context.
294#[derive(Debug)]
295#[must_use = "a request is sent only by `send`"]
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    /// Fails each request it sends, the first and each redirect, that is not
339    /// answered within `timeout`.
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    /// Changes the request as reqwest's builder does, for what this one
359    /// does not offer.
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, with the Request Context and trace of its context
367    /// when it is for one of the app's services, without any Request Context
368    /// otherwise.
369    ///
370    /// Its context is the one it is first polled in, as
371    /// `.send().with_context(cx)` sets it, unless that one holds neither a
372    /// trace nor Request Context: then the one `send` is called in, so a
373    /// future handed to `tokio::spawn` still carries the call's.
374    ///
375    /// It follows up to 10 redirects, each sent with the context its own URL
376    /// is due, so a redirect away from the app's services carries no Request
377    /// Context. As fetch does, a 301 or 302 turns only a `POST` into a `GET`,
378    /// and a 303 anything but a `HEAD`; a 307 or 308 keeps the method and
379    /// body. Past 10 redirects, or when a redirect would need a streamed body
380    /// sent again, the redirect itself is the response.
381    pub fn send(self) -> impl Future<Output = Result<reqwest::Response, reqwest::Error>> {
382        let called_in = Context::current();
383        let request = self.inner.build();
384        async move {
385            let polled_in = Context::current();
386            let cx = if carries_context(&polled_in) {
387                polled_in
388            } else {
389                called_in
390            };
391            follow_redirects(&cx, request?).await
392        }
393    }
394}
395
396/// How many redirects a request follows, as reqwest's default policy.
397const MAX_REDIRECTS: usize = 10;
398
399/// The headers that describe a body, which a redirect dropping it drops too,
400/// as fetch does.
401const BODY_HEADERS: [HeaderName; 5] = [
402    CONTENT_TYPE,
403    CONTENT_LENGTH,
404    CONTENT_ENCODING,
405    CONTENT_LANGUAGE,
406    CONTENT_LOCATION,
407];
408
409/// The headers a redirect to another origin drops, as reqwest's does.
410const CREDENTIAL_HEADERS: [HeaderName; 4] =
411    [AUTHORIZATION, COOKIE, PROXY_AUTHORIZATION, WWW_AUTHENTICATE];
412
413/// Sends `request`, and the requests the redirects it is answered with ask
414/// for, each prepared for its own URL in `cx`.
415async fn follow_redirects(
416    cx: &Context,
417    mut request: reqwest::Request,
418) -> Result<reqwest::Response, reqwest::Error> {
419    let client = shared();
420    let mut redirects = 0;
421    loop {
422        let origin = origin_of(request.url());
423        prepare(cx, origin.as_ref(), request.headers_mut());
424        let again = request.try_clone();
425        let method = request.method().clone();
426        let headers = request.headers().clone();
427        let timeout = request.timeout().copied();
428        let response = client.execute(request).await?;
429        let location = response
430            .headers()
431            .get(LOCATION)
432            .and_then(|l| l.to_str().ok())
433            .and_then(|l| response.url().join(l).ok());
434        let Some(location) = location else {
435            return Ok(response);
436        };
437        if redirects == MAX_REDIRECTS {
438            return Ok(response);
439        }
440        // As fetch does: a 301 or 302 turns only a POST into a GET, and a
441        // 303 anything but a HEAD; the others keep the method and body.
442        let to_get = match response.status() {
443            StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND => method == Method::POST,
444            StatusCode::SEE_OTHER => method != Method::GET && method != Method::HEAD,
445            StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT => false,
446            _ => return Ok(response),
447        };
448        let mut next = if to_get {
449            // Without the body, so a streamed one is no obstacle.
450            let mut next = reqwest::Request::new(Method::GET, location.clone());
451            *next.headers_mut() = headers;
452            *next.timeout_mut() = timeout;
453            for name in BODY_HEADERS {
454                next.headers_mut().remove(name);
455            }
456            next
457        } else {
458            match again {
459                Some(next) => next,
460                // A streamed body cannot be sent again.
461                None => return Ok(response),
462            }
463        };
464        if origin_of(&location) != origin {
465            for name in CREDENTIAL_HEADERS {
466                next.headers_mut().remove(name);
467            }
468        }
469        *next.url_mut() = location;
470        request = next;
471        redirects += 1;
472    }
473}
474
475/// The reqwest client every [`Client`] sends with: one, so they share its
476/// connections. It follows no redirects itself: [`follow_redirects`] does,
477/// preparing each.
478fn shared() -> &'static reqwest::Client {
479    static SHARED: OnceLock<reqwest::Client> = OnceLock::new();
480    SHARED.get_or_init(|| {
481        // The core installs the process's TLS provider, which the client uses.
482        let core = crate::runtime::core();
483        let mut builder = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none());
484        // A system test's process has a Tokio runtime for each test, and one
485        // for each fixture it builds, which ends with it. A connection is
486        // driven by the runtime it was opened in, so one kept for the next
487        // call would be dead by the time another test took it up: there
488        // none is kept.
489        if core.system_test().is_some() {
490            builder = builder.pool_max_idle_per_host(0);
491        }
492        builder
493            .build()
494            .expect("encore: building the HTTP client for service calls")
495    })
496}
497
498/// A tower [`Layer`](tower_layer::Layer) whose services send the trace and
499/// Request Context of the context a request is sent in with each request
500/// for one of the app's services, and no Request Context with any other: for
501/// hyper-util's client, a tonic channel, or any tower HTTP client.
502///
503/// ```ignore
504/// use encore::services;
505///
506/// let base = services::base_url("search");
507/// let channel = tonic::transport::Endpoint::from_static(base).connect_lazy();
508/// let search = SearchClient::with_origin(
509///     tower::ServiceBuilder::new().layer(services::PropagateLayer).service(channel),
510///     base.parse()?,
511/// );
512/// ```
513///
514/// A request is for the app's services when its URI is at the origin of a
515/// base URL [`base_url`] returned. A request whose URI has none, as a tonic
516/// client's without `with_origin`, is not. It follows no redirects; a layer
517/// outside it that does has each one prepared.
518#[derive(Debug, Clone, Copy, Default)]
519pub struct PropagateLayer;
520
521impl<S> tower_layer::Layer<S> for PropagateLayer {
522    type Service = Propagate<S>;
523
524    fn layer(&self, inner: S) -> Propagate<S> {
525        Propagate { inner }
526    }
527}
528
529/// The service of a [`PropagateLayer`].
530#[derive(Debug, Clone)]
531pub struct Propagate<S> {
532    inner: S,
533}
534
535impl<S, B> tower_service::Service<http::Request<B>> for Propagate<S>
536where
537    S: tower_service::Service<http::Request<B>>,
538{
539    type Response = S::Response;
540    type Error = S::Error;
541    type Future = S::Future;
542
543    fn poll_ready(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<(), S::Error>> {
544        self.inner.poll_ready(cx)
545    }
546
547    fn call(&mut self, mut request: http::Request<B>) -> S::Future {
548        let origin = origin_of_uri(request.uri());
549        prepare(&Context::current(), origin.as_ref(), request.headers_mut());
550        self.inner.call(request)
551    }
552}
553
554/// A URL's scheme, host and port, with the scheme's default port when it
555/// has none.
556#[derive(Debug, Clone, PartialEq, Eq, Hash)]
557struct Origin {
558    scheme: String,
559    host: String,
560    port: Option<u16>,
561}
562
563fn origin_of(url: &reqwest::Url) -> Option<Origin> {
564    Some(Origin {
565        scheme: url.scheme().to_ascii_lowercase(),
566        host: url.host_str()?.to_ascii_lowercase(),
567        port: url.port_or_known_default(),
568    })
569}
570
571fn origin_of_uri(uri: &http::Uri) -> Option<Origin> {
572    let scheme = uri.scheme_str()?.to_ascii_lowercase();
573    let port = uri.port_u16().or(match scheme.as_str() {
574        "http" => Some(80),
575        "https" => Some(443),
576        _ => None,
577    });
578    Some(Origin {
579        host: uri.host()?.to_ascii_lowercase(),
580        scheme,
581        port,
582    })
583}
584
585/// The origins of the base URLs [`base_url`] has returned: where the app's
586/// services are reached. Every service URL is the egress endpoint's, or
587/// locally the run proxy's, plus the service's path; nothing else is served
588/// at either.
589static ORIGINS: RwLock<Option<HashSet<Origin>>> = RwLock::new(None);
590
591/// Records the origin of `base`, a service's base URL.
592fn register(base: &str) {
593    let Some(origin) = reqwest::Url::parse(base).ok().and_then(|u| origin_of(&u)) else {
594        return;
595    };
596    if is_service(Some(&origin)) {
597        return;
598    }
599    ORIGINS
600        .write()
601        .unwrap_or_else(|e| e.into_inner())
602        .get_or_insert_with(HashSet::new)
603        .insert(origin);
604}
605
606/// Whether `origin` is one of the app's services'.
607fn is_service(origin: Option<&Origin>) -> bool {
608    origin.is_some_and(|origin| {
609        ORIGINS
610            .read()
611            .unwrap_or_else(|e| e.into_inner())
612            .as_ref()
613            .is_some_and(|o| o.contains(origin))
614    })
615}
616
617/// Whether `cx` holds a trace or Request Context to send.
618pub(crate) fn carries_context(cx: &Context) -> bool {
619    cx.span().span_context().is_valid() || !encore_sdk_core::reqctx::Values::of(cx).is_empty()
620}
621
622const TRACEPARENT: HeaderName = HeaderName::from_static("traceparent");
623const TRACESTATE: HeaderName = HeaderName::from_static("tracestate");
624
625/// Sets the trace and Request Context of `cx` on a request to `origin`:
626/// drops the Request Context headers it carried, then, when it is for one of
627/// the app's services, sets the context's fields and, unless it carries one,
628/// the W3C trace context of its span, whose `tracestate` carries Encore's
629/// mark. Encore's egress records the call's span.
630fn prepare(cx: &Context, origin: Option<&Origin>, headers: &mut HeaderMap) {
631    if !is_service(origin) {
632        let stale: Vec<HeaderName> = headers
633            .keys()
634            .filter(|name| encore_telemetry::propagation::is_context_header(name.as_str()))
635            .cloned()
636            .collect();
637        for name in stale {
638            headers.remove(name);
639        }
640        return;
641    }
642    // In a system test a call carries the test, where `cx` does not. One
643    // whose test cannot be told panics, rather than go out as no test's.
644    let cx = &crate::testing::outgoing(cx);
645    crate::reqctx::inject(cx, headers);
646    if headers.contains_key(TRACEPARENT) {
647        return;
648    }
649    let span = cx.span();
650    let sc = span.span_context();
651    if !sc.is_valid() {
652        return;
653    }
654    if let Ok(value) = HeaderValue::from_str(&sc.to_traceparent()) {
655        headers.insert(TRACEPARENT, value);
656    }
657    // A tracestate the request carried belongs to another trace's
658    // traceparent: the span's own, with Encore's mark, replaces it.
659    headers.remove(TRACESTATE);
660    let state = sc.trace_state().header();
661    if !state.is_empty() {
662        if let Ok(value) = HeaderValue::from_str(&state) {
663            headers.insert(TRACESTATE, value);
664        }
665    }
666}
667
668#[cfg(test)]
669mod tests {
670    use super::*;
671
672    #[test]
673    fn absolute_urls_are_told_from_paths() {
674        for url in ["http://x/y", "https://x", "h2c+x://y"] {
675            assert!(has_scheme(url), "{url}");
676        }
677        for path in ["/x", "x", "x/y:z", "", "1a:b", "/a:b"] {
678            assert!(!has_scheme(path), "{path}");
679        }
680    }
681
682    #[test]
683    fn origins_have_the_schemes_default_port() {
684        let url = |s: &str| origin_of(&reqwest::Url::parse(s).unwrap());
685        let uri = |s: &str| origin_of_uri(&s.parse().unwrap());
686        assert_eq!(url("http://LocalHost/x"), url("http://localhost:80/y"));
687        assert_eq!(url("https://egress"), uri("HTTPS://egress:443/a"));
688        assert_eq!(url("http://[::1]:9000/a"), uri("http://[::1]:9000"));
689        assert_ne!(url("http://localhost:4000"), url("http://localhost:4001"));
690        assert_eq!(uri("/package.Service/Method"), None);
691    }
692}