etcdv3client 0.4.0

a simple etcdv3 client
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
use crate::error::{ErrKind, Error, Result};
use crate::grpc::GrpcService;
use crate::pb;
use crate::utils::build_prefix_end;
use tonic::IntoRequest;

#[derive(Debug, Clone)]
pub struct InnerKvClient<S> {
    service: S,
}
impl<S> InnerKvClient<S>
where
    S: GrpcService,
{
    pub fn new(service: S) -> Self {
        Self { service }
    }
    pub async fn range(
        &mut self,
        request: impl tonic::IntoRequest<pb::RangeRequest>,
    ) -> Result<tonic::Response<pb::RangeResponse>> {
        let path = http::uri::PathAndQuery::from_static("/etcdserverpb.KV/Range");
        self.service.unary(request.into_request(), path).await
    }
    pub async fn put(
        &mut self,
        request: impl tonic::IntoRequest<pb::PutRequest>,
    ) -> Result<tonic::Response<pb::PutResponse>> {
        let path = http::uri::PathAndQuery::from_static("/etcdserverpb.KV/Put");
        self.service.unary(request.into_request(), path).await
    }
    pub async fn delete_range(
        &mut self,
        request: impl tonic::IntoRequest<pb::DeleteRangeRequest>,
    ) -> Result<tonic::Response<pb::DeleteRangeResponse>> {
        let path = http::uri::PathAndQuery::from_static("/etcdserverpb.KV/DeleteRange");
        self.service.unary(request.into_request(), path).await
    }
    pub async fn txn(
        &mut self,
        request: impl tonic::IntoRequest<pb::TxnRequest>,
    ) -> Result<tonic::Response<pb::TxnResponse>> {
        let path = http::uri::PathAndQuery::from_static("/etcdserverpb.KV/Txn");
        self.service.unary(request.into_request(), path).await
    }
    pub async fn compact(
        &mut self,
        request: impl tonic::IntoRequest<pb::CompactionRequest>,
    ) -> Result<tonic::Response<pb::CompactionResponse>> {
        let path = http::uri::PathAndQuery::from_static("/etcdserverpb.KV/Compact");
        self.service.unary(request.into_request(), path).await
    }
}
#[derive(Debug, Clone)]
pub struct KvClient<S> {
    inner: InnerKvClient<S>,
}
impl<S> KvClient<S>
where
    S: GrpcService,
{
    pub async fn range(&mut self, request: pb::RangeRequest) -> Result<pb::RangeResponse> {
        self.inner
            .range(request.into_request())
            .await
            .map(|rsp| rsp.into_inner())
    }
    pub async fn put(&mut self, request: pb::PutRequest) -> Result<pb::PutResponse> {
        self.inner
            .put(request.into_request())
            .await
            .map(|rsp| rsp.into_inner())
    }
    pub async fn delete_range(
        &mut self,
        request: pb::DeleteRangeRequest,
    ) -> Result<pb::DeleteRangeResponse> {
        self.inner
            .delete_range(request.into_request())
            .await
            .map(|rsp| rsp.into_inner())
    }
    pub async fn txn(&mut self, request: pb::TxnRequest) -> Result<pb::TxnResponse> {
        self.inner
            .txn(request.into_request())
            .await
            .map(|rsp| rsp.into_inner())
    }
    pub async fn compact(
        &mut self,
        request: pb::CompactionRequest,
    ) -> Result<pb::CompactionResponse> {
        self.inner
            .compact(request.into_request())
            .await
            .map(|rsp| rsp.into_inner())
    }
}

