Skip to main content

frontend/
server.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::net::SocketAddr;
16use std::sync::Arc;
17use std::time::Duration;
18
19use auth::UserProviderRef;
20use axum::extract::{Request, State};
21use axum::middleware::Next;
22use axum::response::IntoResponse;
23use common_base::Plugins;
24use common_config::Configurable;
25use common_telemetry::{info, warn};
26use meta_client::MetaClientOptions;
27use servers::batcher::{BatchingProtocol, pending_rows_batch_sync_enabled};
28use servers::error::Error as ServerError;
29use servers::grpc::builder::GrpcServerBuilder;
30use servers::grpc::flight::FlightCraftRef;
31use servers::grpc::frontend_grpc_handler::FrontendGrpcHandler;
32use servers::grpc::greptime_handler::GreptimeRequestHandler;
33use servers::grpc::{GrpcOptions, GrpcServer};
34use servers::http::event::LogValidatorRef;
35use servers::http::result::error_result::ErrorResponse;
36use servers::http::utils::router::RouterConfigurator;
37use servers::http::{HttpOptions, HttpServer, HttpServerBuilder};
38use servers::interceptor::LogIngestInterceptorRef;
39use servers::metrics_handler::MetricsHandler;
40use servers::mysql::server::{MysqlServer, MysqlSpawnConfig, MysqlSpawnRef};
41use servers::otel_arrow::OtelArrowServiceHandler;
42use servers::postgres::PostgresServer;
43use servers::request_memory_limiter::ServerMemoryLimiter;
44use servers::server::{Server, ServerHandlers};
45use servers::tls::{ReloadableTlsServerConfig, maybe_watch_server_tls_config};
46use session::context::Channel;
47use snafu::ResultExt;
48use tonic::Status;
49
50use crate::error::{self, Result, StartServerSnafu, TomlFormatSnafu};
51use crate::frontend::FrontendOptions;
52use crate::instance::Instance;
53use crate::service_config::PromStoreOptions;
54
55pub struct Services<T>
56where
57    T: Into<FrontendOptions> + Configurable + Clone,
58{
59    opts: T,
60    instance: Arc<Instance>,
61    grpc_server_builder: Option<GrpcServerBuilder>,
62    http_server_builder: Option<HttpServerBuilder>,
63    plugins: Plugins,
64    flight_handler: Option<FlightCraftRef>,
65    internal_flight_handler: Option<FlightCraftRef>,
66    pub server_memory_limiter: ServerMemoryLimiter,
67}
68
69impl<T> Services<T>
70where
71    T: Into<FrontendOptions> + Configurable + Clone,
72{
73    pub fn new(opts: T, instance: Arc<Instance>, plugins: Plugins) -> Self {
74        let feopts = opts.clone().into();
75        instance.init_logical_batcher(&feopts);
76        let server_memory_limiter = instance.server_memory_limiter().clone();
77
78        Self {
79            opts,
80            instance,
81            grpc_server_builder: None,
82            http_server_builder: None,
83            plugins,
84            flight_handler: None,
85            internal_flight_handler: None,
86            server_memory_limiter,
87        }
88    }
89
90    pub fn grpc_server_builder(
91        &self,
92        opts: &GrpcOptions,
93        request_memory_limiter: ServerMemoryLimiter,
94    ) -> Result<GrpcServerBuilder> {
95        let builder = GrpcServerBuilder::new(opts.as_config(), common_runtime::global_runtime())
96            .with_memory_limiter(request_memory_limiter)
97            .with_tls_config(opts.tls.clone())
98            .context(error::InvalidTlsConfigSnafu)?;
99        Ok(builder)
100    }
101
102    pub fn http_server_builder(
103        &self,
104        opts: &FrontendOptions,
105        request_memory_limiter: ServerMemoryLimiter,
106    ) -> HttpServerBuilder {
107        let mut builder = HttpServerBuilder::new(effective_http_options(opts))
108            .with_batching_protocols(opts.table_batcher_options().protocols.clone())
109            .with_logical_batching_protocols(opts.logical_batcher_options().protocols)
110            .with_memory_limiter(request_memory_limiter)
111            .with_sql_handler(self.instance.clone());
112
113        let validator = self.plugins.get::<LogValidatorRef>();
114        let ingest_interceptor = self.plugins.get::<LogIngestInterceptorRef<ServerError>>();
115        builder =
116            builder.with_log_ingest_handler(self.instance.clone(), validator, ingest_interceptor);
117        builder = builder.with_logs_handler(self.instance.clone());
118
119        if let Some(user_provider) = self.plugins.get::<UserProviderRef>() {
120            builder = builder.with_user_provider(user_provider);
121        }
122
123        if opts.opentsdb.enable {
124            builder = builder.with_opentsdb_handler(self.instance.clone());
125        }
126
127        if opts.influxdb.enable {
128            builder = builder.with_influxdb_handler(self.instance.clone());
129        }
130
131        let prom_store = effective_prom_store_options(opts);
132        if prom_store.enable {
133            let pending_rows_batcher = opts
134                .logical_batcher_options()
135                .protocols
136                .contains(&BatchingProtocol::Prom)
137                .then(|| self.instance.logical_batcher().cloned())
138                .flatten();
139            builder = builder
140                .with_prom_handler(
141                    self.instance.clone(),
142                    Some(self.instance.clone()),
143                    opts.prom_store.with_metric_engine,
144                    opts.prom_store.prom_validation_mode,
145                    pending_rows_batcher,
146                )
147                .with_prometheus_handler(self.instance.clone());
148        }
149
150        if opts.otlp.enable {
151            builder = builder
152                .with_otlp_handler(self.instance.clone(), opts.prom_store.with_metric_engine);
153        }
154
155        if opts.jaeger.enable {
156            builder = builder.with_jaeger_handler(self.instance.clone());
157        }
158
159        builder = builder.with_dashboard_handler(self.instance.clone());
160
161        if let Some(configurator) = self.plugins.get::<RouterConfigurator>() {
162            info!("Adding extra router from plugins");
163            builder = builder.with_extra_router(configurator.router());
164        }
165
166        builder.add_layer(axum::middleware::from_fn_with_state(
167            self.instance.clone(),
168            async move |State(state): State<Arc<Instance>>, request: Request, next: Next| {
169                if state.is_suspended() {
170                    return ErrorResponse::from_error(servers::error::SuspendedSnafu.build())
171                        .into_response();
172                }
173                next.run(request).await
174            },
175        ))
176    }
177
178    pub fn with_grpc_server_builder(self, builder: GrpcServerBuilder) -> Self {
179        Self {
180            grpc_server_builder: Some(builder),
181            ..self
182        }
183    }
184
185    pub fn with_http_server_builder(self, builder: HttpServerBuilder) -> Self {
186        Self {
187            http_server_builder: Some(builder),
188            ..self
189        }
190    }
191
192    pub fn with_flight_handler(self, flight_handler: FlightCraftRef) -> Self {
193        Self {
194            flight_handler: Some(flight_handler),
195            ..self
196        }
197    }
198
199    pub fn with_internal_flight_handler(self, flight_handler: FlightCraftRef) -> Self {
200        Self {
201            internal_flight_handler: Some(flight_handler),
202            ..self
203        }
204    }
205
206    fn build_grpc_server(
207        &mut self,
208        grpc: &GrpcOptions,
209        meta_client: &Option<MetaClientOptions>,
210        name: Option<String>,
211        external: bool,
212        request_memory_limiter: ServerMemoryLimiter,
213    ) -> Result<GrpcServer> {
214        let mut builder = if let Some(builder) = self.grpc_server_builder.take() {
215            builder
216        } else {
217            self.grpc_server_builder(grpc, request_memory_limiter)?
218        };
219        // Browsers never talk to the internal server.
220        if external && grpc.enable_cors {
221            builder = builder.with_cors(grpc.cors_allowed_origins.clone());
222        }
223
224        let user_provider = if external {
225            self.plugins.get::<UserProviderRef>()
226        } else {
227            // skip authentication for internal grpc port
228            None
229        };
230
231        // Determine whether it is Standalone or Distributed mode based on whether the meta client is configured.
232        let runtime = if meta_client.is_none() {
233            Some(builder.runtime().clone())
234        } else {
235            None
236        };
237
238        let greptime_request_handler = GreptimeRequestHandler::new(
239            self.instance.clone(),
240            user_provider.clone(),
241            runtime,
242            grpc.flight_compression,
243        );
244
245        let default_flight_handler = Arc::new(greptime_request_handler.clone()) as FlightCraftRef;
246        let flight_handler = if external {
247            self.flight_handler
248                .clone()
249                .unwrap_or(default_flight_handler)
250        } else {
251            self.internal_flight_handler
252                .clone()
253                .unwrap_or(default_flight_handler)
254        };
255
256        let grpc_server = builder
257            .name(name)
258            .database_handler(greptime_request_handler.clone())
259            .prometheus_handler(self.instance.clone(), user_provider.clone())
260            .otel_arrow_handler(OtelArrowServiceHandler::new(
261                self.instance.clone(),
262                user_provider.clone(),
263            ))
264            .flight_handler(flight_handler)
265            .add_layer(axum::middleware::from_fn_with_state(
266                self.instance.clone(),
267                move |State(state): State<Arc<Instance>>, mut request: Request, next: Next| async move {
268                    if state.is_suspended() {
269                        let status = Status::from(servers::error::SuspendedSnafu.build());
270                        return status.into_http();
271                    }
272                    // The listener owns this marker; clients cannot set request extensions.
273                    if !external {
274                        request.extensions_mut().insert(Channel::Internal);
275                    }
276                    next.run(request).await
277                },
278            ));
279
280        let grpc_server = if !external {
281            let frontend_grpc_handler =
282                FrontendGrpcHandler::new(self.instance.process_manager().clone());
283            grpc_server.frontend_grpc_handler(frontend_grpc_handler)
284        } else {
285            grpc_server
286        }
287        .build();
288
289        Ok(grpc_server)
290    }
291
292    fn build_http_server(
293        &mut self,
294        opts: &FrontendOptions,
295        toml: String,
296        request_memory_limiter: ServerMemoryLimiter,
297    ) -> Result<(HttpServer, Option<HttpServer>)> {
298        let builder = if let Some(builder) = self.http_server_builder.take() {
299            builder
300        } else {
301            self.http_server_builder(opts, request_memory_limiter)
302        };
303
304        // The API server is configured entirely under `[http]` (`enable_api_server`,
305        // `api_server_host`, `api_server_port`) and shares every other `[http]`
306        // option with the main server.
307        let (internal, api) = builder
308            .with_metrics_handler(MetricsHandler)
309            .with_greptime_config_options(toml)
310            .build_servers();
311        Ok((internal, api))
312    }
313
314    pub fn build(mut self) -> Result<ServerHandlers> {
315        let opts = self.opts.clone();
316        let instance = self.instance.clone();
317
318        let toml = opts.to_toml().context(TomlFormatSnafu)?;
319        let opts: FrontendOptions = opts.into();
320
321        let handlers = ServerHandlers::default();
322
323        let user_provider = self.plugins.get::<UserProviderRef>();
324
325        {
326            // Always init GRPC server
327            let grpc_addr = parse_addr(&opts.grpc.bind_addr)?;
328            let grpc_server = self.build_grpc_server(
329                &opts.grpc,
330                &opts.meta_client,
331                None,
332                true,
333                self.server_memory_limiter.clone(),
334            )?;
335            handlers.insert((Box::new(grpc_server), grpc_addr));
336        }
337
338        if let Some(internal_grpc) = &opts.internal_grpc {
339            // Always init Internal GRPC server
340            let grpc_addr = parse_addr(&internal_grpc.bind_addr)?;
341            let grpc_server = self.build_grpc_server(
342                internal_grpc,
343                &opts.meta_client,
344                Some("INTERNAL_GRPC_SERVER".to_string()),
345                false,
346                self.server_memory_limiter.clone(),
347            )?;
348            handlers.insert((Box::new(grpc_server), grpc_addr));
349        }
350
351        {
352            // Always init the internal/full HTTP server (v1 + internal interfaces)
353            // and, when enabled, the dedicated HTTP API server (v1 + dashboard only).
354            let http_options = &opts.http;
355            let http_addr = parse_addr(&http_options.addr)?;
356            let (http_server, http_api_server) =
357                self.build_http_server(&opts, toml, self.server_memory_limiter.clone())?;
358            handlers.insert((Box::new(http_server), http_addr));
359
360            if let Some(http_api_server) = http_api_server {
361                let http_api_addr = parse_addr(&http_options.api_server_addr)?;
362                info!("HTTP API server is enabled at {}", http_api_addr);
363                handlers.insert((Box::new(http_api_server), http_api_addr));
364            }
365        }
366
367        let table_batcher = opts.table_batcher_options();
368        let batching_enabled = table_batcher.pending_rows_batching_enabled();
369        let mysql_batching =
370            batching_enabled && table_batcher.protocols.contains(&BatchingProtocol::Mysql);
371        let postgres_batching = batching_enabled
372            && table_batcher
373                .protocols
374                .contains(&BatchingProtocol::Postgres);
375
376        if opts.mysql.enable {
377            // Init MySQL server
378            let opts = &opts.mysql;
379            let mysql_addr = parse_addr(&opts.addr)?;
380
381            let tls_server_config = Arc::new(
382                ReloadableTlsServerConfig::try_new(opts.tls.clone()).context(StartServerSnafu)?,
383            );
384
385            // will not watch if watch is disabled in tls option
386            maybe_watch_server_tls_config(tls_server_config.clone()).context(StartServerSnafu)?;
387
388            let mysql_server = MysqlServer::create_server(
389                common_runtime::global_runtime(),
390                Arc::new(MysqlSpawnRef::new(instance.clone(), user_provider.clone())),
391                Arc::new(
392                    MysqlSpawnConfig::new(
393                        opts.tls.should_force_tls(),
394                        tls_server_config,
395                        opts.keep_alive.as_secs(),
396                        opts.reject_no_database.unwrap_or(false),
397                        opts.prepared_stmt_cache_size,
398                    )
399                    .with_batching_enabled(mysql_batching),
400                ),
401                Some(instance.process_manager().clone()),
402            );
403            handlers.insert((mysql_server, mysql_addr));
404        }
405
406        if opts.postgres.enable {
407            // Init PosgresSQL Server
408            let prom_store = effective_prom_store_options(&opts);
409            let pending_rows_batcher = opts
410                .logical_batcher_options()
411                .protocols
412                .contains(&BatchingProtocol::Prom)
413                .then(|| instance.logical_batcher().cloned())
414                .flatten();
415            let opts = &opts.postgres;
416            let pg_addr = parse_addr(&opts.addr)?;
417
418            let tls_server_config = Arc::new(
419                ReloadableTlsServerConfig::try_new(opts.tls.clone()).context(StartServerSnafu)?,
420            );
421
422            maybe_watch_server_tls_config(tls_server_config.clone()).context(StartServerSnafu)?;
423
424            let pg_server = Box::new(
425                PostgresServer::new(
426                    instance.clone(),
427                    instance.clone(),
428                    opts.tls.should_force_tls(),
429                    tls_server_config,
430                    opts.keep_alive.as_secs(),
431                    common_runtime::global_runtime(),
432                    user_provider.clone(),
433                    Some(self.instance.process_manager().clone()),
434                )
435                .with_influxdb_handler(instance.clone())
436                .with_otlp_handler(instance.clone(), prom_store.with_metric_engine)
437                .with_memory_limiter(self.server_memory_limiter.clone())
438                .with_prom_remote_write(
439                    instance.clone(),
440                    Some(instance.clone()),
441                    prom_store.with_metric_engine,
442                    prom_store.prom_validation_mode,
443                    pending_rows_batcher,
444                )
445                .with_batching_enabled(postgres_batching),
446            ) as Box<dyn Server>;
447
448            handlers.insert((pg_server, pg_addr));
449        }
450
451        Ok(handlers)
452    }
453}
454
455/// Selected shared controls override legacy Prom batching knobs, not protocol behavior.
456fn effective_prom_store_options(opts: &FrontendOptions) -> PromStoreOptions {
457    let mut prom_store = opts.prom_store.clone();
458    let shared = opts.logical_batcher_options();
459    if shared.protocols.contains(&BatchingProtocol::Prom) {
460        prom_store.pending_rows_flush_interval = shared.pending_rows_flush_interval;
461        prom_store.max_batch_rows = shared.max_batch_rows;
462        prom_store.max_concurrent_flushes = shared.max_concurrent_flushes;
463        prom_store.worker_channel_capacity = shared.worker_channel_capacity;
464        prom_store.max_inflight_requests = shared.max_inflight_requests;
465        prom_store.flow_notification_queue_capacity = shared.flow_notification_queue_capacity;
466    } else {
467        prom_store.pending_rows_flush_interval = Duration::ZERO;
468    }
469    prom_store
470}
471
472/// Resolves HTTP options, allowing synchronous batches enough time to flush.
473pub fn effective_http_options(opts: &FrontendOptions) -> HttpOptions {
474    effective_http_options_with_sync(opts, pending_rows_batch_sync_enabled())
475}
476
477fn effective_http_options_with_sync(opts: &FrontendOptions, batch_sync: bool) -> HttpOptions {
478    let mut http = opts.http.clone();
479    let prom_store = effective_prom_store_options(opts);
480    let shared = opts.table_batcher_options();
481    let common_enabled = batch_sync
482        && shared.pending_rows_batching_enabled()
483        && shared.protocols.iter().any(|protocol| {
484            !matches!(
485                protocol,
486                BatchingProtocol::Mysql | BatchingProtocol::Postgres
487            ) && (*protocol != BatchingProtocol::Prom
488                || (prom_store.enable && !prom_store.with_metric_engine))
489        });
490    let common_interval = common_enabled.then_some(shared.pending_rows_flush_interval);
491    let prom_interval = (prom_store.pending_rows_batching_enabled() && batch_sync)
492        .then_some(prom_store.pending_rows_flush_interval);
493    let logical = opts.logical_batcher_options();
494    let otlp_interval = (batch_sync
495        && opts.otlp.enable
496        && opts.prom_store.with_metric_engine
497        && logical.protocols.contains(&BatchingProtocol::Otlp)
498        && logical.pending_rows_batching_enabled())
499    .then_some(logical.pending_rows_flush_interval);
500    let Some(flush_interval) = common_interval
501        .into_iter()
502        .chain(prom_interval)
503        .chain(otlp_interval)
504        .max()
505    else {
506        return http;
507    };
508    let fallback_timeout = flush_interval.saturating_add(Duration::from_secs(1));
509    if http.timeout.is_zero() || http.timeout > fallback_timeout {
510        return http;
511    }
512
513    let configured_timeout = http.timeout;
514    http.timeout = fallback_timeout;
515    warn!(
516        ?configured_timeout,
517        ?flush_interval,
518        ?fallback_timeout,
519        "HTTP request timeout is not longer than the pending-row timeout fallback; using the fallback"
520    );
521    http
522}
523
524fn parse_addr(addr: &str) -> Result<SocketAddr> {
525    addr.parse().context(error::ParseAddrSnafu { addr })
526}
527
528#[cfg(test)]
529mod tests {
530    use std::num::NonZeroUsize;
531    use std::sync::Arc;
532    use std::sync::atomic::{AtomicUsize, Ordering};
533    use std::time::Duration;
534
535    use api::v1::HealthCheckRequest;
536    use api::v1::health_check_client::HealthCheckClient;
537    use api::v1::meta::Role;
538    use arrow_flight::{FlightData, PutResult, Ticket};
539    use async_trait::async_trait;
540    use auth::{UserProviderRef, static_user_provider_from_option};
541    use client::{Client, Database};
542    use common_grpc::channel_manager::ChannelManager;
543    use meta_client::client::MetaClientBuilder;
544    use reqwest::header::{ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ORIGIN};
545    use servers::grpc::GRPC_SERVER;
546    use servers::grpc::flight::{FlightCraft, FlightCraftRef, TonicStream};
547    use tonic::{Code, Request, Response, Status, Streaming};
548
549    use crate::instance::builder::FrontendBuilder;
550    use crate::server::*;
551
552    #[tokio::test]
553    async fn test_logical_batcher_shared_without_prom_endpoint() {
554        use crate::service_config::BatcherOptions;
555        let mut options = FrontendOptions::default();
556        options.prom_store.enable = false;
557        options.pending_rows_batcher.logical_table = Some(BatcherOptions {
558            protocols: vec![BatchingProtocol::Otlp],
559            pending_rows_flush_interval: Duration::from_millis(5),
560            ..Default::default()
561        });
562        let meta_client = Arc::new(
563            MetaClientBuilder::new(0, Role::Frontend)
564                .enable_procedure()
565                .build(),
566        );
567        let instance = Arc::new(
568            FrontendBuilder::new_test(&options, meta_client)
569                .try_build()
570                .await
571                .unwrap(),
572        );
573        let mut disabled_options = options.clone();
574        disabled_options.otlp.enable = false;
575        instance.init_logical_batcher(&disabled_options);
576        assert!(instance.logical_batcher().is_none());
577
578        let services = Services::new(options.clone(), instance.clone(), Plugins::default());
579        let batcher = instance.logical_batcher().unwrap().clone();
580        instance.init_logical_batcher(&options);
581        assert!(Arc::ptr_eq(&batcher, instance.logical_batcher().unwrap()));
582        let weak = Arc::downgrade(&instance);
583        drop(services);
584        drop(instance);
585        assert!(
586            weak.upgrade().is_none(),
587            "batcher must not retain its schema owner"
588        );
589    }
590
591    #[tokio::test]
592    async fn test_prom_logical_batcher_endpoint_selection() {
593        use crate::service_config::BatcherOptions;
594
595        for (http_prom, postgres, metric_engine, expected) in [
596            (false, false, true, false),
597            (true, false, true, true),
598            (false, true, true, true),
599            (true, true, true, true),
600            (false, true, false, false),
601        ] {
602            let mut options = FrontendOptions::default();
603            options.prom_store.enable = http_prom;
604            options.postgres.enable = postgres;
605            options.prom_store.with_metric_engine = metric_engine;
606            options.pending_rows_batcher.logical_table = Some(BatcherOptions {
607                protocols: vec![BatchingProtocol::Prom],
608                pending_rows_flush_interval: Duration::from_millis(10),
609                ..Default::default()
610            });
611            let meta_client = Arc::new(
612                MetaClientBuilder::new(0, Role::Frontend)
613                    .enable_procedure()
614                    .build(),
615            );
616            let instance = Arc::new(
617                FrontendBuilder::new_test(&options, meta_client)
618                    .try_build()
619                    .await
620                    .unwrap(),
621            );
622            instance.init_logical_batcher(&options);
623            assert_eq!(
624                instance.logical_batcher().is_some(),
625                expected,
626                "http_prom={http_prom}, postgres={postgres}, metric_engine={metric_engine}"
627            );
628        }
629    }
630
631    #[test]
632    fn test_logical_batcher_http_timeout_and_prom_disable() {
633        use crate::service_config::pending_rows_batcher::BatcherOptions;
634        let mut opts = FrontendOptions::default();
635        opts.http.timeout = Duration::from_secs(1);
636        opts.prom_store.pending_rows_flush_interval = Duration::from_secs(2);
637        opts.pending_rows_batcher.logical_table = Some(BatcherOptions {
638            protocols: vec![BatchingProtocol::Otlp],
639            pending_rows_flush_interval: Duration::from_secs(5),
640            ..Default::default()
641        });
642        assert!(!effective_prom_store_options(&opts).pending_rows_batching_enabled());
643        // Both logical protocols follow the global acknowledgement policy,
644        // independently of enabling the Prom HTTP endpoint.
645        opts.prom_store.enable = false;
646        assert_eq!(
647            effective_http_options_with_sync(&opts, true).timeout,
648            Duration::from_secs(6)
649        );
650        assert_eq!(
651            effective_http_options_with_sync(&opts, false).timeout,
652            opts.http.timeout
653        );
654        opts.prom_store.with_metric_engine = false;
655        assert_eq!(
656            effective_http_options_with_sync(&opts, false).timeout,
657            opts.http.timeout
658        );
659        opts.prom_store.with_metric_engine = true;
660        opts.pending_rows_batcher
661            .logical_table
662            .as_mut()
663            .unwrap()
664            .protocols
665            .clear();
666        assert_eq!(
667            effective_http_options_with_sync(&opts, true).timeout,
668            opts.http.timeout
669        );
670    }
671
672    #[test]
673    fn test_effective_prom_batching_controls() {
674        // Only an enabled shared Prom selection replaces the legacy controls.
675        for (selected, shared_enabled, metric_engine, prom_enabled) in [
676            (true, true, true, true),
677            (false, true, true, true),
678            (true, false, true, true),
679            (true, true, false, true),
680            (true, true, true, false),
681        ] {
682            let mut opts = FrontendOptions::default();
683            opts.http.timeout = Duration::from_millis(1);
684            opts.prom_store.pending_rows_flush_interval = Duration::from_secs(2);
685            opts.prom_store.with_metric_engine = metric_engine;
686            opts.prom_store.enable = prom_enabled;
687            let shared = &mut opts.pending_rows_batcher.table;
688            shared.protocols = vec![if selected {
689                BatchingProtocol::Prom
690            } else {
691                BatchingProtocol::Influxdb
692            }];
693            shared.pending_rows_flush_interval = if shared_enabled {
694                Duration::from_secs(5)
695            } else {
696                Duration::ZERO
697            };
698            shared.max_batch_rows = 7;
699            shared.max_concurrent_flushes = 3;
700            shared.worker_channel_capacity = 11;
701            shared.max_inflight_requests = 13;
702            shared.flow_notification_queue_capacity = NonZeroUsize::new(17).unwrap();
703
704            let mut expected = opts.prom_store.clone();
705            if selected && shared_enabled {
706                expected.pending_rows_flush_interval = shared.pending_rows_flush_interval;
707                expected.max_batch_rows = shared.max_batch_rows;
708                expected.max_concurrent_flushes = shared.max_concurrent_flushes;
709                expected.worker_channel_capacity = shared.worker_channel_capacity;
710                expected.max_inflight_requests = shared.max_inflight_requests;
711                expected.flow_notification_queue_capacity = shared.flow_notification_queue_capacity;
712            }
713            let actual = effective_prom_store_options(&opts);
714            assert_eq!(actual, expected);
715            assert_eq!(
716                actual.pending_rows_batching_enabled(),
717                metric_engine && prom_enabled
718            );
719        }
720    }
721
722    #[test]
723    fn test_http_timeout_covers_synchronous_batchers() {
724        // Only synchronous batchers extend the HTTP timeout.
725        for (
726            protocols,
727            metric_engine,
728            batch_sync,
729            shared_secs,
730            legacy_secs,
731            timeout_secs,
732            expected_secs,
733        ) in [
734            (vec![BatchingProtocol::Prom], false, false, 5, 2, 1, 1),
735            (vec![BatchingProtocol::Mysql], false, false, 5, 0, 1, 1),
736            (vec![BatchingProtocol::Postgres], false, false, 5, 0, 1, 1),
737            (vec![BatchingProtocol::Mysql], false, true, 5, 0, 1, 1),
738            (vec![BatchingProtocol::Postgres], false, true, 5, 0, 1, 1),
739            (vec![BatchingProtocol::Prom], true, false, 5, 2, 1, 1),
740            (vec![BatchingProtocol::Prom], true, true, 5, 2, 1, 6),
741            (vec![BatchingProtocol::Influxdb], true, false, 5, 2, 1, 1),
742            (vec![BatchingProtocol::Influxdb], true, true, 5, 8, 1, 9),
743            (vec![BatchingProtocol::Influxdb], true, true, 8, 5, 1, 9),
744            (vec![BatchingProtocol::Influxdb], true, false, 5, 2, 0, 0),
745            (vec![BatchingProtocol::Influxdb], true, false, 5, 2, 10, 10),
746            (vec![BatchingProtocol::Prom], false, false, 0, 2, 1, 1),
747            (vec![], true, false, 5, 2, 1, 1),
748            (vec![], true, true, 5, 2, 1, 3),
749        ] {
750            let mut opts = FrontendOptions::default();
751            opts.http.timeout = Duration::from_secs(timeout_secs);
752            opts.prom_store.with_metric_engine = metric_engine;
753            opts.prom_store.pending_rows_flush_interval = Duration::from_secs(legacy_secs);
754            opts.pending_rows_batcher.table.protocols = protocols;
755            opts.pending_rows_batcher.table.pending_rows_flush_interval =
756                Duration::from_secs(shared_secs);
757            assert_eq!(
758                effective_http_options_with_sync(&opts, batch_sync).timeout,
759                Duration::from_secs(expected_secs)
760            );
761        }
762    }
763
764    struct CountingFlightCraft {
765        inner: FlightCraftRef,
766        do_get_calls: AtomicUsize,
767        do_put_calls: AtomicUsize,
768    }
769
770    #[async_trait]
771    impl FlightCraft for CountingFlightCraft {
772        async fn do_get(
773            &self,
774            request: Request<Ticket>,
775        ) -> std::result::Result<Response<TonicStream<FlightData>>, Status> {
776            assert_eq!(
777                request.extensions().get::<Channel>(),
778                Some(&Channel::Internal)
779            );
780            self.do_get_calls.fetch_add(1, Ordering::SeqCst);
781            self.inner.do_get(request).await
782        }
783
784        async fn do_put(
785            &self,
786            request: Request<Streaming<FlightData>>,
787        ) -> std::result::Result<Response<TonicStream<PutResult>>, Status> {
788            assert_eq!(
789                request.extensions().get::<Channel>(),
790                Some(&Channel::Internal)
791            );
792            self.do_put_calls.fetch_add(1, Ordering::SeqCst);
793            self.inner.do_put(request).await
794        }
795    }
796
797    #[test]
798    fn test_effective_http_timeout_for_pending_rows() {
799        let cases = [
800            ("disabled timeout", 0, 5000, true, true, 0),
801            ("disabled prom store", 1000, 5000, false, true, 1000),
802            ("disabled metric engine", 1000, 5000, true, false, 1000),
803            ("disabled batching", 1000, 0, true, true, 1000),
804            ("timeout below flush interval", 4000, 5000, true, true, 6000),
805            (
806                "timeout equals flush interval",
807                5000,
808                5000,
809                true,
810                true,
811                6000,
812            ),
813            ("timeout below fallback", 5500, 5000, true, true, 6000),
814            ("timeout equals fallback", 6000, 5000, true, true, 6000),
815            ("timeout above fallback", 7000, 5000, true, true, 7000),
816        ];
817
818        for (name, timeout, flush_interval, enable, with_metric_engine, expected) in cases {
819            let mut opts = FrontendOptions::default();
820            opts.http.timeout = Duration::from_millis(timeout);
821            opts.prom_store.pending_rows_flush_interval = Duration::from_millis(flush_interval);
822            opts.prom_store.enable = enable;
823            opts.prom_store.with_metric_engine = with_metric_engine;
824
825            assert_eq!(
826                Duration::from_millis(expected),
827                effective_http_options_with_sync(&opts, true).timeout,
828                "{name}"
829            );
830        }
831    }
832
833    #[test]
834    fn test_effective_http_timeout_skips_fallback_in_async_batch_mode() {
835        // With `PENDING_ROWS_BATCH_SYNC=false`, submissions return right after
836        // enqueue and no request waits for a pending-row flush, so the
837        // timeout must not be raised.
838        let mut opts = FrontendOptions::default();
839        opts.http.timeout = Duration::from_millis(1000);
840        opts.prom_store.pending_rows_flush_interval = Duration::from_millis(5000);
841
842        assert_eq!(
843            Duration::from_millis(1000),
844            effective_http_options_with_sync(&opts, false).timeout,
845        );
846        assert_eq!(
847            Duration::from_millis(6000),
848            effective_http_options_with_sync(&opts, true).timeout,
849        );
850    }
851
852    #[test]
853    fn test_invalid_shared_batching_preserves_prom_store_options() {
854        type KnobMutator = fn(&mut FrontendOptions);
855        let cases: [KnobMutator; 5] = [
856            |opts| opts.pending_rows_batcher.table.max_concurrent_flushes = usize::MAX,
857            |opts| opts.pending_rows_batcher.table.worker_channel_capacity = usize::MAX,
858            |opts| opts.pending_rows_batcher.table.max_inflight_requests = usize::MAX,
859            |opts| {
860                opts.pending_rows_batcher
861                    .table
862                    .flow_notification_queue_capacity = NonZeroUsize::new(usize::MAX).unwrap()
863            },
864            |opts| opts.pending_rows_batcher.table.pending_rows_flush_interval = Duration::MAX,
865        ];
866        for invalidate in cases {
867            let mut opts = FrontendOptions::default();
868            opts.http.timeout = Duration::from_secs(1);
869            opts.prom_store.pending_rows_flush_interval = Duration::from_secs(5);
870            opts.pending_rows_batcher.table.protocols =
871                vec![BatchingProtocol::Prom, BatchingProtocol::Influxdb];
872            opts.pending_rows_batcher.table.pending_rows_flush_interval = Duration::from_secs(10);
873            invalidate(&mut opts);
874            assert!(
875                !opts
876                    .pending_rows_batcher
877                    .table
878                    .pending_rows_batching_enabled()
879            );
880            assert_eq!(opts.prom_store, effective_prom_store_options(&opts));
881            assert_eq!(
882                Duration::from_secs(6),
883                effective_http_options_with_sync(&opts, true).timeout
884            );
885            opts.prom_store.pending_rows_flush_interval = Duration::ZERO;
886            assert_eq!(
887                Duration::from_secs(1),
888                effective_http_options_with_sync(&opts, true).timeout
889            );
890        }
891    }
892
893    #[test]
894    fn test_effective_http_timeout_skips_fallback_when_batcher_disabled() {
895        // Mirrors the conditions under which `LogicalTablePendingRowsBatcher::try_new`
896        // returns `None`; in these cases no request can wait for a pending-row
897        // flush, so the timeout must not be raised.
898        type KnobMutator = fn(&mut FrontendOptions);
899        let cases: [(&str, KnobMutator); 9] = [
900            ("oversized flush concurrency", |opts| {
901                opts.prom_store.max_concurrent_flushes = usize::MAX
902            }),
903            ("oversized worker channel", |opts| {
904                opts.prom_store.worker_channel_capacity = usize::MAX
905            }),
906            ("oversized inflight limit", |opts| {
907                opts.prom_store.max_inflight_requests = usize::MAX
908            }),
909            ("oversized flow queue", |opts| {
910                opts.prom_store.flow_notification_queue_capacity =
911                    std::num::NonZeroUsize::new(usize::MAX).unwrap()
912            }),
913            ("unrepresentable deadline", |opts| {
914                opts.prom_store.pending_rows_flush_interval = Duration::MAX
915            }),
916            ("zero max_batch_rows", |opts| {
917                opts.prom_store.max_batch_rows = 0
918            }),
919            ("zero max_concurrent_flushes", |opts| {
920                opts.prom_store.max_concurrent_flushes = 0
921            }),
922            ("zero worker_channel_capacity", |opts| {
923                opts.prom_store.worker_channel_capacity = 0
924            }),
925            ("zero max_inflight_requests", |opts| {
926                opts.prom_store.max_inflight_requests = 0
927            }),
928        ];
929
930        for (name, disable_batcher) in cases {
931            let mut opts = FrontendOptions::default();
932            opts.http.timeout = Duration::from_millis(1000);
933            opts.prom_store.pending_rows_flush_interval = Duration::from_millis(5000);
934            disable_batcher(&mut opts);
935
936            assert_eq!(
937                Duration::from_millis(1000),
938                effective_http_options_with_sync(&opts, true).timeout,
939                "{name}"
940            );
941        }
942    }
943
944    #[tokio::test]
945    async fn test_database_sql_authentication_differs_between_public_and_internal_grpc() {
946        let options = FrontendOptions {
947            http: HttpOptions {
948                addr: "127.0.0.1:0".to_string(),
949                ..Default::default()
950            },
951            grpc: GrpcOptions::default().with_bind_addr("127.0.0.1:0"),
952            internal_grpc: Some(GrpcOptions::default().with_bind_addr("127.0.0.1:0")),
953            mysql: crate::service_config::MysqlOptions {
954                enable: false,
955                ..Default::default()
956            },
957            postgres: crate::service_config::PostgresOptions {
958                enable: false,
959                ..Default::default()
960            },
961            ..Default::default()
962        };
963        let meta_client = Arc::new(
964            MetaClientBuilder::new(0, Role::Frontend)
965                .enable_procedure()
966                .build(),
967        );
968        let instance = Arc::new(
969            FrontendBuilder::new_test(&options, meta_client)
970                .try_build()
971                .await
972                .unwrap(),
973        );
974        let plugins = Plugins::new();
975        let provider =
976            static_user_provider_from_option("static_user_provider:cmd:greptime=greptime").unwrap();
977        plugins.insert::<UserProviderRef>(Arc::new(provider));
978        let public_flight_handler = Arc::new(GreptimeRequestHandler::new(
979            instance.clone(),
980            plugins.get::<UserProviderRef>(),
981            None,
982            options.grpc.flight_compression,
983        )) as FlightCraftRef;
984        let internal_flight_handler = Arc::new(CountingFlightCraft {
985            inner: Arc::new(GreptimeRequestHandler::new(
986                instance.clone(),
987                None,
988                None,
989                options.grpc.flight_compression,
990            )),
991            do_get_calls: AtomicUsize::new(0),
992            do_put_calls: AtomicUsize::new(0),
993        });
994        let internal_flight_handler_ref = internal_flight_handler.clone() as FlightCraftRef;
995        let mut services = Services::new(options, instance, plugins)
996            .with_flight_handler(public_flight_handler)
997            .with_internal_flight_handler(internal_flight_handler_ref)
998            .build()
999            .unwrap();
1000
1001        services.start_all().await.unwrap();
1002        let public_addr = services.addr(GRPC_SERVER).unwrap();
1003        let internal_addr = services.addr("INTERNAL_GRPC_SERVER").unwrap();
1004        let public_database = Database::new(
1005            "greptime",
1006            "public",
1007            Client::with_query_and_control_managers(
1008                ChannelManager::new(),
1009                ChannelManager::new(),
1010                [public_addr.to_string()],
1011            ),
1012        );
1013        let internal_database = Database::new(
1014            "greptime",
1015            "public",
1016            Client::with_query_and_control_managers(
1017                ChannelManager::new(),
1018                ChannelManager::new(),
1019                [internal_addr.to_string()],
1020            ),
1021        );
1022
1023        let internal_result = internal_database.sql("SELECT 1").await;
1024        let put_result = internal_database
1025            .do_put(Box::pin(futures::stream::empty()))
1026            .await;
1027        let public_result = public_database.sql("SELECT 1").await;
1028
1029        services.shutdown_all().await.unwrap();
1030
1031        assert!(internal_result.is_ok());
1032        assert!(put_result.is_ok());
1033        assert_eq!(
1034            1,
1035            internal_flight_handler.do_get_calls.load(Ordering::SeqCst)
1036        );
1037        assert_eq!(
1038            1,
1039            internal_flight_handler.do_put_calls.load(Ordering::SeqCst)
1040        );
1041        assert_eq!(
1042            Some(Code::Unauthenticated),
1043            public_result
1044                .as_ref()
1045                .err()
1046                .and_then(|err| err.tonic_code())
1047        );
1048    }
1049
1050    #[tokio::test]
1051    async fn test_services_builder_health_check_is_reachable() {
1052        // Arrange
1053        let options = FrontendOptions {
1054            http: HttpOptions {
1055                addr: "127.0.0.1:0".to_string(),
1056                ..Default::default()
1057            },
1058            grpc: GrpcOptions::default().with_bind_addr("127.0.0.1:0"),
1059            mysql: crate::service_config::MysqlOptions {
1060                enable: false,
1061                ..Default::default()
1062            },
1063            postgres: crate::service_config::PostgresOptions {
1064                enable: false,
1065                ..Default::default()
1066            },
1067            ..Default::default()
1068        };
1069        let meta_client = Arc::new(
1070            MetaClientBuilder::new(0, Role::Frontend)
1071                .enable_procedure()
1072                .build(),
1073        );
1074        let instance = Arc::new(
1075            FrontendBuilder::new_test(&options, meta_client)
1076                .try_build()
1077                .await
1078                .unwrap(),
1079        );
1080        let mut services = Services::new(options, instance, Default::default())
1081            .build()
1082            .unwrap();
1083
1084        // Act
1085        services.start_all().await.unwrap();
1086        let addr = services.addr(GRPC_SERVER).unwrap();
1087        let health_check = HealthCheckClient::connect(format!("http://{addr}"))
1088            .await
1089            .unwrap()
1090            .health_check(HealthCheckRequest {})
1091            .await;
1092        services.shutdown_all().await.unwrap();
1093
1094        // Assert
1095        assert!(health_check.is_ok());
1096    }
1097
1098    #[tokio::test]
1099    async fn test_internal_grpc_server_never_serves_cors() {
1100        let options = FrontendOptions {
1101            http: HttpOptions {
1102                addr: "127.0.0.1:0".to_string(),
1103                ..Default::default()
1104            },
1105            grpc: GrpcOptions {
1106                enable_cors: true,
1107                ..GrpcOptions::default().with_bind_addr("127.0.0.1:0")
1108            },
1109            internal_grpc: Some(GrpcOptions {
1110                enable_cors: true,
1111                ..GrpcOptions::default().with_bind_addr("127.0.0.1:0")
1112            }),
1113            mysql: crate::service_config::MysqlOptions {
1114                enable: false,
1115                ..Default::default()
1116            },
1117            postgres: crate::service_config::PostgresOptions {
1118                enable: false,
1119                ..Default::default()
1120            },
1121            ..Default::default()
1122        };
1123        let meta_client = Arc::new(
1124            MetaClientBuilder::new(0, Role::Frontend)
1125                .enable_procedure()
1126                .build(),
1127        );
1128        let instance = Arc::new(
1129            FrontendBuilder::new_test(&options, meta_client)
1130                .try_build()
1131                .await
1132                .unwrap(),
1133        );
1134        let mut services = Services::new(options, instance, Default::default())
1135            .build()
1136            .unwrap();
1137
1138        services.start_all().await.unwrap();
1139        let public_addr = services.addr(GRPC_SERVER).unwrap();
1140        let internal_addr = services.addr("INTERNAL_GRPC_SERVER").unwrap();
1141        let public = send_cors_preflight(public_addr).await;
1142        let internal = send_cors_preflight(internal_addr).await;
1143        services.shutdown_all().await.unwrap();
1144
1145        assert!(public.headers().contains_key(ACCESS_CONTROL_ALLOW_ORIGIN));
1146        assert!(!internal.headers().contains_key(ACCESS_CONTROL_ALLOW_ORIGIN));
1147    }
1148
1149    async fn send_cors_preflight(addr: std::net::SocketAddr) -> reqwest::Response {
1150        reqwest::Client::new()
1151            .request(
1152                reqwest::Method::OPTIONS,
1153                format!("http://{addr}/greptime.v1.HealthCheck/Check"),
1154            )
1155            .header(ORIGIN, "https://example.com")
1156            .header(ACCESS_CONTROL_REQUEST_METHOD, "POST")
1157            .send()
1158            .await
1159            .unwrap()
1160    }
1161}