### Motivation:
Existing get APIs require passing an explicit index and can be misused,
leading to verbose and error-prone code. Adding peek variants that
automatically use the current readerIndex improves safety and clarity.
This aims to address issue #2034 and issue #2736, and is a continuation
of PR #3157
### Modifications:
Introduced peekSlice(), peekLengthPrefixedSlice(), peekData(),
peekUUIDBytes() and peekWebSocketErrorCode().
Added tests for each peek API covering normal, empty and repeated peek
scenarios.
### Result:
Developers can now use nonmutating peek APIs to inspect ByteBuffer
contents without altering the reader index.
### Motivation:
The current readMultipleIntegers methods are used to consume multiple
integer values at once, but lack an equivalent nonmutating API. This can
lead to unnecessary complexity when users want to inspect values without
advancing readerIndex. THis patch introduces peekMultipleIntegers which
uses the current readerIndex, improving safety. This extends previous
work on peek methods (issue #2034, issue #2736).
### Modifications:
Updated the generation script (.sh file) to produce peekMultipleIntegers
variants for each arity of readMultipleIntegers.
Added new tests mirroring the existing multi-read/write tests
### Result:
Users can now inspect multiple integer values in a ByteBuffer without
consuming them, enabling safer workflows.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
One of the SelectorTests used an `@unchecked Sendable` box which did
runtime checking of the `EventLoop`. We have a type for this already,
it's called `NIOLoopBoundBox`, we should use it.
Modifications:
- Replace `Box` with `NIOLoopBoundBox`
Result:
Fewer `@unchecked Sendable`s
### Motivation:
Existing get APIs require passing an explicit index and can be misused,
leading to verbose and error-prone code. Adding peek variants that
automatically use the current readerIndex improves safety and clarity.
This aims to address https://github.com/apple/swift-nio/issues/2034 and
https://github.com/apple/swift-nio/issues/2736, and is a continuation of
PR https://github.com/apple/swift-nio/pull/3157
### Modifications:
- Introduced peekBytes(), peekString(), peekNullTerminatedString(),
peekUTF8ValidatedString() and peekDispatchData().
- Added tests for each peek API covering normal, empty, repeated, and
partial read scenarios.
### Result:
Developers can now use nonmutating peek APIs to inspect ByteBuffer
contents without altering the reader index.
***PS**: I have focussed on the ByteBuffer-aux get\* implementations, so
I'm not sure if I am missing any other important/error-prone get\*
elsewhere, if so, please point me to them and I'll be happy to add
respective peek\*'s!*
Motivation:
A few tests are failing to compiler on 32-bit platforms with recently
nightly toolchains. These tests are skipped if `Int` is 32 bits wide but
the compiler doesn't know that.
Modifications:
- Use overflow addition to stop the compiler from complaining; the
addition won't ever actually overflow because of the runtime check done
ahead of time.
Result:
- Tests compile again
- Resolves#3154
### Motivation:
The existing getInteger API is often used incorrectly, leading to
verbose or error-prone code as mentioned in
https://github.com/apple/swift-nio/issues/2034 and
https://github.com/apple/swift-nio/issues/2736. Users may
unintentionally access data without correctly managing the reader index.
To address this, I added a peekInteger API that reads integers using the
current readerIndex without modifying it.
### Modifications:
* Added a peekInteger method to ByteBuffer, which provides a nonmutating
way to read integers using the current readerIndex.
* Implemented peekInteger using the existing getInteger function.
* Added comprehensive unit tests to validate correct behavior, including
scenarios for different integer types, insufficient bytes, and
multi-write scenarios.
### Result:
* Users now have access to a safer API for inspecting integers in a
buffer without modifying state.
* Added tests for integer reading scenarios.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
Improve usability of NIOAsyncChannel.executeThenClose function from an
Actor
### Motivation:
When calling executeThenClose from inside an actor, the closure which we
pass is not isolated to the same actor
This makes it hard to use
e.g. the following code won’t compile on Swift 6 because the closure is
`self-isolated` so can’t be passed
```
await withDiscardingTaskGroup { group in
do {
try await serverChannel.executeThenClose { inboundStream, _ in
try await self.handleInboundStream(inboundStream: inboundStream, group: &group)
}
} catch {}
}
```
Making the closure as @Sendable allows it to be passed, but then we
can’t access `group` anymore
### Modifications:
Added actor isolation parameter to the `executeThenClose` function.
### Result:
`executeThenClose` will be able to be asynchronously called from inside
an Actor, as it will now be part of the Actor's isolation domain.
---------
Co-authored-by: Franz Busch <privat@franz-busch.de>
Motivation:
Creating a completed future of a non-sendable value when on the current
event loop is currently a little tedious. It requires you to create a
promise, succeed it using the isolated view, or fail it using the
non-isolated view. This is more tedious than it needs to be.
Modifications:
- Add `make{Succeeded,Failed,Completed}Future` methods to the isolated
event loop. These don't require the `Success` value to be `Sendable`.
Result:
It's easier to create completed futures of non sendable values from an
isolated event loop.
Motivation:
At the moment half-closes are actioned immediately and fails all outstanding writes.
We should refuse new writes but allow these writes to complete before
completing the close.
Modifications:
Modify the PendingWritesManager internal buffer to hold an enum of
either writes or close events. We use this to store the close and only
action it when the preceding writes have been handled.
Result:
Outbound close should no longer fail outstanding writes
Allow NIOLoopBoundBox to be initialized by sending in a value
### Motivation:
It should be possible to initialize a loopbound box off-loop if the
initial value of the box is being moved onto the loop.
### Modifications:
Add another static function, to create a loopboundbox by `sending` a
value. This is safe because the compiler will not let the caller use the
value after putting it into the box. Only the box (or rather, the el
which the box is bound to) will be able to access the value thereafter.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
The 'testRawSocketBootstrap_withProtocolNegotiation' test times out when
run in release mode. This is because 'IPHeaderRemoverHandler' removes
the IPv4 headers as a side effect of an assertion. This means that the
headers are only removed when compiled in debug mode.
Modifications:
Always remove the headers.
Result:
The test passes in release mode.
### Motivation:
To ensure NIOHTTP1 concurrency safety.
### Modifications:
* Enable strict concurrency checking in the package manifest.
* Mark several objects `Sendable` with `@preconcurrency` annotations
where they are returned in futures which may execute in arbitrary
concurrency domains.
* `NIOTypedHTTPClientProtocolUpgrader`
* `NIOTypedHTTPClientUpgradeConfiguration`
* `NIOUpgradableHTTPServerPipelineConfiguration`
* `NIOUpgradableHTTPClientPipelineConfiguration`
* `NIOTypedHTTPServerProtocolUpgrader`
* `NIOTypedHTTPServerUpgradeConfiguration`
* Mark handlers as explicitly not sendable
* `NIOTypedHTTPClientUpgradeHandler`
* `NIOTypedHTTPServerUpgradeHandler`
* Added new Sendable type aliases:
* `NIOHTTPClientUpgradeSendableConfiguration`
* `NIOHTTPServerUpgradeSendableConfiguration`
### Result:
No more concurrency warnings. Builds will warn and CI will fail if
regressions are introduced.
Motivation:
The isolated execute on async testing event loop wouldn't execute tasks
in the case of promise being nil
Modifications:
Rewrite the execute logic slightly.
Result:
Correct execution
Co-authored-by: George Barnett <gbarnett@apple.com>
### Motivation:
Whilst working on the NIOHTTP1 strict concurrency work I encountered a
few gaps in the API where I needed isolated analogues of methods on
futures.
### Modifications:
* Add `makeSucceededIsolatedFuture`
* Add a new internal initializer for `EventLoopFuture` which does not
require the value to be Sendable for use in isolated contexts.
* Add a variant of `flatMapError` which can handle closures which return
isolated futures
* Add a `futureResult` computed property which allows us to avoid the
otherwise clumsy `future.nonIsolated().futureResult.assumeIsolated()`
### Result:
More ability to work with isolated futures.
Motivation:
We have a few other file system modules with a small amount of code, and
a lot of tests. Most of these require no changes for strict concurrency,
so let's tackle them all.
Modifications:
Strict concurrency for filesystem targets enabled. Fixed a few incorrect
test case captures.
Result:
Strict concurrency clean filesystem bits.
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:
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 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
I'm about to change all our main event loops to use our new
customisation points. That's great, but it'll have the effect of
removing all the testing of our default implementations, which is not a
good idea. So let's add some more tests.
Modifications
Define a "fallback" event loop for testing the isolated methods.
Result
Reduced likelihood of regressions in future.
### 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>
Motivation:
We were only testing the isolated views on SelectableEventLoop. That was
fine when all the implementation was common, but it isn't going to be
anymore, so we should start having tests across all our EL kinds.
Modifications:
Refactor the tests to take their EL as an argument
Add support for ELs that need to be explicitly run
Add tests for NIOAsyncTestingEL and EmbeddedEL
Result:
Better test coverage.
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:
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>
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:
`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.
…ledOrNotScheduledAnymore
# Motivation
This task was flaky and hit the assertion with the count being 1
# Modification
This changes the expectation to greater than 0 since we can always
guarantee that one scheduled task is run but due to timing windows it
might be that we shutdown the EL before the second task is enqueued
which meant it was immediately failed.
# Result
One less flaky test