Commit Graph
32 Commits
Author SHA1 Message Date
Cory Benfield 26d3fb9097 Make NIOPosix strict-concurrency clean (#3090)
Motivation

NIOPosix should be clean under strict concurrency

Modifications

- Fix newly-added issue in GetaddrinfoResolver
- Fix newly-added issue in SEL
- Lock in the win in Package.swift

Result

We did it!
2025-01-27 08:11:08 +00:00
Cory Benfield 85742bc559 Avoid using stderr explicitly (#3089)
Motivation

It's tempting for us to use the FILE * for stderr whenever we want to
print to it. However, the Linux libc modules aren't appropriately
annotated to call that field constant, and indeed it isn't. This causes
Swift to throw a fit if we even touch it.

Modifications

Introduce an awkward function that issues direct writes to stderr
instead of using the FILE *.

Result

Swift is happier.
2025-01-24 16:33:17 +00:00
Cory Benfield 5ce7fde1df Strict concurrency for SelectableEventLoop & MTELG (#3084)
Motivation

SelectableEventLoop and MTEL are our major entry points for execution.
These need to be strict concurrency clean. Unfortunately, changes in one
tend to ripple into the other, so we need to tackle both at once.

Modifications

- A few closures get annotated @Sendable
- Add a NIOLockedValueBox to convince the compiler that this use is
safe.
- Make a few types explicitly not Sendable

Result

No concurrency warnings in MTELG and SelectableEventLoop.
2025-01-24 11:42:40 +00:00
Cory BenfieldandGeorge Barnett e2bfe0875b Adopt optimized isolated path for SelectableEL (#3075)
Motivation:

Users of SelectableEventLoop deserve to have their code that uses the
isolated event loop view perform at least as well as the code that
doesn't.

Modifications:

- Adopt the extra protocol witnesses.
- Refactor out common code.

Result:

Better performance

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-01-21 16:36:41 +00:00
Cory BenfieldandJohannes Weiss 96877aff7f Fix compiling on 6.1 (#3057)
Motivation:

Swift 6.1 nightlies have added many new warnings and errors to NIO. This
patch resolves all of them.

Modifications:

- Clean up missing imports
- Move away from @_implementationOnly where necessary
- Fix a few things where Sendable mismatches were present.

Result:

Clean compile again

---------

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2025-01-14 16:36:17 +00:00
Si Beaumont c3a8d18219 Add EventLoop.now API for getting the current time (#3015)
### Motivation

Code that tries to work with `NIODeadline` can be challenging to test
using `EmbeddedEventLoop` and `NIOAsyncTestingEventLoop` because they
have their own, fake clock.

These testing event loops do implement `scheduleTask(in:_)` to submit
work in the future, relative to the event loop clock, but there is no
way to get the event loop's current notion of "now", as a `NIODeadline`,
and users sometimes find that `NIODeadline.now`, which returns the time
of the real clock, to be surprising.

### Modifications

Add `EventLoop.now`  to get the current time of the event loop clock.

### Result

New APIs to support writing code that's easier to test.
2024-12-06 17:08:56 +00:00
Johannes Weiss 70dfce82b0 give common blocking functions a clear name (#2984)
### Motivation:

In many situations, for example continuous profiling with sampling
profilers, it's important to distinguish between on- and off-CPU work.
That's most easily done if there are clear function names/prefixes to
grep for that are common places to just wait (off-CPU) and do no real
work. In SwiftNIO those are chiefly three places:
1. The `EventLoops` waiting for work
2. `The NIOThreadPool` threads waiting for work
3. `EventLoopFuture.wait()`

This patch makes sure that each of those will have a function with
prefix `_blockingWaitFor` in the function name which is easily
greppable.

### Modifications:

- Create some non-inlinable functions with `_blockingWaitFor...` that
just wait for `...`.

### Result:

SwiftNIO makes operational excellence easier and your SRE team more
happy.
2024-11-23 22:47:34 +00:00
Cory Benfield 2a3a333d8b Better handle ECONNRESET on connected datagram sockets. (#2979)
Motivation:

When a connected datagram socket sends a datagram to a port or host that
is not listening, an ICMP Destination Unreachable message may be
returned. That message triggers an ECONNRESET to be produced at the
socket layer.

On Darwin we handled this well, but on Linux it turned out that this
would push us into connection teardown and, eventually, into a crash.
Not so good.

To better handle this, we need to distinguish EPOLLERR from EPOLLHUP on
datagram sockets. In these cases, we should check whether the socket
error was fatal and, if it was not, we should continue our execution
having fired the error down the pipeline.

Modifications:

Modify the selector code to distinguish reset and error. Add support for
our channels to handle errors.
Have most channels handle errors as resets.
Override the logic for datagram channels to duplicate the logic in
readable.
Add a unit test.

Result:

Better datagrams for all.
2024-11-20 10:28:14 +00:00
Franz Busch 2fe3d92cf5 Drop support for Swift 5.8 (#2924)
# Motivation

We only support the last three Swift released versions which are at this
time 5.9, 5.10 and 6.

# Modification

This PR drops anything related to Swift 5.8.

# Result

Version support aligned.
2024-10-17 12:22:10 +00:00
Si Beaumont ea78d5aadc Add EventLoop APIs for simpler scheduling of callbacks (#2759)
## Motivation

The current `scheduleTask` APIs make use of _both_ callbacks and
promises, which leads to confusing semantics. For example, on
cancellation, users are notified in two ways: once via the promise and
once via the callback. Additionally the way the API is structured
results in unavoidable allocations—for the closures and the
promise—which could be avoided if we structured the API differently.

## Modifications

This PR introduces new protocol requirements on `EventLoop`:

```swift
protocol EventLoop {
    // ...
    @discardableResult
    func scheduleCallback(at deadline: NIODeadline, handler: some NIOScheduledCallbackHandler) throws -> NIOScheduledCallback

    @discardableResult
    func scheduleCallback(in amount: TimeAmount, handler: some NIOScheduledCallbackHandler) throws -> NIOScheduledCallback

    func cancelScheduledCallback(_ scheduledCallback: NIOScheduledCallback)
}
```

Default implementations have been provided that call through to
`EventLoop.scheduleTask(in:_:)` to not break existing `EventLoop`
implementations, although this implementation will be (at least) as slow
as using `scheduleTask(in:_:)` directly.

The API is structured to allow for `EventLoop` implementations to
provide a custom implementation, as an optimization point and this PR
provides a custom implementation for `SelectableEventLoop`, so that
`MultiThreadedEventLoopGroup` can benefit from a faster implementation.

Finally, this PR adds benchmarks to measure the performance of setting a
simple timer using both `scheduleTask(in:_:)` and
`scheduleCallback(in:_:)` APIs using a `MultiThreadedEventLoopGroup`.

## Result

A simpler and more coherent API surface.

There is also a small performance benefit for heavy users of this API,
e.g. protocols that make extensive use of timers: when using MTELG to
repeatedly set a timer with the same handler, switching from
`scheduleTask(in:_:)` to `scheduleCallback(in:_:)` reduces almost all
allocations (and amortizes to zero allocations) and is ~twice as fast.

```
MTELG.scheduleCallback(in:_:)
╒═══════════════════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╕
│ Metric                │      p0 │     p25 │     p50 │     p75 │     p90 │     p99 │    p100 │ Samples │
╞═══════════════════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╡
│ Malloc (total) *      │       0 │       0 │       0 │       0 │       0 │       0 │       0 │    1109 │
╘═══════════════════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╛

MTELG.scheduleTask(in:_:)
╒═══════════════════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╕
│ Metric                │      p0 │     p25 │     p50 │     p75 │     p90 │     p99 │    p100 │ Samples │
╞═══════════════════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╡
│ Malloc (total) *      │       4 │       4 │       4 │       4 │       4 │       4 │       4 │     576 │
╘═══════════════════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╛
```
2024-10-03 20:14:28 +00:00
Franz Busch c9756e1083 Adopt swift-format (#2794)
* Apply formatting

* Apply no block comments rule

* Apply OmitExplicitReturns

* Apple OnlyOneTrailingClosureArgument

* Apply NoAssignmentInExpressions

* Fix up DontRepeatTypeInStaticProperties lint errors

* Apply `OrderedImports`

* Apply `ReplaceForEachWithForLoop`

* format file

* Enable the formatting pipeline

* Adopt `AmbiguousTrailingClosureOverload`

* Fix license header

* Fix format check

* Fix `EndOfLineComment`

* Fix CI

* Adapt CI script to check if changes when running formatting

* Separate lint and format into to steps

* Fix format

* Adopt `UseEarlyExits`

* Revert "Adopt `UseEarlyExits`"

This reverts commit d1ac5bbe12.
2024-07-19 11:48:17 +02:00
George Barnett 9b86559506 Pre-box some errors to reduce allocations (#2765)
Motivation:

Existential errors (`any Error`) are unconditionally boxed. In NIO we
often create errors to fail promises. One place we do this is in the
head channel handler when the pipeline is closed. This error is created
regardless of whether there are actually any promises to fail. The
result is an unnecessary allocation when every channel is closed. This
is particuarly egregious when multiplexed protocols such as HTTP/2 are
used.

As the majority of errors in NIO carry no information beyond their
type/name we can declare these statically and pay the cost of each error
just once rather than once per use.

Modifications:

- Add internal static constants for `ChannelError` and `EventLoopError`
  and use them throughout NIOCore and NIOPosix where they would
  otherwise be boxed.

Result:

Fewer allocations
2024-07-05 08:01:29 -07:00
hamzahrmalikandCory Benfield 082ac2186f Add delegate for collecting eventloop tick metrics (#2608)
* Add delegate for collecting eventloop tick metrics

* add warning to docc

* add missing headers

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-03-27 16:26:59 +00:00
Gregor Milos (Grzegorz Miłoś) 5e470773ca Track execute() and enqueue() tasks separately from scheduled tasks. (#2645) 2024-03-05 16:01:47 +00:00
Johannes Weiss 5c668eb47e allow setting MTELG.singleton as Swift Concurrency executor (#2564) 2024-01-02 06:57:31 -08:00
Franz Busch c2d8eed7e6 Add customization point for scheduling ExecutorJobs on EventLoops (#2538)
# Motivation
Currently, the NIO's EventLoop conformance to the `SerialExecutor` protocol always uses `execute` to schedule the actual job. However, the closure for `execute` has to close over the job and the `EventLoop` itself; hence, it always allocates. Since jobs are a very fine grained object in Concurrency that are created a lot this lead to millions of allocations in even small benchmarks.

# Modification
This PR provides a customization point for `EventLoop`s to execute `ExecutorJob`s directly. For `SelectableEventLoop` we store a type erased `UnownedJob` in our `ScheduledTask` and just run it right away.

# Result
No more allocations when NIO's EL is used as a `SerialExecutor`.
2023-10-09 06:00:57 -07:00
Cory Benfield 5be5ccb5a7 Initial PoC of Custom Actor Executor support (#2388)
* Support NIO Event Loops as actor executors

Motivation

Swift Concurrency supports having actors opt in to executing
within a "custom executor". This requires being able to be strictly
serial, a constraint that NIO's EventLoops natively meet. It is
useful to have actors be able to express a "tie" to an EventLoop
in order to efficiently access objects that are tied to specific ELs.

Modifications

- Extend EventLoop to expose an executor property
- Provide a simple best-effort default using NIODefaultSerialEventLoopExecutor
- Expose NIOSerialEventLoopExecutor protocol that makes it easy
  for adopters to get a better implementation
- Crash if EmbeddedEventLoop is used
- Add tests

Result

Adopters can use ELs as serial executors

* Prefer #if compiler
2023-07-31 07:19:49 -07:00
Franz Busch e865f6163f Use #if canImport(Darwin) where possible (#2446) 2023-06-22 10:12:01 +01:00
ser 6213ba7a06 Pooled control message storage. (#2422) 2023-05-31 06:06:23 -07:00
serandCory Benfield 8193940b9a Buffer pool for message headers and addresses. (#2378)
* Pool buffers for messages and addresses.

* Revert changes related to controlMessageStorage

* Cosmetic fix.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-03-10 16:06:02 +00:00
Cory Benfield 9afaf801e5 Don't retain a task when all we want is a time (#2373)
Motivation:

To know when we next need to wake up, we keep track of what the next
deadline will be. This works great, but in order to keep track of this
UInt64 we save off an entire ScheduledTask. This object is quite wide (6
pointers wide), and two of those pointers require ARC traffic, so doing
this saving produces unnecessary overhead.

Worse, saving this task plays poorly with task cancellation. If the
saved task is cancelled, this has the effect of "retaining" that task
until the next event loop tick. This is unlikely to produce catastrophic
bugs in real programs, where the loop does tick, but it violates our
tests which rigorously assume that we will always drop a task when it is
cancelled. In specific manufactured cases it's possible to produce leaks
of non-trivial duration.

Modifications:

- Wrote a weirdly complex test.
- Moved the implementation of Task.readyIn to a method on NIODeadline
- Saved a NIODeadline instead of a ScheduledTask

Result:

Minor performance improvement in the core event loop processing, minor
correctness improvement.
2023-02-20 07:27:58 -08:00
Cory Benfield 39047aec7c Make PooledBuffer safer. (#2363)
Motivation:

PooledBuffer is an inherently unsafe type, but its original incarnation
was less safe than it needed to be. In particular, we can rewrite it to
ensure that it is compatible with automatic reference counting.

Modifications:

- Rewrite PooledBuffer to use ManagedBuffer
- Clean up alignment math
- Use scoped accessors
- Add hooks for future non-scoped access

Result:

Safer, clearer code
2023-02-08 07:59:17 +00:00
ser 1e7ad9a0db Pool buffers for ivecs and storage refs in the event loop. (#2358)
* Pool buffers for ivecs and storage refs in the event loop.

* Introduce PoolElement for poolable objects and add some bounds checks for the pooled buffers.

* Some polishes.

* Fix build failure with Swift 5.5/5.6

* User raw pointers instead of typed.
2023-02-07 13:48:26 +00:00
thomas-gill-0xff b201ff561d Remove useless instance variables in the SelectableEventLoop (#2338)
Motivation:

Less code we have - less bugs we have.
The fix remove few lines of code keeping the same functionality.

Modifications:

Just remove some useless instance variables.

Result:

Less code.
2022-12-21 03:41:44 -08:00
Johannes Weiss 4ed8e1e228 rename class Lock to struct NIOLock (#2266) 2022-09-21 07:36:42 -07:00
YR ChenandCory Benfield a501353ef6 Deprecate NIOAtomics in favor of Atomics (#2204)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2022-07-01 02:31:14 -07:00
Si BeaumontandCory Benfield 69bb75df32 Throw fatalError when scheduling on shutdown EL if SWIFTNIO_STRICT is set (#2190)
* Throw fatalError when scheduling on shutdown EL if SWIFTNIO_STRICT is set

Signed-off-by: Si Beaumont <beaumont@apple.com>

* Add CrashTest for SWIFTNIO_STRICT crash

Signed-off-by: Si Beaumont <beaumont@apple.com>

* fixup: Extract env var parsing to static let

Signed-off-by: Si Beaumont <beaumont@apple.com>

Co-authored-by: Cory Benfield <lukasa@apple.com>
2022-06-14 05:43:48 -07:00
Fabian FettandCory Benfield c74c3bbabf [SelectableEventLoop] SR-15872; Save allocations when appending task (#2046)
* [SelectableEventLoop] SR-15872; Save allocations when appending task

* Add pr to workaround list

* Update alloc counters

* Update alloc script to include 5.6

* Update alloc counters

Co-authored-by: Cory Benfield <lukasa@apple.com>
2022-02-17 12:18:21 -08:00
Franz Busch f228e264fc Convert ScheduledTask to a struct (#2010)
### Motivation:

In my previous PR https://github.com/apple/swift-nio/pull/2009, I added baseline performance and allocation tests around `scheduleTask` and `execute`. After analysing, the various allocations that happen when scheduling a task there were only a few that could be optimized away potentially.

### Modifications:

This PR converts the `ScheduledTask` class to a struct which will reduce the number of allocations for scheduling tasks by 1. The only thing that needs to be worked around when converting to a struct is giving it an identity so that we can implement `Equatable` conformance properly. I explored two options. First, using an `ObjectIdentifier` passed to the init. Second, using an atomic counter per EventLoop. I went with the latter since the former requires an additional allocation in the case of calling `execute`

### Result:

`scheduleTask` and `execute` require one less allocation
2021-12-14 17:40:40 +00:00
Johannes Weiss 0697d5a599 remove/deprecate the file:line: parameters from flatMap and friends (#1998)
Motivation:

For NIO's 'promise leak detector' we added file:line: labels to
makePromise and there it makes sense. A user might create a promise and
then never fulfil it, bad. With the file:line: arguments we can give
good diagnostics.

However, we (probably that @weissi again) also added it to flatMap and
friends where it doesn't make sense at all.

Sure, EventLoopFuture's implementation may create a promise in the
implementation of flatMap but this promise is never leaked unless the
previous future is never fulfilled (or NIO has a terrible bug). Suffice
to say that in a future chain, it's never a flatMap etc which is
responsible for leaking the first promise...

Explain here the context, and why you're making that change.
What is the problem you're trying to solve.

Modifications:

Remove all unnecessary `file:line:` parameters whilst keeping the public
API intact.

Result:

More sensible code.
2021-12-03 08:27:55 -08:00
Johannes Weiss 773b3797d7 provide EventLoopGroup.any() which is sticky to the current EventLoop (#2003)
Motivation:

A lot of libraries that use SwiftNIO don't allow/require the user to
specify what `EventLoop`s a certain function runs on. Something like

```
myHTTPClient.get("https://example.com) -> EventLoopFuture<...>
```

Internally `MyHTTPClient` has not much choice but using the
`EventLoopGroup.next()` method to obtain an `EventLoop` on which to
create the `EventLoopFuture` (that is returned).

This all works fine but unfortunately it usually forces a thread switch
which is most of the time avoidable if we're already running on an
`EventLoop`.

Modifications:

Provide an `EventLoopGroup.any()` method which can be used like so:

```swift
func get(_ url: String) -> EventLoopFuture<Response> {
    let promise = self.group.any().makePromise(of: Response.self)

    [...]

    return promise.futureResult
}
```

`EventLoopGroup.any()` very much works like `EventLoopGroup.next()`
except that it tries -- if possible -- to return the _current_
`EventLoop`.

Note that this means that `any()` is _not_ the right solution if you
want to load balance. Likely, everything will now stay on the same
`EventLoop`.

Result:

Fewer thread switches.
2021-12-03 13:10:21 +00:00
Cory Benfield b05c6f2206 Move NIO to NIOPosix, make NIO a shell. (#1936)
Motivation:

The remaining NIO code really conceptually belongs in a module called
NIOPosix, and NIOCore should really be called NIO. We can't really do
that last step, but we can prepare by pushing the bulk of the remaining
code into a module called NIOPosix.

Modifications:

- Move NIO to NIOPosix
- Make NIO an umbrella module.

Result:

NIOPosix exists.
2021-08-16 16:50:40 +01:00