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