impl<S> KvClient<S>
where
    S: GrpcService,
{
    pub fn new(service: S) -> Self {
        KvClient {
            inner: InnerKvClient::new(service),
        }
    }

    /// Do range request
    ///
    /// ```no_run
    /// # use etcdv3client::{EtcdClient, Error, KvClient};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// # let client = EtcdClient::new(vec!["localhost:2379"], None).await?;
    /// let resp = KvClient::new(client.service()).do_range("hello").with_prefix().await.unwrap();
    /// # Ok(())
    /// # }
    /// ```
    pub fn do_range(&mut self, key: impl Into<Vec<u8>>) -> DoRangeRequest<S> {
        pb::RangeRequest::new(key).build(self)
    }

    /// Get value by key
    #[inline]
    pub async fn get(&mut self, key: impl Into<Vec<u8>>) -> Result<Vec<u8>> {
        let resp = self.do_range(key).with_limit(1).await?;
        let kv = resp
            .kvs
            .into_iter()
            .next()
            .ok_or_else(|| Error::from_kind(ErrKind::KeyNotFound))?;
        Ok(kv.value.clone())
    }

    /// Get string by key
    ///
    /// ```no_run
    /// # use etcdv3client::{EtcdClient, Error, KvClient};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// # let client = EtcdClient::new(vec!["localhost:2379"], None).await?;
    /// let resp = KvClient::new(client.service()).get("hello").await.unwrap();
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub async fn get_string(&mut self, key: impl Into<Vec<u8>>) -> Result<String> {
        let value = self.get(key).await?;

        String::from_utf8(value).map_err(|err| Error::new(ErrKind::InvalidData, err))
    }

    /// Get key-value pairs with prefix
    #[inline]
    pub async fn get_with_prefix(&mut self, key: impl Into<Vec<u8>>) -> Result<Vec<pb::KeyValue>> {
        let resp = self.do_range(key).with_prefix().await?;

        Ok(resp.kvs)
    }

    /// Get all key-value pairs
    #[inline]
    pub async fn all(&mut self) -> Result<Vec<pb::KeyValue>> {
        let resp = self.do_range([0x00]).with_range_end(vec![0x00]).await?;

        Ok(resp.kvs)
    }

    /// Do put request
    ///
    /// ```no_run
    /// # use etcdv3client::{EtcdClient, Error, KvClient, pb};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// # let client = EtcdClient::new(vec!["localhost:2379"], None).await?;
    /// let resp = KvClient::new(client.service()).do_put("hello", "world").with_prev_kv(true).await.unwrap();
    /// # Ok(())
    /// # }
    pub fn do_put(
        &mut self,
        key: impl Into<Vec<u8>>,
        value: impl Into<Vec<u8>>,
    ) -> DoPutRequest<S> {
        pb::PutRequest::new(key, value).build(self)
    }

    /// Put a key-value paire
    pub async fn put_kv(
        &mut self,
        key: impl Into<Vec<u8>>,
        value: impl Into<Vec<u8>>,
    ) -> Result<()> {
        self.do_put(key, value).await.map(|_| ())
    }

    /// Do delete range request
    ///
    /// ```no_run
    /// # use etcdv3client::{EtcdClient, Error, KvClient, pb};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// # let client = EtcdClient::new(vec!["localhost:2379"], None).await?;
    /// let resp = KvClient::new(client.service()).do_delete_range("hello").with_prefix().await.unwrap();
    /// # Ok(())
    /// # }
    pub fn do_delete_range(&mut self, key: impl Into<Vec<u8>>) -> DoDeleteRangeRequest<S> {
        pb::DeleteRangeRequest::new(key).build(self)
    }

    /// Delete a key-value paire
    pub async fn delete(&mut self, key: impl Into<Vec<u8>>) -> Result<()> {
        self.do_delete_range(key).await.map(|_| ())
    }

    pub fn do_txn(&mut self) -> DoTxnRequest<S> {
        pb::TxnRequest::default().build(self)
    }

    pub fn do_compaction(&mut self, revision: i64, physical: bool) -> DoCompactionRequest<S> {
        pb::CompactionRequest::new(revision, physical).build(self)
    }

    /// Compact compacts the event history in the etcd key-value store.
    pub async fn compact_history(&mut self, revision: i64, physical: bool) -> Result<()> {
        let _resp = self.do_compaction(revision, physical).await?;
        Ok(())
    }
}

impl pb::RangeRequest {
    pub fn new(key: impl Into<Vec<u8>>) -> Self {
        pb::RangeRequest {
            key: key.into(),
            ..Default::default()
        }
    }

    /// Set key prefix.
    pub fn with_prefix(mut self) -> Self {
        self.range_end = build_prefix_end(&self.key);
        self
    }

