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
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
//! Asynchronous client & synchronous client.

use crate::channel::Channel;
use crate::error::{Error, Result};
#[cfg(feature = "tls-openssl")]
use crate::openssl_tls::{self, OpenSslClientConfig, OpenSslConnector};
use crate::rpc::auth::Permission;
use crate::rpc::auth::{AuthClient, AuthDisableResponse, AuthEnableResponse};
use crate::rpc::auth::{
    RoleAddResponse, RoleDeleteResponse, RoleGetResponse, RoleGrantPermissionResponse,
    RoleListResponse, RoleRevokePermissionOptions, RoleRevokePermissionResponse, UserAddOptions,
    UserAddResponse, UserChangePasswordResponse, UserDeleteResponse, UserGetResponse,
    UserGrantRoleResponse, UserListResponse, UserRevokeRoleResponse,
};
use crate::rpc::cluster::{
    ClusterClient, MemberAddOptions, MemberAddResponse, MemberListResponse, MemberPromoteResponse,
    MemberRemoveResponse, MemberUpdateResponse,
};
use crate::rpc::election::{
    CampaignResponse, ElectionClient, LeaderResponse, ObserveStream, ProclaimOptions,
    ProclaimResponse, ResignOptions, ResignResponse,
};
use crate::rpc::kv::{
    CompactionOptions, CompactionResponse, DeleteOptions, DeleteResponse, GetOptions, GetResponse,
    KvClient, PutOptions, PutResponse, Txn, TxnResponse,
};
use crate::rpc::lease::{
    LeaseClient, LeaseGrantOptions, LeaseGrantResponse, LeaseKeepAliveStream, LeaseKeeper,
    LeaseLeasesResponse, LeaseRevokeResponse, LeaseTimeToLiveOptions, LeaseTimeToLiveResponse,
};
use crate::rpc::lock::{LockClient, LockOptions, LockResponse, UnlockResponse};
use crate::rpc::maintenance::{
    AlarmAction, AlarmOptions, AlarmResponse, AlarmType, DefragmentResponse, HashKvResponse,
    HashResponse, MaintenanceClient, MoveLeaderResponse, SnapshotStreaming, StatusResponse,
};
use crate::rpc::watch::{WatchClient, WatchOptions, WatchStream, Watcher};
#[cfg(feature = "tls-openssl")]
use crate::OpenSslResult;
#[cfg(feature = "tls")]
use crate::TlsOptions;
use http::uri::Uri;

use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc::Sender;

use tonic::transport::Endpoint;

use tower::discover::Change;

const HTTP_PREFIX: &str = "http://";
const HTTPS_PREFIX: &str = "https://";

/// Asynchronous `etcd` client using v3 API.
#[derive(Clone)]
pub struct Client {
    kv: KvClient,
    watch: WatchClient,
    lease: LeaseClient,
    lock: LockClient,
    auth: AuthClient,
    maintenance: MaintenanceClient,
    cluster: ClusterClient,
    election: ElectionClient,
    options: Option<ConnectOptions>,
    tx: Sender<Change<Uri, Endpoint>>,
}

impl Client {
    /// Connect to `etcd` servers from given `endpoints`.
    pub async fn connect<E: AsRef<str>, S: AsRef<[E]>>(
        endpoints: S,
        options: Option<ConnectOptions>,
    ) -> Result<Self> {
        let endpoints = {
            let mut eps = Vec::new();
            for e in endpoints.as_ref() {
                let channel = Self::build_endpoint(e.as_ref(), &options)?;
                eps.push(channel);
            }
            eps
        };

        if endpoints.is_empty() {
            return Err(Error::InvalidArgs(String::from("empty endpoints")));
        }

        // Always use balance strategy even if there is only one endpoint.
        #[cfg(not(feature = "tls-openssl"))]
        let (channel, tx) = Channel::balance_channel(64);
        #[cfg(feature = "tls-openssl")]
        let (channel, tx) = openssl_tls::balanced_channel(
            options
                .clone()
                .and_then(|o| o.otls)
                .unwrap_or_else(OpenSslConnector::create_default)?,
        )?;
        for endpoint in endpoints {
            // The rx inside `channel` won't be closed or dropped here
            tx.send(Change::Insert(endpoint.uri().clone(), endpoint))
                .await
                .unwrap();
        }

        let mut options = options;
        let auth_token = Self::auth(channel.clone(), &mut options).await?;
        Ok(Self::build_client(channel, tx, auth_token, options))
    }

    fn build_endpoint(url: &str, options: &Option<ConnectOptions>) -> Result<Endpoint> {
        #[cfg(feature = "tls-openssl")]
        use tonic::transport::Channel;
        let mut endpoint = if url.starts_with(HTTP_PREFIX) {
            #[cfg(feature = "tls")]
            if let Some(connect_options) = options {
                if connect_options.tls.is_some() {
                    return Err(Error::InvalidArgs(String::from(
                        "TLS options are only supported with HTTPS URLs",
                    )));
                }
            }

            Channel::builder(url.parse()?)
        } else if url.starts_with(HTTPS_PREFIX) {
            #[cfg(not(any(feature = "tls", feature = "tls-openssl")))]
            return Err(Error::InvalidArgs(String::from(
                "HTTPS URLs are only supported with the feature \"tls\"",
            )));

            #[cfg(all(feature = "tls-openssl", not(feature = "tls")))]
            {
                Channel::builder(url.parse()?)
            }

            #[cfg(feature = "tls")]
            {
                let tls = if let Some(connect_options) = options {
                    connect_options.tls.clone()
                } else {
                    None
                }
                .unwrap_or_else(TlsOptions::new);

                Channel::builder(url.parse()?).tls_config(tls)?
            }
        } else {
            #[cfg(feature = "tls")]
            {
                let tls = if let Some(connect_options) = options {
                    connect_options.tls.clone()
                } else {
                    None
                };

                match tls {
                    Some(tls) => {
                        let e = HTTPS_PREFIX.to_owned() + url;
                        Channel::builder(e.parse()?).tls_config(tls)?
                    }
                    None => {
                        let e = HTTP_PREFIX.to_owned() + url;
                        Channel::builder(e.parse()?)
                    }
                }
            }

            #[cfg(all(feature = "tls-openssl", not(feature = "tls")))]
            {
                let pfx = if options.as_ref().and_then(|o| o.otls.as_ref()).is_some() {
                    HTTPS_PREFIX
                } else {
                    HTTP_PREFIX
                };
                let e = pfx.to_owned() + url;
                Channel::builder(e.parse()?)
            }

            #[cfg(all(not(feature = "tls"), not(feature = "tls-openssl")))]
            {
                let e = HTTP_PREFIX.to_owned() + url;
                Channel::builder(e.parse()?)
            }
        };

        if let Some(opts) = options {
            if let Some((interval, timeout)) = opts.keep_alive {
                endpoint = endpoint
                    .keep_alive_while_idle(opts.keep_alive_while_idle)
                    .http2_keep_alive_interval(interval)
                    .keep_alive_timeout(timeout);
            }

            if let Some(timeout) = opts.timeout {
                endpoint = endpoint.timeout(timeout);
            }

            if let Some(timeout) = opts.connect_timeout {
                endpoint = endpoint.connect_timeout(timeout);
            }
        }

        Ok(endpoint)
    }

