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
use std::{
future::{Future, IntoFuture},
pin::Pin,
task::{Context, Poll},
};
use crate::{Client, ResponseHeader, Revision, client::ClientInner, pb::etcdserverpb};
/// # Compaction
impl Client {
/// Compact the key-value store's revision history up to `revision`.
///
/// Compaction discards superseded key revisions older than `revision`, freeing space in the
/// store. Reading history (for example, watching with a `start_revision`) from before the
/// compacted revision will fail afterwards. Use [`physical`][Compact::physical] to wait until
/// the compaction is physically applied to the backend database.
///
/// ```no_run
/// # async {
/// let client: etcdrs::Client = todo!();
/// let revision = client.put("foo").value("bar").await.unwrap().header().revision();
/// client.compact(revision).physical().await.unwrap();
/// # };
/// ```
pub fn compact(&self, revision: Revision) -> Compact<Self> {
Compact::new(revision).with_client(self.clone())
}
}
/// A [`Client::compact`] operation.
#[derive(Clone, Debug)]
#[must_use = "Compact does nothing unless you `await` it"]
pub struct Compact<C> {
client: C,
pub(crate) request: etcdserverpb::CompactionRequest,
}
impl Compact<()> {
pub fn new(revision: Revision) -> Self {
Self {
client: (),
request: etcdserverpb::CompactionRequest {
revision: revision.get(),
..Default::default()
},
}
}
}
impl<C> Compact<C> {
/// Attach a `client` to this operation.
///
/// You typically do not have to call this function, as it is called automatically by
/// [`compact`][`Client::compact`].
pub fn with_client<C2>(self, client: C2) -> Compact<C2> {
Compact {
client,
request: self.request,
}
}
/// Wait for the compaction to be physically applied to the database.
///
/// By default, the server responds as soon as the compaction is logically applied. With this
/// set, the response is not sent until the compacted entries are actually removed from the
/// backend database and the space is reclaimable.
pub fn physical(mut self) -> Self {
self.request.physical = true;
self
}
/// The revision this operation will compact up to.
pub fn revision(&self) -> Revision {
Revision::new(self.request.revision).expect("compaction revision should be non-zero")
}
/// Whether this operation waits for the compaction to be physically applied.
pub fn is_physical(&self) -> bool {
self.request.physical
}
/// Decompose this operation into its client and a detached `Compact<()>`.
pub(crate) fn into_parts(self) -> (C, Compact<()>) {
(
self.client,
Compact {
client: (),
request: self.request,
},
)
}
}
/// The response from a [`compact`][Client::compact] operation.
#[derive(Clone, Copy, Debug)]
pub struct CompactResponse {
header: ResponseHeader,
}
impl CompactResponse {
/// Construct a new `CompactResponse`.
pub fn new(header: ResponseHeader) -> Self {
Self { header }
}
/// The response header containing cluster metadata and the store revision.
pub fn header(&self) -> &ResponseHeader {
&self.header
}
}
/// The [`Future`] type returned by awaiting a [`compact`][`Client::compact`].
pub struct CompactFuture(Pin<Box<dyn Future<Output = Result<CompactResponse, CompactError>> + Send>>);
impl CompactFuture {
pub(crate) fn new(future: impl Future<Output = Result<CompactResponse, CompactError>> + Send + 'static) -> Self {
Self(Box::pin(future))
}
}
impl Future for CompactFuture {
type Output = Result<CompactResponse, CompactError>;
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 Compact<C> {
type Output = Result<CompactResponse, CompactError>;
type IntoFuture = C::CompactFuture;
fn into_future(self) -> C::CompactFuture {
let (client, detached) = self.into_parts();
client.execute_compact(detached)
}
}
/// An enumeration of the [`kind`][CompactError::kind]s of errors that can occur from a
/// [`compact`][Client::compact] operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CompactErrorKind {
/// The requested revision has already been compacted.
///
/// This comes from the gRPC API as `OUT_OF_RANGE`. Because the client retries requests when
/// the connection drops, a compaction that succeeded on the server but whose response was lost
/// can also surface as this error on retry.
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 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. They should not happen unless the etcd server has
/// changed its error codes.
Unknown,
}
define_op_error! {
/// An error from a [`compact`][Client::compact] operation.
pub struct CompactError(CompactErrorKind);
}
impl CompactError {
pub(crate) fn from_status(status: tonic::Status) -> Self {
let kind = match status.code() {
tonic::Code::Unauthenticated => CompactErrorKind::Authentication,
tonic::Code::PermissionDenied => CompactErrorKind::Authentication,
tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => {
CompactErrorKind::Authentication
}
tonic::Code::ResourceExhausted => CompactErrorKind::Exhausted,
tonic::Code::OutOfRange => {
if status.message().contains("compacted") {
CompactErrorKind::CompactedRevision
} else if status.message().contains("future") {
CompactErrorKind::FutureRevision
} else {
CompactErrorKind::Unknown
}
}
tonic::Code::DataLoss => CompactErrorKind::DataLoss,
tonic::Code::Unavailable => CompactErrorKind::Unavailable,
// Don't care who timed us out
tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => CompactErrorKind::Timeout,
_ => CompactErrorKind::Unknown,
};
Self::new(kind, "", Some(status))
}
}
const _: () = {
fn _assert_send<T: Send>() {}
fn _check() {
_assert_send::<CompactFuture>();
}
};
#[cfg(test)]
mod test {
use super::*;
#[test]
fn invalid_argument_is_authentication_only_for_token_messages() {
use CompactErrorKind::*;
for (message, expected) in [
("etcdserver: user name is empty", Authentication),
("etcdserver: revision of auth store is old", Authentication),
("etcdserver: request is too large", Unknown),
("etcdserver: invalid client api version", Unknown),
] {
let kind = CompactError::from_status(tonic::Status::invalid_argument(message)).kind();
assert_eq!(kind, expected, "{message:?}");
}
}
}