RemoteSettings.swift 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. internal import FirebaseCoreInternal
  17. /// Extends ApplicationInfoProtocol to string-format a combined appDisplayVersion and
  18. /// appBuildVersion
  19. extension ApplicationInfoProtocol {
  20. var synthesizedVersion: String { return "\(appDisplayVersion) (\(appBuildVersion))" }
  21. }
  22. final class RemoteSettings: SettingsProvider, Sendable {
  23. private static let flagSessionsEnabled = "sessions_enabled"
  24. private static let flagSamplingRate = "sampling_rate"
  25. private static let flagSessionTimeout = "session_timeout_seconds"
  26. private static let flagSessionsCache = "app_quality"
  27. private let appInfo: ApplicationInfoProtocol
  28. private let downloader: SettingsDownloadClient
  29. private let cache: FIRAllocatedUnfairLock<SettingsCacheClient>
  30. private var sessionsCache: [String: Any] {
  31. cache.withLock { cache in
  32. cache.cacheContent[RemoteSettings.flagSessionsCache] as? [String: Any] ?? [:]
  33. }
  34. }
  35. init(appInfo: ApplicationInfoProtocol,
  36. downloader: SettingsDownloadClient,
  37. cache: SettingsCacheClient = SettingsCache()) {
  38. self.appInfo = appInfo
  39. self.cache = FIRAllocatedUnfairLock(initialState: cache)
  40. self.downloader = downloader
  41. }
  42. private func fetchAndCacheSettings(currentTime: Date) {
  43. let shouldFetch = cache.withLock { cache in
  44. // Only fetch if cache is expired, otherwise do nothing
  45. guard cache.isExpired(for: appInfo, time: currentTime) else {
  46. Logger.logDebug("[Settings] Cache is not expired, no fetch will be made.")
  47. return false
  48. }
  49. return true
  50. }
  51. if shouldFetch {
  52. downloader.fetch { result in
  53. switch result {
  54. case let .success(dictionary):
  55. self.cache.withLock { cache in
  56. // Saves all newly fetched Settings to cache
  57. cache.cacheContent = dictionary
  58. // Saves a "cache-key" which carries TTL metadata about current cache
  59. cache.cacheKey = CacheKey(
  60. createdAt: currentTime,
  61. googleAppID: self.appInfo.appID,
  62. appVersion: self.appInfo.synthesizedVersion
  63. )
  64. }
  65. case let .failure(error):
  66. Logger.logError("[Settings] Fetching newest settings failed with error: \(error)")
  67. }
  68. }
  69. }
  70. }
  71. }
  72. typealias RemoteSettingsConfigurations = RemoteSettings
  73. extension RemoteSettingsConfigurations {
  74. var sessionsEnabled: Bool? {
  75. return sessionsCache[RemoteSettings.flagSessionsEnabled] as? Bool
  76. }
  77. var samplingRate: Double? {
  78. return sessionsCache[RemoteSettings.flagSamplingRate] as? Double
  79. }
  80. var sessionTimeout: TimeInterval? {
  81. return sessionsCache[RemoteSettings.flagSessionTimeout] as? Double
  82. }
  83. }
  84. typealias RemoteSettingsProvider = RemoteSettings
  85. extension RemoteSettingsConfigurations {
  86. func updateSettings(currentTime: Date) {
  87. fetchAndCacheSettings(currentTime: currentTime)
  88. }
  89. func updateSettings() {
  90. updateSettings(currentTime: Date())
  91. }
  92. func isSettingsStale() -> Bool {
  93. cache.withLock { cache in
  94. cache.isExpired(for: appInfo, time: Date())
  95. }
  96. }
  97. }