    async fn auth(
        channel: Channel,
        options: &mut Option<ConnectOptions>,
    ) -> Result<Option<Arc<http::HeaderValue>>> {
        let user = match options {
            None => return Ok(None),
            Some(opt) => {
                // Take away the user, the password should not be stored in client.
                opt.user.take()
            }
        };

        if let Some((name, password)) = user {
            let mut tmp_auth = AuthClient::new(channel, None);
            let resp = tmp_auth.authenticate(name, password).await?;
            Ok(Some(Arc::new(resp.token().parse()?)))
        } else {
            Ok(None)
        }
    }

    fn build_client(
        channel: Channel,
        tx: Sender<Change<Uri, Endpoint>>,
        auth_token: Option<Arc<http::HeaderValue>>,
        options: Option<ConnectOptions>,
    ) -> Self {
        let kv = KvClient::new(channel.clone(), auth_token.clone());
        let watch = WatchClient::new(channel.clone(), auth_token.clone());
        let lease = LeaseClient::new(channel.clone(), auth_token.clone());
        let lock = LockClient::new(channel.clone(), auth_token.clone());
        let auth = AuthClient::new(channel.clone(), auth_token.clone());
        let cluster = ClusterClient::new(channel.clone(), auth_token.clone());
        let maintenance = MaintenanceClient::new(channel.clone(), auth_token.clone());
        let election = ElectionClient::new(channel, auth_token);

        Self {
            kv,
            watch,
            lease,
            lock,
            auth,
            maintenance,
            cluster,
            election,
            options,
            tx,
        }
    }

    /// Dynamically add an endpoint to the client.
    ///
    /// Which can be used to add a new member to the underlying balance cache.
    /// The typical scenario is that application can use a services discovery
    /// to discover the member list changes and add/remove them to/from the client.
    ///
    /// Note that the [`Client`] doesn't check the authentication before added.
    /// So the etcd member of the added endpoint REQUIRES to use the same auth
    /// token as when create the client. Otherwise, the underlying balance
    /// services will not be able to connect to the new endpoint.
    #[inline]
    pub async fn add_endpoint<E: AsRef<str>>(&self, endpoint: E) -> Result<()> {
        let endpoint = Self::build_endpoint(endpoint.as_ref(), &self.options)?;
        let tx = &self.tx;
        tx.send(Change::Insert(endpoint.uri().clone(), endpoint))
            .await
            .map_err(|e| Error::EndpointError(format!("failed to add endpoint because of {}", e)))
    }

    /// Dynamically remove an endpoint from the client.
    ///
    /// Note that the `endpoint` str should be the same as it was added.
    /// And the underlying balance services cache used the hash from the Uri,
    /// which was parsed from `endpoint` str, to do the equality comparisons.
    #[inline]
    pub async fn remove_endpoint<E: AsRef<str>>(&self, endpoint: E) -> Result<()> {
        let uri = http::Uri::from_str(endpoint.as_ref())?;
        let tx = &self.tx;
        tx.send(Change::Remove(uri)).await.map_err(|e| {
            Error::EndpointError(format!("failed to remove endpoint because of {}", e))
        })
    }

    /// Gets a KV client.
    #[inline]
    pub fn kv_client(&self) -> KvClient {
        self.kv.clone()
    }

    /// Gets a watch client.
    #[inline]
    pub fn watch_client(&self) -> WatchClient {
        self.watch.clone()
    }

    /// Gets a lease client.
    #[inline]
    pub fn lease_client(&self) -> LeaseClient {
        self.lease.clone()
    }

    /// Gets an auth client.
    #[inline]
    pub fn auth_client(&self) -> AuthClient {
        self.auth.clone()
    }

    /// Gets a maintenance client.
    #[inline]
    pub fn maintenance_client(&self) -> MaintenanceClient {
        self.maintenance.clone()
    }

    /// Gets a cluster client.
    #[inline]
    pub fn cluster_client(&self) -> ClusterClient {
        self.cluster.clone()
    }

    /// Gets a lock client.
    #[inline]
    pub fn lock_client(&self) -> LockClient {
        self.lock.clone()
    }

    /// Gets a election client.
    #[inline]
    pub fn election_client(&self) -> ElectionClient {
        self.election.clone()
    }

    /// Put the given key into the key-value store.
    /// A put request increments the revision of the key-value store
    /// and generates one event in the event history.
    #[inline]
    pub async fn put(
        &mut self,
        key: impl Into<Vec<u8>>,
        value: impl Into<Vec<u8>>,
        options: Option<PutOptions>,
    ) -> Result<PutResponse> {
        self.kv.put(key, value, options).await
    }

    /// Gets the key from the key-value store.
    #[inline]
    pub async fn get(
        &mut self,
        key: impl Into<Vec<u8>>,
        options: Option<GetOptions>,
    ) -> Result<GetResponse> {
        self.kv.get(key, options).await
    }

