1113 Commits
Author SHA1 Message Date
Gwynne Raskind 1a9a543b6b Use self as the decoder when decoding a ByteBuffer (#1221)
Motivation:

JSONDecoder settings should be respected but were not.

Modifications:

This allows actually configuring the `JSONDecoder` instead of being stuck with the defaults.

Result:

Settings respected.
2019-11-06 16:08:31 +00:00
Cory Benfield fbe0c8a6b8 Add inlinability to ByteBuffer getters. (#1220)
Motivation:

In complex ByteBuffer parsing code a surprising amount of cost comes
from retain/release operations that are emitted by the compiler around
calls to readerIndex/writerIndex, readableBytes/writableBytes, and
ByteBufferSlice._lowerBound. These are all straightforward computed
properties based on usableFromInline operations, and so they can be made
inlinable.

Modifications:

Joannis' sample benchmark runtime is halved by eliminating
retains/releases.

Result:

Better, faster parsing code.
2019-11-04 19:31:26 +01:00
Christian Weinberger a0ab329d9d Add an option to ByteBuffer.clear() to specify minimumCapacity (#1204) 2019-10-31 21:19:24 +01:00
Heidi Puk Hermann bad79c584e Add function preconditionIsNotBlacklistedErrno (#1201)
Motivation:

Certain POSIX error numbers mean the NIO program is broken beyond repair and should crash. One such value is EBADF, which indicates that the file descriptor that NIO passed to the kernel is invalid for some reason. SR-11557 was discovered in part because debug builds of NIO crash for this.
I have promoted these checks from an assertion to a precondition adding a function preconditionIsNotBlacklistedErrno. Issue was raised in issue #1156

Modifications:

- Add function preconditionIsNotBlacklistedErrno to enable option to stop program execution in both debug mode and release mode if the errno is blacklisted.
- Update assertIsNotBlacklistedErrno to all preconditionIsNotBlacklistedErrno when the program is in debug mode
- Update wrapSyscallMayBlock, wrapSyscall, wrapErrorIsNullReturnCall, and close to call preconditionIsNotBlacklistedErrno in stead of assertIsNotBlacklistedErrno

Result:

Functions wrapSyscallMayBlock, wrapSyscall, wrapErrorIsNullReturnCall, and close will stop the execution in both debug mode and release mode if the errno is blacklisted.
2019-10-31 13:10:00 +01:00
Kamil Borzym 62fd8729d3 ByteBuffer.clear should reset the ByteBuffer._slice. (#1212)
Motivation:

ByteBuffer.clear doesn't reset the ByteBuffer._slice. Imagine having a byte buffer slice (ByteBuffer.getSlice). Calling ByteBuffer.clear on the slice will reset the reader and writer, but the ByteBuffer.capacity will return the old slice size, not the full storage capacity. After this change ByteBuffer.clear will also reset the ByteBuffer._slice to regain the whole ByteBuffer._storage.

Modifications:

Just setting the full storage slice in the ByteBuffer.clear method.

Result:

After that change ByteBuffer.clear will reset byte buffer slice to full capacity of underlying storage.
2019-10-31 09:05:51 +01:00
David Evans c83a4317f3 Fix typo (#1206) 2019-10-30 14:16:46 +01:00
Emil Marashliev 08b9d59573 Add an benchmark for WebSocket frame decoder (#1203)
Motivation:

It's important to know how websocket frame decoder perform.

Modification:

- Wrote simple benchmark for WebSocket frame decoding.

Result:

Better insight
2019-10-30 14:01:05 +01:00
Siemen SikkemaandGeorge Barnett 6ac4cd5a21 Make SocketAddress.port mutable (#1200)
* Make SocketAddress.port mutable

* Add linux test

* Precondition for setting non-nil port to unix socket

* Update Sources/NIO/SocketAddresses.swift

Co-Authored-By: George Barnett <gbrntt@gmail.com>
2019-10-30 12:53:06 +01:00
Johannes Weiss 22073b97be add socketpair to the POSIX wrappers (#1198)
Motivation:

For some reason, we never added `socketpair` to the POSIX wrappers but
it should be there.

Modifications:

Add socketpair to the POSIX wrappers and make use of it.

Result:

Nicer code base.
2019-10-30 08:01:42 +00:00
Lupurus 1ef89d378d added a public var to extract the IP address of the SocketAddress (#1194) 2019-10-29 22:28:28 +01:00
Jake 84169468fc Add ApplicationProtocolNegotiationHandler init that takes a closure that receives the Channel (#1196)
Motivation:

Currently ApplicationProtocolNegotiationHandler accepts a closure that takes only one argument, the ALPN result. This forces the user to capture the Channel in the closure so that it can be mutated.

Modifications:

Add a new init which takes a closure that has both the result and the Channel as parameters. Modify the original init to call the new init (wrapping the passed in closure.)

Result:

New APNL init available that takes a 2 parameter closure. Original APNL init will now be a convenience init.
2019-10-28 17:23:19 +00:00
Cory Benfield 82fb7126aa Make future builders and scheduled tasks inlinable (#1193)
Motivation:

While we successfully made all operations _on_ futures inlinable a while
ago, we managed to miss the functions that construct futures. These
remain public generic non-inlinable functions, and are called quite
heavily in NIO programs. Making them inlinable would unlock a bunch of
free performance.

Modifications:

- Make future and promise constructors inlinable.
- Make Scheduled inlinable.

Result:

A whole bunch of code will be faster.
2019-10-26 02:45:04 -07:00
Johannes Weiss 2985cc04ce DatagramChannel: Remove incorrect docs (#1191)
Motivation:

DatagramChannel claimed that it doesn't support broadcast or multicast
which isn't true anymore.

Modifications:

Remove the incorrect docs.

Result:

Better docs.
2019-10-25 02:47:05 -07:00
Johannes Weiss 3599912c8a make use of EventLoop.flatSubmit (#1179)
Motivation:

Since #1174 we've finally got EventLoop.flatSubmit and we should make
use of it to replace the silly `.wait().wait()` calls as well as the
similarly silly `.flatMap { $0 }`.

Modifications:

Use `flatSubmit` where appropriate.

Result:

Nicer codebase.
2019-10-24 11:05:01 -07:00
Jake 8066b0f581 Add option to reserve writable capacity to writeWithUnsafeMutableBytes (#1105) (#1175)
Motivation:

writeWithUnsafeMutableBytes cannot tolerate arbitrarily large writes because it is not possible to resize the buffer by the time body receives the buffer pointer. This change provides an option for the user to reserve writable capacity before the pointer is passed to body.

Modifications:

Added a backward compatible optional parameter to writeWithUnsafeMutableBytes which can reserve writable capacity before the pointer is passed to body.

Result:

Additive change only. Users can optionally specify a minimum writable capacity when calling writeWithUnsafeMutableBytes.
2019-10-22 16:40:02 -07:00
Jake 4761f96301 Add flatSubmit method to EventLoop (#426) (#1174)
Motivation:

Calling EventLoop's submit method with a task that returns an EventLoopFuture results in a double future. flatSubmit provides an alternative which does not return a double future.

Modifications:

Added flatSubmit() to the EventLoop protocol and provided a default implementation that returns the result of calling flatMap { $0 } on the EventLoopFuture returned from task.

Result:

Additive change only. flatSubmit method on EventLoop will be available for use.
2019-10-22 13:25:49 -07:00
Jake 58001dac80 namespace ChannelOptions types (#1148) (#1176)
Motivation:

ChannelOptions types like WriteBufferWaterMarkOption are global, public types. These types should be namespaced.

Modifications:

Moved global, public ChannelOptions types into ChannelOptions.Types enum. Created global, public typealiases with deprecation attributes which point to the namespaced types. Switched usage of these types in the codebase to use the namespaced versions.

Result:

Usage of the global, public versions of these types will cause deprecation warnings.
2019-10-22 12:32:45 -07:00
Cory Benfield 4ab52d1066 Add API for modifying BB without CoW (#1173)
Motivation:

From time to time a NIO application holds a ByteBuffer that it may want
to edit. Whether it wants to do that may potentially be contingent on
whether having to do so will cause an allocation, as it may be
preferable to prefer a different operation.

Modifications:

- Added API for modifying a ByteBuffer if it will not CoW.

Result:

People can write allocation-sensitive code on ByteBuffer.
2019-10-21 13:23:33 -07:00
Johannes Weiss 892276cbb2 ByteBuffer: slight improvement in the capacity docs (#1172)
Motivation:

ByteBuffer didn't document well that its capacity is really an initial
capacity only.

Modifications:

Clearly state that it's an initial capacity.

Result:

Better docs.
2019-10-19 14:18:48 -07:00
Johannes Weiss 2fe1154d4f fix new Swift compiler warnings (#1170)
Motivation:

Very recent Swift compilers have more warnings.

Modifications:

Fix the warnings.

Result:

No warnings when compiling.
2019-10-19 13:09:29 -07:00
Johannes Weiss 8dd62cb068 ByteBuffer: add direct Codable support (#1153)
Motivation:

So far, it has been harder than necessary to use Codable & ByteBuffer.
These new APIs should simplify that and allow future optimisations.

Modifications:

Add new API to use `JSONEncoder` and `JSONDecoder` directly with
`ByteBuffer`.

Result:

Easier Codable + ByteBuffer usage.
2019-10-17 16:03:44 -07:00
Johannes Weiss e102aa9ae9 add PipeChannel (#1138)
Motivation:

There are use-cases for SwiftNIO where there are no actual sockets but
rather two pipe file descriptors - one for input, one for output.
There's no real reason why SwiftNIO shouldn't work for those.

Modifications:

Add a PipeChannel.

Result:

More use-cases for SwiftNIO.
2019-10-16 22:06:55 -07:00
Cory Benfield a796af1a96 Reduce allocations in WebSocketFrameEncoder. (#1161)
Motivation:

The WebSocketFrameEncoder naively allocated a new block to write the
frame header into every time it wrote. This is excessive: in many cases
it would be able to re-use the same buffer as last time.

Modifications:

- Attempt to re-use the buffer we used for the last header.

Result:

Fewer allocations in some applications.
2019-10-15 15:45:26 -07:00
Cory Benfield 55ed652a78 Save the performance tests from the OOM killer (#1164)
Motivation:

A dark force walks abroad our lands. In a place where well-behaved
processes close their blinds, lock their doors, and try not to make
noise late at night, processes that shine just a little too brightly,
consume just a little too much RAM, attract the attention of a dark
force whose name is spoken only in whispers. Some call this force a
myth, but others say that the deniers of this force have whispered dark
incantations, invoking the power word "oom_adj".

It is time we intervened to keep the law-abiding processes in our CI
systems safe.

Modifications:

- Prevent the websocket performance tests comnsuming 4GB of RAM.

Result:

Peace will reign.
2019-10-15 14:03:27 +01:00
Cory Benfield 37873bb265 Add some websocket encode benchmarks. (#1159)
Motivation:

To improve the performance of a given component it is very helpful to
know how it performs! This patch adds benchmarks and allocation counter
tests to NIO for websocket frame encoding.

Modifications:

- Wrote some benchmarks for WebSocket frame encoding.
- Wrote some allocation counter tests for WebSocket frame encoding.
- Extend the allocation counter tests to properly account for sub-tests

Result:

Better insight
2019-10-11 16:04:08 +01:00
Konrad `ktoso` Malawski 7e16856aff Prefer handlerAdded/handlerRemoved in websocket example (#1158)
Motivation:

Cory recently mentioned that

> handlerAdded is generally a better choice for a "setup" function than
> channelRegistered, as a handler is always guaranteed to receive
> handlerAdded, but is not guaranteed to receive channelRegistered
> (depending on specifics of pipeline setup).

Thus using the better way in examples is good.

Modifications:

- change `channelRegistered` to `handlerAdded`

Result:

- More idiomatic example app
2019-10-10 09:43:43 +01:00
Mario Sangiorgio 23303e7ce7 NIOHTTP1TestServer (#1152)
* NIOHTTP1TestServer implementation

* Test simple request and two concurrent requests

* Accepting multiple connections but keeping only one active at a time

* Linux tests

* Addressed some PR comments
2019-10-02 12:10:09 +01:00
tomer doron b9293596bc assert EventLoopGroup::syncShutdownGracefully is not called on the event loop (#1151)
motivation: calling syncShutdownGracefully on the event loop can lead to deadlock

changes: assert before calling syncShutdownGracefully that no eventloop context exists
2019-10-01 10:08:35 -07:00
Johannes Weiss 43413cefac fix thread-safety of BaseSocketChannel's description (#1142)
Motivation:

BaseSocketChannel's description method accessed the (mutable) socket
property of the channel which must only be accessed on the EventLoop.
Description however call be called on any thread.

Modifications:

Don't access the socket from description.

Result:

- more thread-safety
- fixes #1141
2019-09-23 16:14:26 +01:00
George Barnett a545d59c47 Fix creating HTTPResponseStatus from 418 (#1140)
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`
2019-09-13 15:28:40 +01:00
George Barnett 9201908b54 Allow promises to be completed with a Result<Value, Error> (#1124)
Motivation:

When dealing with `Result` types and promises it is inconvenient having to
switch over the result in order to succeed or fail a promise.

Modifications:

- Allow promises to be completed with a `Result<Value, Error>` directly.
- Added tests.

Result:

Promises are easier to fulfill with `Result` types.
2019-09-10 09:25:08 +01:00
Johannes Weiss a22389aa4a fix NIODeadline/TimeAmount maths (#1136)
Motivation:

Previously the maths on NIODeadline/TimeAmount could sometimes crash and
weren't always right.

Modifications:

Fix the maths and add tests.

Result:

Fewer crashes, more happy times.
2019-09-09 20:24:08 +01:00
Johannes Weiss f411d158ce ChannelPipeline: fail double removal of handler (#1133) 2019-09-09 18:57:57 +01:00
Johannes Weiss 8aa84453d4 HTTPServerUpgradeHandler: Tolerate futures from other ELs (#1134) 2019-09-09 18:03:40 +01:00
Johannes Weiss cee3db7072 Lock: guarantee crash instead of undefined behaviour (#1131)
Motivation:

NIO's Lock currently just deadlocks if a thread which already holds a
lock tries to reacquire it. This however isn't even really defined
behaviour.

Modifications:

Switch us to a guaranteed crash from a unguarnateed hang.

Result:

Easier to debug deadlocks with NIO's lock.
2019-09-09 09:50:03 +01:00
Konrad `ktoso` Malawski dc92174424 Avoid having cascade be title of all methods in jazzy docs (#1129)
Motivation:

Documentation in jazzy looks misleading, listing all methods under
"cascade" since no new MARKs are defined

Modifications:

declare more MARKs, it's repetetive but not wrong now

Result:

Nicer docs
2019-09-04 18:10:48 +01:00
Tom Counsell 7cd55dfb69 Fix doc typo: before possible -> are possible (#1122) 2019-08-27 14:38:25 +01:00
Johannes Weiss 32760eae40 BaseSocketChannel: accept immediately closed socket (#1121)
Motivation:

In the grpc-swift test suite, we saw a case where the server would
always immediately close the accepted socket. This lead NIO to misbehave
badly because kqueue would send us the `readEOF` before the `writable`
event that finishes an asynchronous `connect`.

What happened is that we just dropped the `readEOF` on the floor so we
would never actually tell the user if the channel ever went away.

Modifications:

Only register for `readEOF` after becoming active.

Result:

- we're happy with servers that immediately close the socket
2019-08-24 12:23:16 +01:00
Johannes Weiss e38f1b695a apply suggestions from #1117 (#1118)
Motivation:

@ravikandhadai suggested some minor changes in #1117 which we should
apply.

Modifications:

Apply all suggested changes all over the code base.

Result:

- fixes #1117
2019-08-20 09:24:58 +01:00
Gwynne Raskind 790827800d Remove cpp_magic.h import and ancient Clang compatibility hack from CNIOAtomics.h (#1111)
The inclusion of `cpp_magic.h` in `CNIOAtomics.h` is unnecessary and pollutes the namespace of anyone else importing the header. NIO now also requires Swift 5, which itself will not be built with a Clang too old to understand `_Nonnull`. Note: Removing the extra import of cpp-magic.h required moving it to the src/ directory to avoid complaints about its inclusion (or lack thereof) in the module's umbrella header.
2019-08-15 10:54:43 +01:00
Johannes Weiss 04831e62c5 MTELG: Add EventLoopGroup identifier (#1109)
Motivation:

With multiple MultiThreadedEventLoopGroups, the thread names are often
useless because there can be two NIO-ELT-#0s etc.

Modifications:

Add a unique MultiThreadedEventLoopGroup identifier.

Result:

NIO thread names unique. Side benefit: It should be easier to see if
people cycle through MTELGs like crazy.
2019-08-14 10:07:07 +01:00
Johannes Weiss eb5d26b595 bootstraps: tolerate random EventLoops (#1108)
Motivation:

Although that's a rare usecase, the Bootstraps must support random
EventLoops. That includes the EventLoops they're called on but also the
EventLoops of the futures returned from the channel initializers.

Modifications:

Make sure we're always on the correct EventLoop.

Result:

Fewer crashes and bugs.
2019-08-14 08:49:48 +01:00
Gwynne Raskind 584e107928 Rename BOOL to BOOLIFY (#1107)
Prevents conflicts when this header is included in a project using Objective-C.
2019-08-13 09:46:51 +01:00
Gwynne Raskind ab9b8eb701 Remove unused wrapper functions for atomic_flag (#1106)
The `atomic_flag` wrappers (structure, `create` helper, and `destroy` helper) are not referenced from anywhere else in the NIO source tree; they can not be invoked, and appear to serve no purpose. Under sufficiently strict compiler settings, they even cause errors due to the functions lacking prototype declarations.
2019-08-13 09:17:40 +01:00
Trevör a28a8668b5 Conform CircularBuffer to ExpressibleByArrayLiteral (#1102)
Motivation:
Making CircularBuffer conform to ExpressibleByArrayLiteral enables
directly initializing it from an array literal, which can sometimes
make its use simpler and more natural, for instance:
foo.circularBuffer = [1,2,3] // vs `= CircularBuffer([1,2,3])`
Foo(circularBuffer: [a, b, c]) // vs `: CircularBuffer([a, b, c])`
This is consistent with other standard Swift collections, such as
Set, as well as existing NIO types (eg: WebSocketMaskingKey).

Modifications:
Extend CircularBuffer to conform to ExpressibleByArrayLiteral

Result:
CircularBuffer can now be initialized from array literals
2019-08-12 15:44:34 +01:00
Johannes Weiss dcb3099b77 docs: EmbeddedChannel isn't as broken as it claims (#1103)
Motivation:

EmbeddedChannel used to only support IOData on its outbound path, that
has been fixed in #763.

Modifications:

Remove the incorrectly documented brokenness.

Result:

More correct docs.
2019-08-12 12:20:47 +01:00
Trevör d30aa6a9f1 Add conditional conformances of CircularBuffer to Equatable and Hashable (#1101)
Motivation:
In general, Swift collections and sequences automatically conforms to
Equatable and Hashable when their Element conforms to Equatable and
Hashhable, respectively. This wasn't the case of CircularBuffer, which
was unintuitive and could cause useless boilerplate code.

Modifications:
CircularBuffer has been extended so that it conforms to Equatable when
its Element is Equatable, and to Hashable when its element is Hashable.
Corresponding test cases have been added.

Result:
Appropriate conditional conformances of CircularBuffer to Equatable and
Hashable
2019-08-11 17:06:07 +01:00
Johannes Weiss 8c6c83c05d NIOThreadPool: backed by NIOThreads (pthreads) instead of DispatchQueues (#1100)
Motivation:

NIOThreadPool was grossly abusing Dispatch to block a large number of
threads for (usually) blocking IO work.

Modifications:

Back the NIOThreadPool by NIOThreads (pthreads) instead of
DispatchQueues.

Result:

Less abuse.
2019-08-09 15:20:53 +01:00
Will Lisac 26586835fd Fail promise in MessageToByteHandler write error cases (#1096)
* Fail promise in MessageToByteHandler write error cases

* Add test case for MessageToByteHandler failing write promises
2019-08-08 10:33:00 +01:00
Johannes Weiss b564a726a9 really no double handlerRemoved calls (#1094)
Motivation:

In #1091 we fixed the most common case of handlerRemoved being called
multiple times. There was still another (less likely) problem left which
is if a manual removal is triggered from _within_ the handlerRemoved
call from a pipeline teardown, then we would still call handlerRemoved
another time.

Modifications:

Properly guard against handlerRemoved being called twice.

Result:

Fewer bugs.
2019-08-06 18:10:53 +01:00