etcdrs 0.1.2

An async etcd v3 client built on tonic and tokio, with composable operation builders and type-safe responses
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
use std::{
    future::{Future, IntoFuture},
    pin::Pin,
    task::{Context, Poll},
};

use bytes::Bytes;

use crate::{
    Client, ResponseHeader,
    client::ClientInner,
    pb::{authpb, etcdserverpb},
    range::{AsRange, TargetRange},
};

/// # Role Management
impl Client {
    /// Add a new role to the cluster.
    pub fn role_add(&self, name: &str) -> RoleAdd<Self> {
        RoleAdd::new(name).with_client(self.clone())
    }

    /// Get a role, including the [permissions][Permission] granted to it.
    pub fn role_get(&self, name: &str) -> RoleGet<Self> {
        RoleGet::new(name).with_client(self.clone())
    }

    /// List the names of all roles.
    pub fn role_list(&self) -> RoleList<Self> {
        RoleList::new().with_client(self.clone())
    }

    /// Delete a role.
    pub fn role_delete(&self, name: &str) -> RoleDelete<Self> {
        RoleDelete::new(name).with_client(self.clone())
    }

    /// Grant a [`Permission`] to a role.
    ///
    /// A permission couples an access type (read, write, or read-write) with a set of keys. The
    /// key set uses the same range syntax as [`list`][Client::list] queries: a single key, a
    /// bounded range, a [`Prefix`][crate::Prefix], or all keys (`..`).
    ///
    /// ```no_run
    /// # async {
    /// # let client: etcdrs::Client = todo!();
    /// use etcdrs::{Permission, Prefix};
    ///
    /// // Read-write access to every key prefixed with "app/"
    /// client
    ///     .role_grant_permission("app", Permission::read_write(Prefix("app/")))
    ///     .await
    ///     .expect("failed to grant permission");
    ///
    /// // Read access to the single key "config"
    /// client
    ///     .role_grant_permission("app", Permission::read("config"))
    ///     .await
    ///     .expect("failed to grant permission");
    /// # };
    /// ```
    pub fn role_grant_permission(&self, name: &str, permission: Permission) -> RoleGrantPermission<Self> {
        RoleGrantPermission::new(name, permission).with_client(self.clone())
    }

    /// Revoke a previously granted permission from a role by its range.
    ///
    /// etcd revokes only a permission whose `key` and `range_end` equal the ones `range` encodes to,
    /// so covering the same keys is not enough: `"a"` and `"a"..="a"` both cover only the key `a`,
    /// but neither revokes a permission [granted][Client::role_grant_permission] with the other. To
    /// see how a granted permission is encoded, read it back with [`role_get`][Client::role_get] and
    /// call [`Permission::target_range`]. Revoking a permission that was not granted fails with
    /// [`RoleErrorKind::PermissionNotGranted`].
    pub fn role_revoke_permission(&self, name: &str, range: impl AsRange) -> RoleRevokePermission<Self> {
        RoleRevokePermission::new(name, range).with_client(self.clone())
    }
}

/// The type of access a [`Permission`] grants.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PermissionType {
    /// The permission grants read access.
    Read,
    /// The permission grants write access.
    Write,
    /// The permission grants both read and write access.
    ReadWrite,
}

/// A permission grantable to a role, covering a single key, a range, a prefix, or all keys.
///
/// The covered keys are expressed with the same [`AsRange`] expressions used by
/// [`list`][Client::list] and [`delete_range`][Client::delete_range]:
///
/// ```
/// use etcdrs::{Permission, Prefix};
///
/// Permission::read("config");                 // a single key
/// Permission::write("a".."b");                // a range
/// Permission::read_write(Prefix("app/"));     // a prefix
/// Permission::read(..);                       // all keys
/// # ;
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Permission {
    perm_type: PermissionType,
    key: Bytes,
    range_end: Bytes,
}

impl Permission {
    /// Create a permission granting read access over `range`.
    pub fn read(range: impl AsRange) -> Self {
        Self::new(PermissionType::Read, range)
    }

    /// Create a permission granting write access over `range`.
    pub fn write(range: impl AsRange) -> Self {
        Self::new(PermissionType::Write, range)
    }

