use super::super::notification::Notification;
use super::super::stream::PgStream;
use super::super::{AuthSettings, EnterpriseAuthMechanism};
use crate::protocol::PROTOCOL_VERSION_3_2;
use bytes::BytesMut;
use std::collections::{HashMap, VecDeque};
use std::num::NonZeroUsize;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use tokio::net::TcpStream;
pub(super) const STMT_CACHE_CAPACITY: NonZeroUsize = NonZeroUsize::new(100).unwrap();
#[derive(Debug)]
pub(crate) struct StatementCache {
capacity: NonZeroUsize,
entries: HashMap<u64, String>,
order: VecDeque<u64>, }
impl StatementCache {
pub(crate) fn new(capacity: NonZeroUsize) -> Self {
Self {
capacity,
entries: HashMap::with_capacity(capacity.get()),
order: VecDeque::with_capacity(capacity.get()),
}
}
pub(crate) fn len(&self) -> usize {
self.entries.len()
}
pub(crate) fn cap(&self) -> NonZeroUsize {
self.capacity
}
pub(crate) fn contains(&self, key: &u64) -> bool {
self.entries.contains_key(key)
}
pub(crate) fn get(&mut self, key: &u64) -> Option<String> {
let value = self.entries.get(key).cloned()?;
self.touch(*key);
Some(value)
}
pub(crate) fn peek(&self, key: &u64) -> Option<&str> {
self.entries.get(key).map(String::as_str)
}
pub(crate) fn touch_key(&mut self, key: u64) {
if self.entries.contains_key(&key) {
self.touch(key);
}
}
pub(crate) fn put(&mut self, key: u64, value: String) {
if let std::collections::hash_map::Entry::Occupied(mut e) = self.entries.entry(key) {
e.insert(value);
self.touch(key);
return;
}
if self.entries.len() >= self.capacity.get() {
let _ = self.pop_lru();
}
self.entries.insert(key, value);
self.order.push_back(key);
}
pub(crate) fn pop_lru(&mut self) -> Option<(u64, String)> {
while let Some(key) = self.order.pop_front() {
if let Some(value) = self.entries.remove(&key) {
return Some((key, value));
}
}
None
}
pub(crate) fn remove(&mut self, key: &u64) -> Option<String> {
let removed = self.entries.remove(key);
if removed.is_some() {
self.order.retain(|k| k != key);
}
removed
}
pub(crate) fn clear(&mut self) {
self.entries.clear();
self.order.clear();
}
fn touch(&mut self, key: u64) {
self.order.retain(|k| *k != key);
self.order.push_back(key);
}
}
pub(crate) const BUFFER_CAPACITY: usize = 65536;
pub(super) const SSL_REQUEST: [u8; 8] = [0, 0, 0, 8, 4, 210, 22, 47];
pub(super) const GSSENC_REQUEST: [u8; 8] = [0, 0, 0, 8, 4, 210, 22, 48];
#[derive(Debug)]
pub(super) enum GssEncNegotiationResult {
Accepted(TcpStream),
Rejected,
ServerError,
}
pub(crate) const CANCEL_REQUEST_CODE: i32 = 80877102;
pub(super) static GSS_SESSION_COUNTER: AtomicU64 = AtomicU64::new(1);
pub(crate) const DEFAULT_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
pub(super) const CONNECT_TRANSPORT_PLAIN: &str = "plain";
pub(super) const CONNECT_TRANSPORT_TLS: &str = "tls";
pub(super) const CONNECT_TRANSPORT_MTLS: &str = "mtls";
pub(super) const CONNECT_TRANSPORT_GSSENC: &str = "gssenc";
pub(super) const CONNECT_BACKEND_TOKIO: &str = "tokio";
#[cfg(all(target_os = "linux", feature = "io_uring"))]
pub(super) const CONNECT_BACKEND_IO_URING: &str = "io_uring";
#[derive(Debug, Clone)]
pub struct TlsConfig {
pub client_cert_pem: Vec<u8>,
pub client_key_pem: Vec<u8>,
pub ca_cert_pem: Option<Vec<u8>>,
}
impl TlsConfig {
pub fn from_files(
cert_path: impl AsRef<std::path::Path>,
key_path: impl AsRef<std::path::Path>,
ca_path: Option<impl AsRef<std::path::Path>>,
) -> std::io::Result<Self> {
Ok(Self {
client_cert_pem: std::fs::read(cert_path)?,
client_key_pem: std::fs::read(key_path)?,
ca_cert_pem: ca_path.map(|p| std::fs::read(p)).transpose()?,
})
}
}
#[derive(Clone)]
pub(super) struct ConnectParams<'a> {
pub(super) host: &'a str,
pub(super) port: u16,
pub(super) user: &'a str,
pub(super) database: &'a str,
pub(super) password: Option<&'a str>,
pub(super) auth_settings: AuthSettings,
pub(super) gss_token_provider: Option<super::super::GssTokenProvider>,
pub(super) gss_token_provider_ex: Option<super::super::GssTokenProviderEx>,
pub(super) protocol_minor: u16,
pub(super) startup_params: Vec<(String, String)>,
}
#[inline]
pub(super) fn has_logical_replication_startup_mode(startup_params: &[(String, String)]) -> bool {
startup_params
.iter()
.any(|(k, v)| k.eq_ignore_ascii_case("replication") && v.eq_ignore_ascii_case("database"))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum StartupAuthFlow {
CleartextPassword,
Md5Password,
Scram { server_final_seen: bool },
EnterpriseGss { mechanism: EnterpriseAuthMechanism },
}
impl StartupAuthFlow {
pub(super) fn label(self) -> &'static str {
match self {
Self::CleartextPassword => "cleartext-password",
Self::Md5Password => "md5-password",
Self::Scram { .. } => "scram",
Self::EnterpriseGss { mechanism } => match mechanism {
EnterpriseAuthMechanism::KerberosV5 => "kerberos-v5",
EnterpriseAuthMechanism::GssApi => "gssapi",
EnterpriseAuthMechanism::Sspi => "sspi",
},
}
}
}
pub struct PgConnection {
pub(crate) stream: PgStream,
pub(crate) buffer: BytesMut,
pub(crate) write_buf: BytesMut,
pub(crate) sql_buf: BytesMut,
pub(crate) params_buf: Vec<Option<Vec<u8>>>,
pub(crate) prepared_statements: HashMap<String, String>,
pub(crate) stmt_cache: StatementCache,
pub(crate) column_info_cache: HashMap<u64, Arc<super::super::ColumnInfo>>,
pub(crate) process_id: i32,
pub(crate) secret_key: i32,
pub(crate) cancel_key_bytes: Vec<u8>,
pub(crate) requested_protocol_minor: u16,
pub(crate) negotiated_protocol_minor: u16,
pub(crate) notifications: VecDeque<Notification>,
pub(crate) replication_stream_active: bool,
pub(crate) replication_mode_enabled: bool,
pub(crate) last_replication_wal_end: Option<u64>,
pub(crate) io_desynced: bool,
pub(crate) pending_statement_closes: Vec<String>,
pub(crate) draining_statement_closes: bool,
}
impl PgConnection {
#[inline]
pub(crate) fn default_protocol_minor() -> u16 {
(PROTOCOL_VERSION_3_2 & 0xFFFF) as u16
}
#[inline]
pub fn requested_protocol_minor(&self) -> u16 {
self.requested_protocol_minor
}
#[inline]
pub fn negotiated_protocol_minor(&self) -> u16 {
self.negotiated_protocol_minor
}
#[inline]
pub fn transport_backend(&self) -> &'static str {
super::helpers::connect_backend_for_stream(&self.stream)
}
}