FirebaseSessions.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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: SessionCoordinator
  30. private let initiator: SessionInitiator
  31. private let sessionGenerator: SessionGenerator
  32. private let appInfo: ApplicationInfo
  33. private let settings: SessionsSettings
  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(settings: settings)
  60. let coordinator = SessionCoordinator(
  61. installations: installations,
  62. fireLogger: fireLogger
  63. )
  64. let initiator = SessionInitiator(settings: settings)
  65. self.init(appID: appID,
  66. sessionGenerator: sessionGenerator,
  67. coordinator: coordinator,
  68. initiator: initiator,
  69. appInfo: appInfo,
  70. settings: settings)
  71. }
  72. // Initializes the SDK and begines the process of listening for lifecycle events and logging events
  73. init(appID: String, sessionGenerator: SessionGenerator, coordinator: SessionCoordinator,
  74. initiator: SessionInitiator, appInfo: ApplicationInfo, settings: SessionsSettings) {
  75. self.appID = appID
  76. self.sessionGenerator = sessionGenerator
  77. self.coordinator = coordinator
  78. self.initiator = initiator
  79. self.appInfo = appInfo
  80. self.settings = settings
  81. super.init()
  82. SessionsDependencies.dependencies.forEach { subscriberName in
  83. self.subscriberPromises[subscriberName] = Promise<Void>.pending()
  84. }
  85. Logger.logDebug("Expecting subscriptions from: \(SessionsDependencies.dependencies)")
  86. self.initiator.beginListening {
  87. // Generating a Session ID early is important as Subscriber
  88. // SDKs will need to read it immediately upon registration.
  89. let sessionInfo = self.sessionGenerator.generateNewSession()
  90. // Post a notification so subscriber SDKs can get an updated Session ID
  91. self.notificationCenter.post(name: Sessions.SessionIDChangedNotificationName,
  92. object: nil)
  93. let event = SessionStartEvent(sessionInfo: sessionInfo, appInfo: self.appInfo)
  94. // Wait until all subscriber promises have been fulfilled before
  95. // doing any data collection.
  96. all(self.subscriberPromises.values).then(on: .global(qos: .background)) { _ in
  97. guard self.isAnyDataCollectionEnabled else {
  98. Logger
  99. .logDebug(
  100. "Data Collection is disabled for all subscribers. Skipping this Session Event"
  101. )
  102. return
  103. }
  104. Logger.logDebug("Data Collection is enabled for at least one Subscriber")
  105. // Fetch settings if they have expired. This must happen after the check for
  106. // data collection because it uses the network, but it must happen before the
  107. // check for sessionsEnabled from Settings because otherwise we would permanently
  108. // turn off the Sessions SDK when we disabled it.
  109. self.settings.updateSettings()
  110. self.addEventDataCollectionState(event: event)
  111. if !(self.settings.sessionsEnabled && sessionInfo.shouldDispatchEvents) {
  112. Logger
  113. .logDebug(
  114. "Session Event logging is disabled sessionsEnabled: \(self.settings.sessionsEnabled), shouldDispatchEvents: \(sessionInfo.shouldDispatchEvents)"
  115. )
  116. return
  117. }
  118. self.coordinator.attemptLoggingSessionStart(event: event) { result in
  119. }
  120. }
  121. }
  122. }
  123. // MARK: - Data Collection
  124. var isAnyDataCollectionEnabled: Bool {
  125. for subscriber in subscribers {
  126. if subscriber.isDataCollectionEnabled {
  127. return true
  128. }
  129. }
  130. return false
  131. }
  132. func addEventDataCollectionState(event: SessionStartEvent) {
  133. subscribers.forEach { subscriber in
  134. event.set(subscriber: subscriber.sessionsSubscriberName,
  135. isDataCollectionEnabled: subscriber.isDataCollectionEnabled)
  136. }
  137. }
  138. // MARK: - SessionsProvider
  139. var currentSessionDetails: SessionDetails {
  140. return SessionDetails(sessionId: sessionGenerator.currentSession?.sessionId)
  141. }
  142. func register(subscriber: SessionsSubscriber) {
  143. Logger
  144. .logDebug(
  145. "Registering Sessions SDK subscriber with name: \(subscriber.sessionsSubscriberName), data collection enabled: \(subscriber.isDataCollectionEnabled)"
  146. )
  147. notificationCenter.addObserver(
  148. forName: Sessions.SessionIDChangedNotificationName,
  149. object: nil,
  150. queue: nil
  151. ) { notification in
  152. subscriber.onSessionChanged(self.currentSessionDetails)
  153. }
  154. // Immediately call the callback because the Sessions SDK starts
  155. // before subscribers, so subscribers will miss the first Notification
  156. subscriber.onSessionChanged(currentSessionDetails)
  157. // Fulfil this subscriber's promise
  158. subscribers.append(subscriber)
  159. subscriberPromises[subscriber.sessionsSubscriberName]?.fulfill(())
  160. }
  161. // MARK: - Library conformance
  162. static func componentsToRegister() -> [Component] {
  163. return [Component(SessionsProvider.self,
  164. instantiationTiming: .alwaysEager,
  165. dependencies: []) { container, isCacheable in
  166. // Sessions SDK only works for the default app
  167. guard let app = container.app, app.isDefaultApp else { return nil }
  168. isCacheable.pointee = true
  169. let installations = Installations.installations(app: app)
  170. return self.init(appID: app.options.googleAppID, installations: installations)
  171. }]
  172. }
  173. }