-
Notifications
You must be signed in to change notification settings - Fork 125
add response decompression support #86
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 16 commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
b0f15a6
add response decompression support
artemredkin 35fa5e0
Merge branch 'master' into support_response_decompression
artemredkin cc18c6d
Merge branch 'master' into support_response_decompression
artemredkin 88b674a
review fix: add decompression limit
artemredkin a51fe72
make limit configurable
artemredkin 6d96880
fix missing linux tests
artemredkin b577f79
fix formatting
artemredkin 18438fe
Merge branch 'master' into support_response_decompression
artemredkin 0782d81
formatting fix after merge
artemredkin 8e8c30d
add docker dependency for zlib
artemredkin 69ec369
review fixes: unset all pointers after use and make inflate methods i…
artemredkin 2891b7d
review fix: re-factor to not use a callback
artemredkin dbcfd44
review fixes: throw instead of precondition
artemredkin 5d59a66
fix formatting
artemredkin 2f1959f
review fix: flatten compression settings
artemredkin 8a95c2a
Merge branch 'master' into support_response_decompression
artemredkin 0e08fdb
Merge branch 'master' into support_response_decompression
artemredkin dd83963
use new decompression support from nio-extras
artemredkin f1848d2
Merge branch 'master' into support_response_decompression
artemredkin 495b27a
remove unused types
artemredkin 4c4ac19
rewrite backpressure test
artemredkin 807761e
rewrite backpressure test
artemredkin f2c8b09
Merge branch 'support_response_decompression' of github.com:swift-ser…
artemredkin 646d3c7
use real version
artemredkin 1ed16d4
remove commented code
artemredkin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,171 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the AsyncHTTPClient open source project | ||
// | ||
// Copyright (c) 2018-2019 Swift Server Working Group and the AsyncHTTPClient project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import CNIOExtrasZlib | ||
import NIO | ||
import NIOHTTP1 | ||
|
||
private enum CompressionAlgorithm: String { | ||
case gzip | ||
case deflate | ||
} | ||
|
||
extension z_stream { | ||
mutating func inflatePart(input: inout ByteBuffer, output: inout ByteBuffer) throws { | ||
try input.readWithUnsafeMutableReadableBytes { (dataPtr: UnsafeMutableRawBufferPointer) -> Int in | ||
let typedPtr = dataPtr.baseAddress!.assumingMemoryBound(to: UInt8.self) | ||
let typedDataPtr = UnsafeMutableBufferPointer(start: typedPtr, count: dataPtr.count) | ||
|
||
self.avail_in = UInt32(typedDataPtr.count) | ||
self.next_in = typedDataPtr.baseAddress! | ||
|
||
defer { | ||
self.avail_in = 0 | ||
self.next_in = nil | ||
self.avail_out = 0 | ||
self.next_out = nil | ||
} | ||
|
||
try self.inflatePart(to: &output) | ||
|
||
return typedDataPtr.count - Int(self.avail_in) | ||
} | ||
weissi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
private mutating func inflatePart(to buffer: inout ByteBuffer) throws { | ||
try buffer.writeWithUnsafeMutableBytes { outputPtr in | ||
let typedOutputPtr = UnsafeMutableBufferPointer(start: outputPtr.baseAddress!.assumingMemoryBound(to: UInt8.self), count: outputPtr.count) | ||
|
||
self.avail_out = UInt32(typedOutputPtr.count) | ||
self.next_out = typedOutputPtr.baseAddress! | ||
|
||
let rc = inflate(&self, Z_NO_FLUSH) | ||
guard rc == Z_OK || rc == Z_STREAM_END else { | ||
throw HTTPClientError.decompression(rc) | ||
} | ||
|
||
return typedOutputPtr.count - Int(self.avail_out) | ||
} | ||
} | ||
} | ||
|
||
final class HTTPResponseDecompressor: ChannelDuplexHandler, RemovableChannelHandler { | ||
weissi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
typealias InboundIn = HTTPClientResponsePart | ||
typealias InboundOut = HTTPClientResponsePart | ||
typealias OutboundIn = HTTPClientRequestPart | ||
typealias OutboundOut = HTTPClientRequestPart | ||
|
||
private enum State { | ||
case empty | ||
case compressed(CompressionAlgorithm, Int) | ||
} | ||
|
||
private let limit: HTTPClient.DecompressionLimit | ||
private var state = State.empty | ||
private var stream = z_stream() | ||
private var inflated = 0 | ||
|
||
init(limit: HTTPClient.DecompressionLimit) { | ||
self.limit = limit | ||
} | ||
|
||
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { | ||
let request = self.unwrapOutboundIn(data) | ||
switch request { | ||
case .head(var head): | ||
if head.headers.contains(name: "Accept-Encoding") { | ||
context.write(data, promise: promise) | ||
} else { | ||
head.headers.replaceOrAdd(name: "Accept-Encoding", value: "deflate, gzip") | ||
context.write(self.wrapOutboundOut(.head(head)), promise: promise) | ||
} | ||
default: | ||
context.write(data, promise: promise) | ||
} | ||
} | ||
|
||
public func channelRead(context: ChannelHandlerContext, data: NIOAny) { | ||
switch self.unwrapInboundIn(data) { | ||
case .head(let head): | ||
let algorithm: CompressionAlgorithm? | ||
let contentType = head.headers[canonicalForm: "Content-Encoding"].first?.lowercased() | ||
if contentType == "gzip" { | ||
algorithm = .gzip | ||
} else if contentType == "deflate" { | ||
algorithm = .deflate | ||
} else { | ||
algorithm = nil | ||
} | ||
|
||
let length = head.headers[canonicalForm: "Content-Length"].first.flatMap { Int($0) } | ||
|
||
if let algorithm = algorithm, let length = length { | ||
do { | ||
try self.initializeDecoder(encoding: algorithm, length: length) | ||
} catch { | ||
context.fireErrorCaught(error) | ||
} | ||
} | ||
|
||
context.fireChannelRead(data) | ||
case .body(var part): | ||
switch self.state { | ||
case .compressed(_, let originalLength): | ||
while part.readableBytes > 0 { | ||
do { | ||
var buffer = context.channel.allocator.buffer(capacity: 16384) | ||
try self.stream.inflatePart(input: &part, output: &buffer) | ||
self.inflated += buffer.readableBytes | ||
|
||
if self.limit.exceeded(compressed: originalLength, decompressed: self.inflated) { | ||
context.fireErrorCaught(HTTPClientError.decompressionLimit) | ||
return | ||
} | ||
|
||
context.fireChannelRead(self.wrapInboundOut(.body(buffer))) | ||
} catch { | ||
context.fireErrorCaught(error) | ||
return | ||
} | ||
} | ||
default: | ||
context.fireChannelRead(data) | ||
} | ||
case .end: | ||
deflateEnd(&self.stream) | ||
context.fireChannelRead(data) | ||
} | ||
} | ||
|
||
private func initializeDecoder(encoding: CompressionAlgorithm, length: Int) throws { | ||
self.state = .compressed(encoding, length) | ||
|
||
self.stream.zalloc = nil | ||
self.stream.zfree = nil | ||
self.stream.opaque = nil | ||
weissi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
let window: Int32 | ||
switch encoding { | ||
case .gzip: | ||
window = 15 + 16 | ||
default: | ||
window = 15 | ||
} | ||
|
||
let rc = CNIOExtrasZlib_inflateInit2(&self.stream, window) | ||
guard rc == Z_OK else { | ||
throw HTTPClientError.decompressionInitialization(rc) | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.