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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
use std::{
    collections::VecDeque,
    future::{Future, IntoFuture},
    marker::PhantomData,
    ops::{Deref, DerefMut},
    pin::Pin,
    sync::Arc,
    task::{Context, Poll, ready},
    time::Duration,
};

use bytes::Bytes;
use futures_core::Stream;

use crate::{Client, LeaseId, ResponseHeader, client::ClientInner, pb::etcdserverpb};

/// # Leases
impl Client {
    /// Create a lease used to create ephemeral records.
    ///
    /// ```no_run
    /// # async {
    /// let client: etcdrs::Client = todo!();
    /// let lease_info = client.grant_lease()
    ///     .ttl(std::time::Duration::from_secs(60))
    ///     .await
    ///     .expect("failed to grant lease");
    ///
    /// // Put a key using that lease
    /// client.put("foo")
    ///     .value("bar")
    ///     .lease(lease_info.lease_id)
    ///     .await
    ///     .expect("failed to put key");
    ///
    /// // Wait for the lease to expire
    /// std::thread::sleep(lease_info.ttl.unwrap());
    ///
    /// // etcd does not always immediately revoke leases, but if you just have one
    /// // server and the clocks are in sync, it will be fast and this will be None
    /// println!("foo? {:?}", client.get("foo").await.unwrap());
    /// # };
    /// ```
    pub fn grant_lease(&self) -> GrantLease<Self> {
        GrantLease::new().with_client(self.clone())
    }

    /// Revoke an existing lease.
    pub fn revoke_lease(&self, lease_id: LeaseId) -> RevokeLease<Self> {
        RevokeLease::new(lease_id).with_client(self.clone())
    }

    /// Retrieve the remaining time-to-live of a lease.
    ///
    /// A missing or expired lease is reported as a successful response with no remaining
    /// [`ttl`][LeaseInfo::ttl]. Use [`with_keys`][LeaseTimeToLive::with_keys] to also fetch the
    /// keys attached to the lease.
    ///
    /// ```no_run
    /// # async {
    /// let client: etcdrs::Client = todo!();
    /// # let lease_id: etcdrs::LeaseId = todo!();
    /// let response = client.lease_time_to_live(lease_id).await.unwrap();
    /// match response.ttl {
    ///     Some(remaining) => println!("lease expires in {remaining:?}"),
    ///     None => println!("lease has expired"),
    /// }
    /// # };
    /// ```
    pub fn lease_time_to_live(&self, lease_id: LeaseId) -> LeaseTimeToLive<Self> {
        LeaseTimeToLive::new(lease_id).with_client(self.clone())
    }

    /// List the IDs of the leases the responding member knows about.
    ///
    /// etcd answers this from that member's own lease table, without a linearizable read and
    /// without forwarding to the leader, and the request carries no option to ask for either. A
    /// lease granted or revoked through a different member is therefore absent, or still listed,
    /// until the responding member applies that change. Only
    /// [`lease_time_to_live`][Client::lease_time_to_live] is answered by the leader.
    ///
    /// ```no_run
    /// # async {
    /// let client: etcdrs::Client = todo!();
    /// for lease_id in client.leases().await.unwrap().leases() {
    ///     println!("active lease: {lease_id:?}");
    /// }
    /// # };
    /// ```
    pub fn leases(&self) -> Leases<Self> {
        Leases::new().with_client(self.clone())
    }

    /// Create a [`LeaseKeeper`] for keeping leases alive via a bidirectional streaming RPC.
    ///
    /// The gRPC stream is established lazily on the first poll of the returned [`LeaseKeeper`].
    /// Use [`keep_alive`][LeaseKeeper::keep_alive] to send keep-alive requests for specific
    /// leases, and consume the stream to receive responses.
    ///
    /// The stream ends after its first error, unless etcd stopped accepting the auth token it
    /// carries: it then reopens with a refreshed token (see
    /// [`ClientBuilder::credentials`][crate::client::ClientBuilder::credentials]) and sends again
    /// the keep-alives etcd did not answer.
    ///
    /// ```no_run
    /// use futures::StreamExt;
    /// # async {
    /// # let client: etcdrs::Client = todo!();
    /// # let lease_id: etcdrs::LeaseId = todo!();
    /// let keeper = client.lease_keeper();
    /// keeper.keep_alive(lease_id);
    /// while let Some(resp) = keeper.next().await {
    ///     let resp = resp.unwrap();
    ///     println!("lease {:?} TTL: {:?}", resp.lease_id, resp.ttl);
    /// }
    /// # };
    /// ```
    pub fn lease_keeper(&self) -> LeaseKeeper {
        crate::driver::LeaseDriver::start_lease_keeper(self.clone())
    }
}

