summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/AddressCache/AddressCacheStore.swift
blob: ef479858e3eafc3fe5a87decea4be13df3480edd (plain)
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
//
//  AddressCacheStore.swift
//  MullvadVPN
//
//  Created by pronebird on 08/12/2021.
//  Copyright © 2021 Mullvad VPN AB. All rights reserved.
//

import Foundation
import Logging

extension AddressCache {

    struct CachedAddresses: Codable {
        /// Date when the cached addresses were last updated.
        var updatedAt: Date

        /// API endpoints.
        var endpoints: [AnyIPEndpoint]
    }

    enum CacheSource: CustomStringConvertible {
        /// Cache file originates from disk location.
        case disk

        /// Cache file originates from application bundle.
        case bundle

        var description: String {
            switch self {
            case .disk:
                return "disk"
            case .bundle:
                return "bundle"
            }
        }
    }

    struct ReadResult {
        var cachedAddresses: CachedAddresses
        var source: CacheSource
    }

    class Store {

        static let shared: Store = {
            let cacheFilename = "api-ip-address.json"
            let cacheDirectoryURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
            let cacheFileURL = cacheDirectoryURL.appendingPathComponent(cacheFilename, isDirectory: false)
            let prebundledCacheFileURL = Bundle.main.url(forResource: cacheFilename, withExtension: nil)!

            return Store(
                cacheFileURL: cacheFileURL,
                prebundledCacheFileURL: prebundledCacheFileURL
            )
        }()

        static var defaultCachedAddresses: CachedAddresses {
            return CachedAddresses(
                updatedAt: Date(timeIntervalSince1970: 0),
                endpoints: [
                    ApplicationConfiguration.defaultAPIEndpoint
                ]
            )
        }

        /// Logger.
        private let logger = Logger(label: "AddressCache.Store")

        /// Memory cache.
        private var cachedAddresses: CachedAddresses

        /// Cache file location.
        private let cacheFileURL: URL

        /// The location of pre-bundled address cache file.
        private let prebundledCacheFileURL: URL

        /// Queue used for synchronizing access to instance members.
        private let stateQueue = DispatchQueue(label: "AddressCacheStoreQueue")

        /// Designated initializer
        init(cacheFileURL: URL, prebundledCacheFileURL: URL) {
            self.cacheFileURL = cacheFileURL
            self.prebundledCacheFileURL = prebundledCacheFileURL
            self.cachedAddresses = Self.defaultCachedAddresses

            switch readFromCacheLocationWithFallback() {
            case .success(let readResult):
                if readResult.cachedAddresses.endpoints.isEmpty {
                    logger.debug("Read empty cache from \(readResult.source). Fallback to default API endpoint.")

                    cachedAddresses = Self.defaultCachedAddresses

                    logger.debug("Initialized cache with default API endpoint.")
                } else {
                    switch readResult.source {
                    case .disk:
                        cachedAddresses = readResult.cachedAddresses

                    case .bundle:
                        var addresses = readResult.cachedAddresses
                        addresses.endpoints.shuffle()
                        cachedAddresses = addresses

                        logger.debug("Persist address list read from bundle.")

                        if case .failure(let error) = self.writeToDisk() {
                            logger.error(chainedError: error, message: "Failed to persist address cache after reading it from bundle.")
                        }
                    }

                    logger.debug("Initialized cache from \(readResult.source) with \(cachedAddresses.endpoints.count) endpoint(s).")
                }

            case .failure(let error):
                logger.error(chainedError: error, message: "Failed to read address cache. Fallback to default API endpoint.")

                cachedAddresses = Self.defaultCachedAddresses

                logger.debug("Initialized cache with default API endpoint.")
            }
        }

        func getCurrentEndpoint(_ completionHandler: @escaping (AnyIPEndpoint) -> Void) {
            stateQueue.async {
                let currentEndpoint = self.cachedAddresses.endpoints.first!

                completionHandler(currentEndpoint)
            }
        }

