-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathSDAM.swift
436 lines (363 loc) · 16.5 KB
/
SDAM.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
import CLibMongoC
import Foundation
internal enum SDAMConstants {
internal static let defaultHeartbeatFrequencyMS = 10000
internal static let idleWritePeriodMS = 10000
internal static let smallestMaxStalenessSeconds = 90
internal static let defaultLocalThresholdMS = 15
internal static let defaultServerSelectionTimeoutMS = 30000
internal static let minWireVersion = 6 // 3.6
internal static let maxWireVersion = 15 // 5.2
}
/// A struct representing a network address, consisting of a host and port.
public struct ServerAddress: Equatable, Hashable {
/// The hostname or IP address.
public let host: String
/// The port number.
public let port: UInt16
/// Initializes a ServerAddress from an UnsafePointer to a mongoc_host_list_t.
internal init(_ hostList: UnsafePointer<mongoc_host_list_t>) {
var hostData = hostList.pointee
self.host = withUnsafeBytes(of: &hostData.host) { rawPtr -> String in
// if baseAddress is nil, the buffer is empty.
guard let baseAddress = rawPtr.baseAddress else {
return ""
}
return String(cString: baseAddress.assumingMemoryBound(to: CChar.self))
}
self.port = hostData.port
}
/// Initializes a ServerAddress, using the default localhost:27017 if a host/port is not provided.
internal init(_ hostAndPort: String = "localhost:27017") throws {
let parts = hostAndPort.split(separator: ":")
self.host = String(parts[0])
guard let port = UInt16(parts[1]) else {
throw MongoError.InternalError(message: "couldn't parse address from \(hostAndPort)")
}
self.port = port
}
internal init(host: String, port: UInt16) {
self.host = host
self.port = port
}
}
extension ServerAddress: CustomStringConvertible {
public var description: String {
"\(self.host):\(self.port)"
}
}
private struct HelloResponse: Decodable {
fileprivate struct LastWrite: Decodable {
public let lastWriteDate: Date?
}
fileprivate let lastWrite: LastWrite?
fileprivate let minWireVersion: Int?
fileprivate let maxWireVersion: Int?
fileprivate let me: String?
fileprivate let setName: String?
fileprivate let setVersion: Int?
fileprivate let electionID: BSONObjectID?
fileprivate let primary: String?
fileprivate let logicalSessionTimeoutMinutes: Int?
fileprivate let hosts: [String]?
fileprivate let passives: [String]?
fileprivate let arbiters: [String]?
fileprivate let tags: [String: String]?
}
/// A struct describing a mongod or mongos process.
public struct ServerDescription {
/// The possible types for a server.
public struct ServerType: RawRepresentable, Equatable, Decodable {
/// A standalone mongod server.
public static let standalone = ServerType(.standalone)
/// A router to a sharded cluster, i.e. a mongos server.
public static let mongos = ServerType(.mongos)
/// A replica set member which is not yet checked, but another member thinks it is the primary.
public static let possiblePrimary = ServerType(.possiblePrimary)
/// A replica set primary.
public static let rsPrimary = ServerType(.rsPrimary)
/// A replica set secondary.
public static let rsSecondary = ServerType(.rsSecondary)
/// A replica set arbiter.
public static let rsArbiter = ServerType(.rsArbiter)
/// A replica set member that is none of the other types (a passive, for example).
public static let rsOther = ServerType(.rsOther)
/// A replica set member that does not report a set name or a hosts list.
public static let rsGhost = ServerType(.rsGhost)
/// A server type that is not yet known.
public static let unknown = ServerType(.unknown)
/// A load balancer.
public static let loadBalancer = ServerType(.loadBalancer)
/// Internal representation of server type. If enums could be marked non-exhaustive in Swift, this would be the
/// public representation too.
private enum _ServerType: String, Equatable {
case standalone = "Standalone"
case mongos = "Mongos"
case possiblePrimary = "PossiblePrimary"
case rsPrimary = "RSPrimary"
case rsSecondary = "RSSecondary"
case rsArbiter = "RSArbiter"
case rsOther = "RSOther"
case rsGhost = "RSGhost"
case unknown = "Unknown"
case loadBalancer = "LoadBalancer"
}
private let _serverType: _ServerType
private init(_ _type: _ServerType) {
self._serverType = _type
}
public var rawValue: String {
self._serverType.rawValue
}
public init?(rawValue: String) {
guard let _type = _ServerType(rawValue: rawValue) else {
return nil
}
self._serverType = _type
}
}
/// The hostname or IP and the port number that the client connects to. Note that this is not the "me" field in the
/// server's hello or legacy hello response, in the case that the server reports an address different from the
/// address the client uses.
public let address: ServerAddress
/// Opaque identifier for this server, used for testing only.
internal let serverId: UInt32
/// The duration in milliseconds of the server's last "hello" call.
public let roundTripTime: Int?
/// The average duration in milliseconds of the server's "hello" calls.
internal var averageRoundTripTimeMS: Double?
/// The date of the most recent write operation seen by this server.
public var lastWriteDate: Date?
/// The type of this server.
public let type: ServerType
/// The minimum wire protocol version supported by the server.
public let minWireVersion: Int
/// The maximum wire protocol version supported by the server.
public let maxWireVersion: Int
/// The hostname or IP and the port number that this server was configured with in the replica set.
public let me: ServerAddress?
/// This server's opinion of the replica set's hosts, if any.
public let hosts: [ServerAddress]
/// This server's opinion of the replica set's arbiters, if any.
public let arbiters: [ServerAddress]
/// "Passives" are priority-zero replica set members that cannot become primary.
/// The client treats them precisely the same as other members.
public let passives: [ServerAddress]
/// Tags for this server.
public let tags: [String: String]
/// The replica set name.
public let setName: String?
/// The replica set version.
public let setVersion: Int?
/// The election ID where this server was elected, if this is a replica set member that believes it is primary.
public let electionID: BSONObjectID?
/// This server's opinion of who the primary is.
public let primary: ServerAddress?
/// When this server was last checked.
public let lastUpdateTime: Date
/// The logicalSessionTimeoutMinutes value for this server.
public let logicalSessionTimeoutMinutes: Int?
/// An internal initializer to create a `ServerDescription` from an OpaquePointer to a
/// mongoc_server_description_t.
internal init(_ description: OpaquePointer) {
self.address = ServerAddress(mongoc_server_description_host(description))
self.serverId = mongoc_server_description_id(description)
self.roundTripTime = Int(mongoc_server_description_round_trip_time(description))
// averageRoundTripTimeMS is an internally-calculated value used for server selection. Because we still rely
// upon libmongoc for server selection, this value is not relevant.
self.averageRoundTripTimeMS = nil
self.lastUpdateTime = Date(msSinceEpoch: mongoc_server_description_last_update_time(description))
self.type = ServerType(rawValue: String(cString: mongoc_server_description_type(description))) ?? .unknown
// initialize the rest of the values from the hello response.
// we have to copy because libmongoc owns the pointer.
let helloDoc = BSONDocument(copying: mongoc_server_description_hello_response(description))
// TODO: SWIFT-349 log errors encountered here
let hello = try? BSONDecoder().decode(HelloResponse.self, from: helloDoc)
self.lastWriteDate = hello?.lastWrite?.lastWriteDate
self.minWireVersion = hello?.minWireVersion ?? 0
self.maxWireVersion = hello?.maxWireVersion ?? 0
self.me = try? hello?.me.map(ServerAddress.init) // TODO: SWIFT-349 log error
self.setName = hello?.setName
self.setVersion = hello?.setVersion
self.electionID = hello?.electionID
self.primary = try? hello?.primary.map(ServerAddress.init) // TODO: SWIFT-349 log error
self.logicalSessionTimeoutMinutes = hello?.logicalSessionTimeoutMinutes
self.hosts = hello?.hosts?.compactMap { host in
try? ServerAddress(host) // TODO: SWIFT-349 log error
} ?? []
self.passives = hello?.passives?.compactMap { passive in
try? ServerAddress(passive) // TODO: SWIFT-349 log error
} ?? []
self.arbiters = hello?.arbiters?.compactMap { arbiter in
try? ServerAddress(arbiter) // TODO: SWIFT-349 log error
} ?? []
self.tags = hello?.tags ?? [:]
}
// Used for server selection/max staleness tests.
internal init(
address: ServerAddress,
type: ServerType,
tags: [String: String]?,
lastWriteDate: Date?,
maxWireVersion: Int?,
lastUpdateTime: Date?,
averageRoundTripTimeMS: Double?
) {
self.address = address
self.type = type
self.tags = tags ?? [:]
self.lastWriteDate = lastWriteDate
self.lastUpdateTime = lastUpdateTime ?? Date()
self.maxWireVersion = maxWireVersion ?? SDAMConstants.maxWireVersion
self.averageRoundTripTimeMS = averageRoundTripTimeMS
// these fields are not used by the server selection tests
self.serverId = 0
self.roundTripTime = 0
self.minWireVersion = SDAMConstants.minWireVersion
self.me = self.address
self.setName = nil
self.setVersion = nil
self.electionID = nil
self.primary = nil
self.logicalSessionTimeoutMinutes = nil
self.hosts = []
self.passives = []
self.arbiters = []
}
// Used for RTT calculation tests.
internal init(averageRoundTripTimeMS: Double?) {
self.averageRoundTripTimeMS = averageRoundTripTimeMS
// these fields are not used by the RTT calculation tests
self.address = ServerAddress(host: "test", port: 0)
self.type = .unknown
self.tags = [:]
self.serverId = 0
self.roundTripTime = nil
self.lastWriteDate = nil
self.minWireVersion = 0
self.maxWireVersion = 0
self.me = nil
self.hosts = []
self.arbiters = []
self.passives = []
self.setName = nil
self.setVersion = nil
self.electionID = nil
self.primary = nil
self.lastUpdateTime = Date()
self.logicalSessionTimeoutMinutes = nil
}
}
extension ServerDescription: Equatable {
public static func == (lhs: ServerDescription, rhs: ServerDescription) -> Bool {
// As per the SDAM spec, only some fields are necessary to compare for equality.
lhs.address == rhs.address &&
lhs.type == rhs.type &&
lhs.minWireVersion == rhs.minWireVersion &&
lhs.maxWireVersion == rhs.maxWireVersion &&
lhs.me == rhs.me &&
lhs.hosts == rhs.hosts &&
lhs.arbiters == rhs.arbiters &&
lhs.passives == rhs.passives &&
lhs.tags == rhs.tags &&
lhs.setName == rhs.setName &&
lhs.setVersion == rhs.setVersion &&
lhs.electionID == rhs.electionID &&
lhs.primary == rhs.primary &&
lhs.logicalSessionTimeoutMinutes == rhs.logicalSessionTimeoutMinutes
}
}
/// A struct describing the state of a MongoDB deployment: its type (standalone, replica set, or sharded),
/// which servers are up, what type of servers they are, which is primary, and so on.
public struct TopologyDescription: Equatable {
/// The possible types for a topology.
public struct TopologyType: RawRepresentable, Equatable, CustomStringConvertible, Decodable {
/// A single mongod server.
public static let single = TopologyType(.single)
/// A replica set with no primary.
public static let replicaSetNoPrimary = TopologyType(.replicaSetNoPrimary)
/// A replica set with a primary.
public static let replicaSetWithPrimary = TopologyType(.replicaSetWithPrimary)
/// Sharded topology.
public static let sharded = TopologyType(.sharded)
/// A topology whose type is not yet known.
public static let unknown = TopologyType(.unknown)
/// A topology with a load balancer in front.
public static let loadBalanced = TopologyType(.loadBalanced)
/// Internal representation of topology type. If enums could be marked non-exhaustive in Swift, this would be
/// the public representation too.
internal enum _TopologyType: String, Equatable {
case single = "Single"
case replicaSetNoPrimary = "ReplicaSetNoPrimary"
case replicaSetWithPrimary = "ReplicaSetWithPrimary"
case sharded = "Sharded"
case unknown = "Unknown"
case loadBalanced = "LoadBalanced"
}
internal let _topologyType: _TopologyType
private init(_ _type: _TopologyType) {
self._topologyType = _type
}
public var rawValue: String {
self._topologyType.rawValue
}
public init?(rawValue: String) {
guard let _type = _TopologyType(rawValue: rawValue) else {
return nil
}
self._topologyType = _type
}
public var description: String {
self.rawValue
}
}
/// The type of this topology.
public let type: TopologyType
/// The replica set name.
public var setName: String? {
guard !self.servers.isEmpty else {
return nil
}
return self.servers[0].setName
}
/// The servers comprising this topology.
public let servers: [ServerDescription]
/// The logicalSessionTimeoutMinutes value for this topology. This value is the minimum
/// of the `logicalSessionTimeoutMinutes` values across all the servers in `servers`,
/// or `nil` if any of them are `nil`.
public var logicalSessionTimeoutMinutes: Int? {
let timeoutValues = self.servers.map { $0.logicalSessionTimeoutMinutes }
if timeoutValues.contains(where: { $0 == nil }) {
return nil
}
return timeoutValues.compactMap { $0 }.min()
}
/// Returns `true` if the topology has a readable server available, and `false` otherwise.
public func hasReadableServer() -> Bool {
// TODO: SWIFT-244: amend this method to take in a read preference.
[.single, .replicaSetWithPrimary, .sharded].contains(self.type)
}
/// Returns `true` if the topology has a writable server available, and `false` otherwise.
public func hasWritableServer() -> Bool {
[.single, .replicaSetWithPrimary].contains(self.type)
}
/// An internal initializer to create a `TopologyDescription` from an OpaquePointer
/// to a `mongoc_server_description_t`
internal init(_ description: OpaquePointer) {
let topologyType = String(cString: mongoc_topology_description_type(description))
// swiftlint:disable:next force_unwrapping
self.type = TopologyType(rawValue: topologyType)! // libmongoc will only give us back valid raw values.
var size = size_t()
let serverData = mongoc_topology_description_get_servers(description, &size)
defer { mongoc_server_descriptions_destroy_all(serverData, size) }
let buffer = UnsafeBufferPointer(start: serverData, count: size)
// swiftlint:disable:next force_unwrapping
self.servers = size > 0 ? Array(buffer).map { ServerDescription($0!) } : []
// the buffer is documented as always containing non-nil pointers (if non-empty).
}
// For testing purposes
internal init(type: TopologyType, servers: [ServerDescription]) {
self.type = type
self.servers = servers
}
}