#[derive(Clone, Copy, Debug)]
pub struct LeaseInfo {
    pub lease_id: LeaseId,
    /// The remaining time-to-live on the lease, or `None` if the lease has expired.
    pub ttl: Option<Duration>,
}

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

impl GrantLease<()> {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self {
            client: (),
            request: etcdserverpb::LeaseGrantRequest::default(),
        }
    }
}

impl<C> GrantLease<C> {
    /// Attach a `client` to this operation.
    ///
    /// You typically do not have to call this function, as it is called automatically by
    /// [`grant_lease`][`Client::grant_lease`].
    pub fn with_client<C2>(self, client: C2) -> GrantLease<C2> {
        GrantLease {
            client,
            request: self.request,
        }
    }

    /// Request a specific ID for the lease.
    ///
    /// If left unspecified (the default), a unique ID will be generated for you.
    pub fn lease_id(mut self, lease_id: LeaseId) -> Self {
        self.request.id = lease_id.get();
        self
    }

    /// Request a time-to-live on the lease.
    ///
    /// This is only the requested time-to-live; the service raises one below its minimum to that minimum. Check the
    /// returned [`ttl`][LeaseInfo::ttl] to see how long you were given in the lease. One above 9,000,000,000 seconds
    /// fails with [`TtlTooLarge`][GrantLeaseErrorKind::TtlTooLarge].
    ///
    /// While a [`Duration`] can be nanosecond resolution, the service itself only respects whole seconds. Leaving this
    /// unspecified will use the lowest-possible TTL the server supports (usually 2 seconds).
    pub fn ttl(mut self, duration: Duration) -> Self {
        self.request.ttl = i64::try_from(duration.as_secs()).unwrap_or(i64::MAX);
        self
    }

    /// The requested lease ID, or `None` when etcd should choose one.
    pub fn requested_lease_id(&self) -> Option<LeaseId> {
        LeaseId::new(self.request.id)
    }

    /// The requested lease TTL in whole seconds, at most `i64::MAX` of them, or `None` when the server default is
    /// used.
    pub fn requested_ttl(&self) -> Option<Duration> {
        (self.request.ttl > 0).then(|| Duration::from_secs(self.request.ttl as _))
    }

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

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

impl GrantLeaseResponse {
    pub(crate) fn new(header: ResponseHeader, info: LeaseInfo) -> Self {
        Self { header, info }
    }

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

    /// The lease information, including the assigned ID and granted TTL.
    pub fn info(&self) -> &LeaseInfo {
        &self.info
    }

    /// Consume the response and return the [`LeaseInfo`].
    pub fn into_info(self) -> LeaseInfo {
        self.info
    }
}

impl Deref for GrantLeaseResponse {
    type Target = LeaseInfo;

    fn deref(&self) -> &LeaseInfo {
        &self.info
    }
}

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

impl RevokeLeaseResponse {
    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
    }
}

/// The [`Future`] type returned by awaiting a [`grant_lease`][`Client::grant_lease`].
pub struct GrantLeaseFuture(Pin<Box<dyn Future<Output = Result<GrantLeaseResponse, GrantLeaseError>> + Send>>);

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

impl Future for GrantLeaseFuture {
    type Output = Result<GrantLeaseResponse, GrantLeaseError>;

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

impl<C: crate::driver::LeaseDriver> IntoFuture for GrantLease<C> {
    type Output = Result<GrantLeaseResponse, GrantLeaseError>;
    type IntoFuture = C::GrantFuture;

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

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

impl RevokeLease<()> {
    pub fn new(lease_id: LeaseId) -> Self {
        Self { client: (), lease_id }
    }
}

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

