-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathReadPreference.swift
273 lines (252 loc) · 13.1 KB
/
ReadPreference.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
import CLibMongoC
/// Represents a MongoDB read preference, indicating which member(s) of a replica set read operations should be
/// directed to.
/// - SeeAlso: https://docs.mongodb.com/manual/reference/read-preference/
public struct ReadPreference: Equatable {
/// An enumeration of possible read preference modes.
/// - SeeAlso: https://docs.mongodb.com/manual/core/read-preference/#read-preference-modes
public enum Mode: String {
/// Default mode. All operations read from the current replica set primary.
case primary
/// In most situations, operations read from the primary but if it is unavailable, operations read from
/// secondary members.
case primaryPreferred
/// All operations read from the secondary members of the replica set.
case secondary
/// In most situations, operations read from secondary members but if no secondary members are available,
/// operations read from the primary.
case secondaryPreferred
/// Operations read from the member of the replica set with the least network latency, irrespective of the
/// member's type.
case nearest
fileprivate var mongocMode: mongoc_read_mode_t {
switch self {
case .primary:
return MONGOC_READ_PRIMARY
case .primaryPreferred:
return MONGOC_READ_PRIMARY_PREFERRED
case .secondary:
return MONGOC_READ_SECONDARY
case .secondaryPreferred:
return MONGOC_READ_SECONDARY_PREFERRED
case .nearest:
return MONGOC_READ_NEAREST
}
}
fileprivate init(mongocMode: mongoc_read_mode_t) {
switch mongocMode {
case MONGOC_READ_PRIMARY:
self = .primary
case MONGOC_READ_PRIMARY_PREFERRED:
self = .primaryPreferred
case MONGOC_READ_SECONDARY:
self = .secondary
case MONGOC_READ_SECONDARY_PREFERRED:
self = .secondaryPreferred
case MONGOC_READ_NEAREST:
self = .nearest
default:
fatalError("Unexpected read preference mode: \(mongocMode)")
}
}
}
/// The mode specified for this read preference.
/// - SeeAlso: https://docs.mongodb.com/manual/core/read-preference/#read-preference-modes
public var mode: Mode
/// Optionally specified ordered array of tag sets. If provided, a server will only be considered suitable if its
/// tags are a superset of at least one of the tag sets.
/// - SeeAlso: https://docs.mongodb.com/manual/core/read-preference-tags/#replica-set-read-preference-tag-sets
public var tagSets: [BSONDocument]?
// swiftlint:disable line_length
/// An optionally specified value indicating a maximum replication lag, or "staleness", for reads from secondaries.
/// - SeeAlso: https://docs.mongodb.com/manual/core/read-preference-staleness/#replica-set-read-preference-max-staleness
public var maxStalenessSeconds: Int?
// swiftlint:enable line_length
/// A `ReadPreference` with mode `primary`. This is the default mode. With this mode, all operations read from the
/// current replica set primary.
public static let primary = ReadPreference(.primary)
/// A `ReadPreference` with mode `primaryPreferred`. With this mode, in most situations operations read from the
/// primary, but if it is unavailable, operations read from secondary members.
public static let primaryPreferred = ReadPreference(.primaryPreferred)
/// A `ReadPreference` with mode `secondary`. With this mode, all operations read from secondary members of the
/// replica set.
public static let secondary = ReadPreference(.secondary)
/// A `ReadPreference` with mode `secondaryPreferred`. With this mode, in most situations operations read from
/// secondary members, but if no secondary members are available, operations read from the primary.
public static let secondaryPreferred = ReadPreference(.secondaryPreferred)
/// A `ReadPreference` with mode `nearest`. With this mode, operations read from the member of the replica set with
/// the least network latency, irrespective of the member’s type.
public static let nearest = ReadPreference(.nearest)
/**
* Initializes a new `ReadPreference` with the mode `primaryPreferred`. With this mode, in most situations
* operations read from the primary, but if it is unavailable, operations read from secondary members.
*
* - Parameters:
* - tagSets: an optional `[Document]`, containing an ordered array of tag sets. If provided, a server will only
* be considered suitable if its tags are a superset of at least one of the tag sets.
* - maxStalenessSeconds: an optional `Int`, indicating a maximum replication lag, or "staleness", for reads from
* secondaries.
*
* - Throws:
* - `MongoError.InvalidArgumentError` if `maxStalenessSeconds` is non-nil and < 90.
*
* - SeeAlso:
* - https://docs.mongodb.com/manual/core/read-preference/#primaryPreferred
* - https://docs.mongodb.com/manual/core/read-preference-tags/#replica-set-read-preference-tag-sets
* - https://docs.mongodb.com/manual/core/read-preference-staleness/#replica-set-read-preference-max-staleness
*/
public static func primaryPreferred(
tagSets: [BSONDocument]? = nil,
maxStalenessSeconds: Int? = nil
) throws -> ReadPreference {
try ReadPreference(.primaryPreferred, tagSets: tagSets, maxStalenessSeconds: maxStalenessSeconds)
}
/**
* Initializes a new `ReadPreference` with the mode `secondary`. With this mode, all operations read from the
* secondary members of the replica set.
*
* - Parameters:
* - tagSets: an optional `[Document]`, containing an ordered array of tag sets. If provided, a server will only
* be considered suitable if its tags are a superset of at least one of the tag sets.
* - maxStalenessSeconds: an optional `Int`, indicating a maximum replication lag, or "staleness", for reads from
* secondaries.
*
* - Throws:
* - `MongoError.InvalidArgumentError` if `maxStalenessSeconds` is non-nil and < 90.
*
* - SeeAlso:
* - https://docs.mongodb.com/manual/core/read-preference/#secondary
* - https://docs.mongodb.com/manual/core/read-preference-tags/#replica-set-read-preference-tag-sets
* - https://docs.mongodb.com/manual/core/read-preference-staleness/#replica-set-read-preference-max-staleness
*/
public static func secondary(
tagSets: [BSONDocument]? = nil,
maxStalenessSeconds: Int? = nil
) throws -> ReadPreference {
try ReadPreference(.secondary, tagSets: tagSets, maxStalenessSeconds: maxStalenessSeconds)
}
/**
* Initializes a new `ReadPreference` with the mode `secondaryPreferred`. With this mode, in most situations,
* operations read from secondary members but if no secondary members are available, operations read from the
* primary.
*
* - Parameters:
* - tagSets: an optional `[Document]`, containing an ordered array of tag sets. If provided, a server will only
* be considered suitable if its tags are a superset of at least one of the tag sets.
* - maxStalenessSeconds: an optional `Int`, indicating a maximum replication lag, or "staleness", for reads from
* secondaries.
*
* - Throws:
* - `MongoError.InvalidArgumentError` if `maxStalenessSeconds` is non-nil and < 90.
*
* - SeeAlso:
* - https://docs.mongodb.com/manual/core/read-preference/#secondaryPreferred
* - https://docs.mongodb.com/manual/core/read-preference-tags/#replica-set-read-preference-tag-sets
* - https://docs.mongodb.com/manual/core/read-preference-staleness/#replica-set-read-preference-max-staleness
*/
public static func secondaryPreferred(
tagSets: [BSONDocument]? = nil,
maxStalenessSeconds: Int? = nil
) throws -> ReadPreference {
try ReadPreference(.secondaryPreferred, tagSets: tagSets, maxStalenessSeconds: maxStalenessSeconds)
}
/**
* Initializes a new `ReadPreference` with the mode `nearest`. With this mode, operations read from the member of
* the replica set with the least network latency, irrespective of the member’s type.
*
* - Parameters:
* - tagSets: an optional `[Document]`, containing an ordered array of tag sets. If provided, a server will only
* be considered suitable if its tags are a superset of at least one of the tag sets.
* - maxStalenessSeconds: an optional `Int`, indicating a maximum replication lag, or "staleness", for reads from
* secondaries.
*
* - Throws:
* - `MongoError.InvalidArgumentError` if `maxStalenessSeconds` is non-nil and < 90.
*
* - SeeAlso:
* - https://docs.mongodb.com/manual/core/read-preference/#nearest
* - https://docs.mongodb.com/manual/core/read-preference-tags/#replica-set-read-preference-tag-sets
* - https://docs.mongodb.com/manual/core/read-preference-staleness/#replica-set-read-preference-max-staleness
*/
public static func nearest(
tagSets: [BSONDocument]? = nil,
maxStalenessSeconds: Int? = nil
) throws -> ReadPreference {
try ReadPreference(.nearest, tagSets: tagSets, maxStalenessSeconds: maxStalenessSeconds)
}
/// Initializes a `ReadPreference` from a `Mode`.
internal init(_ mode: Mode) {
self.mode = mode
self.tagSets = nil
self.maxStalenessSeconds = nil
}
internal init(_ mode: Mode, tagSets: [BSONDocument]? = nil, maxStalenessSeconds: Int? = nil) throws {
if let maxStaleness = maxStalenessSeconds {
guard maxStaleness >= MONGOC_SMALLEST_MAX_STALENESS_SECONDS else {
throw MongoError.InvalidArgumentError(
message: "Invalid \(MONGOC_URI_MAXSTALENESSSECONDS) \(maxStaleness): " +
"must be at least \(MONGOC_SMALLEST_MAX_STALENESS_SECONDS)"
)
}
}
if let tagSets = tagSets {
if mode == .primary {
guard tagSets == [BSONDocument()] else {
throw MongoError.InvalidArgumentError(
message: "Invalid \(MongoConnectionString.OptionName.readPreferenceTags) \(tagSets): " +
"when mode is primary, tag_sets must be empty"
)
}
}
}
self.mode = mode
self.tagSets = tagSets
self.maxStalenessSeconds = maxStalenessSeconds
}
/// Initializes a new `ReadPreference` by copying a `mongoc_read_prefs_t`. Does not free the original.
internal init(copying pointer: OpaquePointer) {
self.mode = Mode(mongocMode: mongoc_read_prefs_get_mode(pointer))
guard let tagsPointer = mongoc_read_prefs_get_tags(pointer) else {
fatalError("Failed to retrieve read preference tags")
}
// we have to copy because libmongoc owns the pointer.
let wrappedTags = BSONDocument(copying: tagsPointer)
if !wrappedTags.isEmpty {
// swiftlint:disable:next force_unwrapping
self.tagSets = wrappedTags.values.map { $0.documentValue! } // libmongoc will always return array of docs
}
let maxStalenessValue = mongoc_read_prefs_get_max_staleness_seconds(pointer)
if maxStalenessValue != MONGOC_NO_MAX_STALENESS {
self.maxStalenessSeconds = Int(exactly: maxStalenessValue)
}
}
/// Executes the provided closure using a pointer to an equivalent `mongoc_read_prefs_t`. The pointer is only valid
/// within the closure and must not escape. If you need to use the pointed-to struct after the closure completes
/// you must make a copy via `mongoc_read_prefs_copy`.
internal func withMongocReadPreference<T>(body: (OpaquePointer) throws -> T) rethrows -> T {
// swiftlint:disable:next force_unwrapping
let rp = mongoc_read_prefs_new(self.mode.mongocMode)! // never returns nil
defer { mongoc_read_prefs_destroy(rp) }
if let tagSets = self.tagSets, !tagSets.isEmpty {
let tags = BSONDocument(tagSets.map { .document($0) })
tags.withBSONPointer { tagsPtr in
mongoc_read_prefs_set_tags(rp, tagsPtr)
}
}
if let maxStaleness = self.maxStalenessSeconds {
mongoc_read_prefs_set_max_staleness_seconds(rp, Int64(maxStaleness))
}
return try body(rp)
}
/// If the provided ReadPreference is non-nil, executes the provided closure via `withMongocReadPreference`.
/// Otherwise, executes the provided closure, passing in nil as its single argument.
internal static func withOptionalMongocReadPreference<T>(
from rp: ReadPreference?,
body: (OpaquePointer?) throws -> T
) rethrows -> T {
guard let rp = rp else {
return try body(nil)
}
return try rp.withMongocReadPreference(body: body)
}
}