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
use std::{
future::{Future, IntoFuture},
pin::Pin,
task::{Context, Poll},
};
use bytes::Bytes;
use crate::{
Client, ResponseHeader, Revision,
client::ClientInner,
pb::etcdserverpb,
record::{AsKey, Record},
};
/// # Reading Keys
impl Client {
/// Get the contents of `key` from the database.
///
/// ```no_run
/// # async {
/// let client: etcdrs::Client = todo!();
/// let response = client.get("path/to/foo").await.unwrap();
/// if let Some(entry) = response.record() {
/// println!("found: {entry:?}");
/// } else {
/// println!("not found");
/// }
/// # };
/// ```
pub fn get(&self, key: impl AsKey) -> Get<Self> {
Get::new(key).with_client(self.clone())
}
}
/// A [`Client::get`] operation.
#[derive(Clone, Debug)]
pub struct Get<C> {
pub(crate) client: C,
pub(crate) request: etcdserverpb::RangeRequest,
}
impl Get<()> {
pub fn new(key: impl AsKey) -> Self {
Self {
client: (),
request: etcdserverpb::RangeRequest {
key: Bytes::copy_from_slice(key.as_key()),
..Default::default()
},
}
}
}
impl<C> Get<C> {
/// Attach a `client` to this operation.
///
/// You typically do not have to call this function, as it is called automatically by [`get`][`Client::get`].
pub fn with_client<C2>(self, client: C2) -> Get<C2> {
Get {
client,
request: self.request,
}
}
/// Read the key as of a historical store `revision` instead of the current one.
///
/// The revision is the global store revision from a [`ResponseHeader`] (or a record's
/// [`modified_revision`][crate::Metadata::modified_revision]), not the key's version. Reading
/// a revision that has been [compacted][Client::compact] fails with
/// [`CompactedRevision`][GetErrorKind::CompactedRevision]; reading a revision the server has
/// not reached yet fails with [`FutureRevision`][GetErrorKind::FutureRevision].
///
/// ```no_run
/// # async {
/// let client: etcdrs::Client = todo!();
/// let revision = client.put("foo").value("old").await.unwrap().header().revision();
/// client.put("foo").value("new").await.unwrap();
///
/// let old = client.get("foo").at_revision(revision).await.unwrap();
/// assert_eq!(old.record().unwrap().value(), &b"old"[..]);
/// # };
/// ```
pub fn at_revision(mut self, revision: Revision) -> Self {
self.request.revision = revision.get();
self
}
/// The key this operation addresses.
pub fn target_key(&self) -> &[u8] {
&self.request.key
}
/// The revision this operation reads from, or `None` for the server's current revision.
pub fn revision(&self) -> Option<Revision> {
Revision::new(self.request.revision)
}
/// Decompose this operation into its client and a detached `Get<()>`.
pub(crate) fn into_parts(self) -> (C, Get<()>) {
(
self.client,
Get {
client: (),
request: self.request,
},
)
}
}
/// The response from a [`get`][Client::get] operation.
#[derive(Clone, Debug)]
pub struct GetResponse {
header: ResponseHeader,
record: Option<Record>,
}
impl GetResponse {
/// Construct a new `GetResponse`.
pub fn new(header: ResponseHeader, record: Option<Record>) -> Self {
Self { header, record }
}
/// The response header containing cluster metadata and the store revision.
pub fn header(&self) -> &ResponseHeader {
&self.header
}
/// The record associated with the key, or `None` if the key does not exist.
pub fn record(&self) -> Option<&Record> {
self.record.as_ref()
}
/// Consume the response and return the record, or `None` if the key does not exist.
pub fn into_record(self) -> Option<Record> {
self.record
}
}
/// The [`Future`] type returned by awaiting a [`get`][`Client::get`].
pub struct GetFuture(Pin<Box<dyn Future<Output = Result<GetResponse, GetError>> + Send>>);
impl GetFuture {
pub(crate) fn new(future: impl Future<Output = Result<GetResponse, GetError>> + Send + 'static) -> Self {
Self(Box::pin(future))
}
}
impl Future for GetFuture {
type Output = Result<GetResponse, GetError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.get_mut().0.as_mut().poll(cx)
}
}
impl<C: crate::driver::KvDriver> IntoFuture for Get<C> {
type Output = Result<GetResponse, GetError>;
type IntoFuture = C::GetFuture;
fn into_future(self) -> C::GetFuture {
let (client, detached) = self.into_parts();
client.execute_get(detached)
}
}
/// A enumeration of the [`kind`][GetError::kind]s of errors that can occur from a [`get`][Client::get] or
/// [`list`][Client::list] operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GetErrorKind {
/// The requested revision is older than the server has.
///
/// This comes from the gRPC API as `OUT_OF_RANGE`.
CompactedRevision,
/// The requested revision is newer than the server has.
///
/// This comes from the gRPC API as `OUT_OF_RANGE`.
FutureRevision,
/// 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,
/// The server has lost data.
///
/// This comes from the gRPC API as `DATA_LOSS`.
DataLoss,
/// 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`][GetError::grpc_status]. Other uncovered errors should not happen unless the etcd server has
/// changed its error codes. These can also be emitted from the client if the server does something unexpected
/// (for example, returning more than one record for a single-key get).
Unknown,
}
define_op_error! {
/// An error from a [`get`][Client::get] or [`list`][Client::list] operation.
pub struct GetError(GetErrorKind);
}
impl GetError {
pub(crate) fn from_status(status: tonic::Status) -> Self {
let kind = match status.code() {
tonic::Code::Unauthenticated => GetErrorKind::Authentication,
tonic::Code::PermissionDenied => GetErrorKind::Authentication,
tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => GetErrorKind::Authentication,
tonic::Code::ResourceExhausted => GetErrorKind::Exhausted,
tonic::Code::OutOfRange => {
if status.message().contains("compacted") {
GetErrorKind::CompactedRevision
} else if status.message().contains("future") {
GetErrorKind::FutureRevision
} else {
GetErrorKind::Unknown
}
}
tonic::Code::Unavailable => GetErrorKind::Unavailable,
// Don't care who timed us out
tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => GetErrorKind::Timeout,
_ => GetErrorKind::Unknown,
};
Self::new(kind, "", Some(status))
}
}
const _: () = {
fn _assert_send<T: Send>() {}
fn _check() {
_assert_send::<GetFuture>();
}
};
#[cfg(test)]
mod test {
use super::*;
/// `get("")` gets "key is not provided", which is about the request.
#[test]
fn invalid_argument_is_authentication_only_for_token_messages() {
use GetErrorKind::*;
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: invalid sort option", Unknown),
] {
let kind = GetError::from_status(tonic::Status::invalid_argument(message)).kind();
assert_eq!(kind, expected, "{message:?}");
}
}
}