    pub fn lease_id(&self) -> LeaseId {
        self.lease_id
    }

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

pub struct RevokeLeaseFuture(Pin<Box<dyn Future<Output = Result<RevokeLeaseResponse, RevokeLeaseError>> + Send>>);

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

impl Future for RevokeLeaseFuture {
    type Output = Result<RevokeLeaseResponse, RevokeLeaseError>;

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

impl<C: crate::driver::LeaseDriver> IntoFuture for RevokeLease<C> {
    type Output = Result<RevokeLeaseResponse, RevokeLeaseError>;
    type IntoFuture = C::RevokeFuture;

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

/// An enumeration of the [`kind`][GrantLeaseError::kind]s of errors that can occur from a
/// [`grant_lease`][Client::grant_lease] operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GrantLeaseErrorKind {
    /// The requested lease ID already exists.
    ///
    /// This comes from the gRPC API as `FAILED_PRECONDITION` with "lease already exists", or via the response's error
    /// field from older etcd servers.
    LeaseExists,
    /// The requested TTL exceeds the server's maximum lease TTL.
    ///
    /// This comes from the gRPC API as `OUT_OF_RANGE`.
    TtlTooLarge,
    /// 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 [`grant_lease`][Client::grant_lease] operation.
    pub struct GrantLeaseError(GrantLeaseErrorKind);
}

impl GrantLeaseError {
    pub(crate) fn from_status(status: tonic::Status) -> Self {
        let kind = match status.code() {
            tonic::Code::Unauthenticated => GrantLeaseErrorKind::Authentication,
            tonic::Code::PermissionDenied => GrantLeaseErrorKind::Authentication,
            tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => {
                GrantLeaseErrorKind::Authentication
            }
            tonic::Code::ResourceExhausted => GrantLeaseErrorKind::Exhausted,
            tonic::Code::OutOfRange => GrantLeaseErrorKind::TtlTooLarge,
            tonic::Code::FailedPrecondition => {
                if status.message().contains("already exists") {
                    GrantLeaseErrorKind::LeaseExists
                } else {
                    GrantLeaseErrorKind::Unknown
                }
            }
            tonic::Code::DataLoss => GrantLeaseErrorKind::DataLoss,
            tonic::Code::Unavailable => GrantLeaseErrorKind::Unavailable,
            // Don't care who timed us out
            tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => GrantLeaseErrorKind::Timeout,
            _ => GrantLeaseErrorKind::Unknown,
        };
        Self::new(kind, "", Some(status))
    }
}

/// An enumeration of the [`kind`][RevokeLeaseError::kind]s of errors that can occur from a
/// [`revoke_lease`][Client::revoke_lease] operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RevokeLeaseErrorKind {
    /// The lease was not found.
    ///
    /// This comes from the gRPC API as `NOT_FOUND`.
    NotFound,
    /// 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 [`revoke_lease`][Client::revoke_lease] operation.
    pub struct RevokeLeaseError(RevokeLeaseErrorKind);
}

impl RevokeLeaseError {
    pub(crate) fn from_status(status: tonic::Status) -> Self {
        let kind = match status.code() {
            tonic::Code::NotFound => RevokeLeaseErrorKind::NotFound,
            tonic::Code::Unauthenticated => RevokeLeaseErrorKind::Authentication,
            tonic::Code::PermissionDenied => RevokeLeaseErrorKind::Authentication,
            tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => {
                RevokeLeaseErrorKind::Authentication
            }
            tonic::Code::ResourceExhausted => RevokeLeaseErrorKind::Exhausted,
            tonic::Code::DataLoss => RevokeLeaseErrorKind::DataLoss,
            tonic::Code::Unavailable => RevokeLeaseErrorKind::Unavailable,
            // Don't care who timed us out
            tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => RevokeLeaseErrorKind::Timeout,
            _ => RevokeLeaseErrorKind::Unknown,
        };
        Self::new(kind, "", Some(status))
    }
}

// -------------------------------------------------------------------------------------------------
// Time-to-live
// -------------------------------------------------------------------------------------------------

/// A [`Client::lease_time_to_live`] operation.
#[derive(Clone, Debug)]
#[must_use = "LeaseTimeToLive does nothing unless you `await` it"]
pub struct LeaseTimeToLive<C, K = ()> {
    client: C,
    pub(crate) request: etcdserverpb::LeaseTimeToLiveRequest,
    _keys: PhantomData<fn() -> K>,
}

impl LeaseTimeToLive<()> {
    pub fn new(lease_id: LeaseId) -> Self {
        Self {
            client: (),
            request: etcdserverpb::LeaseTimeToLiveRequest {
                id: lease_id.get(),
                ..Default::default()
            },
            _keys: PhantomData,
        }
    }
}

impl<C, K> LeaseTimeToLive<C, K> {
    /// Attach a `client` to this operation.
    ///
    /// You typically do not have to call this function, as it is called automatically by
    /// [`lease_time_to_live`][`Client::lease_time_to_live`].
    pub fn with_client<C2>(self, client: C2) -> LeaseTimeToLive<C2, K> {
        LeaseTimeToLive {
            client,
            request: self.request,
            _keys: PhantomData,
        }
    }

    /// Return the keys attached to the lease.
    pub fn with_keys(self) -> LeaseTimeToLive<C, WithKeys> {
        let mut request = self.request;
        request.keys = true;
        LeaseTimeToLive {
            client: self.client,
            request,
            _keys: PhantomData,
        }
    }

