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;
use crate::runtime::core;
use crate::testing;
pub use encore_macros::ConfigType;
pub trait ConfigType: DeserializeOwned + Send + Sync + 'static {}
#[doc(hidden)]
pub mod __private {
pub use serde::de::DeserializeOwned;
}
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)
}
}
pub(crate) use sealed::Scope;
struct Inner<T> {
name: &'static str,
scope: Scope,
handle: OnceLock<Option<Arc<core_config::Config>>>,
current: RwLock<Option<(Arc<core_config::Revision>, Arc<T>)>>,
defaults: OnceLock<Arc<T>>,
_type: PhantomData<fn() -> T>,
}
impl<T: ConfigType> Inner<T> {
const fn new(name: &'static str, scope: Scope) -> Self {
Self {
name,
scope,
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.scope, self.name))
.as_ref()
}
fn get(&self) -> Value<T> {
if let Some(test) = testing::active().ok().flatten() {
if let Some(value) = test.config(self.scope, 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 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());
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 {
return;
};
let name = self.name;
let mut changes = handle.subscribe();
core().tokio_handle().spawn(async move {
while changes.changed().await.is_ok() {
let revision = changes.borrow_and_update().clone();
f(Value(Arc::new(read::<T>(name, &revision.value))));
}
});
}
}
fn read<T: ConfigType>(name: &str, value: &serde_json::Value) -> T {
T::deserialize(value).unwrap_or_else(|err| {
panic!(
"config {name:?}: the value satisfies the schema Encore derived from `{}`, but serde \
could not read it: {err}. This is a bug in Encore: please report it",
std::any::type_name::<T>()
)
})
}
fn lookup(scope: Scope, name: &str) -> Option<Arc<core_config::Config>> {
let configs = core().configs();
match scope {
Scope::Service => configs.service_config(name),
Scope::App => configs.shared_config(name),
}
}
macro_rules! config_type {
($(#[$doc:meta])* $name:ident, $scope:expr) => {
$(#[$doc])*
pub struct $name<T>(Inner<T>);
impl<T: ConfigType> $name<T> {
pub const fn new(name: &'static str) -> Self {
Self(Inner::new(name, $scope))
}
pub const fn name(&self) -> &'static str {
self.0.name
}
pub fn get(&self) -> Value<T> {
self.0.get()
}
pub fn on_change(&self, f: impl Fn(Value<T>) + Send + Sync + 'static) {
self.0.on_change(f)
}
}
impl<T> sealed::Sealed for $name<T> {
fn key(&self) -> (Scope, &'static str) {
(self.0.scope, self.0.name)
}
}
impl<T: ConfigType> AnyConfig<T> for $name<T> {}
};
}
config_type!(
Config,
Scope::Service
);
config_type!(
SharedConfig,
Scope::App
);
config_type!(
GlobalConfig,
Scope::App
);
mod sealed {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Scope {
App,
Service,
}
pub trait Sealed {
fn key(&self) -> (Scope, &'static str);
}
}
pub trait AnyConfig<T>: sealed::Sealed {}
pub(crate) fn key_of<T>(config: &impl AnyConfig<T>) -> (Scope, &'static str) {
config.key()
}
pub(crate) fn test_value<T: ConfigType>(
config: &impl AnyConfig<T>,
mut value: serde_json::Value,
) -> Result<Arc<dyn Any + Send + Sync>, crate::Error> {
let (scope, name) = key_of(config);
if let Some(handle) = lookup(scope, name) {
value = handle.prepare(value).map_err(|errors| {
crate::Error::invalid_argument(format!(
"the value for config {name:?} does not satisfy its schema: {}",
errors.join("; ")
))
})?;
}
let value = T::deserialize(&value).map_err(|err| {
crate::Error::invalid_argument(format!(
"the value for config {name:?} could not be read: {err}"
))
})?;
Ok(Arc::new(value))
}
#[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 duration, such as \"30s\", \"250ms\" or \"1h30m\""
))
})
}
}
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..];
}
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() {
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)),
("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}");
}
}
#[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}"
);
}
}
}