Skip to main content

common_meta/
kv_backend.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::sync::Arc;
17
18use async_trait::async_trait;
19use common_error::ext::ErrorExt;
20pub use txn::{TxnCapability, TxnService};
21
22use crate::error::Error;
23use crate::kv_backend::txn::{Txn, TxnOpResponse};
24use crate::rpc::KeyValue;
25use crate::rpc::store::{
26    BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse, BatchPutRequest,
27    BatchPutResponse, CompareAndPutRequest, CompareAndPutResponse, DeleteRangeRequest,
28    DeleteRangeResponse, PutRequest, PutResponse, RangeRequest, RangeResponse,
29};
30
31pub mod chroot;
32pub mod etcd;
33pub mod memory;
34#[cfg(any(feature = "mysql_kvbackend", feature = "pg_kvbackend"))]
35pub mod rds;
36pub mod read_only;
37pub mod test;
38#[cfg(any(test, feature = "testing"))]
39pub mod test_util;
40pub mod txn;
41pub mod util;
42pub type KvBackendRef<E = Error> = Arc<dyn KvBackend<Error = E> + Send + Sync>;
43
44/// A [KvBackend] holding resources that must be released explicitly on shutdown, because
45/// components sharing it may keep it alive until the process exits.
46///
47/// Wrappers of a closable backend must forward [ClosableKvBackend::close] to it.
48#[async_trait]
49pub trait ClosableKvBackend: KvBackend<Error = Error> {
50    /// Releases the backend's resources; any later use fails.
51    /// May wait for in-flight operations to release their resources, so callers must
52    /// stop consumers first. Closing is terminal, not a pause for role transitions.
53    async fn close(&self) -> Result<(), Error>;
54}
55
56pub type ClosableKvBackendRef = Arc<dyn ClosableKvBackend + Send + Sync>;
57
58#[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
59// The default meta table name, default is "greptime_metakv".
60pub const DEFAULT_META_TABLE_NAME: &str = "greptime_metakv";
61
62#[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
63// The default lock id for election, default is 1.
64pub const DEFAULT_META_ELECTION_LOCK_ID: u64 = 1;
65
66/// Guarantees provided by a key-value backend.
67#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
68pub struct KvBackendCapabilities {
69    /// All key-value pairs in one [`KvBackend::batch_put`] call are applied atomically.
70    pub atomic_batch_put: bool,
71}
72
73#[async_trait]
74pub trait KvBackend: TxnService
75where
76    Self::Error: ErrorExt,
77{
78    fn capabilities(&self) -> KvBackendCapabilities {
79        KvBackendCapabilities::default()
80    }
81
82    fn name(&self) -> &str;
83
84    fn as_any(&self) -> &dyn Any;
85
86    async fn range(&self, req: RangeRequest) -> Result<RangeResponse, Self::Error>;
87
88    async fn put(&self, req: PutRequest) -> Result<PutResponse, Self::Error>;
89
90    async fn batch_put(&self, req: BatchPutRequest) -> Result<BatchPutResponse, Self::Error>;
91
92    async fn batch_get(&self, req: BatchGetRequest) -> Result<BatchGetResponse, Self::Error>;
93
94    async fn delete_range(
95        &self,
96        req: DeleteRangeRequest,
97    ) -> Result<DeleteRangeResponse, Self::Error>;
98
99    async fn batch_delete(
100        &self,
101        req: BatchDeleteRequest,
102    ) -> Result<BatchDeleteResponse, Self::Error>;
103
104    // The following methods are implemented based on the above methods,
105    // and a higher-level interface is provided for to simplify usage.
106
107    async fn get(&self, key: &[u8]) -> Result<Option<KeyValue>, Self::Error> {
108        let req = RangeRequest::new().with_key(key.to_vec());
109        let mut resp = self.range(req).await?;
110        Ok(if resp.kvs.is_empty() {
111            None
112        } else {
113            Some(resp.kvs.remove(0))
114        })
115    }
116
117    /// CAS: Compares the value at the key with the given value, and if they are
118    /// equal, puts the new value at the key.
119    async fn compare_and_put(
120        &self,
121        req: CompareAndPutRequest,
122    ) -> Result<CompareAndPutResponse, Self::Error> {
123        let CompareAndPutRequest { key, expect, value } = req;
124        let txn = if expect.is_empty() {
125            Txn::put_if_not_exists(key, value)
126        } else {
127            Txn::compare_and_put(key, expect, value)
128        };
129        let txn_res = self.txn(txn).await?;
130
131        let success = txn_res.succeeded;
132        // The response is guaranteed to have at most one element.
133        let op_res = txn_res.responses.into_iter().next();
134        let prev_kv = match op_res {
135            Some(TxnOpResponse::ResponsePut(res)) => res.prev_kv,
136            Some(TxnOpResponse::ResponseGet(res)) => res.kvs.into_iter().next(),
137            Some(TxnOpResponse::ResponseDelete(res)) => res.prev_kvs.into_iter().next(),
138            None => None,
139        };
140
141        Ok(CompareAndPutResponse { success, prev_kv })
142    }
143
144    /// Puts a value at a key. If `if_not_exists` is `true`, the operation
145    /// ensures the key does not exist before applying the PUT operation.
146    /// Otherwise, it simply applies the PUT operation without checking for
147    /// the key's existence.
148    async fn put_conditionally(
149        &self,
150        key: Vec<u8>,
151        value: Vec<u8>,
152        if_not_exists: bool,
153    ) -> Result<bool, Self::Error> {
154        let success = if if_not_exists {
155            let req = CompareAndPutRequest::new()
156                .with_key(key)
157                .with_expect(vec![])
158                .with_value(value);
159            let res = self.compare_and_put(req).await?;
160            res.success
161        } else {
162            let req = PutRequest::new().with_key(key).with_value(value);
163            self.put(req).await?;
164            true
165        };
166
167        Ok(success)
168    }
169
170    /// Check if the key exists, not returning the value.
171    /// If the value is large, this method is more efficient than `get`.
172    async fn exists(&self, key: &[u8]) -> Result<bool, Self::Error> {
173        let req = RangeRequest::new().with_key(key.to_vec()).with_keys_only();
174        let resp = self.range(req).await?;
175        Ok(!resp.kvs.is_empty())
176    }
177
178    /// Returns previous key-value pair if `prev_kv` is `true`.
179    async fn delete(&self, key: &[u8], prev_kv: bool) -> Result<Option<KeyValue>, Self::Error> {
180        let mut req = DeleteRangeRequest::new().with_key(key.to_vec());
181        if prev_kv {
182            req = req.with_prev_kv();
183        }
184
185        let resp = self.delete_range(req).await?;
186
187        if prev_kv {
188            Ok(resp.prev_kvs.into_iter().next())
189        } else {
190            Ok(None)
191        }
192    }
193}
194
195pub trait ResettableKvBackend: KvBackend
196where
197    Self::Error: ErrorExt,
198{
199    fn reset(&self);
200
201    /// Upcast as `KvBackendRef`. Since https://github.com/rust-lang/rust/issues/65991 is not yet stable.
202    fn as_kv_backend_ref(self: Arc<Self>) -> KvBackendRef<Self::Error>;
203}
204
205pub type ResettableKvBackendRef<E = Error> = Arc<dyn ResettableKvBackend<Error = E> + Send + Sync>;