    /// Create a permission granting read and write access over `range`.
    pub fn read_write(range: impl AsRange) -> Self {
        Self::new(PermissionType::ReadWrite, range)
    }

    fn new(perm_type: PermissionType, range: impl AsRange) -> Self {
        let (key, range_end) = range.as_boundaries();
        Self {
            perm_type,
            key,
            range_end,
        }
    }

    /// The type of access this permission grants.
    pub fn permission_type(&self) -> PermissionType {
        self.perm_type
    }

    /// The keys this permission covers.
    pub fn target_range(&self) -> TargetRange<'_> {
        TargetRange::from_wire(&self.key, &self.range_end)
    }

    pub(crate) fn from_pb(pb: authpb::Permission) -> Self {
        let perm_type = match authpb::permission::Type::try_from(pb.perm_type)
            .expect("etcd should return a known permission type")
        {
            authpb::permission::Type::Read => PermissionType::Read,
            authpb::permission::Type::Write => PermissionType::Write,
            authpb::permission::Type::Readwrite => PermissionType::ReadWrite,
        };
        Self {
            perm_type,
            key: pb.key,
            range_end: pb.range_end,
        }
    }

    pub(crate) fn into_pb(self) -> authpb::Permission {
        let perm_type = match self.perm_type {
            PermissionType::Read => authpb::permission::Type::Read,
            PermissionType::Write => authpb::permission::Type::Write,
            PermissionType::ReadWrite => authpb::permission::Type::Readwrite,
        };
        authpb::Permission {
            perm_type: perm_type as i32,
            key: self.key,
            range_end: self.range_end,
        }
    }
}

/// The response from a [`role_add`][Client::role_add] operation.
#[derive(Clone, Copy, Debug)]
pub struct RoleAddResponse {
    header: ResponseHeader,
}

impl RoleAddResponse {
    pub(crate) fn new(header: ResponseHeader) -> Self {
        Self { header }
    }

    /// The response header containing cluster metadata and the store revision.
    pub fn header(&self) -> &ResponseHeader {
        &self.header
    }
}

/// A [`Client::role_add`] operation.
#[derive(Clone)]
#[must_use = "RoleAdd does nothing unless you `await` it"]
pub struct RoleAdd<C> {
    client: C,
    pub(crate) request: etcdserverpb::AuthRoleAddRequest,
}

impl RoleAdd<()> {
    pub fn new(name: &str) -> Self {
        Self {
            client: (),
            request: etcdserverpb::AuthRoleAddRequest { name: name.into() },
        }
    }
}

impl<C> RoleAdd<C> {
    pub fn with_client<C2>(self, client: C2) -> RoleAdd<C2> {
        RoleAdd {
            client,
            request: self.request,
        }
    }

    pub fn name(&self) -> &str {
        &self.request.name
    }

    pub(crate) fn into_parts(self) -> (C, RoleAdd<()>) {
        (
            self.client,
            RoleAdd {
                client: (),
                request: self.request,
            },
        )
    }
}

pub struct RoleAddFuture(Pin<Box<dyn Future<Output = Result<RoleAddResponse, RoleError>> + Send>>);

impl RoleAddFuture {
    pub(crate) fn new(future: impl Future<Output = Result<RoleAddResponse, RoleError>> + Send + 'static) -> Self {
        Self(Box::pin(future))
    }
}

impl Future for RoleAddFuture {
    type Output = Result<RoleAddResponse, RoleError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.as_mut().poll(cx)
    }
}

impl<C: crate::driver::AuthDriver> IntoFuture for RoleAdd<C> {
    type Output = Result<RoleAddResponse, RoleError>;
    type IntoFuture = C::RoleAddFuture;

    fn into_future(self) -> Self::IntoFuture {
        let (client, detached) = self.into_parts();
        client.execute_role_add(detached)
    }
}

/// A [`Client::role_get`] operation.
#[derive(Clone)]
#[must_use = "RoleGet does nothing unless you `await` it"]
pub struct RoleGet<C> {
    client: C,
    pub(crate) request: etcdserverpb::AuthRoleGetRequest,
}

impl RoleGet<()> {
    pub fn new(name: &str) -> Self {
        Self {
            client: (),
            request: etcdserverpb::AuthRoleGetRequest { role: name.into() },
        }
    }
}

