1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::borrow::Cow;
use std::sync::Arc;

use api::prom_store::remote::ReadRequest;
use api::v1::greptime_request::Request;
use api::v1::RowInsertRequests;
use async_trait::async_trait;
use common_error::ext::ErrorExt;
use common_query::Output;
use datafusion_expr::LogicalPlan;
use query::parser::PromQuery;
use serde_json::Value;
use session::context::QueryContextRef;
use sql::statements::statement::Statement;

/// SqlQueryInterceptor can track life cycle of a sql query and customize or
/// abort its execution at given point.
pub trait SqlQueryInterceptor {
    type Error: ErrorExt;

    /// Called before a query string is parsed into sql statements.
    /// The implementation is allowed to change the sql string if needed.
    fn pre_parsing<'a>(
        &self,
        query: &'a str,
        _query_ctx: QueryContextRef,
    ) -> Result<Cow<'a, str>, Self::Error> {
        Ok(Cow::Borrowed(query))
    }

    /// Called after sql is parsed into statements. This interceptor is called
    /// on each statement and the implementation can alter the statement or
    /// abort execution by raising an error.
    fn post_parsing(
        &self,
        statements: Vec<Statement>,
        _query_ctx: QueryContextRef,
    ) -> Result<Vec<Statement>, Self::Error> {
        Ok(statements)
    }

    /// Called before sql is actually executed. This hook is not called at the moment.
    fn pre_execute(
        &self,
        _statement: &Statement,
        _plan: Option<&LogicalPlan>,
        _query_ctx: QueryContextRef,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Called after execution finished. The implementation can modify the
    /// output if needed.
    fn post_execute(
        &self,
        output: Output,
        _query_ctx: QueryContextRef,
    ) -> Result<Output, Self::Error> {
        Ok(output)
    }
}

pub type SqlQueryInterceptorRef<E> =
    Arc<dyn SqlQueryInterceptor<Error = E> + Send + Sync + 'static>;

impl<E> SqlQueryInterceptor for Option<&SqlQueryInterceptorRef<E>>
where
    E: ErrorExt,
{
    type Error = E;

    fn pre_parsing<'a>(
        &self,
        query: &'a str,
        query_ctx: QueryContextRef,
    ) -> Result<Cow<'a, str>, Self::Error> {
        if let Some(this) = self {
            this.pre_parsing(query, query_ctx)
        } else {
            Ok(Cow::Borrowed(query))
        }
    }

    fn post_parsing(
        &self,
        statements: Vec<Statement>,
        query_ctx: QueryContextRef,
    ) -> Result<Vec<Statement>, Self::Error> {
        if let Some(this) = self {
            this.post_parsing(statements, query_ctx)
        } else {
            Ok(statements)
        }
    }

    fn pre_execute(
        &self,
        statement: &Statement,
        plan: Option<&LogicalPlan>,
        query_ctx: QueryContextRef,
    ) -> Result<(), Self::Error> {
        if let Some(this) = self {
            this.pre_execute(statement, plan, query_ctx)
        } else {
            Ok(())
        }
    }

    fn post_execute(
        &self,
        output: Output,
        query_ctx: QueryContextRef,
    ) -> Result<Output, Self::Error> {
        if let Some(this) = self {
            this.post_execute(output, query_ctx)
        } else {
            Ok(output)
        }
    }
}

/// GrpcQueryInterceptor can track life cycle of a grpc request and customize or
/// abort its execution at given point.
pub trait GrpcQueryInterceptor {
    type Error: ErrorExt;

