UploadRequest.swift 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. //
  2. // UploadRequest.swift
  3. //
  4. // Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
  26. public final class UploadRequest: DataRequest, @unchecked Sendable {
  27. /// Type describing the origin of the upload, whether `Data`, file, or stream.
  28. public enum Uploadable: @unchecked Sendable { // Must be @unchecked Sendable due to InputStream.
  29. /// Upload from the provided `Data` value.
  30. case data(Data)
  31. /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
  32. /// automatically removed once uploaded.
  33. case file(URL, shouldRemove: Bool)
  34. /// Upload from the provided `InputStream`.
  35. case stream(InputStream)
  36. }
  37. // MARK: Initial State
  38. /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
  39. public let upload: any UploadableConvertible
  40. /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
  41. /// to disk.
  42. public let fileManager: FileManager
  43. // MARK: Mutable State
  44. /// `Uploadable` value used by the instance.
  45. public var uploadable: Uploadable?
  46. /// Creates an `UploadRequest` using the provided parameters.
  47. ///
  48. /// - Parameters:
  49. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  50. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
  51. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  52. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  53. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  54. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  55. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  56. /// - shouldAutomaticallyResume: Whether the instance should resume after the first response handler is added.
  57. /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart
  58. /// form encoded payloads written to disk.
  59. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  60. init(id: UUID = UUID(),
  61. convertible: any UploadConvertible,
  62. underlyingQueue: DispatchQueue,
  63. serializationQueue: DispatchQueue,
  64. eventMonitor: (any EventMonitor)?,
  65. interceptor: (any RequestInterceptor)?,
  66. shouldAutomaticallyResume: Bool?,
  67. fileManager: FileManager,
  68. delegate: any RequestDelegate) {
  69. upload = convertible
  70. self.fileManager = fileManager
  71. super.init(id: id,
  72. convertible: convertible,
  73. underlyingQueue: underlyingQueue,
  74. serializationQueue: serializationQueue,
  75. eventMonitor: eventMonitor,
  76. interceptor: interceptor,
  77. shouldAutomaticallyResume: shouldAutomaticallyResume,
  78. delegate: delegate)
  79. }
  80. /// Called when the `Uploadable` value has been created from the `UploadConvertible`.
  81. ///
  82. /// - Parameter uploadable: The `Uploadable` that was created.
  83. func didCreateUploadable(_ uploadable: Uploadable) {
  84. self.uploadable = uploadable
  85. eventMonitor?.request(self, didCreateUploadable: uploadable)
  86. }
  87. /// Called when the `Uploadable` value could not be created.
  88. ///
  89. /// - Parameter error: `AFError` produced by the failure.
  90. func didFailToCreateUploadable(with error: AFError) {
  91. self.error = error
  92. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  93. retryOrFinish(error: error)
  94. }
  95. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  96. guard let uploadable else {
  97. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  98. }
  99. switch uploadable {
  100. case let .data(data): return session.uploadTask(with: request, from: data)
  101. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  102. case .stream: return session.uploadTask(withStreamedRequest: request)
  103. }
  104. }
  105. override func reset() {
  106. // Uploadable must be recreated on every retry.
  107. uploadable = nil
  108. super.reset()
  109. }
  110. /// Produces the `InputStream` from `uploadable`, if it can.
  111. ///
  112. /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
  113. ///
  114. /// - Returns: The `InputStream`.
  115. func inputStream() -> InputStream {
  116. guard let uploadable else {
  117. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  118. }
  119. guard case let .stream(stream) = uploadable else {
  120. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  121. }
  122. eventMonitor?.request(self, didProvideInputStream: stream)
  123. return stream
  124. }
  125. override public func cleanup() {
  126. defer { super.cleanup() }
  127. guard
  128. let uploadable,
  129. case let .file(url, shouldRemove) = uploadable,
  130. shouldRemove
  131. else { return }
  132. try? fileManager.removeItem(at: url)
  133. }
  134. }
  135. /// A type that can produce an `UploadRequest.Uploadable` value.
  136. public protocol UploadableConvertible: Sendable {
  137. /// Produces an `UploadRequest.Uploadable` value from the instance.
  138. ///
  139. /// - Returns: The `UploadRequest.Uploadable`.
  140. /// - Throws: Any `Error` produced during creation.
  141. func createUploadable() throws -> UploadRequest.Uploadable
  142. }
  143. extension UploadRequest.Uploadable: UploadableConvertible {
  144. public func createUploadable() throws -> UploadRequest.Uploadable {
  145. self
  146. }
  147. }
  148. /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
  149. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}