    pub fn build<S: GrpcService>(self, client: &mut KvClient<S>) -> DoRangeRequest<'_, S> {
        DoRangeRequest {
            request: self,
            client,
        }
    }
}
#[must_use]
pub struct DoRangeRequest<'a, S> {
    pub request: pb::RangeRequest,
    pub(crate) client: &'a mut KvClient<S>,
}
impl<'a, S> DoRangeRequest<'a, S>
where
    S: GrpcService,
{
    pub fn with_client(mut self, client: &'a mut KvClient<S>) -> Self {
        self.client = client;
        self
    }

    /// Set key prefix.
    pub fn with_prefix(mut self) -> Self {
        self.request = self.request.with_prefix();
        self
    }

    pub fn with_key(mut self, key: Vec<u8>) -> Self {
        self.request.key = key;
        self
    }
    pub fn with_range_end(mut self, range_end: Vec<u8>) -> Self {
        self.request.range_end = range_end;
        self
    }
    pub fn with_limit(mut self, limit: i64) -> Self {
        self.request.limit = limit;
        self
    }
    pub fn with_revision(mut self, revision: i64) -> Self {
        self.request.revision = revision;
        self
    }
    pub fn with_sort_order(mut self, sort_order: i32) -> Self {
        self.request.sort_order = sort_order;
        self
    }
    pub fn with_sort_target(mut self, sort_target: i32) -> Self {
        self.request.sort_target = sort_target;
        self
    }
    pub fn with_serializable(mut self, serializable: bool) -> Self {
        self.request.serializable = serializable;
        self
    }
    pub fn with_keys_only(mut self, keys_only: bool) -> Self {
        self.request.keys_only = keys_only;
        self
    }
    pub fn with_count_only(mut self, count_only: bool) -> Self {
        self.request.count_only = count_only;
        self
    }
    pub fn with_min_mod_revision(mut self, min_mod_revision: i64) -> Self {
        self.request.min_mod_revision = min_mod_revision;
        self
    }
    pub fn with_max_mod_revision(mut self, max_mod_revision: i64) -> Self {
        self.request.max_mod_revision = max_mod_revision;
        self
    }
    pub fn with_min_create_revision(mut self, min_create_revision: i64) -> Self {
        self.request.min_create_revision = min_create_revision;
        self
    }
    pub fn with_max_create_revision(mut self, max_create_revision: i64) -> Self {
        self.request.max_create_revision = max_create_revision;
        self
    }
}
impl<'a, S> std::future::IntoFuture for DoRangeRequest<'a, S>
where
    S: GrpcService,
{
    type Output = Result<pb::RangeResponse>;
    type IntoFuture = std::pin::Pin<
        Box<dyn std::future::Future<Output = crate::error::Result<pb::RangeResponse>> + 'a>,
    >;
    fn into_future(self) -> Self::IntoFuture {
        let DoRangeRequest { request, client } = self;
        Box::pin(async move { client.range(request).await })
    }
}
impl pb::PutRequest {
    pub fn new(key: impl Into<Vec<u8>>, value: impl Into<Vec<u8>>) -> Self {
        pb::PutRequest {
            key: key.into(),
            value: value.into(),
            ..Default::default()
        }
    }

    pub fn build<S: GrpcService>(self, client: &mut KvClient<S>) -> DoPutRequest<'_, S> {
        DoPutRequest {
            request: self,
            client,
        }
    }
}
#[must_use]
pub struct DoPutRequest<'a, S> {
    pub request: pb::PutRequest,
    pub(crate) client: &'a mut KvClient<S>,
}
impl<'a, S> DoPutRequest<'a, S>
where
    S: GrpcService,
{
    pub fn with_client(mut self, client: &'a mut KvClient<S>) -> Self {
        self.client = client;
        self
    }
    pub fn with_key(mut self, key: Vec<u8>) -> Self {
        self.request.key = key;
        self
    }
    pub fn with_value(mut self, value: Vec<u8>) -> Self {
        self.request.value = value;
        self
    }
    pub fn with_lease(mut self, lease: i64) -> Self {
        self.request.lease = lease;
        self
    }
    pub fn with_prev_kv(mut self, prev_kv: bool) -> Self {
        self.request.prev_kv = prev_kv;
        self
    }
    pub fn with_ignore_value(mut self, ignore_value: bool) -> Self {
        self.request.ignore_value = ignore_value;
        self
    }
    pub fn with_ignore_lease(mut self, ignore_lease: bool) -> Self {
        self.request.ignore_lease = ignore_lease;
        self
    }
}
impl<'a, S> std::future::IntoFuture for DoPutRequest<'a, S>
where
    S: GrpcService,
{
    type Output = Result<pb::PutResponse>;
    type IntoFuture = std::pin::Pin<
        Box<dyn std::future::Future<Output = crate::error::Result<pb::PutResponse>> + 'a>,
    >;
    fn into_future(self) -> Self::IntoFuture {
        let DoPutRequest { request, client } = self;
        Box::pin(async move { client.put(request).await })
    }
}