    /// Called before request is actually executed.
    fn pre_execute(
        &self,
        _request: &Request,
        _query_ctx: QueryContextRef,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Called after execution finished. The implementation can modify the
    /// output if needed.
    fn post_execute(
        &self,
        output: Output,
        _query_ctx: QueryContextRef,
    ) -> Result<Output, Self::Error> {
        Ok(output)
    }
}

pub type GrpcQueryInterceptorRef<E> =
    Arc<dyn GrpcQueryInterceptor<Error = E> + Send + Sync + 'static>;

impl<E> GrpcQueryInterceptor for Option<&GrpcQueryInterceptorRef<E>>
where
    E: ErrorExt,
{
    type Error = E;

    fn pre_execute(
        &self,
        _request: &Request,
        _query_ctx: QueryContextRef,
    ) -> Result<(), Self::Error> {
        if let Some(this) = self {
            this.pre_execute(_request, _query_ctx)
        } else {
            Ok(())
        }
    }

    fn post_execute(
        &self,
        output: Output,
        _query_ctx: QueryContextRef,
    ) -> Result<Output, Self::Error> {
        if let Some(this) = self {
            this.post_execute(output, _query_ctx)
        } else {
            Ok(output)
        }
    }
}

/// PromQueryInterceptor can track life cycle of a prometheus request and customize or
/// abort its execution at given point.
pub trait PromQueryInterceptor {
    type Error: ErrorExt;

    /// Called before request is actually executed.
    fn pre_execute(
        &self,
        _query: &PromQuery,
        _query_ctx: QueryContextRef,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Called after execution finished. The implementation can modify the
    /// output if needed.
    fn post_execute(
        &self,
        output: Output,
        _query_ctx: QueryContextRef,
    ) -> Result<Output, Self::Error> {
        Ok(output)
    }
}

pub type PromQueryInterceptorRef<E> =
    Arc<dyn PromQueryInterceptor<Error = E> + Send + Sync + 'static>;

impl<E> PromQueryInterceptor for Option<PromQueryInterceptorRef<E>>
where
    E: ErrorExt,
{
    type Error = E;

    fn pre_execute(
        &self,
        query: &PromQuery,
        query_ctx: QueryContextRef,
    ) -> Result<(), Self::Error> {
        if let Some(this) = self {
            this.pre_execute(query, query_ctx)
        } else {
            Ok(())
        }
    }

    fn post_execute(
        &self,
        output: Output,
        query_ctx: QueryContextRef,
    ) -> Result<Output, Self::Error> {
        if let Some(this) = self {
            this.post_execute(output, query_ctx)
        } else {
            Ok(output)
        }
    }
}

/// ScriptInterceptor can track life cycle of a script request and customize or
/// abort its execution at given point.
pub trait ScriptInterceptor {
    type Error: ErrorExt;

    /// Called before script request is actually executed.
    fn pre_execute(&self, _name: &str, _query_ctx: QueryContextRef) -> Result<(), Self::Error> {
        Ok(())
    }
}

pub type ScriptInterceptorRef<E> = Arc<dyn ScriptInterceptor<Error = E> + Send + Sync + 'static>;

impl<E: ErrorExt> ScriptInterceptor for Option<ScriptInterceptorRef<E>> {
    type Error = E;

    fn pre_execute(&self, name: &str, query_ctx: QueryContextRef) -> Result<(), Self::Error> {
        if let Some(this) = self {
            this.pre_execute(name, query_ctx)
        } else {
            Ok(())
        }
    }
}

/// LineProtocolInterceptor can track life cycle of a line protocol request
/// and customize or abort its execution at given point.
#[async_trait]
pub trait LineProtocolInterceptor {
    type Error: ErrorExt;

    fn pre_execute(&self, _line: &str, _query_ctx: QueryContextRef) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Called after the lines are converted to the [RowInsertRequests].
    /// We can then modify the resulting requests if needed.
    /// Typically used in some backward compatibility situation.
    async fn post_lines_conversion(
        &self,
        requests: RowInsertRequests,
        query_context: QueryContextRef,
    ) -> Result<RowInsertRequests, Self::Error> {
        let _ = query_context;
        Ok(requests)
    }
}

pub type LineProtocolInterceptorRef<E> =
    Arc<dyn LineProtocolInterceptor<Error = E> + Send + Sync + 'static>;

#[async_trait]
impl<E: ErrorExt> LineProtocolInterceptor for Option<LineProtocolInterceptorRef<E>> {
    type Error = E;

    fn pre_execute(&self, line: &str, query_ctx: QueryContextRef) -> Result<(), Self::Error> {
        if let Some(this) = self {
            this.pre_execute(line, query_ctx)
        } else {
            Ok(())
        }
    }

