etcdrs 0.1.2

An async etcd v3 client built on tonic and tokio, with composable operation builders and type-safe responses
Documentation
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Key-value record types.

use std::ops::{Deref, DerefMut};

use crate::{LeaseId, Revision, Version};

/// Couples the components of a database entry's three parts: the key, the value, and the associated metadata.
///
/// Monadic operations are provided for all elements. By default, the operand is the value (for example, [`Self::map`]
/// transforms the value). Functions which transform the key and metadata elements have `_key` and `_metadata` in their
/// names (for example, [`Self::map_key`] and [`Self::map_metadata`]).
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct Record<K = ::bytes::Bytes, V = ::bytes::Bytes, M = Metadata> {
    metadata: M,
    key: K,
    value: V,
}

impl<K, V, M> Record<K, V, M> {
    pub fn new(key: K, value: V, metadata: M) -> Self {
        Self { metadata, key, value }
    }

    /// Decompose this record into its constituent parts.
    pub fn into_parts(self) -> (M, K, V) {
        (self.metadata, self.key, self.value)
    }

    pub fn key(&self) -> &K {
        &self.key
    }

    pub fn key_mut(&mut self) -> &mut K {
        &mut self.key
    }

    pub fn take_key(self) -> K {
        self.key
    }

    pub fn value(&self) -> &V {
        &self.value
    }

    pub fn value_mut(&mut self) -> &mut V {
        &mut self.value
    }

    pub fn take_value(self) -> V {
        self.value
    }

    pub fn metadata(&self) -> &M {
        &self.metadata
    }

    pub fn metadata_mut(&mut self) -> &mut M {
        &mut self.metadata
    }

    pub fn take_metadata(self) -> M {
        self.metadata
    }

    pub fn without_value(self) -> KeyWithMetadata<K, M> {
        KeyWithMetadata::new(self.key, self.metadata)
    }

    /// Call `f` with the `value` and return a new `Record` with the result of the function call.
    pub fn map<RV>(self, f: impl FnOnce(V) -> RV) -> Record<K, RV, M> {
        Record {
            metadata: self.metadata,
            key: self.key,
            value: f(self.value),
        }
    }

    /// Call `f` with the `value`. If it returns `Ok(v)`, then this returns a new `Record` with that constructed `v`. If
    /// it returns `Err(e)`, then that is returned instead.
    ///
    /// ```
    /// # use etcdrs::record::Record;
    /// let r = Record::new(b"key", b"value", 1);
    /// let Ok(r) = r.map_checked(|v| std::str::from_utf8(v)) else {
    ///     panic!("not UTF-8!");
    /// };
    /// ```
    pub fn map_checked<RV, E>(self, f: impl FnOnce(V) -> Result<RV, E>) -> Result<Record<K, RV, M>, E> {
        Ok(Record {
            metadata: self.metadata,
            key: self.key,
            value: f(self.value)?,
        })
    }

    pub fn map_key<RK>(self, f: impl FnOnce(K) -> RK) -> Record<RK, V, M> {
        Record {
            metadata: self.metadata,
            key: f(self.key),
            value: self.value,
        }
    }

    pub fn map_key_checked<RK, E>(self, f: impl FnOnce(K) -> Result<RK, E>) -> Result<Record<RK, V, M>, E> {
        Ok(Record {
            metadata: self.metadata,
            key: f(self.key)?,
            value: self.value,
        })
    }

    pub fn map_metadata<RM>(self, f: impl FnOnce(M) -> RM) -> Record<K, V, RM> {
        Record {
            metadata: f(self.metadata),
            key: self.key,
            value: self.value,
        }
    }

    pub fn map_metadata_checked<RM, E>(self, f: impl FnOnce(M) -> Result<RM, E>) -> Result<Record<K, V, RM>, E> {
        Ok(Record {
            metadata: f(self.metadata)?,
            key: self.key,
            value: self.value,
        })
    }

