156 Commits
Author SHA1 Message Date
976ccdd0d0 Scheduling tasks Int.max ns into future results in an obtuse fatal error (#1056) (#1642)
Motivation:

When scheduling a task too far into the future on a Darwin-kernel,
a fatal error is produced. Whilst the error indicates that a parameter
to the kevent syscall was invalid (EINVAL) it gives no further
information as to the root cause.

As the user's intent is to schedule an task far into the future, a fatal
error should not result. Instead the time should be clamped to the
maximum value that the Darwin-kernel supports. This ensures that
, provided the system remains running, the task will eventually run
(though this may be several yeasr into the future).

Modifications:

Duplicated the bounds checks from those in Darwin-kernel interval timer,
clamping timespec values to the maximum value. Added an assert to check
that the timespec tv_nsec field is valid (according to definition of
the timespec datatype in ISO C11). And a precondition on the tv_sec
field being > 0 (tasks schedule with times <= 0 should not result in
a kevent being registered as they are scheduled immediately).

Added note clarifying behaviour under Darwin-based OSes to the EventLoop
scheduleTask() method.

Added new unit test scheduling a task at the maximum value (which
under any regression would crash).

Result:

Scheduled tasks where the timeout exceed the maximum value supported by
Darwin-based OSes will be clamped to the maximum.

Co-authored-by: Graeme Jenkinson <graemee_jenkinson@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-09-24 15:05:54 +01:00
pokryfkaandKonrad `ktoso` Malawski 3141b02d2f Define public EventLoopGroupProvider type (#1609)
Closes #1608

Co-authored-by: Konrad `ktoso` Malawski <konrad.malawski@project13.pl>
2020-08-03 13:25:26 +01:00
Gregor Milos (Grzegorz Miłoś) 3c5ea83a9a Fix RepeatedTask scheduling logic to run on the correct EL (#1567)
Motivation:

Fixes: #1334

Modifications:

ELF hops on the correct EL before executing.

Result:

Fixes precondition failure, caused by being on the wrong ELG.
2020-06-26 09:19:06 +01:00
George Barnett 8a25c0f5a0 Make TimeAmount Hashable (#1571)
Motivation:

TimeAmount wasn't `Hashable` and there's no clear reason it shouldn't
be.

Modifications:

Add synthesized `Hashable` conformance to `TimeAmount`

Result:

`TimeAmount` is hashable.
2020-06-24 12:31:05 +01:00
George Barnett 7d2e632da2 Execute tasks scheduled at the same time in order on EmbeddedEventLoop (#1540)
Motivation:

`EmbeddedEventLoop` executes scheduled tasks in their run-time order.
If multiple tasks are scheduled for the same time then the order in
which they are eventually executed is undefined.

Since `execute` defers to scheduling a task for "now" it is possible for
tasks to be executed out of order if `run()` is not called between each
execute.

In "real" event loops this isn't an issue because the system time must
advance between each call to `execute`.

Modifications:

- Add a 'insertionOrder' to `EmbeddedScheduledTask`; use it to break
  ties when comparing two tasks with the same run time
- Add a task counter to `EmbeddedEventLoop` which is used to provide an
  insertion order when scheduling tasks.

Result:

- EmbeddedEventLoop will `execute` tasks in order
2020-06-17 10:56:32 +01:00
ac55c57408 Add flatScheduledTask() methods to EventLoop (#1497)
Motivation:

Currently the best, or at least simplest, way to schedule a delayed asynchronous task and wait on its complete result is something like `eventLoop.scheduleTask(in: ...) { return somethingAsync(...) }.futureResult.flatMap { $0 }`. This is not only unobvious but also a bit ugly.

Modifications:

I have added methods which correspond to scheduleTask() in the same way flatSubmit() does to submit(). The returned Scheduled<T> object allows cancellation of the asynchronous task's execution in the same way that is possible for synchronous scheduled tasks, and the futureResult does not complete until the entire asynchronous task does. Callers wishing to wait only for submission of the delayed task, rather than its overall completion, may continue to use the existing scheduleTask() APIs to do so. Tests have been added to verify that the behavior of the new methods is as expected.

These changes are purely additive.

Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-05-11 15:47:05 +01:00
Johannes WeissandCory Benfield 5821c53ee8 allow completely single-threaded NIO programs (#1499)
Motivation:

Usually, you spawn a new MultiThreadedEventLoopGroup to run NIO
programs. But if you're a very simple command line utility, that may not
be necessary, so why not just re-use the main thread?

Modifications:

Allow taking over threads and making them EventLoops.

Result:

Fewer threads if you want.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-05-11 15:33:02 +01:00
Gwynne Raskind add3e402b5 Add inverse of preconditionInEventLoop() and ability to add messages to the assertion (#1508)
Motivation:

It is valuable to be able to provide additional context for any kind of assertion failure, such as obvious points of API misuse or when the purpose of the assertion itself is unclear.

Modifications:

Added an overload of preconditionInEventLoop() that accepts a message autoclosure parameter in the same fashion as `Swift.precondition(_:file:line:)`. Default the implementation of the original version to calling the new one with an empty message. Add defaulted implementation of the new version which forwards the message closure to precondition(). Add the new message parameter directly to assertInEventLoop() without a forwarder since it is not a customization point.

Result:

It is now possible to optionally provide explanatory messages to be included when the "in event loop" precondition fails, as with any other precondition.
2020-05-11 14:07:56 +01:00
Johannes WeissandCory Benfield 2ad77f9a9b WIP: universal bootstrap (#1323)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-03-18 16:20:19 +00:00
George Barnett a678727747 Provide descriptions for EventLoopError (#1381)
Motivation:

EventLoopError does not conform to CustomStringConvertible. When these
errors appear in programs depending on NIO the source of the error is
non-obvious to the user.

EventLoopError.shutdown, for example, would appear in logs as
"shutdown" with no indication that it was the event loop being referred
to.

Modifications:

- Conform EventLoopError to CustomStringConvertible

Result:

- More helpful error descriptions for EventLoopError
2020-02-05 11:26:41 +00:00
Johannes Weiss 52a4cae14d add SAL (Syscall Abstraction Layer) and new SALChannelTests
## Motivation:

In SwiftNIO's codebase, most things were always testable just as well as user code is. With one big missing piece: We could never make the `Selector` do arbitrary things to the `Channel` implementations which lead to super expensive to (create, read, understand) integration tests like [`testWriteAndFlushFromReentrantFlushNowTriggeredOutOfWritabilityWhereOuterSaysAllWrittenAndInnerDoesNot `](https://github.com/apple/swift-nio/blob/5dc9083c6a78b10432b4b55b95704e61ca08f09d/Tests/NIOTests/StreamChannelsTest.swift#L468-L760).

## Modification

Add SAL, a 'syscall abstraction layer' which makes it possible to assert all syscalls that come through a `Socket` or the `Selector` by mocking them. It lets the NIO programmer play the kernel in these "SAL tests" which makes it possible to assert the exact syscalls (with their parameters) and decide the syscalls' returns.

## Result

Finally, we're able to write proper unit tests for scenarios where the `Channel` drove the `Selector` incorrectly.
2020-01-28 12:36:36 +00:00
Johannes Weiss 6174c9802c add descriptions to EventLoop and NIOThread (#1317)
Motivation:

Certain issues are easier debugged if we can print the thread names.

Modifications:

- add the thread name to SelectableEventLoop's description
- make EventLoop and NIOThread CustomStringConvertible

Result:

easier debugging.
2019-12-19 14:52:03 +00:00
Johannes Weiss 5a567709b2 remove phantom publics from EventLoop and Heap (#1298)
Motivation:

In SelectableEventloop, Heap, PriorityQueue, etc there were quite a few
phantom publics left which cause issues with #1257 and are confusing.

Modifications:

- remove the phantom publics
- move SelectableEventLoop to its own file

Result:

- clearer what's going on (public means public)
2019-12-11 18:41:51 +00:00
Joe Smith 06dab4e04b Create a ClientBootstrap protocol (#1253)
This allows other EventLoopGroup implementations to swap in other
bootstrap implementations. By default, it is unimplemented and will
throw an error once `connect` is called on the returned Bootstrap.

Support is implemented for `MultiThreadedEventLoopGroup`,
`SelectableEventLoop` and `EmbeddedEventLoop`.
2019-12-11 12:06:11 +00:00
Jake 3c879ebbaf Fast atomics (#1263)
Motivation:

The existing Atomic class holds an UnsafeEmbeddedAtomic which holds an OpaquePointer to raw memory for the C atomic. This results in multiple allocations on init. The new NIOAtomic class uses ManagedBufferPointer which tail allocates memory for the C atomic as part of the NIOAtomic class allocation.

Modifications:

Created NIOAtomic class that uses ManagedBufferPointer to allocate memory for the C atomic. Created version of catmc_atomic_* C functions that expect memory to be allocated/deallocated by caller. Created NIOAtomicPrimitive protocol for the new version of catmc_atomic_* functions.

Result:

Purely additive. NIOAtomic is available as a replacement for Atomic which results in fewer memory allocations.
2019-11-28 07:45:05 +00:00
Johannes Weiss 74944a937d use Optional<T> instead of T? to workaround SR-11777 (#1252)
Motivation:

In Swift, writing

    var something: T?

    init() {
        self.something = someValue
    }

means that the compiler will first set `self.something` to `nil` and
then in the init override it with `self.someValue`
(https://bugs.swift.org/browse/SR-11777). Unfortunately, because of
https://bugs.swift.org/browse/SR-11768 , stored property initialisation
cannot be made `@inlinable` (short of using `@frozen` which isn't
available in Swift 5.0).

The combination of SR-11768 and SR-11777 leads to `var something: T?`
having much worse code than `var something: Optional<T>` iff the `init`
is `public` and `@inlinable`.

Modifications:

Change all `var something: T?` to `var something: Optional<T>`

Result:

Faster code, sad NIO developers.
2019-11-27 18:37:38 +00:00
Johannes Weiss 732a6e0ef4 join the threads of a MultiThreadedEventLoopGroup on shutdown (#1261)
Motivation:

We should join the threads that we spawned which has the extra benefit
of TSan being able to detect our thread leaks.

Modifications:

Join the SelectableEventLoop's thread after it's shut down.

Result:

We join all the threads.
2019-11-27 17:55:50 +00:00
Pushparaj Zala 86f41d8d40 Added parentheses in TimeAmount constructors to generate optimal code. As Per issue #1249 (#1250)
Motivation:

For better codegen for TimeAmount struct.
After this change overflow will not be checked at each multiplication stage.

Modifications:

- Added parentheses in static constructors of `TimeAmount`

Result:

No change logically except better codegen
2019-11-18 16:10:34 +01:00
Richard Low d4a18c58df Disallow zero EventLoop threads (#1230)
Motivation:

Zero EventLoop threads makes no sense and leads to a crash (see #1223)

Modifications:

Add a precondition

Result:

Initializing EventLoop with zero threads will fail precondition rather than crash later.
2019-11-12 14:27:04 +00:00
David Evans c83a4317f3 Fix typo (#1206) 2019-10-30 14:16:46 +01: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 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 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
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
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 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 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
Dario Rexin 5cd9a7faa8 Add comments to the handling in MultiThreadedEventLoopGroup.shutdownGracefully (#1089) 2019-07-30 17:52:42 +01:00
Dario Rexin 0dc794498f Fix hanging thread when shutting down an already closed EventLoopGroup (#1085)
* Fix hanging thread when shutting down an already closed EventLoopGroup

* Generate Linux tests

* Remove accidental shutdownLock.unlock

* Move dispatching of callbacks out of lock

* Use Lock.withLock instead of manual lock/unlock

* Remove superfluous lock.unlock
2019-07-30 17:18:10 +01:00
Johannes Weiss 22822a949c fix subtracting NIODeadlines (#1074)
Motivation:

Subtracting deadlines should just work, no matter if the result is
positive or negative.

Modifications:

Don't crash on earlierDeadline - laterDeadline.

Result:

- fewer crashes
- fixes https://github.com/swift-server/async-http-client/issues/71
2019-07-19 16:50:10 +01:00
Johannes Weiss 5f0a703818 make illegal SelectableEventLoop.shutdown impossible (#1055)
Motivation:

It's illegal to shut down a SelectableEventLoop because the only valid
owner is a MultiThreadedEventLoopGroup which never uses
shutdownGracefully on its EventLoops.

Modifications:

Fail shutdown attempts instead of running some random, untested code.

Result:

Fail illegal calls rather than running some dangerous code which will
lead to deadlocks further down the line.
2019-07-12 08:42:46 +01:00
Johannes Weiss d1c9ed1d3f add some documentation around EventLoops (#944)
Motivation:

There were a bunch of docs missing around EventLoops.

Modifications:

Add some more docs.

Result:

Happier users, CC @ianpartridge :)
2019-04-03 19:30:06 +02:00
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