Storage.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. #if COCOAPODS
  19. import GTMSessionFetcher
  20. #else
  21. import GTMSessionFetcherCore
  22. #endif
  23. // Avoids exposing internal FirebaseCore APIs to Swift users.
  24. @_implementationOnly import FirebaseCoreExtension
  25. /// Firebase Storage is a service that supports uploading and downloading binary objects,
  26. /// such as images, videos, and other files to Google Cloud Storage. Instances of `Storage`
  27. /// are not thread-safe, but can be accessed from any thread.
  28. ///
  29. /// If you call `Storage.storage()`, the instance will initialize with the default `FirebaseApp`,
  30. /// `FirebaseApp.app()`, and the storage location will come from the provided
  31. /// `GoogleService-Info.plist`.
  32. ///
  33. /// If you provide a custom instance of `FirebaseApp`,
  34. /// the storage location will be specified via the `FirebaseOptions.storageBucket` property.
  35. @objc(FIRStorage) open class Storage: NSObject {
  36. // MARK: - Public APIs
  37. /// The default `Storage` instance.
  38. /// - Returns: An instance of `Storage`, configured with the default `FirebaseApp`.
  39. @objc(storage) open class func storage() -> Storage {
  40. return storage(app: FirebaseApp.app()!)
  41. }
  42. /// A method used to create `Storage` instances initialized with a custom storage bucket URL.
  43. ///
  44. /// Any `StorageReferences` generated from this instance of `Storage` will reference files
  45. /// and directories within the specified bucket.
  46. /// - Parameter url: The `gs://` URL to your Firebase Storage bucket.
  47. /// - Returns: A `Storage` instance, configured with the custom storage bucket.
  48. @objc(storageWithURL:) open class func storage(url: String) -> Storage {
  49. return storage(app: FirebaseApp.app()!, url: url)
  50. }
  51. /// Creates an instance of `Storage`, configured with a custom `FirebaseApp`. `StorageReference`s
  52. /// generated from a resulting instance will reference files in the Firebase project
  53. /// associated with custom `FirebaseApp`.
  54. /// - Parameter app: The custom `FirebaseApp` used for initialization.
  55. /// - Returns: A `Storage` instance, configured with the custom `FirebaseApp`.
  56. @objc(storageForApp:) open class func storage(app: FirebaseApp) -> Storage {
  57. return storage(app: app, bucket: Storage.bucket(for: app))
  58. }
  59. /// Creates an instance of `Storage`, configured with a custom `FirebaseApp` and a custom storage
  60. /// bucket URL.
  61. /// - Parameters:
  62. /// - app: The custom `FirebaseApp` used for initialization.
  63. /// - url: The `gs://` url to your Firebase Storage bucket.
  64. /// - Returns: The `Storage` instance, configured with the custom `FirebaseApp` and storage bucket
  65. /// URL.
  66. @objc(storageForApp:URL:)
  67. open class func storage(app: FirebaseApp, url: String) -> Storage {
  68. return storage(app: app, bucket: Storage.bucket(for: app, urlString: url))
  69. }
  70. private class func storage(app: FirebaseApp, bucket: String) -> Storage {
  71. os_unfair_lock_lock(&instancesLock)
  72. defer { os_unfair_lock_unlock(&instancesLock) }
  73. if let instance = instances[bucket] {
  74. return instance
  75. }
  76. let newInstance = FirebaseStorage.Storage(app: app, bucket: bucket)
  77. instances[bucket] = newInstance
  78. return newInstance
  79. }
  80. /// The `FirebaseApp` associated with this Storage instance.
  81. @objc public let app: FirebaseApp
  82. /// The maximum time in seconds to retry an upload if a failure occurs.
  83. /// Defaults to 10 minutes (600 seconds).
  84. @objc public var maxUploadRetryTime: TimeInterval {
  85. didSet {
  86. maxUploadRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxUploadRetryTime)
  87. }
  88. }
  89. /// The maximum time in seconds to retry a download if a failure occurs.
  90. /// Defaults to 10 minutes (600 seconds).
  91. @objc public var maxDownloadRetryTime: TimeInterval {
  92. didSet {
  93. maxDownloadRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxDownloadRetryTime)
  94. }
  95. }
  96. /// The maximum time in seconds to retry operations other than upload and download if a failure
  97. /// occurs.
  98. /// Defaults to 2 minutes (120 seconds).
  99. @objc public var maxOperationRetryTime: TimeInterval {
  100. didSet {
  101. maxOperationRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxOperationRetryTime)
  102. }
  103. }
  104. /// Specify the maximum upload chunk size. Values less than 256K (262144) will be rounded up to
  105. /// 256K. Values
  106. /// above 256K will be rounded down to the nearest 256K multiple. The default is no maximum.
  107. @objc public var uploadChunkSizeBytes: Int64 = .max
  108. /// A `DispatchQueue` that all developer callbacks are fired on. Defaults to the main queue.
  109. @objc public var callbackQueue: DispatchQueue {
  110. get {
  111. ensureConfigured()
  112. guard let queue = fetcherService?.callbackQueue else {
  113. fatalError("Internal error: Failed to initialize fetcherService callbackQueue")
  114. }
  115. return queue
  116. }
  117. set(newValue) {
  118. ensureConfigured()
  119. fetcherService?.callbackQueue = newValue
  120. }
  121. }
  122. /// Creates a `StorageReference` initialized at the root Firebase Storage location.
  123. /// - Returns: An instance of `StorageReference` referencing the root of the storage bucket.
  124. @objc open func reference() -> StorageReference {
  125. ensureConfigured()
  126. let path = StoragePath(with: storageBucket)
  127. return StorageReference(storage: self, path: path)
  128. }
  129. /// Creates a StorageReference given a `gs://`, `http://`, or `https://` URL pointing to a
  130. /// Firebase Storage location.
  131. ///
  132. /// For example, you can pass in an `https://` download URL retrieved from
  133. /// `StorageReference.downloadURL(completion:)` or the `gs://` URL from
  134. /// `StorageReference.description`.
  135. /// - Parameter url: A gs:// or https:// URL to initialize the reference with.
  136. /// - Returns: An instance of StorageReference at the given child path.
  137. /// - Throws: Throws a fatal error if `url` is not associated with the `FirebaseApp` used to
  138. /// initialize
  139. /// this Storage instance.
  140. @objc open func reference(forURL url: String) -> StorageReference {
  141. ensureConfigured()
  142. do {
  143. let path = try StoragePath.path(string: url)
  144. // If no default bucket exists (empty string), accept anything.
  145. if storageBucket == "" {
  146. return StorageReference(storage: self, path: path)
  147. }
  148. // If there exists a default bucket, throw if provided a different bucket.
  149. if path.bucket != storageBucket {
  150. fatalError("Provided bucket: `\(path.bucket)` does not match the Storage bucket of the current " +
  151. "instance: `\(storageBucket)`")
  152. }
  153. return StorageReference(storage: self, path: path)
  154. } catch let StoragePathError.storagePathError(message) {
  155. fatalError(message)
  156. } catch {
  157. fatalError("Internal error finding StoragePath: \(error)")
  158. }
  159. }
  160. /// Creates a StorageReference given a `gs://`, `http://`, or `https://` URL pointing to a
  161. /// Firebase Storage location.
  162. ///
  163. /// For example, you can pass in an `https://` download URL retrieved from
  164. /// `StorageReference.downloadURL(completion:)` or the `gs://` URL from
  165. /// `StorageReference.description`.
  166. /// - Parameter url: A gs:// or https:// URL to initialize the reference with.
  167. /// - Returns: An instance of StorageReference at the given child path.
  168. /// - Throws: Throws an Error if `url` is not associated with the `FirebaseApp` used to initialize
  169. /// this Storage instance.
  170. open func reference(for url: URL) throws -> StorageReference {
  171. ensureConfigured()
  172. var path: StoragePath
  173. do {
  174. path = try StoragePath.path(string: url.absoluteString)
  175. } catch let StoragePathError.storagePathError(message) {
  176. throw StorageError.pathError(message: message)
  177. } catch {
  178. throw StorageError.pathError(message: "Internal error finding StoragePath: \(error)")
  179. }
  180. // If no default bucket exists (empty string), accept anything.
  181. if storageBucket == "" {
  182. return StorageReference(storage: self, path: path)
  183. }
  184. // If there exists a default bucket, throw if provided a different bucket.
  185. if path.bucket != storageBucket {
  186. throw StorageError
  187. .bucketMismatch(message: "Provided bucket: `\(path.bucket)` does not match the Storage " +
  188. "bucket of the current instance: `\(storageBucket)`")
  189. }
  190. return StorageReference(storage: self, path: path)
  191. }
  192. /// Creates a `StorageReference` initialized at a location specified by the `path` parameter.
  193. /// - Parameter path: A relative path from the root of the storage bucket,
  194. /// for instance @"path/to/object".
  195. /// - Returns: An instance of `StorageReference` pointing to the given path.
  196. @objc(referenceWithPath:) open func reference(withPath path: String) -> StorageReference {
  197. return reference().child(path)
  198. }
  199. /// Configures the Storage SDK to use an emulated backend instead of the default remote backend.
  200. ///
  201. /// This method should be called before invoking any other methods on a new instance of `Storage`.
  202. /// - Parameter host: A string specifying the host.
  203. /// - Parameter port: The port specified as an `Int`.
  204. @objc open func useEmulator(withHost host: String, port: Int) {
  205. guard host.count > 0 else {
  206. fatalError("Invalid host argument: Cannot connect to empty host.")
  207. }
  208. guard port >= 0 else {
  209. fatalError("Invalid port argument: Port must be greater or equal to zero.")
  210. }
  211. guard fetcherService == nil else {
  212. fatalError("Cannot connect to emulator after Storage SDK initialization. " +
  213. "Call useEmulator(host:port:) before creating a Storage " +
  214. "reference or trying to load data.")
  215. }
  216. usesEmulator = true
  217. scheme = "http"
  218. self.host = host
  219. self.port = port
  220. }
  221. // MARK: - NSObject overrides
  222. @objc override open func copy() -> Any {
  223. let storage = Storage(app: app, bucket: storageBucket)
  224. storage.callbackQueue = callbackQueue
  225. return storage
  226. }
  227. @objc override open func isEqual(_ object: Any?) -> Bool {
  228. guard let ref = object as? Storage else {
  229. return false
  230. }
  231. return app == ref.app && storageBucket == ref.storageBucket
  232. }
  233. @objc override public var hash: Int {
  234. return app.hash ^ callbackQueue.hashValue
  235. }
  236. // MARK: - Internal and Private APIs
  237. private var fetcherService: GTMSessionFetcherService?
  238. var fetcherServiceForApp: GTMSessionFetcherService {
  239. guard let value = fetcherService else {
  240. fatalError("Internal error: fetcherServiceForApp not yet configured.")
  241. }
  242. return value
  243. }
  244. let dispatchQueue: DispatchQueue
  245. init(app: FirebaseApp, bucket: String) {
  246. self.app = app
  247. auth = ComponentType<AuthInterop>.instance(for: AuthInterop.self,
  248. in: app.container)
  249. appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self,
  250. in: app.container)
  251. storageBucket = bucket
  252. host = "firebasestorage.googleapis.com"
  253. scheme = "https"
  254. port = 443
  255. fetcherService = nil // Configured in `ensureConfigured()`
  256. // Must be a serial queue.
  257. dispatchQueue = DispatchQueue(label: "com.google.firebase.storage")
  258. maxDownloadRetryTime = 600.0
  259. maxDownloadRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxDownloadRetryTime)
  260. maxOperationRetryTime = 120.0
  261. maxOperationRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxOperationRetryTime)
  262. maxUploadRetryTime = 600.0
  263. maxUploadRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxUploadRetryTime)
  264. }
  265. /// Map of apps to a dictionary of buckets to GTMSessionFetcherService.
  266. private static let fetcherServiceLock = NSObject()
  267. private static var fetcherServiceMap: [String: [String: GTMSessionFetcherService]] = [:]
  268. private static var retryWhenOffline: GTMSessionFetcherRetryBlock = {
  269. (suggestedWillRetry: Bool,
  270. error: Error?,
  271. response: @escaping GTMSessionFetcherRetryResponse) in
  272. var shouldRetry = suggestedWillRetry
  273. // GTMSessionFetcher does not consider being offline a retryable error, but we do, so we
  274. // special-case it here.
  275. if !shouldRetry, error != nil {
  276. shouldRetry = (error as? NSError)?.code == URLError.notConnectedToInternet.rawValue
  277. }
  278. response(shouldRetry)
  279. }
  280. private static func initFetcherServiceForApp(_ app: FirebaseApp,
  281. _ bucket: String,
  282. _ auth: AuthInterop?,
  283. _ appCheck: AppCheckInterop?)
  284. -> GTMSessionFetcherService {
  285. objc_sync_enter(fetcherServiceLock)
  286. defer { objc_sync_exit(fetcherServiceLock) }
  287. var bucketMap = fetcherServiceMap[app.name]
  288. if bucketMap == nil {
  289. bucketMap = [:]
  290. fetcherServiceMap[app.name] = bucketMap
  291. }
  292. var fetcherService = bucketMap?[bucket]
  293. if fetcherService == nil {
  294. fetcherService = GTMSessionFetcherService()
  295. fetcherService?.isRetryEnabled = true
  296. fetcherService?.retryBlock = retryWhenOffline
  297. fetcherService?.allowLocalhostRequest = true
  298. let authorizer = StorageTokenAuthorizer(
  299. googleAppID: app.options.googleAppID,
  300. fetcherService: fetcherService!,
  301. authProvider: auth,
  302. appCheck: appCheck
  303. )
  304. fetcherService?.authorizer = authorizer
  305. bucketMap?[bucket] = fetcherService
  306. }
  307. return fetcherService!
  308. }
  309. private let auth: AuthInterop?
  310. private let appCheck: AppCheckInterop?
  311. private let storageBucket: String
  312. private var usesEmulator: Bool = false
  313. /// A map of active instances, grouped by app. Keys are FirebaseApp names and values are
  314. /// instances of Storage associated with the given app.
  315. private static var instances: [String: Storage] = [:]
  316. /// Lock to manage access to the instances array to avoid race conditions.
  317. private static var instancesLock: os_unfair_lock = .init()
  318. var host: String
  319. var scheme: String
  320. var port: Int
  321. var maxDownloadRetryInterval: TimeInterval
  322. var maxOperationRetryInterval: TimeInterval
  323. var maxUploadRetryInterval: TimeInterval
  324. /// Performs a crude translation of the user provided timeouts to the retry intervals that
  325. /// GTMSessionFetcher accepts. GTMSessionFetcher times out operations if the time between
  326. /// individual
  327. /// retry attempts exceed a certain threshold, while our API contract looks at the total observed
  328. /// time of the operation (i.e. the sum of all retries).
  329. /// @param retryTime A timeout that caps the sum of all retry attempts
  330. /// @return A timeout that caps the timeout of the last retry attempt
  331. static func computeRetryInterval(fromRetryTime retryTime: TimeInterval) -> TimeInterval {
  332. // GTMSessionFetcher's retry starts at 1 second and then doubles every time. We use this
  333. // information to compute a best-effort estimate of what to translate the user provided retry
  334. // time into.
  335. // Note that this is the same as 2 << (log2(retryTime) - 1), but deemed more readable.
  336. var lastInterval = 1.0
  337. var sumOfAllIntervals = 1.0
  338. while sumOfAllIntervals < retryTime {
  339. lastInterval *= 2
  340. sumOfAllIntervals += lastInterval
  341. }
  342. return lastInterval
  343. }
  344. /// Configures the storage instance. Freezes the host setting.
  345. private func ensureConfigured() {
  346. guard fetcherService == nil else {
  347. return
  348. }
  349. fetcherService = Storage.initFetcherServiceForApp(app, storageBucket, auth, appCheck)
  350. if usesEmulator {
  351. fetcherService?.allowLocalhostRequest = true
  352. fetcherService?.allowedInsecureSchemes = ["http"]
  353. }
  354. }
  355. private static func bucket(for app: FirebaseApp) -> String {
  356. guard let bucket = app.options.storageBucket else {
  357. fatalError("No default Storage bucket found. Did you configure Firebase Storage properly?")
  358. }
  359. if bucket == "" {
  360. return Storage.bucket(for: app, urlString: "")
  361. } else {
  362. return Storage.bucket(for: app, urlString: "gs://\(bucket)/")
  363. }
  364. }
  365. private static func bucket(for app: FirebaseApp, urlString: String) -> String {
  366. if urlString == "" {
  367. return ""
  368. } else {
  369. guard let path = try? StoragePath.path(GSURI: urlString),
  370. path.object == nil || path.object == "" else {
  371. fatalError("Internal Error: Storage bucket cannot be initialized with a path")
  372. }
  373. return path.bucket
  374. }
  375. }
  376. }