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, self.memory_limiter.clone()),
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 memory_limiter: self.memory_limiter.clone(),
740 };
741
742 Self {
743 router: self.router.nest(
744 &format!("/{HTTP_API_VERSION}/prometheus"),
745 HttpServer::route_prom(state),
746 ),
747 ..self
748 }
749 }
750
751 pub fn with_prometheus_handler(self, handler: PrometheusHandlerRef) -> Self {
752 Self {
753 router: self.router.nest(
754 &format!("/{HTTP_API_VERSION}/prometheus/api/v1"),
755 HttpServer::route_prometheus(handler),
756 ),
757 ..self
758 }
759 }
760
761 pub fn with_otlp_handler(
762 self,
763 handler: OpenTelemetryProtocolHandlerRef,
764 with_metric_engine: bool,
765 ) -> Self {
766 Self {
767 router: self.router.nest(
768 &format!("/{HTTP_API_VERSION}/otlp"),
769 HttpServer::route_otlp(handler, with_metric_engine, self.memory_limiter.clone()),
770 ),
771 ..self
772 }
773 }
774
775 pub fn with_user_provider(self, user_provider: UserProviderRef) -> Self {
776 Self {
777 user_provider: Some(user_provider),
778 ..self
779 }
780 }
781
782 pub fn with_metrics_handler(self, handler: MetricsHandler) -> Self {
783 Self {
784 router: self.router.merge(HttpServer::route_metrics(handler)),
785 ..self
786 }
787 }
788
789 pub fn with_log_ingest_handler(
790 self,
791 handler: PipelineHandlerRef,
792 validator: Option<LogValidatorRef>,
793 ingest_interceptor: Option<LogIngestInterceptorRef<Error>>,
794 ) -> Self {
795 let log_state = LogState {
796 log_handler: handler,
797 log_validator: validator,
798 ingest_interceptor,
799 };
800
801 let router = self.router.nest(
802 &format!("/{HTTP_API_VERSION}"),
803 HttpServer::route_pipelines(log_state.clone(), self.memory_limiter.clone()),
804 );
805 let router = router.nest(
807 &format!("/{HTTP_API_VERSION}/events"),
808 #[allow(deprecated)]
809 HttpServer::route_log_deprecated(log_state.clone(), self.memory_limiter.clone()),
810 );
811
812 let router = router.nest(
813 &format!("/{HTTP_API_VERSION}/loki"),
814 HttpServer::route_loki(log_state.clone(), self.memory_limiter.clone()),
815 );
816
817 let router = router.nest(
818 &format!("/{HTTP_API_VERSION}/elasticsearch"),
819 HttpServer::route_elasticsearch(log_state.clone(), self.memory_limiter.clone()),
820 );
821
822 let router = router.nest(
823 &format!("/{HTTP_API_VERSION}/elasticsearch/"),
824 Router::new()
825 .route("/", routing::get(elasticsearch::handle_get_version))
826 .with_state(log_state.clone()),
827 );
828
829 let router = router.nest(
830 &format!("/{HTTP_API_VERSION}/splunk"),
831 HttpServer::route_splunk(log_state, self.memory_limiter.clone()),
832 );
833
834 Self { router, ..self }
835 }
836
837 pub fn with_greptime_config_options(self, opts: String) -> Self {
838 let config_router = HttpServer::route_config(GreptimeOptionsConfigState {
839 greptime_config_options: opts,
840 });
841
842 Self {
843 router: self.router.merge(config_router),
844 ..self
845 }
846 }
847
848 pub fn with_jaeger_handler(self, handler: JaegerQueryHandlerRef) -> Self {
849 Self {
850 router: self.router.nest(
851 &format!("/{HTTP_API_VERSION}/jaeger"),
852 HttpServer::route_jaeger(handler),
853 ),
854 ..self
855 }
856 }
857
858 pub fn with_dashboard_handler(self, handler: DashboardHandlerRef) -> Self {
859 Self {
860 router: self.router.nest(
861 &format!("/{HTTP_API_VERSION}/dashboards"),
862 HttpServer::route_dashboard(handler, self.memory_limiter.clone()),
863 ),
864 ..self
865 }
866 }
867
868 pub fn with_extra_router(self, router: Router) -> Self {
869 Self {
870 router: self.router.merge(router),
871 ..self
872 }
873 }
874
875 pub fn add_layer<L>(self, layer: L) -> Self
876 where
877 L: Layer<Route> + Clone + Send + Sync + 'static,
878 L::Service: Service<Request> + Clone + Send + Sync + 'static,
879 <L::Service as Service<Request>>::Response: IntoResponse + 'static,
880 <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
881 <L::Service as Service<Request>>::Future: Send + 'static,
882 {
883 Self {
884 router: self.router.layer(layer),
885 ..self
886 }
887 }
888
889 pub fn build(self) -> HttpServer {
890 HttpServer {
891 options: self.options,
892 batching_protocols: self.batching_protocols.clone(),
893 logical_batching_protocols: self.logical_batching_protocols.clone(),
894 user_provider: self.user_provider,
895 shutdown_tx: Mutex::new(None),
896 router: StdMutex::new(self.router),
897 bind_addr: None,
898 memory_limiter: self.memory_limiter,
899 kind: HttpServerKind::Full,
900 }
901 }
902
903 pub fn build_servers(self) -> (HttpServer, Option<HttpServer>) {
922 let api_enabled = self.options.enable_api_server;
923 let api_addr = self.options.api_server_addr.clone();
924
925 let internal = HttpServer {
926 options: self.options,
927 batching_protocols: self.batching_protocols.clone(),
928 logical_batching_protocols: self.logical_batching_protocols.clone(),
929 user_provider: self.user_provider.clone(),
930 shutdown_tx: Mutex::new(None),
931 router: StdMutex::new(self.router.clone()),
932 bind_addr: None,
933 memory_limiter: self.memory_limiter.clone(),
934 kind: HttpServerKind::Full,
935 };
936
937 let api = if api_enabled {
938 let api_options = HttpOptions {
941 addr: api_addr,
942 ..internal.options.clone()
943 };
944 Some(HttpServer {
945 options: api_options,
946 batching_protocols: self.batching_protocols,
947 logical_batching_protocols: self.logical_batching_protocols,
948 user_provider: self.user_provider.clone(),
949 shutdown_tx: Mutex::new(None),
950 router: StdMutex::new(self.router),
951 bind_addr: None,
952 memory_limiter: self.memory_limiter,
953 kind: HttpServerKind::Api,
954 })
955 } else {
956 None
957 };
958
959 (internal, api)
960 }
961}
962
963impl HttpServer {
964 pub fn make_app(&self) -> Router {
974 let mut router = self.router.lock().unwrap().clone();
975
976 router = router
977 .route(
978 &format!("/{HTTP_API_VERSION}/health"),
979 routing::get(handler::health).post(handler::health),
980 )
981 .route("/", routing::get(handler::index))
982 .route(
983 "/health",
984 routing::get(handler::health).post(handler::health),
985 )
986 .route(
987 "/ready",
988 routing::get(handler::health).post(handler::health),
989 )
990 .route("/status", routing::get(handler::status));
991
992 #[cfg(feature = "dashboard")]
995 {
996 if !self.options.disable_dashboard {
997 info!("Enable dashboard service at '/dashboard'");
998 router = router.route(
1000 "/dashboard",
1001 routing::get(|uri: axum::http::uri::Uri| async move {
1002 let path = uri.path();
1003 let query = uri.query().map(|q| format!("?{}", q)).unwrap_or_default();
1004
1005 let new_uri = format!("{}/{}", path, query);
1006 axum::response::Redirect::permanent(&new_uri)
1007 }),
1008 );
1009
1010 router = router
1014 .route(
1015 "/dashboard/",
1016 routing::get(dashboard::static_handler).post(dashboard::static_handler),
1017 )
1018 .route(
1019 "/dashboard/{*x}",
1020 routing::get(dashboard::static_handler).post(dashboard::static_handler),
1021 );
1022 }
1023 }
1024
1025 router = router.route_layer(middleware::from_fn(http_metrics_layer));
1027
1028 router
1029 }
1030
1031 pub fn build(&self, router: Router) -> Result<Router> {
1034 let timeout_layer = if self.options.timeout != Duration::default() {
1035 Some(
1036 ServiceBuilder::new().layer(
1037 DynamicTimeoutLayer::new(self.options.timeout)
1038 .with_status_code_fn(Self::request_timeout_status_code),
1039 ),
1040 )
1041 } else {
1042 info!("HTTP server timeout is disabled");
1043 None
1044 };
1045 let body_limit_layer = if self.options.body_limit != ReadableSize(0) {
1046 Some(
1047 ServiceBuilder::new()
1048 .layer(DefaultBodyLimit::max(self.options.body_limit.0 as usize)),
1049 )
1050 } else {
1051 info!("HTTP server body limit is disabled");
1052 None
1053 };
1054 let cors_layer = if self.options.enable_cors {
1055 Some(
1056 CorsLayer::new()
1057 .allow_methods([
1058 Method::GET,
1059 Method::POST,
1060 Method::PUT,
1061 Method::DELETE,
1062 Method::HEAD,
1063 ])
1064 .allow_origin(if self.options.cors_allowed_origins.is_empty() {
1065 AllowOrigin::from(Any)
1066 } else {
1067 AllowOrigin::from(
1068 self.options
1069 .cors_allowed_origins
1070 .iter()
1071 .map(|s| {
1072 HeaderValue::from_str(s.as_str())
1073 .context(InvalidHeaderValueSnafu)
1074 })
1075 .collect::<Result<Vec<HeaderValue>>>()?,
1076 )
1077 })
1078 .allow_headers(Any),
1079 )
1080 } else {
1081 info!("HTTP server cross-origin is disabled");
1082 None
1083 };
1084
1085 let router = router
1086 .layer(
1088 ServiceBuilder::new()
1089 .layer(TraceLayer::new_for_http().on_failure(()))
1092 .option_layer(cors_layer)
1093 .option_layer(timeout_layer)
1094 .option_layer(body_limit_layer)
1095 .layer(middleware::from_fn_with_state(
1097 self.memory_limiter.clone(),
1098 memory_limit::memory_limit_middleware,
1099 ))
1100 .layer(middleware::from_fn_with_state(
1102 AuthState::new(self.user_provider.clone()),
1103 authorize::check_http_auth,
1104 ))
1105 .layer(Extension(Arc::new(self.batching_protocols.clone())))
1106 .layer(Extension(LogicalBatchingProtocols(
1107 self.logical_batching_protocols.clone(),
1108 )))
1109 .layer(middleware::from_fn(hints::extract_hints))
1110 .layer(middleware::from_fn(client_ip::log_error_with_client_ip))
1111 .layer(middleware::from_fn(
1112 read_preference::extract_read_preference,
1113 ))
1114 .layer(middleware::from_fn(skip_wal::extract_skip_wal)),
1115 );
1116
1117 let router = router.nest(
1120 "/debug",
1121 Router::new()
1122 .route("/log_level", routing::post(dyn_log::dyn_log_handler))
1124 .route(
1125 "/workload_scheduler",
1126 routing::get(workload_scheduler::get_status_handler),
1127 )
1128 .route(
1129 "/workload_scheduler/enabled",
1130 routing::post(workload_scheduler::set_enabled_handler),
1131 )
1132 .route(
1133 "/workload_scheduler/weights",
1134 routing::post(workload_scheduler::set_weights_handler),
1135 )
1136 .route("/enable_trace", routing::post(dyn_trace::dyn_trace_handler))
1137 .nest(
1138 "/prof",
1139 Router::new()
1140 .route("/cpu", routing::post(pprof::pprof_handler))
1141 .route("/mem", routing::post(mem_prof::mem_prof_handler))
1142 .route("/mem/symbol", routing::post(mem_prof::symbolicate_handler))
1143 .route(
1144 "/mem/activate",
1145 routing::post(mem_prof::activate_heap_prof_handler),
1146 )
1147 .route(
1148 "/mem/deactivate",
1149 routing::post(mem_prof::deactivate_heap_prof_handler),
1150 )
1151 .route(
1152 "/mem/status",
1153 routing::get(mem_prof::heap_prof_status_handler),
1154 ) .route(
1156 "/mem/gdump",
1157 routing::get(mem_prof::gdump_status_handler)
1158 .post(mem_prof::gdump_toggle_handler),
1159 ),
1160 ),
1161 );
1162
1163 if self.kind == HttpServerKind::Api {
1168 Ok(router.layer(middleware::from_fn(enforce_api_surface)))
1169 } else {
1170 Ok(router)
1171 }
1172 }
1173
1174 fn request_timeout_status_code(request: &Request) -> HttpStatusCode {
1175 if request.uri().path() == "/v1/prometheus/write" {
1176 HttpStatusCode::GATEWAY_TIMEOUT
1177 } else {
1178 HttpStatusCode::REQUEST_TIMEOUT
1179 }
1180 }
1181
1182 fn route_metrics<S>(metrics_handler: MetricsHandler) -> Router<S> {
1183 Router::new()
1184 .route("/metrics", routing::get(handler::metrics))
1185 .with_state(metrics_handler)
1186 }
1187
1188 fn route_loki<S>(log_state: LogState, memory_limiter: ServerMemoryLimiter) -> Router<S> {
1189 Router::new()
1190 .route("/api/v1/push", routing::post(loki::loki_ingest))
1191 .layer(middleware::from_fn_with_state(
1192 memory_limiter,
1193 memory_limit::decoded_body_accounting_middleware,
1194 ))
1195 .layer(
1196 ServiceBuilder::new()
1197 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1198 )
1199 .layer(middleware::from_fn_with_state(
1200 BatchingProtocol::Loki,
1201 set_http_write_batching,
1202 ))
1203 .with_state(log_state)
1204 }
1205
1206 fn route_splunk<S>(log_state: LogState, memory_limiter: ServerMemoryLimiter) -> Router<S> {
1207 Router::new()
1208 .route(
1209 "/services/collector/health",
1210 routing::get(splunk::handle_health),
1211 )
1212 .route(
1213 "/services/collector/health/1.0",
1214 routing::get(splunk::handle_health),
1215 )
1216 .route(
1219 "/services/collector/event",
1220 routing::post(splunk::handle_event),
1221 )
1222 .route("/services/collector", routing::post(splunk::handle_event))
1223 .route(
1224 "/services/collector/event/1.0",
1225 routing::post(splunk::handle_event),
1226 )
1227 .route("/services/collector/raw", routing::post(splunk::handle_raw))
1230 .route(
1231 "/services/collector/raw/1.0",
1232 routing::post(splunk::handle_raw),
1233 )
1234 .layer(middleware::from_fn_with_state(
1235 memory_limiter,
1236 memory_limit::decoded_body_accounting_middleware,
1237 ))
1238 .layer(
1239 ServiceBuilder::new()
1240 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1241 )
1242 .layer(middleware::from_fn_with_state(
1243 BatchingProtocol::Splunk,
1244 set_http_write_batching,
1245 ))
1246 .with_state(log_state)
1247 }
1248
1249 fn route_elasticsearch<S>(
1250 log_state: LogState,
1251 memory_limiter: ServerMemoryLimiter,
1252 ) -> Router<S> {
1253 Router::new()
1254 .route(
1256 "/",
1257 routing::head((HttpStatusCode::OK, elasticsearch::elasticsearch_headers())),
1258 )
1259 .route("/", routing::get(elasticsearch::handle_get_version))
1261 .route("/_license", routing::get(elasticsearch::handle_get_license))
1263 .route("/_bulk", routing::post(elasticsearch::handle_bulk_api))
1264 .route(
1265 "/{index}/_bulk",
1266 routing::post(elasticsearch::handle_bulk_api_with_index),
1267 )
1268 .route(
1270 "/_ilm/policy/{*path}",
1271 routing::any((
1272 HttpStatusCode::OK,
1273 elasticsearch::elasticsearch_headers(),
1274 axum::Json(serde_json::json!({})),
1275 )),
1276 )
1277 .route(
1279 "/_index_template/{*path}",
1280 routing::any((
1281 HttpStatusCode::OK,
1282 elasticsearch::elasticsearch_headers(),
1283 axum::Json(serde_json::json!({})),
1284 )),
1285 )
1286 .route(
1289 "/_ingest/{*path}",
1290 routing::any((
1291 HttpStatusCode::OK,
1292 elasticsearch::elasticsearch_headers(),
1293 axum::Json(serde_json::json!({})),
1294 )),
1295 )
1296 .route(
1299 "/_nodes/{*path}",
1300 routing::any((
1301 HttpStatusCode::OK,
1302 elasticsearch::elasticsearch_headers(),
1303 axum::Json(serde_json::json!({})),
1304 )),
1305 )
1306 .route(
1309 "/logstash/{*path}",
1310 routing::any((
1311 HttpStatusCode::OK,
1312 elasticsearch::elasticsearch_headers(),
1313 axum::Json(serde_json::json!({})),
1314 )),
1315 )
1316 .route(
1317 "/_logstash/{*path}",
1318 routing::any((
1319 HttpStatusCode::OK,
1320 elasticsearch::elasticsearch_headers(),
1321 axum::Json(serde_json::json!({})),
1322 )),
1323 )
1324 .layer(middleware::from_fn_with_state(
1325 memory_limiter,
1326 memory_limit::decoded_body_accounting_middleware,
1327 ))
1328 .layer(ServiceBuilder::new().layer(RequestDecompressionLayer::new()))
1329 .layer(middleware::from_fn_with_state(
1330 BatchingProtocol::Elasticsearch,
1331 set_http_write_batching,
1332 ))
1333 .with_state(log_state)
1334 }
1335
1336 #[deprecated(since = "0.11.0", note = "Use `route_pipelines()` instead.")]
1337 fn route_log_deprecated<S>(
1338 log_state: LogState,
1339 memory_limiter: ServerMemoryLimiter,
1340 ) -> Router<S> {
1341 Router::new()
1342 .route("/logs", routing::post(event::log_ingester))
1343 .route(
1344 "/pipelines/{pipeline_name}",
1345 routing::get(event::query_pipeline),
1346 )
1347 .route(
1348 "/pipelines/{pipeline_name}",
1349 routing::post(event::add_pipeline),
1350 )
1351 .route(
1352 "/pipelines/{pipeline_name}",
1353 routing::delete(event::delete_pipeline),
1354 )
1355 .route("/pipelines/dryrun", routing::post(event::pipeline_dryrun))
1356 .layer(middleware::from_fn_with_state(
1357 memory_limiter,
1358 memory_limit::decoded_body_accounting_middleware,
1359 ))
1360 .layer(
1361 ServiceBuilder::new()
1362 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1363 )
1364 .layer(middleware::from_fn_with_state(
1365 BatchingProtocol::Logs,
1366 set_http_write_batching,
1367 ))
1368 .with_state(log_state)
1369 }
1370
1371 fn route_pipelines<S>(log_state: LogState, memory_limiter: ServerMemoryLimiter) -> Router<S> {
1372 Router::new()
1373 .route("/ingest", routing::post(event::log_ingester))
1374 .route(
1375 "/pipelines/{pipeline_name}",
1376 routing::get(event::query_pipeline),
1377 )
1378 .route(
1379 "/pipelines/{pipeline_name}/ddl",
1380 routing::get(event::query_pipeline_ddl),
1381 )
1382 .route(
1383 "/pipelines/{pipeline_name}",
1384 routing::post(event::add_pipeline),
1385 )
1386 .route(
1387 "/pipelines/{pipeline_name}",
1388 routing::delete(event::delete_pipeline),
1389 )
1390 .route("/pipelines/_dryrun", routing::post(event::pipeline_dryrun))
1391 .layer(middleware::from_fn_with_state(
1392 memory_limiter,
1393 memory_limit::decoded_body_accounting_middleware,
1394 ))
1395 .layer(
1396 ServiceBuilder::new()
1397 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1398 )
1399 .layer(middleware::from_fn_with_state(
1400 BatchingProtocol::Logs,
1401 set_http_write_batching,
1402 ))
1403 .with_state(log_state)
1404 }
1405
1406 fn route_sql<S>(api_state: ApiState) -> Router<S> {
1407 Router::new()
1408 .route(
1409 "/capabilities",
1410 routing::get(|| async {
1411 axum::Json(
1412 serde_json::json!({"metric_packed_import": 1, "metric_packed_export": 1}),
1413 )
1414 }),
1415 )
1416 .route(
1417 "/sql",
1418 routing::get(handler::sql).post(handler::sql).layer(
1419 middleware::from_fn_with_state(
1420 BatchingProtocol::HttpSql,
1421 set_http_write_batching,
1422 ),
1423 ),
1424 )
1425 .route(
1426 "/sql/parse",
1427 routing::get(handler::sql_parse).post(handler::sql_parse),
1428 )
1429 .route(
1430 "/sql/format",
1431 routing::get(handler::sql_format).post(handler::sql_format),
1432 )
1433 .route(
1434 "/promql",
1435 routing::get(handler::promql).post(handler::promql),
1436 )
1437 .route(
1438 "/sql/analyze/stream",
1439 routing::post(handler::sql_analyze_stream),
1440 )
1441 .with_state(api_state)
1442 }
1443
1444 fn route_logs<S>(log_handler: LogQueryHandlerRef) -> Router<S> {
1445 Router::new()
1446 .route("/logs", routing::get(logs::logs).post(logs::logs))
1447 .with_state(log_handler)
1448 }
1449
1450 pub fn route_prometheus<S>(prometheus_handler: PrometheusHandlerRef) -> Router<S> {
1454 Router::new()
1455 .route(
1456 "/format_query",
1457 routing::post(format_query).get(format_query),
1458 )
1459 .route("/status/buildinfo", routing::get(build_info_query))
1460 .route("/query", routing::post(instant_query).get(instant_query))
1461 .route("/query_range", routing::post(range_query).get(range_query))
1462 .route("/labels", routing::post(labels_query).get(labels_query))
1463 .route("/metadata", routing::get(metadata_query))
1464 .route("/series", routing::post(series_query).get(series_query))
1465 .route("/parse_query", routing::post(parse_query).get(parse_query))
1466 .route(
1467 "/label/{label_name}/values",
1468 routing::get(label_values_query),
1469 )
1470 .layer(ServiceBuilder::new().layer(CompressionLayer::new()))
1471 .with_state(prometheus_handler)
1472 }
1473
1474 fn route_prom<S>(state: PromStoreState) -> Router<S> {
1480 let write = routing::post(prom_store::remote_write);
1481 let write = if state.prom_store_with_metric_engine {
1482 write
1483 } else {
1484 write.layer(middleware::from_fn_with_state(
1485 BatchingProtocol::Prom,
1486 set_http_write_batching,
1487 ))
1488 };
1489 Router::new()
1490 .route("/read", routing::post(prom_store::remote_read))
1491 .route("/write", write)
1492 .with_state(state)
1493 }
1494
1495 fn route_influxdb<S>(
1496 influxdb_handler: InfluxdbLineProtocolHandlerRef,
1497 memory_limiter: ServerMemoryLimiter,
1498 ) -> Router<S> {
1499 Router::new()
1500 .route("/write", routing::post(influxdb_write_v1))
1501 .route("/api/v2/write", routing::post(influxdb_write_v2))
1502 .layer(middleware::from_fn_with_state(
1503 memory_limiter,
1504 memory_limit::decoded_body_accounting_middleware,
1505 ))
1506 .layer(
1507 ServiceBuilder::new()
1508 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1509 )
1510 .route("/ping", routing::get(influxdb_ping))
1511 .route("/health", routing::get(influxdb_health))
1512 .layer(middleware::from_fn_with_state(
1513 BatchingProtocol::Influxdb,
1514 set_http_write_batching,
1515 ))
1516 .with_state(influxdb_handler)
1517 }
1518
1519 fn route_opentsdb<S>(opentsdb_handler: OpentsdbProtocolHandlerRef) -> Router<S> {
1520 Router::new()
1521 .route("/api/put", routing::post(opentsdb::put))
1522 .layer(middleware::from_fn_with_state(
1523 BatchingProtocol::Opentsdb,
1524 set_http_write_batching,
1525 ))
1526 .with_state(opentsdb_handler)
1527 }
1528
1529 fn route_otlp<S>(
1530 otlp_handler: OpenTelemetryProtocolHandlerRef,
1531 with_metric_engine: bool,
1532 memory_limiter: ServerMemoryLimiter,
1533 ) -> Router<S> {
1534 Router::new()
1535 .route("/v1/metrics", routing::post(otlp::metrics))
1536 .route("/v1/traces", routing::post(otlp::traces))
1537 .route("/v1/logs", routing::post(otlp::logs))
1538 .layer(middleware::from_fn_with_state(
1539 memory_limiter,
1540 memory_limit::decoded_body_accounting_middleware,
1541 ))
1542 .layer(
1543 ServiceBuilder::new()
1544 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1545 )
1546 .layer(middleware::from_fn_with_state(
1547 BatchingProtocol::Otlp,
1548 set_http_write_batching,
1549 ))
1550 .with_state(OtlpState {
1551 with_metric_engine,
1552 handler: otlp_handler,
1553 })
1554 }
1555
1556 fn route_config<S>(state: GreptimeOptionsConfigState) -> Router<S> {
1557 Router::new()
1558 .route("/config", routing::get(handler::config))
1559 .with_state(state)
1560 }
1561
1562 fn route_jaeger<S>(handler: JaegerQueryHandlerRef) -> Router<S> {
1563 Router::new()
1564 .route("/api/services", routing::get(jaeger::handle_get_services))
1565 .route(
1566 "/api/services/{service_name}/operations",
1567 routing::get(jaeger::handle_get_operations_by_service),
1568 )
1569 .route(
1570 "/api/operations",
1571 routing::get(jaeger::handle_get_operations),
1572 )
1573 .route("/api/traces", routing::get(jaeger::handle_find_traces))
1574 .route(
1575 "/api/traces/{trace_id}",
1576 routing::get(jaeger::handle_get_trace),
1577 )
1578 .with_state(handler)
1579 }
1580
1581 #[cfg(feature = "dashboard")]
1582 fn route_dashboard<S>(
1583 handler: DashboardHandlerRef,
1584 memory_limiter: ServerMemoryLimiter,
1585 ) -> Router<S> {
1586 use crate::http::dashboard::{add_dashboard, delete_dashboard, list_dashboards};
1587
1588 Router::new()
1589 .route("/", routing::get(list_dashboards))
1590 .route("/{dashboard_name}", routing::post(add_dashboard))
1591 .route("/{dashboard_name}", routing::delete(delete_dashboard))
1592 .layer(middleware::from_fn_with_state(
1593 memory_limiter,
1594 memory_limit::decoded_body_accounting_middleware,
1595 ))
1596 .layer(
1597 ServiceBuilder::new()
1598 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1599 )
1600 .with_state(DashboardState { handler })
1601 }
1602
1603 #[cfg(not(feature = "dashboard"))]
1604 fn route_dashboard<S>(
1605 handler: DashboardHandlerRef,
1606 _memory_limiter: ServerMemoryLimiter,
1607 ) -> Router<S> {
1608 Router::new().with_state(DashboardState { handler })
1609 }
1610}
1611
1612pub const HTTP_SERVER: &str = "HTTP_SERVER";
1613pub const HTTP_API_SERVER: &str = "HTTP_API_SERVER";
1614
1615#[async_trait]
1616impl Server for HttpServer {
1617 async fn shutdown(&self) -> Result<()> {
1618 let mut shutdown_tx = self.shutdown_tx.lock().await;
1619 if let Some(tx) = shutdown_tx.take()
1620 && tx.send(()).is_err()
1621 {
1622 info!("Receiver dropped, the HTTP server has already exited");
1623 }
1624 info!("Shutdown {}", self.kind());
1625
1626 Ok(())
1627 }
1628
1629 async fn start(&mut self, listening: SocketAddr) -> Result<()> {
1630 let (tx, rx) = oneshot::channel();
1631 let serve = {
1632 let mut shutdown_tx = self.shutdown_tx.lock().await;
1633 ensure!(
1634 shutdown_tx.is_none(),
1635 AlreadyStartedSnafu {
1636 server: self.kind()
1637 }
1638 );
1639
1640 let app = self.build(self.make_app())?;
1641 let listener = tokio::net::TcpListener::bind(listening)
1642 .await
1643 .context(AddressBindSnafu { addr: listening })?
1644 .tap_io(|tcp_stream| {
1645 if let Err(e) = tcp_stream.set_nodelay(true) {
1646 error!(e; "Failed to set TCP_NODELAY on incoming connection");
1647 }
1648 });
1649 let serve = axum::serve(
1650 listener,
1651 app.into_make_service_with_connect_info::<SocketAddr>(),
1652 );
1653
1654 *shutdown_tx = Some(tx);
1671
1672 serve
1673 };
1674 let listening = serve.local_addr().context(InternalIoSnafu)?;
1675 info!("{} server is bound to {}", self.kind(), listening);
1676
1677 common_runtime::spawn_global(async move {
1678 if let Err(e) = serve
1679 .with_graceful_shutdown(rx.map(drop))
1680 .await
1681 .context(InternalIoSnafu)
1682 {
1683 error!(e; "Failed to shutdown http server");
1684 }
1685 });
1686
1687 self.bind_addr = Some(listening);
1688 Ok(())
1689 }
1690
1691 fn name(&self) -> &str {
1692 match self.kind {
1693 HttpServerKind::Api => HTTP_API_SERVER,
1694 HttpServerKind::Full => HTTP_SERVER,
1695 }
1696 }
1697
1698 fn bind_addr(&self) -> Option<SocketAddr> {
1699 self.bind_addr
1700 }
1701
1702 fn as_any(&self) -> &dyn std::any::Any {
1703 self
1704 }
1705}
1706
1707#[cfg(test)]
1708mod test {
1709 use std::future::pending;
1710 use std::io::Cursor;
1711 use std::sync::Arc;
1712
1713 use arrow_ipc::reader::StreamReader;
1714 use arrow_schema::DataType;
1715 use axum::http::StatusCode;
1716 use axum::routing::{get, post};
1717 use common_query::{Output, OutputData};
1718 use common_recordbatch::RecordBatches;
1719 use datafusion_expr::LogicalPlan;
1720 use datatypes::prelude::*;
1721 use datatypes::schema::{ColumnSchema, Schema};
1722 use datatypes::vectors::{StringVector, UInt32Vector};
1723 use header::constants::GREPTIME_DB_HEADER_TIMEOUT;
1724 use query::parser::PromQuery;
1725 use query::query_engine::DescribeResult;
1726 use session::context::QueryContextRef;
1727 use sql::statements::statement::Statement;
1728 use tokio::sync::mpsc;
1729 use tokio::time::Instant;
1730
1731 use crate::http::test_helpers::TestClient;
1732 use crate::http::*;
1733 use crate::prom_remote_write::validation::validate_label_name;
1734 use crate::query_handler::sql::SqlQueryHandler;
1735
1736 struct DummyInstance {
1737 _tx: mpsc::Sender<(String, Vec<u8>)>,
1738 }
1739
1740 #[async_trait]
1741 impl SqlQueryHandler for DummyInstance {
1742 async fn do_query(&self, _: &str, _: QueryContextRef) -> Vec<Result<Output>> {
1743 unimplemented!()
1744 }
1745
1746 async fn do_analyze_stream_query(&self, _: &str, _: QueryContextRef) -> Result<Output> {
1747 let stream = common_recordbatch::RecordBatches::empty().as_stream();
1748 Ok(Output::new(OutputData::Stream(stream), Default::default()))
1749 }
1750
1751 async fn do_promql_query(&self, _: &PromQuery, _: QueryContextRef) -> Vec<Result<Output>> {
1752 unimplemented!()
1753 }
1754
1755 async fn do_exec_plan(
1756 &self,
1757 _plan: LogicalPlan,
1758 _stmt: Option<Statement>,
1759 _query_ctx: QueryContextRef,
1760 ) -> Result<Output> {
1761 unimplemented!()
1762 }
1763
1764 async fn do_describe(
1765 &self,
1766 _stmt: sql::statements::statement::Statement,
1767 _query_ctx: QueryContextRef,
1768 ) -> Result<Option<DescribeResult>> {
1769 unimplemented!()
1770 }
1771
1772 async fn is_valid_schema(&self, _catalog: &str, _schema: &str) -> Result<bool> {
1773 Ok(true)
1774 }
1775 }
1776
1777 async fn forever() {
1778 pending().await
1779 }
1780
1781 fn make_test_app(tx: mpsc::Sender<(String, Vec<u8>)>) -> Router {
1782 make_test_app_custom(tx, HttpOptions::default())
1783 }
1784
1785 fn make_test_app_custom(tx: mpsc::Sender<(String, Vec<u8>)>, options: HttpOptions) -> Router {
1786 let instance = Arc::new(DummyInstance { _tx: tx });
1787 let server = HttpServerBuilder::new(options)
1788 .with_sql_handler(instance.clone())
1789 .build();
1790 let app = server
1791 .make_app()
1792 .route("/test/timeout", get(forever))
1793 .route("/v1/prometheus/write", post(forever));
1794 server.build(app).unwrap()
1795 }
1796
1797 fn make_split_builder() -> HttpServerBuilder {
1798 let (tx, _rx) = mpsc::channel(100);
1799 let instance = Arc::new(DummyInstance { _tx: tx });
1800 let options = HttpOptions {
1802 enable_api_server: true,
1803 ..HttpOptions::default()
1804 };
1805 HttpServerBuilder::new(options)
1806 .with_sql_handler(instance)
1807 .with_metrics_handler(MetricsHandler)
1808 .with_greptime_config_options("dummy = \"value\"".to_string())
1809 }
1810
1811 #[tokio::test]
1812 pub async fn test_http_api_options_defaults() {
1813 let opts = HttpOptions::default();
1814 assert!(!opts.enable_api_server);
1816 assert_eq!(opts.api_server_addr, "127.0.0.1:4006");
1817 }
1818
1819 #[tokio::test]
1820 pub async fn test_build_serves_all_routes() {
1821 let server = make_split_builder().build();
1825 assert_eq!(server.name(), HTTP_SERVER);
1826
1827 let app = server.build(server.make_app()).unwrap();
1828 let client = TestClient::new(app).await;
1829
1830 for path in ["/v1/health", "/health", "/status", "/metrics", "/config"] {
1831 let res = client.get(path).send().await;
1832 assert_eq!(
1833 res.status(),
1834 StatusCode::OK,
1835 "internal/full server should serve {path}"
1836 );
1837 }
1838 }
1839
1840 #[tokio::test]
1841 pub async fn test_build_servers_separates_api_and_internal_routes() {
1842 let (internal, api) = make_split_builder().build_servers();
1845 let api = api.expect("API server is explicitly enabled in make_split_builder");
1846 assert_eq!(internal.name(), HTTP_SERVER);
1847 assert_eq!(api.name(), HTTP_API_SERVER);
1848
1849 let internal_app = internal.build(internal.make_app()).unwrap();
1850 let api_app = api.build(api.make_app()).unwrap();
1851
1852 let internal_client = TestClient::new(internal_app).await;
1853 let api_client = TestClient::new(api_app).await;
1854
1855 assert_eq!(
1857 internal_client.get("/v1/health").send().await.status(),
1858 StatusCode::OK
1859 );
1860 assert_eq!(
1861 api_client.get("/v1/health").send().await.status(),
1862 StatusCode::OK
1863 );
1864
1865 for path in ["/health", "/status", "/metrics", "/config"] {
1867 assert_eq!(
1868 internal_client.get(path).send().await.status(),
1869 StatusCode::OK,
1870 "internal/full server should serve {path}"
1871 );
1872 assert_eq!(
1874 api_client.get(path).send().await.status(),
1875 StatusCode::NOT_FOUND,
1876 "API server should NOT serve {path}"
1877 );
1878 }
1879 }
1880
1881 #[test]
1882 fn test_build_servers_api_inherits_http_options() {
1883 let http_opts = HttpOptions {
1885 timeout: Duration::from_secs(42),
1886 body_limit: ReadableSize::mb(128),
1887 cors_allowed_origins: vec!["https://example.com".to_string()],
1888 enable_api_server: true,
1889 ..HttpOptions::default()
1890 };
1891 let (internal, api) = HttpServerBuilder::new(http_opts.clone()).build_servers();
1892 let api = api.expect("API server is explicitly enabled");
1893
1894 assert_eq!(internal.options.addr, http_opts.addr);
1896 assert_eq!(api.options.addr, "127.0.0.1:4006");
1897 assert_eq!(api.options.timeout, http_opts.timeout);
1899 assert_eq!(api.options.body_limit, http_opts.body_limit);
1900 assert_eq!(
1901 api.options.cors_allowed_origins,
1902 http_opts.cors_allowed_origins
1903 );
1904 }
1905
1906 #[test]
1907 fn test_is_api_listener_path() {
1908 assert!(is_api_listener_path("/v1"));
1910 assert!(is_api_listener_path("/v1/"));
1911 assert!(is_api_listener_path("/v1/sql"));
1912 assert!(!is_api_listener_path("/v10/sql"));
1913 assert!(!is_api_listener_path("/v1-internal"));
1914 assert!(is_api_listener_path("/dashboard"));
1916 assert!(is_api_listener_path("/dashboard/app.js"));
1917 assert!(!is_api_listener_path("/dashboard-admin"));
1918 assert!(!is_api_listener_path("/metrics"));
1920 assert!(!is_api_listener_path("/status/plugin"));
1921 assert!(!is_api_listener_path("/health"));
1922 }
1923
1924 #[tokio::test]
1925 async fn packed_capability_requires_auth_on_full_and_api_listeners() {
1926 let (tx, _rx) = mpsc::channel(1);
1927 let provider =
1928 auth::static_user_provider_from_option("static_user_provider:cmd:user=password")
1929 .unwrap();
1930 let (full, api) = HttpServerBuilder::new(HttpOptions {
1931 enable_api_server: true,
1932 ..Default::default()
1933 })
1934 .with_sql_handler(Arc::new(DummyInstance { _tx: tx }))
1935 .with_user_provider(Arc::new(provider))
1936 .build_servers();
1937 for server in [full, api.unwrap()] {
1938 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
1939 assert_eq!(
1940 client.get("/v1/capabilities").send().await.status(),
1941 StatusCode::UNAUTHORIZED
1942 );
1943 let response = client
1944 .get("/v1/capabilities")
1945 .header("Authorization", "Basic dXNlcjpwYXNzd29yZA==")
1946 .send()
1947 .await;
1948 assert_eq!(response.status(), StatusCode::OK);
1949 assert_eq!(
1950 response.json::<serde_json::Value>().await,
1951 serde_json::json!({"metric_packed_import": 1, "metric_packed_export": 1})
1952 );
1953 }
1954 }
1955
1956 #[tokio::test]
1957 pub async fn test_extra_router_respects_api_surface() {
1958 let (tx, _rx) = mpsc::channel(100);
1964 let instance = Arc::new(DummyInstance { _tx: tx });
1965 let options = HttpOptions {
1966 enable_api_server: true,
1967 ..HttpOptions::default()
1968 };
1969 let builder = HttpServerBuilder::new(options)
1970 .with_sql_handler(instance)
1971 .with_extra_router(
1972 Router::new()
1973 .route("/status/plugin", routing::get(|| async { "ok" }))
1974 .route("/v1/plugin", routing::get(|| async { "ok" })),
1975 );
1976 let (full, api) = builder.build_servers();
1977 let api = api.expect("API server is explicitly enabled");
1978
1979 let full_client = TestClient::new(full.build(full.make_app()).unwrap()).await;
1980 let api_client = TestClient::new(api.build(api.make_app()).unwrap()).await;
1981
1982 assert_eq!(
1984 full_client.get("/status/plugin").send().await.status(),
1985 StatusCode::OK
1986 );
1987 assert_eq!(
1989 api_client.get("/status/plugin").send().await.status(),
1990 StatusCode::NOT_FOUND
1991 );
1992
1993 assert_eq!(
1995 full_client.get("/v1/plugin").send().await.status(),
1996 StatusCode::OK
1997 );
1998 assert_eq!(
1999 api_client.get("/v1/plugin").send().await.status(),
2000 StatusCode::OK
2001 );
2002
2003 assert_eq!(
2005 api_client.get("/v10/plugin").send().await.status(),
2006 StatusCode::NOT_FOUND
2007 );
2008 }
2009
2010 #[test]
2011 fn test_build_servers_api_disabled_by_default() {
2012 let (_internal, api) = HttpServerBuilder::new(HttpOptions::default()).build_servers();
2015 assert!(api.is_none());
2016 }
2017
2018 #[tokio::test]
2019 pub async fn test_cors() {
2020 let (tx, _rx) = mpsc::channel(100);
2022 let app = make_test_app(tx);
2023 let client = TestClient::new(app).await;
2024
2025 let res = client.get("/health").send().await;
2026
2027 assert_eq!(res.status(), StatusCode::OK);
2028 assert_eq!(
2029 res.headers()
2030 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2031 .expect("expect cors header origin"),
2032 "*"
2033 );
2034
2035 let res = client.get("/v1/health").send().await;
2036
2037 assert_eq!(res.status(), StatusCode::OK);
2038 assert_eq!(
2039 res.headers()
2040 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2041 .expect("expect cors header origin"),
2042 "*"
2043 );
2044
2045 let res = client
2046 .options("/health")
2047 .header("Access-Control-Request-Headers", "x-greptime-auth")
2048 .header("Access-Control-Request-Method", "DELETE")
2049 .header("Origin", "https://example.com")
2050 .send()
2051 .await;
2052 assert_eq!(res.status(), StatusCode::OK);
2053 assert_eq!(
2054 res.headers()
2055 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2056 .expect("expect cors header origin"),
2057 "*"
2058 );
2059 assert_eq!(
2060 res.headers()
2061 .get(http::header::ACCESS_CONTROL_ALLOW_HEADERS)
2062 .expect("expect cors header headers"),
2063 "*"
2064 );
2065 assert_eq!(
2066 res.headers()
2067 .get(http::header::ACCESS_CONTROL_ALLOW_METHODS)
2068 .expect("expect cors header methods"),
2069 "GET,POST,PUT,DELETE,HEAD"
2070 );
2071 }
2072
2073 #[tokio::test]
2074 pub async fn test_cors_custom_origins() {
2075 let (tx, _rx) = mpsc::channel(100);
2077 let origin = "https://example.com";
2078
2079 let options = HttpOptions {
2080 cors_allowed_origins: vec![origin.to_string()],
2081 ..Default::default()
2082 };
2083
2084 let app = make_test_app_custom(tx, options);
2085 let client = TestClient::new(app).await;
2086
2087 let res = client.get("/health").header("Origin", origin).send().await;
2088
2089 assert_eq!(res.status(), StatusCode::OK);
2090 assert_eq!(
2091 res.headers()
2092 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2093 .expect("expect cors header origin"),
2094 origin
2095 );
2096
2097 let res = client
2098 .get("/health")
2099 .header("Origin", "https://notallowed.com")
2100 .send()
2101 .await;
2102
2103 assert_eq!(res.status(), StatusCode::OK);
2104 assert!(
2105 !res.headers()
2106 .contains_key(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2107 );
2108 }
2109
2110 #[tokio::test]
2111 pub async fn test_cors_disabled() {
2112 let (tx, _rx) = mpsc::channel(100);
2114
2115 let options = HttpOptions {
2116 enable_cors: false,
2117 ..Default::default()
2118 };
2119
2120 let app = make_test_app_custom(tx, options);
2121 let client = TestClient::new(app).await;
2122
2123 let res = client.get("/health").send().await;
2124
2125 assert_eq!(res.status(), StatusCode::OK);
2126 assert!(
2127 !res.headers()
2128 .contains_key(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2129 );
2130 }
2131
2132 #[test]
2133 fn test_http_options_default() {
2134 let default = HttpOptions::default();
2135 assert_eq!("127.0.0.1:4000".to_string(), default.addr);
2136 assert_eq!(Duration::from_secs(0), default.timeout)
2137 }
2138
2139 #[tokio::test]
2140 async fn test_http_options_legacy_analyze_stream_config_is_ignored() {
2141 let options: HttpOptions = serde_json::from_value(serde_json::json!({
2142 "addr": "127.0.0.1:4000",
2143 "timeout": "0s",
2144 "body_limit": "64MiB",
2145 "cors_allowed_origins": [],
2146 "enable_cors": true,
2147 "experimental_enable_explain_analyze_stream": false,
2148 "enable_api_server": false,
2149 "api_server_addr": "127.0.0.1:4006"
2150 }))
2151 .unwrap();
2152 let serialized = serde_json::to_string(&options).unwrap();
2153 assert!(!serialized.contains("experimental_enable_explain_analyze_stream"));
2154
2155 let (tx, _rx) = mpsc::channel(100);
2156 let app = make_test_app_custom(tx, options);
2157 let client = TestClient::new(app).await;
2158 let response = client
2159 .post("/v1/sql/analyze/stream")
2160 .form(&handler::SqlQuery {
2161 sql: Some("EXPLAIN ANALYZE VERBOSE SELECT 1".to_string()),
2162 ..Default::default()
2163 })
2164 .send()
2165 .await;
2166 assert_ne!(response.status(), StatusCode::NOT_FOUND);
2167 }
2168
2169 #[tokio::test]
2170 async fn test_http_server_request_timeout() {
2171 common_telemetry::init_default_ut_logging();
2172
2173 let (tx, _rx) = mpsc::channel(100);
2174 let options = HttpOptions {
2175 timeout: Duration::from_millis(10),
2176 ..Default::default()
2177 };
2178 let app = make_test_app_custom(tx, options);
2179 let client = TestClient::new(app).await;
2180 let res = client.get("/test/timeout").send().await;
2181 assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
2182
2183 let res = client.post("/v1/prometheus/write").send().await;
2184 assert_eq!(res.status(), StatusCode::GATEWAY_TIMEOUT);
2185
2186 let now = Instant::now();
2187 let res = client
2188 .get("/test/timeout")
2189 .header(GREPTIME_DB_HEADER_TIMEOUT, "20ms")
2190 .send()
2191 .await;
2192 assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
2193 let elapsed = now.elapsed();
2194 assert!(elapsed > Duration::from_millis(15));
2195
2196 tokio::time::timeout(
2197 Duration::from_millis(15),
2198 client
2199 .get("/test/timeout")
2200 .header(GREPTIME_DB_HEADER_TIMEOUT, "0s")
2201 .send(),
2202 )
2203 .await
2204 .unwrap_err();
2205
2206 tokio::time::timeout(
2207 Duration::from_millis(15),
2208 client
2209 .get("/test/timeout")
2210 .header(
2211 GREPTIME_DB_HEADER_TIMEOUT,
2212 humantime::format_duration(Duration::default()).to_string(),
2213 )
2214 .send(),
2215 )
2216 .await
2217 .unwrap_err();
2218 }
2219
2220 #[tokio::test]
2221 async fn test_schema_for_empty_response() {
2222 let column_schemas = vec![
2223 ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
2224 ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
2225 ];
2226 let schema = Arc::new(Schema::new(column_schemas));
2227
2228 let recordbatches = RecordBatches::try_new(schema.clone(), vec![]).unwrap();
2229 let outputs = vec![Ok(Output::new_with_record_batches(recordbatches))];
2230
2231 let json_resp = GreptimedbV1Response::from_output(outputs).await;
2232 if let HttpResponse::GreptimedbV1(json_resp) = json_resp {
2233 let json_output = &json_resp.output[0];
2234 if let GreptimeQueryOutput::Records(r) = json_output {
2235 assert_eq!(r.num_rows(), 0);
2236 assert_eq!(r.num_cols(), 2);
2237 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2238 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2239 } else {
2240 panic!("invalid output type");
2241 }
2242 } else {
2243 panic!("invalid format")
2244 }
2245 }
2246
2247 #[tokio::test]
2248 async fn test_recordbatches_conversion() {
2249 let column_schemas = vec![
2250 ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
2251 ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
2252 ];
2253 let schema = Arc::new(Schema::new(column_schemas));
2254 let columns: Vec<VectorRef> = vec![
2255 Arc::new(UInt32Vector::from_slice(vec![1, 2, 3, 4])),
2256 Arc::new(StringVector::from(vec![
2257 None,
2258 Some("hello"),
2259 Some("greptime"),
2260 None,
2261 ])),
2262 ];
2263 let recordbatch = RecordBatch::new(schema.clone(), columns).unwrap();
2264
2265 for format in [
2266 ResponseFormat::GreptimedbV1,
2267 ResponseFormat::InfluxdbV1,
2268 ResponseFormat::Csv(true, true),
2269 ResponseFormat::Table,
2270 ResponseFormat::Arrow,
2271 ResponseFormat::Json,
2272 ResponseFormat::Null,
2273 ] {
2274 let recordbatches =
2275 RecordBatches::try_new(schema.clone(), vec![recordbatch.clone()]).unwrap();
2276 let outputs = vec![Ok(Output::new_with_record_batches(recordbatches))];
2277 let json_resp = match format {
2278 ResponseFormat::Arrow => ArrowResponse::from_output(outputs, None).await,
2279 ResponseFormat::Csv(with_names, with_types) => {
2280 CsvResponse::from_output(outputs, with_names, with_types).await
2281 }
2282 ResponseFormat::Table => TableResponse::from_output(outputs).await,
2283 ResponseFormat::GreptimedbV1 => GreptimedbV1Response::from_output(outputs).await,
2284 ResponseFormat::InfluxdbV1 => InfluxdbV1Response::from_output(outputs, None).await,
2285 ResponseFormat::Json => JsonResponse::from_output(outputs).await,
2286 ResponseFormat::Null => NullResponse::from_output(outputs).await,
2287 };
2288
2289 match json_resp {
2290 HttpResponse::GreptimedbV1(resp) => {
2291 let json_output = &resp.output[0];
2292 if let GreptimeQueryOutput::Records(r) = json_output {
2293 assert_eq!(r.num_rows(), 4);
2294 assert_eq!(r.num_cols(), 2);
2295 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2296 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2297 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2298 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2299 } else {
2300 panic!("invalid output type");
2301 }
2302 }
2303 HttpResponse::InfluxdbV1(resp) => {
2304 let json_output = &resp.results()[0];
2305 assert_eq!(json_output.num_rows(), 4);
2306 assert_eq!(json_output.num_cols(), 2);
2307 assert_eq!(json_output.series[0].columns.clone()[0], "numbers");
2308 assert_eq!(
2309 json_output.series[0].values[0][0],
2310 serde_json::Value::from(1)
2311 );
2312 assert_eq!(json_output.series[0].values[0][1], serde_json::Value::Null);
2313 }
2314 HttpResponse::Csv(resp) => {
2315 let output = &resp.output()[0];
2316 if let GreptimeQueryOutput::Records(r) = output {
2317 assert_eq!(r.num_rows(), 4);
2318 assert_eq!(r.num_cols(), 2);
2319 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2320 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2321 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2322 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2323 } else {
2324 panic!("invalid output type");
2325 }
2326 }
2327
2328 HttpResponse::Table(resp) => {
2329 let output = &resp.output()[0];
2330 if let GreptimeQueryOutput::Records(r) = output {
2331 assert_eq!(r.num_rows(), 4);
2332 assert_eq!(r.num_cols(), 2);
2333 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2334 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2335 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2336 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2337 } else {
2338 panic!("invalid output type");
2339 }
2340 }
2341
2342 HttpResponse::Arrow(resp) => {
2343 let output = resp.data;
2344 let mut reader = StreamReader::try_new(Cursor::new(output), None)
2345 .expect("Arrow reader error");
2346 let schema = reader.schema();
2347 assert_eq!(schema.fields[0].name(), "numbers");
2348 assert_eq!(schema.fields[0].data_type(), &DataType::UInt32);
2349 assert_eq!(schema.fields[1].name(), "strings");
2350 assert_eq!(schema.fields[1].data_type(), &DataType::Utf8);
2351
2352 let rb = reader.next().unwrap().expect("read record batch failed");
2353 assert_eq!(rb.num_columns(), 2);
2354 assert_eq!(rb.num_rows(), 4);
2355 }
2356
2357 HttpResponse::Json(resp) => {
2358 let output = &resp.output()[0];
2359 if let GreptimeQueryOutput::Records(r) = output {
2360 assert_eq!(r.num_rows(), 4);
2361 assert_eq!(r.num_cols(), 2);
2362 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2363 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2364 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2365 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2366 } else {
2367 panic!("invalid output type");
2368 }
2369 }
2370
2371 HttpResponse::Null(resp) => {
2372 assert_eq!(resp.rows(), 4);
2373 }
2374
2375 HttpResponse::Error(err) => unreachable!("{err:?}"),
2376 }
2377 }
2378 }
2379
2380 #[test]
2381 fn test_response_format_misc() {
2382 assert_eq!(ResponseFormat::default(), ResponseFormat::GreptimedbV1);
2383 assert_eq!(ResponseFormat::parse("arrow"), Some(ResponseFormat::Arrow));
2384 assert_eq!(
2385 ResponseFormat::parse("csv"),
2386 Some(ResponseFormat::Csv(false, false))
2387 );
2388 assert_eq!(
2389 ResponseFormat::parse("csvwithnames"),
2390 Some(ResponseFormat::Csv(true, false))
2391 );
2392 assert_eq!(
2393 ResponseFormat::parse("csvwithnamesandtypes"),
2394 Some(ResponseFormat::Csv(true, true))
2395 );
2396 assert_eq!(ResponseFormat::parse("table"), Some(ResponseFormat::Table));
2397 assert_eq!(
2398 ResponseFormat::parse("greptimedb_v1"),
2399 Some(ResponseFormat::GreptimedbV1)
2400 );
2401 assert_eq!(
2402 ResponseFormat::parse("influxdb_v1"),
2403 Some(ResponseFormat::InfluxdbV1)
2404 );
2405 assert_eq!(ResponseFormat::parse("json"), Some(ResponseFormat::Json));
2406 assert_eq!(ResponseFormat::parse("null"), Some(ResponseFormat::Null));
2407
2408 assert_eq!(ResponseFormat::parse("invalid"), None);
2410 assert_eq!(ResponseFormat::parse(""), None);
2411 assert_eq!(ResponseFormat::parse("CSV"), None); assert_eq!(ResponseFormat::Arrow.as_str(), "arrow");
2415 assert_eq!(ResponseFormat::Csv(false, false).as_str(), "csv");
2416 assert_eq!(ResponseFormat::Csv(true, true).as_str(), "csv");
2417 assert_eq!(ResponseFormat::Table.as_str(), "table");
2418 assert_eq!(ResponseFormat::GreptimedbV1.as_str(), "greptimedb_v1");
2419 assert_eq!(ResponseFormat::InfluxdbV1.as_str(), "influxdb_v1");
2420 assert_eq!(ResponseFormat::Json.as_str(), "json");
2421 assert_eq!(ResponseFormat::Null.as_str(), "null");
2422 assert_eq!(ResponseFormat::default().as_str(), "greptimedb_v1");
2423 }
2424
2425 #[test]
2426 fn test_decode_label_name_strict() {
2427 let strict = PromValidationMode::Strict;
2428
2429 assert!(strict.decode_label_name(b"__name__").is_ok());
2431 assert!(strict.decode_label_name(b"job").is_ok());
2432 assert!(strict.decode_label_name(b"instance").is_ok());
2433 assert!(strict.decode_label_name(b"_private").is_ok());
2434 assert!(strict.decode_label_name(b"label_with_underscores").is_ok());
2435 assert!(strict.decode_label_name(b"abc123").is_ok());
2436 assert!(strict.decode_label_name(b"A").is_ok());
2437 assert!(strict.decode_label_name(b"_").is_ok());
2438
2439 assert!(strict.decode_label_name(b"0abc").is_err());
2441 assert!(strict.decode_label_name(b"123").is_err());
2442
2443 assert!(strict.decode_label_name(b"label-name").is_err());
2445 assert!(strict.decode_label_name(b"label.name").is_err());
2446 assert!(strict.decode_label_name(b"label name").is_err());
2447 assert!(strict.decode_label_name(b"label/name").is_err());
2448
2449 assert!(strict.decode_label_name(b"").is_err());
2451
2452 assert!(strict.decode_label_name("ラベル".as_bytes()).is_err());
2454
2455 assert!(strict.decode_label_name(&[0xff, 0xfe]).is_err());
2457 }
2458
2459 #[test]
2460 fn test_decode_label_name_lossy() {
2461 let lossy = PromValidationMode::Lossy;
2462
2463 assert!(lossy.decode_label_name(b"__name__").is_ok());
2465 assert!(lossy.decode_label_name(b"label-name").is_err());
2466 assert!(lossy.decode_label_name(b"0abc").is_err());
2467
2468 assert!(lossy.decode_label_name(&[0xff, 0xfe]).is_err());
2470 }
2471
2472 #[test]
2473 fn test_decode_label_name_unchecked() {
2474 let unchecked = PromValidationMode::Unchecked;
2475
2476 assert!(unchecked.decode_label_name(b"__name__").is_ok());
2478 assert!(unchecked.decode_label_name(b"label-name").is_err());
2479 assert!(unchecked.decode_label_name(b"0abc").is_err());
2480 }
2481
2482 #[test]
2483 fn test_is_valid_prom_label_name_bytes() {
2484 assert!(validate_label_name(b"__name__"));
2485 assert!(validate_label_name(b"job"));
2486 assert!(validate_label_name(b"_"));
2487 assert!(validate_label_name(b"A"));
2488 assert!(validate_label_name(b"abc123"));
2489 assert!(validate_label_name(b"_leading_underscore"));
2490
2491 assert!(!validate_label_name(b""));
2492 assert!(!validate_label_name(b"0starts_with_digit"));
2493 assert!(!validate_label_name(b"has-dash"));
2494 assert!(!validate_label_name(b"has.dot"));
2495 assert!(!validate_label_name(b"has space"));
2496 assert!(!validate_label_name(&[0xff, 0xfe]));
2497 }
2498}
2499
2500#[cfg(test)]
2501mod batching_tests {
2502 use std::sync::{Arc, Mutex};
2503
2504 use axum::http::StatusCode;
2505 use common_query::Output;
2506 use session::context::QueryContextRef;
2507
2508 use crate::batcher::BatchingProtocol;
2509 use crate::error::Result as ServerResult;
2510 use crate::http::test_helpers::TestClient;
2511 use crate::http::{HttpOptions, HttpServerBuilder};
2512 use crate::influxdb::InfluxdbRequest;
2513 use crate::opentsdb::codec::DataPoint;
2514 use crate::query_handler::{InfluxdbLineProtocolHandler, OpentsdbProtocolHandler};
2515
2516 #[tokio::test]
2517 async fn test_batching_selectors_are_independent() {
2518 use axum::routing::post;
2519 use axum::{Extension, Json, Router, middleware};
2520 use session::context::{QueryContext, QueryContextBuilder};
2521
2522 use crate::http::{LogicalBatchingProtocols, set_http_write_batching};
2523 for table in [false, true] {
2524 for logical in [false, true] {
2525 let app = Router::new()
2526 .route(
2527 "/",
2528 post(|Extension(ctx): Extension<QueryContext>| async move {
2529 Json([ctx.batching_enabled(), ctx.logical_batching_enabled()])
2530 }),
2531 )
2532 .route_layer(middleware::from_fn_with_state(
2533 BatchingProtocol::Otlp,
2534 set_http_write_batching,
2535 ))
2536 .layer(Extension(QueryContextBuilder::default().build()))
2537 .layer(Extension(Arc::new(if table {
2538 vec![BatchingProtocol::Otlp]
2539 } else {
2540 vec![]
2541 })))
2542 .layer(Extension(LogicalBatchingProtocols(if logical {
2543 vec![BatchingProtocol::Otlp]
2544 } else {
2545 vec![]
2546 })));
2547 let client = TestClient::new(app).await;
2548 let actual: [bool; 2] = client.post("/").send().await.json().await;
2549 assert_eq!(actual, [table, logical]);
2550 }
2551 }
2552 }
2553
2554 #[derive(Default)]
2555 struct RecordingWriteHandler {
2556 selections: Mutex<Vec<bool>>,
2557 }
2558
2559 #[async_trait::async_trait]
2560 impl OpentsdbProtocolHandler for RecordingWriteHandler {
2561 async fn preflight(&self, _: &[DataPoint], _: QueryContextRef) -> ServerResult<()> {
2562 Ok(())
2563 }
2564
2565 async fn exec(&self, points: Vec<DataPoint>, ctx: QueryContextRef) -> ServerResult<usize> {
2566 self.selections.lock().unwrap().push(ctx.batching_enabled());
2567 Ok(points.len())
2568 }
2569 }
2570
2571 #[async_trait::async_trait]
2572 impl InfluxdbLineProtocolHandler for RecordingWriteHandler {
2573 async fn exec(&self, _: InfluxdbRequest, ctx: QueryContextRef) -> ServerResult<Output> {
2574 self.selections.lock().unwrap().push(ctx.batching_enabled());
2575 Ok(Output::new_with_affected_rows(1))
2576 }
2577 }
2578
2579 #[tokio::test]
2580 async fn test_real_influx_and_opentsdb_routes_keep_selection() {
2581 for protocols in [
2582 vec![],
2583 vec![BatchingProtocol::Influxdb],
2584 vec![BatchingProtocol::Opentsdb],
2585 vec![BatchingProtocol::Influxdb, BatchingProtocol::Opentsdb],
2586 ] {
2587 let handler = Arc::new(RecordingWriteHandler::default());
2588 let influx_enabled = protocols.contains(&BatchingProtocol::Influxdb);
2589 let opentsdb_enabled = protocols.contains(&BatchingProtocol::Opentsdb);
2590 let server = HttpServerBuilder::new(HttpOptions::default())
2591 .with_batching_protocols(protocols)
2592 .with_influxdb_handler(handler.clone())
2593 .with_opentsdb_handler(handler.clone())
2594 .build();
2595 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
2596 for path in [
2597 "/v1/influxdb/write",
2598 "/v1/influxdb/api/v2/write?bucket=public",
2599 ] {
2600 assert_eq!(
2601 client
2602 .post(path)
2603 .body("cpu value=1 42")
2604 .send()
2605 .await
2606 .status(),
2607 StatusCode::NO_CONTENT
2608 );
2609 }
2610 let point =
2611 serde_json::json!({"metric":"cpu", "timestamp":42, "value":1, "tags":{"host":"a"}});
2612 for query in ["", "?summary", "?details"] {
2613 let response = client
2614 .post(&format!("/v1/opentsdb/api/put{query}"))
2615 .json(&point)
2616 .send()
2617 .await;
2618 assert_eq!(
2619 response.status(),
2620 if query.is_empty() {
2621 StatusCode::NO_CONTENT
2622 } else {
2623 StatusCode::OK
2624 }
2625 );
2626 }
2627 assert_eq!(
2628 *handler.selections.lock().unwrap(),
2629 vec![
2630 influx_enabled,
2631 influx_enabled,
2632 opentsdb_enabled,
2633 opentsdb_enabled,
2634 opentsdb_enabled
2635 ]
2636 );
2637 }
2638 }
2639}