FirebaseSessions.swift 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. // Copyright 2022 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. // Avoids exposing internal FirebaseCore APIs to Swift users.
  16. @_implementationOnly import FirebaseCoreExtension
  17. @_implementationOnly import FirebaseInstallations
  18. @_implementationOnly import GoogleDataTransport
  19. #if swift(>=6.0)
  20. internal import Promises
  21. #elseif swift(>=5.10)
  22. import Promises
  23. #else
  24. @_implementationOnly import Promises
  25. #endif
  26. private enum GoogleDataTransportConfig {
  27. static let sessionsLogSource = "1974"
  28. static let sessionsTarget = GDTCORTarget.FLL
  29. }
  30. @objc(FIRSessions) final class Sessions: NSObject, Library, SessionsProvider {
  31. // MARK: - Private Variables
  32. /// The Firebase App ID associated with Sessions.
  33. private let appID: String
  34. /// Top-level Classes in the Sessions SDK
  35. private let coordinator: SessionCoordinatorProtocol
  36. private let initiator: SessionInitiator
  37. private let sessionGenerator: SessionGenerator
  38. private let appInfo: ApplicationInfoProtocol
  39. private let settings: SettingsProtocol
  40. /// Subscribers
  41. /// `subscribers` are used to determine the Data Collection state of the Sessions SDK.
  42. /// If any Subscribers has Data Collection enabled, the Sessions SDK will send events
  43. private var subscribers: [SessionsSubscriber] = []
  44. /// `subscriberPromises` are used to wait until all Subscribers have registered
  45. /// themselves. Subscribers must have Data Collection state available upon registering.
  46. private var subscriberPromises: [SessionsSubscriberName: Promise<Void>] = [:]
  47. /// Notifications
  48. static let SessionIDChangedNotificationName = Notification
  49. .Name("SessionIDChangedNotificationName")
  50. let notificationCenter = NotificationCenter()
  51. // MARK: - Initializers
  52. // Initializes the SDK and top-level classes
  53. required convenience init(appID: String, installations: InstallationsProtocol) {
  54. let googleDataTransport = GDTCORTransport(
  55. mappingID: GoogleDataTransportConfig.sessionsLogSource,
  56. transformers: nil,
  57. target: GoogleDataTransportConfig.sessionsTarget
  58. )
  59. let fireLogger = EventGDTLogger(googleDataTransport: googleDataTransport!)
  60. let appInfo = ApplicationInfo(appID: appID)
  61. let settings = SessionsSettings(
  62. appInfo: appInfo,
  63. installations: installations
  64. )
  65. let sessionGenerator = SessionGenerator(collectEvents: Sessions
  66. .shouldCollectEvents(settings: settings))
  67. let coordinator = SessionCoordinator(
  68. installations: installations,
  69. fireLogger: fireLogger
  70. )
  71. let initiator = SessionInitiator(settings: settings)
  72. self.init(appID: appID,
  73. sessionGenerator: sessionGenerator,
  74. coordinator: coordinator,
  75. initiator: initiator,
  76. appInfo: appInfo,
  77. settings: settings) { result in
  78. switch result {
  79. case .success(()):
  80. Logger.logInfo("Successfully logged Session Start event")
  81. case let .failure(sessionsError):
  82. switch sessionsError {
  83. case let .SessionInstallationsError(error):
  84. Logger.logError(
  85. "Error getting Firebase Installation ID: \(error). Skipping this Session Event"
  86. )
  87. case let .DataTransportError(error):
  88. Logger
  89. .logError(
  90. "Error logging Session Start event to GoogleDataTransport: \(error)."
  91. )
  92. case .NoDependenciesError:
  93. Logger
  94. .logError(
  95. "Sessions SDK did not have any dependent SDKs register as dependencies. Events will not be sent."
  96. )
  97. case .SessionSamplingError:
  98. Logger
  99. .logDebug(
  100. "Sessions SDK has sampled this session"
  101. )
  102. case .DisabledViaSettingsError:
  103. Logger
  104. .logDebug(
  105. "Sessions SDK is disabled via Settings"
  106. )
  107. case .DataCollectionError:
  108. Logger
  109. .logDebug(
  110. "Data Collection is disabled for all subscribers. Skipping this Session Event"
  111. )
  112. case .SessionInstallationsTimeOutError:
  113. Logger.logError(
  114. "Error getting Firebase Installation ID due to timeout. Skipping this Session Event"
  115. )
  116. }
  117. }
  118. }
  119. }
  120. // Initializes the SDK and begins the process of listening for lifecycle events and logging
  121. // events
  122. init(appID: String, sessionGenerator: SessionGenerator, coordinator: SessionCoordinatorProtocol,
  123. initiator: SessionInitiator, appInfo: ApplicationInfoProtocol, settings: SettingsProtocol,
  124. loggedEventCallback: @escaping (Result<Void, FirebaseSessionsError>) -> Void) {
  125. self.appID = appID
  126. self.sessionGenerator = sessionGenerator
  127. self.coordinator = coordinator
  128. self.initiator = initiator
  129. self.appInfo = appInfo
  130. self.settings = settings
  131. super.init()
  132. for subscriberName in SessionsDependencies.dependencies {
  133. subscriberPromises[subscriberName] = Promise<Void>.pending()
  134. }
  135. Logger
  136. .logDebug(
  137. "Version \(FirebaseVersion()). Expecting subscriptions from: \(SessionsDependencies.dependencies)"
  138. )
  139. self.initiator.beginListening {
  140. // Generating a Session ID early is important as Subscriber
  141. // SDKs will need to read it immediately upon registration.
  142. let sessionInfo = self.sessionGenerator.generateNewSession()
  143. // Post a notification so subscriber SDKs can get an updated Session ID
  144. self.notificationCenter.post(name: Sessions.SessionIDChangedNotificationName,
  145. object: nil)
  146. let event = SessionStartEvent(sessionInfo: sessionInfo, appInfo: self.appInfo)
  147. // If there are no Dependencies, then the Sessions SDK can't acknowledge
  148. // any products data collection state, so the Sessions SDK won't send events.
  149. guard !self.subscriberPromises.isEmpty else {
  150. loggedEventCallback(.failure(.NoDependenciesError))
  151. return
  152. }
  153. // Wait until all subscriber promises have been fulfilled before
  154. // doing any data collection.
  155. all(self.subscriberPromises.values).then(on: .global(qos: .background)) { _ in
  156. guard self.isAnyDataCollectionEnabled else {
  157. loggedEventCallback(.failure(.DataCollectionError))
  158. return
  159. }
  160. Logger.logDebug("Data Collection is enabled for at least one Subscriber")
  161. // Fetch settings if they have expired. This must happen after the check for
  162. // data collection because it uses the network, but it must happen before the
  163. // check for sessionsEnabled from Settings because otherwise we would permanently
  164. // turn off the Sessions SDK when we disabled it.
  165. self.settings.updateSettings()
  166. self.addSubscriberFields(event: event)
  167. event.setSamplingRate(samplingRate: self.settings.samplingRate)
  168. guard sessionInfo.shouldDispatchEvents else {
  169. loggedEventCallback(.failure(.SessionSamplingError))
  170. return
  171. }
  172. guard self.settings.sessionsEnabled else {
  173. loggedEventCallback(.failure(.DisabledViaSettingsError))
  174. return
  175. }
  176. self.coordinator.attemptLoggingSessionStart(event: event) { result in
  177. loggedEventCallback(result)
  178. }
  179. }
  180. }
  181. }
  182. // MARK: - Sampling
  183. static func shouldCollectEvents(settings: SettingsProtocol) -> Bool {
  184. // Calculate whether we should sample events using settings data
  185. // Sampling rate of 1 means we do not sample.
  186. let randomValue = Double.random(in: 0 ... 1)
  187. return randomValue <= settings.samplingRate
  188. }
  189. // MARK: - Data Collection
  190. var isAnyDataCollectionEnabled: Bool {
  191. for subscriber in subscribers {
  192. if subscriber.isDataCollectionEnabled {
  193. return true
  194. }
  195. }
  196. return false
  197. }
  198. func addSubscriberFields(event: SessionStartEvent) {
  199. for subscriber in subscribers {
  200. event.set(subscriber: subscriber.sessionsSubscriberName,
  201. isDataCollectionEnabled: subscriber.isDataCollectionEnabled,
  202. appInfo: appInfo)
  203. }
  204. }
  205. // MARK: - SessionsProvider
  206. var currentSessionDetails: SessionDetails {
  207. return SessionDetails(sessionId: sessionGenerator.currentSession?.sessionId)
  208. }
  209. func register(subscriber: SessionsSubscriber) {
  210. Logger
  211. .logDebug(
  212. "Registering Sessions SDK subscriber with name: \(subscriber.sessionsSubscriberName), data collection enabled: \(subscriber.isDataCollectionEnabled)"
  213. )
  214. notificationCenter.addObserver(
  215. forName: Sessions.SessionIDChangedNotificationName,
  216. object: nil,
  217. queue: nil
  218. ) { notification in
  219. subscriber.onSessionChanged(self.currentSessionDetails)
  220. }
  221. // Immediately call the callback because the Sessions SDK starts
  222. // before subscribers, so subscribers will miss the first Notification
  223. subscriber.onSessionChanged(currentSessionDetails)
  224. // Fulfil this subscriber's promise
  225. subscribers.append(subscriber)
  226. subscriberPromises[subscriber.sessionsSubscriberName]?.fulfill(())
  227. }
  228. // MARK: - Library conformance
  229. static func componentsToRegister() -> [Component] {
  230. return [Component(SessionsProvider.self,
  231. instantiationTiming: .alwaysEager) { container, isCacheable in
  232. // Sessions SDK only works for the default app
  233. guard let app = container.app, app.isDefaultApp else { return nil }
  234. isCacheable.pointee = true
  235. let installations = Installations.installations(app: app)
  236. return self.init(appID: app.options.googleAppID, installations: installations)
  237. }]
  238. }
  239. }