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
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
#[cfg(test)]
mod test;
use std::{
collections::HashSet,
fmt,
fs::File,
hash::{Hash, Hasher},
io::{BufReader, Seek, SeekFrom},
net::{SocketAddr, ToSocketAddrs},
str::FromStr,
sync::Arc,
time::Duration,
};
use bson::{Bson, Document};
use derivative::Derivative;
use lazy_static::lazy_static;
use rustls::{
internal::pemfile,
Certificate,
RootCertStore,
ServerCertVerified,
ServerCertVerifier,
TLSError,
};
use typed_builder::TypedBuilder;
use webpki_roots::TLS_SERVER_ROOTS;
use crate::{
client::auth::{AuthMechanism, Credential},
concern::{Acknowledgment, ReadConcern, WriteConcern},
error::{ErrorKind, Result},
event::{cmap::CmapEventHandler, command::CommandEventHandler},
sdam::MIN_HEARTBEAT_FREQUENCY,
selection_criteria::{ReadPreference, SelectionCriteria, TagSet},
srv::SrvResolver,
};
const DEFAULT_PORT: u16 = 27017;
lazy_static! {
/// Reserved characters as defined by [Section 2.2 of RFC-3986](https://tools.ietf.org/html/rfc3986#section-2.2).
/// Usernames / passwords that contain these characters must instead include the URL encoded version of them when included
/// as part of the connection string.
static ref USERINFO_RESERVED_CHARACTERS: HashSet<&'static char> = {
[':', '/', '?', '#', '[', ']', '@'].iter().collect()
};
static ref ILLEGAL_DATABASE_CHARACTERS: HashSet<&'static char> = {
['/', '\\', ' ', '"', '$', '.'].iter().collect()
};
}
/// A hostname:port address pair.
#[derive(Clone, Debug, Eq)]
pub struct StreamAddress {
/// The hostname of the address.
pub hostname: String,
/// The port of the address.
///
/// The default is 27017.
pub port: Option<u16>,
}
impl Default for StreamAddress {
fn default() -> Self {
Self {
hostname: "localhost".into(),
port: None,
}
}
}
impl PartialEq for StreamAddress {
fn eq(&self, other: &Self) -> bool {
self.hostname == other.hostname && self.port.unwrap_or(27017) == other.port.unwrap_or(27017)
}
}
impl Hash for StreamAddress {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
self.hostname.hash(state);
self.port.unwrap_or(27017).hash(state);
}
}
impl ToSocketAddrs for StreamAddress {
type Iter = std::vec::IntoIter<SocketAddr>;
fn to_socket_addrs(&self) -> std::io::Result<Self::Iter> {
(self.hostname.as_str(), self.port.unwrap_or(27017)).to_socket_addrs()
}
}
impl StreamAddress {
pub fn parse(address: &str) -> Result<Self> {
let mut parts = address.split(':');
let hostname = match parts.next() {
Some(part) => part,
None => {
return Err(ErrorKind::InvalidHostname {
hostname: address.to_string(),
}
.into())
}
};
let port = match parts.next() {
Some(part) => {
let port = u16::from_str(part).map_err(|_| ErrorKind::InvalidHostname {
hostname: address.to_string(),
})?;
if parts.next().is_some() {
return Err(ErrorKind::InvalidHostname {
hostname: address.to_string(),
}
.into());
}
Some(port)
}
None => None,
};
Ok(StreamAddress {
hostname: hostname.to_string(),
port,
})
}
#[cfg(test)]
pub(crate) fn into_document(mut self) -> Document {
let mut doc = Document::new();
doc.insert("host", &self.hostname);
if let Some(i) = self.port.take() {
doc.insert("port", i64::from(i));
} else {
doc.insert("port", Bson::Null);
}
doc
}
}
impl fmt::Display for StreamAddress {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(
fmt,
"{}:{}",
self.hostname,
self.port.unwrap_or(DEFAULT_PORT)
)
}
}
/// Contains the options that can be used to create a new [`Client`](../struct.Client.html).
#[derive(Clone, Derivative, TypedBuilder)]
#[derivative(Debug, PartialEq)]
pub struct ClientOptions {
/// The initial list of seeds that the Client should connect to.
///
/// Note that by default, the driver will autodiscover other nodes in the cluster. To connect
/// directly to a single server (rather than autodiscovering the rest of the cluster), set the
/// `direct` field to `true`.
#[builder(default_code = "vec![ StreamAddress {
hostname: \"localhost\".to_string(),
port: Some(27017),
}]")]
pub hosts: Vec<StreamAddress>,
/// The application name that the Client will send to the server as part of the handshake. This
/// can be used in combination with the server logs to determine which Client is connected to a
/// server.
#[builder(default)]
pub app_name: Option<String>,
#[builder(default)]
pub(crate) compressors: Option<Vec<String>>,
/// The handler that should process all Connection Monitoring and Pooling events. See the
/// CmapEventHandler type documentation for more details.
#[derivative(Debug = "ignore", PartialEq = "ignore")]
#[builder(default)]
pub cmap_event_handler: Option<Arc<dyn CmapEventHandler>>,
/// The handler that should process all command-related events. See the CommandEventHandler
/// type documentation for more details.
#[derivative(Debug = "ignore", PartialEq = "ignore")]
#[builder(default)]
pub command_event_handler: Option<Arc<dyn CommandEventHandler>>,
/// The connect timeout passed to each underlying TcpStream when attemtping to connect to the
/// server.
///
/// The default value is 10 seconds.
#[builder(default)]
pub connect_timeout: Option<Duration>,
/// The credential to use for authenticating connections made by this client.
#[builder(default)]
pub credential: Option<Credential>,
/// Specifies whether the Client should directly connect to a single host rather than
/// autodiscover all servers in the cluster.
///
/// The default value is false.
#[builder(default)]
pub direct_connection: Option<bool>,
/// The amount of time each monitoring thread should wait between sending an isMaster command
/// to its respective server.
///
/// The default value is 10 seconds.
#[builder(default)]
pub heartbeat_freq: Option<Duration>,
/// When running a read operation with a ReadPreference that allows selecting secondaries,
/// `local_threshold` is used to determine how much longer the average round trip time between
/// the driver and server is allowed compared to the least round trip time of all the suitable
/// servers. For example, if the average round trip times of the suitable servers are 5 ms, 10
/// ms, and 15 ms, and the local threshold is 8 ms, then the first two servers are within the
/// latency window and could be chosen for the operation, but the last one is not.
///
/// A value of zero indicates that there is no latency window, so only the server with the
/// lowest average round trip time is eligible.
///
/// The default value is 15 ms.
#[builder(default)]
pub local_threshold: Option<Duration>,
/// The amount of time that a connection can remain idle in a connection pool before being
/// closed. A value of zero indicates that connections should not be closed due to being idle.
///
/// By default, connections will not be closed due to being idle.
#[builder(default)]
pub max_idle_time: Option<Duration>,
/// The maximum amount of connections that the Client should allow to be created in a
/// connection pool for a given server. If an operation is attempted on a server while
/// `max_pool_size` connections are checked out, the operation will block until an in-progress
/// operation finishes and its connection is checked back into the pool.
///
/// The default value is 100.
#[builder(default)]
pub max_pool_size: Option<u32>,
/// The minimum number of connections that should be available in a server's connection pool at
/// a given time. If fewer than `min_pool_size` connections are in the pool, connections will
/// be added to the pool in the background until `min_pool_size` is reached.
///
/// The default value is 0.
#[builder(default)]
pub min_pool_size: Option<u32>,
/// Specifies the default read concern for operations performed on the Client. See the
/// ReadConcern type documentation for more details.
#[builder(default)]
pub read_concern: Option<ReadConcern>,
/// The name of the replica set that the Client should connect to.
#[builder(default)]
pub repl_set_name: Option<String>,
#[builder(default)]
pub(crate) retry_reads: Option<bool>,
#[builder(default)]
pub(crate) retry_writes: Option<bool>,
/// The default selection criteria for operations performed on the Client. See the
/// SelectionCriteria type documentation for more details.
#[builder(default)]
pub selection_criteria: Option<SelectionCriteria>,
/// The amount of time the Client should attempt to select a server for an operation before
/// timing outs
///
/// The default value is 30 seconds.
#[builder(default)]
pub server_selection_timeout: Option<Duration>,
#[builder(default)]
pub(crate) socket_timeout: Option<Duration>,
/// The TLS configuration for the Client to use in its connections with the server.
///
/// By default, TLS is disabled.
#[builder(default)]
pub tls: Option<Tls>,
/// The amount of time a thread should block while waiting to check out a connection before
/// returning an error. Note that if there are fewer than `max_pool_size` connections checked
/// out or if a connection is available in the pool, checking out a connection will not block.
///
/// By default, threads will wait indefinitely for a connection to become available.
#[builder(default)]
pub wait_queue_timeout: Option<Duration>,
/// Specifies the default write concern for operations performed on the Client. See the
/// WriteConcern type documentation for more details.
#[builder(default)]
pub write_concern: Option<WriteConcern>,
#[builder(default)]
pub(crate) zlib_compression: Option<i32>,
#[builder(default)]
original_uri: Option<String>,
}
impl Default for ClientOptions {
fn default() -> Self {
Self::builder().build()
}
}
#[derive(Debug, Default, PartialEq)]
struct ClientOptionsParser {
pub hosts: Vec<StreamAddress>,
pub srv: bool,
pub app_name: Option<String>,
pub tls: Option<Tls>,
pub heartbeat_freq: Option<Duration>,
pub local_threshold: Option<Duration>,
pub read_concern: Option<ReadConcern>,
pub selection_criteria: Option<SelectionCriteria>,
pub repl_set_name: Option<String>,
pub write_concern: Option<WriteConcern>,
pub server_selection_timeout: Option<Duration>,
pub max_pool_size: Option<u32>,
pub min_pool_size: Option<u32>,
pub max_idle_time: Option<Duration>,
pub wait_queue_timeout: Option<Duration>,
pub compressors: Option<Vec<String>>,
pub connect_timeout: Option<Duration>,
pub retry_reads: Option<bool>,
pub retry_writes: Option<bool>,
pub socket_timeout: Option<Duration>,
pub zlib_compression: Option<i32>,
pub direct_connection: Option<bool>,
pub credential: Option<Credential>,
max_staleness: Option<Duration>,
tls_insecure: Option<bool>,
auth_mechanism: Option<AuthMechanism>,
auth_source: Option<String>,
auth_mechanism_properties: Option<Document>,
read_preference: Option<ReadPreference>,
read_preference_tags: Option<Vec<TagSet>>,
original_uri: String,
}
/// Specifies whether TLS configuration should be used with the operations that the
/// [`Client`](../struct.Client.html) performs.
#[derive(Clone, Debug, PartialEq)]
pub enum Tls {
Enabled(TlsOptions),
Disabled,
}
impl From<TlsOptions> for Tls {
fn from(options: TlsOptions) -> Self {
Self::Enabled(options)
}
}
impl From<TlsOptions> for Option<Tls> {
fn from(options: TlsOptions) -> Self {
Some(Tls::Enabled(options))
}
}
/// Specifies the TLS configuration that the [`Client`](../struct.Client.html) should use.
#[derive(Clone, Debug, Default, PartialEq, TypedBuilder)]
pub struct TlsOptions {
/// Whether or not the [`Client`](../struct.Client.html) should return an error if the server
/// presents an invalid certificate. This setting should _not_ be set to `true` in
/// production; it should only be used for testing.
///
/// The default value is to error when the server presents an invalid certificate.
#[builder(default)]
pub allow_invalid_certificates: Option<bool>,
/// The path to the CA file that the [`Client`](../struct.Client.html) should use for TLS. If
/// none is specified, then the driver will use the Mozilla root certificates from the
/// `webpki-roots` crate.
#[builder(default)]
pub ca_file_path: Option<String>,
/// The path to the certificate file that the [`Client`](../struct.Client.html) should present
/// to the server to verify its identify. If none is specified, then the
/// [`Client`](../struct.Client.html) will not attempt to verify its identity to the
/// server.
#[builder(default)]
pub cert_key_file_path: Option<String>,
}
struct NoCertVerifier {}
impl ServerCertVerifier for NoCertVerifier {
fn verify_server_cert(
&self,
_: &RootCertStore,
_: &[Certificate],
_: webpki::DNSNameRef,
_: &[u8],
) -> std::result::Result<ServerCertVerified, TLSError> {
Ok(ServerCertVerified::assertion())
}
}
impl TlsOptions {
pub fn into_rustls_config(self) -> Result<rustls::ClientConfig> {
let mut config = rustls::ClientConfig::new();
if let Some(true) = self.allow_invalid_certificates {
config
.dangerous()
.set_certificate_verifier(Arc::new(NoCertVerifier {}));
}
let mut store = RootCertStore::empty();
if let Some(path) = self.ca_file_path {
store
.add_pem_file(&mut BufReader::new(File::open(&path)?))
.map_err(|_| ErrorKind::ParseError {
data_type: "PEM-encoded root certificate".to_string(),
file_path: path,
})?;
} else {
store.add_server_trust_anchors(&TLS_SERVER_ROOTS);
}
config.root_store = store;
if let Some(path) = self.cert_key_file_path {
let mut file = BufReader::new(File::open(&path)?);
let certs = match pemfile::certs(&mut file) {
Ok(certs) => certs,
Err(()) => {
return Err(ErrorKind::ParseError {
data_type: "PEM-encoded client certificate".to_string(),
file_path: path,
}
.into())
}
};
file.seek(SeekFrom::Start(0))?;
let key = match pemfile::rsa_private_keys(&mut file) {
Ok(key) => key,
Err(()) => {
return Err(ErrorKind::ParseError {
data_type: "PEM-encoded RSA key".to_string(),
file_path: path,
}
.into())
}
};
// TODO: Get rid of unwrap
config.set_single_client_cert(certs, key.into_iter().next().unwrap());
}
Ok(config)
}
}
impl From<ClientOptionsParser> for ClientOptions {
fn from(parser: ClientOptionsParser) -> Self {
Self {
hosts: parser.hosts,
app_name: parser.app_name,
tls: parser.tls,
heartbeat_freq: parser.heartbeat_freq,
local_threshold: parser.local_threshold,
read_concern: parser.read_concern,
selection_criteria: parser.selection_criteria,
repl_set_name: parser.repl_set_name,
write_concern: parser.write_concern,
max_pool_size: parser.max_pool_size,
min_pool_size: parser.min_pool_size,
max_idle_time: parser.max_idle_time,
wait_queue_timeout: parser.wait_queue_timeout,
server_selection_timeout: parser.server_selection_timeout,
compressors: parser.compressors,
connect_timeout: parser.connect_timeout,
retry_reads: parser.retry_reads,
retry_writes: parser.retry_writes,
socket_timeout: parser.socket_timeout,
zlib_compression: parser.zlib_compression,
direct_connection: parser.direct_connection,
credential: parser.credential,
cmap_event_handler: None,
command_event_handler: None,
original_uri: Some(parser.original_uri),
}
}
}
impl ClientOptions {
/// Parses a MongoDB connection string into a ClientOptions struct. If the string is malformed
/// or one of the options has an invalid value, an error will be returned.
///
/// In the case that "mongodb+srv" is used, SRV and TXT record lookups will be done as
/// part of this method.
///
/// The format of a MongoDB connection string is described [here](https://docs.mongodb.com/manual/reference/connection-string/#connection-string-formats).
///
/// The following options are supported in the options query string:
///
/// * `appName`: maps to the `app_name` field
/// * `authMechanism`: maps to the `mechanism` field of the `credential` field
/// * `authSource`: maps to the `source` field of the `credential` field
/// * `authMechanismProperties`: maps to the `mechanism_properties` field of the `credential`
/// field
/// * `compressors`: not yet implemented
/// * `connectTimeoutMS`: maps to the `connect_timeout` field
/// * `direct`: maps to the `direct` field
/// * `heartbeatFrequencyMS`: maps to the `heartbeat_frequency` field
/// * `journal`: maps to the `journal` field of the `write_concern` field
/// * `localThresholdMS`: maps to the `local_threshold` field
/// * `maxIdleTimeMS`: maps to the `max_idle_time` field
/// * `maxStalenessSeconds`: maps to the `max_staleness` field of the `selection_criteria`
/// field
/// * `maxPoolSize`: maps to the `max_pool_size` field
/// * `minPoolSize`: maps to the `min_pool_size` field
/// * `readConcernLevel`: maps to the `read_concern` field
/// * `readPreferenceField`: maps to the ReadPreference enum variant of the
/// `selection_criteria` field
/// * `readPreferenceTags`: maps to the `tags` field of the `selection_criteria` field. Note
/// that this option can appear more than once; each instance will be mapped to a separate
/// tag set
/// * `replicaSet`: maps to the `repl_set_name` field
/// * `retryWrites`: not yet implemented
/// * `retryReads`: not yet implemented
/// * `serverSelectionTimeoutMS`: maps to the `server_selection_timeout` field
/// * `socketTimeoutMS`: maps to the `socket_timeout` field
/// * `ssl`: an alias of the `tls` option
/// * `tls`: maps to the TLS variant of the `tls` field`.
/// * `tlsInsecure`: relaxes the TLS constraints on connections being made; currently is just
/// an alias of `tlsAllowInvalidCertificates`, but more behavior may be added to this option
/// in the future
/// * `tlsAllowInvalidCertificates`: maps to the `allow_invalidCertificates` field of the
/// `tls` field
/// * `tlsCAFile`: maps to the `ca_file_path` field of the `tls` field
/// * `tlsCertificateKeyFile`: maps to the `cert_key_file_path` field of the `tls` field
/// * `w`: maps to the `w` field of the `write_concern` field
/// * `waitQueueTimeoutMS`: maps to the `wait_queue_timeout` field
/// * `wTimeoutMS`: maps to the `w_timeout` field of the `write_concern` field
/// * `zlibCompressionLevel`: not yet implemented
pub fn parse(s: &str) -> Result<Self> {
let parser = ClientOptionsParser::parse(s)?;
let srv = parser.srv;
let auth_source_present = parser.auth_source.is_some();
let mut options: Self = parser.into();
if srv {
let resolver = SrvResolver::new()?;
let mut config = resolver.resolve_client_options(&options.hosts[0].hostname)?;
// Set the ClientOptions hosts to those found during the SRV lookup.
options.hosts = config.hosts;
// Enable TLS unless the user explicitly disabled it.
if options.tls.is_none() {
options.tls = Some(Tls::Enabled(Default::default()));
}
// Set the authSource TXT option found during SRV lookup unless the user already set it.
// Note that this _does_ override the default database specified in the URI, since it is
// supposed to be overriden by authSource.
if !auth_source_present {
if let Some(auth_source) = config.auth_source.take() {
options
.credential
.get_or_insert_with(Default::default)
.source = Some(auth_source);
}
}
// Set the replica set name TXT option found during SRV lookup unless the user already
// set it.
if options.repl_set_name.is_none() {
if let Some(replica_set) = config.replica_set.take() {
options.repl_set_name = Some(replica_set);
}
}
}
Ok(options)
}
pub(crate) fn tls_options(&self) -> Option<TlsOptions> {
match self.tls {
Some(Tls::Enabled(ref opts)) => Some(opts.clone()),
_ => None,
}
}
}
/// Splits a string into a section before a given index and a section exclusively after the index.
/// Empty portions are returned as `None`.
fn exclusive_split_at(s: &str, i: usize) -> (Option<&str>, Option<&str>) {
let (l, r) = s.split_at(i);
let lout = if !l.is_empty() { Some(l) } else { None };
let rout = if r.len() > 1 { Some(&r[1..]) } else { None };
(lout, rout)
}
fn percent_decode(s: &str, err_message: &str) -> Result<String> {
match percent_encoding::percent_decode_str(s).decode_utf8() {
Ok(result) => Ok(result.to_string()),
Err(_) => Err(ErrorKind::ArgumentError {
message: err_message.to_string(),
}
.into()),
}
}
fn validate_userinfo(s: &str, userinfo_type: &str) -> Result<()> {
if s.chars().any(|c| USERINFO_RESERVED_CHARACTERS.contains(&c)) {
return Err(ErrorKind::ArgumentError {
message: format!("{} must be URL encoded", userinfo_type),
}
.into());
}
Ok(())
}
impl ClientOptionsParser {
fn parse(s: &str) -> Result<Self> {
let end_of_scheme = match s.find("://") {
Some(index) => index,
None => {
return Err(ErrorKind::ArgumentError {
message: "connection string contains no scheme".to_string(),
}
.into())
}
};
let srv = match &s[..end_of_scheme] {
"mongodb" => false,
"mongodb+srv" => true,
_ => {
return Err(ErrorKind::ArgumentError {
message: format!("invalid connection string scheme: {}", &s[..end_of_scheme]),
}
.into())
}
};
let after_scheme = &s[end_of_scheme + 3..];
let (pre_slash, post_slash) = match after_scheme.find('/') {
Some(slash_index) => match exclusive_split_at(after_scheme, slash_index) {
(Some(section), o) => (section, o),
(None, _) => {
return Err(ErrorKind::ArgumentError {
message: "missing hosts".to_string(),
}
.into())
}
},
None => {
if after_scheme.find('?').is_some() {
return Err(ErrorKind::ArgumentError {
message: "Missing delimiting slash between hosts and options".to_string(),
}
.into());
}
(after_scheme, None)
}
};
let (database, options_section) = match post_slash {
Some(section) => match section.find('?') {
Some(index) => exclusive_split_at(section, index),
None => (post_slash, None),
},
None => (None, None),
};
let db = match database {
Some(db) => {
let decoded = percent_decode(db, "database name must be URL encoded")?;
if decoded
.chars()
.any(|c| ILLEGAL_DATABASE_CHARACTERS.contains(&c))
{
return Err(ErrorKind::ArgumentError {
message: "illegal character in database name".to_string(),
}
.into());
}
Some(decoded)
}
None => None,
};
let (authentication_requested, cred_section, hosts_section) = match pre_slash.rfind('@') {
Some(index) => {
// if '@' is in the host section, it MUST be interpreted as a request for
// authentication, even if the credentials are empty.
let (creds, hosts) = exclusive_split_at(pre_slash, index);
match hosts {
Some(hs) => (true, creds, hs),
None => {
return Err(ErrorKind::ArgumentError {
message: "missing hosts".to_string(),
}
.into())
}
}
}
None => (false, None, pre_slash),
};
let (username, password) = match cred_section {
Some(creds) => match creds.find(':') {
Some(index) => match exclusive_split_at(creds, index) {
(username, None) => (username, Some("")),
(username, password) => (username, password),
},
None => (Some(creds), None), // Lack of ":" implies whole string is username
},
None => (None, None),
};
let hosts: Result<Vec<_>> = hosts_section
.split(',')
.map(|host| {
let (hostname, port) = match host.find(':') {
Some(index) => host.split_at(index),
None => (host, ""),
};
if hostname.is_empty() {
return Err(ErrorKind::ArgumentError {
message: "connection string contains no host".to_string(),
}
.into());
}
let port = if port.is_empty() {
None
} else {
let port_string_without_colon = &port[1..];
let p = u16::from_str_radix(port_string_without_colon, 10).map_err(|_| {
ErrorKind::ArgumentError {
message: format!(
"invalid port specified in connection string: {}",
port
),
}
})?;
if p == 0 {
return Err(ErrorKind::ArgumentError {
message: format!(
"invalid port specified in connection string: {}",
port
),
}
.into());
}
Some(p)
};
Ok(StreamAddress {
hostname: hostname.to_lowercase(),
port,
})
})
.collect();
let hosts = hosts?;
if srv {
if hosts.len() != 1 {
return Err(ErrorKind::ArgumentError {
message: "exactly one host must be specified with 'mongodb+srv'".into(),
}
.into());
}
if hosts[0].port.is_some() {
return Err(ErrorKind::ArgumentError {
message: "a port cannot be specified with 'mongodb+srv'".into(),
}
.into());
}
}
let mut options = ClientOptionsParser {
hosts,
srv,
original_uri: s.into(),
..Default::default()
};
if let Some(opts) = options_section {
options.parse_options(opts)?;
}
if let Some(ref write_concern) = options.write_concern {
write_concern.validate()?;
}
// Set username and password.
if let Some(u) = username {
let mut credential = options.credential.get_or_insert_with(Default::default);
validate_userinfo(u, "username")?;
let decoded_u = percent_decode(u, "username must be URL encoded")?;
if decoded_u.chars().any(|c| c == '%') {
return Err(ErrorKind::ArgumentError {
message: "username/passowrd cannot contain unescaped %".to_string(),
}
.into());
}
credential.username = Some(decoded_u);
if let Some(pass) = password {
validate_userinfo(pass, "password")?;
let decoded_p = percent_decode(pass, "password must be URL encoded")?;
credential.password = Some(decoded_p)
}
}
let db_str = db.as_ref().map(String::as_str);
match options.auth_mechanism {
Some(ref mechanism) => {
let mut credential = options.credential.get_or_insert_with(Default::default);
credential.source = options
.auth_source
.clone()
.or_else(|| Some(mechanism.default_source(db_str).into()));
if let Some(mut doc) = options.auth_mechanism_properties.take() {
match doc.remove("CANONICALIZE_HOST_NAME") {
Some(Bson::String(s)) => {
let val = match &s.to_lowercase()[..] {
"true" => Bson::Boolean(true),
"false" => Bson::Boolean(false),
_ => Bson::String(s),
};
doc.insert("CANONICALIZE_HOST_NAME", val);
}
Some(val) => {
doc.insert("CANONICALIZE_HOST_NAME", val);
}
None => {}
}
credential.mechanism_properties = Some(doc);
}
mechanism.validate_credential(&credential)?;
credential.mechanism = options.auth_mechanism.take();
}
None => {
if let Some(ref mut credential) = options.credential {
// If credentials exist (i.e. username is specified) but no mechanism, the
// default source is chosen from the following list in
// order (skipping null ones): authSource option, connection string db,
// SCRAM default (i.e. "admin").
credential.source = options
.auth_source
.clone()
.or(db)
.or_else(|| Some("admin".into()));
} else if authentication_requested {
return Err(ErrorKind::ArgumentError {
message: "username and mechanism both not provided, but authentication \
was requested"
.to_string(),
}
.into());
} else if options.auth_source.is_some() {
return Err(ErrorKind::ArgumentError {
message: "username and mechanism both not provided, but authSource was \
specified"
.to_string(),
}
.into());
}
}
};
if options.tls.is_none() && options.srv {
options.tls = Some(Tls::Enabled(Default::default()));
}
Ok(options)
}
fn parse_options(&mut self, options: &str) -> Result<()> {
if options.is_empty() {
return Ok(());
}
let mut keys: Vec<&str> = Vec::new();
for option_pair in options.split('&') {
let (key, value) = match option_pair.find('=') {
Some(index) => option_pair.split_at(index),
None => {
return Err(ErrorKind::ArgumentError {
message: format!(
"connection string options is not a `key=value` pair: {}",
option_pair,
),
}
.into())
}
};
if key.to_lowercase() != "readpreferencetags" && keys.contains(&key) {
return Err(ErrorKind::ArgumentError {
message: "repeated options are not allowed in the connection string"
.to_string(),
}
.into());
} else {
keys.push(key);
}
// Skip leading '=' in value.
self.parse_option_pair(
&key.to_lowercase(),
percent_encoding::percent_decode(&value.as_bytes()[1..])
.decode_utf8_lossy()
.as_ref(),
)?;
}
if let Some(tags) = self.read_preference_tags.take() {
self.read_preference = match self.read_preference.take() {
Some(read_pref) => Some(read_pref.with_tags(tags)?),
None => {
return Err(ErrorKind::ArgumentError {
message: "cannot set read preference tags without also setting read \
preference mode"
.to_string(),
}
.into())
}
};
}
if let Some(max_staleness) = self.max_staleness.take() {
self.read_preference = match self.read_preference.take() {
Some(read_pref) => Some(read_pref.with_max_staleness(max_staleness)?),
None => {
return Err(ErrorKind::ArgumentError {
message: "cannot set max staleness without also setting read preference \
mode"
.to_string(),
}
.into())
}
};
}
self.selection_criteria = self.read_preference.take().map(Into::into);
Ok(())
}
fn parse_option_pair(&mut self, key: &str, value: &str) -> Result<()> {
macro_rules! get_bool {
($value:expr, $option:expr) => {
match $value {
"true" => true,
"false" => false,
_ => {
return Err(ErrorKind::ArgumentError {
message: format!(
"connection string `{}` option must be a boolean",
$option,
),
}
.into())
}
}
};
}
macro_rules! get_duration {
($value:expr, $option:expr) => {
match u64::from_str_radix($value, 10) {
Ok(i) => i,
_ => {
return Err(ErrorKind::ArgumentError {
message: format!(
"connection string `{}` option must be a non-negative integer",
$option
),
}
.into())
}
}
};
}
macro_rules! get_u32 {
($value:expr, $option:expr) => {
match u32::from_str_radix(value, 10) {
Ok(u) => u,
Err(_) => {
return Err(ErrorKind::ArgumentError {
message: format!(
"connection string `{}` argument must be a positive integer",
$option,
),
}
.into())
}
}
};
}
macro_rules! get_i32 {
($value:expr, $option:expr) => {
match i32::from_str_radix(value, 10) {
Ok(u) => u,
Err(_) => {
return Err(ErrorKind::ArgumentError {
message: format!(
"connection string `{}` argument must be an integer",
$option
),
}
.into())
}
}
};
}
match key {
"appname" => {
self.app_name = Some(value.into());
}
"authmechanism" => {
self.auth_mechanism = Some(AuthMechanism::from_str(value)?);
}
"authsource" => self.auth_source = Some(value.to_string()),
"authmechanismproperties" => {
let mut doc = Document::new();
let err_func = || {
ErrorKind::ArgumentError {
message: "improperly formatted authMechanismProperties".to_string(),
}
.into()
};
for kvp in value.split(',') {
match kvp.find(':') {
Some(index) => {
let (k, v) = exclusive_split_at(kvp, index);
let key = k.ok_or_else(err_func)?;
let value = v.ok_or_else(err_func)?;
doc.insert(key, value);
}
None => return Err(err_func()),
};
}
self.auth_mechanism_properties = Some(doc);
}
"compressors" => {
self.compressors = Some(value.split(',').map(String::from).collect());
}
k @ "connecttimeoutms" => {
self.connect_timeout = Some(Duration::from_millis(get_duration!(value, k)));
}
k @ "direct" => {
self.direct_connection = Some(get_bool!(value, k));
}
k @ "heartbeatfrequencyms" => {
let duration = get_duration!(value, k);
if duration < MIN_HEARTBEAT_FREQUENCY.num_milliseconds() as u64 {
return Err(ErrorKind::ArgumentError {
message: format!(
"'heartbeatFrequencyMS' must be at least 500, but {} was given",
duration
),
}
.into());
}
self.heartbeat_freq = Some(Duration::from_millis(duration));
}
k @ "journal" => {
let mut write_concern = self.write_concern.get_or_insert_with(Default::default);
write_concern.journal = Some(get_bool!(value, k));
}
k @ "localthresholdms" => {
self.local_threshold = Some(Duration::from_millis(get_duration!(value, k)))
}
k @ "maxidletimems" => {
self.max_idle_time = Some(Duration::from_millis(get_duration!(value, k)));
}
k @ "maxstalenessseconds" => {
let max_staleness = Duration::from_secs(get_duration!(value, k));
if max_staleness > Duration::from_secs(0) && max_staleness < Duration::from_secs(90)
{
return Err(ErrorKind::ArgumentError {
message: "'maxStalenessSeconds' cannot be both positive and below 90"
.into(),
}
.into());
}
self.max_staleness = Some(max_staleness);
}
k @ "maxpoolsize" => {
self.max_pool_size = Some(get_u32!(value, k));
}
k @ "minpoolsize" => {
self.max_pool_size = Some(get_u32!(value, k));
}
"readconcernlevel" => {
self.read_concern = Some(ReadConcern::Custom(value.to_string()));
}
"readpreference" => {
self.read_preference = Some(match &value.to_lowercase()[..] {
"primary" => ReadPreference::Primary,
"secondary" => ReadPreference::Secondary {
tag_sets: None,
max_staleness: None,
},
"primarypreferred" => ReadPreference::PrimaryPreferred {
tag_sets: None,
max_staleness: None,
},
"secondarypreferred" => ReadPreference::SecondaryPreferred {
tag_sets: None,
max_staleness: None,
},
"nearest" => ReadPreference::Nearest {
tag_sets: None,
max_staleness: None,
},
other => {
return Err(ErrorKind::ArgumentError {
message: format!("'{}' is not a valid read preference", other),
}
.into())
}
});
}
"readpreferencetags" => {
let tags: Result<TagSet> = if value.is_empty() {
Ok(TagSet::new())
} else {
value
.split(',')
.map(|tag| {
let mut values = tag.split(':');
match (values.next(), values.next()) {
(Some(key), Some(value)) => {
Ok((key.to_string(), value.to_string()))
}
_ => Err(ErrorKind::ArgumentError {
message: format!(
"'{}' is not a valid read preference tag (which must be \
of the form 'key:value'",
value,
),
}
.into()),
}
})
.collect()
};
self.read_preference_tags
.get_or_insert_with(Vec::new)
.push(tags?);
}
"replicaset" => {
self.repl_set_name = Some(value.to_string());
}
k @ "retrywrites" => {
self.retry_writes = Some(get_bool!(value, k));
}
k @ "retryreads" => {
self.retry_reads = Some(get_bool!(value, k));
}
k @ "serverselectiontimeoutms" => {
self.server_selection_timeout = Some(Duration::from_millis(get_duration!(value, k)))
}
k @ "sockettimeoutms" => {
self.socket_timeout = Some(Duration::from_millis(get_duration!(value, k)));
}
k @ "tls" | k @ "ssl" => {
let tls = get_bool!(value, k);
match (self.tls.as_ref(), tls) {
(Some(Tls::Disabled), true) | (Some(Tls::Enabled(..)), false) => {
return Err(ErrorKind::ArgumentError {
message: "All instances of `tls` and `ssl` must have the same
value"
.to_string(),
}
.into());
}
_ => {}
};
if self.tls.is_none() {
let tls = if tls {
Tls::Enabled(Default::default())
} else {
Tls::Disabled
};
self.tls = Some(tls);
}
}
k @ "tlsinsecure" | k @ "tlsallowinvalidcertificates" => {
let val = get_bool!(value, k);
let allow_invalid_certificates = if k == "tlsinsecure" { !val } else { val };
match self.tls {
Some(Tls::Disabled) => {
return Err(ErrorKind::ArgumentError {
message: "'tlsInsecure' can't be set if tls=false".into(),
}
.into())
}
Some(Tls::Enabled(ref options))
if options.allow_invalid_certificates.is_some()
&& options.allow_invalid_certificates
!= Some(allow_invalid_certificates) =>
{
return Err(ErrorKind::ArgumentError {
message: "all instances of 'tlsInsecure' and \
'tlsAllowInvalidCertificates' must be consistent (e.g. \
'tlsInsecure' cannot be true when \
'tlsAllowInvalidCertificates' is false, or vice-versa)"
.into(),
}
.into());
}
Some(Tls::Enabled(ref mut options)) => {
options.allow_invalid_certificates = Some(allow_invalid_certificates);
}
None => {
self.tls = Some(Tls::Enabled(
TlsOptions::builder()
.allow_invalid_certificates(allow_invalid_certificates)
.build(),
))
}
}
}
"tlscafile" => match self.tls {
Some(Tls::Disabled) => {
return Err(ErrorKind::ArgumentError {
message: "'tlsCAFile' can't be set if tls=false".into(),
}
.into());
}
Some(Tls::Enabled(ref mut options)) => {
options.ca_file_path = Some(value.to_string());
}
None => {
self.tls = Some(Tls::Enabled(
TlsOptions::builder()
.ca_file_path(value.to_string())
.build(),
))
}
},
"tlscertificatekeyfile" => match self.tls {
Some(Tls::Disabled) => {
return Err(ErrorKind::ArgumentError {
message: "'tlsCertificateKeyFile' can't be set if tls=false".into(),
}
.into());
}
Some(Tls::Enabled(ref mut options)) => {
options.cert_key_file_path = Some(value.to_string());
}
None => {
self.tls = Some(Tls::Enabled(
TlsOptions::builder()
.cert_key_file_path(value.to_string())
.build(),
))
}
},
"w" => {
let mut write_concern = self.write_concern.get_or_insert_with(Default::default);
match i32::from_str_radix(value, 10) {
Ok(w) => {
if w < 0 {
return Err(ErrorKind::ArgumentError {
message: "connection string `w` option cannot be a negative \
integer"
.to_string(),
}
.into());
}
write_concern.w = Some(Acknowledgment::from(w));
}
Err(_) => {
write_concern.w = Some(Acknowledgment::from(value.to_string()));
}
};
}
k @ "waitqueuetimeoutms" => {
self.wait_queue_timeout = Some(Duration::from_millis(get_duration!(value, k)));
}
k @ "wtimeoutms" => {
let write_concern = self.write_concern.get_or_insert_with(Default::default);
write_concern.w_timeout = Some(Duration::from_millis(get_duration!(value, k)));
}
k @ "zlibcompressionlevel" => {
let i = get_i32!(value, k);
if i < -1 {
return Err(ErrorKind::ArgumentError {
message: "'zlibCompressionLevel' cannot be less than -1".to_string(),
}
.into());
}
if i > 9 {
return Err(ErrorKind::ArgumentError {
message: "'zlibCompressionLevel' cannot be greater than 9".to_string(),
}
.into());
}
self.zlib_compression = Some(i);
}
_ => {
return Err(ErrorKind::ArgumentError {
message: "invalid option warning".to_string(),
}
.into());
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use pretty_assertions::assert_eq;
use super::{ClientOptions, StreamAddress};
use crate::{
concern::{Acknowledgment, ReadConcern, WriteConcern},
selection_criteria::ReadPreference,
};
macro_rules! tag_set {
( $($k:expr => $v:expr),* ) => {
#[allow(clippy::let_and_return)]
{
use std::collections::HashMap;
#[allow(unused_mut)]
let mut ts = HashMap::new();
$(
ts.insert($k.to_string(), $v.to_string());
)*
ts
}
}
}
fn host_without_port(hostname: &str) -> StreamAddress {
StreamAddress {
hostname: hostname.to_string(),
port: None,
}
}
#[test]
fn fails_without_scheme() {
assert!(ClientOptions::parse("localhost:27017").is_err());
}
#[test]
fn fails_with_invalid_scheme() {
assert!(ClientOptions::parse("mangodb://localhost:27017").is_err());
}
#[test]
fn fails_with_nothing_after_scheme() {
assert!(ClientOptions::parse("mongodb://").is_err());
}
#[test]
fn fails_with_only_slash_after_scheme() {
assert!(ClientOptions::parse("mongodb:///").is_err());
}
#[test]
fn fails_with_no_host() {
assert!(ClientOptions::parse("mongodb://:27017").is_err());
}
#[test]
fn no_port() {
let uri = "mongodb://localhost";
assert_eq!(
ClientOptions::parse(uri).unwrap(),
ClientOptions {
hosts: vec![host_without_port("localhost")],
original_uri: Some(uri.into()),
..Default::default()
}
);
}
#[test]
fn no_port_trailing_slash() {
let uri = "mongodb://localhost/";
assert_eq!(
ClientOptions::parse(uri).unwrap(),
ClientOptions {
hosts: vec![host_without_port("localhost")],
original_uri: Some(uri.into()),
..Default::default()
}
);
}
#[test]
fn with_port() {
let uri = "mongodb://localhost/";
assert_eq!(
ClientOptions::parse(uri).unwrap(),
ClientOptions {
hosts: vec![StreamAddress {
hostname: "localhost".to_string(),
port: Some(27017),
}],
original_uri: Some(uri.into()),
..Default::default()
}
);
}
#[test]
fn with_port_and_trailing_slash() {
let uri = "mongodb://localhost:27017/";
assert_eq!(
ClientOptions::parse(uri).unwrap(),
ClientOptions {
hosts: vec![StreamAddress {
hostname: "localhost".to_string(),
port: Some(27017),
}],
original_uri: Some(uri.into()),
..Default::default()
}
);
}
#[test]
fn with_read_concern() {
let uri = "mongodb://localhost:27017/?readConcernLevel=foo";
assert_eq!(
ClientOptions::parse(uri).unwrap(),
ClientOptions {
hosts: vec![StreamAddress {
hostname: "localhost".to_string(),
port: Some(27017),
}],
read_concern: Some(ReadConcern::Custom("foo".to_string())),
original_uri: Some(uri.into()),
..Default::default()
}
);
}
#[test]
fn with_w_negative_int() {
assert!(ClientOptions::parse("mongodb://localhost:27017/?w=-1").is_err());
}
#[test]
fn with_w_non_negative_int() {
let uri = "mongodb://localhost:27017/?w=1";
let write_concern = WriteConcern::builder().w(Acknowledgment::from(1)).build();
assert_eq!(
ClientOptions::parse(uri).unwrap(),
ClientOptions {
hosts: vec![StreamAddress {
hostname: "localhost".to_string(),
port: Some(27017),
}],
write_concern: Some(write_concern),
original_uri: Some(uri.into()),
..Default::default()
}
);
}
#[test]
fn with_w_string() {
let uri = "mongodb://localhost:27017/?w=foo";
let write_concern = WriteConcern::builder()
.w(Acknowledgment::from("foo".to_string()))
.build();
assert_eq!(
ClientOptions::parse(uri).unwrap(),
ClientOptions {
hosts: vec![StreamAddress {
hostname: "localhost".to_string(),
port: Some(27017),
}],
write_concern: Some(write_concern),
original_uri: Some(uri.into()),
..Default::default()
}
);
}
#[test]
fn with_invalid_j() {
assert!(ClientOptions::parse("mongodb://localhost:27017/?journal=foo").is_err());
}
#[test]
fn with_j() {
let uri = "mongodb://localhost:27017/?journal=true";
let write_concern = WriteConcern::builder().journal(true).build();
assert_eq!(
ClientOptions::parse(uri).unwrap(),
ClientOptions {
hosts: vec![StreamAddress {
hostname: "localhost".to_string(),
port: Some(27017),
}],
write_concern: Some(write_concern),
original_uri: Some(uri.into()),
..Default::default()
}
);
}
#[test]
fn with_wtimeout_non_int() {
assert!(ClientOptions::parse("mongodb://localhost:27017/?wtimeoutMS=foo").is_err());
}
#[test]
fn with_wtimeout_negative_int() {
assert!(ClientOptions::parse("mongodb://localhost:27017/?wtimeoutMS=-1").is_err());
}
#[test]
fn with_wtimeout() {
let uri = "mongodb://localhost:27017/?wtimeoutMS=27";
let write_concern = WriteConcern::builder()
.w_timeout(Duration::from_millis(27))
.build();
assert_eq!(
ClientOptions::parse(uri).unwrap(),
ClientOptions {
hosts: vec![StreamAddress {
hostname: "localhost".to_string(),
port: Some(27017),
}],
write_concern: Some(write_concern),
original_uri: Some(uri.into()),
..Default::default()
}
);
}
#[test]
fn with_all_write_concern_options() {
let uri = "mongodb://localhost:27017/?w=majority&journal=false&wtimeoutMS=27";
let write_concern = WriteConcern::builder()
.w(Acknowledgment::Majority)
.journal(false)
.w_timeout(Duration::from_millis(27))
.build();
assert_eq!(
ClientOptions::parse(uri).unwrap(),
ClientOptions {
hosts: vec![StreamAddress {
hostname: "localhost".to_string(),
port: Some(27017),
}],
write_concern: Some(write_concern),
original_uri: Some(uri.into()),
..Default::default()
}
);
}
#[test]
fn with_invalid_read_preference_mode() {}
#[test]
fn with_mixed_options() {
let uri = "mongodb://localhost,localhost:27018/?w=majority&readConcernLevel=majority&\
journal=false&wtimeoutMS=27&replicaSet=foo&heartbeatFrequencyMS=1000&\
localThresholdMS=4000&readPreference=secondaryPreferred&readpreferencetags=dc:\
ny,rack:1&serverselectiontimeoutms=2000&readpreferencetags=dc:ny&\
readpreferencetags=";
let write_concern = WriteConcern::builder()
.w(Acknowledgment::Majority)
.journal(false)
.w_timeout(Duration::from_millis(27))
.build();
assert_eq!(
ClientOptions::parse(uri).unwrap(),
ClientOptions {
hosts: vec![
StreamAddress {
hostname: "localhost".to_string(),
port: None,
},
StreamAddress {
hostname: "localhost".to_string(),
port: Some(27018),
},
],
selection_criteria: Some(
ReadPreference::SecondaryPreferred {
tag_sets: Some(vec![
tag_set! {
"dc" => "ny",
"rack" => "1"
},
tag_set! {
"dc" => "ny"
},
tag_set! {},
]),
max_staleness: None,
}
.into()
),
read_concern: Some(ReadConcern::Majority),
write_concern: Some(write_concern),
repl_set_name: Some("foo".to_string()),
heartbeat_freq: Some(Duration::from_millis(1000)),
local_threshold: Some(Duration::from_millis(4000)),
server_selection_timeout: Some(Duration::from_millis(2000)),
original_uri: Some(uri.into()),
..Default::default()
}
);
}
}