Skip to main content

plexus_core/plexus/config/
activation.rs

1//! NEST-21 · the `config` activation: a service's settings over Plexus.
2//!
3//! ```text
4//! config.list                          every setting, as it stands
5//! config.watch { key? }                each change, as it is made (open-ended)
6//! config.names                         the first segments (the slot's names)
7//! config.{key}.get                     one setting
8//! config.{key}.set { value, confirm_within? }
9//! config.{key}.reset                   back to the flag's, the file's or the default
10//! config.{key}.confirm                 keep a change made with confirm_within
11//! ```
12//!
13//! A key is a path of dynamic children (`config.transport.insecure_ws.set`):
14//! the slot `config.{key}` is typed (each method its grant,
15//! `config.{key}.set`); below it the slot repeats its own type, so it is
16//! untyped there (`config.{key}.{key}`, every method). Admin holds all of
17//! them; a role holds one key's method by listing its path
18//! (`config.transport.insecure_ws.get`), the literal grant NEST-5 keeps.
19//!
20//! Over the wire a setting declared `remote = false` is refused
21//! (`not_remote`); a `critical` one needs the grant [`CRITICAL_GRANT`]
22//! (admin's unless a role lists it) and a `confirm_within` (SIGN-1 turns
23//! this into a signed call). A secret is never read back.
24
25use async_stream::stream;
26use futures::Stream;
27use schemars::JsonSchema;
28use serde::{Deserialize, Serialize};
29use serde_json::Value;
30
31use super::{current_actor, parse_duration, Config, ConfigChange, ConfigError, KeyInfo, Source};
32use crate::plexus::AuthContext;
33
34/// The grant a critical setting's set, reset and confirm need beside the
35/// key's own: listed by no role, so an admin's alone. SIGN-1's
36/// `signed(hardware, uv)` takes its place.
37pub const CRITICAL_GRANT: &str = "config.critical";
38
39/// Why the `config` activation refused.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
41#[serde(rename_all = "snake_case")]
42pub enum ConfigRefusal {
43    /// No setting has this key.
44    UnknownKey,
45    /// A prefix of keys, not a key.
46    NotAKey,
47    /// The value does not fit the key's type (or `confirm_within` is not a
48    /// duration).
49    Invalid,
50    /// Declared `remote = false`: the host's code or file alone sets it.
51    NotRemote,
52    /// A critical setting: an admin's (`config.critical`).
53    Critical,
54    /// A critical setting is set as a confirmed commit (`confirm_within`).
55    ConfirmRequired,
56    /// Nothing waits to be confirmed.
57    NothingToConfirm,
58    /// The store's file could not be written (the change is in effect).
59    Store,
60}
61
62/// What the `config` activation answers.
63#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
64#[serde(tag = "type", rename_all = "snake_case")]
65pub enum SettingEvent {
66    /// A setting as it stands.
67    Setting(KeyInfo),
68    /// Set: what was in effect before (a secret's hash only) and what is
69    /// now; `confirm_until` when it reverts unless confirmed.
70    Set {
71        key: String,
72        #[serde(default, skip_serializing_if = "Option::is_none")]
73        previous: Option<Value>,
74        previous_hash: String,
75        previous_source: Source,
76        setting: KeyInfo,
77    },
78    /// Back to below the runtime.
79    Reset { setting: KeyInfo },
80    /// The change waiting on `key` is kept.
81    Confirmed { key: String },
82    /// Refused, and why in a word.
83    Refused { reason: ConfigRefusal, key: String, message: String },
84    /// Why not.
85    Error { message: String },
86}
87
88impl plexus_client::FromClientError for SettingEvent {
89    fn from_client_error(e: plexus_client::ClientError) -> Self {
90        SettingEvent::Error { message: e.to_string() }
91    }
92}
93
94fn refused(reason: ConfigRefusal, key: &str, message: impl Into<String>) -> SettingEvent {
95    SettingEvent::Refused { reason, key: key.into(), message: message.into() }
96}
97
98fn of_error(e: ConfigError) -> SettingEvent {
99    let reason = match &e {
100        ConfigError::Unknown { keys, .. } if !keys.is_empty() => ConfigRefusal::NotAKey,
101        ConfigError::Unknown { .. } => ConfigRefusal::UnknownKey,
102        ConfigError::Invalid { .. } => ConfigRefusal::Invalid,
103        ConfigError::NothingToConfirm { .. } => ConfigRefusal::NothingToConfirm,
104        ConfigError::Store { .. } => ConfigRefusal::Store,
105    };
106    let key = match &e {
107        ConfigError::Unknown { key, .. } | ConfigError::Invalid { key, .. } | ConfigError::NothingToConfirm { key } => key.clone(),
108        ConfigError::Store { .. } => String::new(),
109    };
110    refused(reason, &key, e.to_string())
111}
112
113/// The names one level below `prefix` (`""`: the first segments).
114fn names_below(config: &Config, prefix: &str) -> Vec<String> {
115    let mut out: Vec<String> = config
116        .keys()
117        .into_iter()
118        .filter_map(|k| {
119            let rest = if prefix.is_empty() { Some(k.as_str()) } else { k.strip_prefix(prefix).and_then(|r| r.strip_prefix('.')) }?;
120            Some(rest.split('.').next().unwrap_or(rest).to_string())
121        })
122        .collect();
123    out.dedup();
124    out
125}
126
127/// The `config` activation: a service's settings, each key a dynamic child.
128#[derive(Clone)]
129pub struct ConfigActivation {
130    config: Config,
131}
132
133impl ConfigActivation {
134    /// Serve `config` (the service's: [`DynamicHub::config`]).
135    ///
136    /// [`DynamicHub::config`]: crate::plexus::DynamicHub::config
137    pub fn new(config: Config) -> Self {
138        Self { config }
139    }
140
141    /// The store it serves.
142    pub fn config(&self) -> &Config {
143        &self.config
144    }
145
146    fn node(&self, name: &str) -> Option<ConfigKeyActivation> {
147        let path = name.to_string();
148        let prefix = format!("{path}.");
149        self.config.keys().iter().any(|k| *k == path || k.starts_with(&prefix)).then(|| ConfigKeyActivation { config: self.config.clone(), path })
150    }
151}
152
153/// A service's settings: read, set, reset and watch them, each key on its
154/// own grant.
155#[plexus_macros::activation(namespace = "config", description = "A service's settings at runtime: each key a node, on its own grant")]
156impl ConfigActivation {
157    /// Every setting, as it stands (a secret as set or not and a hash).
158    #[plexus_macros::method]
159    pub async fn list(&self) -> impl Stream<Item = KeyInfo> + Send + 'static {
160        futures::stream::iter(self.config.list())
161    }
162
163    /// Each change as it is made — set, reset, confirmed, reverted — of
164    /// every setting, or of `key` and the keys under it. Open-ended.
165    #[plexus_macros::method]
166    pub async fn watch(&self, key: Option<String>) -> impl Stream<Item = ConfigChange> + Send + 'static {
167        let mut rx = self.config.changes();
168        stream! {
169            loop {
170                match rx.recv().await {
171                    Ok(c) => {
172                        if key.as_deref().is_none_or(|k| c.key == k || c.key.starts_with(&format!("{k}."))) {
173                            yield c;
174                        }
175                    }
176                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
177                    Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
178                }
179            }
180        }
181    }
182
183    /// The first segments of the keys: the slot's names.
184    #[plexus_macros::method]
185    pub async fn names(&self) -> impl Stream<Item = String> + Send + 'static {
186        futures::stream::iter(names_below(&self.config, ""))
187    }
188
189    /// A setting, or a group of them: `config.<segment>…`.
190    #[plexus_macros::child(list = names)]
191    fn key(&self, name: &str) -> Option<ConfigKeyActivation> {
192        self.node(name)
193    }
194}
195
196/// One node of the key tree: a setting (`transport.insecure_ws`) or a group
197/// of them (`transport`).
198#[derive(Clone)]
199pub struct ConfigKeyActivation {
200    config: Config,
201    path: String,
202}
203
204impl ConfigKeyActivation {
205    /// The dotted path it stands for.
206    pub fn path(&self) -> &str {
207        &self.path
208    }
209
210    fn is_key(&self) -> Result<(bool, bool), SettingEvent> {
211        match self.config.flags(&self.path) {
212            Some(f) => Ok(f),
213            None => Err(of_error(ConfigError::Unknown { key: self.path.clone(), keys: self.config.keys().into_iter().filter(|k| k.starts_with(&format!("{}.", self.path))).collect() })),
214        }
215    }
216
217    /// A write over the wire: refused for a `remote = false` key, and for a
218    /// critical one unless the caller holds [`CRITICAL_GRANT`] (and, for a
219    /// set, gives `confirm_within`).
220    fn may_write(&self, auth: Option<&AuthContext>, confirming: Option<bool>) -> Result<(), SettingEvent> {
221        let (remote, critical) = self.is_key()?;
222        let refuse = |reason, why: String| {
223            self.config.refused(&self.path, current_actor(), &why);
224            Err(refused(reason, &self.path, why))
225        };
226        if !remote {
227            return refuse(ConfigRefusal::NotRemote, format!("`{}` is not settable over the wire: the host's code or its file sets it", self.path));
228        }
229        if critical {
230            if !holds_critical(auth) {
231                return refuse(ConfigRefusal::Critical, format!("`{}` is critical: an admin's (the grant `{CRITICAL_GRANT}`)", self.path));
232            }
233            if confirming == Some(false) {
234                return refuse(ConfigRefusal::ConfirmRequired, format!("`{}` is critical: set it with confirm_within (a confirmed commit), then confirm", self.path));
235            }
236        }
237        Ok(())
238    }
239
240    fn info(&self) -> KeyInfo {
241        self.config.info(&self.path).expect("a key")
242    }
243}
244
245/// Whether the caller holds [`CRITICAL_GRANT`] by the service's gate (a
246/// service without one admits every call, as it always has).
247fn holds_critical(auth: Option<&AuthContext>) -> bool {
248    let gate = crate::plexus::service_scope::current().and_then(|w| w.upgrade()).and_then(|s| s.gate().cloned());
249    match gate {
250        None => true,
251        Some(g) => g.check(auth, &plexus_auth_core::grants::Grant::new(CRITICAL_GRANT), None).is_ok(),
252    }
253}
254
255/// A setting (or a group of them).
256#[plexus_macros::activation(namespace = "config_key", description = "A setting: get, set, reset, confirm")]
257impl ConfigKeyActivation {
258    /// The setting as it stands: its value (a secret's hash only), where it
259    /// comes from, its default, how it reloads, its type's schema.
260    #[plexus_macros::method]
261    pub async fn get(&self) -> SettingEvent {
262        match self.is_key() {
263            Ok(_) => SettingEvent::Setting(self.info()),
264            Err(e) => e,
265        }
266    }
267
268    /// Set it at runtime. `value` in the setting's type (a string is read
269    /// as JSON when it does not fit as text: `--value true`).
270    /// `confirm_within` (`60s`): applied at once, reverted unless
271    /// `confirm` comes in time — so a change that cuts the caller off undoes
272    /// itself.
273    #[plexus_macros::method]
274    pub async fn set(&self, auth: Option<&AuthContext>, value: Value, confirm_within: Option<String>) -> SettingEvent {
275        let within = match confirm_within.as_deref().map(parse_duration).transpose() {
276            Ok(w) => w,
277            Err(why) => return refused(ConfigRefusal::Invalid, &self.path, format!("confirm_within: {why}")),
278        };
279        if let Err(e) = self.may_write(auth, Some(within.is_some())) {
280            return e;
281        }
282        match self.config.set_value(&self.path, value, within, current_actor()) {
283            Ok((previous, previous_source)) => {
284                let setting = self.info();
285                let secret = setting.value.is_none();
286                let previous_hash = if secret { String::new() } else { crate::plexus::content_hash::hash16(crate::plexus::content_hash::canonical_json(&previous).as_bytes()) };
287                SettingEvent::Set { key: self.path.clone(), previous: (!secret).then_some(previous), previous_hash, previous_source, setting }
288            }
289            Err(e) => of_error(e),
290        }
291    }
292
293    /// Take its runtime value away: back to the flag's, the file's or the
294    /// default.
295    #[plexus_macros::method]
296    pub async fn reset(&self, auth: Option<&AuthContext>) -> SettingEvent {
297        if let Err(e) = self.may_write(auth, None) {
298            return e;
299        }
300        match self.config.reset_key(&self.path, current_actor()) {
301            Ok(()) => SettingEvent::Reset { setting: self.info() },
302            Err(e) => of_error(e),
303        }
304    }
305
306    /// Keep the change made with `confirm_within`.
307    #[plexus_macros::method]
308    pub async fn confirm(&self, auth: Option<&AuthContext>) -> SettingEvent {
309        if let Err(e) = self.may_write(auth, None) {
310            return e;
311        }
312        match self.config.confirm(&self.path, current_actor()) {
313            Ok(()) => SettingEvent::Confirmed { key: self.path.clone() },
314            Err(e) => of_error(e),
315        }
316    }
317
318    /// The names one level below it.
319    #[plexus_macros::method]
320    pub async fn names(&self) -> impl Stream<Item = String> + Send + 'static {
321        futures::stream::iter(names_below(&self.config, &self.path))
322    }
323
324    /// The next segment of a key below it.
325    #[plexus_macros::child(list = names)]
326    fn key(&self, name: &str) -> Option<ConfigKeyActivation> {
327        let path = format!("{}.{name}", self.path);
328        let prefix = format!("{path}.");
329        self.config.keys().iter().any(|k| *k == path || k.starts_with(&prefix)).then(|| ConfigKeyActivation { config: self.config.clone(), path })
330    }
331}