    async fn post_lines_conversion(
        &self,
        requests: RowInsertRequests,
        query_context: QueryContextRef,
    ) -> Result<RowInsertRequests, Self::Error> {
        if let Some(this) = self {
            this.post_lines_conversion(requests, query_context).await
        } else {
            Ok(requests)
        }
    }
}

/// OpenTelemetryProtocolInterceptor can track life cycle of an open telemetry protocol request
/// and customize or abort its execution at given point.
pub trait OpenTelemetryProtocolInterceptor {
    type Error: ErrorExt;

    fn pre_execute(&self, _query_ctx: QueryContextRef) -> Result<(), Self::Error> {
        Ok(())
    }
}

pub type OpenTelemetryProtocolInterceptorRef<E> =
    Arc<dyn OpenTelemetryProtocolInterceptor<Error = E> + Send + Sync + 'static>;

impl<E: ErrorExt> OpenTelemetryProtocolInterceptor
    for Option<OpenTelemetryProtocolInterceptorRef<E>>
{
    type Error = E;

    fn pre_execute(&self, query_ctx: QueryContextRef) -> Result<(), Self::Error> {
        if let Some(this) = self {
            this.pre_execute(query_ctx)
        } else {
            Ok(())
        }
    }
}

/// PromStoreProtocolInterceptor can track life cycle of a prom store request
/// and customize or abort its execution at given point.
pub trait PromStoreProtocolInterceptor {
    type Error: ErrorExt;

    fn pre_write(
        &self,
        _write_req: &RowInsertRequests,
        _ctx: QueryContextRef,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    fn pre_read(&self, _read_req: &ReadRequest, _ctx: QueryContextRef) -> Result<(), Self::Error> {
        Ok(())
    }
}

pub type PromStoreProtocolInterceptorRef<E> =
    Arc<dyn PromStoreProtocolInterceptor<Error = E> + Send + Sync + 'static>;

impl<E: ErrorExt> PromStoreProtocolInterceptor for Option<PromStoreProtocolInterceptorRef<E>> {
    type Error = E;

    fn pre_write(
        &self,
        write_req: &RowInsertRequests,
        ctx: QueryContextRef,
    ) -> Result<(), Self::Error> {
        if let Some(this) = self {
            this.pre_write(write_req, ctx)
        } else {
            Ok(())
        }
    }

    fn pre_read(&self, read_req: &ReadRequest, ctx: QueryContextRef) -> Result<(), Self::Error> {
        if let Some(this) = self {
            this.pre_read(read_req, ctx)
        } else {
            Ok(())
        }
    }
}

/// LogIngestInterceptor can track life cycle of a log ingestion request
/// and customize or abort its execution at given point.
pub trait LogIngestInterceptor {
    type Error: ErrorExt;

    /// Called before pipeline execution.
    fn pre_pipeline(
        &self,
        values: Vec<Value>,
        _query_ctx: QueryContextRef,
    ) -> Result<Vec<Value>, Self::Error> {
        Ok(values)
    }

    /// Called before insertion.
    fn pre_ingest(
        &self,
        request: RowInsertRequests,
        _query_ctx: QueryContextRef,
    ) -> Result<RowInsertRequests, Self::Error> {
        Ok(request)
    }
}

pub type LogIngestInterceptorRef<E> =
    Arc<dyn LogIngestInterceptor<Error = E> + Send + Sync + 'static>;

impl<E> LogIngestInterceptor for Option<&LogIngestInterceptorRef<E>>
where
    E: ErrorExt,
{
    type Error = E;

    fn pre_pipeline(
        &self,
        values: Vec<Value>,
        query_ctx: QueryContextRef,
    ) -> Result<Vec<Value>, Self::Error> {
        if let Some(this) = self {
            this.pre_pipeline(values, query_ctx)
        } else {
            Ok(values)
        }
    }

    fn pre_ingest(
        &self,
        request: RowInsertRequests,
        query_ctx: QueryContextRef,
    ) -> Result<RowInsertRequests, Self::Error> {
        if let Some(this) = self {
            this.pre_ingest(request, query_ctx)
        } else {
            Ok(request)
        }
    }
}