encore-dev 2.0.0-beta.18

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
//! Request Context: typed fields that travel with a request to every service
//! it reaches (for example, the authenticated user).
//!
//! Declare each field once in the application as a module-level `static` with a
//! string literal name and value type so Encore can parse it statically:
//!
//! ```no_run
//! use encore::reqctx::Field;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize, Deserialize, Clone)]
//! pub struct User {
//!     pub id: String,
//!     pub email: String,
//! }
//!
//! /// The authenticated user for a request, set by the gateway.
//! pub static CURRENT_USER: Field<User> = Field::new("user");
//! ```
//!
//! Gateway middleware attaches fields to forwarded requests using `set_field`
//! in `on_request` (`encore::gateway`), and downstream services read them while
//! handling requests:
//!
//! ```no_run
//! # use encore::reqctx::Field;
//! # #[derive(serde::Serialize, serde::Deserialize, Clone)]
//! # pub struct User { pub id: String }
//! # static CURRENT_USER: Field<User> = Field::new("user");
//! async fn orders() -> Result<(), encore::Error> {
//!     let Some(user) = CURRENT_USER.get() else {
//!         return Err(encore::Error::unauthenticated("not signed in"));
//!     };
//!     // …load orders for user.id…
//!     Ok(())
//! }
//! ```
//!
//! A service can also set or clear fields for nested operations and outbound
//! service calls:
//!
//! ```no_run
//! # use encore::reqctx::Field;
//! # #[derive(serde::Serialize, serde::Deserialize, Clone)]
//! # pub struct User { pub id: String }
//! # static CURRENT_USER: Field<User> = Field::new("user");
//! # async fn billing_invoices() {}
//! # async fn f() -> Result<(), encore::reqctx::Error> {
//! let system = User { id: "system".into() };
//! CURRENT_USER.scope(&system, billing_invoices())?.await;
//! # Ok(())
//! # }
//! ```
//!
//! Another service (even in a different language) can bind an existing field by
//! name with `Field::named("user")`.
//!
//! # Context propagation
//!
//! Fields live inside [`opentelemetry::Context`](crate::opentelemetry::Context)
//! alongside the trace, so they propagate across `.await` points with
//! [`FutureExt::with_context`](crate::opentelemetry::trace::FutureExt::with_context).
//! Tasks spawned with `tokio::spawn` do not inherit the current context
//! automatically; wrap them with `fut.with_current_context()` to preserve both
//! tracing and Request Context fields.
//!
//! # Trust model
//!
//! External clients cannot set Request Context fields. Encore strips the
//! underlying headers at every public entry point and cryptographically signs
//! them between containers, so services can trust field values from other
//! services in the application.
//!
//! # Extracting and injecting headers
//!
//! [`extract`] reads Request Context fields from incoming request headers into
//! a context. [`inject`] writes context fields onto outgoing request headers;
//! only call it for requests to other Encore services in the same application,
//! never for external third-party URLs. Pub/Sub messages automatically carry
//! any set fields declared with [`Field::pubsub`] into their subscribers'
//! contexts.
//!
//! # Size limits
//!
//! Each field is encoded as base64url JSON in its own header, so values must be
//! compact: at most 4 KiB per field (1 KiB for fields marked with
//! [`Field::pubsub`]), and at most 8 KiB across all fields on a request.
//! Exceeding a limit fails immediately at the call site that sets the field.
//!
//! # Errors
//!
//! Setting a field returns this module's [`Error`] if serialization fails or a
//! size limit is exceeded. It does not automatically convert into
//! [`encore::Error`](crate::Error); map it to an appropriate error code at the
//! call site.

use std::collections::HashSet;
use std::future::Future;
use std::marker::PhantomData;
use std::sync::Mutex;

use encore_sdk_core::reqctx::{self as core_reqctx, FieldConfig, Values};
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::opentelemetry::trace::{FutureExt, WithContext};
use crate::opentelemetry::Context;

pub use encore_sdk_core::reqctx::SizeError;