impl pb::DeleteRangeRequest {
    pub fn new(key: impl Into<Vec<u8>>) -> Self {
        pb::DeleteRangeRequest {
            key: key.into(),
            ..Default::default()
        }
    }

    pub fn build<S: GrpcService>(self, client: &mut KvClient<S>) -> DoDeleteRangeRequest<'_, S> {
        DoDeleteRangeRequest {
            request: self,
            client,
        }
    }
}
#[must_use]
pub struct DoDeleteRangeRequest<'a, S> {
    pub request: pb::DeleteRangeRequest,
    pub(crate) client: &'a mut KvClient<S>,
}
impl<'a, S> DoDeleteRangeRequest<'a, S>
where
    S: GrpcService,
{
    pub fn with_client(mut self, client: &'a mut KvClient<S>) -> Self {
        self.client = client;
        self
    }

    pub fn with_key(mut self, key: Vec<u8>) -> Self {
        self.request.key = key;
        self
    }

    /// Delete key-value pairs with key prefix.
    pub fn with_prefix(mut self) -> Self {
        self.request.range_end = build_prefix_end(&self.request.key);
        self
    }

    pub fn with_range_end(mut self, range_end: Vec<u8>) -> Self {
        self.request.range_end = range_end;
        self
    }
    pub fn with_prev_kv(mut self, prev_kv: bool) -> Self {
        self.request.prev_kv = prev_kv;
        self
    }
}
impl<'a, S> std::future::IntoFuture for DoDeleteRangeRequest<'a, S>
where
    S: GrpcService,
{
    type Output = Result<pb::DeleteRangeResponse>;
    type IntoFuture = std::pin::Pin<
        Box<dyn std::future::Future<Output = crate::error::Result<pb::DeleteRangeResponse>> + 'a>,
    >;
    fn into_future(self) -> Self::IntoFuture {
        let DoDeleteRangeRequest { request, client } = self;
        Box::pin(async move { client.delete_range(request).await })
    }
}

impl From<pb::RangeRequest> for pb::RequestOp {
    fn from(request: pb::RangeRequest) -> Self {
        let request_op = pb::request_op::Request::RequestRange(request);
        pb::RequestOp {
            request: Some(request_op),
        }
    }
}

impl From<pb::PutRequest> for pb::RequestOp {
    fn from(request: pb::PutRequest) -> Self {
        let request_op = pb::request_op::Request::RequestPut(request);
        pb::RequestOp {
            request: Some(request_op),
        }
    }
}

impl From<pb::DeleteRangeRequest> for pb::RequestOp {
    fn from(request: pb::DeleteRangeRequest) -> Self {
        let request_op = pb::request_op::Request::RequestDeleteRange(request);
        pb::RequestOp {
            request: Some(request_op),
        }
    }
}

impl From<pb::TxnRequest> for pb::RequestOp {
    fn from(request: pb::TxnRequest) -> Self {
        let request_op = pb::request_op::Request::RequestTxn(request);
        pb::RequestOp {
            request: Some(request_op),
        }
    }
}

impl pb::Compare {
    pub fn new(
        key: impl Into<Vec<u8>>,
        result: pb::compare::CompareResult,
        target_union: pb::compare::TargetUnion,
    ) -> Self {
        let target = match target_union {
            pb::compare::TargetUnion::Version(_) => pb::compare::CompareTarget::Version,
            pb::compare::TargetUnion::CreateRevision(_) => pb::compare::CompareTarget::Create,
            pb::compare::TargetUnion::ModRevision(_) => pb::compare::CompareTarget::Mod,
            pb::compare::TargetUnion::Value(_) => pb::compare::CompareTarget::Value,
            pb::compare::TargetUnion::Lease(_) => pb::compare::CompareTarget::Lease,
        };

        pb::Compare {
            key: key.into(),
            result: result.into(),
            target: target.into(),
            target_union: Some(target_union),
            ..Default::default()
        }
    }

