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, query_exemplars, 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
115pub use memory_limit::decoded_body_accounting_middleware;
116use result::HttpOutputWriter;
117pub(crate) use timeout::DynamicTimeoutLayer;
118
119mod client_ip;
120use crate::prom_remote_write::validation::PromValidationMode;
121mod hints;
122mod read_preference;
123mod skip_wal;
124#[cfg(any(test, feature = "testing"))]
125pub mod test_helpers;
126
127pub const HTTP_API_VERSION: &str = "v1";
128pub const HTTP_API_PREFIX: &str = "/v1/";
129pub const HTTP_API_PREFIX_WITHOUT_TRAILING_SLASH: &str = "/v1";
130
131pub trait ExtraHttpRouterProvider: Send + Sync {
133 fn router(&self) -> Router;
135}
136
137pub type ExtraHttpRouterProviderRef = Arc<dyn ExtraHttpRouterProvider>;
138
139#[derive(Clone, Default)]
141pub struct ExtraHttpRouterProviders {
142 providers: Vec<ExtraHttpRouterProviderRef>,
143}
144
145impl ExtraHttpRouterProviders {
146 pub fn new() -> Self {
148 Self::default()
149 }
150
151 pub fn add(&mut self, provider: ExtraHttpRouterProviderRef) {
153 self.providers.push(provider);
154 }
155
156 pub fn iter(&self) -> impl Iterator<Item = &dyn ExtraHttpRouterProvider> {
158 self.providers.iter().map(|x| x.as_ref())
159 }
160}
161
162const DEFAULT_BODY_LIMIT: ReadableSize = ReadableSize::mb(64);
164const DEFAULT_HTTP_API_ADDR_PORT: u16 = 4006;
166
167pub const AUTHORIZATION_HEADER: &str = "x-greptime-auth";
169
170pub static PUBLIC_API_PREFIX: [&str; 5] = [
173 "/v1/auth/config",
174 "/v1/influxdb/ping",
175 "/v1/influxdb/health",
176 "/v1/health",
177 "/v1/splunk/services/collector/health",
178];
179
180#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
186pub(crate) enum HttpServerKind {
187 #[default]
190 Full,
191 Api,
193}
194
195#[derive(Default)]
196pub struct HttpServer {
197 router: StdMutex<Router>,
198 shutdown_tx: Mutex<Option<Sender<()>>>,
199 user_provider: Option<UserProviderRef>,
200 memory_limiter: ServerMemoryLimiter,
201
202 options: HttpOptions,
204 batching_protocols: Vec<BatchingProtocol>,
205 logical_batching_protocols: Vec<BatchingProtocol>,
206 bind_addr: Option<SocketAddr>,
207 kind: HttpServerKind,
209}
210
211pub(crate) fn is_namespace(path: &str, root: &str) -> bool {
215 path == root
216 || path
217 .strip_prefix(root)
218 .is_some_and(|suffix| suffix.starts_with('/'))
219}
220
221pub fn is_api_listener_path(path: &str) -> bool {
223 is_namespace(path, HTTP_API_PREFIX_WITHOUT_TRAILING_SLASH) || is_namespace(path, "/dashboard")
224}
225
226#[derive(Clone)]
227struct LogicalBatchingProtocols(Vec<BatchingProtocol>);
228
229pub async fn set_http_write_batching(
231 State(protocol): State<BatchingProtocol>,
232 mut req: Request,
233 next: Next,
234) -> Response {
235 let enabled = req
236 .extensions()
237 .get::<Arc<Vec<BatchingProtocol>>>()
238 .is_some_and(|protocols| protocols.contains(&protocol));
239 let logical_enabled = req
240 .extensions()
241 .get::<LogicalBatchingProtocols>()
242 .is_some_and(|protocols| protocols.0.contains(&protocol));
243 let body_memory_bytes = req
244 .extensions()
245 .get::<memory_limit::BodyMemoryAccounting>()
246 .map(memory_limit::BodyMemoryAccounting::reserved_bytes_counter);
247 if let Some(ctx) = req.extensions_mut().get_mut::<QueryContext>() {
248 ctx.set_batching_enabled(enabled);
249 ctx.set_logical_batching_enabled(logical_enabled);
250 if let Some(bytes) = body_memory_bytes {
251 ctx.set_body_memory_bytes(bytes);
252 }
253 }
254 next.run(req).await
255}
256
257async fn enforce_api_surface(req: Request, next: Next) -> Response {
261 if !is_api_listener_path(req.uri().path()) {
262 return HttpStatusCode::NOT_FOUND.into_response();
263 }
264 next.run(req).await
265}
266
267impl HttpServer {
268 fn kind(&self) -> &'static str {
270 match self.kind {
271 HttpServerKind::Api => "HTTP API",
272 HttpServerKind::Full => "HTTP",
273 }
274 }
275}
276
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
278#[serde(default)]
279pub struct HttpOptions {
280 pub addr: String,
281
282 #[serde(with = "humantime_serde")]
285 pub timeout: Duration,
286
287 #[serde(skip)]
288 pub disable_dashboard: bool,
289
290 pub body_limit: ReadableSize,
291
292 pub cors_allowed_origins: Vec<String>,
293
294 pub enable_cors: bool,
295
296 pub enable_api_server: bool,
301 pub api_server_addr: String,
304}
305
306impl Default for HttpOptions {
307 fn default() -> Self {
308 Self {
309 addr: "127.0.0.1:4000".to_string(),
310 timeout: Duration::from_secs(0),
311 disable_dashboard: false,
312 body_limit: DEFAULT_BODY_LIMIT,
313 cors_allowed_origins: Vec::new(),
314 enable_cors: true,
315 enable_api_server: false,
316 api_server_addr: format!("127.0.0.1:{}", DEFAULT_HTTP_API_ADDR_PORT),
317 }
318 }
319}
320
321#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
322pub struct ColumnSchema {
323 name: String,
324 data_type: String,
325}
326
327impl ColumnSchema {
328 pub fn new(name: String, data_type: String) -> ColumnSchema {
329 ColumnSchema { name, data_type }
330 }
331}
332
333#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
334pub struct OutputSchema {
335 column_schemas: Vec<ColumnSchema>,
336}
337
338impl OutputSchema {
339 pub fn new(columns: Vec<ColumnSchema>) -> OutputSchema {
340 OutputSchema {
341 column_schemas: columns,
342 }
343 }
344}
345
346impl From<SchemaRef> for OutputSchema {
347 fn from(schema: SchemaRef) -> OutputSchema {
348 OutputSchema {
349 column_schemas: schema
350 .column_schemas()
351 .iter()
352 .map(|cs| ColumnSchema {
353 name: cs.name.clone(),
354 data_type: cs.data_type.name(),
355 })
356 .collect(),
357 }
358 }
359}
360
361#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
362pub struct HttpRecordsOutput {
363 schema: OutputSchema,
364 rows: Vec<Vec<Value>>,
365 #[serde(default)]
368 total_rows: usize,
369
370 #[serde(skip_serializing_if = "HashMap::is_empty")]
372 #[serde(default)]
373 metrics: HashMap<String, Value>,
374}
375
376impl HttpRecordsOutput {
377 pub fn num_rows(&self) -> usize {
378 self.rows.len()
379 }
380
381 pub fn num_cols(&self) -> usize {
382 self.schema.column_schemas.len()
383 }
384
385 pub fn schema(&self) -> &OutputSchema {
386 &self.schema
387 }
388
389 pub fn rows(&self) -> &Vec<Vec<Value>> {
390 &self.rows
391 }
392}
393
394impl HttpRecordsOutput {
395 pub fn try_new(
396 schema: SchemaRef,
397 recordbatches: Vec<RecordBatch>,
398 ) -> std::result::Result<HttpRecordsOutput, Error> {
399 if recordbatches.is_empty() {
400 Ok(HttpRecordsOutput {
401 schema: OutputSchema::from(schema),
402 rows: vec![],
403 total_rows: 0,
404 metrics: Default::default(),
405 })
406 } else {
407 let num_rows = recordbatches.iter().map(|r| r.num_rows()).sum::<usize>();
408 let mut rows = Vec::with_capacity(num_rows);
409
410 for recordbatch in recordbatches {
411 let mut writer = HttpOutputWriter::new(schema.num_columns(), None);
412 writer.write(recordbatch, &mut rows)?;
413 }
414
415 Ok(HttpRecordsOutput {
416 schema: OutputSchema::from(schema),
417 total_rows: rows.len(),
418 rows,
419 metrics: Default::default(),
420 })
421 }
422 }
423}
424
425#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
426#[serde(rename_all = "lowercase")]
427pub enum GreptimeQueryOutput {
428 AffectedRows(usize),
429 Records(HttpRecordsOutput),
430}
431
432#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
434pub enum ResponseFormat {
435 Arrow,
436 Csv(bool, bool),
438 Table,
439 #[default]
440 GreptimedbV1,
441 InfluxdbV1,
442 Json,
443 Null,
444}
445
446impl ResponseFormat {
447 pub fn parse(s: &str) -> Option<Self> {
448 match s {
449 "arrow" => Some(ResponseFormat::Arrow),
450 "csv" => Some(ResponseFormat::Csv(false, false)),
451 "csvwithnames" => Some(ResponseFormat::Csv(true, false)),
452 "csvwithnamesandtypes" => Some(ResponseFormat::Csv(true, true)),
453 "table" => Some(ResponseFormat::Table),
454 "greptimedb_v1" => Some(ResponseFormat::GreptimedbV1),
455 "influxdb_v1" => Some(ResponseFormat::InfluxdbV1),
456 "json" => Some(ResponseFormat::Json),
457 "null" => Some(ResponseFormat::Null),
458 _ => None,
459 }
460 }
461
462 pub fn as_str(&self) -> &'static str {
463 match self {
464 ResponseFormat::Arrow => "arrow",
465 ResponseFormat::Csv(_, _) => "csv",
466 ResponseFormat::Table => "table",
467 ResponseFormat::GreptimedbV1 => "greptimedb_v1",
468 ResponseFormat::InfluxdbV1 => "influxdb_v1",
469 ResponseFormat::Json => "json",
470 ResponseFormat::Null => "null",
471 }
472 }
473}
474
475#[derive(Debug, Clone, Copy, PartialEq, Eq)]
476pub enum Epoch {
477 Nanosecond,
478 Microsecond,
479 Millisecond,
480 Second,
481}
482
483impl Epoch {
484 pub fn parse(s: &str) -> Option<Epoch> {
485 match s {
490 "ns" => Some(Epoch::Nanosecond),
491 "u" | "µ" => Some(Epoch::Microsecond),
492 "ms" => Some(Epoch::Millisecond),
493 "s" => Some(Epoch::Second),
494 _ => None, }
496 }
497
498 pub fn convert_timestamp(&self, ts: Timestamp) -> Option<Timestamp> {
499 match self {
500 Epoch::Nanosecond => ts.convert_to(TimeUnit::Nanosecond),
501 Epoch::Microsecond => ts.convert_to(TimeUnit::Microsecond),
502 Epoch::Millisecond => ts.convert_to(TimeUnit::Millisecond),
503 Epoch::Second => ts.convert_to(TimeUnit::Second),
504 }
505 }
506}
507
508impl Display for Epoch {
509 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
510 match self {
511 Epoch::Nanosecond => write!(f, "Epoch::Nanosecond"),
512 Epoch::Microsecond => write!(f, "Epoch::Microsecond"),
513 Epoch::Millisecond => write!(f, "Epoch::Millisecond"),
514 Epoch::Second => write!(f, "Epoch::Second"),
515 }
516 }
517}
518
519#[derive(Serialize, Deserialize, Debug)]
520pub enum HttpResponse {
521 Arrow(ArrowResponse),
522 Csv(CsvResponse),
523 Table(TableResponse),
524 Error(ErrorResponse),
525 GreptimedbV1(GreptimedbV1Response),
526 InfluxdbV1(InfluxdbV1Response),
527 Json(JsonResponse),
528 Null(NullResponse),
529}
530
531impl HttpResponse {
532 pub fn with_execution_time(self, execution_time: u64) -> Self {
533 match self {
534 HttpResponse::Arrow(resp) => resp.with_execution_time(execution_time).into(),
535 HttpResponse::Csv(resp) => resp.with_execution_time(execution_time).into(),
536 HttpResponse::Table(resp) => resp.with_execution_time(execution_time).into(),
537 HttpResponse::GreptimedbV1(resp) => resp.with_execution_time(execution_time).into(),
538 HttpResponse::InfluxdbV1(resp) => resp.with_execution_time(execution_time).into(),
539 HttpResponse::Json(resp) => resp.with_execution_time(execution_time).into(),
540 HttpResponse::Null(resp) => resp.with_execution_time(execution_time).into(),
541 HttpResponse::Error(resp) => resp.with_execution_time(execution_time).into(),
542 }
543 }
544
545 pub fn with_limit(self, limit: usize) -> Self {
546 match self {
547 HttpResponse::Csv(resp) => resp.with_limit(limit).into(),
548 HttpResponse::Table(resp) => resp.with_limit(limit).into(),
549 HttpResponse::GreptimedbV1(resp) => resp.with_limit(limit).into(),
550 HttpResponse::Json(resp) => resp.with_limit(limit).into(),
551 _ => self,
552 }
553 }
554}
555
556pub fn process_with_limit(
557 mut outputs: Vec<GreptimeQueryOutput>,
558 limit: usize,
559) -> Vec<GreptimeQueryOutput> {
560 outputs
561 .drain(..)
562 .map(|data| match data {
563 GreptimeQueryOutput::Records(mut records) => {
564 if records.rows.len() > limit {
565 records.rows.truncate(limit);
566 records.total_rows = limit;
567 }
568 GreptimeQueryOutput::Records(records)
569 }
570 _ => data,
571 })
572 .collect()
573}
574
575impl IntoResponse for HttpResponse {
576 fn into_response(self) -> Response {
577 match self {
578 HttpResponse::Arrow(resp) => resp.into_response(),
579 HttpResponse::Csv(resp) => resp.into_response(),
580 HttpResponse::Table(resp) => resp.into_response(),
581 HttpResponse::GreptimedbV1(resp) => resp.into_response(),
582 HttpResponse::InfluxdbV1(resp) => resp.into_response(),
583 HttpResponse::Json(resp) => resp.into_response(),
584 HttpResponse::Null(resp) => resp.into_response(),
585 HttpResponse::Error(resp) => resp.into_response(),
586 }
587 }
588}
589
590impl From<ArrowResponse> for HttpResponse {
591 fn from(value: ArrowResponse) -> Self {
592 HttpResponse::Arrow(value)
593 }
594}
595
596impl From<CsvResponse> for HttpResponse {
597 fn from(value: CsvResponse) -> Self {
598 HttpResponse::Csv(value)
599 }
600}
601
602impl From<TableResponse> for HttpResponse {
603 fn from(value: TableResponse) -> Self {
604 HttpResponse::Table(value)
605 }
606}
607
608impl From<ErrorResponse> for HttpResponse {
609 fn from(value: ErrorResponse) -> Self {
610 HttpResponse::Error(value)
611 }
612}
613
614impl From<GreptimedbV1Response> for HttpResponse {
615 fn from(value: GreptimedbV1Response) -> Self {
616 HttpResponse::GreptimedbV1(value)
617 }
618}
619
620impl From<InfluxdbV1Response> for HttpResponse {
621 fn from(value: InfluxdbV1Response) -> Self {
622 HttpResponse::InfluxdbV1(value)
623 }
624}
625
626impl From<JsonResponse> for HttpResponse {
627 fn from(value: JsonResponse) -> Self {
628 HttpResponse::Json(value)
629 }
630}
631
632impl From<NullResponse> for HttpResponse {
633 fn from(value: NullResponse) -> Self {
634 HttpResponse::Null(value)
635 }
636}
637
638#[derive(Clone)]
639pub struct ApiState {
640 pub sql_handler: ServerSqlQueryHandlerRef,
641}
642
643#[derive(Clone)]
644pub struct GreptimeOptionsConfigState {
645 pub greptime_config_options: String,
646}
647
648#[derive(Clone)]
649pub struct DashboardState {
650 pub handler: DashboardHandlerRef,
651}
652
653pub struct HttpServerBuilder {
654 options: HttpOptions,
655 batching_protocols: Vec<BatchingProtocol>,
656 logical_batching_protocols: Vec<BatchingProtocol>,
657 user_provider: Option<UserProviderRef>,
658 router: Router,
659 memory_limiter: ServerMemoryLimiter,
660}
661
662impl HttpServerBuilder {
663 pub fn new(options: HttpOptions) -> Self {
664 Self {
665 options,
666 batching_protocols: Vec::new(),
667 logical_batching_protocols: Vec::new(),
668 user_provider: None,
669 router: Router::new(),
670 memory_limiter: ServerMemoryLimiter::default(),
671 }
672 }
673
674 pub fn with_logical_batching_protocols(mut self, protocols: Vec<BatchingProtocol>) -> Self {
676 self.logical_batching_protocols = protocols;
677 self
678 }
679
680 pub fn with_batching_protocols(mut self, protocols: Vec<BatchingProtocol>) -> Self {
682 self.batching_protocols = protocols;
683 self
684 }
685
686 pub fn with_memory_limiter(mut self, limiter: ServerMemoryLimiter) -> Self {
688 self.memory_limiter = limiter;
689 self
690 }
691
692 pub fn with_sql_handler(self, sql_handler: ServerSqlQueryHandlerRef) -> Self {
693 let batch_body_limit = if self.options.body_limit.0 == 0 {
694 4 * 1024 * 1024
695 } else {
696 (self.options.body_limit.0 as usize).min(4 * 1024 * 1024)
697 };
698 let sql_router = HttpServer::route_sql(ApiState { sql_handler }, batch_body_limit);
699
700 Self {
701 router: self
702 .router
703 .nest(&format!("/{HTTP_API_VERSION}"), sql_router),
704 ..self
705 }
706 }
707
708 pub fn with_logs_handler(self, logs_handler: LogQueryHandlerRef) -> Self {
709 let logs_router = HttpServer::route_logs(logs_handler);
710
711 Self {
712 router: self
713 .router
714 .nest(&format!("/{HTTP_API_VERSION}"), logs_router),
715 ..self
716 }
717 }
718
719 pub fn with_opentsdb_handler(self, handler: OpentsdbProtocolHandlerRef) -> Self {
720 Self {
721 router: self.router.nest(
722 &format!("/{HTTP_API_VERSION}/opentsdb"),
723 HttpServer::route_opentsdb(handler),
724 ),
725 ..self
726 }
727 }
728
729 pub fn with_influxdb_handler(self, handler: InfluxdbLineProtocolHandlerRef) -> Self {
730 Self {
731 router: self.router.nest(
732 &format!("/{HTTP_API_VERSION}/influxdb"),
733 HttpServer::route_influxdb(handler, self.memory_limiter.clone()),
734 ),
735 ..self
736 }
737 }
738
739 pub fn with_prom_handler(
740 self,
741 handler: PromStoreProtocolHandlerRef,
742 pipeline_handler: Option<PipelineHandlerRef>,
743 prom_store_with_metric_engine: bool,
744 prom_validation_mode: PromValidationMode,
745 pending_rows_batcher: Option<Arc<LogicalTablePendingRowsBatcher>>,
746 ) -> Self {
747 let state = PromStoreState {
748 prom_store_handler: handler,
749 pipeline_handler,
750 prom_store_with_metric_engine,
751 prom_validation_mode,
752 pending_rows_batcher,
753 memory_limiter: self.memory_limiter.clone(),
754 };
755
756 Self {
757 router: self.router.nest(
758 &format!("/{HTTP_API_VERSION}/prometheus"),
759 HttpServer::route_prom(state),
760 ),
761 ..self
762 }
763 }
764
765 pub fn with_prometheus_handler(self, handler: PrometheusHandlerRef) -> Self {
766 Self {
767 router: self.router.nest(
768 &format!("/{HTTP_API_VERSION}/prometheus/api/v1"),
769 HttpServer::route_prometheus(handler),
770 ),
771 ..self
772 }
773 }
774
775 pub fn with_otlp_handler(
776 self,
777 handler: OpenTelemetryProtocolHandlerRef,
778 with_metric_engine: bool,
779 ) -> Self {
780 Self {
781 router: self.router.nest(
782 &format!("/{HTTP_API_VERSION}/otlp"),
783 HttpServer::route_otlp(handler, with_metric_engine, self.memory_limiter.clone()),
784 ),
785 ..self
786 }
787 }
788
789 pub fn with_user_provider(self, user_provider: UserProviderRef) -> Self {
790 Self {
791 user_provider: Some(user_provider),
792 ..self
793 }
794 }
795
796 pub fn with_metrics_handler(self, handler: MetricsHandler) -> Self {
797 Self {
798 router: self.router.merge(HttpServer::route_metrics(handler)),
799 ..self
800 }
801 }
802
803 pub fn with_log_ingest_handler(
804 self,
805 handler: PipelineHandlerRef,
806 validator: Option<LogValidatorRef>,
807 ingest_interceptor: Option<LogIngestInterceptorRef<Error>>,
808 ) -> Self {
809 let log_state = LogState {
810 log_handler: handler,
811 log_validator: validator,
812 ingest_interceptor,
813 };
814
815 let router = self.router.nest(
816 &format!("/{HTTP_API_VERSION}"),
817 HttpServer::route_pipelines(log_state.clone(), self.memory_limiter.clone()),
818 );
819 let router = router.nest(
821 &format!("/{HTTP_API_VERSION}/events"),
822 #[allow(deprecated)]
823 HttpServer::route_log_deprecated(log_state.clone(), self.memory_limiter.clone()),
824 );
825
826 let router = router.nest(
827 &format!("/{HTTP_API_VERSION}/loki"),
828 HttpServer::route_loki(log_state.clone(), self.memory_limiter.clone()),
829 );
830
831 let router = router.nest(
832 &format!("/{HTTP_API_VERSION}/elasticsearch"),
833 HttpServer::route_elasticsearch(log_state.clone(), self.memory_limiter.clone()),
834 );
835
836 let router = router.nest(
837 &format!("/{HTTP_API_VERSION}/elasticsearch/"),
838 Router::new()
839 .route("/", routing::get(elasticsearch::handle_get_version))
840 .with_state(log_state.clone()),
841 );
842
843 let router = router.nest(
844 &format!("/{HTTP_API_VERSION}/splunk"),
845 HttpServer::route_splunk(log_state, self.memory_limiter.clone()),
846 );
847
848 Self { router, ..self }
849 }
850
851 pub fn with_greptime_config_options(self, opts: String) -> Self {
852 let config_router = HttpServer::route_config(GreptimeOptionsConfigState {
853 greptime_config_options: opts,
854 });
855
856 Self {
857 router: self.router.merge(config_router),
858 ..self
859 }
860 }
861
862 pub fn with_jaeger_handler(self, handler: JaegerQueryHandlerRef) -> Self {
863 Self {
864 router: self.router.nest(
865 &format!("/{HTTP_API_VERSION}/jaeger"),
866 HttpServer::route_jaeger(handler),
867 ),
868 ..self
869 }
870 }
871
872 pub fn with_dashboard_handler(self, handler: DashboardHandlerRef) -> Self {
873 Self {
874 router: self.router.nest(
875 &format!("/{HTTP_API_VERSION}/dashboards"),
876 HttpServer::route_dashboard(handler, self.memory_limiter.clone()),
877 ),
878 ..self
879 }
880 }
881
882 pub fn with_extra_router(self, router: Router) -> Self {
883 Self {
884 router: self.router.merge(router),
885 ..self
886 }
887 }
888
889 pub fn add_layer<L>(self, layer: L) -> Self
890 where
891 L: Layer<Route> + Clone + Send + Sync + 'static,
892 L::Service: Service<Request> + Clone + Send + Sync + 'static,
893 <L::Service as Service<Request>>::Response: IntoResponse + 'static,
894 <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
895 <L::Service as Service<Request>>::Future: Send + 'static,
896 {
897 Self {
898 router: self.router.layer(layer),
899 ..self
900 }
901 }
902
903 pub fn build(self) -> HttpServer {
904 HttpServer {
905 options: self.options,
906 batching_protocols: self.batching_protocols.clone(),
907 logical_batching_protocols: self.logical_batching_protocols.clone(),
908 user_provider: self.user_provider,
909 shutdown_tx: Mutex::new(None),
910 router: StdMutex::new(self.router),
911 bind_addr: None,
912 memory_limiter: self.memory_limiter,
913 kind: HttpServerKind::Full,
914 }
915 }
916
917 pub fn build_servers(self) -> (HttpServer, Option<HttpServer>) {
936 let api_enabled = self.options.enable_api_server;
937 let api_addr = self.options.api_server_addr.clone();
938
939 let internal = HttpServer {
940 options: self.options,
941 batching_protocols: self.batching_protocols.clone(),
942 logical_batching_protocols: self.logical_batching_protocols.clone(),
943 user_provider: self.user_provider.clone(),
944 shutdown_tx: Mutex::new(None),
945 router: StdMutex::new(self.router.clone()),
946 bind_addr: None,
947 memory_limiter: self.memory_limiter.clone(),
948 kind: HttpServerKind::Full,
949 };
950
951 let api = if api_enabled {
952 let api_options = HttpOptions {
955 addr: api_addr,
956 ..internal.options.clone()
957 };
958 Some(HttpServer {
959 options: api_options,
960 batching_protocols: self.batching_protocols,
961 logical_batching_protocols: self.logical_batching_protocols,
962 user_provider: self.user_provider.clone(),
963 shutdown_tx: Mutex::new(None),
964 router: StdMutex::new(self.router),
965 bind_addr: None,
966 memory_limiter: self.memory_limiter,
967 kind: HttpServerKind::Api,
968 })
969 } else {
970 None
971 };
972
973 (internal, api)
974 }
975}
976
977impl HttpServer {
978 pub fn make_app(&self) -> Router {
988 let mut router = self.router.lock().unwrap().clone();
989 let auth_router = Router::new()
990 .route("/v1/auth/config", routing::get(authorize::auth_config))
991 .with_state(AuthState::new(self.user_provider.clone()));
992
993 router = router
994 .merge(auth_router)
995 .route(
996 &format!("/{HTTP_API_VERSION}/health"),
997 routing::get(handler::health).post(handler::health),
998 )
999 .route("/", routing::get(handler::index))
1000 .route(
1001 "/health",
1002 routing::get(handler::health).post(handler::health),
1003 )
1004 .route(
1005 "/ready",
1006 routing::get(handler::health).post(handler::health),
1007 )
1008 .route("/status", routing::get(handler::status));
1009
1010 #[cfg(feature = "dashboard")]
1013 {
1014 if !self.options.disable_dashboard {
1015 info!("Enable dashboard service at '/dashboard'");
1016 router = router.route(
1018 "/dashboard",
1019 routing::get(|uri: axum::http::uri::Uri| async move {
1020 let path = uri.path();
1021 let query = uri.query().map(|q| format!("?{}", q)).unwrap_or_default();
1022
1023 let new_uri = format!("{}/{}", path, query);
1024 axum::response::Redirect::permanent(&new_uri)
1025 }),
1026 );
1027
1028 router = router
1032 .route(
1033 "/dashboard/",
1034 routing::get(dashboard::static_handler).post(dashboard::static_handler),
1035 )
1036 .route(
1037 "/dashboard/{*x}",
1038 routing::get(dashboard::static_handler).post(dashboard::static_handler),
1039 );
1040 }
1041 }
1042
1043 router = router.route_layer(middleware::from_fn(http_metrics_layer));
1045
1046 router
1047 }
1048
1049 pub fn build(&self, router: Router) -> Result<Router> {
1052 let timeout_layer = ServiceBuilder::new().layer(
1053 DynamicTimeoutLayer::new(self.options.timeout)
1054 .with_status_code_fn(Self::request_timeout_status_code),
1055 );
1056 let body_limit_layer = if self.options.body_limit != ReadableSize(0) {
1057 Some(
1058 ServiceBuilder::new()
1059 .layer(DefaultBodyLimit::max(self.options.body_limit.0 as usize)),
1060 )
1061 } else {
1062 info!("HTTP server body limit is disabled");
1063 None
1064 };
1065 let cors_layer = if self.options.enable_cors {
1066 Some(
1067 CorsLayer::new()
1068 .allow_methods([
1069 Method::GET,
1070 Method::POST,
1071 Method::PUT,
1072 Method::DELETE,
1073 Method::HEAD,
1074 ])
1075 .allow_origin(cors_allow_origin(&self.options.cors_allowed_origins)?)
1076 .allow_headers(Any),
1077 )
1078 } else {
1079 info!("HTTP server cross-origin is disabled");
1080 None
1081 };
1082
1083 let router = router
1084 .layer(
1086 ServiceBuilder::new()
1087 .layer(TraceLayer::new_for_http().on_failure(()))
1090 .option_layer(cors_layer)
1091 .layer(timeout_layer)
1092 .option_layer(body_limit_layer)
1093 .layer(middleware::from_fn_with_state(
1095 self.memory_limiter.clone(),
1096 memory_limit::memory_limit_middleware,
1097 ))
1098 .layer(middleware::from_fn_with_state(
1100 AuthState::new(self.user_provider.clone()),
1101 authorize::check_http_auth,
1102 ))
1103 .layer(Extension(Arc::new(self.batching_protocols.clone())))
1104 .layer(Extension(LogicalBatchingProtocols(
1105 self.logical_batching_protocols.clone(),
1106 )))
1107 .layer(middleware::from_fn(hints::extract_hints))
1108 .layer(middleware::from_fn(client_ip::log_error_with_client_ip))
1109 .layer(middleware::from_fn(
1110 read_preference::extract_read_preference,
1111 ))
1112 .layer(middleware::from_fn(skip_wal::extract_skip_wal)),
1113 );
1114
1115 let debug_router = Router::new().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 let router = debug_router
1165 .layer(middleware::from_fn_with_state(
1166 AuthState::new(self.user_provider.clone()),
1167 authorize::check_http_auth,
1168 ))
1169 .merge(router);
1170
1171 if self.kind == HttpServerKind::Api {
1176 Ok(router.layer(middleware::from_fn(enforce_api_surface)))
1177 } else {
1178 Ok(router)
1179 }
1180 }
1181
1182 fn request_timeout_status_code(request: &Request) -> HttpStatusCode {
1183 if request.uri().path() == "/v1/prometheus/write" {
1184 HttpStatusCode::GATEWAY_TIMEOUT
1185 } else {
1186 HttpStatusCode::REQUEST_TIMEOUT
1187 }
1188 }
1189
1190 fn route_metrics<S>(metrics_handler: MetricsHandler) -> Router<S> {
1191 Router::new()
1192 .route("/metrics", routing::get(handler::metrics))
1193 .with_state(metrics_handler)
1194 }
1195
1196 fn route_loki<S>(log_state: LogState, memory_limiter: ServerMemoryLimiter) -> Router<S> {
1197 Router::new()
1198 .route("/api/v1/push", routing::post(loki::loki_ingest))
1199 .layer(middleware::from_fn_with_state(
1200 memory_limiter,
1201 memory_limit::decoded_body_accounting_middleware,
1202 ))
1203 .layer(
1204 ServiceBuilder::new()
1205 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1206 )
1207 .layer(middleware::from_fn_with_state(
1208 BatchingProtocol::Loki,
1209 set_http_write_batching,
1210 ))
1211 .with_state(log_state)
1212 }
1213
1214 fn route_splunk<S>(log_state: LogState, memory_limiter: ServerMemoryLimiter) -> Router<S> {
1215 Router::new()
1216 .route(
1217 "/services/collector/health",
1218 routing::get(splunk::handle_health),
1219 )
1220 .route(
1221 "/services/collector/health/1.0",
1222 routing::get(splunk::handle_health),
1223 )
1224 .route(
1227 "/services/collector/event",
1228 routing::post(splunk::handle_event),
1229 )
1230 .route("/services/collector", routing::post(splunk::handle_event))
1231 .route(
1232 "/services/collector/event/1.0",
1233 routing::post(splunk::handle_event),
1234 )
1235 .route("/services/collector/raw", routing::post(splunk::handle_raw))
1238 .route(
1239 "/services/collector/raw/1.0",
1240 routing::post(splunk::handle_raw),
1241 )
1242 .layer(middleware::from_fn_with_state(
1243 memory_limiter,
1244 memory_limit::decoded_body_accounting_middleware,
1245 ))
1246 .layer(
1247 ServiceBuilder::new()
1248 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1249 )
1250 .layer(middleware::from_fn_with_state(
1251 BatchingProtocol::Splunk,
1252 set_http_write_batching,
1253 ))
1254 .with_state(log_state)
1255 }
1256
1257 fn route_elasticsearch<S>(
1258 log_state: LogState,
1259 memory_limiter: ServerMemoryLimiter,
1260 ) -> Router<S> {
1261 Router::new()
1262 .route(
1264 "/",
1265 routing::head((HttpStatusCode::OK, elasticsearch::elasticsearch_headers())),
1266 )
1267 .route("/", routing::get(elasticsearch::handle_get_version))
1269 .route("/_license", routing::get(elasticsearch::handle_get_license))
1271 .route("/_bulk", routing::post(elasticsearch::handle_bulk_api))
1272 .route(
1273 "/{index}/_bulk",
1274 routing::post(elasticsearch::handle_bulk_api_with_index),
1275 )
1276 .route(
1278 "/_ilm/policy/{*path}",
1279 routing::any((
1280 HttpStatusCode::OK,
1281 elasticsearch::elasticsearch_headers(),
1282 axum::Json(serde_json::json!({})),
1283 )),
1284 )
1285 .route(
1287 "/_index_template/{*path}",
1288 routing::any((
1289 HttpStatusCode::OK,
1290 elasticsearch::elasticsearch_headers(),
1291 axum::Json(serde_json::json!({})),
1292 )),
1293 )
1294 .route(
1297 "/_ingest/{*path}",
1298 routing::any((
1299 HttpStatusCode::OK,
1300 elasticsearch::elasticsearch_headers(),
1301 axum::Json(serde_json::json!({})),
1302 )),
1303 )
1304 .route(
1307 "/_nodes/{*path}",
1308 routing::any((
1309 HttpStatusCode::OK,
1310 elasticsearch::elasticsearch_headers(),
1311 axum::Json(serde_json::json!({})),
1312 )),
1313 )
1314 .route(
1317 "/logstash/{*path}",
1318 routing::any((
1319 HttpStatusCode::OK,
1320 elasticsearch::elasticsearch_headers(),
1321 axum::Json(serde_json::json!({})),
1322 )),
1323 )
1324 .route(
1325 "/_logstash/{*path}",
1326 routing::any((
1327 HttpStatusCode::OK,
1328 elasticsearch::elasticsearch_headers(),
1329 axum::Json(serde_json::json!({})),
1330 )),
1331 )
1332 .layer(middleware::from_fn_with_state(
1333 memory_limiter,
1334 memory_limit::decoded_body_accounting_middleware,
1335 ))
1336 .layer(ServiceBuilder::new().layer(RequestDecompressionLayer::new()))
1337 .layer(middleware::from_fn_with_state(
1338 BatchingProtocol::Elasticsearch,
1339 set_http_write_batching,
1340 ))
1341 .with_state(log_state)
1342 }
1343
1344 #[deprecated(since = "0.11.0", note = "Use `route_pipelines()` instead.")]
1345 fn route_log_deprecated<S>(
1346 log_state: LogState,
1347 memory_limiter: ServerMemoryLimiter,
1348 ) -> Router<S> {
1349 Router::new()
1350 .route("/logs", routing::post(event::log_ingester))
1351 .route(
1352 "/pipelines/{pipeline_name}",
1353 routing::get(event::query_pipeline),
1354 )
1355 .route(
1356 "/pipelines/{pipeline_name}",
1357 routing::post(event::add_pipeline),
1358 )
1359 .route(
1360 "/pipelines/{pipeline_name}",
1361 routing::delete(event::delete_pipeline),
1362 )
1363 .route("/pipelines/dryrun", routing::post(event::pipeline_dryrun))
1364 .layer(middleware::from_fn_with_state(
1365 memory_limiter,
1366 memory_limit::decoded_body_accounting_middleware,
1367 ))
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_pipelines<S>(log_state: LogState, memory_limiter: ServerMemoryLimiter) -> Router<S> {
1380 Router::new()
1381 .route("/ingest", routing::post(event::log_ingester))
1382 .route(
1383 "/pipelines/{pipeline_name}",
1384 routing::get(event::query_pipeline),
1385 )
1386 .route(
1387 "/pipelines/{pipeline_name}/ddl",
1388 routing::get(event::query_pipeline_ddl),
1389 )
1390 .route(
1391 "/pipelines/{pipeline_name}",
1392 routing::post(event::add_pipeline),
1393 )
1394 .route(
1395 "/pipelines/{pipeline_name}",
1396 routing::delete(event::delete_pipeline),
1397 )
1398 .route("/pipelines/_dryrun", routing::post(event::pipeline_dryrun))
1399 .layer(middleware::from_fn_with_state(
1400 memory_limiter,
1401 memory_limit::decoded_body_accounting_middleware,
1402 ))
1403 .layer(
1404 ServiceBuilder::new()
1405 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1406 )
1407 .layer(middleware::from_fn_with_state(
1408 BatchingProtocol::Logs,
1409 set_http_write_batching,
1410 ))
1411 .with_state(log_state)
1412 }
1413
1414 fn route_sql<S>(api_state: ApiState, batch_body_limit: usize) -> Router<S> {
1415 Router::new()
1416 .route(
1417 "/capabilities",
1418 routing::get(|State(state): State<ApiState>| async move {
1419 let mut capabilities =
1420 serde_json::json!({"metric_packed_import": 1, "metric_packed_export": 1});
1421 if state.sql_handler.supports_metric_batch_ddl() {
1422 capabilities["metric_batch_ddl"] = serde_json::json!(1);
1423 }
1424 axum::Json(capabilities)
1425 }),
1426 )
1427 .route(
1428 "/ddl/logical-tables",
1429 routing::post(handler::create_logical_tables)
1430 .layer(DefaultBodyLimit::max(batch_body_limit)),
1431 )
1432 .route(
1433 "/sql",
1434 routing::get(handler::sql).post(handler::sql).layer(
1435 middleware::from_fn_with_state(
1436 BatchingProtocol::HttpSql,
1437 set_http_write_batching,
1438 ),
1439 ),
1440 )
1441 .route(
1442 "/sql/parse",
1443 routing::get(handler::sql_parse).post(handler::sql_parse),
1444 )
1445 .route(
1446 "/sql/format",
1447 routing::get(handler::sql_format).post(handler::sql_format),
1448 )
1449 .route(
1450 "/promql",
1451 routing::get(handler::promql).post(handler::promql),
1452 )
1453 .route(
1454 "/sql/analyze/stream",
1455 routing::post(handler::sql_analyze_stream),
1456 )
1457 .with_state(api_state)
1458 }
1459
1460 fn route_logs<S>(log_handler: LogQueryHandlerRef) -> Router<S> {
1461 Router::new()
1462 .route("/logs", routing::get(logs::logs).post(logs::logs))
1463 .with_state(log_handler)
1464 }
1465
1466 pub fn route_prometheus<S>(prometheus_handler: PrometheusHandlerRef) -> Router<S> {
1470 Router::new()
1471 .route(
1472 "/format_query",
1473 routing::post(format_query).get(format_query),
1474 )
1475 .route("/status/buildinfo", routing::get(build_info_query))
1476 .route("/query", routing::post(instant_query).get(instant_query))
1477 .route("/query_range", routing::post(range_query).get(range_query))
1478 .route(
1479 "/query_exemplars",
1480 routing::post(query_exemplars).get(query_exemplars),
1481 )
1482 .route("/labels", routing::post(labels_query).get(labels_query))
1483 .route("/metadata", routing::get(metadata_query))
1484 .route("/series", routing::post(series_query).get(series_query))
1485 .route("/parse_query", routing::post(parse_query).get(parse_query))
1486 .route(
1487 "/label/{label_name}/values",
1488 routing::get(label_values_query),
1489 )
1490 .layer(ServiceBuilder::new().layer(CompressionLayer::new()))
1491 .with_state(prometheus_handler)
1492 }
1493
1494 fn route_prom<S>(state: PromStoreState) -> Router<S> {
1500 let write = routing::post(prom_store::remote_write);
1501 let write = if state.prom_store_with_metric_engine {
1502 write
1503 } else {
1504 write.layer(middleware::from_fn_with_state(
1505 BatchingProtocol::Prom,
1506 set_http_write_batching,
1507 ))
1508 };
1509 Router::new()
1510 .route("/read", routing::post(prom_store::remote_read))
1511 .route("/write", write)
1512 .with_state(state)
1513 }
1514
1515 fn route_influxdb<S>(
1516 influxdb_handler: InfluxdbLineProtocolHandlerRef,
1517 memory_limiter: ServerMemoryLimiter,
1518 ) -> Router<S> {
1519 Router::new()
1520 .route("/write", routing::post(influxdb_write_v1))
1521 .route("/api/v2/write", routing::post(influxdb_write_v2))
1522 .layer(middleware::from_fn_with_state(
1523 memory_limiter,
1524 memory_limit::decoded_body_accounting_middleware,
1525 ))
1526 .layer(
1527 ServiceBuilder::new()
1528 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1529 )
1530 .route("/ping", routing::get(influxdb_ping))
1531 .route("/health", routing::get(influxdb_health))
1532 .layer(middleware::from_fn_with_state(
1533 BatchingProtocol::Influxdb,
1534 set_http_write_batching,
1535 ))
1536 .with_state(influxdb_handler)
1537 }
1538
1539 fn route_opentsdb<S>(opentsdb_handler: OpentsdbProtocolHandlerRef) -> Router<S> {
1540 Router::new()
1541 .route("/api/put", routing::post(opentsdb::put))
1542 .layer(middleware::from_fn_with_state(
1543 BatchingProtocol::Opentsdb,
1544 set_http_write_batching,
1545 ))
1546 .with_state(opentsdb_handler)
1547 }
1548
1549 fn route_otlp<S>(
1550 otlp_handler: OpenTelemetryProtocolHandlerRef,
1551 with_metric_engine: bool,
1552 memory_limiter: ServerMemoryLimiter,
1553 ) -> Router<S> {
1554 Router::new()
1555 .route("/v1/metrics", routing::post(otlp::metrics))
1556 .route("/v1/traces", routing::post(otlp::traces))
1557 .route("/v1/logs", routing::post(otlp::logs))
1558 .layer(middleware::from_fn_with_state(
1559 memory_limiter,
1560 memory_limit::decoded_body_accounting_middleware,
1561 ))
1562 .layer(
1563 ServiceBuilder::new()
1564 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1565 )
1566 .layer(middleware::from_fn_with_state(
1567 BatchingProtocol::Otlp,
1568 set_http_write_batching,
1569 ))
1570 .with_state(OtlpState {
1571 with_metric_engine,
1572 handler: otlp_handler,
1573 })
1574 }
1575
1576 fn route_config<S>(state: GreptimeOptionsConfigState) -> Router<S> {
1577 Router::new()
1578 .route("/config", routing::get(handler::config))
1579 .with_state(state)
1580 }
1581
1582 fn route_jaeger<S>(handler: JaegerQueryHandlerRef) -> Router<S> {
1583 Router::new()
1584 .route("/api/services", routing::get(jaeger::handle_get_services))
1585 .route(
1586 "/api/services/{service_name}/operations",
1587 routing::get(jaeger::handle_get_operations_by_service),
1588 )
1589 .route(
1590 "/api/operations",
1591 routing::get(jaeger::handle_get_operations),
1592 )
1593 .route("/api/traces", routing::get(jaeger::handle_find_traces))
1594 .route(
1595 "/api/traces/{trace_id}",
1596 routing::get(jaeger::handle_get_trace),
1597 )
1598 .route(
1599 "/api/v3/services",
1600 routing::get(jaeger::v3::handle_get_services),
1601 )
1602 .route(
1603 "/api/v3/operations",
1604 routing::get(jaeger::v3::handle_get_operations),
1605 )
1606 .route(
1607 "/api/v3/traces",
1608 routing::get(jaeger::v3::handle_find_traces),
1609 )
1610 .route(
1611 "/api/v3/trace-summaries",
1612 routing::get(jaeger::v3::handle_find_trace_summaries),
1613 )
1614 .route(
1615 "/api/v3/traces/{trace_id}",
1616 routing::get(jaeger::v3::handle_get_trace),
1617 )
1618 .with_state(handler)
1619 }
1620
1621 #[cfg(feature = "dashboard")]
1622 fn route_dashboard<S>(
1623 handler: DashboardHandlerRef,
1624 memory_limiter: ServerMemoryLimiter,
1625 ) -> Router<S> {
1626 use crate::http::dashboard::{add_dashboard, delete_dashboard, list_dashboards};
1627
1628 Router::new()
1629 .route("/", routing::get(list_dashboards))
1630 .route("/{dashboard_name}", routing::post(add_dashboard))
1631 .route("/{dashboard_name}", routing::delete(delete_dashboard))
1632 .layer(middleware::from_fn_with_state(
1633 memory_limiter,
1634 memory_limit::decoded_body_accounting_middleware,
1635 ))
1636 .layer(
1637 ServiceBuilder::new()
1638 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1639 )
1640 .with_state(DashboardState { handler })
1641 }
1642
1643 #[cfg(not(feature = "dashboard"))]
1644 fn route_dashboard<S>(
1645 handler: DashboardHandlerRef,
1646 _memory_limiter: ServerMemoryLimiter,
1647 ) -> Router<S> {
1648 Router::new().with_state(DashboardState { handler })
1649 }
1650}
1651
1652pub const HTTP_SERVER: &str = "HTTP_SERVER";
1653pub const HTTP_API_SERVER: &str = "HTTP_API_SERVER";
1654
1655pub(crate) fn cors_allow_origin(origins: &[String]) -> Result<AllowOrigin> {
1657 if origins.is_empty() {
1658 return Ok(AllowOrigin::any());
1659 }
1660 let origins = origins
1661 .iter()
1662 .map(|origin| HeaderValue::from_str(origin).context(InvalidHeaderValueSnafu))
1663 .collect::<Result<Vec<_>>>()?;
1664 Ok(AllowOrigin::list(origins))
1665}
1666
1667#[async_trait]
1668impl Server for HttpServer {
1669 async fn shutdown(&self) -> Result<()> {
1670 let mut shutdown_tx = self.shutdown_tx.lock().await;
1671 if let Some(tx) = shutdown_tx.take()
1672 && tx.send(()).is_err()
1673 {
1674 info!("Receiver dropped, the HTTP server has already exited");
1675 }
1676 info!("Shutdown {}", self.kind());
1677
1678 Ok(())
1679 }
1680
1681 async fn start(&mut self, listening: SocketAddr) -> Result<()> {
1682 let (tx, rx) = oneshot::channel();
1683 let serve = {
1684 let mut shutdown_tx = self.shutdown_tx.lock().await;
1685 ensure!(
1686 shutdown_tx.is_none(),
1687 AlreadyStartedSnafu {
1688 server: self.kind()
1689 }
1690 );
1691
1692 let app = self.build(self.make_app())?;
1693 let listener = tokio::net::TcpListener::bind(listening)
1694 .await
1695 .context(AddressBindSnafu { addr: listening })?
1696 .tap_io(|tcp_stream| {
1697 if let Err(e) = tcp_stream.set_nodelay(true) {
1698 error!(e; "Failed to set TCP_NODELAY on incoming connection");
1699 }
1700 });
1701 let serve = axum::serve(
1702 listener,
1703 app.into_make_service_with_connect_info::<SocketAddr>(),
1704 );
1705
1706 *shutdown_tx = Some(tx);
1723
1724 serve
1725 };
1726 let listening = serve.local_addr().context(InternalIoSnafu)?;
1727 info!("{} server is bound to {}", self.kind(), listening);
1728
1729 common_runtime::spawn_global(async move {
1730 if let Err(e) = serve
1731 .with_graceful_shutdown(rx.map(drop))
1732 .await
1733 .context(InternalIoSnafu)
1734 {
1735 error!(e; "Failed to shutdown http server");
1736 }
1737 });
1738
1739 self.bind_addr = Some(listening);
1740 Ok(())
1741 }
1742
1743 fn name(&self) -> &str {
1744 match self.kind {
1745 HttpServerKind::Api => HTTP_API_SERVER,
1746 HttpServerKind::Full => HTTP_SERVER,
1747 }
1748 }
1749
1750 fn bind_addr(&self) -> Option<SocketAddr> {
1751 self.bind_addr
1752 }
1753
1754 fn as_any(&self) -> &dyn std::any::Any {
1755 self
1756 }
1757}
1758
1759#[cfg(test)]
1760mod test {
1761 use std::future::pending;
1762 use std::io::Cursor;
1763 use std::sync::Arc;
1764
1765 use arrow_ipc::reader::StreamReader;
1766 use arrow_schema::DataType;
1767 use axum::http::StatusCode;
1768 use axum::routing::{get, post};
1769 use common_query::{Output, OutputData};
1770 use common_recordbatch::RecordBatches;
1771 use datafusion_expr::LogicalPlan;
1772 use datatypes::prelude::*;
1773 use datatypes::schema::{ColumnSchema, Schema};
1774 use datatypes::vectors::{StringVector, UInt32Vector};
1775 use header::constants::GREPTIME_DB_HEADER_TIMEOUT;
1776 use query::parser::PromQuery;
1777 use query::query_engine::DescribeResult;
1778 use session::context::QueryContextRef;
1779 use sql::statements::statement::Statement;
1780 use tokio::sync::mpsc;
1781 use tokio::time::Instant;
1782
1783 use crate::http::test_helpers::TestClient;
1784 use crate::http::*;
1785 use crate::prom_remote_write::validation::validate_label_name;
1786 use crate::query_handler::sql::SqlQueryHandler;
1787
1788 struct DummyInstance {
1789 _tx: mpsc::Sender<(String, Vec<u8>)>,
1790 }
1791
1792 #[async_trait]
1793 impl SqlQueryHandler for DummyInstance {
1794 async fn do_query(&self, _: &str, _: QueryContextRef) -> Vec<Result<Output>> {
1795 unimplemented!()
1796 }
1797
1798 async fn do_analyze_stream_query(&self, _: &str, _: QueryContextRef) -> Result<Output> {
1799 let stream = common_recordbatch::RecordBatches::empty().as_stream();
1800 Ok(Output::new(OutputData::Stream(stream), Default::default()))
1801 }
1802
1803 async fn do_promql_query(&self, _: &PromQuery, _: QueryContextRef) -> Vec<Result<Output>> {
1804 unimplemented!()
1805 }
1806
1807 async fn do_exec_plan(
1808 &self,
1809 _plan: LogicalPlan,
1810 _stmt: Option<Statement>,
1811 _query_ctx: QueryContextRef,
1812 ) -> Result<Output> {
1813 unimplemented!()
1814 }
1815
1816 async fn do_describe(
1817 &self,
1818 _stmt: sql::statements::statement::Statement,
1819 _query_ctx: QueryContextRef,
1820 ) -> Result<Option<DescribeResult>> {
1821 unimplemented!()
1822 }
1823
1824 async fn is_valid_schema(&self, _catalog: &str, _schema: &str) -> Result<bool> {
1825 Ok(true)
1826 }
1827 }
1828
1829 async fn forever() {
1830 pending().await
1831 }
1832
1833 fn make_test_app(tx: mpsc::Sender<(String, Vec<u8>)>) -> Router {
1834 make_test_app_custom(tx, HttpOptions::default())
1835 }
1836
1837 fn make_test_app_custom(tx: mpsc::Sender<(String, Vec<u8>)>, options: HttpOptions) -> Router {
1838 let instance = Arc::new(DummyInstance { _tx: tx });
1839 let server = HttpServerBuilder::new(options)
1840 .with_sql_handler(instance.clone())
1841 .build();
1842 let app = server
1843 .make_app()
1844 .route("/test/timeout", get(forever))
1845 .route("/v1/prometheus/write", post(forever));
1846 server.build(app).unwrap()
1847 }
1848
1849 fn make_split_builder() -> HttpServerBuilder {
1850 let (tx, _rx) = mpsc::channel(100);
1851 let instance = Arc::new(DummyInstance { _tx: tx });
1852 let options = HttpOptions {
1854 enable_api_server: true,
1855 ..HttpOptions::default()
1856 };
1857 HttpServerBuilder::new(options)
1858 .with_sql_handler(instance)
1859 .with_metrics_handler(MetricsHandler)
1860 .with_greptime_config_options("dummy = \"value\"".to_string())
1861 }
1862
1863 #[tokio::test]
1864 pub async fn test_http_api_options_defaults() {
1865 let opts = HttpOptions::default();
1866 assert!(!opts.enable_api_server);
1868 assert_eq!(opts.api_server_addr, "127.0.0.1:4006");
1869 }
1870
1871 #[tokio::test]
1872 async fn test_auth_config_without_provider_disables_auth() {
1873 let server = HttpServerBuilder::new(HttpOptions::default()).build();
1874 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
1875 let response = client.get("/v1/auth/config").send().await;
1876
1877 assert_eq!(response.status(), StatusCode::OK);
1878 assert_eq!(
1879 response.json::<serde_json::Value>().await,
1880 serde_json::json!({"auth_required": false, "methods": []})
1881 );
1882 }
1883
1884 #[tokio::test]
1885 async fn test_auth_config_with_provider_is_public() {
1886 let provider =
1887 auth::static_user_provider_from_option("static_user_provider:cmd:user=password")
1888 .unwrap();
1889 let server = HttpServerBuilder::new(HttpOptions::default())
1890 .with_user_provider(Arc::new(provider))
1891 .build();
1892 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
1893 let response = client.get("/v1/auth/config").send().await;
1894
1895 assert_eq!(response.status(), StatusCode::OK);
1896 assert_eq!(
1897 response.json::<serde_json::Value>().await,
1898 serde_json::json!({
1899 "auth_required": true,
1900 "methods": [{"type": "password"}]
1901 })
1902 );
1903 }
1904
1905 #[tokio::test]
1906 pub async fn test_build_serves_all_routes() {
1907 let server = make_split_builder().build();
1911 assert_eq!(server.name(), HTTP_SERVER);
1912
1913 let app = server.build(server.make_app()).unwrap();
1914 let client = TestClient::new(app).await;
1915
1916 for path in ["/v1/health", "/health", "/status", "/metrics", "/config"] {
1917 let res = client.get(path).send().await;
1918 assert_eq!(
1919 res.status(),
1920 StatusCode::OK,
1921 "internal/full server should serve {path}"
1922 );
1923 }
1924 }
1925
1926 #[tokio::test]
1927 pub async fn test_build_servers_separates_api_and_internal_routes() {
1928 let (internal, api) = make_split_builder().build_servers();
1931 let api = api.expect("API server is explicitly enabled in make_split_builder");
1932 assert_eq!(internal.name(), HTTP_SERVER);
1933 assert_eq!(api.name(), HTTP_API_SERVER);
1934
1935 let internal_app = internal.build(internal.make_app()).unwrap();
1936 let api_app = api.build(api.make_app()).unwrap();
1937
1938 let internal_client = TestClient::new(internal_app).await;
1939 let api_client = TestClient::new(api_app).await;
1940
1941 assert_eq!(
1943 internal_client.get("/v1/health").send().await.status(),
1944 StatusCode::OK
1945 );
1946 assert_eq!(
1947 api_client.get("/v1/health").send().await.status(),
1948 StatusCode::OK
1949 );
1950
1951 for path in ["/health", "/status", "/metrics", "/config"] {
1953 assert_eq!(
1954 internal_client.get(path).send().await.status(),
1955 StatusCode::OK,
1956 "internal/full server should serve {path}"
1957 );
1958 assert_eq!(
1960 api_client.get(path).send().await.status(),
1961 StatusCode::NOT_FOUND,
1962 "API server should NOT serve {path}"
1963 );
1964 }
1965 }
1966
1967 #[test]
1968 fn test_build_servers_api_inherits_http_options() {
1969 let http_opts = HttpOptions {
1971 timeout: Duration::from_secs(42),
1972 body_limit: ReadableSize::mb(128),
1973 cors_allowed_origins: vec!["https://example.com".to_string()],
1974 enable_api_server: true,
1975 ..HttpOptions::default()
1976 };
1977 let (internal, api) = HttpServerBuilder::new(http_opts.clone()).build_servers();
1978 let api = api.expect("API server is explicitly enabled");
1979
1980 assert_eq!(internal.options.addr, http_opts.addr);
1982 assert_eq!(api.options.addr, "127.0.0.1:4006");
1983 assert_eq!(api.options.timeout, http_opts.timeout);
1985 assert_eq!(api.options.body_limit, http_opts.body_limit);
1986 assert_eq!(
1987 api.options.cors_allowed_origins,
1988 http_opts.cors_allowed_origins
1989 );
1990 }
1991
1992 #[test]
1993 fn test_is_api_listener_path() {
1994 assert!(is_api_listener_path("/v1"));
1996 assert!(is_api_listener_path("/v1/"));
1997 assert!(is_api_listener_path("/v1/sql"));
1998 assert!(!is_api_listener_path("/v10/sql"));
1999 assert!(!is_api_listener_path("/v1-internal"));
2000 assert!(is_api_listener_path("/dashboard"));
2002 assert!(is_api_listener_path("/dashboard/app.js"));
2003 assert!(!is_api_listener_path("/dashboard-admin"));
2004 assert!(!is_api_listener_path("/metrics"));
2006 assert!(!is_api_listener_path("/status/plugin"));
2007 assert!(!is_api_listener_path("/health"));
2008 }
2009
2010 #[tokio::test]
2011 async fn debug_routes_require_auth_when_provider_is_configured() {
2012 let server = HttpServerBuilder::new(HttpOptions::default()).build();
2013 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
2014 assert_eq!(
2015 client
2016 .get("/debug/workload_scheduler")
2017 .send()
2018 .await
2019 .status(),
2020 StatusCode::OK
2021 );
2022 let response = client
2023 .get("/no_such_path")
2024 .header("Origin", "https://example.com")
2025 .send()
2026 .await;
2027 assert_eq!(response.status(), StatusCode::NOT_FOUND);
2028 assert!(
2029 response
2030 .headers()
2031 .contains_key(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2032 );
2033
2034 let provider =
2035 auth::static_user_provider_from_option("static_user_provider:cmd:user=password")
2036 .unwrap();
2037 let server = HttpServerBuilder::new(HttpOptions::default())
2038 .with_user_provider(Arc::new(provider))
2039 .build();
2040 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
2041 assert_eq!(
2042 client
2043 .get("/debug/workload_scheduler")
2044 .send()
2045 .await
2046 .status(),
2047 StatusCode::UNAUTHORIZED
2048 );
2049 assert_eq!(
2050 client
2051 .post("/debug/log_level")
2052 .body("info")
2053 .send()
2054 .await
2055 .status(),
2056 StatusCode::UNAUTHORIZED
2057 );
2058 assert_eq!(
2059 client
2060 .get("/debug/workload_scheduler")
2061 .header("Authorization", "Basic dXNlcjpwYXNzd29yZA==")
2062 .send()
2063 .await
2064 .status(),
2065 StatusCode::OK
2066 );
2067 }
2068
2069 #[tokio::test]
2070 async fn packed_capability_requires_auth_on_full_and_api_listeners() {
2071 let (tx, _rx) = mpsc::channel(1);
2072 let provider =
2073 auth::static_user_provider_from_option("static_user_provider:cmd:user=password")
2074 .unwrap();
2075 let (full, api) = HttpServerBuilder::new(HttpOptions {
2076 enable_api_server: true,
2077 ..Default::default()
2078 })
2079 .with_sql_handler(Arc::new(DummyInstance { _tx: tx }))
2080 .with_user_provider(Arc::new(provider))
2081 .build_servers();
2082 for server in [full, api.unwrap()] {
2083 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
2084 assert_eq!(
2085 client.get("/v1/capabilities").send().await.status(),
2086 StatusCode::UNAUTHORIZED
2087 );
2088 assert_eq!(
2089 client
2090 .post("/v1/ddl/logical-tables")
2091 .form(&[("sql", "SELECT 1")])
2092 .send()
2093 .await
2094 .status(),
2095 StatusCode::UNAUTHORIZED
2096 );
2097 let response = client
2098 .get("/v1/capabilities")
2099 .header("Authorization", "Basic dXNlcjpwYXNzd29yZA==")
2100 .send()
2101 .await;
2102 assert_eq!(response.status(), StatusCode::OK);
2103 assert_eq!(
2104 response.json::<serde_json::Value>().await,
2105 serde_json::json!({"metric_packed_import": 1, "metric_packed_export": 1})
2106 );
2107 }
2108 }
2109
2110 #[tokio::test]
2111 async fn logical_ddl_form_limits_and_unsupported_handler() {
2112 use axum::body::{Body, to_bytes};
2113 use tower::ServiceExt;
2114
2115 async fn post_form(app: Router, body: String) -> (StatusCode, serde_json::Value) {
2116 let response = app
2117 .oneshot(
2118 Request::builder()
2119 .method(Method::POST)
2120 .uri("/v1/ddl/logical-tables")
2121 .header("Content-Type", "application/x-www-form-urlencoded")
2122 .body(Body::from(body))
2123 .unwrap(),
2124 )
2125 .await
2126 .unwrap();
2127 let status = response.status();
2128 let body = to_bytes(response.into_body(), 4096).await.unwrap();
2129 (status, serde_json::from_slice(&body).unwrap())
2130 }
2131
2132 for limit in [0, 64] {
2133 let (tx, _rx) = mpsc::channel(1);
2134 let server = HttpServerBuilder::new(HttpOptions {
2135 body_limit: ReadableSize(limit),
2136 ..Default::default()
2137 })
2138 .with_sql_handler(Arc::new(DummyInstance { _tx: tx }))
2139 .build();
2140 let app = server.build(server.make_app()).unwrap();
2141 let client = TestClient::new(app.clone()).await;
2142 assert_eq!(
2143 client.get("/v1/ddl/logical-tables").send().await.status(),
2144 StatusCode::METHOD_NOT_ALLOWED
2145 );
2146 let small = client
2147 .post("/v1/ddl/logical-tables")
2148 .form(&[("sql", "CREATE TABLE t")])
2149 .send()
2150 .await;
2151 assert_eq!(
2152 small.json::<serde_json::Value>().await["code"],
2153 common_error::status_code::StatusCode::Unsupported as u32
2154 );
2155 let (_, body) = post_form(
2156 app.clone(),
2157 if limit == 0 {
2158 format!("sql={}", "%20".repeat(1024 * 1024))
2159 } else {
2160 "sql=".to_string() + &" ".repeat(65)
2161 },
2162 )
2163 .await;
2164 let code = body["code"].clone();
2165 assert_eq!(
2166 code,
2167 if limit == 0 {
2168 common_error::status_code::StatusCode::Unsupported as u32
2169 } else {
2170 common_error::status_code::StatusCode::InvalidArguments as u32
2171 }
2172 );
2173 for body in [
2174 format!("sql={}", "x".repeat(1024 * 1024 + 1)),
2175 format!("sql={}", "%C3%A9".repeat(512 * 1024 + 1)),
2176 format!("sql=CREATE+TABLE+t&padding={}", "x".repeat(4 * 1024 * 1024)),
2177 ] {
2178 let (status, body) = post_form(app.clone(), body).await;
2179 assert_eq!(status, StatusCode::BAD_REQUEST);
2180 assert_eq!(
2181 body["code"],
2182 common_error::status_code::StatusCode::InvalidArguments as u32
2183 );
2184 }
2185 }
2186 }
2187
2188 #[tokio::test]
2189 pub async fn test_extra_router_respects_api_surface() {
2190 let (tx, _rx) = mpsc::channel(100);
2196 let instance = Arc::new(DummyInstance { _tx: tx });
2197 let options = HttpOptions {
2198 enable_api_server: true,
2199 ..HttpOptions::default()
2200 };
2201 let builder = HttpServerBuilder::new(options)
2202 .with_sql_handler(instance)
2203 .with_extra_router(
2204 Router::new()
2205 .route("/status/plugin", routing::get(|| async { "ok" }))
2206 .route("/v1/plugin", routing::get(|| async { "ok" })),
2207 );
2208 let (full, api) = builder.build_servers();
2209 let api = api.expect("API server is explicitly enabled");
2210
2211 let full_client = TestClient::new(full.build(full.make_app()).unwrap()).await;
2212 let api_client = TestClient::new(api.build(api.make_app()).unwrap()).await;
2213
2214 assert_eq!(
2216 full_client.get("/status/plugin").send().await.status(),
2217 StatusCode::OK
2218 );
2219 assert_eq!(
2221 api_client.get("/status/plugin").send().await.status(),
2222 StatusCode::NOT_FOUND
2223 );
2224
2225 assert_eq!(
2227 full_client.get("/v1/plugin").send().await.status(),
2228 StatusCode::OK
2229 );
2230 assert_eq!(
2231 api_client.get("/v1/plugin").send().await.status(),
2232 StatusCode::OK
2233 );
2234
2235 assert_eq!(
2237 api_client.get("/v10/plugin").send().await.status(),
2238 StatusCode::NOT_FOUND
2239 );
2240 }
2241
2242 #[test]
2243 fn test_build_servers_api_disabled_by_default() {
2244 let (_internal, api) = HttpServerBuilder::new(HttpOptions::default()).build_servers();
2247 assert!(api.is_none());
2248 }
2249
2250 #[tokio::test]
2251 pub async fn test_cors() {
2252 let (tx, _rx) = mpsc::channel(100);
2254 let app = make_test_app(tx);
2255 let client = TestClient::new(app).await;
2256
2257 let res = client.get("/health").send().await;
2258
2259 assert_eq!(res.status(), StatusCode::OK);
2260 assert_eq!(
2261 res.headers()
2262 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2263 .expect("expect cors header origin"),
2264 "*"
2265 );
2266
2267 let res = client.get("/v1/health").send().await;
2268
2269 assert_eq!(res.status(), StatusCode::OK);
2270 assert_eq!(
2271 res.headers()
2272 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2273 .expect("expect cors header origin"),
2274 "*"
2275 );
2276
2277 let res = client
2278 .options("/health")
2279 .header("Access-Control-Request-Headers", "x-greptime-auth")
2280 .header("Access-Control-Request-Method", "DELETE")
2281 .header("Origin", "https://example.com")
2282 .send()
2283 .await;
2284 assert_eq!(res.status(), StatusCode::OK);
2285 assert_eq!(
2286 res.headers()
2287 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2288 .expect("expect cors header origin"),
2289 "*"
2290 );
2291 assert_eq!(
2292 res.headers()
2293 .get(http::header::ACCESS_CONTROL_ALLOW_HEADERS)
2294 .expect("expect cors header headers"),
2295 "*"
2296 );
2297 assert_eq!(
2298 res.headers()
2299 .get(http::header::ACCESS_CONTROL_ALLOW_METHODS)
2300 .expect("expect cors header methods"),
2301 "GET,POST,PUT,DELETE,HEAD"
2302 );
2303 }
2304
2305 #[tokio::test]
2306 pub async fn test_cors_custom_origins() {
2307 let (tx, _rx) = mpsc::channel(100);
2309 let origin = "https://example.com";
2310
2311 let options = HttpOptions {
2312 cors_allowed_origins: vec![origin.to_string()],
2313 ..Default::default()
2314 };
2315
2316 let app = make_test_app_custom(tx, options);
2317 let client = TestClient::new(app).await;
2318
2319 let res = client.get("/health").header("Origin", origin).send().await;
2320
2321 assert_eq!(res.status(), StatusCode::OK);
2322 assert_eq!(
2323 res.headers()
2324 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2325 .expect("expect cors header origin"),
2326 origin
2327 );
2328
2329 let res = client
2330 .get("/health")
2331 .header("Origin", "https://notallowed.com")
2332 .send()
2333 .await;
2334
2335 assert_eq!(res.status(), StatusCode::OK);
2336 assert!(
2337 !res.headers()
2338 .contains_key(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2339 );
2340 }
2341
2342 #[tokio::test]
2343 pub async fn test_cors_disabled() {
2344 let (tx, _rx) = mpsc::channel(100);
2346
2347 let options = HttpOptions {
2348 enable_cors: false,
2349 ..Default::default()
2350 };
2351
2352 let app = make_test_app_custom(tx, options);
2353 let client = TestClient::new(app).await;
2354
2355 let res = client.get("/health").send().await;
2356
2357 assert_eq!(res.status(), StatusCode::OK);
2358 assert!(
2359 !res.headers()
2360 .contains_key(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2361 );
2362 }
2363
2364 #[test]
2365 fn test_http_options_default() {
2366 let default = HttpOptions::default();
2367 assert_eq!("127.0.0.1:4000".to_string(), default.addr);
2368 assert_eq!(Duration::from_secs(0), default.timeout)
2369 }
2370
2371 #[tokio::test]
2372 async fn test_http_options_legacy_analyze_stream_config_is_ignored() {
2373 let options: HttpOptions = serde_json::from_value(serde_json::json!({
2374 "addr": "127.0.0.1:4000",
2375 "timeout": "0s",
2376 "body_limit": "64MiB",
2377 "cors_allowed_origins": [],
2378 "enable_cors": true,
2379 "experimental_enable_explain_analyze_stream": false,
2380 "enable_api_server": false,
2381 "api_server_addr": "127.0.0.1:4006"
2382 }))
2383 .unwrap();
2384 let serialized = serde_json::to_string(&options).unwrap();
2385 assert!(!serialized.contains("experimental_enable_explain_analyze_stream"));
2386
2387 let (tx, _rx) = mpsc::channel(100);
2388 let app = make_test_app_custom(tx, options);
2389 let client = TestClient::new(app).await;
2390 let response = client
2391 .post("/v1/sql/analyze/stream")
2392 .form(&handler::SqlQuery {
2393 sql: Some("EXPLAIN ANALYZE VERBOSE SELECT 1".to_string()),
2394 ..Default::default()
2395 })
2396 .send()
2397 .await;
2398 assert_ne!(response.status(), StatusCode::NOT_FOUND);
2399 }
2400
2401 #[tokio::test]
2402 async fn test_http_server_request_timeout() {
2403 common_telemetry::init_default_ut_logging();
2404
2405 let (tx, _rx) = mpsc::channel(100);
2406 let options = HttpOptions {
2407 timeout: Duration::from_millis(10),
2408 ..Default::default()
2409 };
2410 let app = make_test_app_custom(tx, options);
2411 let client = TestClient::new(app).await;
2412 let res = client.get("/test/timeout").send().await;
2413 assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
2414
2415 let res = client.post("/v1/prometheus/write").send().await;
2416 assert_eq!(res.status(), StatusCode::GATEWAY_TIMEOUT);
2417
2418 let now = Instant::now();
2419 let res = client
2420 .get("/test/timeout")
2421 .header(GREPTIME_DB_HEADER_TIMEOUT, "20ms")
2422 .send()
2423 .await;
2424 assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
2425 let elapsed = now.elapsed();
2426 assert!(elapsed > Duration::from_millis(15));
2427
2428 tokio::time::timeout(
2429 Duration::from_millis(15),
2430 client
2431 .get("/test/timeout")
2432 .header(GREPTIME_DB_HEADER_TIMEOUT, "0s")
2433 .send(),
2434 )
2435 .await
2436 .unwrap_err();
2437
2438 tokio::time::timeout(
2439 Duration::from_millis(15),
2440 client
2441 .get("/test/timeout")
2442 .header(
2443 GREPTIME_DB_HEADER_TIMEOUT,
2444 humantime::format_duration(Duration::default()).to_string(),
2445 )
2446 .send(),
2447 )
2448 .await
2449 .unwrap_err();
2450 }
2451
2452 #[tokio::test]
2453 async fn test_schema_for_empty_response() {
2454 let column_schemas = vec![
2455 ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
2456 ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
2457 ];
2458 let schema = Arc::new(Schema::new(column_schemas));
2459
2460 let recordbatches = RecordBatches::try_new(schema.clone(), vec![]).unwrap();
2461 let outputs = vec![Ok(Output::new_with_record_batches(recordbatches))];
2462
2463 let json_resp = GreptimedbV1Response::from_output(outputs).await;
2464 if let HttpResponse::GreptimedbV1(json_resp) = json_resp {
2465 let json_output = &json_resp.output[0];
2466 if let GreptimeQueryOutput::Records(r) = json_output {
2467 assert_eq!(r.num_rows(), 0);
2468 assert_eq!(r.num_cols(), 2);
2469 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2470 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2471 } else {
2472 panic!("invalid output type");
2473 }
2474 } else {
2475 panic!("invalid format")
2476 }
2477 }
2478
2479 #[tokio::test]
2480 async fn test_recordbatches_conversion() {
2481 let column_schemas = vec![
2482 ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
2483 ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
2484 ];
2485 let schema = Arc::new(Schema::new(column_schemas));
2486 let columns: Vec<VectorRef> = vec![
2487 Arc::new(UInt32Vector::from_slice(vec![1, 2, 3, 4])),
2488 Arc::new(StringVector::from(vec![
2489 None,
2490 Some("hello"),
2491 Some("greptime"),
2492 None,
2493 ])),
2494 ];
2495 let recordbatch = RecordBatch::new(schema.clone(), columns).unwrap();
2496
2497 for format in [
2498 ResponseFormat::GreptimedbV1,
2499 ResponseFormat::InfluxdbV1,
2500 ResponseFormat::Csv(true, true),
2501 ResponseFormat::Table,
2502 ResponseFormat::Arrow,
2503 ResponseFormat::Json,
2504 ResponseFormat::Null,
2505 ] {
2506 let recordbatches =
2507 RecordBatches::try_new(schema.clone(), vec![recordbatch.clone()]).unwrap();
2508 let outputs = vec![Ok(Output::new_with_record_batches(recordbatches))];
2509 let json_resp = match format {
2510 ResponseFormat::Arrow => ArrowResponse::from_output(outputs, None).await,
2511 ResponseFormat::Csv(with_names, with_types) => {
2512 CsvResponse::from_output(outputs, with_names, with_types).await
2513 }
2514 ResponseFormat::Table => TableResponse::from_output(outputs).await,
2515 ResponseFormat::GreptimedbV1 => GreptimedbV1Response::from_output(outputs).await,
2516 ResponseFormat::InfluxdbV1 => InfluxdbV1Response::from_output(outputs, None).await,
2517 ResponseFormat::Json => JsonResponse::from_output(outputs).await,
2518 ResponseFormat::Null => NullResponse::from_output(outputs).await,
2519 };
2520
2521 match json_resp {
2522 HttpResponse::GreptimedbV1(resp) => {
2523 let json_output = &resp.output[0];
2524 if let GreptimeQueryOutput::Records(r) = json_output {
2525 assert_eq!(r.num_rows(), 4);
2526 assert_eq!(r.num_cols(), 2);
2527 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2528 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2529 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2530 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2531 } else {
2532 panic!("invalid output type");
2533 }
2534 }
2535 HttpResponse::InfluxdbV1(resp) => {
2536 let json_output = &resp.results()[0];
2537 assert_eq!(json_output.num_rows(), 4);
2538 assert_eq!(json_output.num_cols(), 2);
2539 assert_eq!(json_output.series[0].columns.clone()[0], "numbers");
2540 assert_eq!(
2541 json_output.series[0].values[0][0],
2542 serde_json::Value::from(1)
2543 );
2544 assert_eq!(json_output.series[0].values[0][1], serde_json::Value::Null);
2545 }
2546 HttpResponse::Csv(resp) => {
2547 let output = &resp.output()[0];
2548 if let GreptimeQueryOutput::Records(r) = output {
2549 assert_eq!(r.num_rows(), 4);
2550 assert_eq!(r.num_cols(), 2);
2551 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2552 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2553 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2554 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2555 } else {
2556 panic!("invalid output type");
2557 }
2558 }
2559
2560 HttpResponse::Table(resp) => {
2561 let output = &resp.output()[0];
2562 if let GreptimeQueryOutput::Records(r) = output {
2563 assert_eq!(r.num_rows(), 4);
2564 assert_eq!(r.num_cols(), 2);
2565 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2566 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2567 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2568 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2569 } else {
2570 panic!("invalid output type");
2571 }
2572 }
2573
2574 HttpResponse::Arrow(resp) => {
2575 let output = resp.data;
2576 let mut reader = StreamReader::try_new(Cursor::new(output), None)
2577 .expect("Arrow reader error");
2578 let schema = reader.schema();
2579 assert_eq!(schema.fields[0].name(), "numbers");
2580 assert_eq!(schema.fields[0].data_type(), &DataType::UInt32);
2581 assert_eq!(schema.fields[1].name(), "strings");
2582 assert_eq!(schema.fields[1].data_type(), &DataType::Utf8);
2583
2584 let rb = reader.next().unwrap().expect("read record batch failed");
2585 assert_eq!(rb.num_columns(), 2);
2586 assert_eq!(rb.num_rows(), 4);
2587 }
2588
2589 HttpResponse::Json(resp) => {
2590 let output = &resp.output()[0];
2591 if let GreptimeQueryOutput::Records(r) = output {
2592 assert_eq!(r.num_rows(), 4);
2593 assert_eq!(r.num_cols(), 2);
2594 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2595 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2596 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2597 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2598 } else {
2599 panic!("invalid output type");
2600 }
2601 }
2602
2603 HttpResponse::Null(resp) => {
2604 assert_eq!(resp.rows(), 4);
2605 }
2606
2607 HttpResponse::Error(err) => unreachable!("{err:?}"),
2608 }
2609 }
2610 }
2611
2612 #[test]
2613 fn test_response_format_misc() {
2614 assert_eq!(ResponseFormat::default(), ResponseFormat::GreptimedbV1);
2615 assert_eq!(ResponseFormat::parse("arrow"), Some(ResponseFormat::Arrow));
2616 assert_eq!(
2617 ResponseFormat::parse("csv"),
2618 Some(ResponseFormat::Csv(false, false))
2619 );
2620 assert_eq!(
2621 ResponseFormat::parse("csvwithnames"),
2622 Some(ResponseFormat::Csv(true, false))
2623 );
2624 assert_eq!(
2625 ResponseFormat::parse("csvwithnamesandtypes"),
2626 Some(ResponseFormat::Csv(true, true))
2627 );
2628 assert_eq!(ResponseFormat::parse("table"), Some(ResponseFormat::Table));
2629 assert_eq!(
2630 ResponseFormat::parse("greptimedb_v1"),
2631 Some(ResponseFormat::GreptimedbV1)
2632 );
2633 assert_eq!(
2634 ResponseFormat::parse("influxdb_v1"),
2635 Some(ResponseFormat::InfluxdbV1)
2636 );
2637 assert_eq!(ResponseFormat::parse("json"), Some(ResponseFormat::Json));
2638 assert_eq!(ResponseFormat::parse("null"), Some(ResponseFormat::Null));
2639
2640 assert_eq!(ResponseFormat::parse("invalid"), None);
2642 assert_eq!(ResponseFormat::parse(""), None);
2643 assert_eq!(ResponseFormat::parse("CSV"), None); assert_eq!(ResponseFormat::Arrow.as_str(), "arrow");
2647 assert_eq!(ResponseFormat::Csv(false, false).as_str(), "csv");
2648 assert_eq!(ResponseFormat::Csv(true, true).as_str(), "csv");
2649 assert_eq!(ResponseFormat::Table.as_str(), "table");
2650 assert_eq!(ResponseFormat::GreptimedbV1.as_str(), "greptimedb_v1");
2651 assert_eq!(ResponseFormat::InfluxdbV1.as_str(), "influxdb_v1");
2652 assert_eq!(ResponseFormat::Json.as_str(), "json");
2653 assert_eq!(ResponseFormat::Null.as_str(), "null");
2654 assert_eq!(ResponseFormat::default().as_str(), "greptimedb_v1");
2655 }
2656
2657 #[test]
2658 fn test_decode_label_name_strict() {
2659 let strict = PromValidationMode::Strict;
2660
2661 assert!(strict.decode_label_name(b"__name__").is_ok());
2663 assert!(strict.decode_label_name(b"job").is_ok());
2664 assert!(strict.decode_label_name(b"instance").is_ok());
2665 assert!(strict.decode_label_name(b"_private").is_ok());
2666 assert!(strict.decode_label_name(b"label_with_underscores").is_ok());
2667 assert!(strict.decode_label_name(b"abc123").is_ok());
2668 assert!(strict.decode_label_name(b"A").is_ok());
2669 assert!(strict.decode_label_name(b"_").is_ok());
2670
2671 assert!(strict.decode_label_name(b"0abc").is_err());
2673 assert!(strict.decode_label_name(b"123").is_err());
2674
2675 assert!(strict.decode_label_name(b"label-name").is_err());
2677 assert!(strict.decode_label_name(b"label.name").is_err());
2678 assert!(strict.decode_label_name(b"label name").is_err());
2679 assert!(strict.decode_label_name(b"label/name").is_err());
2680
2681 assert!(strict.decode_label_name(b"").is_err());
2683
2684 assert!(strict.decode_label_name("ラベル".as_bytes()).is_err());
2686
2687 assert!(strict.decode_label_name(&[0xff, 0xfe]).is_err());
2689 }
2690
2691 #[test]
2692 fn test_decode_label_name_lossy() {
2693 let lossy = PromValidationMode::Lossy;
2694
2695 assert!(lossy.decode_label_name(b"__name__").is_ok());
2697 assert!(lossy.decode_label_name(b"label-name").is_err());
2698 assert!(lossy.decode_label_name(b"0abc").is_err());
2699
2700 assert!(lossy.decode_label_name(&[0xff, 0xfe]).is_err());
2702 }
2703
2704 #[test]
2705 fn test_decode_label_name_unchecked() {
2706 let unchecked = PromValidationMode::Unchecked;
2707
2708 assert!(unchecked.decode_label_name(b"__name__").is_ok());
2710 assert!(unchecked.decode_label_name(b"label-name").is_err());
2711 assert!(unchecked.decode_label_name(b"0abc").is_err());
2712 }
2713
2714 #[test]
2715 fn test_is_valid_prom_label_name_bytes() {
2716 assert!(validate_label_name(b"__name__"));
2717 assert!(validate_label_name(b"job"));
2718 assert!(validate_label_name(b"_"));
2719 assert!(validate_label_name(b"A"));
2720 assert!(validate_label_name(b"abc123"));
2721 assert!(validate_label_name(b"_leading_underscore"));
2722
2723 assert!(!validate_label_name(b""));
2724 assert!(!validate_label_name(b"0starts_with_digit"));
2725 assert!(!validate_label_name(b"has-dash"));
2726 assert!(!validate_label_name(b"has.dot"));
2727 assert!(!validate_label_name(b"has space"));
2728 assert!(!validate_label_name(&[0xff, 0xfe]));
2729 }
2730}
2731
2732#[cfg(test)]
2733mod batching_tests {
2734 use std::sync::{Arc, Mutex};
2735
2736 use axum::http::StatusCode;
2737 use common_query::Output;
2738 use session::context::QueryContextRef;
2739
2740 use crate::batcher::BatchingProtocol;
2741 use crate::error::Result as ServerResult;
2742 use crate::http::test_helpers::TestClient;
2743 use crate::http::{HttpOptions, HttpServerBuilder};
2744 use crate::influxdb::InfluxdbRequest;
2745 use crate::opentsdb::codec::DataPoint;
2746 use crate::query_handler::{InfluxdbLineProtocolHandler, OpentsdbProtocolHandler};
2747
2748 #[tokio::test]
2749 async fn test_batching_selectors_are_independent() {
2750 use axum::routing::post;
2751 use axum::{Extension, Json, Router, middleware};
2752 use session::context::{QueryContext, QueryContextBuilder};
2753
2754 use crate::http::{LogicalBatchingProtocols, set_http_write_batching};
2755 for table in [false, true] {
2756 for logical in [false, true] {
2757 let app = Router::new()
2758 .route(
2759 "/",
2760 post(|Extension(ctx): Extension<QueryContext>| async move {
2761 Json([ctx.batching_enabled(), ctx.logical_batching_enabled()])
2762 }),
2763 )
2764 .route_layer(middleware::from_fn_with_state(
2765 BatchingProtocol::Otlp,
2766 set_http_write_batching,
2767 ))
2768 .layer(Extension(QueryContextBuilder::default().build()))
2769 .layer(Extension(Arc::new(if table {
2770 vec![BatchingProtocol::Otlp]
2771 } else {
2772 vec![]
2773 })))
2774 .layer(Extension(LogicalBatchingProtocols(if logical {
2775 vec![BatchingProtocol::Otlp]
2776 } else {
2777 vec![]
2778 })));
2779 let client = TestClient::new(app).await;
2780 let actual: [bool; 2] = client.post("/").send().await.json().await;
2781 assert_eq!(actual, [table, logical]);
2782 }
2783 }
2784 }
2785
2786 #[derive(Default)]
2787 struct RecordingWriteHandler {
2788 selections: Mutex<Vec<bool>>,
2789 }
2790
2791 #[async_trait::async_trait]
2792 impl OpentsdbProtocolHandler for RecordingWriteHandler {
2793 async fn preflight(&self, _: &[DataPoint], _: QueryContextRef) -> ServerResult<()> {
2794 Ok(())
2795 }
2796
2797 async fn exec(&self, points: Vec<DataPoint>, ctx: QueryContextRef) -> ServerResult<usize> {
2798 self.selections.lock().unwrap().push(ctx.batching_enabled());
2799 Ok(points.len())
2800 }
2801 }
2802
2803 #[async_trait::async_trait]
2804 impl InfluxdbLineProtocolHandler for RecordingWriteHandler {
2805 async fn exec(&self, _: InfluxdbRequest, ctx: QueryContextRef) -> ServerResult<Output> {
2806 self.selections.lock().unwrap().push(ctx.batching_enabled());
2807 Ok(Output::new_with_affected_rows(1))
2808 }
2809 }
2810
2811 #[tokio::test]
2812 async fn test_real_influx_and_opentsdb_routes_keep_selection() {
2813 for protocols in [
2814 vec![],
2815 vec![BatchingProtocol::Influxdb],
2816 vec![BatchingProtocol::Opentsdb],
2817 vec![BatchingProtocol::Influxdb, BatchingProtocol::Opentsdb],
2818 ] {
2819 let handler = Arc::new(RecordingWriteHandler::default());
2820 let influx_enabled = protocols.contains(&BatchingProtocol::Influxdb);
2821 let opentsdb_enabled = protocols.contains(&BatchingProtocol::Opentsdb);
2822 let server = HttpServerBuilder::new(HttpOptions::default())
2823 .with_batching_protocols(protocols)
2824 .with_influxdb_handler(handler.clone())
2825 .with_opentsdb_handler(handler.clone())
2826 .build();
2827 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
2828 for path in [
2829 "/v1/influxdb/write",
2830 "/v1/influxdb/api/v2/write?bucket=public",
2831 ] {
2832 assert_eq!(
2833 client
2834 .post(path)
2835 .body("cpu value=1 42")
2836 .send()
2837 .await
2838 .status(),
2839 StatusCode::NO_CONTENT
2840 );
2841 }
2842 let point =
2843 serde_json::json!({"metric":"cpu", "timestamp":42, "value":1, "tags":{"host":"a"}});
2844 for query in ["", "?summary", "?details"] {
2845 let response = client
2846 .post(&format!("/v1/opentsdb/api/put{query}"))
2847 .json(&point)
2848 .send()
2849 .await;
2850 assert_eq!(
2851 response.status(),
2852 if query.is_empty() {
2853 StatusCode::NO_CONTENT
2854 } else {
2855 StatusCode::OK
2856 }
2857 );
2858 }
2859 assert_eq!(
2860 *handler.selections.lock().unwrap(),
2861 vec![
2862 influx_enabled,
2863 influx_enabled,
2864 opentsdb_enabled,
2865 opentsdb_enabled,
2866 opentsdb_enabled
2867 ]
2868 );
2869 }
2870 }
2871}