Răsfoiți Sursa

Add Request Compression (#3701)

### Goals :soccer:
For large request bodies it may be beneficial to compress the outgoing
data. This PR adds support for the `deflate` compression encoding as a
`RequestInterceptor`.

### Implementation Details :construction:
`DeflateRequestCompressor` manually compresses body data using
`NSData.compressed` while adding the header bytes and adler32 checksum
from zlib manually.

### Testing Details :mag:
Firewalk has been updated to support compressed requests, so tests have
been added to exercise that. Additionally, simple unit tests have been
added to confirm our deflate and adler32 implementations are correct.
Jon Shier 2 ani în urmă
părinte
comite
f3f0f13615

+ 19 - 0
.github/workflows/ci.yml

@@ -280,3 +280,22 @@ jobs:
           set SDKROOT=%SystemDrive%\Library\Developer\Platforms\Windows.platform\Developer\SDKs\Windows.sdk
           %SystemDrive%\Library\Developer\Toolchains\unknown-Asserts-development.xctoolchain\usr\bin\swift-build.exe --build-tests -c debug -Xlinker /INCREMENTAL:NO -v
           if not exist .build\x86_64-unknown-windows-msvc\debug\Alamofire.swiftmodule exit 1
+  CodeQL:
+    name: Analyze with CodeQL
+    runs-on: macOS-12
+    env:
+      DEVELOPER_DIR: "/Applications/Xcode_14.2.app/Contents/Developer"
+      CODEQL_ENABLE_EXPERIMENTAL_FEATURES_SWIFT: true
+    timeout-minutes: 10
+    steps:
+      - uses: actions/checkout@v3
+      - name: Initialize CodeQL
+        uses: github/codeql-action/init@v2
+        with:
+          languages: swift
+      - name: Build macOS
+        run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project "Alamofire.xcodeproj" -scheme "Alamofire macOS" -destination "platform=macOS" clean build | xcpretty
+      - name: Perform CodeQL Analysis
+        uses: github/codeql-action/analyze@v2
+        with:
+          category: "/language:swift"

+ 18 - 1
Alamofire.xcodeproj/project.pbxproj

@@ -212,6 +212,10 @@
 		315A4C57241EF28B00D57C7A /* StringEncoding+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 315A4C55241EF28B00D57C7A /* StringEncoding+Alamofire.swift */; };
 		315A4C58241EF28B00D57C7A /* StringEncoding+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 315A4C55241EF28B00D57C7A /* StringEncoding+Alamofire.swift */; };
 		315A4C59241EF28B00D57C7A /* StringEncoding+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 315A4C55241EF28B00D57C7A /* StringEncoding+Alamofire.swift */; };
+		3165407329AEBC0400C9BE08 /* RequestCompression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3165407229AEBC0400C9BE08 /* RequestCompression.swift */; };
+		3165407429AEBC0400C9BE08 /* RequestCompression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3165407229AEBC0400C9BE08 /* RequestCompression.swift */; };
+		3165407529AEBC0400C9BE08 /* RequestCompression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3165407229AEBC0400C9BE08 /* RequestCompression.swift */; };
+		3165407629AEBC0400C9BE08 /* RequestCompression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3165407229AEBC0400C9BE08 /* RequestCompression.swift */; };
 		31727418218BAEC90039FFCC /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31727417218BAEC90039FFCC /* HTTPMethod.swift */; };
 		31727419218BAEC90039FFCC /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31727417218BAEC90039FFCC /* HTTPMethod.swift */; };
 		3172741A218BAEC90039FFCC /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31727417218BAEC90039FFCC /* HTTPMethod.swift */; };
