StorageComponent.swift 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. import FirebaseAppCheckInterop
  16. import FirebaseAuthInterop
  17. import FirebaseCore
  18. // Avoids exposing internal FirebaseCore APIs to Swift users.
  19. @_implementationOnly import FirebaseCoreExtension
  20. @objc(FIRStorageProvider)
  21. protocol StorageProvider {
  22. @objc func storage(for bucket: String) -> Storage
  23. }
  24. @objc(FIRStorageComponent) class StorageComponent: NSObject, Library, StorageProvider {
  25. // MARK: - Private Variables
  26. /// The app associated with all Storage instances in this container.
  27. private let app: FirebaseApp
  28. /// A map of active instances, grouped by app. Keys are FirebaseApp names and values are arrays
  29. /// containing all instances of Storage associated with the given app.
  30. private var instances: [String: Storage] = [:]
  31. /// Lock to manage access to the instances array to avoid race conditions.
  32. private var instancesLock: os_unfair_lock = .init()
  33. // MARK: - Initializers
  34. required init(app: FirebaseApp) {
  35. self.app = app
  36. }
  37. // MARK: - Library conformance
  38. static func componentsToRegister() -> [Component] {
  39. let appCheckInterop = Dependency(with: AppCheckInterop.self, isRequired: false)
  40. let authInterop = Dependency(with: AuthInterop.self, isRequired: false)
  41. return [Component(StorageProvider.self,
  42. instantiationTiming: .lazy,
  43. dependencies: [
  44. appCheckInterop,
  45. authInterop,
  46. ]) { container, isCacheable in
  47. guard let app = container.app else { return nil }
  48. isCacheable.pointee = true
  49. return self.init(app: app)
  50. }]
  51. }
  52. // MARK: - StorageProvider conformance
  53. func storage(for bucket: String) -> Storage {
  54. os_unfair_lock_lock(&instancesLock)
  55. // Unlock before the function returns.
  56. defer { os_unfair_lock_unlock(&instancesLock) }
  57. if let instance = instances[bucket] {
  58. return instance
  59. }
  60. let newInstance = FirebaseStorage.Storage(app: app, bucket: bucket)
  61. instances[bucket] = newInstance
  62. return newInstance
  63. }
  64. }