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