Motivation:
It's not always possible to initialize `HTTPHeaders` with all the headers one needs to set. In such case, the underlying array will be expanded as and when needed upon headers being appended. `Array` provides the means to reserve capacity to optimize such use case. This PR exposes this functionality in `HTTPHeaders`.
Modifications:
Expose method `reserveCapacity(_ minimumCapacity: Int)` and computed variable `capacity: Int` in `HTTPHeaders` and added some tests.
Result:
Developers will be able to control the capacity of the underlying headers array as such:
```
var headers = HTTPHeaders()
headers.reserveCapacity(5)
```
Co-authored-by: Ludovic Dewailly <ldewailly@apple.com>
Motivation:
`subscript(name:)` and `first(name:)` incorrectly referred users to
`getCanonicalForm` for a maximally decomposed list of header fields.
This no longer exists.
Modifications:
Point users to `subscript(canonicalForm:)`.
Result:
More accurate documenation.
Motivation:
When initializing an `HTTPMethod` with a `String` we currently switch over all expected values to pick an explicit value, only to overwrite our found explicit value with a catchall `RAW(value: String)`. This doesn’t make a ton of sense. This went unnoticed because we use the conditional conformance on `RawRepresentable` to be `Equatable`. But `switch`es don’t use the `Equatable` protocol to match enums. The issue is visible there.
Modifications:
Added a testcase with a switch that fails, if the `.RAW(value: String)` value is used for `”GET”`. Removed the final overwrite in HTTPMethod(rawValue: String). Therefore the test passes.
Result:
We can initialize the HTTPMethod with a String and get an explicit value.
Motivation:
We incorrectly asserted that HEAD and DELETE may not have request
bodies, but they can, it's just unlikely.
Modifications:
Change the categorisation of HEAD and DELETE.
Result:
Better behaviour in unusual cases.
Motivation:
In some cases you only expect (or care about) a single value for a
header. However, getting this value without allocating an array or
traversing the whole array requres using first(where:) provided by
Sequence. This is not very ergonomic as it requires users to do the
case-insensitive comparison and then exctact the value from the
HTTPHeaders. Additionally, users cannot use NIO's case insensitive
ASCII comparison.
Modifications:
- Provide a first(name:) method on HTTPHeaders which returns the value
from the first header whose name is a case insentive match of the
subscript parameter.
Result:
It's easier to get the first value from HTTPHeaders matching a given
name.
Motivation:
I ran across a case in a test where `HTTPResponseStatus(statusCode: 418)`
unexpectedly returned a `.custom` response status.
Modifications:
- Add a missing `case` for creating a status from `418`
- Shuffled some of cases around so that they are correctly listed in the
correct 2xx, 3xx, 4xx etc. sections
Result:
- `HTTPResponseStatus(statusCode: 418)` now returns `.imATeapot`
* Allow adding a sequence of headers to HTTPHeaders
Motivation:
When combining two collections of headers, adding each pair one-by-one
using add(name:value:) can cause multiple unnecessary reallocations of
the underlying array.
Modifications:
Provide two additional add methods to HTTPHeaders: one to add a sequence
of name/value pairs and another to add the headers from another
HTTPHeaders, both of which use `append(contentsOf:)` on the underlying
array to avoid additional reallocations.
Result:
Fewer reallocations when adding multiple headers.
* Fix incorrect documentation, make add<S: Sequence>(contentsOf:) @inlineable
* Reserve capacity and add sequentially instead of using append(contentsOf:)
* Add tests and missing @usableFromInline
Motivation:
Due to https://bugs.swift.org/browse/SR-10614, assigning an array containing a tuple type
to a variable that expects an array containing a different-but-compatible tuple type will cause
an allocation and copy of that array storage.
In some cases this is necessary, but we were doing it in the HTTPHeaders constructors, which meant
that the swift-nio-http2 code was hitting a hilariously over the top number of allocations.
Modifications:
- Change the internal storage type of HTTPHeaders to match the public constructor.
Result:
Fewer allocations when constructing HTTPHeaders
Motivation:
https://github.com/apple/swift-nio/issues/701
Modifications:
* Add `init(rawValue:)`
* Add `rawValue`
* Add tests in HTTPTypesTest.swift
Result:
Users no longer have to write their own conversion methods.
* make HTTPMethod.hasRequestBody internal
Motivation:
HTTPMethod.hasRequestBody was unnecessarily public.
Modifications:
make it internal
Result:
fixes#151
* Update public-api-changes-NIO1-to-NIO2.md
Motivation:
Before native UTF-8, the rawURI was a performance optimisation but
that's no longer true. Before this patch, we still had the rawURIs but
weren't using them at all.
Modifications:
remove any mention of rawURI
Result:
less clutter
Motivation:
The HTTP/1 headers were quite complicated, CoW-boxed and exposed their
guts (being a ByteBuffer). In Swift 5 this is no longer necessary
because of native UTF-8 Strings.
Modifications:
- make headers simply `[(String, String)]`
- remove `HTTPHeaderIndex`, `HTTPListHeaderIterator`, etc
Result:
- simpler and more performant code
Motivation:
Previously, ByteBuffers get* methods would get bytes from anywhere, even
if the bytes were not readable. That can lead to security issues in code
that doesn't expect this. NIO shouldn't contain such unsafe methods
without the word 'unsafe'.
Modifications:
Made all `get*` methods respect reader/writerIndex.
Result:
safer user code
Motivation:
Use better protocol instead of Sequence since it doesn't do much. Inspired by #676
Modifications:
Conform HTTPHeaders to RandomAccessCollection
Result:
HTTPHeaders will have RandomAccessCollection functionalities.
Motivation:
public/internal modifiers for `extension`s are confusing as a
`func foo` is public if within a `public extension`.
Modifications:
remove all `internal` (redundant) and `public` (dangerous) modifiers for
`extensions`.
Result:
- code easier to read
- code much easier to review in a small diff
### Motivation:
A convenience/shorthand for developers.
### Modifications:
Add conformance to ExpressibleByDictionaryLiteral along with implementation.
### Result:
The following is would then be legal in Vapor:
```
return HTTPResponse(status: .ok, headers: ["Content-Type": "text/html"],
body: "<table border=1><tr><td><i>Hello</i>, plugin!")
```
Motivation:
ByteBuffer methods like `set(string:)` never felt very Swift-like and
also didn't look the same as their counterparts like `getString(...)`.
Modifications:
- rename all `ByteBuffer.set/write(<type>:,...)` methods to
`ByteBuffer.set/write<Type>(...)`
- polyfill the old spellings in `_NIO1APIShims`
Result:
code more Swift-like
Motivation:
No code is the best code, let's have the compiler generate more
Equatable instances for us.
Modifications:
remove some hand-written Equatable conformances
Result:
less code, possibly fewer bugs
Motivation:
ByteBuffer has pretty good string writing APIs, but they're imperfect.
In particular, the methods in ByteBuffer-aux both return optional Int,
which is strange as they cannot fail. We also only have support for writing
strings in UTF-8.
Modifications:
- ByteBuffer.set(string:at:) and ByteBuffer.write(string:) now both
return `Int`, and their return value has been made discardable.
- NIOFoundationCompat has been expanded with two new methods for writing
strings to ByteBuffers in various encodings using Foundation's
encoding support: ByteBuffer.set(string:encoding:at:) and
ByteBuffer.write(string:encoding:).
- NIOFoundationCompat has also been expanded with a companion to the
already existing ByteBuffer.getString(at:length:encoding), namely
ByteBuffer.readString(length:encoding:).
- New error enum for reporting failures to encode.
Result:
Easier to work with strings in a wider variety of cases with
ByteBuffer
Resolves#253.
Motivation:
- `Int` is the currency type for integral things and we already sort of
changed the the type for ports but not everywhere.
- generic parameters that aren't just 'any type' shouldn't be just `T`
or `S` or something
Modifications:
- make more use of `Int`
- rename generic parameters to something more descriptive like `Bytes`
Result:
easier to read/write NIO code
Motivation:
NIO2 development starts now.
Modifications:
Made NIO Swift 5-only for everything else see docs/public-api-changes-NIO1-to-NIO2.md
Result:
NIO2 development can start.
Motivation:
Swift 5 complains on redundant modifiers. For example declaring a
`public func` inside of a `public extension` is now a warning. I don't
agree with this but I dislike warnings even more, so...
Modifications:
remove all redundant modifiers that the compiler now warns about such as
swift-nio/Sources/NIOPriorityQueue/PriorityQueue.swift:90:5: warning: 'public' modifier is redundant for property declared in a public extension
Result:
no warnings in Swift 5
* CONNECT method has no request body
### Motivation:
[rfc7231](https://tools.ietf.org/html/rfc7231#section-4.3.6) said:
> A payload within a `CONNECT` request message has no defined semantics;
sending a payload body on a `CONNECT` request might cause some existing
implementations to reject the request.
### Modifications:
Change `HTTPMethod.CONNECT.hasRequestBody` to returns `.no`.
### Result:
`HTTPRequestEncoder` does not generate chunked body for `CONNECT` method.
* Change `HTTPMethod.CONNECT.hasRequestBody` to returns `.unlikely`
Motivation:
It's generally good style to explain why something needs to be force
unwrapped/tried if not obvious.
Modifications:
Add explanations to a bunch of places.
Result:
Code easier to understand.
Motivation:
HTTP/2 adds an additional item to a header key/value pair:
its indexability. By default, headers can be inserted into
the HPACK header table index; sometimes this will be denied
(common case is 'content-length' header, which is rarely going
to be the same, and will just cause the table to purge more
often than is really necessary). Additionally, a header may be
marked as not only non-indexable but also non-rewritable by
proxies. HTTPHeaders provides nowhere to store this, so the
HPACKHeaders implementation referenced in
apple/swift-nio-http2#10 was created to add in that capability.
Now, given that we really want the HTTP version to be an
implementation detail, we want to keep the HPACK details hidden,
and would thus be using HTTPHeaders in client APIs. NIOHTTP2
already has a HTTP1-to-HTTP2 channel handler that translates
between the two. Thus it behooves us to have the means to copy
the actual key/value pairs between the two types without making
a round-trip from UTF-8 bytes to UTF-16 Strings. These changes
allow NIOHPACK or NIOHTTP2 to implement that round-trip internally.
Modifications:
- HTTPHeader and HTTPHeaderIndex types are now public.
- HTTPHeaders.buffer and HTTPHeaders.headers properties are now
public.
- A new static method, HTTPHeaders.createHeaderBlock(buffer:headers:)
was created to serve as a public means to create a HTTPHeaders from
a ByteBuffer from outside NIOHTTP1. @Lukasa suggested this should
be a static method rather than an initializer.
Result:
Nothing in NIOHTTP1 changes in operation. All public types have
documentation comments noting that they are only public for very
specific reasons, and are not intended for general use. Once this
is committed, NIOHPACK & NIOHTTP2 will be able to implement fast
round-trips between HTTPHeaders and HPACKHeaders.
match all values in HTTPHeaders.isKeepAlive(...)
HTTPHeaders.isKeepAlive(...) does only match the first value.
### Motivation:
Keep-alive and Close may be something on comma separated arrays
### Modifications:
- Made an extension function to `ByteBuffer` that could separate the strings at low level, without Swift string API, so that it could split the values
- Another extension functions that compares the comma separated array with a given array to tell the caller which exists and which no
- Added unit tests for them
- Used them in the HTTPHeader
### Result:
- Now, if a request is sent using Keep-alive or Close where it was in an array, it will be handled
- fixes#410
Motivation:
It's poor style to assume a certain piece of memory is bound to a
certain type across a whole program. That's because any piece of code
run in between might have rebound the memory and also it's hard to prove
that the binding assumption is actually correct. Therefore we should
restrain from using them.
Modifications:
remove more assumptions that memory is bound to a certain type.
Result:
better code
Motivation:
In certain cases it's useful to quiesce a channel instead of just
closing them immediately for example when receiving a signal.
This lays the groundwork by introducing the
`ChannelShouldQuiesceUserEvent` user event that when received can be
interpreted by a ChannelHandler in a protocol & application specific
way. Some protocols support tear down and that would be a good place to
initiate the tear down.
Modifications:
- introduce `ChannelShouldQuiesceUserEvent`
- handle `ChannelShouldQuiesceUserEvent` in the `AcceptHandler` with
closing the server socket
- handle `ChannelShouldQuiesceUserEvent` in the
`HTTPServerPipelineHandler` by only handling a already in-flight
request and then no longer accepting input
- added `CircularBuffer.removeAll` (& tests)
- added tests for `nextPowerOf2()`
Result:
- handlers can now support quiescing
Motivation:
We can check if a HTTP message is using keep alive without any allocation.
Modifications:
Directly act on the internal storage of HTTPHeaders to find out if keep alive is used or not.
Result:
Less allocations
Motivation:
To detect if keepalive is used we need to search the headers (if HTTP/1.1 is used). This may be expensive depending how many headers are present. http_parser itself detects already if keep alive should be used and so we can re-use this as long as the user did not modify the headers.
Modifications:
Reuse keepalive parsed by http_parser as long as the headers were not modified.
Result:
Less overhead as long as the headers are not modified.
Motivation:
HTTP{Request,Response}Head were too large even with a less than 3 word
ByteBuffer, this shrinks them box CoW boxing them. Should also reduce
ARC traffic when passing around a bunch.
Modifications:
CoW box HTTP{Request,Response}Head
Result:
fewer existential containers created, more performance
Refactored extension HTTPResponseStatus: Equatable, no change to the efficacy of the code.
Motivation:
Code readability is essential to a long-lasting maintainable project, the code this PR changes was "readable" however this PR will enhance the readability by removing excess lines of code.
Modifications:
Changed a long case statement, to a much shorter one.
Result:
There will be fewer lines of code, no change to the efficacy of product should occur. I am not familiar enough with the compiler to know if this will have a deleterious effect on performance I don't think it should be based on the way public var code: UInt { get } is implemented.
Motivation:
It's quite common that someone asks for the canonical form of a header
and we don't have any header values. There's no need to do string
comparisons then, we can just return an empty array.
Modifications:
Check if we're asking for a header that isn't present and if so, just
return the empty array.
Result:
Should be ever so slightly faster.
Motivation:
We recently changed the backing for the HTTP request and response
objects so that the URI string was no longer visible in
`request.description`. This patch fixes that and prints a format like
this:
HTTPRequestHead { method: GET, uri: "/", version: HTTP/1.1, headers: [("Host", "localhost:8888"), ("User-Agent", "curl/7.54.0"), ("Accept", "*/*")] }
and
HTTPResponseHead { version: HTTP/1.1, status: ok, headers: [("content-length", "12")] }
Modifications:
improved the HTTP request/response descriptions
Result:
debugging is easier
Motivation:
Immutable members of structs (properties defined with let) can never be changed
even if the struct itself is mutable (defined withh var). This makes it difficult
to build rich convenience APIs on top of these structs.
Modifications:
Changed all 'let' stored properties on HTTP{Request|Response}Head to 'var'.
Result:
HTTP{Request|Response}Head are easier to use now.
Motivation:
Its very likely that the response will be HTTP/1.1 or HTTP/1.0 so we can optimize for it by minimizing the buffer.write(...) calls.
Beside this we should also change the pattern of *.write(into: inout ByteBuffer) to extension on ByteBuffer itself.
Modificiations:
- Optimize for HTTP/1.0 and 1.1
- Use extensions on ByteBuffer
Result:
Faster and more clean code.
Motivation:
The Swift compiler seems to get very nervous when variadic inits
are used for types that have constructors with optional values. In
general we're not worried about breaking downstream consumers'
extensions when we update our code, but in this case we break the
ability to conform HTTPHeaders to ExpressibleByDictionaryLiteral,
which is a bit annoying. See https://bugs.swift.org/browse/SR-7415
for more details.
For 1.5.0 we should conform HTTPHeaders ourselves, but until that
time we can restore anyone who was conforming HTTPHeaders to
ExpressibleByDictionaryLiteral by restoring the old unary initializer
and delegating it to the new one. This presents an effect that is
equivalent to the old behaviour, but is new.
As a side note, in general it's a bad idea to conform types that you
do not own to standard library protocols. NIO reserves the right to
add conformances to our types in any Semver Minor release, so having
that conformance in your own code risks breakage without a Semver
Major patch bump. Please be aware.
Modifications:
Restored the unary initializer for HTTPHeaders.
Result:
Less breakage, more happiness.
Motivation:
We are currently parsing each header eagly which means we need to convert from bytes to String frequently. The reality is that most of the times the user is not really interested in all the headers and so it is kind of wasteful to do so.
Modification:
Rewrite our internal storage of HTTPHeaders to use a ByteBuffer as internal storage and so only parse headers on demand.
Result:
Less overhead for parsing headers.
Motivation:
HTTPHeaders had an unusual API for Swift: `getCanonicalForm(String)` which is
better suited as a subscript `[canonicalForm: String]`.
Also the implementation was needlessly inefficient.
Modifications:
- renamed HTTPHeaders.getCanonicalForm to HTTPHeaders[canonicalForm]
- improved efficiency by replacing anti-pattern
Array.map { ... }.reduce(+, []) by flatMap
Result:
more Swift in both meanings
Motivation:
header iterator that could be used to keep access to the iterator with
type erasure. However, it was accidentally made internal, and therefore
useless.
Modifications:
Made the shim public.
Result:
Users can actually upgrade their systems.
Motivation:
There are quite a few `switch`es that cover just two cases. Explicitly state this via an `if case` + `else` structure.
Modifications:
Changes something like:
switch a {
case .b:
return c
default:
return d
}
to
if case .b = a {
return c
} else {
return d
}
Result:
This should prevent misinterpretation and thus potential bugs in the future.
Motivation:
This changes two things:
- it removes the negation of non-used associated types (the removal of `(_)`).
- it prefers exhausting `switch`es over `default`ing.
This change does not impact bahavior; it is pure refactoring.
Modifications:
Omitting needless `(_)`'s and explicitly exhausting switches.
Result:
This change is pure refactoring.
Motivation:
In order to create a `HTTPResponseStatus` value from an status code code
currently one would have to make a custom HTTPResponseStatus. The
problem with that is that:
`HTTPResponseStatus.custom(code: 200, reasonPhrase: "") != HTTPResponseStatus.ok`
The logic of detecting whether a status code matches one of the known
cases already exists but only in an internal factory method.
Modifications:
- removed internal static `from` method from `HTTPResponseStatus`
- added public init with the functionality previously in `from`
- replace the single use of the `from` method with the new `init`
Result:
When initializing a `HTTPResponseStatus` value with a value of e.g.
`200` the init method will result in a `HTTPResponseStatus.ok`.