encore-dev 2.0.0-beta.17

Rust SDK for Encore applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! Calling other services in the application.
//!
//! A [`Client`] targets a single service. Because [`client`] is `const`, you
//! can declare clients as module-level `static`s:
//!
//! ```ignore
//! use encore::services;
//!
//! static BILLING: services::Client = services::client("billing");
//!
//! async fn invoices() -> anyhow::Result<Vec<Invoice>> {
//!     Ok(BILLING.get("/invoices").send().await?.error_for_status()?.json().await?)
//! }
//! ```
//!
//! Outgoing requests to application services automatically propagate the active
//! trace context and Request Context ([`crate::reqctx`]), so downstream
//! services continue the same trace and request metadata. Requests to external
//! origins never include Request Context headers. All [`Client`] instances
//! share a single connection pool, so creating a client on demand is as cheap
//! as using a `static`.
//!
//! For Tower-based HTTP clients (such as `hyper-util` or a `tonic` channel),
//! use [`PropagateLayer`] for the same propagation behavior.
//!
//! Calling [`base_url`] or [`client`] declares a dependency on the target
//! service. Because Encore parses dependencies statically from source code,
//! pass the service name as a string literal, call the function directly
//! (rather than through a function pointer), and make the call inside a
//! service.
//!
//! # Generated clients
//!
//! When a service lists another service under `clients` in its
//! `encore.service.json`, Encore generates typed clients in
//! `encore_gen::clients` — one module per service, containing one module per
//! declared API. Each operation is a top-level function returning a call builder
//! that executes when `.await`ed:
//!
//! ```ignore
//! mod encore_gen;
//! use encore_gen::clients::catalog;
//!
//! let product = catalog::openapi::get_product("xyz").await?;
//! let users = catalog::openapi::list_users().limit(10).await?;
//! ```
//!
//! Failed calls return [`CallError`] regardless of API protocol, and `?`
//! converts it into an [`encore::Error`](crate::Error) with the same error
//! code:
//!
//! ```ignore
//! let product = match catalog::openapi::get_product("xyz").await {
//!     Ok(product) => Some(product),
//!     Err(err) if err.code == encore::ErrCode::NotFound => None,
//!     Err(err) => return Err(err.into()),
//! };
//! ```
//!
//! Use [`UnlessNotFound`] to turn a `NotFound` error into `Ok(None)`:
//!
//! ```ignore
//! use encore::services::UnlessNotFound;
//!
//! let product = catalog::openapi::get_product("xyz").await.unless_not_found()?;
//! ```
//!
//! For APIs that require a `Future` directly (such as `tokio::spawn` or
//! `join_all`), call `.into_future()`. The resulting future captures the
//! caller's trace and Request Context just like an awaited call:
//!
//! ```ignore
//! use std::future::IntoFuture;
//!
//! let product = tokio::spawn(catalog::openapi::get_product("xyz").into_future());
//! ```
//!
//! Individual calls can override timeouts and headers, and each API module
//! provides a `Client` for sharing default settings across calls:
//!
//! ```ignore
//! let product = catalog::openapi::get_product("xyz")
//!     .timeout(Duration::from_secs(2))
//!     .await?;
//! let storefront = catalog::storefront::Client::new().header("x-tenant", "a");
//! ```
//!
//! Generated HTTP/OpenAPI/GraphQL clients use the same shared connection pool
//! and context propagation as [`Client`]. Generated gRPC clients ([`Unary`],
//! [`ServerStreaming`], [`ClientStreaming`], and [`BidiStreaming`]) speak gRPC
//! over HTTP/2 via `tonic`, sharing one channel per base URL — using cleartext
//! HTTP/2 (`h2c`) for `http://` URLs and TLS (trusting system roots or
//! `SSL_CERT_FILE`) for `https://` URLs.
//!
//! For gRPC calls, a timeout acts as an end-to-end deadline covering
//! connecting and every message on a stream. Bidirectional streams resolve
//! immediately without waiting for server headers so the server can read an
//! initial client message first. Decoded protobuf messages preserve unknown
//! fields from newer schemas when re-encoded, and gRPC error details are
//! exposed on [`CallError::grpc_details`]. Because a generated `Client` only
//! holds settings, constructing one per call is free and requires no cleanup.
//!
//! # Tests
//!
//! In unit tests under `encore test`, peer services are not started. Every
//! service still has a placeholder base URL so clients can be constructed, but
//! calls return `501 Not Implemented` identifying the service and path; mock
//! downstream calls in unit tests (or use [system tests](crate::testing::system)).

