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
mod delete;
mod put;
mod range;
mod txn;

pub use delete::{DeleteRequest, DeleteResponse};
pub use put::{PutRequest, PutResponse};
pub use range::{RangeRequest, RangeResponse};
pub use txn::{TxnCmp, TxnOp, TxnOpResponse, TxnRequest, TxnResponse};

use tonic::transport::Channel;

use crate::proto::etcdserverpb::kv_client::KvClient;
use crate::proto::mvccpb;
use crate::Result as Res;

/// Key-Value client.
#[derive(Clone)]
pub struct Kv {
    client: KvClient<Channel>,
}

impl Kv {
    pub(crate) fn new(client: KvClient<Channel>) -> Self {
        Self { client }
    }

    /// Performs a key-value saving operation.
    pub async fn put(&mut self, req: PutRequest) -> Res<PutResponse> {
        let resp = self.client.put(tonic::Request::new(req.into())).await?;

        Ok(resp.into_inner().into())
    }

    /// Performs a key-value fetching operation.
    pub async fn range(&mut self, req: RangeRequest) -> Res<RangeResponse> {
        let resp = self.client.range(tonic::Request::new(req.into())).await?;

        Ok(resp.into_inner().into())
    }

    /// Performs a key-value deleting operation.
    pub async fn delete(&mut self, req: DeleteRequest) -> Res<DeleteResponse> {
        let resp = self
            .client
            .delete_range(tonic::Request::new(req.into()))
            .await?;

        Ok(resp.into_inner().into())
    }

    /// Performs a transaction operation.
    pub async fn txn(&mut self, req: TxnRequest) -> Res<TxnResponse> {
        let resp = self.client.txn(tonic::Request::new(req.into())).await?;

        Ok(resp.into_inner().into())
    }
}

/// Key-Value pair.
#[derive(Clone, PartialEq)]
pub struct KeyValue {
    proto: mvccpb::KeyValue,
}

impl KeyValue {
    /// Gets the key in bytes. An empty key is not allowed.
    pub fn key(&self) -> &[u8] {
        &self.proto.key
    }

    /// Takes the key out of response, leaving an empty vector in its place.
    pub fn take_key(&mut self) -> Vec<u8> {
        std::mem::take(&mut self.proto.key)
    }

    /// Converts the key from bytes `&[u8]` to `&str`.
    /// Leaves the original `&[u8]` in place, and creates a new string slice containing the entire content.
    pub fn key_str(&self) -> &str {
        std::str::from_utf8(&self.proto.key).expect("convert bytes to string")
    }

    /// Gets the value held by the key, in bytes.
    pub fn value(&self) -> &[u8] {
        &self.proto.value
    }

    /// Takes the value out of response, leaving an empty vector in its place.
    pub fn take_value(&mut self) -> Vec<u8> {
        std::mem::take(&mut self.proto.value)
    }

    /// Converts the value from bytes `&[u8]` to `&str`.
    /// Leaves the original `&[u8]` in place, and creates a new string slice containing the entire content.
    pub fn value_str(&self) -> &str {
        std::str::from_utf8(&self.proto.value).expect("convert bytes to string")
    }

    /// Gets the revision of last creation on this key.
    pub fn create_revision(&self) -> usize {
        self.proto.create_revision as usize
    }

    /// Gets the revision of last modification on this key.
    pub fn mod_revision(&self) -> usize {
        self.proto.mod_revision as usize
    }

    /// Gets the version of the key.
    pub fn version(&self) -> usize {
        self.proto.version as usize
    }

    /// Gets the ID of the lease that attached to key.
    pub fn lease(&self) -> usize {
        self.proto.lease as usize
    }

    /// Returns `true` if this KeyValue has a lease attached, and `false` otherwise.
    pub fn has_lease(&self) -> bool {
        self.proto.lease != 0
    }
}

impl From<mvccpb::KeyValue> for KeyValue {
    fn from(kv: mvccpb::KeyValue) -> Self {
        Self { proto: kv }
    }
}

/// KeyRange is an abstraction for describing etcd key of various types.
pub struct KeyRange {
    pub key: Vec<u8>,
    pub range_end: Vec<u8>,
}

impl KeyRange {
    /// Creates a new KeyRange for describing a range of multiple keys.
    pub fn range<K, R>(key: K, range_end: R) -> Self
    where
        K: Into<Vec<u8>>,
        R: Into<Vec<u8>>,
    {
        Self {
            key: key.into(),
            range_end: range_end.into(),
        }
    }

    /// Creates a new KeyRange for describing a specified key.
    pub fn key<K>(key: K) -> Self
    where
        K: Into<Vec<u8>>,
    {
        Self {
            key: key.into(),
            range_end: vec![],
        }
    }

    /// Creates a new KeyRange for describing all keys.
    pub fn all() -> Self {
        Self {
            key: vec![0],
            range_end: vec![0],
        }
    }

    /// Creates a new KeyRange for describing keys prefixed with specified value.
    pub fn prefix<K>(prefix: K) -> Self
    where
        K: Into<Vec<u8>>,
    {
        let key = prefix.into();
        if key.is_empty() {
            // An empty Vec<u8> results in an invalid KeyRange.
            // Assume that an empty value passed to this method implies no prefix (i.e., all keys).
            return KeyRange::all();
        }

        let range_end = {
            let mut end = key.clone();

            for i in (0..end.len()).rev() {
                if end[i] < 0xff {
                    end[i] += 1;
                    end.truncate(i + 1);
                    break;
                }
            }
            end
        };
        Self { key, range_end }
    }
}