encore-dev 2.0.0-beta.14

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
//! Application config: typed values a service reads, written in TOML or JSON
//! files beside the code, and changed while the app runs.
//!
//! ```ignore
//! use encore::config::{Config, ConfigType, Duration};
//! use serde::Deserialize;
//!
//! #[derive(Deserialize, ConfigType)]
//! struct Checkout {
//!     /// Most items one order may hold.
//!     #[config(min = 1, max = 500)]
//!     max_items: u32,
//!     #[serde(default)]
//!     promo: Option<Promo>,
//!     payment_timeout: Duration,
//! }
//!
//! static CHECKOUT: Config<Checkout> = Config::new("checkout");
//!
//! fn too_many(items: usize) -> bool {
//!     items > CHECKOUT.get().max_items as usize
//! }
//! ```
//!
//! The type is the schema. Encore reads it from the code — its fields, their
//! types and serde attributes, the `#[config(...)]` constraints, the doc
//! comments — and checks every value against it before the service sees it:
//! as you edit a file under `encore run`, on a deploy, and as the service
//! starts, which it refuses to do with a value it could not read. That is why
//! [`Config::get`] cannot fail.
//!
//! # Scope
//!
//! How a config is declared says who it belongs to, as for
//! [secrets](crate::secrets#scope):
//!
//! - `Config::new("checkout")` belongs to the service that declares it. Two
//!   services may each declare one of the same name and hold different values
//!   in them. It must be declared inside a service.
//! - `Config::new("checkout").shared()` has one value for the whole app. Any
//!   service may read it, and each that does is recorded as using it.
//! - `Config::new("checkout").global()` has one value for the whole app and is
//!   available to every service, without being recorded.
//!
//! A config name has one scope across the app, as a secret's has: a name
//! declared shared or global can't also be a service's own.
//!
//! The scope is written out in the declaration, as the name is: Encore reads
//! both from the source.
//!
//! # Values
//!
//! A config's value is written in a file named after it — `checkout.config.toml`,
//! or `.json` — beside the declaring service's `encore.service.json`,
//! or beside `encore.app.json` for a shared or global config. Files over it change
//! it for some environments only, and are merged onto it field by field
//! (JSON Merge Patch: tables merge, anything else replaces, `null` deletes):
//!
//! ```text
//! checkout.config.toml              every environment
//! checkout.production.config.toml   environments of a type: local, test,
//!                                   development, preview, production
//! checkout.@prod-eu.config.toml     the environment named prod-eu
//! checkout.user.config.toml         your own values, on `encore run` only
//! ```
//!
//! The last, the user override, is yours alone: keep it out of version
//! control. It applies to your own `encore run` and never to tests. A field
//! no file sets takes its default in code (`#[serde(default)]`, `Option`).
//!
//! # Snapshots and changes
//!
//! [`Config::get`] returns a [`Value`]: a snapshot of the value, cheap to make
//! and to clone, that reads as the value itself. A config's value can change
//! while the app runs — edit its file under `encore run` and the running
//! service has the new value within a second, without a restart. A snapshot
//! keeps the value it was made with, so hold one for as long as you need the
//! value to be consistent (a request, say) and call `get` again for the next.
//! Code that builds something from a config — a client, a pool — rebuilds it
//! with [`Config::on_change`].
//!
//! # Secrets
//!
//! A field may read a secret rather than hold a value. The type names it:
//!
//! ```ignore
//! #[derive(Deserialize, ConfigType)]
//! struct Stripe {
//!     endpoint: String,
//!     #[config(secret = "StripeKey")]
//!     api_key: encore::secrets::Secret,
//! }
//!
//! let key = CHECKOUT.get().stripe.api_key.value();
//! ```
//!
//! The secret has the config's own scope: a service's own config reads its
//! service's own secret, a shared config a shared one, a global config a
//! global one. It is declared in code as any secret is
//! (`Secret::new("StripeKey")` in the service, with `.shared()` or
//! `.global()` for the app's); one that isn't is an error. No config file sets the field; the secret holds the value, per
//! environment as secrets do.
//!
//! # Tests
//!
//! Under `encore test` a config's value is what the files say for the `test`
//! environment type. A test can give a config a value of its own, which no
//! other test sees: [`testing::set_config`](crate::testing::set_config).

use std::any::Any;
use std::fmt;
use std::marker::PhantomData;
use std::ops::Deref;
use std::sync::{Arc, OnceLock, RwLock};