    /// The lease this operation queries.
    pub fn lease_id(&self) -> LeaseId {
        LeaseId::new(self.request.id).expect("LeaseTimeToLive lease ID should be non-zero")
    }

    /// Whether the keys attached to the lease will be returned.
    pub fn returns_keys(&self) -> bool {
        self.request.keys
    }

    pub(crate) fn into_parts(self) -> (C, LeaseTimeToLive<(), K>) {
        (
            self.client,
            LeaseTimeToLive {
                client: (),
                request: self.request,
                _keys: PhantomData,
            },
        )
    }
}

/// The response from a [`lease_time_to_live`][Client::lease_time_to_live] operation.
#[derive(Clone, Debug)]
pub struct LeaseTimeToLiveResponse<K = ()> {
    header: ResponseHeader,
    info: LeaseInfo,
    granted_ttl: Option<Duration>,
    keys: Vec<Bytes>,
    _marker: PhantomData<fn() -> K>,
}

impl<K> LeaseTimeToLiveResponse<K> {
    /// Construct a new `LeaseTimeToLiveResponse`.
    pub fn new(header: ResponseHeader, info: LeaseInfo, granted_ttl: Option<Duration>, keys: Vec<Bytes>) -> Self {
        Self {
            header,
            info,
            granted_ttl,
            keys,
            _marker: PhantomData,
        }
    }

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

    /// The lease information, including the ID and the remaining TTL.
    ///
    /// A [`ttl`][LeaseInfo::ttl] of [`None`] indicates the lease has expired or does not exist.
    pub fn info(&self) -> &LeaseInfo {
        &self.info
    }

    /// The TTL originally granted to the lease, or `None` if the lease has expired or does not
    /// exist.
    pub fn granted_ttl(&self) -> Option<Duration> {
        self.granted_ttl
    }
}

impl LeaseTimeToLiveResponse<WithKeys> {
    /// The keys attached to the lease.
    pub fn keys(&self) -> &[Bytes] {
        &self.keys
    }

    /// Consume the response and return the keys attached to the lease.
    pub fn into_keys(self) -> Vec<Bytes> {
        self.keys
    }
}

impl<K> Deref for LeaseTimeToLiveResponse<K> {
    type Target = LeaseInfo;

    fn deref(&self) -> &LeaseInfo {
        &self.info
    }
}

/// The [`Future`] type returned by awaiting a [`lease_time_to_live`][`Client::lease_time_to_live`].
pub struct LeaseTimeToLiveFuture<T>(Pin<Box<dyn Future<Output = T> + Send>>);

impl<T> LeaseTimeToLiveFuture<T> {
    pub(crate) fn new(future: impl Future<Output = T> + Send + 'static) -> Self {
        Self(Box::pin(future))
    }
}

impl<T> Future for LeaseTimeToLiveFuture<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, K> IntoFuture for LeaseTimeToLive<C, K>
where
    C: crate::driver::LeaseDriver,
{
    type Output = Result<LeaseTimeToLiveResponse<K>, LeaseTimeToLiveError>;
    type IntoFuture = C::TimeToLiveFuture<K>;

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

/// Used in [`LeaseTimeToLive`]s to denote that the keys attached to the lease should be returned.
pub struct WithKeys;

/// An enumeration of the [`kind`][LeaseTimeToLiveError::kind]s of errors that can occur from a
/// [`lease_time_to_live`][Client::lease_time_to_live] operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LeaseTimeToLiveErrorKind {
    /// The lease was not found.
    ///
    /// This comes from the gRPC API as `NOT_FOUND`. Only very old etcd servers report a missing
    /// lease this way; modern servers respond successfully with no remaining
    /// [`ttl`][LeaseInfo::ttl].
    NotFound,
    /// 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 [`lease_time_to_live`][Client::lease_time_to_live] operation.
    pub struct LeaseTimeToLiveError(LeaseTimeToLiveErrorKind);
}

impl LeaseTimeToLiveError {
    pub(crate) fn from_status(status: tonic::Status) -> Self {
        let kind = match status.code() {
            tonic::Code::NotFound => LeaseTimeToLiveErrorKind::NotFound,
            tonic::Code::Unauthenticated => LeaseTimeToLiveErrorKind::Authentication,
            tonic::Code::PermissionDenied => LeaseTimeToLiveErrorKind::Authentication,
            tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => {
                LeaseTimeToLiveErrorKind::Authentication
            }
            tonic::Code::ResourceExhausted => LeaseTimeToLiveErrorKind::Exhausted,
            tonic::Code::DataLoss => LeaseTimeToLiveErrorKind::DataLoss,
            tonic::Code::Unavailable => LeaseTimeToLiveErrorKind::Unavailable,
            // Don't care who timed us out
            tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => LeaseTimeToLiveErrorKind::Timeout,
            _ => LeaseTimeToLiveErrorKind::Unknown,
        };
        Self::new(kind, "", Some(status))
    }
}

// -------------------------------------------------------------------------------------------------
// Lease listing
// -------------------------------------------------------------------------------------------------

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

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

impl<C> Leases<C> {
    /// Attach a `client` to this operation.
    ///
    /// You typically do not have to call this function, as it is called automatically by
    /// [`leases`][`Client::leases`].
    pub fn with_client<C2>(self, client: C2) -> Leases<C2> {
        Leases { client }
    }

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

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

impl LeasesResponse {
    pub(crate) fn new(header: ResponseHeader, leases: Vec<LeaseId>) -> Self {
        Self { header, leases }
    }

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