use std::collections::HashSet;
use std::future::Future;
use std::sync::{OnceLock, RwLock};
use std::task::{Context as TaskContext, Poll};
use std::time::Duration;

use encore_sdk_core::telemetry::SpanContextExt;
use http::header::{
    HeaderName, HeaderValue, AUTHORIZATION, CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_LENGTH,
    CONTENT_LOCATION, CONTENT_TYPE, COOKIE, LOCATION, PROXY_AUTHORIZATION, WWW_AUTHENTICATE,
};
use http::{HeaderMap, Method, StatusCode};
use serde::Serialize;

use crate::opentelemetry::trace::TraceContextExt;
use crate::opentelemetry::Context;

/// Re-export of `reqwest` for working with [`Client`] request and response types.
pub use reqwest;

#[doc(hidden)]
pub mod clients;

pub use clients::{
    BidiStreaming, CallError, ClientStreaming, ServerStreaming, Stream, Streaming, Unary,
    UnlessNotFound,
};

/// Returns the base URL for calling `service`, without a trailing slash (so
/// paths can be appended directly, e.g. `{base}/users/42`).
///
/// # Panics
///
/// Panics if the runtime has no base URL configured for `service` — either
/// because no service with that name exists or because the process was started
/// without Encore service discovery (such as a plain `cargo test`).
pub fn base_url(service: &str) -> &'static str {
    lookup(service).unwrap_or_else(|| panic!("{}", unknown_service(service)))
}

/// The base URL of `service`, as [`base_url`] returns it, and `None` where
/// that panics.
fn lookup(service: &str) -> Option<&'static str> {
    let url = crate::runtime::core()
        .runtime_config()
        .services
        .get(service)?
        .trim_end_matches('/');
    register(url);
    Some(url)
}

/// Formats the error message for an unknown or unconfigured service.
pub(crate) fn unknown_service(service: &str) -> String {
    format!("encore: no base URL configured for service {service:?}")
}

/// Creates a [`Client`] for calling `service`.
///
/// Requests accept paths relative to the service's base URL and automatically
/// propagate the active trace and Request Context. This function is `const` so
/// it can initialize a module-level `static`; the service URL is resolved on
/// first use.
///
/// Like [`base_url`], calling `client` records a static dependency on
/// `service`, so pass the service name as a string literal and call `client`
/// directly inside a service.
///
/// ```ignore
/// static ORDERS: encore::services::Client = encore::services::client("orders");
/// ```
pub const fn client(service: &'static str) -> Client {
    Client {
        service,
        base: OnceLock::new(),
    }
}

/// HTTP client for calling another service in the application, created with
/// [`client`].
#[derive(Debug)]
pub struct Client {
    service: &'static str,
    base: OnceLock<&'static str>,
}

