encore-dev 2.0.0-beta.11

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
//! Request Context: typed fields that travel with a request to every service
//! it reaches, such as the user it is made for.
//!
//! A field is declared once in the app, as a module-level `static`, with a
//! name and the type of its value. Encore's parser reads the declaration, so
//! the name must be a string literal:
//!
//! ```no_run
//! use encore::reqctx::Field;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize, Deserialize, Clone)]
//! pub struct User {
//!     pub id: String,
//!     pub email: String,
//! }
//!
//! /// The user a request is made for, set by the gateway.
//! pub static CURRENT_USER: Field<User> = Field::new("user");
//! ```
//!
//! Gateway Middleware sets fields on the requests it lets through, with
//! `set_field` on what `on_request` returns (`encore::gateway`), and a
//! service reads them while handling one:
//!
//! ```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"));
//!     };
//!     // …the orders of user.id…
//!     Ok(())
//! }
//! ```
//!
//! A service may set any field, or clear one, for the code it runs and the
//! calls it makes:
//!
//! ```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, possibly in another language, binds a field by name,
//! with the type of its value: `Field::named("user")`.
//!
//! # Where fields are
//!
//! The fields are in the [`opentelemetry::Context`](crate::opentelemetry::Context),
//! with the trace, so they follow what carries it: the current context, as
//! [`FutureExt::with_context`](crate::opentelemetry::trace::FutureExt::with_context)
//! has it across `.await`. A task spawned with `tokio::spawn` starts without
//! them, as it starts without the span: spawn
//! `fut.with_current_context()` to keep both.
//!
//! # Trust
//!
//! No client can set a field: Encore strips the headers fields travel in
//! wherever a request enters the app, and signs them between containers. So
//! a service can trust what it reads, as far as it trusts the app's other
//! services.
//!
//! # Receiving and sending fields
//!
//! [`extract`] takes the fields a request a service receives carries into
//! its context. [`inject`] sets the fields of a context on a request for
//! another of the app's services, and only on those: anything else would be
//! sent who the request is made for. A Pub/Sub message carries the fields
//! declared with [`Field::pubsub`] that are set where it is published, into
//! its handler's context.
//!
//! # Limits
//!
//! A field travels as the base64url of its value's JSON, in a header of its
//! own, so it must be small: its encoding may be at most 4 KiB, and those of
//! all of a request's fields at most 8 KiB; a field carried on Pub/Sub
//! messages, at most 1 KiB. Setting a value beyond that is an error, at the
//! code that set it, rather than the request failing some hops later.
//!
//! # Errors
//!
//! Setting a field fails with this module's [`Error`]: the value doesn't
//! serialize, or it is beyond the limits. It is the module's own and doesn't
//! convert into [`encore::Error`](crate::Error): where a function returns
//! one, map it with the code that fits the caller.

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;

/// Why a field can't be set to a value. See the [module docs](self#errors).
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The value doesn't serialize as JSON.
    #[error("reqctx: field {field:?}: cannot encode the {type_name} as JSON: {error}")]
    Encode {
        /// The field's name.
        field: &'static str,
        /// The value's type.
        type_name: &'static str,
        /// Why it doesn't serialize.
        error: serde_json::Error,
    },
    /// The value, or the fields with it, encodes to more than it may: see
    /// the [limits](self#limits).
    #[error("reqctx: field {field:?}: the value {size}")]
    Size {
        /// The field's name.
        field: &'static str,
        /// Which limit, and by how much.
        size: SizeError,
    },
}

/// A Request Context field holding a `T`, which travels as JSON.
///
/// Declare it as a module-level `static`: `static USER: Field<User> =
/// Field::new("user");`. Its type argument is the value's type, which Encore
/// describes, and checks the bindings of the field by name against. It is
/// serialized with serde, and must be a type Encore can describe as a config's
/// type.
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 field. `const` so it can initialize a module-level
    /// `static`.
    ///
    /// The name is unique within the app, in kebab-case: lowercase letters,
    /// digits and hyphens, starting with a letter and ending with a letter
    /// or digit. Encore's parser checks it.
    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 app, possibly in another
    /// language. Encore checks the value's type against the declaration's.
    /// It travels as the declaration says: carried on Pub/Sub messages, and
    /// put on spans, as declared.
    pub const fn named(name: &'static str) -> Self {
        Self {
            name,
            config: None,
            _value: PhantomData,
        }
    }

    /// Also carries the field on the Pub/Sub messages published with it set,
    /// into the context of the handlers that receive them. Its value may
    /// then encode to at most 1 KiB, GCP Pub/Sub's limit on an attribute's
    /// value.
    ///
    /// Part of the declaration: it takes the field by value, so it cannot be
    /// called on the `static`.
    pub const fn pubsub(mut self) -> Self {
        if let Some(config) = &mut self.config {
            config.pubsub = true;
        }
        self
    }

    /// Puts the value on the spans started with it set, as the attribute
    /// `encore.ctx.<name>`, holding its JSON: for identifiers worth finding
    /// traces by, such as a tenant's. Never for secrets.
    pub const fn trace(mut self) -> Self {
        if let Some(config) = &mut self.config {
            config.trace = true;
        }
        self
    }

    /// Tags the field with `key` and `value`: key/value classification, such
    /// as `.tag("data", "pci")`, for policies to read. One call per tag, each
    /// with its own key. Encore reads them from the source, so both are string
    /// literals. A key is lowercase letters, digits, `_` and `-`, starting with
    /// a letter and not with `encore`, which is kept for Encore's own tags; a
    /// value is the same characters, or empty. Each is at most 63 characters,
    /// and a field has at most 32 tags.
    ///
    /// Part of the declaration: it takes the field by value, so it cannot be
    /// called on the `static`.
    ///
    /// ```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
    }

    /// The name the 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> {
    /// The field's value in the current context; `None` when it is not set.
    ///
    /// Each call decodes the value anew. A value that does not decode as a
    /// `T`, as one set by a service that disagrees about its type, reads as
    /// not set; Encore logs it, once.
    pub fn get(&self) -> Option<T> {
        Context::map_current(|cx| self.get_in(cx))
    }

    /// The field's value in `cx`; `None` when it is not set.
    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
            }
        }
    }

    /// The current context with the field set to `value`, for code that
    /// passes contexts explicitly.
    ///
    /// # Errors
    ///
    /// [`Error::Encode`] when the value does not serialize, and
    /// [`Error::Size`] when it encodes to more than the field may: 4 KiB, or
    /// 1 KiB for a field declared with [`pubsub`](Self::pubsub), or makes the
    /// context's fields encode to more than 8 KiB.
    pub fn context(&self, value: &T) -> Result<Context, Error> {
        Context::map_current(|cx| self.context_in(cx, value))
    }

    /// `cx` with the 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))
    }

    /// The current context without the field.
    pub fn without(&self) -> Context {
        Context::map_current(|cx| self.without_in(cx))
    }

    /// `cx` without the field.
    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)
    }

    /// `fut`, run with the field set to `value`, for the code it runs and the
    /// calls it makes. To run one with the field cleared:
    /// `fut.with_context(FIELD.without())`.
    ///
    /// # 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)?))
    }
}

/// A copy of `cx` holding the fields a request's headers carry, in place of
/// those it held: the first value of each header named for a field.
pub fn extract(cx: &Context, headers: &http::HeaderMap) -> Context {
    Values::from_headers(headers).in_context(cx)
}

/// Sets the fields of `cx` on a request's headers, in place of any it
/// carried.
///
/// Use it only for requests to the app's own services: anything else is
/// sent who the request is made for.
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}, so it reads as not set: {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()));
    }
}