    /// The IDs of all active leases in the cluster.
    pub fn leases(&self) -> &[LeaseId] {
        &self.leases
    }

    /// Consume the response and return the lease IDs.
    pub fn into_leases(self) -> Vec<LeaseId> {
        self.leases
    }
}

/// The [`Future`] type returned by awaiting a [`leases`][`Client::leases`].
pub struct LeasesFuture(Pin<Box<dyn Future<Output = Result<LeasesResponse, LeasesError>> + Send>>);

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

impl Future for LeasesFuture {
    type Output = Result<LeasesResponse, LeasesError>;

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

impl<C: crate::driver::LeaseDriver> IntoFuture for Leases<C> {
    type Output = Result<LeasesResponse, LeasesError>;
    type IntoFuture = C::LeasesFuture;

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

/// An enumeration of the [`kind`][LeasesError::kind]s of errors that can occur from a
/// [`leases`][Client::leases] operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LeasesErrorKind {
    /// 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 [`leases`][Client::leases] operation.
    pub struct LeasesError(LeasesErrorKind);
}

impl LeasesError {
    pub(crate) fn from_status(status: tonic::Status) -> Self {
        let kind = match status.code() {
            tonic::Code::Unauthenticated => LeasesErrorKind::Authentication,
            tonic::Code::PermissionDenied => LeasesErrorKind::Authentication,
            tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => {
                LeasesErrorKind::Authentication
            }
            tonic::Code::ResourceExhausted => LeasesErrorKind::Exhausted,
            tonic::Code::DataLoss => LeasesErrorKind::DataLoss,
            tonic::Code::Unavailable => LeasesErrorKind::Unavailable,
            // Don't care who timed us out
            tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => LeasesErrorKind::Timeout,
            _ => LeasesErrorKind::Unknown,
        };
        Self::new(kind, "", Some(status))
    }
}

// -------------------------------------------------------------------------------------------------
// Keep-alive
// -------------------------------------------------------------------------------------------------

/// The response from a single lease keep-alive round-trip.
#[derive(Clone, Copy, Debug)]
pub struct KeepAliveResponse {
    header: ResponseHeader,
    info: LeaseInfo,
}

impl KeepAliveResponse {
    pub(crate) fn new(header: ResponseHeader, info: LeaseInfo) -> Self {
        Self { header, info }
    }

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

    /// The lease information, including the ID and the remaining TTL.
    ///
    /// A [`ttl`][LeaseInfo::ttl] of [`None`] indicates the lease has expired.
    pub fn info(&self) -> &LeaseInfo {
        &self.info
    }
}

impl Deref for KeepAliveResponse {
    type Target = LeaseInfo;

    fn deref(&self) -> &LeaseInfo {
        &self.info
    }
}

/// An active lease keep-alive stream.
///
/// Created by [`Client::lease_keeper`]. A `LeaseKeeper` combines a [`KeepAliveStream`] (for
/// receiving responses) and a [`KeepAliveSender`] (for sending keep-alive requests).
///
/// `LeaseKeeper` dereferences to [`KeepAliveStream`], so it can be used directly as a [`Stream`]:
///
/// ```no_run
/// use futures::StreamExt;
/// # async {
/// # let client: etcdrs::Client = todo!();
/// # let lease_id: etcdrs::LeaseId = todo!();
/// let keeper = client.lease_keeper();
/// keeper.keep_alive(lease_id);
/// while let Some(resp) = keeper.next().await {
///     let resp = resp.unwrap();
///     println!("lease {:?} TTL: {:?}", resp.lease_id, resp.ttl);
/// }
/// # };
/// ```
///
/// Use [`into_parts`][Self::into_parts] to split the keeper when you need to send keep-alive
/// requests concurrently with consuming the stream (e.g. from separate tasks).
///
/// ## Cleanup
///
/// Dropping a `LeaseKeeper` closes the underlying gRPC stream. Leases that are no longer
/// refreshed will expire naturally after their TTL.
pub struct LeaseKeeper {
    sender: KeepAliveSender,
    stream: KeepAliveStream,
}

impl LeaseKeeper {
    pub(crate) fn new(sender: KeepAliveSender, stream: KeepAliveStream) -> Self {
        Self { sender, stream }
    }

