Skip to main content

micromegas_analytics/lakehouse/
datafusion_config.rs

1use anyhow::{Context, Result, anyhow};
2use async_trait::async_trait;
3use datafusion::config::ConfigOptions;
4use micromegas_tracing::prelude::*;
5use std::collections::BTreeMap;
6use std::fmt::{self, Debug, Display};
7use std::sync::Arc;
8
9/// Keys every session forces; an override could never take effect, so storing one is rejected.
10pub const PINNED_KEYS: &[&str] = &[
11    "datafusion.execution.parquet.enable_page_index",
12    "datafusion.sql_parser.collect_spans",
13    "datafusion.catalog.information_schema",
14];
15
16/// Validated DataFusion config overrides: key -> value as `ConfigOptions::set` takes it.
17///
18/// A sparse map applied on top of `SessionConfig::default()`; keys it does not list keep
19/// DataFusion's defaults.
20#[derive(Debug, Clone, Default, PartialEq, Eq)]
21pub struct DataFusionConfigOverrides(BTreeMap<String, String>);
22
23fn stringify_value(key: &str, value: &serde_json::Value) -> Result<String> {
24    match value {
25        serde_json::Value::String(s) => Ok(s.clone()),
26        serde_json::Value::Number(n) => Ok(n.to_string()),
27        serde_json::Value::Bool(b) => Ok(b.to_string()),
28        _ => Err(anyhow!(
29            "value for '{key}' must be a string, number or boolean"
30        )),
31    }
32}
33
34fn validate_entry(key: &str, value: &serde_json::Value) -> Result<String> {
35    let value = stringify_value(key, value)?;
36    if PINNED_KEYS.contains(&key) {
37        return Err(anyhow!(
38            "'{key}' is set by micromegas on every session and cannot be overridden"
39        ));
40    }
41    // A scratch ConfigOptions lets DataFusion judge both the key and the value.
42    ConfigOptions::new()
43        .set(key, &value)
44        .with_context(|| format!("invalid DataFusion option '{key}'"))?;
45    Ok(value)
46}
47
48fn as_object(value: &serde_json::Value) -> Result<&serde_json::Map<String, serde_json::Value>> {
49    value
50        .as_object()
51        .ok_or_else(|| anyhow!("DataFusion config must be a JSON object of option -> value"))
52}
53
54impl DataFusionConfigOverrides {
55    /// Strict: any bad entry is an error. Used by the PUT handler.
56    pub fn parse_strict(value: &serde_json::Value) -> Result<Self> {
57        let mut map = BTreeMap::new();
58        for (key, v) in as_object(value)? {
59            map.insert(key.clone(), validate_entry(key, v)?);
60        }
61        Ok(Self(map))
62    }
63
64    /// Lenient: a non-object is an error, but an entry DataFusion rejects is skipped with a
65    /// warning. A stored entry can become invalid when DataFusion is upgraded, and that must not
66    /// take the whole settings load down.
67    pub fn parse_lenient(value: &serde_json::Value) -> Result<Self> {
68        let mut map = BTreeMap::new();
69        for (key, v) in as_object(value)? {
70            match validate_entry(key, v) {
71                Ok(v) => {
72                    map.insert(key.clone(), v);
73                }
74                Err(e) => warn!("ignoring stored DataFusion config entry '{key}': {e:#}"),
75            }
76        }
77        Ok(Self(map))
78    }
79
80    /// Sets every override on `options`.
81    pub fn apply(&self, options: &mut ConfigOptions) -> Result<()> {
82        for (key, value) in &self.0 {
83            options
84                .set(key, value)
85                .with_context(|| format!("applying DataFusion option '{key}'"))?;
86        }
87        Ok(())
88    }
89
90    /// True when no option is overridden.
91    pub fn is_empty(&self) -> bool {
92        self.0.is_empty()
93    }
94}
95
96/// Comma-separated `key=value` list.
97impl Display for DataFusionConfigOverrides {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        for (i, (k, v)) in self.0.iter().enumerate() {
100            if i > 0 {
101                write!(f, ", ")?;
102            }
103            write!(f, "{k}={v}")?;
104        }
105        Ok(())
106    }
107}
108
109/// Resolves the overrides applied to every session a `LakehouseContext` builds.
110#[async_trait]
111pub trait DataFusionConfigSource: Send + Sync + Debug {
112    /// The current overrides.
113    async fn overrides(&self) -> Result<Arc<DataFusionConfigOverrides>>;
114}
115
116/// The source of a `LakehouseContext` nobody configured: no overrides.
117#[derive(Debug)]
118pub struct NoDataFusionOverrides;
119
120#[async_trait]
121impl DataFusionConfigSource for NoDataFusionOverrides {
122    async fn overrides(&self) -> Result<Arc<DataFusionConfigOverrides>> {
123        Ok(Arc::new(DataFusionConfigOverrides::default()))
124    }
125}