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
use std::{
future::{Future, IntoFuture},
marker::PhantomData,
pin::Pin,
task::{Context, Poll},
};
use bytes::Bytes;
use crate::{
Client, LeaseId, ResponseHeader,
client::ClientInner,
pb::etcdserverpb,
record::{AsKey, AsValue, Record},
};
/// # Writing Keys
impl Client {
/// Put a new value for the `key`.
///
/// ```no_run
/// # async {
/// let client: etcdrs::Client = todo!();
/// client
/// .put("foo")
/// .value("bar")
/// .await
/// .unwrap();
/// # };
/// ```
pub fn put(&self, key: impl AsKey) -> Put<Self, ()> {
Put::new(key).with_client(self.clone())
}
}
/// A [`Client::put`] operation.
#[derive(Clone, Debug)]
pub struct Put<C, R> {
client: C,
pub(crate) request: etcdserverpb::PutRequest,
_return: PhantomData<fn() -> R>,
}
impl Put<(), ()> {
pub fn new(key: impl AsKey) -> Self {
Self {
client: (),
request: etcdserverpb::PutRequest {
key: Bytes::copy_from_slice(key.as_key()),
..Default::default()
},
_return: PhantomData,
}
}
}
impl<C, R> Put<C, R> {
/// Attach a `client` to this operation.
///
/// You typically do not have to call this function, as it is called automatically by [`put`][`Client::put`] or when
/// given to a transaction.
pub fn with_client<C2>(self, client: C2) -> Put<C2, R> {
Put {
client,
request: self.request,
_return: PhantomData,
}
}
/// The key this operation addresses.
pub fn target_key(&self) -> &[u8] {
&self.request.key
}
/// The value this operation will write.
pub fn value_bytes(&self) -> &[u8] {
&self.request.value
}
/// Whether this operation leaves the existing value unchanged.
pub fn ignores_value(&self) -> bool {
self.request.ignore_value
}
/// The lease this operation will attach to the key, if one was specified.
pub fn lease_id(&self) -> Option<LeaseId> {
LeaseId::new(self.request.lease)
}
/// Whether this operation leaves the existing lease unchanged.
pub fn ignores_lease(&self) -> bool {
self.request.ignore_lease
}
/// Whether the previous key-value will be returned.
pub fn returns_previous(&self) -> bool {
self.request.prev_kv
}
/// Decompose this operation into its client and a detached `Put<(), R>`.
pub(crate) fn into_parts(self) -> (C, Put<(), R>) {
(
self.client,
Put {
client: (),
request: self.request,
_return: PhantomData,
},
)
}
/// Return the previous key-value.
pub fn get_previous(self) -> Put<C, GetPreviousValue> {
let mut request = self.request;
request.prev_kv = true;
Put {
client: self.client,
request,
_return: Default::default(),
}
}
/// Set the record to `value`.
pub fn value(mut self, value: impl AsValue) -> Self {
self.request.value = Bytes::copy_from_slice(value.as_value());
self.request.ignore_value = false;
self
}
/// Update the key, leaving the current value in-place.
pub fn ignore_value(mut self) -> Self {
self.request.value.clear();
self.request.ignore_value = true;
self
}
pub fn lease(mut self, lease: LeaseId) -> Self {
self.request.lease = lease.get();
self.request.ignore_lease = false;
self
}
/// Update the key using its current lease. If the key does not exist, `NotFound` will be returned.
pub fn ignore_lease(mut self) -> Self {
self.request.lease = 0;
self.request.ignore_lease = true;
self
}
}
/// The response from a [`put`][Client::put] operation.
#[derive(Clone, Debug)]
pub struct PutResponse<R = ()> {
header: ResponseHeader,
previous: Option<Record>,
_marker: PhantomData<fn() -> R>,
}
impl<R> PutResponse<R> {
/// Construct a new `PutResponse`.
pub fn new(header: ResponseHeader, previous: Option<Record>) -> Self {
Self {
header,
previous,
_marker: PhantomData,
}
}
/// The response header containing cluster metadata and the store revision.
pub fn header(&self) -> &ResponseHeader {
&self.header
}
}
impl PutResponse<GetPreviousValue> {
/// The previous value of the key, or `None` if the key did not exist before the put.
pub fn previous(&self) -> Option<&Record> {
self.previous.as_ref()
}
/// Consume the response and return the previous value.
pub fn into_previous(self) -> Option<Record> {
self.previous
}
}
/// The [`Future`] type returned by awaiting [`put`][Client::put] operations.
pub struct PutFuture<T>(Pin<Box<dyn Future<Output = T> + Send>>);
impl<T> PutFuture<T> {
pub(crate) fn new(future: impl Future<Output = T> + Send + 'static) -> Self {
Self(Box::pin(future))
}
}
impl<T> Future for PutFuture<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> IntoFuture for Put<C, R>
where
C: crate::driver::KvDriver,
{
type Output = Result<PutResponse<R>, PutError>;
type IntoFuture = C::PutFuture<R>;
fn into_future(self) -> Self::IntoFuture {
let (client, detached) = self.into_parts();
client.execute_put(detached)
}
}
/// Used in [`Put`]s to denote that the previous value should be returned.
pub struct GetPreviousValue;
/// An enumeration of the [`kind`][PutError::kind]s of errors that can occur from a [`put`][Client::put] operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PutErrorKind {
/// The specified lease does not exist.
///
/// This comes from the gRPC API as `NOT_FOUND`.
LeaseNotFound,
/// The key does not exist, but the operation requires it.
///
/// This happens when using [`ignore_value`][Put::ignore_value] or [`ignore_lease`][Put::ignore_lease] on a key that
/// does not exist in the store. This comes from the gRPC API as `INVALID_ARGUMENT` with "key not found".
KeyNotFound,
/// 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 [`KeyNotFound`][Self::KeyNotFound]
/// or [`Unknown`][Self::Unknown].
Authentication,
/// The server or transport is resource-exhausted.
///
/// This comes from the gRPC API as `RESOURCE_EXHAUSTED`.
Exhausted,
/// The server has lost data.
///
/// This comes from the gRPC API as `DATA_LOSS`.
DataLoss,
/// 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, or "etcdserver: request is
/// too large" for a request over the server's `--max-request-bytes`. Their message is available from
/// [`grpc_status`][PutError::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 [`put`][Client::put] operation.
pub struct PutError(PutErrorKind);
}
impl PutError {
pub(crate) fn from_status(status: tonic::Status) -> Self {
let kind = match status.code() {
tonic::Code::NotFound => PutErrorKind::LeaseNotFound,
tonic::Code::Unauthenticated => PutErrorKind::Authentication,
tonic::Code::PermissionDenied => PutErrorKind::Authentication,
tonic::Code::InvalidArgument => {
if status.message().contains("key not found") {
PutErrorKind::KeyNotFound
} else if ClientInner::is_stale_token_error(&status) {
PutErrorKind::Authentication
} else {
PutErrorKind::Unknown
}
}
tonic::Code::ResourceExhausted => PutErrorKind::Exhausted,
tonic::Code::DataLoss => PutErrorKind::DataLoss,
tonic::Code::Unavailable => PutErrorKind::Unavailable,
// Don't care who timed us out
tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => PutErrorKind::Timeout,
_ => PutErrorKind::Unknown,
};
Self::new(kind, "", Some(status))
}
}
const _: () = {
fn _assert_send<T: Send>() {}
fn _check() {
_assert_send::<PutFuture<Result<PutResponse, PutError>>>();
_assert_send::<PutFuture<Result<PutResponse<GetPreviousValue>, PutError>>>();
}
};
#[cfg(test)]
mod test {
use super::*;
/// `put("")` gets "key is not provided", and a put over `--max-request-bytes` gets "request is too large". Both
/// are about the request.
#[test]
fn invalid_argument_is_authentication_only_for_token_messages() {
use PutErrorKind::*;
for (message, expected) in [
("etcdserver: user name is empty", Authentication),
("etcdserver: revision of auth store is old", Authentication),
("etcdserver: key not found", KeyNotFound),
("etcdserver: key is not provided", Unknown),
("etcdserver: request is too large", Unknown),
] {
let kind = PutError::from_status(tonic::Status::invalid_argument(message)).kind();
assert_eq!(kind, expected, "{message:?}");
}
}
}