use encore_sdk_core::config as core_config;
use serde::de::{DeserializeOwned, Deserializer, Error as _};
use serde::{Deserialize, Serialize, Serializer};

use crate::runtime::core;
use crate::testing;

/// Derives [`ConfigType`](trait@ConfigType) for a type a config is declared
/// with, and allows `#[config(...)]` on its fields:
///
/// - `min = N`, `max = N`: the least and greatest number allowed.
/// - `min_len = N`, `max_len = N`: the fewest and most characters in a string.
/// - `pattern = "regex"`: a regular expression a string must match.
/// - `min_items = N`, `max_items = N`: the fewest and most items in a list.
/// - `secret = "Name"`: the field reads this secret; see the [module
///   documentation](self#secrets).
pub use encore_macros::ConfigType;

/// A type a config can be declared with. Derive it: `#[derive(ConfigType)]`,
/// alongside serde's `Deserialize`.
pub trait ConfigType: DeserializeOwned + Send + Sync + 'static {}

#[doc(hidden)]
pub mod __private {
    pub use serde::de::DeserializeOwned;
}

/// A snapshot of a config's value, as it was when the snapshot was made.
/// Reads as the value: `&*value`, or any of its fields directly.
///
/// Cheap to clone: the clones share the value.
pub struct Value<T>(Arc<T>);

impl<T> Deref for Value<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.0
    }
}

impl<T> Clone for Value<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<T: fmt::Debug> fmt::Debug for Value<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// What a [`Config`] is: a name, the runtime's config once looked up, and the
/// value as last read. A config name has one scope across the app, so the name
/// alone says which config the runtime holds.
struct Inner<T> {
    name: &'static str,
    /// The runtime's config, looked up at first use: `None` when the runtime
    /// config has no value for it.
    handle: OnceLock<Option<Arc<core_config::Config>>>,
    /// The value last read, with the revision it was read from.
    current: RwLock<Option<(Arc<core_config::Revision>, Arc<T>)>>,
    /// Read when the runtime has no value: the defaults in code.
    defaults: OnceLock<Arc<T>>,
    _type: PhantomData<fn() -> T>,
}

impl<T: ConfigType> Inner<T> {
    const fn new(name: &'static str) -> Self {
        Self {
            name,
            handle: OnceLock::new(),
            current: RwLock::new(None),
            defaults: OnceLock::new(),
            _type: PhantomData,
        }
    }

    fn handle(&self) -> Option<&Arc<core_config::Config>> {
        self.handle.get_or_init(|| lookup(self.name)).as_ref()
    }

    fn get(&self) -> Value<T> {
        // A test's own value for the config, if it set one.
        if let Some(test) = testing::active().ok().flatten() {
            if let Some(value) = test.config(self.name) {
                if let Ok(value) = value.downcast::<T>() {
                    return Value(value);
                }
            }
        }

        let Some(handle) = self.handle() else {
            let value = self.defaults.get_or_init(|| {
                match T::deserialize(&serde_json::Value::Object(Default::default())) {
                    Ok(value) => Arc::new(value),
                    Err(err) => panic!(
                        "config {:?} has no value, and its type has no defaults to fall back \
                         to: {err}",
                        self.name
                    ),
                }
            });
            return Value(value.clone());
        };

        let revision = handle.current();
        {
            let current = self.current.read().unwrap_or_else(|e| e.into_inner());
            if let Some((read_from, value)) = current.as_ref() {
                if Arc::ptr_eq(read_from, &revision) {
                    return Value(value.clone());
                }
            }
        }
        let value = Arc::new(read::<T>(self.name, &revision.value));
        let mut current = self.current.write().unwrap_or_else(|e| e.into_inner());
        // Another thread may have read the same revision meanwhile: one
        // revision is one snapshot, so keep the one already handed out.
        if let Some((read_from, existing)) = current.as_ref() {
            if Arc::ptr_eq(read_from, &revision) {
                return Value(existing.clone());
            }
        }
        *current = Some((revision, value.clone()));
        Value(value)
    }

    fn on_change(&self, f: impl Fn(Value<T>) + Send + Sync + 'static) {
        let Some(handle) = self.handle().cloned() else {
            // Nothing gives it a new value.
            return;
        };
        let name = self.name;
        // Sees the value now as seen: only what comes after is a change.
        let mut changes = handle.subscribe();
        core().tokio_handle().spawn(async move {
            while changes.changed().await.is_ok() {
                // The revision the change is, marked seen: never the value
                // now, which may be a later one that would come again.
                let revision = changes.borrow_and_update().clone();
                f(Value(Arc::new(read::<T>(name, &revision.value))));
            }
        });
    }
}

