Skip to main content

servers/
http.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::collections::HashMap;
16use std::convert::Infallible;
17use std::fmt::Display;
18use std::net::SocketAddr;
19use std::sync::{Arc, Mutex as StdMutex};
20use std::time::Duration;
21
22use async_trait::async_trait;
23use auth::UserProviderRef;
24use axum::extract::{DefaultBodyLimit, Request};
25use axum::http::StatusCode as HttpStatusCode;
26use axum::response::{IntoResponse, Response};
27use axum::routing::Route;
28use axum::serve::ListenerExt;
29use axum::{Router, middleware, routing};
30use common_base::readable_size::ReadableSize;
31use common_recordbatch::RecordBatch;
32use common_telemetry::{error, info};
33use common_time::Timestamp;
34use common_time::timestamp::TimeUnit;
35use datatypes::data_type::DataType;
36use datatypes::schema::SchemaRef;
37use event::{LogState, LogValidatorRef};
38use futures::FutureExt;
39use http::{HeaderValue, Method};
40use serde::{Deserialize, Serialize};
41use serde_json::Value;
42use snafu::{ResultExt, ensure};
43use tokio::sync::Mutex;
44use tokio::sync::oneshot::{self, Sender};
45use tonic::codegen::Service;
46use tower::{Layer, ServiceBuilder};
47use tower_http::compression::CompressionLayer;
48use tower_http::cors::{AllowOrigin, Any, CorsLayer};
49use tower_http::decompression::RequestDecompressionLayer;
50use tower_http::trace::TraceLayer;
51
52use self::authorize::AuthState;
53use self::result::table_result::TableResponse;
54use crate::elasticsearch;
55use crate::error::{
56    AddressBindSnafu, AlreadyStartedSnafu, Error, InternalIoSnafu, InvalidHeaderValueSnafu, Result,
57};
58use crate::http::influxdb::{influxdb_health, influxdb_ping, influxdb_write_v1, influxdb_write_v2};
59use crate::http::otlp::OtlpState;
60use crate::http::prom_store::PromStoreState;
61use crate::http::prometheus::{
62    build_info_query, format_query, instant_query, label_values_query, labels_query, parse_query,
63    range_query, series_query,
64};
65use crate::http::result::arrow_result::ArrowResponse;
66use crate::http::result::csv_result::CsvResponse;
67use crate::http::result::error_result::ErrorResponse;
68use crate::http::result::greptime_result_v1::GreptimedbV1Response;
69use crate::http::result::influxdb_result_v1::InfluxdbV1Response;
70use crate::http::result::json_result::JsonResponse;
71use crate::http::result::null_result::NullResponse;
72use crate::interceptor::LogIngestInterceptorRef;
73use crate::metrics::http_metrics_layer;
74use crate::metrics_handler::MetricsHandler;
75use crate::pending_rows_batcher::PendingRowsBatcher;
76use crate::prometheus_handler::PrometheusHandlerRef;
77use crate::query_handler::sql::ServerSqlQueryHandlerRef;
78use crate::query_handler::{
79    DashboardHandlerRef, InfluxdbLineProtocolHandlerRef, JaegerQueryHandlerRef, LogQueryHandlerRef,
80    OpenTelemetryProtocolHandlerRef, OpentsdbProtocolHandlerRef, PipelineHandlerRef,
81    PromStoreProtocolHandlerRef,
82};
83use crate::request_memory_limiter::ServerMemoryLimiter;
84use crate::server::Server;
85
86pub mod authorize;
87#[cfg(feature = "dashboard")]
88mod dashboard;
89pub mod dyn_log;
90pub mod dyn_trace;
91pub mod event;
92pub mod extractor;
93pub mod handler;
94pub mod header;
95pub mod influxdb;
96pub mod jaeger;
97pub mod logs;
98pub mod loki;
99pub mod mem_prof;
100mod memory_limit;
101pub mod opentsdb;
102pub mod otlp;
103pub mod pprof;
104pub mod prom_store;
105pub mod prometheus;
106pub mod result;
107pub mod splunk;
108mod timeout;
109pub mod utils;
110
111use result::HttpOutputWriter;
112pub(crate) use timeout::DynamicTimeoutLayer;
113
114mod client_ip;
115use crate::prom_remote_write::validation::PromValidationMode;
116mod hints;
117mod read_preference;
118#[cfg(any(test, feature = "testing"))]
119pub mod test_helpers;
120
121pub const HTTP_API_VERSION: &str = "v1";
122pub const HTTP_API_PREFIX: &str = "/v1/";
123pub const HTTP_API_PREFIX_WITHOUT_TRAILING_SLASH: &str = "/v1";
124/// Default http body limit (64M).
125const DEFAULT_BODY_LIMIT: ReadableSize = ReadableSize::mb(64);
126
127/// Authorization header
128pub const AUTHORIZATION_HEADER: &str = "x-greptime-auth";
129
130// TODO(fys): This is a temporary workaround, it will be improved later
131pub static PUBLIC_API_PREFIX: [&str; 4] = [
132    "/v1/influxdb/ping",
133    "/v1/influxdb/health",
134    "/v1/health",
135    "/v1/splunk/services/collector/health",
136];
137
138#[derive(Default)]
139pub struct HttpServer {
140    router: StdMutex<Router>,
141    shutdown_tx: Mutex<Option<Sender<()>>>,
142    user_provider: Option<UserProviderRef>,
143    memory_limiter: ServerMemoryLimiter,
144
145    // server configs
146    options: HttpOptions,
147    bind_addr: Option<SocketAddr>,
148}
149
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
151#[serde(default)]
152pub struct HttpOptions {
153    pub addr: String,
154
155    #[serde(with = "humantime_serde")]
156    pub timeout: Duration,
157
158    #[serde(skip)]
159    pub disable_dashboard: bool,
160
161    pub body_limit: ReadableSize,
162
163    /// Validation mode while decoding Prometheus remote write requests.
164    pub prom_validation_mode: PromValidationMode,
165
166    /// Enables experimental Prometheus remote write v2 native histogram ingestion.
167    pub experimental_enable_prometheus_native_histogram: bool,
168
169    pub cors_allowed_origins: Vec<String>,
170
171    pub enable_cors: bool,
172
173    pub experimental_enable_explain_analyze_stream: bool,
174}
175
176impl Default for HttpOptions {
177    fn default() -> Self {
178        Self {
179            addr: "127.0.0.1:4000".to_string(),
180            timeout: Duration::from_secs(0),
181            disable_dashboard: false,
182            body_limit: DEFAULT_BODY_LIMIT,
183            cors_allowed_origins: Vec::new(),
184            enable_cors: true,
185            prom_validation_mode: PromValidationMode::Strict,
186            experimental_enable_prometheus_native_histogram: false,
187            experimental_enable_explain_analyze_stream: false,
188        }
189    }
190}
191
192#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
193pub struct ColumnSchema {
194    name: String,
195    data_type: String,
196}
197
198impl ColumnSchema {
199    pub fn new(name: String, data_type: String) -> ColumnSchema {
200        ColumnSchema { name, data_type }
201    }
202}
203
204#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
205pub struct OutputSchema {
206    column_schemas: Vec<ColumnSchema>,
207}
208
209impl OutputSchema {
210    pub fn new(columns: Vec<ColumnSchema>) -> OutputSchema {
211        OutputSchema {
212            column_schemas: columns,
213        }
214    }
215}
216
217impl From<SchemaRef> for OutputSchema {
218    fn from(schema: SchemaRef) -> OutputSchema {
219        OutputSchema {
220            column_schemas: schema
221                .column_schemas()
222                .iter()
223                .map(|cs| ColumnSchema {
224                    name: cs.name.clone(),
225                    data_type: cs.data_type.name(),
226                })
227                .collect(),
228        }
229    }
230}
231
232#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
233pub struct HttpRecordsOutput {
234    schema: OutputSchema,
235    rows: Vec<Vec<Value>>,
236    // total_rows is equal to rows.len() in most cases,
237    // the Dashboard query result may be truncated, so we need to return the total_rows.
238    #[serde(default)]
239    total_rows: usize,
240
241    // plan level execution metrics
242    #[serde(skip_serializing_if = "HashMap::is_empty")]
243    #[serde(default)]
244    metrics: HashMap<String, Value>,
245}
246
247impl HttpRecordsOutput {
248    pub fn num_rows(&self) -> usize {
249        self.rows.len()
250    }
251
252    pub fn num_cols(&self) -> usize {
253        self.schema.column_schemas.len()
254    }
255
256    pub fn schema(&self) -> &OutputSchema {
257        &self.schema
258    }
259
260    pub fn rows(&self) -> &Vec<Vec<Value>> {
261        &self.rows
262    }
263}
264
265impl HttpRecordsOutput {
266    pub fn try_new(
267        schema: SchemaRef,
268        recordbatches: Vec<RecordBatch>,
269    ) -> std::result::Result<HttpRecordsOutput, Error> {
270        if recordbatches.is_empty() {
271            Ok(HttpRecordsOutput {
272                schema: OutputSchema::from(schema),
273                rows: vec![],
274                total_rows: 0,
275                metrics: Default::default(),
276            })
277        } else {
278            let num_rows = recordbatches.iter().map(|r| r.num_rows()).sum::<usize>();
279            let mut rows = Vec::with_capacity(num_rows);
280
281            for recordbatch in recordbatches {
282                let mut writer = HttpOutputWriter::new(schema.num_columns(), None);
283                writer.write(recordbatch, &mut rows)?;
284            }
285
286            Ok(HttpRecordsOutput {
287                schema: OutputSchema::from(schema),
288                total_rows: rows.len(),
289                rows,
290                metrics: Default::default(),
291            })
292        }
293    }
294}
295
296#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
297#[serde(rename_all = "lowercase")]
298pub enum GreptimeQueryOutput {
299    AffectedRows(usize),
300    Records(HttpRecordsOutput),
301}
302
303/// It allows the results of SQL queries to be presented in different formats.
304#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
305pub enum ResponseFormat {
306    Arrow,
307    // (with_names, with_types)
308    Csv(bool, bool),
309    Table,
310    #[default]
311    GreptimedbV1,
312    InfluxdbV1,
313    Json,
314    Null,
315}
316
317impl ResponseFormat {
318    pub fn parse(s: &str) -> Option<Self> {
319        match s {
320            "arrow" => Some(ResponseFormat::Arrow),
321            "csv" => Some(ResponseFormat::Csv(false, false)),
322            "csvwithnames" => Some(ResponseFormat::Csv(true, false)),
323            "csvwithnamesandtypes" => Some(ResponseFormat::Csv(true, true)),
324            "table" => Some(ResponseFormat::Table),
325            "greptimedb_v1" => Some(ResponseFormat::GreptimedbV1),
326            "influxdb_v1" => Some(ResponseFormat::InfluxdbV1),
327            "json" => Some(ResponseFormat::Json),
328            "null" => Some(ResponseFormat::Null),
329            _ => None,
330        }
331    }
332
333    pub fn as_str(&self) -> &'static str {
334        match self {
335            ResponseFormat::Arrow => "arrow",
336            ResponseFormat::Csv(_, _) => "csv",
337            ResponseFormat::Table => "table",
338            ResponseFormat::GreptimedbV1 => "greptimedb_v1",
339            ResponseFormat::InfluxdbV1 => "influxdb_v1",
340            ResponseFormat::Json => "json",
341            ResponseFormat::Null => "null",
342        }
343    }
344}
345
346#[derive(Debug, Clone, Copy, PartialEq, Eq)]
347pub enum Epoch {
348    Nanosecond,
349    Microsecond,
350    Millisecond,
351    Second,
352}
353
354impl Epoch {
355    pub fn parse(s: &str) -> Option<Epoch> {
356        // Both u and µ indicate microseconds.
357        // epoch = [ns,u,µ,ms,s],
358        // For details, see the Influxdb documents.
359        // https://docs.influxdata.com/influxdb/v1/tools/api/#query-string-parameters-1
360        match s {
361            "ns" => Some(Epoch::Nanosecond),
362            "u" | "µ" => Some(Epoch::Microsecond),
363            "ms" => Some(Epoch::Millisecond),
364            "s" => Some(Epoch::Second),
365            _ => None, // just returns None for other cases
366        }
367    }
368
369    pub fn convert_timestamp(&self, ts: Timestamp) -> Option<Timestamp> {
370        match self {
371            Epoch::Nanosecond => ts.convert_to(TimeUnit::Nanosecond),
372            Epoch::Microsecond => ts.convert_to(TimeUnit::Microsecond),
373            Epoch::Millisecond => ts.convert_to(TimeUnit::Millisecond),
374            Epoch::Second => ts.convert_to(TimeUnit::Second),
375        }
376    }
377}
378
379impl Display for Epoch {
380    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
381        match self {
382            Epoch::Nanosecond => write!(f, "Epoch::Nanosecond"),
383            Epoch::Microsecond => write!(f, "Epoch::Microsecond"),
384            Epoch::Millisecond => write!(f, "Epoch::Millisecond"),
385            Epoch::Second => write!(f, "Epoch::Second"),
386        }
387    }
388}
389
390#[derive(Serialize, Deserialize, Debug)]
391pub enum HttpResponse {
392    Arrow(ArrowResponse),
393    Csv(CsvResponse),
394    Table(TableResponse),
395    Error(ErrorResponse),
396    GreptimedbV1(GreptimedbV1Response),
397    InfluxdbV1(InfluxdbV1Response),
398    Json(JsonResponse),
399    Null(NullResponse),
400}
401
402impl HttpResponse {
403    pub fn with_execution_time(self, execution_time: u64) -> Self {
404        match self {
405            HttpResponse::Arrow(resp) => resp.with_execution_time(execution_time).into(),
406            HttpResponse::Csv(resp) => resp.with_execution_time(execution_time).into(),
407            HttpResponse::Table(resp) => resp.with_execution_time(execution_time).into(),
408            HttpResponse::GreptimedbV1(resp) => resp.with_execution_time(execution_time).into(),
409            HttpResponse::InfluxdbV1(resp) => resp.with_execution_time(execution_time).into(),
410            HttpResponse::Json(resp) => resp.with_execution_time(execution_time).into(),
411            HttpResponse::Null(resp) => resp.with_execution_time(execution_time).into(),
412            HttpResponse::Error(resp) => resp.with_execution_time(execution_time).into(),
413        }
414    }
415
416    pub fn with_limit(self, limit: usize) -> Self {
417        match self {
418            HttpResponse::Csv(resp) => resp.with_limit(limit).into(),
419            HttpResponse::Table(resp) => resp.with_limit(limit).into(),
420            HttpResponse::GreptimedbV1(resp) => resp.with_limit(limit).into(),
421            HttpResponse::Json(resp) => resp.with_limit(limit).into(),
422            _ => self,
423        }
424    }
425}
426
427pub fn process_with_limit(
428    mut outputs: Vec<GreptimeQueryOutput>,
429    limit: usize,
430) -> Vec<GreptimeQueryOutput> {
431    outputs
432        .drain(..)
433        .map(|data| match data {
434            GreptimeQueryOutput::Records(mut records) => {
435                if records.rows.len() > limit {
436                    records.rows.truncate(limit);
437                    records.total_rows = limit;
438                }
439                GreptimeQueryOutput::Records(records)
440            }
441            _ => data,
442        })
443        .collect()
444}
445
446impl IntoResponse for HttpResponse {
447    fn into_response(self) -> Response {
448        match self {
449            HttpResponse::Arrow(resp) => resp.into_response(),
450            HttpResponse::Csv(resp) => resp.into_response(),
451            HttpResponse::Table(resp) => resp.into_response(),
452            HttpResponse::GreptimedbV1(resp) => resp.into_response(),
453            HttpResponse::InfluxdbV1(resp) => resp.into_response(),
454            HttpResponse::Json(resp) => resp.into_response(),
455            HttpResponse::Null(resp) => resp.into_response(),
456            HttpResponse::Error(resp) => resp.into_response(),
457        }
458    }
459}
460
461impl From<ArrowResponse> for HttpResponse {
462    fn from(value: ArrowResponse) -> Self {
463        HttpResponse::Arrow(value)
464    }
465}
466
467impl From<CsvResponse> for HttpResponse {
468    fn from(value: CsvResponse) -> Self {
469        HttpResponse::Csv(value)
470    }
471}
472
473impl From<TableResponse> for HttpResponse {
474    fn from(value: TableResponse) -> Self {
475        HttpResponse::Table(value)
476    }
477}
478
479impl From<ErrorResponse> for HttpResponse {
480    fn from(value: ErrorResponse) -> Self {
481        HttpResponse::Error(value)
482    }
483}
484
485impl From<GreptimedbV1Response> for HttpResponse {
486    fn from(value: GreptimedbV1Response) -> Self {
487        HttpResponse::GreptimedbV1(value)
488    }
489}
490
491impl From<InfluxdbV1Response> for HttpResponse {
492    fn from(value: InfluxdbV1Response) -> Self {
493        HttpResponse::InfluxdbV1(value)
494    }
495}
496
497impl From<JsonResponse> for HttpResponse {
498    fn from(value: JsonResponse) -> Self {
499        HttpResponse::Json(value)
500    }
501}
502
503impl From<NullResponse> for HttpResponse {
504    fn from(value: NullResponse) -> Self {
505        HttpResponse::Null(value)
506    }
507}
508
509#[derive(Clone)]
510pub struct ApiState {
511    pub sql_handler: ServerSqlQueryHandlerRef,
512    pub experimental_enable_explain_analyze_stream: bool,
513}
514
515#[derive(Clone)]
516pub struct GreptimeOptionsConfigState {
517    pub greptime_config_options: String,
518}
519
520#[derive(Clone)]
521pub struct DashboardState {
522    pub handler: DashboardHandlerRef,
523}
524
525pub struct HttpServerBuilder {
526    options: HttpOptions,
527    user_provider: Option<UserProviderRef>,
528    router: Router,
529    memory_limiter: ServerMemoryLimiter,
530}
531
532impl HttpServerBuilder {
533    pub fn new(options: HttpOptions) -> Self {
534        Self {
535            options,
536            user_provider: None,
537            router: Router::new(),
538            memory_limiter: ServerMemoryLimiter::default(),
539        }
540    }
541
542    /// Set a global memory limiter for all server protocols.
543    pub fn with_memory_limiter(mut self, limiter: ServerMemoryLimiter) -> Self {
544        self.memory_limiter = limiter;
545        self
546    }
547
548    pub fn with_sql_handler(self, sql_handler: ServerSqlQueryHandlerRef) -> Self {
549        let sql_router = HttpServer::route_sql(ApiState {
550            sql_handler,
551            experimental_enable_explain_analyze_stream: self
552                .options
553                .experimental_enable_explain_analyze_stream,
554        });
555
556        Self {
557            router: self
558                .router
559                .nest(&format!("/{HTTP_API_VERSION}"), sql_router),
560            ..self
561        }
562    }
563
564    pub fn with_logs_handler(self, logs_handler: LogQueryHandlerRef) -> Self {
565        let logs_router = HttpServer::route_logs(logs_handler);
566
567        Self {
568            router: self
569                .router
570                .nest(&format!("/{HTTP_API_VERSION}"), logs_router),
571            ..self
572        }
573    }
574
575    pub fn with_opentsdb_handler(self, handler: OpentsdbProtocolHandlerRef) -> Self {
576        Self {
577            router: self.router.nest(
578                &format!("/{HTTP_API_VERSION}/opentsdb"),
579                HttpServer::route_opentsdb(handler),
580            ),
581            ..self
582        }
583    }
584
585    pub fn with_influxdb_handler(self, handler: InfluxdbLineProtocolHandlerRef) -> Self {
586        Self {
587            router: self.router.nest(
588                &format!("/{HTTP_API_VERSION}/influxdb"),
589                HttpServer::route_influxdb(handler),
590            ),
591            ..self
592        }
593    }
594
595    pub fn with_prom_handler(
596        self,
597        handler: PromStoreProtocolHandlerRef,
598        pipeline_handler: Option<PipelineHandlerRef>,
599        prom_store_with_metric_engine: bool,
600        prom_validation_mode: PromValidationMode,
601        pending_rows_batcher: Option<Arc<PendingRowsBatcher>>,
602    ) -> Self {
603        let state = PromStoreState {
604            prom_store_handler: handler,
605            pipeline_handler,
606            prom_store_with_metric_engine,
607            prom_validation_mode,
608            experimental_enable_prometheus_native_histogram: self
609                .options
610                .experimental_enable_prometheus_native_histogram,
611            pending_rows_batcher,
612        };
613
614        Self {
615            router: self.router.nest(
616                &format!("/{HTTP_API_VERSION}/prometheus"),
617                HttpServer::route_prom(state),
618            ),
619            ..self
620        }
621    }
622
623    pub fn with_prometheus_handler(self, handler: PrometheusHandlerRef) -> Self {
624        Self {
625            router: self.router.nest(
626                &format!("/{HTTP_API_VERSION}/prometheus/api/v1"),
627                HttpServer::route_prometheus(handler),
628            ),
629            ..self
630        }
631    }
632
633    pub fn with_otlp_handler(
634        self,
635        handler: OpenTelemetryProtocolHandlerRef,
636        with_metric_engine: bool,
637    ) -> Self {
638        Self {
639            router: self.router.nest(
640                &format!("/{HTTP_API_VERSION}/otlp"),
641                HttpServer::route_otlp(handler, with_metric_engine),
642            ),
643            ..self
644        }
645    }
646
647    pub fn with_user_provider(self, user_provider: UserProviderRef) -> Self {
648        Self {
649            user_provider: Some(user_provider),
650            ..self
651        }
652    }
653
654    pub fn with_metrics_handler(self, handler: MetricsHandler) -> Self {
655        Self {
656            router: self.router.merge(HttpServer::route_metrics(handler)),
657            ..self
658        }
659    }
660
661    pub fn with_log_ingest_handler(
662        self,
663        handler: PipelineHandlerRef,
664        validator: Option<LogValidatorRef>,
665        ingest_interceptor: Option<LogIngestInterceptorRef<Error>>,
666    ) -> Self {
667        let log_state = LogState {
668            log_handler: handler,
669            log_validator: validator,
670            ingest_interceptor,
671        };
672
673        let router = self.router.nest(
674            &format!("/{HTTP_API_VERSION}"),
675            HttpServer::route_pipelines(log_state.clone()),
676        );
677        // deprecated since v0.11.0. Use `/logs` and `/pipelines` instead.
678        let router = router.nest(
679            &format!("/{HTTP_API_VERSION}/events"),
680            #[allow(deprecated)]
681            HttpServer::route_log_deprecated(log_state.clone()),
682        );
683
684        let router = router.nest(
685            &format!("/{HTTP_API_VERSION}/loki"),
686            HttpServer::route_loki(log_state.clone()),
687        );
688
689        let router = router.nest(
690            &format!("/{HTTP_API_VERSION}/elasticsearch"),
691            HttpServer::route_elasticsearch(log_state.clone()),
692        );
693
694        let router = router.nest(
695            &format!("/{HTTP_API_VERSION}/elasticsearch/"),
696            Router::new()
697                .route("/", routing::get(elasticsearch::handle_get_version))
698                .with_state(log_state.clone()),
699        );
700
701        let router = router.nest(
702            &format!("/{HTTP_API_VERSION}/splunk"),
703            HttpServer::route_splunk(log_state),
704        );
705
706        Self { router, ..self }
707    }
708
709    pub fn with_greptime_config_options(self, opts: String) -> Self {
710        let config_router = HttpServer::route_config(GreptimeOptionsConfigState {
711            greptime_config_options: opts,
712        });
713
714        Self {
715            router: self.router.merge(config_router),
716            ..self
717        }
718    }
719
720    pub fn with_jaeger_handler(self, handler: JaegerQueryHandlerRef) -> Self {
721        Self {
722            router: self.router.nest(
723                &format!("/{HTTP_API_VERSION}/jaeger"),
724                HttpServer::route_jaeger(handler),
725            ),
726            ..self
727        }
728    }
729
730    pub fn with_dashboard_handler(self, handler: DashboardHandlerRef) -> Self {
731        Self {
732            router: self.router.nest(
733                &format!("/{HTTP_API_VERSION}/dashboards"),
734                HttpServer::route_dashboard(handler),
735            ),
736            ..self
737        }
738    }
739
740    pub fn with_extra_router(self, router: Router) -> Self {
741        Self {
742            router: self.router.merge(router),
743            ..self
744        }
745    }
746
747    pub fn add_layer<L>(self, layer: L) -> Self
748    where
749        L: Layer<Route> + Clone + Send + Sync + 'static,
750        L::Service: Service<Request> + Clone + Send + Sync + 'static,
751        <L::Service as Service<Request>>::Response: IntoResponse + 'static,
752        <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
753        <L::Service as Service<Request>>::Future: Send + 'static,
754    {
755        Self {
756            router: self.router.layer(layer),
757            ..self
758        }
759    }
760
761    pub fn build(self) -> HttpServer {
762        HttpServer {
763            options: self.options,
764            user_provider: self.user_provider,
765            shutdown_tx: Mutex::new(None),
766            router: StdMutex::new(self.router),
767            bind_addr: None,
768            memory_limiter: self.memory_limiter,
769        }
770    }
771}
772
773impl HttpServer {
774    /// Gets the router and adds necessary root routes (health, status, dashboard).
775    pub fn make_app(&self) -> Router {
776        let mut router = {
777            let router = self.router.lock().unwrap();
778            router.clone()
779        };
780
781        router = router
782            .route("/", routing::get(handler::index))
783            .route(
784                "/health",
785                routing::get(handler::health).post(handler::health),
786            )
787            .route(
788                &format!("/{HTTP_API_VERSION}/health"),
789                routing::get(handler::health).post(handler::health),
790            )
791            .route(
792                "/ready",
793                routing::get(handler::health).post(handler::health),
794            );
795
796        router = router.route("/status", routing::get(handler::status));
797
798        #[cfg(feature = "dashboard")]
799        {
800            if !self.options.disable_dashboard {
801                info!("Enable dashboard service at '/dashboard'");
802                // redirect /dashboard to /dashboard/
803                router = router.route(
804                    "/dashboard",
805                    routing::get(|uri: axum::http::uri::Uri| async move {
806                        let path = uri.path();
807                        let query = uri.query().map(|q| format!("?{}", q)).unwrap_or_default();
808
809                        let new_uri = format!("{}/{}", path, query);
810                        axum::response::Redirect::permanent(&new_uri)
811                    }),
812                );
813
814                // "/dashboard" and "/dashboard/" are two different paths in Axum.
815                // We cannot nest "/dashboard/", because we already mapping "/dashboard/{*x}" while nesting "/dashboard".
816                // So we explicitly route "/dashboard/" here.
817                router = router
818                    .route(
819                        "/dashboard/",
820                        routing::get(dashboard::static_handler).post(dashboard::static_handler),
821                    )
822                    .route(
823                        "/dashboard/{*x}",
824                        routing::get(dashboard::static_handler).post(dashboard::static_handler),
825                    );
826            }
827        }
828
829        // Add a layer to collect HTTP metrics for axum.
830        router = router.route_layer(middleware::from_fn(http_metrics_layer));
831
832        router
833    }
834
835    /// Attaches middlewares and debug routes to the router.
836    /// Callers should call this method after [HttpServer::make_app()].
837    pub fn build(&self, router: Router) -> Result<Router> {
838        let timeout_layer = if self.options.timeout != Duration::default() {
839            Some(ServiceBuilder::new().layer(DynamicTimeoutLayer::new(self.options.timeout)))
840        } else {
841            info!("HTTP server timeout is disabled");
842            None
843        };
844        let body_limit_layer = if self.options.body_limit != ReadableSize(0) {
845            Some(
846                ServiceBuilder::new()
847                    .layer(DefaultBodyLimit::max(self.options.body_limit.0 as usize)),
848            )
849        } else {
850            info!("HTTP server body limit is disabled");
851            None
852        };
853        let cors_layer = if self.options.enable_cors {
854            Some(
855                CorsLayer::new()
856                    .allow_methods([
857                        Method::GET,
858                        Method::POST,
859                        Method::PUT,
860                        Method::DELETE,
861                        Method::HEAD,
862                    ])
863                    .allow_origin(if self.options.cors_allowed_origins.is_empty() {
864                        AllowOrigin::from(Any)
865                    } else {
866                        AllowOrigin::from(
867                            self.options
868                                .cors_allowed_origins
869                                .iter()
870                                .map(|s| {
871                                    HeaderValue::from_str(s.as_str())
872                                        .context(InvalidHeaderValueSnafu)
873                                })
874                                .collect::<Result<Vec<HeaderValue>>>()?,
875                        )
876                    })
877                    .allow_headers(Any),
878            )
879        } else {
880            info!("HTTP server cross-origin is disabled");
881            None
882        };
883
884        Ok(router
885            // middlewares
886            .layer(
887                ServiceBuilder::new()
888                    // disable on failure tracing. because printing out isn't very helpful,
889                    // and we have impl IntoResponse for Error. It will print out more detailed error messages
890                    .layer(TraceLayer::new_for_http().on_failure(()))
891                    .option_layer(cors_layer)
892                    .option_layer(timeout_layer)
893                    .option_layer(body_limit_layer)
894                    // memory limit layer - must be before body is consumed
895                    .layer(middleware::from_fn_with_state(
896                        self.memory_limiter.clone(),
897                        memory_limit::memory_limit_middleware,
898                    ))
899                    // auth layer
900                    .layer(middleware::from_fn_with_state(
901                        AuthState::new(self.user_provider.clone()),
902                        authorize::check_http_auth,
903                    ))
904                    .layer(middleware::from_fn(hints::extract_hints))
905                    .layer(middleware::from_fn(client_ip::log_error_with_client_ip))
906                    .layer(middleware::from_fn(
907                        read_preference::extract_read_preference,
908                    )),
909            )
910            // Handlers for debug, we don't expect a timeout.
911            .nest(
912                "/debug",
913                Router::new()
914                    // handler for changing log level dynamically
915                    .route("/log_level", routing::post(dyn_log::dyn_log_handler))
916                    .route("/enable_trace", routing::post(dyn_trace::dyn_trace_handler))
917                    .nest(
918                        "/prof",
919                        Router::new()
920                            .route("/cpu", routing::post(pprof::pprof_handler))
921                            .route("/mem", routing::post(mem_prof::mem_prof_handler))
922                            .route("/mem/symbol", routing::post(mem_prof::symbolicate_handler))
923                            .route(
924                                "/mem/activate",
925                                routing::post(mem_prof::activate_heap_prof_handler),
926                            )
927                            .route(
928                                "/mem/deactivate",
929                                routing::post(mem_prof::deactivate_heap_prof_handler),
930                            )
931                            .route(
932                                "/mem/status",
933                                routing::get(mem_prof::heap_prof_status_handler),
934                            ) // jemalloc gdump flag status and toggle
935                            .route(
936                                "/mem/gdump",
937                                routing::get(mem_prof::gdump_status_handler)
938                                    .post(mem_prof::gdump_toggle_handler),
939                            ),
940                    ),
941            ))
942    }
943
944    fn route_metrics<S>(metrics_handler: MetricsHandler) -> Router<S> {
945        Router::new()
946            .route("/metrics", routing::get(handler::metrics))
947            .with_state(metrics_handler)
948    }
949
950    fn route_loki<S>(log_state: LogState) -> Router<S> {
951        Router::new()
952            .route("/api/v1/push", routing::post(loki::loki_ingest))
953            .layer(
954                ServiceBuilder::new()
955                    .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
956            )
957            .with_state(log_state)
958    }
959
960    fn route_splunk<S>(log_state: LogState) -> Router<S> {
961        Router::new()
962            .route(
963                "/services/collector/health",
964                routing::get(splunk::handle_health),
965            )
966            .route(
967                "/services/collector/health/1.0",
968                routing::get(splunk::handle_health),
969            )
970            // The event endpoint plus its base and versioned aliases all serve
971            // the same handler (Splunk JSON event protocol).
972            .route(
973                "/services/collector/event",
974                routing::post(splunk::handle_event),
975            )
976            .route("/services/collector", routing::post(splunk::handle_event))
977            .route(
978                "/services/collector/event/1.0",
979                routing::post(splunk::handle_event),
980            )
981            .layer(
982                ServiceBuilder::new()
983                    .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
984            )
985            .with_state(log_state)
986    }
987
988    fn route_elasticsearch<S>(log_state: LogState) -> Router<S> {
989        Router::new()
990            // Return fake responsefor HEAD '/' request.
991            .route(
992                "/",
993                routing::head((HttpStatusCode::OK, elasticsearch::elasticsearch_headers())),
994            )
995            // Return fake response for Elasticsearch version request.
996            .route("/", routing::get(elasticsearch::handle_get_version))
997            // Return fake response for Elasticsearch license request.
998            .route("/_license", routing::get(elasticsearch::handle_get_license))
999            .route("/_bulk", routing::post(elasticsearch::handle_bulk_api))
1000            .route(
1001                "/{index}/_bulk",
1002                routing::post(elasticsearch::handle_bulk_api_with_index),
1003            )
1004            // Return fake response for Elasticsearch ilm request.
1005            .route(
1006                "/_ilm/policy/{*path}",
1007                routing::any((
1008                    HttpStatusCode::OK,
1009                    elasticsearch::elasticsearch_headers(),
1010                    axum::Json(serde_json::json!({})),
1011                )),
1012            )
1013            // Return fake response for Elasticsearch index template request.
1014            .route(
1015                "/_index_template/{*path}",
1016                routing::any((
1017                    HttpStatusCode::OK,
1018                    elasticsearch::elasticsearch_headers(),
1019                    axum::Json(serde_json::json!({})),
1020                )),
1021            )
1022            // Return fake response for Elasticsearch ingest pipeline request.
1023            // See: https://www.elastic.co/guide/en/elasticsearch/reference/8.8/put-pipeline-api.html.
1024            .route(
1025                "/_ingest/{*path}",
1026                routing::any((
1027                    HttpStatusCode::OK,
1028                    elasticsearch::elasticsearch_headers(),
1029                    axum::Json(serde_json::json!({})),
1030                )),
1031            )
1032            // Return fake response for Elasticsearch nodes discovery request.
1033            // See: https://www.elastic.co/guide/en/elasticsearch/reference/8.8/cluster.html.
1034            .route(
1035                "/_nodes/{*path}",
1036                routing::any((
1037                    HttpStatusCode::OK,
1038                    elasticsearch::elasticsearch_headers(),
1039                    axum::Json(serde_json::json!({})),
1040                )),
1041            )
1042            // Return fake response for Logstash APIs requests.
1043            // See: https://www.elastic.co/guide/en/elasticsearch/reference/8.8/logstash-apis.html
1044            .route(
1045                "/logstash/{*path}",
1046                routing::any((
1047                    HttpStatusCode::OK,
1048                    elasticsearch::elasticsearch_headers(),
1049                    axum::Json(serde_json::json!({})),
1050                )),
1051            )
1052            .route(
1053                "/_logstash/{*path}",
1054                routing::any((
1055                    HttpStatusCode::OK,
1056                    elasticsearch::elasticsearch_headers(),
1057                    axum::Json(serde_json::json!({})),
1058                )),
1059            )
1060            .layer(ServiceBuilder::new().layer(RequestDecompressionLayer::new()))
1061            .with_state(log_state)
1062    }
1063
1064    #[deprecated(since = "0.11.0", note = "Use `route_pipelines()` instead.")]
1065    fn route_log_deprecated<S>(log_state: LogState) -> Router<S> {
1066        Router::new()
1067            .route("/logs", routing::post(event::log_ingester))
1068            .route(
1069                "/pipelines/{pipeline_name}",
1070                routing::get(event::query_pipeline),
1071            )
1072            .route(
1073                "/pipelines/{pipeline_name}",
1074                routing::post(event::add_pipeline),
1075            )
1076            .route(
1077                "/pipelines/{pipeline_name}",
1078                routing::delete(event::delete_pipeline),
1079            )
1080            .route("/pipelines/dryrun", routing::post(event::pipeline_dryrun))
1081            .layer(
1082                ServiceBuilder::new()
1083                    .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1084            )
1085            .with_state(log_state)
1086    }
1087
1088    fn route_pipelines<S>(log_state: LogState) -> Router<S> {
1089        Router::new()
1090            .route("/ingest", routing::post(event::log_ingester))
1091            .route(
1092                "/pipelines/{pipeline_name}",
1093                routing::get(event::query_pipeline),
1094            )
1095            .route(
1096                "/pipelines/{pipeline_name}/ddl",
1097                routing::get(event::query_pipeline_ddl),
1098            )
1099            .route(
1100                "/pipelines/{pipeline_name}",
1101                routing::post(event::add_pipeline),
1102            )
1103            .route(
1104                "/pipelines/{pipeline_name}",
1105                routing::delete(event::delete_pipeline),
1106            )
1107            .route("/pipelines/_dryrun", routing::post(event::pipeline_dryrun))
1108            .layer(
1109                ServiceBuilder::new()
1110                    .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1111            )
1112            .with_state(log_state)
1113    }
1114
1115    fn route_sql<S>(api_state: ApiState) -> Router<S> {
1116        let mut router = Router::new()
1117            .route("/sql", routing::get(handler::sql).post(handler::sql))
1118            .route(
1119                "/sql/parse",
1120                routing::get(handler::sql_parse).post(handler::sql_parse),
1121            )
1122            .route(
1123                "/sql/format",
1124                routing::get(handler::sql_format).post(handler::sql_format),
1125            )
1126            .route(
1127                "/promql",
1128                routing::get(handler::promql).post(handler::promql),
1129            );
1130
1131        if api_state.experimental_enable_explain_analyze_stream {
1132            router = router.route(
1133                "/sql/analyze/stream",
1134                routing::post(handler::sql_analyze_stream),
1135            );
1136        }
1137
1138        router.with_state(api_state)
1139    }
1140
1141    fn route_logs<S>(log_handler: LogQueryHandlerRef) -> Router<S> {
1142        Router::new()
1143            .route("/logs", routing::get(logs::logs).post(logs::logs))
1144            .with_state(log_handler)
1145    }
1146
1147    /// Route Prometheus [HTTP API].
1148    ///
1149    /// [HTTP API]: https://prometheus.io/docs/prometheus/latest/querying/api/
1150    pub fn route_prometheus<S>(prometheus_handler: PrometheusHandlerRef) -> Router<S> {
1151        Router::new()
1152            .route(
1153                "/format_query",
1154                routing::post(format_query).get(format_query),
1155            )
1156            .route("/status/buildinfo", routing::get(build_info_query))
1157            .route("/query", routing::post(instant_query).get(instant_query))
1158            .route("/query_range", routing::post(range_query).get(range_query))
1159            .route("/labels", routing::post(labels_query).get(labels_query))
1160            .route("/series", routing::post(series_query).get(series_query))
1161            .route("/parse_query", routing::post(parse_query).get(parse_query))
1162            .route(
1163                "/label/{label_name}/values",
1164                routing::get(label_values_query),
1165            )
1166            .layer(ServiceBuilder::new().layer(CompressionLayer::new()))
1167            .with_state(prometheus_handler)
1168    }
1169
1170    /// Route Prometheus remote [read] and [write] API. In other places the related modules are
1171    /// called `prom_store`.
1172    ///
1173    /// [read]: https://prometheus.io/docs/prometheus/latest/querying/remote_read_api/
1174    /// [write]: https://prometheus.io/docs/concepts/remote_write_spec/
1175    fn route_prom<S>(state: PromStoreState) -> Router<S> {
1176        Router::new()
1177            .route("/read", routing::post(prom_store::remote_read))
1178            .route("/write", routing::post(prom_store::remote_write))
1179            .with_state(state)
1180    }
1181
1182    fn route_influxdb<S>(influxdb_handler: InfluxdbLineProtocolHandlerRef) -> Router<S> {
1183        Router::new()
1184            .route("/write", routing::post(influxdb_write_v1))
1185            .route("/api/v2/write", routing::post(influxdb_write_v2))
1186            .layer(
1187                ServiceBuilder::new()
1188                    .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1189            )
1190            .route("/ping", routing::get(influxdb_ping))
1191            .route("/health", routing::get(influxdb_health))
1192            .with_state(influxdb_handler)
1193    }
1194
1195    fn route_opentsdb<S>(opentsdb_handler: OpentsdbProtocolHandlerRef) -> Router<S> {
1196        Router::new()
1197            .route("/api/put", routing::post(opentsdb::put))
1198            .with_state(opentsdb_handler)
1199    }
1200
1201    fn route_otlp<S>(
1202        otlp_handler: OpenTelemetryProtocolHandlerRef,
1203        with_metric_engine: bool,
1204    ) -> Router<S> {
1205        Router::new()
1206            .route("/v1/metrics", routing::post(otlp::metrics))
1207            .route("/v1/traces", routing::post(otlp::traces))
1208            .route("/v1/logs", routing::post(otlp::logs))
1209            .layer(
1210                ServiceBuilder::new()
1211                    .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1212            )
1213            .with_state(OtlpState {
1214                with_metric_engine,
1215                handler: otlp_handler,
1216            })
1217    }
1218
1219    fn route_config<S>(state: GreptimeOptionsConfigState) -> Router<S> {
1220        Router::new()
1221            .route("/config", routing::get(handler::config))
1222            .with_state(state)
1223    }
1224
1225    fn route_jaeger<S>(handler: JaegerQueryHandlerRef) -> Router<S> {
1226        Router::new()
1227            .route("/api/services", routing::get(jaeger::handle_get_services))
1228            .route(
1229                "/api/services/{service_name}/operations",
1230                routing::get(jaeger::handle_get_operations_by_service),
1231            )
1232            .route(
1233                "/api/operations",
1234                routing::get(jaeger::handle_get_operations),
1235            )
1236            .route("/api/traces", routing::get(jaeger::handle_find_traces))
1237            .route(
1238                "/api/traces/{trace_id}",
1239                routing::get(jaeger::handle_get_trace),
1240            )
1241            .with_state(handler)
1242    }
1243
1244    #[cfg(feature = "dashboard")]
1245    fn route_dashboard<S>(handler: DashboardHandlerRef) -> Router<S> {
1246        use crate::http::dashboard::{add_dashboard, delete_dashboard, list_dashboards};
1247
1248        Router::new()
1249            .route("/", routing::get(list_dashboards))
1250            .route("/{dashboard_name}", routing::post(add_dashboard))
1251            .route("/{dashboard_name}", routing::delete(delete_dashboard))
1252            .layer(
1253                ServiceBuilder::new()
1254                    .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1255            )
1256            .with_state(DashboardState { handler })
1257    }
1258
1259    #[cfg(not(feature = "dashboard"))]
1260    fn route_dashboard<S>(handler: DashboardHandlerRef) -> Router<S> {
1261        Router::new().with_state(DashboardState { handler })
1262    }
1263}
1264
1265pub const HTTP_SERVER: &str = "HTTP_SERVER";
1266
1267#[async_trait]
1268impl Server for HttpServer {
1269    async fn shutdown(&self) -> Result<()> {
1270        let mut shutdown_tx = self.shutdown_tx.lock().await;
1271        if let Some(tx) = shutdown_tx.take()
1272            && tx.send(()).is_err()
1273        {
1274            info!("Receiver dropped, the HTTP server has already exited");
1275        }
1276        info!("Shutdown HTTP server");
1277
1278        Ok(())
1279    }
1280
1281    async fn start(&mut self, listening: SocketAddr) -> Result<()> {
1282        let (tx, rx) = oneshot::channel();
1283        let serve = {
1284            let mut shutdown_tx = self.shutdown_tx.lock().await;
1285            ensure!(
1286                shutdown_tx.is_none(),
1287                AlreadyStartedSnafu { server: "HTTP" }
1288            );
1289
1290            let app = self.build(self.make_app())?;
1291            let listener = tokio::net::TcpListener::bind(listening)
1292                .await
1293                .context(AddressBindSnafu { addr: listening })?
1294                .tap_io(|tcp_stream| {
1295                    if let Err(e) = tcp_stream.set_nodelay(true) {
1296                        error!(e; "Failed to set TCP_NODELAY on incoming connection");
1297                    }
1298                });
1299            let serve = axum::serve(
1300                listener,
1301                app.into_make_service_with_connect_info::<SocketAddr>(),
1302            );
1303
1304            // FIXME(yingwen): Support keepalive.
1305            // See:
1306            // - https://github.com/tokio-rs/axum/discussions/2939
1307            // - https://stackoverflow.com/questions/73069718/how-do-i-keep-alive-tokiotcpstream-in-rust
1308            // let server = axum::Server::try_bind(&listening)
1309            //     .with_context(|_| AddressBindSnafu { addr: listening })?
1310            //     .tcp_nodelay(true)
1311            //     // Enable TCP keepalive to close the dangling established connections.
1312            //     // It's configured to let the keepalive probes first send after the connection sits
1313            //     // idle for 59 minutes, and then send every 10 seconds for 6 times.
1314            //     // So the connection will be closed after roughly 1 hour.
1315            //     .tcp_keepalive(Some(Duration::from_secs(59 * 60)))
1316            //     .tcp_keepalive_interval(Some(Duration::from_secs(10)))
1317            //     .tcp_keepalive_retries(Some(6))
1318            //     .serve(app.into_make_service());
1319
1320            *shutdown_tx = Some(tx);
1321
1322            serve
1323        };
1324        let listening = serve.local_addr().context(InternalIoSnafu)?;
1325        info!("HTTP server is bound to {}", listening);
1326
1327        common_runtime::spawn_global(async move {
1328            if let Err(e) = serve
1329                .with_graceful_shutdown(rx.map(drop))
1330                .await
1331                .context(InternalIoSnafu)
1332            {
1333                error!(e; "Failed to shutdown http server");
1334            }
1335        });
1336
1337        self.bind_addr = Some(listening);
1338        Ok(())
1339    }
1340
1341    fn name(&self) -> &str {
1342        HTTP_SERVER
1343    }
1344
1345    fn bind_addr(&self) -> Option<SocketAddr> {
1346        self.bind_addr
1347    }
1348
1349    fn as_any(&self) -> &dyn std::any::Any {
1350        self
1351    }
1352}
1353
1354#[cfg(test)]
1355mod test {
1356    use std::future::pending;
1357    use std::io::Cursor;
1358    use std::sync::Arc;
1359
1360    use arrow_ipc::reader::StreamReader;
1361    use arrow_schema::DataType;
1362    use axum::handler::Handler;
1363    use axum::http::StatusCode;
1364    use axum::routing::get;
1365    use common_query::{Output, OutputData};
1366    use common_recordbatch::RecordBatches;
1367    use datafusion_expr::LogicalPlan;
1368    use datatypes::prelude::*;
1369    use datatypes::schema::{ColumnSchema, Schema};
1370    use datatypes::vectors::{StringVector, UInt32Vector};
1371    use header::constants::GREPTIME_DB_HEADER_TIMEOUT;
1372    use query::parser::PromQuery;
1373    use query::query_engine::DescribeResult;
1374    use session::context::QueryContextRef;
1375    use sql::statements::statement::Statement;
1376    use tokio::sync::mpsc;
1377    use tokio::time::Instant;
1378
1379    use super::*;
1380    use crate::http::test_helpers::TestClient;
1381    use crate::prom_remote_write::validation::validate_label_name;
1382    use crate::query_handler::sql::SqlQueryHandler;
1383
1384    struct DummyInstance {
1385        _tx: mpsc::Sender<(String, Vec<u8>)>,
1386    }
1387
1388    #[async_trait]
1389    impl SqlQueryHandler for DummyInstance {
1390        async fn do_query(&self, _: &str, _: QueryContextRef) -> Vec<Result<Output>> {
1391            unimplemented!()
1392        }
1393
1394        async fn do_analyze_stream_query(&self, _: &str, _: QueryContextRef) -> Result<Output> {
1395            let stream = common_recordbatch::RecordBatches::empty().as_stream();
1396            Ok(Output::new(OutputData::Stream(stream), Default::default()))
1397        }
1398
1399        async fn do_promql_query(&self, _: &PromQuery, _: QueryContextRef) -> Vec<Result<Output>> {
1400            unimplemented!()
1401        }
1402
1403        async fn do_exec_plan(
1404            &self,
1405            _plan: LogicalPlan,
1406            _stmt: Option<Statement>,
1407            _query_ctx: QueryContextRef,
1408        ) -> Result<Output> {
1409            unimplemented!()
1410        }
1411
1412        async fn do_describe(
1413            &self,
1414            _stmt: sql::statements::statement::Statement,
1415            _query_ctx: QueryContextRef,
1416        ) -> Result<Option<DescribeResult>> {
1417            unimplemented!()
1418        }
1419
1420        async fn is_valid_schema(&self, _catalog: &str, _schema: &str) -> Result<bool> {
1421            Ok(true)
1422        }
1423    }
1424
1425    fn timeout() -> DynamicTimeoutLayer {
1426        DynamicTimeoutLayer::new(Duration::from_millis(10))
1427    }
1428
1429    async fn forever() {
1430        pending().await
1431    }
1432
1433    fn make_test_app(tx: mpsc::Sender<(String, Vec<u8>)>) -> Router {
1434        make_test_app_custom(tx, HttpOptions::default())
1435    }
1436
1437    fn make_test_app_custom(tx: mpsc::Sender<(String, Vec<u8>)>, options: HttpOptions) -> Router {
1438        let instance = Arc::new(DummyInstance { _tx: tx });
1439        let server = HttpServerBuilder::new(options)
1440            .with_sql_handler(instance.clone())
1441            .build();
1442        server.build(server.make_app()).unwrap().route(
1443            "/test/timeout",
1444            get(forever.layer(ServiceBuilder::new().layer(timeout()))),
1445        )
1446    }
1447
1448    #[tokio::test]
1449    pub async fn test_analyze_stream_route_config_gate() {
1450        let (tx, _rx) = mpsc::channel(100);
1451        let app = make_test_app_custom(tx, HttpOptions::default());
1452        let client = TestClient::new(app).await;
1453        let res = client
1454            .post("/v1/sql/analyze/stream?sql=EXPLAIN%20ANALYZE%20VERBOSE%20SELECT%201")
1455            .send()
1456            .await;
1457        assert_eq!(res.status(), StatusCode::NOT_FOUND);
1458
1459        let (tx, _rx) = mpsc::channel(100);
1460        let options = HttpOptions {
1461            experimental_enable_explain_analyze_stream: true,
1462            ..Default::default()
1463        };
1464        let app = make_test_app_custom(tx, options);
1465        let client = TestClient::new(app).await;
1466        let res = client
1467            .post("/v1/sql/analyze/stream?sql=EXPLAIN%20ANALYZE%20VERBOSE%20SELECT%201")
1468            .send()
1469            .await;
1470        assert_ne!(res.status(), StatusCode::NOT_FOUND);
1471    }
1472
1473    #[tokio::test]
1474    pub async fn test_cors() {
1475        // cors is on by default
1476        let (tx, _rx) = mpsc::channel(100);
1477        let app = make_test_app(tx);
1478        let client = TestClient::new(app).await;
1479
1480        let res = client.get("/health").send().await;
1481
1482        assert_eq!(res.status(), StatusCode::OK);
1483        assert_eq!(
1484            res.headers()
1485                .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
1486                .expect("expect cors header origin"),
1487            "*"
1488        );
1489
1490        let res = client.get("/v1/health").send().await;
1491
1492        assert_eq!(res.status(), StatusCode::OK);
1493        assert_eq!(
1494            res.headers()
1495                .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
1496                .expect("expect cors header origin"),
1497            "*"
1498        );
1499
1500        let res = client
1501            .options("/health")
1502            .header("Access-Control-Request-Headers", "x-greptime-auth")
1503            .header("Access-Control-Request-Method", "DELETE")
1504            .header("Origin", "https://example.com")
1505            .send()
1506            .await;
1507        assert_eq!(res.status(), StatusCode::OK);
1508        assert_eq!(
1509            res.headers()
1510                .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
1511                .expect("expect cors header origin"),
1512            "*"
1513        );
1514        assert_eq!(
1515            res.headers()
1516                .get(http::header::ACCESS_CONTROL_ALLOW_HEADERS)
1517                .expect("expect cors header headers"),
1518            "*"
1519        );
1520        assert_eq!(
1521            res.headers()
1522                .get(http::header::ACCESS_CONTROL_ALLOW_METHODS)
1523                .expect("expect cors header methods"),
1524            "GET,POST,PUT,DELETE,HEAD"
1525        );
1526    }
1527
1528    #[tokio::test]
1529    pub async fn test_cors_custom_origins() {
1530        // cors is on by default
1531        let (tx, _rx) = mpsc::channel(100);
1532        let origin = "https://example.com";
1533
1534        let options = HttpOptions {
1535            cors_allowed_origins: vec![origin.to_string()],
1536            ..Default::default()
1537        };
1538
1539        let app = make_test_app_custom(tx, options);
1540        let client = TestClient::new(app).await;
1541
1542        let res = client.get("/health").header("Origin", origin).send().await;
1543
1544        assert_eq!(res.status(), StatusCode::OK);
1545        assert_eq!(
1546            res.headers()
1547                .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
1548                .expect("expect cors header origin"),
1549            origin
1550        );
1551
1552        let res = client
1553            .get("/health")
1554            .header("Origin", "https://notallowed.com")
1555            .send()
1556            .await;
1557
1558        assert_eq!(res.status(), StatusCode::OK);
1559        assert!(
1560            !res.headers()
1561                .contains_key(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
1562        );
1563    }
1564
1565    #[tokio::test]
1566    pub async fn test_cors_disabled() {
1567        // cors is on by default
1568        let (tx, _rx) = mpsc::channel(100);
1569
1570        let options = HttpOptions {
1571            enable_cors: false,
1572            ..Default::default()
1573        };
1574
1575        let app = make_test_app_custom(tx, options);
1576        let client = TestClient::new(app).await;
1577
1578        let res = client.get("/health").send().await;
1579
1580        assert_eq!(res.status(), StatusCode::OK);
1581        assert!(
1582            !res.headers()
1583                .contains_key(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
1584        );
1585    }
1586
1587    #[test]
1588    fn test_http_options_default() {
1589        let default = HttpOptions::default();
1590        assert_eq!("127.0.0.1:4000".to_string(), default.addr);
1591        assert_eq!(Duration::from_secs(0), default.timeout)
1592    }
1593
1594    #[tokio::test]
1595    async fn test_http_server_request_timeout() {
1596        common_telemetry::init_default_ut_logging();
1597
1598        let (tx, _rx) = mpsc::channel(100);
1599        let app = make_test_app(tx);
1600        let client = TestClient::new(app).await;
1601        let res = client.get("/test/timeout").send().await;
1602        assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
1603
1604        let now = Instant::now();
1605        let res = client
1606            .get("/test/timeout")
1607            .header(GREPTIME_DB_HEADER_TIMEOUT, "20ms")
1608            .send()
1609            .await;
1610        assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
1611        let elapsed = now.elapsed();
1612        assert!(elapsed > Duration::from_millis(15));
1613
1614        tokio::time::timeout(
1615            Duration::from_millis(15),
1616            client
1617                .get("/test/timeout")
1618                .header(GREPTIME_DB_HEADER_TIMEOUT, "0s")
1619                .send(),
1620        )
1621        .await
1622        .unwrap_err();
1623
1624        tokio::time::timeout(
1625            Duration::from_millis(15),
1626            client
1627                .get("/test/timeout")
1628                .header(
1629                    GREPTIME_DB_HEADER_TIMEOUT,
1630                    humantime::format_duration(Duration::default()).to_string(),
1631                )
1632                .send(),
1633        )
1634        .await
1635        .unwrap_err();
1636    }
1637
1638    #[tokio::test]
1639    async fn test_schema_for_empty_response() {
1640        let column_schemas = vec![
1641            ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
1642            ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
1643        ];
1644        let schema = Arc::new(Schema::new(column_schemas));
1645
1646        let recordbatches = RecordBatches::try_new(schema.clone(), vec![]).unwrap();
1647        let outputs = vec![Ok(Output::new_with_record_batches(recordbatches))];
1648
1649        let json_resp = GreptimedbV1Response::from_output(outputs).await;
1650        if let HttpResponse::GreptimedbV1(json_resp) = json_resp {
1651            let json_output = &json_resp.output[0];
1652            if let GreptimeQueryOutput::Records(r) = json_output {
1653                assert_eq!(r.num_rows(), 0);
1654                assert_eq!(r.num_cols(), 2);
1655                assert_eq!(r.schema.column_schemas[0].name, "numbers");
1656                assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
1657            } else {
1658                panic!("invalid output type");
1659            }
1660        } else {
1661            panic!("invalid format")
1662        }
1663    }
1664
1665    #[tokio::test]
1666    async fn test_recordbatches_conversion() {
1667        let column_schemas = vec![
1668            ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
1669            ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
1670        ];
1671        let schema = Arc::new(Schema::new(column_schemas));
1672        let columns: Vec<VectorRef> = vec![
1673            Arc::new(UInt32Vector::from_slice(vec![1, 2, 3, 4])),
1674            Arc::new(StringVector::from(vec![
1675                None,
1676                Some("hello"),
1677                Some("greptime"),
1678                None,
1679            ])),
1680        ];
1681        let recordbatch = RecordBatch::new(schema.clone(), columns).unwrap();
1682
1683        for format in [
1684            ResponseFormat::GreptimedbV1,
1685            ResponseFormat::InfluxdbV1,
1686            ResponseFormat::Csv(true, true),
1687            ResponseFormat::Table,
1688            ResponseFormat::Arrow,
1689            ResponseFormat::Json,
1690            ResponseFormat::Null,
1691        ] {
1692            let recordbatches =
1693                RecordBatches::try_new(schema.clone(), vec![recordbatch.clone()]).unwrap();
1694            let outputs = vec![Ok(Output::new_with_record_batches(recordbatches))];
1695            let json_resp = match format {
1696                ResponseFormat::Arrow => ArrowResponse::from_output(outputs, None).await,
1697                ResponseFormat::Csv(with_names, with_types) => {
1698                    CsvResponse::from_output(outputs, with_names, with_types).await
1699                }
1700                ResponseFormat::Table => TableResponse::from_output(outputs).await,
1701                ResponseFormat::GreptimedbV1 => GreptimedbV1Response::from_output(outputs).await,
1702                ResponseFormat::InfluxdbV1 => InfluxdbV1Response::from_output(outputs, None).await,
1703                ResponseFormat::Json => JsonResponse::from_output(outputs).await,
1704                ResponseFormat::Null => NullResponse::from_output(outputs).await,
1705            };
1706
1707            match json_resp {
1708                HttpResponse::GreptimedbV1(resp) => {
1709                    let json_output = &resp.output[0];
1710                    if let GreptimeQueryOutput::Records(r) = json_output {
1711                        assert_eq!(r.num_rows(), 4);
1712                        assert_eq!(r.num_cols(), 2);
1713                        assert_eq!(r.schema.column_schemas[0].name, "numbers");
1714                        assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
1715                        assert_eq!(r.rows[0][0], serde_json::Value::from(1));
1716                        assert_eq!(r.rows[0][1], serde_json::Value::Null);
1717                    } else {
1718                        panic!("invalid output type");
1719                    }
1720                }
1721                HttpResponse::InfluxdbV1(resp) => {
1722                    let json_output = &resp.results()[0];
1723                    assert_eq!(json_output.num_rows(), 4);
1724                    assert_eq!(json_output.num_cols(), 2);
1725                    assert_eq!(json_output.series[0].columns.clone()[0], "numbers");
1726                    assert_eq!(
1727                        json_output.series[0].values[0][0],
1728                        serde_json::Value::from(1)
1729                    );
1730                    assert_eq!(json_output.series[0].values[0][1], serde_json::Value::Null);
1731                }
1732                HttpResponse::Csv(resp) => {
1733                    let output = &resp.output()[0];
1734                    if let GreptimeQueryOutput::Records(r) = output {
1735                        assert_eq!(r.num_rows(), 4);
1736                        assert_eq!(r.num_cols(), 2);
1737                        assert_eq!(r.schema.column_schemas[0].name, "numbers");
1738                        assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
1739                        assert_eq!(r.rows[0][0], serde_json::Value::from(1));
1740                        assert_eq!(r.rows[0][1], serde_json::Value::Null);
1741                    } else {
1742                        panic!("invalid output type");
1743                    }
1744                }
1745
1746                HttpResponse::Table(resp) => {
1747                    let output = &resp.output()[0];
1748                    if let GreptimeQueryOutput::Records(r) = output {
1749                        assert_eq!(r.num_rows(), 4);
1750                        assert_eq!(r.num_cols(), 2);
1751                        assert_eq!(r.schema.column_schemas[0].name, "numbers");
1752                        assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
1753                        assert_eq!(r.rows[0][0], serde_json::Value::from(1));
1754                        assert_eq!(r.rows[0][1], serde_json::Value::Null);
1755                    } else {
1756                        panic!("invalid output type");
1757                    }
1758                }
1759
1760                HttpResponse::Arrow(resp) => {
1761                    let output = resp.data;
1762                    let mut reader = StreamReader::try_new(Cursor::new(output), None)
1763                        .expect("Arrow reader error");
1764                    let schema = reader.schema();
1765                    assert_eq!(schema.fields[0].name(), "numbers");
1766                    assert_eq!(schema.fields[0].data_type(), &DataType::UInt32);
1767                    assert_eq!(schema.fields[1].name(), "strings");
1768                    assert_eq!(schema.fields[1].data_type(), &DataType::Utf8);
1769
1770                    let rb = reader.next().unwrap().expect("read record batch failed");
1771                    assert_eq!(rb.num_columns(), 2);
1772                    assert_eq!(rb.num_rows(), 4);
1773                }
1774
1775                HttpResponse::Json(resp) => {
1776                    let output = &resp.output()[0];
1777                    if let GreptimeQueryOutput::Records(r) = output {
1778                        assert_eq!(r.num_rows(), 4);
1779                        assert_eq!(r.num_cols(), 2);
1780                        assert_eq!(r.schema.column_schemas[0].name, "numbers");
1781                        assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
1782                        assert_eq!(r.rows[0][0], serde_json::Value::from(1));
1783                        assert_eq!(r.rows[0][1], serde_json::Value::Null);
1784                    } else {
1785                        panic!("invalid output type");
1786                    }
1787                }
1788
1789                HttpResponse::Null(resp) => {
1790                    assert_eq!(resp.rows(), 4);
1791                }
1792
1793                HttpResponse::Error(err) => unreachable!("{err:?}"),
1794            }
1795        }
1796    }
1797
1798    #[test]
1799    fn test_response_format_misc() {
1800        assert_eq!(ResponseFormat::default(), ResponseFormat::GreptimedbV1);
1801        assert_eq!(ResponseFormat::parse("arrow"), Some(ResponseFormat::Arrow));
1802        assert_eq!(
1803            ResponseFormat::parse("csv"),
1804            Some(ResponseFormat::Csv(false, false))
1805        );
1806        assert_eq!(
1807            ResponseFormat::parse("csvwithnames"),
1808            Some(ResponseFormat::Csv(true, false))
1809        );
1810        assert_eq!(
1811            ResponseFormat::parse("csvwithnamesandtypes"),
1812            Some(ResponseFormat::Csv(true, true))
1813        );
1814        assert_eq!(ResponseFormat::parse("table"), Some(ResponseFormat::Table));
1815        assert_eq!(
1816            ResponseFormat::parse("greptimedb_v1"),
1817            Some(ResponseFormat::GreptimedbV1)
1818        );
1819        assert_eq!(
1820            ResponseFormat::parse("influxdb_v1"),
1821            Some(ResponseFormat::InfluxdbV1)
1822        );
1823        assert_eq!(ResponseFormat::parse("json"), Some(ResponseFormat::Json));
1824        assert_eq!(ResponseFormat::parse("null"), Some(ResponseFormat::Null));
1825
1826        // invalid formats
1827        assert_eq!(ResponseFormat::parse("invalid"), None);
1828        assert_eq!(ResponseFormat::parse(""), None);
1829        assert_eq!(ResponseFormat::parse("CSV"), None); // Case sensitive
1830
1831        // as str
1832        assert_eq!(ResponseFormat::Arrow.as_str(), "arrow");
1833        assert_eq!(ResponseFormat::Csv(false, false).as_str(), "csv");
1834        assert_eq!(ResponseFormat::Csv(true, true).as_str(), "csv");
1835        assert_eq!(ResponseFormat::Table.as_str(), "table");
1836        assert_eq!(ResponseFormat::GreptimedbV1.as_str(), "greptimedb_v1");
1837        assert_eq!(ResponseFormat::InfluxdbV1.as_str(), "influxdb_v1");
1838        assert_eq!(ResponseFormat::Json.as_str(), "json");
1839        assert_eq!(ResponseFormat::Null.as_str(), "null");
1840        assert_eq!(ResponseFormat::default().as_str(), "greptimedb_v1");
1841    }
1842
1843    #[test]
1844    fn test_decode_label_name_strict() {
1845        let strict = PromValidationMode::Strict;
1846
1847        // Valid Prometheus label names
1848        assert!(strict.decode_label_name(b"__name__").is_ok());
1849        assert!(strict.decode_label_name(b"job").is_ok());
1850        assert!(strict.decode_label_name(b"instance").is_ok());
1851        assert!(strict.decode_label_name(b"_private").is_ok());
1852        assert!(strict.decode_label_name(b"label_with_underscores").is_ok());
1853        assert!(strict.decode_label_name(b"abc123").is_ok());
1854        assert!(strict.decode_label_name(b"A").is_ok());
1855        assert!(strict.decode_label_name(b"_").is_ok());
1856
1857        // Invalid: starts with digit
1858        assert!(strict.decode_label_name(b"0abc").is_err());
1859        assert!(strict.decode_label_name(b"123").is_err());
1860
1861        // Invalid: contains special characters
1862        assert!(strict.decode_label_name(b"label-name").is_err());
1863        assert!(strict.decode_label_name(b"label.name").is_err());
1864        assert!(strict.decode_label_name(b"label name").is_err());
1865        assert!(strict.decode_label_name(b"label/name").is_err());
1866
1867        // Invalid: empty
1868        assert!(strict.decode_label_name(b"").is_err());
1869
1870        // Invalid: non-ASCII UTF-8
1871        assert!(strict.decode_label_name("ラベル".as_bytes()).is_err());
1872
1873        // Invalid UTF-8 bytes should fail
1874        assert!(strict.decode_label_name(&[0xff, 0xfe]).is_err());
1875    }
1876
1877    #[test]
1878    fn test_decode_label_name_lossy() {
1879        let lossy = PromValidationMode::Lossy;
1880
1881        // Label name validation is always enforced.
1882        assert!(lossy.decode_label_name(b"__name__").is_ok());
1883        assert!(lossy.decode_label_name(b"label-name").is_err());
1884        assert!(lossy.decode_label_name(b"0abc").is_err());
1885
1886        // Invalid UTF-8 bytes fail the label-name byte check.
1887        assert!(lossy.decode_label_name(&[0xff, 0xfe]).is_err());
1888    }
1889
1890    #[test]
1891    fn test_decode_label_name_unchecked() {
1892        let unchecked = PromValidationMode::Unchecked;
1893
1894        // Label name validation is always enforced.
1895        assert!(unchecked.decode_label_name(b"__name__").is_ok());
1896        assert!(unchecked.decode_label_name(b"label-name").is_err());
1897        assert!(unchecked.decode_label_name(b"0abc").is_err());
1898    }
1899
1900    #[test]
1901    fn test_is_valid_prom_label_name_bytes() {
1902        assert!(validate_label_name(b"__name__"));
1903        assert!(validate_label_name(b"job"));
1904        assert!(validate_label_name(b"_"));
1905        assert!(validate_label_name(b"A"));
1906        assert!(validate_label_name(b"abc123"));
1907        assert!(validate_label_name(b"_leading_underscore"));
1908
1909        assert!(!validate_label_name(b""));
1910        assert!(!validate_label_name(b"0starts_with_digit"));
1911        assert!(!validate_label_name(b"has-dash"));
1912        assert!(!validate_label_name(b"has.dot"));
1913        assert!(!validate_label_name(b"has space"));
1914        assert!(!validate_label_name(&[0xff, 0xfe]));
1915    }
1916}