qail_pg/driver/connection/
types.rs1use super::super::notification::Notification;
16use super::super::stream::PgStream;
17use super::super::{AuthSettings, EnterpriseAuthMechanism};
18use crate::protocol::PROTOCOL_VERSION_3_2;
19use bytes::BytesMut;
20use std::collections::{HashMap, VecDeque};
21use std::num::NonZeroUsize;
22use std::sync::Arc;
23use std::sync::atomic::AtomicU64;
24use tokio::net::TcpStream;
25
26pub(super) const STMT_CACHE_CAPACITY: NonZeroUsize = NonZeroUsize::new(100).unwrap();
28
29#[derive(Debug)]
34pub(crate) struct StatementCache {
35 capacity: NonZeroUsize,
36 entries: HashMap<u64, String>,
37 order: VecDeque<u64>, }
39
40impl StatementCache {
41 pub(crate) fn new(capacity: NonZeroUsize) -> Self {
42 Self {
43 capacity,
44 entries: HashMap::with_capacity(capacity.get()),
45 order: VecDeque::with_capacity(capacity.get()),
46 }
47 }
48
49 pub(crate) fn len(&self) -> usize {
50 self.entries.len()
51 }
52
53 pub(crate) fn cap(&self) -> NonZeroUsize {
54 self.capacity
55 }
56
57 pub(crate) fn contains(&self, key: &u64) -> bool {
58 self.entries.contains_key(key)
59 }
60
61 pub(crate) fn get(&mut self, key: &u64) -> Option<String> {
62 let value = self.entries.get(key).cloned()?;
63 self.touch(*key);
64 Some(value)
65 }
66
67 pub(crate) fn put(&mut self, key: u64, value: String) {
68 if let std::collections::hash_map::Entry::Occupied(mut e) = self.entries.entry(key) {
69 e.insert(value);
70 self.touch(key);
71 return;
72 }
73
74 if self.entries.len() >= self.capacity.get() {
75 let _ = self.pop_lru();
76 }
77
78 self.entries.insert(key, value);
79 self.order.push_back(key);
80 }
81
82 pub(crate) fn pop_lru(&mut self) -> Option<(u64, String)> {
83 while let Some(key) = self.order.pop_front() {
84 if let Some(value) = self.entries.remove(&key) {
85 return Some((key, value));
86 }
87 }
88 None
89 }
90
91 pub(crate) fn remove(&mut self, key: &u64) -> Option<String> {
92 let removed = self.entries.remove(key);
93 if removed.is_some() {
94 self.order.retain(|k| k != key);
95 }
96 removed
97 }
98
99 pub(crate) fn clear(&mut self) {
100 self.entries.clear();
101 self.order.clear();
102 }
103
104 fn touch(&mut self, key: u64) {
105 self.order.retain(|k| *k != key);
106 self.order.push_back(key);
107 }
108}
109
110pub(crate) const BUFFER_CAPACITY: usize = 65536;
112
113pub(super) const SSL_REQUEST: [u8; 8] = [0, 0, 0, 8, 4, 210, 22, 47];
115
116pub(super) const GSSENC_REQUEST: [u8; 8] = [0, 0, 0, 8, 4, 210, 22, 48];
119
120#[derive(Debug)]
122pub(super) enum GssEncNegotiationResult {
123 Accepted(TcpStream),
127 Rejected,
129 ServerError,
132}
133
134pub(crate) const CANCEL_REQUEST_CODE: i32 = 80877102;
136
137pub(super) static GSS_SESSION_COUNTER: AtomicU64 = AtomicU64::new(1);
139
140pub(crate) const DEFAULT_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
143pub(super) const CONNECT_TRANSPORT_PLAIN: &str = "plain";
144pub(super) const CONNECT_TRANSPORT_TLS: &str = "tls";
145pub(super) const CONNECT_TRANSPORT_MTLS: &str = "mtls";
146pub(super) const CONNECT_TRANSPORT_GSSENC: &str = "gssenc";
147pub(super) const CONNECT_BACKEND_TOKIO: &str = "tokio";
148#[cfg(all(target_os = "linux", feature = "io_uring"))]
149pub(super) const CONNECT_BACKEND_IO_URING: &str = "io_uring";
150
151#[derive(Debug, Clone)]
153pub struct TlsConfig {
154 pub client_cert_pem: Vec<u8>,
156 pub client_key_pem: Vec<u8>,
158 pub ca_cert_pem: Option<Vec<u8>>,
160}
161
162impl TlsConfig {
163 pub fn from_files(
165 cert_path: impl AsRef<std::path::Path>,
166 key_path: impl AsRef<std::path::Path>,
167 ca_path: Option<impl AsRef<std::path::Path>>,
168 ) -> std::io::Result<Self> {
169 Ok(Self {
170 client_cert_pem: std::fs::read(cert_path)?,
171 client_key_pem: std::fs::read(key_path)?,
172 ca_cert_pem: ca_path.map(|p| std::fs::read(p)).transpose()?,
173 })
174 }
175}
176
177#[derive(Clone)]
182pub(super) struct ConnectParams<'a> {
183 pub(super) host: &'a str,
184 pub(super) port: u16,
185 pub(super) user: &'a str,
186 pub(super) database: &'a str,
187 pub(super) password: Option<&'a str>,
188 pub(super) auth_settings: AuthSettings,
189 pub(super) gss_token_provider: Option<super::super::GssTokenProvider>,
190 pub(super) gss_token_provider_ex: Option<super::super::GssTokenProviderEx>,
191 pub(super) protocol_minor: u16,
192 pub(super) startup_params: Vec<(String, String)>,
193}
194
195#[inline]
196pub(super) fn has_logical_replication_startup_mode(startup_params: &[(String, String)]) -> bool {
197 startup_params
198 .iter()
199 .any(|(k, v)| k.eq_ignore_ascii_case("replication") && v.eq_ignore_ascii_case("database"))
200}
201
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub(super) enum StartupAuthFlow {
204 CleartextPassword,
205 Md5Password,
206 Scram { server_final_seen: bool },
207 EnterpriseGss { mechanism: EnterpriseAuthMechanism },
208}
209
210impl StartupAuthFlow {
211 pub(super) fn label(self) -> &'static str {
212 match self {
213 Self::CleartextPassword => "cleartext-password",
214 Self::Md5Password => "md5-password",
215 Self::Scram { .. } => "scram",
216 Self::EnterpriseGss { mechanism } => match mechanism {
217 EnterpriseAuthMechanism::KerberosV5 => "kerberos-v5",
218 EnterpriseAuthMechanism::GssApi => "gssapi",
219 EnterpriseAuthMechanism::Sspi => "sspi",
220 },
221 }
222 }
223}
224
225pub struct PgConnection {
227 pub(crate) stream: PgStream,
228 pub(crate) buffer: BytesMut,
229 pub(crate) write_buf: BytesMut,
230 pub(crate) sql_buf: BytesMut,
231 pub(crate) params_buf: Vec<Option<Vec<u8>>>,
232 pub(crate) prepared_statements: HashMap<String, String>,
233 pub(crate) stmt_cache: StatementCache,
234 pub(crate) column_info_cache: HashMap<u64, Arc<super::super::ColumnInfo>>,
238 pub(crate) process_id: i32,
239 pub(crate) secret_key: i32,
244 pub(crate) cancel_key_bytes: Vec<u8>,
246 pub(crate) requested_protocol_minor: u16,
248 pub(crate) negotiated_protocol_minor: u16,
250 pub(crate) notifications: VecDeque<Notification>,
253 pub(crate) replication_stream_active: bool,
255 pub(crate) replication_mode_enabled: bool,
257 pub(crate) last_replication_wal_end: Option<u64>,
259 pub(crate) io_desynced: bool,
262 pub(crate) pending_statement_closes: Vec<String>,
265 pub(crate) draining_statement_closes: bool,
267}
268
269impl PgConnection {
270 #[inline]
271 pub(crate) fn default_protocol_minor() -> u16 {
272 (PROTOCOL_VERSION_3_2 & 0xFFFF) as u16
273 }
274
275 #[inline]
277 pub fn requested_protocol_minor(&self) -> u16 {
278 self.requested_protocol_minor
279 }
280
281 #[inline]
283 pub fn negotiated_protocol_minor(&self) -> u16 {
284 self.negotiated_protocol_minor
285 }
286}