Skip to main content

plexus_core/plexus/config/
mod.rs

1//! NEST-21 · a service's configuration at runtime, in three layers.
2//!
3//! 1. **Settings.** A subsystem declares each knob once, as a typed
4//!    constant:
5//!
6//!    ```
7//!    use plexus_core::plexus::config::Setting;
8//!    pub const INSECURE_WS: Setting<bool> = plexus_core::setting!(
9//!        "transport.insecure_ws", default = false,
10//!        reload = Live, sensitivity = Public, scope = Service, critical = true,
11//!        doc = "plain ws:// to a host beyond loopback");
12//!    ```
13//!
14//!    Its schema is its type's `JsonSchema`. `reload` is [`Reload::Live`]
15//!    (applies at once, watchers told) or [`Reload::Restart`] (a runtime set
16//!    is stored and shown as `pending` until the service starts again).
17//!    [`Sensitivity::Secret`] is write-only: read back as set or unset and a
18//!    hash, never the value. `remote = false`: readable over the wire,
19//!    settable only from the host's code or its file. `critical = true`:
20//!    over the wire only by an admin (the grant `config.critical`) and only
21//!    as a confirmed commit — the seam SIGN-1's signed calls fill
22//!    (`signed(hardware, uv)`).
23//! 2. **The library.** [`Config`] is a capability handle, not a global: a
24//!    service holds one ([`DynamicHub::config`](super::DynamicHub::config))
25//!    and hands it to what it builds. [`Config::get`], [`Config::set`],
26//!    [`Config::reset`], [`Config::watch`], [`Config::list`],
27//!    [`Config::schema`]. Sources, lowest first: the default < the file <
28//!    a flag or the environment < a set at runtime ([`Source`]). A runtime
29//!    set is kept across a restart only when the host gives the store a file
30//!    ([`Config::with_file`]); at the next start the file's values are the
31//!    file layer, under the flags. Every set, reset, confirm and revert is
32//!    an audit record ([`ConfigRecord`]: who — the actor chain — when, the
33//!    key, the old and new value's hashes, never a value) on the
34//!    `plexus::audit` target DYNAUTH-7's records use, and to every
35//!    [`ConfigAudit`] sink.
36//! 3. **The `config` activation** ([`ConfigActivation`]): each key a dynamic
37//!    child — `config.{key}.get | set | reset | confirm`, `config.list`,
38//!    `config.watch` — granted per key through NEST-5's slot grants, and
39//!    admin's alone unless a role lists one. `set --confirm-within 60s`
40//!    applies at once and reverts unless `config.{key}.confirm` comes in
41//!    time.
42
43mod 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/// When a change to a setting takes effect.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
61#[serde(rename_all = "snake_case")]
62pub enum Reload {
63    /// At once: [`Config::get`] answers it and watchers are told.
64    Live,
65    /// At the next start: a runtime set is stored and shown as `pending`;
66    /// [`Config::get`] answers what the service started with.
67    Restart,
68}
69
70/// Whether a setting's value may be read back.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
72#[serde(rename_all = "snake_case")]
73pub enum Sensitivity {
74    /// Read back as it is.
75    Public,
76    /// Write-only: read back as set or unset and a hash (salted per process,
77    /// so it tells a change, never the value).
78    Secret,
79}
80
81/// What a setting governs.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
83#[serde(rename_all = "snake_case")]
84pub enum Scope {
85    /// This service.
86    Service,
87    /// The whole process (the log's redactor): the last service to set it wins.
88    Process,
89}
90
91/// Where a setting's value comes from, lowest first.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
93#[serde(rename_all = "snake_case")]
94pub enum Source {
95    /// The setting's own default.
96    Default,
97    /// The store's file, as read at start.
98    File,
99    /// A flag or the environment, given at start by the host.
100    Flag,
101    /// A set at runtime (the library or the `config` activation).
102    Runtime,
103}
104
105/// A value a setting may hold.
106pub trait SettingValue: Serialize + DeserializeOwned + JsonSchema + Clone + Send + Sync + 'static {}
107impl<T: Serialize + DeserializeOwned + JsonSchema + Clone + Send + Sync + 'static> SettingValue for T {}
108
109/// A setting, declared once by the subsystem it governs — usually through
110/// [`setting!`](crate::setting).
111pub struct Setting<T> {
112    /// Dotted, each segment `[a-z][a-z0-9_]*`: `transport.insecure_ws`.
113    pub key: &'static str,
114    /// What it governs, in a line.
115    pub doc: &'static str,
116    pub default: fn() -> T,
117    pub reload: Reload,
118    pub sensitivity: Sensitivity,
119    pub scope: Scope,
120    /// Settable over the wire (the `config` activation); `false`: only from
121    /// the host's code or the file.
122    pub remote: bool,
123    /// Over the wire, admin only and only as a confirmed commit (SIGN-1:
124    /// later `signed(hardware, uv)`).
125    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    /// `key` with `default`: live, public, the service's, settable over the
144    /// wire, not critical.
145    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/// Declare a [`Setting`]: `setting!("key", default = EXPR, reload = Live,
175/// sensitivity = Public, scope = Service, remote = false, critical = true,
176/// doc = "…")` — everything after `default` optional, in any order.
177#[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/// A duration as a setting holds it: `"5s"`, `"500ms"`, `"2m"`.
204#[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
255/// `5s`, `500ms`, `2m` (a bare number is seconds).
256pub 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
275/// The segments a key may not use: the key nodes' own methods.
276pub const RESERVED_SEGMENTS: &[&str] = &["get", "set", "reset", "confirm", "names", "list", "watch", "schema"];
277
278/// Whether `key` is a setting's key: dotted segments of `[a-z][a-z0-9_]*`,
279/// none of [`RESERVED_SEGMENTS`].
280pub 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
294/// Who did it: the principal, then each service it came through, nearest
295/// first — or `["host"]` for the host's own code.
296pub type Actor = Vec<String>;
297
298/// The actor of the running call: its caller as the gate admitted them (or
299/// the hop's chain, in a child), else the host.
300pub 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/// What an audit record is of.
317#[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    /// A set refused (over the wire: `remote = false`, critical without a
325    /// confirm, not admin).
326    Refused,
327}
328
329/// NEST-21: one audit record — never a value, only hashes.
330#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
331pub struct ConfigRecord {
332    pub action: ConfigAction,
333    pub key: String,
334    /// Who: the principal, then each service it came through.
335    pub actor: Actor,
336    /// Unix milliseconds.
337    pub at: i64,
338    /// The value in effect before, hashed.
339    #[serde(default, skip_serializing_if = "Option::is_none")]
340    pub old_hash: Option<String>,
341    /// The value set, hashed.
342    #[serde(default, skip_serializing_if = "Option::is_none")]
343    pub new_hash: Option<String>,
344    /// A confirmed commit's deadline (unix ms).
345    #[serde(default, skip_serializing_if = "Option::is_none")]
346    pub confirm_until: Option<i64>,
347    /// Why, for a refusal.
348    #[serde(default, skip_serializing_if = "Option::is_none")]
349    pub why: Option<String>,
350}
351
352/// NEST-21: where a configuration audit record goes besides `tracing`
353/// (`plexus::audit`, beside DYNAUTH-7's token records) — PRIVACY-1's sink,
354/// when there is one.
355pub trait ConfigAudit: Send + Sync {
356    fn record(&self, r: &ConfigRecord);
357}
358
359/// Why a set was refused by the library.
360#[derive(Debug, Clone, PartialEq, Eq)]
361pub enum ConfigError {
362    /// No setting has this key (a prefix of some: `keys` lists them).
363    Unknown { key: String, keys: Vec<String> },
364    /// The value does not fit the setting's type.
365    Invalid { key: String, message: String },
366    /// Nothing to confirm on this key.
367    NothingToConfirm { key: String },
368    /// The store's file could not be written.
369    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/// What a set replaced.
387#[derive(Debug, Clone, PartialEq)]
388pub struct Previous<T> {
389    /// The value in effect before.
390    pub value: T,
391    pub source: Source,
392}
393
394/// A setting as it stands, as `config.list` and `config.{key}.get` show it.
395#[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    /// The value in effect (`None` for a secret).
401    #[serde(default, skip_serializing_if = "Option::is_none")]
402    pub value: Option<Value>,
403    /// The value in effect, hashed (a secret's salted).
404    pub hash: String,
405    /// Set by anything above the default.
406    pub set: bool,
407    pub source: Source,
408    /// The default (`None` for a secret).
409    #[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    /// A `Restart` setting's runtime value, waiting for the next start
417    /// (`Some(null)` for a secret: one is waiting).
418    #[serde(default, skip_serializing_if = "Option::is_none")]
419    pub pending: Option<Value>,
420    /// A confirmed commit waiting: reverted at this time (unix ms) unless
421    /// confirmed.
422    #[serde(default, skip_serializing_if = "Option::is_none")]
423    pub confirm_until: Option<i64>,
424    /// Its type's JSON Schema.
425    pub schema: Value,
426}
427
428/// A change, as `config.watch` and [`Config::changes`] say it.
429#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
430pub struct ConfigChange {
431    pub action: ConfigAction,
432    pub key: String,
433    /// The value in effect now (`None` for a secret).
434    #[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    /// A `Restart` setting: stored, not in effect until the next start.
441    #[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    /// The runtime layer before the first unconfirmed set.
454    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    /// What `get` answers: the effective value (a `Restart` setting's: as
471    /// it was without its runtime layer).
472    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    /// Recompute what is applied; whether it moved.
498    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    /// The store's file, and what it holds (keys not declared yet too).
521    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/// NEST-21: a service's configuration — a capability handle, cheap to
530/// clone; every clone is the same store.
531#[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    /// A store kept in memory, with plexus-core's own settings declared
555    /// ([`settings::declare_core`]).
556    pub fn new() -> Self {
557        Self::build(None, BTreeMap::new())
558    }
559
560    /// A store kept in `file` (JSON, `{ "key": value }`, 0600): read now —
561    /// its values the file layer of each key, as it is declared — and
562    /// written at every runtime set and reset. A missing file is an empty
563    /// one.
564    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    /// Also record to `sink`.
593    pub fn with_audit(self, sink: Arc<dyn ConfigAudit>) -> Self {
594        self.add_audit(sink);
595        self
596    }
597
598    /// Also record to `sink` (on a shared handle).
599    pub fn add_audit(&self, sink: Arc<dyn ConfigAudit>) {
600        self.inner.audit.lock().unwrap().push(sink);
601    }
602
603    /// The store's file, if it has one.
604    pub fn file(&self) -> Option<&Path> {
605        self.inner.file.as_deref()
606    }
607
608    /// Whether two handles are the same store.
609    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    /// Declare `s` here (once; again is nothing). A key declared with
618    /// another type, or not a key, is refused, said loudly, and the first
619    /// declaration kept.
620    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    /// [`Config::declare`], saying why not.
627    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                // A CLI sends `--value true` as the string "true": read a
642                // string that does not fit as JSON.
643                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    /// What `s` is now (its default if its stored value no longer fits).
683    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    /// Where `s`'s value in effect comes from.
690    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    /// Set `s` at runtime, as the running call's caller (or the host).
696    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    /// Give `s` a value from below the runtime: the file's or a flag's —
705    /// what the host read at start. `None` takes it away.
706    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    /// Back to below the runtime (the flag's, the file's, the default), as
726    /// the running call's caller.
727    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    /// Watch `s`: its value now, and every change to what is in effect.
734    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    /// Call `f` with `s`'s value now and at every change of it — inside the
741    /// set that made it, after the store is unlocked. For a subsystem whose
742    /// state follows a setting (the redactor's keys).
743    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    /// Every change, as it is made.
757    pub fn changes(&self) -> tokio::sync::broadcast::Receiver<ConfigChange> {
758        self.inner.changes.subscribe()
759    }
760
761    /// Every setting declared, as it stands.
762    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    /// One setting, as it stands.
768    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    /// The keys declared.
774    pub fn keys(&self) -> Vec<String> {
775        self.inner.entries.lock().unwrap().keys().cloned().collect()
776    }
777
778    /// Every setting's JSON Schema, by key.
779    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    /// The facts the `config` activation decides on: `(remote, critical)`.
818    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    /// The untyped set the `config` activation makes: `value` checked
829    /// against the key's type, applied, stored, audited, said; with
830    /// `confirm_within`, reverted unless [`Config::confirm`] comes in time.
831    /// Answers the value in effect before and where it came from.
832    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                    // A set over a waiting one keeps the revert to the
849                    // value before the first.
850                    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    /// Take a key's runtime value away, as `actor`.
873    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    /// Keep the change waiting on `key`: it is not reverted.
895    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    /// Record a refusal the activation made (never the value).
915    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    /// The deadline of the change `generation` on `key` passed: undo it,
931    /// unless it was confirmed or another took its place.
932    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    /// Write `key`'s runtime value (or its absence) to the file, if there is one.
995    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
1009/// Write `text` to `file`, 0600, whole (a temporary beside it renamed in).
1010fn 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
1028/// A setting watched: its value now, and each change.
1029pub struct Watch<T> {
1030    rx: tokio::sync::watch::Receiver<Value>,
1031    default: fn() -> T,
1032}
1033
1034impl<T: SettingValue> Watch<T> {
1035    /// The value now.
1036    pub fn current(&self) -> T {
1037        serde_json::from_value(self.rx.borrow().clone()).unwrap_or_else(|_| (self.default)())
1038    }
1039
1040    /// The next change; `None` once the store is gone.
1041    pub async fn changed(&mut self) -> Option<T> {
1042        self.rx.changed().await.ok()?;
1043        Some(self.current())
1044    }
1045}