Commit Graph
55 Commits
Author SHA1 Message Date
Johannes Weiss 0ac7e2266b remove extension public/internal modifiers (#822)
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
2019-02-14 13:25:30 +00:00
John Holdsworth f84b5b8087 Accept dictionary literals for HTTPHeaders (#824)
### 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!")
```
2019-02-14 09:03:31 +00:00
Johannes Weiss 1198931823 ByteBuffer: rename set(<type>:, ...) to set<Type>(...) (#812)
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
2019-02-12 11:11:45 +00:00
Johannes Weiss 95b290a51f use automatic Equatable conformances (#737)
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
2019-01-07 11:52:22 +00:00
Cory Benfield 15be5243ef Improve ByteBuffer String APIs (#696)
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.
2018-12-14 17:25:13 +00:00
Johannes Weiss f6b4acc133 changed port/HTTP version parts to Ints (#691)
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
2018-12-10 20:18:13 +00:00
Johannes Weiss 9b78557aff kick off NIO2 (#678)
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.
2018-12-07 21:15:34 +00:00
Jim Dovey bf0cd5295e Make the member variables of HTTPHeader and HTTPHeaderIndex visible to swift-nio-http2. (#654) 2018-11-15 10:46:27 +00:00
Johannes Weiss 26bee21674 fix Swift 5 warnings (mostly redundant modifiers (#642)
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
2018-11-01 09:50:55 +00:00
Norio Nomura 287d50c373 CONNECT method should not have request body (#637)
* 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`
2018-10-29 22:54:52 -07:00
Johannes Weiss 2e96e47016 explain some force tries/unwraps (#619)
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.
2018-09-19 15:51:03 +01:00
Jim Dovey 5279d73d25 Changes to HTTPHeaders API to integrate with HTTP/2 HPACKHeaders API (#525)
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.
2018-08-09 14:03:31 +01:00
fadi-botros 78729bd4ad Solving issue #410 (#414)
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
2018-08-07 18:49:30 +01:00
Johannes Weiss b0b8a15100 remove more memory binding assumptions (#541)
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
2018-08-02 12:14:01 +01:00
Johannes Weiß cea84765de Channel quiescing support (#399)
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
2018-05-18 10:48:18 +02:00
Norman Maurer e029edef2a Do not allocate String to check if HTTP message is keep alive (#402)
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
2018-05-16 11:42:22 +01:00
Norman Maurer a7614d9180 Reuse detected keepalive of http_parser as long as possible (#299)
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.
2018-05-14 18:04:52 +02:00
Ludovic Dewailly 6fcbfc9b75 Minor typo: becuase -> because - issue#393 (#394) 2018-05-08 08:42:59 +02:00
adamnemecek 776c3f42cb trimmed whitespace (#361)
Trimmed trailing whitespace.

Motivation:

Trimmed trailing whitespace.

Modifications:

Trimmed trailing whitespace.

Result:

Less trailing whitespace.
2018-04-27 08:33:32 +02:00
Johannes Weiß bc61e6a815 shrink HTTP{Request,Response}Head by CoW boxing them (#351)
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
2018-04-24 20:03:27 +02:00
Shaun Hubbard 163827b68e Refactor http response status equatable (#335)
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.
2018-04-24 15:36:36 +02:00
Johannes Weiß 7fe7ed6a89 canonical form for headers: fast path for 0 headers (#344)
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.
2018-04-23 06:58:28 +02:00
Johannes Weiß 56b540bfda better descriptions for HTTP{Response,Request}Head and HTTPVersion (#339)
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
2018-04-19 17:51:46 +01:00
Tanner 1360fc6995 Make all members of HTTP{Request|Response}Head mutable. (#324)
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.
2018-04-18 20:48:33 +02:00
Norman Maurer 575e7686cf Optimize for HTTP/1.1 and HTTP/1.0 responses (#300)
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.
2018-04-12 16:22:32 +02:00
Cory Benfield 241aed70c8 Restore unary initializer for HTTPHeaders (#301)
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.
2018-04-11 17:55:00 +01:00
Norman Maurer 48cef4a59b Implement lazy headers parsing (#291)
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.
2018-04-10 14:57:58 +02:00
Johannes Weiß 7e70bf5a87 rename HTTPHeaders.getCanonicalForm to subject and improve efficiency (#293)
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
2018-04-09 08:18:48 +01:00
Cory Benfield 28d4ddb33b Correctly expose backward-compat shim for header iterator. (#194)
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.
2018-03-19 23:53:20 +09:00
Bas Broek a095decbc2 Prefer if case over switch
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.
2018-03-19 14:45:32 +01:00
Bas Broek b180113d81 Improve switch readability
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.
2018-03-19 14:43:38 +01:00
Siemen Sikkema 37ee542874 Replace internal HTTPResponseStatus factory method with public init (#158)
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`.
2018-03-16 23:34:49 +09:00
Ben Cohen 41b8941402 Nest HTTPHeaderIterator inside HTTPHeader, un-erase makeIterator() return type. (#94)
Motivation:

Simplifies the code by putting the iterator in HTTPHeader's namespace.

Additionally, removing the type erasure should result in more performant code as `AnyIterator` is an optimization barrier. The type erasure did not appear to be adding an abstraction benefit.

Modifications:

Nested (internal) type `HTTPHeaderIterator` as `HTTPHeader.Iterator`
Explicit rather than inferred types for `Element` and `Iterator`.
Eliminated `AnyIterator` wrapper from `makeIterator()`
Added lower-priority version that still returns `AnyIterator` for source compatibility.

Result:

Unless caller was explicitly typing the iterator, should have no noticeable impact other than performance.
2018-03-12 18:44:43 +00:00
adamnemecek 0bbed6d72f * removed trailing whitespace (#52) 2018-03-02 15:40:52 +09:00
Johannes Weiß 73a805c7f6 minor stylistic improvements (#36)
Motivation:

Sometimes we deviated from the style the Swift stdlib sets out for no
reason.

Modifications:

Fixed some stylistic deviations.

Result:

Looks more Swift-like.
2018-02-26 15:52:49 +00:00
Johannes Weiss ca6b0ff28d replace Foundation whitespace trimming
Motivation:

For HTTP parsing, we used Foundation to trim whitespace which is not
needed.

Modifications:

Implemented whitespace trimming in Swift.

Result:

less Foundation
2018-02-19 12:55:29 +00:00
Johannes Weiss 7d5109a673 no auto headers for GET 2018-01-19 15:46:52 +00:00
Cory Benfield d61e084d3c Doc comments for NIOHTTP1 2017-11-30 16:07:41 +00:00
Johannes Weiß 202e1c37d7 port integration tests for HTTP server 2017-10-10 19:41:01 +01:00
Max (Swift) Moiseev 198d6b447b Explicit access modifiers on members in extensions 2017-11-18 04:40:26 -08:00
Johannes Weiß 79726e3b5f make HTTPDecoder typesafe (& refactoring) 2017-11-09 20:19:35 -08:00
Norman Maurer 976f4752df Add HTTPRequestEncoder / HTTPResponseDecoder implementation and tests 2017-11-02 13:50:46 +01:00
Norman Maurer 22a35b2bdb Add FileRegion support when using HTTP
Motivation:

Often people want to transfer large files over http which should be done using sendfile(...) for best performance.

Modifications:

- Add support for using FileRegion when sending body parts.
- Add tests

Result:

Be able to serve files without loading these into memory
2017-11-01 16:02:14 +01:00
Cory Benfield b2cbe766f0 Add support for HTTP Upgrade 2017-10-12 17:24:00 -07:00
Cory Benfield 0803012b7a Add support for retrieving headers in canonical form 2017-10-13 14:13:45 -07:00
Cory Benfield 6f17b320d5 Ensure no transfer-encoding when body is forbidden 2017-10-13 13:44:51 -07:00
Cory Benfield 1f52bac1f9 Add support for HTTP trailers 2017-10-04 13:49:03 +01:00
Johannes Weiss 1adb581f59 remove more Foundation imports 2017-10-10 16:25:43 +01:00
Cory Benfield 47ac46bbe3 Don't join Set-Cookie headers together 2017-10-09 10:37:13 -07:00
Johannes Weiss a73d46f218 HTTP/1.1 Chunked Encoding
* HTTP/1.1 Chunked Encoding

* fix MarkedCircularBuffer: if not marked do not try to move mark when removing first

* fix HTTPRequestDecoder: dispatch callouts after parsing is complete

* fix HTTPTest: feed pipeline the inbound data correctly
2017-09-25 15:33:02 +01:00