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