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
93//! service. They speak gRPC over HTTP/2, through tonic, where Go's,
94//! TypeScript's and Python's speak the Connect protocol, which works over
95//! HTTP/1.1 too. A client holds only its settings, so one made for a single
96//! call costs nothing to make, and there is nothing to close.
97//!
98//! # Tests
99//!
100//! No service runs under `encore test`. Every service still has a base URL
101//! there, so a client can be made as usual, but a call to it is answered with
102//! `501 Not Implemented` and an error saying which service and path the test
103//! called: mock the call in the test instead.
104
105use std::collections::HashSet;
106use std::future::Future;
107use std::sync::{OnceLock, RwLock};
108use std::task::{Context as TaskContext, Poll};
109use std::time::Duration;
110
111use encore_sdk_core::telemetry::SpanContextExt;
112use http::header::{
113    HeaderName, HeaderValue, AUTHORIZATION, CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_LENGTH,
114    CONTENT_LOCATION, CONTENT_TYPE, COOKIE, LOCATION, PROXY_AUTHORIZATION, WWW_AUTHENTICATE,
115};
116use http::{HeaderMap, Method, StatusCode};
117use serde::Serialize;
118
119use crate::opentelemetry::trace::TraceContextExt;
120use crate::opentelemetry::Context;
121
122/// The reqwest a [`Client`] is made with, for the types its requests take
123/// and its responses are.
124pub use reqwest;
125
126#[doc(hidden)]
127pub mod clients;
128
129pub use clients::{
130    BidiStreaming, CallError, ClientStreaming, ServerStreaming, Stream, Streaming, Unary,
131    UnlessNotFound,
132};
133
134/// The base URL the calling service reaches `service` at, for
135/// service-to-service calls, without a trailing slash: a call's path goes
136/// after it, `{base}/users/42`.
137///
138/// # Panics
139///
140/// If the runtime has no address for `service`: the app has no service of
141/// that name, which Encore's parser reports, or this process was started
142/// without the app's service discovery, as a plain `cargo test` is.
143pub fn base_url(service: &str) -> &'static str {
144    lookup(service).unwrap_or_else(|| panic!("{}", unknown_service(service)))
145}
146
147/// The base URL of `service`, as [`base_url`] returns it, and `None` where
148/// that panics.
149fn lookup(service: &str) -> Option<&'static str> {
150    let url = crate::runtime::core()
151        .runtime_config()
152        .services
153        .get(service)?
154        .trim_end_matches('/');
155    register(url);
156    Some(url)
157}
158
159/// What a lookup of a service the runtime knows no address for says.
160pub(crate) fn unknown_service(service: &str) -> String {
161    format!("encore: no base URL is known for service {service:?}")
162}
163
164/// A client for `service`, for service-to-service calls: its requests take
165/// the service's paths, and carry the trace and Request Context of the
166/// context they are sent in.
167///
168/// It is `const`, so it can be a `static`, and looks the service up when it
169/// is first used. Like [`base_url`], it makes the calling service depend on
170/// `service`, so the name must be a string literal and the call made
171/// directly, in a service.
172///
173/// ```ignore
174/// static ORDERS: encore::services::Client = encore::services::client("orders");
175/// ```
176pub const fn client(service: &'static str) -> Client {
177    Client {
178        service,
179        base: OnceLock::new(),
180    }
181}
182
183/// A client for one of the app's services, made with [`client`].
184#[derive(Debug)]
185pub struct Client {
186    service: &'static str,
187    base: OnceLock<&'static str>,
188}
189
190impl Client {
191    /// The service's base URL, without a trailing slash, as [`base_url`]
192    /// returns it.
193    ///
194    /// # Panics
195    ///
196    /// As [`base_url`] does.
197    pub fn base_url(&self) -> &'static str {
198        self.try_base_url()
199            .unwrap_or_else(|| panic!("{}", unknown_service(self.service)))
200    }
201
202    /// The service's base URL, as [`Client::base_url`] returns it, and `None`
203    /// where that panics.
204    pub(crate) fn try_base_url(&self) -> Option<&'static str> {
205        if let Some(base) = self.base.get() {
206            return Some(base);
207        }
208        let base = lookup(self.service)?;
209        Some(self.base.get_or_init(|| base))
210    }
211
212    /// The service's name.
213    pub(crate) fn name(&self) -> &'static str {
214        self.service
215    }
216
217    /// A `GET` request for `path`. See [`Client::request`].
218    pub fn get(&self, path: &str) -> RequestBuilder {
219        self.request(Method::GET, path)
220    }
221
222    /// A `POST` request for `path`. See [`Client::request`].
223    pub fn post(&self, path: &str) -> RequestBuilder {
224        self.request(Method::POST, path)
225    }
226
227    /// A `PUT` request for `path`. See [`Client::request`].
228    pub fn put(&self, path: &str) -> RequestBuilder {
229        self.request(Method::PUT, path)
230    }
231
232    /// A `PATCH` request for `path`. See [`Client::request`].
233    pub fn patch(&self, path: &str) -> RequestBuilder {
234        self.request(Method::PATCH, path)
235    }
236
237    /// A `DELETE` request for `path`. See [`Client::request`].
238    pub fn delete(&self, path: &str) -> RequestBuilder {
239        self.request(Method::DELETE, path)
240    }
241
242    /// A `HEAD` request for `path`. See [`Client::request`].
243    pub fn head(&self, path: &str) -> RequestBuilder {
244        self.request(Method::HEAD, path)
245    }
246
247    /// A request for `path`, which is the service's: it is joined to the base
248    /// URL with a single `/`, so `/invoices` and `invoices` are the same
249    /// request. An absolute URL is used as it is.
250    ///
251    /// # Panics
252    ///
253    /// As [`base_url`] does.
254    pub fn request(&self, method: Method, path: &str) -> RequestBuilder {
255        // Looked up for an absolute URL too: the lookup is what records the
256        // service's origin, and what fails for an unknown service.
257        let base = self.base_url();
258        let url = if has_scheme(path) {
259            path.to_string()
260        } else {
261            format!("{base}/{}", path.trim_start_matches('/'))
262        };
263        request_to(method, url)
264    }
265}
266
267/// A request for absolute `url`, sent as a [`Client`]'s are, for one that
268/// has looked its service up already, or tried to.
269pub(crate) fn request_to(method: Method, url: String) -> RequestBuilder {
270    RequestBuilder {
271        inner: shared().request(method, url),
272    }
273}
274
275/// Whether `path` is an absolute URL: it starts with a scheme.
276fn has_scheme(path: &str) -> bool {
277    let Some((scheme, _)) = path.split_once(':') else {
278        return false;
279    };
280    let mut chars = scheme.chars();
281    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
282        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
283}
284
285/// A request a [`Client`] sends: reqwest's builder, whose
286/// [`send`](RequestBuilder::send) carries the call's context.
287#[derive(Debug)]
288#[must_use = "a request is sent only by `send`"]
289pub struct RequestBuilder {
290    inner: reqwest::RequestBuilder,
291}
292
293impl RequestBuilder {
294    /// Adds a header.
295    pub fn header<K, V>(self, key: K, value: V) -> Self
296    where
297        HeaderName: TryFrom<K>,
298        <HeaderName as TryFrom<K>>::Error: Into<http::Error>,
299        HeaderValue: TryFrom<V>,
300        <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
301    {
302        self.map(|b| b.header(key, value))
303    }
304
305    /// Adds headers.
306    pub fn headers(self, headers: HeaderMap) -> Self {
307        self.map(|b| b.headers(headers))
308    }
309
310    /// Adds query parameters, as reqwest's
311    /// [`query`](reqwest::RequestBuilder::query) does.
312    pub fn query<T: Serialize + ?Sized>(self, query: &T) -> Self {
313        self.map(|b| b.query(query))
314    }
315
316    /// Sends `json` as the body, as JSON.
317    pub fn json<T: Serialize + ?Sized>(self, json: &T) -> Self {
318        self.map(|b| b.json(json))
319    }
320
321    /// Sends `form` as the body, URL-encoded.
322    pub fn form<T: Serialize + ?Sized>(self, form: &T) -> Self {
323        self.map(|b| b.form(form))
324    }
325
326    /// Sends `body` as the body.
327    pub fn body<T: Into<reqwest::Body>>(self, body: T) -> Self {
328        self.map(|b| b.body(body))
329    }
330
331    /// Fails each request it sends, the first and each redirect, that is not
332    /// answered within `timeout`.
333    pub fn timeout(self, timeout: Duration) -> Self {
334        self.map(|b| b.timeout(timeout))
335    }
336
337    /// Adds a bearer token `Authorization` header.
338    pub fn bearer_auth<T: std::fmt::Display>(self, token: T) -> Self {
339        self.map(|b| b.bearer_auth(token))
340    }
341
342    /// Adds a basic `Authorization` header.
343    pub fn basic_auth<U: std::fmt::Display, P: std::fmt::Display>(
344        self,
345        username: U,
346        password: Option<P>,
347    ) -> Self {
348        self.map(|b| b.basic_auth(username, password))
349    }
350
351    /// Changes the request as reqwest's builder does, for what this one
352    /// does not offer.
353    pub fn map(self, f: impl FnOnce(reqwest::RequestBuilder) -> reqwest::RequestBuilder) -> Self {
354        RequestBuilder {
355            inner: f(self.inner),
356        }
357    }
358
359    /// Sends the request, with the Request Context and trace of its context
360    /// when it is for one of the app's services, without any Request Context
361    /// otherwise.
362    ///
363    /// Its context is the one it is first polled in, as
364    /// `.send().with_context(cx)` sets it, unless that one holds neither a
365    /// trace nor Request Context: then the one `send` is called in, so a
366    /// future handed to `tokio::spawn` still carries the call's.
367    ///
368    /// It follows up to 10 redirects, each sent with the context its own URL
369    /// is due, so a redirect away from the app's services carries no Request
370    /// Context. As fetch does, a 301 or 302 turns only a `POST` into a `GET`,
371    /// and a 303 anything but a `HEAD`; a 307 or 308 keeps the method and
372    /// body. Past 10 redirects, or when a redirect would need a streamed body
373    /// sent again, the redirect itself is the response.
374    pub fn send(self) -> impl Future<Output = Result<reqwest::Response, reqwest::Error>> {
375        let called_in = Context::current();
376        let request = self.inner.build();
377        async move {
378            let polled_in = Context::current();
379            let cx = if carries_context(&polled_in) {
380                polled_in
381            } else {
382                called_in
383            };
384            follow_redirects(&cx, request?).await
385        }
386    }
387}
388
389/// How many redirects a request follows, as reqwest's default policy.
390const MAX_REDIRECTS: usize = 10;
391
392/// The headers that describe a body, which a redirect dropping it drops too,
393/// as fetch does.
394const BODY_HEADERS: [HeaderName; 5] = [
395    CONTENT_TYPE,
396    CONTENT_LENGTH,
397    CONTENT_ENCODING,
398    CONTENT_LANGUAGE,
399    CONTENT_LOCATION,
400];
401
402/// The headers a redirect to another origin drops, as reqwest's does.
403const CREDENTIAL_HEADERS: [HeaderName; 4] =
404    [AUTHORIZATION, COOKIE, PROXY_AUTHORIZATION, WWW_AUTHENTICATE];
405
406/// Sends `request`, and the requests the redirects it is answered with ask
407/// for, each prepared for its own URL in `cx`.
408async fn follow_redirects(
409    cx: &Context,
410    mut request: reqwest::Request,
411) -> Result<reqwest::Response, reqwest::Error> {
412    let client = shared();
413    let mut redirects = 0;
414    loop {
415        let origin = origin_of(request.url());
416        prepare(cx, origin.as_ref(), request.headers_mut());
417        let again = request.try_clone();
418        let method = request.method().clone();
419        let headers = request.headers().clone();
420        let timeout = request.timeout().copied();
421        let response = client.execute(request).await?;
422        let location = response
423            .headers()
424            .get(LOCATION)
425            .and_then(|l| l.to_str().ok())
426            .and_then(|l| response.url().join(l).ok());
427        let Some(location) = location else {
428            return Ok(response);
429        };
430        if redirects == MAX_REDIRECTS {
431            return Ok(response);
432        }
433        // As fetch does: a 301 or 302 turns only a POST into a GET, and a
434        // 303 anything but a HEAD; the others keep the method and body.
435        let to_get = match response.status() {
436            StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND => method == Method::POST,
437            StatusCode::SEE_OTHER => method != Method::GET && method != Method::HEAD,
438            StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT => false,
439            _ => return Ok(response),
440        };
441        let mut next = if to_get {
442            // Without the body, so a streamed one is no obstacle.
443            let mut next = reqwest::Request::new(Method::GET, location.clone());
444            *next.headers_mut() = headers;
445            *next.timeout_mut() = timeout;
446            for name in BODY_HEADERS {
447                next.headers_mut().remove(name);
448            }
449            next
450        } else {
451            match again {
452                Some(next) => next,
453                // A streamed body cannot be sent again.
454                None => return Ok(response),
455            }
456        };
457        if origin_of(&location) != origin {
458            for name in CREDENTIAL_HEADERS {
459                next.headers_mut().remove(name);
460            }
461        }
462        *next.url_mut() = location;
463        request = next;
464        redirects += 1;
465    }
466}
467
468/// The reqwest client every [`Client`] sends with: one, so they share its
469/// connections. It follows no redirects itself: [`follow_redirects`] does,
470/// preparing each.
471fn shared() -> &'static reqwest::Client {
472    static SHARED: OnceLock<reqwest::Client> = OnceLock::new();
473    SHARED.get_or_init(|| {
474        // The core installs the process's TLS provider, which the client uses.
475        let core = crate::runtime::core();
476        let mut builder = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none());
477        // A system test's process has a Tokio runtime for each test, and one
478        // for each fixture it builds, which ends with it. A connection is
479        // driven by the runtime it was opened in, so one kept for the next
480        // call would be dead by the time another test took it up: there
481        // none is kept.
482        if core.system_test().is_some() {
483            builder = builder.pool_max_idle_per_host(0);
484        }
485        builder
486            .build()
487            .expect("encore: building the HTTP client for service calls")
488    })
489}
490
491/// A tower [`Layer`](tower_layer::Layer) whose services send the trace and
492/// Request Context of the context a request is sent in with each request
493/// for one of the app's services, and no Request Context with any other: for
494/// hyper-util's client, a tonic channel, or any tower HTTP client.
495///
496/// ```ignore
497/// use encore::services;
498///
499/// let base = services::base_url("search");
500/// let channel = tonic::transport::Endpoint::from_static(base).connect_lazy();
501/// let search = SearchClient::with_origin(
502///     tower::ServiceBuilder::new().layer(services::PropagateLayer).service(channel),
503///     base.parse()?,
504/// );
505/// ```
506///
507/// A request is for the app's services when its URI is at the origin of a
508/// base URL [`base_url`] returned. A request whose URI has none, as a tonic
509/// client's without `with_origin`, is not. It follows no redirects; a layer
510/// outside it that does has each one prepared.
511#[derive(Debug, Clone, Copy, Default)]
512pub struct PropagateLayer;
513
514impl<S> tower_layer::Layer<S> for PropagateLayer {
515    type Service = Propagate<S>;
516
517    fn layer(&self, inner: S) -> Propagate<S> {
518        Propagate { inner }
519    }
520}
521
522/// The service of a [`PropagateLayer`].
523#[derive(Debug, Clone)]
524pub struct Propagate<S> {
525    inner: S,
526}
527
528impl<S, B> tower_service::Service<http::Request<B>> for Propagate<S>
529where
530    S: tower_service::Service<http::Request<B>>,
531{
532    type Response = S::Response;
533    type Error = S::Error;
534    type Future = S::Future;
535
536    fn poll_ready(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<(), S::Error>> {
537        self.inner.poll_ready(cx)
538    }
539
540    fn call(&mut self, mut request: http::Request<B>) -> S::Future {
541        let origin = origin_of_uri(request.uri());
542        prepare(&Context::current(), origin.as_ref(), request.headers_mut());
543        self.inner.call(request)
544    }
545}
546
547/// A URL's scheme, host and port, with the scheme's default port when it
548/// has none.
549#[derive(Debug, Clone, PartialEq, Eq, Hash)]
550struct Origin {
551    scheme: String,
552    host: String,
553    port: Option<u16>,
554}
555
556fn origin_of(url: &reqwest::Url) -> Option<Origin> {
557    Some(Origin {
558        scheme: url.scheme().to_ascii_lowercase(),
559        host: url.host_str()?.to_ascii_lowercase(),
560        port: url.port_or_known_default(),
561    })
562}
563
564fn origin_of_uri(uri: &http::Uri) -> Option<Origin> {
565    let scheme = uri.scheme_str()?.to_ascii_lowercase();
566    let port = uri.port_u16().or(match scheme.as_str() {
567        "http" => Some(80),
568        "https" => Some(443),
569        _ => None,
570    });
571    Some(Origin {
572        host: uri.host()?.to_ascii_lowercase(),
573        scheme,
574        port,
575    })
576}
577
578/// The origins of the base URLs [`base_url`] has returned: where the app's
579/// services are reached. Every service URL is the egress endpoint's, or
580/// locally the run proxy's, plus the service's path; nothing else is served
581/// at either.
582static ORIGINS: RwLock<Option<HashSet<Origin>>> = RwLock::new(None);
583
584/// Records the origin of `base`, a service's base URL.
585fn register(base: &str) {
586    let Some(origin) = reqwest::Url::parse(base).ok().and_then(|u| origin_of(&u)) else {
587        return;
588    };
589    if is_service(Some(&origin)) {
590        return;
591    }
592    ORIGINS
593        .write()
594        .unwrap_or_else(|e| e.into_inner())
595        .get_or_insert_with(HashSet::new)
596        .insert(origin);
597}
598
599/// Whether `origin` is one of the app's services'.
600fn is_service(origin: Option<&Origin>) -> bool {
601    origin.is_some_and(|origin| {
602        ORIGINS
603            .read()
604            .unwrap_or_else(|e| e.into_inner())
605            .as_ref()
606            .is_some_and(|o| o.contains(origin))
607    })
608}
609
610/// Whether `cx` holds a trace or Request Context to send.
611pub(crate) fn carries_context(cx: &Context) -> bool {
612    cx.span().span_context().is_valid() || !encore_sdk_core::reqctx::Values::of(cx).is_empty()
613}
614
615const TRACEPARENT: HeaderName = HeaderName::from_static("traceparent");
616const TRACESTATE: HeaderName = HeaderName::from_static("tracestate");
617
618/// Sets the trace and Request Context of `cx` on a request to `origin`:
619/// drops the Request Context headers it carried, then, when it is for one of
620/// the app's services, sets the context's fields and, unless it carries one,
621/// the W3C trace context of its span, whose `tracestate` carries Encore's
622/// mark. Encore's egress records the call's span.
623fn prepare(cx: &Context, origin: Option<&Origin>, headers: &mut HeaderMap) {
624    if !is_service(origin) {
625        let stale: Vec<HeaderName> = headers
626            .keys()
627            .filter(|name| encore_telemetry::propagation::is_context_header(name.as_str()))
628            .cloned()
629            .collect();
630        for name in stale {
631            headers.remove(name);
632        }
633        return;
634    }
635    // In a system test a call carries the test, where `cx` does not.
636    let cx = &crate::testing::outgoing(cx);
637    crate::reqctx::inject(cx, headers);
638    if headers.contains_key(TRACEPARENT) {
639        return;
640    }
641    let span = cx.span();
642    let sc = span.span_context();
643    if !sc.is_valid() {
644        return;
645    }
646    if let Ok(value) = HeaderValue::from_str(&sc.to_traceparent()) {
647        headers.insert(TRACEPARENT, value);
648    }
649    // A tracestate the request carried belongs to another trace's
650    // traceparent: the span's own, with Encore's mark, replaces it.
651    headers.remove(TRACESTATE);
652    let state = sc.trace_state().header();
653    if !state.is_empty() {
654        if let Ok(value) = HeaderValue::from_str(&state) {
655            headers.insert(TRACESTATE, value);
656        }
657    }
658}
659
660#[cfg(test)]
661mod tests {
662    use super::*;
663
664    #[test]
665    fn absolute_urls_are_told_from_paths() {
666        for url in ["http://x/y", "https://x", "h2c+x://y"] {
667            assert!(has_scheme(url), "{url}");
668        }
669        for path in ["/x", "x", "x/y:z", "", "1a:b", "/a:b"] {
670            assert!(!has_scheme(path), "{path}");
671        }
672    }
673
674    #[test]
675    fn origins_have_the_schemes_default_port() {
676        let url = |s: &str| origin_of(&reqwest::Url::parse(s).unwrap());
677        let uri = |s: &str| origin_of_uri(&s.parse().unwrap());
678        assert_eq!(url("http://LocalHost/x"), url("http://localhost:80/y"));
679        assert_eq!(url("https://egress"), uri("HTTPS://egress:443/a"));
680        assert_eq!(url("http://[::1]:9000/a"), uri("http://[::1]:9000"));
681        assert_ne!(url("http://localhost:4000"), url("http://localhost:4001"));
682        assert_eq!(uri("/package.Service/Method"), None);
683    }
684}