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 if let Some(value) = test.config(self.name) {
205 if let Ok(value) = value.downcast::<T>() {
206 return Value(value);
207 }
208 }
209 }
210
211 let Some(handle) = self.handle() else {
212 let value = self.defaults.get_or_init(|| {
213 match T::deserialize(&serde_json::Value::Object(Default::default())) {
214 Ok(value) => Arc::new(value),
215 Err(err) => panic!(
216 "config {:?} has no configured value and its type has no defaults to fall \
217 back to: {err}",
218 self.name
219 ),
220 }
221 });
222 return Value(value.clone());
223 };
224
225 let revision = handle.current();
226 {
227 let current = self.current.read().unwrap_or_else(|e| e.into_inner());
228 if let Some((read_from, value)) = current.as_ref() {
229 if Arc::ptr_eq(read_from, &revision) {
230 return Value(value.clone());
231 }
232 }
233 }
234 let value = Arc::new(read::<T>(self.name, &revision.value));
235 let mut current = self.current.write().unwrap_or_else(|e| e.into_inner());
236 // Another thread may have read the same revision meanwhile: one
237 // revision is one snapshot, so keep the one already handed out.
238 if let Some((read_from, existing)) = current.as_ref() {
239 if Arc::ptr_eq(read_from, &revision) {
240 return Value(existing.clone());
241 }
242 }
243 *current = Some((revision, value.clone()));
244 Value(value)
245 }
246
247 fn on_change(&self, f: impl Fn(Value<T>) + Send + Sync + 'static) {
248 let Some(handle) = self.handle().cloned() else {
249 // Nothing gives it a new value.
250 return;
251 };
252 let name = self.name;
253 // Sees the value now as seen: only what comes after is a change.
254 let mut changes = handle.subscribe();
255 core().tokio_handle().spawn(async move {
256 while changes.changed().await.is_ok() {
257 // The revision the change is, marked seen: never the value
258 // now, which may be a later one that would come again.
259 let revision = changes.borrow_and_update().clone();
260 f(Value(Arc::new(read::<T>(name, &revision.value))));
261 }
262 });
263 }
264}
265
266/// Reads a value the runtime has checked against the schema. Failing here is
267/// Encore's bug: the schema it derived from the type accepted a value serde
268/// does not.
269fn read<T: ConfigType>(name: &str, value: &serde_json::Value) -> T {
270 T::deserialize(value).unwrap_or_else(|err| {
271 panic!(
272 "config {name:?}: value matched the schema Encore derived from `{}`, but Serde \
273 failed to deserialize it: {err}. This is a bug in Encore; please report it.",
274 std::any::type_name::<T>()
275 )
276 })
277}
278
279/// The runtime's config of this name, whatever its scope.
280fn lookup(name: &str) -> Option<Arc<core_config::Config>> {
281 core().configs().get(name)
282}
283
284/// A typed configuration handle declared as a module-level `static`:
285/// `static CHECKOUT: Config<Checkout> = Config::new("checkout");`.
286///
287/// See the [module documentation](self) for schema rules, file layouts, and live
288/// updates. By default [`Config::new`] declares a service-scoped config; call
289/// [`shared`](Self::shared) or [`global`](Self::global) for app-wide scope.
290pub struct Config<T>(Inner<T>);
291
292impl<T: ConfigType> Config<T> {
293 /// Declares a config with the given `name`.
294 ///
295 /// This constructor is `const` so it can initialize a module-scope `static`,
296 /// and nothing is read until [`get`](Self::get) is called. `name` must be a
297 /// string literal so Encore can parse it statically.
298 pub const fn new(name: &'static str) -> Self {
299 Self(Inner::new(name))
300 }
301
302 /// Declares the config with shared app-wide scope rather than service scope.
303 ///
304 /// Any service may read a shared config, and each service that does is
305 /// recorded as using it. See [scope](self#scope).
306 pub const fn shared(self) -> Self {
307 self
308 }
309
310 /// Declares the config with global app-wide scope, making it available to
311 /// every service without tracking per-service usage. See [scope](self#scope).
312 pub const fn global(self) -> Self {
313 self
314 }
315
316 /// Attaches a key/value tag to the config (for example, `.tag("data", "pci")`)
317 /// for policy and governance tooling.
318 ///
319 /// Call once per tag with unique keys. Both `key` and `value` must be string
320 /// literals so Encore can parse them statically. Keys must start with a letter,
321 /// contain only lowercase letters, digits, `_`, and `-`, and must not start
322 /// with `encore` (reserved for Encore's own tags). Values use the same
323 /// character set or may be empty. Each key and value is at most 63 characters,
324 /// and a config may have at most 32 tags.
325 ///
326 /// ```ignore
327 /// static CHECKOUT: Config<Checkout> = Config::new("checkout").tag("team", "payments");
328 /// ```
329 pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
330 self
331 }
332
333 /// Returns the name this config was declared with.
334 pub const fn name(&self) -> &'static str {
335 self.0.name
336 }
337
338 /// Returns a snapshot of the config's current value. See [`Value`].
339 pub fn get(&self) -> Value<T> {
340 self.0.get()
341 }
342
343 /// Registers a callback `f` invoked whenever the config value changes while
344 /// the process is running.
345 ///
346 /// Rapid consecutive updates are coalesced so `f` receives the latest value.
347 /// Callbacks run on the runtime's threads, so keep `f` fast and spawn async
348 /// tasks for any blocking or I/O work.
349 pub fn on_change(&self, f: impl Fn(Value<T>) + Send + Sync + 'static) {
350 self.0.on_change(f)
351 }
352
353 /// The name the config is held under: a config name has one scope across
354 /// the app.
355 pub(crate) fn key(&self) -> &'static str {
356 self.0.name
357 }
358}
359
360/// Reads a test's value for the config `name` as `T`, once the core has
361/// checked it against the config's schema, as the runtime would a value of its
362/// own: for [`testing::set_config`].
363pub(crate) fn test_value<T: ConfigType>(
364 name: &str,
365 value: serde_json::Value,
366) -> Result<Arc<dyn Any + Send + Sync>, crate::Error> {
367 let value = T::deserialize(&value).map_err(|err| {
368 crate::Error::invalid_argument(format!(
369 "failed to deserialize value for config {name:?}: {err}"
370 ))
371 })?;
372 Ok(Arc::new(value))
373}
374
375/// A duration parsed from human-readable config strings such as `"30s"`,
376/// `"250ms"`, `"1h30m"`, or `"1.5h"`.
377///
378/// Supported units are `ns`, `us` (or `µs`), `ms`, `s`, `m`, and `h`.
379/// Dereferences to [`std::time::Duration`].
380#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
381pub struct Duration(pub std::time::Duration);
382
383impl Deref for Duration {
384 type Target = std::time::Duration;
385
386 fn deref(&self) -> &std::time::Duration {
387 &self.0
388 }
389}
390
391impl From<Duration> for std::time::Duration {
392 fn from(d: Duration) -> Self {
393 d.0
394 }
395}
396
397impl<'de> Deserialize<'de> for Duration {
398 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
399 let text = String::deserialize(deserializer)?;
400 parse_duration(&text).map(Duration).ok_or_else(|| {
401 D::Error::custom(format!(
402 "{text:?} is not a valid duration (expected values like \"30s\", \"250ms\", or \"1h30m\")"
403 ))
404 })
405 }
406}
407
408/// Serializes as a whole number of microseconds (for example, `"1500000us"`),
409/// preserving microsecond precision when round-tripped.
410impl Serialize for Duration {
411 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
412 serializer.serialize_str(&format!("{}us", self.0.as_micros()))
413 }
414}
415
416/// Parses what `encore_appconfig::schema::DURATION_PATTERN` matches: one or
417/// more numbers, each with a unit. `None` for anything else, or a duration
418/// too long to hold.
419pub(crate) fn parse_duration(text: &str) -> Option<std::time::Duration> {
420 const UNITS: [(&str, u128); 7] = [
421 ("ns", 1),
422 ("us", 1_000),
423 ("µs", 1_000),
424 ("ms", 1_000_000),
425 ("s", 1_000_000_000),
426 ("m", 60_000_000_000),
427 ("h", 3_600_000_000_000),
428 ];
429 if text.is_empty() {
430 return None;
431 }
432 let mut rest = text;
433 let mut nanos: u128 = 0;
434 while !rest.is_empty() {
435 let whole_len = rest.bytes().take_while(u8::is_ascii_digit).count();
436 if whole_len == 0 {
437 return None;
438 }
439 let whole: u128 = rest[..whole_len].parse().ok()?;
440 rest = &rest[whole_len..];
441 let mut fraction = "";
442 if let Some(after) = rest.strip_prefix('.') {
443 let len = after.bytes().take_while(u8::is_ascii_digit).count();
444 if len == 0 {
445 return None;
446 }
447 fraction = &after[..len];
448 rest = &after[len..];
449 }
450 // The longest unit that matches: `ms` before `m`.
451 let (unit, scale) = UNITS
452 .iter()
453 .filter(|(u, _)| rest.starts_with(u))
454 .max_by_key(|(u, _)| u.len())?;
455 rest = &rest[unit.len()..];
456 let mut part = whole.checked_mul(*scale)?;
457 if !fraction.is_empty() {
458 // Precision past the nanosecond is dropped. 24 digits are past the
459 // nanosecond of an hour, as the validator keeps, and their
460 // numerator times an hour's nanoseconds still fits a u128.
461 let digits = &fraction[..fraction.len().min(24)];
462 let numerator: u128 = digits.parse().ok()?;
463 let denominator = 10u128.checked_pow(digits.len() as u32)?;
464 part = part.checked_add(numerator.checked_mul(*scale)? / denominator)?;
465 }
466 nanos = nanos.checked_add(part)?;
467 }
468 let secs = u64::try_from(nanos / 1_000_000_000).ok()?;
469 Some(std::time::Duration::new(
470 secs,
471 (nanos % 1_000_000_000) as u32,
472 ))
473}
474
475#[cfg(test)]
476mod tests {
477 use std::time::Duration as D;
478
479 use super::*;
480
481 #[test]
482 fn durations_parse_as_go_writes_them() {
483 let ok = [
484 ("0s", D::ZERO),
485 ("30s", D::from_secs(30)),
486 ("250ms", D::from_millis(250)),
487 ("1h30m", D::from_secs(5400)),
488 ("1.5h", D::from_secs(5400)),
489 // Digits past the nanosecond don't overflow the arithmetic.
490 ("1.000000000000000000000000001h", D::from_secs(3600)),
491 ("10us", D::from_micros(10)),
492 ("10µs", D::from_micros(10)),
493 ("7ns", D::from_nanos(7)),
494 ("2m3.5s", D::from_millis(123_500)),
495 ("1h1m1s1ms1us1ns", D::new(3661, 1_001_001)),
496 ("0.000000001s", D::from_nanos(1)),
497 ];
498 for (text, want) in ok {
499 assert_eq!(parse_duration(text), Some(want), "{text}");
500 }
501 let bad = [
502 "",
503 "30",
504 "s",
505 "-1s",
506 "+1s",
507 "1.s",
508 ".5s",
509 "1 s",
510 "1d",
511 "1sec",
512 "1h 30m",
513 "1S",
514 "99999999999999999999h",
515 ];
516 for text in bad {
517 assert_eq!(parse_duration(text), None, "{text}");
518 }
519 }
520
521 /// What the schema's pattern accepts, `Duration` reads, and the other way
522 /// around.
523 #[test]
524 fn durations_agree_with_the_schema_pattern() {
525 let pattern = regex::Regex::new(encore_sdk_core::config::DURATION_PATTERN).unwrap();
526 for text in [
527 "30s", "250ms", "1h30m", "1.5h", "10µs", "2m3.5s", "", "30", "-1s", "1.s", ".5s", "1d",
528 "1S", "1 s", "1sec",
529 ] {
530 assert_eq!(
531 pattern.is_match(text),
532 parse_duration(text).is_some(),
533 "{text}"
534 );
535 }
536 }
537}