encore/config.rs
1//! Application config: typed values a service reads, written in TOML or JSON
2//! files beside the code, and changed 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//! /// Most items one order may hold.
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//! The type is the schema. Encore reads it from the code — its fields, their
26//! types and serde attributes, the `#[config(...)]` constraints, the doc
27//! comments — and checks every value against it before the service sees it:
28//! as you edit a file under `encore run`, on a deploy, and as the service
29//! starts, which it refuses to do with a value it could not read. That is why
30//! [`Config::get`] cannot fail.
31//!
32//! # Scope
33//!
34//! Which of the three types a config is declared with says who it belongs to,
35//! as for [secrets](crate::secrets):
36//!
37//! - A [`Config`] belongs to the service that declares it. Two services may
38//! each declare one of the same name and hold different values in them. It
39//! must be declared inside a service.
40//! - A [`SharedConfig`] has one value for the whole app. Any service may read
41//! it, and each that does is recorded as using it.
42//! - A [`GlobalConfig`] has one value for the whole app and is available to
43//! every service, without being recorded.
44//!
45//! # Values
46//!
47//! A config's value is written in a file named after it — `checkout.config.toml`,
48//! or `.json` — beside the declaring service's `encore.service.json`,
49//! or beside `encore.app` for a shared or global config. Files over it change
50//! it for some environments only, and are merged onto it field by field
51//! (JSON Merge Patch: tables merge, anything else replaces, `null` deletes):
52//!
53//! ```text
54//! checkout.config.toml every environment
55//! checkout.production.config.toml environments of a type: local, test,
56//! development, preview, production
57//! checkout.@prod-eu.config.toml the environment named prod-eu
58//! checkout.user.config.toml your own values, on `encore run` only
59//! ```
60//!
61//! The last, the user override, is yours alone: keep it out of version
62//! control. It applies to your own `encore run` and never to tests. A field
63//! no file sets takes its default in code (`#[serde(default)]`, `Option`).
64//!
65//! # Snapshots and changes
66//!
67//! [`Config::get`] returns a [`Value`]: a snapshot of the value, cheap to make
68//! and to clone, that reads as the value itself. A config's value can change
69//! while the app runs — edit its file under `encore run` and the running
70//! service has the new value within a second, without a restart. A snapshot
71//! keeps the value it was made with, so hold one for as long as you need the
72//! value to be consistent (a request, say) and call `get` again for the next.
73//! Code that builds something from a config — a client, a pool — rebuilds it
74//! with [`Config::on_change`].
75//!
76//! # Secrets
77//!
78//! A field may read a secret rather than hold a value. The type names it:
79//!
80//! ```ignore
81//! #[derive(Deserialize, ConfigType)]
82//! struct Stripe {
83//! endpoint: String,
84//! #[config(secret = "StripeKey")]
85//! api_key: encore::secrets::Secret,
86//! }
87//!
88//! let key = CHECKOUT.get().stripe.api_key.value()?;
89//! ```
90//!
91//! The secret has the config's own scope: a [`Config`] reads its service's
92//! own secret, a [`SharedConfig`] a shared one, a [`GlobalConfig`] a global
93//! one. It is declared in code as any secret is (`Secret::new("StripeKey")` in
94//! the service, `SharedSecret::new`, `GlobalSecret::new`); one that isn't is an
95//! error. No config file sets the field; the secret holds the value, per
96//! environment as secrets do.
97//!
98//! # Tests
99//!
100//! Under `encore test` a config's value is what the files say for the `test`
101//! environment type. A test can give a config a value of its own, which no
102//! other test sees: [`testing::set_config`](crate::testing::set_config).
103
104use std::any::Any;
105use std::fmt;
106use std::marker::PhantomData;
107use std::ops::Deref;
108use std::sync::{Arc, OnceLock, RwLock};
109
110use encore_sdk_core::config as core_config;
111use serde::de::{DeserializeOwned, Deserializer, Error as _};
112use serde::Deserialize;
113
114use crate::runtime::core;
115use crate::testing;
116
117/// Derives [`ConfigType`](trait@ConfigType) for a type a config is declared
118/// with, and allows `#[config(...)]` on its fields:
119///
120/// - `min = N`, `max = N`: the least and greatest number allowed.
121/// - `min_len = N`, `max_len = N`: the fewest and most characters in a string.
122/// - `pattern = "regex"`: a regular expression a string must match.
123/// - `min_items = N`, `max_items = N`: the fewest and most items in a list.
124/// - `secret = "Name"`: the field reads this secret; see the [module
125/// documentation](self#secrets).
126pub use encore_macros::ConfigType;
127
128/// A type a config can be declared with. Derive it: `#[derive(ConfigType)]`,
129/// alongside serde's `Deserialize`.
130pub trait ConfigType: DeserializeOwned + Send + Sync + 'static {}
131
132#[doc(hidden)]
133pub mod __private {
134 pub use serde::de::DeserializeOwned;
135}
136
137/// A snapshot of a config's value, as it was when the snapshot was made.
138/// Reads as the value: `&*value`, or any of its fields directly.
139///
140/// Cheap to clone: the clones share the value.
141pub struct Value<T>(Arc<T>);
142
143impl<T> Deref for Value<T> {
144 type Target = T;
145
146 fn deref(&self) -> &T {
147 &self.0
148 }
149}
150
151impl<T> Clone for Value<T> {
152 fn clone(&self) -> Self {
153 Self(self.0.clone())
154 }
155}
156
157impl<T: fmt::Debug> fmt::Debug for Value<T> {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 self.0.fmt(f)
160 }
161}
162
163pub(crate) use sealed::Scope;
164
165/// What the three config types are: a name and scope, the runtime's config
166/// once looked up, and the value as last read.
167struct Inner<T> {
168 name: &'static str,
169 scope: Scope,
170 /// The runtime's config, looked up at first use: `None` when the runtime
171 /// config has no value for it.
172 handle: OnceLock<Option<Arc<core_config::Config>>>,
173 /// The value last read, with the revision it was read from.
174 current: RwLock<Option<(Arc<core_config::Revision>, Arc<T>)>>,
175 /// Read when the runtime has no value: the defaults in code.
176 defaults: OnceLock<Arc<T>>,
177 _type: PhantomData<fn() -> T>,
178}
179
180impl<T: ConfigType> Inner<T> {
181 const fn new(name: &'static str, scope: Scope) -> Self {
182 Self {
183 name,
184 scope,
185 handle: OnceLock::new(),
186 current: RwLock::new(None),
187 defaults: OnceLock::new(),
188 _type: PhantomData,
189 }
190 }
191
192 fn handle(&self) -> Option<&Arc<core_config::Config>> {
193 self.handle
194 .get_or_init(|| lookup(self.scope, self.name))
195 .as_ref()
196 }
197
198 fn get(&self) -> Value<T> {
199 // A test's own value for the config, if it set one.
200 if let Some(test) = testing::active().ok().flatten() {
201 if let Some(value) = test.config(self.scope, self.name) {
202 if let Ok(value) = value.downcast::<T>() {
203 return Value(value);
204 }
205 }
206 }
207
208 let Some(handle) = self.handle() else {
209 let value = self.defaults.get_or_init(|| {
210 match T::deserialize(&serde_json::Value::Object(Default::default())) {
211 Ok(value) => Arc::new(value),
212 Err(err) => panic!(
213 "config {:?} has no value, and its type has no defaults to fall back \
214 to: {err}",
215 self.name
216 ),
217 }
218 });
219 return Value(value.clone());
220 };
221
222 let revision = handle.current();
223 {
224 let current = self.current.read().unwrap_or_else(|e| e.into_inner());
225 if let Some((read_from, value)) = current.as_ref() {
226 if Arc::ptr_eq(read_from, &revision) {
227 return Value(value.clone());
228 }
229 }
230 }
231 let value = Arc::new(read::<T>(self.name, &revision.value));
232 let mut current = self.current.write().unwrap_or_else(|e| e.into_inner());
233 // Another thread may have read the same revision meanwhile: one
234 // revision is one snapshot, so keep the one already handed out.
235 if let Some((read_from, existing)) = current.as_ref() {
236 if Arc::ptr_eq(read_from, &revision) {
237 return Value(existing.clone());
238 }
239 }
240 *current = Some((revision, value.clone()));
241 Value(value)
242 }
243
244 fn on_change(&self, f: impl Fn(Value<T>) + Send + Sync + 'static) {
245 let Some(handle) = self.handle().cloned() else {
246 // Nothing gives it a new value.
247 return;
248 };
249 let name = self.name;
250 // Sees the value now as seen: only what comes after is a change.
251 let mut changes = handle.subscribe();
252 core().tokio_handle().spawn(async move {
253 while changes.changed().await.is_ok() {
254 // The revision the change is, marked seen: never the value
255 // now, which may be a later one that would come again.
256 let revision = changes.borrow_and_update().clone();
257 f(Value(Arc::new(read::<T>(name, &revision.value))));
258 }
259 });
260 }
261}
262
263/// Reads a value the runtime has checked against the schema. Failing here is
264/// Encore's bug: the schema it derived from the type accepted a value serde
265/// does not.
266fn read<T: ConfigType>(name: &str, value: &serde_json::Value) -> T {
267 T::deserialize(value).unwrap_or_else(|err| {
268 panic!(
269 "config {name:?}: the value satisfies the schema Encore derived from `{}`, but serde \
270 could not read it: {err}. This is a bug in Encore: please report it",
271 std::any::type_name::<T>()
272 )
273 })
274}
275
276/// The runtime's config of this scope and name.
277fn lookup(scope: Scope, name: &str) -> Option<Arc<core_config::Config>> {
278 let configs = core().configs();
279 match scope {
280 Scope::Service => configs.service_config(name),
281 Scope::App => configs.shared_config(name),
282 }
283}
284
285macro_rules! config_type {
286 ($(#[$doc:meta])* $name:ident, $scope:expr) => {
287 $(#[$doc])*
288 pub struct $name<T>(Inner<T>);
289
290 impl<T: ConfigType> $name<T> {
291 /// Declare a config by name. `const` so it can initialize a
292 /// module-scope `static`; nothing is read until its value is
293 /// asked for.
294 pub const fn new(name: &'static str) -> Self {
295 Self(Inner::new(name, $scope))
296 }
297
298 /// The name the config was declared with.
299 pub const fn name(&self) -> &'static str {
300 self.0.name
301 }
302
303 /// The config's value now: see [`Value`].
304 pub fn get(&self) -> Value<T> {
305 self.0.get()
306 }
307
308 /// Calls `f` with each new value the config is given while the
309 /// process runs, from now on. Values that come faster than `f`
310 /// is called are coalesced: `f` gets the latest, once. `f` runs
311 /// on the runtime's threads: keep it quick, and spawn anything
312 /// that waits.
313 pub fn on_change(&self, f: impl Fn(Value<T>) + Send + Sync + 'static) {
314 self.0.on_change(f)
315 }
316 }
317
318 impl<T> sealed::Sealed for $name<T> {
319 fn key(&self) -> (Scope, &'static str) {
320 (self.0.scope, self.0.name)
321 }
322 }
323
324 impl<T: ConfigType> AnyConfig<T> for $name<T> {}
325 };
326}
327
328config_type!(
329 /// A config belonging to the service that declares it, which holds its own
330 /// value for it. Must be declared inside a service.
331 Config,
332 Scope::Service
333);
334
335config_type!(
336 /// A config with one value for the whole app. A service that reads it is
337 /// recorded as using it.
338 SharedConfig,
339 Scope::App
340);
341
342config_type!(
343 /// A config with one value for the whole app, available to every service
344 /// without being recorded.
345 GlobalConfig,
346 Scope::App
347);
348
349mod sealed {
350 /// Who a config belongs to.
351 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
352 pub enum Scope {
353 /// One value for the app: a `SharedConfig` or a `GlobalConfig`.
354 App,
355 /// The declaring service's own: a `Config`.
356 Service,
357 }
358
359 pub trait Sealed {
360 fn key(&self) -> (Scope, &'static str);
361 }
362}
363
364/// Any of the config types, of a value type `T`. Sealed: [`Config`],
365/// [`SharedConfig`] and [`GlobalConfig`] are the only ones.
366pub trait AnyConfig<T>: sealed::Sealed {}
367
368/// The scope and name a config is held under.
369pub(crate) fn key_of<T>(config: &impl AnyConfig<T>) -> (Scope, &'static str) {
370 config.key()
371}
372
373/// Checks a test's value for a config and reads it as `T`, as the runtime
374/// would a value of its own: for [`testing::set_config`].
375pub(crate) fn test_value<T: ConfigType>(
376 config: &impl AnyConfig<T>,
377 mut value: serde_json::Value,
378) -> Result<Arc<dyn Any + Send + Sync>, crate::Error> {
379 let (scope, name) = key_of(config);
380 if let Some(handle) = lookup(scope, name) {
381 value = handle.prepare(value).map_err(|errors| {
382 crate::Error::invalid_argument(format!(
383 "the value for config {name:?} does not satisfy its schema: {}",
384 errors.join("; ")
385 ))
386 })?;
387 }
388 let value = T::deserialize(&value).map_err(|err| {
389 crate::Error::invalid_argument(format!(
390 "the value for config {name:?} could not be read: {err}"
391 ))
392 })?;
393 Ok(Arc::new(value))
394}
395
396/// A length of time, written in a config as a number and a unit, or several:
397/// `"30s"`, `"250ms"`, `"1h30m"`, `"1.5h"`. The units are `ns`, `us` (or
398/// `µs`), `ms`, `s`, `m` and `h`. Reads as a [`std::time::Duration`].
399#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
400pub struct Duration(pub std::time::Duration);
401
402impl Deref for Duration {
403 type Target = std::time::Duration;
404
405 fn deref(&self) -> &std::time::Duration {
406 &self.0
407 }
408}
409
410impl From<Duration> for std::time::Duration {
411 fn from(d: Duration) -> Self {
412 d.0
413 }
414}
415
416impl<'de> Deserialize<'de> for Duration {
417 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
418 let text = String::deserialize(deserializer)?;
419 parse_duration(&text).map(Duration).ok_or_else(|| {
420 D::Error::custom(format!(
421 "{text:?} is not a duration, such as \"30s\", \"250ms\" or \"1h30m\""
422 ))
423 })
424 }
425}
426
427/// Parses what `encore_appconfig::schema::DURATION_PATTERN` matches: one or
428/// more numbers, each with a unit. `None` for anything else, or a duration
429/// too long to hold.
430pub(crate) fn parse_duration(text: &str) -> Option<std::time::Duration> {
431 const UNITS: [(&str, u128); 7] = [
432 ("ns", 1),
433 ("us", 1_000),
434 ("µs", 1_000),
435 ("ms", 1_000_000),
436 ("s", 1_000_000_000),
437 ("m", 60_000_000_000),
438 ("h", 3_600_000_000_000),
439 ];
440 if text.is_empty() {
441 return None;
442 }
443 let mut rest = text;
444 let mut nanos: u128 = 0;
445 while !rest.is_empty() {
446 let whole_len = rest.bytes().take_while(u8::is_ascii_digit).count();
447 if whole_len == 0 {
448 return None;
449 }
450 let whole: u128 = rest[..whole_len].parse().ok()?;
451 rest = &rest[whole_len..];
452 let mut fraction = "";
453 if let Some(after) = rest.strip_prefix('.') {
454 let len = after.bytes().take_while(u8::is_ascii_digit).count();
455 if len == 0 {
456 return None;
457 }
458 fraction = &after[..len];
459 rest = &after[len..];
460 }
461 // The longest unit that matches: `ms` before `m`.
462 let (unit, scale) = UNITS
463 .iter()
464 .filter(|(u, _)| rest.starts_with(u))
465 .max_by_key(|(u, _)| u.len())?;
466 rest = &rest[unit.len()..];
467 let mut part = whole.checked_mul(*scale)?;
468 if !fraction.is_empty() {
469 // Precision past the nanosecond is dropped. 24 digits are past the
470 // nanosecond of an hour, as the validator keeps, and their
471 // numerator times an hour's nanoseconds still fits a u128.
472 let digits = &fraction[..fraction.len().min(24)];
473 let numerator: u128 = digits.parse().ok()?;
474 let denominator = 10u128.checked_pow(digits.len() as u32)?;
475 part = part.checked_add(numerator.checked_mul(*scale)? / denominator)?;
476 }
477 nanos = nanos.checked_add(part)?;
478 }
479 let secs = u64::try_from(nanos / 1_000_000_000).ok()?;
480 Some(std::time::Duration::new(
481 secs,
482 (nanos % 1_000_000_000) as u32,
483 ))
484}
485
486#[cfg(test)]
487mod tests {
488 use std::time::Duration as D;
489
490 use super::*;
491
492 #[test]
493 fn durations_parse_as_go_writes_them() {
494 let ok = [
495 ("0s", D::ZERO),
496 ("30s", D::from_secs(30)),
497 ("250ms", D::from_millis(250)),
498 ("1h30m", D::from_secs(5400)),
499 ("1.5h", D::from_secs(5400)),
500 // Digits past the nanosecond don't overflow the arithmetic.
501 ("1.000000000000000000000000001h", D::from_secs(3600)),
502 ("10us", D::from_micros(10)),
503 ("10µs", D::from_micros(10)),
504 ("7ns", D::from_nanos(7)),
505 ("2m3.5s", D::from_millis(123_500)),
506 ("1h1m1s1ms1us1ns", D::new(3661, 1_001_001)),
507 ("0.000000001s", D::from_nanos(1)),
508 ];
509 for (text, want) in ok {
510 assert_eq!(parse_duration(text), Some(want), "{text}");
511 }
512 let bad = [
513 "",
514 "30",
515 "s",
516 "-1s",
517 "+1s",
518 "1.s",
519 ".5s",
520 "1 s",
521 "1d",
522 "1sec",
523 "1h 30m",
524 "1S",
525 "99999999999999999999h",
526 ];
527 for text in bad {
528 assert_eq!(parse_duration(text), None, "{text}");
529 }
530 }
531
532 /// What the schema's pattern accepts, `Duration` reads, and the other way
533 /// around.
534 #[test]
535 fn durations_agree_with_the_schema_pattern() {
536 let pattern = regex::Regex::new(encore_sdk_core::config::DURATION_PATTERN).unwrap();
537 for text in [
538 "30s", "250ms", "1h30m", "1.5h", "10µs", "2m3.5s", "", "30", "-1s", "1.s", ".5s", "1d",
539 "1S", "1 s", "1sec",
540 ] {
541 assert_eq!(
542 pattern.is_match(text),
543 parse_duration(text).is_some(),
544 "{text}"
545 );
546 }
547 }
548}