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 let core = crate::runtime::core();
483 let mut builder = reqwest::Client::builder()
484 // The core's TLS, as its own HTTP clients have: the system's
485 // roots, which honour `SSL_CERT_FILE`, as the gRPC clients'.
486 .tls_backend_preconfigured(encore_sdk_core::tls::http_client_config())
487 .redirect(reqwest::redirect::Policy::none());
488 // A system test's process has a Tokio runtime for each test, and one
489 // for each fixture it builds, which ends with it. A connection is
490 // driven by the runtime it was opened in, so one kept for the next
491 // call would be dead by the time another test took it up: there
492 // none is kept.
493 if core.system_test().is_some() {
494 builder = builder.pool_max_idle_per_host(0);
495 }
496 builder
497 .build()
498 .expect("encore: building the HTTP client for service calls")
499 })
500}
501
502/// Tower [`Layer`](tower_layer::Layer) that propagates the active trace and
503/// Request Context on outgoing requests to application services (and strips
504/// Request Context headers for all other origins).
505///
506/// Use this with `hyper-util`, `tonic` channels, or any Tower HTTP client:
507///
508/// ```ignore
509/// use encore::services;
510///
511/// let base = services::base_url("search");
512/// let channel = tonic::transport::Endpoint::from_static(base).connect_lazy();
513/// let search = SearchClient::with_origin(
514/// tower::ServiceBuilder::new().layer(services::PropagateLayer).service(channel),
515/// base.parse()?,
516/// );
517/// ```
518///
519/// A request is treated as targeting an application service if its URI matches
520/// the origin of a URL returned by [`base_url`] (requests without an explicit
521/// origin, such as a `tonic` client not constructed with `with_origin`, are
522/// not). This layer does not follow redirects itself; place redirect middleware
523/// outside it so each redirected request is prepared individually.
524#[derive(Debug, Clone, Copy, Default)]
525pub struct PropagateLayer;
526
527impl<S> tower_layer::Layer<S> for PropagateLayer {
528 type Service = Propagate<S>;
529
530 fn layer(&self, inner: S) -> Propagate<S> {
531 Propagate { inner }
532 }
533}
534
535/// Tower service produced by [`PropagateLayer`].
536#[derive(Debug, Clone)]
537pub struct Propagate<S> {
538 inner: S,
539}
540
541impl<S, B> tower_service::Service<http::Request<B>> for Propagate<S>
542where
543 S: tower_service::Service<http::Request<B>>,
544{
545 type Response = S::Response;
546 type Error = S::Error;
547 type Future = S::Future;
548
549 fn poll_ready(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<(), S::Error>> {
550 self.inner.poll_ready(cx)
551 }
552
553 fn call(&mut self, mut request: http::Request<B>) -> S::Future {
554 let origin = origin_of_uri(request.uri());
555 prepare(&Context::current(), origin.as_ref(), request.headers_mut());
556 self.inner.call(request)
557 }
558}
559
560/// A URL's scheme, host and port, with the scheme's default port when it
561/// has none.
562#[derive(Debug, Clone, PartialEq, Eq, Hash)]
563struct Origin {
564 scheme: String,
565 host: String,
566 port: Option<u16>,
567}
568
569fn origin_of(url: &reqwest::Url) -> Option<Origin> {
570 Some(Origin {
571 scheme: url.scheme().to_ascii_lowercase(),
572 host: url.host_str()?.to_ascii_lowercase(),
573 port: url.port_or_known_default(),
574 })
575}
576
577fn origin_of_uri(uri: &http::Uri) -> Option<Origin> {
578 let scheme = uri.scheme_str()?.to_ascii_lowercase();
579 let port = uri.port_u16().or(match scheme.as_str() {
580 "http" => Some(80),
581 "https" => Some(443),
582 _ => None,
583 });
584 Some(Origin {
585 host: uri.host()?.to_ascii_lowercase(),
586 scheme,
587 port,
588 })
589}
590
591/// The origins of the base URLs [`base_url`] has returned: where the app's
592/// services are reached. Every service URL is the egress endpoint's, or
593/// locally the run proxy's, plus the service's path; nothing else is served
594/// at either.
595static ORIGINS: RwLock<Option<HashSet<Origin>>> = RwLock::new(None);
596
597/// Records the origin of `base`, a service's base URL.
598fn register(base: &str) {
599 let Some(origin) = reqwest::Url::parse(base).ok().and_then(|u| origin_of(&u)) else {
600 return;
601 };
602 if is_service(Some(&origin)) {
603 return;
604 }
605 ORIGINS
606 .write()
607 .unwrap_or_else(|e| e.into_inner())
608 .get_or_insert_with(HashSet::new)
609 .insert(origin);
610}
611
612/// Whether `origin` is one of the app's services'.
613fn is_service(origin: Option<&Origin>) -> bool {
614 origin.is_some_and(|origin| {
615 ORIGINS
616 .read()
617 .unwrap_or_else(|e| e.into_inner())
618 .as_ref()
619 .is_some_and(|o| o.contains(origin))
620 })
621}
622
623/// Whether `cx` holds a trace or Request Context to send.
624pub(crate) fn carries_context(cx: &Context) -> bool {
625 cx.span().span_context().is_valid() || !encore_sdk_core::reqctx::Values::of(cx).is_empty()
626}
627
628const TRACEPARENT: HeaderName = HeaderName::from_static("traceparent");
629const TRACESTATE: HeaderName = HeaderName::from_static("tracestate");
630
631/// Sets the trace and Request Context of `cx` on a request to `origin`:
632/// drops the Request Context headers it carried, then, when it is for one of
633/// the app's services, sets the context's fields and, unless it carries one,
634/// the W3C trace context of its span, whose `tracestate` carries Encore's
635/// mark. Encore's egress records the call's span.
636fn prepare(cx: &Context, origin: Option<&Origin>, headers: &mut HeaderMap) {
637 if !is_service(origin) {
638 let stale: Vec<HeaderName> = headers
639 .keys()
640 .filter(|name| encore_telemetry::propagation::is_context_header(name.as_str()))
641 .cloned()
642 .collect();
643 for name in stale {
644 headers.remove(name);
645 }
646 return;
647 }
648 // In a system test a call carries the test, where `cx` does not. One
649 // whose test cannot be told panics, rather than go out as no test's.
650 let cx = &crate::testing::outgoing(cx);
651 crate::reqctx::inject(cx, headers);
652 if headers.contains_key(TRACEPARENT) {
653 return;
654 }
655 let span = cx.span();
656 let sc = span.span_context();
657 if !sc.is_valid() {
658 return;
659 }
660 if let Ok(value) = HeaderValue::from_str(&sc.to_traceparent()) {
661 headers.insert(TRACEPARENT, value);
662 }
663 // A tracestate the request carried belongs to another trace's
664 // traceparent: the span's own, with Encore's mark, replaces it.
665 headers.remove(TRACESTATE);
666 let state = sc.trace_state().header();
667 if !state.is_empty() {
668 if let Ok(value) = HeaderValue::from_str(&state) {
669 headers.insert(TRACESTATE, value);
670 }
671 }
672}
673
674#[cfg(test)]
675mod tests {
676 use super::*;
677
678 #[test]
679 fn absolute_urls_are_told_from_paths() {
680 for url in ["http://x/y", "https://x", "h2c+x://y"] {
681 assert!(has_scheme(url), "{url}");
682 }
683 for path in ["/x", "x", "x/y:z", "", "1a:b", "/a:b"] {
684 assert!(!has_scheme(path), "{path}");
685 }
686 }
687
688 #[test]
689 fn origins_have_the_schemes_default_port() {
690 let url = |s: &str| origin_of(&reqwest::Url::parse(s).unwrap());
691 let uri = |s: &str| origin_of_uri(&s.parse().unwrap());
692 assert_eq!(url("http://LocalHost/x"), url("http://localhost:80/y"));
693 assert_eq!(url("https://egress"), uri("HTTPS://egress:443/a"));
694 assert_eq!(url("http://[::1]:9000/a"), uri("http://[::1]:9000"));
695 assert_ne!(url("http://localhost:4000"), url("http://localhost:4001"));
696 assert_eq!(uri("/package.Service/Method"), None);
697 }
698}