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
use std::{
future::{Future, IntoFuture},
marker::PhantomData,
pin::Pin,
task::{Context, Poll},
};
use bytes::Bytes;
use crate::{
AsRange, Client, Prefix, ResponseHeader, TargetRange,
client::{ClientInner, GetPreviousValue},
pb::etcdserverpb,
record::{AsKey, Record},
};
/// # Deleting Keys
impl Client {
/// Delete the given `key` from the database.
///
/// The value returned from `await`ing the operation is `true` if the key was deleted or `false` if the key was not
/// found. In other words, it is not an error to try to delete a key that does not exist.
///
/// ```no_run
/// # async {
/// # let client: etcdrs::Client = todo!();
/// let deleted = client
/// .delete("foo")
/// .await
/// .unwrap()
/// .deleted();
/// println!("deleted? {deleted}");
/// # };
/// ```
pub fn delete(&self, key: impl AsKey) -> Delete<Self, bool> {
Delete::new(key).with_client(self.clone())
}
/// Delete all keys matching the given `range`.
///
/// The value returned from `await`ing the operation is the number of keys that were deleted.
///
/// ```no_run
/// # async {
/// # let client: etcdrs::Client = todo!();
/// // Delete a range of keys
/// let count = client.delete_range("foo/a".."foo/z").await.unwrap().deleted();
/// println!("deleted {count} keys");
///
/// // Delete ranges use the Rust range syntax:
/// let _ = client.delete_range(..); // all keys
/// let _ = client.delete_range("a"..="b"); // from "a" up to and including "b"
/// let _ = client.delete_range(.."taco"); // everything up to "taco"
/// let _ = client.delete_range("taco"..); // "taco" and everything after
/// # };
/// ```
///
/// You can specify a [prefix][crate::Prefix] query as well, but it is usually easier to use the
/// [`delete_prefix`][Self::delete_prefix] method instead.
pub fn delete_range(&self, range: impl AsRange) -> Delete<Self, usize> {
Delete::with_range(range).with_client(self.clone())
}
/// Delete all keys matching the given `prefix`.
///
/// This is the same as calling [`delete_range`][Self::delete_range] with a [`Prefix`] query. An empty prefix
/// deletes every key.
///
/// ```no_run
/// # async {
/// # let client: etcdrs::Client = todo!();
/// let count = client.delete_prefix("foo/").await.unwrap().deleted();
/// println!("deleted {count} keys");
/// # };
/// ```
pub fn delete_prefix(&self, prefix: impl AsKey) -> Delete<Self, usize> {
self.delete_range(Prefix(prefix))
}
}
/// A [`Client::delete`], [`Client::delete_range`], or [`Client::delete_prefix`] operation.
#[derive(Clone, Debug)]
pub struct Delete<C, R, P = ()> {
client: C,
pub(crate) request: etcdserverpb::DeleteRangeRequest,
_return: PhantomData<fn() -> (R, P)>,
}
impl Delete<(), bool> {
pub fn new(key: impl AsKey) -> Self {
Self {
client: (),
request: etcdserverpb::DeleteRangeRequest {
key: Bytes::copy_from_slice(key.as_key()),
..Default::default()
},
_return: PhantomData,
}
}
}
impl Delete<(), usize> {
/// Create a new delete operation with the specified `range`.
///
/// See [`delete_range`][Client::delete_range] for more information.
pub fn with_range(range: impl AsRange) -> Self {
let (key, range_end) = range.as_boundaries();
Self {
client: (),
request: etcdserverpb::DeleteRangeRequest {
key,
range_end,
..Default::default()
},
_return: PhantomData,
}
}
/// Create a new delete operation with the specified `prefix`.
///
/// See [`delete_prefix`][Client::delete_prefix] for more information.
pub fn with_prefix(prefix: impl AsKey) -> Self {
Self::with_range(Prefix(prefix))
}
}
impl<C, R, P> Delete<C, R, P> {
pub fn with_client<C2>(self, client: C2) -> Delete<C2, R, P> {
Delete {
client,
request: self.request,
_return: PhantomData,
}
}
/// The range this operation addresses.
pub fn target_range(&self) -> TargetRange<'_> {
TargetRange::from_wire(&self.request.key, &self.request.range_end)
}
/// Whether the previous key-value(s) will be returned.
pub fn returns_previous(&self) -> bool {
self.request.prev_kv
}
/// Decompose this operation into its client and a detached `Delete<(), R, P>`.
pub(crate) fn into_parts(self) -> (C, Delete<(), R, P>) {
(
self.client,
Delete {
client: (),
request: self.request,
_return: PhantomData,
},
)
}
}
impl<C, P> Delete<C, bool, P> {
/// The key this single-key delete addresses.
pub fn target_key(&self) -> &[u8] {
&self.request.key
}
}
impl<C, R, P> Delete<C, R, P> {
/// Return the previous key-value.
///
/// If you are deleting a single key, this means the previous value of the key will be returned.
/// If you are deleting a range, this means the previous key-values in the range will be
/// returned in a vector.
///
/// > **WARNING**
/// >
/// > Getting the previous value of the key has no pagination mechanism. If you are deleting a
/// > range (or a large key), the delete will succeed, but the response will fail with a
/// > `RESOURCE_EXHAUSTED` "message too large" error. There is not really a good way to handle
/// > this, so be careful when using this method.
pub fn get_previous(self) -> Delete<C, R, GetPreviousValue> {
let mut request = self.request;
request.prev_kv = true;
Delete {
client: self.client,
request,
_return: PhantomData,
}
}
}
/// The response from a [`delete`][Client::delete] or [`delete_range`][Client::delete_range]
/// operation.
#[derive(Clone, Debug)]
pub struct DeleteResponse<R, P = ()> {
header: ResponseHeader,
deleted: usize,
previous: Vec<Record>,
_marker: PhantomData<fn() -> (R, P)>,
}
impl<R, P> DeleteResponse<R, P> {
/// Construct a new `DeleteResponse`.
///
/// Note that `previous` is only meaningful with certain `R` and `P` types. While you can
/// provide many values in a `previous` vector, it can't be looked at if `P = ()` and only the
/// first element will be looked at if `R = bool`.
pub fn new(header: ResponseHeader, deleted: usize, previous: Vec<Record>) -> Self {
Self {
header,
deleted,
previous,
_marker: PhantomData,
}
}
/// The response header containing cluster metadata and the store revision.
pub fn header(&self) -> &ResponseHeader {
&self.header
}
}
impl<P> DeleteResponse<bool, P> {
/// Returns `true` if the key was deleted, `false` if it did not exist.
pub fn deleted(&self) -> bool {
self.deleted > 0
}
}
impl<P> DeleteResponse<usize, P> {
/// The number of keys that were deleted.
pub fn deleted(&self) -> usize {
self.deleted
}
}
impl DeleteResponse<bool, GetPreviousValue> {
/// The previous value of the key, or `None` if it did not exist.
pub fn previous(&self) -> Option<&Record> {
self.previous.first()
}
/// Consume the response and return the previous value.
pub fn into_previous(self) -> Option<Record> {
self.previous.into_iter().next()
}
}
impl DeleteResponse<usize, GetPreviousValue> {
/// The previous values of the deleted keys.
pub fn previous(&self) -> &[Record] {
&self.previous
}
/// Consume the response and return the previous values.
pub fn into_previous(self) -> Vec<Record> {
self.previous
}
}
/// The [`Future`] type returned by awaiting [`delete`][Client::delete] and
/// [`delete_range`][Client::delete_range] operations.
pub struct DeleteFuture<T>(Pin<Box<dyn Future<Output = T> + Send>>);
impl<T> DeleteFuture<T> {
pub(crate) fn new(future: impl Future<Output = T> + Send + 'static) -> Self {
Self(Box::pin(future))
}
}
impl<T> Future for DeleteFuture<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.get_mut().0.as_mut().poll(cx)
}
}
impl<C, R, P> IntoFuture for Delete<C, R, P>
where
C: crate::driver::KvDriver,
{
type Output = Result<DeleteResponse<R, P>, DeleteError>;
type IntoFuture = C::DeleteFuture<R, P>;
fn into_future(self) -> Self::IntoFuture {
let (client, detached) = self.into_parts();
client.execute_delete(detached)
}
}
/// An enumeration of the [`kind`][DeleteError::kind]s of errors that can occur from a
/// [`delete`][Client::delete] or [`delete_range`][Client::delete_range] operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DeleteErrorKind {
/// There is an authentication or authorization error.
///
/// This comes from the gRPC API as `UNAUTHENTICATED` or `PERMISSION_DENIED`, or as `INVALID_ARGUMENT` with
/// "etcdserver: user name is empty" or "etcdserver: revision of auth store is old". Other `INVALID_ARGUMENT`
/// responses describe the request rather than the caller, and are reported as [`Unknown`][Self::Unknown].
Authentication,
/// The server or transport is resource-exhausted.
///
/// This comes from the gRPC API as `RESOURCE_EXHAUSTED`.
Exhausted,
/// The server is not ready to serve that request.
///
/// This comes from the gRPC API as `UNAVAILABLE`.
Unavailable,
/// The request timed out.
///
/// This comes from the gRPC API as `CANCELLED` or `DEADLINE_EXCEEDED`. We do not distinguish between the two, as
/// the source of the timeout is usually not important.
Timeout,
/// An error that is not covered by any other error kind.
///
/// All uncovered gRPC errors are mapped to this kind of error. Among them are `INVALID_ARGUMENT` responses that
/// describe the request, such as "etcdserver: key is not provided" for the empty key. Their message is available
/// from [`grpc_status`][DeleteError::grpc_status]. Other uncovered errors should not happen unless the etcd server
/// has changed its error codes.
Unknown,
}
define_op_error! {
/// An error from a [`delete`][Client::delete] or [`delete_range`][Client::delete_range] operation.
pub struct DeleteError(DeleteErrorKind);
}
impl DeleteError {
pub(crate) fn from_status(status: tonic::Status) -> Self {
let kind = match status.code() {
tonic::Code::Unauthenticated => DeleteErrorKind::Authentication,
tonic::Code::PermissionDenied => DeleteErrorKind::Authentication,
tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => {
DeleteErrorKind::Authentication
}
tonic::Code::ResourceExhausted => DeleteErrorKind::Exhausted,
tonic::Code::Unavailable => DeleteErrorKind::Unavailable,
// Don't care who timed us out
tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => DeleteErrorKind::Timeout,
_ => DeleteErrorKind::Unknown,
};
Self::new(kind, "", Some(status))
}
}
const _: () = {
fn _assert_send<T: Send>() {}
fn _check() {
_assert_send::<DeleteFuture<Result<DeleteResponse<bool>, DeleteError>>>();
_assert_send::<DeleteFuture<Result<DeleteResponse<bool, GetPreviousValue>, DeleteError>>>();
_assert_send::<DeleteFuture<Result<DeleteResponse<usize>, DeleteError>>>();
_assert_send::<DeleteFuture<Result<DeleteResponse<usize, GetPreviousValue>, DeleteError>>>();
}
};
#[cfg(test)]
mod test {
use super::*;
/// `delete("")` gets "key is not provided", which is about the request.
#[test]
fn invalid_argument_is_authentication_only_for_token_messages() {
use DeleteErrorKind::*;
for (message, expected) in [
("etcdserver: user name is empty", Authentication),
("etcdserver: revision of auth store is old", Authentication),
("etcdserver: key is not provided", Unknown),
("etcdserver: request is too large", Unknown),
] {
let kind = DeleteError::from_status(tonic::Status::invalid_argument(message)).kind();
assert_eq!(kind, expected, "{message:?}");
}
}
}