    /// Deletes the given key from the key-value store.
    #[inline]
    pub async fn delete(
        &mut self,
        key: impl Into<Vec<u8>>,
        options: Option<DeleteOptions>,
    ) -> Result<DeleteResponse> {
        self.kv.delete(key, options).await
    }

    /// Compacts the event history in the etcd key-value store. The key-value
    /// store should be periodically compacted or the event history will continue to grow
    /// indefinitely.
    #[inline]
    pub async fn compact(
        &mut self,
        revision: i64,
        options: Option<CompactionOptions>,
    ) -> Result<CompactionResponse> {
        self.kv.compact(revision, options).await
    }

    /// Processes multiple operations in a single transaction.
    /// A txn request increments the revision of the key-value store
    /// and generates events with the same revision for every completed operation.
    /// It is not allowed to modify the same key several times within one txn.
    #[inline]
    pub async fn txn(&mut self, txn: Txn) -> Result<TxnResponse> {
        self.kv.txn(txn).await
    }

    /// Watches for events happening or that have happened. Both input and output
    /// are streams; the input stream is for creating and canceling watcher and the output
    /// stream sends events. The entire event history can be watched starting from the
    /// last compaction revision.
    #[inline]
    pub async fn watch(
        &mut self,
        key: impl Into<Vec<u8>>,
        options: Option<WatchOptions>,
    ) -> Result<(Watcher, WatchStream)> {
        self.watch.watch(key, options).await
    }

    /// Creates a lease which expires if the server does not receive a keepAlive
    /// within a given time to live period. All keys attached to the lease will be expired and
    /// deleted if the lease expires. Each expired key generates a delete event in the event history.
    #[inline]
    pub async fn lease_grant(
        &mut self,
        ttl: i64,
        options: Option<LeaseGrantOptions>,
    ) -> Result<LeaseGrantResponse> {
        self.lease.grant(ttl, options).await
    }

    /// Revokes a lease. All keys attached to the lease will expire and be deleted.
    #[inline]
    pub async fn lease_revoke(&mut self, id: i64) -> Result<LeaseRevokeResponse> {
        self.lease.revoke(id).await
    }

    /// Keeps the lease alive by streaming keep alive requests from the client
    /// to the server and streaming keep alive responses from the server to the client.
    #[inline]
    pub async fn lease_keep_alive(
        &mut self,
        id: i64,
    ) -> Result<(LeaseKeeper, LeaseKeepAliveStream)> {
        self.lease.keep_alive(id).await
    }

    /// Retrieves lease information.
    #[inline]
    pub async fn lease_time_to_live(
        &mut self,
        id: i64,
        options: Option<LeaseTimeToLiveOptions>,
    ) -> Result<LeaseTimeToLiveResponse> {
        self.lease.time_to_live(id, options).await
    }

    /// Lists all existing leases.
    #[inline]
    pub async fn leases(&mut self) -> Result<LeaseLeasesResponse> {
        self.lease.leases().await
    }

    /// Lock acquires a distributed shared lock on a given named lock.
    /// On success, it will return a unique key that exists so long as the
    /// lock is held by the caller. This key can be used in conjunction with
    /// transactions to safely ensure updates to etcd only occur while holding
    /// lock ownership. The lock is held until Unlock is called on the key or the
    /// lease associate with the owner expires.
    #[inline]
    pub async fn lock(
        &mut self,
        name: impl Into<Vec<u8>>,
        options: Option<LockOptions>,
    ) -> Result<LockResponse> {
        self.lock.lock(name, options).await
    }

    /// Unlock takes a key returned by Lock and releases the hold on lock. The
    /// next Lock caller waiting for the lock will then be woken up and given
    /// ownership of the lock.
    #[inline]
    pub async fn unlock(&mut self, key: impl Into<Vec<u8>>) -> Result<UnlockResponse> {
        self.lock.unlock(key).await
    }

    /// Enables authentication.
    #[inline]
    pub async fn auth_enable(&mut self) -> Result<AuthEnableResponse> {
        self.auth.auth_enable().await
    }

    /// Disables authentication.
    #[inline]
    pub async fn auth_disable(&mut self) -> Result<AuthDisableResponse> {
        self.auth.auth_disable().await
    }

    /// Adds role.
    #[inline]
    pub async fn role_add(&mut self, name: impl Into<String>) -> Result<RoleAddResponse> {
        self.auth.role_add(name).await
    }

    /// Deletes role.
    #[inline]
    pub async fn role_delete(&mut self, name: impl Into<String>) -> Result<RoleDeleteResponse> {
        self.auth.role_delete(name).await
    }

    /// Gets role.
    #[inline]
    pub async fn role_get(&mut self, name: impl Into<String>) -> Result<RoleGetResponse> {
        self.auth.role_get(name).await
    }

    /// Lists role.
    #[inline]
    pub async fn role_list(&mut self) -> Result<RoleListResponse> {
        self.auth.role_list().await
    }

    /// Grants role permission.
    #[inline]
    pub async fn role_grant_permission(
        &mut self,
        name: impl Into<String>,
        perm: Permission,
    ) -> Result<RoleGrantPermissionResponse> {
        self.auth.role_grant_permission(name, perm).await
    }

    /// Revokes role permission.
    #[inline]
    pub async fn role_revoke_permission(
        &mut self,
        name: impl Into<String>,
        key: impl Into<Vec<u8>>,
        options: Option<RoleRevokePermissionOptions>,
    ) -> Result<RoleRevokePermissionResponse> {
        self.auth.role_revoke_permission(name, key, options).await
    }

    /// Add an user.
    #[inline]
    pub async fn user_add(
        &mut self,
        name: impl Into<String>,
        password: impl Into<String>,
        options: Option<UserAddOptions>,
    ) -> Result<UserAddResponse> {
        self.auth.user_add(name, password, options).await
    }

    /// Gets the user info by the user name.
    #[inline]
    pub async fn user_get(&mut self, name: impl Into<String>) -> Result<UserGetResponse> {
        self.auth.user_get(name).await
    }

    /// Lists all users.
    #[inline]
    pub async fn user_list(&mut self) -> Result<UserListResponse> {
        self.auth.user_list().await
    }

