Skip to main content

servers/
postgres.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
15mod auth_handler;
16mod copy_in;
17mod fixtures;
18mod handler;
19mod server;
20mod types;
21mod utils;
22
23pub(crate) const METADATA_USER: &str = "user";
24pub(crate) const METADATA_DATABASE: &str = "database";
25/// key to store our parsed catalog
26pub(crate) const METADATA_CATALOG: &str = "catalog";
27/// key to store our parsed schema
28pub(crate) const METADATA_SCHEMA: &str = "schema";
29
30use std::collections::HashMap;
31use std::net::SocketAddr;
32use std::sync::Arc;
33use std::sync::atomic::AtomicBool;
34
35use ::auth::{UserInfoRef, UserProviderRef};
36pub use copy_in::COPY_IN_MAX_PAYLOAD_BYTES;
37use derive_builder::Builder;
38use pgwire::api::auth::{AuthDriver, ServerParameterProvider, StartupHandler};
39use pgwire::api::query::{ExtendedQueryHandler, SimpleQueryHandler};
40use pgwire::api::{ClientInfo, ErrorHandler, PgWireServerHandlers};
41pub use server::PostgresServer;
42use session::Session;
43use session::context::Channel;
44
45use self::auth_handler::{PgUserProviderSource, ZeroPidSecretKeyGenerator};
46use self::handler::DefaultQueryParser;
47use crate::query_handler::sql::ServerSqlQueryHandlerRef;
48use crate::query_handler::{
49    CopyInHandlerRef, InfluxdbLineProtocolHandlerRef, OpenTelemetryProtocolHandlerRef,
50};
51use crate::request_memory_limiter::ServerMemoryLimiter;
52
53pub(crate) struct GreptimeDBStartupParameters {
54    version: String,
55}
56
57impl GreptimeDBStartupParameters {
58    fn new() -> GreptimeDBStartupParameters {
59        GreptimeDBStartupParameters {
60            version: format!(
61                "16.3-{}-{}",
62                common_version::product_name(),
63                common_version::version()
64            ),
65        }
66    }
67}
68
69impl ServerParameterProvider for GreptimeDBStartupParameters {
70    fn server_parameters<C>(&self, _client: &C) -> Option<HashMap<String, String>>
71    where
72        C: ClientInfo,
73    {
74        Some(HashMap::from([
75            ("server_version".to_owned(), self.version.clone()),
76            ("server_encoding".to_owned(), "UTF8".to_owned()),
77            ("client_encoding".to_owned(), "UTF8".to_owned()),
78            ("DateStyle".to_owned(), "ISO YMD".to_owned()),
79            ("integer_datetimes".to_owned(), "on".to_owned()),
80        ]))
81    }
82}
83
84pub struct PostgresServerHandlerInner {
85    query_handler: ServerSqlQueryHandlerRef,
86    auth_source: Option<Arc<PgUserProviderSource>>,
87    copy_in_handler: CopyInHandlerRef,
88    /// Executes influxdb line-protocol batches flushed by a table-less
89    /// COPY FROM STDIN — the same handler the HTTP write endpoints use.
90    /// Absent on servers not wired for it; such connections reject the
91    /// influxdb format when a copy starts.
92    influxdb_handler: Option<InfluxdbLineProtocolHandlerRef>,
93    /// Executes the OTLP payload flushed by a table-less
94    /// `COPY FROM STDIN WITH (FORMAT otlp)` — the same handler the
95    /// OTLP/HTTP endpoints use — plus the with-metric-engine flag the
96    /// HTTP wiring passes from its options.
97    otlp_handler: Option<OpenTelemetryProtocolHandlerRef>,
98    otlp_with_metric_engine: bool,
99    memory_limiter: ServerMemoryLimiter,
100    /// Upper bound of a table-less COPY FROM STDIN payload, in bytes; 0 is
101    /// unbounded. Checked before the chunk is charged against the limiter.
102    max_copy_in_payload: u64,
103    /// Completes `COPY FROM STDIN WITH (FORMAT promwrite)` payloads
104    /// through the shared remote-write ingestion core — the same state
105    /// the `/v1/prometheus/write` endpoint runs.
106    prom_write_state: Option<crate::http::prom_store::PromStoreState>,
107    force_tls: bool,
108    auth_driver: AuthDriver<Arc<GreptimeDBStartupParameters>, UserInfoRef>,
109    /// SCRAM selected; failures get the uniform metric label.
110    is_scram_auth: AtomicBool,
111
112    batching_enabled: bool,
113    session: Arc<Session>,
114    query_parser: Arc<DefaultQueryParser>,
115
116    /// State of an in-progress `COPY ... FROM STDIN`; set when the copy
117    /// starts and taken when it finishes, fails or the connection drops.
118    copy_in_state: tokio::sync::Mutex<Option<copy_in::CopyInState>>,
119}
120
121#[derive(Builder)]
122pub(crate) struct MakePostgresServerHandler {
123    query_handler: ServerSqlQueryHandlerRef,
124    copy_in_handler: CopyInHandlerRef,
125    #[builder(default)]
126    influxdb_handler: Option<InfluxdbLineProtocolHandlerRef>,
127    #[builder(default)]
128    otlp_handler: Option<OpenTelemetryProtocolHandlerRef>,
129    #[builder(default)]
130    otlp_with_metric_engine: bool,
131    #[builder(default)]
132    memory_limiter: ServerMemoryLimiter,
133    #[builder(default = "COPY_IN_MAX_PAYLOAD_BYTES")]
134    max_copy_in_payload: u64,
135    #[builder(default)]
136    prom_write_state: Option<crate::http::prom_store::PromStoreState>,
137    user_provider: Option<UserProviderRef>,
138    #[builder(default = "Arc::new(GreptimeDBStartupParameters::new())")]
139    param_provider: Arc<GreptimeDBStartupParameters>,
140    force_tls: bool,
141}
142
143pub(crate) struct PostgresServerHandler(Arc<PostgresServerHandlerInner>);
144
145impl PgWireServerHandlers for PostgresServerHandler {
146    fn simple_query_handler(&self) -> Arc<impl SimpleQueryHandler> {
147        self.0.clone()
148    }
149
150    fn extended_query_handler(&self) -> Arc<impl ExtendedQueryHandler> {
151        self.0.clone()
152    }
153
154    fn startup_handler(&self) -> Arc<impl StartupHandler> {
155        self.0.clone()
156    }
157
158    fn copy_handler(&self) -> Arc<impl pgwire::api::copy::CopyHandler> {
159        self.0.clone()
160    }
161
162    fn error_handler(&self) -> Arc<impl ErrorHandler> {
163        self.0.clone()
164    }
165}
166
167impl MakePostgresServerHandler {
168    fn make(
169        &self,
170        addr: Option<SocketAddr>,
171        process_id: u32,
172        batching_enabled: bool,
173    ) -> PostgresServerHandler {
174        let session = Arc::new(Session::new(
175            addr,
176            Channel::Postgres,
177            Default::default(),
178            process_id,
179        ));
180        let handler = PostgresServerHandlerInner {
181            query_handler: self.query_handler.clone(),
182            auth_source: self
183                .user_provider
184                .clone()
185                .map(|p| Arc::new(PgUserProviderSource::new(p))),
186            copy_in_handler: self.copy_in_handler.clone(),
187            influxdb_handler: self.influxdb_handler.clone(),
188            otlp_handler: self.otlp_handler.clone(),
189            otlp_with_metric_engine: self.otlp_with_metric_engine,
190            memory_limiter: self.memory_limiter.clone(),
191            max_copy_in_payload: self.max_copy_in_payload,
192            prom_write_state: self.prom_write_state.clone(),
193            force_tls: self.force_tls,
194            auth_driver: AuthDriver::new(self.param_provider.clone())
195                .with_pid_secret_key_generator(Arc::new(ZeroPidSecretKeyGenerator)),
196            is_scram_auth: AtomicBool::new(false),
197
198            batching_enabled,
199            session: session.clone(),
200            query_parser: Arc::new(DefaultQueryParser::new(self.query_handler.clone(), session)),
201            copy_in_state: tokio::sync::Mutex::new(None),
202        };
203        PostgresServerHandler(Arc::new(handler))
204    }
205}