/// Error returned when setting a Request Context field fails. See the
/// [module documentation](self#errors).
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The field value failed to serialize to JSON.
    #[error("reqctx: field {field:?}: cannot encode {type_name} as JSON: {error}")]
    Encode {
        /// The field's name.
        field: &'static str,
        /// The Rust type name of the value.
        type_name: &'static str,
        /// The underlying Serde serialization error.
        error: serde_json::Error,
    },
    /// The encoded value (or total context size) exceeds the allowed limit; see
    /// [size limits](self#size-limits).
    #[error("reqctx: field {field:?}: the value {size}")]
    Size {
        /// The field's name.
        field: &'static str,
        /// Details about which limit was exceeded.
        size: SizeError,
    },
}

/// A typed Request Context field serialized as JSON.
///
/// Declare as a module-level `static` (for example,
/// `static USER: Field<User> = Field::new("user");`). The type parameter `T`
/// defines the field's schema, which Encore validates across all bindings by
/// name. `T` must be serializable with Serde and representable in Encore's
/// config schema.
pub struct Field<T> {
    name: &'static str,
    /// The declaration's, or `None` for a field bound by name.
    config: Option<FieldConfig>,
    _value: PhantomData<fn() -> T>,
}

impl<T> Field<T> {
    /// Declares a Request Context field.
    ///
    /// This constructor is `const` so it can initialize a module-level
    /// `static`. `name` must be unique across the app and use kebab-case
    /// (lowercase letters, digits, and hyphens, starting with a letter and
    /// ending with a letter or digit).
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            config: Some(FieldConfig {
                pubsub: false,
                trace: false,
            }),
            _value: PhantomData,
        }
    }

    /// Binds a field declared elsewhere in the application (possibly in another
    /// service or language).
    ///
    /// Encore checks that `T` is compatible with the original declaration, and
    /// the bound field inherits its Pub/Sub and tracing behavior.
    pub const fn named(name: &'static str) -> Self {
        Self {
            name,
            config: None,
            _value: PhantomData,
        }
    }

    /// Propagates this field on Pub/Sub messages published while it is set,
    /// making it available in subscriber contexts.
    ///
    /// Enabling Pub/Sub propagation limits the field's encoded size to 1 KiB
    /// (matching GCP Pub/Sub's attribute value limit).
    pub const fn pubsub(mut self) -> Self {
        if let Some(config) = &mut self.config {
            config.pubsub = true;
        }
        self
    }

    /// Records this field's JSON value as the `encore.ctx.<name>` attribute on
    /// spans started while it is set.
    ///
    /// Useful for searchable identifiers such as tenant IDs. Never enable on
    /// fields containing secrets.
    pub const fn trace(mut self) -> Self {
        if let Some(config) = &mut self.config {
            config.trace = true;
        }
        self
    }

    /// Attaches a key/value tag to the field (for example, `.tag("data", "pci")`)
    /// for policy and governance tooling.
    ///
    /// Call once per tag with unique keys. Both `key` and `value` must be string
    /// literals so Encore can parse them statically. Keys must start with a
    /// letter, contain only lowercase letters, digits, `_`, and `-`, and must
    /// not start with `encore` (reserved for Encore's own tags). Values use the
    /// same character set or may be empty. Each key and value is at most 63
    /// characters, and a field may have at most 32 tags.
    ///
    /// ```no_run
    /// use encore::reqctx::Field;
    ///
    /// static TENANT: Field<String> = Field::new("tenant").tag("data", "pii");
    /// ```
    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
        self
    }

    /// Returns the name this field was declared with.
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// How the field travels: as the app declares it, wherever that is,
    /// else as this declaration says.
    fn config(&self) -> FieldConfig {
        crate::runtime::configured()
            .and_then(|rt| rt.reqctx_fields().get(self.name))
            .or(self.config)
            .unwrap_or_default()
    }
}

impl<T> std::fmt::Debug for Field<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("Field").field(&self.name).finish()
    }
}