impl Client {
    /// Returns the service's base URL without a trailing slash.
    ///
    /// # Panics
    ///
    /// Panics under the same conditions as [`base_url`].
    pub fn base_url(&self) -> &'static str {
        self.try_base_url()
            .unwrap_or_else(|| panic!("{}", unknown_service(self.service)))
    }

    /// The service's base URL, as [`Client::base_url`] returns it, and `None`
    /// where that panics.
    pub(crate) fn try_base_url(&self) -> Option<&'static str> {
        if let Some(base) = self.base.get() {
            return Some(base);
        }
        let base = lookup(self.service)?;
        Some(self.base.get_or_init(|| base))
    }

    /// The service's name.
    pub(crate) fn name(&self) -> &'static str {
        self.service
    }

    /// A `GET` request for `path`. See [`Client::request`].
    pub fn get(&self, path: &str) -> RequestBuilder {
        self.request(Method::GET, path)
    }

    /// A `POST` request for `path`. See [`Client::request`].
    pub fn post(&self, path: &str) -> RequestBuilder {
        self.request(Method::POST, path)
    }

    /// A `PUT` request for `path`. See [`Client::request`].
    pub fn put(&self, path: &str) -> RequestBuilder {
        self.request(Method::PUT, path)
    }

    /// A `PATCH` request for `path`. See [`Client::request`].
    pub fn patch(&self, path: &str) -> RequestBuilder {
        self.request(Method::PATCH, path)
    }

    /// A `DELETE` request for `path`. See [`Client::request`].
    pub fn delete(&self, path: &str) -> RequestBuilder {
        self.request(Method::DELETE, path)
    }

    /// A `HEAD` request for `path`. See [`Client::request`].
    pub fn head(&self, path: &str) -> RequestBuilder {
        self.request(Method::HEAD, path)
    }

    /// Starts a request with `method` and `path`.
    ///
    /// Relative paths are joined to the service's base URL with a single `/`
    /// (so `/invoices` and `invoices` are equivalent). Absolute URLs with a
    /// scheme are used as-is.
    ///
    /// # Panics
    ///
    /// Panics under the same conditions as [`base_url`].
    pub fn request(&self, method: Method, path: &str) -> RequestBuilder {
        // Looked up for an absolute URL too: the lookup is what records the
        // service's origin, and what fails for an unknown service.
        let base = self.base_url();
        let url = if has_scheme(path) {
            path.to_string()
        } else {
            format!("{base}/{}", path.trim_start_matches('/'))
        };
        request_to(method, url)
    }
}

/// A request for absolute `url`, sent as a [`Client`]'s are, for one that
/// has looked its service up already, or tried to.
pub(crate) fn request_to(method: Method, url: String) -> RequestBuilder {
    RequestBuilder {
        inner: shared().request(method, url),
    }
}

/// Whether `path` is an absolute URL: it starts with a scheme.
fn has_scheme(path: &str) -> bool {
    let Some((scheme, _)) = path.split_once(':') else {
        return false;
    };
    let mut chars = scheme.chars();
    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
}

/// Builder for an HTTP request sent by [`Client`], wrapping
/// [`reqwest::RequestBuilder`] with Encore context propagation.
#[derive(Debug)]
#[must_use = "a request is not sent until `.send()` is called"]
pub struct RequestBuilder {
    inner: reqwest::RequestBuilder,
}

