Skip to main content

common_meta/kv_backend/
txn.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::cmp::max;
16
17use common_error::ext::ErrorExt;
18
19use crate::rpc::store::{DeleteRangeResponse, PutResponse, RangeResponse};
20
21mod etcd;
22
23/// Limits for backends that support explicit transactions.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct TxnCapability {
26    /// Maximum number of operations permitted in one transaction.
27    pub max_ops: usize,
28}
29
30#[async_trait::async_trait]
31pub trait TxnService: Sync + Send {
32    type Error: ErrorExt;
33
34    async fn txn(&self, _txn: Txn) -> Result<TxnResponse, Self::Error> {
35        unimplemented!("txn is not implemented")
36    }
37
38    /// Returns None when explicit transactions are unsupported.
39    fn txn_capability(&self) -> Option<TxnCapability> {
40        None
41    }
42}
43
44#[derive(Debug, Clone, PartialEq)]
45pub enum CompareOp {
46    Equal,
47    Greater,
48    Less,
49    NotEqual,
50}
51
52#[derive(Debug, Clone, PartialEq)]
53pub struct Compare {
54    pub key: Vec<u8>,
55    pub cmp: CompareOp,
56    /// None means the key does not exist.
57    pub target: Option<Vec<u8>>,
58}
59
60impl Compare {
61    pub fn new(key: Vec<u8>, cmp: CompareOp, target: Option<Vec<u8>>) -> Self {
62        Self { key, cmp, target }
63    }
64
65    pub fn with_value(key: Vec<u8>, cmp: CompareOp, target: Vec<u8>) -> Self {
66        Self::new(key, cmp, Some(target))
67    }
68
69    pub fn with_value_not_exists(key: Vec<u8>, cmp: CompareOp) -> Self {
70        Self::new(key, cmp, None)
71    }
72
73    pub fn compare_value(&self, value: Option<&Vec<u8>>) -> bool {
74        match (value, &self.target) {
75            (Some(value), Some(target)) => match self.cmp {
76                CompareOp::Equal => *value == *target,
77                CompareOp::Greater => *value > *target,
78                CompareOp::Less => *value < *target,
79                CompareOp::NotEqual => *value != *target,
80            },
81            (Some(_), None) => match self.cmp {
82                CompareOp::Equal => false,
83                CompareOp::Greater => true,
84                CompareOp::Less => false,
85                CompareOp::NotEqual => true,
86            },
87            (None, Some(_)) => match self.cmp {
88                CompareOp::Equal => false,
89                CompareOp::Greater => false,
90                CompareOp::Less => true,
91                CompareOp::NotEqual => true,
92            },
93            (None, None) => match self.cmp {
94                CompareOp::Equal => true,
95                CompareOp::Greater => false,
96                CompareOp::Less => false,
97                CompareOp::NotEqual => false,
98            },
99        }
100    }
101}
102
103#[derive(Debug, Clone, PartialEq)]
104pub enum TxnOp {
105    Put(Vec<u8>, Vec<u8>),
106    Get(Vec<u8>),
107    Delete(Vec<u8>),
108}
109
110#[derive(Debug, Clone, Default, PartialEq)]
111pub struct TxnRequest {
112    pub compare: Vec<Compare>,
113    pub success: Vec<TxnOp>,
114    pub failure: Vec<TxnOp>,
115}
116
117impl TxnRequest {
118    pub fn extend(&mut self, other: TxnRequest) {
119        self.compare.extend(other.compare);
120        self.success.extend(other.success);
121        self.failure.extend(other.failure);
122    }
123}
124
125#[derive(Debug, Clone, PartialEq)]
126pub enum TxnOpResponse {
127    ResponsePut(PutResponse),
128    ResponseGet(RangeResponse),
129    ResponseDelete(DeleteRangeResponse),
130}
131
132pub struct TxnResponse {
133    pub succeeded: bool,
134    pub responses: Vec<TxnOpResponse>,
135}
136
137#[derive(Debug, Clone, Default, PartialEq)]
138pub struct Txn {
139    // HACK - chroot would modify this field
140    pub(super) req: TxnRequest,
141    pub(super) c_when: bool,
142    pub(super) c_then: bool,
143    pub(super) c_else: bool,
144}
145
146#[cfg(any(test, feature = "testing"))]
147impl Txn {
148    pub fn req(&self) -> &TxnRequest {
149        &self.req
150    }
151}
152
153impl Txn {
154    pub fn merge_all<T: IntoIterator<Item = Txn>>(values: T) -> Self {
155        values
156            .into_iter()
157            .reduce(|acc, e| acc.merge(e))
158            .unwrap_or_default()
159    }
160
161    pub fn merge(mut self, other: Txn) -> Self {
162        self.c_when |= other.c_when;
163        self.c_then |= other.c_then;
164        self.c_else |= other.c_else;
165
166        self.req.extend(other.req);
167
168        self
169    }
170
171    pub fn new() -> Self {
172        Txn::default()
173    }
174
175    /// Builds a transaction that puts a value at a key if the key does not exist.
176    pub fn put_if_not_exists(key: Vec<u8>, value: Vec<u8>) -> Self {
177        Self::new()
178            .when(vec![Compare::with_value_not_exists(
179                key.clone(),
180                CompareOp::Equal,
181            )])
182            .and_then(vec![TxnOp::Put(key.clone(), value)])
183            .or_else(vec![TxnOp::Get(key)])
184    }
185
186    /// Builds a transaction that puts a value at a key if the key exists and the value
187    /// is equal to `expect`.
188    pub fn compare_and_put(key: Vec<u8>, expect: Vec<u8>, value: Vec<u8>) -> Self {
189        Self::new()
190            .when(vec![Compare::with_value(
191                key.clone(),
192                CompareOp::Equal,
193                expect,
194            )])
195            .and_then(vec![TxnOp::Put(key.clone(), value)])
196            .or_else(vec![TxnOp::Get(key)])
197    }
198
199    /// Takes a list of comparison. If all comparisons passed in succeed,
200    /// the operations passed into `and_then()` will be executed. Or the operations
201    /// passed into `or_else()` will be executed.
202    #[inline]
203    pub fn when(mut self, compares: impl Into<Vec<Compare>>) -> Self {
204        assert!(!self.c_when, "cannot call `when` twice");
205        assert!(!self.c_then, "cannot call `when` after `and_then`");
206        assert!(!self.c_else, "cannot call `when` after `or_else`");
207
208        self.c_when = true;
209        self.req.compare = compares.into();
210        self
211    }
212
213    /// Takes a list of operations. The operations list will be executed, if the
214    /// comparisons passed into `when()` succeed.
215    #[inline]
216    pub fn and_then(mut self, operations: impl Into<Vec<TxnOp>>) -> Self {
217        assert!(!self.c_then, "cannot call `and_then` twice");
218        assert!(!self.c_else, "cannot call `and_then` after `or_else`");
219
220        self.c_then = true;
221        self.req.success = operations.into();
222        self
223    }
224
225    /// Takes a list of operations. The operations list will be executed, if the
226    /// comparisons passed into `when()` fail.
227    #[inline]
228    pub fn or_else(mut self, operations: impl Into<Vec<TxnOp>>) -> Self {
229        assert!(!self.c_else, "cannot call `or_else` twice");
230
231        self.c_else = true;
232        self.req.failure = operations.into();
233        self
234    }
235
236    #[inline]
237    pub fn max_operations(&self) -> usize {
238        let opc = max(self.req.compare.len(), self.req.success.len());
239        max(opc, self.req.failure.len())
240    }
241}
242
243impl From<Txn> for TxnRequest {
244    fn from(txn: Txn) -> Self {
245        txn.req
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn test_compare() {
255        // Equal
256        let compare = Compare::with_value(vec![1], CompareOp::Equal, vec![1]);
257        assert!(compare.compare_value(Some(&vec![1])));
258        assert!(!compare.compare_value(None));
259        let compare = Compare::with_value_not_exists(vec![1], CompareOp::Equal);
260        assert!(compare.compare_value(None));
261
262        // Greater
263        let compare = Compare::with_value(vec![1], CompareOp::Greater, vec![1]);
264        assert!(compare.compare_value(Some(&vec![2])));
265        assert!(!compare.compare_value(None));
266        let compare = Compare::with_value_not_exists(vec![1], CompareOp::Greater);
267        assert!(!compare.compare_value(None));
268        assert!(compare.compare_value(Some(&vec![1])));
269
270        // Less
271        let compare = Compare::with_value(vec![1], CompareOp::Less, vec![1]);
272        assert!(compare.compare_value(Some(&vec![0])));
273        assert!(compare.compare_value(None));
274        let compare = Compare::with_value_not_exists(vec![1], CompareOp::Less);
275        assert!(!compare.compare_value(None));
276        assert!(!compare.compare_value(Some(&vec![1])));
277
278        // NotEqual
279        let compare = Compare::with_value(vec![1], CompareOp::NotEqual, vec![1]);
280        assert!(!compare.compare_value(Some(&vec![1])));
281        assert!(compare.compare_value(Some(&vec![2])));
282        assert!(compare.compare_value(None));
283        let compare = Compare::with_value_not_exists(vec![1], CompareOp::NotEqual);
284        assert!(!compare.compare_value(None));
285        assert!(compare.compare_value(Some(&vec![1])));
286    }
287
288    #[test]
289    fn test_txn() {
290        let txn = Txn::new()
291            .when(vec![Compare::with_value(
292                vec![1],
293                CompareOp::Equal,
294                vec![1],
295            )])
296            .and_then(vec![TxnOp::Put(vec![1], vec![1])])
297            .or_else(vec![TxnOp::Put(vec![1], vec![2])]);
298
299        assert_eq!(
300            txn,
301            Txn {
302                req: TxnRequest {
303                    compare: vec![Compare::with_value(vec![1], CompareOp::Equal, vec![1])],
304                    success: vec![TxnOp::Put(vec![1], vec![1])],
305                    failure: vec![TxnOp::Put(vec![1], vec![2])],
306                },
307                c_when: true,
308                c_then: true,
309                c_else: true,
310            }
311        );
312    }
313}