Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ Second example show same request but this time audio file is just some raw unkno
static func send(audioFile: Data) throws -> Request<SendAudioResponse> {
var multipart = MultipartFormData()

try multipart.add(data: audioFile, name: "your_name", mimeType: "audioFile_mimeType")
multipart.add(data: audioFile, name: "your_name", mimeType: "audioFile_mimeType")

return .post("v1/sendAudio", body: multipart)
}
Expand All @@ -142,7 +142,7 @@ extension Request {
var multipart = MultipartFormData()

try multipart.add(url: audio, name: "define_your_name")
try multipart.add(data: image, name: "your_name", mimeType: "image_mimeType")
multipart.add(data: image, name: "your_name", mimeType: "image_mimeType")

return .post("v1/send", body: multipart)
}
Expand Down
56 changes: 11 additions & 45 deletions Sources/SimpleHTTP/MultipartForm/MultipartFormData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,51 +46,29 @@ enum Boundary: Sendable {
}
}

struct BodyPart {
let headers: [Header]
let length: Int
let stream: @Sendable () throws -> InputStream

var hasInitialBoundary = false
var hasFinalBoundary = false

private init(headers: [Header], stream: @Sendable @escaping () throws -> InputStream, length: Int) {
self.headers = headers
self.length = length
self.stream = stream
}

init(headers: [Header], url: URL, length: Int) {
let stream: @Sendable () throws -> InputStream = {
guard let stream = InputStream(url: url) else {
throw MultipartFormData.Error.inputStreamCreationFailed(url)
}
return stream
}
self.init(headers: headers, stream: stream, length: length)
struct BodyPart: Sendable {
enum Content: Sendable {
case data(Data)
case file(URL)
}

init(headers: [Header], data: Data) {
self.init(headers: headers, stream: { InputStream(data: data) }, length: data.count)
}
let headers: [Header]
let content: Content
}

/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body.
/// We encode the data directly in memory. It's very efficient, but can lead to memory issues if the dataset is too large (eg: a Video)
///
/// `Warning`: A Second approch to encode bigger dataset will be addes later
public struct MultipartFormData {
public struct MultipartFormData: Sendable {
let boundary: String
let fileManager: FileManager
var bodyParts = [BodyPart]()

/// Creates an instance
///
/// - Parameters:
/// - fileManager: `FileManager` to use for file operation, if needed
/// - boundary: `String` used to separate body parts
public init(fileManager: FileManager = .default, boundary: String? = nil) {
self.fileManager = fileManager
public init(boundary: String? = nil) {
self.boundary = boundary ?? Boundary.random()
}

Expand Down Expand Up @@ -136,12 +114,9 @@ public struct MultipartFormData {
public mutating func add(url: URL, name: String, fileName: String, mimeType: String) throws {
let headers = defineBodyPartHeader(name: name, fileName: fileName, mimeType: mimeType)

guard let fileSize = try fileManager.attributesOfItem(atPath: url.path)[.size] as? NSNumber else {
throw MultipartFormData.Error.fileSizeNotAvailable(url)
}
_ = try url.checkResourceIsReachable()

let length = fileSize.intValue
bodyParts.append(BodyPart(headers: headers, url: url, length: length))
bodyParts.append(BodyPart(headers: headers, content: .file(url)))
}

/// Creates a body part from the data and add it to the instance.
Expand All @@ -161,7 +136,7 @@ public struct MultipartFormData {
public mutating func add(data: Data, name: String, fileName: String? = nil, mimeType: String? = nil) {
let headers = defineBodyPartHeader(name: name, fileName: fileName, mimeType: mimeType)

bodyParts.append(BodyPart(headers: headers, data: data))
bodyParts.append(BodyPart(headers: headers, content: .data(data)))
}

private func defineBodyPartHeader(name: String, fileName: String?, mimeType: String?) -> [Header] {
Expand Down Expand Up @@ -206,12 +181,3 @@ public struct MultipartFormData {
}

}

public extension MultipartFormData {

enum Error: Swift.Error {
case fileSizeNotAvailable(URL)
case inputStreamCreationFailed(URL)
}

}
86 changes: 14 additions & 72 deletions Sources/SimpleHTTP/MultipartForm/MultipartFormDataEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,102 +2,44 @@ import Foundation

struct MultipartFormDataEncoder {
let boundary: String
private var bodyParts: [BodyPart]

//
// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
// information, please refer to the following article:
// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
//
private let streamBufferSize = 1024
private let bodyParts: [BodyPart]

public init(body: MultipartFormData) {
self.boundary = body.boundary
self.bodyParts = body.bodyParts
}

mutating func encode() throws -> Data {
var encoded = Data()

if var first = bodyParts.first {
first.hasInitialBoundary = true
bodyParts[0] = first
}

if var last = bodyParts.last {
last.hasFinalBoundary = true
bodyParts[bodyParts.count - 1] = last
}

for bodyPart in bodyParts {
encoded.append(try encodeBodyPart(bodyPart))
}

return encoded
}

private func encodeBodyPart(_ bodyPart: BodyPart) throws -> Data {
func encode() throws -> Data {
var encoded = Data()

if bodyPart.hasInitialBoundary {
encoded.append(Boundary.data(for: .initial, boundary: boundary))
} else {
encoded.append(Boundary.data(for: .encapsulated, boundary: boundary))
for (index, bodyPart) in bodyParts.enumerated() {
encoded.append(Boundary.data(for: index == 0 ? .initial : .encapsulated, boundary: boundary))
encoded.append(encodeBodyPart(headers: bodyPart.headers))
encoded.append(try encodeBodyPart(content: bodyPart.content))
}

encoded.append(try encodeBodyPart(headers: bodyPart.headers))
encoded.append(try encodeBodyPart(stream: bodyPart.stream(), length: bodyPart.length))

if bodyPart.hasFinalBoundary {
if !bodyParts.isEmpty {
encoded.append(Boundary.data(for: .final, boundary: boundary))
}

return encoded
}

private func encodeBodyPart(headers: [Header]) throws -> Data {
private func encodeBodyPart(headers: [Header]) -> Data {
let headerText = headers.map { "\($0.name.key): \($0.value)\(EncodingCharacters.crlf)" }
.joined()
+ EncodingCharacters.crlf

return Data(headerText.utf8)
}

private func encodeBodyPart(stream: InputStream, length: Int) throws -> Data {
var encoded = Data()

stream.open()
defer { stream.close() }

while stream.hasBytesAvailable {
var buffer = [UInt8](repeating: 0, count: streamBufferSize)
let bytesRead = stream.read(&buffer, maxLength: streamBufferSize)

if let error = stream.streamError {
throw BodyPart.Error.inputStreamReadFailed(error.localizedDescription)
}

if bytesRead > 0 {
encoded.append(buffer, count: bytesRead)
} else {
break
}
private func encodeBodyPart(content: BodyPart.Content) throws -> Data {
switch content {
case .data(let data):
return data
case .file(let url):
return try Data(contentsOf: url)
}

guard encoded.count == length else {
throw BodyPart.Error.unexpectedInputStreamLength(expected: length, bytesRead: encoded.count)
}

return encoded
}

}

extension BodyPart {

enum Error: Swift.Error {
case inputStreamReadFailed(String)
case unexpectedInputStreamLength(expected: Int, bytesRead: Int)
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import FoundationNetworking

extension URLRequest {
public mutating func multipartBody(_ body: MultipartFormData) throws {
var multipartEncode = MultipartFormDataEncoder(body: body)
let multipartEncode = MultipartFormDataEncoder(body: body)

httpBody = try multipartEncode.encode()

Expand Down
4 changes: 2 additions & 2 deletions Sources/SimpleHTTP/Query/QueryParam.swift
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import Foundation

/// Protocol allowing to use a type as a query parameter
public protocol QueryParam {
public protocol QueryParam: Sendable {
/// the parameter value
var queryValue: QueryValue? { get }
}

/// Query parameter value
public enum QueryValue: Equatable {
public enum QueryValue: Equatable, Sendable {
case single(String)
case collection([String])
}
Expand Down
14 changes: 7 additions & 7 deletions Sources/SimpleHTTP/Request/Request.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ public enum Method: String, Sendable {
case delete
}

public enum Body {
case encodable(Encodable)
public enum Body: Sendable {
case encodable(any Encodable & Sendable)
case multipart(MultipartFormData)
}

/// A HTTP request safely typed for an `Output` response
///
/// Highly inspired by https://swiftwithmajid.com/2021/02/10/building-type-safe-networking-in-swift/
public struct Request<Output> {
public struct Request<Output>: Sendable {
/// request relative path
public let path: Path
public let method: Method
Expand All @@ -31,7 +31,7 @@ public struct Request<Output> {
}

/// Creates a request suitable for a HTTP POST with a `Encodable` body
public static func post(_ path: Path, body: Encodable?, query: [String: QueryParam] = [:])
public static func post(_ path: Path, body: (any Encodable & Sendable)?, query: [String: QueryParam] = [:])
-> Self {
self.init(path: path, method: .post, query: query, body: body.map(Body.encodable))
}
Expand All @@ -44,7 +44,7 @@ public struct Request<Output> {
}

/// Creates a request suitable for a HTTP PUT with a `Encodable` body
public static func put(_ path: Path, body: Encodable, query: [String: QueryParam] = [:])
public static func put(_ path: Path, body: any Encodable & Sendable, query: [String: QueryParam] = [:])
-> Self {
self.init(path: path, method: .put, query: query, body: .encodable(body))
}
Expand All @@ -61,7 +61,7 @@ public struct Request<Output> {
}

/// Creates a request suitable for a HTTP PATCH with a `Encodable` body
public static func patch(_ path: Path, body: Encodable, query: [String: QueryParam] = [:])
public static func patch(_ path: Path, body: any Encodable & Sendable, query: [String: QueryParam] = [:])
-> Self {
self.init(path: path, method: .patch, query: query, body: .encodable(body))
}
Expand All @@ -78,7 +78,7 @@ public struct Request<Output> {
}

/// Creates a DELETE request with a Encodable body
public static func delete(_ path: Path, body: Encodable, query: [String: QueryParam] = [:]) -> Self {
public static func delete(_ path: Path, body: any Encodable & Sendable, query: [String: QueryParam] = [:]) -> Self {
self.init(path: path, method: .delete, query: query, body: .encodable(body))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class MultipartFormDataEncoderTests: XCTestCase {
let expectedData = Data(expectedString.utf8)

// When
var encoder = MultipartFormDataEncoder(body: multipart)
let encoder = MultipartFormDataEncoder(body: multipart)
let encodedData = try encoder.encode()

// Then
Expand Down Expand Up @@ -55,7 +55,7 @@ class MultipartFormDataEncoderTests: XCTestCase {
)
let expectedData = Data(expectedString.utf8)

var encoder = MultipartFormDataEncoder(body: multipart)
let encoder = MultipartFormDataEncoder(body: multipart)
let encodedData = try encoder.encode()

XCTAssertEqual(encodedData, expectedData)
Expand All @@ -80,7 +80,7 @@ class MultipartFormDataEncoderTests: XCTestCase {
expectedData.append(try Data(contentsOf: url))
expectedData.append(Boundary.data(for: .final, boundary: boundary))

var encoder = MultipartFormDataEncoder(body: multipart)
let encoder = MultipartFormDataEncoder(body: multipart)
let encodedData = try encoder.encode()

XCTAssertEqual(encodedData, expectedData)
Expand Down Expand Up @@ -116,7 +116,7 @@ class MultipartFormDataEncoderTests: XCTestCase {
expectedData.append(try Data(contentsOf: url2))
expectedData.append(Boundary.data(for: .final, boundary: boundary))

var encoder = MultipartFormDataEncoder(body: multipart)
let encoder = MultipartFormDataEncoder(body: multipart)
let encodedData = try encoder.encode()

XCTAssertEqual(encodedData, expectedData)
Expand Down Expand Up @@ -152,7 +152,7 @@ class MultipartFormDataEncoderTests: XCTestCase {
expectedData.append(try Data(contentsOf: url))
expectedData.append(Boundary.data(for: .final, boundary: boundary))

var encoder = MultipartFormDataEncoder(body: multipart)
let encoder = MultipartFormDataEncoder(body: multipart)
let encodedData = try encoder.encode()

XCTAssertEqual(encodedData, expectedData)
Expand All @@ -166,10 +166,23 @@ class MultipartFormDataEncoderTests: XCTestCase {
let name1 = "data"
multipart.add(data: Data(data.utf8), name: name1)

var encoder = MultipartFormDataEncoder(body: multipart)
let encoder = MultipartFormDataEncoder(body: multipart)
_ = try encoder.encode()

XCTAssertNoThrow(_ = try encoder.encode())
}

func test_encode_fileRemovedAfterAdd_throw() throws {
var multipart = MultipartFormData(boundary: "boundary")
let url = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).txt")
try Data("content".utf8).write(to: url)

try multipart.add(url: url, name: "file")
try FileManager.default.removeItem(at: url)

let encoder = MultipartFormDataEncoder(body: multipart)

XCTAssertThrowsError(try encoder.encode())
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,12 @@ class MultipartFormDataTest: XCTestCase {
XCTAssertEqual(bodyPart.headers, expectedHeaders)
}

func test_addURL_fileNotFound_throw() {
var multipart = MultipartFormData(boundary: "boundary")
let url = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).png")

XCTAssertThrowsError(try multipart.add(url: url, name: "missing"))
XCTAssertTrue(multipart.bodyParts.isEmpty)
}

}
Loading