use async_stream::stream;
use futures::Stream;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::{current_actor, parse_duration, Config, ConfigChange, ConfigError, KeyInfo, Source};
use crate::plexus::AuthContext;
pub const CRITICAL_GRANT: &str = "config.critical";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ConfigRefusal {
UnknownKey,
NotAKey,
Invalid,
NotRemote,
Critical,
ConfirmRequired,
NothingToConfirm,
Store,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SettingEvent {
Setting(KeyInfo),
Set {
key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
previous: Option<Value>,
previous_hash: String,
previous_source: Source,
setting: KeyInfo,
},
Reset { setting: KeyInfo },
Confirmed { key: String },
Refused { reason: ConfigRefusal, key: String, message: String },
Error { message: String },
}
impl plexus_client::FromClientError for SettingEvent {
fn from_client_error(e: plexus_client::ClientError) -> Self {
SettingEvent::Error { message: e.to_string() }
}
}
fn refused(reason: ConfigRefusal, key: &str, message: impl Into<String>) -> SettingEvent {
SettingEvent::Refused { reason, key: key.into(), message: message.into() }
}
fn of_error(e: ConfigError) -> SettingEvent {
let reason = match &e {
ConfigError::Unknown { keys, .. } if !keys.is_empty() => ConfigRefusal::NotAKey,
ConfigError::Unknown { .. } => ConfigRefusal::UnknownKey,
ConfigError::Invalid { .. } => ConfigRefusal::Invalid,
ConfigError::NothingToConfirm { .. } => ConfigRefusal::NothingToConfirm,
ConfigError::Store { .. } => ConfigRefusal::Store,
};
let key = match &e {
ConfigError::Unknown { key, .. } | ConfigError::Invalid { key, .. } | ConfigError::NothingToConfirm { key } => key.clone(),
ConfigError::Store { .. } => String::new(),
};
refused(reason, &key, e.to_string())
}
fn names_below(config: &Config, prefix: &str) -> Vec<String> {
let mut out: Vec<String> = config
.keys()
.into_iter()
.filter_map(|k| {
let rest = if prefix.is_empty() { Some(k.as_str()) } else { k.strip_prefix(prefix).and_then(|r| r.strip_prefix('.')) }?;
Some(rest.split('.').next().unwrap_or(rest).to_string())
})
.collect();
out.dedup();
out
}
#[derive(Clone)]
pub struct ConfigActivation {
config: Config,
}
impl ConfigActivation {
pub fn new(config: Config) -> Self {
Self { config }
}
pub fn config(&self) -> &Config {
&self.config
}
fn node(&self, name: &str) -> Option<ConfigKeyActivation> {
let path = name.to_string();
let prefix = format!("{path}.");
self.config.keys().iter().any(|k| *k == path || k.starts_with(&prefix)).then(|| ConfigKeyActivation { config: self.config.clone(), path })
}
}
#[plexus_macros::activation(namespace = "config", description = "A service's settings at runtime: each key a node, on its own grant")]
impl ConfigActivation {
#[plexus_macros::method]
pub async fn list(&self) -> impl Stream<Item = KeyInfo> + Send + 'static {
futures::stream::iter(self.config.list())
}
#[plexus_macros::method]
pub async fn watch(&self, key: Option<String>) -> impl Stream<Item = ConfigChange> + Send + 'static {
let mut rx = self.config.changes();
stream! {
loop {
match rx.recv().await {
Ok(c) => {
if key.as_deref().is_none_or(|k| c.key == k || c.key.starts_with(&format!("{k}."))) {
yield c;
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
}
}
}
}
#[plexus_macros::method]
pub async fn names(&self) -> impl Stream<Item = String> + Send + 'static {
futures::stream::iter(names_below(&self.config, ""))
}
#[plexus_macros::child(list = names)]
fn key(&self, name: &str) -> Option<ConfigKeyActivation> {
self.node(name)
}
}
#[derive(Clone)]
pub struct ConfigKeyActivation {
config: Config,
path: String,
}
impl ConfigKeyActivation {
pub fn path(&self) -> &str {
&self.path
}
fn is_key(&self) -> Result<(bool, bool), SettingEvent> {
match self.config.flags(&self.path) {
Some(f) => Ok(f),
None => Err(of_error(ConfigError::Unknown { key: self.path.clone(), keys: self.config.keys().into_iter().filter(|k| k.starts_with(&format!("{}.", self.path))).collect() })),
}
}
fn may_write(&self, auth: Option<&AuthContext>, confirming: Option<bool>) -> Result<(), SettingEvent> {
let (remote, critical) = self.is_key()?;
let refuse = |reason, why: String| {
self.config.refused(&self.path, current_actor(), &why);
Err(refused(reason, &self.path, why))
};
if !remote {
return refuse(ConfigRefusal::NotRemote, format!("`{}` is not settable over the wire: the host's code or its file sets it", self.path));
}
if critical {
if !holds_critical(auth) {
return refuse(ConfigRefusal::Critical, format!("`{}` is critical: an admin's (the grant `{CRITICAL_GRANT}`)", self.path));
}
if confirming == Some(false) {
return refuse(ConfigRefusal::ConfirmRequired, format!("`{}` is critical: set it with confirm_within (a confirmed commit), then confirm", self.path));
}
}
Ok(())
}
fn info(&self) -> KeyInfo {
self.config.info(&self.path).expect("a key")
}
}
fn holds_critical(auth: Option<&AuthContext>) -> bool {
let gate = crate::plexus::service_scope::current().and_then(|w| w.upgrade()).and_then(|s| s.gate().cloned());
match gate {
None => match crate::call::context() {
Ok(ctx) if ctx.hop().is_some() => ctx.reach().is_some_and(|r| r.is_everywhere()),
_ => true,
},
Some(g) => g.check_everywhere(auth, &plexus_auth_core::grants::Grant::new(CRITICAL_GRANT)).is_ok(),
}
}
pub const EVERYWHERE: &[&str] = &["set", "reset", "confirm"];
pub(crate) fn require_everywhere() -> Result<(), String> {
let schema = <ConfigKeyActivation as crate::plexus::Activation>::slot_schema()
.ok_or_else(|| "config_key: no schema to check".to_string())?;
crate::plexus::grant_gate::require_everywhere(&schema, EVERYWHERE)
}
#[plexus_macros::activation(namespace = "config_key", description = "A setting: get, set, reset, confirm")]
impl ConfigKeyActivation {
#[plexus_macros::method]
pub async fn get(&self) -> SettingEvent {
match self.is_key() {
Ok(_) => SettingEvent::Setting(self.info()),
Err(e) => e,
}
}
#[plexus_macros::method(everywhere)]
pub async fn set(&self, auth: Option<&AuthContext>, value: Value, confirm_within: Option<String>) -> SettingEvent {
let within = match confirm_within.as_deref().map(parse_duration).transpose() {
Ok(w) => w,
Err(why) => return refused(ConfigRefusal::Invalid, &self.path, format!("confirm_within: {why}")),
};
if let Err(e) = self.may_write(auth, Some(within.is_some())) {
return e;
}
match self.config.set_value(&self.path, value, within, current_actor()) {
Ok((previous, previous_source)) => {
let setting = self.info();
let secret = setting.value.is_none();
let previous_hash = if secret { String::new() } else { crate::plexus::content_hash::hash16(crate::plexus::content_hash::canonical_json(&previous).as_bytes()) };
SettingEvent::Set { key: self.path.clone(), previous: (!secret).then_some(previous), previous_hash, previous_source, setting }
}
Err(e) => of_error(e),
}
}
#[plexus_macros::method(everywhere)]
pub async fn reset(&self, auth: Option<&AuthContext>) -> SettingEvent {
if let Err(e) = self.may_write(auth, None) {
return e;
}
match self.config.reset_key(&self.path, current_actor()) {
Ok(()) => SettingEvent::Reset { setting: self.info() },
Err(e) => of_error(e),
}
}
#[plexus_macros::method(everywhere)]
pub async fn confirm(&self, auth: Option<&AuthContext>) -> SettingEvent {
if let Err(e) = self.may_write(auth, None) {
return e;
}
match self.config.confirm(&self.path, current_actor()) {
Ok(()) => SettingEvent::Confirmed { key: self.path.clone() },
Err(e) => of_error(e),
}
}
#[plexus_macros::method]
pub async fn names(&self) -> impl Stream<Item = String> + Send + 'static {
futures::stream::iter(names_below(&self.config, &self.path))
}
#[plexus_macros::child(list = names)]
fn key(&self, name: &str) -> Option<ConfigKeyActivation> {
let path = format!("{}.{name}", self.path);
let prefix = format!("{path}.");
self.config.keys().iter().any(|k| *k == path || k.starts_with(&prefix)).then(|| ConfigKeyActivation { config: self.config.clone(), path })
}
}