Skip to main content

common_meta/kv_backend/
chroot.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;
16
17use crate::error::Error;
18use crate::kv_backend::txn::{Txn, TxnOp, TxnOpResponse, TxnResponse};
19use crate::kv_backend::{
20    KvBackend, KvBackendCapabilities, KvBackendRef, TxnCapability, TxnService,
21};
22use crate::rpc::KeyValue;
23use crate::rpc::store::{
24    BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse, BatchPutRequest,
25    BatchPutResponse, CompareAndPutRequest, CompareAndPutResponse, DeleteRangeRequest,
26    DeleteRangeResponse, PutRequest, PutResponse, RangeRequest, RangeResponse,
27};
28
29pub struct ChrootKvBackend {
30    root: Vec<u8>,
31    inner: KvBackendRef,
32}
33
34impl ChrootKvBackend {
35    pub fn new(root: Vec<u8>, inner: KvBackendRef) -> ChrootKvBackend {
36        debug_assert!(!root.is_empty());
37        ChrootKvBackend { root, inner }
38    }
39}
40
41#[async_trait::async_trait]
42impl TxnService for ChrootKvBackend {
43    type Error = Error;
44
45    async fn txn(&self, txn: Txn) -> Result<TxnResponse, Self::Error> {
46        let txn = self.txn_prepend_root(txn);
47        let txn_res = self.inner.txn(txn).await?;
48        Ok(self.chroot_txn_response(txn_res))
49    }
50
51    fn txn_capability(&self) -> Option<TxnCapability> {
52        self.inner.txn_capability()
53    }
54}
55
56#[async_trait::async_trait]
57impl KvBackend for ChrootKvBackend {
58    fn capabilities(&self) -> KvBackendCapabilities {
59        self.inner.capabilities()
60    }
61
62    fn name(&self) -> &str {
63        self.inner.name()
64    }
65
66    fn as_any(&self) -> &dyn Any {
67        self
68    }
69
70    async fn range(&self, mut req: RangeRequest) -> Result<RangeResponse, Self::Error> {
71        req.key = self.key_prepend_root(req.key);
72        req.range_end = self.range_end_prepend_root(req.range_end);
73        let mut res = self.inner.range(req).await?;
74        res.kvs = res
75            .kvs
76            .drain(..)
77            .map(self.chroot_key_value_with())
78            .collect();
79        Ok(res)
80    }
81
82    async fn put(&self, mut req: PutRequest) -> Result<PutResponse, Self::Error> {
83        req.key = self.key_prepend_root(req.key);
84        let mut res = self.inner.put(req).await?;
85        res.prev_kv = res.prev_kv.take().map(self.chroot_key_value_with());
86        Ok(res)
87    }
88
89    async fn batch_put(&self, mut req: BatchPutRequest) -> Result<BatchPutResponse, Self::Error> {
90        for kv in req.kvs.iter_mut() {
91            kv.key = self.key_prepend_root(std::mem::take(&mut kv.key));
92        }
93        let mut res = self.inner.batch_put(req).await?;
94        res.prev_kvs = res
95            .prev_kvs
96            .drain(..)
97            .map(self.chroot_key_value_with())
98            .collect();
99        Ok(res)
100    }
101
102    async fn batch_get(&self, mut req: BatchGetRequest) -> Result<BatchGetResponse, Self::Error> {
103        req.keys = req
104            .keys
105            .drain(..)
106            .map(|key| self.key_prepend_root(key))
107            .collect();
108        let mut res = self.inner.batch_get(req).await?;
109        res.kvs = res
110            .kvs
111            .drain(..)
112            .map(self.chroot_key_value_with())
113            .collect();
114        Ok(res)
115    }
116
117    async fn compare_and_put(
118        &self,
119        mut req: CompareAndPutRequest,
120    ) -> Result<CompareAndPutResponse, Self::Error> {
121        req.key = self.key_prepend_root(req.key);
122        let mut res = self.inner.compare_and_put(req).await?;
123        res.prev_kv = res.prev_kv.take().map(self.chroot_key_value_with());
124        Ok(res)
125    }
126
127    async fn delete_range(
128        &self,
129        mut req: DeleteRangeRequest,
130    ) -> Result<DeleteRangeResponse, Self::Error> {
131        req.key = self.key_prepend_root(req.key);
132        req.range_end = self.range_end_prepend_root(req.range_end);
133        let mut res = self.inner.delete_range(req).await?;
134        res.prev_kvs = res
135            .prev_kvs
136            .drain(..)
137            .map(self.chroot_key_value_with())
138            .collect();
139        Ok(res)
140    }
141
142    async fn batch_delete(
143        &self,
144        mut req: BatchDeleteRequest,
145    ) -> Result<BatchDeleteResponse, Self::Error> {
146        req.keys = req
147            .keys
148            .drain(..)
149            .map(|key| self.key_prepend_root(key))
150            .collect();
151        let mut res = self.inner.batch_delete(req).await?;
152        res.prev_kvs = res
153            .prev_kvs
154            .drain(..)
155            .map(self.chroot_key_value_with())
156            .collect();
157        Ok(res)
158    }
159}
160
161impl ChrootKvBackend {
162    fn key_strip_root(&self, mut key: Vec<u8>) -> Vec<u8> {
163        let root = &self.root;
164        debug_assert!(
165            key.starts_with(root),
166            "key={}, root={}",
167            String::from_utf8_lossy(&key),
168            String::from_utf8_lossy(root),
169        );
170        key.split_off(root.len())
171    }
172
173    fn chroot_key_value_with(&self) -> impl FnMut(KeyValue) -> KeyValue + '_ {
174        |kv| KeyValue {
175            key: self.key_strip_root(kv.key),
176            value: kv.value,
177        }
178    }
179    fn chroot_txn_response(&self, mut txn_res: TxnResponse) -> TxnResponse {
180        for resp in txn_res.responses.iter_mut() {
181            match resp {
182                TxnOpResponse::ResponsePut(r) => {
183                    r.prev_kv = r.prev_kv.take().map(self.chroot_key_value_with());
184                }
185                TxnOpResponse::ResponseGet(r) => {
186                    r.kvs = r.kvs.drain(..).map(self.chroot_key_value_with()).collect();
187                }
188                TxnOpResponse::ResponseDelete(r) => {
189                    r.prev_kvs = r
190                        .prev_kvs
191                        .drain(..)
192                        .map(self.chroot_key_value_with())
193                        .collect();
194                }
195            }
196        }
197        txn_res
198    }
199
200    fn key_prepend_root(&self, mut key: Vec<u8>) -> Vec<u8> {
201        let mut new_key = self.root.clone();
202        new_key.append(&mut key);
203        new_key
204    }
205
206    // see namespace.prefixInterval - https://github.com/etcd-io/etcd/blob/v3.5.10/client/v3/namespace/util.go
207    fn range_end_prepend_root(&self, mut range_end: Vec<u8>) -> Vec<u8> {
208        let root = &self.root;
209        if range_end == [0] {
210            // the edge of the keyspace
211            let mut new_end = root.clone();
212            let mut ok = false;
213            for i in (0..new_end.len()).rev() {
214                new_end[i] = new_end[i].wrapping_add(1);
215                if new_end[i] != 0 {
216                    ok = true;
217                    break;
218                }
219            }
220            if !ok {
221                // 0xff..ff => 0x00
222                new_end = vec![0];
223            }
224            new_end
225        } else if !range_end.is_empty() {
226            let mut new_end = root.clone();
227            new_end.append(&mut range_end);
228            new_end
229        } else {
230            vec![]
231        }
232    }
233
234    fn txn_prepend_root(&self, mut txn: Txn) -> Txn {
235        let op_prepend_root = |op: TxnOp| match op {
236            TxnOp::Put(k, v) => TxnOp::Put(self.key_prepend_root(k), v),
237            TxnOp::Get(k) => TxnOp::Get(self.key_prepend_root(k)),
238            TxnOp::Delete(k) => TxnOp::Delete(self.key_prepend_root(k)),
239        };
240        txn.req.success = txn.req.success.drain(..).map(op_prepend_root).collect();
241        txn.req.failure = txn.req.failure.drain(..).map(op_prepend_root).collect();
242        txn.req.compare = txn
243            .req
244            .compare
245            .drain(..)
246            .map(|cmp| super::txn::Compare {
247                key: self.key_prepend_root(cmp.key),
248                cmp: cmp.cmp,
249                target: cmp.target,
250            })
251            .collect();
252        txn
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use std::sync::Arc;
259
260    use crate::kv_backend::chroot::ChrootKvBackend;
261    use crate::kv_backend::memory::MemoryKvBackend;
262
263    #[test]
264    fn test_prefix_key_and_range_end() {
265        fn run_test_case(pfx: &[u8], key: &[u8], end: &[u8], w_key: &[u8], w_end: &[u8]) {
266            let chroot = ChrootKvBackend::new(pfx.into(), Arc::new(MemoryKvBackend::new()));
267            assert_eq!(chroot.key_prepend_root(key.into()), w_key);
268            assert_eq!(chroot.range_end_prepend_root(end.into()), w_end);
269        }
270
271        // single key
272        run_test_case(b"pfx/", b"a", b"", b"pfx/a", b"");
273
274        // range
275        run_test_case(b"pfx/", b"abc", b"def", b"pfx/abc", b"pfx/def");
276
277        // one-sided range (HACK - b'/' + 1 = b'0')
278        run_test_case(b"pfx/", b"abc", b"\0", b"pfx/abc", b"pfx0");
279
280        // one-sided range, end of keyspace
281        run_test_case(b"\xFF\xFF", b"abc", b"\0", b"\xff\xffabc", b"\0");
282    }
283}