1use 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, State};
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::{Extension, 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 session::context::QueryContext;
44use snafu::{ResultExt, ensure};
45use tokio::sync::Mutex;
46use tokio::sync::oneshot::{self, Sender};
47use tonic::codegen::Service;
48use tower::{Layer, ServiceBuilder};
49use tower_http::compression::CompressionLayer;
50use tower_http::cors::{AllowOrigin, Any, CorsLayer};
51use tower_http::decompression::RequestDecompressionLayer;
52use tower_http::trace::TraceLayer;
53
54use self::authorize::AuthState;
55use self::result::table_result::TableResponse;
56use crate::batcher::BatchingProtocol;
57use crate::batcher::logical_table::LogicalTablePendingRowsBatcher;
58use crate::elasticsearch;
59use crate::error::{
60 AddressBindSnafu, AlreadyStartedSnafu, Error, InternalIoSnafu, InvalidHeaderValueSnafu, Result,
61};
62use crate::http::influxdb::{influxdb_health, influxdb_ping, influxdb_write_v1, influxdb_write_v2};
63use crate::http::otlp::OtlpState;
64use crate::http::prom_store::PromStoreState;
65use crate::http::prometheus::{
66 build_info_query, format_query, instant_query, label_values_query, labels_query,
67 metadata_query, parse_query, range_query, series_query,
68};
69use crate::http::result::arrow_result::ArrowResponse;
70use crate::http::result::csv_result::CsvResponse;
71use crate::http::result::error_result::ErrorResponse;
72use crate::http::result::greptime_result_v1::GreptimedbV1Response;
73use crate::http::result::influxdb_result_v1::InfluxdbV1Response;
74use crate::http::result::json_result::JsonResponse;
75use crate::http::result::null_result::NullResponse;
76use crate::interceptor::LogIngestInterceptorRef;
77use crate::metrics::http_metrics_layer;
78use crate::metrics_handler::MetricsHandler;
79use crate::prometheus_handler::PrometheusHandlerRef;
80use crate::query_handler::sql::ServerSqlQueryHandlerRef;
81use crate::query_handler::{
82 DashboardHandlerRef, InfluxdbLineProtocolHandlerRef, JaegerQueryHandlerRef, LogQueryHandlerRef,
83 OpenTelemetryProtocolHandlerRef, OpentsdbProtocolHandlerRef, PipelineHandlerRef,
84 PromStoreProtocolHandlerRef,
85};
86use crate::request_memory_limiter::ServerMemoryLimiter;
87use crate::server::Server;
88
89pub mod authorize;
90#[cfg(feature = "dashboard")]
91mod dashboard;
92pub mod dyn_log;
93pub mod dyn_trace;
94pub mod event;
95pub mod extractor;
96pub mod handler;
97pub mod header;
98pub mod influxdb;
99pub mod jaeger;
100pub mod logs;
101pub mod loki;
102pub mod mem_prof;
103mod memory_limit;
104pub mod opentsdb;
105pub mod otlp;
106pub mod pprof;
107pub mod prom_store;
108pub mod prometheus;
109pub mod result;
110pub mod splunk;
111mod timeout;
112pub mod utils;
113mod workload_scheduler;
114
115use result::HttpOutputWriter;
116pub(crate) use timeout::DynamicTimeoutLayer;
117
118mod client_ip;
119use crate::prom_remote_write::validation::PromValidationMode;
120mod hints;
121mod read_preference;
122mod skip_wal;
123#[cfg(any(test, feature = "testing"))]
124pub mod test_helpers;
125
126pub const HTTP_API_VERSION: &str = "v1";
127pub const HTTP_API_PREFIX: &str = "/v1/";
128pub const HTTP_API_PREFIX_WITHOUT_TRAILING_SLASH: &str = "/v1";
129
130pub trait ExtraHttpRouterProvider: Send + Sync {
132 fn router(&self) -> Router;
134}
135
136pub type ExtraHttpRouterProviderRef = Arc<dyn ExtraHttpRouterProvider>;
137
138#[derive(Clone, Default)]
140pub struct ExtraHttpRouterProviders {
141 providers: Vec<ExtraHttpRouterProviderRef>,
142}
143
144impl ExtraHttpRouterProviders {
145 pub fn new() -> Self {
147 Self::default()
148 }
149
150 pub fn add(&mut self, provider: ExtraHttpRouterProviderRef) {
152 self.providers.push(provider);
153 }
154
155 pub fn iter(&self) -> impl Iterator<Item = &dyn ExtraHttpRouterProvider> {
157 self.providers.iter().map(|x| x.as_ref())
158 }
159}
160
161const DEFAULT_BODY_LIMIT: ReadableSize = ReadableSize::mb(64);
163const DEFAULT_HTTP_API_ADDR_PORT: u16 = 4006;
165
166pub const AUTHORIZATION_HEADER: &str = "x-greptime-auth";
168
169pub static PUBLIC_API_PREFIX: [&str; 4] = [
172 "/v1/influxdb/ping",
173 "/v1/influxdb/health",
174 "/v1/health",
175 "/v1/splunk/services/collector/health",
176];
177
178#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
184pub(crate) enum HttpServerKind {
185 #[default]
188 Full,
189 Api,
191}
192
193#[derive(Default)]
194pub struct HttpServer {
195 router: StdMutex<Router>,
196 shutdown_tx: Mutex<Option<Sender<()>>>,
197 user_provider: Option<UserProviderRef>,
198 memory_limiter: ServerMemoryLimiter,
199
200 options: HttpOptions,
202 batching_protocols: Vec<BatchingProtocol>,
203 logical_batching_protocols: Vec<BatchingProtocol>,
204 bind_addr: Option<SocketAddr>,
205 kind: HttpServerKind,
207}
208
209pub(crate) fn is_namespace(path: &str, root: &str) -> bool {
213 path == root
214 || path
215 .strip_prefix(root)
216 .is_some_and(|suffix| suffix.starts_with('/'))
217}
218
219pub fn is_api_listener_path(path: &str) -> bool {
221 is_namespace(path, HTTP_API_PREFIX_WITHOUT_TRAILING_SLASH) || is_namespace(path, "/dashboard")
222}
223
224#[derive(Clone)]
225struct LogicalBatchingProtocols(Vec<BatchingProtocol>);
226
227async fn set_http_write_batching(
229 State(protocol): State<BatchingProtocol>,
230 mut req: Request,
231 next: Next,
232) -> Response {
233 let enabled = req
234 .extensions()
235 .get::<Arc<Vec<BatchingProtocol>>>()
236 .is_some_and(|protocols| protocols.contains(&protocol));
237 let logical_enabled = req
238 .extensions()
239 .get::<LogicalBatchingProtocols>()
240 .is_some_and(|protocols| protocols.0.contains(&protocol));
241 if let Some(ctx) = req.extensions_mut().get_mut::<QueryContext>() {
242 ctx.set_batching_enabled(enabled);
243 ctx.set_logical_batching_enabled(logical_enabled);
244 }
245 next.run(req).await
246}
247
248async fn enforce_api_surface(req: Request, next: Next) -> Response {
252 if !is_api_listener_path(req.uri().path()) {
253 return HttpStatusCode::NOT_FOUND.into_response();
254 }
255 next.run(req).await
256}
257
258impl HttpServer {
259 fn kind(&self) -> &'static str {
261 match self.kind {
262 HttpServerKind::Api => "HTTP API",
263 HttpServerKind::Full => "HTTP",
264 }
265 }
266}
267
268#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(default)]
270pub struct HttpOptions {
271 pub addr: String,
272
273 #[serde(with = "humantime_serde")]
276 pub timeout: Duration,
277
278 #[serde(skip)]
279 pub disable_dashboard: bool,
280
281 pub body_limit: ReadableSize,
282
283 pub cors_allowed_origins: Vec<String>,
284
285 pub enable_cors: bool,
286
287 pub enable_api_server: bool,
292 pub api_server_addr: String,
295}
296
297impl Default for HttpOptions {
298 fn default() -> Self {
299 Self {
300 addr: "127.0.0.1:4000".to_string(),
301 timeout: Duration::from_secs(0),
302 disable_dashboard: false,
303 body_limit: DEFAULT_BODY_LIMIT,
304 cors_allowed_origins: Vec::new(),
305 enable_cors: true,
306 enable_api_server: false,
307 api_server_addr: format!("127.0.0.1:{}", DEFAULT_HTTP_API_ADDR_PORT),
308 }
309 }
310}
311
312#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
313pub struct ColumnSchema {
314 name: String,
315 data_type: String,
316}
317
318impl ColumnSchema {
319 pub fn new(name: String, data_type: String) -> ColumnSchema {
320 ColumnSchema { name, data_type }
321 }
322}
323
324#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
325pub struct OutputSchema {
326 column_schemas: Vec<ColumnSchema>,
327}
328
329impl OutputSchema {
330 pub fn new(columns: Vec<ColumnSchema>) -> OutputSchema {
331 OutputSchema {
332 column_schemas: columns,
333 }
334 }
335}
336
337impl From<SchemaRef> for OutputSchema {
338 fn from(schema: SchemaRef) -> OutputSchema {
339 OutputSchema {
340 column_schemas: schema
341 .column_schemas()
342 .iter()
343 .map(|cs| ColumnSchema {
344 name: cs.name.clone(),
345 data_type: cs.data_type.name(),
346 })
347 .collect(),
348 }
349 }
350}
351
352#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
353pub struct HttpRecordsOutput {
354 schema: OutputSchema,
355 rows: Vec<Vec<Value>>,
356 #[serde(default)]
359 total_rows: usize,
360
361 #[serde(skip_serializing_if = "HashMap::is_empty")]
363 #[serde(default)]
364 metrics: HashMap<String, Value>,
365}
366
367impl HttpRecordsOutput {
368 pub fn num_rows(&self) -> usize {
369 self.rows.len()
370 }
371
372 pub fn num_cols(&self) -> usize {
373 self.schema.column_schemas.len()
374 }
375
376 pub fn schema(&self) -> &OutputSchema {
377 &self.schema
378 }
379
380 pub fn rows(&self) -> &Vec<Vec<Value>> {
381 &self.rows
382 }
383}
384
385impl HttpRecordsOutput {
386 pub fn try_new(
387 schema: SchemaRef,
388 recordbatches: Vec<RecordBatch>,
389 ) -> std::result::Result<HttpRecordsOutput, Error> {
390 if recordbatches.is_empty() {
391 Ok(HttpRecordsOutput {
392 schema: OutputSchema::from(schema),
393 rows: vec![],
394 total_rows: 0,
395 metrics: Default::default(),
396 })
397 } else {
398 let num_rows = recordbatches.iter().map(|r| r.num_rows()).sum::<usize>();
399 let mut rows = Vec::with_capacity(num_rows);
400
401 for recordbatch in recordbatches {
402 let mut writer = HttpOutputWriter::new(schema.num_columns(), None);
403 writer.write(recordbatch, &mut rows)?;
404 }
405
406 Ok(HttpRecordsOutput {
407 schema: OutputSchema::from(schema),
408 total_rows: rows.len(),
409 rows,
410 metrics: Default::default(),
411 })
412 }
413 }
414}
415
416#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
417#[serde(rename_all = "lowercase")]
418pub enum GreptimeQueryOutput {
419 AffectedRows(usize),
420 Records(HttpRecordsOutput),
421}
422
423#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
425pub enum ResponseFormat {
426 Arrow,
427 Csv(bool, bool),
429 Table,
430 #[default]
431 GreptimedbV1,
432 InfluxdbV1,
433 Json,
434 Null,
435}
436
437impl ResponseFormat {
438 pub fn parse(s: &str) -> Option<Self> {
439 match s {
440 "arrow" => Some(ResponseFormat::Arrow),
441 "csv" => Some(ResponseFormat::Csv(false, false)),
442 "csvwithnames" => Some(ResponseFormat::Csv(true, false)),
443 "csvwithnamesandtypes" => Some(ResponseFormat::Csv(true, true)),
444 "table" => Some(ResponseFormat::Table),
445 "greptimedb_v1" => Some(ResponseFormat::GreptimedbV1),
446 "influxdb_v1" => Some(ResponseFormat::InfluxdbV1),
447 "json" => Some(ResponseFormat::Json),
448 "null" => Some(ResponseFormat::Null),
449 _ => None,
450 }
451 }
452
453 pub fn as_str(&self) -> &'static str {
454 match self {
455 ResponseFormat::Arrow => "arrow",
456 ResponseFormat::Csv(_, _) => "csv",
457 ResponseFormat::Table => "table",
458 ResponseFormat::GreptimedbV1 => "greptimedb_v1",
459 ResponseFormat::InfluxdbV1 => "influxdb_v1",
460 ResponseFormat::Json => "json",
461 ResponseFormat::Null => "null",
462 }
463 }
464}
465
466#[derive(Debug, Clone, Copy, PartialEq, Eq)]
467pub enum Epoch {
468 Nanosecond,
469 Microsecond,
470 Millisecond,
471 Second,
472}
473
474impl Epoch {
475 pub fn parse(s: &str) -> Option<Epoch> {
476 match s {
481 "ns" => Some(Epoch::Nanosecond),
482 "u" | "µ" => Some(Epoch::Microsecond),
483 "ms" => Some(Epoch::Millisecond),
484 "s" => Some(Epoch::Second),
485 _ => None, }
487 }
488
489 pub fn convert_timestamp(&self, ts: Timestamp) -> Option<Timestamp> {
490 match self {
491 Epoch::Nanosecond => ts.convert_to(TimeUnit::Nanosecond),
492 Epoch::Microsecond => ts.convert_to(TimeUnit::Microsecond),
493 Epoch::Millisecond => ts.convert_to(TimeUnit::Millisecond),
494 Epoch::Second => ts.convert_to(TimeUnit::Second),
495 }
496 }
497}
498
499impl Display for Epoch {
500 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
501 match self {
502 Epoch::Nanosecond => write!(f, "Epoch::Nanosecond"),
503 Epoch::Microsecond => write!(f, "Epoch::Microsecond"),
504 Epoch::Millisecond => write!(f, "Epoch::Millisecond"),
505 Epoch::Second => write!(f, "Epoch::Second"),
506 }
507 }
508}
509
510#[derive(Serialize, Deserialize, Debug)]
511pub enum HttpResponse {
512 Arrow(ArrowResponse),
513 Csv(CsvResponse),
514 Table(TableResponse),
515 Error(ErrorResponse),
516 GreptimedbV1(GreptimedbV1Response),
517 InfluxdbV1(InfluxdbV1Response),
518 Json(JsonResponse),
519 Null(NullResponse),
520}
521
522impl HttpResponse {
523 pub fn with_execution_time(self, execution_time: u64) -> Self {
524 match self {
525 HttpResponse::Arrow(resp) => resp.with_execution_time(execution_time).into(),
526 HttpResponse::Csv(resp) => resp.with_execution_time(execution_time).into(),
527 HttpResponse::Table(resp) => resp.with_execution_time(execution_time).into(),
528 HttpResponse::GreptimedbV1(resp) => resp.with_execution_time(execution_time).into(),
529 HttpResponse::InfluxdbV1(resp) => resp.with_execution_time(execution_time).into(),
530 HttpResponse::Json(resp) => resp.with_execution_time(execution_time).into(),
531 HttpResponse::Null(resp) => resp.with_execution_time(execution_time).into(),
532 HttpResponse::Error(resp) => resp.with_execution_time(execution_time).into(),
533 }
534 }
535
536 pub fn with_limit(self, limit: usize) -> Self {
537 match self {
538 HttpResponse::Csv(resp) => resp.with_limit(limit).into(),
539 HttpResponse::Table(resp) => resp.with_limit(limit).into(),
540 HttpResponse::GreptimedbV1(resp) => resp.with_limit(limit).into(),
541 HttpResponse::Json(resp) => resp.with_limit(limit).into(),
542 _ => self,
543 }
544 }
545}
546
547pub fn process_with_limit(
548 mut outputs: Vec<GreptimeQueryOutput>,
549 limit: usize,
550) -> Vec<GreptimeQueryOutput> {
551 outputs
552 .drain(..)
553 .map(|data| match data {
554 GreptimeQueryOutput::Records(mut records) => {
555 if records.rows.len() > limit {
556 records.rows.truncate(limit);
557 records.total_rows = limit;
558 }
559 GreptimeQueryOutput::Records(records)
560 }
561 _ => data,
562 })
563 .collect()
564}
565
566impl IntoResponse for HttpResponse {
567 fn into_response(self) -> Response {
568 match self {
569 HttpResponse::Arrow(resp) => resp.into_response(),
570 HttpResponse::Csv(resp) => resp.into_response(),
571 HttpResponse::Table(resp) => resp.into_response(),
572 HttpResponse::GreptimedbV1(resp) => resp.into_response(),
573 HttpResponse::InfluxdbV1(resp) => resp.into_response(),
574 HttpResponse::Json(resp) => resp.into_response(),
575 HttpResponse::Null(resp) => resp.into_response(),
576 HttpResponse::Error(resp) => resp.into_response(),
577 }
578 }
579}
580
581impl From<ArrowResponse> for HttpResponse {
582 fn from(value: ArrowResponse) -> Self {
583 HttpResponse::Arrow(value)
584 }
585}
586
587impl From<CsvResponse> for HttpResponse {
588 fn from(value: CsvResponse) -> Self {
589 HttpResponse::Csv(value)
590 }
591}
592
593impl From<TableResponse> for HttpResponse {
594 fn from(value: TableResponse) -> Self {
595 HttpResponse::Table(value)
596 }
597}
598
599impl From<ErrorResponse> for HttpResponse {
600 fn from(value: ErrorResponse) -> Self {
601 HttpResponse::Error(value)
602 }
603}
604
605impl From<GreptimedbV1Response> for HttpResponse {
606 fn from(value: GreptimedbV1Response) -> Self {
607 HttpResponse::GreptimedbV1(value)
608 }
609}
610
611impl From<InfluxdbV1Response> for HttpResponse {
612 fn from(value: InfluxdbV1Response) -> Self {
613 HttpResponse::InfluxdbV1(value)
614 }
615}
616
617impl From<JsonResponse> for HttpResponse {
618 fn from(value: JsonResponse) -> Self {
619 HttpResponse::Json(value)
620 }
621}
622
623impl From<NullResponse> for HttpResponse {
624 fn from(value: NullResponse) -> Self {
625 HttpResponse::Null(value)
626 }
627}
628
629#[derive(Clone)]
630pub struct ApiState {
631 pub sql_handler: ServerSqlQueryHandlerRef,
632}
633
634#[derive(Clone)]
635pub struct GreptimeOptionsConfigState {
636 pub greptime_config_options: String,
637}
638
639#[derive(Clone)]
640pub struct DashboardState {
641 pub handler: DashboardHandlerRef,
642}
643
644pub struct HttpServerBuilder {
645 options: HttpOptions,
646 batching_protocols: Vec<BatchingProtocol>,
647 logical_batching_protocols: Vec<BatchingProtocol>,
648 user_provider: Option<UserProviderRef>,
649 router: Router,
650 memory_limiter: ServerMemoryLimiter,
651}
652
653impl HttpServerBuilder {
654 pub fn new(options: HttpOptions) -> Self {
655 Self {
656 options,
657 batching_protocols: Vec::new(),
658 logical_batching_protocols: Vec::new(),
659 user_provider: None,
660 router: Router::new(),
661 memory_limiter: ServerMemoryLimiter::default(),
662 }
663 }
664
665 pub fn with_logical_batching_protocols(mut self, protocols: Vec<BatchingProtocol>) -> Self {
667 self.logical_batching_protocols = protocols;
668 self
669 }
670
671 pub fn with_batching_protocols(mut self, protocols: Vec<BatchingProtocol>) -> Self {
673 self.batching_protocols = protocols;
674 self
675 }
676
677 pub fn with_memory_limiter(mut self, limiter: ServerMemoryLimiter) -> Self {
679 self.memory_limiter = limiter;
680 self
681 }
682
683 pub fn with_sql_handler(self, sql_handler: ServerSqlQueryHandlerRef) -> Self {
684 let sql_router = HttpServer::route_sql(ApiState { sql_handler });
685
686 Self {
687 router: self
688 .router
689 .nest(&format!("/{HTTP_API_VERSION}"), sql_router),
690 ..self
691 }
692 }
693
694 pub fn with_logs_handler(self, logs_handler: LogQueryHandlerRef) -> Self {
695 let logs_router = HttpServer::route_logs(logs_handler);
696
697 Self {
698 router: self
699 .router
700 .nest(&format!("/{HTTP_API_VERSION}"), logs_router),
701 ..self
702 }
703 }
704
705 pub fn with_opentsdb_handler(self, handler: OpentsdbProtocolHandlerRef) -> Self {
706 Self {
707 router: self.router.nest(
708 &format!("/{HTTP_API_VERSION}/opentsdb"),
709 HttpServer::route_opentsdb(handler),
710 ),
711 ..self
712 }
713 }
714
715 pub fn with_influxdb_handler(self, handler: InfluxdbLineProtocolHandlerRef) -> Self {
716 Self {
717 router: self.router.nest(
718 &format!("/{HTTP_API_VERSION}/influxdb"),
719 HttpServer::route_influxdb(handler),
720 ),
721 ..self
722 }
723 }
724
725 pub fn with_prom_handler(
726 self,
727 handler: PromStoreProtocolHandlerRef,
728 pipeline_handler: Option<PipelineHandlerRef>,
729 prom_store_with_metric_engine: bool,
730 prom_validation_mode: PromValidationMode,
731 pending_rows_batcher: Option<Arc<LogicalTablePendingRowsBatcher>>,
732 ) -> Self {
733 let state = PromStoreState {
734 prom_store_handler: handler,
735 pipeline_handler,
736 prom_store_with_metric_engine,
737 prom_validation_mode,
738 pending_rows_batcher,
739 };
740
741 Self {
742 router: self.router.nest(
743 &format!("/{HTTP_API_VERSION}/prometheus"),
744 HttpServer::route_prom(state),
745 ),
746 ..self
747 }
748 }
749
750 pub fn with_prometheus_handler(self, handler: PrometheusHandlerRef) -> Self {
751 Self {
752 router: self.router.nest(
753 &format!("/{HTTP_API_VERSION}/prometheus/api/v1"),
754 HttpServer::route_prometheus(handler),
755 ),
756 ..self
757 }
758 }
759
760 pub fn with_otlp_handler(
761 self,
762 handler: OpenTelemetryProtocolHandlerRef,
763 with_metric_engine: bool,
764 ) -> Self {
765 Self {
766 router: self.router.nest(
767 &format!("/{HTTP_API_VERSION}/otlp"),
768 HttpServer::route_otlp(handler, with_metric_engine),
769 ),
770 ..self
771 }
772 }
773
774 pub fn with_user_provider(self, user_provider: UserProviderRef) -> Self {
775 Self {
776 user_provider: Some(user_provider),
777 ..self
778 }
779 }
780
781 pub fn with_metrics_handler(self, handler: MetricsHandler) -> Self {
782 Self {
783 router: self.router.merge(HttpServer::route_metrics(handler)),
784 ..self
785 }
786 }
787
788 pub fn with_log_ingest_handler(
789 self,
790 handler: PipelineHandlerRef,
791 validator: Option<LogValidatorRef>,
792 ingest_interceptor: Option<LogIngestInterceptorRef<Error>>,
793 ) -> Self {
794 let log_state = LogState {
795 log_handler: handler,
796 log_validator: validator,
797 ingest_interceptor,
798 };
799
800 let router = self.router.nest(
801 &format!("/{HTTP_API_VERSION}"),
802 HttpServer::route_pipelines(log_state.clone()),
803 );
804 let router = router.nest(
806 &format!("/{HTTP_API_VERSION}/events"),
807 #[allow(deprecated)]
808 HttpServer::route_log_deprecated(log_state.clone()),
809 );
810
811 let router = router.nest(
812 &format!("/{HTTP_API_VERSION}/loki"),
813 HttpServer::route_loki(log_state.clone()),
814 );
815
816 let router = router.nest(
817 &format!("/{HTTP_API_VERSION}/elasticsearch"),
818 HttpServer::route_elasticsearch(log_state.clone()),
819 );
820
821 let router = router.nest(
822 &format!("/{HTTP_API_VERSION}/elasticsearch/"),
823 Router::new()
824 .route("/", routing::get(elasticsearch::handle_get_version))
825 .with_state(log_state.clone()),
826 );
827
828 let router = router.nest(
829 &format!("/{HTTP_API_VERSION}/splunk"),
830 HttpServer::route_splunk(log_state),
831 );
832
833 Self { router, ..self }
834 }
835
836 pub fn with_greptime_config_options(self, opts: String) -> Self {
837 let config_router = HttpServer::route_config(GreptimeOptionsConfigState {
838 greptime_config_options: opts,
839 });
840
841 Self {
842 router: self.router.merge(config_router),
843 ..self
844 }
845 }
846
847 pub fn with_jaeger_handler(self, handler: JaegerQueryHandlerRef) -> Self {
848 Self {
849 router: self.router.nest(
850 &format!("/{HTTP_API_VERSION}/jaeger"),
851 HttpServer::route_jaeger(handler),
852 ),
853 ..self
854 }
855 }
856
857 pub fn with_dashboard_handler(self, handler: DashboardHandlerRef) -> Self {
858 Self {
859 router: self.router.nest(
860 &format!("/{HTTP_API_VERSION}/dashboards"),
861 HttpServer::route_dashboard(handler),
862 ),
863 ..self
864 }
865 }
866
867 pub fn with_extra_router(self, router: Router) -> Self {
868 Self {
869 router: self.router.merge(router),
870 ..self
871 }
872 }
873
874 pub fn add_layer<L>(self, layer: L) -> Self
875 where
876 L: Layer<Route> + Clone + Send + Sync + 'static,
877 L::Service: Service<Request> + Clone + Send + Sync + 'static,
878 <L::Service as Service<Request>>::Response: IntoResponse + 'static,
879 <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
880 <L::Service as Service<Request>>::Future: Send + 'static,
881 {
882 Self {
883 router: self.router.layer(layer),
884 ..self
885 }
886 }
887
888 pub fn build(self) -> HttpServer {
889 HttpServer {
890 options: self.options,
891 batching_protocols: self.batching_protocols.clone(),
892 logical_batching_protocols: self.logical_batching_protocols.clone(),
893 user_provider: self.user_provider,
894 shutdown_tx: Mutex::new(None),
895 router: StdMutex::new(self.router),
896 bind_addr: None,
897 memory_limiter: self.memory_limiter,
898 kind: HttpServerKind::Full,
899 }
900 }
901
902 pub fn build_servers(self) -> (HttpServer, Option<HttpServer>) {
921 let api_enabled = self.options.enable_api_server;
922 let api_addr = self.options.api_server_addr.clone();
923
924 let internal = HttpServer {
925 options: self.options,
926 batching_protocols: self.batching_protocols.clone(),
927 logical_batching_protocols: self.logical_batching_protocols.clone(),
928 user_provider: self.user_provider.clone(),
929 shutdown_tx: Mutex::new(None),
930 router: StdMutex::new(self.router.clone()),
931 bind_addr: None,
932 memory_limiter: self.memory_limiter.clone(),
933 kind: HttpServerKind::Full,
934 };
935
936 let api = if api_enabled {
937 let api_options = HttpOptions {
940 addr: api_addr,
941 ..internal.options.clone()
942 };
943 Some(HttpServer {
944 options: api_options,
945 batching_protocols: self.batching_protocols,
946 logical_batching_protocols: self.logical_batching_protocols,
947 user_provider: self.user_provider.clone(),
948 shutdown_tx: Mutex::new(None),
949 router: StdMutex::new(self.router),
950 bind_addr: None,
951 memory_limiter: self.memory_limiter,
952 kind: HttpServerKind::Api,
953 })
954 } else {
955 None
956 };
957
958 (internal, api)
959 }
960}
961
962impl HttpServer {
963 pub fn make_app(&self) -> Router {
973 let mut router = self.router.lock().unwrap().clone();
974
975 router = router
976 .route(
977 &format!("/{HTTP_API_VERSION}/health"),
978 routing::get(handler::health).post(handler::health),
979 )
980 .route("/", routing::get(handler::index))
981 .route(
982 "/health",
983 routing::get(handler::health).post(handler::health),
984 )
985 .route(
986 "/ready",
987 routing::get(handler::health).post(handler::health),
988 )
989 .route("/status", routing::get(handler::status));
990
991 #[cfg(feature = "dashboard")]
994 {
995 if !self.options.disable_dashboard {
996 info!("Enable dashboard service at '/dashboard'");
997 router = router.route(
999 "/dashboard",
1000 routing::get(|uri: axum::http::uri::Uri| async move {
1001 let path = uri.path();
1002 let query = uri.query().map(|q| format!("?{}", q)).unwrap_or_default();
1003
1004 let new_uri = format!("{}/{}", path, query);
1005 axum::response::Redirect::permanent(&new_uri)
1006 }),
1007 );
1008
1009 router = router
1013 .route(
1014 "/dashboard/",
1015 routing::get(dashboard::static_handler).post(dashboard::static_handler),
1016 )
1017 .route(
1018 "/dashboard/{*x}",
1019 routing::get(dashboard::static_handler).post(dashboard::static_handler),
1020 );
1021 }
1022 }
1023
1024 router = router.route_layer(middleware::from_fn(http_metrics_layer));
1026
1027 router
1028 }
1029
1030 pub fn build(&self, router: Router) -> Result<Router> {
1033 let timeout_layer = if self.options.timeout != Duration::default() {
1034 Some(
1035 ServiceBuilder::new().layer(
1036 DynamicTimeoutLayer::new(self.options.timeout)
1037 .with_status_code_fn(Self::request_timeout_status_code),
1038 ),
1039 )
1040 } else {
1041 info!("HTTP server timeout is disabled");
1042 None
1043 };
1044 let body_limit_layer = if self.options.body_limit != ReadableSize(0) {
1045 Some(
1046 ServiceBuilder::new()
1047 .layer(DefaultBodyLimit::max(self.options.body_limit.0 as usize)),
1048 )
1049 } else {
1050 info!("HTTP server body limit is disabled");
1051 None
1052 };
1053 let cors_layer = if self.options.enable_cors {
1054 Some(
1055 CorsLayer::new()
1056 .allow_methods([
1057 Method::GET,
1058 Method::POST,
1059 Method::PUT,
1060 Method::DELETE,
1061 Method::HEAD,
1062 ])
1063 .allow_origin(if self.options.cors_allowed_origins.is_empty() {
1064 AllowOrigin::from(Any)
1065 } else {
1066 AllowOrigin::from(
1067 self.options
1068 .cors_allowed_origins
1069 .iter()
1070 .map(|s| {
1071 HeaderValue::from_str(s.as_str())
1072 .context(InvalidHeaderValueSnafu)
1073 })
1074 .collect::<Result<Vec<HeaderValue>>>()?,
1075 )
1076 })
1077 .allow_headers(Any),
1078 )
1079 } else {
1080 info!("HTTP server cross-origin is disabled");
1081 None
1082 };
1083
1084 let router = router
1085 .layer(
1087 ServiceBuilder::new()
1088 .layer(TraceLayer::new_for_http().on_failure(()))
1091 .option_layer(cors_layer)
1092 .option_layer(timeout_layer)
1093 .option_layer(body_limit_layer)
1094 .layer(middleware::from_fn_with_state(
1096 self.memory_limiter.clone(),
1097 memory_limit::memory_limit_middleware,
1098 ))
1099 .layer(middleware::from_fn_with_state(
1101 AuthState::new(self.user_provider.clone()),
1102 authorize::check_http_auth,
1103 ))
1104 .layer(Extension(Arc::new(self.batching_protocols.clone())))
1105 .layer(Extension(LogicalBatchingProtocols(
1106 self.logical_batching_protocols.clone(),
1107 )))
1108 .layer(middleware::from_fn(hints::extract_hints))
1109 .layer(middleware::from_fn(client_ip::log_error_with_client_ip))
1110 .layer(middleware::from_fn(
1111 read_preference::extract_read_preference,
1112 ))
1113 .layer(middleware::from_fn(skip_wal::extract_skip_wal)),
1114 );
1115
1116 let router = router.nest(
1119 "/debug",
1120 Router::new()
1121 .route("/log_level", routing::post(dyn_log::dyn_log_handler))
1123 .route(
1124 "/workload_scheduler",
1125 routing::get(workload_scheduler::get_status_handler),
1126 )
1127 .route(
1128 "/workload_scheduler/enabled",
1129 routing::post(workload_scheduler::set_enabled_handler),
1130 )
1131 .route(
1132 "/workload_scheduler/weights",
1133 routing::post(workload_scheduler::set_weights_handler),
1134 )
1135 .route("/enable_trace", routing::post(dyn_trace::dyn_trace_handler))
1136 .nest(
1137 "/prof",
1138 Router::new()
1139 .route("/cpu", routing::post(pprof::pprof_handler))
1140 .route("/mem", routing::post(mem_prof::mem_prof_handler))
1141 .route("/mem/symbol", routing::post(mem_prof::symbolicate_handler))
1142 .route(
1143 "/mem/activate",
1144 routing::post(mem_prof::activate_heap_prof_handler),
1145 )
1146 .route(
1147 "/mem/deactivate",
1148 routing::post(mem_prof::deactivate_heap_prof_handler),
1149 )
1150 .route(
1151 "/mem/status",
1152 routing::get(mem_prof::heap_prof_status_handler),
1153 ) .route(
1155 "/mem/gdump",
1156 routing::get(mem_prof::gdump_status_handler)
1157 .post(mem_prof::gdump_toggle_handler),
1158 ),
1159 ),
1160 );
1161
1162 if self.kind == HttpServerKind::Api {
1167 Ok(router.layer(middleware::from_fn(enforce_api_surface)))
1168 } else {
1169 Ok(router)
1170 }
1171 }
1172
1173 fn request_timeout_status_code(request: &Request) -> HttpStatusCode {
1174 if request.uri().path() == "/v1/prometheus/write" {
1175 HttpStatusCode::GATEWAY_TIMEOUT
1176 } else {
1177 HttpStatusCode::REQUEST_TIMEOUT
1178 }
1179 }
1180
1181 fn route_metrics<S>(metrics_handler: MetricsHandler) -> Router<S> {
1182 Router::new()
1183 .route("/metrics", routing::get(handler::metrics))
1184 .with_state(metrics_handler)
1185 }
1186
1187 fn route_loki<S>(log_state: LogState) -> Router<S> {
1188 Router::new()
1189 .route("/api/v1/push", routing::post(loki::loki_ingest))
1190 .layer(
1191 ServiceBuilder::new()
1192 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1193 )
1194 .layer(middleware::from_fn_with_state(
1195 BatchingProtocol::Loki,
1196 set_http_write_batching,
1197 ))
1198 .with_state(log_state)
1199 }
1200
1201 fn route_splunk<S>(log_state: LogState) -> Router<S> {
1202 Router::new()
1203 .route(
1204 "/services/collector/health",
1205 routing::get(splunk::handle_health),
1206 )
1207 .route(
1208 "/services/collector/health/1.0",
1209 routing::get(splunk::handle_health),
1210 )
1211 .route(
1214 "/services/collector/event",
1215 routing::post(splunk::handle_event),
1216 )
1217 .route("/services/collector", routing::post(splunk::handle_event))
1218 .route(
1219 "/services/collector/event/1.0",
1220 routing::post(splunk::handle_event),
1221 )
1222 .route("/services/collector/raw", routing::post(splunk::handle_raw))
1225 .route(
1226 "/services/collector/raw/1.0",
1227 routing::post(splunk::handle_raw),
1228 )
1229 .layer(
1230 ServiceBuilder::new()
1231 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1232 )
1233 .layer(middleware::from_fn_with_state(
1234 BatchingProtocol::Splunk,
1235 set_http_write_batching,
1236 ))
1237 .with_state(log_state)
1238 }
1239
1240 fn route_elasticsearch<S>(log_state: LogState) -> Router<S> {
1241 Router::new()
1242 .route(
1244 "/",
1245 routing::head((HttpStatusCode::OK, elasticsearch::elasticsearch_headers())),
1246 )
1247 .route("/", routing::get(elasticsearch::handle_get_version))
1249 .route("/_license", routing::get(elasticsearch::handle_get_license))
1251 .route("/_bulk", routing::post(elasticsearch::handle_bulk_api))
1252 .route(
1253 "/{index}/_bulk",
1254 routing::post(elasticsearch::handle_bulk_api_with_index),
1255 )
1256 .route(
1258 "/_ilm/policy/{*path}",
1259 routing::any((
1260 HttpStatusCode::OK,
1261 elasticsearch::elasticsearch_headers(),
1262 axum::Json(serde_json::json!({})),
1263 )),
1264 )
1265 .route(
1267 "/_index_template/{*path}",
1268 routing::any((
1269 HttpStatusCode::OK,
1270 elasticsearch::elasticsearch_headers(),
1271 axum::Json(serde_json::json!({})),
1272 )),
1273 )
1274 .route(
1277 "/_ingest/{*path}",
1278 routing::any((
1279 HttpStatusCode::OK,
1280 elasticsearch::elasticsearch_headers(),
1281 axum::Json(serde_json::json!({})),
1282 )),
1283 )
1284 .route(
1287 "/_nodes/{*path}",
1288 routing::any((
1289 HttpStatusCode::OK,
1290 elasticsearch::elasticsearch_headers(),
1291 axum::Json(serde_json::json!({})),
1292 )),
1293 )
1294 .route(
1297 "/logstash/{*path}",
1298 routing::any((
1299 HttpStatusCode::OK,
1300 elasticsearch::elasticsearch_headers(),
1301 axum::Json(serde_json::json!({})),
1302 )),
1303 )
1304 .route(
1305 "/_logstash/{*path}",
1306 routing::any((
1307 HttpStatusCode::OK,
1308 elasticsearch::elasticsearch_headers(),
1309 axum::Json(serde_json::json!({})),
1310 )),
1311 )
1312 .layer(ServiceBuilder::new().layer(RequestDecompressionLayer::new()))
1313 .layer(middleware::from_fn_with_state(
1314 BatchingProtocol::Elasticsearch,
1315 set_http_write_batching,
1316 ))
1317 .with_state(log_state)
1318 }
1319
1320 #[deprecated(since = "0.11.0", note = "Use `route_pipelines()` instead.")]
1321 fn route_log_deprecated<S>(log_state: LogState) -> Router<S> {
1322 Router::new()
1323 .route("/logs", routing::post(event::log_ingester))
1324 .route(
1325 "/pipelines/{pipeline_name}",
1326 routing::get(event::query_pipeline),
1327 )
1328 .route(
1329 "/pipelines/{pipeline_name}",
1330 routing::post(event::add_pipeline),
1331 )
1332 .route(
1333 "/pipelines/{pipeline_name}",
1334 routing::delete(event::delete_pipeline),
1335 )
1336 .route("/pipelines/dryrun", routing::post(event::pipeline_dryrun))
1337 .layer(
1338 ServiceBuilder::new()
1339 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1340 )
1341 .layer(middleware::from_fn_with_state(
1342 BatchingProtocol::Logs,
1343 set_http_write_batching,
1344 ))
1345 .with_state(log_state)
1346 }
1347
1348 fn route_pipelines<S>(log_state: LogState) -> Router<S> {
1349 Router::new()
1350 .route("/ingest", routing::post(event::log_ingester))
1351 .route(
1352 "/pipelines/{pipeline_name}",
1353 routing::get(event::query_pipeline),
1354 )
1355 .route(
1356 "/pipelines/{pipeline_name}/ddl",
1357 routing::get(event::query_pipeline_ddl),
1358 )
1359 .route(
1360 "/pipelines/{pipeline_name}",
1361 routing::post(event::add_pipeline),
1362 )
1363 .route(
1364 "/pipelines/{pipeline_name}",
1365 routing::delete(event::delete_pipeline),
1366 )
1367 .route("/pipelines/_dryrun", routing::post(event::pipeline_dryrun))
1368 .layer(
1369 ServiceBuilder::new()
1370 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1371 )
1372 .layer(middleware::from_fn_with_state(
1373 BatchingProtocol::Logs,
1374 set_http_write_batching,
1375 ))
1376 .with_state(log_state)
1377 }
1378
1379 fn route_sql<S>(api_state: ApiState) -> Router<S> {
1380 Router::new()
1381 .route(
1382 "/capabilities",
1383 routing::get(|| async {
1384 axum::Json(
1385 serde_json::json!({"metric_packed_import": 1, "metric_packed_export": 1}),
1386 )
1387 }),
1388 )
1389 .route(
1390 "/sql",
1391 routing::get(handler::sql).post(handler::sql).layer(
1392 middleware::from_fn_with_state(
1393 BatchingProtocol::HttpSql,
1394 set_http_write_batching,
1395 ),
1396 ),
1397 )
1398 .route(
1399 "/sql/parse",
1400 routing::get(handler::sql_parse).post(handler::sql_parse),
1401 )
1402 .route(
1403 "/sql/format",
1404 routing::get(handler::sql_format).post(handler::sql_format),
1405 )
1406 .route(
1407 "/promql",
1408 routing::get(handler::promql).post(handler::promql),
1409 )
1410 .route(
1411 "/sql/analyze/stream",
1412 routing::post(handler::sql_analyze_stream),
1413 )
1414 .with_state(api_state)
1415 }
1416
1417 fn route_logs<S>(log_handler: LogQueryHandlerRef) -> Router<S> {
1418 Router::new()
1419 .route("/logs", routing::get(logs::logs).post(logs::logs))
1420 .with_state(log_handler)
1421 }
1422
1423 pub fn route_prometheus<S>(prometheus_handler: PrometheusHandlerRef) -> Router<S> {
1427 Router::new()
1428 .route(
1429 "/format_query",
1430 routing::post(format_query).get(format_query),
1431 )
1432 .route("/status/buildinfo", routing::get(build_info_query))
1433 .route("/query", routing::post(instant_query).get(instant_query))
1434 .route("/query_range", routing::post(range_query).get(range_query))
1435 .route("/labels", routing::post(labels_query).get(labels_query))
1436 .route("/metadata", routing::get(metadata_query))
1437 .route("/series", routing::post(series_query).get(series_query))
1438 .route("/parse_query", routing::post(parse_query).get(parse_query))
1439 .route(
1440 "/label/{label_name}/values",
1441 routing::get(label_values_query),
1442 )
1443 .layer(ServiceBuilder::new().layer(CompressionLayer::new()))
1444 .with_state(prometheus_handler)
1445 }
1446
1447 fn route_prom<S>(state: PromStoreState) -> Router<S> {
1453 let write = routing::post(prom_store::remote_write);
1454 let write = if state.prom_store_with_metric_engine {
1455 write
1456 } else {
1457 write.layer(middleware::from_fn_with_state(
1458 BatchingProtocol::Prom,
1459 set_http_write_batching,
1460 ))
1461 };
1462 Router::new()
1463 .route("/read", routing::post(prom_store::remote_read))
1464 .route("/write", write)
1465 .with_state(state)
1466 }
1467
1468 fn route_influxdb<S>(influxdb_handler: InfluxdbLineProtocolHandlerRef) -> Router<S> {
1469 Router::new()
1470 .route("/write", routing::post(influxdb_write_v1))
1471 .route("/api/v2/write", routing::post(influxdb_write_v2))
1472 .layer(
1473 ServiceBuilder::new()
1474 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1475 )
1476 .route("/ping", routing::get(influxdb_ping))
1477 .route("/health", routing::get(influxdb_health))
1478 .layer(middleware::from_fn_with_state(
1479 BatchingProtocol::Influxdb,
1480 set_http_write_batching,
1481 ))
1482 .with_state(influxdb_handler)
1483 }
1484
1485 fn route_opentsdb<S>(opentsdb_handler: OpentsdbProtocolHandlerRef) -> Router<S> {
1486 Router::new()
1487 .route("/api/put", routing::post(opentsdb::put))
1488 .layer(middleware::from_fn_with_state(
1489 BatchingProtocol::Opentsdb,
1490 set_http_write_batching,
1491 ))
1492 .with_state(opentsdb_handler)
1493 }
1494
1495 fn route_otlp<S>(
1496 otlp_handler: OpenTelemetryProtocolHandlerRef,
1497 with_metric_engine: bool,
1498 ) -> Router<S> {
1499 Router::new()
1500 .route("/v1/metrics", routing::post(otlp::metrics))
1501 .route("/v1/traces", routing::post(otlp::traces))
1502 .route("/v1/logs", routing::post(otlp::logs))
1503 .layer(
1504 ServiceBuilder::new()
1505 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1506 )
1507 .layer(middleware::from_fn_with_state(
1508 BatchingProtocol::Otlp,
1509 set_http_write_batching,
1510 ))
1511 .with_state(OtlpState {
1512 with_metric_engine,
1513 handler: otlp_handler,
1514 })
1515 }
1516
1517 fn route_config<S>(state: GreptimeOptionsConfigState) -> Router<S> {
1518 Router::new()
1519 .route("/config", routing::get(handler::config))
1520 .with_state(state)
1521 }
1522
1523 fn route_jaeger<S>(handler: JaegerQueryHandlerRef) -> Router<S> {
1524 Router::new()
1525 .route("/api/services", routing::get(jaeger::handle_get_services))
1526 .route(
1527 "/api/services/{service_name}/operations",
1528 routing::get(jaeger::handle_get_operations_by_service),
1529 )
1530 .route(
1531 "/api/operations",
1532 routing::get(jaeger::handle_get_operations),
1533 )
1534 .route("/api/traces", routing::get(jaeger::handle_find_traces))
1535 .route(
1536 "/api/traces/{trace_id}",
1537 routing::get(jaeger::handle_get_trace),
1538 )
1539 .with_state(handler)
1540 }
1541
1542 #[cfg(feature = "dashboard")]
1543 fn route_dashboard<S>(handler: DashboardHandlerRef) -> Router<S> {
1544 use crate::http::dashboard::{add_dashboard, delete_dashboard, list_dashboards};
1545
1546 Router::new()
1547 .route("/", routing::get(list_dashboards))
1548 .route("/{dashboard_name}", routing::post(add_dashboard))
1549 .route("/{dashboard_name}", routing::delete(delete_dashboard))
1550 .layer(
1551 ServiceBuilder::new()
1552 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1553 )
1554 .with_state(DashboardState { handler })
1555 }
1556
1557 #[cfg(not(feature = "dashboard"))]
1558 fn route_dashboard<S>(handler: DashboardHandlerRef) -> Router<S> {
1559 Router::new().with_state(DashboardState { handler })
1560 }
1561}
1562
1563pub const HTTP_SERVER: &str = "HTTP_SERVER";
1564pub const HTTP_API_SERVER: &str = "HTTP_API_SERVER";
1565
1566#[async_trait]
1567impl Server for HttpServer {
1568 async fn shutdown(&self) -> Result<()> {
1569 let mut shutdown_tx = self.shutdown_tx.lock().await;
1570 if let Some(tx) = shutdown_tx.take()
1571 && tx.send(()).is_err()
1572 {
1573 info!("Receiver dropped, the HTTP server has already exited");
1574 }
1575 info!("Shutdown {}", self.kind());
1576
1577 Ok(())
1578 }
1579
1580 async fn start(&mut self, listening: SocketAddr) -> Result<()> {
1581 let (tx, rx) = oneshot::channel();
1582 let serve = {
1583 let mut shutdown_tx = self.shutdown_tx.lock().await;
1584 ensure!(
1585 shutdown_tx.is_none(),
1586 AlreadyStartedSnafu {
1587 server: self.kind()
1588 }
1589 );
1590
1591 let app = self.build(self.make_app())?;
1592 let listener = tokio::net::TcpListener::bind(listening)
1593 .await
1594 .context(AddressBindSnafu { addr: listening })?
1595 .tap_io(|tcp_stream| {
1596 if let Err(e) = tcp_stream.set_nodelay(true) {
1597 error!(e; "Failed to set TCP_NODELAY on incoming connection");
1598 }
1599 });
1600 let serve = axum::serve(
1601 listener,
1602 app.into_make_service_with_connect_info::<SocketAddr>(),
1603 );
1604
1605 *shutdown_tx = Some(tx);
1622
1623 serve
1624 };
1625 let listening = serve.local_addr().context(InternalIoSnafu)?;
1626 info!("{} server is bound to {}", self.kind(), listening);
1627
1628 common_runtime::spawn_global(async move {
1629 if let Err(e) = serve
1630 .with_graceful_shutdown(rx.map(drop))
1631 .await
1632 .context(InternalIoSnafu)
1633 {
1634 error!(e; "Failed to shutdown http server");
1635 }
1636 });
1637
1638 self.bind_addr = Some(listening);
1639 Ok(())
1640 }
1641
1642 fn name(&self) -> &str {
1643 match self.kind {
1644 HttpServerKind::Api => HTTP_API_SERVER,
1645 HttpServerKind::Full => HTTP_SERVER,
1646 }
1647 }
1648
1649 fn bind_addr(&self) -> Option<SocketAddr> {
1650 self.bind_addr
1651 }
1652
1653 fn as_any(&self) -> &dyn std::any::Any {
1654 self
1655 }
1656}
1657
1658#[cfg(test)]
1659mod test {
1660 use std::future::pending;
1661 use std::io::Cursor;
1662 use std::sync::Arc;
1663
1664 use arrow_ipc::reader::StreamReader;
1665 use arrow_schema::DataType;
1666 use axum::http::StatusCode;
1667 use axum::routing::{get, post};
1668 use common_query::{Output, OutputData};
1669 use common_recordbatch::RecordBatches;
1670 use datafusion_expr::LogicalPlan;
1671 use datatypes::prelude::*;
1672 use datatypes::schema::{ColumnSchema, Schema};
1673 use datatypes::vectors::{StringVector, UInt32Vector};
1674 use header::constants::GREPTIME_DB_HEADER_TIMEOUT;
1675 use query::parser::PromQuery;
1676 use query::query_engine::DescribeResult;
1677 use session::context::QueryContextRef;
1678 use sql::statements::statement::Statement;
1679 use tokio::sync::mpsc;
1680 use tokio::time::Instant;
1681
1682 use crate::http::test_helpers::TestClient;
1683 use crate::http::*;
1684 use crate::prom_remote_write::validation::validate_label_name;
1685 use crate::query_handler::sql::SqlQueryHandler;
1686
1687 struct DummyInstance {
1688 _tx: mpsc::Sender<(String, Vec<u8>)>,
1689 }
1690
1691 #[async_trait]
1692 impl SqlQueryHandler for DummyInstance {
1693 async fn do_query(&self, _: &str, _: QueryContextRef) -> Vec<Result<Output>> {
1694 unimplemented!()
1695 }
1696
1697 async fn do_analyze_stream_query(&self, _: &str, _: QueryContextRef) -> Result<Output> {
1698 let stream = common_recordbatch::RecordBatches::empty().as_stream();
1699 Ok(Output::new(OutputData::Stream(stream), Default::default()))
1700 }
1701
1702 async fn do_promql_query(&self, _: &PromQuery, _: QueryContextRef) -> Vec<Result<Output>> {
1703 unimplemented!()
1704 }
1705
1706 async fn do_exec_plan(
1707 &self,
1708 _plan: LogicalPlan,
1709 _stmt: Option<Statement>,
1710 _query_ctx: QueryContextRef,
1711 ) -> Result<Output> {
1712 unimplemented!()
1713 }
1714
1715 async fn do_describe(
1716 &self,
1717 _stmt: sql::statements::statement::Statement,
1718 _query_ctx: QueryContextRef,
1719 ) -> Result<Option<DescribeResult>> {
1720 unimplemented!()
1721 }
1722
1723 async fn is_valid_schema(&self, _catalog: &str, _schema: &str) -> Result<bool> {
1724 Ok(true)
1725 }
1726 }
1727
1728 async fn forever() {
1729 pending().await
1730 }
1731
1732 fn make_test_app(tx: mpsc::Sender<(String, Vec<u8>)>) -> Router {
1733 make_test_app_custom(tx, HttpOptions::default())
1734 }
1735
1736 fn make_test_app_custom(tx: mpsc::Sender<(String, Vec<u8>)>, options: HttpOptions) -> Router {
1737 let instance = Arc::new(DummyInstance { _tx: tx });
1738 let server = HttpServerBuilder::new(options)
1739 .with_sql_handler(instance.clone())
1740 .build();
1741 let app = server
1742 .make_app()
1743 .route("/test/timeout", get(forever))
1744 .route("/v1/prometheus/write", post(forever));
1745 server.build(app).unwrap()
1746 }
1747
1748 fn make_split_builder() -> HttpServerBuilder {
1749 let (tx, _rx) = mpsc::channel(100);
1750 let instance = Arc::new(DummyInstance { _tx: tx });
1751 let options = HttpOptions {
1753 enable_api_server: true,
1754 ..HttpOptions::default()
1755 };
1756 HttpServerBuilder::new(options)
1757 .with_sql_handler(instance)
1758 .with_metrics_handler(MetricsHandler)
1759 .with_greptime_config_options("dummy = \"value\"".to_string())
1760 }
1761
1762 #[tokio::test]
1763 pub async fn test_http_api_options_defaults() {
1764 let opts = HttpOptions::default();
1765 assert!(!opts.enable_api_server);
1767 assert_eq!(opts.api_server_addr, "127.0.0.1:4006");
1768 }
1769
1770 #[tokio::test]
1771 pub async fn test_build_serves_all_routes() {
1772 let server = make_split_builder().build();
1776 assert_eq!(server.name(), HTTP_SERVER);
1777
1778 let app = server.build(server.make_app()).unwrap();
1779 let client = TestClient::new(app).await;
1780
1781 for path in ["/v1/health", "/health", "/status", "/metrics", "/config"] {
1782 let res = client.get(path).send().await;
1783 assert_eq!(
1784 res.status(),
1785 StatusCode::OK,
1786 "internal/full server should serve {path}"
1787 );
1788 }
1789 }
1790
1791 #[tokio::test]
1792 pub async fn test_build_servers_separates_api_and_internal_routes() {
1793 let (internal, api) = make_split_builder().build_servers();
1796 let api = api.expect("API server is explicitly enabled in make_split_builder");
1797 assert_eq!(internal.name(), HTTP_SERVER);
1798 assert_eq!(api.name(), HTTP_API_SERVER);
1799
1800 let internal_app = internal.build(internal.make_app()).unwrap();
1801 let api_app = api.build(api.make_app()).unwrap();
1802
1803 let internal_client = TestClient::new(internal_app).await;
1804 let api_client = TestClient::new(api_app).await;
1805
1806 assert_eq!(
1808 internal_client.get("/v1/health").send().await.status(),
1809 StatusCode::OK
1810 );
1811 assert_eq!(
1812 api_client.get("/v1/health").send().await.status(),
1813 StatusCode::OK
1814 );
1815
1816 for path in ["/health", "/status", "/metrics", "/config"] {
1818 assert_eq!(
1819 internal_client.get(path).send().await.status(),
1820 StatusCode::OK,
1821 "internal/full server should serve {path}"
1822 );
1823 assert_eq!(
1825 api_client.get(path).send().await.status(),
1826 StatusCode::NOT_FOUND,
1827 "API server should NOT serve {path}"
1828 );
1829 }
1830 }
1831
1832 #[test]
1833 fn test_build_servers_api_inherits_http_options() {
1834 let http_opts = HttpOptions {
1836 timeout: Duration::from_secs(42),
1837 body_limit: ReadableSize::mb(128),
1838 cors_allowed_origins: vec!["https://example.com".to_string()],
1839 enable_api_server: true,
1840 ..HttpOptions::default()
1841 };
1842 let (internal, api) = HttpServerBuilder::new(http_opts.clone()).build_servers();
1843 let api = api.expect("API server is explicitly enabled");
1844
1845 assert_eq!(internal.options.addr, http_opts.addr);
1847 assert_eq!(api.options.addr, "127.0.0.1:4006");
1848 assert_eq!(api.options.timeout, http_opts.timeout);
1850 assert_eq!(api.options.body_limit, http_opts.body_limit);
1851 assert_eq!(
1852 api.options.cors_allowed_origins,
1853 http_opts.cors_allowed_origins
1854 );
1855 }
1856
1857 #[test]
1858 fn test_is_api_listener_path() {
1859 assert!(is_api_listener_path("/v1"));
1861 assert!(is_api_listener_path("/v1/"));
1862 assert!(is_api_listener_path("/v1/sql"));
1863 assert!(!is_api_listener_path("/v10/sql"));
1864 assert!(!is_api_listener_path("/v1-internal"));
1865 assert!(is_api_listener_path("/dashboard"));
1867 assert!(is_api_listener_path("/dashboard/app.js"));
1868 assert!(!is_api_listener_path("/dashboard-admin"));
1869 assert!(!is_api_listener_path("/metrics"));
1871 assert!(!is_api_listener_path("/status/plugin"));
1872 assert!(!is_api_listener_path("/health"));
1873 }
1874
1875 #[tokio::test]
1876 async fn packed_capability_requires_auth_on_full_and_api_listeners() {
1877 let (tx, _rx) = mpsc::channel(1);
1878 let provider =
1879 auth::static_user_provider_from_option("static_user_provider:cmd:user=password")
1880 .unwrap();
1881 let (full, api) = HttpServerBuilder::new(HttpOptions {
1882 enable_api_server: true,
1883 ..Default::default()
1884 })
1885 .with_sql_handler(Arc::new(DummyInstance { _tx: tx }))
1886 .with_user_provider(Arc::new(provider))
1887 .build_servers();
1888 for server in [full, api.unwrap()] {
1889 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
1890 assert_eq!(
1891 client.get("/v1/capabilities").send().await.status(),
1892 StatusCode::UNAUTHORIZED
1893 );
1894 let response = client
1895 .get("/v1/capabilities")
1896 .header("Authorization", "Basic dXNlcjpwYXNzd29yZA==")
1897 .send()
1898 .await;
1899 assert_eq!(response.status(), StatusCode::OK);
1900 assert_eq!(
1901 response.json::<serde_json::Value>().await,
1902 serde_json::json!({"metric_packed_import": 1, "metric_packed_export": 1})
1903 );
1904 }
1905 }
1906
1907 #[tokio::test]
1908 pub async fn test_extra_router_respects_api_surface() {
1909 let (tx, _rx) = mpsc::channel(100);
1915 let instance = Arc::new(DummyInstance { _tx: tx });
1916 let options = HttpOptions {
1917 enable_api_server: true,
1918 ..HttpOptions::default()
1919 };
1920 let builder = HttpServerBuilder::new(options)
1921 .with_sql_handler(instance)
1922 .with_extra_router(
1923 Router::new()
1924 .route("/status/plugin", routing::get(|| async { "ok" }))
1925 .route("/v1/plugin", routing::get(|| async { "ok" })),
1926 );
1927 let (full, api) = builder.build_servers();
1928 let api = api.expect("API server is explicitly enabled");
1929
1930 let full_client = TestClient::new(full.build(full.make_app()).unwrap()).await;
1931 let api_client = TestClient::new(api.build(api.make_app()).unwrap()).await;
1932
1933 assert_eq!(
1935 full_client.get("/status/plugin").send().await.status(),
1936 StatusCode::OK
1937 );
1938 assert_eq!(
1940 api_client.get("/status/plugin").send().await.status(),
1941 StatusCode::NOT_FOUND
1942 );
1943
1944 assert_eq!(
1946 full_client.get("/v1/plugin").send().await.status(),
1947 StatusCode::OK
1948 );
1949 assert_eq!(
1950 api_client.get("/v1/plugin").send().await.status(),
1951 StatusCode::OK
1952 );
1953
1954 assert_eq!(
1956 api_client.get("/v10/plugin").send().await.status(),
1957 StatusCode::NOT_FOUND
1958 );
1959 }
1960
1961 #[test]
1962 fn test_build_servers_api_disabled_by_default() {
1963 let (_internal, api) = HttpServerBuilder::new(HttpOptions::default()).build_servers();
1966 assert!(api.is_none());
1967 }
1968
1969 #[tokio::test]
1970 pub async fn test_cors() {
1971 let (tx, _rx) = mpsc::channel(100);
1973 let app = make_test_app(tx);
1974 let client = TestClient::new(app).await;
1975
1976 let res = client.get("/health").send().await;
1977
1978 assert_eq!(res.status(), StatusCode::OK);
1979 assert_eq!(
1980 res.headers()
1981 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
1982 .expect("expect cors header origin"),
1983 "*"
1984 );
1985
1986 let res = client.get("/v1/health").send().await;
1987
1988 assert_eq!(res.status(), StatusCode::OK);
1989 assert_eq!(
1990 res.headers()
1991 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
1992 .expect("expect cors header origin"),
1993 "*"
1994 );
1995
1996 let res = client
1997 .options("/health")
1998 .header("Access-Control-Request-Headers", "x-greptime-auth")
1999 .header("Access-Control-Request-Method", "DELETE")
2000 .header("Origin", "https://example.com")
2001 .send()
2002 .await;
2003 assert_eq!(res.status(), StatusCode::OK);
2004 assert_eq!(
2005 res.headers()
2006 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2007 .expect("expect cors header origin"),
2008 "*"
2009 );
2010 assert_eq!(
2011 res.headers()
2012 .get(http::header::ACCESS_CONTROL_ALLOW_HEADERS)
2013 .expect("expect cors header headers"),
2014 "*"
2015 );
2016 assert_eq!(
2017 res.headers()
2018 .get(http::header::ACCESS_CONTROL_ALLOW_METHODS)
2019 .expect("expect cors header methods"),
2020 "GET,POST,PUT,DELETE,HEAD"
2021 );
2022 }
2023
2024 #[tokio::test]
2025 pub async fn test_cors_custom_origins() {
2026 let (tx, _rx) = mpsc::channel(100);
2028 let origin = "https://example.com";
2029
2030 let options = HttpOptions {
2031 cors_allowed_origins: vec![origin.to_string()],
2032 ..Default::default()
2033 };
2034
2035 let app = make_test_app_custom(tx, options);
2036 let client = TestClient::new(app).await;
2037
2038 let res = client.get("/health").header("Origin", origin).send().await;
2039
2040 assert_eq!(res.status(), StatusCode::OK);
2041 assert_eq!(
2042 res.headers()
2043 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2044 .expect("expect cors header origin"),
2045 origin
2046 );
2047
2048 let res = client
2049 .get("/health")
2050 .header("Origin", "https://notallowed.com")
2051 .send()
2052 .await;
2053
2054 assert_eq!(res.status(), StatusCode::OK);
2055 assert!(
2056 !res.headers()
2057 .contains_key(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2058 );
2059 }
2060
2061 #[tokio::test]
2062 pub async fn test_cors_disabled() {
2063 let (tx, _rx) = mpsc::channel(100);
2065
2066 let options = HttpOptions {
2067 enable_cors: false,
2068 ..Default::default()
2069 };
2070
2071 let app = make_test_app_custom(tx, options);
2072 let client = TestClient::new(app).await;
2073
2074 let res = client.get("/health").send().await;
2075
2076 assert_eq!(res.status(), StatusCode::OK);
2077 assert!(
2078 !res.headers()
2079 .contains_key(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2080 );
2081 }
2082
2083 #[test]
2084 fn test_http_options_default() {
2085 let default = HttpOptions::default();
2086 assert_eq!("127.0.0.1:4000".to_string(), default.addr);
2087 assert_eq!(Duration::from_secs(0), default.timeout)
2088 }
2089
2090 #[tokio::test]
2091 async fn test_http_options_legacy_analyze_stream_config_is_ignored() {
2092 let options: HttpOptions = serde_json::from_value(serde_json::json!({
2093 "addr": "127.0.0.1:4000",
2094 "timeout": "0s",
2095 "body_limit": "64MiB",
2096 "cors_allowed_origins": [],
2097 "enable_cors": true,
2098 "experimental_enable_explain_analyze_stream": false,
2099 "enable_api_server": false,
2100 "api_server_addr": "127.0.0.1:4006"
2101 }))
2102 .unwrap();
2103 let serialized = serde_json::to_string(&options).unwrap();
2104 assert!(!serialized.contains("experimental_enable_explain_analyze_stream"));
2105
2106 let (tx, _rx) = mpsc::channel(100);
2107 let app = make_test_app_custom(tx, options);
2108 let client = TestClient::new(app).await;
2109 let response = client
2110 .post("/v1/sql/analyze/stream")
2111 .form(&handler::SqlQuery {
2112 sql: Some("EXPLAIN ANALYZE VERBOSE SELECT 1".to_string()),
2113 ..Default::default()
2114 })
2115 .send()
2116 .await;
2117 assert_ne!(response.status(), StatusCode::NOT_FOUND);
2118 }
2119
2120 #[tokio::test]
2121 async fn test_http_server_request_timeout() {
2122 common_telemetry::init_default_ut_logging();
2123
2124 let (tx, _rx) = mpsc::channel(100);
2125 let options = HttpOptions {
2126 timeout: Duration::from_millis(10),
2127 ..Default::default()
2128 };
2129 let app = make_test_app_custom(tx, options);
2130 let client = TestClient::new(app).await;
2131 let res = client.get("/test/timeout").send().await;
2132 assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
2133
2134 let res = client.post("/v1/prometheus/write").send().await;
2135 assert_eq!(res.status(), StatusCode::GATEWAY_TIMEOUT);
2136
2137 let now = Instant::now();
2138 let res = client
2139 .get("/test/timeout")
2140 .header(GREPTIME_DB_HEADER_TIMEOUT, "20ms")
2141 .send()
2142 .await;
2143 assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
2144 let elapsed = now.elapsed();
2145 assert!(elapsed > Duration::from_millis(15));
2146
2147 tokio::time::timeout(
2148 Duration::from_millis(15),
2149 client
2150 .get("/test/timeout")
2151 .header(GREPTIME_DB_HEADER_TIMEOUT, "0s")
2152 .send(),
2153 )
2154 .await
2155 .unwrap_err();
2156
2157 tokio::time::timeout(
2158 Duration::from_millis(15),
2159 client
2160 .get("/test/timeout")
2161 .header(
2162 GREPTIME_DB_HEADER_TIMEOUT,
2163 humantime::format_duration(Duration::default()).to_string(),
2164 )
2165 .send(),
2166 )
2167 .await
2168 .unwrap_err();
2169 }
2170
2171 #[tokio::test]
2172 async fn test_schema_for_empty_response() {
2173 let column_schemas = vec![
2174 ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
2175 ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
2176 ];
2177 let schema = Arc::new(Schema::new(column_schemas));
2178
2179 let recordbatches = RecordBatches::try_new(schema.clone(), vec![]).unwrap();
2180 let outputs = vec![Ok(Output::new_with_record_batches(recordbatches))];
2181
2182 let json_resp = GreptimedbV1Response::from_output(outputs).await;
2183 if let HttpResponse::GreptimedbV1(json_resp) = json_resp {
2184 let json_output = &json_resp.output[0];
2185 if let GreptimeQueryOutput::Records(r) = json_output {
2186 assert_eq!(r.num_rows(), 0);
2187 assert_eq!(r.num_cols(), 2);
2188 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2189 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2190 } else {
2191 panic!("invalid output type");
2192 }
2193 } else {
2194 panic!("invalid format")
2195 }
2196 }
2197
2198 #[tokio::test]
2199 async fn test_recordbatches_conversion() {
2200 let column_schemas = vec![
2201 ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
2202 ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
2203 ];
2204 let schema = Arc::new(Schema::new(column_schemas));
2205 let columns: Vec<VectorRef> = vec![
2206 Arc::new(UInt32Vector::from_slice(vec![1, 2, 3, 4])),
2207 Arc::new(StringVector::from(vec![
2208 None,
2209 Some("hello"),
2210 Some("greptime"),
2211 None,
2212 ])),
2213 ];
2214 let recordbatch = RecordBatch::new(schema.clone(), columns).unwrap();
2215
2216 for format in [
2217 ResponseFormat::GreptimedbV1,
2218 ResponseFormat::InfluxdbV1,
2219 ResponseFormat::Csv(true, true),
2220 ResponseFormat::Table,
2221 ResponseFormat::Arrow,
2222 ResponseFormat::Json,
2223 ResponseFormat::Null,
2224 ] {
2225 let recordbatches =
2226 RecordBatches::try_new(schema.clone(), vec![recordbatch.clone()]).unwrap();
2227 let outputs = vec![Ok(Output::new_with_record_batches(recordbatches))];
2228 let json_resp = match format {
2229 ResponseFormat::Arrow => ArrowResponse::from_output(outputs, None).await,
2230 ResponseFormat::Csv(with_names, with_types) => {
2231 CsvResponse::from_output(outputs, with_names, with_types).await
2232 }
2233 ResponseFormat::Table => TableResponse::from_output(outputs).await,
2234 ResponseFormat::GreptimedbV1 => GreptimedbV1Response::from_output(outputs).await,
2235 ResponseFormat::InfluxdbV1 => InfluxdbV1Response::from_output(outputs, None).await,
2236 ResponseFormat::Json => JsonResponse::from_output(outputs).await,
2237 ResponseFormat::Null => NullResponse::from_output(outputs).await,
2238 };
2239
2240 match json_resp {
2241 HttpResponse::GreptimedbV1(resp) => {
2242 let json_output = &resp.output[0];
2243 if let GreptimeQueryOutput::Records(r) = json_output {
2244 assert_eq!(r.num_rows(), 4);
2245 assert_eq!(r.num_cols(), 2);
2246 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2247 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2248 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2249 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2250 } else {
2251 panic!("invalid output type");
2252 }
2253 }
2254 HttpResponse::InfluxdbV1(resp) => {
2255 let json_output = &resp.results()[0];
2256 assert_eq!(json_output.num_rows(), 4);
2257 assert_eq!(json_output.num_cols(), 2);
2258 assert_eq!(json_output.series[0].columns.clone()[0], "numbers");
2259 assert_eq!(
2260 json_output.series[0].values[0][0],
2261 serde_json::Value::from(1)
2262 );
2263 assert_eq!(json_output.series[0].values[0][1], serde_json::Value::Null);
2264 }
2265 HttpResponse::Csv(resp) => {
2266 let output = &resp.output()[0];
2267 if let GreptimeQueryOutput::Records(r) = output {
2268 assert_eq!(r.num_rows(), 4);
2269 assert_eq!(r.num_cols(), 2);
2270 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2271 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2272 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2273 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2274 } else {
2275 panic!("invalid output type");
2276 }
2277 }
2278
2279 HttpResponse::Table(resp) => {
2280 let output = &resp.output()[0];
2281 if let GreptimeQueryOutput::Records(r) = output {
2282 assert_eq!(r.num_rows(), 4);
2283 assert_eq!(r.num_cols(), 2);
2284 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2285 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2286 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2287 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2288 } else {
2289 panic!("invalid output type");
2290 }
2291 }
2292
2293 HttpResponse::Arrow(resp) => {
2294 let output = resp.data;
2295 let mut reader = StreamReader::try_new(Cursor::new(output), None)
2296 .expect("Arrow reader error");
2297 let schema = reader.schema();
2298 assert_eq!(schema.fields[0].name(), "numbers");
2299 assert_eq!(schema.fields[0].data_type(), &DataType::UInt32);
2300 assert_eq!(schema.fields[1].name(), "strings");
2301 assert_eq!(schema.fields[1].data_type(), &DataType::Utf8);
2302
2303 let rb = reader.next().unwrap().expect("read record batch failed");
2304 assert_eq!(rb.num_columns(), 2);
2305 assert_eq!(rb.num_rows(), 4);
2306 }
2307
2308 HttpResponse::Json(resp) => {
2309 let output = &resp.output()[0];
2310 if let GreptimeQueryOutput::Records(r) = output {
2311 assert_eq!(r.num_rows(), 4);
2312 assert_eq!(r.num_cols(), 2);
2313 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2314 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2315 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2316 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2317 } else {
2318 panic!("invalid output type");
2319 }
2320 }
2321
2322 HttpResponse::Null(resp) => {
2323 assert_eq!(resp.rows(), 4);
2324 }
2325
2326 HttpResponse::Error(err) => unreachable!("{err:?}"),
2327 }
2328 }
2329 }
2330
2331 #[test]
2332 fn test_response_format_misc() {
2333 assert_eq!(ResponseFormat::default(), ResponseFormat::GreptimedbV1);
2334 assert_eq!(ResponseFormat::parse("arrow"), Some(ResponseFormat::Arrow));
2335 assert_eq!(
2336 ResponseFormat::parse("csv"),
2337 Some(ResponseFormat::Csv(false, false))
2338 );
2339 assert_eq!(
2340 ResponseFormat::parse("csvwithnames"),
2341 Some(ResponseFormat::Csv(true, false))
2342 );
2343 assert_eq!(
2344 ResponseFormat::parse("csvwithnamesandtypes"),
2345 Some(ResponseFormat::Csv(true, true))
2346 );
2347 assert_eq!(ResponseFormat::parse("table"), Some(ResponseFormat::Table));
2348 assert_eq!(
2349 ResponseFormat::parse("greptimedb_v1"),
2350 Some(ResponseFormat::GreptimedbV1)
2351 );
2352 assert_eq!(
2353 ResponseFormat::parse("influxdb_v1"),
2354 Some(ResponseFormat::InfluxdbV1)
2355 );
2356 assert_eq!(ResponseFormat::parse("json"), Some(ResponseFormat::Json));
2357 assert_eq!(ResponseFormat::parse("null"), Some(ResponseFormat::Null));
2358
2359 assert_eq!(ResponseFormat::parse("invalid"), None);
2361 assert_eq!(ResponseFormat::parse(""), None);
2362 assert_eq!(ResponseFormat::parse("CSV"), None); assert_eq!(ResponseFormat::Arrow.as_str(), "arrow");
2366 assert_eq!(ResponseFormat::Csv(false, false).as_str(), "csv");
2367 assert_eq!(ResponseFormat::Csv(true, true).as_str(), "csv");
2368 assert_eq!(ResponseFormat::Table.as_str(), "table");
2369 assert_eq!(ResponseFormat::GreptimedbV1.as_str(), "greptimedb_v1");
2370 assert_eq!(ResponseFormat::InfluxdbV1.as_str(), "influxdb_v1");
2371 assert_eq!(ResponseFormat::Json.as_str(), "json");
2372 assert_eq!(ResponseFormat::Null.as_str(), "null");
2373 assert_eq!(ResponseFormat::default().as_str(), "greptimedb_v1");
2374 }
2375
2376 #[test]
2377 fn test_decode_label_name_strict() {
2378 let strict = PromValidationMode::Strict;
2379
2380 assert!(strict.decode_label_name(b"__name__").is_ok());
2382 assert!(strict.decode_label_name(b"job").is_ok());
2383 assert!(strict.decode_label_name(b"instance").is_ok());
2384 assert!(strict.decode_label_name(b"_private").is_ok());
2385 assert!(strict.decode_label_name(b"label_with_underscores").is_ok());
2386 assert!(strict.decode_label_name(b"abc123").is_ok());
2387 assert!(strict.decode_label_name(b"A").is_ok());
2388 assert!(strict.decode_label_name(b"_").is_ok());
2389
2390 assert!(strict.decode_label_name(b"0abc").is_err());
2392 assert!(strict.decode_label_name(b"123").is_err());
2393
2394 assert!(strict.decode_label_name(b"label-name").is_err());
2396 assert!(strict.decode_label_name(b"label.name").is_err());
2397 assert!(strict.decode_label_name(b"label name").is_err());
2398 assert!(strict.decode_label_name(b"label/name").is_err());
2399
2400 assert!(strict.decode_label_name(b"").is_err());
2402
2403 assert!(strict.decode_label_name("ラベル".as_bytes()).is_err());
2405
2406 assert!(strict.decode_label_name(&[0xff, 0xfe]).is_err());
2408 }
2409
2410 #[test]
2411 fn test_decode_label_name_lossy() {
2412 let lossy = PromValidationMode::Lossy;
2413
2414 assert!(lossy.decode_label_name(b"__name__").is_ok());
2416 assert!(lossy.decode_label_name(b"label-name").is_err());
2417 assert!(lossy.decode_label_name(b"0abc").is_err());
2418
2419 assert!(lossy.decode_label_name(&[0xff, 0xfe]).is_err());
2421 }
2422
2423 #[test]
2424 fn test_decode_label_name_unchecked() {
2425 let unchecked = PromValidationMode::Unchecked;
2426
2427 assert!(unchecked.decode_label_name(b"__name__").is_ok());
2429 assert!(unchecked.decode_label_name(b"label-name").is_err());
2430 assert!(unchecked.decode_label_name(b"0abc").is_err());
2431 }
2432
2433 #[test]
2434 fn test_is_valid_prom_label_name_bytes() {
2435 assert!(validate_label_name(b"__name__"));
2436 assert!(validate_label_name(b"job"));
2437 assert!(validate_label_name(b"_"));
2438 assert!(validate_label_name(b"A"));
2439 assert!(validate_label_name(b"abc123"));
2440 assert!(validate_label_name(b"_leading_underscore"));
2441
2442 assert!(!validate_label_name(b""));
2443 assert!(!validate_label_name(b"0starts_with_digit"));
2444 assert!(!validate_label_name(b"has-dash"));
2445 assert!(!validate_label_name(b"has.dot"));
2446 assert!(!validate_label_name(b"has space"));
2447 assert!(!validate_label_name(&[0xff, 0xfe]));
2448 }
2449}
2450
2451#[cfg(test)]
2452mod batching_tests {
2453 use std::sync::{Arc, Mutex};
2454
2455 use axum::http::StatusCode;
2456 use common_query::Output;
2457 use session::context::QueryContextRef;
2458
2459 use crate::batcher::BatchingProtocol;
2460 use crate::error::Result as ServerResult;
2461 use crate::http::test_helpers::TestClient;
2462 use crate::http::{HttpOptions, HttpServerBuilder};
2463 use crate::influxdb::InfluxdbRequest;
2464 use crate::opentsdb::codec::DataPoint;
2465 use crate::query_handler::{InfluxdbLineProtocolHandler, OpentsdbProtocolHandler};
2466
2467 #[tokio::test]
2468 async fn test_batching_selectors_are_independent() {
2469 use axum::routing::post;
2470 use axum::{Extension, Json, Router, middleware};
2471 use session::context::{QueryContext, QueryContextBuilder};
2472
2473 use crate::http::{LogicalBatchingProtocols, set_http_write_batching};
2474 for table in [false, true] {
2475 for logical in [false, true] {
2476 let app = Router::new()
2477 .route(
2478 "/",
2479 post(|Extension(ctx): Extension<QueryContext>| async move {
2480 Json([ctx.batching_enabled(), ctx.logical_batching_enabled()])
2481 }),
2482 )
2483 .route_layer(middleware::from_fn_with_state(
2484 BatchingProtocol::Otlp,
2485 set_http_write_batching,
2486 ))
2487 .layer(Extension(QueryContextBuilder::default().build()))
2488 .layer(Extension(Arc::new(if table {
2489 vec![BatchingProtocol::Otlp]
2490 } else {
2491 vec![]
2492 })))
2493 .layer(Extension(LogicalBatchingProtocols(if logical {
2494 vec![BatchingProtocol::Otlp]
2495 } else {
2496 vec![]
2497 })));
2498 let client = TestClient::new(app).await;
2499 let actual: [bool; 2] = client.post("/").send().await.json().await;
2500 assert_eq!(actual, [table, logical]);
2501 }
2502 }
2503 }
2504
2505 #[derive(Default)]
2506 struct RecordingWriteHandler {
2507 selections: Mutex<Vec<bool>>,
2508 }
2509
2510 #[async_trait::async_trait]
2511 impl OpentsdbProtocolHandler for RecordingWriteHandler {
2512 async fn preflight(&self, _: &[DataPoint], _: QueryContextRef) -> ServerResult<()> {
2513 Ok(())
2514 }
2515
2516 async fn exec(&self, points: Vec<DataPoint>, ctx: QueryContextRef) -> ServerResult<usize> {
2517 self.selections.lock().unwrap().push(ctx.batching_enabled());
2518 Ok(points.len())
2519 }
2520 }
2521
2522 #[async_trait::async_trait]
2523 impl InfluxdbLineProtocolHandler for RecordingWriteHandler {
2524 async fn exec(&self, _: InfluxdbRequest, ctx: QueryContextRef) -> ServerResult<Output> {
2525 self.selections.lock().unwrap().push(ctx.batching_enabled());
2526 Ok(Output::new_with_affected_rows(1))
2527 }
2528 }
2529
2530 #[tokio::test]
2531 async fn test_real_influx_and_opentsdb_routes_keep_selection() {
2532 for protocols in [
2533 vec![],
2534 vec![BatchingProtocol::Influxdb],
2535 vec![BatchingProtocol::Opentsdb],
2536 vec![BatchingProtocol::Influxdb, BatchingProtocol::Opentsdb],
2537 ] {
2538 let handler = Arc::new(RecordingWriteHandler::default());
2539 let influx_enabled = protocols.contains(&BatchingProtocol::Influxdb);
2540 let opentsdb_enabled = protocols.contains(&BatchingProtocol::Opentsdb);
2541 let server = HttpServerBuilder::new(HttpOptions::default())
2542 .with_batching_protocols(protocols)
2543 .with_influxdb_handler(handler.clone())
2544 .with_opentsdb_handler(handler.clone())
2545 .build();
2546 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
2547 for path in [
2548 "/v1/influxdb/write",
2549 "/v1/influxdb/api/v2/write?bucket=public",
2550 ] {
2551 assert_eq!(
2552 client
2553 .post(path)
2554 .body("cpu value=1 42")
2555 .send()
2556 .await
2557 .status(),
2558 StatusCode::NO_CONTENT
2559 );
2560 }
2561 let point =
2562 serde_json::json!({"metric":"cpu", "timestamp":42, "value":1, "tags":{"host":"a"}});
2563 for query in ["", "?summary", "?details"] {
2564 let response = client
2565 .post(&format!("/v1/opentsdb/api/put{query}"))
2566 .json(&point)
2567 .send()
2568 .await;
2569 assert_eq!(
2570 response.status(),
2571 if query.is_empty() {
2572 StatusCode::NO_CONTENT
2573 } else {
2574 StatusCode::OK
2575 }
2576 );
2577 }
2578 assert_eq!(
2579 *handler.selections.lock().unwrap(),
2580 vec![
2581 influx_enabled,
2582 influx_enabled,
2583 opentsdb_enabled,
2584 opentsdb_enabled,
2585 opentsdb_enabled
2586 ]
2587 );
2588 }
2589 }
2590}