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