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 operator::insert::PreparedMetricInserts;
43use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest;
44use pipeline::{
45    GreptimePipelineParams, Pipeline, PipelineInfo, PipelineOptions, PipelineVersion, PipelineWay,
46};
47use serde_json::Value;
48use session::context::{QueryContext, QueryContextRef};
49use table::metadata::TableInfoRef;
50
51#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
52pub struct DashboardDefinition {
53    pub name: String,
54    pub definition: String,
55}
56
57use crate::error::Result;
58use crate::http::jaeger::QueryTraceParams;
59use crate::influxdb::InfluxdbRequest;
60use crate::opentsdb::codec::DataPoint;
61use crate::request_memory_limiter::ServerMemoryLimiter;
62pub type OpentsdbProtocolHandlerRef = Arc<dyn OpentsdbProtocolHandler + Send + Sync>;
63pub type InfluxdbLineProtocolHandlerRef = Arc<dyn InfluxdbLineProtocolHandler + Send + Sync>;
64pub type PromStoreProtocolHandlerRef = Arc<dyn PromStoreProtocolHandler + Send + Sync>;
65pub type OpenTelemetryProtocolHandlerRef = Arc<dyn OpenTelemetryProtocolHandler + Send + Sync>;
66pub type PipelineHandlerRef = Arc<dyn PipelineHandler + Send + Sync>;
67pub type LogQueryHandlerRef = Arc<dyn LogQueryHandler + Send + Sync>;
68pub type JaegerQueryHandlerRef = Arc<dyn JaegerQueryHandler + Send + Sync>;
69
70#[derive(Debug, Default, Clone)]
71pub struct TraceIngestOutcome {
72    pub write_cost: usize,
73    pub accepted_spans: usize,
74    pub rejected_spans: usize,
75    pub error_message: Option<String>,
76}
77
78/// Result of ingesting one OTLP metrics request or Arrow batch.
79#[derive(Debug, Default, Clone)]
80pub struct MetricsIngestOutcome {
81    pub write_cost: usize,
82    pub accepted_data_points: i64,
83    pub rejected_data_points: i64,
84    pub error_message: Option<String>,
85}
86
87#[async_trait]
88pub trait InfluxdbLineProtocolHandler {
89    async fn exec(&self, request: InfluxdbRequest, ctx: QueryContextRef) -> Result<Output>;
90}
91
92#[async_trait]
93pub trait OpentsdbProtocolHandler {
94    /// Checks all points in one external request before per-point debug execution.
95    async fn preflight(&self, data_points: &[DataPoint], ctx: QueryContextRef) -> Result<()>;
96
97    async fn exec(&self, data_points: Vec<DataPoint>, ctx: QueryContextRef) -> Result<usize>;
98
99    /// Executes an ordinary HTTP put with optional batching. Debug callers
100    /// retain [`Self::exec`]; the frontend clears HTTP batching selection
101    /// there so diagnostic requests preserve direct, per-point error attribution.
102    async fn exec_batch(&self, data_points: Vec<DataPoint>, ctx: QueryContextRef) -> Result<usize> {
103        self.exec(data_points, ctx).await
104    }
105}
106
107pub struct PromStoreResponse {
108    pub content_type: HeaderValue,
109    pub content_encoding: HeaderValue,
110    pub resp_metrics: HashMap<String, Value>,
111    pub body: Vec<u8>,
112}
113
114#[async_trait]
115pub trait PromStoreProtocolHandler {
116    /// Resolves metric destinations before source identities are attached to exemplars.
117    /// Requires pre-write checks and admission to have succeeded for the entire request.
118    async fn prepare_metric_write(
119        &self,
120        _request: RowInsertRequests,
121        _ctx: QueryContextRef,
122    ) -> Result<PreparedMetricInserts> {
123        crate::error::NotSupportedSnafu {
124            feat: "metric write preparation",
125        }
126        .fail()
127    }
128
129    /// Executes the same routed metric writes used to resolve exemplar source identities.
130    async fn write_prepared_metric(
131        &self,
132        _request: PreparedMetricInserts,
133        _ctx: QueryContextRef,
134    ) -> Result<Output> {
135        crate::error::NotSupportedSnafu {
136            feat: "prepared metric ingestion",
137        }
138        .fail()
139    }
140
141    /// Writes exemplars using table identities captured while preparing the source metrics.
142    async fn write_exemplars_with_sources(
143        &self,
144        exemplars: operator::insert::ExemplarBatch,
145        ctx: QueryContextRef,
146        _sources: &[TableInfoRef],
147    ) -> Result<Output> {
148        self.write_exemplars_prepared(exemplars, ctx).await
149    }
150
151    async fn write_exemplars_prepared(
152        &self,
153        _exemplars: operator::insert::ExemplarBatch,
154        _ctx: QueryContextRef,
155    ) -> Result<Output> {
156        crate::error::NotSupportedSnafu {
157            feat: "exemplar ingestion",
158        }
159        .fail()
160    }
161
162    /// Runs routing hooks and authorizes both the exemplar destination and source metric tables.
163    /// Handlers that accept exemplars must override this; [`Self::pre_write`] only sees metric rows.
164    async fn pre_write_exemplars(
165        &self,
166        _exemplars: &operator::insert::ExemplarBatch,
167        _ctx: QueryContextRef,
168    ) -> Result<()> {
169        crate::error::NotSupportedSnafu {
170            feat: "exemplar destination preflight",
171        }
172        .fail()
173    }
174
175    /// Runs pre-write checks/hooks for prometheus remote write requests.
176    async fn pre_write(&self, request: &RowInsertRequests, ctx: QueryContextRef) -> Result<()>;
177
178    /// Writes one batch after [`Self::pre_write`] has succeeded for the entire request.
179    async fn write_prepared(
180        &self,
181        request: RowInsertRequests,
182        ctx: QueryContextRef,
183        with_metric_engine: bool,
184    ) -> Result<Output>;
185
186    /// Handling prometheus remote write requests
187    async fn write(
188        &self,
189        request: RowInsertRequests,
190        ctx: QueryContextRef,
191        with_metric_engine: bool,
192    ) -> Result<Output>;
193
194    /// Checks every batch before writing any of them.
195    async fn write_all(
196        &self,
197        requests: Vec<(QueryContextRef, RowInsertRequests)>,
198        with_metric_engine: bool,
199    ) -> Result<Vec<Result<Output>>>;
200
201    /// Handling prometheus remote read requests
202    async fn read(&self, request: ReadRequest, ctx: QueryContextRef) -> Result<PromStoreResponse>;
203}
204
205#[async_trait]
206pub trait OpenTelemetryProtocolHandler: PipelineHandler {
207    /// Handles metrics, reserving row expansion against the transport's limiter.
208    /// The accompanying byte count includes permits already held by this request.
209    async fn metrics(
210        &self,
211        request: ExportMetricsServiceRequest,
212        ctx: QueryContextRef,
213        memory_limiter: Option<(ServerMemoryLimiter, u64)>,
214    ) -> Result<MetricsIngestOutcome>;
215
216    /// Handling opentelemetry traces request
217    async fn traces(
218        &self,
219        pipeline_handler: PipelineHandlerRef,
220        request: ExportTraceServiceRequest,
221        pipeline: PipelineWay,
222        pipeline_params: GreptimePipelineParams,
223        table_name: String,
224        ctx: QueryContextRef,
225    ) -> Result<TraceIngestOutcome>;
226
227    async fn logs(
228        &self,
229        pipeline_handler: PipelineHandlerRef,
230        request: ExportLogsServiceRequest,
231        pipeline: PipelineWay,
232        pipeline_params: GreptimePipelineParams,
233        table_name: String,
234        ctx: QueryContextRef,
235    ) -> Result<Vec<Output>>;
236}
237
238/// PipelineHandler is responsible for handling pipeline related requests.
239///
240/// The "Pipeline" is a series of transformations that can be applied to unstructured
241/// data like logs. This handler is responsible to manage pipelines and accept data for
242/// processing.
243///
244/// The pipeline is stored in the database and can be retrieved by its name.
245#[async_trait]
246pub trait PipelineHandler {
247    async fn insert(&self, input: RowInsertRequests, ctx: QueryContextRef) -> Result<Output>;
248
249    /// Checks every batch before inserting any of them.
250    async fn insert_all(
251        &self,
252        inputs: Vec<(QueryContextRef, RowInsertRequests)>,
253    ) -> Result<Vec<Result<Output>>>;
254
255    fn check_pipeline_query_permission(&self, query_ctx: &QueryContextRef) -> Result<()>;
256
257    /// Loads a compiled pipeline for execution.
258    ///
259    /// This intentionally does not check pipeline-query permission: users with
260    /// write-only permission can ingest through an existing pipeline. Inspection
261    /// and preview callers must check query permission first; ingestion enforces
262    /// write and table-target permissions separately.
263    async fn get_pipeline(
264        &self,
265        name: &str,
266        version: PipelineVersion,
267        query_ctx: QueryContextRef,
268    ) -> Result<Arc<Pipeline>>;
269
270    async fn insert_pipeline(
271        &self,
272        name: &str,
273        content_type: &str,
274        pipeline: &str,
275        query_ctx: QueryContextRef,
276    ) -> Result<PipelineInfo>;
277
278    async fn delete_pipeline(
279        &self,
280        name: &str,
281        version: PipelineVersion,
282        query_ctx: QueryContextRef,
283    ) -> Result<Option<()>>;
284
285    async fn get_table(
286        &self,
287        table: &str,
288        query_ctx: &QueryContext,
289    ) -> std::result::Result<Option<Arc<table::Table>>, catalog::error::Error>;
290
291    /// Returns the server's pipeline options.
292    fn pipeline_options(&self) -> &PipelineOptions;
293
294    //// Build a pipeline from a string.
295    fn build_pipeline(&self, pipeline: &str) -> Result<Pipeline>;
296
297    /// Get a original pipeline by name.
298    async fn get_pipeline_str(
299        &self,
300        name: &str,
301        version: PipelineVersion,
302        query_ctx: QueryContextRef,
303    ) -> Result<(String, TimestampNanosecond)>;
304}
305
306/// Handling dashboard as code CRUD
307pub type DashboardHandlerRef = Arc<dyn DashboardHandler + Send + Sync>;
308
309#[async_trait]
310pub trait DashboardHandler {
311    async fn save(&self, name: &str, definition: &str, ctx: QueryContextRef) -> Result<()>;
312
313    async fn list(&self, ctx: QueryContextRef) -> Result<Vec<DashboardDefinition>>;
314
315    async fn delete(&self, name: &str, ctx: QueryContextRef) -> Result<()>;
316}
317
318/// Handle log query requests.
319#[async_trait]
320pub trait LogQueryHandler {
321    /// Execute a log query.
322    async fn query(&self, query: LogQuery, ctx: QueryContextRef) -> Result<Output>;
323
324    /// Get catalog manager.
325    fn catalog_manager(&self, ctx: &QueryContext) -> Result<&dyn CatalogManager>;
326}
327
328/// Handle Jaeger query requests.
329#[async_trait]
330pub trait JaegerQueryHandler {
331    /// Get trace services. It's used for `/api/services` API.
332    async fn get_services(&self, ctx: QueryContextRef) -> Result<Output>;
333
334    /// Get Jaeger operations. It's used for `/api/operations` and `/api/services/{service_name}/operations` API.
335    async fn get_operations(
336        &self,
337        ctx: QueryContextRef,
338        service_name: &str,
339        span_kind: Option<&str>,
340    ) -> Result<Output>;
341
342    /// Retrieves a trace by its unique identifier.
343    ///
344    /// This method is used to handle requests to the `/api/traces/{trace_id}` endpoint.
345    /// It accepts optional `start_time` and `end_time` parameters in nanoseconds to filter the trace data within a specific time range.
346    async fn get_trace(
347        &self,
348        ctx: QueryContextRef,
349        trace_id: &str,
350        start_time: Option<i64>,
351        end_time: Option<i64>,
352        limit: Option<usize>,
353    ) -> Result<Output>;
354
355    /// Find traces by query params. It's used for `/api/traces` API.
356    async fn find_traces(
357        &self,
358        ctx: QueryContextRef,
359        query_params: QueryTraceParams,
360    ) -> Result<Output>;
361}
362
363/// Handler for the PostgreSQL `COPY ... FROM STDIN` (copy-in) sub-protocol.
364///
365/// The servers layer owns the wire protocol and data parsing; this trait is
366/// the boundary to catalog lookup and ingestion, implemented by the
367/// frontend instance.
368#[async_trait]
369pub trait CopyInHandler: Send + Sync {
370    /// Resolves the target table of a COPY and returns its metadata, or
371    /// `None` when the table does not exist. Implementations should also
372    /// enforce the write permission for the table here so unauthorized
373    /// copies fail before any data is transferred.
374    async fn copy_in_table(
375        &self,
376        catalog: &str,
377        schema: &str,
378        table: &str,
379        query_ctx: QueryContextRef,
380    ) -> Result<Option<TableInfoRef>>;
381
382    /// Validates that a COPY target's resolved catalog/schema is within
383    /// the session's allowed scope, before any data is transferred.
384    /// Enforces the `disallow_cross_catalog_query` restriction for
385    /// targets that leave the session's catalog — the same restriction
386    /// SQL INSERT and `copy_in_table` enforce. A no-op when the
387    /// restriction is disabled.
388    async fn copy_in_validate_scope(
389        &self,
390        catalog: &str,
391        schema: &str,
392        query_ctx: QueryContextRef,
393    ) -> Result<()>;
394
395    /// Ingests Arrow batches through the same bulk path as Flight DoPut.
396    /// The COPY transport owns framing and memory admission; implementations
397    /// retain stream-level authorization and schema reconciliation.
398    fn copy_in_arrow(
399        &self,
400        _stream: crate::grpc::flight::PutRecordBatchRequestStream,
401        _query_ctx: QueryContextRef,
402    ) -> Result<
403        futures::stream::BoxStream<'static, Result<common_grpc::flight::do_put::DoPutResponse>>,
404    > {
405        crate::error::NotSupportedSnafu {
406            feat: "Arrow COPY ingestion",
407        }
408        .fail()
409    }
410
411    /// Inserts a parsed batch produced by a COPY stream. Returns the
412    /// number of affected rows.
413    async fn copy_in_insert(
414        &self,
415        requests: RowInsertRequests,
416        query_ctx: QueryContextRef,
417    ) -> Result<Output>;
418}
419
420pub type CopyInHandlerRef = Arc<dyn CopyInHandler + Send + Sync>;