    /// Deletes the given key from the key-value store.
    #[inline]
    pub async fn user_delete(&mut self, name: impl Into<String>) -> Result<UserDeleteResponse> {
        self.auth.user_delete(name).await
    }

    /// Change password for an user.
    #[inline]
    pub async fn user_change_password(
        &mut self,
        name: impl Into<String>,
        password: impl Into<String>,
    ) -> Result<UserChangePasswordResponse> {
        self.auth.user_change_password(name, password).await
    }

    /// Grant role for an user.
    #[inline]
    pub async fn user_grant_role(
        &mut self,
        user: impl Into<String>,
        role: impl Into<String>,
    ) -> Result<UserGrantRoleResponse> {
        self.auth.user_grant_role(user, role).await
    }

    /// Revoke role for an user.
    #[inline]
    pub async fn user_revoke_role(
        &mut self,
        user: impl Into<String>,
        role: impl Into<String>,
    ) -> Result<UserRevokeRoleResponse> {
        self.auth.user_revoke_role(user, role).await
    }

    /// Maintain(get, active or inactive) alarms of members.
    #[inline]
    pub async fn alarm(
        &mut self,
        alarm_action: AlarmAction,
        alarm_type: AlarmType,
        options: Option<AlarmOptions>,
    ) -> Result<AlarmResponse> {
        self.maintenance
            .alarm(alarm_action, alarm_type, options)
            .await
    }

    /// Gets the status of a member.
    #[inline]
    pub async fn status(&mut self) -> Result<StatusResponse> {
        self.maintenance.status().await
    }

    /// Defragments a member's backend database to recover storage space.
    #[inline]
    pub async fn defragment(&mut self) -> Result<DefragmentResponse> {
        self.maintenance.defragment().await
    }

    /// Computes the hash of whole backend keyspace.
    /// including key, lease, and other buckets in storage.
    /// This is designed for testing ONLY!
    #[inline]
    pub async fn hash(&mut self) -> Result<HashResponse> {
        self.maintenance.hash().await
    }

    /// Computes the hash of all MVCC keys up to a given revision.
    /// It only iterates \"key\" bucket in backend storage.
    #[inline]
    pub async fn hash_kv(&mut self, revision: i64) -> Result<HashKvResponse> {
        self.maintenance.hash_kv(revision).await
    }

    /// Gets a snapshot of the entire backend from a member over a stream to a client.
    #[inline]
    pub async fn snapshot(&mut self) -> Result<SnapshotStreaming> {
        self.maintenance.snapshot().await
    }

    /// Adds current connected server as a member.
    #[inline]
    pub async fn member_add<E: AsRef<str>, S: AsRef<[E]>>(
        &mut self,
        urls: S,
        options: Option<MemberAddOptions>,
    ) -> Result<MemberAddResponse> {
        let mut eps = Vec::new();
        for e in urls.as_ref() {
            let e = e.as_ref();
            let url = if e.starts_with(HTTP_PREFIX) || e.starts_with(HTTPS_PREFIX) {
                e.to_string()
            } else {
                HTTP_PREFIX.to_owned() + e
            };
            eps.push(url);
        }

        self.cluster.member_add(eps, options).await
    }

    /// Remove a member.
    #[inline]
    pub async fn member_remove(&mut self, id: u64) -> Result<MemberRemoveResponse> {
        self.cluster.member_remove(id).await
    }

    /// Updates the member.
    #[inline]
    pub async fn member_update(
        &mut self,
        id: u64,
        url: impl Into<Vec<String>>,
    ) -> Result<MemberUpdateResponse> {
        self.cluster.member_update(id, url).await
    }

    /// Promotes the member.
    #[inline]
    pub async fn member_promote(&mut self, id: u64) -> Result<MemberPromoteResponse> {
        self.cluster.member_promote(id).await
    }

    /// Lists members.
    #[inline]
    pub async fn member_list(&mut self) -> Result<MemberListResponse> {
        self.cluster.member_list().await
    }

    /// Moves the current leader node to target node.
    #[inline]
    pub async fn move_leader(&mut self, target_id: u64) -> Result<MoveLeaderResponse> {
        self.maintenance.move_leader(target_id).await
    }

    /// Puts a value as eligible for the election on the prefix key.
    /// Multiple sessions can participate in the election for the
    /// same prefix, but only one can be the leader at a time.
    #[inline]
    pub async fn campaign(
        &mut self,
        name: impl Into<Vec<u8>>,
        value: impl Into<Vec<u8>>,
        lease: i64,
    ) -> Result<CampaignResponse> {
        self.election.campaign(name, value, lease).await
    }

    /// Lets the leader announce a new value without another election.
    #[inline]
    pub async fn proclaim(
        &mut self,
        value: impl Into<Vec<u8>>,
        options: Option<ProclaimOptions>,
    ) -> Result<ProclaimResponse> {
        self.election.proclaim(value, options).await
    }

    /// Returns the leader value for the current election.
    #[inline]
    pub async fn leader(&mut self, name: impl Into<Vec<u8>>) -> Result<LeaderResponse> {
        self.election.leader(name).await
    }

    /// Returns a channel that reliably observes ordered leader proposals
    /// as GetResponse values on every current elected leader key.
    #[inline]
    pub async fn observe(&mut self, name: impl Into<Vec<u8>>) -> Result<ObserveStream> {
        self.election.observe(name).await
    }

    /// Releases election leadership and then start a new election
    #[inline]
    pub async fn resign(&mut self, option: Option<ResignOptions>) -> Result<ResignResponse> {
        self.election.resign(option).await
    }
}

/// Options for `Connect` operation.
#[derive(Debug, Default, Clone)]
pub struct ConnectOptions {
    /// user is a pair values of name and password
    user: Option<(String, String)>,
    /// HTTP2 keep-alive: (keep_alive_interval, keep_alive_timeout)
    keep_alive: Option<(Duration, Duration)>,
    /// Whether send keep alive pings even there are no active streams.
    keep_alive_while_idle: bool,
    /// Apply a timeout to each gRPC request.
    timeout: Option<Duration>,
    /// Apply a timeout to connecting to the endpoint.
    connect_timeout: Option<Duration>,
    #[cfg(feature = "tls")]
    tls: Option<TlsOptions>,
    #[cfg(feature = "tls-openssl")]
    otls: Option<OpenSslResult<OpenSslConnector>>,
}

