SettingsCacheClient.swift 5.7 KB

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