SettingsCacheClient.swift 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. //
  2. // Copyright 2022 Google LLC
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. import Foundation
  16. /// CacheKey is like a "key" to a "safe". It provides necessary metadata about the current cache to know if it should be expired.
  17. struct CacheKey: Codable {
  18. var createdAt: Date
  19. var googleAppID: String
  20. var appVersion: String
  21. }
  22. /// SettingsCacheClient is responsible for accessing the cache that Settings are stored in.
  23. protocol SettingsCacheClient {
  24. /// Returns in-memory cache content in O(1) time. Returns empty dictionary if it does not exist in cache.
  25. var cacheContent: [String: Any] { get set }
  26. /// Returns in-memory cache-key, no performance guarantee because type-casting depends on size of CacheKey
  27. var cacheKey: CacheKey? { get set }
  28. /// Removes all cache content and cache-key
  29. func removeCache()
  30. }
  31. /// SettingsCache uses UserDefaults to store Settings on-disk, but also directly query UserDefaults when accessing Settings values during run-time. This is because UserDefaults encapsulates both in-memory and persisted-on-disk storage, allowing fast synchronous access in-app while hiding away the complexity of managing persistence asynchronously.
  32. class SettingsCache: SettingsCacheClient {
  33. private static let settingsVersion: Int = 1
  34. private enum UserDefaultsKeys {
  35. static let forContent = "firebase-sessions-settings"
  36. static let forCacheKey = "firebase-sessions-cache-key"
  37. }
  38. /// UserDefaults holds values in memory, making access O(1) and synchronous within the app, while abstracting away async disk IO.
  39. private let cache: UserDefaults = .standard
  40. /// Converting to dictionary is O(1) because object conversion is O(1)
  41. var cacheContent: [String: Any] {
  42. get {
  43. return cache.dictionary(forKey: UserDefaultsKeys.forContent) ?? [:]
  44. }
  45. set {
  46. cache.set(newValue, forKey: UserDefaultsKeys.forContent)
  47. }
  48. }
  49. /// Casting to Codable from Data is O(n)
  50. var cacheKey: CacheKey? {
  51. get {
  52. if let data = cache.data(forKey: UserDefaultsKeys.forCacheKey) {
  53. do {
  54. return try JSONDecoder().decode(CacheKey.self, from: data)
  55. } catch {
  56. Logger.logError("[Settings] Decoding CacheKey failed with error: \(error)")
  57. }
  58. }
  59. return nil
  60. }
  61. set {
  62. do {
  63. cache.set(try JSONEncoder().encode(newValue), forKey: UserDefaultsKeys.forCacheKey)
  64. } catch {
  65. Logger.logError("[Settings] Encoding CacheKey failed with error: \(error)")
  66. }
  67. }
  68. }
  69. /// Removes stored cache
  70. func removeCache() {
  71. cache.set(nil, forKey: UserDefaultsKeys.forContent)
  72. cache.set(nil, forKey: UserDefaultsKeys.forCacheKey)
  73. }
  74. }