    /// Set key range end.
    pub fn with_range_end(mut self, end: impl Into<Vec<u8>>) -> Self {
        self.range_end = end.into();
        self
    }

    /// Set key prefix.
    pub fn with_prefix(mut self) -> Self {
        self.range_end = build_prefix_end(&self.key);
        self
    }
}

impl pb::TxnRequest {
    pub fn new() -> Self {
        pb::TxnRequest {
            ..Default::default()
        }
    }

    pub fn with_if(mut self, cmps: Vec<pb::Compare>) -> Self {
        self.compare = cmps;
        self
    }

    pub fn with_then(mut self, ops: Vec<pb::RequestOp>) -> Self {
        self.success = ops;
        self
    }

    pub fn with_else(mut self, ops: Vec<pb::RequestOp>) -> Self {
        self.failure = ops;
        self
    }

    pub fn build<S: GrpcService>(self, client: &mut KvClient<S>) -> DoTxnRequest<'_, S> {
        DoTxnRequest {
            request: self,
            client,
        }
    }
}
#[must_use]
pub struct DoTxnRequest<'a, S> {
    pub request: pb::TxnRequest,
    pub(crate) client: &'a mut KvClient<S>,
}
impl<'a, S> DoTxnRequest<'a, S>
where
    S: GrpcService,
{
    pub fn with_if(mut self, cmps: Vec<pb::Compare>) -> Self {
        self.request = self.request.with_if(cmps);
        self
    }

    pub fn with_then(mut self, ops: Vec<pb::RequestOp>) -> Self {
        self.request = self.request.with_then(ops);
        self
    }

    pub fn with_else(mut self, ops: Vec<pb::RequestOp>) -> Self {
        self.request = self.request.with_else(ops);
        self
    }

    pub fn with_client(mut self, client: &'a mut KvClient<S>) -> Self {
        self.client = client;
        self
    }
}
impl<'a, S> std::future::IntoFuture for DoTxnRequest<'a, S>
where
    S: GrpcService,
{
    type Output = Result<pb::TxnResponse>;
    type IntoFuture = std::pin::Pin<
        Box<dyn std::future::Future<Output = crate::error::Result<pb::TxnResponse>> + 'a>,
    >;
    fn into_future(self) -> Self::IntoFuture {
        let DoTxnRequest { request, client } = self;
        Box::pin(async move { client.txn(request).await })
    }
}
impl pb::CompactionRequest {
    pub fn new(revision: i64, physical: bool) -> Self {
        pb::CompactionRequest { revision, physical }
    }

    pub fn build<S: GrpcService>(self, client: &mut KvClient<S>) -> DoCompactionRequest<'_, S> {
        DoCompactionRequest {
            request: self,
            client,
        }
    }
}
#[must_use]
pub struct DoCompactionRequest<'a, S> {
    pub request: pb::CompactionRequest,
    pub(crate) client: &'a mut KvClient<S>,
}
impl<'a, S> DoCompactionRequest<'a, S>
where
    S: GrpcService,
{
    pub fn with_client(mut self, client: &'a mut KvClient<S>) -> Self {
        self.client = client;
        self
    }
    pub fn with_revision(mut self, revision: i64) -> Self {
        self.request.revision = revision;
        self
    }
    pub fn with_physical(mut self, physical: bool) -> Self {
        self.request.physical = physical;
        self
    }
}
impl<'a, S> std::future::IntoFuture for DoCompactionRequest<'a, S>
where
    S: GrpcService,
{
    type Output = Result<pb::CompactionResponse>;
    type IntoFuture = std::pin::Pin<
        Box<dyn std::future::Future<Output = crate::error::Result<pb::CompactionResponse>> + 'a>,
    >;
    fn into_future(self) -> Self::IntoFuture {
        let DoCompactionRequest { request, client } = self;
        Box::pin(async move { client.compact(request).await })
    }
}