Skip to main content

servers/postgres/copy_in/
otlp.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//! The `otlp` format for COPY FROM STDIN: one binary OTLP payload for
16//! any of the three signals — `ExportMetricsServiceRequest`,
17//! `ExportTraceServiceRequest` or `ExportLogsServiceRequest`.
18//!
19//! `COPY FROM STDIN WITH (FORMAT otlp [, signal 'traces'] [, <options>])`
20//! is a GreptimeDB-specific, **binary** format (wire format code 1).
21//! Metrics are table-less; traces and logs also accept
22//! `COPY [catalog.][schema.]table FROM STDIN`. For those signals the
23//! destination precedence is `WITH (table_name ...)`, then the COPY
24//! target's table name, then the signal's default table. A qualified COPY
25//! target sets the catalog/schema even when `table_name` overrides its
26//! table name. Targets need not exist before ingestion. Column lists
27//! are not supported: the payload determines the ingested columns.
28//! A target that leaves the session's catalog/schema is subject to the
29//! same `disallow_cross_catalog_query` restriction as SQL INSERT and the
30//! csv format, and the user provider must authorize the target scope —
31//! the same `UserProvider::authorize` check a login to that database
32//! would run — before any data is transferred.
33//!
34//! This format does not decode here: the whole payload is buffered
35//! until `CopyDone` — exactly like an
36//! OTLP/HTTP request body — then decoded and completed through the
37//! frontend's `OpenTelemetryProtocolHandler`, the same path the
38//! `/v1/otlp/v1/{metrics,traces,logs}` endpoints use, under the
39//! connection's regular postgres query context.
40//!
41//! The `WITH` options carry what the HTTP endpoints take as request
42//! headers; values already provided by the postgres session (database,
43//! user, permissions) are not repeated. Option semantics, defaults and
44//! parsing helpers are shared with the HTTP extractors (`truthy`,
45//! `SelectInfo`, `GreptimePipelineParams`, `PipelineWay`), so the two
46//! ingestion routes cannot drift.
47//!
48//! One COPY statement is one bounded ingestion request (see
49//! [`crate::postgres::copy_in::COPY_IN_MAX_PAYLOAD_BYTES`]).
50
51use ahash::HashSet;
52
53use pgwire::error::PgWireResult;
54use pipeline::truthy;
55use session::protocol_ctx::OtlpMetricTranslationStrategy;
56
57use crate::postgres::copy_in::bad_copy_data;
58use crate::postgres::copy_in::codec::CopyFormat;
59use crate::postgres::copy_in::options::{CopyOptionSet, CopyOptionValue};
60
61/// The format's validated options: the signal and its header-equivalent
62/// configuration, carried to the flush that completes the copy.
63#[derive(Debug, Clone)]
64pub(super) struct OtlpOptions {
65    pub(super) signal: OtlpSignal,
66}
67
68#[derive(Debug, Clone)]
69pub(super) enum OtlpSignal {
70    /// Metric options mirroring the `x-greptime-otlp-metric-*` headers.
71    Metrics {
72        /// Persist all resource attributes; `resource_attrs` then acts
73        /// as an exclude list, otherwise as an include list.
74        promote_all_resource_attrs: bool,
75        resource_attrs: HashSet<String>,
76        promote_scope_attrs: bool,
77        translation_strategy: OtlpMetricTranslationStrategy,
78    },
79    /// Trace options mirroring `x-greptime-trace-table-name` and the
80    /// pipeline headers. The raw pipeline-params string is parsed by the
81    /// shared `GreptimePipelineParams::from_params` when the copy
82    /// completes, like the HTTP request does.
83    Traces {
84        table_name: Option<String>,
85        pipeline_name: Option<String>,
86        pipeline_version: Option<String>,
87        pipeline_params: Option<String>,
88    },
89    /// Log options mirroring `x-greptime-log-table-name`,
90    /// `x-greptime-log-extract-keys` and the pipeline headers.
91    Logs {
92        table_name: Option<String>,
93        pipeline_name: Option<String>,
94        pipeline_version: Option<String>,
95        pipeline_params: Option<String>,
96        extract_keys: Option<String>,
97    },
98}
99
100pub(super) fn build_otlp_codec(mut options: CopyOptionSet) -> PgWireResult<CopyFormat> {
101    let signal = options.take_string("signal")?;
102    let metric_options = (
103        take_truthy(&mut options, "promote_all_resource_attrs")?,
104        options.take_string("resource_attrs")?,
105        take_truthy(&mut options, "promote_scope_attrs")?,
106        options.take_string("translation_strategy")?,
107    );
108    let trace_log_options = (
109        options.take_string("table_name")?,
110        options.take_string("pipeline_name")?,
111        options.take_string("pipeline_version")?,
112        options.take_string("pipeline_params")?,
113    );
114    let extract_keys = options.take_string("extract_keys")?;
115    options.reject_leftovers("otlp")?;
116
117    let unexpected = |option: &str| {
118        bad_copy_data(format!(
119            "COPY option \"{option}\" does not apply to the selected signal"
120        ))
121    };
122    let signal = match signal.as_deref() {
123        None | Some("metrics") => {
124            if trace_log_options != (None, None, None, None) || extract_keys.is_some() {
125                return Err(unexpected("table_name/pipeline/extract_keys"));
126            }
127            let (promote_all, resource_attrs, promote_scope, strategy) = metric_options;
128            let promote_all = promote_all.unwrap_or(false);
129            let promote_scope = promote_scope.unwrap_or(false);
130            let translation_strategy = match strategy.as_deref() {
131                None => OtlpMetricTranslationStrategy::default(),
132                // Same values as the HTTP header (`VALUES`), parsed by
133                // the same `FromStr`.
134                Some(value) => value.parse().map_err(|_| {
135                    bad_copy_data(format!(
136                        "invalid translation_strategy \"{value}\", expected one of: {}",
137                        OtlpMetricTranslationStrategy::VALUES.join(", ")
138                    ))
139                })?,
140            };
141            let resource_attrs = resource_attrs
142                // Same ';'-separated list and trimming as the header
143                // extractor.
144                .map(|s| s.split(';').map(|s| s.trim().to_string()).collect())
145                .unwrap_or_default();
146            OtlpSignal::Metrics {
147                promote_all_resource_attrs: promote_all,
148                resource_attrs,
149                promote_scope_attrs: promote_scope,
150                translation_strategy,
151            }
152        }
153        Some("traces") | Some("logs") => {
154            if metric_options != (None, None, None, None) {
155                return Err(unexpected("promote_*/resource_attrs/translation_strategy"));
156            }
157            let (table_name, pipeline_name, pipeline_version, pipeline_params) = trace_log_options;
158            if signal.as_deref() == Some("traces") {
159                if extract_keys.is_some() {
160                    // `extract_keys` only applies to logs.
161                    return Err(unexpected("extract_keys"));
162                }
163                OtlpSignal::Traces {
164                    table_name,
165                    pipeline_name,
166                    pipeline_version,
167                    pipeline_params,
168                }
169            } else {
170                OtlpSignal::Logs {
171                    table_name,
172                    pipeline_name,
173                    pipeline_version,
174                    pipeline_params,
175                    extract_keys,
176                }
177            }
178        }
179        Some(unknown) => {
180            return Err(bad_copy_data(format!(
181                "invalid signal \"{unknown}\", expected one of: metrics, traces, logs"
182            )));
183        }
184    };
185    Ok(CopyFormat::Otlp(OtlpOptions { signal }))
186}
187
188/// Takes a boolean option with the HTTP header's exact truthy
189/// spellings (`true`, `1`, `yes`, `on`, `t`), plus the COPY forms
190/// (bare flag or `TRUE`/`FALSE`), so both routes accept the same values.
191fn take_truthy(options: &mut CopyOptionSet, key: &str) -> PgWireResult<Option<bool>> {
192    match options.take_value(key) {
193        None => Ok(None),
194        Some(CopyOptionValue::Flag) => Ok(Some(true)),
195        Some(CopyOptionValue::Boolean(b)) => Ok(Some(b)),
196        Some(CopyOptionValue::String(v)) | Some(CopyOptionValue::Ident(v)) => Ok(Some(truthy(v))),
197        Some(other) => Err(bad_copy_data(format!(
198            "COPY option {key} requires a boolean value, got {}",
199            other.kind()
200        ))),
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207    use crate::postgres::copy_in::options::CopyOptionValue;
208
209    fn opts(entries: &[(&str, CopyOptionValue)]) -> CopyOptionSet {
210        let mut set = CopyOptionSet::default();
211        for (k, v) in entries {
212            set.insert((*k).into(), v.clone()).unwrap();
213        }
214        set
215    }
216
217    #[test]
218    fn test_signal_defaults_and_options() {
219        // Default signal is metrics.
220        assert!(matches!(
221            build_otlp_codec(CopyOptionSet::default()).unwrap(),
222            CopyFormat::Otlp(OtlpOptions {
223                signal: OtlpSignal::Metrics { .. }
224            })
225        ));
226
227        // Metric options parse like the headers.
228        let format = build_otlp_codec(opts(&[
229            ("promote_all_resource_attrs", CopyOptionValue::Flag),
230            (
231                "resource_attrs",
232                CopyOptionValue::String("service.name; host.id ".into()),
233            ),
234            ("promote_scope_attrs", CopyOptionValue::Flag),
235            (
236                "translation_strategy",
237                CopyOptionValue::String("NoTranslation".into()),
238            ),
239        ]))
240        .unwrap();
241        let CopyFormat::Otlp(OtlpOptions {
242            signal:
243                OtlpSignal::Metrics {
244                    promote_all_resource_attrs,
245                    resource_attrs,
246                    promote_scope_attrs,
247                    translation_strategy,
248                },
249        }) = format
250        else {
251            panic!("expected metrics");
252        };
253        assert!(promote_all_resource_attrs && promote_scope_attrs);
254        assert_eq!(
255            resource_attrs,
256            ["service.name", "host.id"]
257                .into_iter()
258                .map(String::from)
259                .collect()
260        );
261        assert!(matches!(
262            translation_strategy,
263            OtlpMetricTranslationStrategy::NoTranslation
264        ));
265
266        // Traces and logs accept their header equivalents.
267        assert!(matches!(
268            build_otlp_codec(opts(&[(
269                "signal",
270                CopyOptionValue::String("traces".into())
271            )]))
272            .unwrap(),
273            CopyFormat::Otlp(OtlpOptions {
274                signal: OtlpSignal::Traces { .. }
275            })
276        ));
277        assert!(matches!(
278            build_otlp_codec(opts(&[
279                ("signal", CopyOptionValue::String("logs".into())),
280                ("table_name", CopyOptionValue::String("my_logs".into())),
281                ("extract_keys", CopyOptionValue::String("a,b".into())),
282            ]))
283            .unwrap(),
284            CopyFormat::Otlp(OtlpOptions {
285                signal: OtlpSignal::Logs { .. }
286            })
287        ));
288    }
289
290    #[test]
291    fn test_rejects_unknown_and_mismatched_options() {
292        // Unknown signal.
293        let set = opts(&[("signal", CopyOptionValue::String("spans".into()))]);
294        assert!(build_otlp_codec(set).is_err());
295
296        // Unknown option.
297        let set = opts(&[("precision", CopyOptionValue::String("ns".into()))]);
298        assert!(build_otlp_codec(set).is_err());
299
300        // Signal-specific options do not cross.
301        let set = opts(&[
302            ("signal", CopyOptionValue::String("traces".into())),
303            ("promote_scope_attrs", CopyOptionValue::Flag),
304        ]);
305        assert!(build_otlp_codec(set).is_err());
306        let set = opts(&[
307            ("signal", CopyOptionValue::String("metrics".into())),
308            ("table_name", CopyOptionValue::String("t".into())),
309        ]);
310        assert!(build_otlp_codec(set).is_err());
311        let set = opts(&[
312            ("signal", CopyOptionValue::String("traces".into())),
313            (
314                "extract_keys",
315                CopyOptionValue::String("attributes.foo".into()),
316            ),
317        ]);
318        assert!(build_otlp_codec(set).is_err());
319    }
320}