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