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
|
//
// RelayCacheTracker.swift
// MullvadVPN
//
// Created by pronebird on 05/06/2019.
// Copyright © 2019 Mullvad VPN AB. All rights reserved.
//
import Foundation
import MullvadLogging
import MullvadREST
import MullvadTypes
import Operations
import UIKit
protocol RelayCacheTrackerProtocol {
func startPeriodicUpdates()
func stopPeriodicUpdates()
func updateRelays(completionHandler: ((Result<RelaysFetchResult, Error>) -> Void)?) -> Cancellable
func getCachedRelays() throws -> CachedRelays
func getNextUpdateDate() -> Date
func addObserver(_ observer: RelayCacheTrackerObserver)
func removeObserver(_ observer: RelayCacheTrackerObserver)
}
final class RelayCacheTracker: RelayCacheTrackerProtocol {
/// Relay update interval.
static let relayUpdateInterval: Duration = .hours(1)
/// Tracker log.
private let logger = Logger(label: "RelayCacheTracker")
/// Relay cache.
private let cache: RelayCacheProtocol
private let application: UIApplication
/// Lock used for synchronization.
private let nslock = NSLock()
/// Internal operation queue.
private let operationQueue = AsyncOperationQueue.makeSerial()
/// A timer source used for periodic updates.
private var timerSource: DispatchSourceTimer?
/// A flag that indicates whether periodic updates are running.
private var isPeriodicUpdatesEnabled = false
/// API proxy.
private let apiProxy: APIQuerying
/// Observers.
private let observerList = ObserverList<RelayCacheTrackerObserver>()
/// Memory cache.
private var cachedRelays: CachedRelays?
init(relayCache: RelayCacheProtocol, application: UIApplication, apiProxy: APIQuerying) {
self.application = application
self.apiProxy = apiProxy
cache = relayCache
do {
cachedRelays = try cache.read()
} catch {
logger.error(
error: error,
message: "Failed to read the relay cache during initialization."
)
_ = updateRelays(completionHandler: nil)
}
}
func startPeriodicUpdates() {
nslock.lock()
defer { nslock.unlock() }
guard !isPeriodicUpdatesEnabled else { return }
logger.debug("Start periodic relay updates.")
isPeriodicUpdatesEnabled = true
let nextUpdate = _getNextUpdateDate()
scheduleRepeatingTimer(startTime: .now() + nextUpdate.timeIntervalSinceNow)
}
func stopPeriodicUpdates() {
nslock.lock()
defer { nslock.unlock() }
guard isPeriodicUpdatesEnabled else { return }
logger.debug("Stop periodic relay updates.")
isPeriodicUpdatesEnabled = false
timerSource?.cancel()
timerSource = nil
}
func updateRelays(completionHandler: ((Result<RelaysFetchResult, Error>) -> Void)? = nil)
-> Cancellable {
let operation = ResultBlockOperation<RelaysFetchResult> { finish in
let cachedRelays = try? self.getCachedRelays()
if self.getNextUpdateDate() > Date() {
finish(.success(.throttled))
return AnyCancellable()
}
return self.apiProxy.getRelays(etag: cachedRelays?.etag, retryStrategy: .noRetry) { result in
finish(self.handleResponse(result: result))
}
}
operation.addObserver(
BackgroundObserver(
application: application,
name: "Update relays",
cancelUponExpiration: true
)
)
operation.completionQueue = .main
operation.completionHandler = completionHandler
operationQueue.addOperation(operation)
return operation
}
func getCachedRelays() throws -> CachedRelays {
nslock.lock()
defer { nslock.unlock() }
if let cachedRelays {
return cachedRelays
} else {
throw NoCachedRelaysError()
}
}
func getNextUpdateDate() -> Date {
nslock.lock()
defer { nslock.unlock() }
return _getNextUpdateDate()
}
// MARK: - Observation
func addObserver(_ observer: RelayCacheTrackerObserver) {
observerList.append(observer)
}
func removeObserver(_ observer: RelayCacheTrackerObserver) {
observerList.remove(observer)
}
// MARK: - Private
private func _getNextUpdateDate() -> Date {
let now = Date()
guard let cachedRelays else {
return now
}
let nextUpdate = cachedRelays.updatedAt.addingTimeInterval(Self.relayUpdateInterval.timeInterval)
return max(nextUpdate, Date())
}
private func handleResponse(result: Result<REST.ServerRelaysCacheResponse, Error>)
-> Result<RelaysFetchResult, Error> {
result.tryMap { response -> RelaysFetchResult in
switch response {
case let .newContent(etag, relays):
try self.storeResponse(etag: etag, relays: relays)
return .newContent
case .notModified:
return .sameContent
}
}.inspectError { error in
guard !error.isOperationCancellationError else { return }
logger.error(
error: error,
message: "Failed to update relays."
)
}
}
private func storeResponse(etag: String?, relays: REST.ServerRelaysResponse) throws {
let numRelays = relays.wireguard.relays.count
logger.info("Downloaded \(numRelays) relays.")
let newCachedRelays = CachedRelays(
etag: etag,
relays: relays,
updatedAt: Date()
)
nslock.lock()
cachedRelays = newCachedRelays
nslock.unlock()
try cache.write(record: newCachedRelays)
DispatchQueue.main.async {
self.observerList.forEach { observer in
observer.relayCacheTracker(self, didUpdateCachedRelays: newCachedRelays)
}
}
}
private func scheduleRepeatingTimer(startTime: DispatchWallTime) {
let timerSource = DispatchSource.makeTimerSource()
timerSource.setEventHandler { [weak self] in
_ = self?.updateRelays()
}
timerSource.schedule(
wallDeadline: startTime,
repeating: Self.relayUpdateInterval.timeInterval
)
timerSource.activate()
self.timerSource = timerSource
}
}
/// Type describing the result of an attempt to fetch the new relay list from server.
enum RelaysFetchResult: CustomStringConvertible {
/// Request to update relays was throttled.
case throttled
/// Refreshed relays but the same content was found on remote.
case sameContent
/// Refreshed relays with new content.
case newContent
var description: String {
switch self {
case .throttled:
return "throttled"
case .sameContent:
return "same content"
case .newContent:
return "new content"
}
}
}
struct NoCachedRelaysError: LocalizedError {
var errorDescription: String? {
"Relay cache is empty."
}
}
|