impl<T: Serialize + DeserializeOwned> Field<T> {
    /// Returns this field's value from the current context, or `None` if unset.
    ///
    /// Each call decodes the value from the context. If the stored payload
    /// cannot be decoded as `T` (for example, due to a type mismatch across
    /// services), Encore logs a warning once and returns `None`.
    pub fn get(&self) -> Option<T> {
        Context::map_current(|cx| self.get_in(cx))
    }

    /// Returns this field's value from `cx`, or `None` if unset.
    pub fn get_in(&self, cx: &Context) -> Option<T> {
        let values = Values::of(cx);
        let value = values.get(self.name)?;
        match decode(value) {
            Ok(v) => Some(v),
            Err(why) => {
                log_undecodable(self.name, std::any::type_name::<T>(), &why);
                None
            }
        }
    }

    /// Returns a copy of the current context with this field set to `value`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Encode`] if `value` fails to serialize, or
    /// [`Error::Size`] if the encoded value exceeds the field limit (4 KiB, or
    /// 1 KiB with [`Field::pubsub`]) or causes the total Request Context to
    /// exceed 8 KiB.
    pub fn context(&self, value: &T) -> Result<Context, Error> {
        Context::map_current(|cx| self.context_in(cx, value))
    }

    /// Returns a copy of `cx` with this field set to `value`. See
    /// [`context`](Self::context).
    pub fn context_in(&self, cx: &Context, value: &T) -> Result<Context, Error> {
        let json = serde_json::to_vec(value).map_err(|error| Error::Encode {
            field: self.name,
            type_name: std::any::type_name::<T>(),
            error,
        })?;
        let values = Values::of(cx)
            .with(self.name, core_reqctx::encode(&json), self.config())
            .map_err(|size| Error::Size {
                field: self.name,
                size,
            })?;
        Ok(values.in_context(cx))
    }

    /// Returns a copy of the current context with this field removed.
    pub fn without(&self) -> Context {
        Context::map_current(|cx| self.without_in(cx))
    }

    /// Returns a copy of `cx` with this field removed.
    pub fn without_in(&self, cx: &Context) -> Context {
        let values = Values::of(cx);
        if values.get(self.name).is_none() {
            return cx.clone();
        }
        values.without(self.name).in_context(cx)
    }

    /// Runs `fut` with this field set to `value` for nested operations and
    /// outbound calls.
    ///
    /// To run a future with the field cleared instead, use
    /// `fut.with_context(FIELD.without())`.
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`context`](Self::context) before `fut` runs.
    pub fn scope<F: Future>(&self, value: &T, fut: F) -> Result<WithContext<F>, Error> {
        Ok(fut.with_context(self.context(value)?))
    }
}

/// Returns a copy of `cx` populated with Request Context fields extracted from
/// `headers`, replacing any existing fields in `cx`.
pub fn extract(cx: &Context, headers: &http::HeaderMap) -> Context {
    Values::from_headers(headers).in_context(cx)
}

/// Writes the Request Context fields from `cx` into `headers`, replacing any
/// existing Request Context headers.
///
/// Only call this for requests to other Encore services in the same
/// application; calling it on external requests would leak Request Context data
/// to third parties.
pub fn inject(cx: &Context, headers: &mut http::HeaderMap) {
    Values::of(cx).to_headers(headers);
}

/// The value a field's wire form holds. Says where it is wrong, never what
/// it holds: a field may hold who a request is made for.
fn decode<T: DeserializeOwned>(value: &str) -> Result<T, String> {
    let json = core_reqctx::decode(value).map_err(|e| e.to_string())?;
    serde_json::from_slice(&json).map_err(|e| {
        let what = match e.classify() {
            serde_json::error::Category::Data => "it is JSON of another shape",
            _ => "it is not valid JSON",
        };
        format!(
            "{what}: the error is at line {} column {}",
            e.line(),
            e.column()
        )
    })
}

/// The fields, with the type read, whose undecodable values have been
/// logged.
static LOGGED: Mutex<Option<HashSet<(&'static str, &'static str)>>> = Mutex::new(None);

