encore-dev 2.0.0-beta.16

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
//! Application configuration: typed values read by a service, defined in TOML or JSON
//! files beside the code and updated dynamically while the app runs.
//!
//! ```ignore
//! use encore::config::{Config, ConfigType, Duration};
//! use serde::Deserialize;
//!
//! #[derive(Deserialize, ConfigType)]
//! struct Checkout {
//!     /// Maximum number of items allowed in a single order.
//!     #[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
//! }
//! ```
//!
//! Your Rust type defines the schema. Encore extracts it from the source code —
//! including fields, types, Serde attributes, `#[config(...)]` constraints, and doc
//! comments — and validates every value before the service sees it. Validation runs
//! when you edit a file under `encore run`, during deployment, and at service startup
//! (the service refuses to start with an invalid config). Because of this,
//! [`Config::get`] cannot fail.
//!
//! # Scope
//!
//! A config's declaration determines which services can access it, just like
//! [secrets](crate::secrets#scope):
//!
//! - `Config::new("checkout")` belongs to the service that declares it. Two
//!   services can each declare a config with the same name and hold separate values.
//!   It must be declared inside a service.
//! - `Config::new("checkout").shared()` defines a single app-wide value. Any
//!   service may read it, and each service that does is recorded as using it.
//! - `Config::new("checkout").global()` defines a single app-wide value available
//!   to every service without tracking per-service usage.
//!
//! A config name has a single scope across the app, just like a secret: a name
//! declared as shared or global cannot also be declared as a service-scoped config.
//!
//! Both the name and scope must be written directly in the declaration so Encore can
//! parse them statically.
//!
//! # Values
//!
//! Config values live in a file named after the config — `checkout.config.toml` or
//! `checkout.config.json` — next to the declaring service's `encore.service.json`
//! (or next to `encore.app.json` for shared or global configs). Environment-specific
//! overlay files are merged on top field by field using JSON Merge Patch (tables
//! merge, other values replace, and `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 local overrides, applied on `encore run` only
//! ```
//!
//! Keep user override files out of version control; they apply only to your local
//! `encore run` sessions and never to tests. Any field not set in a config file uses
//! its code default (`#[serde(default)]` or `Option`).
//!
//! # Snapshots and live updates
//!
//! [`Config::get`] returns a [`Value`], which is a cheap-to-clone snapshot that
//! dereferences to `T`. Config values can change while the app is running — editing
//! a config file under `encore run` pushes the new value to the service within a
//! second without restarting. Because each snapshot preserves the value from when it
//! was created, hold onto one for as long as you need consistency (for example,
//! across a single request) and call `get` again for the next. To rebuild derived
//! objects like clients or connection pools on updates, register a callback with
//! [`Config::on_change`].
//!
//! # Secrets
//!
//! A config field can reference a secret instead of holding a plain value:
//!
//! ```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 referenced secret must share the config's scope: a service config reads a
//! service secret, a shared config reads a shared secret, and a global config reads
//! a global secret. The secret must be declared in code like any other secret
//! (`Secret::new("StripeKey")` in the service, or with `.shared()` / `.global()`
//! for app-wide secrets); referencing an undeclared secret is an error. Do not set
//! secret fields in config files — their values are managed per environment as
//! secrets.
//!
//! # Tests
//!
//! Under `encore test`, configs load values from the `test` environment overlay.
//! Individual tests can override a config value in isolation using
//! [`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 config struct or enum, and
/// enables `#[config(...)]` validation attributes on its fields:
///
/// - `min = N`, `max = N`: minimum and maximum allowed numeric values.
/// - `min_len = N`, `max_len = N`: minimum and maximum string length in characters.
/// - `pattern = "regex"`: regular expression that a string must match.
/// - `min_items = N`, `max_items = N`: minimum and maximum number of items in a list.
/// - `secret = "Name"`: binds the field to a declared secret; see the
///   [module documentation](self#secrets).
pub use encore_macros::ConfigType;

/// Marker trait for types that can be used with [`Config`].
///
/// Derive it with `#[derive(ConfigType)]` alongside Serde's `Deserialize`.
pub trait ConfigType: DeserializeOwned + Send + Sync + 'static {}

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

/// An immutable snapshot of a config's value at the time it was read.
///
/// Dereferences to `T` so you can access fields directly. Cloning is cheap and
/// shares the underlying 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 configured 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:?}: value matched the schema Encore derived from `{}`, but Serde \
             failed to deserialize 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 typed configuration handle declared as a module-level `static`:
/// `static CHECKOUT: Config<Checkout> = Config::new("checkout");`.
///
/// See the [module documentation](self) for schema rules, file layouts, and live
/// updates. By default [`Config::new`] declares a service-scoped config; call
/// [`shared`](Self::shared) or [`global`](Self::global) for app-wide scope.
pub struct Config<T>(Inner<T>);

impl<T: ConfigType> Config<T> {
    /// Declares a config with the given `name`.
    ///
    /// This constructor is `const` so it can initialize a module-scope `static`,
    /// and nothing is read until [`get`](Self::get) is called. `name` must be a
    /// string literal so Encore can parse it statically.
    pub const fn new(name: &'static str) -> Self {
        Self(Inner::new(name))
    }

    /// Declares the config with shared app-wide scope rather than service scope.
    ///
    /// Any service may read a shared config, and each service that does is
    /// recorded as using it. See [scope](self#scope).
    pub const fn shared(self) -> Self {
        self
    }

    /// Declares the config with global app-wide scope, making it available to
    /// every service without tracking per-service usage. See [scope](self#scope).
    pub const fn global(self) -> Self {
        self
    }

    /// Attaches a key/value tag to the config (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 config may have at most 32 tags.
    ///
    /// ```ignore
    /// static CHECKOUT: Config<Checkout> = Config::new("checkout").tag("team", "payments");
    /// ```
    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
        self
    }

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

    /// Returns a snapshot of the config's current value. See [`Value`].
    pub fn get(&self) -> Value<T> {
        self.0.get()
    }

    /// Registers a callback `f` invoked whenever the config value changes while
    /// the process is running.
    ///
    /// Rapid consecutive updates are coalesced so `f` receives the latest value.
    /// Callbacks run on the runtime's threads, so keep `f` fast and spawn async
    /// tasks for any blocking or I/O work.
    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!(
            "failed to deserialize value for config {name:?}: {err}"
        ))
    })?;
    Ok(Arc::new(value))
}

/// A duration parsed from human-readable config strings such as `"30s"`,
/// `"250ms"`, `"1h30m"`, or `"1.5h"`.
///
/// Supported units are `ns`, `us` (or `µs`), `ms`, `s`, `m`, and `h`.
/// Dereferences to [`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 valid duration (expected values like \"30s\", \"250ms\", or \"1h30m\")"
            ))
        })
    }
}

/// Serializes as a whole number of microseconds (for example, `"1500000us"`),
/// preserving microsecond precision when round-tripped.
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}"
            );
        }
    }
}