impl<C> RoleGet<C> {
    pub fn with_client<C2>(self, client: C2) -> RoleGet<C2> {
        RoleGet {
            client,
            request: self.request,
        }
    }

    /// The role name to look up.
    pub fn name(&self) -> &str {
        &self.request.role
    }

    pub(crate) fn into_parts(self) -> (C, RoleGet<()>) {
        (
            self.client,
            RoleGet {
                client: (),
                request: self.request,
            },
        )
    }
}

/// The response from a [`role_get`][Client::role_get] operation.
#[derive(Clone, Debug)]
pub struct RoleGetResponse {
    header: ResponseHeader,
    permissions: Vec<Permission>,
}

impl RoleGetResponse {
    pub(crate) fn new(header: ResponseHeader, permissions: Vec<Permission>) -> Self {
        Self { header, permissions }
    }

    /// The response header containing cluster metadata and the store revision.
    pub fn header(&self) -> &ResponseHeader {
        &self.header
    }

    /// The permissions granted to the role.
    pub fn permissions(&self) -> &[Permission] {
        &self.permissions
    }

    /// Consume the response and return the permissions granted to the role.
    pub fn into_permissions(self) -> Vec<Permission> {
        self.permissions
    }
}

pub struct RoleGetFuture(Pin<Box<dyn Future<Output = Result<RoleGetResponse, RoleError>> + Send>>);

impl RoleGetFuture {
    pub(crate) fn new(future: impl Future<Output = Result<RoleGetResponse, RoleError>> + Send + 'static) -> Self {
        Self(Box::pin(future))
    }
}

impl Future for RoleGetFuture {
    type Output = Result<RoleGetResponse, RoleError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.as_mut().poll(cx)
    }
}

impl<C: crate::driver::AuthDriver> IntoFuture for RoleGet<C> {
    type Output = Result<RoleGetResponse, RoleError>;
    type IntoFuture = C::RoleGetFuture;

    fn into_future(self) -> Self::IntoFuture {
        let (client, detached) = self.into_parts();
        client.execute_role_get(detached)
    }
}

/// A [`Client::role_list`] operation.
#[derive(Clone)]
#[must_use = "RoleList does nothing unless you `await` it"]
pub struct RoleList<C> {
    client: C,
}

impl RoleList<()> {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self { client: () }
    }
}

impl<C> RoleList<C> {
    pub fn with_client<C2>(self, client: C2) -> RoleList<C2> {
        RoleList { client }
    }

    pub(crate) fn into_parts(self) -> (C, RoleList<()>) {
        (self.client, RoleList { client: () })
    }
}

/// The response from a [`role_list`][Client::role_list] operation.
#[derive(Clone, Debug)]
pub struct RoleListResponse {
    header: ResponseHeader,
    roles: Vec<String>,
}

impl RoleListResponse {
    pub(crate) fn new(header: ResponseHeader, roles: Vec<String>) -> Self {
        Self { header, roles }
    }

    /// The response header containing cluster metadata and the store revision.
    pub fn header(&self) -> &ResponseHeader {
        &self.header
    }

    /// The names of all roles.
    pub fn roles(&self) -> &[String] {
        &self.roles
    }

    /// Consume the response and return the role names.
    pub fn into_roles(self) -> Vec<String> {
        self.roles
    }
}

pub struct RoleListFuture(Pin<Box<dyn Future<Output = Result<RoleListResponse, RoleError>> + Send>>);

impl RoleListFuture {
    pub(crate) fn new(future: impl Future<Output = Result<RoleListResponse, RoleError>> + Send + 'static) -> Self {
        Self(Box::pin(future))
    }
}

impl Future for RoleListFuture {
    type Output = Result<RoleListResponse, RoleError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.as_mut().poll(cx)
    }
}

impl<C: crate::driver::AuthDriver> IntoFuture for RoleList<C> {
    type Output = Result<RoleListResponse, RoleError>;
    type IntoFuture = C::RoleListFuture;

    fn into_future(self) -> Self::IntoFuture {
        let (client, detached) = self.into_parts();
        client.execute_role_list(detached)
    }
}