@@ -510,6 +514,7 @@
 		31501E872196962A005829F2 /* ParameterEncoderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParameterEncoderTests.swift; sourceTree = "<group>"; };
 		31577E0A2676E72D001C7532 /* FUNDING.yml */ = {isa = PBXFileReference; lastKnownFileType = text.yaml; path = FUNDING.yml; sourceTree = "<group>"; };
 		315A4C55241EF28B00D57C7A /* StringEncoding+Alamofire.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "StringEncoding+Alamofire.swift"; sourceTree = "<group>"; };
+		3165407229AEBC0400C9BE08 /* RequestCompression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestCompression.swift; sourceTree = "<group>"; };
 		31727417218BAEC90039FFCC /* HTTPMethod.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPMethod.swift; sourceTree = "<group>"; };
 		3172741C218BB1790039FFCC /* ParameterEncoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParameterEncoder.swift; sourceTree = "<group>"; };
 		31727421218BB9A50039FFCC /* TestHelpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestHelpers.swift; sourceTree = "<group>"; };
@@ -907,6 +912,7 @@
 				311B198F20B0D3B40036823B /* MultipartUpload.swift */,
 				4C3D00531C66A63000D1F709 /* NetworkReachabilityManager.swift */,
 				4C0CB645220CA8A400604EDC /* RedirectHandler.swift */,
+				3165407229AEBC0400C9BE08 /* RequestCompression.swift */,
 				4C256A0521EEB69000AD5D87 /* RequestInterceptor.swift */,
 				4CDE2C451AF89FF300BABAE5 /* ResponseSerialization.swift */,
 				4C256A1921F1449C00AD5D87 /* RetryPolicy.swift */,
