SessionSampler.swift 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. protocol SessionSamplerProtocol {
  16. /// Sampling rate that has to be applied across sessions.
  17. /// Ranges from 0 to 1 in Double.
  18. var sessionSamplingRate: Double { get set }
  19. /// Determines if a provided sessionID should be sampled or not.
  20. /// Note: Sample means allowed. A return of true means the event should be allowed, else dropped.
  21. func shouldSendEventForSession(sessionId: String) -> Bool
  22. }
  23. class SessionSampler: SessionSamplerProtocol {
  24. var sessionSamplingRate: Double
  25. /// TODO: Update this to a sampling logic once we have the configuration flags in place.
  26. /// Currently defaulted to 1.0 where no events are dropped.
  27. init(sessionSamplingRate: Double = 1.0) {
  28. self.sessionSamplingRate = sessionSamplingRate
  29. }
  30. func shouldSendEventForSession(sessionId: String) -> Bool {
  31. let randomValue = Double.random(in: 0 ... 1)
  32. if randomValue > sessionSamplingRate {
  33. return false
  34. }
  35. return true
  36. }
  37. }