/// A [`Client::role_delete`] operation.
#[derive(Clone)]
#[must_use = "RoleDelete does nothing unless you `await` it"]
pub struct RoleDelete<C> {
    client: C,
    pub(crate) request: etcdserverpb::AuthRoleDeleteRequest,
}

impl RoleDelete<()> {
    pub fn new(name: &str) -> Self {
        Self {
            client: (),
            request: etcdserverpb::AuthRoleDeleteRequest { role: name.into() },
        }
    }
}

impl<C> RoleDelete<C> {
    pub fn with_client<C2>(self, client: C2) -> RoleDelete<C2> {
        RoleDelete {
            client,
            request: self.request,
        }
    }

    /// The role name to delete.
    pub fn name(&self) -> &str {
        &self.request.role
    }

    pub(crate) fn into_parts(self) -> (C, RoleDelete<()>) {
        (
            self.client,
            RoleDelete {
                client: (),
                request: self.request,
            },
        )
    }
}

/// The response from a [`role_delete`][Client::role_delete] operation.
#[derive(Clone, Copy, Debug)]
pub struct RoleDeleteResponse {
    header: ResponseHeader,
}

impl RoleDeleteResponse {
    pub(crate) fn new(header: ResponseHeader) -> Self {
        Self { header }
    }

    /// The response header containing cluster metadata and the store revision.
    pub fn header(&self) -> &ResponseHeader {
        &self.header
    }
}

pub struct RoleDeleteFuture(Pin<Box<dyn Future<Output = Result<RoleDeleteResponse, RoleError>> + Send>>);

impl RoleDeleteFuture {
    pub(crate) fn new(future: impl Future<Output = Result<RoleDeleteResponse, RoleError>> + Send + 'static) -> Self {
        Self(Box::pin(future))
    }
}

impl Future for RoleDeleteFuture {
    type Output = Result<RoleDeleteResponse, RoleError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.as_mut().poll(cx)
    }
}

impl<C: crate::driver::AuthDriver> IntoFuture for RoleDelete<C> {
    type Output = Result<RoleDeleteResponse, RoleError>;
    type IntoFuture = C::RoleDeleteFuture;

    fn into_future(self) -> Self::IntoFuture {
        let (client, detached) = self.into_parts();
        client.execute_role_delete(detached)
    }
}

/// A [`Client::role_grant_permission`] operation.
#[derive(Clone)]
#[must_use = "RoleGrantPermission does nothing unless you `await` it"]
pub struct RoleGrantPermission<C> {
    client: C,
    pub(crate) name: String,
    pub(crate) permission: Permission,
}

impl RoleGrantPermission<()> {
    pub fn new(name: &str, permission: Permission) -> Self {
        Self {
            client: (),
            name: name.into(),
            permission,
        }
    }
}

impl<C> RoleGrantPermission<C> {
    pub fn with_client<C2>(self, client: C2) -> RoleGrantPermission<C2> {
        RoleGrantPermission {
            client,
            name: self.name,
            permission: self.permission,
        }
    }

    /// The role the permission will be granted to.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The permission to grant.
    pub fn permission(&self) -> &Permission {
        &self.permission
    }

    pub(crate) fn into_parts(self) -> (C, RoleGrantPermission<()>) {
        (
            self.client,
            RoleGrantPermission {
                client: (),
                name: self.name,
                permission: self.permission,
            },
        )
    }
}

/// The response from a [`role_grant_permission`][Client::role_grant_permission] operation.
#[derive(Clone, Copy, Debug)]
pub struct RoleGrantPermissionResponse {
    header: ResponseHeader,
}

impl RoleGrantPermissionResponse {
    pub(crate) fn new(header: ResponseHeader) -> Self {
        Self { header }
    }

    /// The response header containing cluster metadata and the store revision.
    pub fn header(&self) -> &ResponseHeader {
        &self.header
    }
}

pub struct RoleGrantPermissionFuture(
    Pin<Box<dyn Future<Output = Result<RoleGrantPermissionResponse, RoleError>> + Send>>,
);

impl RoleGrantPermissionFuture {
    pub(crate) fn new(
        future: impl Future<Output = Result<RoleGrantPermissionResponse, RoleError>> + Send + 'static,
    ) -> Self {
        Self(Box::pin(future))
    }
}