        func selectNextEndpoint(_ failedEndpoint: AnyIPEndpoint, completionHandler: @escaping (AnyIPEndpoint) -> Void) {
            stateQueue.async {
                var currentEndpoint = self.cachedAddresses.endpoints.first!

                if failedEndpoint == currentEndpoint {
                    self.cachedAddresses.endpoints.removeFirst()
                    self.cachedAddresses.endpoints.append(failedEndpoint)

                    currentEndpoint = self.cachedAddresses.endpoints.first!

                    self.logger.debug("Failed to communicate using \(failedEndpoint). Next endpoint: \(currentEndpoint)")

                    if case .failure(let error) = self.writeToDisk() {
                        self.logger.error(chainedError: error, message: "Failed to write address cache after selecting next endpoint.")
                    }
                }

                completionHandler(currentEndpoint)
            }
        }

        func setEndpoints(_ endpoints: [AnyIPEndpoint], completionHandler: @escaping (AddressCache.StoreError?) -> Void) {
            stateQueue.async {
                guard !endpoints.isEmpty else {
                    completionHandler(.emptyAddressList)
                    return
                }

                if Set(self.cachedAddresses.endpoints) == Set(endpoints) {
                    self.cachedAddresses.updatedAt = Date()
                } else {
                    // Shuffle new endpoints
                    var newEndpoints = endpoints.shuffled()

                    // Move current endpoint to the top of the list
                    let currentEndpoint = self.cachedAddresses.endpoints.first!
                    if let index = newEndpoints.firstIndex(of: currentEndpoint) {
                        newEndpoints.remove(at: index)
                        newEndpoints.insert(currentEndpoint, at: 0)
                    }
                    
                    self.cachedAddresses = CachedAddresses(
                        updatedAt: Date(),
                        endpoints: newEndpoints
                    )
                }

                let writeResult = self.writeToDisk()

                completionHandler(writeResult.error)
            }
        }

        func getLastUpdateDate(_ completionHandler: @escaping (Date) -> Void) {
            stateQueue.async {
                completionHandler(self.cachedAddresses.updatedAt)
            }
        }

        func getLastUpdateDateAndWait() -> Date {
            return stateQueue.sync {
                return self.cachedAddresses.updatedAt
            }
        }

        private func readFromCacheLocationWithFallback() -> Result<ReadResult, AddressCache.StoreError> {
            return readFromCacheLocation()
                .map { addresses in
                    return ReadResult(
                        cachedAddresses: addresses,
                        source: .disk
                    )
                }
                .flatMapError { error in
                    logger.error(chainedError: error, message: "Failed to read address cache from disk. Fallback to pre-bundled cache.")

                    return readFromBundle().map { cachedAddresses in
                        return ReadResult(
                            cachedAddresses: cachedAddresses,
                            source: .bundle
                        )
                    }
                }
        }

        private func readFromCacheLocation() -> Result<CachedAddresses, AddressCache.StoreError> {
            return Result { try Data(contentsOf: cacheFileURL) }
                .mapError { error in
                    return .readCache(error)
                }
                .flatMap { data in
                    return Result { try JSONDecoder().decode(CachedAddresses.self, from: data) }
                        .mapError { error in
                            return .decodeCache(error)
                        }
                }
        }

        private func writeToDisk() -> Result<(), AddressCache.StoreError> {
            let cacheDirectoryURL = cacheFileURL.deletingLastPathComponent()

            try? FileManager.default.createDirectory(
                at: cacheDirectoryURL,
                withIntermediateDirectories: true,
                attributes: nil
            )

            return Result { try JSONEncoder().encode(cachedAddresses) }
                .mapError { error in
                    return .encodeCache(error)
                }
                .flatMap { data in
                    return Result { try data.write(to: cacheFileURL, options: .atomic) }
                        .mapError { error in
                            return .writeCache(error)
                        }
                }
        }

        private func readFromBundle() -> Result<CachedAddresses, AddressCache.StoreError> {
            return Result { try Data(contentsOf: prebundledCacheFileURL) }
                .mapError { error in
                    return .readCacheFromBundle(error)
                }
                .flatMap { data in
                    return Result { try JSONDecoder().decode([AnyIPEndpoint].self, from: data) }
                        .mapError { error in
                            return .decodeCacheFromBundle(error)
                        }
                        .map { endpoints in
                            return CachedAddresses(
                                updatedAt: Date(timeIntervalSince1970: 0),
                                endpoints: endpoints
                            )
                        }
                }
        }

    }
}