fn log_undecodable(name: &'static str, ty: &'static str, why: &str) {
    let mut logged = LOGGED.lock().unwrap_or_else(|e| e.into_inner());
    if !logged.get_or_insert_with(HashSet::new).insert((name, ty)) {
        return;
    }
    drop(logged);
    tracing::warn!(
        field = name,
        value_type = ty,
        "cannot decode Request Context field {name:?} as {ty}, treating it as unset: {why}"
    );
}

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

    #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
    struct User {
        id: String,
        admin: bool,
    }

    static USER: Field<User> = Field::new("test-user");
    static BY_NAME: Field<User> = Field::named("test-user");
    static TENANT: Field<String> = Field::new("test-tenant").pubsub().trace();
    static COUNT: Field<u32> = Field::named("test-user");

    fn alice() -> User {
        User {
            id: "alice".into(),
            admin: false,
        }
    }

    #[test]
    fn a_field_reads_what_was_set_in_its_context() {
        assert_eq!(USER.get(), None);
        let cx = USER.context(&alice()).unwrap();
        assert_eq!(USER.get_in(&cx), Some(alice()));
        // Bound by name, it is the same field.
        assert_eq!(BY_NAME.get_in(&cx), Some(alice()));
        assert_eq!(USER.get_in(&USER.without_in(&cx)), None);
        let _guard = cx.attach();
        assert_eq!(USER.get(), Some(alice()));
        assert_eq!(USER.get_in(&USER.without()), None);
    }

    #[test]
    fn a_scope_carries_the_field_across_awaits() {
        let rt = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        let seen = rt.block_on(async {
            let fut = async {
                tokio::task::yield_now().await;
                USER.get()
            };
            USER.scope(&alice(), fut).unwrap().await
        });
        assert_eq!(seen, Some(alice()));
        assert_eq!(USER.get(), None);
        let cleared = rt.block_on(async {
            let cx = USER.context(&alice()).unwrap();
            async { async { USER.get() }.with_context(USER.without()).await }
                .with_context(cx)
                .await
        });
        assert_eq!(cleared, None);
    }

    #[test]
    fn a_value_of_another_shape_reads_as_unset() {
        let cx = USER.context(&alice()).unwrap();
        assert_eq!(COUNT.get_in(&cx), None);
        assert!(
            decode::<u32>(&core_reqctx::encode(b"{\"id\":\"secret-id\"}"))
                .unwrap_err()
                .contains("another shape")
        );
        let why = decode::<User>(&core_reqctx::encode(b"{\"id\":\"secret")).unwrap_err();
        assert!(why.starts_with("it is not valid JSON"), "{why}");
        assert!(!why.contains("secret"), "{why}");
        assert_eq!(
            decode::<u32>("!").unwrap_err(),
            "it is not base64url without padding"
        );
    }

    #[test]
    fn limits_fail_where_the_value_is_set() {
        let err = TENANT.context(&"a".repeat(1100)).unwrap_err();
        assert!(
            matches!(
                err,
                Error::Size {
                    field: "test-tenant",
                    size: SizeError::MessageValue(_)
                }
            ),
            "{err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("reqctx: field \"test-tenant\": the value encodes to")
                && msg.contains("carried on Pub/Sub messages"),
            "{msg}"
        );
        let err = USER
            .context(&User {
                id: "a".repeat(5000),
                admin: true,
            })
            .unwrap_err();
        assert!(
            matches!(
                err,
                Error::Size {
                    size: SizeError::Value(_),
                    ..
                }
            ),
            "{err:?}"
        );
        assert!(err.to_string().contains("more than the 4096"), "{err}");
    }

    #[test]
    fn headers_carry_the_fields() {
        let cx = TENANT.context(&"acme".to_string()).unwrap();
        let mut headers = http::HeaderMap::new();
        headers.insert("x-encore-meta-ctx-stale", "e30".parse().unwrap());
        inject(&cx, &mut headers);
        assert!(headers.get("x-encore-meta-ctx-stale").is_none());
        let received = extract(&Context::new(), &headers);
        assert_eq!(TENANT.get_in(&received), Some("acme".to_string()));
    }
}