-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathMongoConnectionString.swift
1419 lines (1318 loc) · 64.8 KB
/
MongoConnectionString.swift
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
import CLibMongoC
import Foundation
import SwiftBSON
/// Represents a MongoDB connection string.
/// - SeeAlso: https://docs.mongodb.com/manual/reference/connection-string/
public struct MongoConnectionString: Codable, LosslessStringConvertible {
/// Characters that must not be present in a database name.
private static let forbiddenDBCharacters = ["/", "\\", " ", "\"", "$"]
/// General delimiters as defined by RFC 3986. These characters must be percent-encoded when present in the hosts,
/// default authentication database, and user info.
/// - SeeAlso: https://datatracker.ietf.org/doc/html/rfc3986#section-2.2
fileprivate static let genDelims = ":/?#[]@"
/// Characters that do not need to be percent-encoded when reconstructing the hosts, default authentication
/// database, and user info.
fileprivate static let allowedForNonOptionEncoding = CharacterSet(charactersIn: genDelims).inverted
/// Characters that do not need to be percent-encoded when reconstructing URI options.
fileprivate static let allowedForOptionEncoding = CharacterSet(charactersIn: "=&,:").inverted
internal enum OptionName: String {
case appName = "appname"
case authSource = "authsource"
case authMechanism = "authmechanism"
case authMechanismProperties = "authmechanismproperties"
case compressors
case connectTimeoutMS = "connecttimeoutms"
case directConnection = "directconnection"
case heartbeatFrequencyMS = "heartbeatfrequencyms"
case journal
case loadBalanced = "loadbalanced"
case localThresholdMS = "localthresholdms"
case maxPoolSize = "maxpoolsize"
case maxStalenessSeconds = "maxstalenessseconds"
case readConcernLevel = "readconcernlevel"
case readPreference = "readpreference"
case readPreferenceTags = "readpreferencetags"
case replicaSet = "replicaset"
case retryReads = "retryreads"
case retryWrites = "retrywrites"
case serverSelectionTimeoutMS = "serverselectiontimeoutms"
case socketTimeoutMS = "sockettimeoutms"
case srvMaxHosts = "srvmaxhosts"
case srvServiceName = "srvservicename"
case ssl
case tls
case tlsAllowInvalidCertificates = "tlsallowinvalidcertificates"
case tlsAllowInvalidHostnames = "tlsallowinvalidhostnames"
case tlsCAFile = "tlscafile"
case tlsCertificateKeyFile = "tlscertificatekeyfile"
case tlsCertificateKeyFilePassword = "tlscertificatekeyfilepassword"
case tlsDisableCertificateRevocationCheck = "tlsdisablecertificaterevocationcheck"
case tlsDisableOCSPEndpointCheck = "tlsdisableocspendpointcheck"
case tlsInsecure = "tlsinsecure"
case w
case wTimeoutMS = "wtimeoutms"
case zlibCompressionLevel = "zlibcompressionlevel"
}
/// Represents a connection string scheme.
public struct Scheme: LosslessStringConvertible, Equatable {
/// Indicates that this connection string uses the scheme `mongodb`.
public static let mongodb = Scheme(.mongodb)
/// Indicates that this connection string uses the scheme `mongodb+srv`.
public static let srv = Scheme(.srv)
/// Internal representation of a scheme.
private enum _Scheme: String {
case mongodb
case srv = "mongodb+srv"
}
private let _scheme: _Scheme
private init(_ value: _Scheme) {
self._scheme = value
}
/// LosslessStringConvertible` protocol requirements
public init?(_ description: String) {
guard let _scheme = _Scheme(rawValue: description) else {
return nil
}
self.init(_scheme)
}
public var description: String { self._scheme.rawValue }
}
/// A struct representing a host identifier, consisting of a host and an optional port.
/// In standard connection strings, this describes the address of a mongod or mongos to connect to.
/// In mongodb+srv connection strings, this describes a DNS name to be queried for SRV and TXT records.
public struct HostIdentifier: Equatable, CustomStringConvertible {
private static func parsePort(from: String) throws -> UInt16 {
guard let port = UInt16(from), port > 0 else {
throw MongoError.InvalidArgumentError(
message: "port must be a valid, positive unsigned 16 bit integer"
)
}
return port
}
internal enum HostType: String {
case ipv4
case ipLiteral = "ip_literal"
case hostname
case unixDomainSocket
}
/// The hostname or IP address.
public let host: String
/// The port number.
public let port: UInt16?
internal let type: HostType
/// Initializes a ServerAddress, using the default localhost:27017 if a host/port is not provided.
internal init(_ hostAndPort: String = "localhost:27017") throws {
// Check if host is an IPv6 literal.
if hostAndPort.first == "[" {
let ipLiteralRegex = try NSRegularExpression(pattern: #"^\[(.*)\](?::([0-9]+))?$"#)
guard
let match = ipLiteralRegex.firstMatch(
in: hostAndPort,
range: NSRange(hostAndPort.startIndex..<hostAndPort.endIndex, in: hostAndPort)
),
let hostRange = Range(match.range(at: 1), in: hostAndPort)
else {
throw MongoError.InvalidArgumentError(message: "couldn't parse address from \(hostAndPort)")
}
self.host = String(hostAndPort[hostRange])
if let portRange = Range(match.range(at: 2), in: hostAndPort) {
self.port = try HostIdentifier.parsePort(from: String(hostAndPort[portRange]))
} else {
self.port = nil
}
self.type = .ipLiteral
} else {
let parts = hostAndPort.components(separatedBy: ":")
guard parts.count <= 2 else {
throw MongoError.InvalidArgumentError(
message: "expected only a single port delimiter ':' in \(hostAndPort)"
)
}
let host = parts[0]
if host.hasSuffix(".sock") {
self.host = try host.getPercentDecoded(forKey: "UNIX domain socket")
self.type = .unixDomainSocket
} else if host.isIPv4() {
self.host = host
self.type = .ipv4
} else {
self.host = try host.getPercentDecoded(forKey: "hostname")
self.type = .hostname
}
if parts.count > 1 {
self.port = try HostIdentifier.parsePort(from: parts[1])
} else {
self.port = nil
}
}
}
public var description: String {
var hostDescription = ""
switch self.type {
case .ipLiteral:
hostDescription += "[\(self.host)]"
case .ipv4:
hostDescription += self.host
case .unixDomainSocket, .hostname:
hostDescription += self.host.getPercentEncoded(
withAllowedCharacters: MongoConnectionString.allowedForNonOptionEncoding
)
}
if let port = self.port {
hostDescription += ":\(port)"
}
return hostDescription
}
}
private struct Options {
fileprivate var appName: String?
fileprivate var authSource: String?
fileprivate var authMechanism: MongoCredential.Mechanism?
fileprivate var authMechanismProperties: BSONDocument?
fileprivate var compressors: [String]?
fileprivate var connectTimeoutMS: Int?
fileprivate var directConnection: Bool?
fileprivate var heartbeatFrequencyMS: Int?
fileprivate var journal: Bool?
fileprivate var loadBalanced: Bool?
fileprivate var localThresholdMS: Int?
fileprivate var maxPoolSize: Int?
fileprivate var maxStalenessSeconds: Int?
fileprivate var readConcern: ReadConcern?
fileprivate var readPreference: String?
fileprivate var readPreferenceTags: [BSONDocument]?
fileprivate var replicaSet: String?
fileprivate var retryReads: Bool?
fileprivate var retryWrites: Bool?
fileprivate var serverSelectionTimeoutMS: Int?
fileprivate var socketTimeoutMS: Int?
fileprivate var srvMaxHosts: Int?
fileprivate var srvServiceName: String?
fileprivate var ssl: Bool?
fileprivate var tls: Bool?
fileprivate var tlsAllowInvalidCertificates: Bool?
fileprivate var tlsAllowInvalidHostnames: Bool?
fileprivate var tlsCAFile: URL?
fileprivate var tlsCertificateKeyFile: URL?
fileprivate var tlsCertificateKeyFilePassword: String?
fileprivate var tlsDisableCertificateRevocationCheck: Bool?
fileprivate var tlsDisableOCSPEndpointCheck: Bool?
fileprivate var tlsInsecure: Bool?
fileprivate var w: WriteConcern.W?
fileprivate var wTimeoutMS: Int?
fileprivate var zlibCompressionLevel: Int?
fileprivate init(_ uriOptions: Substring) throws {
let options = uriOptions.components(separatedBy: "&")
// tracks options that have already been set to error on duplicates
var setOptions: Set<String> = []
for option in options {
let nameAndValue = option.components(separatedBy: "=")
guard nameAndValue.count == 2 else {
throw MongoError.InvalidArgumentError(
message: "Option name and value must be of the form <name>=<value> not containing unescaped"
+ " equals signs"
)
}
guard let name = OptionName(rawValue: nameAndValue[0].lowercased()) else {
throw MongoError.InvalidArgumentError(
message: "Connection string contains unsupported option: \(nameAndValue[0])"
)
}
// read preference tags can be specified multiple times
guard setOptions.insert(name.rawValue).inserted || name == .readPreferenceTags else {
throw MongoError.InvalidArgumentError(
message: "Connection string contains duplicate option: \(name)"
)
}
let value = try nameAndValue[1].getPercentDecoded(forKey: name.rawValue)
switch name {
case .appName:
self.appName = value
case .authSource:
self.authSource = value
case .authMechanism:
self.authMechanism = try MongoCredential.Mechanism(value)
case .authMechanismProperties:
self.authMechanismProperties = try Self.parseAuthMechanismProperties(properties: value)
case .compressors:
self.compressors = value.components(separatedBy: ",")
case .connectTimeoutMS:
self.connectTimeoutMS = try value.getInt(forKey: name.rawValue)
case .directConnection:
self.directConnection = try value.getBool(forKey: name.rawValue)
case .heartbeatFrequencyMS:
self.heartbeatFrequencyMS = try value.getInt(forKey: name.rawValue)
case .journal:
self.journal = try value.getBool(forKey: name.rawValue)
case .loadBalanced:
self.loadBalanced = try value.getBool(forKey: name.rawValue)
case .localThresholdMS:
self.localThresholdMS = try value.getInt(forKey: name.rawValue)
case .maxPoolSize:
self.maxPoolSize = try value.getInt(forKey: name.rawValue)
case .maxStalenessSeconds:
self.maxStalenessSeconds = try value.getInt(forKey: name.rawValue)
case .readConcernLevel:
self.readConcern = ReadConcern(value)
case .readPreference:
self.readPreference = value
case .readPreferenceTags:
let tags = try Self.parseReadPreferenceTags(tags: value)
if self.readPreferenceTags == nil {
self.readPreferenceTags = []
}
self.readPreferenceTags?.append(tags)
case .replicaSet:
self.replicaSet = value
case .retryReads:
self.retryReads = try value.getBool(forKey: name.rawValue)
case .retryWrites:
self.retryWrites = try value.getBool(forKey: name.rawValue)
case .serverSelectionTimeoutMS:
self.serverSelectionTimeoutMS = try value.getInt(forKey: name.rawValue)
case .socketTimeoutMS:
self.socketTimeoutMS = try value.getInt(forKey: name.rawValue)
case .srvMaxHosts:
self.srvMaxHosts = try value.getInt(forKey: name.rawValue)
case .srvServiceName:
self.srvServiceName = value
case .ssl:
self.ssl = try value.getBool(forKey: name.rawValue)
case .tls:
self.tls = try value.getBool(forKey: name.rawValue)
case .tlsAllowInvalidCertificates:
self.tlsAllowInvalidCertificates = try value.getBool(forKey: name.rawValue)
case .tlsAllowInvalidHostnames:
self.tlsAllowInvalidHostnames = try value.getBool(forKey: name.rawValue)
case .tlsCAFile:
self.tlsCAFile = URL(string: value)
case .tlsCertificateKeyFile:
self.tlsCertificateKeyFile = URL(string: value)
case .tlsCertificateKeyFilePassword:
self.tlsCertificateKeyFilePassword = value
case .tlsDisableCertificateRevocationCheck:
self.tlsDisableCertificateRevocationCheck = try value.getBool(forKey: name.rawValue)
case .tlsDisableOCSPEndpointCheck:
self.tlsDisableOCSPEndpointCheck = try value.getBool(forKey: name.rawValue)
case .tlsInsecure:
self.tlsInsecure = try value.getBool(forKey: name.rawValue)
case .w:
self.w = try WriteConcern.W(value)
case .wTimeoutMS:
self.wTimeoutMS = try value.getInt(forKey: name.rawValue)
case .zlibCompressionLevel:
self.zlibCompressionLevel = try value.getInt(forKey: name.rawValue)
}
}
}
private static func parseAuthMechanismProperties(properties: String) throws -> BSONDocument {
enum PropertyName: String {
case serviceName = "service_name"
case serviceRealm = "service_realm"
case canonicalizeHostName = "canonicalize_host_name"
}
var propertiesDoc = BSONDocument()
for property in properties.components(separatedBy: ",") {
let kv = property.components(separatedBy: ":")
guard kv.count == 2 else {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.authMechanismProperties) must be a comma-separated list of"
+ " colon-separated key-value pairs"
)
}
guard let name = PropertyName(rawValue: kv[0].lowercased()) else {
throw MongoError.InvalidArgumentError(
message: "Unknown key for \(OptionName.authMechanismProperties): \(kv[0])"
)
}
switch name {
case .serviceName, .serviceRealm:
propertiesDoc[kv[0]] = .string(kv[1])
case .canonicalizeHostName:
propertiesDoc[kv[0]] = .bool(try kv[1].getBool(forKey: name.rawValue))
}
}
return propertiesDoc
}
private static func parseReadPreferenceTags(tags: String) throws -> BSONDocument {
var tagsDoc = BSONDocument()
for tag in tags.components(separatedBy: ",") {
let kv = tag.components(separatedBy: ":")
guard kv.count == 2 else {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.readPreferenceTags) must be a comma-separated list of colon-separated"
+ " key-value pairs"
)
}
tagsDoc[kv[0]] = .string(kv[1])
}
return tagsDoc
}
}
/// Parses a new `MongoConnectionString` instance from the provided string.
/// - Throws:
/// - `MongoError.InvalidArgumentError` if the input is invalid.
public init(string input: String) throws {
// Parse the connection string's scheme.
let schemeAndRest = input.components(separatedBy: "://")
guard schemeAndRest.count == 2, let scheme = Scheme(schemeAndRest[0]) else {
throw MongoError.InvalidArgumentError(
message: "Invalid connection string scheme, expecting \'mongodb\' or \'mongodb+srv\'"
)
}
guard !schemeAndRest[1].isEmpty else {
throw MongoError.InvalidArgumentError(message: "The connection string must contain host information")
}
// Split the rest of the connection string into its components.
let infoAndOptions = schemeAndRest[1].split(separator: "?", maxSplits: 1, omittingEmptySubsequences: false)
if infoAndOptions[0].isEmpty {
throw MongoError.InvalidArgumentError(message: "The connection string must contain host information")
}
let userHostsAndAuthDB = infoAndOptions[0].split(separator: "/", omittingEmptySubsequences: false)
if userHostsAndAuthDB.count > 2 {
throw MongoError.InvalidArgumentError(
message: "The user information, host information, and defaultAuthDB in the connection string must not"
+ " contain unescaped slashes"
)
} else if userHostsAndAuthDB.count == 1 && infoAndOptions.count == 2 {
throw MongoError.InvalidArgumentError(
message: "The connection string must contain a delimiting slash between the host information and"
+ " options"
)
}
let userInfoAndHosts = userHostsAndAuthDB[0].split(separator: "@", omittingEmptySubsequences: false)
if userInfoAndHosts.count > 2 {
throw MongoError.InvalidArgumentError(
message: "The user information and host information in the connection string must not contain"
+ " unescaped @ symbols"
)
}
// Parse user information if present and set the hosts string.
let hostsString: Substring
if userInfoAndHosts.count == 2 {
let userInfo = userInfoAndHosts[0].split(separator: ":", omittingEmptySubsequences: false)
if userInfo.count > 2 {
throw MongoError.InvalidArgumentError(
message: "Username and password in the connection string must not contain unescaped colons"
)
}
var credential = MongoCredential()
credential.username = try userInfo[0].getValidatedUserInfo(forKey: "username")
if userInfo.count == 2 {
credential.password = try userInfo[1].getValidatedUserInfo(forKey: "password")
}
// If no other authentication options or defaultAuthDB were provided, we should use "admin" as the
// credential source. This will be overwritten later if a defaultAuthDB or an authSource is provided.
credential.source = "admin"
// Overwrite the sourceFromAuthSource field to false as the source is a default.
credential.sourceFromAuthSource = false
self.credential = credential
hostsString = userInfoAndHosts[1]
} else {
hostsString = userInfoAndHosts[0]
}
// Parse host information.
let hosts = try hostsString.components(separatedBy: ",").map(HostIdentifier.init)
if case .srv = scheme {
guard hosts.count == 1 else {
throw MongoError.InvalidArgumentError(
message: "Only a single host identifier may be specified in a mongodb+srv connection string"
)
}
guard hosts[0].port == nil else {
throw MongoError.InvalidArgumentError(
message: "A port cannot be specified in a mongodb+srv connection string"
)
}
guard hosts[0].host.filter({ $0 == "." }).count >= 2 else {
throw MongoError.InvalidArgumentError(
message: "The host specified in a mongodb+srv connection string must contain a host name, a domain"
+ " name, and a top-level domain"
)
}
}
self.scheme = scheme
self.hosts = hosts
// Parse the defaultAuthDB if present.
if userHostsAndAuthDB.count == 2 && !userHostsAndAuthDB[1].isEmpty {
let defaultAuthDB = try userHostsAndAuthDB[1].getPercentDecoded(forKey: "defaultAuthDB")
for character in Self.forbiddenDBCharacters {
if defaultAuthDB.contains(character) {
throw MongoError.InvalidArgumentError(
message: "defaultAuthDB contains invalid character: \(character)"
)
}
}
self.defaultAuthDB = defaultAuthDB
// If no other authentication options were provided, we should use the defaultAuthDB as the credential
// source. This will be overwritten later if an authSource is provided.
if self.credential == nil {
self.credential = MongoCredential()
}
self.credential?.source = defaultAuthDB
// Overwrite the sourceFromAuthSource field to false as the source is a default.
self.credential?.sourceFromAuthSource = false
}
// Return early if no options were specified.
guard infoAndOptions.count == 2 else {
try self.validate()
return
}
let options = try Options(infoAndOptions[1])
// Validate and set compressors. This validation is only necessary for compressors provided in the URI string
// and therefore is not included in the general validate method.
try self.validateAndSetCompressors(options)
// Parse authentication options into a MongoCredential.
var credential = self.credential ?? MongoCredential()
credential.mechanism = options.authMechanism
credential.mechanismProperties = options.authMechanismProperties
credential.source = options.authSource
self.credential = credential != MongoCredential() ? credential : nil
// Validate and set the read preference. This validation is only necessary for a read preference provided in
// the URI string and therefore is not included in the general validate method.
try self.validateAndSetReadPreference(options)
// Validate and set the write concern. This validation is only necessary for a write concern provided in the
// URI string and therefore is not included in the general validate method.
try self.validateAndSetWriteConcern(options)
// ssl can only be provided in a URI string, so this validation is not included in the general validate method.
if let tls = options.tls, let ssl = options.ssl, tls != ssl {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.tls) and \(OptionName.ssl) must have the same value if both are specified in"
+ " the connection string"
)
}
// If either tls or ssl is specified, the value should be stored in the tls field.
self.tls = options.tls ?? options.ssl
// Set rest of options.
self.appName = options.appName
self.connectTimeoutMS = options.connectTimeoutMS
self.directConnection = options.directConnection
self.heartbeatFrequencyMS = options.heartbeatFrequencyMS
self.loadBalanced = options.loadBalanced
self.localThresholdMS = options.localThresholdMS
self.maxPoolSize = options.maxPoolSize
self.readConcern = options.readConcern
self.replicaSet = options.replicaSet
self.retryReads = options.retryReads
self.retryWrites = options.retryWrites
self.serverSelectionTimeoutMS = options.serverSelectionTimeoutMS
self.socketTimeoutMS = options.socketTimeoutMS
self.srvMaxHosts = options.srvMaxHosts
self.srvServiceName = options.srvServiceName
self.tlsAllowInvalidCertificates = options.tlsAllowInvalidCertificates
self.tlsAllowInvalidHostnames = options.tlsAllowInvalidHostnames
self.tlsCAFile = options.tlsCAFile
self.tlsCertificateKeyFile = options.tlsCertificateKeyFile
self.tlsCertificateKeyFilePassword = options.tlsCertificateKeyFilePassword
self.tlsDisableCertificateRevocationCheck = options.tlsDisableCertificateRevocationCheck
self.tlsDisableOCSPEndpointCheck = options.tlsDisableOCSPEndpointCheck
self.tlsInsecure = options.tlsInsecure
try self.validate()
}
/// Updates this `MongoConnectionString` to incorporate options specified in the provided `MongoClientOptions`. If
/// the same option is specified in both, the option in the `MongoClientOptions` takes precedence.
/// - Throws:
/// - `MongoError.InvalidArgumentError` if the provided `MongoClientOptions` contains any invalid options, or
/// applying the options leads to an invalid combination of options.
public mutating func applyOptions(_ options: MongoClientOptions) throws {
if let appName = options.appName {
self.appName = appName
}
if let compressors = options.compressors {
self.compressors = compressors
}
if let connectTimeoutMS = options.connectTimeoutMS {
self.connectTimeoutMS = connectTimeoutMS
}
if let credential = options.credential {
self.credential = credential
}
if let directConnection = options.directConnection {
self.directConnection = directConnection
}
if let heartbeatFrequencyMS = options.heartbeatFrequencyMS {
self.heartbeatFrequencyMS = heartbeatFrequencyMS
}
if let loadBalanced = options.loadBalanced {
self.loadBalanced = loadBalanced
}
if let localThresholdMS = options.localThresholdMS {
self.localThresholdMS = localThresholdMS
}
if let maxPoolSize = options.maxPoolSize {
self.maxPoolSize = maxPoolSize
}
if let minHeartbeatFrequencyMS = options.minHeartbeatFrequencyMS {
self.minHeartbeatFrequencyMS = minHeartbeatFrequencyMS
}
if let readConcern = options.readConcern {
self.readConcern = readConcern
}
if let readPreference = options.readPreference {
self.readPreference = readPreference
}
if let replicaSet = options.replicaSet {
self.replicaSet = replicaSet
}
if let retryReads = options.retryReads {
self.retryReads = retryReads
}
if let retryWrites = options.retryWrites {
self.retryWrites = retryWrites
}
if let serverSelectionTimeoutMS = options.serverSelectionTimeoutMS {
self.serverSelectionTimeoutMS = serverSelectionTimeoutMS
}
if let srvMaxHosts = options.srvMaxHosts {
self.srvMaxHosts = srvMaxHosts
}
if let srvServiceName = options.srvServiceName {
self.srvServiceName = srvServiceName
}
if let tls = options.tls {
self.tls = tls
}
if let tlsAllowInvalidCertificates = options.tlsAllowInvalidCertificates {
self.tlsAllowInvalidCertificates = tlsAllowInvalidCertificates
}
if let tlsAllowInvalidHostnames = options.tlsAllowInvalidHostnames {
self.tlsAllowInvalidHostnames = tlsAllowInvalidHostnames
}
if let tlsCAFile = options.tlsCAFile {
self.tlsCAFile = tlsCAFile
}
if let tlsCertificateKeyFile = options.tlsCertificateKeyFile {
self.tlsCertificateKeyFile = tlsCertificateKeyFile
}
if let tlsCertificateKeyFilePassword = options.tlsCertificateKeyFilePassword {
self.tlsCertificateKeyFilePassword = tlsCertificateKeyFilePassword
}
if let tlsDisableCertificateRevocationCheck = options.tlsDisableCertificateRevocationCheck {
self.tlsDisableCertificateRevocationCheck = tlsDisableCertificateRevocationCheck
}
if let tlsDisableOCSPEndpointCheck = options.tlsDisableOCSPEndpointCheck {
self.tlsDisableOCSPEndpointCheck = tlsDisableOCSPEndpointCheck
}
if let tlsInsecure = options.tlsInsecure {
self.tlsInsecure = tlsInsecure
}
if let writeConcern = options.writeConcern {
self.writeConcern = writeConcern
}
try self.validate()
}
internal mutating func validate() throws {
func optionError(name: OptionName, violation: String) -> MongoError.InvalidArgumentError {
MongoError.InvalidArgumentError(
message: "Value for \(name) in the connection string must " + violation
)
}
// Validate option values.
if let source = self.credential?.source, source.isEmpty {
throw optionError(name: .authSource, violation: "not be empty")
}
if let connectTimeoutMS = self.connectTimeoutMS {
if connectTimeoutMS <= 0 {
throw optionError(name: .connectTimeoutMS, violation: "be positive")
}
if connectTimeoutMS > Int32.max {
throw optionError(
name: .connectTimeoutMS,
violation: "be <= \(Int32.max) (maximum 32-bit integer value)"
)
}
}
if let heartbeatFrequencyMS = self.heartbeatFrequencyMS {
if heartbeatFrequencyMS < self.minHeartbeatFrequencyMS {
throw optionError(name: .heartbeatFrequencyMS, violation: "be >= \(self.minHeartbeatFrequencyMS)")
}
if heartbeatFrequencyMS > Int32.max {
throw optionError(
name: .heartbeatFrequencyMS,
violation: "be <= \(Int32.max) (maximum 32-bit integer value)"
)
}
}
if let localThresholdMS = self.localThresholdMS {
if localThresholdMS < 0 {
throw optionError(name: .localThresholdMS, violation: "be nonnegative")
}
if localThresholdMS > Int32.max {
throw optionError(
name: .localThresholdMS,
violation: "be <= \(Int32.max) (maximum 32-bit integer value)"
)
}
}
if let maxPoolSize = self.maxPoolSize {
if maxPoolSize <= 0 {
throw optionError(name: .maxPoolSize, violation: "be positive")
}
if maxPoolSize > Int32.max {
throw optionError(name: .maxPoolSize, violation: "be <= \(Int32.max) (maximum 32-bit integer value)")
}
}
if let maxStalenessSeconds = self.readPreference?.maxStalenessSeconds,
!(maxStalenessSeconds == -1 || maxStalenessSeconds >= 90)
{
throw optionError(name: .maxStalenessSeconds, violation: "be -1 (for no max staleness check) or >= 90")
}
if let serverSelectionTimeoutMS = self.serverSelectionTimeoutMS {
if serverSelectionTimeoutMS <= 0 {
throw optionError(name: .serverSelectionTimeoutMS, violation: "be positive")
}
if serverSelectionTimeoutMS > Int32.max {
throw optionError(
name: .serverSelectionTimeoutMS,
violation: "be <= \(Int32.max) (maximum 32-bit integer value)"
)
}
}
if let socketTimeoutMS = self.socketTimeoutMS, socketTimeoutMS < 0 {
throw optionError(name: .socketTimeoutMS, violation: "be nonnegative")
}
if let srvMaxHosts = self.srvMaxHosts, srvMaxHosts < 0 {
throw optionError(name: .srvMaxHosts, violation: "be nonnegative")
}
if let srvServiceName = self.srvServiceName {
try srvServiceName.validateSRVServiceName()
}
if let wTimeoutMS = self.writeConcern?.wtimeoutMS, wTimeoutMS < 0 {
throw optionError(name: .wTimeoutMS, violation: "be nonnegative")
}
// Validate the compressors do not contain any duplicates. Currently this is equivalent to checking that the
// size of the compressors list does not exceed one as we only support one compressor.
if let compressors = self.compressors, compressors.count > 1 {
throw MongoError.InvalidArgumentError(
message: "The \(OptionName.compressors) list in the connection string must not contain duplicates"
)
}
// Validate the credential and set defaults as necessary.
if self.credential != nil {
// If no source was specified, fall back to:
// 1) the mechanism's default if one was provided
// 2) the defaultAuthDB if one was provided
// 3) "admin"
if self.credential?.source == nil {
let defaultSource = self.credential?.mechanism?.getDefaultSource(defaultAuthDB: self.defaultAuthDB)
?? self.defaultAuthDB
?? "admin"
self.credential?.source = defaultSource
// Overwrite the sourceFromAuthSource field to false as the source is a default.
self.credential?.sourceFromAuthSource = false
}
if self.credential?.mechanism != nil {
// credential cannot be nil within the external conditional
// swiftlint:disable:next force_unwrapping
try self.credential?.mechanism?.validateAndUpdateCredential(credential: &self.credential!)
} else if self.credential?.mechanismProperties != nil {
throw MongoError.InvalidArgumentError(
message: "Connection string specified \(OptionName.authMechanismProperties) but no"
+ " \(OptionName.authMechanism) was specified"
)
}
}
// Validate that directConnection is not set with incompatible options.
if self.directConnection == true {
guard self.scheme != .srv else {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.directConnection) cannot be set to true if the connection string scheme is"
+ " SRV"
)
}
guard self.hosts.count == 1 else {
throw MongoError.InvalidArgumentError(
message: "Multiple hosts cannot be specified in the connection string if"
+ " \(OptionName.directConnection) is set to true"
)
}
}
// Validate that loadBalanced is not set with incompatible options.
if self.loadBalanced == true {
if self.hosts.count > 1 {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.loadBalanced) cannot be set to true if multiple hosts are specified in the"
+ " connection string"
)
}
if self.replicaSet != nil {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.loadBalanced) cannot be set to true if \(OptionName.replicaSet) is"
+ " specified in the connection string"
)
}
if self.directConnection == true {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.loadBalanced) and \(OptionName.directConnection) cannot both be set to true"
+ " in the connection string"
)
}
}
// Validate that SRV options are not set with incompatible options.
guard self.scheme == .srv || (self.srvMaxHosts == nil && self.srvServiceName == nil) else {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.srvMaxHosts) and \(OptionName.srvServiceName) must not be specified if the"
+ " connection string scheme is not SRV"
)
}
if let srvMaxHosts = self.srvMaxHosts {
guard !(srvMaxHosts > 0 && self.replicaSet != nil) else {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.replicaSet) must not be specified in the connection string if the value for"
+ " \(OptionName.srvMaxHosts) is greater than zero"
)
}
guard !(srvMaxHosts > 0 && self.loadBalanced == true) else {
throw MongoError.InvalidArgumentError(
message: "The value for \(OptionName.loadBalanced) in the connection string must not be true if"
+ " the value for \(OptionName.srvMaxHosts) is greater than zero"
)
}
}
// Validate that TLS options are not set with incompatible options.
guard self.tlsInsecure == nil
|| (self.tlsAllowInvalidCertificates == nil
&& self.tlsAllowInvalidHostnames == nil
&& self.tlsDisableCertificateRevocationCheck == nil
&& self.tlsDisableOCSPEndpointCheck == nil)
else {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.tlsAllowInvalidCertificates), \(OptionName.tlsAllowInvalidHostnames),"
+ " \(OptionName.tlsDisableCertificateRevocationCheck), and"
+ " \(OptionName.tlsDisableOCSPEndpointCheck) cannot be specified if \(OptionName.tlsInsecure)"
+ " is specified in the connection string"
)
}
guard !(self.tlsAllowInvalidCertificates != nil && self.tlsDisableOCSPEndpointCheck != nil) else {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.tlsAllowInvalidCertificates) and \(OptionName.tlsDisableOCSPEndpointCheck)"
+ " cannot both be specified in the connection string"
)
}
guard !(self.tlsAllowInvalidCertificates != nil && self.tlsDisableCertificateRevocationCheck != nil) else {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.tlsAllowInvalidCertificates) and"
+ " \(OptionName.tlsDisableCertificateRevocationCheck) cannot both be specified in the connection"
+ " string"
)
}
guard !(self.tlsDisableOCSPEndpointCheck != nil && self.tlsDisableCertificateRevocationCheck != nil) else {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.tlsDisableOCSPEndpointCheck) and"
+ " \(OptionName.tlsDisableCertificateRevocationCheck) cannot both be specified in the connection"
+ " string"
)
}
}
private mutating func validateAndSetCompressors(_ options: Options) throws {
if let compressorStrings = options.compressors {
self.compressors = try compressorStrings.map {
switch $0 {
case "zlib":
if let zlibCompressionLevel = options.zlibCompressionLevel {
return try Compressor.zlib(level: zlibCompressionLevel)
} else {
return Compressor.zlib
}
case let other:
throw MongoError.InvalidArgumentError(
message: "Unrecognized compressor specified in the connection string: \(other)"
)
}
}
}
}
private mutating func validateAndSetReadPreference(_ options: Options) throws {
if let modeString = options.readPreference {
guard let mode = ReadPreference.Mode(rawValue: modeString) else {
throw MongoError.InvalidArgumentError(
message: "Unknown \(OptionName.readPreference) specified in the connection string: \(modeString)"
)
}
self.readPreference = try ReadPreference(
mode,
tagSets: options.readPreferenceTags,
maxStalenessSeconds: options.maxStalenessSeconds
)
} else if options.readPreferenceTags != nil || options.maxStalenessSeconds != nil {
throw MongoError.InvalidArgumentError(
message: "\(OptionName.readPreferenceTags) and \(OptionName.maxStalenessSeconds) should not be"
+ " specified in the connection string if \(OptionName.readPreference) is not specified"
)
}
}
private mutating func validateAndSetWriteConcern(_ options: Options) throws {
if options.journal != nil || options.w != nil || options.wTimeoutMS != nil {
self.writeConcern = try WriteConcern(
journal: options.journal,
w: options.w,
wtimeoutMS: options.wTimeoutMS
)
}
}
/// `Codable` conformance
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.description)
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let stringValue = try container.decode(String.self)
do {
try self.init(string: stringValue)
} catch let error as MongoError.InvalidArgumentError {
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: error.message
)
}
}
/// `LosslessStringConvertible` protocol requirements
public init?(_ description: String) {
try? self.init(string: description)
}
public var description: String {
var uri = ""
uri += "\(self.scheme)://"
if let username = self.credential?.username {
uri += username.getPercentEncoded(withAllowedCharacters: Self.allowedForNonOptionEncoding)
if let password = self.credential?.password {
uri += ":" + password.getPercentEncoded(withAllowedCharacters: Self.allowedForNonOptionEncoding)
}
uri += "@"
}
uri += self.hosts.map { $0.description }.joined(separator: ",")
// A trailing slash in the connection string is valid so we can append this unconditionally.
uri += "/"
if let defaultAuthDB = self.defaultAuthDB {
uri += defaultAuthDB.getPercentEncoded(withAllowedCharacters: Self.allowedForNonOptionEncoding)
}
uri += "?"
uri.appendOption(name: .appName, option: self.appName)
uri.appendOption(name: .authMechanism, option: self.credential?.mechanism?.description)
uri.appendOption(name: .authMechanismProperties, option: self.credential?.mechanismProperties?.map {
var property = $0.key + ":"
switch $0.value {
case let .string(s):
property += s
case let .bool(b):
property += String(b)
// the possible values for authMechanismProperties are only strings and booleans
default:
property += ""
}
return property
}.joined(separator: ","))
if self.credential?.sourceFromAuthSource == true {
uri.appendOption(name: .authSource, option: self.credential?.source)
}
uri.appendOption(name: .compressors, option: self.compressors?.map {
switch $0._compressor {
case let .zlib(level):
uri.appendOption(name: .zlibCompressionLevel, option: level)
return "zlib"
}
}.joined(separator: ","))
uri.appendOption(name: .connectTimeoutMS, option: self.connectTimeoutMS)
uri.appendOption(name: .directConnection, option: self.directConnection)
uri.appendOption(name: .heartbeatFrequencyMS, option: self.heartbeatFrequencyMS)
uri.appendOption(name: .journal, option: self.writeConcern?.journal)
uri.appendOption(name: .loadBalanced, option: self.loadBalanced)
uri.appendOption(name: .localThresholdMS, option: self.localThresholdMS)
uri.appendOption(name: .maxPoolSize, option: self.maxPoolSize)
uri.appendOption(name: .maxStalenessSeconds, option: self.readPreference?.maxStalenessSeconds)
uri.appendOption(name: .readConcernLevel, option: self.readConcern?.level)
uri.appendOption(name: .readPreference, option: self.readPreference?.mode.rawValue)
if let tagSets = self.readPreference?.tagSets {
for tags in tagSets {
uri.appendOption(name: .readPreferenceTags, option: tags.map {
var tag = $0.key + ":"
switch $0.value {
case let .string(s):
tag += s
// tags are always parsed as strings
default:
tag += ""
}
return tag
}.joined(separator: ","))
}
}
uri.appendOption(name: .replicaSet, option: self.replicaSet)
uri.appendOption(name: .retryReads, option: self.retryReads)
uri.appendOption(name: .retryWrites, option: self.retryWrites)