@@ -1194,8 +1200,9 @@
 		F8111E2A19A95C8B0040E7D1 /* Project object */ = {
 			isa = PBXProject;
 			attributes = {
+				BuildIndependentTargetsInParallel = YES;
 				LastSwiftUpdateCheck = 1250;
-				LastUpgradeCheck = 1400;
+				LastUpgradeCheck = 1430;
 				ORGANIZATIONNAME = Alamofire;
 				TargetAttributes = {
 					31293064263E17D600473CEA = {
@@ -1511,6 +1518,7 @@
 				4C0CB643220CA89400604EDC /* URLRequest+Alamofire.swift in Sources */,
 				4CF6270F1BA7CBF60011A099 /* ResponseSerialization.swift in Sources */,
 				4C256A0821EEB69000AD5D87 /* RequestInterceptor.swift in Sources */,
+				3165407529AEBC0400C9BE08 /* RequestCompression.swift in Sources */,
 				4C43669D1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift in Sources */,
 				315A4C58241EF28B00D57C7A /* StringEncoding+Alamofire.swift in Sources */,
 				4C3D00561C66A63000D1F709 /* NetworkReachabilityManager.swift in Sources */,
@@ -1599,6 +1607,7 @@
 				31FB2F8822C828D8007FD6D5 /* URLEncodedFormEncoder.swift in Sources */,
 				4C0CB642220CA89400604EDC /* URLRequest+Alamofire.swift in Sources */,
 				4C23EB441B327C5B0090E0BC /* MultipartFormData.swift in Sources */,
+				3165407429AEBC0400C9BE08 /* RequestCompression.swift in Sources */,
 				4C256A0721EEB69000AD5D87 /* RequestInterceptor.swift in Sources */,
 				315A4C57241EF28B00D57C7A /* StringEncoding+Alamofire.swift in Sources */,
 				4C43669C1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift in Sources */,
@@ -1642,6 +1651,7 @@
 				31FB2F8A22C828D8007FD6D5 /* URLEncodedFormEncoder.swift in Sources */,
 				4C0CB644220CA89400604EDC /* URLRequest+Alamofire.swift in Sources */,
 				4C256A0921EEB69000AD5D87 /* RequestInterceptor.swift in Sources */,
+				3165407629AEBC0400C9BE08 /* RequestCompression.swift in Sources */,
 				4C43669E1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift in Sources */,
 				315A4C59241EF28B00D57C7A /* StringEncoding+Alamofire.swift in Sources */,
 				E4202FD41B667AA100C997FB /* Alamofire.swift in Sources */,
@@ -1685,6 +1695,7 @@
 				31FB2F8722C828D8007FD6D5 /* URLEncodedFormEncoder.swift in Sources */,
 				4C0CB641220CA89400604EDC /* URLRequest+Alamofire.swift in Sources */,
 				4C811F8D1B51856D00E0F59A /* ServerTrustEvaluation.swift in Sources */,
+				3165407329AEBC0400C9BE08 /* RequestCompression.swift in Sources */,
 				4C256A0621EEB69000AD5D87 /* RequestInterceptor.swift in Sources */,
 				315A4C56241EF28B00D57C7A /* StringEncoding+Alamofire.swift in Sources */,
 				4C43669B1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift in Sources */,
@@ -1884,6 +1895,7 @@
 		4CF627001BA7CB3E0011A099 /* Debug */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
+				CODE_SIGN_IDENTITY = "";
 				DYLIB_COMPATIBILITY_VERSION = 1;
 				DYLIB_CURRENT_VERSION = 1;
 				DYLIB_INSTALL_NAME_BASE = "@rpath";
@@ -1901,6 +1913,7 @@
 		4CF627011BA7CB3E0011A099 /* Release */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
+				CODE_SIGN_IDENTITY = "";
 				DYLIB_COMPATIBILITY_VERSION = 1;
 				DYLIB_CURRENT_VERSION = 1;
 				DYLIB_INSTALL_NAME_BASE = "@rpath";
@@ -1988,6 +2001,7 @@
 		E4202FDE1B667AA100C997FB /* Debug */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
+				CODE_SIGN_IDENTITY = "";
 				DYLIB_COMPATIBILITY_VERSION = 1;
 				DYLIB_CURRENT_VERSION = 1;
 				DYLIB_INSTALL_NAME_BASE = "@rpath";
@@ -2006,6 +2020,7 @@
 		E4202FDF1B667AA100C997FB /* Release */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
+				CODE_SIGN_IDENTITY = "";
 				DYLIB_COMPATIBILITY_VERSION = 1;
 				DYLIB_CURRENT_VERSION = 1;
 				DYLIB_INSTALL_NAME_BASE = "@rpath";
@@ -2164,6 +2179,7 @@
 		F8111E4719A95C8B0040E7D1 /* Debug */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
+				CODE_SIGN_IDENTITY = "";
 				DYLIB_COMPATIBILITY_VERSION = 1;
 				DYLIB_CURRENT_VERSION = 1;
 				DYLIB_INSTALL_NAME_BASE = "@rpath";
@@ -2182,6 +2198,7 @@
 		F8111E4819A95C8B0040E7D1 /* Release */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
+				CODE_SIGN_IDENTITY = "";
 				DYLIB_COMPATIBILITY_VERSION = 1;
 				DYLIB_CURRENT_VERSION = 1;
 				DYLIB_INSTALL_NAME_BASE = "@rpath";

+ 1 - 1
Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire iOS.xcscheme

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <Scheme
-   LastUpgradeVersion = "1400"
+   LastUpgradeVersion = "1430"
    version = "1.7">
    <BuildAction
       parallelizeBuildables = "YES"

+ 1 - 1
Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire macOS.xcscheme

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <Scheme
-   LastUpgradeVersion = "1400"
+   LastUpgradeVersion = "1430"
    version = "1.7">
    <BuildAction
       parallelizeBuildables = "YES"

+ 1 - 1
Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire tvOS.xcscheme

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <Scheme
-   LastUpgradeVersion = "1400"
+   LastUpgradeVersion = "1430"
    version = "1.7">
    <BuildAction
       parallelizeBuildables = "YES"

+ 1 - 1
Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire watchOS.xcscheme

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <Scheme
-   LastUpgradeVersion = "1400"
+   LastUpgradeVersion = "1430"
    version = "1.7">
    <BuildAction
       parallelizeBuildables = "YES"

Fișier diff suprimat deoarece este prea mare
+ 252 - 139
Documentation/AdvancedUsage.md


+ 1 - 1
Example/iOS Example.xcodeproj/xcshareddata/xcschemes/iOS Example.xcscheme

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <Scheme
-   LastUpgradeVersion = "1400"
+   LastUpgradeVersion = "1430"
    version = "1.3">
    <BuildAction
       parallelizeBuildables = "YES"

+ 11 - 2
Source/HTTPHeaders.swift

@@ -300,10 +300,19 @@ extension HTTPHeader {
         HTTPHeader(name: "Content-Disposition", value: value)
     }
 
+    /// Returns a `Content-Encoding` header.
+    ///
+    /// - Parameter value: The `Content-Encoding`.
+    ///
+    /// - Returns:         The header.
+    public static func contentEncoding(_ value: String) -> HTTPHeader {
+        HTTPHeader(name: "Content-Encoding", value: value)
+    }
+
     /// Returns a `Content-Type` header.
     ///
-    /// All Alamofire `ParameterEncoding`s and `ParameterEncoder`s set the `Content-Type` of the request, so it may not be necessary to manually
-    /// set this value.
+    /// All Alamofire `ParameterEncoding`s and `ParameterEncoder`s set the `Content-Type` of the request, so it may not
+    /// be necessary to manually set this value.
     ///
     /// - Parameter value: The `Content-Type` value.
     ///

+ 153 - 0
Source/RequestCompression.swift

@@ -0,0 +1,153 @@
+//
+//  RequestCompression.swift
+//
+//  Copyright (c) 2023 Alamofire Software Foundation (http://alamofire.org/)
+//
+//  Permission is hereby granted, free of charge, to any person obtaining a copy
+//  of this software and associated documentation files (the "Software"), to deal
+//  in the Software without restriction, including without limitation the rights
+//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+//  copies of the Software, and to permit persons to whom the Software is
+//  furnished to do so, subject to the following conditions:
+//
+//  The above copyright notice and this permission notice shall be included in
+//  all copies or substantial portions of the Software.
+//
+//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+//  THE SOFTWARE.
+//
+
+#if canImport(zlib)
+import Foundation
+import zlib
+
+/// `RequestAdapter` which compresses outgoing `URLRequest` bodies using the `deflate` `Content-Encoding` and adds the
+/// appropriate header.
+///
+/// - Note: Most requests to most APIs are small and so would only be slowed down by applying this adapter. Measure the
+///         size of your request bodies and the performance impact of using this adapter before use. Using this adapter
+///         with already compressed data, such as images, will, at best, have no effect. Additionally, body compression
+///         is a synchronous operation, so measuring the performance impact may be important to determine whether you
+///         want to use a dedicated `requestQueue` in your `Session` instance. Finally, not all servers support request
+///         compression, so test with all of your server configurations before deploying.
+@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
+public struct DeflateRequestCompressor: RequestInterceptor {
+    /// Type that determines the action taken when the `URLRequest` already has a `Content-Encoding` header.
+    public enum DuplicateHeaderBehavior {
+        /// Throws a `DuplicateHeaderError`. The default.
+        case error
+        /// Replaces the existing header value with `deflate`.
+        case replace
+        /// Silently skips compression when the header exists.
+        case skip
+    }
+
+    /// `Error` produced when the outgoing `URLRequest` already has a `Content-Encoding` header, when the instance has
+    /// been configured to produce an error.
+    public struct DuplicateHeaderError: Error {}
+
+    /// Behavior to use when the outgoing `URLRequest` already has a `Content-Encoding` header.
+    public let duplicateHeaderBehavior: DuplicateHeaderBehavior
+    /// Closure which determines whether the outgoing body data should be compressed.
+    public let shouldCompressBodyData: (_ bodyData: Data) -> Bool
+
+    /// Creates an instance with the provided parameters.
+    ///
+    /// - Parameters:
+    ///   - duplicateHeaderBehavior: `DuplicateHeaderBehavior` to use. `.error` by default.
+    ///   - shouldCompressBodyData:  Closure which determines whether the outgoing body data should be compressed. `true` by default.
+    public init(duplicateHeaderBehavior: DuplicateHeaderBehavior = .error,
+                shouldCompressBodyData: @escaping (_ bodyData: Data) -> Bool = { _ in true }) {
+        self.duplicateHeaderBehavior = duplicateHeaderBehavior
+        self.shouldCompressBodyData = shouldCompressBodyData
+    }
+
+    public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
+        // No need to compress unless we have body data. No support for compressing streams.
+        guard let bodyData = urlRequest.httpBody else {
+            completion(.success(urlRequest))
+            return
+        }
+
+        guard shouldCompressBodyData(bodyData) else {
+            completion(.success(urlRequest))
+            return
+        }
+
+        if urlRequest.headers.value(for: "Content-Encoding") != nil {
+            switch duplicateHeaderBehavior {
+            case .error:
+                completion(.failure(DuplicateHeaderError()))
+                return
+            case .replace:
+                // Header will be replaced once the body data is compressed.
+                break
+            case .skip:
+                completion(.success(urlRequest))
+                return
+            }
+        }
+
+        var compressedRequest = urlRequest
+
+        do {
+            compressedRequest.httpBody = try deflate(bodyData)
+            compressedRequest.headers.update(.contentEncoding("deflate"))
+            completion(.success(compressedRequest))
+        } catch {
+            completion(.failure(error))
+        }
+    }
+
+    func deflate(_ data: Data) throws -> Data {
+        var output = Data([0x78, 0x5E]) // Header
+        try output.append((data as NSData).compressed(using: .zlib) as Data)
+        var checksum = adler32Checksum(of: data).bigEndian
+        output.append(Data(bytes: &checksum, count: MemoryLayout<UInt32>.size))
+
+        return output
+    }
+
+    func adler32Checksum(of data: Data) -> UInt32 {
+        #if swift(>=5.6)
+        data.withUnsafeBytes { buffer in
+            UInt32(adler32(1, buffer.baseAddress, UInt32(buffer.count)))
+        }
+        #else
+        data.withUnsafeBytes { buffer in
+            let buffer = buffer.bindMemory(to: UInt8.self)
+            return UInt32(adler32(1, buffer.baseAddress, UInt32(buffer.count)))
+        }
+        #endif
+    }
+}
+
+@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
+extension RequestInterceptor where Self == DeflateRequestCompressor {
+    /// Create a `DeflateRequestCompressor` with default `duplicateHeaderBehavior` and `shouldCompressBodyData` values.
+    public static var deflateCompressor: DeflateRequestCompressor {
+        DeflateRequestCompressor()
+    }
+
+    /// Creates a `DeflateRequestCompressor` with the provided `DuplicateHeaderBehavior` and `shouldCompressBodyData`
+    /// closure.
+    ///
+    /// - Parameters:
+    ///   - duplicateHeaderBehavior: `DuplicateHeaderBehavior` to use.
+    ///   - shouldCompressBodyData: Closure which determines whether the outgoing body data should be compressed. `true` by default.
+    ///
+    /// - Returns: The `DeflateRequestCompressor`.
+    public static func deflateCompressor(
+        duplicateHeaderBehavior: DeflateRequestCompressor.DuplicateHeaderBehavior = .error,
+        shouldCompressBodyData: @escaping (_ bodyData: Data) -> Bool = { _ in true }
+    ) -> DeflateRequestCompressor {
+        DeflateRequestCompressor(duplicateHeaderBehavior: duplicateHeaderBehavior,
+                                 shouldCompressBodyData: shouldCompressBodyData)
+    }
+}
+#endif

+ 27 - 0
Tests/InternalRequestTests.swift

@@ -47,4 +47,31 @@ final class InternalRequestTests: BaseTestCase {
         // Then
         XCTAssertNotNil(response)
     }
+
+    #if canImport(zlib)
+    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
+    func testThatRequestCompressorProperlyCalculatesAdler32() {
+        // Given
+        let compressor = DeflateRequestCompressor()
+
+        // When
+        let checksum = compressor.adler32Checksum(of: Data("Wikipedia".utf8))
+
+        // Then
+        // From https://en.wikipedia.org/wiki/Adler-32
+        XCTAssertEqual(checksum, 300_286_872)
+    }
+
+    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
+    func testThatRequestCompressorDeflatesDataCorrectly() throws {
+        // Given
+        let compressor = DeflateRequestCompressor()
+
+        // When
+        let compressedData = try compressor.deflate(Data([0]))
+
+        // Then
+        XCTAssertEqual(compressedData, Data([0x78, 0x5E, 0x63, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01]))
+    }
+    #endif
 }

+ 122 - 0
Tests/RequestTests.swift

@@ -1237,3 +1237,125 @@ final class RequestInvalidURLTestCase: BaseTestCase {
         XCTAssertNil(response?.response)
     }
 }
+
+#if canImport(zlib) && swift(>=5.6) // Same condition as `DeflateRequestCompressor`.
+@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
+final class RequestCompressionTests: BaseTestCase {
+    func testThatRequestsCanBeCompressed() async {
+        // Given
+        let url = Endpoint.method(.post).url
+        let parameters = TestParameters(property: "compressed")
+
+        // When
+        let result = await AF.request(url,
+                                      method: .post,
+                                      parameters: parameters,
+                                      encoder: .json,
+                                      interceptor: .deflateCompressor)
+            .serializingDecodable(TestResponse.self)
+            .result
+
+        // Then
+        XCTAssertTrue(result.isSuccess)
+    }
+
+    func testThatDeflateCompressorThrowsErrorByDefaultWhenRequestAlreadyHasHeader() async {
+        // Given
+        let url = Endpoint.method(.post).url
+        let parameters = TestParameters(property: "compressed")
+
+        // When
+        let result = await AF.request(url,
+                                      method: .post,
+                                      parameters: parameters,
+                                      encoder: .json,
+                                      headers: [.contentEncoding("value")],
+                                      interceptor: .deflateCompressor)
+            .serializingDecodable(TestResponse.self)
+            .result
+
+        // Then
+        XCTAssertFalse(result.isSuccess)
+        XCTAssertNotNil(result.failure?.underlyingError as? DeflateRequestCompressor.DuplicateHeaderError)
+    }
+
+    func testThatDeflateCompressorThrowsErrorWhenConfigured() async {
+        // Given
+        let url = Endpoint.method(.post).url
+        let parameters = TestParameters(property: "compressed")
+
+        // When
+        let result = await AF.request(url,
+                                      method: .post,
+                                      parameters: parameters,
+                                      encoder: .json,
+                                      headers: [.contentEncoding("value")],
+                                      interceptor: .deflateCompressor(duplicateHeaderBehavior: .error))
+            .serializingDecodable(TestResponse.self)
+            .result
+
+        // Then
+        XCTAssertFalse(result.isSuccess)
+        XCTAssertNotNil(result.failure?.underlyingError as? DeflateRequestCompressor.DuplicateHeaderError)
+    }
+
+    func testThatDeflateCompressorReplacesHeaderWhenConfigured() async {
+        // Given
+        let url = Endpoint.method(.post).url
+        let parameters = TestParameters(property: "compressed")
+
+        // When
+        let result = await AF.request(url,
+                                      method: .post,
+                                      parameters: parameters,
+                                      encoder: .json,
+                                      headers: [.contentEncoding("value")],
+                                      interceptor: .deflateCompressor(duplicateHeaderBehavior: .replace))
+            .serializingDecodable(TestResponse.self)
+            .result
+
+        // Then
+        XCTAssertTrue(result.isSuccess)
+    }
+
+    func testThatDeflateCompressorSkipsCompressionWhenConfigured() async {
+        // Given
+        let url = Endpoint.method(.post).url
+        let parameters = TestParameters(property: "compressed")
+
+        // When
+        let result = await AF.request(url,
+                                      method: .post,
+                                      parameters: parameters,
+                                      encoder: .json,
+                                      headers: [.contentEncoding("gzip")],
+                                      interceptor: .deflateCompressor(duplicateHeaderBehavior: .skip))
+            .serializingDecodable(TestResponse.self)
+            .result
+
+        // Then
+        // Request fails as the server expects gzip compression.
+        XCTAssertFalse(result.isSuccess)
+    }
+
+    func testThatDeflateCompressorDoesNotCompressDataWhenClosureReturnsFalse() async {
+        // Given
+        let url = Endpoint.method(.post).url
+        let parameters = TestParameters(property: "compressed")
+
+        // When
+        let result = await AF.request(url,
+                                      method: .post,
+                                      parameters: parameters,
+                                      encoder: .json,
+                                      interceptor: .deflateCompressor { _ in false })
+            .serializingDecodable(TestResponse.self)
+            .result
+
+        // Then
+        XCTAssertTrue(result.isSuccess)
+        // With no compression, request headers reflected from server should have no Content-Encoding.
+        XCTAssertNil(result.success?.headers["Content-Encoding"])
+    }
+}
+#endif

+ 1 - 1
watchOS Example/watchOS Example.xcodeproj/xcshareddata/xcschemes/watchOS Example WatchKit App.xcscheme

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <Scheme
-   LastUpgradeVersion = "1400"
+   LastUpgradeVersion = "1430"
    version = "1.3">
    <BuildAction
       parallelizeBuildables = "YES"

Unele fișiere nu au fost afișate deoarece prea multe fișiere au fost modificate în acest diff