Adds a new `ChannelPipeline.SynchronousOperations.Position` type to fill
a hole in the API that prevented non-sendable Channel handlers being
added at a position to the pipeline via the synchronous operations.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
We're continuing out Strict Concurrency journey, making sure users of
NIO can write data-race-free code.
Modifications:
- Added some missing Sendable annotations in NIOAsyncSequenceProducer
- Made BufferedStream unconditionally Sendable, and required its Element
type to also be Sendable.
The prior constraint wasn't actually correct. We always
behaved as though the element types were Sendable, by passing
them into continuations. This cleans things up.
- Made AnyAsyncSequence Sendable, which it needs to be.
- Made BufferedOrAnyStream Sendable, which it needs to be.
- Made DirectoryEntries explicitly Sendable, which it was.
- Made DirectoryEntries.Batched explicitly Sendable.
Result:
Better concurrency-safety
Motivation:
Our next suite of examples for strict concurrency are the chat ones.
These are very similar to the rest: either no violation at all, or just
a need to use the sync operations on pipeline setup.
Modifications:
- Use sync operations
- Lock in strict concurrency checking
Result:
We continue our march.
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
Motivation:
NIOUDPEchoClient should be strict concurrency clean.
Modifications:
Annotate one closure @Sendable to convince Swift it's ok.
Result:
Strict concurrency clean in NIOUDPEchoClient.
Motivation:
Another strict concurrency change, another echo handler.
Modifications:
Move to sync operations.
Result:
Another step on strict concurrency.
Motivation:
We're getting to the examples now! This patch updates NIOEchoClient to
be clean under strict concurrency.
Modifications:
Use the sync operations to add echo handler.
Result:
Another strict concurrency module.
Co-authored-by: George Barnett <gbarnett@apple.com>
### Motivation:
Xcode 13 is really quite old (3 major releases and it was the GM release
anyway) and this workaround can cause other issues.
### Modifications:
- Remove the Xcode 13 GM workaround.
-
### Result:
Better, possibly faster code.
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!
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.
Motivation
Unfortunately there are a few places where we have to help the compiler
out to realise that our copies of the libc functions are also Sendable,
and -require-explicit-sendable can cause us some trouble if we don't
annotate our usableFromInline types.
Modifications
Annotate our usableFromInline types
Add some @Sendable
Results
The march continues
### Motivation:
Explicit Sendable requires a bunch of annotations in SelectorGeneric, as
many of these types are `@usableFromInline`. This patch applies those.
### Modifications:
- Make many types Sendable
- Make some explicitly not Sendable
### Result:
No missing Sendable warnings
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.
Motivation
RawSocketBootstrap isn't strict concurrency clean yet, and it should be.
Modifications
Add a few necessary Sendable constraints.
Result
No warnings here boss.
### Motivation:
NonBlockingFileIO is now mostly in a good state, but there are some
missed Sendable annotations. Let's clean that up.
### Modifications:
Mark an inner function as `@Sendable`
Add `Sendable` to `NIODirectoryEntry`.
### Result:
The road continues
Motivation
Next on my journey of discovery is NIOThread and NIOThreadPool. These
are basically fine, but they need some Sendability annotations and a bit
of a cleanup.
Modifications
Add some Sendability
Clean up some shutdown logic to avoid semaphores.
Result
Another step forward to a strict-concurrency safe world.
### Motivation:
The HappyEyeballsResolver, being an old part of our stack, has a lot of
code in it that fails to pass strict concurrency checking. That's deeply
suboptimal.
### Modifications:
- Clean up the happy eyeballs resolver under strict concurrency
- Further cleanups to the bootstraps
### Result:
Another step taken on the road to strict concurrency.
Motivation:
As pointed out in #3071, the `flatScheduleTask` implementations can be
improved.
Modifications:
- Refactor the `flatScheduleTask` implementations to skip `flatMap`
calls, which avoids creating an extra promise.
- As there is now a lower number of allocations, reduce the necessary
thresholds for the allocation tests.
Result:
Reduction in the number of allocations in the package.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
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>
Motivation:
NIOAsyncTestingEL is another place where we can reduce the overhead of
the isolated EL views. It's nice for the tests to run faster.
Modifications:
- Implement the new protocol witnesses for AsyncTestingEL
- Refactor common code for scheduleTask out
Result:
AsyncTestingEL is faster.
Motivation:
This patch takes advantage of the fast-path for isolated views on
EmbeddedEventLoop, reducing overhead when using EmbeddedEL.
Modifications:
- Implement the new witnesses in EmbeddedEL
Result:
EmbeddedEL is faster when using isolated views.
### Motivation:
As outlined in this
[issue](https://github.com/apple/swift-nio/issues/2930) by @weissi, the
current performance of calling `description` on `HTTPHeaders` is
undermined by the dynamism of Array.
### Modifications:
The proposed solution replaces the implementation of `description` to
iterate over the items and print them out manually. This provides a
faster solution since we bypass the cost of calling into `description`
of an Array.
### Result:
A more performant implementation of `HTTPHeaders` description.
---------
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation
Right now the isolated view on the EventLoop has to implement its
interface in terms of UnsafeTransfer, because there are no non-Sendable
operations it can use.
That hurts us because we have to allocate an extra closure for all these
operations, making them slower than they need to be. This is unavoidable
in some contexts, but most EventLoops would be able to offer a fast-path
that avoids this extra allocation.
To achieve that, we need to move this logic into a customisation point
on the EventLoop protocol. Our fallback default implementation can be
the same as we do today.
Modifications
- Add customisation points for EventLoop for each of its operations that
has a protocol witness already.
- Add default implementations of these, using the implementation from
EventLoop.Isolated.
Results
No behavioural changes, but the code has moved.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
### Motivation:
Makes it possible to make integers out of ByteBuffers directly with an
initializer. I.e. `UInt32(buffer: ByteBuffer(bytes: [0, 1, 2, 3]))`.
Closes#3012.
### Modifications:
- Adds the `Int(buffer:)` initializer in `ByteBuffer-int.swift`
- Adds tests in `ByteBufferTest.swift`. _Holy hell this file is huge._
- Note that `Int(buffer:)` will crash if the buffer does not have enough
bytes in it to represent the desired integer type.
- It also does _not_ expose endianness and uses `Endianness.host`, to
keep the public API clean and simple. It's a convenience initializer, so
I thought keeping it minimal is a good idea.
### Result:
Nicer direct initializer for integers from ByteBuffers.
---------
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Adds `TimeAmount.init(string:)` and `TimeAmount.description` for parsing
time amounts from strings and pretty printing them.
Closes#2504.
### Motivation:
Had a minute, wanted to work on Swift-NIO a bit more, and saw @weissi
still wanted this.
### Modifications:
It's largely based on the snippet @weissi made in #2504 with a few
changes:
- Added unit tests.
- Added support for more unit aliases for convenience based on
@glbrntt's suggestion.
- Changed `.gitignore` to ignore `.build` everywhere, I've got a few of
them when testing locally.
### Open questions:
- I originally thought perhaps I should add support for multiple number
and unit pairs, i.e. `1h 31m`, but decided against it. Feels like an
edge case. Happy to add this if you think it's needed.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
Makes it possible to read contents of an NIOFileSystem.FilePath into a
String directly. Closes#3010.
### Modifications:
- Added a new `String+FileSystem.swift` into `NIOFileSystem` target.
- Added basic tests to the existing `ConvenienceTests.swift`.
- Added a test to cover `Array+FileSystem` initializer as well.
### Result:
- String initializer for `FilePath` is now available
- Array initializer for `FilePath` now has a test
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Enhance `WebSocketProtocolErrorHandler` to correctly add masking key for
client/server.
### Motivation:
In `NIOWebSocket`, the automatic error handling provided by
`WebSocketProtocolErrorHandler` offers a convenient way for both clients
and servers to handle protocol-level errors. However, the
`WebSocketFrame` used in `WebSocketProtocolErrorHandler` does not fully
adhere to the RFC 6455 standard. Specifically, as per [RFC 6455 Section
5.1](https://datatracker.ietf.org/doc/html/rfc6455#section-5.1), a
client *must* mask all frames it sends to the server, while a server
*must not* mask any frames it sends to the client. This PR addressed
this discrepancy to ensure compliance with the WebSocket protocol.
### Modifications:
In the `WebSocketProtocolErrorHandler` initializer, the user can specify
whether the handler is used for a WebSocket client or server. Within the
`errorCaught` method, the `WebSocketFrame` will include a maskingKey if
the handler is used by a client, or nil if it is used by a server.
Additionally, the `@unchecked` annotation is removed from
`NIOWebSocketServerUpgrader` since the project is now using swift 5.9
toolchain.
### Result:
The `WebSocketProtocolErrorHandler` is more robust and can correctly
close the connection is error occurs.
Motivation
We have a few types lying around that can trivially be Sendable, and
that `-require-explicit-sendable` needs to be `Sendable`. Let's add
those annotations.
Modifications
Made a few types Sendable
Result
One step closer to our strict concurrency goal
### Motivation:
The bootstraps are the next most obvious target for cleaning up
Sendability issues. These issues are mostly just missing annotations,
but there are a few places where we had actual latent threading bugs
that were missed. A lot more of the control flow is made more explicit
in this patch, and in general it should get a lot easier to be confident
that the code is correct.
### Modifications:
- Add necessary `@Sendable` annotations
- Clean up some incorrect `self` captures of bootstraps, which are not
`Sendable`, and which could lead to real threading bugs
- Make a few methods `static` to avoid needing to capture `self` at all.
- Make a few threading assumptions clear by using the isolated views or
the sync operations
- Add some missing `Sendable` constraints on interior generic functions.
### Result:
Better safety, better correctness in the bootstraps.
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>
This fixes hitting the following preconditionFailure in NIOAsyncWriter:
"This should have already been handled by `yield()`".
It doesn't expect a yield to be suspended when the state is
`.writerFinished`, but this can definitely happen. This seemed to be the
correct solution to me, but please check it carefully, because I'm
unfamiliar with this code.
I'm not happy about the test for this. It's blocking the `didYield` call
for a while, to make sure the correct state is reached. See also the
'FIXME' line. What would be a better way to do this?
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Unfortunately, closure composition is really expensive: closures that
capture closures always heap allocate. To make ELF.Isolated perform
well, then, we need to inline the method bodies directly.
Modifications:
- Add some isolated functions into ELF for enqueueing callbacks.
- Inline the implementation of the ELF methods into the isolated view.
Result:
Allocation counts match between isolated/nonisolated.
Since nio 2.78, adding handlers to a pipeline requires the handlers to
be sendable.
That makes the
[NIOAsyncTestingChannel.init(handlers➿)](https://swiftpackageindex.com/apple/swift-nio/2.78.0/documentation/nioembedded/nioasynctestingchannel/init(handlers➿))
function cumbersome, because you cannot create handlers and then call
the function (unless your handlers are Sendable) even if you never use
the handlers elsewhere.
This PR adds a new initializer which takes a closure. The closure is run
on-loop before the channel is registered. This means we can do:
```swift
let channel = try await NIOAsyncTestingChannel {
let handler = MyUnsendableHandler()
try $0.pipeline.syncOperations.addHandler(handler)
}
```
### Motivation:
All of NIO's channels are thread-safe, and that includes the NIOPosix
ones. In an ideal world we'd have written these in such a way that they
rely on very small, easily-verified types to enforce this constraint. We
will migrate towards that in time, but for expediency we can mark these
as they are, which is `@unchecked Sendable`.
### Modifications:
Mark the core NIOPosix channel types `@unchecked Sendable`.
### Result:
Fewer warnings.
### Motivation:
SocketOptionProvider is used to apply a number of socket options. As
part of using it in NIOPosix, it became apparent that several necessary
sendability annotations are missing. Let's add those.
### Modifications:
- Add Sendable constraints with @preconcurrency to SocketOptionProvider.
- Update the BaseSocketChannel conformance to match
### Result:
Tighter Sendable constraints on SocketOptionProvider.
### Motivation:
`testClientBindWorksOnSocketsBoundToEitherIPv4OrIPv6Only` would fail
sometimes leaking the IPv4 promise in `GetaddrinfoResolver`
`HappyEyeballsConnector` returns the connection when it resolves either
IPv4 of IPv6. It uses the `GetaddrinfoResolver` which holds a promise
for each of the IPv4 and IPv6 resolution; when one is completed the
connection will be returned and it is possible to start tearing down the
test and shutting down the event loop before the other is completed and
we leak the promise.
### Modifications:
Complete both futures on the event loop rather than the dispatch queue.
### Result:
The futures are completed in the same event loop tick meaning that we
cannot continue execution and leak one.
Motivation:
The compiler now self-presents as 6.2 on the nightlies, and the executor
takeover still works. Lift the guard.
Modifications:
Lift the guard on compiler version.
Result:
Integration tests pass again.
After the changes introduced in
https://github.com/apple/swift-nio-http2/pull/487, we need to make a
small change in the implementation of `NIOAsyncChannel` to wait on the
`closeFuture` instead of on `close`'s promise in the `executeThenClose`
implementation.
### Motivation:
`executeThenClose` shouldn't fail from errors arising from closing the
channel - at this point, the user of the channel cannot really do
anything, and since the channel has been closed, we should not fail
since resources have been cleaned up anyways.
### Modifications:
This PR changes the implementation of `NIOAsyncChannel` to wait on the
`closeFuture` instead of on `close`'s promise in the `executeThenClose`
implementation.
It also updates the docs for `closeFuture` to better explain when it
will be succeeded and why it won't ever be failed.
### Result:
`executeThenClose` won't throw errors upon closing.
Enable MemberImportVisibility check on all targets. Use a standard
string header and footer to bracket the new block for ease of updating
in the future with scripts.
See https://github.com/apple/swift-nio/pull/3021
Motivation:
NIOEmbedded is used all over NIO-land for testing various pieces of the
infrastructure, and so requires a substantial audit for strict
concurrency.
Modifications:
- Mark a few things Sendable.
- Fix the tests, which actually did have some nasty bugs
Result:
Sendable-clean NIOEmbedded
Motivation:
Users writing NIO code in a strict concurrency world often need to
interact with futures, promises, and event loops. The main interface to
these has strict sendability requirements, as it is possible the user is
doing so from outside the EventLoop that provides the isolation domain
for these types.
However, in many cases the user knows that they are on the isolation
domain in question. In that case, they need more capabilities. While
they can achieve their goals with NIOLoopBound today, it'd be nice if
they had a better option.
Modifications:
- Make EventLoop.Isolated public.
- Make EventLoopFuture.Isolated public.
- Make EventLoopPromise.Isolated public.
- Make all their relevant methods public.
- Move the runtime isolation check from the point of use to the point of
construction.
- Make the types non-Sendable to ensure that isolation check is
sufficient.
- Add unsafeUnchecked options to create these types when performance
matters and correctness is clear.
- Add tests for their behaviour.
- Update the documentation.
Result:
Writing safe code with promises, futures, and event loops is easier.
### Motivation:
SwiftNIO contained a bogus error message:
```
BUG in SwiftNIO (please report), unleakable promise leaked.:486: Fatal error: leaking promise created at (file: "BUG in SwiftNIO (please report), unleakable promise leaked.", line: 486)
```
The actual meaning is that the ELG was shut down prematurely.
### Modifications:
- Replace the message with an accurate one
### Result:
- Users less confused
- fixes#2855
- fixes#2201
I added this changed function call for Android in #2660 earlier this
year, because of [an incorrect Bionic function signature as explained
recently](https://github.com/apple/swift-nio/pull/3009#discussion_r1864807270),
but now that it has been worked around through a new API note as
mentioned there, this change is no longer needed.
I simply did not notice this earlier because it still compiles and
merely gives a warning, which removing this call now silences.
Motivation:
6.0.3 added new warnings about Sendable issues, so let's fix those to
keep things warnings free.
Modifications:
A bunch of Sendable usage fixes.
Result:
Warnings free builds again!
Motivation:
The not-actually-public `_NIOBase64` module has public extensions on
`String`. These are visible when transitively depending on `_NIOBase64`
but shouldn't be.
Modifications:
- Add underscored variants
- Deprecate public variants
Result:
Stricter API
Removes an outdated recommendation about shutting down
`MultiThreadedEventLoopGroup`s before the program exits. It's now
considered best practice to just exit the application and allow the host
OS to do resource clean up.