1mod activation;
44pub mod settings;
45
46pub use activation::{ConfigActivation, SettingEvent, ConfigKeyActivation, ConfigRefusal, CRITICAL_GRANT};
47pub(crate) use activation::require_everywhere;
48
49use std::collections::BTreeMap;
50use std::marker::PhantomData;
51use std::path::{Path, PathBuf};
52use std::sync::{Arc, Mutex, Weak};
53use std::time::Duration;
54
55use schemars::JsonSchema;
56use serde::de::DeserializeOwned;
57use serde::{Deserialize, Serialize};
58use serde_json::Value;
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
62#[serde(rename_all = "snake_case")]
63pub enum Reload {
64 Live,
66 Restart,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
73#[serde(rename_all = "snake_case")]
74pub enum Sensitivity {
75 Public,
77 Secret,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
84#[serde(rename_all = "snake_case")]
85pub enum Scope {
86 Service,
88 Process,
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
94#[serde(rename_all = "snake_case")]
95pub enum Source {
96 Default,
98 File,
100 Flag,
102 Runtime,
104}
105
106pub trait SettingValue: Serialize + DeserializeOwned + JsonSchema + Clone + Send + Sync + 'static {}
108impl<T: Serialize + DeserializeOwned + JsonSchema + Clone + Send + Sync + 'static> SettingValue for T {}
109
110pub struct Setting<T> {
113 pub key: &'static str,
115 pub doc: &'static str,
117 pub default: fn() -> T,
118 pub reload: Reload,
119 pub sensitivity: Sensitivity,
120 pub scope: Scope,
121 pub remote: bool,
124 pub critical: bool,
127 _t: PhantomData<fn() -> T>,
128}
129
130impl<T> Clone for Setting<T> {
131 fn clone(&self) -> Self {
132 *self
133 }
134}
135impl<T> Copy for Setting<T> {}
136
137impl<T> std::fmt::Debug for Setting<T> {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 write!(f, "Setting({})", self.key)
140 }
141}
142
143impl<T> Setting<T> {
144 pub const fn new(key: &'static str, default: fn() -> T) -> Self {
147 Self { key, doc: "", default, reload: Reload::Live, sensitivity: Sensitivity::Public, scope: Scope::Service, remote: true, critical: false, _t: PhantomData }
148 }
149 pub const fn reload(mut self, r: Reload) -> Self {
150 self.reload = r;
151 self
152 }
153 pub const fn sensitivity(mut self, s: Sensitivity) -> Self {
154 self.sensitivity = s;
155 self
156 }
157 pub const fn scope(mut self, s: Scope) -> Self {
158 self.scope = s;
159 self
160 }
161 pub const fn remote(mut self, r: bool) -> Self {
162 self.remote = r;
163 self
164 }
165 pub const fn critical(mut self, c: bool) -> Self {
166 self.critical = c;
167 self
168 }
169 pub const fn doc(mut self, d: &'static str) -> Self {
170 self.doc = d;
171 self
172 }
173}
174
175#[macro_export]
179macro_rules! setting {
180 ($key:literal, default = $d:expr $(, $($rest:tt)*)?) => {
181 $crate::setting!(@opt ($crate::plexus::config::Setting::new($key, || $d)) $($($rest)*)?)
182 };
183 (@opt ($s:expr)) => { $s };
184 (@opt ($s:expr) reload = $v:ident $(, $($rest:tt)*)?) => {
185 $crate::setting!(@opt ($s.reload($crate::plexus::config::Reload::$v)) $($($rest)*)?)
186 };
187 (@opt ($s:expr) sensitivity = $v:ident $(, $($rest:tt)*)?) => {
188 $crate::setting!(@opt ($s.sensitivity($crate::plexus::config::Sensitivity::$v)) $($($rest)*)?)
189 };
190 (@opt ($s:expr) scope = $v:ident $(, $($rest:tt)*)?) => {
191 $crate::setting!(@opt ($s.scope($crate::plexus::config::Scope::$v)) $($($rest)*)?)
192 };
193 (@opt ($s:expr) remote = $v:literal $(, $($rest:tt)*)?) => {
194 $crate::setting!(@opt ($s.remote($v)) $($($rest)*)?)
195 };
196 (@opt ($s:expr) critical = $v:literal $(, $($rest:tt)*)?) => {
197 $crate::setting!(@opt ($s.critical($v)) $($($rest)*)?)
198 };
199 (@opt ($s:expr) doc = $v:literal $(, $($rest:tt)*)?) => {
200 $crate::setting!(@opt ($s.doc($v)) $($($rest)*)?)
201 };
202}
203
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub struct Millis(pub Duration);
207
208impl Millis {
209 pub const fn ms(n: u64) -> Self {
210 Self(Duration::from_millis(n))
211 }
212 pub const fn secs(n: u64) -> Self {
213 Self(Duration::from_secs(n))
214 }
215}
216
217impl Serialize for Millis {
218 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
219 let ms = self.0.as_millis();
220 if ms % 1000 == 0 {
221 s.serialize_str(&format!("{}s", ms / 1000))
222 } else {
223 s.serialize_str(&format!("{ms}ms"))
224 }
225 }
226}
227
228impl<'de> Deserialize<'de> for Millis {
229 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
230 #[derive(Deserialize)]
231 #[serde(untagged)]
232 enum Either {
233 Text(String),
234 Ms(u64),
235 }
236 match Either::deserialize(d)? {
237 Either::Text(t) => parse_duration(&t).map(Millis).map_err(serde::de::Error::custom),
238 Either::Ms(n) => Ok(Millis::ms(n)),
239 }
240 }
241}
242
243impl JsonSchema for Millis {
244 fn schema_name() -> std::borrow::Cow<'static, str> {
245 "Duration".into()
246 }
247 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
248 schemars::json_schema!({
249 "type": "string",
250 "pattern": "^[0-9]+(\\.[0-9]+)?(ms|s|m)$",
251 "description": "a duration: 500ms, 5s, 2m"
252 })
253 }
254}
255
256pub fn parse_duration(s: &str) -> Result<Duration, String> {
258 let s = s.trim();
259 let (num, unit) = match s.find(|c: char| !(c.is_ascii_digit() || c == '.')) {
260 Some(i) => (&s[..i], s[i..].trim()),
261 None => (s, "s"),
262 };
263 let n: f64 = num.parse().map_err(|_| format!("`{s}` is not a duration (5s, 500ms, 2m)"))?;
264 let secs = match unit {
265 "ms" => n / 1e3,
266 "s" | "" => n,
267 "m" => n * 60.0,
268 _ => return Err(format!("`{s}`: the unit is ms, s or m")),
269 };
270 if !secs.is_finite() || secs <= 0.0 {
271 return Err(format!("`{s}` is not a positive duration"));
272 }
273 Ok(Duration::from_secs_f64(secs))
274}
275
276pub const RESERVED_SEGMENTS: &[&str] = &["get", "set", "reset", "confirm", "names", "list", "watch", "schema"];
278
279pub fn check_key(key: &str) -> Result<(), String> {
282 let ok_seg = |s: &str| {
283 let mut b = s.bytes();
284 matches!(b.next(), Some(c) if c.is_ascii_lowercase()) && b.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_')
285 };
286 if key.is_empty() || !key.split('.').all(ok_seg) {
287 return Err(format!("`{key}` is not a setting's key: dotted segments of [a-z][a-z0-9_]*"));
288 }
289 if let Some(r) = key.split('.').find(|s| RESERVED_SEGMENTS.contains(s)) {
290 return Err(format!("`{key}`: `{r}` is a key node's method, not a segment"));
291 }
292 Ok(())
293}
294
295pub type Actor = Vec<String>;
298
299pub fn current_actor() -> Actor {
302 if let Ok(c) = crate::call::caller() {
303 let mut out = vec![c.auth().and_then(|a| a.principal()).map(|p| p.to_string()).unwrap_or_else(|| "anonymous".into())];
304 if let Some(h) = c.context().hop() {
305 out.push(h.principal.clone());
306 }
307 return out;
308 }
309 if let Ok(h) = crate::call::hop() {
310 let mut out: Vec<String> = h.for_.iter().rev().cloned().collect();
311 out.push(h.principal.clone());
312 return out;
313 }
314 vec!["host".into()]
315}
316
317#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
319#[serde(rename_all = "snake_case")]
320pub enum ConfigAction {
321 Set,
322 Reset,
323 Confirmed,
324 Reverted,
325 Refused,
328}
329
330#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
332pub struct ConfigRecord {
333 pub action: ConfigAction,
334 pub key: String,
335 pub actor: Actor,
337 pub at: i64,
339 #[serde(default, skip_serializing_if = "Option::is_none")]
341 pub old_hash: Option<String>,
342 #[serde(default, skip_serializing_if = "Option::is_none")]
344 pub new_hash: Option<String>,
345 #[serde(default, skip_serializing_if = "Option::is_none")]
347 pub confirm_until: Option<i64>,
348 #[serde(default, skip_serializing_if = "Option::is_none")]
350 pub why: Option<String>,
351}
352
353pub trait ConfigAudit: Send + Sync {
357 fn record(&self, r: &ConfigRecord);
358}
359
360#[derive(Debug, Clone, PartialEq, Eq)]
362pub enum ConfigError {
363 Unknown { key: String, keys: Vec<String> },
365 Invalid { key: String, message: String },
367 NothingToConfirm { key: String },
369 Store { message: String },
371}
372
373impl std::fmt::Display for ConfigError {
374 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
375 match self {
376 Self::Unknown { key, keys } if keys.is_empty() => write!(f, "no setting `{key}`"),
377 Self::Unknown { key, keys } => write!(f, "`{key}` is not a setting; under it: {}", keys.join(", ")),
378 Self::Invalid { key, message } => write!(f, "`{key}`: {message}"),
379 Self::NothingToConfirm { key } => write!(f, "`{key}` has no change waiting to be confirmed"),
380 Self::Store { message } => write!(f, "the store: {message}"),
381 }
382 }
383}
384
385impl std::error::Error for ConfigError {}
386
387#[derive(Debug, Clone, PartialEq)]
389pub struct Previous<T> {
390 pub value: T,
392 pub source: Source,
393}
394
395#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
397pub struct KeyInfo {
398 pub key: String,
399 #[serde(default, skip_serializing_if = "String::is_empty")]
400 pub doc: String,
401 #[serde(default, skip_serializing_if = "Option::is_none")]
403 pub value: Option<Value>,
404 pub hash: String,
406 pub set: bool,
408 pub source: Source,
409 #[serde(default, skip_serializing_if = "Option::is_none")]
411 pub default: Option<Value>,
412 pub reload: Reload,
413 pub sensitivity: Sensitivity,
414 pub scope: Scope,
415 pub remote: bool,
416 pub critical: bool,
417 #[serde(default, skip_serializing_if = "Option::is_none")]
420 pub pending: Option<Value>,
421 #[serde(default, skip_serializing_if = "Option::is_none")]
424 pub confirm_until: Option<i64>,
425 pub schema: Value,
427}
428
429#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
431pub struct ConfigChange {
432 pub action: ConfigAction,
433 pub key: String,
434 #[serde(default, skip_serializing_if = "Option::is_none")]
436 pub value: Option<Value>,
437 pub hash: String,
438 pub source: Source,
439 pub actor: Actor,
440 pub at: i64,
441 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
443 pub pending: bool,
444 #[serde(default, skip_serializing_if = "Option::is_none")]
445 pub confirm_until: Option<i64>,
446}
447
448type Check = Arc<dyn Fn(Value) -> Result<Value, String> + Send + Sync>;
449type Hook = Arc<dyn Fn(&Value) + Send + Sync>;
450
451struct Pending {
452 generation: u64,
453 until: i64,
454 revert_to: Option<Value>,
456}
457
458struct Entry {
459 doc: &'static str,
460 reload: Reload,
461 sensitivity: Sensitivity,
462 scope: Scope,
463 remote: bool,
464 critical: bool,
465 schema: Value,
466 default: Value,
467 check: Check,
468 file: Option<Value>,
469 flag: Option<Value>,
470 runtime: Option<Value>,
471 applied: Value,
474 applied_source: Source,
475 tx: tokio::sync::watch::Sender<Value>,
476 hooks: Vec<Hook>,
477 confirm: Option<Pending>,
478}
479
480impl Entry {
481 fn effective(&self) -> (Value, Source) {
482 if let Some(v) = &self.runtime {
483 return (v.clone(), Source::Runtime);
484 }
485 self.below_runtime()
486 }
487
488 fn below_runtime(&self) -> (Value, Source) {
489 if let Some(v) = &self.flag {
490 (v.clone(), Source::Flag)
491 } else if let Some(v) = &self.file {
492 (v.clone(), Source::File)
493 } else {
494 (self.default.clone(), Source::Default)
495 }
496 }
497
498 fn reapply(&mut self) -> bool {
500 let (v, src) = match self.reload {
501 Reload::Live => self.effective(),
502 Reload::Restart if self.applied_source == Source::Runtime => return false,
503 Reload::Restart => self.below_runtime(),
504 };
505 let moved = v != self.applied;
506 self.applied = v;
507 self.applied_source = src;
508 moved
509 }
510
511 fn pending(&self) -> Option<Value> {
512 match (self.reload, &self.runtime) {
513 (Reload::Restart, Some(v)) if *v != self.applied => Some(v.clone()),
514 _ => None,
515 }
516 }
517}
518
519struct Inner {
520 entries: Mutex<BTreeMap<String, Entry>>,
521 file: Option<PathBuf>,
523 stored: Mutex<BTreeMap<String, Value>>,
524 changes: tokio::sync::broadcast::Sender<ConfigChange>,
525 audit: Mutex<Vec<Arc<dyn ConfigAudit>>>,
526 salt: [u8; 16],
527 generation: std::sync::atomic::AtomicU64,
528}
529
530#[derive(Clone)]
533pub struct Config {
534 inner: Arc<Inner>,
535}
536
537impl std::fmt::Debug for Config {
538 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
539 let keys: Vec<String> = self.inner.entries.lock().unwrap().keys().cloned().collect();
540 f.debug_struct("Config").field("file", &self.inner.file).field("keys", &keys).finish()
541 }
542}
543
544impl Default for Config {
545 fn default() -> Self {
546 Self::new()
547 }
548}
549
550fn now_ms() -> i64 {
551 chrono::Utc::now().timestamp_millis()
552}
553
554impl Config {
555 pub fn new() -> Self {
558 Self::build(None, BTreeMap::new())
559 }
560
561 pub fn with_file(file: impl AsRef<Path>) -> Result<Self, String> {
566 let file = file.as_ref().to_path_buf();
567 let stored = match std::fs::read_to_string(&file) {
568 Ok(text) => serde_json::from_str::<BTreeMap<String, Value>>(&text).map_err(|e| format!("{}: {e}", file.display()))?,
569 Err(e) if e.kind() == std::io::ErrorKind::NotFound => BTreeMap::new(),
570 Err(e) => return Err(format!("{}: {e}", file.display())),
571 };
572 Ok(Self::build(Some(file), stored))
573 }
574
575 fn build(file: Option<PathBuf>, stored: BTreeMap<String, Value>) -> Self {
576 let mut salt = [0u8; 16];
577 let _ = getrandom_02::getrandom(&mut salt);
578 let c = Self {
579 inner: Arc::new(Inner {
580 entries: Mutex::default(),
581 file,
582 stored: Mutex::new(stored),
583 changes: tokio::sync::broadcast::Sender::new(256),
584 audit: Mutex::default(),
585 salt,
586 generation: Default::default(),
587 }),
588 };
589 settings::declare_core(&c);
590 c
591 }
592
593 pub fn with_audit(self, sink: Arc<dyn ConfigAudit>) -> Self {
595 self.add_audit(sink);
596 self
597 }
598
599 pub fn add_audit(&self, sink: Arc<dyn ConfigAudit>) {
601 self.inner.audit.lock().unwrap().push(sink);
602 }
603
604 pub fn file(&self) -> Option<&Path> {
606 self.inner.file.as_deref()
607 }
608
609 pub fn same(&self, other: &Config) -> bool {
611 Arc::ptr_eq(&self.inner, &other.inner)
612 }
613
614 fn downgrade(&self) -> Weak<Inner> {
615 Arc::downgrade(&self.inner)
616 }
617
618 pub fn declare<T: SettingValue>(&self, s: &Setting<T>) {
622 if let Err(why) = self.try_declare(s) {
623 tracing::error!(target: "plexus::config", "{why}");
624 }
625 }
626
627 pub fn try_declare<T: SettingValue>(&self, s: &Setting<T>) -> Result<(), String> {
629 check_key(s.key)?;
630 let schema = serde_json::to_value(schemars::schema_for!(T)).unwrap_or(Value::Null);
631 let mut entries = self.inner.entries.lock().unwrap();
632 if let Some(e) = entries.get(s.key) {
633 return if e.schema == schema { Ok(()) } else { Err(format!("`{}` is declared already with another type", s.key)) };
634 }
635 if let Some(clash) = entries.keys().find(|k| k.starts_with(&format!("{}.", s.key)) || s.key.starts_with(&format!("{k}."))) {
636 return Err(format!("`{}` and `{clash}`: a key is never another's prefix", s.key));
637 }
638 let default = serde_json::to_value((s.default)()).map_err(|e| format!("`{}`'s default: {e}", s.key))?;
639 let check: Check = Arc::new(|v: Value| {
640 let t: T = match serde_json::from_value::<T>(v.clone()) {
641 Ok(t) => t,
642 Err(first) => match v.as_str().and_then(|s| serde_json::from_str::<Value>(s).ok()).and_then(|j| serde_json::from_value::<T>(j).ok()) {
645 Some(t) => t,
646 None => return Err(first.to_string()),
647 },
648 };
649 serde_json::to_value(t).map_err(|e| e.to_string())
650 });
651 let file = self.inner.stored.lock().unwrap().get(s.key).cloned().and_then(|v| match check(v) {
652 Ok(v) => Some(v),
653 Err(why) => {
654 tracing::error!(target: "plexus::config", key = s.key, "the file's value does not fit, ignored: {why}");
655 None
656 }
657 });
658 let mut e = Entry {
659 doc: s.doc,
660 reload: s.reload,
661 sensitivity: s.sensitivity,
662 scope: s.scope,
663 remote: s.remote,
664 critical: s.critical,
665 schema,
666 default: default.clone(),
667 check,
668 file,
669 flag: None,
670 runtime: None,
671 applied: default.clone(),
672 applied_source: Source::Default,
673 tx: tokio::sync::watch::Sender::new(default),
674 hooks: Vec::new(),
675 confirm: None,
676 };
677 e.reapply();
678 e.tx.send_replace(e.applied.clone());
679 entries.insert(s.key.to_string(), e);
680 Ok(())
681 }
682
683 pub fn get<T: SettingValue>(&self, s: &Setting<T>) -> T {
685 self.declare(s);
686 let v = self.inner.entries.lock().unwrap().get(s.key).map(|e| e.applied.clone());
687 v.and_then(|v| serde_json::from_value(v).ok()).unwrap_or_else(s.default)
688 }
689
690 pub fn source<T: SettingValue>(&self, s: &Setting<T>) -> Source {
692 self.declare(s);
693 self.inner.entries.lock().unwrap().get(s.key).map(|e| e.applied_source).unwrap_or(Source::Default)
694 }
695
696 pub fn set<T: SettingValue>(&self, s: &Setting<T>, value: T) -> Result<Previous<T>, ConfigError> {
698 self.declare(s);
699 let v = serde_json::to_value(value).map_err(|e| ConfigError::Invalid { key: s.key.into(), message: e.to_string() })?;
700 let (old, source) = self.set_value(s.key, v, None, current_actor())?;
701 let value = serde_json::from_value(old).unwrap_or_else(|_| (s.default)());
702 Ok(Previous { value, source })
703 }
704
705 pub fn seed<T: SettingValue>(&self, s: &Setting<T>, source: Source, value: Option<T>) {
708 self.declare(s);
709 let v = value.and_then(|v| serde_json::to_value(v).ok());
710 let moved = {
711 let mut entries = self.inner.entries.lock().unwrap();
712 let Some(e) = entries.get_mut(s.key) else { return };
713 match source {
714 Source::File => e.file = v,
715 Source::Flag => e.flag = v,
716 Source::Default | Source::Runtime => return,
717 }
718 e.reapply().then(|| (e.applied.clone(), e.tx.clone(), e.hooks.clone()))
719 };
720 if let Some((v, tx, hooks)) = moved {
721 tx.send_replace(v.clone());
722 hooks.iter().for_each(|h| h(&v));
723 }
724 }
725
726 pub fn reset<T: SettingValue>(&self, s: &Setting<T>) -> Result<T, ConfigError> {
729 self.declare(s);
730 self.reset_key(s.key, current_actor())?;
731 Ok(self.get(s))
732 }
733
734 pub fn watch<T: SettingValue>(&self, s: &Setting<T>) -> Watch<T> {
736 self.declare(s);
737 let rx = self.inner.entries.lock().unwrap().get(s.key).map(|e| e.tx.subscribe()).expect("declared");
738 Watch { rx, default: s.default }
739 }
740
741 pub fn on_change<T: SettingValue>(&self, s: &Setting<T>, f: impl Fn(T) + Send + Sync + 'static) {
745 self.declare(s);
746 let default = s.default;
747 let hook: Hook = Arc::new(move |v: &Value| f(serde_json::from_value(v.clone()).unwrap_or_else(|_| default())));
748 let now = {
749 let mut entries = self.inner.entries.lock().unwrap();
750 let e = entries.get_mut(s.key).expect("declared");
751 e.hooks.push(Arc::clone(&hook));
752 e.applied.clone()
753 };
754 hook(&now);
755 }
756
757 pub fn changes(&self) -> tokio::sync::broadcast::Receiver<ConfigChange> {
759 self.inner.changes.subscribe()
760 }
761
762 pub fn list(&self) -> Vec<KeyInfo> {
764 let entries = self.inner.entries.lock().unwrap();
765 entries.iter().map(|(k, e)| self.info_of(k, e)).collect()
766 }
767
768 pub fn info(&self, key: &str) -> Option<KeyInfo> {
770 let entries = self.inner.entries.lock().unwrap();
771 entries.get(key).map(|e| self.info_of(key, e))
772 }
773
774 pub fn keys(&self) -> Vec<String> {
776 self.inner.entries.lock().unwrap().keys().cloned().collect()
777 }
778
779 pub fn schema(&self) -> Value {
781 let entries = self.inner.entries.lock().unwrap();
782 Value::Object(entries.iter().map(|(k, e)| (k.clone(), e.schema.clone())).collect())
783 }
784
785 fn info_of(&self, key: &str, e: &Entry) -> KeyInfo {
786 let secret = e.sensitivity == Sensitivity::Secret;
787 KeyInfo {
788 key: key.to_string(),
789 doc: e.doc.to_string(),
790 value: (!secret).then(|| e.applied.clone()),
791 hash: self.hash(e, &e.applied),
792 set: e.applied_source != Source::Default,
793 source: e.applied_source,
794 default: (!secret).then(|| e.default.clone()),
795 reload: e.reload,
796 sensitivity: e.sensitivity,
797 scope: e.scope,
798 remote: e.remote,
799 critical: e.critical,
800 pending: e.pending().map(|v| if secret { Value::Null } else { v }),
801 confirm_until: e.confirm.as_ref().map(|p| p.until),
802 schema: e.schema.clone(),
803 }
804 }
805
806 fn hash(&self, e: &Entry, v: &Value) -> String {
807 let text = super::content_hash::canonical_json(v);
808 match e.sensitivity {
809 Sensitivity::Public => super::content_hash::hash16(text.as_bytes()),
810 Sensitivity::Secret => {
811 let mut b = self.inner.salt.to_vec();
812 b.extend_from_slice(text.as_bytes());
813 format!("salted:{}", super::content_hash::hash16(&b))
814 }
815 }
816 }
817
818 pub fn flags(&self, key: &str) -> Option<(bool, bool)> {
820 self.inner.entries.lock().unwrap().get(key).map(|e| (e.remote, e.critical))
821 }
822
823 fn unknown(&self, key: &str) -> ConfigError {
824 let prefix = format!("{key}.");
825 let keys = self.inner.entries.lock().unwrap().keys().filter(|k| k.starts_with(&prefix)).cloned().collect();
826 ConfigError::Unknown { key: key.into(), keys }
827 }
828
829 pub fn set_value(&self, key: &str, value: Value, confirm_within: Option<Duration>, actor: Actor) -> Result<(Value, Source), ConfigError> {
834 let at = now_ms();
835 let (old, old_src, record, change, notify, kept) = {
836 let mut entries = self.inner.entries.lock().unwrap();
837 let Some(e) = entries.get_mut(key) else {
838 drop(entries);
839 return Err(self.unknown(key));
840 };
841 let value = (e.check)(value).map_err(|message| ConfigError::Invalid { key: key.into(), message })?;
842 let (old, old_src) = (e.applied.clone(), e.applied_source);
843 let before = e.runtime.clone();
844 e.runtime = Some(value.clone());
845 let confirm_until = match confirm_within {
846 Some(d) => {
847 let generation = self.inner.generation.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
848 let until = at + d.as_millis() as i64;
849 let revert_to = e.confirm.take().map_or(before, |p| p.revert_to);
852 e.confirm = Some(Pending { generation, until, revert_to });
853 self.revert_after(key.to_string(), generation, d);
854 Some(until)
855 }
856 None => {
857 e.confirm = None;
858 None
859 }
860 };
861 let moved = e.reapply();
862 let record = ConfigRecord { action: ConfigAction::Set, key: key.into(), actor: actor.clone(), at, old_hash: Some(self.hash(e, &old)), new_hash: Some(self.hash(e, &value)), confirm_until, why: None };
863 let change = self.change_of(key, e, ConfigAction::Set, actor, at, confirm_until);
864 let notify = moved.then(|| (e.applied.clone(), e.tx.clone(), e.hooks.clone()));
865 (old, old_src, record, change, notify, value)
866 };
867 let stored = self.store(key, Some(kept));
868 self.after(record, change, notify);
869 stored?;
870 Ok((old, old_src))
871 }
872
873 pub fn reset_key(&self, key: &str, actor: Actor) -> Result<(), ConfigError> {
875 let at = now_ms();
876 let (record, change, notify) = {
877 let mut entries = self.inner.entries.lock().unwrap();
878 let Some(e) = entries.get_mut(key) else {
879 drop(entries);
880 return Err(self.unknown(key));
881 };
882 let old = e.applied.clone();
883 e.runtime = None;
884 e.confirm = None;
885 let moved = e.reapply();
886 let record = ConfigRecord { action: ConfigAction::Reset, key: key.into(), actor: actor.clone(), at, old_hash: Some(self.hash(e, &old)), new_hash: Some(self.hash(e, &e.applied)), confirm_until: None, why: None };
887 let change = self.change_of(key, e, ConfigAction::Reset, actor, at, None);
888 (record, change, moved.then(|| (e.applied.clone(), e.tx.clone(), e.hooks.clone())))
889 };
890 let stored = self.store(key, None);
891 self.after(record, change, notify);
892 stored
893 }
894
895 pub fn confirm(&self, key: &str, actor: Actor) -> Result<(), ConfigError> {
897 let at = now_ms();
898 let (record, change) = {
899 let mut entries = self.inner.entries.lock().unwrap();
900 let Some(e) = entries.get_mut(key) else {
901 drop(entries);
902 return Err(self.unknown(key));
903 };
904 if e.confirm.take().is_none() {
905 return Err(ConfigError::NothingToConfirm { key: key.into() });
906 }
907 let h = self.hash(e, &e.applied);
908 let record = ConfigRecord { action: ConfigAction::Confirmed, key: key.into(), actor: actor.clone(), at, old_hash: None, new_hash: Some(h), confirm_until: None, why: None };
909 (record, self.change_of(key, e, ConfigAction::Confirmed, actor, at, None))
910 };
911 self.after(record, change, None);
912 Ok(())
913 }
914
915 pub fn refused(&self, key: &str, actor: Actor, why: &str) {
917 let r = ConfigRecord { action: ConfigAction::Refused, key: key.into(), actor, at: now_ms(), old_hash: None, new_hash: None, confirm_until: None, why: Some(why.into()) };
918 self.audit(&r);
919 }
920
921 fn revert_after(&self, key: String, generation: u64, d: Duration) {
922 let weak = self.downgrade();
923 crate::rt::spawn(async move {
924 crate::rt::sleep(d).await;
925 if let Some(inner) = weak.upgrade() {
926 Config { inner }.revert(&key, generation);
927 }
928 });
929 }
930
931 fn revert(&self, key: &str, generation: u64) {
934 let at = now_ms();
935 let (record, change, notify, stored) = {
936 let mut entries = self.inner.entries.lock().unwrap();
937 let Some(e) = entries.get_mut(key) else { return };
938 match &e.confirm {
939 Some(p) if p.generation == generation => {}
940 _ => return,
941 }
942 let p = e.confirm.take().expect("checked");
943 let old = e.applied.clone();
944 e.runtime = p.revert_to.clone();
945 let moved = e.reapply();
946 let actor = vec!["config:revert".to_string()];
947 let record = ConfigRecord { action: ConfigAction::Reverted, key: key.into(), actor: actor.clone(), at, old_hash: Some(self.hash(e, &old)), new_hash: Some(self.hash(e, &e.applied)), confirm_until: None, why: Some("not confirmed in time".into()) };
948 let change = self.change_of(key, e, ConfigAction::Reverted, actor, at, None);
949 (record, change, moved.then(|| (e.applied.clone(), e.tx.clone(), e.hooks.clone())), p.revert_to)
950 };
951 if let Err(e) = self.store(key, stored) {
952 tracing::error!(target: "plexus::config", key, "{e}");
953 }
954 tracing::warn!(target: "plexus::config", key, "a change not confirmed in time is reverted");
955 self.after(record, change, notify);
956 }
957
958 fn change_of(&self, key: &str, e: &Entry, action: ConfigAction, actor: Actor, at: i64, confirm_until: Option<i64>) -> ConfigChange {
959 ConfigChange {
960 action,
961 key: key.into(),
962 value: (e.sensitivity == Sensitivity::Public).then(|| e.applied.clone()),
963 hash: self.hash(e, &e.applied),
964 source: e.applied_source,
965 actor,
966 at,
967 pending: e.pending().is_some(),
968 confirm_until,
969 }
970 }
971
972 fn after(&self, record: ConfigRecord, change: ConfigChange, notify: Option<(Value, tokio::sync::watch::Sender<Value>, Vec<Hook>)>) {
973 self.audit(&record);
974 if let Some((v, tx, hooks)) = notify {
975 tx.send_replace(v.clone());
976 hooks.iter().for_each(|h| h(&v));
977 }
978 let _ = self.inner.changes.send(change);
979 }
980
981 fn audit(&self, r: &ConfigRecord) {
982 tracing::info!(
983 target: "plexus::audit",
984 action = ?r.action, key = %r.key, actor = %r.actor.join(" < "), at = r.at,
985 old_hash = r.old_hash.as_deref().unwrap_or(""), new_hash = r.new_hash.as_deref().unwrap_or(""),
986 confirm_until = r.confirm_until.unwrap_or(0), why = r.why.as_deref().unwrap_or(""),
987 "config"
988 );
989 let sinks = self.inner.audit.lock().unwrap().clone();
990 for s in sinks {
991 s.record(r);
992 }
993 }
994
995 fn store(&self, key: &str, value: Option<Value>) -> Result<(), ConfigError> {
997 let Some(file) = &self.inner.file else { return Ok(()) };
998 let snapshot = {
999 let mut stored = self.inner.stored.lock().unwrap();
1000 match value {
1001 Some(v) => stored.insert(key.to_string(), v),
1002 None => stored.remove(key),
1003 };
1004 stored.clone()
1005 };
1006 write_private(file, &serde_json::to_string_pretty(&snapshot).unwrap_or_default()).map_err(|message| ConfigError::Store { message })
1007 }
1008}
1009
1010fn write_private(file: &Path, text: &str) -> Result<(), String> {
1012 use std::io::Write;
1013 if let Some(dir) = file.parent().filter(|d| !d.as_os_str().is_empty()) {
1014 std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
1015 }
1016 let tmp = file.with_extension("tmp");
1017 let mut o = std::fs::OpenOptions::new();
1018 o.write(true).create(true).truncate(true);
1019 #[cfg(unix)]
1020 {
1021 use std::os::unix::fs::OpenOptionsExt;
1022 o.mode(0o600);
1023 }
1024 let mut f = o.open(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
1025 f.write_all(text.as_bytes()).map_err(|e| format!("{}: {e}", tmp.display()))?;
1026 std::fs::rename(&tmp, file).map_err(|e| format!("{}: {e}", file.display()))
1027}
1028
1029pub struct Watch<T> {
1031 rx: tokio::sync::watch::Receiver<Value>,
1032 default: fn() -> T,
1033}
1034
1035impl<T: SettingValue> Watch<T> {
1036 pub fn current(&self) -> T {
1038 serde_json::from_value(self.rx.borrow().clone()).unwrap_or_else(|_| (self.default)())
1039 }
1040
1041 pub async fn changed(&mut self) -> Option<T> {
1043 self.rx.changed().await.ok()?;
1044 Some(self.current())
1045 }
1046}