Skip to main content

renox_core/
settings.rs

1//! Typed settings kept in the database: a company's name and tax number, a
2//! document number format, which features are on. They are read quickly from
3//! any handler, job or command, edited by an administrator, and changed
4//! without a new `.env` or a deploy. Opt in with `App::module(Settings)`,
5//! which adds the `settings` table and the `settings:get`, `settings:set` and
6//! `settings:list` commands.
7//!
8//! A group of settings is a plain struct with defaults:
9//!
10//! ```
11//! use renox::prelude::*;
12//! use renox::settings::{Settings, SettingsGroup};
13//! use serde::{Deserialize, Serialize};
14//!
15//! #[derive(Serialize, Deserialize, Validate, Default, Clone)]
16//! pub struct Company {
17//!     #[validate(required, max(120))]
18//!     pub name: String,
19//!     pub tax_number: Option<String>,
20//!     #[validate(max(40))]
21//!     pub invoice_format: String, // "INV-{yyyy}-{0000}"
22//! }
23//!
24//! impl SettingsGroup for Company {
25//!     const KEY: &'static str = "company"; // one row per group
26//! }
27//!
28//! # fn app() -> App {
29//! App::new()
30//!     .module(Settings)          // the table and the commands
31//!     .settings::<Company>()     // declares the group
32//! # }
33//!
34//! # async fn demo(state: AppState, user: User) -> Result {
35//! // Read (cached; the first read of a group is one query):
36//! let company = state.settings::<Company>().await?; // Arc<Company>, the defaults until saved
37//! # let _ = company;
38//!
39//! // Write (validated with the struct's rules, audited when `Audit` is on):
40//! let mut company = Company { name: "Acme".into(), ..Company::default() };
41//! company.tax_number = Some("12.345.678".into());
42//! state.save_settings(&company, Some(&user)).await?;
43//! # Ok(()) }
44//! ```
45//!
46//! In a handler, the [`Setting`] extractor reads a group; in templates,
47//! `settings.company.name` works for the groups declared with
48//! `App::settings_in_views`. The guide is docs/settings.md.
49//!
50//! # How it is cached
51//!
52//! Each process keeps the groups it has read. A save replaces the group in
53//! the process that wrote it at once and stamps a version row in the `cache`
54//! table (`renox:settings:<key>`), so with several servers on one database
55//! the others notice: a process asks for that stamp (one small query) at
56//! most once a second per group and reloads the group when it changed.
57//! Between those checks a read costs no query.
58//!
59//! # Rules
60//!
61//! - A group's [`Validate`] rules run on every save
62//!   (`rules` only; the `authorize` and `after` hooks need a request).
63//!   Invalid values are rejected with the rules' messages.
64//! - `ENCRYPTED = true` stores the group sealed with `APP_KEY`, as
65//!   [`Encrypted`] columns are, for gateway keys and
66//!   other secrets. `settings:get` and `settings:list` print `<sealed>` for
67//!   it unless `--reveal` is given.
68//! - Fields a stored group lacks (added to the struct later) take the
69//!   struct's `Default`, so adding a setting needs no migration.
70//! - A *scope* names a variant of a group, such as one per company or
71//!   branch: `state.settings_in::<T>("branch-7")`. The default scope is `""`.
72//!   Scopes are for your code and the commands (`--scope`); the groups of
73//!   `App::settings_in_views` and the admin pages use the default scope.
74
75use std::any::{Any, TypeId};
76use std::collections::HashMap;
77use std::future::Future;
78use std::ops::Deref;
79use std::pin::Pin;
80use std::sync::{Arc, Mutex};
81
82use axum::extract::FromRequestParts;
83use axum::http::request::Parts;
84use serde::Serialize;
85use serde::de::DeserializeOwned;
86use serde_json::{Map, Value};
87
88use crate::auth::User;
89use crate::clock::Stamp;
90use crate::db::{DateTime, Encrypted, Migration, now, sql};
91use crate::events::Event;
92use crate::validation::Errors;
93use crate::{AppState, Error, Module, Registry, Result, Routes, Validate, Validator};
94
95const MIGRATIONS: &[Migration] = &[crate::db::framework_migration!(
96    "settings",
97    "00010101000400_create_settings_table"
98)];
99
100/// How long a process trusts the group it holds before asking the `cache`
101/// table whether another server changed it.
102const RECHECK: std::time::Duration = std::time::Duration::from_secs(1);
103
104/// A group of settings: a plain struct that serializes, validates and has
105/// defaults. Declare it with `App::settings::<T>()`, read it with
106/// [`AppState::settings`], change it with [`AppState::save_settings`].
107///
108/// ```
109/// use renox::prelude::*;
110/// use renox::settings::SettingsGroup;
111///
112/// #[derive(serde::Serialize, serde::Deserialize, Validate, Default, Clone)]
113/// struct Payments {
114///     #[validate(required)]
115///     secret_key: String,
116///     test_mode: bool,
117/// }
118///
119/// impl SettingsGroup for Payments {
120///     const KEY: &'static str = "payments";
121///     const ENCRYPTED: bool = true; // sealed with APP_KEY
122/// }
123/// ```
124pub trait SettingsGroup:
125    Serialize + DeserializeOwned + Validate + Default + Clone + Send + Sync + 'static
126{
127    /// The group's name: its row in the `settings` table, and the first part
128    /// of `settings:set company.name …`. Letters, digits, `_` and `-`.
129    const KEY: &'static str;
130
131    /// Seals the group with `APP_KEY` before it is stored (gateway keys,
132    /// tokens). The admin page and the commands then never show its values.
133    const ENCRYPTED: bool = false;
134}
135
136/// The opt-in module: the `settings` table and the `settings:get`,
137/// `settings:set` and `settings:list` commands. Groups are declared with
138/// `App::settings::<T>()`.
139///
140/// ```
141/// use renox::prelude::*;
142/// use renox::settings::Settings;
143///
144/// # let _ =
145/// App::new().module(Settings)
146/// # ;
147/// ```
148pub struct Settings;
149
150impl Module for Settings {
151    fn name(&self) -> &'static str {
152        "settings"
153    }
154
155    fn migrations(&self) -> &'static [Migration] {
156        MIGRATIONS
157    }
158
159    fn routes(&self) -> Routes {
160        Routes::new()
161    }
162
163    fn register(&self, app: &mut Registry) {
164        app.settings_module = true;
165        app.command(
166            "settings:get",
167            "Print a group or one setting: settings:get company[.name] [--scope S] [--reveal]",
168            |args, state| async move {
169                let path = args.positional().first().copied().unwrap_or_default();
170                let scope = args.value("--scope").unwrap_or_default();
171                if path.is_empty() {
172                    return Err(Error::BadRequest(
173                        "usage: settings:get <group>[.<field>] [--scope S] [--reveal]".into(),
174                    ));
175                }
176                println!(
177                    "{}",
178                    describe(&state, path, scope, args.has("--reveal")).await?
179                );
180                Ok(())
181            },
182        );
183        app.command(
184            "settings:set",
185            "Change one setting, validated: settings:set company.name \"Acme\" [--scope S]",
186            |args, state| async move {
187                let words = args.positional();
188                let (Some(path), Some(text)) = (words.first(), words.get(1)) else {
189                    return Err(Error::BadRequest(
190                        "usage: settings:set <group>.<field> <value> [--scope S]".into(),
191                    ));
192                };
193                let scope = args.value("--scope").unwrap_or_default();
194                set_from_text(&state, path, text, scope).await?;
195                println!("Saved {path}.");
196                Ok(())
197            },
198        );
199        app.command(
200            "settings:list",
201            "Print every declared group: settings:list [--scope S] [--reveal]",
202            |args, state| async move {
203                let scope = args.value("--scope").unwrap_or_default();
204                println!(
205                    "{}",
206                    describe_all(&state, scope, args.has("--reveal")).await?
207                );
208                Ok(())
209            },
210        );
211    }
212}
213
214/// A group of settings was saved. Emitted by [`AppState::save_settings`],
215/// the commands and the admin page; listen for it to warm a cache or notify
216/// someone, without needing `Audit`.
217///
218/// ```
219/// use renox::prelude::*;
220/// use renox::settings::SettingsChanged;
221///
222/// # let _ =
223/// App::new().listen(|changed: SettingsChanged, _state| async move {
224///     println!("{} changed: {}", changed.key, changed.changed.join(", "));
225///     Ok(())
226/// })
227/// # ;
228/// ```
229#[derive(Debug, Clone)]
230#[non_exhaustive]
231pub struct SettingsChanged {
232    /// The group's [`SettingsGroup::KEY`].
233    pub key: String,
234    /// The scope, `""` for the default one.
235    pub scope: String,
236    /// The user who saved it, if one did (not for a seed or a command).
237    pub actor: Option<i64>,
238    /// The names of the fields whose values changed.
239    pub changed: Vec<String>,
240    /// The group before, as JSON (the defaults when it was never saved).
241    /// `null` for an encrypted group: only `changed` tells what moved.
242    pub previous: Value,
243    /// The group after, as JSON; `null` for an encrypted group.
244    pub current: Value,
245}
246
247impl Event for SettingsChanged {}
248
249/// When a group was last saved, and by whom.
250#[derive(Debug, Clone)]
251#[non_exhaustive]
252pub struct SettingInfo {
253    /// When the row was last written.
254    pub updated_at: DateTime,
255    /// The user who wrote it, when one did.
256    pub updated_by: Option<i64>,
257}
258
259/// A group of settings as a handler's argument: the same as
260/// `state.settings::<T>()`.
261///
262/// ```
263/// use renox::prelude::*;
264/// use renox::settings::{Setting, SettingsGroup};
265///
266/// #[derive(serde::Serialize, serde::Deserialize, Validate, Default, Clone)]
267/// struct Company { name: String }
268/// impl SettingsGroup for Company { const KEY: &'static str = "company"; }
269///
270/// async fn footer(company: Setting<Company>) -> String {
271///     format!("© {}", company.name) // `Setting` derefs to `Company`
272/// }
273/// ```
274pub struct Setting<T>(pub Arc<T>);
275
276impl<T> Deref for Setting<T> {
277    type Target = T;
278
279    fn deref(&self) -> &T {
280        &self.0
281    }
282}
283
284impl<T: SettingsGroup> FromRequestParts<AppState> for Setting<T> {
285    type Rejection = Error;
286
287    async fn from_request_parts(
288        _: &mut Parts,
289        state: &AppState,
290    ) -> std::result::Result<Self, Error> {
291        state.settings::<T>().await.map(Setting)
292    }
293}
294
295// ---------------------------------------------------------------------
296// What the app declares
297// ---------------------------------------------------------------------
298
299/// What checking a value against a group found.
300pub(crate) enum Checked {
301    /// Valid: the group as it will be stored.
302    Valid(Value),
303    /// The value fits the struct but its rules failed.
304    Invalid(Errors),
305    /// The value doesn't fit the struct's types.
306    Mismatch(String),
307}
308
309type CheckFn =
310    fn(AppState, Value, Option<User>) -> Pin<Box<dyn Future<Output = Result<Checked>> + Send>>;
311
312/// A group an app or module declared (`App::settings`).
313#[derive(Clone)]
314pub(crate) struct Group {
315    pub(crate) key: &'static str,
316    pub(crate) type_id: TypeId,
317    pub(crate) encrypted: bool,
318    pub(crate) shared: bool,
319    pub(crate) default: Value,
320    check: CheckFn,
321}
322
323impl Group {
324    pub(crate) fn of<T: SettingsGroup>() -> Self {
325        assert!(
326            !T::KEY.is_empty()
327                && T::KEY.len() <= 64
328                && T::KEY
329                    .chars()
330                    .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
331            "SettingsGroup::KEY `{}` may only have letters, digits, `_` and `-`",
332            T::KEY
333        );
334        Self {
335            key: T::KEY,
336            type_id: TypeId::of::<T>(),
337            encrypted: T::ENCRYPTED,
338            shared: false,
339            default: serde_json::to_value(T::default()).unwrap_or(Value::Null),
340            check: check_erased::<T>,
341        }
342    }
343}
344
345fn check_erased<T: SettingsGroup>(
346    state: AppState,
347    json: Value,
348    actor: Option<User>,
349) -> Pin<Box<dyn Future<Output = Result<Checked>> + Send>> {
350    Box::pin(check::<T>(state, json, actor))
351}
352
353async fn check<T: SettingsGroup>(
354    state: AppState,
355    json: Value,
356    actor: Option<User>,
357) -> Result<Checked> {
358    let merged = overlay(serde_json::to_value(T::default())?, json);
359    let mut value: T = match serde_json::from_value(merged) {
360        Ok(value) => value,
361        Err(err) => return Ok(Checked::Mismatch(err.to_string())),
362    };
363    value.prepare();
364    let errors = Validator::rules_of(&value)
365        .finish_for(&state, actor.as_ref())
366        .await?;
367    if !errors.is_empty() {
368        return Ok(Checked::Invalid(errors));
369    }
370    Ok(Checked::Valid(serde_json::to_value(&value)?))
371}
372
373/// `over`'s fields on top of `base`'s (one level), so a stored group that
374/// lacks a field added later takes its default.
375fn overlay(base: Value, over: Value) -> Value {
376    match (base, over) {
377        (Value::Object(mut base), Value::Object(over)) => {
378            for (name, value) in over {
379                base.insert(name, value);
380            }
381            Value::Object(base)
382        }
383        (_, over) => over,
384    }
385}
386
387impl Registry {
388    /// Declares a group of settings, as `App::settings` does: the commands
389    /// and the admin pages find it by [`SettingsGroup::KEY`]. Needs the
390    /// [`Settings`] module (boot says so if it is missing). Declaring the
391    /// same type twice keeps one.
392    ///
393    /// # Panics
394    ///
395    /// If the group's key has characters other than letters, digits, `_`
396    /// and `-`.
397    pub fn settings<T: SettingsGroup>(&mut self) -> &mut Self {
398        if !self
399            .settings_groups
400            .iter()
401            .any(|g| g.type_id == TypeId::of::<T>())
402        {
403            self.settings_groups.push(Group::of::<T>());
404        }
405        self
406    }
407
408    /// Declares a group like [`Registry::settings`] and gives every view its
409    /// default-scope values as `settings.<key>` (`settings.company.name`).
410    ///
411    /// # Panics
412    ///
413    /// For an `ENCRYPTED` group, which must not reach templates.
414    pub fn settings_in_views<T: SettingsGroup>(&mut self) -> &mut Self {
415        assert!(
416            !T::ENCRYPTED,
417            "settings_in_views::<{}>: an encrypted group can't be shared with views",
418            T::KEY
419        );
420        self.settings::<T>();
421        if let Some(group) = self
422            .settings_groups
423            .iter_mut()
424            .find(|g| g.type_id == TypeId::of::<T>())
425        {
426            group.shared = true;
427        }
428        self
429    }
430}
431
432// ---------------------------------------------------------------------
433// The per-process cache
434// ---------------------------------------------------------------------
435
436struct Entry {
437    json: Arc<Value>,
438    /// The `cache` row's value when this was loaded (`None`: never saved).
439    version: Option<String>,
440    checked: Stamp,
441    /// The group as its struct, once someone asked for it.
442    typed: Option<Arc<dyn Any + Send + Sync>>,
443}
444
445/// The groups the app declared, the seed file's values and the loaded groups.
446pub(crate) struct Store {
447    groups: Vec<Group>,
448    seed: Option<Map<String, Value>>,
449    cache: Mutex<HashMap<(String, String), Entry>>,
450}
451
452impl Store {
453    pub(crate) fn new(groups: Vec<Group>, seed: Option<Map<String, Value>>) -> Self {
454        Self {
455            groups,
456            seed,
457            cache: Mutex::default(),
458        }
459    }
460
461    pub(crate) fn group(&self, key: &str) -> Option<&Group> {
462        self.groups.iter().find(|g| g.key == key)
463    }
464
465    pub(crate) fn groups(&self) -> &[Group] {
466        &self.groups
467    }
468
469    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<(String, String), Entry>> {
470        self.cache.lock().unwrap_or_else(|e| e.into_inner())
471    }
472}
473
474/// Reads the seed file `App::settings_from` names: a JSON object of groups.
475/// A missing file is no seed (a first run may not have one yet).
476pub(crate) fn read_seed(path: &std::path::Path) -> Result<Option<Map<String, Value>>> {
477    let text = match std::fs::read_to_string(path) {
478        Ok(text) => text,
479        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
480        Err(err) => {
481            return Err(anyhow::anyhow!("can't read {}: {err}", path.display()).into());
482        }
483    };
484    match serde_json::from_str::<Value>(&text) {
485        Ok(Value::Object(map)) => Ok(Some(map)),
486        Ok(_) => Err(anyhow::anyhow!(
487            "{}: the settings file must be a JSON object of groups, e.g. {{\"company\": {{\"name\": \"Acme\"}}}}",
488            path.display()
489        )
490        .into()),
491        Err(err) => Err(anyhow::anyhow!("{}: {err}", path.display()).into()),
492    }
493}
494
495fn version_key(key: &str, scope: &str) -> String {
496    if scope.is_empty() {
497        format!("renox:settings:{key}")
498    } else {
499        format!("renox:settings:{key}@{scope}")
500    }
501}
502
503fn new_version() -> String {
504    format!("{}-{}", crate::clock::unix_millis(), crate::random_token())
505}
506
507/// Top-level field names whose values differ.
508fn changed_fields(previous: &Value, current: &Value) -> Vec<String> {
509    let empty = Map::new();
510    let (before, after) = (
511        previous.as_object().unwrap_or(&empty),
512        current.as_object().unwrap_or(&empty),
513    );
514    let mut names: Vec<String> = after
515        .keys()
516        .chain(before.keys())
517        .filter(|name| before.get(*name) != after.get(*name))
518        .cloned()
519        .collect();
520    names.sort();
521    names.dedup();
522    names
523}
524
525// ---------------------------------------------------------------------
526// Reading and writing
527// ---------------------------------------------------------------------
528
529type DefaultFn<'a> = &'a (dyn Fn() -> Result<Value> + Sync);
530
531impl AppState {
532    /// The default-scope group `T`: what was saved, with the struct's
533    /// defaults for anything missing; the defaults before anything was saved.
534    /// Cached in this process, so a read is free until someone saves (see
535    /// the [module](crate::settings) for how other servers notice).
536    ///
537    /// ```
538    /// # use renox::prelude::*;
539    /// # use renox::settings::SettingsGroup;
540    /// # #[derive(serde::Serialize, serde::Deserialize, Validate, Default, Clone)]
541    /// # struct Company { name: String }
542    /// # impl SettingsGroup for Company { const KEY: &'static str = "company"; }
543    /// # async fn demo(state: AppState) -> Result {
544    /// let company = state.settings::<Company>().await?;
545    /// println!("{}", company.name);
546    /// # Ok(()) }
547    /// ```
548    pub async fn settings<T: SettingsGroup>(&self) -> Result<Arc<T>> {
549        self.settings_in::<T>("").await
550    }
551
552    /// Like [`AppState::settings`] for a scope: one variant of the group per
553    /// company, branch or account (`""` is the default scope).
554    pub async fn settings_in<T: SettingsGroup>(&self, scope: &str) -> Result<Arc<T>> {
555        let default = || Ok(serde_json::to_value(T::default())?);
556        let (json, typed) = self
557            .settings_entry(T::KEY, scope, T::ENCRYPTED, &default)
558            .await?;
559        if let Some(typed) = typed
560            && let Ok(typed) = typed.downcast::<T>()
561        {
562            return Ok(typed);
563        }
564        let value: T = serde_json::from_value((*json).clone()).map_err(|err| {
565            anyhow::anyhow!(
566                "the stored `{}` settings don't fit {}: {err}",
567                T::KEY,
568                std::any::type_name::<T>()
569            )
570        })?;
571        let value = Arc::new(value);
572        let mut cache = self.settings_store.lock();
573        if let Some(entry) = cache.get_mut(&(T::KEY.to_owned(), scope.to_owned()))
574            && Arc::ptr_eq(&entry.json, &json)
575        {
576            entry.typed = Some(value.clone());
577        }
578        Ok(value)
579    }
580
581    /// Saves the default-scope group `T`, after its rules pass (invalid
582    /// values are a `ValidationError` with the rules' messages and nothing
583    /// is written). The change is seen at once in this process and within a
584    /// second by the other servers; it emits [`SettingsChanged`], and the
585    /// `Audit` module (when on) records it. `by` is who changed it.
586    ///
587    /// ```
588    /// # use renox::prelude::*;
589    /// # use renox::settings::SettingsGroup;
590    /// # #[derive(serde::Serialize, serde::Deserialize, Validate, Default, Clone)]
591    /// # struct Company { name: String }
592    /// # impl SettingsGroup for Company { const KEY: &'static str = "company"; }
593    /// # async fn demo(state: AppState, user: User) -> Result {
594    /// let mut company = (*state.settings::<Company>().await?).clone();
595    /// company.name = "Acme".into();
596    /// state.save_settings(&company, Some(&user)).await?;
597    /// # Ok(()) }
598    /// ```
599    pub async fn save_settings<T: SettingsGroup>(&self, value: &T, by: Option<&User>) -> Result {
600        self.save_settings_in(value, "", by).await
601    }
602
603    /// Like [`AppState::save_settings`] for a scope.
604    pub async fn save_settings_in<T: SettingsGroup>(
605        &self,
606        value: &T,
607        scope: &str,
608        by: Option<&User>,
609    ) -> Result {
610        let mut value = value.clone();
611        value.prepare();
612        let errors = Validator::rules_of(&value).finish_for(self, by).await?;
613        if !errors.is_empty() {
614            return Err(errors.into());
615        }
616        let json = serde_json::to_value(&value)?;
617        let typed: Arc<dyn Any + Send + Sync> = Arc::new(value);
618        self.commit_settings(
619            T::KEY,
620            scope,
621            T::ENCRYPTED,
622            json,
623            by.map(|u| u.id),
624            Some(typed),
625        )
626        .await
627    }
628
629    /// When the default-scope group `T` was last saved and by whom; `None`
630    /// while it never was (the defaults are in use).
631    pub async fn settings_info<T: SettingsGroup>(&self) -> Result<Option<SettingInfo>> {
632        self.settings_info_in::<T>("").await
633    }
634
635    /// Like [`AppState::settings_info`] for a scope.
636    pub async fn settings_info_in<T: SettingsGroup>(
637        &self,
638        scope: &str,
639    ) -> Result<Option<SettingInfo>> {
640        let row = sql("SELECT updated_at, updated_by FROM settings WHERE key = ? AND scope = ?")
641            .bind(T::KEY)
642            .bind(scope)
643            .fetch_optional(&self.db)
644            .await?;
645        row.map(|row| {
646            Ok(SettingInfo {
647                updated_at: row.try_get("updated_at")?,
648                updated_by: row.try_get("updated_by")?,
649            })
650        })
651        .transpose()
652    }
653
654    /// The group `key` as JSON (the declared defaults under what was saved),
655    /// for the commands, the admin panel and views.
656    pub(crate) async fn settings_json(&self, key: &str, scope: &str) -> Result<Arc<Value>> {
657        let group = self.declared_settings(key)?;
658        let default = group.default.clone();
659        let default = move || Ok(default.clone());
660        let (json, _) = self
661            .settings_entry(group.key, scope, group.encrypted, &default)
662            .await?;
663        Ok(json)
664    }
665
666    pub(crate) fn declared_settings(&self, key: &str) -> Result<&Group> {
667        self.settings_store.group(key).ok_or_else(|| {
668            let known: Vec<&str> = self.settings_store.groups().iter().map(|g| g.key).collect();
669            Error::BadRequest(format!(
670                "no settings group `{key}` (declared: {})",
671                if known.is_empty() {
672                    "none".into()
673                } else {
674                    known.join(", ")
675                }
676            ))
677        })
678    }
679
680    /// `settings` for the views: every shared group, by key.
681    pub(crate) async fn settings_for_views(&self) -> Result<Value> {
682        let mut all = Map::new();
683        for group in self.settings_store.groups().iter().filter(|g| g.shared) {
684            let json = self.settings_json(group.key, "").await?;
685            all.insert(group.key.to_owned(), (*json).clone());
686        }
687        Ok(Value::Object(all))
688    }
689
690    /// Checks `json` against the group `key`'s types and rules, and saves
691    /// it. The path the commands take.
692    pub(crate) async fn save_settings_json(
693        &self,
694        key: &str,
695        scope: &str,
696        json: Value,
697        by: Option<&User>,
698    ) -> Result {
699        let group = self.declared_settings(key)?;
700        match (group.check)(self.clone(), json, by.cloned()).await? {
701            Checked::Valid(json) => {
702                self.commit_settings(
703                    group.key,
704                    scope,
705                    group.encrypted,
706                    json,
707                    by.map(|u| u.id),
708                    None,
709                )
710                .await
711            }
712            Checked::Invalid(errors) => Err(errors.into()),
713            Checked::Mismatch(message) => Err(Error::BadRequest(message)),
714        }
715    }
716
717    /// The group's cached JSON and typed value, loading it when this
718    /// process has none or another server may have changed it.
719    async fn settings_entry(
720        &self,
721        key: &str,
722        scope: &str,
723        encrypted: bool,
724        default: DefaultFn<'_>,
725    ) -> Result<(Arc<Value>, Option<Arc<dyn Any + Send + Sync>>)> {
726        let id = (key.to_owned(), scope.to_owned());
727        let known = {
728            let cache = self.settings_store.lock();
729            match cache.get(&id) {
730                Some(entry) if entry.checked.elapsed() < RECHECK => {
731                    return Ok((entry.json.clone(), entry.typed.clone()));
732                }
733                Some(entry) => Some(entry.version.clone()),
734                None => None,
735            }
736        };
737        if let Some(known) = known {
738            let current: Option<String> = sql("SELECT value FROM cache WHERE key = ?")
739                .bind(version_key(key, scope))
740                .scalar_optional(&self.db)
741                .await?;
742            let mut cache = self.settings_store.lock();
743            if let Some(entry) = cache.get_mut(&id)
744                && entry.version == known
745                && current == known
746            {
747                entry.checked = Stamp::now();
748                return Ok((entry.json.clone(), entry.typed.clone()));
749            }
750        }
751        let (json, version) = self
752            .load_settings(key, scope, encrypted, default, true)
753            .await?;
754        let json = Arc::new(json);
755        self.settings_store.lock().insert(
756            id,
757            Entry {
758                json: json.clone(),
759                version,
760                checked: Stamp::now(),
761                typed: None,
762            },
763        );
764        Ok((json, None))
765    }
766
767    /// One query: the group's row and the version stamp. A group never
768    /// saved is the defaults, or what the seed file says.
769    async fn load_settings(
770        &self,
771        key: &str,
772        scope: &str,
773        encrypted: bool,
774        default: DefaultFn<'_>,
775        seeding: bool,
776    ) -> Result<(Value, Option<String>)> {
777        let row = sql(
778            "SELECT (SELECT value FROM cache WHERE key = ?) AS version, \
779             (SELECT value FROM settings WHERE key = ? AND scope = ?) AS value",
780        )
781        .bind(version_key(key, scope))
782        .bind(key)
783        .bind(scope)
784        .fetch_one(&self.db)
785        .await?;
786        let version: Option<String> = row.try_get("version")?;
787        let stored: Option<Value> = if encrypted {
788            row.try_get::<Option<Encrypted<Value>>>("value")?
789                .map(Encrypted::into_inner)
790        } else {
791            row.try_get::<Option<String>>("value")?
792                .map(|text| serde_json::from_str(&text))
793                .transpose()?
794        };
795        match stored {
796            Some(stored) => Ok((overlay(default()?, stored), version)),
797            None if seeding && scope.is_empty() && self.seed_for(key).is_some() => {
798                self.apply_seed(key, encrypted).await?;
799                Box::pin(self.load_settings(key, scope, encrypted, default, false)).await
800            }
801            None => Ok((default()?, version)),
802        }
803    }
804
805    fn seed_for(&self, key: &str) -> Option<&Value> {
806        self.settings_store
807            .seed
808            .as_ref()
809            .and_then(|seed| seed.get(key))
810            .filter(|_| self.settings_store.group(key).is_some())
811    }
812
813    /// Stores the seed file's values for `key` unless a row exists.
814    async fn apply_seed(&self, key: &str, encrypted: bool) -> Result {
815        let (Some(seed), Some(group)) = (self.seed_for(key), self.settings_store.group(key)) else {
816            return Ok(());
817        };
818        let json = match (group.check)(self.clone(), seed.clone(), None).await? {
819            Checked::Valid(json) => json,
820            Checked::Invalid(errors) => {
821                return Err(anyhow::anyhow!(
822                    "the settings file's `{key}` is invalid: {}",
823                    errors
824                        .iter()
825                        .flat_map(|(field, m)| m.iter().map(move |m| format!("{field}: {m}")))
826                        .collect::<Vec<_>>()
827                        .join("; ")
828                )
829                .into());
830            }
831            Checked::Mismatch(message) => {
832                return Err(
833                    anyhow::anyhow!("the settings file's `{key}` doesn't fit: {message}").into(),
834                );
835            }
836        };
837        let mut tx = self.db.begin().await?;
838        let inserted = write_row(&mut tx, key, "", encrypted, &json, None, true).await?;
839        if inserted > 0 {
840            stamp_version(&mut tx, key, "").await?;
841        }
842        tx.commit().await?;
843        Ok(())
844    }
845
846    /// Writes the group, stamps the version, refreshes this process's copy
847    /// and emits the event.
848    async fn commit_settings(
849        &self,
850        key: &str,
851        scope: &str,
852        encrypted: bool,
853        json: Value,
854        actor: Option<i64>,
855        typed: Option<Arc<dyn Any + Send + Sync>>,
856    ) -> Result {
857        let group_default = self.settings_store.group(key).map(|g| g.default.clone());
858        let mut tx = self.db.begin().await?;
859        let row = sql("SELECT value FROM settings WHERE key = ? AND scope = ?")
860            .bind(key)
861            .bind(scope)
862            .fetch_optional(&mut tx)
863            .await?;
864        let before: Option<Value> = match row {
865            None => None,
866            Some(row) if encrypted => Some(row.try_get::<Encrypted<Value>>("value")?.into_inner()),
867            Some(row) => Some(serde_json::from_str(&row.try_get::<String>("value")?)?),
868        };
869        let previous = before.clone().or(group_default).unwrap_or(Value::Null);
870        let changed = changed_fields(&previous, &json);
871        if before.is_some() && changed.is_empty() {
872            return Ok(());
873        }
874        write_row(&mut tx, key, scope, encrypted, &json, actor, false).await?;
875        let version = stamp_version(&mut tx, key, scope).await?;
876        tx.commit().await?;
877        self.settings_store.lock().insert(
878            (key.to_owned(), scope.to_owned()),
879            Entry {
880                json: Arc::new(json.clone()),
881                version: Some(version),
882                checked: Stamp::now(),
883                typed,
884            },
885        );
886        let shown = |value: Value| if encrypted { Value::Null } else { value };
887        self.emit(SettingsChanged {
888            key: key.to_owned(),
889            scope: scope.to_owned(),
890            actor,
891            changed,
892            previous: shown(previous),
893            current: shown(json),
894        })
895        .await
896    }
897}
898
899/// Inserts or replaces the row; `insert_only` leaves an existing one alone.
900async fn write_row(
901    tx: &mut crate::db::Transaction,
902    key: &str,
903    scope: &str,
904    encrypted: bool,
905    json: &Value,
906    actor: Option<i64>,
907    insert_only: bool,
908) -> Result<u64> {
909    let conflict = if insert_only {
910        "DO NOTHING"
911    } else {
912        "DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at, \
913         updated_by = excluded.updated_by"
914    };
915    let statement = sql(format!(
916        "INSERT INTO settings (key, scope, value, updated_at, updated_by) \
917         VALUES (?, ?, ?, ?, ?) ON CONFLICT (key, scope) {conflict}"
918    ))
919    .bind(key)
920    .bind(scope);
921    let statement = if encrypted {
922        statement.bind(Encrypted::new(json.clone()))
923    } else {
924        statement.bind(json.to_string())
925    };
926    Ok(statement.bind(now()).bind(actor).execute(&mut *tx).await?)
927}
928
929/// A new version stamp in the `cache` table, which other servers compare.
930async fn stamp_version(tx: &mut crate::db::Transaction, key: &str, scope: &str) -> Result<String> {
931    let version = new_version();
932    sql(
933        "INSERT INTO cache (key, value, expires_at) VALUES (?, ?, NULL) \
934         ON CONFLICT (key) DO UPDATE SET value = excluded.value, expires_at = NULL",
935    )
936    .bind(version_key(key, scope))
937    .bind(version.clone())
938    .execute(&mut *tx)
939    .await?;
940    Ok(version)
941}
942
943// ---------------------------------------------------------------------
944// What the commands run
945// ---------------------------------------------------------------------
946
947/// A path like `company` or `company.name` split into the group and the
948/// field path under it.
949fn split_path(path: &str) -> (&str, Vec<&str>) {
950    let mut parts = path.split('.');
951    let key = parts.next().unwrap_or_default();
952    (key, parts.filter(|p| !p.is_empty()).collect())
953}
954
955fn show(value: &Value) -> String {
956    match value {
957        Value::String(text) => text.clone(),
958        other => other.to_string(),
959    }
960}
961
962/// What `settings:get <group>[.<field>]` prints: the group as JSON, or one
963/// field's value. An encrypted group is `<sealed>` unless `reveal`.
964///
965/// ```
966/// # use renox::prelude::*;
967/// # async fn demo(state: AppState) -> Result {
968/// let text = renox::settings::describe(&state, "company.name", "", false).await?;
969/// # let _ = text; Ok(()) }
970/// ```
971pub async fn describe(state: &AppState, path: &str, scope: &str, reveal: bool) -> Result<String> {
972    let (key, fields) = split_path(path);
973    let group = state.declared_settings(key)?;
974    if group.encrypted && !reveal {
975        return Ok("<sealed>".into());
976    }
977    let json = state.settings_json(key, scope).await?;
978    let mut at = &*json;
979    for field in &fields {
980        at = at.get(*field).ok_or_else(|| {
981            Error::BadRequest(format!(
982                "the `{key}` settings have no field `{}`",
983                fields.join(".")
984            ))
985        })?;
986    }
987    if fields.is_empty() {
988        Ok(serde_json::to_string_pretty(at)?)
989    } else {
990        Ok(show(at))
991    }
992}
993
994/// What `settings:list` prints: a line per declared group.
995pub async fn describe_all(state: &AppState, scope: &str, reveal: bool) -> Result<String> {
996    let mut lines = Vec::new();
997    for group in state.settings_store.groups() {
998        let value = if group.encrypted && !reveal {
999            "<sealed>".to_owned()
1000        } else {
1001            state.settings_json(group.key, scope).await?.to_string()
1002        };
1003        lines.push(format!("{} = {value}", group.key));
1004    }
1005    if lines.is_empty() {
1006        lines.push("No settings groups are declared (App::settings::<T>()).".into());
1007    }
1008    Ok(lines.join("\n"))
1009}
1010
1011/// What `settings:set <group>.<field> <value>` does: sets one field of a
1012/// group and saves it, after the group's types and rules accept it. The text
1013/// is read as JSON when it is (`true`, `42`, `["a"]`), else as a string.
1014///
1015/// ```
1016/// # use renox::prelude::*;
1017/// # async fn demo(state: AppState) -> Result {
1018/// renox::settings::set_from_text(&state, "company.name", "Acme", "").await?;
1019/// # Ok(()) }
1020/// ```
1021pub async fn set_from_text(state: &AppState, path: &str, text: &str, scope: &str) -> Result {
1022    let (key, fields) = split_path(path);
1023    if fields.is_empty() {
1024        return Err(Error::BadRequest(
1025            "name a field: settings:set <group>.<field> <value>".into(),
1026        ));
1027    }
1028    let group = state.declared_settings(key)?;
1029    let current = state.settings_json(key, scope).await?;
1030    if current.get(fields[0]).is_none() {
1031        return Err(Error::BadRequest(format!(
1032            "the `{key}` settings have no field `{}`",
1033            fields[0]
1034        )));
1035    }
1036    let mut candidates = Vec::new();
1037    if let Ok(parsed) = serde_json::from_str::<Value>(text)
1038        && !parsed.is_string()
1039    {
1040        candidates.push(parsed);
1041    }
1042    candidates.push(Value::String(text.to_owned()));
1043    if text.is_empty() {
1044        candidates.push(Value::Null);
1045    }
1046    let (mut invalid, mut mismatch) = (None, None);
1047    for candidate in candidates {
1048        let mut json = (*current).clone();
1049        let mut at = &mut json;
1050        for field in &fields[..fields.len() - 1] {
1051            if !at.get(*field).is_some_and(Value::is_object) {
1052                at[*field] = Value::Object(Map::new());
1053            }
1054            at = &mut at[*field];
1055        }
1056        at[fields[fields.len() - 1]] = candidate;
1057        match (group.check)(state.clone(), json, None).await? {
1058            Checked::Valid(json) => {
1059                return state.save_settings_json(key, scope, json, None).await;
1060            }
1061            Checked::Invalid(errors) => {
1062                invalid.get_or_insert(errors);
1063            }
1064            Checked::Mismatch(message) => {
1065                mismatch.get_or_insert(message);
1066            }
1067        }
1068    }
1069    if let Some(errors) = invalid {
1070        let lines: Vec<String> = errors
1071            .iter()
1072            .flat_map(|(field, messages)| {
1073                messages.iter().map(move |m| format!("{key}.{field}: {m}"))
1074            })
1075            .collect();
1076        return Err(Error::BadRequest(lines.join("\n")));
1077    }
1078    Err(Error::BadRequest(format!(
1079        "`{text}` doesn't fit {path}: {}",
1080        mismatch.unwrap_or_default()
1081    )))
1082}