Skip to main content

servers/postgres/copy_in/
prom_write.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 `promwrite` format for COPY FROM STDIN: one Prometheus Remote
16//! Write request body (v1 or v2), snappy- or zstd-compressed protobuf.
17//!
18//! `COPY FROM STDIN WITH (FORMAT promwrite [, version 2] [, <options>])`
19//! is a GreptimeDB-specific, **binary** format (wire format code 1).
20//! The payload is byte-for-byte the body a Prometheus remote-write
21//! client POSTs to `/v1/prometheus/write` — compression and protobuf
22//! framing included — buffered until `CopyDone` and then completed
23//! through the exact ingestion core that endpoint runs: the same
24//! decode, validation, conversion, batched/prepared write paths and
25//! context extensions, under the connection's regular postgres query
26//! context.
27//!
28//! The `WITH` options carry what the HTTP endpoint takes as its
29//! content-type/-encoding and query parameters; values already provided
30//! by the postgres session (database, user) are not repeated:
31//!
32//! - `version 1|2` — the remote-write protocol version, matching the
33//!   HTTP content-type's proto (default `1`).
34//! - `zstd` — the body uses zstd instead of the default snappy
35//!   compression, matching `Content-Encoding: zstd`.
36//! - `physical_table 'name'` — the `?physical_table=` query parameter.
37//! - `pipeline_name`/`pipeline_version` — the pipeline headers (v1
38//!   only; for v2 they are accepted and ignored by the core, exactly
39//!   like the HTTP route — except that their presence still feeds the
40//!   pipelines-with-exemplars restriction).
41//!
42//! One COPY statement is one bounded ingestion request (see
43//! [`crate::postgres::copy_in::COPY_IN_MAX_PAYLOAD_BYTES`]); the row
44//! count includes samples, histograms and exemplars. With asynchronous v2
45//! batching it reports accepted counts; COPY cannot distinguish HTTP 202
46//! acceptance from completed writes or return partial counts on an error.
47
48use pgwire::error::PgWireResult;
49
50use crate::postgres::copy_in::bad_copy_data;
51use crate::postgres::copy_in::codec::CopyFormat;
52use crate::postgres::copy_in::options::CopyOptionSet;
53
54/// The format's validated options, carried to the flush that completes
55/// the copy through the shared remote-write ingestion core.
56#[derive(Debug, Clone)]
57pub(crate) struct PromWriteOptions {
58    pub(crate) version: PromWriteVersion,
59    /// The `?physical_table=` query-parameter equivalent.
60    pub(crate) physical_table: Option<String>,
61    /// Pipeline headers (v1 only).
62    pub(crate) pipeline_name: Option<String>,
63    pub(crate) pipeline_version: Option<String>,
64    /// `Content-Encoding: zstd` equivalent; snappy by default.
65    pub(crate) zstd: bool,
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
69pub(crate) enum PromWriteVersion {
70    #[default]
71    V1,
72    V2,
73}
74
75pub(crate) fn build_prom_write_codec(mut options: CopyOptionSet) -> PgWireResult<CopyFormat> {
76    let version = match options.take_value("version") {
77        Some(value) => match &value {
78            crate::postgres::copy_in::options::CopyOptionValue::Number(n) if n == "2" => {
79                PromWriteVersion::V2
80            }
81            crate::postgres::copy_in::options::CopyOptionValue::Number(n) if n == "1" => {
82                PromWriteVersion::V1
83            }
84            crate::postgres::copy_in::options::CopyOptionValue::String(s)
85                if s == "2" || s.eq_ignore_ascii_case("v2") =>
86            {
87                PromWriteVersion::V2
88            }
89            crate::postgres::copy_in::options::CopyOptionValue::String(s)
90                if s == "1" || s.eq_ignore_ascii_case("v1") =>
91            {
92                PromWriteVersion::V1
93            }
94            other => {
95                return Err(bad_copy_data(format!(
96                    "invalid promwrite version {:?}, expected 1 or 2",
97                    other.kind()
98                )));
99            }
100        },
101        None => PromWriteVersion::V1,
102    };
103    let physical_table = options.take_string("physical_table")?;
104    let pipeline_name = options.take_string("pipeline_name")?;
105    let pipeline_version = options.take_string("pipeline_version")?;
106    let zstd = options.take_flag("zstd")?.unwrap_or(false);
107    options.reject_leftovers("promwrite")?;
108    // The pipeline options are accepted for version 2 but ignored by its
109    // ingestion core, exactly like the HTTP route — except that their
110    // PRESENCE still feeds the pipelines-with-exemplars restriction the
111    // core enforces, so the option must be retained here (see
112    // `flush_prom_write`).
113    Ok(CopyFormat::PromWrite(PromWriteOptions {
114        version,
115        physical_table,
116        pipeline_name,
117        pipeline_version,
118        zstd,
119    }))
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125    use crate::postgres::copy_in::options::CopyOptionValue;
126
127    fn opts(entries: &[(&str, CopyOptionValue)]) -> CopyOptionSet {
128        let mut set = CopyOptionSet::default();
129        for (k, v) in entries {
130            set.insert((*k).into(), v.clone()).unwrap();
131        }
132        set
133    }
134
135    #[test]
136    fn test_defaults_and_versions() {
137        let CopyFormat::PromWrite(options) =
138            build_prom_write_codec(CopyOptionSet::default()).unwrap()
139        else {
140            panic!("expected promwrite");
141        };
142        assert_eq!(options.version, PromWriteVersion::V1);
143        assert!(!options.zstd);
144        assert!(options.physical_table.is_none());
145
146        for (entry, expected) in [
147            (CopyOptionValue::Number("2".into()), PromWriteVersion::V2),
148            (CopyOptionValue::String("v2".into()), PromWriteVersion::V2),
149            (CopyOptionValue::Number("1".into()), PromWriteVersion::V1),
150        ] {
151            let CopyFormat::PromWrite(options) =
152                build_prom_write_codec(opts(&[("version", entry)])).unwrap()
153            else {
154                panic!("expected promwrite");
155            };
156            assert_eq!(options.version, expected);
157        }
158
159        let set = opts(&[
160            ("version", CopyOptionValue::Number("2".into())),
161            ("zstd", CopyOptionValue::Flag),
162            ("physical_table", CopyOptionValue::String("phys".into())),
163        ]);
164        let CopyFormat::PromWrite(options) = build_prom_write_codec(set).unwrap() else {
165            panic!("expected promwrite");
166        };
167        assert_eq!(options.version, PromWriteVersion::V2);
168        assert!(options.zstd);
169        assert_eq!(options.physical_table.as_deref(), Some("phys"));
170    }
171
172    #[test]
173    fn test_rejects_bad_options() {
174        let set = opts(&[("version", CopyOptionValue::Number("3".into()))]);
175        assert!(build_prom_write_codec(set).is_err());
176
177        let set = opts(&[("unknown", CopyOptionValue::Flag)]);
178        assert!(build_prom_write_codec(set).is_err());
179    }
180
181    #[test]
182    fn test_v2_accepts_and_ignores_pipeline_options() {
183        // The HTTP v2 route deliberately ignores pipeline information
184        // except for the pipelines-with-exemplars restriction; COPY
185        // accepts the options and retains them so the same restriction
186        // can fire, while the core otherwise ignores them.
187        let CopyFormat::PromWrite(options) = build_prom_write_codec(opts(&[
188            ("version", CopyOptionValue::Number("2".into())),
189            ("pipeline_name", CopyOptionValue::String("p".into())),
190            ("pipeline_version", CopyOptionValue::String("v1".into())),
191        ]))
192        .unwrap() else {
193            panic!("expected promwrite");
194        };
195        assert_eq!(options.version, PromWriteVersion::V2);
196        assert_eq!(options.pipeline_name.as_deref(), Some("p"));
197        assert_eq!(options.pipeline_version.as_deref(), Some("v1"));
198    }
199}