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>
Motivation:
Fixes: #1334
Modifications:
ELF hops on the correct EL before executing.
Result:
Fixes precondition failure, caused by being on the wrong ELG.
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.
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
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>
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>
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.
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
## 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.
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.
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)
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`.
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.
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.
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.
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
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.
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.
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.
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.
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.
motivation: calling syncShutdownGracefully on the event loop can lead to deadlock
changes: assert before calling syncShutdownGracefully that no eventloop context exists
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.
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.
* 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
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
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.
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 :)
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
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
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
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
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:)`
* 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.
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.
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`.
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
Motivation:
EventLoopPromise.succeed/fail has extraneous labels that don't add
anything but noise.
Modifications:
remove extraneous labels
Result:
less noise in the code
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
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.
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:
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
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