use std::{
collections::{HashMap, HashSet},
sync::{Arc, Weak},
};
use serde::Deserialize;
use tokio::{
sync::{Mutex, RwLock, mpsc},
task::JoinHandle,
};
use tokio_util::sync::CancellationToken;
use crate::{accessor::Accessor, config::Config};
#[derive(Clone, Debug)]
pub(crate) struct DkMeta {
pub tier: Option<String>,
pub keys: Vec<(u16, u32)>,
}
pub(crate) fn parse_dk_notice(notice: &pg::error::DbError) -> Option<(String, DkMeta)> {
let parsed: NoticePayload = serde_json::from_str(notice.message()).ok()?;
Some((
parsed.query,
DkMeta {
tier: parsed.tier,
keys: parsed.dk_meta,
},
))
}
#[derive(Deserialize)]
struct NoticePayload {
query: String,
tier: Option<String>,
dk_meta: Vec<(u16, u32)>,
}
pub(crate) type MetadataInitReceiver = tokio::sync::oneshot::Receiver<Result<(), crate::Error>>;
type DkCache = Arc<RwLock<HashMap<String, Option<Arc<DkMeta>>>>>;
const PREFETCH_QUEUE_CAPACITY: usize = 1024;
const PREFETCH_SQL_BYTES: usize = 512 * 1024 * 1024;
#[derive(Default)]
struct PendingQueries {
queries: HashSet<Arc<str>>,
bytes: usize,
}
impl PendingQueries {
fn enqueue(&mut self, query: &str, tx: &mpsc::Sender<Arc<str>>, byte_limit: usize) {
if self.queries.len() >= PREFETCH_QUEUE_CAPACITY
|| query.len() > byte_limit - self.bytes
|| self.queries.contains(query)
{
return;
}
if let Ok(permit) = tx.try_reserve() {
let sql = Arc::<str>::from(query);
self.bytes += sql.len();
self.queries.insert(Arc::clone(&sql));
permit.send(sql);
}
}
fn finish(&mut self, query: &str) {
if self.queries.remove(query) {
self.bytes -= query.len();
}
}
}
struct ServiceConnection {
client: pg::Client,
notice_rx: mpsc::UnboundedReceiver<pg::error::DbError>,
conn_task: JoinHandle<()>,
}
impl Drop for ServiceConnection {
fn drop(&mut self) {
self.conn_task.abort();
}
}
pub(crate) struct Metadata {
accessor: Arc<Accessor>,
config: Config,
token: CancellationToken,
cache: DkCache,
pending: Arc<Mutex<PendingQueries>>,
request_tx: mpsc::Sender<Arc<str>>,
request_rx: mpsc::Receiver<Arc<str>>,
}
impl Metadata {
pub(crate) fn new(accessor: Arc<Accessor>, config: Config, token: CancellationToken) -> Self {
let (request_tx, request_rx) = mpsc::channel(PREFETCH_QUEUE_CAPACITY);
Self {
accessor,
config,
token,
cache: Arc::new(RwLock::new(HashMap::new())),
pending: Arc::default(),
request_tx,
request_rx,
}
}
pub(crate) fn start(self) -> (MetadataHandle, MetadataInitReceiver) {
let (init_tx, init_rx) = tokio::sync::oneshot::channel();
let handle = MetadataHandle {
cache: self.cache.clone(),
pending: Arc::downgrade(&self.pending),
request_tx: self.request_tx.clone(),
_task: tokio::spawn(self.run(init_tx)),
};
(handle, init_rx)
}
async fn handle_notice(&self, notice: pg::error::DbError) {
if let Some((query, dk)) = parse_dk_notice(¬ice) {
log::debug!(
"metadata: received dk_meta notice: query={query}, tier={:?}, keys={:?}",
dk.tier,
dk.keys
);
let meta = if dk.keys.is_empty() {
None
} else {
Some(Arc::new(dk))
};
self.cache.write().await.insert(query, meta);
} else {
log::debug!("metadata: received non-dk notice: {}", notice.message());
}
}
async fn handle_request(&self, client: &pg::Client, sql: &str) -> bool {
if self.cache.read().await.contains_key(sql) {
log::debug!("metadata: cache hit, skipping prepare for: {sql}");
return true;
}
log::debug!("metadata: cache miss, preparing: {sql}");
match client.prepare(sql).await {
Ok(_) => true,
Err(e) if e.is_closed() => false,
Err(e) => {
log::error!("metadata: prepare failed: {e}");
true
}
}
}
async fn connect(accessor: &Accessor, config: &Config) -> Option<ServiceConnection> {
let guard = accessor.read().await;
let instances: Vec<_> = guard
.topology()
.instances
.values()
.filter(|i| i.is_online())
.cloned()
.collect();
drop(guard);
log::debug!(
"metadata: found {} online instances to try",
instances.len()
);
for inst in instances {
let mut cfg = config.clone_for(&inst);
enable_query_metadata(&mut cfg.postgres);
if let Some(svc) = open_service_connection(&cfg).await {
log::debug!("metadata: connected to {}", inst.addr);
return Some(svc);
}
log::error!("metadata: failed to connect to {}", inst.addr);
}
None
}
async fn connect_with_retry(
&self,
mut init_tx: Option<tokio::sync::oneshot::Sender<Result<(), crate::Error>>>,
) -> Option<ServiceConnection> {
let mut backoff = ReconnectBackoff::new();
loop {
let connect = Self::connect(&self.accessor, &self.config);
let connected = self.token.run_until_cancelled(connect).await?;
if let Some(tx) = init_tx.take() {
let result = connected.as_ref().map(|_| ()).ok_or_else(|| {
crate::Error::IO(std::io::Error::new(
std::io::ErrorKind::ConnectionRefused,
"metadata: no online instances to connect",
))
});
tx.send(result).ok()?;
}
if connected.is_some() {
return connected;
}
let delay = backoff.next_delay(rand::random());
self.token
.run_until_cancelled(tokio::time::sleep(delay))
.await?;
}
}
async fn run(mut self, init_tx: tokio::sync::oneshot::Sender<Result<(), crate::Error>>) {
let token = self.token.clone();
let Some(mut svc) = self.connect_with_retry(Some(init_tx)).await else {
return;
};
loop {
let next_event = async {
tokio::select! {
notice = svc.notice_rx.recv() => match notice {
Some(n) => { self.handle_notice(n).await; false }
None => true,
},
Some(sql) = self.request_rx.recv() => {
let reconnect = !self.handle_request(&svc.client, &sql).await;
while let Ok(notice) = svc.notice_rx.try_recv() {
self.handle_notice(notice).await;
}
self.pending.lock().await.finish(&sql);
reconnect
}
}
};
let Some(reconnect) = token.run_until_cancelled(next_event).await else {
return;
};
if !reconnect {
continue;
}
log::warn!("metadata: connection lost, reconnecting");
drop(svc);
let Some(new_svc) = self.connect_with_retry(None).await else {
return;
};
svc = new_svc;
}
}
}
pub(crate) struct MetadataHandle {
cache: DkCache,
pending: Weak<Mutex<PendingQueries>>,
request_tx: mpsc::Sender<Arc<str>>,
_task: JoinHandle<()>,
}
impl MetadataHandle {
pub(crate) async fn resolve(&self, query: &str) -> Option<Arc<DkMeta>> {
let cache = self.cache.read().await;
if let Some(meta) = cache.get(query) {
log::debug!("metadata: resolve cache hit for: {query}");
return meta.clone();
}
if let Some(pending) = self.pending.upgrade() {
pending
.lock()
.await
.enqueue(query, &self.request_tx, PREFETCH_SQL_BYTES);
}
None
}
pub(crate) async fn invalidate(&self, query: &str) {
log::debug!("metadata: invalidating cache for: {query}");
self.cache.write().await.remove(query);
}
}
const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
struct ReconnectBackoff {
attempt: u32,
previous: f64,
}
impl ReconnectBackoff {
fn new() -> Self {
Self {
attempt: 0,
previous: 0.0,
}
}
fn next_delay(&mut self, sample: f64) -> std::time::Duration {
const MAX_DELAY: std::time::Duration = std::time::Duration::from_secs(30);
if self.attempt >= 64 {
return MAX_DELAY;
}
let t = f64::from(self.attempt) + sample;
let current = t.exp2() * (4.0 * t).sqrt().tanh();
let seconds = (current - self.previous) / 1.4;
self.previous = current;
self.attempt += 1;
std::time::Duration::from_secs_f64(seconds.min(MAX_DELAY.as_secs_f64()))
}
}
fn enable_query_metadata(cfg: &mut pg::Config) {
let mut options = cfg.get_options().unwrap_or_default().to_owned();
if !options.is_empty() {
options.push(' ');
}
options.push_str("pico_query_metadata=true");
cfg.options(options);
}
async fn open_service_connection(cfg: &Config) -> Option<ServiceConnection> {
#[cfg(feature = "tls")]
if let Ok(Some(tls)) = crate::tls::connector(cfg) {
return open_tls_connection(cfg, tls).await;
}
open_plain_connection(cfg).await
}
#[cfg(feature = "tls")]
async fn open_tls_connection(
cfg: &Config,
tls: tokio_postgres_rustls::MakeRustlsConnect,
) -> Option<ServiceConnection> {
let result = tokio::time::timeout(CONNECT_TIMEOUT, cfg.postgres.connect(tls)).await;
match result {
Ok(Ok((client, mut conn))) => {
let (notice_tx, notice_rx) = mpsc::unbounded_channel();
let conn_task = tokio::spawn(async move {
drive_connection(&mut conn, ¬ice_tx).await;
});
Some(ServiceConnection {
client,
notice_rx,
conn_task,
})
}
Ok(Err(e)) => {
log::debug!("metadata: tls connect error: {e}");
None
}
Err(_) => {
log::debug!("metadata: tls connect timeout");
None
}
}
}
async fn open_plain_connection(cfg: &Config) -> Option<ServiceConnection> {
let result = tokio::time::timeout(CONNECT_TIMEOUT, cfg.postgres.connect(pg::NoTls)).await;
match result {
Ok(Ok((client, mut conn))) => {
let (notice_tx, notice_rx) = mpsc::unbounded_channel();
let conn_task = tokio::spawn(async move {
drive_connection(&mut conn, ¬ice_tx).await;
});
Some(ServiceConnection {
client,
notice_rx,
conn_task,
})
}
Ok(Err(e)) => {
log::debug!("metadata: connect error: {e}");
None
}
Err(_) => {
log::debug!("metadata: connect timeout");
None
}
}
}
async fn drive_connection<S, T>(
conn: &mut pg::Connection<S, T>,
tx: &mpsc::UnboundedSender<pg::error::DbError>,
) where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
{
log::debug!("metadata: connection driver task started");
loop {
match std::future::poll_fn(|cx| conn.poll_message(cx)).await {
Some(Ok(pg::AsyncMessage::Notice(n))) => {
log::debug!("metadata: conn task got Notice: {}", n.message());
if tx.send(n).is_err() {
break;
}
}
Some(Ok(msg)) => {
log::debug!("metadata: conn task got async msg: {msg:?}");
}
Some(Err(e)) => {
log::error!("metadata: connection error: {e}");
break;
}
None => {
log::debug!("metadata: connection closed");
break;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{pool::Pool, strategy::RoundRobin};
#[test]
fn query_metadata_flag_appends_to_user_options() {
let mut postgres = pg::Config::new();
postgres.options("-c statement_timeout=5s");
enable_query_metadata(&mut postgres);
assert_eq!(
postgres.get_options(),
Some("-c statement_timeout=5s pico_query_metadata=true")
);
let mut postgres = pg::Config::new();
enable_query_metadata(&mut postgres);
assert_eq!(postgres.get_options(), Some("pico_query_metadata=true"));
}
#[test]
fn reconnect_backoff_uses_jittered_intervals_and_caps_long_outages() {
let mut backoff = ReconnectBackoff::new();
assert_eq!(backoff.next_delay(0.5).as_millis(), 897);
assert_eq!(backoff.next_delay(0.25).as_millis(), 763);
for _ in 0..1000 {
let delay = backoff.next_delay(0.5);
assert!(delay <= std::time::Duration::from_secs(30));
}
assert_eq!(backoff.next_delay(0.5), std::time::Duration::from_secs(30));
}
#[tokio::test]
async fn dropping_service_connection_releases_a_parked_driver() {
use tokio::io::{AsyncReadExt, AsyncWriteExt, duplex};
use tokio::sync::oneshot;
use tokio::time::{Duration, timeout};
let (transport, mut peer) = duplex(256);
let mut config = pg::Config::new();
config.user("test").ssl_mode(pg::config::SslMode::Disable);
let handshake = async {
let len = peer.read_u32().await.unwrap();
let mut startup = vec![0; usize::try_from(len - 4).unwrap()];
peer.read_exact(&mut startup).await.unwrap();
peer.write_all(b"R\0\0\0\x08\0\0\0\0Z\0\0\0\x05I")
.await
.unwrap();
};
let (result, ()) = tokio::join!(config.connect_raw(transport, pg::NoTls), handshake);
let (client, mut connection) = result.unwrap();
let (notice_tx, notice_rx) = mpsc::unbounded_channel();
let (resume, parked) = oneshot::channel::<()>();
let task = tokio::spawn(async move {
if parked.await.is_ok() {
drive_connection(&mut connection, ¬ice_tx).await;
}
});
drop(ServiceConnection {
client,
notice_rx,
conn_task: task,
});
let mut byte = [0];
let n = timeout(Duration::from_secs(2), peer.read(&mut byte))
.await
.expect("dropping ServiceConnection must release the driver's transport")
.unwrap();
assert_eq!(n, 0, "expected EOF");
drop(resume);
}
#[tokio::test]
async fn full_prefetch_queue_drops_misses_and_accepts_a_later_retry() {
let accessor = Arc::new(Accessor::new(Pool::new(), Box::new(RoundRobin::new())));
let mut metadata = Metadata::new(
accessor,
Config::from(pg::Config::new()),
CancellationToken::new(),
);
let handle = MetadataHandle {
cache: metadata.cache,
pending: Arc::downgrade(&metadata.pending),
request_tx: metadata.request_tx,
_task: tokio::spawn(async {}),
};
for i in 0..PREFETCH_QUEUE_CAPACITY {
assert!(handle.resolve(&format!("SELECT {i}")).await.is_none());
}
let result = tokio::time::timeout(
std::time::Duration::from_secs(1),
handle.resolve("another query"),
)
.await
.expect("a full prefetch queue must not block routing");
assert!(result.is_none());
let in_flight = metadata.request_rx.try_recv().unwrap();
handle.resolve("another query").await;
assert_eq!(metadata.request_rx.len(), PREFETCH_QUEUE_CAPACITY - 1);
metadata.pending.lock().await.finish(&in_flight);
handle.resolve("another query").await;
assert_eq!(metadata.request_rx.len(), PREFETCH_QUEUE_CAPACITY);
}
#[test]
fn pending_queries_share_text_and_limit_bytes() {
let (tx, mut rx) = mpsc::channel(8);
let mut pending = PendingQueries::default();
pending.enqueue("é", &tx, 4);
pending.enqueue("é", &tx, 4);
let sql = rx.try_recv().unwrap();
assert!(Arc::ptr_eq(&sql, pending.queries.get("é").unwrap()));
pending.enqueue("é", &tx, 4);
pending.enqueue("abc", &tx, 4);
assert!(rx.is_empty());
pending.enqueue("xy", &tx, 4);
assert_eq!(pending.bytes, 4);
pending.finish(&sql);
pending.enqueue("é", &tx, 4);
assert_eq!(&*rx.try_recv().unwrap(), "xy");
assert_eq!(&*rx.try_recv().unwrap(), "é");
assert_eq!(pending.bytes, 4);
}
#[tokio::test]
async fn start_ends_quietly_when_init_receiver_is_dropped() {
let accessor = Arc::new(Accessor::new(Pool::new(), Box::new(RoundRobin::new())));
let metadata = Metadata::new(
accessor,
Config::from(pg::Config::new()),
CancellationToken::new(),
);
let (handle, receiver) = metadata.start();
drop(receiver);
#[allow(clippy::used_underscore_binding)]
let task = handle._task;
task.await.expect("metadata task must not panic");
}
}