Skip to main content

encore/
reqctx.rs

1//! Request Context: typed fields that travel with a request to every service
2//! it reaches, such as the user it is made for.
3//!
4//! A field is declared once in the app, as a module-level `static`, with a
5//! name and the type of its value. Encore's parser reads the declaration, so
6//! the name must be a string literal:
7//!
8//! ```no_run
9//! use encore::reqctx::Field;
10//! use serde::{Deserialize, Serialize};
11//!
12//! #[derive(Serialize, Deserialize, Clone)]
13//! pub struct User {
14//!     pub id: String,
15//!     pub email: String,
16//! }
17//!
18//! /// The user a request is made for, set by the gateway.
19//! pub static CURRENT_USER: Field<User> = Field::new("user");
20//! ```
21//!
22//! Gateway Middleware sets fields on the requests it lets through, with
23//! `set_field` on what `on_request` returns (`encore::gateway`), and a
24//! service reads them while handling one:
25//!
26//! ```no_run
27//! # use encore::reqctx::Field;
28//! # #[derive(serde::Serialize, serde::Deserialize, Clone)]
29//! # pub struct User { pub id: String }
30//! # static CURRENT_USER: Field<User> = Field::new("user");
31//! async fn orders() -> Result<(), encore::Error> {
32//!     let Some(user) = CURRENT_USER.get() else {
33//!         return Err(encore::Error::unauthenticated("not signed in"));
34//!     };
35//!     // …the orders of user.id…
36//!     Ok(())
37//! }
38//! ```
39//!
40//! A service may set any field, or clear one, for the code it runs and the
41//! calls it makes:
42//!
43//! ```no_run
44//! # use encore::reqctx::Field;
45//! # #[derive(serde::Serialize, serde::Deserialize, Clone)]
46//! # pub struct User { pub id: String }
47//! # static CURRENT_USER: Field<User> = Field::new("user");
48//! # async fn billing_invoices() {}
49//! # async fn f() -> Result<(), encore::reqctx::Error> {
50//! let system = User { id: "system".into() };
51//! CURRENT_USER.scope(&system, billing_invoices())?.await;
52//! # Ok(())
53//! # }
54//! ```
55//!
56//! Another service, possibly in another language, binds a field by name,
57//! with the type of its value: `Field::named("user")`.
58//!
59//! # Where fields are
60//!
61//! The fields are in the [`opentelemetry::Context`](crate::opentelemetry::Context),
62//! with the trace, so they follow what carries it: the current context, as
63//! [`FutureExt::with_context`](crate::opentelemetry::trace::FutureExt::with_context)
64//! has it across `.await`. A task spawned with `tokio::spawn` starts without
65//! them, as it starts without the span: spawn
66//! `fut.with_current_context()` to keep both.
67//!
68//! # Trust
69//!
70//! No client can set a field: Encore strips the headers fields travel in
71//! wherever a request enters the app, and signs them between containers. So
72//! a service can trust what it reads, as far as it trusts the app's other
73//! services.
74//!
75//! # Receiving and sending fields
76//!
77//! [`extract`] takes the fields a request a service receives carries into
78//! its context. [`inject`] sets the fields of a context on a request for
79//! another of the app's services, and only on those: anything else would be
80//! sent who the request is made for. A Pub/Sub message carries the fields
81//! declared with [`Field::pubsub`] that are set where it is published, into
82//! its handler's context.
83//!
84//! # Limits
85//!
86//! A field travels as the base64url of its value's JSON, in a header of its
87//! own, so it must be small: its encoding may be at most 4 KiB, and those of
88//! all of a request's fields at most 8 KiB; a field carried on Pub/Sub
89//! messages, at most 1 KiB. Setting a value beyond that is an error, at the
90//! code that set it, rather than the request failing some hops later.
91//!
92//! # Errors
93//!
94//! Setting a field fails with this module's [`Error`]: the value doesn't
95//! serialize, or it is beyond the limits. It is the module's own and doesn't
96//! convert into [`encore::Error`](crate::Error): where a function returns
97//! one, map it with the code that fits the caller.
98
99use std::collections::HashSet;
100use std::future::Future;
101use std::marker::PhantomData;
102use std::sync::Mutex;
103
104use encore_sdk_core::reqctx::{self as core_reqctx, FieldConfig, Values};
105use serde::de::DeserializeOwned;
106use serde::Serialize;
107
108use crate::opentelemetry::trace::{FutureExt, WithContext};
109use crate::opentelemetry::Context;
110
111pub use encore_sdk_core::reqctx::SizeError;
112
113/// Why a field can't be set to a value. See the [module docs](self#errors).
114#[derive(Debug, thiserror::Error)]
115#[non_exhaustive]
116pub enum Error {
117    /// The value doesn't serialize as JSON.
118    #[error("reqctx: field {field:?}: cannot encode the {type_name} as JSON: {error}")]
119    Encode {
120        /// The field's name.
121        field: &'static str,
122        /// The value's type.
123        type_name: &'static str,
124        /// Why it doesn't serialize.
125        error: serde_json::Error,
126    },
127    /// The value, or the fields with it, encodes to more than it may: see
128    /// the [limits](self#limits).
129    #[error("reqctx: field {field:?}: the value {size}")]
130    Size {
131        /// The field's name.
132        field: &'static str,
133        /// Which limit, and by how much.
134        size: SizeError,
135    },
136}
137
138/// A Request Context field holding a `T`, which travels as JSON.
139///
140/// Declare it as a module-level `static`: `static USER: Field<User> =
141/// Field::new("user");`. Its type argument is the value's type, which Encore
142/// describes, and checks the bindings of the field by name against. It is
143/// serialized with serde, and must be a type Encore can describe as a config's
144/// type.
145pub struct Field<T> {
146    name: &'static str,
147    /// The declaration's, or `None` for a field bound by name.
148    config: Option<FieldConfig>,
149    _value: PhantomData<fn() -> T>,
150}
151
152impl<T> Field<T> {
153    /// Declares a field. `const` so it can initialize a module-level
154    /// `static`.
155    ///
156    /// The name is unique within the app, in kebab-case: lowercase letters,
157    /// digits and hyphens, starting with a letter and ending with a letter
158    /// or digit. Encore's parser checks it.
159    pub const fn new(name: &'static str) -> Self {
160        Self {
161            name,
162            config: Some(FieldConfig {
163                pubsub: false,
164                trace: false,
165            }),
166            _value: PhantomData,
167        }
168    }
169
170    /// Binds a field declared elsewhere in the app, possibly in another
171    /// language. Encore checks the value's type against the declaration's.
172    /// It travels as the declaration says: carried on Pub/Sub messages, and
173    /// put on spans, as declared.
174    pub const fn named(name: &'static str) -> Self {
175        Self {
176            name,
177            config: None,
178            _value: PhantomData,
179        }
180    }
181
182    /// Also carries the field on the Pub/Sub messages published with it set,
183    /// into the context of the handlers that receive them. Its value may
184    /// then encode to at most 1 KiB, GCP Pub/Sub's limit on an attribute's
185    /// value.
186    ///
187    /// Part of the declaration: it takes the field by value, so it cannot be
188    /// called on the `static`.
189    pub const fn pubsub(mut self) -> Self {
190        if let Some(config) = &mut self.config {
191            config.pubsub = true;
192        }
193        self
194    }
195
196    /// Puts the value on the spans started with it set, as the attribute
197    /// `encore.ctx.<name>`, holding its JSON: for identifiers worth finding
198    /// traces by, such as a tenant's. Never for secrets.
199    pub const fn trace(mut self) -> Self {
200        if let Some(config) = &mut self.config {
201            config.trace = true;
202        }
203        self
204    }
205
206    /// Tags the field with `key` and `value`: key/value classification, such
207    /// as `.tag("data", "pci")`, for policies to read. One call per tag, each
208    /// with its own key. Encore reads them from the source, so both are string
209    /// literals. A key is lowercase letters, digits, `_` and `-`, starting with
210    /// a letter and not with `encore`, which is kept for Encore's own tags; a
211    /// value is the same characters, or empty. Each is at most 63 characters,
212    /// and a field has at most 32 tags.
213    ///
214    /// Part of the declaration: it takes the field by value, so it cannot be
215    /// called on the `static`.
216    ///
217    /// ```no_run
218    /// use encore::reqctx::Field;
219    ///
220    /// static TENANT: Field<String> = Field::new("tenant").tag("data", "pii");
221    /// ```
222    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
223        self
224    }
225
226    /// The name the field was declared with.
227    pub const fn name(&self) -> &'static str {
228        self.name
229    }
230
231    /// How the field travels: as the app declares it, wherever that is,
232    /// else as this declaration says.
233    fn config(&self) -> FieldConfig {
234        crate::runtime::configured()
235            .and_then(|rt| rt.reqctx_fields().get(self.name))
236            .or(self.config)
237            .unwrap_or_default()
238    }
239}
240
241impl<T> std::fmt::Debug for Field<T> {
242    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
243        f.debug_tuple("Field").field(&self.name).finish()
244    }
245}
246
247impl<T: Serialize + DeserializeOwned> Field<T> {
248    /// The field's value in the current context; `None` when it is not set.
249    ///
250    /// Each call decodes the value anew. A value that does not decode as a
251    /// `T`, as one set by a service that disagrees about its type, reads as
252    /// not set; Encore logs it, once.
253    pub fn get(&self) -> Option<T> {
254        Context::map_current(|cx| self.get_in(cx))
255    }
256
257    /// The field's value in `cx`; `None` when it is not set.
258    pub fn get_in(&self, cx: &Context) -> Option<T> {
259        let values = Values::of(cx);
260        let value = values.get(self.name)?;
261        match decode(value) {
262            Ok(v) => Some(v),
263            Err(why) => {
264                log_undecodable(self.name, std::any::type_name::<T>(), &why);
265                None
266            }
267        }
268    }
269
270    /// The current context with the field set to `value`, for code that
271    /// passes contexts explicitly.
272    ///
273    /// # Errors
274    ///
275    /// [`Error::Encode`] when the value does not serialize, and
276    /// [`Error::Size`] when it encodes to more than the field may: 4 KiB, or
277    /// 1 KiB for a field declared with [`pubsub`](Self::pubsub), or makes the
278    /// context's fields encode to more than 8 KiB.
279    pub fn context(&self, value: &T) -> Result<Context, Error> {
280        Context::map_current(|cx| self.context_in(cx, value))
281    }
282
283    /// `cx` with the field set to `value`. See [`context`](Self::context).
284    pub fn context_in(&self, cx: &Context, value: &T) -> Result<Context, Error> {
285        let json = serde_json::to_vec(value).map_err(|error| Error::Encode {
286            field: self.name,
287            type_name: std::any::type_name::<T>(),
288            error,
289        })?;
290        let values = Values::of(cx)
291            .with(self.name, core_reqctx::encode(&json), self.config())
292            .map_err(|size| Error::Size {
293                field: self.name,
294                size,
295            })?;
296        Ok(values.in_context(cx))
297    }
298
299    /// The current context without the field.
300    pub fn without(&self) -> Context {
301        Context::map_current(|cx| self.without_in(cx))
302    }
303
304    /// `cx` without the field.
305    pub fn without_in(&self, cx: &Context) -> Context {
306        let values = Values::of(cx);
307        if values.get(self.name).is_none() {
308            return cx.clone();
309        }
310        values.without(self.name).in_context(cx)
311    }
312
313    /// `fut`, run with the field set to `value`, for the code it runs and the
314    /// calls it makes. To run one with the field cleared:
315    /// `fut.with_context(FIELD.without())`.
316    ///
317    /// # Errors
318    ///
319    /// As [`context`](Self::context), before `fut` runs.
320    pub fn scope<F: Future>(&self, value: &T, fut: F) -> Result<WithContext<F>, Error> {
321        Ok(fut.with_context(self.context(value)?))
322    }
323}
324
325/// A copy of `cx` holding the fields a request's headers carry, in place of
326/// those it held: the first value of each header named for a field.
327pub fn extract(cx: &Context, headers: &http::HeaderMap) -> Context {
328    Values::from_headers(headers).in_context(cx)
329}
330
331/// Sets the fields of `cx` on a request's headers, in place of any it
332/// carried.
333///
334/// Use it only for requests to the app's own services: anything else is
335/// sent who the request is made for.
336pub fn inject(cx: &Context, headers: &mut http::HeaderMap) {
337    Values::of(cx).to_headers(headers);
338}
339
340/// The value a field's wire form holds. Says where it is wrong, never what
341/// it holds: a field may hold who a request is made for.
342fn decode<T: DeserializeOwned>(value: &str) -> Result<T, String> {
343    let json = core_reqctx::decode(value).map_err(|e| e.to_string())?;
344    serde_json::from_slice(&json).map_err(|e| {
345        let what = match e.classify() {
346            serde_json::error::Category::Data => "it is JSON of another shape",
347            _ => "it is not valid JSON",
348        };
349        format!(
350            "{what}: the error is at line {} column {}",
351            e.line(),
352            e.column()
353        )
354    })
355}
356
357/// The fields, with the type read, whose undecodable values have been
358/// logged.
359static LOGGED: Mutex<Option<HashSet<(&'static str, &'static str)>>> = Mutex::new(None);
360
361fn log_undecodable(name: &'static str, ty: &'static str, why: &str) {
362    let mut logged = LOGGED.lock().unwrap_or_else(|e| e.into_inner());
363    if !logged.get_or_insert_with(HashSet::new).insert((name, ty)) {
364        return;
365    }
366    drop(logged);
367    tracing::warn!(
368        field = name,
369        value_type = ty,
370        "cannot decode Request Context field {name:?} as {ty}, so it reads as not set: {why}"
371    );
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use serde::Deserialize;
378
379    #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
380    struct User {
381        id: String,
382        admin: bool,
383    }
384
385    static USER: Field<User> = Field::new("test-user");
386    static BY_NAME: Field<User> = Field::named("test-user");
387    static TENANT: Field<String> = Field::new("test-tenant").pubsub().trace();
388    static COUNT: Field<u32> = Field::named("test-user");
389
390    fn alice() -> User {
391        User {
392            id: "alice".into(),
393            admin: false,
394        }
395    }
396
397    #[test]
398    fn a_field_reads_what_was_set_in_its_context() {
399        assert_eq!(USER.get(), None);
400        let cx = USER.context(&alice()).unwrap();
401        assert_eq!(USER.get_in(&cx), Some(alice()));
402        // Bound by name, it is the same field.
403        assert_eq!(BY_NAME.get_in(&cx), Some(alice()));
404        assert_eq!(USER.get_in(&USER.without_in(&cx)), None);
405        let _guard = cx.attach();
406        assert_eq!(USER.get(), Some(alice()));
407        assert_eq!(USER.get_in(&USER.without()), None);
408    }
409
410    #[test]
411    fn a_scope_carries_the_field_across_awaits() {
412        let rt = tokio::runtime::Builder::new_current_thread()
413            .build()
414            .unwrap();
415        let seen = rt.block_on(async {
416            let fut = async {
417                tokio::task::yield_now().await;
418                USER.get()
419            };
420            USER.scope(&alice(), fut).unwrap().await
421        });
422        assert_eq!(seen, Some(alice()));
423        assert_eq!(USER.get(), None);
424        let cleared = rt.block_on(async {
425            let cx = USER.context(&alice()).unwrap();
426            async { async { USER.get() }.with_context(USER.without()).await }
427                .with_context(cx)
428                .await
429        });
430        assert_eq!(cleared, None);
431    }
432
433    #[test]
434    fn a_value_of_another_shape_reads_as_unset() {
435        let cx = USER.context(&alice()).unwrap();
436        assert_eq!(COUNT.get_in(&cx), None);
437        assert!(
438            decode::<u32>(&core_reqctx::encode(b"{\"id\":\"secret-id\"}"))
439                .unwrap_err()
440                .contains("another shape")
441        );
442        let why = decode::<User>(&core_reqctx::encode(b"{\"id\":\"secret")).unwrap_err();
443        assert!(why.starts_with("it is not valid JSON"), "{why}");
444        assert!(!why.contains("secret"), "{why}");
445        assert_eq!(
446            decode::<u32>("!").unwrap_err(),
447            "it is not base64url without padding"
448        );
449    }
450
451    #[test]
452    fn limits_fail_where_the_value_is_set() {
453        let err = TENANT.context(&"a".repeat(1100)).unwrap_err();
454        assert!(
455            matches!(
456                err,
457                Error::Size {
458                    field: "test-tenant",
459                    size: SizeError::MessageValue(_)
460                }
461            ),
462            "{err:?}"
463        );
464        let msg = err.to_string();
465        assert!(
466            msg.contains("reqctx: field \"test-tenant\": the value encodes to")
467                && msg.contains("carried on Pub/Sub messages"),
468            "{msg}"
469        );
470        let err = USER
471            .context(&User {
472                id: "a".repeat(5000),
473                admin: true,
474            })
475            .unwrap_err();
476        assert!(
477            matches!(
478                err,
479                Error::Size {
480                    size: SizeError::Value(_),
481                    ..
482                }
483            ),
484            "{err:?}"
485        );
486        assert!(err.to_string().contains("more than the 4096"), "{err}");
487    }
488
489    #[test]
490    fn headers_carry_the_fields() {
491        let cx = TENANT.context(&"acme".to_string()).unwrap();
492        let mut headers = http::HeaderMap::new();
493        headers.insert("x-encore-meta-ctx-stale", "e30".parse().unwrap());
494        inject(&cx, &mut headers);
495        assert!(headers.get("x-encore-meta-ctx-stale").is_none());
496        let received = extract(&Context::new(), &headers);
497        assert_eq!(TENANT.get_in(&received), Some("acme".to_string()));
498    }
499}