encore-dev 2.0.0-beta.13

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
//! Calling the app's other services.
//!
//! A [`Client`] calls one service. It is `const`, so it can be a `static`:
//!
//! ```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?)
//! }
//! ```
//!
//! Its calls carry the trace and Request Context ([`crate::reqctx`]) of the
//! context they are sent in to the app's services, so the services they reach
//! continue the request they are made for. A request to anything else carries
//! no Request Context: who a request is made for is no business of a third
//! party's. Every client shares the same connections, so making one where it
//! is needed costs no more than a `static`.
//!
//! A tower client, as hyper-util's or a tonic channel, does the same through
//! [`PropagateLayer`].
//!
//! Looking up a service's URL, or making a client for it, makes the calling
//! service depend on it. Encore reads the dependency from the code, as it
//! reads which resources a service uses: so the name must be a string
//! literal, the function must be called directly rather than passed around,
//! and the call must be in a service.
//!
//! # Generated clients
//!
//! A service that lists another in its `encore.service.json` `clients` gets
//! clients for calling it in `encore_gen::clients`: a module per service,
//! with a module per API the service declares. Each operation is a function
//! of its module, returning the call, which `.await` sends, so there is no
//! client to make first:
//!
//! ```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?;
//! ```
//!
//! A call that fails is a [`CallError`], whatever kind of API it calls, and
//! `?` turns it into an [`encore::Error`](crate::Error) with the same 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()),
//! };
//! ```
//!
//! [`UnlessNotFound`] makes a `NotFound` failure `None`, for a call for
//! something that may not be there:
//!
//! ```ignore
//! use encore::services::UnlessNotFound;
//!
//! let product = catalog::openapi::get_product("xyz").await.unless_not_found()?;
//! ```
//!
//! A call is a `Future` once `into_future` makes it one, for what takes a
//! future rather than something to await, as `tokio::spawn` and `join_all`
//! do. It carries the context of the code that made it, as an awaited call
//! does:
//!
//! ```ignore
//! use std::future::IntoFuture;
//!
//! let product = tokio::spawn(catalog::openapi::get_product("xyz").into_future());
//! ```
//!
//! Every call also takes a timeout and headers of its own, which go over its
//! client's, and a module's `Client` holds settings for every call made with
//! it:
//!
//! ```ignore
//! let product = catalog::openapi::get_product("xyz")
//!     .timeout(Duration::from_secs(2))
//!     .await?;
//! let storefront = catalog::storefront::Client::new().header("x-tenant", "a");
//! ```
//!
//! The clients send as a [`Client`] does, so their calls carry the trace and
//! Request Context of the context they are made in, and share its
//! connections; a gRPC API's calls, which are [`Unary`], [`ServerStreaming`],
//! [`ClientStreaming`] and [`BidiStreaming`], share one connection per base
//! URL. They speak gRPC over HTTP/2, through tonic, as every language's
//! generated clients do: in the clear (h2c) to an `http://` base URL, and
//! with TLS to an `https://` one, trusting the system's roots, or those of
//! `SSL_CERT_FILE`. A gRPC call's timeout is its deadline, which holds for
//! the whole call, connecting and each message of a stream too. A
//! bidirectional call is ready before the service answers, as a service may
//! wait for a message first. A gRPC message keeps the fields its schema
//! lacks, as a newer schema's, and sends them on; a failed call keeps its
//! status's details, in [`CallError::grpc_details`]. A client holds only its
//! settings, so one made for a single call costs nothing to make, and there
//! is nothing to close.
//!
//! # Tests
//!
//! No service runs under `encore test`. Every service still has a base URL
//! there, so a client can be made as usual, but a call to it is answered with
//! `501 Not Implemented` and an error saying which service and path the test
//! called: mock the call in the test instead.

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;

/// The reqwest a [`Client`] is made with, for the types its requests take
/// and its responses are.
pub use reqwest;

#[doc(hidden)]
pub mod clients;

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

/// The base URL the calling service reaches `service` at, for
/// service-to-service calls, without a trailing slash: a call's path goes
/// after it, `{base}/users/42`.
///
/// # Panics
///
/// If the runtime has no address for `service`: the app has no service of
/// that name, which Encore's parser reports, or this process was started
/// without the app's service discovery, as a plain `cargo test` is.
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)
}

/// What a lookup of a service the runtime knows no address for says.
pub(crate) fn unknown_service(service: &str) -> String {
    format!("encore: no base URL is known for service {service:?}")
}

/// A client for `service`, for service-to-service calls: its requests take
/// the service's paths, and carry the trace and Request Context of the
/// context they are sent in.
///
/// It is `const`, so it can be a `static`, and looks the service up when it
/// is first used. Like [`base_url`], it makes the calling service depend on
/// `service`, so the name must be a string literal and the call made
/// directly, in 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(),
    }
}

/// A client for one of the app's services, made with [`client`].
#[derive(Debug)]
pub struct Client {
    service: &'static str,
    base: OnceLock<&'static str>,
}

impl Client {
    /// The service's base URL, without a trailing slash, as [`base_url`]
    /// returns it.
    ///
    /// # Panics
    ///
    /// As [`base_url`] does.
    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)
    }

    /// A request for `path`, which is the service's: it is joined to the base
    /// URL with a single `/`, so `/invoices` and `invoices` are the same
    /// request. An absolute URL is used as it is.
    ///
    /// # Panics
    ///
    /// As [`base_url`] does.
    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, '+' | '-' | '.'))
}

/// A request a [`Client`] sends: reqwest's builder, whose
/// [`send`](RequestBuilder::send) carries the call's context.
#[derive(Debug)]
#[must_use = "a request is sent only by `send`"]
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))
    }

    /// Fails each request it sends, the first and each redirect, that is not
    /// answered within `timeout`.
    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))
    }

    /// Changes the request as reqwest's builder does, for what this one
    /// does not offer.
    pub fn map(self, f: impl FnOnce(reqwest::RequestBuilder) -> reqwest::RequestBuilder) -> Self {
        RequestBuilder {
            inner: f(self.inner),
        }
    }

    /// Sends the request, with the Request Context and trace of its context
    /// when it is for one of the app's services, without any Request Context
    /// otherwise.
    ///
    /// Its context is the one it is first polled in, as
    /// `.send().with_context(cx)` sets it, unless that one holds neither a
    /// trace nor Request Context: then the one `send` is called in, so a
    /// future handed to `tokio::spawn` still carries the call's.
    ///
    /// It follows up to 10 redirects, each sent with the context its own URL
    /// is due, so a redirect away from the app's services carries no Request
    /// Context. As fetch does, a 301 or 302 turns only a `POST` into a `GET`,
    /// and a 303 anything but a `HEAD`; a 307 or 308 keeps the method and
    /// body. Past 10 redirects, or when a redirect would need a streamed body
    /// sent again, the redirect itself is the response.
    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")
    })
}

/// A tower [`Layer`](tower_layer::Layer) whose services send the trace and
/// Request Context of the context a request is sent in with each request
/// for one of the app's services, and no Request Context with any other: for
/// hyper-util's client, a tonic channel, 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 for the app's services when its URI is at the origin of a
/// base URL [`base_url`] returned. A request whose URI has none, as a tonic
/// client's without `with_origin`, is not. It follows no redirects; a layer
/// outside it that does has each one prepared.
#[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 }
    }
}

/// The service of a [`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);
    }
}