/// Reads a value the runtime has checked against the schema. Failing here is
/// Encore's bug: the schema it derived from the type accepted a value serde
/// does not.
fn read<T: ConfigType>(name: &str, value: &serde_json::Value) -> T {
    T::deserialize(value).unwrap_or_else(|err| {
        panic!(
            "config {name:?}: the value satisfies the schema Encore derived from `{}`, but serde \
             could not read it: {err}. This is a bug in Encore: please report it",
            std::any::type_name::<T>()
        )
    })
}

/// The runtime's config of this name, whatever its scope.
fn lookup(name: &str) -> Option<Arc<core_config::Config>> {
    core().configs().get(name)
}

/// A config, declared as a module-level `static` with its value's type:
/// `static CHECKOUT: Config<Checkout> = Config::new("checkout");`. See the
/// [module documentation](self).
///
/// `new` declares a config of the service that declares it;
/// [`shared`](Self::shared) and [`global`](Self::global) make it the whole
/// app's.
pub struct Config<T>(Inner<T>);

impl<T: ConfigType> Config<T> {
    /// Declare a config by name. `const` so it can initialize a module-scope
    /// `static`; nothing is read until its value is asked for. The name must
    /// be a string literal: Encore reads it from the source.
    pub const fn new(name: &'static str) -> Self {
        Self(Inner::new(name))
    }

    /// Makes the config one value for the whole app, rather than the
    /// declaring service's own. Any service may read it, and each that does
    /// is recorded as using it. See [scope](self#scope).
    ///
    /// Encore reads the scope from the source; the runtime holds the config by
    /// its name, which has one scope across the app.
    pub const fn shared(self) -> Self {
        self
    }

    /// Makes the config one value for the whole app, available to every
    /// service without being recorded. See [scope](self#scope).
    ///
    /// Encore reads the scope from the source, as for [`shared`](Self::shared).
    pub const fn global(self) -> Self {
        self
    }

    /// Tags the config 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 config has at most 32 tags.
    ///
    /// Part of the declaration: it takes the config by value, so it cannot be
    /// called on the `static`.
    ///
    /// ```ignore
    /// static CHECKOUT: Config<Checkout> = Config::new("checkout").tag("team", "payments");
    /// ```
    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
        self
    }

    /// The name the config was declared with.
    pub const fn name(&self) -> &'static str {
        self.0.name
    }

    /// The config's value now: see [`Value`].
    pub fn get(&self) -> Value<T> {
        self.0.get()
    }

    /// Calls `f` with each new value the config is given while the process
    /// runs, from now on. Values that come faster than `f` is called are
    /// coalesced: `f` gets the latest, once. `f` runs on the runtime's
    /// threads: keep it quick, and spawn anything that waits.
    pub fn on_change(&self, f: impl Fn(Value<T>) + Send + Sync + 'static) {
        self.0.on_change(f)
    }

    /// The name the config is held under: a config name has one scope across
    /// the app.
    pub(crate) fn key(&self) -> &'static str {
        self.0.name
    }
}

/// Reads a test's value for the config `name` as `T`, once the core has
/// checked it against the config's schema, as the runtime would a value of its
/// own: for [`testing::set_config`].
pub(crate) fn test_value<T: ConfigType>(
    name: &str,
    value: serde_json::Value,
) -> Result<Arc<dyn Any + Send + Sync>, crate::Error> {
    let value = T::deserialize(&value).map_err(|err| {
        crate::Error::invalid_argument(format!(
            "the value for config {name:?} could not be read: {err}"
        ))
    })?;
    Ok(Arc::new(value))
}

/// A length of time, written in a config as a number and a unit, or several:
/// `"30s"`, `"250ms"`, `"1h30m"`, `"1.5h"`. The units are `ns`, `us` (or
/// `µs`), `ms`, `s`, `m` and `h`. Reads as a [`std::time::Duration`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Duration(pub std::time::Duration);

impl Deref for Duration {
    type Target = std::time::Duration;

    fn deref(&self) -> &std::time::Duration {
        &self.0
    }
}

impl From<Duration> for std::time::Duration {
    fn from(d: Duration) -> Self {
        d.0
    }
}

impl<'de> Deserialize<'de> for Duration {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = String::deserialize(deserializer)?;
        parse_duration(&text).map(Duration).ok_or_else(|| {
            D::Error::custom(format!(
                "{text:?} is not a duration, such as \"30s\", \"250ms\" or \"1h30m\""
            ))
        })
    }
}

