FirebaseSessions.swift 9.7 KB

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