    pub fn as_ref(&self) -> Record<&K, &V, &M> {
        Record {
            metadata: &self.metadata,
            key: &self.key,
            value: &self.value,
        }
    }

    pub fn as_mut(&mut self) -> Record<&mut K, &mut V, &mut M> {
        Record {
            metadata: &mut self.metadata,
            key: &mut self.key,
            value: &mut self.value,
        }
    }

    pub fn as_deref(&self) -> Record<&K, &V::Target, &M>
    where
        V: Deref,
    {
        self.as_ref().map(Deref::deref)
    }

    pub fn as_deref_mut(&mut self) -> Record<&mut K, &mut V::Target, &mut M>
    where
        V: DerefMut,
    {
        self.as_mut().map(DerefMut::deref_mut)
    }

    /// Call `f` with this instance, then return the original record. This is useful when doing method chaining.
    ///
    /// ```
    /// # use etcdrs::record::Record;
    /// Record::new("key-1", 5, ()) // <- imagine you got this from a function
    ///     .inspect(|r| println!("got {:?} = {}", r.key(), r.value()))
    ///     .map(|x| x * x)
    ///     // ... and so on ...
    ///     ;
    /// ```
    #[inline]
    pub fn inspect(self, f: impl FnOnce(&Self)) -> Self {
        f(&self);
        self
    }
}

