picodata-driver 4.0.0

A native asyncronous cluster-aware Picodata client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
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};

/// Distribution key metadata received from server via Notice after Parse.
#[derive(Clone, Debug)]
pub(crate) struct DkMeta {
    /// Tier name for bucket routing. None for global tables.
    pub tier: Option<String>,
    /// (`param_index`, `oid`) pairs forming the distribution key.
    pub keys: Vec<(u16, u32)>,
}

/// Parses a picodata Notice message into `(query, DkMeta)`.
/// Returns `None` if the message is not a `PreparedStatementMetadata` JSON.
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,
        },
    ))
}

/// JSON structure of the `PreparedStatementMetadata` Notice from picodata.
#[derive(Deserialize)]
struct NoticePayload {
    query: String,
    tier: Option<String>,
    dk_meta: Vec<(u16, u32)>,
}

/// Receiver for the metadata service initialization result.
pub(crate) type MetadataInitReceiver = tokio::sync::oneshot::Receiver<Result<(), crate::Error>>;

/// Shared cache: SQL query → optional `DkMeta` (None for queries without distribution key).
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();
        }
    }
}

/// Active connection: client for sending queries, notice channel for receiving
/// `dk_meta` from the spawned connection driver task.
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();
    }
}

/// Background service that caches distribution key metadata by sending Parse
/// requests to picodata and receiving Notice messages with `dk_meta`.
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 {
    /// Creates a new metadata service (not yet started).
    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,
        }
    }

    /// Spawns the background task and returns a handle + init receiver.
    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(&notice) {
            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;
        }
    }
}

/// Handle used by `Manager` to interact with the running `MetadataService`.
pub(crate) struct MetadataHandle {
    cache: DkCache,
    pending: Weak<Mutex<PendingQueries>>,
    request_tx: mpsc::Sender<Arc<str>>,
    _task: JoinHandle<()>,
}

impl MetadataHandle {
    /// Returns cached `dk_meta` for the query, or requests a prefetch on a miss if the queue has room.
    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
    }

    /// Removes cached `dk_meta` for the query (e.g. after DDL invalidation).
    pub(crate) async fn invalidate(&self, query: &str) {
        log::debug!("metadata: invalidating cache for: {query}");
        self.cache.write().await.remove(query);
    }
}

/// Timeout for establishing a metadata service connection to picodata.
const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// Decorrelated Jitter V2 with a one-second median first retry.
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);
        // At this scale even a single f64 spacing exceeds the cap.
        if self.attempt >= 64 {
            return MAX_DELAY;
        }
        // https://github.com/Polly-Contrib/Polly.Contrib.WaitAndRetry/blob/master/src/Polly.Contrib.WaitAndRetry/Backoff.DecorrelatedJitterV2.cs
        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()))
    }
}

/// Appends the `pico_query_metadata` startup option, keeping whatever
/// startup options the consumer configured.
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);
}

/// Opens a raw pg connection with `pico_query_metadata=true` and spawns its driver task.
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
}

/// Opens a TLS connection and spawns the driver task.
#[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, &notice_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
        }
    }
}

/// Opens a plain (no TLS) connection and spawns the driver task.
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, &notice_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
        }
    }
}

/// Polls the pg connection, forwarding Notice messages to the channel.
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};

    /// The service flag must not discard the startup options of the config.
    #[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();
        // Reference V2 intervals for successive uniform samples of 0.5 and 0.25.
        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();
            // PostgreSQL AuthenticationOk and ReadyForQuery.
            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 {
            // Keep the driver from completing graceful shutdown on its own.
            if parked.await.is_ok() {
                drive_connection(&mut connection, &notice_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");
    }
}