Skip to main content

common_meta/kv_backend/
rds.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
15use std::any::Any;
16use std::collections::HashMap;
17use std::marker::PhantomData;
18#[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
19use std::sync::{LazyLock, OnceLock};
20use std::time::Duration;
21
22use backon::{BackoffBuilder, ExponentialBuilder};
23use common_telemetry::{debug, info};
24
25use crate::error::{Error, RdsTransactionRetryFailedSnafu, Result, UnexpectedSnafu};
26use crate::kv_backend::txn::{
27    Compare, Txn as KvTxn, TxnOp, TxnOpResponse, TxnResponse as KvTxnResponse,
28};
29use crate::kv_backend::{
30    ClosableKvBackend, KvBackend, KvBackendCapabilities, TxnCapability, TxnService,
31};
32use crate::metrics::METRIC_META_TXN_REQUEST;
33use crate::rpc::KeyValue;
34use crate::rpc::store::{
35    BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse, BatchPutRequest,
36    BatchPutResponse, DeleteRangeRequest, DeleteRangeResponse, PutRequest, PutResponse,
37    RangeRequest, RangeResponse,
38};
39
40const RDS_STORE_OP_BATCH_GET: &str = "batch_get";
41const RDS_STORE_OP_BATCH_PUT: &str = "batch_put";
42const RDS_STORE_OP_RANGE_QUERY: &str = "range_query";
43const RDS_STORE_OP_RANGE_DELETE: &str = "range_delete";
44const RDS_STORE_OP_BATCH_DELETE: &str = "batch_delete";
45
46#[cfg(feature = "pg_kvbackend")]
47pub mod postgres;
48#[cfg(feature = "pg_kvbackend")]
49pub use postgres::PgStore;
50
51#[cfg(feature = "mysql_kvbackend")]
52mod mysql;
53#[cfg(feature = "mysql_kvbackend")]
54pub use mysql::MySqlStore;
55
56const RDS_STORE_TXN_RETRY_COUNT: usize = 3;
57
58/// Maximum keys or key-value pairs per statement, read once on first use.
59/// `GREPTIME_RDS_BATCH_SIZE` accepts 1..=65_535; other values use 65_535.
60/// Each backend additionally caps writes by its bind-parameter limit.
61#[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
62pub(crate) static RDS_BATCH_SIZE: LazyLock<usize> = LazyLock::new(|| {
63    let value = std::env::var("GREPTIME_RDS_BATCH_SIZE").ok();
64    parse_batch_size(value.as_deref())
65});
66
67#[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
68static RUSTLS_CRYPTO_PROVIDER_INIT: OnceLock<std::result::Result<(), String>> = OnceLock::new();
69
70#[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
71pub(crate) fn ensure_rustls_crypto_provider_installed() -> Result<()> {
72    RUSTLS_CRYPTO_PROVIDER_INIT
73        .get_or_init(|| {
74            if rustls::crypto::CryptoProvider::get_default().is_some() {
75                return Ok(());
76            }
77
78            match rustls::crypto::CryptoProvider::install_default(
79                rustls::crypto::aws_lc_rs::default_provider(),
80            ) {
81                Ok(()) => Ok(()),
82                Err(_provider) if rustls::crypto::CryptoProvider::get_default().is_some() => {
83                    Ok(())
84                }
85                Err(provider) => Err(format!(
86                    "Failed to install rustls CryptoProvider, existing default: {:?}, attempted provider: {:?}",
87                    rustls::crypto::CryptoProvider::get_default(),
88                    provider
89                )),
90            }
91        })
92        .clone()
93        .map_err(|err_msg| {
94            info!("Failed to install rustls crypto provider: {err_msg}");
95            UnexpectedSnafu { err_msg }.build()
96        })
97}
98
99/// Query executor for rds. It can execute queries or generate a transaction executor.
100#[async_trait::async_trait]
101pub trait Executor: Send + Sync {
102    type Transaction<'a>: 'a + Transaction<'a>
103    where
104        Self: 'a;
105
106    fn name() -> &'static str;
107
108    async fn query(&mut self, query: &str, params: &[&Vec<u8>]) -> Result<Vec<KeyValue>>;
109
110    /// Some queries don't need to return any result, such as `DELETE`.
111    async fn execute(&mut self, query: &str, params: &[&Vec<u8>]) -> Result<()> {
112        self.query(query, params).await?;
113        Ok(())
114    }
115
116    async fn txn_executor<'a>(&'a mut self) -> Result<Self::Transaction<'a>>;
117
118    /// Starts a read-only transaction whose plain reads share one snapshot.
119    async fn read_only_txn_executor<'a>(&'a mut self) -> Result<Self::Transaction<'a>>;
120}
121
122/// Transaction query executor for rds. It can execute queries in transaction or commit the transaction.
123#[async_trait::async_trait]
124pub trait Transaction<'a>: Send + Sync {
125    async fn query(&mut self, query: &str, params: &[&Vec<u8>]) -> Result<Vec<KeyValue>>;
126
127    async fn execute(&mut self, query: &str, params: &[&Vec<u8>]) -> Result<()> {
128        self.query(query, params).await?;
129        Ok(())
130    }
131
132    async fn commit(self) -> Result<()>;
133}
134
135/// Factory for creating default and transaction query executors.
136#[async_trait::async_trait]
137pub trait ExecutorFactory<T: Executor>: Send + Sync {
138    /// Closes the connection pool to new acquisitions. This affects all shared pool handles.
139    /// MySQL waits for checked-out connections to be returned; PostgreSQL allows them to
140    /// finish and releases them when returned. Stop consumers before closing the backend.
141    async fn close(&self);
142
143    async fn default_executor(&self) -> Result<T>;
144
145    async fn txn_executor<'a>(&self, default_executor: &'a mut T) -> Result<T::Transaction<'a>>;
146}
147
148/// Rds backed store for metsrv
149pub struct RdsStore<T, S, R>
150where
151    T: Executor + Send + Sync,
152    S: ExecutorFactory<T> + Send + Sync,
153{
154    max_txn_ops: usize,
155    txn_retry_count: usize,
156    executor_factory: S,
157    sql_template_set: R,
158    _phantom: PhantomData<T>,
159}
160
161pub enum ExecutorImpl<'a, T: Executor + 'a> {
162    Default(T),
163    Txn(T::Transaction<'a>),
164}
165
166impl<T: Executor> ExecutorImpl<'_, T> {
167    async fn query(&mut self, query: &str, params: &Vec<&Vec<u8>>) -> Result<Vec<KeyValue>> {
168        match self {
169            Self::Default(executor) => executor.query(query, params).await,
170            Self::Txn(executor) => executor.query(query, params).await,
171        }
172    }
173
174    #[allow(dead_code)] // Used in #[cfg(feature = "mysql_kvbackend")]
175    async fn execute(&mut self, query: &str, params: &Vec<&Vec<u8>>) -> Result<()> {
176        match self {
177            Self::Default(executor) => executor.execute(query, params).await,
178            Self::Txn(executor) => executor.execute(query, params).await,
179        }
180    }
181
182    async fn commit(self) -> Result<()> {
183        match self {
184            Self::Txn(executor) => executor.commit().await,
185            _ => Ok(()),
186        }
187    }
188}
189
190#[async_trait::async_trait]
191pub trait KvQueryExecutor<T: Executor> {
192    async fn range_with_query_executor(
193        &self,
194        query_executor: &mut ExecutorImpl<'_, T>,
195        req: RangeRequest,
196    ) -> Result<RangeResponse>;
197
198    async fn put_with_query_executor(
199        &self,
200        query_executor: &mut ExecutorImpl<'_, T>,
201        req: PutRequest,
202    ) -> Result<PutResponse> {
203        let kv = KeyValue {
204            key: req.key,
205            value: req.value,
206        };
207        let mut res = self
208            .batch_put_with_query_executor(
209                query_executor,
210                BatchPutRequest {
211                    kvs: vec![kv],
212                    prev_kv: req.prev_kv,
213                },
214            )
215            .await?;
216
217        if !res.prev_kvs.is_empty() {
218            debug_assert!(req.prev_kv);
219            return Ok(PutResponse {
220                prev_kv: Some(res.prev_kvs.remove(0)),
221            });
222        }
223        Ok(PutResponse::default())
224    }
225
226    /// Applies all writes atomically. Implementations that split a request across
227    /// statements must run them in one transaction, reusing the caller's transaction if present.
228    async fn batch_put_with_query_executor(
229        &self,
230        query_executor: &mut ExecutorImpl<'_, T>,
231        req: BatchPutRequest,
232    ) -> Result<BatchPutResponse>;
233
234    /// Batch get with certain client. It's needed for a client with transaction.
235    async fn batch_get_with_query_executor(
236        &self,
237        query_executor: &mut ExecutorImpl<'_, T>,
238        req: BatchGetRequest,
239    ) -> Result<BatchGetResponse>;
240
241    async fn delete_range_with_query_executor(
242        &self,
243        query_executor: &mut ExecutorImpl<'_, T>,
244        req: DeleteRangeRequest,
245    ) -> Result<DeleteRangeResponse>;
246
247    async fn batch_delete_with_query_executor(
248        &self,
249        query_executor: &mut ExecutorImpl<'_, T>,
250        req: BatchDeleteRequest,
251    ) -> Result<BatchDeleteResponse>;
252}
253
254impl<T, S, R> RdsStore<T, S, R>
255where
256    Self: KvQueryExecutor<T> + Send + Sync,
257    T: Executor + Send + Sync,
258    S: ExecutorFactory<T> + Send + Sync,
259{
260    async fn execute_txn_cmp(
261        &self,
262        query_executor: &mut ExecutorImpl<'_, T>,
263        cmp: &[Compare],
264    ) -> Result<bool> {
265        let batch_get_req = BatchGetRequest {
266            keys: cmp.iter().map(|c| c.key.clone()).collect(),
267        };
268        let res = self
269            .batch_get_with_query_executor(query_executor, batch_get_req)
270            .await?;
271        debug!("batch get res: {:?}", res);
272        let res_map = res
273            .kvs
274            .into_iter()
275            .map(|kv| (kv.key, kv.value))
276            .collect::<HashMap<Vec<u8>, Vec<u8>>>();
277        for c in cmp {
278            let value = res_map.get(&c.key);
279            if !c.compare_value(value) {
280                return Ok(false);
281            }
282        }
283        Ok(true)
284    }
285
286    /// Execute a batch of transaction operations. This function is only used for transactions with the same operation type.
287    async fn try_batch_txn(
288        &self,
289        query_executor: &mut ExecutorImpl<'_, T>,
290        txn_ops: &[TxnOp],
291    ) -> Result<Option<Vec<TxnOpResponse>>> {
292        if !check_txn_ops(txn_ops)? {
293            return Ok(None);
294        }
295        // Safety: txn_ops is not empty
296        match txn_ops.first().unwrap() {
297            TxnOp::Delete(_) => self.handle_batch_delete(query_executor, txn_ops).await,
298            TxnOp::Put(_, _) => self.handle_batch_put(query_executor, txn_ops).await,
299            TxnOp::Get(_) => self.handle_batch_get(query_executor, txn_ops).await,
300        }
301    }
302
303    async fn handle_batch_delete(
304        &self,
305        query_executor: &mut ExecutorImpl<'_, T>,
306        txn_ops: &[TxnOp],
307    ) -> Result<Option<Vec<TxnOpResponse>>> {
308        let mut batch_del_req = BatchDeleteRequest {
309            keys: vec![],
310            prev_kv: true,
311        };
312        for op in txn_ops {
313            if let TxnOp::Delete(key) = op {
314                batch_del_req.keys.push(key.clone());
315            }
316        }
317        let res = self
318            .batch_delete_with_query_executor(query_executor, batch_del_req)
319            .await?;
320        let res_map = res
321            .prev_kvs
322            .into_iter()
323            .map(|kv| (kv.key, kv.value))
324            .collect::<HashMap<Vec<u8>, Vec<u8>>>();
325        let mut resps = Vec::with_capacity(txn_ops.len());
326        for op in txn_ops {
327            if let TxnOp::Delete(key) = op {
328                let value = res_map.get(key);
329                resps.push(TxnOpResponse::ResponseDelete(DeleteRangeResponse {
330                    deleted: if value.is_some() { 1 } else { 0 },
331                    prev_kvs: vec![],
332                }));
333            }
334        }
335        Ok(Some(resps))
336    }
337
338    async fn handle_batch_put(
339        &self,
340        query_executor: &mut ExecutorImpl<'_, T>,
341        txn_ops: &[TxnOp],
342    ) -> Result<Option<Vec<TxnOpResponse>>> {
343        let mut batch_put_req = BatchPutRequest {
344            kvs: vec![],
345            prev_kv: false,
346        };
347        for op in txn_ops {
348            if let TxnOp::Put(key, value) = op {
349                batch_put_req.kvs.push(KeyValue {
350                    key: key.clone(),
351                    value: value.clone(),
352                });
353            }
354        }
355        let _ = self
356            .batch_put_with_query_executor(query_executor, batch_put_req)
357            .await?;
358        let mut resps = Vec::with_capacity(txn_ops.len());
359        for op in txn_ops {
360            if let TxnOp::Put(_, _) = op {
361                resps.push(TxnOpResponse::ResponsePut(PutResponse { prev_kv: None }));
362            }
363        }
364        Ok(Some(resps))
365    }
366
367    async fn handle_batch_get(
368        &self,
369        query_executor: &mut ExecutorImpl<'_, T>,
370        txn_ops: &[TxnOp],
371    ) -> Result<Option<Vec<TxnOpResponse>>> {
372        let mut batch_get_req = BatchGetRequest { keys: vec![] };
373        for op in txn_ops {
374            if let TxnOp::Get(key) = op {
375                batch_get_req.keys.push(key.clone());
376            }
377        }
378        let res = self
379            .batch_get_with_query_executor(query_executor, batch_get_req)
380            .await?;
381        let res_map = res
382            .kvs
383            .into_iter()
384            .map(|kv| (kv.key, kv.value))
385            .collect::<HashMap<Vec<u8>, Vec<u8>>>();
386        let mut resps = Vec::with_capacity(txn_ops.len());
387        for op in txn_ops {
388            if let TxnOp::Get(key) = op {
389                let value = res_map.get(key);
390                resps.push(TxnOpResponse::ResponseGet(RangeResponse {
391                    kvs: value
392                        .map(|v| {
393                            vec![KeyValue {
394                                key: key.clone(),
395                                value: v.clone(),
396                            }]
397                        })
398                        .unwrap_or_default(),
399                    more: false,
400                }));
401            }
402        }
403        Ok(Some(resps))
404    }
405
406    async fn execute_txn_op(
407        &self,
408        query_executor: &mut ExecutorImpl<'_, T>,
409        op: &TxnOp,
410    ) -> Result<TxnOpResponse> {
411        match op {
412            TxnOp::Put(key, value) => {
413                let res = self
414                    .put_with_query_executor(
415                        query_executor,
416                        PutRequest {
417                            key: key.clone(),
418                            value: value.clone(),
419                            prev_kv: false,
420                        },
421                    )
422                    .await?;
423                Ok(TxnOpResponse::ResponsePut(res))
424            }
425            TxnOp::Get(key) => {
426                let res = self
427                    .range_with_query_executor(
428                        query_executor,
429                        RangeRequest {
430                            key: key.clone(),
431                            range_end: vec![],
432                            limit: 1,
433                            keys_only: false,
434                        },
435                    )
436                    .await?;
437                Ok(TxnOpResponse::ResponseGet(res))
438            }
439            TxnOp::Delete(key) => {
440                let res = self
441                    .delete_range_with_query_executor(
442                        query_executor,
443                        DeleteRangeRequest {
444                            key: key.clone(),
445                            range_end: vec![],
446                            prev_kv: false,
447                        },
448                    )
449                    .await?;
450                Ok(TxnOpResponse::ResponseDelete(res))
451            }
452        }
453    }
454
455    async fn txn_inner(&self, txn: &KvTxn) -> Result<KvTxnResponse> {
456        let mut default_executor = self.executor_factory.default_executor().await?;
457        let mut txn_executor = ExecutorImpl::Txn(
458            self.executor_factory
459                .txn_executor(&mut default_executor)
460                .await?,
461        );
462        let mut success = true;
463        if txn.c_when {
464            success = self
465                .execute_txn_cmp(&mut txn_executor, &txn.req.compare)
466                .await?;
467        }
468        let mut responses = vec![];
469        if success && txn.c_then {
470            match self
471                .try_batch_txn(&mut txn_executor, &txn.req.success)
472                .await?
473            {
474                Some(res) => responses.extend(res),
475                None => {
476                    for txnop in &txn.req.success {
477                        let res = self.execute_txn_op(&mut txn_executor, txnop).await?;
478                        responses.push(res);
479                    }
480                }
481            }
482        } else if !success && txn.c_else {
483            match self
484                .try_batch_txn(&mut txn_executor, &txn.req.failure)
485                .await?
486            {
487                Some(res) => responses.extend(res),
488                None => {
489                    for txnop in &txn.req.failure {
490                        let res = self.execute_txn_op(&mut txn_executor, txnop).await?;
491                        responses.push(res);
492                    }
493                }
494            }
495        }
496
497        txn_executor.commit().await?;
498        Ok(KvTxnResponse {
499            responses,
500            succeeded: success,
501        })
502    }
503}
504
505#[async_trait::async_trait]
506impl<T, S, R> KvBackend for RdsStore<T, S, R>
507where
508    R: 'static,
509    Self: KvQueryExecutor<T> + Send + Sync,
510    T: Executor + 'static,
511    S: ExecutorFactory<T> + 'static,
512{
513    fn capabilities(&self) -> KvBackendCapabilities {
514        KvBackendCapabilities {
515            atomic_batch_put: true,
516        }
517    }
518
519    fn name(&self) -> &str {
520        T::name()
521    }
522
523    fn as_any(&self) -> &dyn Any {
524        self
525    }
526
527    async fn range(&self, req: RangeRequest) -> Result<RangeResponse> {
528        let client = self.executor_factory.default_executor().await?;
529        let mut query_executor = ExecutorImpl::Default(client);
530        self.range_with_query_executor(&mut query_executor, req)
531            .await
532    }
533
534    async fn put(&self, req: PutRequest) -> Result<PutResponse> {
535        let client = self.executor_factory.default_executor().await?;
536        let mut query_executor = ExecutorImpl::Default(client);
537        self.put_with_query_executor(&mut query_executor, req).await
538    }
539
540    async fn batch_put(&self, req: BatchPutRequest) -> Result<BatchPutResponse> {
541        let client = self.executor_factory.default_executor().await?;
542        let mut query_executor = ExecutorImpl::Default(client);
543        self.batch_put_with_query_executor(&mut query_executor, req)
544            .await
545    }
546
547    async fn batch_get(&self, req: BatchGetRequest) -> Result<BatchGetResponse> {
548        let client = self.executor_factory.default_executor().await?;
549        let mut query_executor = ExecutorImpl::Default(client);
550        self.batch_get_with_query_executor(&mut query_executor, req)
551            .await
552    }
553
554    async fn delete_range(&self, req: DeleteRangeRequest) -> Result<DeleteRangeResponse> {
555        let client = self.executor_factory.default_executor().await?;
556        let mut query_executor = ExecutorImpl::Default(client);
557        self.delete_range_with_query_executor(&mut query_executor, req)
558            .await
559    }
560
561    async fn batch_delete(&self, req: BatchDeleteRequest) -> Result<BatchDeleteResponse> {
562        let client = self.executor_factory.default_executor().await?;
563        let mut query_executor = ExecutorImpl::Default(client);
564        self.batch_delete_with_query_executor(&mut query_executor, req)
565            .await
566    }
567}
568
569#[async_trait::async_trait]
570impl<T, S, R> TxnService for RdsStore<T, S, R>
571where
572    Self: KvQueryExecutor<T> + Send + Sync,
573    T: Executor + 'static,
574    S: ExecutorFactory<T> + 'static,
575{
576    type Error = Error;
577
578    async fn txn(&self, txn: KvTxn) -> Result<KvTxnResponse> {
579        let _timer = METRIC_META_TXN_REQUEST
580            .with_label_values(&[T::name(), "txn"])
581            .start_timer();
582
583        let mut backoff = ExponentialBuilder::default()
584            .with_min_delay(Duration::from_millis(10))
585            .with_max_delay(Duration::from_millis(200))
586            .with_max_times(self.txn_retry_count)
587            .build();
588
589        loop {
590            match self.txn_inner(&txn).await {
591                Ok(res) => return Ok(res),
592                Err(e) => {
593                    if e.is_serialization_error() {
594                        let d = backoff.next();
595                        if let Some(d) = d {
596                            tokio::time::sleep(d).await;
597                            continue;
598                        }
599                        break;
600                    } else {
601                        return Err(e);
602                    }
603                }
604            }
605        }
606
607        RdsTransactionRetryFailedSnafu {}.fail()
608    }
609
610    fn txn_capability(&self) -> Option<TxnCapability> {
611        Some(TxnCapability {
612            max_ops: self.max_txn_ops,
613        })
614    }
615}
616
617#[async_trait::async_trait]
618impl<T, S, R> ClosableKvBackend for RdsStore<T, S, R>
619where
620    R: 'static,
621    Self: KvQueryExecutor<T> + Send + Sync,
622    T: Executor + 'static,
623    S: ExecutorFactory<T> + 'static,
624{
625    async fn close(&self) -> Result<()> {
626        self.executor_factory.close().await;
627        Ok(())
628    }
629}
630
631/// Parses an optional row limit without exceeding the statement's parameter budget.
632#[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
633fn parse_batch_size(value: Option<&str>) -> usize {
634    value
635        .and_then(|value| value.parse().ok())
636        .filter(|size| (1..=u16::MAX as usize).contains(size))
637        .unwrap_or(u16::MAX as usize)
638}
639
640/// Checks if the transaction operations are the same type.
641fn check_txn_ops(txn_ops: &[TxnOp]) -> Result<bool> {
642    if txn_ops.is_empty() {
643        return Ok(false);
644    }
645    let same = txn_ops.windows(2).all(|a| {
646        matches!(
647            (&a[0], &a[1]),
648            (TxnOp::Put(_, _), TxnOp::Put(_, _))
649                | (TxnOp::Get(_), TxnOp::Get(_))
650                | (TxnOp::Delete(_), TxnOp::Delete(_))
651        )
652    });
653    Ok(same)
654}
655
656#[macro_export]
657macro_rules! record_rds_sql_execute_elapsed {
658    ($result:expr, $label_store:expr,$label_op:expr,$label_type:expr) => {{
659        let timer = std::time::Instant::now();
660        $result
661            .inspect(|_| {
662                $crate::metrics::RDS_SQL_EXECUTE_ELAPSED
663                    .with_label_values(&[$label_store, "success", $label_op, $label_type])
664                    .observe(timer.elapsed().as_millis() as f64)
665            })
666            .inspect_err(|_| {
667                $crate::metrics::RDS_SQL_EXECUTE_ELAPSED
668                    .with_label_values(&[$label_store, "error", $label_op, $label_type])
669                    .observe(timer.elapsed().as_millis() as f64);
670            })
671    }};
672}
673
674#[cfg(all(test, any(feature = "pg_kvbackend", feature = "mysql_kvbackend")))]
675mod tests {
676    use super::*;
677
678    #[test]
679    fn test_parse_batch_size() {
680        for (value, expected) in [
681            (None, 65_535),
682            (Some("1"), 1),
683            (Some("1024"), 1024),
684            (Some("65535"), 65_535),
685            (Some("0"), 65_535),
686            (Some("65536"), 65_535),
687            (Some("-1"), 65_535),
688            (Some("invalid"), 65_535),
689            (Some(""), 65_535),
690            (Some("18446744073709551616"), 65_535),
691        ] {
692            assert_eq!(parse_batch_size(value), expected, "{value:?}");
693        }
694    }
695}