impl ConnectOptions {
    /// name is the identifier for the distributed shared lock to be acquired.
    #[inline]
    pub fn with_user(mut self, name: impl Into<String>, password: impl Into<String>) -> Self {
        self.user = Some((name.into(), password.into()));
        self
    }

    /// Sets TLS options.
    ///
    /// Notes that this function have to work with `HTTPS` URLs.
    #[cfg_attr(docsrs, doc(cfg(feature = "tls")))]
    #[cfg(feature = "tls")]
    #[inline]
    pub fn with_tls(mut self, tls: TlsOptions) -> Self {
        self.tls = Some(tls);
        self
    }

    /// Sets TLS options, however using the OpenSSL implementation.
    #[cfg_attr(docsrs, doc(cfg(feature = "tls-openssl")))]
    #[cfg(feature = "tls-openssl")]
    #[inline]
    pub fn with_openssl_tls(mut self, otls: OpenSslClientConfig) -> Self {
        // NOTE1: Perhaps we can unify the essential TLS config terms by something like `TlsBuilder`?
        //
        // NOTE2: we delay the checking at connection step to keep consistency with tonic, however would
        // things be better if we validate the config at here?
        self.otls = Some(otls.build());
        self
    }

    /// Enable HTTP2 keep-alive with `interval` and `timeout`.
    #[inline]
    pub fn with_keep_alive(mut self, interval: Duration, timeout: Duration) -> Self {
        self.keep_alive = Some((interval, timeout));
        self
    }

