Skip to main content

micromegas/servers/
flight_sql_server.rs

1use crate::config::DEFAULT_FLIGHTSQL_LISTEN_ADDR;
2use crate::settings::{
3    EnvFallbacks, ServiceRole, SettingsDataFusionConfig, SettingsSource, settings_cache_ttl,
4};
5use anyhow::{Context, Result};
6use micromegas_analytics::lakehouse::lakehouse_context::LakehouseContext;
7use micromegas_analytics::lakehouse::partition_cache::LivePartitionProvider;
8use micromegas_analytics::lakehouse::read_scope::IsolationConfig;
9use micromegas_analytics::lakehouse::session_configurator::SessionConfigurator;
10use micromegas_analytics::lakehouse::static_tables_configurator::StaticTablesConfigurator;
11use micromegas_analytics::lakehouse::view_definition_store::PgViewDefinitionStore;
12use micromegas_analytics::lakehouse::view_factory::{ViewFactory, default_view_factory};
13use micromegas_analytics::lakehouse::view_registry::ViewRegistry;
14use micromegas_auth::db_api_key::{ApiKeyTable, dedicated_key_store_pool};
15use micromegas_auth::db_audience_grants::{DbAudienceGrantsConfig, DbAudienceGrantsSource};
16use micromegas_auth::default_provider::ProviderBuilder;
17use micromegas_auth::policy::{AudienceGrants, AudienceReadPolicy, ReadPolicy};
18use micromegas_auth::tower::AuthService;
19use micromegas_auth::types::AuthProvider;
20use micromegas_ingestion::data_lake_connection::{DataLakeConnection, WritablePolicy};
21use micromegas_ingestion::sql_migration::warn_if_data_lake_schema_stale;
22use micromegas_tracing::prelude::*;
23use std::future::Future;
24use std::net::SocketAddr;
25use std::pin::Pin;
26use std::sync::Arc;
27use std::time::Duration;
28
29use arrow_flight::flight_service_server::FlightServiceServer;
30use datafusion::execution::runtime_env::RuntimeEnv;
31use tonic::transport::Server;
32use tower::ServiceBuilder;
33use tower::layer::layer_fn;
34
35use super::connect_info_layer::ConnectedIncoming;
36use super::flight_sql_service_impl::FlightSqlServiceImpl;
37use super::grpc_health_service::GrpcHealthService;
38use super::log_uri_service::LogUriService;
39use super::query_admission::{admission_scheduler_from_env, opaque_leaf_cost_from_env};
40
41type ViewFactoryFn = Box<
42    dyn FnOnce(
43            Arc<RuntimeEnv>,
44            Arc<DataLakeConnection>,
45        ) -> Pin<Box<dyn Future<Output = Result<ViewFactory>> + Send>>
46        + Send,
47>;
48
49/// The auth provider plus the default `ReadPolicy` `build_and_serve` resolves per branch, before
50/// `self.read_policy` (if set) overrides it.
51type AuthAndDefaults = (Option<Arc<dyn AuthProvider>>, Arc<dyn ReadPolicy>);
52
53/// The env is not read at all when the caller supplied a config: `with_isolation_config` wins
54/// regardless, so reading anyway would invent a startup failure on a variable the caller
55/// deliberately overrode.
56fn resolve_env_fallbacks(explicit: &Option<Arc<IsolationConfig>>) -> Result<Option<EnvFallbacks>> {
57    match explicit {
58        Some(_) => Ok(None),
59        None => Ok(Some(EnvFallbacks::from_env()?)),
60    }
61}
62
63/// An explicit config pins the source; otherwise the settings table is cached over a dedicated
64/// pool on every auth branch, so a setting stored in the DB cannot be ignored on one path while
65/// looking effective on another.
66fn resolve_settings(
67    explicit: Option<Arc<IsolationConfig>>,
68    env: Option<EnvFallbacks>,
69    lake_pool: &sqlx::PgPool,
70) -> Result<SettingsSource> {
71    match (explicit, env) {
72        (Some(config), _) => Ok(SettingsSource::pinned(config)),
73        (None, Some(env)) => Ok(SettingsSource::new(
74            env,
75            dedicated_key_store_pool(lake_pool),
76            settings_cache_ttl(),
77        )),
78        (None, None) => anyhow::bail!("env fallbacks must be resolved when no explicit config"),
79    }
80}
81
82/// Builder for assembling and running a FlightSQL server.
83///
84/// Encapsulates the full setup sequence: data lake connection, lakehouse migration,
85/// runtime env, view factory, partition provider, session configurator, auth, and
86/// the gRPC tower layer stack.
87///
88/// # Example
89///
90/// ```rust,no_run
91/// use micromegas::servers::flight_sql_server::FlightSqlServer;
92///
93/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
94/// FlightSqlServer::builder()
95///     .with_default_auth()
96///     .build_and_serve()
97///     .await?;
98/// # Ok(())
99/// # }
100/// ```
101pub struct FlightSqlServer;
102
103impl FlightSqlServer {
104    pub fn builder() -> FlightSqlServerBuilder {
105        FlightSqlServerBuilder::default()
106    }
107}
108
109pub struct FlightSqlServerBuilder {
110    view_factory_fn: Option<ViewFactoryFn>,
111    session_configurator: Option<Arc<dyn SessionConfigurator>>,
112    auth_provider: Option<Arc<dyn AuthProvider>>,
113    read_policy: Option<Arc<dyn ReadPolicy>>,
114    isolation_config: Option<Arc<IsolationConfig>>,
115    use_default_auth: bool,
116    max_decoding_message_size: usize,
117    listen_addr: SocketAddr,
118    shutdown_grace: Duration,
119    injected_lakehouse: Option<Arc<LakehouseContext>>,
120    injected_shutdown: Option<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>,
121    health_listen_addr: Option<SocketAddr>,
122}
123
124impl Default for FlightSqlServerBuilder {
125    fn default() -> Self {
126        Self {
127            view_factory_fn: None,
128            session_configurator: None,
129            auth_provider: None,
130            read_policy: None,
131            isolation_config: None,
132            use_default_auth: false,
133            max_decoding_message_size: 100 * 1024 * 1024,
134            listen_addr: DEFAULT_FLIGHTSQL_LISTEN_ADDR,
135            shutdown_grace: Duration::from_secs(25),
136            injected_lakehouse: None,
137            injected_shutdown: None,
138            health_listen_addr: None,
139        }
140    }
141}
142
143impl FlightSqlServerBuilder {
144    /// Override the default view factory with a custom closure.
145    ///
146    /// The closure receives the runtime and data lake created by the builder.
147    pub fn with_view_factory_fn<F, Fut>(mut self, f: F) -> Self
148    where
149        F: FnOnce(Arc<RuntimeEnv>, Arc<DataLakeConnection>) -> Fut + Send + 'static,
150        Fut: Future<Output = Result<ViewFactory>> + Send + 'static,
151    {
152        self.view_factory_fn = Some(Box::new(move |runtime, lake| Box::pin(f(runtime, lake))));
153        self
154    }
155
156    /// Override the default session configurator.
157    ///
158    /// By default the builder loads static tables from `MICROMEGAS_STATIC_TABLES_URL`.
159    /// Use this to replace that behavior entirely.
160    pub fn with_session_configurator(mut self, cfg: Arc<dyn SessionConfigurator>) -> Self {
161        self.session_configurator = Some(cfg);
162        self
163    }
164
165    /// Set an explicit auth provider.
166    pub fn with_auth_provider(mut self, provider: Arc<dyn AuthProvider>) -> Self {
167        self.auth_provider = Some(provider);
168        self.use_default_auth = false;
169        self
170    }
171
172    /// Set an explicit `ReadPolicy`, resolved once per request against the caller's
173    /// `AuthContext`. This policy wins on every `build_and_serve` branch,
174    /// overriding that branch's own default. When never called, the default depends on how auth
175    /// is configured: with `with_default_auth()` or `with_auth_provider(..)`,
176    /// `AudienceReadPolicy::default()` backed by the DB grant store (so the seeded `public`
177    /// read row still resolves); with auth left disabled, `AudienceReadPolicy` with an empty
178    /// grant map, though that branch never actually resolves it. **Not** `ReadScope::All`: the
179    /// absent-`AuthContext`-extension convention already supplies `All` when no provider is
180    /// configured, so this default must not duplicate
181    /// that decision -- it only ever resolves a scope when an `AuthContext` is present to resolve
182    /// one from.
183    pub fn with_read_policy(mut self, policy: Arc<dyn ReadPolicy>) -> Self {
184        self.read_policy = Some(policy);
185        self
186    }
187
188    /// Set an explicit `IsolationConfig` -- the data-isolation config consumed by the row-level
189    /// filter (`OwnershipRewrite`). Mirrors `with_read_policy`: wins regardless of how auth is
190    /// configured, pinning the settings source so neither the `public_view_sets` setting nor its
191    /// `MICROMEGAS_PUBLIC_VIEW_SETS` env fallback is consulted. A pinned source also turns off the
192    /// DB-backed `datafusion_config_query` overrides: sessions run on DataFusion's defaults. It
193    /// also ignores a stored `deployment_notes` (`deployment_notes()` returns no row).
194    pub fn with_isolation_config(mut self, config: Arc<IsolationConfig>) -> Self {
195        self.isolation_config = Some(config);
196        self
197    }
198
199    /// Use the default auth provider from env vars during build.
200    ///
201    /// Errors if no auth providers are configured (fail-fast).
202    pub fn with_default_auth(mut self) -> Self {
203        self.use_default_auth = true;
204        self.auth_provider = None;
205        self
206    }
207
208    /// Set the max decoding message size (default: 100 MB).
209    pub fn with_max_decoding_message_size(mut self, bytes: usize) -> Self {
210        self.max_decoding_message_size = bytes;
211        self
212    }
213
214    /// Set the listen address (default: [`DEFAULT_FLIGHTSQL_LISTEN_ADDR`], `0.0.0.0:50051`).
215    pub fn with_listen_addr(mut self, addr: SocketAddr) -> Self {
216        self.listen_addr = addr;
217        self
218    }
219
220    /// Set the grace period for graceful shutdown on SIGTERM (default: 25s).
221    pub fn with_shutdown_grace(mut self, grace: Duration) -> Self {
222        self.shutdown_grace = grace;
223        self
224    }
225
226    /// Inject a pre-built `LakehouseContext` instead of calling `LakehouseContext::from_env`.
227    ///
228    /// Useful for the monolith, which constructs one shared context for all lake-backed roles.
229    pub fn with_lakehouse(mut self, lakehouse: Arc<LakehouseContext>) -> Self {
230        self.injected_lakehouse = Some(lakehouse);
231        self
232    }
233
234    /// Inject a custom shutdown future instead of the default `wait_for_sigterm()`.
235    ///
236    /// The monolith passes `fanout.subscribe()` here so all roles shut down from one signal.
237    pub fn with_shutdown(mut self, shutdown: impl Future<Output = ()> + Send + 'static) -> Self {
238        self.injected_shutdown = Some(Box::pin(shutdown));
239        self
240    }
241
242    /// Spawn a lightweight HTTP sidecar (`/health`, `/ready`) on `addr`.
243    ///
244    /// Enables plain-HTTP ALB health checks without changing the gRPC protocol.
245    /// If not set, no sidecar is started.
246    pub fn with_health_addr(mut self, addr: SocketAddr) -> Self {
247        self.health_listen_addr = Some(addr);
248        self
249    }
250
251    /// Build and run the FlightSQL server.
252    ///
253    /// Runs the full setup sequence and blocks until the server shuts down.
254    pub async fn build_and_serve(self) -> Result<()> {
255        // Resolved first, ahead of the Postgres/object-store setup below, so a malformed
256        // `MICROMEGAS_PUBLIC_VIEW_SETS` fails fast at no cost.
257        let env_fallbacks = resolve_env_fallbacks(&self.isolation_config)?;
258        // Same fail-fast rationale: a typo in the admission budget must not silently leave the
259        // service running unqueued.
260        let admission = admission_scheduler_from_env()?;
261        let opaque_leaf_cost = opaque_leaf_cost_from_env();
262
263        // Use injected lakehouse or build one from environment. The non-injected path is
264        // standalone FlightSQL, the one role that prefers a writable primary but falls back to
265        // a read-only replica rather than refuse to start (see `high-availability.md`); an
266        // injected lakehouse (the monolith) shares its lake pool with the ingestion role, which
267        // stays strict, so it is never `Prefer` here.
268        let lakehouse = if let Some(lh) = self.injected_lakehouse {
269            lh
270        } else {
271            LakehouseContext::from_env(WritablePolicy::Prefer).await?
272        };
273        let data_lake = lakehouse.lake().clone();
274        let probe_lake = lakehouse.lake().clone();
275        // Cloned here, before `lakehouse` is moved into `FlightSqlServiceImpl::new` below, so the
276        // refresh task (spawned further down, once the shutdown fanout exists) has its own
277        // handle. Only the FlightSQL server builder spawns this -- other `LakehouseContext`
278        // holders (maintenance daemon, tests) keep an empty snapshot and never deny anything.
279        let query_denials = lakehouse.query_denials().clone();
280        info!(
281            "created lakehouse context with metadata cache: {:?}",
282            lakehouse.metadata_cache()
283        );
284
285        let base_view_factory: Arc<ViewFactory> = if let Some(factory_fn) = self.view_factory_fn {
286            Arc::new(factory_fn(lakehouse.runtime().clone(), data_lake.clone()).await?)
287        } else {
288            Arc::new(
289                default_view_factory(
290                    lakehouse.runtime().clone(),
291                    data_lake.clone(),
292                    lakehouse.default_audience(),
293                )
294                .await?,
295            )
296        };
297
298        let partition_provider =
299            Arc::new(LivePartitionProvider::new(lakehouse.lake().db_pool.clone()));
300        // Cloned here, before `lakehouse` is moved into `FlightSqlServiceImpl::new`
301        // below, so `dedicated_key_store_pool` has a pool to read pool options
302        // from.
303        let lake_pool_for_keys = lakehouse.lake().db_pool.clone();
304
305        let warn_on_shadowed_env = self.isolation_config.is_none()
306            && (self.auth_provider.is_some() || self.use_default_auth);
307        let settings = Arc::new(resolve_settings(
308            self.isolation_config,
309            env_fallbacks,
310            &lake_pool_for_keys,
311        )?);
312        if warn_on_shadowed_env {
313            settings.warn_on_shadowed_env().await;
314        }
315        let lakehouse = lakehouse.with_datafusion_config(Arc::new(SettingsDataFusionConfig::new(
316            settings.clone(),
317            ServiceRole::Query,
318        )));
319
320        let session_configurator: Arc<dyn SessionConfigurator> =
321            if let Some(cfg) = self.session_configurator {
322                cfg
323            } else {
324                StaticTablesConfigurator::from_env(
325                    "MICROMEGAS_STATIC_TABLES_URL",
326                    lakehouse.runtime().clone(),
327                )
328                .await?
329            };
330
331        // The shared registry: `base_view_factory` (code-driven views) plus every DDL-defined
332        // global view (`lakehouse_view_set_definitions`), rebuilt on
333        // `MICROMEGAS_VIEW_DEFINITION_REFRESH_SECONDS`. Loaded once, synchronously, before
334        // `serve()` -- failing startup on error, the way `migrate_lakehouse` already does --
335        // so there is never a window after startup where a DDL-defined view (or the now-seeded
336        // `log_stats`) is absent from `current()`.
337        let view_registry = Arc::new(ViewRegistry::new(
338            base_view_factory,
339            Arc::new(PgViewDefinitionStore::new(lakehouse.lake().db_pool.clone())),
340            lakehouse.runtime().clone(),
341            data_lake,
342            session_configurator.clone(),
343        ));
344        view_registry
345            .reload()
346            .await
347            .with_context(|| "initial view_registry reload")?;
348
349        // `FlightSqlServiceImpl::new` takes the resolved `ReadPolicy` as a constructor argument,
350        // so auth/policy resolution happens here, before construction.
351        //
352        // `self.read_policy` (set via `with_read_policy`) must win on every branch below --
353        // each branch only computes its own *default*, used solely when the caller never set an
354        // explicit policy. This keeps `with_read_policy` order-independent with respect to
355        // `with_auth_provider` / `with_default_auth`.
356        let (auth_provider, default_policy): AuthAndDefaults =
357            if let Some(provider) = self.auth_provider {
358                // Injected-provider path (the monolith's `with_auth_provider` call): the caller is
359                // expected to pair `with_auth_provider` with its own `with_read_policy` call, but
360                // when it didn't, this default must still resolve the seeded `public` read grant
361                // rather than the empty set -- an empty-grant-map default was only ever safe
362                // while `resolve` had a built-in `PUBLIC_AUDIENCE` arm; with that arm removed it
363                // would silently deny every query for an embedder that forgot `with_read_policy`.
364                // So this builds the same store-backed policy the `use_default_auth` branch
365                // below does.
366                //
367                // Built only when `self.read_policy` is unset -- `with_read_policy` always wins
368                // below, and the only in-repo `with_auth_provider` caller (the monolith) always
369                // pairs the two, so skipping this avoids a DB round trip whenever it would be
370                // discarded anyway.
371                let policy: Arc<dyn ReadPolicy> = if self.read_policy.is_none() {
372                    let key_store_pool = dedicated_key_store_pool(&lake_pool_for_keys);
373                    warn_if_data_lake_schema_stale(&lake_pool_for_keys).await;
374                    let audience_grants_config = DbAudienceGrantsConfig::from_env_with_prefix("");
375                    let audience_grants_store = Arc::new(DbAudienceGrantsSource::new(
376                        key_store_pool,
377                        Duration::from_secs(audience_grants_config.cache_ttl_secs),
378                    ));
379                    Arc::new(AudienceReadPolicy::default().with_store(audience_grants_store))
380                } else {
381                    Arc::new(AudienceReadPolicy::new(AudienceGrants::empty()))
382                };
383                (Some(provider), policy)
384            } else if self.use_default_auth {
385                let key_store_pool = dedicated_key_store_pool(&lake_pool_for_keys);
386                let group_store_pool = dedicated_key_store_pool(&lake_pool_for_keys);
387                warn_if_data_lake_schema_stale(&lake_pool_for_keys).await;
388                let provider = match ProviderBuilder::new("")
389                    .with_db_key_store(key_store_pool, ApiKeyTable::Analytics)
390                    .with_group_store(group_store_pool)
391                    .build()
392                    .await?
393                {
394                    Some(provider) => provider,
395                    None => {
396                        anyhow::bail!(
397                            "Authentication required but no auth providers configured. Set \
398                         MICROMEGAS_OIDC_CONFIG, or populate the analytics_api_keys DB table"
399                        );
400                    }
401                };
402                // One shared snapshot cache for this process, built from
403                // its own dedicated pool -- not `key_store_pool` above, which
404                // `DbApiKeyAuthProvider` already owns -- via the same `dedicated_key_store_pool`
405                // convention. The cache TTL is the flat, unprefixed
406                // `MICROMEGAS_AUTH_CACHE_TTL_SECONDS`; the `prefix` argument below is passed only
407                // for call-site symmetry -- `from_env_with_prefix` never actually consults it.
408                let audience_grants_pool = dedicated_key_store_pool(&lake_pool_for_keys);
409                let audience_grants_config = DbAudienceGrantsConfig::from_env_with_prefix("");
410                let audience_grants_store = Arc::new(DbAudienceGrantsSource::new(
411                    audience_grants_pool,
412                    Duration::from_secs(audience_grants_config.cache_ttl_secs),
413                ));
414                let policy: Arc<dyn ReadPolicy> =
415                    Arc::new(AudienceReadPolicy::default().with_store(audience_grants_store));
416                (Some(provider), policy)
417            } else {
418                info!("Authentication disabled");
419                // No `AuthContext` extension is ever inserted on this path (no `AuthService`
420                // provider configured), so the absent-extension convention already supplies
421                // `ReadScope::All` -- this default policy is never actually resolved against a
422                // real caller, but must still exist since `FlightSqlServiceImpl::new` requires
423                // one. This never-resolved property is now load-bearing: with the built-in
424                // `PUBLIC_AUDIENCE` read arm removed, an empty grant map resolves to the empty
425                // set, not `{public}` -- fine here only because `resolve` is never actually
426                // called on this branch.
427                (
428                    None,
429                    Arc::new(AudienceReadPolicy::new(AudienceGrants::empty())),
430                )
431            };
432        let read_policy = self.read_policy.unwrap_or(default_policy);
433
434        let svc = FlightServiceServer::new(FlightSqlServiceImpl::new(
435            lakehouse,
436            partition_provider,
437            view_registry.clone(),
438            session_configurator,
439            read_policy,
440            settings,
441            opaque_leaf_cost,
442            admission,
443        ))
444        .max_decoding_message_size(self.max_decoding_message_size);
445
446        let layer = ServiceBuilder::new()
447            .layer(layer_fn(GrpcHealthService::new))
448            .layer(layer_fn(|service| LogUriService { service }))
449            .layer(layer_fn(move |inner| AuthService {
450                inner,
451                auth_provider: auth_provider.clone(),
452            }))
453            .into_inner();
454
455        use super::shutdown::{ShutdownFanout, wait_for_sigterm};
456
457        info!("Listening on {:?}", self.listen_addr);
458        let listener = std::net::TcpListener::bind(self.listen_addr)?;
459        let incoming = ConnectedIncoming::from_std_listener(listener)?;
460
461        // Use injected shutdown future or default to SIGTERM
462        let shutdown_future: Pin<Box<dyn Future<Output = ()> + Send + 'static>> = self
463            .injected_shutdown
464            .unwrap_or_else(|| Box::pin(wait_for_sigterm()));
465        let fanout = ShutdownFanout::new(shutdown_future);
466        let grace_secs = self.shutdown_grace.as_secs();
467        let grace = self.shutdown_grace;
468
469        // Admin-managed query deny list: refreshes the shared snapshot every
470        // `MICROMEGAS_QUERY_DENY_REFRESH_SECONDS`, once immediately and then on a tick, until
471        // this replica shuts down.
472        query_denials.spawn_refresh_task(fanout.subscribe());
473
474        // DDL-defined view sets: refreshes `view_registry.current()` every
475        // `MICROMEGAS_VIEW_DEFINITION_REFRESH_SECONDS`, until this replica shuts down. A
476        // same-node `CREATE`/`DROP MATERIALIZED VIEW` reloads inline instead (see
477        // `flight_sql_service_impl.rs::execute_view_ddl`); this bounds how long a *different*
478        // node lags a definition change.
479        view_registry.spawn_refresh_task(fanout.subscribe());
480
481        if let Some(health_addr) = self.health_listen_addr {
482            use super::readiness::ReadinessProbe;
483            use axum::Extension;
484            use axum::Router;
485            use axum::routing::get;
486            use tokio::net::TcpListener;
487
488            let probe = std::sync::Arc::new(ReadinessProbe::new(probe_lake));
489            let sidecar_listener = TcpListener::bind(health_addr).await?;
490            let shutdown_rx = fanout.subscribe();
491            tokio::spawn(async move {
492                async fn sidecar_ready(
493                    Extension(p): Extension<std::sync::Arc<ReadinessProbe>>,
494                ) -> axum::http::StatusCode {
495                    if p.check_ready().await {
496                        axum::http::StatusCode::OK
497                    } else {
498                        axum::http::StatusCode::SERVICE_UNAVAILABLE
499                    }
500                }
501                let sidecar_app = Router::new()
502                    .route("/health", get(|| async { axum::http::StatusCode::OK }))
503                    .route("/ready", get(sidecar_ready))
504                    .layer(Extension(probe));
505                let _ = axum::serve(sidecar_listener, sidecar_app)
506                    .with_graceful_shutdown(shutdown_rx)
507                    .await;
508                info!("FlightSQL health sidecar stopped");
509            });
510            info!("FlightSQL health sidecar listening on {health_addr}");
511        }
512
513        let serve = Server::builder()
514            .layer(layer)
515            .add_service(svc)
516            .serve_with_incoming_shutdown(incoming, fanout.subscribe());
517
518        let deadline = {
519            let d = fanout.subscribe();
520            async move {
521                d.await;
522                tokio::time::sleep(grace).await;
523            }
524        };
525
526        tokio::select! {
527            res = serve => {
528                info!("drain completed");
529                res?;
530            }
531            _ = deadline => {
532                warn!("grace period of {grace_secs}s elapsed with work still in flight");
533            }
534        }
535
536        info!("bye");
537        Ok(())
538    }
539}
540
541#[cfg(test)]
542mod tests {
543    use super::*;
544    use serial_test::serial;
545
546    const PUBLIC_VIEW_SETS_VAR: &str = "MICROMEGAS_PUBLIC_VIEW_SETS";
547
548    /// Clears the var on drop so a failing assertion in one test can't leak state into the next.
549    struct EnvGuard;
550
551    impl Drop for EnvGuard {
552        fn drop(&mut self) {
553            // SAFETY: tests are serialized with `#[serial]`.
554            unsafe {
555                std::env::remove_var(PUBLIC_VIEW_SETS_VAR);
556            }
557        }
558    }
559
560    /// An explicit config skips the env read entirely, even when the env is malformed: reading
561    /// anyway would invent a startup failure on a variable the caller deliberately overrode.
562    #[test]
563    #[serial]
564    fn explicit_config_skips_a_malformed_env_value() {
565        let _guard = EnvGuard;
566        // SAFETY: serialized via `#[serial]`.
567        unsafe {
568            std::env::set_var(PUBLIC_VIEW_SETS_VAR, r#"["log_stats"]"#);
569        }
570        let explicit = Some(Arc::new(IsolationConfig {
571            public_view_sets: vec!["images".to_string()],
572        }));
573        let env = resolve_env_fallbacks(&explicit).expect("resolve_env_fallbacks");
574        assert!(env.is_none());
575    }
576
577    #[test]
578    #[serial]
579    fn no_explicit_config_reads_env_and_fails_fast_when_malformed() {
580        let _guard = EnvGuard;
581        // SAFETY: serialized via `#[serial]`.
582        unsafe {
583            std::env::set_var(PUBLIC_VIEW_SETS_VAR, r#"["log_stats"]"#);
584        }
585        let err = resolve_env_fallbacks(&None).expect_err("malformed value must be rejected");
586        assert!(err.to_string().contains(PUBLIC_VIEW_SETS_VAR));
587    }
588}