### 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:
NIOLoopBound and NIOLoopBoundBox both have a public-but-underscored
event loop property, i.e. the loop to which the value is bound. It's
often very helpful to be able to access the event loop the value is
isolated to. Having access allows you to execute onto the event loop and
safely access the value.
Modifications:
- Make the property public and add a deprecated shim for the
public-but-underscored variant.
Result:
Can access the event loop of a loop bound value
Co-authored-by: Cory Benfield <lukasa@apple.com>
### 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:
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>
Fixes NIOCore compiler errors for the `wasm32` architecture.
### Motivation:
When compiling NIOCore for a SwiftWasm target, several compilation
errors such as the following occur:
```
> swift build --swift-sdk wasm32-unknown-wasi --target NIOCore
.../swift-nio/Sources/NIOCore/FileHandle.swift:151:42: error: cannot find type 'TwoUInt32s' in scope
149 | public final class NIOFileHandle: FileDescriptor & Sendable {
150 | private static let descriptorClosed: CInt = CInt.min
151 | private let descriptor: UnsafeAtomic<TwoUInt32s>
| `- error: cannot find type 'TwoUInt32s' in scope
152 |
153 | public var isOpen: Bool {
.../swift-nio/Sources/NIOCore/FileHandle.swift:77:8: error: Unknown architecture
75 | typealias TwoUInt32s = DoubleWord
76 | #else
77 | #error("Unknown architecture")
| `- error: Unknown architecture
78 | #endif
79 |
…
```
The compilation errors were introduced with the following change:
https://github.com/apple/swift-nio/pull/2598/files#diff-a041d0c0d50a8f4fcda2020eeb4450ea994920ef61653cc06014457ccdb3ba0cR70
### Modifications:
The fix is straight-forward and unlikely to affect any existing
compilation targets other than the `wasm32` target.
We simply need to add `arch(wasm32)` to compiler architecture condtions
for a new typedef on line, then NIOCore compiles to wasm32 again.
### Result:
Before: NIOCore wasm build fails ❌
After: NIOCore wasm build succeeds ✅
Co-authored-by: Scott Marchant <scottm@passivelogic.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:
We added a fatalError to report NIOHTTP1TestServer handleChannel
failures when doing the strict concurrency work which are now being hit.
We don't know if these failures are actually new or not because the
previous code just swallowed such errors.
### Modifications:
Print the errors but limp-on to see if the test goes on to pass, if so
this might not be a new error.
### Result:
Less severe response to NIOHTTP1TestServer handleChannel failure.
### Motivation:
To ensure `NIOTestUtils` concurrency safety.
### Modifications:
* Enable strict concurrency checking in the package manifest.
* `NIOHTTP1TestServer` does pipeline configuration as synchronous
operations.
### Result:
`NIOTestUtils` does not warn of concurrency issues, builds will warn and
CI will fail if regressions are introduced.
Enable strict concurrency checking for NIOWebSocket
### Motivation:
To ensure NIOWebSocket concurrency safety.
### Modifications:
* Enable strict concurrency checking in the package manifest.
* `NIOWebSocketClientUpgrader._upgrade` private function generic return
type is marked as `Sendable` in line with the only method which calls
it.
* `NIOWebSocketServerUpgrader._upgrade` private function generic return
type is marked as `Sendable` in line with the only method which calls
it.
* `WebSocketOpcode.allCases` public computed variable is replaced with a
`let` which manually enumerates the cases instead
### Result:
`NIOWebSocket` does not warn of concurrency issues, builds will warn and
CI will fail if regressions are introduced.
### Motivation:
To ensure `NIOHTTP1Server` concurrency safety.
### Modifications:
* Enable strict concurrency checking in the package manifest.
* User synchronous operations in pipeline configurations
### Result:
Builds will warn and CI will fail if regressions are introduced.
### Motivation:
The docs don't make it clear that the thread count suggestions for the
singletons are:
- set once
- privileged
- need to happen very early on to be effective
### Modifications:
Clarify that.
### Result:
Fewer surprises.
Make `SocketAddressError` `Equatable` and `Hashable`. This is useful when running tests
that you expect to throw this error as it allows you to write for
example
```swift
await #expect(throws: SocketAddressError.unknown(host: "127.0.0.1", port: Int.max)) {
try await app.startup()
}
```
### 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:
To ensure NIOTLS concurrency safety.
### Modifications:
* Enable strict concurrency checking in the package manifest.
* Require `NegotiationResult` to be `Sendable`
* In `NIOTypedApplicationProtocolNegotiationHandler<NegotiationResult>`
the
result is used to fulfil promises and perform hops so we need it to be
sendable when accessed from these other concurrency domains.
### Result:
Builds will warn and CI will fail if regressions are introduced.
### Motivation:
Not all NIO APIs, particularly the async-bridge interfaces that use
`.get()` under the hood respect Structured Concurrency. That might be
okay, but it definitely ought to be documented.
Note: `NIOAsyncChannel` does follow Structured Concurrency.
### Modifications:
Annotate known Structured Concurrency violations.
### Result:
Better docs.
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.