mirror of
https://github.com/apple/swift-nio
synced 2026-11-25 04:47:49 +00:00
Motivation:
NIO's dynamic pipeline comes with one performance caveat: If your type
isn't specialised in NIOAny (only types in the NIO module can be) and
it's over 3 words (24 bytes on 64-bit platforms), you'll suffer an
allocation for every time you box it in NIOAny. Very unfortunately, both
ByteBuffer and FileRegion were exactly 3 words wide which means that any
enum containing those would be wider than 3 words. Worse, both
HTTP{Request,Response}Head contained types that were wider than 3 words.
The best solution to this problem is to shrink ByteBuffer and FileRegion
to just under 3 words and that's exactly what this PR is doing. That is
slightly tricky as ByteBuffer was already bit packed fairly well
(reader/writer indices & slice begin/end were stored as a UInt32). The
trick we employ now is to store the slice beginning in a UInt24 and the
file region reader index in a UInt56. That saves one byte for both
ByteBuffer and FileRegion with very moderate tradeoffs: The reader index
in a file now needs to be within 64 PiB (peta bytes) and a byte buffer
slice beginning must start within 16 MiB (mega bytes). Note: The
reader/writer indices as well as slice ends are _not_ affected and can
still be within 4 GiB. Clearly no one would care about the restrictions
for FileRegions in the real world but we might hit the ByteBuffer slice
beginning limit in which case the slice would be copied out. But
given that slices are mostly used to slice off headers in network
protocols, 16 MiB should be _plenty_.
Norman was kind enough to measure the perf differences:
master (before this PR):
```
$ wrk -c 256 -d 10s -t 4 -s ~/Downloads/pipeline-many.lua -H "X-Host: SomeValue" -H "Host: swiftnio.io" -H "ThereAreEvenMoreHeaders: AndMoreValues" http://localhost:8888
Running 10s test @ http://localhost:8888
4 threads and 256 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 93.02ms 158.13ms 1.97s 93.07%
Req/Sec 112.79k 26.05k 258.75k 84.50%
4501098 requests in 10.04s, 214.63MB read
Socket errors: connect 0, read 111, write 0, timeout 89
Requests/sec: 448485.61
Transfer/sec: 21.39MB
```
after this PR:
```
$ wrk -c 256 -d 10s -t 4 -s ~/Downloads/pipeline-many.lua -H "X-Host: SomeValue" -H "Host: swiftnio.io" -H "ThereAreEvenMoreHeaders: AndMoreValues" http://localhost:8888
Running 10s test @ http://localhost:8888
4 threads and 256 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 107.53ms 206.56ms 1.99s 90.55%
Req/Sec 124.15k 26.56k 290.41k 89.25%
4952904 requests in 10.03s, 236.17MB read
Socket errors: connect 0, read 161, write 0, timeout 22
Requests/sec: 493852.65
Transfer/sec: 23.55MB
```
so we see a nice 10% improvement
Modifications:
- shrank ByteBuffer by 1 byte, making it 23 bytes in total
- shrank FileRegion by 1 byte, making it 23 bytes in total
- added @_inlineable to NIOAny where appropriate to not suffer boxed existentials in different places
- added tests for the new edge cases
Result:
- more speed
- fewer allocations
256 lines
9.9 KiB
Swift
256 lines
9.9 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the SwiftNIO open source project
|
|
//
|
|
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
|
|
// Licensed under Apache License v2.0
|
|
//
|
|
// See LICENSE.txt for license information
|
|
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
|
//
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
/// `NIOAny` is an opaque container for values of *any* type, similar to Swift's builtin `Any` type. Contrary to
|
|
/// `Any` the overhead of `NIOAny` depends on the the type of the wrapped value. Certain types that are important
|
|
/// for the performance of a SwiftNIO application like `ByteBuffer`, `FileRegion` and `AddressEnvelope<ByteBuffer>` can be expected
|
|
/// to be wrapped almost without overhead. All others will have similar performance as if they were passed as an `Any` as
|
|
/// `NIOAny` just like `Any` will contain them within an existential container.
|
|
///
|
|
/// The most important use-cases for `NIOAny` are values travelling through the `ChannelPipeline` whose type can't
|
|
/// be calculated at compile time. For example:
|
|
///
|
|
/// - the `channelRead` of any `ChannelInboundHandler`
|
|
/// - the `write` method of a `ChannelOutboundHandler`
|
|
///
|
|
/// The abstraction that delivers a `NIOAny` to user code must provide a mechanism to unwrap a `NIOAny` as a
|
|
/// certain type known at run-time. Canonical example:
|
|
///
|
|
/// class SandwichHandler: ChannelInboundHandler {
|
|
/// typealias InboundIn = Bacon /* we expected to be delivered `Bacon` ... */
|
|
/// typealias InboundOut = Sandwich /* ... and we will make and deliver a `Sandwich` from that */
|
|
///
|
|
/// func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
|
|
/// /* we receive the `Bacon` as a `NIOAny` as at compile-time the exact configuration of the channel
|
|
/// pipeline can't be computed. The pipeline can't be computed at compile time as it can change
|
|
/// dynamically at run-time. Yet, we assert that in any configuration the channel handler before
|
|
/// `SandwichHandler` does actually send us a stream of `Bacon`.
|
|
/// */
|
|
/// let bacon = self.unwrapInboundIn(data) /* `Bacon` or crash */
|
|
/// let sandwich = makeSandwich(bacon)
|
|
/// ctx.fireChannelRead(self.wrapInboundOut(sandwich)) /* as promised we deliver a wrapped `Sandwich` */
|
|
/// }
|
|
/// }
|
|
public struct NIOAny {
|
|
@_versioned
|
|
/* private but _versioned */ let _storage: _NIOAny
|
|
|
|
/// Wrap a value in a `NIOAny`. In most cases you should not create a `NIOAny` directly using this constructor.
|
|
/// The abstraction that accepts values of type `NIOAny` must also provide a mechanism to do the wrapping. An
|
|
/// example is a `ChannelInboundHandler` which provides `self.wrapInboundOut(aValueOfTypeInboundOut)`.
|
|
@_inlineable
|
|
public init<T>(_ value: T) {
|
|
self._storage = _NIOAny(value)
|
|
}
|
|
|
|
@_versioned
|
|
enum _NIOAny {
|
|
case ioData(IOData)
|
|
case bufferEnvelope(AddressedEnvelope<ByteBuffer>)
|
|
case other(Any)
|
|
|
|
@_inlineable @_versioned
|
|
init<T>(_ value: T) {
|
|
switch value {
|
|
case let value as ByteBuffer:
|
|
self = .ioData(.byteBuffer(value))
|
|
case let value as FileRegion:
|
|
self = .ioData(.fileRegion(value))
|
|
case let value as IOData:
|
|
self = .ioData(value)
|
|
case let value as AddressedEnvelope<ByteBuffer>:
|
|
self = .bufferEnvelope(value)
|
|
default:
|
|
assert(!(value is NIOAny))
|
|
self = .other(value)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Try unwrapping the wrapped message as `ByteBuffer`.
|
|
///
|
|
/// returns: The wrapped `ByteBuffer` or `nil` if the wrapped message is not a `ByteBuffer`.
|
|
@_versioned @_inlineable
|
|
func tryAsByteBuffer() -> ByteBuffer? {
|
|
if case .ioData(.byteBuffer(let bb)) = self._storage {
|
|
return bb
|
|
} else {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
/// Force unwrapping the wrapped message as `ByteBuffer`.
|
|
///
|
|
/// returns: The wrapped `ByteBuffer` or crash if the wrapped message is not a `ByteBuffer`.
|
|
@_versioned @_inlineable
|
|
func forceAsByteBuffer() -> ByteBuffer {
|
|
if let v = tryAsByteBuffer() {
|
|
return v
|
|
} else {
|
|
fatalError("tried to decode as type \(ByteBuffer.self) but found \(Mirror(reflecting: Mirror(reflecting: self._storage).children.first!.value).subjectType)")
|
|
}
|
|
}
|
|
|
|
/// Try unwrapping the wrapped message as `IOData`.
|
|
///
|
|
/// returns: The wrapped `IOData` or `nil` if the wrapped message is not a `IOData`.
|
|
@_versioned @_inlineable
|
|
func tryAsIOData() -> IOData? {
|
|
if case .ioData(let data) = self._storage {
|
|
return data
|
|
} else {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
/// Force unwrapping the wrapped message as `IOData`.
|
|
///
|
|
/// returns: The wrapped `IOData` or crash if the wrapped message is not a `IOData`.
|
|
@_versioned @_inlineable
|
|
func forceAsIOData() -> IOData {
|
|
if let v = tryAsIOData() {
|
|
return v
|
|
} else {
|
|
fatalError("tried to decode as type \(IOData.self) but found \(Mirror(reflecting: Mirror(reflecting: self._storage).children.first!.value).subjectType)")
|
|
}
|
|
}
|
|
|
|
/// Try unwrapping the wrapped message as `FileRegion`.
|
|
///
|
|
/// returns: The wrapped `FileRegion` or `nil` if the wrapped message is not a `FileRegion`.
|
|
@_versioned @_inlineable
|
|
func tryAsFileRegion() -> FileRegion? {
|
|
if case .ioData(.fileRegion(let f)) = self._storage {
|
|
return f
|
|
} else {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
/// Force unwrapping the wrapped message as `FileRegion`.
|
|
///
|
|
/// returns: The wrapped `FileRegion` or crash if the wrapped message is not a `FileRegion`.
|
|
@_versioned @_inlineable
|
|
func forceAsFileRegion() -> FileRegion {
|
|
if let v = tryAsFileRegion() {
|
|
return v
|
|
} else {
|
|
fatalError("tried to decode as type \(FileRegion.self) but found \(Mirror(reflecting: Mirror(reflecting: self._storage).children.first!.value).subjectType)")
|
|
}
|
|
}
|
|
|
|
/// Try unwrapping the wrapped message as `AddressedEnvelope<ByteBuffer>`.
|
|
///
|
|
/// returns: The wrapped `AddressedEnvelope<ByteBuffer>` or `nil` if the wrapped message is not an `AddressedEnvelope<ByteBuffer>`.
|
|
@_versioned @_inlineable
|
|
func tryAsByteEnvelope() -> AddressedEnvelope<ByteBuffer>? {
|
|
if case .bufferEnvelope(let e) = self._storage {
|
|
return e
|
|
} else {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
/// Force unwrapping the wrapped message as `AddressedEnvelope<ByteBuffer>`.
|
|
///
|
|
/// returns: The wrapped `AddressedEnvelope<ByteBuffer>` or crash if the wrapped message is not an `AddressedEnvelope<ByteBuffer>`.
|
|
@_versioned @_inlineable
|
|
func forceAsByteEnvelope() -> AddressedEnvelope<ByteBuffer> {
|
|
if let e = tryAsByteEnvelope() {
|
|
return e
|
|
} else {
|
|
fatalError("tried to decode as type \(AddressedEnvelope<ByteBuffer>.self) but found \(Mirror(reflecting: Mirror(reflecting: self._storage).children.first!.value).subjectType)")
|
|
}
|
|
}
|
|
|
|
/// Try unwrapping the wrapped message as `T`.
|
|
///
|
|
/// returns: The wrapped `T` or `nil` if the wrapped message is not a `T`.
|
|
@_versioned @_inlineable
|
|
func tryAsOther<T>(type: T.Type = T.self) -> T? {
|
|
if case .other(let any) = self._storage {
|
|
return any as? T
|
|
} else {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
/// Force unwrapping the wrapped message as `T`.
|
|
///
|
|
/// returns: The wrapped `T` or crash if the wrapped message is not a `T`.
|
|
@_versioned @_inlineable
|
|
func forceAsOther<T>(type: T.Type = T.self) -> T {
|
|
if let v = tryAsOther(type: type) {
|
|
return v
|
|
} else {
|
|
fatalError("tried to decode as type \(T.self) but found \(Mirror(reflecting: Mirror(reflecting: self._storage).children.first!.value).subjectType)")
|
|
}
|
|
}
|
|
|
|
/// Force unwrapping the wrapped message as `T`.
|
|
///
|
|
/// returns: The wrapped `T` or crash if the wrapped message is not a `T`.
|
|
@_versioned @_inlineable
|
|
func forceAs<T>(type: T.Type = T.self) -> T {
|
|
switch T.self {
|
|
case let t where t == ByteBuffer.self:
|
|
return self.forceAsByteBuffer() as! T
|
|
case let t where t == FileRegion.self:
|
|
return self.forceAsFileRegion() as! T
|
|
case let t where t == IOData.self:
|
|
return self.forceAsIOData() as! T
|
|
case let t where t == AddressedEnvelope<ByteBuffer>.self:
|
|
return self.forceAsByteEnvelope() as! T
|
|
default:
|
|
return self.forceAsOther(type: type)
|
|
}
|
|
}
|
|
|
|
/// Try unwrapping the wrapped message as `T`.
|
|
///
|
|
/// returns: The wrapped `T` or `nil` if the wrapped message is not a `T`.
|
|
@_versioned @_inlineable
|
|
func tryAs<T>(type: T.Type = T.self) -> T? {
|
|
switch T.self {
|
|
case let t where t == ByteBuffer.self:
|
|
return self.tryAsByteBuffer() as! T?
|
|
case let t where t == FileRegion.self:
|
|
return self.tryAsFileRegion() as! T?
|
|
case let t where t == IOData.self:
|
|
return self.tryAsIOData() as! T?
|
|
case let t where t == AddressedEnvelope<ByteBuffer>.self:
|
|
return self.tryAsByteEnvelope() as! T?
|
|
default:
|
|
return self.tryAsOther(type: type)
|
|
}
|
|
}
|
|
|
|
/// Unwrap the wrapped message.
|
|
///
|
|
/// returns: The wrapped message.
|
|
@_versioned @_inlineable
|
|
func asAny() -> Any {
|
|
switch self._storage {
|
|
case .ioData(.byteBuffer(let bb)):
|
|
return bb
|
|
case .ioData(.fileRegion(let f)):
|
|
return f
|
|
case .bufferEnvelope(let e):
|
|
return e
|
|
case .other(let o):
|
|
return o
|
|
}
|
|
}
|
|
}
|