FirebaseSessions.swift 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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 events
  111. init(appID: String, sessionGenerator: SessionGenerator, coordinator: SessionCoordinatorProtocol,
  112. initiator: SessionInitiator, appInfo: ApplicationInfoProtocol, settings: SettingsProtocol,
  113. loggedEventCallback: @escaping (Result<Void, FirebaseSessionsError>) -> Void) {
  114. self.appID = appID
  115. self.sessionGenerator = sessionGenerator
  116. self.coordinator = coordinator
  117. self.initiator = initiator
  118. self.appInfo = appInfo
  119. self.settings = settings
  120. super.init()
  121. SessionsDependencies.dependencies.forEach { subscriberName in
  122. self.subscriberPromises[subscriberName] = Promise<Void>.pending()
  123. }
  124. Logger
  125. .logDebug(
  126. "Version \(FirebaseVersion()). Expecting subscriptions from: \(SessionsDependencies.dependencies)"
  127. )
  128. self.initiator.beginListening {
  129. // Generating a Session ID early is important as Subscriber
  130. // SDKs will need to read it immediately upon registration.
  131. let sessionInfo = self.sessionGenerator.generateNewSession()
  132. // Post a notification so subscriber SDKs can get an updated Session ID
  133. self.notificationCenter.post(name: Sessions.SessionIDChangedNotificationName,
  134. object: nil)
  135. let event = SessionStartEvent(sessionInfo: sessionInfo, appInfo: self.appInfo)
  136. // If there are no Dependencies, then the Sessions SDK can't acknowledge
  137. // any products data collection state, so the Sessions SDK won't send events.
  138. guard !self.subscriberPromises.isEmpty else {
  139. loggedEventCallback(.failure(.NoDependenciesError))
  140. return
  141. }
  142. // Wait until all subscriber promises have been fulfilled before
  143. // doing any data collection.
  144. all(self.subscriberPromises.values).then(on: .global(qos: .background)) { _ in
  145. guard self.isAnyDataCollectionEnabled else {
  146. loggedEventCallback(.failure(.DataCollectionError))
  147. return
  148. }
  149. Logger.logDebug("Data Collection is enabled for at least one Subscriber")
  150. // Fetch settings if they have expired. This must happen after the check for
  151. // data collection because it uses the network, but it must happen before the
  152. // check for sessionsEnabled from Settings because otherwise we would permanently
  153. // turn off the Sessions SDK when we disabled it.
  154. self.settings.updateSettings()
  155. self.addSubscriberFields(event: event)
  156. event.setSamplingRate(samplingRate: self.settings.samplingRate)
  157. guard sessionInfo.shouldDispatchEvents else {
  158. loggedEventCallback(.failure(.SessionSamplingError))
  159. return
  160. }
  161. guard self.settings.sessionsEnabled else {
  162. loggedEventCallback(.failure(.DisabledViaSettingsError))
  163. return
  164. }
  165. self.coordinator.attemptLoggingSessionStart(event: event) { result in
  166. loggedEventCallback(result)
  167. }
  168. }
  169. }
  170. }
  171. // MARK: - Sampling
  172. static func shouldCollectEvents(settings: SettingsProtocol) -> Bool {
  173. // Calculate whether we should sample events using settings data
  174. // Sampling rate of 1 means we do not sample.
  175. let randomValue = Double.random(in: 0 ... 1)
  176. return randomValue <= settings.samplingRate
  177. }
  178. // MARK: - Data Collection
  179. var isAnyDataCollectionEnabled: Bool {
  180. for subscriber in subscribers {
  181. if subscriber.isDataCollectionEnabled {
  182. return true
  183. }
  184. }
  185. return false
  186. }
  187. func addSubscriberFields(event: SessionStartEvent) {
  188. subscribers.forEach { subscriber in
  189. event.set(subscriber: subscriber.sessionsSubscriberName,
  190. isDataCollectionEnabled: subscriber.isDataCollectionEnabled,
  191. appInfo: self.appInfo)
  192. }
  193. }
  194. // MARK: - SessionsProvider
  195. var currentSessionDetails: SessionDetails {
  196. return SessionDetails(sessionId: sessionGenerator.currentSession?.sessionId)
  197. }
  198. func register(subscriber: SessionsSubscriber) {
  199. Logger
  200. .logDebug(
  201. "Registering Sessions SDK subscriber with name: \(subscriber.sessionsSubscriberName), data collection enabled: \(subscriber.isDataCollectionEnabled)"
  202. )
  203. notificationCenter.addObserver(
  204. forName: Sessions.SessionIDChangedNotificationName,
  205. object: nil,
  206. queue: nil
  207. ) { notification in
  208. subscriber.onSessionChanged(self.currentSessionDetails)
  209. }
  210. // Immediately call the callback because the Sessions SDK starts
  211. // before subscribers, so subscribers will miss the first Notification
  212. subscriber.onSessionChanged(currentSessionDetails)
  213. // Fulfil this subscriber's promise
  214. subscribers.append(subscriber)
  215. subscriberPromises[subscriber.sessionsSubscriberName]?.fulfill(())
  216. }
  217. // MARK: - Library conformance
  218. static func componentsToRegister() -> [Component] {
  219. return [Component(SessionsProvider.self,
  220. instantiationTiming: .alwaysEager,
  221. dependencies: []) { container, isCacheable in
  222. // Sessions SDK only works for the default app
  223. guard let app = container.app, app.isDefaultApp else { return nil }
  224. isCacheable.pointee = true
  225. let installations = Installations.installations(app: app)
  226. return self.init(appID: app.options.googleAppID, installations: installations)
  227. }]
  228. }
  229. }