impl Future for RoleGrantPermissionFuture {
    type Output = Result<RoleGrantPermissionResponse, RoleError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.as_mut().poll(cx)
    }
}

impl<C: crate::driver::AuthDriver> IntoFuture for RoleGrantPermission<C> {
    type Output = Result<RoleGrantPermissionResponse, RoleError>;
    type IntoFuture = C::RoleGrantPermissionFuture;

    fn into_future(self) -> Self::IntoFuture {
        let (client, detached) = self.into_parts();
        client.execute_role_grant_permission(detached)
    }
}

/// A [`Client::role_revoke_permission`] operation.
#[derive(Clone)]
#[must_use = "RoleRevokePermission does nothing unless you `await` it"]
pub struct RoleRevokePermission<C> {
    client: C,
    pub(crate) request: etcdserverpb::AuthRoleRevokePermissionRequest,
}

impl RoleRevokePermission<()> {
    pub fn new(name: &str, range: impl AsRange) -> Self {
        let (key, range_end) = range.as_boundaries();
        Self {
            client: (),
            request: etcdserverpb::AuthRoleRevokePermissionRequest {
                role: name.into(),
                key,
                range_end,
            },
        }
    }
}

impl<C> RoleRevokePermission<C> {
    pub fn with_client<C2>(self, client: C2) -> RoleRevokePermission<C2> {
        RoleRevokePermission {
            client,
            request: self.request,
        }
    }

    /// The role the permission will be revoked from.
    pub fn name(&self) -> &str {
        &self.request.role
    }

    /// The keys of the permission to revoke.
    pub fn target_range(&self) -> TargetRange<'_> {
        TargetRange::from_wire(&self.request.key, &self.request.range_end)
    }

    pub(crate) fn into_parts(self) -> (C, RoleRevokePermission<()>) {
        (
            self.client,
            RoleRevokePermission {
                client: (),
                request: self.request,
            },
        )
    }
}

/// The response from a [`role_revoke_permission`][Client::role_revoke_permission] operation.
#[derive(Clone, Copy, Debug)]
pub struct RoleRevokePermissionResponse {
    header: ResponseHeader,
}

impl RoleRevokePermissionResponse {
    pub(crate) fn new(header: ResponseHeader) -> Self {
        Self { header }
    }

    /// The response header containing cluster metadata and the store revision.
    pub fn header(&self) -> &ResponseHeader {
        &self.header
    }
}

pub struct RoleRevokePermissionFuture(
    Pin<Box<dyn Future<Output = Result<RoleRevokePermissionResponse, RoleError>> + Send>>,
);

impl RoleRevokePermissionFuture {
    pub(crate) fn new(
        future: impl Future<Output = Result<RoleRevokePermissionResponse, RoleError>> + Send + 'static,
    ) -> Self {
        Self(Box::pin(future))
    }
}

impl Future for RoleRevokePermissionFuture {
    type Output = Result<RoleRevokePermissionResponse, RoleError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.as_mut().poll(cx)
    }
}

impl<C: crate::driver::AuthDriver> IntoFuture for RoleRevokePermission<C> {
    type Output = Result<RoleRevokePermissionResponse, RoleError>;
    type IntoFuture = C::RoleRevokePermissionFuture;

    fn into_future(self) -> Self::IntoFuture {
        let (client, detached) = self.into_parts();
        client.execute_role_revoke_permission(detached)
    }
}