    /// Split the `LeaseKeeper` into its sender and stream halves.
    ///
    /// This is useful when you need to send keep-alive requests from a different context than
    /// the one consuming responses.
    pub fn into_parts(self) -> (KeepAliveSender, KeepAliveStream) {
        (self.sender, self.stream)
    }

    /// Send a keep-alive request for the given lease.
    ///
    /// See [`KeepAliveSender::keep_alive`] for details.
    pub fn keep_alive(&self, lease_id: LeaseId) {
        self.sender.keep_alive(lease_id);
    }
}

impl Deref for LeaseKeeper {
    type Target = KeepAliveStream;

    fn deref(&self) -> &Self::Target {
        &self.stream
    }
}

impl DerefMut for LeaseKeeper {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.stream
    }
}

impl Stream for LeaseKeeper {
    type Item = Result<KeepAliveResponse, KeepAliveError>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.stream).poll_next(cx)
    }
}

#[cfg(feature = "nightly-async-iterator")]
impl std::async_iter::AsyncIterator for LeaseKeeper {
    type Item = Result<KeepAliveResponse, KeepAliveError>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Stream::poll_next(Pin::new(&mut self.stream), cx)
    }
}

/// The control half of a [`LeaseKeeper`], used to send keep-alive requests.
///
/// Obtained via [`LeaseKeeper::into_parts`]. All methods send requests through the shared gRPC
/// stream. Because the server processes these asynchronously, there is a window between calling
/// [`keep_alive`][Self::keep_alive] and the server responding.
pub struct KeepAliveSender {
    sender: tokio::sync::mpsc::UnboundedSender<etcdserverpb::LeaseKeepAliveRequest>,
}

impl KeepAliveSender {
    pub(crate) fn new(sender: tokio::sync::mpsc::UnboundedSender<etcdserverpb::LeaseKeepAliveRequest>) -> Self {
        Self { sender }
    }

    /// Send a keep-alive request for the given lease.
    ///
    /// The server will respond with a [`KeepAliveResponse`] containing the lease's remaining TTL.
    /// A [`ttl`][LeaseInfo::ttl] of [`None`] indicates the lease has already expired.
    pub fn keep_alive(&self, lease_id: LeaseId) {
        let _ = self
            .sender
            .send(etcdserverpb::LeaseKeepAliveRequest { id: lease_id.get() });
    }
}

/// The response stream half of a [`LeaseKeeper`].
///
/// Obtained via [`LeaseKeeper::into_parts`]. Implements [`Stream`] — use
/// [`StreamExt::next`][futures_core::Stream] or `for await` to consume responses.
pub struct KeepAliveStream {
    inner: Box<dyn Stream<Item = Result<KeepAliveResponse, KeepAliveError>> + Send>,
}

impl KeepAliveStream {
    pub(crate) fn new(inner: impl Stream<Item = Result<KeepAliveResponse, KeepAliveError>> + Send + 'static) -> Self {
        Self { inner: Box::new(inner) }
    }

    fn poll_next_impl(
        self: Pin<&mut Self>,
        cx: &mut Context,
    ) -> Poll<Result<Option<KeepAliveResponse>, KeepAliveError>> {
        let inner = unsafe { self.map_unchecked_mut(|s| s.inner.as_mut()) };
        inner.poll_next(cx).map(|item| match item {
            None => Ok(None),
            Some(Ok(resp)) => Ok(Some(resp)),
            Some(Err(err)) => Err(err),
        })
    }
}

impl Stream for KeepAliveStream {
    type Item = Result<KeepAliveResponse, KeepAliveError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.poll_next_impl(cx).map(Result::transpose)
    }
}

#[cfg(feature = "nightly-async-iterator")]
impl std::async_iter::AsyncIterator for KeepAliveStream {
    type Item = Result<KeepAliveResponse, KeepAliveError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.poll_next_impl(cx).map(Result::transpose)
    }
}

