SettingsCacheClient.swift 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. internal import GoogleUtilities_UserDefaults
  19. #else
  20. 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. }
  40. /// SettingsCache uses UserDefaults to store Settings on-disk, but also directly query UserDefaults
  41. /// when accessing Settings values during run-time. This is because UserDefaults encapsulates both
  42. /// in-memory and persisted-on-disk storage, allowing fast synchronous access in-app while hiding
  43. /// away the complexity of managing persistence asynchronously.
  44. final class SettingsCache: SettingsCacheClient {
  45. private static let settingsVersion: Int = 1
  46. private enum UserDefaultsKeys {
  47. static let forContent = "firebase-sessions-settings"
  48. static let forCacheKey = "firebase-sessions-cache-key"
  49. }
  50. /// UserDefaults holds values in memory, making access O(1) and synchronous within the app, while
  51. /// abstracting away async disk IO.
  52. private let cache: GULUserDefaults = .standard()
  53. /// Converting to dictionary is O(1) because object conversion is O(1)
  54. var cacheContent: [String: Any] {
  55. get {
  56. return (cache.object(forKey: UserDefaultsKeys.forContent) as? [String: Any]) ?? [:]
  57. }
  58. set {
  59. cache.setObject(newValue, forKey: UserDefaultsKeys.forContent)
  60. }
  61. }
  62. /// Casting to Codable from Data is O(n)
  63. var cacheKey: CacheKey? {
  64. get {
  65. if let data = cache.object(forKey: UserDefaultsKeys.forCacheKey) as? Data {
  66. do {
  67. return try JSONDecoder().decode(CacheKey.self, from: data)
  68. } catch {
  69. Logger.logError("[Settings] Decoding CacheKey failed with error: \(error)")
  70. }
  71. }
  72. return nil
  73. }
  74. set {
  75. do {
  76. try cache.setObject(JSONEncoder().encode(newValue), forKey: UserDefaultsKeys.forCacheKey)
  77. } catch {
  78. Logger.logError("[Settings] Encoding CacheKey failed with error: \(error)")
  79. }
  80. }
  81. }
  82. /// Removes stored cache
  83. func removeCache() {
  84. cache.setObject(nil, forKey: UserDefaultsKeys.forContent)
  85. cache.setObject(nil, forKey: UserDefaultsKeys.forCacheKey)
  86. }
  87. }