SettingsCacheClient.swift 3.1 KB

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