Skip to main content

servers/
query_handler.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! All query handler traits for various request protocols, like SQL or GRPC.
16//!
17//! Instance that wishes to support certain request protocol, just implement the corresponding
18//! trait, the Server will handle codec for you.
19//!
20//! Note:
21//! Query handlers are not confined to only handle read requests, they are expecting to handle
22//! write requests too. So the "query" here not might seem ambiguity. However, "query" has been
23//! used as some kind of "convention", it's the "Q" in "SQL". So we might better stick to the
24//! word "query".
25
26pub mod grpc;
27pub mod sql;
28
29use std::collections::HashMap;
30use std::sync::Arc;
31
32use api::prom_store::remote::ReadRequest;
33use api::v1::RowInsertRequests;
34use async_trait::async_trait;
35use catalog::CatalogManager;
36use common_query::Output;
37use datatypes::timestamp::TimestampNanosecond;
38use headers::HeaderValue;
39use log_query::LogQuery;
40use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;
41use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
42use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest;
43use pipeline::{GreptimePipelineParams, Pipeline, PipelineInfo, PipelineVersion, PipelineWay};
44use serde_json::Value;
45use session::context::{QueryContext, QueryContextRef};
46
47#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
48pub struct DashboardDefinition {
49    pub name: String,
50    pub definition: String,
51}
52
53use crate::error::Result;
54use crate::http::jaeger::QueryTraceParams;
55use crate::influxdb::InfluxdbRequest;
56use crate::opentsdb::codec::DataPoint;
57pub type OpentsdbProtocolHandlerRef = Arc<dyn OpentsdbProtocolHandler + Send + Sync>;
58pub type InfluxdbLineProtocolHandlerRef = Arc<dyn InfluxdbLineProtocolHandler + Send + Sync>;
59pub type PromStoreProtocolHandlerRef = Arc<dyn PromStoreProtocolHandler + Send + Sync>;
60pub type OpenTelemetryProtocolHandlerRef = Arc<dyn OpenTelemetryProtocolHandler + Send + Sync>;
61pub type PipelineHandlerRef = Arc<dyn PipelineHandler + Send + Sync>;
62pub type LogQueryHandlerRef = Arc<dyn LogQueryHandler + Send + Sync>;
63pub type JaegerQueryHandlerRef = Arc<dyn JaegerQueryHandler + Send + Sync>;
64
65#[derive(Debug, Default, Clone)]
66pub struct TraceIngestOutcome {
67    pub write_cost: usize,
68    pub accepted_spans: usize,
69    pub rejected_spans: usize,
70    pub error_message: Option<String>,
71}
72
73/// Result of ingesting one OTLP metrics request or Arrow batch.
74#[derive(Debug, Default, Clone)]
75pub struct MetricsIngestOutcome {
76    pub write_cost: usize,
77    pub accepted_data_points: i64,
78    pub rejected_data_points: i64,
79    pub error_message: Option<String>,
80}
81
82#[async_trait]
83pub trait InfluxdbLineProtocolHandler {
84    /// A successful request will not return a response.
85    /// Only on error will the socket return a line of data.
86    async fn exec(&self, request: InfluxdbRequest, ctx: QueryContextRef) -> Result<Output>;
87}
88
89#[async_trait]
90pub trait OpentsdbProtocolHandler {
91    /// Checks all points in one external request before per-point debug execution.
92    async fn preflight(&self, data_points: &[DataPoint], ctx: QueryContextRef) -> Result<()>;
93
94    /// A successful request will not return a response.
95    /// Only on error will the socket return a line of data.
96    async fn exec(&self, data_points: Vec<DataPoint>, ctx: QueryContextRef) -> Result<usize>;
97}
98
99pub struct PromStoreResponse {
100    pub content_type: HeaderValue,
101    pub content_encoding: HeaderValue,
102    pub resp_metrics: HashMap<String, Value>,
103    pub body: Vec<u8>,
104}
105
106#[async_trait]
107pub trait PromStoreProtocolHandler {
108    /// Runs pre-write checks/hooks for prometheus remote write requests.
109    async fn pre_write(&self, request: &RowInsertRequests, ctx: QueryContextRef) -> Result<()>;
110
111    /// Writes one batch after [`Self::pre_write`] has succeeded for the entire request.
112    async fn write_prepared(
113        &self,
114        request: RowInsertRequests,
115        ctx: QueryContextRef,
116        with_metric_engine: bool,
117    ) -> Result<Output>;
118
119    /// Handling prometheus remote write requests
120    async fn write(
121        &self,
122        request: RowInsertRequests,
123        ctx: QueryContextRef,
124        with_metric_engine: bool,
125    ) -> Result<Output>;
126
127    /// Checks every batch before writing any of them.
128    async fn write_all(
129        &self,
130        requests: Vec<(QueryContextRef, RowInsertRequests)>,
131        with_metric_engine: bool,
132    ) -> Result<Vec<Result<Output>>>;
133
134    /// Handling prometheus remote read requests
135    async fn read(&self, request: ReadRequest, ctx: QueryContextRef) -> Result<PromStoreResponse>;
136}
137
138#[async_trait]
139pub trait OpenTelemetryProtocolHandler: PipelineHandler {
140    /// Handling opentelemetry metrics request
141    async fn metrics(
142        &self,
143        request: ExportMetricsServiceRequest,
144        ctx: QueryContextRef,
145    ) -> Result<MetricsIngestOutcome>;
146
147    /// Handling opentelemetry traces request
148    async fn traces(
149        &self,
150        pipeline_handler: PipelineHandlerRef,
151        request: ExportTraceServiceRequest,
152        pipeline: PipelineWay,
153        pipeline_params: GreptimePipelineParams,
154        table_name: String,
155        ctx: QueryContextRef,
156    ) -> Result<TraceIngestOutcome>;
157
158    async fn logs(
159        &self,
160        pipeline_handler: PipelineHandlerRef,
161        request: ExportLogsServiceRequest,
162        pipeline: PipelineWay,
163        pipeline_params: GreptimePipelineParams,
164        table_name: String,
165        ctx: QueryContextRef,
166    ) -> Result<Vec<Output>>;
167}
168
169/// PipelineHandler is responsible for handling pipeline related requests.
170///
171/// The "Pipeline" is a series of transformations that can be applied to unstructured
172/// data like logs. This handler is responsible to manage pipelines and accept data for
173/// processing.
174///
175/// The pipeline is stored in the database and can be retrieved by its name.
176#[async_trait]
177pub trait PipelineHandler {
178    async fn insert(&self, input: RowInsertRequests, ctx: QueryContextRef) -> Result<Output>;
179
180    /// Checks every batch before inserting any of them.
181    async fn insert_all(
182        &self,
183        inputs: Vec<(QueryContextRef, RowInsertRequests)>,
184    ) -> Result<Vec<Result<Output>>>;
185
186    fn check_pipeline_query_permission(&self, query_ctx: &QueryContextRef) -> Result<()>;
187
188    /// Loads a compiled pipeline for execution.
189    ///
190    /// This intentionally does not check pipeline-query permission: users with
191    /// write-only permission can ingest through an existing pipeline. Inspection
192    /// and preview callers must check query permission first; ingestion enforces
193    /// write and table-target permissions separately.
194    async fn get_pipeline(
195        &self,
196        name: &str,
197        version: PipelineVersion,
198        query_ctx: QueryContextRef,
199    ) -> Result<Arc<Pipeline>>;
200
201    async fn insert_pipeline(
202        &self,
203        name: &str,
204        content_type: &str,
205        pipeline: &str,
206        query_ctx: QueryContextRef,
207    ) -> Result<PipelineInfo>;
208
209    async fn delete_pipeline(
210        &self,
211        name: &str,
212        version: PipelineVersion,
213        query_ctx: QueryContextRef,
214    ) -> Result<Option<()>>;
215
216    async fn get_table(
217        &self,
218        table: &str,
219        query_ctx: &QueryContext,
220    ) -> std::result::Result<Option<Arc<table::Table>>, catalog::error::Error>;
221
222    //// Build a pipeline from a string.
223    fn build_pipeline(&self, pipeline: &str) -> Result<Pipeline>;
224
225    /// Get a original pipeline by name.
226    async fn get_pipeline_str(
227        &self,
228        name: &str,
229        version: PipelineVersion,
230        query_ctx: QueryContextRef,
231    ) -> Result<(String, TimestampNanosecond)>;
232}
233
234/// Handling dashboard as code CRUD
235pub type DashboardHandlerRef = Arc<dyn DashboardHandler + Send + Sync>;
236
237#[async_trait]
238pub trait DashboardHandler {
239    async fn save(&self, name: &str, definition: &str, ctx: QueryContextRef) -> Result<()>;
240
241    async fn list(&self, ctx: QueryContextRef) -> Result<Vec<DashboardDefinition>>;
242
243    async fn delete(&self, name: &str, ctx: QueryContextRef) -> Result<()>;
244}
245
246/// Handle log query requests.
247#[async_trait]
248pub trait LogQueryHandler {
249    /// Execute a log query.
250    async fn query(&self, query: LogQuery, ctx: QueryContextRef) -> Result<Output>;
251
252    /// Get catalog manager.
253    fn catalog_manager(&self, ctx: &QueryContext) -> Result<&dyn CatalogManager>;
254}
255
256/// Handle Jaeger query requests.
257#[async_trait]
258pub trait JaegerQueryHandler {
259    /// Get trace services. It's used for `/api/services` API.
260    async fn get_services(&self, ctx: QueryContextRef) -> Result<Output>;
261
262    /// Get Jaeger operations. It's used for `/api/operations` and `/api/services/{service_name}/operations` API.
263    async fn get_operations(
264        &self,
265        ctx: QueryContextRef,
266        service_name: &str,
267        span_kind: Option<&str>,
268    ) -> Result<Output>;
269
270    /// Retrieves a trace by its unique identifier.
271    ///
272    /// This method is used to handle requests to the `/api/traces/{trace_id}` endpoint.
273    /// It accepts optional `start_time` and `end_time` parameters in nanoseconds to filter the trace data within a specific time range.
274    async fn get_trace(
275        &self,
276        ctx: QueryContextRef,
277        trace_id: &str,
278        start_time: Option<i64>,
279        end_time: Option<i64>,
280        limit: Option<usize>,
281    ) -> Result<Output>;
282
283    /// Find traces by query params. It's used for `/api/traces` API.
284    async fn find_traces(
285        &self,
286        ctx: QueryContextRef,
287        query_params: QueryTraceParams,
288    ) -> Result<Output>;
289}