124 Commits
Author SHA1 Message Date
Johannes Weiss e0f8275ce3 Scheduled: Don't hold onto cancellationTask (#913)
Motivation:

For whatever reason, Scheduled stored the cancellationTask in two
places, one of them it never even used :).

Modifications:

only have the promise have a reference to the cancellationTask

Result:

- don't hold onto things longer than necessary
- shrink Scheduled by one word :)
2019-03-23 15:35:24 +00:00
Johannes Weiss 164f9b12d6 less confusion for Jazzy (#910)
Motivation:

Jazzy adds everything that has a `public` modifier to the documentation,
even if a type is `internal` or `private`. So conforming and internal
type to some protocol and making all those functions `public` has the
effect of essentially documenting stuff that you can't call (as it's not
actually public).

Modifications:

- remove `public` from functions in extensions on types that aren't
  public
- change one `final public` to `public final` because Jazzy doesn't
  normalise that

Result:

better docs
2019-03-19 17:36:27 +00:00
Johannes Weiss ccd386b7db remove deprecated methods (#892)
Motivation:

There were some deprecated methods left on EventLoop.

Modifications:

remove them

Result:

- fixes #779
2019-03-13 18:02:26 +00:00
Johannes Weiss acb37911c0 remove overloading from scheduleRepeatedTask (#886)
Motivation:

scheduleRepeatedTask had two overloads: for synchronous and asynchronous
tasks. They however had the same name so they were pretty much
impossible to use.

Modifications:

rename the asynchronous version of scheduleRepeatedTask to
scheduleRepeatedAsyncTask

Result:

- NIO easier to use
- fixes #882
2019-03-08 15:37:58 +00:00
Johannes Weiss e4774cc6e3 update documentation that EventLoopIterator is no longer optional (#888)
Motivation:

docs were old

Modifications:

update the EventLoopIterator examples
Result:

better docs
2019-03-08 15:21:07 +00:00
Johannes Weiss 549ca82521 ELF: make everything inlinable (#846)
Motivation:

ELFs have loads of generic types and that basically screams allocations
and swift_getGenericMetdata everywhere because nothing was inlinable.

Modifications:

make everything inlinable

Result:

better performance working with ELFs
2019-03-07 11:29:04 +00:00
Johannes Weiss 3d3cc6d685 rename FileHandle to NIOFileHandle (#818)
Motivation:

Collisions with Foundation and other standard libraries is painful.

Modifications:

- rename `FileHandle` to `NIOFileHandle`
- rename `Thread` to `NIOThread` (only exposed in docs)

Result:

fewer collisions
2019-02-19 16:52:00 +00:00
Nathan Harris caf9a3d8da standardize ELF.cascade* collection of methods (#802)
Motivation:

The `ELF.cascade` methods have a parameter label `promise` that does not match Swift API Guidelines, and a way to cascade just successes is not available - while for failures there is.

Modifications:

`ELF.cascade*` methods that already exist have had their `promise` label renamed to `to`, and a new `ELF.cascadeSuccess` method has been added.

Result:

EventLoopFuture now has the cascade methods `ELF.cascade(to:)`, `ELF.cascadeFailure(to:)`, and `ELF.cascadeSuccess(to:)`
2019-02-05 09:01:48 +00:00
Gwynne Raskind 8222af4aad Add cancel notification to RepeatedTask (#783)
* Add cancel notification to RepeatedTask

Motivation:

When cancelling a RepeatedTask, it is often desirable to
wait until any still in-progress execution of the task is
finished - for example, to know when a periodic state save
is done before shutting down. The current API provides no
easy way to perform such a wait. With this addition,
repeating tasks can report completion of a cancellation
request regardless of in what state the task was in when the
request was issued.

Modifications:

A default-nil parameter is added to EventLoop.scheduleRepeatedTask(),
to which a promise can be provided; the promise will be
fulfilled at the time of the task's cancellation, plus any
time required for the task to complete running if it was
cancelled during execution. The promise is signaled even if
the cancellation is the result of the task throwing an error.
A default-nil paramter is also added to RepeatedTask.cancel(),
to which a second promise can be passed. This promise is
fulfilled under the same conditions as the first, even if the
first was not given; neither of the promises is dependent
upon the other and both are fulfilled at the same time if
provided. Further calls to cancel() with different promises
will result in fulfillment of each of those promises as well.

Result:

The observed behavior of RepeatedTask.cancel() now optionally
includes deterministic knowledge of when the task is no longer
executing or scheduled to be executed. The API changes are
designed to be additive in form, but the function signatures
do change. Source compatibility is maintained; binary
compatibility is not.
2019-01-29 13:19:12 +00:00
David Skrundz 0eb85a4478 Add deadlines as an alternative to timeouts (#770)
Add deadlines as an alternative to timeouts

Motivation:

Address #603

Modifications:

- Add NIODeadline type
- Add func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T>
- Reduce the use of DispatchTime in favor of Time
- Replace timeout calls with deadline calls where it makes sense

Result:

Tasks can be scheduled after an amount of time has passed, or at a certain time.
2019-01-25 19:32:55 +00:00
Johannes Weiss 3563b9d795 provide ELF.flatMapResult (#778)
Motivation:

ELFs and the stdlib's Result should be as compatible as possible so a
flatMapResult function which lifts and combines a result into an
EventLoopFuture sounds like a good idea.

Modifications:

add `flatMapResult` which does what it says.

Result:

more interop between `Result` and `EventLoopFuture`.
2019-01-24 20:11:00 +00:00
Johannes Weiss f3294dd803 rename ELF.mapIfError to ELF.recover (#777)
Motivation:

The name `mapIfError` implied that you can transform the error value but
really that's never what it did. Instead, it allowed you to recover
from a failure.

Modifications:

- rename `mapIfError` to `recover`

Result:

cleaner method names
2019-01-24 17:09:13 +00:00
Johannes Weiss c4ff795dda remove ELP.succeed/fail's labels (#776)
Motivation:

EventLoopPromise.succeed/fail has extraneous labels that don't add
anything but noise.

Modifications:

remove extraneous labels

Result:

less noise in the code
2019-01-24 16:42:53 +00:00
Johannes Weiss 3e7d6a7bfd rename ELF.then to ELF.flatMap (#760)
Motivation:

ELF's API should be as close as possible to the new Result's API.
Therefore, we should rename `then` to `flatMap`

Modifications:

- renamed `then` to `flatMap`
- renamed `thenIfError` to `flatMapError`
- renamed ELF's generic parameter from `T` to `Value`

Result:

- more like Result
- fixes #688
2019-01-21 16:41:04 +00:00
Cory Benfield 7a98195524 Actually remove promise logging info. (#752)
Motivation:

While it's really a good idea to keep track of where promises get
allocated, once the promise has been fulfilled we probably don't
need to keep track of it any more.

Happily this leak only affects debug mode.

Modifications:

- Actually removed the element from the promise log when we
  said we would.

Result:

Memory usage doesn't get totally out of hand in debug mode.
2019-01-19 14:15:41 +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
Johannes Weiss 684cad331c EventLoopFuture: use Result type (#734)
Motivation:

Now that the stdlib has introduced the Result type, we can use it in the
implementation (and the whenComplete) function of EventLoopFuture

Modifications:

- replace EventLoopValue with Result
- make whenComplete provide the Result

Result:

use the new shiny stuff
2019-01-05 08:08:47 +00:00
Johannes Weiss 1ac199c195 allow EventLoopIterator to be constructed using [EventLoop] (#706)
Motivation:

Modules outside of NIO core must be able to create `EventLoopIterator`s
in order to conform to the `EventLoop` protocol, therefore we need an
initialiser that's available.

Modifications:

add public initialiser to construct EventLoopIterator from [EventLoop]

Result:

others can implement EventLoops again
2018-12-14 16:13:17 +00:00
Johannes Weiss 305ee9818b make factory method names start with make (#692)
Motivation:

Swift naming guidelines mandate that factory methods start with `make`,
like `makeSomething`. We had a few that were `newSomething`.

Modifications:

make all factories start with make

Result:

more compliant to Swift naming rules
2018-12-10 17:59:24 +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
Johannes Weiss a20e129c22 change newPromise(for: T.Type) to newPromise(of: T.Type) (#672)
Motivation:

making a promise of a type is more grammatical than making a promise for
a type.

Modifications:

s/newPromise(for/newPromise(of/g

Result:

more grammar
2018-11-28 17:32:07 +00:00
Johannes Weiss c1a84a0085 optional type parameter for newPromise() (#671)
Motivation:

When creating new promises I always find it very frustrating to type the
`: EventLoopPromise<Type>` type annotation but it's necessary for the
compiler to know type the promise will be fulfilled with.

Modifications:

allow an optional `for: SomeType.self` parameter for `newPromise` as

    let p = eventLoop.newPromise(for: Int.self)

is much easier to type than

    let p: EventLoopPromise<Int> = eventLoop.newPromise()

Result:

easier to write code
2018-11-28 12:18:03 +00:00
Johannes Weiss 08ab8b51cd remove ugly and unnecessary ignore result (_ = ...) (#652)
Motivation:

_ = expression() is ugly and in many cases unimportant. In fact we train
ourselves to overread it which makes special cases where you'd actually
expect a result to be used just look normal.

Modifications:

remove _ = from a lot of places. In many cases we already had a better
(and sometimes cheaper way) to not return a value but in some cases
(mostly `remove` functions) I added `@discardableResult`

Result:

NIO source code looks nicer
2018-11-13 14:49:08 +00:00
Johannes Weiss 035962e6b6 EventLoop.assertInEventLoop and preconditionInEventLoop (#644)
Motivation:

Dispatch can only precondition that code is run from a certain queue, it
can't return if code is running on a certain queue.
To support that this introduces new EventLoop.assertInEventLoop and
EventLoop.preconditionInEventLoop methods instead of
assert(eventLoop.inEventLoop).

Modifications:

add EventLoop.assertInEventLoop and EventLoop.preconditionInEventLoop

Result:

better support for Network.framework in NIOTS
2018-11-05 09:50:33 +00:00
Johannes Weiss aaf434022f fix limits on 32-bit systems to values that work (#580)
Motivation:

We should have different constants for 32-bit systems where necessary
for example all the maximums should be Int32.max and not UInt32.max
because UInt32.max doesn't fit into an Int on 32-bit platforms. But
where unnecessary 32-bit and 64-bit should share maximum values.

Modifications:

- removed some constraints that should be unnecessary
- skip tests that can't work on 32-bit systems

Result:

better and more consistent 32-bit runs
2018-08-23 10:38:47 +01:00
Johannes Weiss 7de224eaf3 better documentation for MultiThreadedEventLoopGroup (#582)
Motivation:

MultiThreadedEventLoopGroup's docs didn't make it clear that you leak
threads if not shut down.

Modifications:

Add clarification that you should shut down
MultiThreadedEventLoopGroups.

Result:

hopefully clearer documentation.
2018-08-21 11:43:42 +01:00
Johannes Weiss 2fec7a9766 fix races in RepeatedTasks and its tests (#555)
Motivation:

There were a number of race conditions in both the RepeatedTasks
implementation and its tests:

- #554: the RepeatedTask could fire more than once before the
  cancellation was actually processed leading to a crash in tests
- #548: a test was testing that the RepeatedTask ran a certain
  number of times but the counting was racing with the checking
- TOCTOU issue: When a RepeatedTask was cancelled it was possible that
  it fires one extra time because a TOCTOU issue

Modifications:

- fixed the test races
- fixed the TOCTOU issue by checking if it was cancelled when it's
  executed rather than only when it's scheduled to be executed

Result:

- tests should be more stable (fixes #548 & fixes #554)
- RepeatedTask cancellation improved
2018-08-07 07:59:18 +01:00
Ole Begemann c6acf77fc9 Fix some typos in comments (#543)
Motivation:

I came across a few typos and then went through the entire code base
fixing similar errors when I noticed a pattern.

Modifications:

No changes to the code, just to comments.

Result:

No changes.
2018-08-01 15:57:27 +01:00
Franz Busch 82f0f99570 Iterating over the EventLoops from EventLoopGroups (#509)
* EventLoopIterator

Provide a way to iterate over the EventLoops that compose an EventLoopGroup

Motivation:
For some use cases, it might be necessary to access the underlying event loops. See #497.

Modifications:
Added an EventLoopIterator as well as a new protocol requirement to EventLoopGroup called makeIterator() -> EventLoopIterator? . This is optional to avoid a SemVer Major, but will be made non-optional with 2.0.0. A current implementation is provided for every EventLoop through a protocol extension as well as for the MultiThreadedEventLoopGroup.

Result:
It is now possible to iterate over the EventLoops that compose a EventLoopGroup
2018-07-31 13:59:31 +01:00
Franz Busch ae13d135f7 Pass RepeatedTask to its task closure (#515)
Pass the reference to RepeatedTask to its closure to allow a thread-safe cancelling.

Motivation:

With the current implementation, one has to create a reference and use a lock to thread-safely cancel the RepeatedTask. This makes the use more difficult and error-prone.

Modifications:

Added a RepeatedTask parameter to the scheduleRepeatedTask closure.

Result:

It is now possible to cancel the RepeatedTask from within the task closure.
2018-07-17 16:07:55 +01:00
Franz Busch c2c008e53f Repeated Scheduling (#488)
Provide a mechanism to repeatedly schedule a task in the EventLoop

Motivation:
In some cases a certain task should run repeatedly, like polling an API or querying a database. For these scenarios a repeated scheduling mechanism is beneficial.

Modifications:
Added a method to EventLoop to schedule repeated tasks. 

Result:
It is possible to schedule task with an initial delay and a fixed delay now. Furthermore, these task can be cancelled.
2018-07-10 14:59:35 +01:00
Norman Maurer 82a6e4d821 Rename numThreads to numberOfThreads parameter. (#443)
Motivation:

We should be consistent with naming and also choose descriptive names.

Modifications:

- Deprecate old init method that uses numThreads
- Add new init with numberOfThreads param name
- Everywhere use the new init

Result:

More consistent and descriptive naming. Fixes https://github.com/apple/swift-nio/issues/432.
2018-05-25 17:37:55 +02:00
Andrew Edwards bc6618e300 Updated the code comment to explain the correct type of Future result.
Motivation:

This is done because when using Xcode and option + Click on a function you get a help overview inline to see more information and the messaging was incorrect. This helps developers in the future who want to rely on docs via Xcode.

Modification:

Correct the docs

Result:

More correct docs.
2018-05-24 21:02:32 +02:00
Johannes Weiß 2f55baf537 implement lazy selector registration (#388)
Motivation:

Previously we would eagerly register any fd with the selector
(epoll/kqueue) which works well with kqueue. With epoll however, you'll
get `EPOLLHUP` immediately if you supplied a socket that hasn't had
connect/bind called on it.
We got away with this because we took quite a bit of care to always make
sure we call connect/bind pretty much immediately after we registered
it.  And crucially before we ever asked the selector to tell us about
new events.

Modifications:

made selector registration lazy (when we try activating the channel by
calling connect/bind)

Result:

the user can now register and connect whenever they feel like it.
2018-05-04 19:09:59 +02:00
Helge Heß 7fcbff9fce Add support for compiling and running NIO on Raspberry Pi 32-bit (#383)
* Make NIOHTTP1 compile on 32-bit platforms

Motivation:

When building a datacenter out of Apple Watches w/ shattered
glasses, you'll need the ability to build on 32 bit platforms.
This fixes building NIOHTTP1 on such platforms.

Modifications:

This was resetting the parser context pointer using a very
long deadly beef. Had to shorted this for 32bit cows.

Result:

NIOHTTP1 compiles on 32 bit ARM platforms.
2018-05-04 17:13:13 +01: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ß b109389c54 eagerly process input EOF/connection resets (fixes #277) (#286)
Motivation:

We had a number of problems:

1. We wanted to lazily process input EOFs and connection resets only
   when the user actually calls `read()`. On Linux however you cannot
   unsubscribe from `EPOLLHUP` so that's not possible.
2. Lazily processing input EOFs/connection resets wastes kernel
   resources and that could potentially lead to a DOS
3. The very low-level `Selector` interpreted the eventing mechanism's
   events quite a lot so the `EventLoop`/`Channel` only ever saw
   `readable` or `writable` without further information what exactly
   happened.
4. We completely ignored `EPOLLHUP` until now which on Unix Domain
   Socket close leads to a 100% CPU spin (issue #277)

Modifications:

- made the `Selector` interface richer, it now sends the following
  events: `readable`, `writable`, `readEOF` (input EOF), `reset`
  (connection reset or some error)
- process input EOFs and connection resets/errors eagerly
- change all tests which relied on using unconnected and unbound sockets
  to user connected/bound ones as `epoll_wait` otherwise would keep
  sending us a stream of `EPOLLHUP`s which would now lead to an eager
  close

Result:

- most importantly: fix issue #277
- waste less kernel resources (by dealing with input EOFs/connection
  resets eagerly)
- bring kqueue/epoll more in line
2018-04-16 19:36:47 +02:00
Cory Benfield e6b8da38b5 Make Scheduled's constructor public. (#290)
Motivation:

You need to be able to implement EventLoop.scheduleTask to implement
your own event loop. EventLoop.scheduleTask requires creating a
Scheduled. Currently, Scheduled has no public initializer.

Modifications:

Make Scheduled's initializer public.

Result:

It will be possible to actually implement EventLoop.
2018-04-06 17:38:21 +02:00
Matt Eaton 66e4fdfbba Fixed a few minor typos and some force unwraps (#259)
fix some typos, force unwraps and inconsistencies

Motivation:
Reviewing the code I found a few typos that hindered readability, some unnecessary force unwraps and inconsistencies in the codebase.

Modifications:

- The main file in NIOWebSocketServer now accepts command line arguments
and binds to a passed in host and port like the other server examples do.
- Minor typo fixes
- removed one force unwrap

Result:

- The result of my change will bring the NIOWebSocketServer more inline
with how the NIOHTTP1 and NIOChat servers examples are setup.
- less force unwrapping
- fewer typos

[message edited by @weissi]
2018-04-03 11:44:14 +01:00
Johannes Weiß c9c3974276 bring PriorityQueue/Heap implementations inline (#245)
Motivation:

We triggered extra allocations for the generics on PriorityQueue/Heap.
They unfortunately can't be solved using `@_specialize` as the element
type is `ScheduledTask`.
Fortunately we never exposed those types externally so we can just
inline without breaking the public API.

Modifications:

Moved everything from the `NIOPriorityQueue` module into the `NIO`
module.

Result:

Less allocations, more happiness.
2018-03-27 19:04:33 +02:00
Norman Maurer f4036e2b0d Make use of lock.withLockVoid to simplify code (#242)
Motivation:

We should make use of lock.withLockVoid to simplify our code and make it more robust.

Modifications:

- Replace manual lock() / unlock() calls by withLockVoid(...)
- Mark lock.withLock* as @_inlineable to ensure we not get an allocation for the closure.

Result:

Code is cleaner and easier to understand.
2018-03-27 15:22:57 +01:00
Norman Maurer cce02c9e40 Remove one pair of lock() / unlock() during EventLoop run. (#235)
Motivation:

We can remove one lock() / unlock() pair by saving the next ready task during loop execution.

Modifications:

Remvoe one lock() / unlock() pair.

Result:

Less locking during EventLoop run executions.
2018-03-26 16:42:39 +02:00
Norman Maurer 6cf8ca4398 Remove #available(OSX 10.12, *) check which is not needed anymore (#233)
Motivation:

At some point we needed to check for #available(OSX 10.12, *) which is not true anymore as we use our own Thread impl.

Modifications:

Remove #available(OSX 10.12, *) check

Result:

Remove incorrect and not needed check.
2018-03-26 14:23:14 +01:00
Norman Maurer 58a9651d90 Re-use same ContiguousArray for tasks copy operations. (#192)
Motivation:

We allocated a new ContiguousArray per each EventLoop run when tasks needed to be executed. We can just re-use the same instance all the time and so safe malloc operations (we will need to do memset tho).
Beside this we also did not reserve the needed capacity up fron which could lead to realloc operations.

Modifications:

- Reuse same ContiguousArray instance
- Correctly set the initial capacity

Result:

Less overhead when processing tasks via the EventLoop
2018-03-19 19:35:43 +01:00
Norman Maurer b91090f563 Fix possible endless loop when shutdown SelectableEventLoop (#188)
Motivation:

When the SelectableEventLoop is shutdown it will process a defer block in which we tried to fail all scheduled tasks that were not processed yet. The problem here was that we incorrectly not dropped the processed task and so ended in an endless loop which prevent the defer block to complete.

Beside this how we processed the scheduled tasks that were ready for execution was quite in-efficient as we always called removeFirst() which will most likely case a memory copy to move the elements around.

Modifications:

- Correctly fail all scheduled tasks without end up in an endless loop
- Use a for each loop to reduce overhead of processing ready tasks.

Result:

It's always possible to shutdown a SelectableEventLoop and less overhead when processing ready tasks.
2018-03-19 19:53:41 +09:00
Norman Maurer c40c6e1222 Add support to obtain the current EventLoop (#120)
Motivation:

In certain cases it would be useful to be able to access the current EventLoop (which is tied to a thread).

Modifications:

- Add MultiThreadEventLoopGroup.currentEventLoop
- Add tests

Result:

Fixes [#59]
2018-03-15 16:05:35 +01:00
sun_ 2a9e2d6660 Small cleanup in EventLoop. (#96)
Motivation:
Cleaner code.

Modifications:
Change () throws -> (T) to () throws -> T

Result:
Cleaner code.
2018-03-04 06:58:20 -08:00
adamnemecek 0bbed6d72f * removed trailing whitespace (#52) 2018-03-02 15:40:52 +09:00
Norman Maurer d74dda7439 Remove Channel.open and rename Selectable.open to isOpen (#19)
Motivation:

Channel.open was not really needed as for our use-case Selectable already provides everything we need. Also how we used Channel.open in some scenarios was not really correct.

Modifications:

- Remove extension method.
- Rename property
- Remove out-dated comment.
- Fix usage of open

Result:

More clear and correct API
2018-02-27 09:34:26 +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