Skip to main content

servers/
pipeline.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
15use std::collections::BTreeMap;
16use std::sync::Arc;
17
18use ahash::{HashMap, HashMapExt};
19use api::v1::helper::time_index_column_schema;
20use api::v1::{ColumnDataType, RowInsertRequest, Rows, Value};
21use common_time::timestamp::TimeUnit;
22use pipeline::{
23    ContextReq, DispatchedTo, GREPTIME_INTERNAL_IDENTITY_PIPELINE_NAME, Pipeline, PipelineContext,
24    PipelineDefinition, PipelineExecOutput, SchemaInfo, TransformedOutput, TransformerMode,
25    identity_pipeline, unwrap_or_continue_if_err,
26};
27use session::context::{Channel, QueryContextRef};
28use snafu::ResultExt;
29use vrl::value::Value as VrlValue;
30
31use crate::error::{PipelineSnafu, Result};
32use crate::http::event::PipelineIngestRequest;
33use crate::metrics::{
34    METRIC_FAILURE_VALUE, METRIC_HTTP_LOGS_TRANSFORM_ELAPSED, METRIC_SUCCESS_VALUE,
35};
36use crate::query_handler::PipelineHandlerRef;
37
38macro_rules! push_to_map {
39    ($map:expr, $key:expr, $value:expr, $capacity:expr) => {
40        $map.entry($key)
41            .or_insert_with(|| Vec::with_capacity($capacity))
42            .push($value);
43    };
44}
45
46/// Never call this on `GreptimeIdentityPipeline` because it's a real pipeline
47pub async fn get_pipeline(
48    pipeline_def: &PipelineDefinition,
49    handler: &PipelineHandlerRef,
50    query_ctx: &QueryContextRef,
51) -> Result<Arc<Pipeline>> {
52    match pipeline_def {
53        PipelineDefinition::Resolved(pipeline) => Ok(pipeline.clone()),
54        PipelineDefinition::ByNameAndValue((name, version)) => {
55            handler
56                .get_pipeline(name, *version, query_ctx.clone())
57                .await
58        }
59        _ => {
60            unreachable!("Never call get_pipeline on identity.")
61        }
62    }
63}
64
65pub(crate) async fn run_pipeline(
66    handler: &PipelineHandlerRef,
67    pipeline_ctx: &PipelineContext<'_>,
68    pipeline_req: PipelineIngestRequest,
69    query_ctx: &QueryContextRef,
70    is_top_level: bool,
71) -> Result<ContextReq> {
72    if pipeline_ctx.pipeline_definition.is_identity() {
73        run_identity_pipeline(handler, pipeline_ctx, pipeline_req, query_ctx).await
74    } else {
75        run_custom_pipeline(handler, pipeline_ctx, pipeline_req, query_ctx, is_top_level).await
76    }
77}
78
79async fn run_identity_pipeline(
80    handler: &PipelineHandlerRef,
81    pipeline_ctx: &PipelineContext<'_>,
82    pipeline_req: PipelineIngestRequest,
83    query_ctx: &QueryContextRef,
84) -> Result<ContextReq> {
85    let PipelineIngestRequest {
86        table: table_name,
87        values: data_array,
88    } = pipeline_req;
89    let table = if pipeline_ctx.channel == Channel::Prometheus {
90        None
91    } else {
92        handler.get_table(&table_name, query_ctx).await?
93    };
94    identity_pipeline(data_array, table, pipeline_ctx)
95        .map(|opt_map| ContextReq::from_opt_map(opt_map, table_name))
96        .context(PipelineSnafu)
97}
98
99async fn run_custom_pipeline(
100    handler: &PipelineHandlerRef,
101    pipeline_ctx: &PipelineContext<'_>,
102    pipeline_req: PipelineIngestRequest,
103    query_ctx: &QueryContextRef,
104    is_top_level: bool,
105) -> Result<ContextReq> {
106    let skip_error = pipeline_ctx.pipeline_param.skip_error();
107    let db = query_ctx.get_db_string();
108    let pipeline = get_pipeline(pipeline_ctx.pipeline_definition, handler, query_ctx).await?;
109
110    let transform_timer = std::time::Instant::now();
111
112    let PipelineIngestRequest {
113        table: table_name,
114        values: pipeline_maps,
115    } = pipeline_req;
116    let arr_len = pipeline_maps.len();
117    let mut transformed_map = HashMap::new();
118    let mut dispatched: BTreeMap<DispatchedTo, Vec<VrlValue>> = BTreeMap::new();
119
120    let mut schema_info = match pipeline.transformer() {
121        TransformerMode::GreptimeTransformer(greptime_transformer) => {
122            SchemaInfo::from_schema_list(greptime_transformer.schemas().clone())
123        }
124        TransformerMode::AutoTransform(ts_name, timeunit) => {
125            let timeunit = match timeunit {
126                TimeUnit::Second => ColumnDataType::TimestampSecond,
127                TimeUnit::Millisecond => ColumnDataType::TimestampMillisecond,
128                TimeUnit::Microsecond => ColumnDataType::TimestampMicrosecond,
129                TimeUnit::Nanosecond => ColumnDataType::TimestampNanosecond,
130            };
131
132            let mut schema_info = SchemaInfo::default();
133            schema_info
134                .schema
135                .push(time_index_column_schema(ts_name, timeunit).into());
136
137            schema_info
138        }
139    };
140
141    let table = handler.get_table(&table_name, query_ctx).await?;
142    schema_info.set_table(table);
143
144    for pipeline_map in pipeline_maps {
145        let result = pipeline
146            .exec_mut(pipeline_map, pipeline_ctx, &mut schema_info)
147            .inspect_err(|_| {
148                METRIC_HTTP_LOGS_TRANSFORM_ELAPSED
149                    .with_label_values(&[db.as_str(), METRIC_FAILURE_VALUE])
150                    .observe(transform_timer.elapsed().as_secs_f64());
151            })
152            .context(PipelineSnafu);
153
154        let r = unwrap_or_continue_if_err!(result, skip_error);
155        match r {
156            PipelineExecOutput::Transformed(TransformedOutput { rows_by_context }) => {
157                // Process each ContextOpt group separately
158                for (opt, rows_with_suffix) in rows_by_context {
159                    // Group rows by table name within each context
160                    for (row, table_suffix) in rows_with_suffix {
161                        let act_table_name = table_suffix_to_table_name(&table_name, table_suffix);
162                        transformed_map
163                            .entry((opt.clone(), act_table_name))
164                            .or_insert_with(|| Vec::with_capacity(arr_len))
165                            .push(row);
166                    }
167                }
168            }
169            PipelineExecOutput::DispatchedTo(dispatched_to, val) => {
170                push_to_map!(dispatched, dispatched_to, val, arr_len);
171            }
172            PipelineExecOutput::Filtered => {
173                continue;
174            }
175        }
176    }
177
178    let mut results = ContextReq::default();
179
180    // Process transformed outputs. Each entry in transformed_map contains
181    // Vec<Row> grouped by (opt, table_name).
182    let column_count = schema_info.schema.len();
183    for ((opt, table_name), mut rows) in transformed_map {
184        // Pad rows to match final schema size (schema may have evolved during processing)
185        for row in &mut rows {
186            let diff = column_count.saturating_sub(row.values.len());
187            for _ in 0..diff {
188                row.values.push(Value { value_data: None });
189            }
190        }
191
192        results.add_row(
193            &opt,
194            RowInsertRequest {
195                rows: Some(Rows {
196                    rows,
197                    schema: schema_info.column_schemas()?,
198                }),
199                table_name: table_name.clone(),
200            },
201        );
202    }
203
204    // if current pipeline contains dispatcher and has several rules, we may
205    // already accumulated several dispatched rules and rows.
206    for (dispatched_to, coll) in dispatched {
207        // we generate the new table name according to `table_part` and
208        // current custom table name.
209        let table_name = dispatched_to.dispatched_to_table_name(&table_name);
210        let next_pipeline_name = dispatched_to
211            .pipeline
212            .as_deref()
213            .unwrap_or(GREPTIME_INTERNAL_IDENTITY_PIPELINE_NAME);
214
215        // run pipeline recursively.
216        let next_pipeline_def =
217            PipelineDefinition::from_name(next_pipeline_name, None, None).context(PipelineSnafu)?;
218        let next_pipeline_ctx = PipelineContext::new(
219            &next_pipeline_def,
220            pipeline_ctx.pipeline_param,
221            pipeline_ctx.channel,
222        );
223        let requests = Box::pin(run_pipeline(
224            handler,
225            &next_pipeline_ctx,
226            PipelineIngestRequest {
227                table: table_name,
228                values: coll,
229            },
230            query_ctx,
231            false,
232        ))
233        .await?;
234
235        results.merge(requests);
236    }
237
238    if is_top_level {
239        METRIC_HTTP_LOGS_TRANSFORM_ELAPSED
240            .with_label_values(&[db.as_str(), METRIC_SUCCESS_VALUE])
241            .observe(transform_timer.elapsed().as_secs_f64());
242    }
243
244    Ok(results)
245}
246
247#[inline]
248fn table_suffix_to_table_name(table_name: &String, table_suffix: Option<String>) -> String {
249    match table_suffix {
250        Some(suffix) => format!("{}{}", table_name, suffix),
251        None => table_name.clone(),
252    }
253}