/// The keep-alive requests a [`KeepAliveSender`] sends, shared by every stream its
/// [`LeaseKeeper`] opens.
pub(crate) struct KeepAliveRequests {
    receiver: tokio::sync::mpsc::UnboundedReceiver<etcdserverpb::LeaseKeepAliveRequest>,
    /// The requests taken from `receiver` that etcd has not answered, oldest first.
    unanswered: VecDeque<etcdserverpb::LeaseKeepAliveRequest>,
    /// How many of `unanswered` the current stream has sent.
    sent: usize,
    /// The current stream's number. No other stream may take requests: the transport of a stream
    /// that failed keeps polling it until the server resets the stream.
    stream: u64,
}

impl KeepAliveRequests {
    pub(crate) fn new(receiver: tokio::sync::mpsc::UnboundedReceiver<etcdserverpb::LeaseKeepAliveRequest>) -> Self {
        Self {
            receiver,
            unanswered: VecDeque::new(),
            sent: 0,
            stream: 0,
        }
    }

    /// Record etcd's answer to the oldest request it has not answered. etcd answers keep-alives
    /// one at a time, in the order it receives them.
    pub(crate) fn answered(&mut self) {
        self.unanswered.pop_front();
        self.sent = self
            .sent
            .checked_sub(1)
            .expect("etcd should answer only the keep-alives it was sent");
    }
}

/// The requests of one keep-alive stream: every request etcd has not answered, then new ones.
pub(crate) struct KeepAliveReceiverStream {
    requests: Arc<std::sync::Mutex<KeepAliveRequests>>,
    stream: u64,
}

impl KeepAliveReceiverStream {
    /// Start a new stream, which ends every earlier one.
    pub(crate) fn new(requests: &Arc<std::sync::Mutex<KeepAliveRequests>>) -> Self {
        let mut state = requests.lock().unwrap();
        state.stream += 1;
        state.sent = 0;
        Self {
            requests: requests.clone(),
            stream: state.stream,
        }
    }
}

impl Stream for KeepAliveReceiverStream {
    type Item = etcdserverpb::LeaseKeepAliveRequest;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let mut requests = self.requests.lock().unwrap();
        if requests.stream != self.stream {
            return Poll::Ready(None);
        }
        if requests.sent == requests.unanswered.len() {
            let Some(request) = ready!(requests.receiver.poll_recv(cx)) else {
                return Poll::Ready(None);
            };
            requests.unanswered.push_back(request);
        }
        let request = requests.unanswered[requests.sent];
        requests.sent += 1;
        Poll::Ready(Some(request))
    }
}

/// An enumeration of the [`kind`][KeepAliveError::kind]s of errors that can occur from a
/// keep-alive operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeepAliveErrorKind {
    /// The lease was not found.
    ///
    /// This comes from the gRPC API as `NOT_FOUND`.
    NotFound,
    /// 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 keep-alive operation.
    pub struct KeepAliveError(KeepAliveErrorKind);
}

impl KeepAliveError {
    pub(crate) fn from_status(status: tonic::Status) -> Self {
        let kind = match status.code() {
            tonic::Code::NotFound => KeepAliveErrorKind::NotFound,
            tonic::Code::Unauthenticated => KeepAliveErrorKind::Authentication,
            tonic::Code::PermissionDenied => KeepAliveErrorKind::Authentication,
            tonic::Code::InvalidArgument if ClientInner::is_stale_token_error(&status) => {
                KeepAliveErrorKind::Authentication
            }
            tonic::Code::ResourceExhausted => KeepAliveErrorKind::Exhausted,
            tonic::Code::DataLoss => KeepAliveErrorKind::DataLoss,
            tonic::Code::Unavailable => KeepAliveErrorKind::Unavailable,
            // Don't care who timed us out
            tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => KeepAliveErrorKind::Timeout,
            _ => KeepAliveErrorKind::Unknown,
        };
        Self::new(kind, "", Some(status))
    }
}