impl RequestBuilder {
    /// Adds a header.
    pub fn header<K, V>(self, key: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        <HeaderName as TryFrom<K>>::Error: Into<http::Error>,
        HeaderValue: TryFrom<V>,
        <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
    {
        self.map(|b| b.header(key, value))
    }

    /// Adds headers.
    pub fn headers(self, headers: HeaderMap) -> Self {
        self.map(|b| b.headers(headers))
    }

    /// Adds query parameters, as reqwest's
    /// [`query`](reqwest::RequestBuilder::query) does.
    pub fn query<T: Serialize + ?Sized>(self, query: &T) -> Self {
        self.map(|b| b.query(query))
    }

    /// Sends `json` as the body, as JSON.
    pub fn json<T: Serialize + ?Sized>(self, json: &T) -> Self {
        self.map(|b| b.json(json))
    }

    /// Sends `form` as the body, URL-encoded.
    pub fn form<T: Serialize + ?Sized>(self, form: &T) -> Self {
        self.map(|b| b.form(form))
    }

    /// Sends `body` as the body.
    pub fn body<T: Into<reqwest::Body>>(self, body: T) -> Self {
        self.map(|b| b.body(body))
    }

    /// Sets a per-request timeout applied to the initial request and each
    /// redirect.
    pub fn timeout(self, timeout: Duration) -> Self {
        self.map(|b| b.timeout(timeout))
    }

    /// Adds a bearer token `Authorization` header.
    pub fn bearer_auth<T: std::fmt::Display>(self, token: T) -> Self {
        self.map(|b| b.bearer_auth(token))
    }

    /// Adds a basic `Authorization` header.
    pub fn basic_auth<U: std::fmt::Display, P: std::fmt::Display>(
        self,
        username: U,
        password: Option<P>,
    ) -> Self {
        self.map(|b| b.basic_auth(username, password))
    }

    /// Applies a custom transformation to the underlying
    /// [`reqwest::RequestBuilder`] for options not directly exposed here.
    pub fn map(self, f: impl FnOnce(reqwest::RequestBuilder) -> reqwest::RequestBuilder) -> Self {
        RequestBuilder {
            inner: f(self.inner),
        }
    }

    /// Sends the request, propagating the active trace and Request Context
    /// when targeting an application service (and stripping Request Context
    /// headers otherwise).
    ///
    /// Context is taken from the polling context (such as via
    /// `.send().with_context(cx)`) if it contains a trace or Request Context;
    /// otherwise it falls back to the context active when `send` was called so
    /// spawned futures preserve the caller's context.
    ///
    /// Follows up to 10 redirects, re-evaluating context propagation for each
    /// hop so redirects to external origins never receive Request Context
    /// headers. Following the Fetch specification, 301/302 converts `POST` to
    /// `GET`, 303 converts any method other than `GET`/`HEAD` to `GET`, and
    /// 307/308 preserves the method and body. After 10 redirects, or if a
    /// redirect requires re-sending a streamed body, the redirect response is
    /// returned as-is.
    pub fn send(self) -> impl Future<Output = Result<reqwest::Response, reqwest::Error>> {
        let called_in = Context::current();
        let request = self.inner.build();
        async move {
            let polled_in = Context::current();
            let cx = if carries_context(&polled_in) {
                polled_in
            } else {
                called_in
            };
            follow_redirects(&cx, request?).await
        }
    }
}

/// How many redirects a request follows, as reqwest's default policy.
const MAX_REDIRECTS: usize = 10;

/// The headers that describe a body, which a redirect dropping it drops too,
/// as fetch does.
const BODY_HEADERS: [HeaderName; 5] = [
    CONTENT_TYPE,
    CONTENT_LENGTH,
    CONTENT_ENCODING,
    CONTENT_LANGUAGE,
    CONTENT_LOCATION,
];

/// The headers a redirect to another origin drops, as reqwest's does.
const CREDENTIAL_HEADERS: [HeaderName; 4] =
    [AUTHORIZATION, COOKIE, PROXY_AUTHORIZATION, WWW_AUTHENTICATE];

/// Sends `request`, and the requests the redirects it is answered with ask
/// for, each prepared for its own URL in `cx`.
async fn follow_redirects(
    cx: &Context,
    mut request: reqwest::Request,
) -> Result<reqwest::Response, reqwest::Error> {
    let client = shared();
    let mut redirects = 0;
    loop {
        let origin = origin_of(request.url());
        prepare(cx, origin.as_ref(), request.headers_mut());
        let again = request.try_clone();
        let method = request.method().clone();
        let headers = request.headers().clone();
        let timeout = request.timeout().copied();
        let response = client.execute(request).await?;
        let location = response
            .headers()
            .get(LOCATION)
            .and_then(|l| l.to_str().ok())
            .and_then(|l| response.url().join(l).ok());
        let Some(location) = location else {
            return Ok(response);
        };
        if redirects == MAX_REDIRECTS {
            return Ok(response);
        }
        // As fetch does: a 301 or 302 turns only a POST into a GET, and a
        // 303 anything but a HEAD; the others keep the method and body.
        let to_get = match response.status() {
            StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND => method == Method::POST,
            StatusCode::SEE_OTHER => method != Method::GET && method != Method::HEAD,
            StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT => false,
            _ => return Ok(response),
        };
        let mut next = if to_get {
            // Without the body, so a streamed one is no obstacle.
            let mut next = reqwest::Request::new(Method::GET, location.clone());
            *next.headers_mut() = headers;
            *next.timeout_mut() = timeout;
            for name in BODY_HEADERS {
                next.headers_mut().remove(name);
            }
            next
        } else {
            match again {
                Some(next) => next,
                // A streamed body cannot be sent again.
                None => return Ok(response),
            }
        };
        if origin_of(&location) != origin {
            for name in CREDENTIAL_HEADERS {
                next.headers_mut().remove(name);
            }
        }
        *next.url_mut() = location;
        request = next;
        redirects += 1;
    }
}

/// The reqwest client every [`Client`] sends with: one, so they share its
/// connections. It follows no redirects itself: [`follow_redirects`] does,
/// preparing each.
fn shared() -> &'static reqwest::Client {
    static SHARED: OnceLock<reqwest::Client> = OnceLock::new();
    SHARED.get_or_init(|| {
        // The core installs the process's TLS provider, which the client uses.
        let core = crate::runtime::core();
        let mut builder = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none());
        // A system test's process has a Tokio runtime for each test, and one
        // for each fixture it builds, which ends with it. A connection is
        // driven by the runtime it was opened in, so one kept for the next
        // call would be dead by the time another test took it up: there
        // none is kept.
        if core.system_test().is_some() {
            builder = builder.pool_max_idle_per_host(0);
        }
        builder
            .build()
            .expect("encore: building the HTTP client for service calls")
    })
}

