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
|
//
// RelayCacheTracker.swift
// MullvadVPN
//
// Created by pronebird on 05/06/2019.
// Copyright © 2025 Mullvad VPN AB. All rights reserved.
//
import Foundation
import MullvadLogging
import MullvadREST
import MullvadTypes
import Operations
import UIKit
protocol RelayCacheTrackerProtocol: Sendable {
func startPeriodicUpdates()
func stopPeriodicUpdates()
func updateRelays(completionHandler: ((sending Result<RelaysFetchResult, Error>) -> Void)?) -> Cancellable
func getCachedRelays() throws -> CachedRelays
func getNextUpdateDate() -> Date
func addObserver(_ observer: RelayCacheTrackerObserver)
func removeObserver(_ observer: RelayCacheTrackerObserver)
func refreshCachedRelays() throws
}
final class RelayCacheTracker: RelayCacheTrackerProtocol, @unchecked Sendable {
/// Relay update interval.
static let relayUpdateInterval: Duration = .hours(1)
/// Tracker log.
nonisolated(unsafe) private let logger = Logger(label: "RelayCacheTracker")
/// Relay cache.
private let cache: RelayCacheProtocol
private let backgroundTaskProvider: BackgroundTaskProviding
/// Lock used for synchronization.
private let relayCacheLock = 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, backgroundTaskProvider: BackgroundTaskProviding, apiProxy: APIQuerying) {
self.backgroundTaskProvider = backgroundTaskProvider
self.apiProxy = apiProxy
cache = relayCache
do {
cachedRelays = try cache.read().cachedRelays
try hotfixRelaysThatDoNotHaveFeatures()
} catch {
logger.error(
error: error,
message: "Failed to read the relay cache during initialization."
)
_ = updateRelays(completionHandler: nil)
}
}
/// This method updates the cached relay to include "feature" information
///
/// This is a hotfix meant to upgrade clients shipped with 2025.6 or before that did not have
/// feature information in their representation of `ServerRelay`.
/// If a version <= 2025.6 is installed less than an hour before a new upgrade,
/// no servers will be shown in locations when filtering for relays requiring a certain feature.
///
/// > Info: `relayCacheLock` does not need to be accessed here, this method should be ran from `init` only.
private func hotfixRelaysThatDoNotHaveFeatures() throws {
guard let cachedRelays else { return }
let featurePropertyMissing = cachedRelays.relays.wireguard.relays.first { $0.features != nil } == nil
// If the cached relays already have daita information, this fix is not necessary
guard featurePropertyMissing else { return }
let preBundledRelays = try cache.readPrebundledRelays().relays
let preBundledFeatureRelays = preBundledRelays.wireguard.relays.filter { $0.features != nil }
var cachedRelaysWithFixedFeatures = cachedRelays.relays.wireguard.relays
// For each relay with features in the prebundled relays, find the corresponding relay
// in the cache by matching relay hostnames and update it.
for index in 0..<cachedRelaysWithFixedFeatures.endIndex {
let relay = cachedRelaysWithFixedFeatures[index]
preBundledFeatureRelays.forEach {
if $0.hostname == relay.hostname {
cachedRelaysWithFixedFeatures[index] = relay.override(features: $0.features)
}
}
}
let wireguard = REST.ServerWireguardTunnels(
ipv4Gateway:
cachedRelays.relays.wireguard.ipv4Gateway,
ipv6Gateway: cachedRelays.relays.wireguard.ipv6Gateway,
portRanges: cachedRelays.relays.wireguard.portRanges,
relays: cachedRelaysWithFixedFeatures,
shadowsocksPortRanges: cachedRelays.relays.wireguard.shadowsocksPortRanges
)
let updatedRelays = REST.ServerRelaysResponse(
locations: cachedRelays.relays.locations,
wireguard: wireguard,
bridge: cachedRelays.relays.bridge
)
let updatedRawRelayData = try REST.Coding.makeJSONEncoder().encode(updatedRelays)
let updatedCachedRelays = try StoredRelays(
etag: cachedRelays.etag,
rawData: updatedRawRelayData,
updatedAt: cachedRelays.updatedAt
)
try cache.write(record: updatedCachedRelays)
self.cachedRelays = CachedRelays(
etag: cachedRelays.etag,
relays: updatedRelays,
updatedAt: cachedRelays.updatedAt
)
}
func startPeriodicUpdates() {
relayCacheLock.lock()
defer { relayCacheLock.unlock() }
guard !isPeriodicUpdatesEnabled else { return }
logger.debug("Start periodic relay updates.")
isPeriodicUpdatesEnabled = true
let nextUpdate = _getNextUpdateDate()
scheduleRepeatingTimer(startTime: .now() + nextUpdate.timeIntervalSinceNow)
}
func stopPeriodicUpdates() {
relayCacheLock.lock()
defer { relayCacheLock.unlock() }
guard isPeriodicUpdatesEnabled else { return }
logger.debug("Stop periodic relay updates.")
isPeriodicUpdatesEnabled = false
timerSource?.cancel()
timerSource = nil
}
func updateRelays(completionHandler: ((sending 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(
backgroundTaskProvider: backgroundTaskProvider,
name: "Update relays",
cancelUponExpiration: true
)
)
operation.completionQueue = .main
operation.completionHandler = completionHandler
operationQueue.addOperation(operation)
return operation
}
func getCachedRelays() throws -> CachedRelays {
relayCacheLock.lock()
defer { relayCacheLock.unlock() }
if let cachedRelays {
return cachedRelays
} else {
throw NoCachedRelaysError()
}
}
func refreshCachedRelays() throws {
let newCachedRelays = try cache.read().cachedRelays
relayCacheLock.lock()
cachedRelays = newCachedRelays
relayCacheLock.unlock()
DispatchQueue.main.async {
self.observerList.notify { observer in
observer.relayCacheTracker(self, didUpdateCachedRelays: newCachedRelays)
}
}
}
func getNextUpdateDate() -> Date {
relayCacheLock.lock()
defer { relayCacheLock.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, rawData):
try self.storeResponse(etag: etag, rawData: rawData)
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?, rawData: Data) throws {
let newCachedData = try StoredRelays(
etag: etag,
rawData: rawData,
updatedAt: Date()
)
try cache.write(record: newCachedData)
try refreshCachedRelays()
}
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."
}
}
|