SessionGenerator.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. @_implementationOnly import FirebaseInstallations
  17. struct SessionInfo {
  18. let sessionId: String
  19. let previousSessionId: String?
  20. let shouldDispatchEvents: Bool
  21. init(sessionId: String, previousSessionId: String?, dispatchEvents: Bool) {
  22. self.sessionId = sessionId
  23. self.previousSessionId = previousSessionId
  24. shouldDispatchEvents = dispatchEvents
  25. }
  26. }
  27. ///
  28. /// Generator is responsible for:
  29. /// 1) Generating the Session ID
  30. /// 2) Persisting and reading the Session ID from the last session
  31. /// (Maybe) 3) Persisting, reading, and incrementing an increasing index
  32. ///
  33. class SessionGenerator {
  34. private var thisSession: SessionInfo?
  35. private var settings: SessionsSettings
  36. init(settings: SessionsSettings) {
  37. self.settings = settings
  38. }
  39. // Generates a new Session ID. If there was already a generated Session ID
  40. // from the last session during the app's lifecycle, it will also set the last Session ID
  41. func generateNewSession() -> SessionInfo {
  42. let newSessionId = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
  43. var collectEvents = true
  44. let randomValue = Double.random(in: 0 ... 1)
  45. if randomValue > settings.samplingRate {
  46. collectEvents = false
  47. }
  48. let newSession = SessionInfo(sessionId: newSessionId,
  49. previousSessionId: thisSession?.sessionId,
  50. dispatchEvents: collectEvents)
  51. thisSession = newSession
  52. return newSession
  53. }
  54. var currentSession: SessionInfo? {
  55. return thisSession
  56. }
  57. }