/// An enumeration of the [`kind`][RoleError::kind]s of errors that can occur from role management
/// operations ([`role_add`][Client::role_add], [`role_get`][Client::role_get],
/// [`role_list`][Client::role_list], [`role_delete`][Client::role_delete],
/// [`role_grant_permission`][Client::role_grant_permission],
/// [`role_revoke_permission`][Client::role_revoke_permission]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RoleErrorKind {
    /// The role already exists.
    ///
    /// This comes from the gRPC API as `FAILED_PRECONDITION` with "already exists".
    RoleAlreadyExists,
    /// The role was not found.
    ///
    /// This comes from the gRPC API as `FAILED_PRECONDITION` with "role name not found".
    RoleNotFound,
    /// The permission is not granted to the role (when revoking a permission).
    ///
    /// This comes from the gRPC API as `FAILED_PRECONDITION` with "permission is not granted to
    /// the role".
    PermissionNotGranted,
    /// The operation is not permitted on this role, or the permission's range is invalid.
    ///
    /// Two conditions produce this kind:
    ///
    /// - Deleting the root role while authentication is enabled.
    /// - Granting a permission whose range is invalid: its key is empty (`""`), or it ends at or
    ///   before its key (`"b".."a"`, `"a".."a"`). etcd rejects these even when authentication is
    ///   disabled. The permission [`role_get`][Client::role_get] reports for the root role has an
    ///   empty key too, so granting it to another role fails although it covers every key.
    ///
    /// This comes from the gRPC API as `INVALID_ARGUMENT` with "invalid auth management".
    InvalidAuthManagement,
    /// Authentication is not enabled.
    ///
    /// This comes from the gRPC API as `FAILED_PRECONDITION` with "not enabled".
    AuthNotEnabled,
    /// 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 [`InvalidAuthManagement`][Self::InvalidAuthManagement] or
    /// [`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: role name is
    /// empty" for [`role_add`][Client::role_add] with an empty name. Their message is available
    /// from [`grpc_status`][RoleError::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 role management operation ([`role_add`][Client::role_add],
    /// [`role_get`][Client::role_get], [`role_list`][Client::role_list],
    /// [`role_delete`][Client::role_delete],
    /// [`role_grant_permission`][Client::role_grant_permission],
    /// [`role_revoke_permission`][Client::role_revoke_permission]).
    pub struct RoleError(RoleErrorKind);
}

impl RoleError {
    pub(crate) fn from_status(status: tonic::Status) -> Self {
        let kind = match status.code() {
            tonic::Code::FailedPrecondition => {
                let msg = status.message();
                if msg.contains("already exists") {
                    RoleErrorKind::RoleAlreadyExists
                } else if msg.contains("role name not found") {
                    RoleErrorKind::RoleNotFound
                } else if msg.contains("not granted") {
                    RoleErrorKind::PermissionNotGranted
                } else if msg.contains("not enabled") {
                    RoleErrorKind::AuthNotEnabled
                } else {
                    RoleErrorKind::Unknown
                }
            }
            tonic::Code::Unauthenticated => RoleErrorKind::Authentication,
            tonic::Code::PermissionDenied => RoleErrorKind::Authentication,
            tonic::Code::InvalidArgument => {
                if status.message().contains("invalid auth management") {
                    RoleErrorKind::InvalidAuthManagement
                } else if ClientInner::is_stale_token_error(&status) {
                    RoleErrorKind::Authentication
                } else {
                    RoleErrorKind::Unknown
                }
            }
            tonic::Code::ResourceExhausted => RoleErrorKind::Exhausted,
            tonic::Code::Unavailable => RoleErrorKind::Unavailable,
            tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => RoleErrorKind::Timeout,
            _ => RoleErrorKind::Unknown,
        };
        Self::new(kind, "", Some(status))
    }
}

const _: () = {
    fn _assert_send<T: Send>() {}
    fn _check() {
        _assert_send::<RoleAddFuture>();
        _assert_send::<RoleGetFuture>();
        _assert_send::<RoleListFuture>();
        _assert_send::<RoleDeleteFuture>();
        _assert_send::<RoleGrantPermissionFuture>();
        _assert_send::<RoleRevokePermissionFuture>();
    }
};

#[cfg(test)]
mod test {
    use super::*;

    /// `role_add("")` gets "role name is empty", which is about the request.
    #[test]
    fn invalid_argument_is_authentication_only_for_token_messages() {
        use RoleErrorKind::*;

        for (message, expected) in [
            ("etcdserver: user name is empty", Authentication),
            ("etcdserver: revision of auth store is old", Authentication),
            ("etcdserver: invalid auth management", InvalidAuthManagement),
            ("etcdserver: role name is empty", Unknown),
            ("etcdserver: request is too large", Unknown),
        ] {
            let kind = RoleError::from_status(tonic::Status::invalid_argument(message)).kind();
            assert_eq!(kind, expected, "{message:?}");
        }
    }
}