    /// Apply a timeout to each request.
    #[inline]
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Apply a timeout to connecting to the endpoint.
    #[inline]
    pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = Some(timeout);
        self
    }

    /// Whether send keep alive pings even there are no active requests.
    /// If disabled, keep-alive pings are only sent while there are opened request/response streams.
    /// If enabled, pings are also sent when no streams are active.
    /// NOTE: Some implementations of gRPC server may send GOAWAY if there are too many pings.
    ///       This would be useful if you meet some error like `too many pings`.
    #[inline]
    pub fn with_keep_alive_while_idle(mut self, enabled: bool) -> Self {
        self.keep_alive_while_idle = enabled;
        self
    }

    /// Creates a `ConnectOptions`.
    #[inline]
    pub const fn new() -> Self {
        ConnectOptions {
            user: None,
            keep_alive: None,
            keep_alive_while_idle: true,
            timeout: None,
            connect_timeout: None,
            #[cfg(feature = "tls")]
            tls: None,
            #[cfg(feature = "tls-openssl")]
            otls: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Compare, CompareOp, EventType, PermissionType, TxnOp, TxnOpResponse};

    const DEFAULT_TEST_ENDPOINT: &str = "localhost:2379";

    /// Get client for testing.
    async fn get_client() -> Result<Client> {
        Client::connect([DEFAULT_TEST_ENDPOINT], None).await
    }

    #[tokio::test]
    async fn test_put() -> Result<()> {
        let mut client = get_client().await?;
        client.put("put", "123", None).await?;

        // overwrite with prev key
        {
            let resp = client
                .put("put", "456", Some(PutOptions::new().with_prev_key()))
                .await?;
            let prev_key = resp.prev_key();
            assert!(prev_key.is_some());
            let prev_key = prev_key.unwrap();
            assert_eq!(prev_key.key(), b"put");
            assert_eq!(prev_key.value(), b"123");
        }

        // overwrite again with prev key
        {
            let resp = client
                .put("put", "789", Some(PutOptions::new().with_prev_key()))
                .await?;
            let prev_key = resp.prev_key();
            assert!(prev_key.is_some());
            let prev_key = prev_key.unwrap();
            assert_eq!(prev_key.key(), b"put");
            assert_eq!(prev_key.value(), b"456");
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_get() -> Result<()> {
        let mut client = get_client().await?;
        client.put("get10", "10", None).await?;
        client.put("get11", "11", None).await?;
        client.put("get20", "20", None).await?;
        client.put("get21", "21", None).await?;

        // get key
        {
            let resp = client.get("get11", None).await?;
            assert_eq!(resp.count(), 1);
            assert!(!resp.more());
            assert_eq!(resp.kvs().len(), 1);
            assert_eq!(resp.kvs()[0].key(), b"get11");
            assert_eq!(resp.kvs()[0].value(), b"11");
        }

        // get from key
        {
            let resp = client
                .get(
                    "get11",
                    Some(GetOptions::new().with_from_key().with_limit(2)),
                )
                .await?;
            assert!(resp.more());
            assert_eq!(resp.kvs().len(), 2);
            assert_eq!(resp.kvs()[0].key(), b"get11");
            assert_eq!(resp.kvs()[0].value(), b"11");
            assert_eq!(resp.kvs()[1].key(), b"get20");
            assert_eq!(resp.kvs()[1].value(), b"20");
        }

        // get prefix keys
        {
            let resp = client
                .get("get1", Some(GetOptions::new().with_prefix()))
                .await?;
            assert_eq!(resp.count(), 2);
            assert!(!resp.more());
            assert_eq!(resp.kvs().len(), 2);
            assert_eq!(resp.kvs()[0].key(), b"get10");
            assert_eq!(resp.kvs()[0].value(), b"10");
            assert_eq!(resp.kvs()[1].key(), b"get11");
            assert_eq!(resp.kvs()[1].value(), b"11");
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_delete() -> Result<()> {
        let mut client = get_client().await?;
        client.put("del10", "10", None).await?;
        client.put("del11", "11", None).await?;
        client.put("del20", "20", None).await?;
        client.put("del21", "21", None).await?;
        client.put("del31", "31", None).await?;
        client.put("del32", "32", None).await?;

        // delete key
        {
            let resp = client.delete("del11", None).await?;
            assert_eq!(resp.deleted(), 1);
            let resp = client
                .get("del11", Some(GetOptions::new().with_count_only()))
                .await?;
            assert_eq!(resp.count(), 0);
        }

        // delete a range of keys
        {
            let resp = client
                .delete("del11", Some(DeleteOptions::new().with_range("del22")))
                .await?;
            assert_eq!(resp.deleted(), 2);
            let resp = client
                .get(
                    "del11",
                    Some(GetOptions::new().with_range("del22").with_count_only()),
                )
                .await?;
            assert_eq!(resp.count(), 0);
        }

        // delete key with prefix
        {
            let resp = client
                .delete("del3", Some(DeleteOptions::new().with_prefix()))
                .await?;
            assert_eq!(resp.deleted(), 2);
            let resp = client
                .get("del32", Some(GetOptions::new().with_count_only()))
                .await?;
            assert_eq!(resp.count(), 0);
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_compact() -> Result<()> {
        let mut client = get_client().await?;
        let rev0 = client
            .put("compact", "0", None)
            .await?
            .header()
            .unwrap()
            .revision();
        let rev1 = client
            .put("compact", "1", None)
            .await?
            .header()
            .unwrap()
            .revision();

        // before compacting
        let rev0_resp = client
            .get("compact", Some(GetOptions::new().with_revision(rev0)))
            .await?;
        assert_eq!(rev0_resp.kvs()[0].value(), b"0");
        let rev1_resp = client
            .get("compact", Some(GetOptions::new().with_revision(rev1)))
            .await?;
        assert_eq!(rev1_resp.kvs()[0].value(), b"1");

        client.compact(rev1, None).await?;

        // after compacting
        let result = client
            .get("compact", Some(GetOptions::new().with_revision(rev0)))
            .await;
        assert!(result.is_err());
        let rev1_resp = client
            .get("compact", Some(GetOptions::new().with_revision(rev1)))
            .await?;
        assert_eq!(rev1_resp.kvs()[0].value(), b"1");

        Ok(())
    }

    #[tokio::test]
    async fn test_txn() -> Result<()> {
        let mut client = get_client().await?;
        client.put("txn01", "01", None).await?;

        // transaction 1
        {
            let resp = client
                .txn(
                    Txn::new()
                        .when(&[Compare::value("txn01", CompareOp::Equal, "01")][..])
                        .and_then(
                            &[TxnOp::put(
                                "txn01",
                                "02",
                                Some(PutOptions::new().with_prev_key()),
                            )][..],
                        )
                        .or_else(&[TxnOp::get("txn01", None)][..]),
                )
                .await?;

            assert!(resp.succeeded());
            let op_responses = resp.op_responses();
            assert_eq!(op_responses.len(), 1);

            match op_responses[0] {
                TxnOpResponse::Put(ref resp) => assert_eq!(resp.prev_key().unwrap().value(), b"01"),
                _ => panic!("unexpected response"),
            }

            let resp = client.get("txn01", None).await?;
            assert_eq!(resp.kvs()[0].key(), b"txn01");
            assert_eq!(resp.kvs()[0].value(), b"02");
        }

        // transaction 2
        {
            let resp = client
                .txn(
                    Txn::new()
                        .when(&[Compare::value("txn01", CompareOp::Equal, "01")][..])
                        .and_then(&[TxnOp::put("txn01", "02", None)][..])
                        .or_else(&[TxnOp::get("txn01", None)][..]),
                )
                .await?;

            assert!(!resp.succeeded());
            let op_responses = resp.op_responses();
            assert_eq!(op_responses.len(), 1);

            match op_responses[0] {
                TxnOpResponse::Get(ref resp) => assert_eq!(resp.kvs()[0].value(), b"02"),
                _ => panic!("unexpected response"),
            }
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_watch() -> Result<()> {
        let mut client = get_client().await?;

        let (mut watcher, mut stream) = client.watch("watch01", None).await?;

        client.put("watch01", "01", None).await?;

        let resp = stream.message().await?.unwrap();
        assert_eq!(resp.watch_id(), watcher.watch_id());
        assert_eq!(resp.events().len(), 1);

        let kv = resp.events()[0].kv().unwrap();
        assert_eq!(kv.key(), b"watch01");
        assert_eq!(kv.value(), b"01");
        assert_eq!(resp.events()[0].event_type(), EventType::Put);

        watcher.cancel().await?;

        let resp = stream.message().await?.unwrap();
        assert_eq!(resp.watch_id(), watcher.watch_id());
        assert!(resp.canceled());

        Ok(())
    }

    #[tokio::test]
    async fn test_grant_revoke() -> Result<()> {
        let mut client = get_client().await?;
        let resp = client.lease_grant(123, None).await?;
        assert_eq!(resp.ttl(), 123);
        let id = resp.id();
        client.lease_revoke(id).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_keep_alive() -> Result<()> {
        let mut client = get_client().await?;

        let resp = client.lease_grant(60, None).await?;
        assert_eq!(resp.ttl(), 60);
        let id = resp.id();

        let (mut keeper, mut stream) = client.lease_keep_alive(id).await?;
        keeper.keep_alive().await?;

        let resp = stream.message().await?.unwrap();
        assert_eq!(resp.id(), keeper.id());
        assert_eq!(resp.ttl(), 60);

        client.lease_revoke(id).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_time_to_live() -> Result<()> {
        let mut client = get_client().await?;
        let leaseid = 200;
        let resp = client
            .lease_grant(60, Some(LeaseGrantOptions::new().with_id(leaseid)))
            .await?;
        assert_eq!(resp.ttl(), 60);
        assert_eq!(resp.id(), leaseid);

        let resp = client.lease_time_to_live(leaseid, None).await?;
        assert_eq!(resp.id(), leaseid);
        assert_eq!(resp.granted_ttl(), 60);

        client.lease_revoke(leaseid).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_leases() -> Result<()> {
        let lease1 = 100;
        let lease2 = 101;
        let lease3 = 102;

        let mut client = get_client().await?;
        let resp = client
            .lease_grant(60, Some(LeaseGrantOptions::new().with_id(lease1)))
            .await?;
        assert_eq!(resp.ttl(), 60);
        assert_eq!(resp.id(), lease1);

        let resp = client
            .lease_grant(60, Some(LeaseGrantOptions::new().with_id(lease2)))
            .await?;
        assert_eq!(resp.ttl(), 60);
        assert_eq!(resp.id(), lease2);

        let resp = client
            .lease_grant(60, Some(LeaseGrantOptions::new().with_id(lease3)))
            .await?;
        assert_eq!(resp.ttl(), 60);
        assert_eq!(resp.id(), lease3);

        let resp = client.leases().await?;
        let leases: Vec<_> = resp.leases().iter().map(|status| status.id()).collect();
        assert!(leases.contains(&lease1));
        assert!(leases.contains(&lease2));
        assert!(leases.contains(&lease3));

        client.lease_revoke(lease1).await?;
        client.lease_revoke(lease2).await?;
        client.lease_revoke(lease3).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_lock() -> Result<()> {
        let mut client = get_client().await?;
        let resp = client.lock("lock-test", None).await?;
        let key = resp.key();
        let key_str = std::str::from_utf8(key)?;
        assert!(key_str.starts_with("lock-test/"));

        client.unlock(key).await?;
        Ok(())
    }

    #[ignore]
    #[tokio::test]
    async fn test_auth() -> Result<()> {
        let mut client = get_client().await?;
        client.auth_enable().await?;

        // after enable auth, must operate by authenticated client
        client.put("auth-test", "value", None).await.unwrap_err();

        // connect with authenticate, the user must already exists
        let options = Some(ConnectOptions::new().with_user(
            "root",    // user name
            "rootpwd", // password
        ));
        let mut client_auth = Client::connect(["localhost:2379"], options).await?;
        client_auth.put("auth-test", "value", None).await?;

        client_auth.auth_disable().await?;

        // after disable auth, operate ok
        let mut client = get_client().await?;
        client.put("auth-test", "value", None).await?;

        Ok(())
    }

    #[tokio::test]
    async fn test_role() -> Result<()> {
        let mut client = get_client().await?;

        let role1 = "role1";
        let role2 = "role2";

        let _ = client.role_delete(role1).await;
        let _ = client.role_delete(role2).await;

        client.role_add(role1).await?;

        client.role_get(role1).await?;

        client.role_delete(role1).await?;
        client.role_get(role1).await.unwrap_err();

        client.role_add(role2).await?;
        client.role_get(role2).await?;

        {
            let resp = client.role_list().await?;
            assert!(resp.roles().contains(&role2.to_string()));
        }

        client
            .role_grant_permission(role2, Permission::read("123"))
            .await?;
        client
            .role_grant_permission(role2, Permission::write("abc").with_from_key())
            .await?;
        client
            .role_grant_permission(role2, Permission::read_write("hi").with_range_end("hjj"))
            .await?;
        client
            .role_grant_permission(
                role2,
                Permission::new(PermissionType::Write, "pp").with_prefix(),
            )
            .await?;
        client
            .role_grant_permission(
                role2,
                Permission::new(PermissionType::Read, "xyz").with_all_keys(),
            )
            .await?;

        {
            let resp = client.role_get(role2).await?;
            let permissions = resp.permissions();
            assert!(permissions.contains(&Permission::read("123")));
            assert!(permissions.contains(&Permission::write("abc").with_from_key()));
            assert!(permissions.contains(&Permission::read_write("hi").with_range_end("hjj")));
            assert!(permissions.contains(&Permission::write("pp").with_prefix()));
            assert!(permissions.contains(&Permission::read("xyz").with_all_keys()));
        }

        //revoke all permission
        client.role_revoke_permission(role2, "123", None).await?;
        client
            .role_revoke_permission(
                role2,
                "abc",
                Some(RoleRevokePermissionOptions::new().with_from_key()),
            )
            .await?;
        client
            .role_revoke_permission(
                role2,
                "hi",
                Some(RoleRevokePermissionOptions::new().with_range_end("hjj")),
            )
            .await?;
        client
            .role_revoke_permission(
                role2,
                "pp",
                Some(RoleRevokePermissionOptions::new().with_prefix()),
            )
            .await?;
        client
            .role_revoke_permission(
                role2,
                "xyz",
                Some(RoleRevokePermissionOptions::new().with_all_keys()),
            )
            .await?;

        let resp = client.role_get(role2).await?;
        assert!(resp.permissions().is_empty());

        client.role_delete(role2).await?;

        Ok(())
    }

    #[tokio::test]
    async fn test_user() -> Result<()> {
        let name1 = "usr1";
        let password1 = "pwd1";
        let name2 = "usr2";
        let password2 = "pwd2";
        let name3 = "usr3";
        let password3 = "pwd3";
        let role1 = "role1";

        let mut client = get_client().await?;

        // ignore result
        let _resp = client.user_delete(name1).await;
        let _resp = client.user_delete(name2).await;
        let _resp = client.user_delete(name3).await;
        let _resp = client.role_delete(role1).await;

        client
            .user_add(name1, password1, Some(UserAddOptions::new()))
            .await?;

        client
            .user_add(name2, password2, Some(UserAddOptions::new().with_no_pwd()))
            .await?;

        client.user_add(name3, password3, None).await?;

        client.user_get(name1).await?;

        {
            let resp = client.user_list().await?;
            assert!(resp.users().contains(&name1.to_string()));
        }

        client.user_delete(name2).await?;
        client.user_get(name2).await.unwrap_err();

        client.user_change_password(name1, password2).await?;
        client.user_get(name1).await?;

        client.role_add(role1).await?;
        client.user_grant_role(name1, role1).await?;
        client.user_get(name1).await?;

        client.user_revoke_role(name1, role1).await?;
        client.user_get(name1).await?;

        let _ = client.user_delete(name1).await;
        let _ = client.user_delete(name2).await;
        let _ = client.user_delete(name3).await;
        let _ = client.role_delete(role1).await;

        Ok(())
    }

    #[tokio::test]
    async fn test_alarm() -> Result<()> {
        let mut client = get_client().await?;

        // Test deactivate alarm.
        {
            let options = AlarmOptions::new();
            let _resp = client
                .alarm(AlarmAction::Deactivate, AlarmType::None, Some(options))
                .await?;
        }

        // Test get None alarm.
        let member_id = {
            let resp = client
                .alarm(AlarmAction::Get, AlarmType::None, None)
                .await?;
            let mems = resp.alarms();
            assert_eq!(mems.len(), 0);
            0
        };

        let mut options = AlarmOptions::new();
        options.with_member(member_id);

        // Test get no space alarm.
        {
            let resp = client
                .alarm(AlarmAction::Get, AlarmType::Nospace, Some(options.clone()))
                .await?;
            let mems = resp.alarms();
            assert_eq!(mems.len(), 0);
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_status() -> Result<()> {
        let mut client = get_client().await?;
        let resp = client.status().await?;

        let db_size = resp.db_size();
        assert_ne!(db_size, 0);
        Ok(())
    }

    #[tokio::test]
    async fn test_defragment() -> Result<()> {
        let mut client = get_client().await?;
        let resp = client.defragment().await?;
        let hd = resp.header();
        assert!(hd.is_none());
        Ok(())
    }

    #[tokio::test]
    async fn test_hash() -> Result<()> {
        let mut client = get_client().await?;
        let resp = client.hash().await?;
        let hd = resp.header();
        assert!(hd.is_some());
        assert_ne!(resp.hash(), 0);
        Ok(())
    }

    #[tokio::test]
    async fn test_hash_kv() -> Result<()> {
        let mut client = get_client().await?;
        let resp = client.hash_kv(0).await?;
        let hd = resp.header();
        assert!(hd.is_some());
        assert_ne!(resp.hash(), 0);
        assert_ne!(resp.compact_version(), 0);
        Ok(())
    }

    #[tokio::test]
    async fn test_snapshot() -> Result<()> {
        let mut client = get_client().await?;
        let mut msg = client.snapshot().await?;
        loop {
            if let Some(resp) = msg.message().await? {
                assert!(!resp.blob().is_empty());
                if resp.remaining_bytes() == 0 {
                    break;
                }
            }
        }
        Ok(())
    }

    #[ignore]
    #[tokio::test]
    async fn test_cluster() -> Result<()> {
        let node1 = "localhost:2520";
        let node2 = "localhost:2530";
        let node3 = "localhost:2540";
        let mut client = get_client().await?;
        let resp = client
            .member_add([node1], Some(MemberAddOptions::new().with_is_learner()))
            .await?;
        let id1 = resp.member().unwrap().id();

        let resp = client.member_add([node2], None).await?;
        let id2 = resp.member().unwrap().id();
        let resp = client.member_add([node3], None).await?;
        let id3 = resp.member().unwrap().id();

        let resp = client.member_list().await?;
        let members: Vec<_> = resp.members().iter().map(|member| member.id()).collect();
        assert!(members.contains(&id1));
        assert!(members.contains(&id2));
        assert!(members.contains(&id3));
        Ok(())
    }

    #[tokio::test]
    async fn test_move_leader() -> Result<()> {
        let mut client = get_client().await?;
        let resp = client.member_list().await?;
        let member_list = resp.members();

        let resp = client.status().await?;
        let leader_id = resp.leader();
        println!("status {:?}, leader_id {:?}", resp, resp.leader());

        let mut member_id = leader_id;
        for member in member_list {
            println!("member_id {:?}, name is {:?}", member.id(), member.name());
            if member.id() != leader_id {
                member_id = member.id();
                break;
            }
        }

        let resp = client.move_leader(member_id).await?;
        let header = resp.header();
        if member_id == leader_id {
            assert!(header.is_none());
        } else {
            assert!(header.is_some());
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_election() -> Result<()> {
        let mut client = get_client().await?;
        let resp = client.lease_grant(10, None).await?;
        let lease_id = resp.id();
        assert_eq!(resp.ttl(), 10);

        let resp = client.campaign("myElection", "123", lease_id).await?;
        let leader = resp.leader().unwrap();
        assert_eq!(leader.name(), b"myElection");
        assert_eq!(leader.lease(), lease_id);

        let resp = client
            .proclaim(
                "123",
                Some(ProclaimOptions::new().with_leader(leader.clone())),
            )
            .await?;
        let header = resp.header();
        println!("proclaim header {:?}", header.unwrap());
        assert!(header.is_some());

        let mut msg = client.observe(leader.name()).await?;
        loop {
            if let Some(resp) = msg.message().await? {
                assert!(resp.kv().is_some());
                println!("observe key {:?}", resp.kv().unwrap().key_str());
                if resp.kv().is_some() {
                    break;
                }
            }
        }

        let resp = client.leader("myElection").await?;
        let kv = resp.kv().unwrap();
        assert_eq!(kv.value(), b"123");
        assert_eq!(kv.key(), leader.key());
        println!("key is {:?}", kv.key_str());
        println!("value is {:?}", kv.value_str());

        let resign_option = ResignOptions::new().with_leader(leader.clone());

        let resp = client.resign(Some(resign_option)).await?;
        let header = resp.header();
        println!("resign header {:?}", header.unwrap());
        assert!(header.is_some());

        Ok(())
    }

    #[tokio::test]
    async fn test_remove_and_add_endpoint() -> Result<()> {
        let mut client = get_client().await?;
        client.put("endpoint", "add_remove", None).await?;

        // get key
        {
            let resp = client.get("endpoint", None).await?;
            assert_eq!(resp.count(), 1);
            assert!(!resp.more());
            assert_eq!(resp.kvs().len(), 1);
            assert_eq!(resp.kvs()[0].key(), b"endpoint");
            assert_eq!(resp.kvs()[0].value(), b"add_remove");
        }

        // remove endpoint
        client.remove_endpoint(DEFAULT_TEST_ENDPOINT).await?;
        // `Client::get` will hang before adding the endpoint back
        client.add_endpoint(DEFAULT_TEST_ENDPOINT).await?;

        // get key after remove and add endpoint
        {
            let resp = client.get("endpoint", None).await?;
            assert_eq!(resp.count(), 1);
            assert!(!resp.more());
            assert_eq!(resp.kvs().len(), 1);
            assert_eq!(resp.kvs()[0].key(), b"endpoint");
            assert_eq!(resp.kvs()[0].value(), b"add_remove");
        }

        Ok(())
    }
}