impl<K, V, M, E> Record<K, Result<V, E>, M> {
    /// If you have ended up with a `value` which is a `Result` type, lift the value into the `Record` or return the
    /// error.
    ///
    /// ```
    /// # use etcdrs::record::Record;
    /// let r = Record::new(b"key", b"value", 1);
    /// let Ok(r) = r.map(|v| std::str::from_utf8(v)).transpose() else {
    ///     panic!("not UTF-8!");
    /// };
    /// ```
    pub fn transpose(self) -> Result<Record<K, V, M>, E> {
        Ok(Record {
            metadata: self.metadata,
            key: self.key,
            value: self.value?,
        })
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct KeyWithMetadata<K = ::bytes::Bytes, M = Metadata> {
    metadata: M,
    key: K,
}

impl<K, M> KeyWithMetadata<K, M> {
    pub fn new(key: K, metadata: M) -> Self {
        Self { metadata, key }
    }

    /// Decompose this into its constituent parts.
    pub fn into_parts(self) -> (M, K) {
        (self.metadata, self.key)
    }

    pub fn key(&self) -> &K {
        &self.key
    }

    pub fn key_mut(&mut self) -> &mut K {
        &mut self.key
    }

    pub fn take_key(self) -> K {
        self.key
    }

    pub fn metadata(&self) -> &M {
        &self.metadata
    }

    pub fn metadata_mut(&mut self) -> &mut M {
        &mut self.metadata
    }

    pub fn take_metadata(self) -> M {
        self.metadata
    }

    /// Add the `value` to the metadata contents to make a [`Record`].
    pub fn with_value<V>(self, value: V) -> Record<K, V, M> {
        Record::new(self.key, value, self.metadata)
    }

    pub fn map_key<RK>(self, f: impl FnOnce(K) -> RK) -> KeyWithMetadata<RK, M> {
        KeyWithMetadata {
            metadata: self.metadata,
            key: f(self.key),
        }
    }

    pub fn map_key_checked<RK, E>(self, f: impl FnOnce(K) -> Result<RK, E>) -> Result<KeyWithMetadata<RK, M>, E> {
        Ok(KeyWithMetadata {
            metadata: self.metadata,
            key: f(self.key)?,
        })
    }

    pub fn map_metadata<RM>(self, f: impl FnOnce(M) -> RM) -> KeyWithMetadata<K, RM> {
        KeyWithMetadata {
            metadata: f(self.metadata),
            key: self.key,
        }
    }

    pub fn map_metadata_checked<RM, E>(self, f: impl FnOnce(M) -> Result<RM, E>) -> Result<KeyWithMetadata<K, RM>, E> {
        Ok(KeyWithMetadata {
            metadata: f(self.metadata)?,
            key: self.key,
        })
    }

    pub fn as_ref(&self) -> KeyWithMetadata<&K, &M> {
        KeyWithMetadata {
            metadata: &self.metadata,
            key: &self.key,
        }
    }

    pub fn as_mut(&mut self) -> KeyWithMetadata<&mut K, &mut M> {
        KeyWithMetadata {
            metadata: &mut self.metadata,
            key: &mut self.key,
        }
    }

    /// Call `f` with this instance, then return the original record. This is useful when doing method chaining.
    ///
    /// ```
    /// # use etcdrs::record::KeyWithMetadata;
    /// KeyWithMetadata::new("key-1", 5) // <- imagine you got this from a function
    ///     .inspect(|r| println!("got {:?} metdata={}", r.key(), r.metadata()))
    ///     // ... and so on ...
    ///     ;
    /// ```
    #[inline]
    pub fn inspect(self, f: impl FnOnce(&Self)) -> Self {
        f(&self);
        self
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Metadata {
    /// The revision of the last time this key was created.
    pub create_revision: Revision,

    /// The revision of the last time this key was modified.
    pub modified_revision: Revision,

    /// The version of this record. Each modification to the record increments the version.
    pub version: Version,

    /// If the record has a lease, it will be automatically deleted when that lease expires. A value of `None` means the
    /// record is not ephemeral (there is no lease attached to the record).
    pub lease: Option<LeaseId>,
}

/// Convert the source into a database-encoded key.
pub trait AsKey {
    fn as_key(&self) -> &[u8];
}

impl<T: AsKey + ?Sized> AsKey for &'_ T {
    fn as_key(&self) -> &[u8] {
        T::as_key(self)
    }
}

/// Convert the source into a database-encoded value.
pub trait AsValue {
    fn as_value(&self) -> &[u8];
}

macro_rules! impl_basic_as {
    ($trait_name:ident, $fn_name:ident) => {
        impl $trait_name for &[u8] {
            fn $fn_name(&self) -> &[u8] {
                self
            }
        }

        impl<const N: usize> $trait_name for &[u8; N] {
            fn $fn_name(&self) -> &[u8] {
                &self[..]
            }
        }

        impl $trait_name for &mut [u8] {
            fn $fn_name(&self) -> &[u8] {
                self
            }
        }

        impl<const N: usize> $trait_name for &mut [u8; N] {
            fn $fn_name(&self) -> &[u8] {
                &self[..]
            }
        }

        impl $trait_name for Vec<u8> {
            fn $fn_name(&self) -> &[u8] {
                &self
            }
        }

        impl $trait_name for ::bytes::Bytes {
            fn $fn_name(&self) -> &[u8] {
                self
            }
        }

        impl $trait_name for &str {
            fn $fn_name(&self) -> &[u8] {
                self.as_bytes()
            }
        }

        impl $trait_name for &mut str {
            fn $fn_name(&self) -> &[u8] {
                self.as_bytes()
            }
        }

        impl $trait_name for String {
            fn $fn_name(&self) -> &[u8] {
                self.as_bytes()
            }
        }

        impl<T: $trait_name + ?Sized> $trait_name for Box<T> {
            fn $fn_name(&self) -> &[u8] {
                T::$fn_name(&**self)
            }
        }

        impl<T: $trait_name + ?Sized> $trait_name for std::rc::Rc<T> {
            fn $fn_name(&self) -> &[u8] {
                T::$fn_name(&**self)
            }
        }

        impl<T: $trait_name + ?Sized> $trait_name for std::sync::Arc<T> {
            fn $fn_name(&self) -> &[u8] {
                T::$fn_name(&**self)
            }
        }
    };
}

impl_basic_as!(AsKey, as_key);
impl_basic_as!(AsValue, as_value);