SettingsCacheClient.swift 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. // TODO: sendable (remove preconcurrency)
  17. #if SWIFT_PACKAGE
  18. @preconcurrency internal import GoogleUtilities_UserDefaults
  19. #else
  20. @preconcurrency internal import GoogleUtilities
  21. #endif // SWIFT_PACKAGE
  22. /// CacheKey is like a "key" to a "safe". It provides necessary metadata about the current cache to
  23. /// know if it should be expired.
  24. struct CacheKey: Codable {
  25. var createdAt: Date
  26. var googleAppID: String
  27. var appVersion: String
  28. }
  29. /// SettingsCacheClient is responsible for accessing the cache that Settings are stored in.
  30. protocol SettingsCacheClient: Sendable {
  31. /// Returns in-memory cache content in O(1) time. Returns empty dictionary if it does not exist in
  32. /// cache.
  33. var cacheContent: [String: Any] { get set }
  34. /// Returns in-memory cache-key, no performance guarantee because type-casting depends on size of
  35. /// CacheKey
  36. var cacheKey: CacheKey? { get set }
  37. /// Removes all cache content and cache-key
  38. func removeCache()
  39. /// Returns whether the cache is expired for the given app info structure and time.
  40. func isExpired(for appInfo: ApplicationInfoProtocol, time: Date) -> Bool
  41. }
  42. /// SettingsCache uses UserDefaults to store Settings on-disk, but also directly query UserDefaults
  43. /// when accessing Settings values during run-time. This is because UserDefaults encapsulates both
  44. /// in-memory and persisted-on-disk storage, allowing fast synchronous access in-app while hiding
  45. /// away the complexity of managing persistence asynchronously.
  46. final class SettingsCache: SettingsCacheClient {
  47. private static let cacheDurationSecondsDefault: TimeInterval = 60 * 60
  48. private static let flagCacheDuration = "cache_duration"
  49. private static let settingsVersion: Int = 1
  50. private enum UserDefaultsKeys {
  51. static let forContent = "firebase-sessions-settings"
  52. static let forCacheKey = "firebase-sessions-cache-key"
  53. }
  54. /// UserDefaults holds values in memory, making access O(1) and synchronous within the app, while
  55. /// abstracting away async disk IO.
  56. private let cache: GULUserDefaults = .standard()
  57. /// Converting to dictionary is O(1) because object conversion is O(1)
  58. var cacheContent: [String: Any] {
  59. get {
  60. return (cache.object(forKey: UserDefaultsKeys.forContent) as? [String: Any]) ?? [:]
  61. }
  62. set {
  63. cache.setObject(newValue, forKey: UserDefaultsKeys.forContent)
  64. }
  65. }
  66. /// Casting to Codable from Data is O(n)
  67. var cacheKey: CacheKey? {
  68. get {
  69. if let data = cache.object(forKey: UserDefaultsKeys.forCacheKey) as? Data {
  70. do {
  71. return try JSONDecoder().decode(CacheKey.self, from: data)
  72. } catch {
  73. Logger.logError("[Settings] Decoding CacheKey failed with error: \(error)")
  74. }
  75. }
  76. return nil
  77. }
  78. set {
  79. do {
  80. try cache.setObject(JSONEncoder().encode(newValue), forKey: UserDefaultsKeys.forCacheKey)
  81. } catch {
  82. Logger.logError("[Settings] Encoding CacheKey failed with error: \(error)")
  83. }
  84. }
  85. }
  86. /// Removes stored cache
  87. func removeCache() {
  88. cache.setObject(nil, forKey: UserDefaultsKeys.forContent)
  89. cache.setObject(nil, forKey: UserDefaultsKeys.forCacheKey)
  90. }
  91. func isExpired(for appInfo: ApplicationInfoProtocol, time: Date) -> Bool {
  92. guard !cacheContent.isEmpty else {
  93. removeCache()
  94. return true
  95. }
  96. guard let cacheKey = cacheKey else {
  97. Logger.logError("[Settings] Could not load settings cache key")
  98. removeCache()
  99. return true
  100. }
  101. guard cacheKey.googleAppID == appInfo.appID else {
  102. Logger
  103. .logDebug("[Settings] Cache expired because Google App ID changed")
  104. removeCache()
  105. return true
  106. }
  107. if time.timeIntervalSince(cacheKey.createdAt) > cacheDuration() {
  108. Logger.logDebug("[Settings] Cache TTL expired")
  109. return true
  110. }
  111. if appInfo.synthesizedVersion != cacheKey.appVersion {
  112. Logger.logDebug("[Settings] Cache expired because app version changed")
  113. return true
  114. }
  115. return false
  116. }
  117. private func cacheDuration() -> TimeInterval {
  118. guard let duration = cacheContent[Self.flagCacheDuration] as? Double else {
  119. return Self.cacheDurationSecondsDefault
  120. }
  121. print("Duration: \(duration)")
  122. return duration
  123. }
  124. }