Skip to main content

encore/
config.rs

1//! Application configuration: typed values read by a service, defined in TOML or JSON
2//! files beside the code and updated dynamically while the app runs.
3//!
4//! ```ignore
5//! use encore::config::{Config, ConfigType, Duration};
6//! use serde::Deserialize;
7//!
8//! #[derive(Deserialize, ConfigType)]
9//! struct Checkout {
10//!     /// Maximum number of items allowed in a single order.
11//!     #[config(min = 1, max = 500)]
12//!     max_items: u32,
13//!     #[serde(default)]
14//!     promo: Option<Promo>,
15//!     payment_timeout: Duration,
16//! }
17//!
18//! static CHECKOUT: Config<Checkout> = Config::new("checkout");
19//!
20//! fn too_many(items: usize) -> bool {
21//!     items > CHECKOUT.get().max_items as usize
22//! }
23//! ```
24//!
25//! Your Rust type defines the schema. Encore extracts it from the source code —
26//! including fields, types, Serde attributes, `#[config(...)]` constraints, and doc
27//! comments — and validates every value before the service sees it. Validation runs
28//! when you edit a file under `encore run`, during deployment, and at service startup
29//! (the service refuses to start with an invalid config). Because of this,
30//! [`Config::get`] cannot fail.
31//!
32//! # Scope
33//!
34//! A config's declaration determines which services can access it, just like
35//! [secrets](crate::secrets#scope):
36//!
37//! - `Config::new("checkout")` belongs to the service that declares it. Two
38//!   services can each declare a config with the same name and hold separate values.
39//!   It must be declared inside a service.
40//! - `Config::new("checkout").shared()` defines a single app-wide value. Any
41//!   service may read it, and each service that does is recorded as using it.
42//! - `Config::new("checkout").global()` defines a single app-wide value available
43//!   to every service without tracking per-service usage.
44//!
45//! A config name has a single scope across the app, just like a secret: a name
46//! declared as shared or global cannot also be declared as a service-scoped config.
47//!
48//! Both the name and scope must be written directly in the declaration so Encore can
49//! parse them statically.
50//!
51//! # Values
52//!
53//! Config values live in a file named after the config — `checkout.config.toml` or
54//! `checkout.config.json` — next to the declaring service's `encore.service.json`
55//! (or next to `encore.app.json` for shared or global configs). Environment-specific
56//! overlay files are merged on top field by field using JSON Merge Patch (tables
57//! merge, other values replace, and `null` deletes):
58//!
59//! ```text
60//! checkout.config.toml              every environment
61//! checkout.production.config.toml   environments of a type: local, test,
62//!                                   development, preview, production
63//! checkout.@prod-eu.config.toml     the environment named prod-eu
64//! checkout.user.config.toml         your local overrides, applied on `encore run` only
65//! ```
66//!
67//! Keep user override files out of version control; they apply only to your local
68//! `encore run` sessions and never to tests. Any field not set in a config file uses
69//! its code default (`#[serde(default)]` or `Option`).
70//!
71//! # Snapshots and live updates
72//!
73//! [`Config::get`] returns a [`Value`], which is a cheap-to-clone snapshot that
74//! dereferences to `T`. Config values can change while the app is running — editing
75//! a config file under `encore run` pushes the new value to the service within a
76//! second without restarting. Because each snapshot preserves the value from when it
77//! was created, hold onto one for as long as you need consistency (for example,
78//! across a single request) and call `get` again for the next. To rebuild derived
79//! objects like clients or connection pools on updates, register a callback with
80//! [`Config::on_change`].
81//!
82//! # Secrets
83//!
84//! A config field can reference a secret instead of holding a plain value:
85//!
86//! ```ignore
87//! #[derive(Deserialize, ConfigType)]
88//! struct Stripe {
89//!     endpoint: String,
90//!     #[config(secret = "StripeKey")]
91//!     api_key: encore::secrets::Secret,
92//! }
93//!
94//! let key = CHECKOUT.get().stripe.api_key.value();
95//! ```
96//!
97//! The referenced secret must share the config's scope: a service config reads a
98//! service secret, a shared config reads a shared secret, and a global config reads
99//! a global secret. The secret must be declared in code like any other secret
100//! (`Secret::new("StripeKey")` in the service, or with `.shared()` / `.global()`
101//! for app-wide secrets); referencing an undeclared secret is an error. Do not set
102//! secret fields in config files — their values are managed per environment as
103//! secrets.
104//!
105//! # Tests
106//!
107//! Under `encore test`, configs load values from the `test` environment overlay.
108//! Individual tests can override a config value in isolation using
109//! [`testing::set_config`](crate::testing::set_config).
110
111use std::any::Any;
112use std::fmt;
113use std::marker::PhantomData;
114use std::ops::Deref;
115use std::sync::{Arc, OnceLock, RwLock};
116
117use encore_sdk_core::config as core_config;
118use serde::de::{DeserializeOwned, Deserializer, Error as _};
119use serde::{Deserialize, Serialize, Serializer};
120
121use crate::runtime::core;
122use crate::testing;
123
124/// Derives [`ConfigType`](trait@ConfigType) for a config struct or enum, and
125/// enables `#[config(...)]` validation attributes on its fields:
126///
127/// - `min = N`, `max = N`: minimum and maximum allowed numeric values.
128/// - `min_len = N`, `max_len = N`: minimum and maximum string length in characters.
129/// - `pattern = "regex"`: regular expression that a string must match.
130/// - `min_items = N`, `max_items = N`: minimum and maximum number of items in a list.
131/// - `secret = "Name"`: binds the field to a declared secret; see the
132///   [module documentation](self#secrets).
133pub use encore_macros::ConfigType;
134
135/// Marker trait for types that can be used with [`Config`].
136///
137/// Derive it with `#[derive(ConfigType)]` alongside Serde's `Deserialize`.
138pub trait ConfigType: DeserializeOwned + Send + Sync + 'static {}
139
140#[doc(hidden)]
141pub mod __private {
142    pub use serde::de::DeserializeOwned;
143}
144
145/// An immutable snapshot of a config's value at the time it was read.
146///
147/// Dereferences to `T` so you can access fields directly. Cloning is cheap and
148/// shares the underlying value.
149pub struct Value<T>(Arc<T>);
150
151impl<T> Deref for Value<T> {
152    type Target = T;
153
154    fn deref(&self) -> &T {
155        &self.0
156    }
157}
158
159impl<T> Clone for Value<T> {
160    fn clone(&self) -> Self {
161        Self(self.0.clone())
162    }
163}
164
165impl<T: fmt::Debug> fmt::Debug for Value<T> {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        self.0.fmt(f)
168    }
169}
170
171/// What a [`Config`] is: a name, the runtime's config once looked up, and the
172/// value as last read. A config name has one scope across the app, so the name
173/// alone says which config the runtime holds.
174struct Inner<T> {
175    name: &'static str,
176    /// The runtime's config, looked up at first use: `None` when the runtime
177    /// config has no value for it.
178    handle: OnceLock<Option<Arc<core_config::Config>>>,
179    /// The value last read, with the revision it was read from.
180    current: RwLock<Option<(Arc<core_config::Revision>, Arc<T>)>>,
181    /// Read when the runtime has no value: the defaults in code.
182    defaults: OnceLock<Arc<T>>,
183    _type: PhantomData<fn() -> T>,
184}
185
186impl<T: ConfigType> Inner<T> {
187    const fn new(name: &'static str) -> Self {
188        Self {
189            name,
190            handle: OnceLock::new(),
191            current: RwLock::new(None),
192            defaults: OnceLock::new(),
193            _type: PhantomData,
194        }
195    }
196
197    fn handle(&self) -> Option<&Arc<core_config::Config>> {
198        self.handle.get_or_init(|| lookup(self.name)).as_ref()
199    }
200
201    fn get(&self) -> Value<T> {
202        // A test's own value for the config, if it set one.
203        if let Some(test) = testing::active().ok().flatten()
204            && let Some(value) = test.config(self.name)
205            && let Ok(value) = value.downcast::<T>()
206        {
207            return Value(value);
208        }
209
210        let Some(handle) = self.handle() else {
211            let value = self.defaults.get_or_init(|| {
212                match T::deserialize(&serde_json::Value::Object(Default::default())) {
213                    Ok(value) => Arc::new(value),
214                    Err(err) => panic!(
215                        "config {:?} has no configured value and its type has no defaults to fall \
216                         back to: {err}",
217                        self.name
218                    ),
219                }
220            });
221            return Value(value.clone());
222        };
223
224        let revision = handle.current();
225        {
226            let current = self.current.read().unwrap_or_else(|e| e.into_inner());
227            if let Some((read_from, value)) = current.as_ref()
228                && Arc::ptr_eq(read_from, &revision)
229            {
230                return Value(value.clone());
231            }
232        }
233        let value = Arc::new(read::<T>(self.name, &revision.value));
234        let mut current = self.current.write().unwrap_or_else(|e| e.into_inner());
235        // Another thread may have read the same revision meanwhile: one
236        // revision is one snapshot, so keep the one already handed out.
237        if let Some((read_from, existing)) = current.as_ref()
238            && Arc::ptr_eq(read_from, &revision)
239        {
240            return Value(existing.clone());
241        }
242        *current = Some((revision, value.clone()));
243        Value(value)
244    }
245
246    fn on_change(&self, f: impl Fn(Value<T>) + Send + Sync + 'static) {
247        let Some(handle) = self.handle().cloned() else {
248            // Nothing gives it a new value.
249            return;
250        };
251        let name = self.name;
252        // Sees the value now as seen: only what comes after is a change.
253        let mut changes = handle.subscribe();
254        core().tokio_handle().spawn(async move {
255            while changes.changed().await.is_ok() {
256                // The revision the change is, marked seen: never the value
257                // now, which may be a later one that would come again.
258                let revision = changes.borrow_and_update().clone();
259                f(Value(Arc::new(read::<T>(name, &revision.value))));
260            }
261        });
262    }
263}
264
265/// Reads a value the runtime has checked against the schema. Failing here is
266/// Encore's bug: the schema it derived from the type accepted a value serde
267/// does not.
268fn read<T: ConfigType>(name: &str, value: &serde_json::Value) -> T {
269    T::deserialize(value).unwrap_or_else(|err| {
270        panic!(
271            "config {name:?}: value matched the schema Encore derived from `{}`, but Serde \
272             failed to deserialize it: {err}. This is a bug in Encore; please report it.",
273            std::any::type_name::<T>()
274        )
275    })
276}
277
278/// The runtime's config of this name, whatever its scope.
279fn lookup(name: &str) -> Option<Arc<core_config::Config>> {
280    core().configs().get(name)
281}
282
283/// A typed configuration handle declared as a module-level `static`:
284/// `static CHECKOUT: Config<Checkout> = Config::new("checkout");`.
285///
286/// See the [module documentation](self) for schema rules, file layouts, and live
287/// updates. By default [`Config::new`] declares a service-scoped config; call
288/// [`shared`](Self::shared) or [`global`](Self::global) for app-wide scope.
289pub struct Config<T>(Inner<T>);
290
291impl<T: ConfigType> Config<T> {
292    /// Declares a config with the given `name`.
293    ///
294    /// This constructor is `const` so it can initialize a module-scope `static`,
295    /// and nothing is read until [`get`](Self::get) is called. `name` must be a
296    /// string literal so Encore can parse it statically.
297    pub const fn new(name: &'static str) -> Self {
298        Self(Inner::new(name))
299    }
300
301    /// Declares the config with shared app-wide scope rather than service scope.
302    ///
303    /// Any service may read a shared config, and each service that does is
304    /// recorded as using it. See [scope](self#scope).
305    pub const fn shared(self) -> Self {
306        self
307    }
308
309    /// Declares the config with global app-wide scope, making it available to
310    /// every service without tracking per-service usage. See [scope](self#scope).
311    pub const fn global(self) -> Self {
312        self
313    }
314
315    /// Attaches a key/value tag to the config (for example, `.tag("data", "pci")`)
316    /// for policy and governance tooling.
317    ///
318    /// Call once per tag with unique keys. Both `key` and `value` must be string
319    /// literals so Encore can parse them statically. Keys must start with a letter,
320    /// contain only lowercase letters, digits, `_`, and `-`, and must not start
321    /// with `encore` (reserved for Encore's own tags). Values use the same
322    /// character set or may be empty. Each key and value is at most 63 characters,
323    /// and a config may have at most 32 tags.
324    ///
325    /// ```ignore
326    /// static CHECKOUT: Config<Checkout> = Config::new("checkout").tag("team", "payments");
327    /// ```
328    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
329        self
330    }
331
332    /// Returns the name this config was declared with.
333    pub const fn name(&self) -> &'static str {
334        self.0.name
335    }
336
337    /// Returns a snapshot of the config's current value. See [`Value`].
338    pub fn get(&self) -> Value<T> {
339        self.0.get()
340    }
341
342    /// Registers a callback `f` invoked whenever the config value changes while
343    /// the process is running.
344    ///
345    /// Rapid consecutive updates are coalesced so `f` receives the latest value.
346    /// Callbacks run on the runtime's threads, so keep `f` fast and spawn async
347    /// tasks for any blocking or I/O work.
348    pub fn on_change(&self, f: impl Fn(Value<T>) + Send + Sync + 'static) {
349        self.0.on_change(f)
350    }
351
352    /// The name the config is held under: a config name has one scope across
353    /// the app.
354    pub(crate) fn key(&self) -> &'static str {
355        self.0.name
356    }
357}
358
359/// Reads a test's value for the config `name` as `T`, once the core has
360/// checked it against the config's schema, as the runtime would a value of its
361/// own: for [`testing::set_config`].
362pub(crate) fn test_value<T: ConfigType>(
363    name: &str,
364    value: serde_json::Value,
365) -> Result<Arc<dyn Any + Send + Sync>, crate::Error> {
366    let value = T::deserialize(&value).map_err(|err| {
367        crate::Error::invalid_argument(format!(
368            "failed to deserialize value for config {name:?}: {err}"
369        ))
370    })?;
371    Ok(Arc::new(value))
372}
373
374/// A duration parsed from human-readable config strings such as `"30s"`,
375/// `"250ms"`, `"1h30m"`, or `"1.5h"`.
376///
377/// Supported units are `ns`, `us` (or `µs`), `ms`, `s`, `m`, and `h`.
378/// Dereferences to [`std::time::Duration`].
379#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
380pub struct Duration(pub std::time::Duration);
381
382impl Deref for Duration {
383    type Target = std::time::Duration;
384
385    fn deref(&self) -> &std::time::Duration {
386        &self.0
387    }
388}
389
390impl From<Duration> for std::time::Duration {
391    fn from(d: Duration) -> Self {
392        d.0
393    }
394}
395
396impl<'de> Deserialize<'de> for Duration {
397    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
398        let text = String::deserialize(deserializer)?;
399        parse_duration(&text).map(Duration).ok_or_else(|| {
400            D::Error::custom(format!(
401                "{text:?} is not a valid duration (expected values like \"30s\", \"250ms\", or \"1h30m\")"
402            ))
403        })
404    }
405}
406
407/// Serializes as a whole number of microseconds (for example, `"1500000us"`),
408/// preserving microsecond precision when round-tripped.
409impl Serialize for Duration {
410    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
411        serializer.serialize_str(&format!("{}us", self.0.as_micros()))
412    }
413}
414
415/// Parses what `encore_appconfig::schema::DURATION_PATTERN` matches: one or
416/// more numbers, each with a unit. `None` for anything else, or a duration
417/// too long to hold.
418pub(crate) fn parse_duration(text: &str) -> Option<std::time::Duration> {
419    const UNITS: [(&str, u128); 7] = [
420        ("ns", 1),
421        ("us", 1_000),
422        ("µs", 1_000),
423        ("ms", 1_000_000),
424        ("s", 1_000_000_000),
425        ("m", 60_000_000_000),
426        ("h", 3_600_000_000_000),
427    ];
428    if text.is_empty() {
429        return None;
430    }
431    let mut rest = text;
432    let mut nanos: u128 = 0;
433    while !rest.is_empty() {
434        let whole_len = rest.bytes().take_while(u8::is_ascii_digit).count();
435        if whole_len == 0 {
436            return None;
437        }
438        let whole: u128 = rest[..whole_len].parse().ok()?;
439        rest = &rest[whole_len..];
440        let mut fraction = "";
441        if let Some(after) = rest.strip_prefix('.') {
442            let len = after.bytes().take_while(u8::is_ascii_digit).count();
443            if len == 0 {
444                return None;
445            }
446            fraction = &after[..len];
447            rest = &after[len..];
448        }
449        // The longest unit that matches: `ms` before `m`.
450        let (unit, scale) = UNITS
451            .iter()
452            .filter(|(u, _)| rest.starts_with(u))
453            .max_by_key(|(u, _)| u.len())?;
454        rest = &rest[unit.len()..];
455        let mut part = whole.checked_mul(*scale)?;
456        if !fraction.is_empty() {
457            // Precision past the nanosecond is dropped. 24 digits are past the
458            // nanosecond of an hour, as the validator keeps, and their
459            // numerator times an hour's nanoseconds still fits a u128.
460            let digits = &fraction[..fraction.len().min(24)];
461            let numerator: u128 = digits.parse().ok()?;
462            let denominator = 10u128.checked_pow(digits.len() as u32)?;
463            part = part.checked_add(numerator.checked_mul(*scale)? / denominator)?;
464        }
465        nanos = nanos.checked_add(part)?;
466    }
467    let secs = u64::try_from(nanos / 1_000_000_000).ok()?;
468    Some(std::time::Duration::new(
469        secs,
470        (nanos % 1_000_000_000) as u32,
471    ))
472}
473
474#[cfg(test)]
475mod tests {
476    use std::time::Duration as D;
477
478    use super::*;
479
480    #[test]
481    fn durations_parse_as_go_writes_them() {
482        let ok = [
483            ("0s", D::ZERO),
484            ("30s", D::from_secs(30)),
485            ("250ms", D::from_millis(250)),
486            ("1h30m", D::from_secs(5400)),
487            ("1.5h", D::from_secs(5400)),
488            // Digits past the nanosecond don't overflow the arithmetic.
489            ("1.000000000000000000000000001h", D::from_secs(3600)),
490            ("10us", D::from_micros(10)),
491            ("10µs", D::from_micros(10)),
492            ("7ns", D::from_nanos(7)),
493            ("2m3.5s", D::from_millis(123_500)),
494            ("1h1m1s1ms1us1ns", D::new(3661, 1_001_001)),
495            ("0.000000001s", D::from_nanos(1)),
496        ];
497        for (text, want) in ok {
498            assert_eq!(parse_duration(text), Some(want), "{text}");
499        }
500        let bad = [
501            "",
502            "30",
503            "s",
504            "-1s",
505            "+1s",
506            "1.s",
507            ".5s",
508            "1 s",
509            "1d",
510            "1sec",
511            "1h 30m",
512            "1S",
513            "99999999999999999999h",
514        ];
515        for text in bad {
516            assert_eq!(parse_duration(text), None, "{text}");
517        }
518    }
519
520    /// What the schema's pattern accepts, `Duration` reads, and the other way
521    /// around.
522    #[test]
523    fn durations_agree_with_the_schema_pattern() {
524        let pattern = regex::Regex::new(encore_sdk_core::config::DURATION_PATTERN).unwrap();
525        for text in [
526            "30s", "250ms", "1h30m", "1.5h", "10µs", "2m3.5s", "", "30", "-1s", "1.s", ".5s", "1d",
527            "1S", "1 s", "1sec",
528        ] {
529            assert_eq!(
530                pattern.is_match(text),
531                parse_duration(text).is_some(),
532                "{text}"
533            );
534        }
535    }
536}