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