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