/// Tower [`Layer`](tower_layer::Layer) that propagates the active trace and
/// Request Context on outgoing requests to application services (and strips
/// Request Context headers for all other origins).
///
/// Use this with `hyper-util`, `tonic` channels, or any Tower HTTP client:
///
/// ```ignore
/// use encore::services;
///
/// let base = services::base_url("search");
/// let channel = tonic::transport::Endpoint::from_static(base).connect_lazy();
/// let search = SearchClient::with_origin(
///     tower::ServiceBuilder::new().layer(services::PropagateLayer).service(channel),
///     base.parse()?,
/// );
/// ```
///
/// A request is treated as targeting an application service if its URI matches
/// the origin of a URL returned by [`base_url`] (requests without an explicit
/// origin, such as a `tonic` client not constructed with `with_origin`, are
/// not). This layer does not follow redirects itself; place redirect middleware
/// outside it so each redirected request is prepared individually.
#[derive(Debug, Clone, Copy, Default)]
pub struct PropagateLayer;

impl<S> tower_layer::Layer<S> for PropagateLayer {
    type Service = Propagate<S>;

    fn layer(&self, inner: S) -> Propagate<S> {
        Propagate { inner }
    }
}

/// Tower service produced by [`PropagateLayer`].
#[derive(Debug, Clone)]
pub struct Propagate<S> {
    inner: S,
}

impl<S, B> tower_service::Service<http::Request<B>> for Propagate<S>
where
    S: tower_service::Service<http::Request<B>>,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = S::Future;

    fn poll_ready(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<(), S::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut request: http::Request<B>) -> S::Future {
        let origin = origin_of_uri(request.uri());
        prepare(&Context::current(), origin.as_ref(), request.headers_mut());
        self.inner.call(request)
    }
}

/// A URL's scheme, host and port, with the scheme's default port when it
/// has none.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Origin {
    scheme: String,
    host: String,
    port: Option<u16>,
}

fn origin_of(url: &reqwest::Url) -> Option<Origin> {
    Some(Origin {
        scheme: url.scheme().to_ascii_lowercase(),
        host: url.host_str()?.to_ascii_lowercase(),
        port: url.port_or_known_default(),
    })
}

fn origin_of_uri(uri: &http::Uri) -> Option<Origin> {
    let scheme = uri.scheme_str()?.to_ascii_lowercase();
    let port = uri.port_u16().or(match scheme.as_str() {
        "http" => Some(80),
        "https" => Some(443),
        _ => None,
    });
    Some(Origin {
        host: uri.host()?.to_ascii_lowercase(),
        scheme,
        port,
    })
}

