forked from mongodb/mongo-rust-driver
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoptions.rs
2671 lines (2377 loc) · 94.8 KB
/
options.rs
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
#[cfg(test)]
mod test;
mod bulk_write;
mod parse;
mod resolver_config;
use std::{
cmp::Ordering,
collections::HashSet,
convert::TryFrom,
fmt::{self, Display, Formatter, Write},
hash::{Hash, Hasher},
path::PathBuf,
str::FromStr,
time::Duration,
};
use bson::UuidRepresentation;
use derive_where::derive_where;
use once_cell::sync::Lazy;
use serde::{de::Unexpected, Deserialize, Deserializer, Serialize};
use serde_with::skip_serializing_none;
use strsim::jaro_winkler;
use typed_builder::TypedBuilder;
#[cfg(any(
feature = "zstd-compression",
feature = "zlib-compression",
feature = "snappy-compression"
))]
use crate::options::Compressor;
#[cfg(test)]
use crate::srv::LookupHosts;
use crate::{
bson::{doc, Bson, Document},
client::auth::{AuthMechanism, Credential},
concern::{Acknowledgment, ReadConcern, WriteConcern},
error::{Error, ErrorKind, Result},
event::EventHandler,
options::ReadConcernLevel,
sdam::{verify_max_staleness, DEFAULT_HEARTBEAT_FREQUENCY, MIN_HEARTBEAT_FREQUENCY},
selection_criteria::{ReadPreference, SelectionCriteria, TagSet},
serde_util,
srv::{OriginalSrvInfo, SrvResolver},
};
pub use bulk_write::*;
#[cfg(feature = "dns-resolver")]
pub use resolver_config::ResolverConfig;
#[cfg(not(feature = "dns-resolver"))]
pub(crate) use resolver_config::ResolverConfig;
pub(crate) const DEFAULT_PORT: u16 = 27017;
const URI_OPTIONS: &[&str] = &[
"appname",
"authmechanism",
"authsource",
"authmechanismproperties",
"compressors",
"connecttimeoutms",
"directconnection",
"heartbeatfrequencyms",
"journal",
"localthresholdms",
"maxidletimems",
"maxstalenessseconds",
"maxpoolsize",
"minpoolsize",
"maxconnecting",
"readconcernlevel",
"readpreference",
"readpreferencetags",
"replicaset",
"retrywrites",
"retryreads",
"servermonitoringmode",
"serverselectiontimeoutms",
"sockettimeoutms",
"tls",
"ssl",
"tlsinsecure",
"tlsallowinvalidcertificates",
"tlscafile",
"tlscertificatekeyfile",
"uuidRepresentation",
"w",
"waitqueuetimeoutms",
"wtimeoutms",
"zlibcompressionlevel",
];
/// 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 USERINFO_RESERVED_CHARACTERS: Lazy<HashSet<&'static char>> =
Lazy::new(|| [':', '/', '?', '#', '[', ']', '@'].iter().collect());
static ILLEGAL_DATABASE_CHARACTERS: Lazy<HashSet<&'static char>> =
Lazy::new(|| ['/', '\\', ' ', '"', '$'].iter().collect());
/// An enum representing the address of a MongoDB server.
#[derive(Clone, Debug, Eq, Serialize)]
#[non_exhaustive]
pub enum ServerAddress {
/// A TCP/IP host and port combination.
Tcp {
/// The hostname or IP address where the MongoDB server can be found.
host: String,
/// The TCP port that the MongoDB server is listening on.
///
/// The default is 27017.
port: Option<u16>,
},
/// A Unix Domain Socket path.
#[cfg(unix)]
Unix {
/// The path to the Unix Domain Socket.
path: PathBuf,
},
}
impl<'de> Deserialize<'de> for ServerAddress {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s: String = Deserialize::deserialize(deserializer)?;
Self::parse(s.as_str())
.map_err(|e| <D::Error as serde::de::Error>::custom(format!("{}", e)))
}
}
impl Default for ServerAddress {
fn default() -> Self {
Self::Tcp {
host: "localhost".into(),
port: None,
}
}
}
impl PartialEq for ServerAddress {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(
Self::Tcp { host, port },
Self::Tcp {
host: other_host,
port: other_port,
},
) => host == other_host && port.unwrap_or(27017) == other_port.unwrap_or(27017),
#[cfg(unix)]
(Self::Unix { path }, Self::Unix { path: other_path }) => path == other_path,
#[cfg(unix)]
_ => false,
}
}
}
impl Hash for ServerAddress {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
match self {
Self::Tcp { host, port } => {
host.hash(state);
port.unwrap_or(27017).hash(state);
}
#[cfg(unix)]
Self::Unix { path } => path.hash(state),
}
}
}
impl FromStr for ServerAddress {
type Err = Error;
fn from_str(address: &str) -> Result<Self> {
ServerAddress::parse(address)
}
}
impl ServerAddress {
/// Parses an address string into a `ServerAddress`.
pub fn parse(address: impl AsRef<str>) -> Result<Self> {
let address = address.as_ref();
// checks if the address is a unix domain socket
#[cfg(unix)]
{
if address.ends_with(".sock") {
return Ok(ServerAddress::Unix {
path: PathBuf::from(address),
});
}
}
let mut parts = address.split(':');
let hostname = match parts.next() {
Some(part) => {
if part.is_empty() {
return Err(ErrorKind::InvalidArgument {
message: format!(
"invalid server address: \"{}\"; hostname cannot be empty",
address
),
}
.into());
}
part
}
None => {
return Err(ErrorKind::InvalidArgument {
message: format!("invalid server address: \"{}\"", address),
}
.into())
}
};
let port = match parts.next() {
Some(part) => {
let port = u16::from_str(part).map_err(|_| ErrorKind::InvalidArgument {
message: format!(
"port must be valid 16-bit unsigned integer, instead got: {}",
part
),
})?;
if port == 0 {
return Err(ErrorKind::InvalidArgument {
message: format!(
"invalid server address: \"{}\"; port must be non-zero",
address
),
}
.into());
}
if parts.next().is_some() {
return Err(ErrorKind::InvalidArgument {
message: format!(
"address \"{}\" contains more than one unescaped ':'",
address
),
}
.into());
}
Some(port)
}
None => None,
};
Ok(ServerAddress::Tcp {
host: hostname.to_lowercase(),
port,
})
}
#[cfg(feature = "dns-resolver")]
pub(crate) fn host(&self) -> std::borrow::Cow<'_, str> {
match self {
Self::Tcp { host, .. } => std::borrow::Cow::Borrowed(host.as_str()),
#[cfg(unix)]
Self::Unix { path } => path.to_string_lossy(),
}
}
#[cfg(feature = "dns-resolver")]
pub(crate) fn port(&self) -> Option<u16> {
match self {
Self::Tcp { port, .. } => *port,
#[cfg(unix)]
Self::Unix { .. } => None,
}
}
}
impl fmt::Display for ServerAddress {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Tcp { host, port } => {
write!(fmt, "{}:{}", host, port.unwrap_or(DEFAULT_PORT))
}
#[cfg(unix)]
Self::Unix { path } => write!(fmt, "{}", path.display()),
}
}
}
/// Specifies the server API version to declare
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub enum ServerApiVersion {
/// Use API version 1.
#[serde(rename = "1")]
V1,
}
impl FromStr for ServerApiVersion {
type Err = Error;
fn from_str(str: &str) -> Result<Self> {
match str {
"1" => Ok(Self::V1),
_ => Err(ErrorKind::InvalidArgument {
message: format!("invalid server api version string: {}", str),
}
.into()),
}
}
}
impl Display for ServerApiVersion {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::V1 => write!(f, "1"),
}
}
}
impl<'de> Deserialize<'de> for ServerApiVersion {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
ServerApiVersion::from_str(&s).map_err(|_| {
serde::de::Error::invalid_value(Unexpected::Str(&s), &"a valid version number")
})
}
}
/// Options used to declare a stable server API. For more information, see the [Stable API](
/// https://www.mongodb.com/docs/v5.0/reference/stable-api/) manual page.
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct ServerApi {
/// The declared API version.
#[serde(rename = "apiVersion")]
#[builder(!default)]
pub version: ServerApiVersion,
/// Whether the MongoDB server should reject all commands that are not part of the
/// declared API version. This includes command options and aggregation pipeline stages.
#[serde(rename = "apiStrict")]
pub strict: Option<bool>,
/// Whether the MongoDB server should return command failures when functionality that is
/// deprecated from the declared API version is used.
/// Note that at the time of this writing, no deprecations in version 1 exist.
#[serde(rename = "apiDeprecationErrors")]
pub deprecation_errors: Option<bool>,
}
/// Contains the options that can be used to create a new [`Client`](../struct.Client.html).
#[derive(Clone, Deserialize, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
#[derive_where(Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
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_connection` field to `true`.
#[builder(default_code = "vec![ServerAddress::Tcp {
host: \"localhost\".to_string(),
port: Some(27017),
}]")]
#[serde(default = "default_hosts")]
pub hosts: Vec<ServerAddress>,
/// 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.
pub app_name: Option<String>,
/// The allowed compressors to use to compress messages sent to and decompress messages
/// received from the server. This list should be specified in priority order, as the
/// compressor used for messages will be the first compressor in this list that is also
/// supported by the server selected for operations.
#[cfg(any(
feature = "zstd-compression",
feature = "zlib-compression",
feature = "snappy-compression"
))]
#[serde(skip)]
pub compressors: Option<Vec<Compressor>>,
/// The handler that should process all Connection Monitoring and Pooling events.
#[derive_where(skip)]
#[builder(setter(strip_option))]
#[serde(skip)]
pub cmap_event_handler: Option<EventHandler<crate::event::cmap::CmapEvent>>,
/// The handler that should process all command-related events.
///
/// Note that monitoring command events may incur a performance penalty.
#[derive_where(skip)]
#[builder(setter(strip_option))]
#[serde(skip)]
pub command_event_handler: Option<EventHandler<crate::event::command::CommandEvent>>,
/// The connect timeout passed to each underlying TcpStream when attemtping to connect to the
/// server.
///
/// The default value is 10 seconds.
pub connect_timeout: Option<Duration>,
/// The credential to use for authenticating connections made by this client.
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.
pub direct_connection: Option<bool>,
/// Extra information to append to the driver version in the metadata of the handshake with the
/// server. This should be used by libraries wrapping the driver, e.g. ODMs.
pub driver_info: Option<DriverInfo>,
/// The amount of time each monitoring thread should wait between performing server checks.
///
/// The default value is 10 seconds.
pub heartbeat_freq: Option<Duration>,
/// Whether or not the client is connecting to a MongoDB cluster through a load balancer.
#[builder(setter(skip))]
#[serde(rename = "loadbalanced")]
pub load_balanced: Option<bool>,
/// 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.
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.
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 10.
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.
pub min_pool_size: Option<u32>,
/// The maximum number of new connections that can be created concurrently.
///
/// If specified, this value must be greater than 0. The default is 2.
pub max_connecting: Option<u32>,
/// Specifies the default read concern for operations performed on the Client. See the
/// ReadConcern type documentation for more details.
pub read_concern: Option<ReadConcern>,
/// The name of the replica set that the Client should connect to.
pub repl_set_name: Option<String>,
/// Whether or not the client should retry a read operation if the operation fails.
///
/// The default value is true.
pub retry_reads: Option<bool>,
/// Whether or not the client should retry a write operation if the operation fails.
///
/// The default value is true.
pub retry_writes: Option<bool>,
/// Configures which server monitoring protocol to use.
///
/// The default is [`Auto`](ServerMonitoringMode::Auto).
pub server_monitoring_mode: Option<ServerMonitoringMode>,
/// The handler that should process all Server Discovery and Monitoring events.
#[derive_where(skip)]
#[builder(setter(strip_option))]
#[serde(skip)]
pub sdam_event_handler: Option<EventHandler<crate::event::sdam::SdamEvent>>,
/// The default selection criteria for operations performed on the Client. See the
/// SelectionCriteria type documentation for more details.
pub selection_criteria: Option<SelectionCriteria>,
/// The declared API version for this client.
/// The declared API version is applied to all commands run through the client, including those
/// sent through any handle derived from the client.
///
/// Specifying stable API options in the command document passed to `run_command` AND
/// declaring an API version on the client is not supported and is considered undefined
/// behaviour. To run any command with a different API version or without declaring one, create
/// a separate client that declares the appropriate API version.
///
/// For more information, see the [Stable API](
/// https://www.mongodb.com/docs/v5.0/reference/stable-api/) manual page.
pub server_api: Option<ServerApi>,
/// The amount of time the Client should attempt to select a server for an operation before
/// timing outs
///
/// The default value is 30 seconds.
pub server_selection_timeout: Option<Duration>,
/// Default database for this client.
///
/// By default, no default database is specified.
pub default_database: Option<String>,
#[builder(setter(skip))]
#[derive_where(skip(Debug))]
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.
pub tls: Option<Tls>,
/// The maximum number of bytes that the driver should include in a tracing event
/// or log message's extended JSON string representation of a BSON document, e.g. a
/// command or reply from the server.
/// If truncation of a document at the exact specified length would occur in the middle
/// of a Unicode codepoint, the document will be truncated at the closest larger length
/// which falls on a boundary between codepoints.
/// Note that in cases where truncation occurs the output will not be valid JSON.
///
/// The default value is 1000.
#[cfg(feature = "tracing-unstable")]
pub tracing_max_document_length_bytes: Option<usize>,
/// Specifies the default write concern for operations performed on the Client. See the
/// WriteConcern type documentation for more details.
pub write_concern: Option<WriteConcern>,
/// Limit on the number of mongos connections that may be created for sharded topologies.
pub srv_max_hosts: Option<u32>,
/// Information from the SRV URI that generated these client options, if applicable.
#[builder(setter(skip))]
#[serde(skip)]
#[derive_where(skip(Debug))]
pub(crate) original_srv_info: Option<OriginalSrvInfo>,
#[cfg(test)]
#[builder(setter(skip))]
#[derive_where(skip(Debug))]
pub(crate) original_uri: Option<String>,
/// Configuration of the DNS resolver used for SRV and TXT lookups.
/// By default, the host system's resolver configuration will be used.
///
/// On Windows, there is a known performance issue in [hickory_resolver] with using the default
/// system configuration, so a custom configuration is recommended.
#[builder(setter(skip))]
#[serde(skip)]
#[derive_where(skip(Debug))]
#[cfg(feature = "dns-resolver")]
pub(crate) resolver_config: Option<ResolverConfig>,
/// Control test behavior of the client.
#[cfg(test)]
#[builder(setter(skip))]
#[serde(skip)]
#[derive_where(skip)]
pub(crate) test_options: Option<TestOptions>,
}
#[cfg(test)]
#[derive(Debug, Clone, Default)]
pub(crate) struct TestOptions {
/// Override MIN_HEARTBEAT_FREQUENCY.
pub(crate) min_heartbeat_freq: Option<Duration>,
/// Disable server and SRV-polling monitor threads.
pub(crate) disable_monitoring_threads: bool,
/// Mock response for `SrvPollingMonitor::lookup_hosts`.
pub(crate) mock_lookup_hosts: Option<Result<LookupHosts>>,
/// Async-capable command event listener.
pub(crate) async_event_listener: Option<TestEventSender>,
}
pub(crate) type TestEventSender = tokio::sync::mpsc::Sender<
crate::runtime::AcknowledgedMessage<crate::event::command::CommandEvent>,
>;
fn default_hosts() -> Vec<ServerAddress> {
vec![ServerAddress::default()]
}
impl Default for ClientOptions {
fn default() -> Self {
Self::builder().build()
}
}
#[cfg(test)]
impl Serialize for ClientOptions {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
#[derive(Serialize)]
struct ClientOptionsHelper<'a> {
appname: &'a Option<String>,
#[serde(serialize_with = "serde_util::serialize_duration_option_as_int_millis")]
connecttimeoutms: &'a Option<Duration>,
#[serde(flatten, serialize_with = "Credential::serialize_for_client_options")]
credential: &'a Option<Credential>,
directconnection: &'a Option<bool>,
#[serde(serialize_with = "serde_util::serialize_duration_option_as_int_millis")]
heartbeatfrequencyms: &'a Option<Duration>,
#[serde(serialize_with = "serde_util::serialize_duration_option_as_int_millis")]
localthresholdms: &'a Option<Duration>,
#[serde(serialize_with = "serde_util::serialize_duration_option_as_int_millis")]
maxidletimems: &'a Option<Duration>,
maxpoolsize: &'a Option<u32>,
minpoolsize: &'a Option<u32>,
maxconnecting: &'a Option<u32>,
#[serde(flatten, serialize_with = "ReadConcern::serialize_for_client_options")]
readconcern: &'a Option<ReadConcern>,
replicaset: &'a Option<String>,
retryreads: &'a Option<bool>,
retrywrites: &'a Option<bool>,
servermonitoringmode: Option<String>,
#[serde(
flatten,
serialize_with = "SelectionCriteria::serialize_for_client_options"
)]
selectioncriteria: &'a Option<SelectionCriteria>,
#[serde(serialize_with = "serde_util::serialize_duration_option_as_int_millis")]
serverselectiontimeoutms: &'a Option<Duration>,
#[serde(serialize_with = "serde_util::serialize_duration_option_as_int_millis")]
sockettimeoutms: &'a Option<Duration>,
#[serde(flatten, serialize_with = "Tls::serialize_for_client_options")]
tls: &'a Option<Tls>,
#[serde(flatten, serialize_with = "WriteConcern::serialize_for_client_options")]
writeconcern: &'a Option<WriteConcern>,
zlibcompressionlevel: &'a Option<i32>,
loadbalanced: &'a Option<bool>,
srvmaxhosts: Option<i32>,
}
let client_options = ClientOptionsHelper {
appname: &self.app_name,
connecttimeoutms: &self.connect_timeout,
credential: &self.credential,
directconnection: &self.direct_connection,
heartbeatfrequencyms: &self.heartbeat_freq,
localthresholdms: &self.local_threshold,
maxidletimems: &self.max_idle_time,
maxpoolsize: &self.max_pool_size,
minpoolsize: &self.min_pool_size,
maxconnecting: &self.max_connecting,
readconcern: &self.read_concern,
replicaset: &self.repl_set_name,
retryreads: &self.retry_reads,
retrywrites: &self.retry_writes,
servermonitoringmode: self
.server_monitoring_mode
.as_ref()
.map(|m| format!("{:?}", m).to_lowercase()),
selectioncriteria: &self.selection_criteria,
serverselectiontimeoutms: &self.server_selection_timeout,
sockettimeoutms: &self.socket_timeout,
tls: &self.tls,
writeconcern: &self.write_concern,
loadbalanced: &self.load_balanced,
zlibcompressionlevel: &None,
srvmaxhosts: self
.srv_max_hosts
.map(|v| v.try_into())
.transpose()
.map_err(serde::ser::Error::custom)?,
};
client_options.serialize(serializer)
}
}
/// Contains the options that can be set via a MongoDB connection string.
///
/// The format of a MongoDB connection string is described [here](https://www.mongodb.com/docs/manual/reference/connection-string/#connection-string-formats).
#[derive(Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct ConnectionString {
/// The initial list of seeds that the Client should connect to, or a DNS name used for SRV
/// lookup of the initial seed list.
///
/// 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_connection` field to `true`.
pub host_info: HostInfo,
/// 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.
pub app_name: Option<String>,
/// The TLS configuration for the Client to use in its connections with the server.
///
/// By default, TLS is disabled.
pub tls: Option<Tls>,
/// The amount of time each monitoring thread should wait between performing server checks.
///
/// The default value is 10 seconds.
pub heartbeat_frequency: 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.
pub local_threshold: Option<Duration>,
/// Specifies the default read concern for operations performed on the Client. See the
/// ReadConcern type documentation for more details.
pub read_concern: Option<ReadConcern>,
/// The name of the replica set that the Client should connect to.
pub replica_set: Option<String>,
/// Specifies the default write concern for operations performed on the Client. See the
/// WriteConcern type documentation for more details.
pub write_concern: Option<WriteConcern>,
/// The amount of time the Client should attempt to select a server for an operation before
/// timing outs
///
/// The default value is 30 seconds.
pub server_selection_timeout: 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 10.
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.
pub min_pool_size: Option<u32>,
/// The maximum number of new connections that can be created concurrently.
///
/// If specified, this value must be greater than 0. The default is 2.
pub max_connecting: Option<u32>,
/// 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.
pub max_idle_time: Option<Duration>,
#[cfg(any(
feature = "zstd-compression",
feature = "zlib-compression",
feature = "snappy-compression"
))]
/// The compressors that the Client is willing to use in the order they are specified
/// in the configuration. The Client sends this list of compressors to the server.
/// The server responds with the intersection of its supported list of compressors.
/// The order of compressors indicates preference of compressors.
pub compressors: Option<Vec<Compressor>>,
/// The connect timeout passed to each underlying TcpStream when attempting to connect to the
/// server.
///
/// The default value is 10 seconds.
pub connect_timeout: Option<Duration>,
/// Whether or not the client should retry a read operation if the operation fails.
///
/// The default value is true.
pub retry_reads: Option<bool>,
/// Whether or not the client should retry a write operation if the operation fails.
///
/// The default value is true.
pub retry_writes: Option<bool>,
/// Configures which server monitoring protocol to use.
///
/// The default is [`Auto`](ServerMonitoringMode::Auto).
pub server_monitoring_mode: Option<ServerMonitoringMode>,
/// Specifies whether the Client should directly connect to a single host rather than
/// autodiscover all servers in the cluster.
///
/// The default value is false.
pub direct_connection: Option<bool>,
/// The credential to use for authenticating connections made by this client.
pub credential: Option<Credential>,
/// Default database for this client.
///
/// By default, no default database is specified.
pub default_database: Option<String>,
/// Whether or not the client is connecting to a MongoDB cluster through a load balancer.
pub load_balanced: Option<bool>,
/// Amount of time spent attempting to send or receive on a socket before timing out; note that
/// this only applies to application operations, not server discovery and monitoring.
pub socket_timeout: Option<Duration>,
/// Default read preference for the client.
pub read_preference: Option<ReadPreference>,
/// The [`UuidRepresentation`] to use when decoding [`Binary`](bson::Binary) values with the
/// [`UuidOld`](bson::spec::BinarySubtype::UuidOld) subtype. This is not used by the
/// driver; client code can use this when deserializing relevant values with
/// [`Binary::to_uuid_with_representation`](bson::binary::Binary::to_uuid_with_representation).
pub uuid_representation: Option<UuidRepresentation>,
/// Limit on the number of mongos connections that may be created for sharded topologies.
pub srv_max_hosts: Option<u32>,
wait_queue_timeout: Option<Duration>,
tls_insecure: Option<bool>,
#[cfg(test)]
original_uri: String,
}
/// Elements from the connection string that are not top-level fields in `ConnectionString`.
#[derive(Debug, Default)]
struct ConnectionStringParts {
read_preference_tags: Option<Vec<TagSet>>,
max_staleness: Option<Duration>,
auth_mechanism: Option<AuthMechanism>,
auth_mechanism_properties: Option<Document>,
zlib_compression: Option<i32>,
auth_source: Option<String>,
}
/// Specification for mongodb server connections.
#[derive(Debug, PartialEq, Clone)]
#[non_exhaustive]
pub enum HostInfo {
/// A set of addresses.
HostIdentifiers(Vec<ServerAddress>),
/// A DNS record for SRV lookup.
DnsRecord(String),
}
impl Default for HostInfo {
fn default() -> Self {
Self::HostIdentifiers(vec![])
}
}
impl HostInfo {
async fn resolve(self, resolver_config: Option<ResolverConfig>) -> Result<ResolvedHostInfo> {
Ok(match self {
Self::HostIdentifiers(hosts) => ResolvedHostInfo::HostIdentifiers(hosts),
Self::DnsRecord(hostname) => {
let mut resolver = SrvResolver::new(resolver_config.clone()).await?;
let config = resolver.resolve_client_options(&hostname).await?;
ResolvedHostInfo::DnsRecord { hostname, config }
}
})
}
}
enum ResolvedHostInfo {
HostIdentifiers(Vec<ServerAddress>),
DnsRecord {
hostname: String,
config: crate::srv::ResolvedConfig,
},
}
/// Specifies whether TLS configuration should be used with the operations that the
/// [`Client`](../struct.Client.html) performs.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub enum Tls {
/// Enable TLS with the specified options.
Enabled(TlsOptions),
/// Disable TLS.
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))
}
}
impl Tls {
#[cfg(test)]
pub(crate) fn serialize_for_client_options<S>(
tls: &Option<Tls>,
serializer: S,
) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match tls {
Some(Tls::Enabled(tls_options)) => {
TlsOptions::serialize_for_client_options(tls_options, serializer)
}
_ => serializer.serialize_none(),
}
}
}
/// Specifies the TLS configuration that the [`Client`](../struct.Client.html) should use.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
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.
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.
pub ca_file_path: Option<PathBuf>,
/// 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.
pub cert_key_file_path: Option<PathBuf>,
/// Whether or not the [`Client`](../struct.Client.html) should return an error if the hostname
/// is invalid.
///
/// The default value is to error on invalid hostnames.
#[cfg(feature = "openssl-tls")]