Installations+InstallationsProtocol.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. internal import FirebaseInstallations
  17. protocol InstallationsProtocol: Sendable {
  18. var installationsWaitTimeInSecond: Int { get }
  19. /// Override Installation function for testing
  20. func authToken(completion: @escaping (InstallationsAuthTokenResult?, Error?) -> Void)
  21. /// Override Installation function for testing
  22. func installationID(completion: @escaping (String?, Error?) -> Void)
  23. /// Return a tuple: (installationID, authenticationToken) for success result
  24. func installationID(completion: @escaping (Result<(String, String), Error>) -> Void)
  25. }
  26. extension InstallationsProtocol {
  27. var installationsWaitTimeInSecond: Int {
  28. return 10
  29. }
  30. func installationID(completion: @escaping (Result<(String, String), Error>) -> Void) {
  31. var authTokenComplete = ""
  32. var installationComplete: String?
  33. var errorComplete: Error?
  34. let workingGroup = DispatchGroup()
  35. workingGroup.enter()
  36. authToken { (authTokenResult: InstallationsAuthTokenResult?, error: Error?) in
  37. authTokenComplete = authTokenResult?.authToken ?? ""
  38. workingGroup.leave()
  39. }
  40. workingGroup.enter()
  41. installationID { (installationID: String?, error: Error?) in
  42. if let installationID {
  43. installationComplete = installationID
  44. } else if let error = error {
  45. errorComplete = error
  46. }
  47. workingGroup.leave()
  48. }
  49. // adding timeout for 10 seconds
  50. let result = workingGroup
  51. .wait(timeout: .now() + DispatchTimeInterval.seconds(installationsWaitTimeInSecond))
  52. switch result {
  53. case .timedOut:
  54. completion(.failure(FirebaseSessionsError.SessionInstallationsTimeOutError))
  55. return
  56. default:
  57. if let installationComplete {
  58. completion(.success((installationComplete, authTokenComplete)))
  59. } else if let errorComplete {
  60. completion(.failure(errorComplete))
  61. }
  62. }
  63. }
  64. }
  65. extension Installations: InstallationsProtocol {}