use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use futures_core::Stream;
use serde::Serialize;
use serde::de::DeserializeOwned;
use super::oneshot::Answer;
use super::run;
use crate::config::{Env, Explained, File, Snapshot};
use crate::pool::Pool;
use crate::sync::lock;
use crate::{Error, ErrorKind, Result};
#[must_use = "a config opens with open()"]
pub struct ConfigBuilder<T> {
builder: crate::config::ConfigBuilder<T>,
pool: Arc<Pool>,
}
impl super::Store {
pub fn config<T>(&self, name: &str, declaration: T) -> ConfigBuilder<T>
where
T: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
{
ConfigBuilder { builder: self.blocking().config(name, declaration), pool: Arc::clone(self.pool()) }
}
}
impl<T> ConfigBuilder<T>
where
T: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
{
pub fn file(self, file: impl Into<File>) -> Self {
ConfigBuilder { builder: self.builder.file(file), pool: self.pool }
}
pub fn env(self, env: impl Into<Env>) -> Self {
ConfigBuilder { builder: self.builder.env(env), pool: self.pool }
}
pub fn validate(self, validate: impl Fn(&T) -> std::result::Result<(), String> + Send + Sync + 'static) -> Self {
ConfigBuilder { builder: self.builder.validate(validate), pool: self.pool }
}
pub fn strict(self) -> Self {
ConfigBuilder { builder: self.builder.strict(), pool: self.pool }
}
pub fn open(self) -> Result<Config<T>> {
Ok(Config { config: self.builder.open()?, pool: Some(self.pool) })
}
}
pub struct Config<T> {
config: crate::config::Config<T>,
pool: Option<Arc<Pool>>,
}
impl<T> Config<T>
where
T: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
{
pub fn get(&self) -> Snapshot<T> {
self.config.get()
}
pub fn update(
&self,
change: impl FnMut(&mut T) + Send + 'static,
) -> impl Future<Output = Result<()>> + Send + 'static {
changed(self.config.clone(), self.pool.clone(), None, change)
}
pub fn if_version(&self, version: i64) -> IfVersion<'_, T> {
IfVersion { config: self, version }
}
pub fn reset(&self, path: &str) -> impl Future<Output = Result<()>> + Send + 'static {
let (config, pool, path) = (self.config.clone(), self.pool.clone(), path.to_owned());
async move {
if !config.resets(&path)? {
return Ok(());
}
reset(config, pool, path).await
}
}
pub fn reset_all(&self) -> impl Future<Output = Result<()>> + Send + 'static {
reset(self.config.clone(), self.pool.clone(), String::new())
}
pub fn watch(&self) -> Watching<T> {
let latest = Arc::new(Mutex::new(Latest { newest: None, closed: false, ended: false, waker: None }));
let told = Arc::clone(&latest);
let closing: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
let waker = {
let mut latest = lock(&told);
latest.closed = true;
latest.waker.take()
};
if let Some(waker) = waker {
waker.wake();
}
});
if !self.config.on_close(Arc::downgrade(&closing)) {
lock(&latest).closed = true;
}
let seen = Arc::clone(&latest);
let watching = self.config.watch(move |next, _| {
let waker = {
let mut latest = lock(&seen);
latest.newest = Some(next.clone());
latest.waker.take()
};
if let Some(waker) = waker {
waker.wake();
}
});
let name = self.config.name().to_owned();
Watching { latest, name, _watching: watching, _config: self.config.clone(), _closing: closing }
}
pub fn explain(&self) -> Explained {
self.config.explain()
}
pub fn name(&self) -> &str {
self.config.name()
}
pub fn blocking(&self) -> &crate::config::Config<T> {
&self.config
}
}
impl<T> From<crate::config::Config<T>> for Config<T>
where
T: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
{
fn from(config: crate::config::Config<T>) -> Config<T> {
let pool = config.store().ok().map(|store| Pool::of_or_stopped(&store));
Config { config, pool }
}
}
pub struct IfVersion<'a, T> {
config: &'a Config<T>,
version: i64,
}
impl<T> IfVersion<'_, T>
where
T: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
{
pub fn update(
self,
change: impl FnMut(&mut T) + Send + 'static,
) -> impl Future<Output = Result<()>> + Send + 'static {
changed(self.config.config.clone(), self.config.pool.clone(), Some(self.version), change)
}
}
async fn changed<T>(
config: crate::config::Config<T>,
pool: Option<Arc<Pool>>,
if_version: Option<i64>,
mut change: impl FnMut(&mut T) + Send,
) -> Result<()>
where
T: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
{
let pool = alive(config.name(), pool)?;
for _ in 0..crate::config::Config::<T>::ATTEMPTS {
let Some(proposal) = config.proposal(if_version, &mut change)? else { return Ok(()) };
let (submitting, elsewhere) = (config.clone(), run::lead_on(&pool));
let what = format!("config {}: a change", config.name());
let submit = move |answer: Answer<_>| {
submitting.submit_change(proposal, elsewhere, move |written| answer.send(written));
};
match run::write(&pool, what, submit).await?.publish() {
Err(error) if error.kind() == ErrorKind::Conflict && if_version.is_none() => {}
done => return done,
}
}
Err(config.raced())
}
async fn reset<T>(config: crate::config::Config<T>, pool: Option<Arc<Pool>>, path: String) -> Result<()>
where
T: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
{
let pool = alive(config.name(), pool)?;
let (submitting, elsewhere) = (config.clone(), run::lead_on(&pool));
let what = format!("config {}: a reset", config.name());
let submit = move |answer: Answer<_>| {
submitting.submit_reset(&path, elsewhere, move |written| answer.send(written));
};
run::write(&pool, what, submit).await?.publish()
}
fn alive(name: &str, pool: Option<Arc<Pool>>) -> Result<Arc<Pool>> {
pool.ok_or_else(|| Error::closed(format!("config {name}: its store closed")))
}
#[must_use = "a watch is read as a Stream, and stops when dropped"]
pub struct Watching<T> {
latest: Arc<Mutex<Latest<T>>>,
name: String,
_watching: crate::config::Watching,
_config: crate::config::Config<T>,
_closing: Arc<dyn Fn() + Send + Sync>,
}
struct Latest<T> {
newest: Option<Snapshot<T>>,
closed: bool,
ended: bool,
waker: Option<Waker>,
}
impl<T> Stream for Watching<T> {
type Item = Result<Snapshot<T>>;
fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut latest = lock(&self.latest);
if let Some(newest) = latest.newest.take() {
return Poll::Ready(Some(Ok(newest)));
}
if latest.closed {
if std::mem::replace(&mut latest.ended, true) {
return Poll::Ready(None);
}
return Poll::Ready(Some(Err(Error::closed(format!("config {}: the store closed", self.name)))));
}
if !latest.waker.as_ref().is_some_and(|waker| waker.will_wake(context.waker())) {
latest.waker = Some(context.waker().clone());
}
Poll::Pending
}
}
impl<T> Clone for Config<T> {
fn clone(&self) -> Self {
Config { config: self.config.clone(), pool: self.pool.clone() }
}
}
impl<T> fmt::Debug for ConfigBuilder<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.builder, f)
}
}
impl<T> fmt::Debug for Config<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.config, f)
}
}
impl<T> fmt::Debug for IfVersion<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("IfVersion").field("config", &self.config.config).field("version", &self.version).finish()
}
}
impl<T> fmt::Debug for Watching<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Watching").field("config", &self.name).finish_non_exhaustive()
}
}
#[cfg(test)]
#[path = "config_tests.rs"]
mod tests;