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    /// Executes an ordinary HTTP put with optional batching. Debug and socket
99    /// callers retain [`Self::exec`]; the frontend clears HTTP batching selection
100    /// there so diagnostic requests preserve direct, per-point error attribution.
101    async fn exec_batch(&self, data_points: Vec<DataPoint>, ctx: QueryContextRef) -> Result<usize> {
102        self.exec(data_points, ctx).await
103    }
104}
105
106pub struct PromStoreResponse {
107    pub content_type: HeaderValue,
108    pub content_encoding: HeaderValue,
109    pub resp_metrics: HashMap<String, Value>,
110    pub body: Vec<u8>,
111}
112
113#[async_trait]
114pub trait PromStoreProtocolHandler {
115    /// Runs pre-write checks/hooks for prometheus remote write requests.
116    async fn pre_write(&self, request: &RowInsertRequests, ctx: QueryContextRef) -> Result<()>;
117
118    /// Writes one batch after [`Self::pre_write`] has succeeded for the entire request.
119    async fn write_prepared(
120        &self,
121        request: RowInsertRequests,
122        ctx: QueryContextRef,
123        with_metric_engine: bool,
124    ) -> Result<Output>;
125
126    /// Handling prometheus remote write requests
127    async fn write(
128        &self,
129        request: RowInsertRequests,
130        ctx: QueryContextRef,
131        with_metric_engine: bool,
132    ) -> Result<Output>;
133
134    /// Checks every batch before writing any of them.
135    async fn write_all(
136        &self,
137        requests: Vec<(QueryContextRef, RowInsertRequests)>,
138        with_metric_engine: bool,
139    ) -> Result<Vec<Result<Output>>>;
140
141    /// Handling prometheus remote read requests
142    async fn read(&self, request: ReadRequest, ctx: QueryContextRef) -> Result<PromStoreResponse>;
143}
144
145#[async_trait]
146pub trait OpenTelemetryProtocolHandler: PipelineHandler {
147    /// Handling opentelemetry metrics request
148    async fn metrics(
149        &self,
150        request: ExportMetricsServiceRequest,
151        ctx: QueryContextRef,
152    ) -> Result<MetricsIngestOutcome>;
153
154    /// Handling opentelemetry traces request
155    async fn traces(
156        &self,
157        pipeline_handler: PipelineHandlerRef,
158        request: ExportTraceServiceRequest,
159        pipeline: PipelineWay,
160        pipeline_params: GreptimePipelineParams,
161        table_name: String,
162        ctx: QueryContextRef,
163    ) -> Result<TraceIngestOutcome>;
164
165    async fn logs(
166        &self,
167        pipeline_handler: PipelineHandlerRef,
168        request: ExportLogsServiceRequest,
169        pipeline: PipelineWay,
170        pipeline_params: GreptimePipelineParams,
171        table_name: String,
172        ctx: QueryContextRef,
173    ) -> Result<Vec<Output>>;
174}
175
176/// PipelineHandler is responsible for handling pipeline related requests.
177///
178/// The "Pipeline" is a series of transformations that can be applied to unstructured
179/// data like logs. This handler is responsible to manage pipelines and accept data for
180/// processing.
181///
182/// The pipeline is stored in the database and can be retrieved by its name.
183#[async_trait]
184pub trait PipelineHandler {
185    async fn insert(&self, input: RowInsertRequests, ctx: QueryContextRef) -> Result<Output>;
186
187    /// Checks every batch before inserting any of them.
188    async fn insert_all(
189        &self,
190        inputs: Vec<(QueryContextRef, RowInsertRequests)>,
191    ) -> Result<Vec<Result<Output>>>;
192
193    fn check_pipeline_query_permission(&self, query_ctx: &QueryContextRef) -> Result<()>;
194
195    /// Loads a compiled pipeline for execution.
196    ///
197    /// This intentionally does not check pipeline-query permission: users with
198    /// write-only permission can ingest through an existing pipeline. Inspection
199    /// and preview callers must check query permission first; ingestion enforces
200    /// write and table-target permissions separately.
201    async fn get_pipeline(
202        &self,
203        name: &str,
204        version: PipelineVersion,
205        query_ctx: QueryContextRef,
206    ) -> Result<Arc<Pipeline>>;
207
208    async fn insert_pipeline(
209        &self,
210        name: &str,
211        content_type: &str,
212        pipeline: &str,
213        query_ctx: QueryContextRef,
214    ) -> Result<PipelineInfo>;
215
216    async fn delete_pipeline(
217        &self,
218        name: &str,
219        version: PipelineVersion,
220        query_ctx: QueryContextRef,
221    ) -> Result<Option<()>>;
222
223    async fn get_table(
224        &self,
225        table: &str,
226        query_ctx: &QueryContext,
227    ) -> std::result::Result<Option<Arc<table::Table>>, catalog::error::Error>;
228
229    //// Build a pipeline from a string.
230    fn build_pipeline(&self, pipeline: &str) -> Result<Pipeline>;
231
232    /// Get a original pipeline by name.
233    async fn get_pipeline_str(
234        &self,
235        name: &str,
236        version: PipelineVersion,
237        query_ctx: QueryContextRef,
238    ) -> Result<(String, TimestampNanosecond)>;
239}
240
241/// Handling dashboard as code CRUD
242pub type DashboardHandlerRef = Arc<dyn DashboardHandler + Send + Sync>;
243
244#[async_trait]
245pub trait DashboardHandler {
246    async fn save(&self, name: &str, definition: &str, ctx: QueryContextRef) -> Result<()>;
247
248    async fn list(&self, ctx: QueryContextRef) -> Result<Vec<DashboardDefinition>>;
249
250    async fn delete(&self, name: &str, ctx: QueryContextRef) -> Result<()>;
251}
252
253/// Handle log query requests.
254#[async_trait]
255pub trait LogQueryHandler {
256    /// Execute a log query.
257    async fn query(&self, query: LogQuery, ctx: QueryContextRef) -> Result<Output>;
258
259    /// Get catalog manager.
260    fn catalog_manager(&self, ctx: &QueryContext) -> Result<&dyn CatalogManager>;
261}
262
263/// Handle Jaeger query requests.
264#[async_trait]
265pub trait JaegerQueryHandler {
266    /// Get trace services. It's used for `/api/services` API.
267    async fn get_services(&self, ctx: QueryContextRef) -> Result<Output>;
268
269    /// Get Jaeger operations. It's used for `/api/operations` and `/api/services/{service_name}/operations` API.
270    async fn get_operations(
271        &self,
272        ctx: QueryContextRef,
273        service_name: &str,
274        span_kind: Option<&str>,
275    ) -> Result<Output>;
276
277    /// Retrieves a trace by its unique identifier.
278    ///
279    /// This method is used to handle requests to the `/api/traces/{trace_id}` endpoint.
280    /// It accepts optional `start_time` and `end_time` parameters in nanoseconds to filter the trace data within a specific time range.
281    async fn get_trace(
282        &self,
283        ctx: QueryContextRef,
284        trace_id: &str,
285        start_time: Option<i64>,
286        end_time: Option<i64>,
287        limit: Option<usize>,
288    ) -> Result<Output>;
289
290    /// Find traces by query params. It's used for `/api/traces` API.
291    async fn find_traces(
292        &self,
293        ctx: QueryContextRef,
294        query_params: QueryTraceParams,
295    ) -> Result<Output>;
296}