Skip to main content

micromegas_analytics/lakehouse/
lakehouse_context.rs

1use super::audience_guard::{
2    AudienceIndex, DEFAULT_AUDIENCE_CACHE_ENTRIES, DEFAULT_AUDIENCE_CACHE_TTL,
3};
4use super::datafusion_config::{DataFusionConfigSource, NoDataFusionOverrides};
5use super::metadata_cache::MetadataCache;
6use super::migration::migrate_lakehouse;
7use super::query_deny_list::QueryDenyList;
8use super::reader_factory::ReaderFactory;
9use super::runtime::make_runtime_env;
10use crate::audience::default_audience_from_env;
11use anyhow::Context;
12use anyhow::Result;
13use datafusion::execution::runtime_env::RuntimeEnv;
14use datafusion::prelude::SessionConfig;
15use micromegas_ingestion::data_lake_config::DataLakeConfig;
16use micromegas_ingestion::data_lake_connection::{
17    DataLakeConnection, WritablePolicy, connect_to_data_lake,
18};
19use micromegas_tracing::prelude::*;
20use std::sync::Arc;
21
22/// Default metadata cache size in MB
23const DEFAULT_METADATA_CACHE_SIZE_MB: u64 = 50;
24
25/// Bundles all runtime resources needed for lakehouse query execution.
26///
27/// This struct holds the data lake connection, metadata cache, and DataFusion runtime,
28/// providing a single context object that can be passed through the query path. Parquet
29/// byte-range caching is handled by the in-process L1 cache wrapped around the reader
30/// factory's object store (see `object_cache::l1_wrap`), not by this struct.
31#[derive(Clone)]
32pub struct LakehouseContext {
33    lake: Arc<DataLakeConnection>,
34    metadata_cache: Arc<MetadataCache>,
35    runtime: Arc<RuntimeEnv>,
36    reader_factory: Arc<ReaderFactory>,
37    /// The call-level guard -- resolves *any telemetry id -> its
38    /// owning process's audience* from Postgres, size- and TTL-bounded. Fixed shape, no
39    /// operational knob (see [`DEFAULT_AUDIENCE_CACHE_ENTRIES`]'s doc comment for why).
40    audience_index: Arc<AudienceIndex>,
41    /// Admin-managed query deny list. The refresh task that
42    /// keeps its snapshot warm is spawned only by the FlightSQL server builder -- every other
43    /// holder of a `LakehouseContext` (maintenance daemon, tests) keeps an empty snapshot and
44    /// `check` never denies anything.
45    query_denials: Arc<QueryDenyList>,
46    /// The audience a never-stamped process is read as (`MICROMEGAS_DEFAULT_AUDIENCE`).
47    /// Resolved once here and handed to all three sites that read an audience out of Postgres --
48    /// `BlocksView`'s `data_sql`, `metadata::find_process`, and [`AudienceIndex`]'s
49    /// `owner_query_sql` -- so one process can never resolve two different defaults depending on
50    /// which path reached it. It lives here rather than on `IsolationConfig` because the
51    /// maintenance daemon needs it and never builds one of those.
52    default_audience: Arc<str>,
53    /// Where every session built from this context gets its DataFusion config overrides.
54    /// Per-service (query vs. maintenance), so it lives on the context each service holds.
55    datafusion_config: Arc<dyn DataFusionConfigSource>,
56}
57
58impl LakehouseContext {
59    /// Builds a lakehouse context from an already-connected `DataLakeConnection`.
60    ///
61    /// Runs `migrate_lakehouse` on the supplied connection (idempotent) and
62    /// creates the DataFusion runtime.  The caller is responsible for running
63    /// `migrate_db` (ingestion schema) before this if both migrations are needed
64    /// — the monolith does this via `connect_to_remote_data_lake`.
65    pub async fn from_connection(lake: Arc<DataLakeConnection>) -> Result<Arc<Self>> {
66        migrate_lakehouse(lake.db_pool.clone())
67            .await
68            .with_context(|| "migrate_lakehouse")?;
69        let runtime = Arc::new(make_runtime_env()?);
70        Ok(Arc::new(Self::new(lake, runtime)?))
71    }
72
73    /// Reads MICROMEGAS_SQL_CONNECTION_STRING and MICROMEGAS_OBJECT_STORE_URI,
74    /// connects to the data lake under `policy`, runs lakehouse migrations, and creates the
75    /// runtime environment.
76    pub async fn from_env(policy: WritablePolicy) -> Result<Arc<Self>> {
77        let cfg = DataLakeConfig::from_env()?;
78        let data_lake = Arc::new(
79            connect_to_data_lake(policy, &cfg.sql_connection_string, &cfg.object_store_uri).await?,
80        );
81        migrate_lakehouse(data_lake.db_pool.clone())
82            .await
83            .with_context(|| "migrate_lakehouse")?;
84        let runtime = Arc::new(make_runtime_env()?);
85        Ok(Arc::new(Self::new(data_lake, runtime)?))
86    }
87
88    /// Creates a new lakehouse context with a default-sized metadata cache.
89    ///
90    /// Fails if `MICROMEGAS_DEFAULT_AUDIENCE` is set to a malformed value -- every caller is a
91    /// startup path, so a typo in that knob stops the role rather than silently relabelling
92    /// legacy data (see [`default_audience_from_env`]).
93    pub fn new(lake: Arc<DataLakeConnection>, runtime: Arc<RuntimeEnv>) -> Result<Self> {
94        let metadata_cache_mb = match std::env::var("MICROMEGAS_METADATA_CACHE_MB") {
95            Ok(s) => s.parse::<u64>().unwrap_or_else(|_| {
96                warn!(
97                    "Invalid MICROMEGAS_METADATA_CACHE_MB value '{s}', using default {DEFAULT_METADATA_CACHE_SIZE_MB} MB"
98                );
99                DEFAULT_METADATA_CACHE_SIZE_MB
100            }),
101            Err(_) => DEFAULT_METADATA_CACHE_SIZE_MB,
102        };
103
104        let metadata_cache = Arc::new(MetadataCache::new(metadata_cache_mb * 1024 * 1024));
105        let default_audience: Arc<str> = Arc::from(default_audience_from_env()?.as_str());
106
107        let reader_factory = Arc::new(ReaderFactory::new(
108            micromegas_object_cache::l1_wrap(lake.blob_storage.inner(), "lakehouse"),
109            metadata_cache.clone(),
110        ));
111        let audience_index = Arc::new(AudienceIndex::new(
112            lake.db_pool.clone(),
113            DEFAULT_AUDIENCE_CACHE_ENTRIES,
114            DEFAULT_AUDIENCE_CACHE_TTL,
115            default_audience.clone(),
116        ));
117        let query_denials = Arc::new(QueryDenyList::new(lake.db_pool.clone()));
118        Ok(Self {
119            lake,
120            metadata_cache,
121            runtime,
122            reader_factory,
123            audience_index,
124            query_denials,
125            default_audience,
126            datafusion_config: Arc::new(NoDataFusionOverrides),
127        })
128    }
129
130    /// Creates a new lakehouse context with a custom metadata cache.
131    ///
132    /// Takes `default_audience` rather than re-reading the environment: a context built this way
133    /// must resolve the same default as the one it is derived from (see the field's doc comment).
134    pub fn with_caches(
135        lake: Arc<DataLakeConnection>,
136        runtime: Arc<RuntimeEnv>,
137        metadata_cache: Arc<MetadataCache>,
138        default_audience: Arc<str>,
139    ) -> Self {
140        let reader_factory = Arc::new(ReaderFactory::new(
141            micromegas_object_cache::l1_wrap(lake.blob_storage.inner(), "lakehouse"),
142            metadata_cache.clone(),
143        ));
144        let audience_index = Arc::new(AudienceIndex::new(
145            lake.db_pool.clone(),
146            DEFAULT_AUDIENCE_CACHE_ENTRIES,
147            DEFAULT_AUDIENCE_CACHE_TTL,
148            default_audience.clone(),
149        ));
150        let query_denials = Arc::new(QueryDenyList::new(lake.db_pool.clone()));
151        Self {
152            lake,
153            metadata_cache,
154            runtime,
155            reader_factory,
156            audience_index,
157            query_denials,
158            default_audience,
159            datafusion_config: Arc::new(NoDataFusionOverrides),
160        }
161    }
162
163    /// Returns the audience a never-stamped process is read as
164    /// (`MICROMEGAS_DEFAULT_AUDIENCE`).
165    pub fn default_audience(&self) -> Arc<str> {
166        self.default_audience.clone()
167    }
168
169    /// Returns the data lake connection.
170    pub fn lake(&self) -> &Arc<DataLakeConnection> {
171        &self.lake
172    }
173
174    /// Returns the metadata cache.
175    pub fn metadata_cache(&self) -> &Arc<MetadataCache> {
176        &self.metadata_cache
177    }
178
179    /// Returns the DataFusion runtime environment.
180    pub fn runtime(&self) -> &Arc<RuntimeEnv> {
181        &self.runtime
182    }
183
184    /// Clones this context with `runtime` swapped, sharing the metadata cache and reader
185    /// factory. Deliberately a struct-update clone rather than a call to `new()`/
186    /// `with_caches()` — those rebuild the `MetadataCache` and `ReaderFactory`, which would
187    /// throw away the shared metadata cache per query.
188    pub fn with_runtime(&self, runtime: Arc<RuntimeEnv>) -> Arc<Self> {
189        Arc::new(Self {
190            runtime,
191            ..self.clone()
192        })
193    }
194
195    /// Clones this context with a different DataFusion config source, sharing caches and the
196    /// reader factory like [`Self::with_runtime`]. Lets the monolith's roles run different
197    /// configs off one context.
198    pub fn with_datafusion_config(&self, source: Arc<dyn DataFusionConfigSource>) -> Arc<Self> {
199        Arc::new(Self {
200            datafusion_config: source,
201            ..self.clone()
202        })
203    }
204
205    /// The base `SessionConfig` for every session: DataFusion's defaults plus this context's
206    /// overrides. Fails if the source cannot be resolved, so a misconfigured deployment does
207    /// not silently run on defaults.
208    pub async fn session_config(&self) -> Result<SessionConfig> {
209        let overrides = self.datafusion_config.overrides().await?;
210        let mut config = SessionConfig::default();
211        overrides.apply(config.options_mut())?;
212        Ok(config)
213    }
214
215    /// Returns the shared `ReaderFactory`.
216    pub fn reader_factory(&self) -> &Arc<ReaderFactory> {
217        &self.reader_factory
218    }
219
220    /// Returns the shared call-level-guard audience index.
221    pub fn audience_index(&self) -> &Arc<AudienceIndex> {
222        &self.audience_index
223    }
224
225    /// Returns the shared query deny list.
226    pub fn query_denials(&self) -> &Arc<QueryDenyList> {
227        &self.query_denials
228    }
229}
230
231impl std::fmt::Debug for LakehouseContext {
232    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
233        f.debug_struct("LakehouseContext")
234            .field("metadata_cache", &self.metadata_cache)
235            .finish()
236    }
237}