Skip to main content

micromegas/
settings.rs

1//! DB-backed deployment settings.
2//!
3//! The `settings` table (data-lake migration v12) is a generic key/value store. [`SETTINGS`] is
4//! the registry of keys a service understands: it drives the admin page and holds the single
5//! validation rule shared by the write path and the loader. A key with no row is "unset", and the
6//! consuming service falls back to the env var, then to the built-in default.
7//!
8//! Each service caches the whole table through [`SnapshotSource`], the same cache the
9//! audience-grant and group stores use, and reads typed values through [`SettingsSource`].
10
11use anyhow::{Context, Result, anyhow, bail};
12use async_trait::async_trait;
13use micromegas_analytics::delete::{MAX_RETENTION_DAYS, PayloadRetention, RetentionHorizon};
14use micromegas_analytics::lakehouse::datafusion_config::{
15    DataFusionConfigOverrides, DataFusionConfigSource,
16};
17use micromegas_analytics::lakehouse::read_scope::IsolationConfig;
18use micromegas_auth::db_audience_grants::DbAudienceGrantsConfig;
19use micromegas_auth::db_snapshot::{SnapshotLoader, SnapshotSource};
20use micromegas_tracing::prelude::*;
21use sqlx::{PgPool, Row};
22use std::collections::BTreeMap;
23use std::sync::{Arc, Mutex};
24use std::time::Duration;
25
26pub const PUBLIC_VIEW_SETS: &str = "public_view_sets";
27pub const RETENTION_DAYS: &str = "retention_days";
28pub const RETENTION_BY_STREAM_TAG: &str = "retention_by_stream_tag";
29pub const DATAFUSION_CONFIG_QUERY: &str = "datafusion_config_query";
30pub const DATAFUSION_CONFIG_MAINTENANCE: &str = "datafusion_config_maintenance";
31pub const DEPLOYMENT_NOTES: &str = "deployment_notes";
32pub const SELF_SERVICE_MINT: &str = "self_service_mint";
33pub const SELF_SERVICE_MAX_CLAIMS_PER_CALLER: &str = "self_service_max_claims_per_caller";
34pub const SELF_SERVICE_MAX_KEYS_PER_CALLER: &str = "self_service_max_keys_per_caller";
35pub const SELF_SERVICE_MAX_GRANTS_PER_CALLER: &str = "self_service_max_grants_per_caller";
36
37const DEFAULT_RETENTION_DAYS: u32 = 90;
38const DEFAULT_MAX_CLAIMS_PER_CALLER: i64 = 25;
39const DEFAULT_MAX_KEYS_PER_CALLER: i64 = 100;
40const DEFAULT_MAX_GRANTS_PER_CALLER: i64 = 50;
41
42/// The JSON shape a setting's value must have.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum SettingKind {
45    Bool,
46    /// JSON integer in `0..=i64::MAX`.
47    Count,
48    /// JSON array of non-empty, trimmed, unique strings with no `[`, `]` or `"`.
49    NameList,
50    /// JSON integer in `1..=MAX_RETENTION_DAYS`.
51    Days,
52    /// JSON object mapping a stream tag to a `Days` integer or the string `"forever"`.
53    TagHorizons,
54    /// JSON object mapping a DataFusion config key to a string, number or boolean value.
55    DataFusionConfig,
56    /// JSON string holding a markdown document.
57    Markdown,
58}
59
60impl SettingKind {
61    pub fn as_str(&self) -> &'static str {
62        match self {
63            SettingKind::Bool => "bool",
64            SettingKind::Count => "count",
65            SettingKind::NameList => "name_list",
66            SettingKind::Days => "days",
67            SettingKind::TagHorizons => "tag_horizons",
68            SettingKind::DataFusionConfig => "datafusion_config",
69            SettingKind::Markdown => "markdown",
70        }
71    }
72}
73
74/// One registered setting.
75#[derive(Debug)]
76pub struct SettingSpec {
77    pub key: &'static str,
78    /// `None` for a setting with no env fallback.
79    pub env_var: Option<&'static str>,
80    pub kind: SettingKind,
81    /// JSON text of the built-in default, shown in the admin page.
82    pub default: &'static str,
83    pub description: &'static str,
84}
85
86pub const SETTINGS: &[SettingSpec] = &[
87    SettingSpec {
88        key: PUBLIC_VIEW_SETS,
89        env_var: Some("MICROMEGAS_PUBLIC_VIEW_SETS"),
90        kind: SettingKind::NameList,
91        default: "[]",
92        description: "View sets exempt from the row-level audience filter: every caller sees all of their rows.",
93    },
94    SettingSpec {
95        key: RETENTION_DAYS,
96        env_var: Some("MICROMEGAS_RETENTION_DAYS"),
97        kind: SettingKind::Days,
98        default: "90",
99        description: "Default number of days raw payloads (blocks) and lakehouse partitions are kept.",
100    },
101    SettingSpec {
102        key: RETENTION_BY_STREAM_TAG,
103        env_var: None,
104        kind: SettingKind::TagHorizons,
105        default: "{}",
106        description: "Per stream tag override of how long raw payloads are kept: a number of days or \"forever\". A stream with several overridden tags keeps the longest.",
107    },
108    SettingSpec {
109        key: DATAFUSION_CONFIG_QUERY,
110        env_var: None,
111        kind: SettingKind::DataFusionConfig,
112        default: "{}",
113        description: "DataFusion config overrides for every FlightSQL query session, e.g. {\"datafusion.execution.target_partitions\": 2}. Parquet page-index reading, span collection and the information schema are fixed and cannot be overridden; merges keep their own forced optimizer settings.",
114    },
115    SettingSpec {
116        key: DATAFUSION_CONFIG_MAINTENANCE,
117        env_var: None,
118        kind: SettingKind::DataFusionConfig,
119        default: "{}",
120        description: "DataFusion config overrides for the maintenance daemon's materialization and merge sessions, e.g. {\"datafusion.execution.target_partitions\": 2}. Parquet page-index reading, span collection and the information schema are fixed and cannot be overridden; merges keep their own forced optimizer settings.",
121    },
122    SettingSpec {
123        key: SELF_SERVICE_MINT,
124        env_var: Some("MICROMEGAS_SELF_SERVICE_MINT"),
125        kind: SettingKind::Bool,
126        default: "false",
127        description: "Let non-admin callers mint their own ingestion keys and manage audience grants.",
128    },
129    SettingSpec {
130        key: SELF_SERVICE_MAX_CLAIMS_PER_CALLER,
131        env_var: Some("MICROMEGAS_SELF_SERVICE_MAX_CLAIMS_PER_CALLER"),
132        kind: SettingKind::Count,
133        default: "25",
134        description: "Maximum number of distinct audiences one non-admin caller may claim.",
135    },
136    SettingSpec {
137        key: SELF_SERVICE_MAX_KEYS_PER_CALLER,
138        env_var: Some("MICROMEGAS_SELF_SERVICE_MAX_KEYS_PER_CALLER"),
139        kind: SettingKind::Count,
140        default: "100",
141        description: "Maximum number of ingestion keys a non-admin caller may hold.",
142    },
143    SettingSpec {
144        key: SELF_SERVICE_MAX_GRANTS_PER_CALLER,
145        env_var: Some("MICROMEGAS_SELF_SERVICE_MAX_GRANTS_PER_CALLER"),
146        kind: SettingKind::Count,
147        default: "50",
148        description: "Maximum number of audience grants one non-admin caller may have created, excluding their own user:<email> rows.",
149    },
150    SettingSpec {
151        key: DEPLOYMENT_NOTES,
152        env_var: None,
153        kind: SettingKind::Markdown,
154        default: "\"\"",
155        description: "Markdown notes about this deployment for everyone querying it (environment conventions, preferred views, row counts, stricter time windows). Served by deployment_notes() and read by the micromegas-query skill.",
156    },
157];
158
159/// Looks a key up in [`SETTINGS`].
160pub fn find_spec(key: &str) -> Option<&'static SettingSpec> {
161    SETTINGS.iter().find(|s| s.key == key)
162}
163
164impl SettingSpec {
165    /// The single validation rule used by the PUT handler and the loader.
166    pub fn validate(&self, value: &serde_json::Value) -> Result<()> {
167        match self.kind {
168            SettingKind::Bool => {
169                if !value.is_boolean() {
170                    bail!("{}: expected a JSON boolean", self.key);
171                }
172            }
173            SettingKind::Count => {
174                if value.as_i64().is_none_or(|n| n < 0) {
175                    bail!(
176                        "{}: expected a JSON integer between 0 and {}",
177                        self.key,
178                        i64::MAX
179                    );
180                }
181            }
182            SettingKind::NameList => {
183                name_list(self.key, value)?;
184            }
185            SettingKind::Days => {
186                days(self.key, value)?;
187            }
188            SettingKind::TagHorizons => {
189                parse_tag_horizons(self.key, value)?;
190            }
191            SettingKind::DataFusionConfig => {
192                DataFusionConfigOverrides::parse_strict(value)
193                    .with_context(|| format!("{}: invalid DataFusion config", self.key))?;
194            }
195            SettingKind::Markdown => {
196                if !value.is_string() {
197                    bail!("{}: expected a JSON string", self.key);
198                }
199            }
200        }
201        Ok(())
202    }
203}
204
205fn days(key: &str, value: &serde_json::Value) -> Result<u32> {
206    value
207        .as_u64()
208        .filter(|n| (1..=u64::from(MAX_RETENTION_DAYS)).contains(n))
209        .map(|n| n as u32)
210        .ok_or_else(|| anyhow!("{key}: expected a JSON integer between 1 and {MAX_RETENTION_DAYS}"))
211}
212
213/// Parses `{tag: days | "forever"}`.
214pub fn parse_tag_horizons(
215    key: &str,
216    value: &serde_json::Value,
217) -> Result<BTreeMap<String, RetentionHorizon>> {
218    let map = value
219        .as_object()
220        .ok_or_else(|| anyhow!("{key}: expected a JSON object of tag to days or \"forever\""))?;
221    let mut out = BTreeMap::new();
222    for (tag, horizon) in map {
223        if tag.is_empty() {
224            bail!("{key}: empty tag");
225        }
226        if tag.trim() != tag {
227            bail!("{key}: tag {tag:?} has leading or trailing whitespace");
228        }
229        let horizon = if horizon.as_str() == Some("forever") {
230            RetentionHorizon::Forever
231        } else {
232            RetentionHorizon::Days(days(key, horizon).map_err(|_| {
233                anyhow!(
234                    "{key}: horizon for tag {tag:?} must be an integer between 1 and {MAX_RETENTION_DAYS}, or \"forever\""
235                )
236            })?)
237        };
238        out.insert(tag.clone(), horizon);
239    }
240    Ok(out)
241}
242
243fn name_list(key: &str, value: &serde_json::Value) -> Result<Vec<String>> {
244    let items = value
245        .as_array()
246        .ok_or_else(|| anyhow!("{key}: expected a JSON array of strings"))?;
247    let mut names: Vec<String> = Vec::with_capacity(items.len());
248    for item in items {
249        let name = item
250            .as_str()
251            .ok_or_else(|| anyhow!("{key}: entry {item} is not a string"))?;
252        if name.is_empty() {
253            bail!("{key}: empty entry");
254        }
255        if name.trim() != name {
256            bail!("{key}: entry {name:?} has leading or trailing whitespace");
257        }
258        if name.contains(['[', ']', '"']) {
259            bail!("{key}: entry {name:?} contains '[', ']', or '\"'");
260        }
261        if names.iter().any(|n| n == name) {
262            bail!("{key}: duplicate entry {name:?}");
263        }
264        names.push(name.to_string());
265    }
266    Ok(names)
267}
268
269/// Self-service knobs resolved to concrete values.
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub struct SelfServiceSettings {
272    pub mint_enabled: bool,
273    pub max_claims_per_caller: i64,
274    pub max_keys_per_caller: i64,
275    pub max_grants_per_caller: i64,
276}
277
278impl Default for SelfServiceSettings {
279    fn default() -> Self {
280        Self {
281            mint_enabled: false,
282            max_claims_per_caller: DEFAULT_MAX_CLAIMS_PER_CALLER,
283            max_keys_per_caller: DEFAULT_MAX_KEYS_PER_CALLER,
284            max_grants_per_caller: DEFAULT_MAX_GRANTS_PER_CALLER,
285        }
286    }
287}
288
289/// The DB values, already parsed into typed fields. `None` means no row (or an unregistered key).
290#[derive(Debug, Default)]
291pub struct DbOverrides {
292    pub isolation: Option<Arc<IsolationConfig>>,
293    pub self_service_mint: Option<bool>,
294    pub max_claims_per_caller: Option<i64>,
295    pub max_keys_per_caller: Option<i64>,
296    pub max_grants_per_caller: Option<i64>,
297    pub retention_days: Option<u32>,
298    pub retention_by_stream_tag: Option<BTreeMap<String, RetentionHorizon>>,
299    pub datafusion_config_query: Option<Arc<DataFusionConfigOverrides>>,
300    pub datafusion_config_maintenance: Option<Arc<DataFusionConfigOverrides>>,
301    pub deployment_notes: Option<Arc<str>>,
302}
303
304impl DbOverrides {
305    /// Builds the typed set from `(key, value)` rows. Keys missing from [`SETTINGS`] are ignored,
306    /// because during a rolling upgrade a newer replica may have written keys an older one does
307    /// not know. A known key that fails validation fails the whole parse rather than falling back
308    /// to env for that key, which could silently widen exposure. The DataFusion config keys are
309    /// the exception: an entry DataFusion rejects (removed or renamed by an upgrade) is skipped
310    /// with a warning, since failing the load would take isolation and self-service down too.
311    /// Only a non-object value fails the parse.
312    pub fn from_rows<I>(rows: I) -> Result<Self>
313    where
314        I: IntoIterator<Item = (String, serde_json::Value)>,
315    {
316        let mut out = Self::default();
317        for (key, value) in rows {
318            let Some(spec) = find_spec(&key) else {
319                continue;
320            };
321            if spec.kind != SettingKind::DataFusionConfig {
322                spec.validate(&value)
323                    .with_context(|| format!("invalid stored value for settings.{key}"))?;
324            }
325            match spec.key {
326                PUBLIC_VIEW_SETS => {
327                    out.isolation = Some(Arc::new(IsolationConfig {
328                        public_view_sets: name_list(spec.key, &value)?,
329                    }));
330                }
331                SELF_SERVICE_MINT => out.self_service_mint = value.as_bool(),
332                SELF_SERVICE_MAX_CLAIMS_PER_CALLER => out.max_claims_per_caller = value.as_i64(),
333                SELF_SERVICE_MAX_KEYS_PER_CALLER => out.max_keys_per_caller = value.as_i64(),
334                SELF_SERVICE_MAX_GRANTS_PER_CALLER => out.max_grants_per_caller = value.as_i64(),
335                RETENTION_DAYS => out.retention_days = Some(days(spec.key, &value)?),
336                RETENTION_BY_STREAM_TAG => {
337                    out.retention_by_stream_tag = Some(parse_tag_horizons(spec.key, &value)?);
338                }
339                DATAFUSION_CONFIG_QUERY | DATAFUSION_CONFIG_MAINTENANCE => {
340                    let parsed = DataFusionConfigOverrides::parse_lenient(&value)
341                        .with_context(|| format!("invalid stored value for settings.{key}"))?;
342                    if spec.key == DATAFUSION_CONFIG_QUERY {
343                        out.datafusion_config_query = Some(Arc::new(parsed));
344                    } else {
345                        out.datafusion_config_maintenance = Some(Arc::new(parsed));
346                    }
347                }
348                DEPLOYMENT_NOTES => {
349                    out.deployment_notes = value.as_str().map(Arc::from);
350                }
351                other => bail!("settings key {other:?} is registered but not handled"),
352            }
353        }
354        Ok(out)
355    }
356
357    /// Keys that have a stored value.
358    pub fn stored_keys(&self) -> Vec<&'static str> {
359        let mut keys = Vec::new();
360        if self.isolation.is_some() {
361            keys.push(PUBLIC_VIEW_SETS);
362        }
363        if self.self_service_mint.is_some() {
364            keys.push(SELF_SERVICE_MINT);
365        }
366        if self.max_claims_per_caller.is_some() {
367            keys.push(SELF_SERVICE_MAX_CLAIMS_PER_CALLER);
368        }
369        if self.max_keys_per_caller.is_some() {
370            keys.push(SELF_SERVICE_MAX_KEYS_PER_CALLER);
371        }
372        if self.max_grants_per_caller.is_some() {
373            keys.push(SELF_SERVICE_MAX_GRANTS_PER_CALLER);
374        }
375        if self.retention_days.is_some() {
376            keys.push(RETENTION_DAYS);
377        }
378        if self.retention_by_stream_tag.is_some() {
379            keys.push(RETENTION_BY_STREAM_TAG);
380        }
381        if self.datafusion_config_query.is_some() {
382            keys.push(DATAFUSION_CONFIG_QUERY);
383        }
384        if self.datafusion_config_maintenance.is_some() {
385            keys.push(DATAFUSION_CONFIG_MAINTENANCE);
386        }
387        if self.deployment_notes.is_some() {
388            keys.push(DEPLOYMENT_NOTES);
389        }
390        keys
391    }
392}
393
394/// [`SnapshotLoader`] for the `settings` table.
395#[derive(Debug)]
396pub struct SettingsLoader;
397
398#[async_trait]
399impl SnapshotLoader for SettingsLoader {
400    type Snapshot = DbOverrides;
401    const NAME: &'static str = "settings store";
402
403    async fn fetch(pool: &PgPool) -> Result<DbOverrides> {
404        // Read as text and parsed here so the crate does not need sqlx's `json` feature.
405        let rows = sqlx::query("SELECT key, value::text AS value FROM settings")
406            .fetch_all(pool)
407            .await
408            .context("querying settings")?;
409        let mut pairs = Vec::with_capacity(rows.len());
410        for row in rows {
411            let key: String = row.try_get("key").context("reading key")?;
412            let raw: String = row.try_get("value").context("reading value")?;
413            let value = serde_json::from_str(&raw)
414                .with_context(|| format!("parsing stored value for settings.{key}"))?;
415            pairs.push((key, value));
416        }
417        DbOverrides::from_rows(pairs)
418    }
419
420    fn count_refresh_error() {
421        micromegas_tracing::imetric!("settings_refresh_error_count", "count", 1_u64);
422    }
423}
424
425/// Parses a boolean env knob the `v == "true" || v == "1"` way.
426pub fn resolve_bool_env(var: &str, default: bool) -> bool {
427    std::env::var(var)
428        .map(|v| v == "true" || v == "1")
429        .unwrap_or(default)
430}
431
432/// Parses an unsigned integer env knob, warn-and-default on an unparseable value. Parsing
433/// unsigned makes a negative value a parse failure, and `0` a valid "none permitted".
434pub fn resolve_u64_env(var: &str, default: u64) -> u64 {
435    match std::env::var(var) {
436        Ok(raw) => raw.parse::<u64>().unwrap_or_else(|_| {
437            warn!("Invalid {var} value '{raw}', using default {default}");
438            default
439        }),
440        Err(_) => default,
441    }
442}
443
444/// Same as [`resolve_u64_env`], for a knob stored as `i64` downstream: a value that overflows
445/// `i64` warns and defaults rather than wrapping negative.
446pub fn resolve_i64_env(var: &str, default: i64) -> i64 {
447    let value = resolve_u64_env(var, default as u64);
448    i64::try_from(value).unwrap_or_else(|_| {
449        warn!("{var} value {value} exceeds i64::MAX, using default {default}");
450        default
451    })
452}
453
454/// The env-and-default half of the resolution order, resolved once per process at startup.
455#[derive(Debug, Clone)]
456pub struct EnvFallbacks {
457    pub isolation: Arc<IsolationConfig>,
458    pub self_service: SelfServiceSettings,
459    /// Fallback for `retention_days`; the maintenance services overwrite it through
460    /// [`EnvFallbacks::with_deprecated_retention_days`].
461    pub retention_days: u32,
462}
463
464impl EnvFallbacks {
465    /// Fails fast on a malformed `MICROMEGAS_PUBLIC_VIEW_SETS`.
466    pub fn from_env() -> Result<Self> {
467        let isolation = Arc::new(IsolationConfig::from_env()?);
468        let spec = |key| {
469            find_spec(key)
470                .expect("registered key")
471                .env_var
472                .expect("setting has an env var")
473        };
474        let self_service = SelfServiceSettings {
475            mint_enabled: resolve_bool_env(spec(SELF_SERVICE_MINT), false),
476            max_claims_per_caller: resolve_i64_env(
477                spec(SELF_SERVICE_MAX_CLAIMS_PER_CALLER),
478                DEFAULT_MAX_CLAIMS_PER_CALLER,
479            ),
480            max_keys_per_caller: resolve_i64_env(
481                spec(SELF_SERVICE_MAX_KEYS_PER_CALLER),
482                DEFAULT_MAX_KEYS_PER_CALLER,
483            ),
484            max_grants_per_caller: resolve_i64_env(
485                spec(SELF_SERVICE_MAX_GRANTS_PER_CALLER),
486                DEFAULT_MAX_GRANTS_PER_CALLER,
487            ),
488        };
489        Ok(Self {
490            isolation,
491            self_service,
492            retention_days: DEFAULT_RETENTION_DAYS,
493        })
494    }
495
496    /// Applies the deprecated `--retention-days` flag / `MICROMEGAS_RETENTION_DAYS` value, if
497    /// one was given, and warns that it will stop being read.
498    pub fn with_deprecated_retention_days(mut self, retention_days: Option<u32>) -> Self {
499        if let Some(days) = retention_days {
500            warn!(
501                "--retention-days / MICROMEGAS_RETENTION_DAYS is deprecated and will be removed in the next release; set the `{RETENTION_DAYS}` setting instead (Admin -> Settings)"
502            );
503            self.retention_days = days;
504        }
505        self
506    }
507}
508
509/// `MICROMEGAS_AUTH_CACHE_TTL_SECONDS`, which governs every snapshot cache in the process.
510pub fn settings_cache_ttl() -> Duration {
511    Duration::from_secs(DbAudienceGrantsConfig::from_env_with_prefix("").cache_ttl_secs)
512}
513
514enum Backing {
515    Db(SnapshotSource<SettingsLoader>),
516    Fixed(Arc<DbOverrides>),
517}
518
519/// Typed access to the settings, resolving DB row, then env var, then built-in default.
520pub struct SettingsSource {
521    db: Backing,
522    env: EnvFallbacks,
523}
524
525impl std::fmt::Debug for SettingsSource {
526    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
527        f.debug_struct("SettingsSource").finish_non_exhaustive()
528    }
529}
530
531impl SettingsSource {
532    /// `env` is already resolved by the caller; `pool` should be small and bounded (e.g. from
533    /// `dedicated_key_store_pool`, or the service's existing key-store pool).
534    pub fn new(env: EnvFallbacks, pool: PgPool, ttl: Duration) -> Self {
535        Self {
536            db: Backing::Db(SnapshotSource::new(pool, ttl)),
537            env,
538        }
539    }
540
541    /// For a process with no telemetry-DB pool configured.
542    pub fn env_only(env: EnvFallbacks) -> Self {
543        Self::with_overrides(env, DbOverrides::default())
544    }
545
546    /// An explicit isolation config that ignores both env and DB, for `with_isolation_config`
547    /// and tests. The self-service half is the built-in defaults, and the DataFusion config
548    /// overrides are empty.
549    pub fn pinned(isolation: Arc<IsolationConfig>) -> Self {
550        Self::env_only(EnvFallbacks {
551            isolation,
552            self_service: SelfServiceSettings::default(),
553            retention_days: DEFAULT_RETENTION_DAYS,
554        })
555    }
556
557    /// A fixed set of DB values, never reading process env or a database.
558    pub fn with_overrides(env: EnvFallbacks, db: DbOverrides) -> Self {
559        Self {
560            db: Backing::Fixed(Arc::new(db)),
561            env,
562        }
563    }
564
565    /// The env-resolved isolation config, with no DB access. Used where the value has no effect
566    /// (auth disabled makes every scope `ReadScope::All`).
567    pub fn env_isolation_config(&self) -> Arc<IsolationConfig> {
568        self.env.isolation.clone()
569    }
570
571    async fn overrides(&self) -> Result<Arc<DbOverrides>> {
572        match &self.db {
573            Backing::Db(source) => source.current().await,
574            Backing::Fixed(fixed) => Ok(fixed.clone()),
575        }
576    }
577
578    pub async fn isolation_config(&self) -> Result<Arc<IsolationConfig>> {
579        let overrides = self.overrides().await?;
580        Ok(overrides
581            .isolation
582            .clone()
583            .unwrap_or_else(|| self.env.isolation.clone()))
584    }
585
586    pub async fn self_service(&self) -> Result<SelfServiceSettings> {
587        let o = self.overrides().await?;
588        let e = &self.env.self_service;
589        Ok(SelfServiceSettings {
590            mint_enabled: o.self_service_mint.unwrap_or(e.mint_enabled),
591            max_claims_per_caller: o.max_claims_per_caller.unwrap_or(e.max_claims_per_caller),
592            max_keys_per_caller: o.max_keys_per_caller.unwrap_or(e.max_keys_per_caller),
593            max_grants_per_caller: o.max_grants_per_caller.unwrap_or(e.max_grants_per_caller),
594        })
595    }
596
597    /// The payload retention policy. Errors when the settings can't be loaded, so the caller
598    /// never falls back to the default horizon and deletes what an override was keeping.
599    pub async fn payload_retention(&self) -> Result<PayloadRetention> {
600        let o = self.overrides().await?;
601        Ok(PayloadRetention {
602            default_days: o.retention_days.unwrap_or(self.env.retention_days),
603            by_stream_tag: o.retention_by_stream_tag.clone().unwrap_or_default(),
604        })
605    }
606
607    /// The DataFusion config overrides for `role`: the stored value, else none.
608    pub async fn datafusion_config(
609        &self,
610        role: ServiceRole,
611    ) -> Result<Arc<DataFusionConfigOverrides>> {
612        let o = self.overrides().await?;
613        let stored = match role {
614            ServiceRole::Query => &o.datafusion_config_query,
615            ServiceRole::Maintenance => &o.datafusion_config_maintenance,
616        };
617        Ok(stored.clone().unwrap_or_default())
618    }
619
620    /// The stored deployment notes, or `None` when unset or blank so a saved empty editor behaves
621    /// like no notes. Has no env fallback.
622    pub async fn deployment_notes(&self) -> Result<Option<Arc<str>>> {
623        let o = self.overrides().await?;
624        Ok(o.deployment_notes
625            .clone()
626            .filter(|notes| !notes.trim().is_empty()))
627    }
628
629    /// Best-effort startup diagnostic: warns about each env var that is set but ignored because
630    /// the setting has a stored value.
631    pub async fn warn_on_shadowed_env(&self) {
632        match self.overrides().await {
633            Ok(overrides) => {
634                for spec in shadowed(&overrides.stored_keys(), |var| std::env::var(var).is_ok()) {
635                    let env_var = spec.env_var.expect("shadowed specs have an env var");
636                    warn!(
637                        "{env_var} is set but ignored: settings.{} is stored",
638                        spec.key
639                    );
640                }
641            }
642            Err(e) => {
643                warn!(
644                    "could not check for env vars shadowed by stored settings \
645                     (best-effort startup diagnostic, not fatal): {e:#}"
646                );
647            }
648        }
649    }
650}
651
652/// The registered settings that have a stored row and whose env var is also set.
653pub fn shadowed(
654    stored_keys: &[&str],
655    env_is_set: impl Fn(&str) -> bool,
656) -> Vec<&'static SettingSpec> {
657    SETTINGS
658        .iter()
659        .filter(|s| stored_keys.contains(&s.key) && s.env_var.is_some_and(&env_is_set))
660        .collect()
661}
662
663/// Which service a [`SettingsDataFusionConfig`] serves; each reads its own setting key.
664#[derive(Debug, Clone, Copy, PartialEq, Eq)]
665pub enum ServiceRole {
666    Query,
667    Maintenance,
668}
669
670impl std::fmt::Display for ServiceRole {
671    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
672        match self {
673            ServiceRole::Query => write!(f, "query"),
674            ServiceRole::Maintenance => write!(f, "maintenance"),
675        }
676    }
677}
678
679/// [`DataFusionConfigSource`] backed by the DB settings for one service role.
680pub struct SettingsDataFusionConfig {
681    settings: Arc<SettingsSource>,
682    role: ServiceRole,
683    last_logged: Mutex<Option<Arc<DataFusionConfigOverrides>>>,
684}
685
686impl SettingsDataFusionConfig {
687    pub fn new(settings: Arc<SettingsSource>, role: ServiceRole) -> Self {
688        Self {
689            settings,
690            role,
691            last_logged: Mutex::new(None),
692        }
693    }
694}
695
696impl std::fmt::Debug for SettingsDataFusionConfig {
697    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
698        f.debug_struct("SettingsDataFusionConfig")
699            .field("role", &self.role)
700            .finish_non_exhaustive()
701    }
702}
703
704#[async_trait]
705impl DataFusionConfigSource for SettingsDataFusionConfig {
706    async fn overrides(&self) -> Result<Arc<DataFusionConfigOverrides>> {
707        let current = self.settings.datafusion_config(self.role).await?;
708        // Process properties are fixed before the DB is reachable, so the applied config is
709        // reported through the log instead, once per distinct value.
710        let changed = {
711            let mut last = self.last_logged.lock().expect("last_logged lock");
712            if last.as_deref() == Some(&*current) {
713                false
714            } else {
715                *last = Some(current.clone());
716                true
717            }
718        };
719        if changed {
720            info!("datafusion config ({}): {current}", self.role);
721        }
722        Ok(current)
723    }
724}