encore-dev 2.0.0-beta.5

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
//! 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
//!
//! Which of the three types a config is declared with says who it belongs to,
//! as for [secrets](crate::secrets):
//!
//! - A [`Config`] 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.
//! - A [`SharedConfig`] has one value for the whole app. Any service may read
//!   it, and each that does is recorded as using it.
//! - A [`GlobalConfig`] has one value for the whole app and is available to
//!   every service, without being recorded.
//!
//! # 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 [`Config`] reads its service's
//! own secret, a [`SharedConfig`] a shared one, a [`GlobalConfig`] a global
//! one. It is declared in code as any secret is (`Secret::new("StripeKey")` in
//! the service, `SharedSecret::new`, `GlobalSecret::new`); 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;

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)
    }
}

pub(crate) use sealed::Scope;

/// What the three config types are: a name and scope, the runtime's config
/// once looked up, and the value as last read.
struct Inner<T> {
    name: &'static str,
    scope: Scope,
    /// 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, scope: Scope) -> Self {
        Self {
            name,
            scope,
            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.scope, 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.scope, 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 scope and name.
fn lookup(scope: Scope, name: &str) -> Option<Arc<core_config::Config>> {
    let configs = core().configs();
    match scope {
        Scope::Service => configs.service_config(name),
        Scope::App => configs.shared_config(name),
    }
}

macro_rules! config_type {
    ($(#[$doc:meta])* $name:ident, $scope:expr) => {
        $(#[$doc])*
        pub struct $name<T>(Inner<T>);

        impl<T: ConfigType> $name<T> {
            /// Declare a config by name. `const` so it can initialize a
            /// module-scope `static`; nothing is read until its value is
            /// asked for.
            pub const fn new(name: &'static str) -> Self {
                Self(Inner::new(name, $scope))
            }

            /// 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)
            }
        }

        impl<T> sealed::Sealed for $name<T> {
            fn key(&self) -> (Scope, &'static str) {
                (self.0.scope, self.0.name)
            }
        }

        impl<T: ConfigType> AnyConfig<T> for $name<T> {}
    };
}

config_type!(
    /// A config belonging to the service that declares it, which holds its own
    /// value for it. Must be declared inside a service.
    Config,
    Scope::Service
);

config_type!(
    /// A config with one value for the whole app. A service that reads it is
    /// recorded as using it.
    SharedConfig,
    Scope::App
);

config_type!(
    /// A config with one value for the whole app, available to every service
    /// without being recorded.
    GlobalConfig,
    Scope::App
);

mod sealed {
    /// Who a config belongs to.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum Scope {
        /// One value for the app: a `SharedConfig` or a `GlobalConfig`.
        App,
        /// The declaring service's own: a `Config`.
        Service,
    }

    pub trait Sealed {
        fn key(&self) -> (Scope, &'static str);
    }
}

/// Any of the config types, of a value type `T`. Sealed: [`Config`],
/// [`SharedConfig`] and [`GlobalConfig`] are the only ones.
pub trait AnyConfig<T>: sealed::Sealed {}

/// The scope and name a config is held under.
pub(crate) fn key_of<T>(config: &impl AnyConfig<T>) -> (Scope, &'static str) {
    config.key()
}

/// Checks a test's value for a config and reads it as `T`, as the runtime
/// would a value of its own: for [`testing::set_config`].
pub(crate) fn test_value<T: ConfigType>(
    config: &impl AnyConfig<T>,
    mut value: serde_json::Value,
) -> Result<Arc<dyn Any + Send + Sync>, crate::Error> {
    let (scope, name) = key_of(config);
    if let Some(handle) = lookup(scope, name) {
        value = handle.prepare(value).map_err(|errors| {
            crate::Error::invalid_argument(format!(
                "the value for config {name:?} does not satisfy its schema: {}",
                errors.join("; ")
            ))
        })?;
    }
    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\""
            ))
        })
    }
}

/// 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}"
            );
        }
    }
}