const _: () = {
    fn _assert_send<T: Send>() {}
    fn _check() {
        _assert_send::<GrantLeaseFuture>();
        _assert_send::<KeepAliveSender>();
        _assert_send::<KeepAliveStream>();
        _assert_send::<LeaseKeeper>();
        _assert_send::<LeaseTimeToLiveFuture<Result<LeaseTimeToLiveResponse, LeaseTimeToLiveError>>>();
        _assert_send::<LeaseTimeToLiveFuture<Result<LeaseTimeToLiveResponse<WithKeys>, LeaseTimeToLiveError>>>();
        _assert_send::<LeasesFuture>();
    }
};

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

    fn requests() -> (KeepAliveSender, Arc<std::sync::Mutex<KeepAliveRequests>>) {
        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
        let requests = Arc::new(std::sync::Mutex::new(KeepAliveRequests::new(receiver)));
        (KeepAliveSender::new(sender), requests)
    }

    /// The lease ID of the next request `stream` takes.
    fn take(stream: &mut KeepAliveReceiverStream) -> Poll<Option<i64>> {
        let mut cx = Context::from_waker(std::task::Waker::noop());
        Pin::new(stream)
            .poll_next(&mut cx)
            .map(|request| request.map(|request| request.id))
    }

    fn keep_alive(sender: &KeepAliveSender, id: i64) {
        sender.keep_alive(LeaseId::new(id).unwrap());
    }

    /// A stream that failed takes nothing more, and the next sends what etcd never answered before
    /// anything new.
    #[test]
    fn a_new_stream_sends_what_etcd_never_answered_first() {
        let (sender, requests) = requests();
        let mut failed = KeepAliveReceiverStream::new(&requests);
        for id in 1..=3 {
            keep_alive(&sender, id);
        }
        assert_eq!(take(&mut failed), Poll::Ready(Some(1)));
        assert_eq!(take(&mut failed), Poll::Ready(Some(2)));
        requests.lock().unwrap().answered();

        let mut next = KeepAliveReceiverStream::new(&requests);
        // The transport of a failed stream keeps polling it until the server resets the stream.
        assert_eq!(take(&mut failed), Poll::Ready(None));
        keep_alive(&sender, 4);
        assert_eq!(take(&mut next), Poll::Ready(Some(2)));
        assert_eq!(take(&mut next), Poll::Ready(Some(3)));
        assert_eq!(take(&mut next), Poll::Ready(Some(4)));
        assert_eq!(take(&mut next), Poll::Pending);
    }

    /// A stream can fail again before it has sent everything an earlier one left unanswered.
    #[test]
    fn a_stream_that_fails_while_sending_again_keeps_the_order() {
        let (sender, requests) = requests();
        let mut first = KeepAliveReceiverStream::new(&requests);
        for id in 1..=3 {
            keep_alive(&sender, id);
            assert_eq!(take(&mut first), Poll::Ready(Some(id)));
        }

        let mut second = KeepAliveReceiverStream::new(&requests);
        assert_eq!(take(&mut second), Poll::Ready(Some(1)));
        requests.lock().unwrap().answered();
        assert_eq!(take(&mut second), Poll::Ready(Some(2)));

        let mut third = KeepAliveReceiverStream::new(&requests);
        assert_eq!(take(&mut third), Poll::Ready(Some(2)));
        assert_eq!(take(&mut third), Poll::Ready(Some(3)));
        assert_eq!(take(&mut third), Poll::Pending);
    }

    /// Dropping the sender still ends the request stream, once it has sent what etcd never
    /// answered.
    #[test]
    fn dropping_the_sender_ends_the_stream() {
        let (sender, requests) = requests();
        let mut first = KeepAliveReceiverStream::new(&requests);
        keep_alive(&sender, 1);
        assert_eq!(take(&mut first), Poll::Ready(Some(1)));
        drop(sender);

        let mut second = KeepAliveReceiverStream::new(&requests);
        assert_eq!(take(&mut second), Poll::Ready(Some(1)));
        assert_eq!(take(&mut second), Poll::Ready(None));
    }

    /// etcd raises a negative TTL to its minimum, so a TTL past `i64::MAX` seconds must not wrap.
    #[test]
    fn a_ttl_past_i64_max_seconds_saturates() {
        for ttl in [Duration::from_secs(1 << 63), Duration::MAX] {
            let grant = GrantLease::new().ttl(ttl);
            assert_eq!(
                grant.requested_ttl(),
                Some(Duration::from_secs(i64::MAX as u64)),
                "{ttl:?}"
            );
        }
    }

    #[test]
    fn invalid_argument_is_authentication_only_for_token_messages() {
        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 status = || tonic::Status::invalid_argument(message);
            let kinds = [
                format!("{:?}", GrantLeaseError::from_status(status()).kind()),
                format!("{:?}", RevokeLeaseError::from_status(status()).kind()),
                format!("{:?}", LeaseTimeToLiveError::from_status(status()).kind()),
                format!("{:?}", LeasesError::from_status(status()).kind()),
                format!("{:?}", KeepAliveError::from_status(status()).kind()),
            ];
            assert_eq!(kinds, [expected; 5], "{message:?}");
        }
    }
}