/// The origins of the base URLs [`base_url`] has returned: where the app's
/// services are reached. Every service URL is the egress endpoint's, or
/// locally the run proxy's, plus the service's path; nothing else is served
/// at either.
static ORIGINS: RwLock<Option<HashSet<Origin>>> = RwLock::new(None);

/// Records the origin of `base`, a service's base URL.
fn register(base: &str) {
    let Some(origin) = reqwest::Url::parse(base).ok().and_then(|u| origin_of(&u)) else {
        return;
    };
    if is_service(Some(&origin)) {
        return;
    }
    ORIGINS
        .write()
        .unwrap_or_else(|e| e.into_inner())
        .get_or_insert_with(HashSet::new)
        .insert(origin);
}

/// Whether `origin` is one of the app's services'.
fn is_service(origin: Option<&Origin>) -> bool {
    origin.is_some_and(|origin| {
        ORIGINS
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .as_ref()
            .is_some_and(|o| o.contains(origin))
    })
}

/// Whether `cx` holds a trace or Request Context to send.
pub(crate) fn carries_context(cx: &Context) -> bool {
    cx.span().span_context().is_valid() || !encore_sdk_core::reqctx::Values::of(cx).is_empty()
}

const TRACEPARENT: HeaderName = HeaderName::from_static("traceparent");
const TRACESTATE: HeaderName = HeaderName::from_static("tracestate");

/// Sets the trace and Request Context of `cx` on a request to `origin`:
/// drops the Request Context headers it carried, then, when it is for one of
/// the app's services, sets the context's fields and, unless it carries one,
/// the W3C trace context of its span, whose `tracestate` carries Encore's
/// mark. Encore's egress records the call's span.
fn prepare(cx: &Context, origin: Option<&Origin>, headers: &mut HeaderMap) {
    if !is_service(origin) {
        let stale: Vec<HeaderName> = headers
            .keys()
            .filter(|name| encore_telemetry::propagation::is_context_header(name.as_str()))
            .cloned()
            .collect();
        for name in stale {
            headers.remove(name);
        }
        return;
    }
    // In a system test a call carries the test, where `cx` does not. One
    // whose test cannot be told panics, rather than go out as no test's.
    let cx = &crate::testing::outgoing(cx);
    crate::reqctx::inject(cx, headers);
    if headers.contains_key(TRACEPARENT) {
        return;
    }
    let span = cx.span();
    let sc = span.span_context();
    if !sc.is_valid() {
        return;
    }
    if let Ok(value) = HeaderValue::from_str(&sc.to_traceparent()) {
        headers.insert(TRACEPARENT, value);
    }
    // A tracestate the request carried belongs to another trace's
    // traceparent: the span's own, with Encore's mark, replaces it.
    headers.remove(TRACESTATE);
    let state = sc.trace_state().header();
    if !state.is_empty() {
        if let Ok(value) = HeaderValue::from_str(&state) {
            headers.insert(TRACESTATE, value);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn absolute_urls_are_told_from_paths() {
        for url in ["http://x/y", "https://x", "h2c+x://y"] {
            assert!(has_scheme(url), "{url}");
        }
        for path in ["/x", "x", "x/y:z", "", "1a:b", "/a:b"] {
            assert!(!has_scheme(path), "{path}");
        }
    }

    #[test]
    fn origins_have_the_schemes_default_port() {
        let url = |s: &str| origin_of(&reqwest::Url::parse(s).unwrap());
        let uri = |s: &str| origin_of_uri(&s.parse().unwrap());
        assert_eq!(url("http://LocalHost/x"), url("http://localhost:80/y"));
        assert_eq!(url("https://egress"), uri("HTTPS://egress:443/a"));
        assert_eq!(url("http://[::1]:9000/a"), uri("http://[::1]:9000"));
        assert_ne!(url("http://localhost:4000"), url("http://localhost:4001"));
        assert_eq!(uri("/package.Service/Method"), None);
    }
}