servers/postgres/copy_in/
otlp.rs1use 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#[derive(Debug, Clone)]
64pub(super) struct OtlpOptions {
65 pub(super) signal: OtlpSignal,
66}
67
68#[derive(Debug, Clone)]
69pub(super) enum OtlpSignal {
70 Metrics {
72 promote_all_resource_attrs: bool,
75 resource_attrs: HashSet<String>,
76 promote_scope_attrs: bool,
77 translation_strategy: OtlpMetricTranslationStrategy,
78 },
79 Traces {
84 table_name: Option<String>,
85 pipeline_name: Option<String>,
86 pipeline_version: Option<String>,
87 pipeline_params: Option<String>,
88 },
89 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 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 .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 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
188fn 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 assert!(matches!(
221 build_otlp_codec(CopyOptionSet::default()).unwrap(),
222 CopyFormat::Otlp(OtlpOptions {
223 signal: OtlpSignal::Metrics { .. }
224 })
225 ));
226
227 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 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 let set = opts(&[("signal", CopyOptionValue::String("spans".into()))]);
294 assert!(build_otlp_codec(set).is_err());
295
296 let set = opts(&[("precision", CopyOptionValue::String("ns".into()))]);
298 assert!(build_otlp_codec(set).is_err());
299
300 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}