/// Written as a whole number of microseconds (`"1500000us"`), which reads
/// back as the same duration but for what is finer than that.
impl Serialize for Duration {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&format!("{}us", self.0.as_micros()))
    }
}

/// Parses what `encore_appconfig::schema::DURATION_PATTERN` matches: one or
/// more numbers, each with a unit. `None` for anything else, or a duration
/// too long to hold.
pub(crate) fn parse_duration(text: &str) -> Option<std::time::Duration> {
    const UNITS: [(&str, u128); 7] = [
        ("ns", 1),
        ("us", 1_000),
        ("µs", 1_000),
        ("ms", 1_000_000),
        ("s", 1_000_000_000),
        ("m", 60_000_000_000),
        ("h", 3_600_000_000_000),
    ];
    if text.is_empty() {
        return None;
    }
    let mut rest = text;
    let mut nanos: u128 = 0;
    while !rest.is_empty() {
        let whole_len = rest.bytes().take_while(u8::is_ascii_digit).count();
        if whole_len == 0 {
            return None;
        }
        let whole: u128 = rest[..whole_len].parse().ok()?;
        rest = &rest[whole_len..];
        let mut fraction = "";
        if let Some(after) = rest.strip_prefix('.') {
            let len = after.bytes().take_while(u8::is_ascii_digit).count();
            if len == 0 {
                return None;
            }
            fraction = &after[..len];
            rest = &after[len..];
        }
        // The longest unit that matches: `ms` before `m`.
        let (unit, scale) = UNITS
            .iter()
            .filter(|(u, _)| rest.starts_with(u))
            .max_by_key(|(u, _)| u.len())?;
        rest = &rest[unit.len()..];
        let mut part = whole.checked_mul(*scale)?;
        if !fraction.is_empty() {
            // Precision past the nanosecond is dropped. 24 digits are past the
            // nanosecond of an hour, as the validator keeps, and their
            // numerator times an hour's nanoseconds still fits a u128.
            let digits = &fraction[..fraction.len().min(24)];
            let numerator: u128 = digits.parse().ok()?;
            let denominator = 10u128.checked_pow(digits.len() as u32)?;
            part = part.checked_add(numerator.checked_mul(*scale)? / denominator)?;
        }
        nanos = nanos.checked_add(part)?;
    }
    let secs = u64::try_from(nanos / 1_000_000_000).ok()?;
    Some(std::time::Duration::new(
        secs,
        (nanos % 1_000_000_000) as u32,
    ))
}

#[cfg(test)]
mod tests {
    use std::time::Duration as D;

    use super::*;

    #[test]
    fn durations_parse_as_go_writes_them() {
        let ok = [
            ("0s", D::ZERO),
            ("30s", D::from_secs(30)),
            ("250ms", D::from_millis(250)),
            ("1h30m", D::from_secs(5400)),
            ("1.5h", D::from_secs(5400)),
            // Digits past the nanosecond don't overflow the arithmetic.
            ("1.000000000000000000000000001h", D::from_secs(3600)),
            ("10us", D::from_micros(10)),
            ("10µs", D::from_micros(10)),
            ("7ns", D::from_nanos(7)),
            ("2m3.5s", D::from_millis(123_500)),
            ("1h1m1s1ms1us1ns", D::new(3661, 1_001_001)),
            ("0.000000001s", D::from_nanos(1)),
        ];
        for (text, want) in ok {
            assert_eq!(parse_duration(text), Some(want), "{text}");
        }
        let bad = [
            "",
            "30",
            "s",
            "-1s",
            "+1s",
            "1.s",
            ".5s",
            "1 s",
            "1d",
            "1sec",
            "1h 30m",
            "1S",
            "99999999999999999999h",
        ];
        for text in bad {
            assert_eq!(parse_duration(text), None, "{text}");
        }
    }

    /// What the schema's pattern accepts, `Duration` reads, and the other way
    /// around.
    #[test]
    fn durations_agree_with_the_schema_pattern() {
        let pattern = regex::Regex::new(encore_sdk_core::config::DURATION_PATTERN).unwrap();
        for text in [
            "30s", "250ms", "1h30m", "1.5h", "10µs", "2m3.5s", "", "30", "-1s", "1.s", ".5s", "1d",
            "1S", "1 s", "1sec",
        ] {
            assert_eq!(
                pattern.is_match(text),
                parse_duration(text).is_some(),
                "{text}"
            );
        }
    }
}