SettingsCacheClient.swift 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. #if SWIFT_PACKAGE
  17. @_implementationOnly import GoogleUtilities_UserDefaults
  18. #else
  19. @_implementationOnly import GoogleUtilities
  20. #endif // SWIFT_PACKAGE
  21. /// CacheKey is like a "key" to a "safe". It provides necessary metadata about the current cache to
  22. /// know if it should be expired.
  23. struct CacheKey: Codable {
  24. var createdAt: Date
  25. var googleAppID: String
  26. var appVersion: String
  27. }
  28. /// SettingsCacheClient is responsible for accessing the cache that Settings are stored in.
  29. protocol SettingsCacheClient {
  30. /// Returns in-memory cache content in O(1) time. Returns empty dictionary if it does not exist in
  31. /// cache.
  32. var cacheContent: [String: Any] { get set }
  33. /// Returns in-memory cache-key, no performance guarantee because type-casting depends on size of
  34. /// CacheKey
  35. var cacheKey: CacheKey? { get set }
  36. /// Removes all cache content and cache-key
  37. func removeCache()
  38. }
  39. /// SettingsCache uses UserDefaults to store Settings on-disk, but also directly query UserDefaults
  40. /// when accessing Settings values during run-time. This is because UserDefaults encapsulates both
  41. /// in-memory and persisted-on-disk storage, allowing fast synchronous access in-app while hiding
  42. /// away the complexity of managing persistence asynchronously.
  43. class SettingsCache: SettingsCacheClient {
  44. private static let settingsVersion: Int = 1
  45. private enum UserDefaultsKeys {
  46. static let forContent = "firebase-sessions-settings"
  47. static let forCacheKey = "firebase-sessions-cache-key"
  48. }
  49. /// UserDefaults holds values in memory, making access O(1) and synchronous within the app, while
  50. /// abstracting away async disk IO.
  51. private let cache: GULUserDefaults = .standard()
  52. /// Converting to dictionary is O(1) because object conversion is O(1)
  53. var cacheContent: [String: Any] {
  54. get {
  55. return (cache.object(forKey: UserDefaultsKeys.forContent) as? [String: Any]) ?? [:]
  56. }
  57. set {
  58. cache.setObject(newValue, forKey: UserDefaultsKeys.forContent)
  59. }
  60. }
  61. /// Casting to Codable from Data is O(n)
  62. var cacheKey: CacheKey? {
  63. get {
  64. if let data = cache.object(forKey: UserDefaultsKeys.forCacheKey) as? Data {
  65. do {
  66. return try JSONDecoder().decode(CacheKey.self, from: data)
  67. } catch {
  68. Logger.logError("[Settings] Decoding CacheKey failed with error: \(error)")
  69. }
  70. }
  71. return nil
  72. }
  73. set {
  74. do {
  75. try cache.setObject(JSONEncoder().encode(newValue), forKey: UserDefaultsKeys.forCacheKey)
  76. } catch {
  77. Logger.logError("[Settings] Encoding CacheKey failed with error: \(error)")
  78. }
  79. }
  80. }
  81. /// Removes stored cache
  82. func removeCache() {
  83. cache.setObject(nil, forKey: UserDefaultsKeys.forContent)
  84. cache.setObject(nil, forKey: UserDefaultsKeys.forCacheKey)
  85. }
  86. }