### Motivation
We want our tests to pass in reasonable time.
### Changes
- Disable test
`ByteBufferCrashTests.setBytesWithoutContigiousStorageMoreThanUInt32maxBytes`
- Do not initialize data in `ByteBufferCrashTests.
takingOwnershipOfPointerThatsToLarge`
### Result
Tests are faster again.
Add configurable HTTP/1 decoder parsing limits
### Motivation:
The HTTP/1 decoder previously enforced a single hardcoded limit (80 KB per header field) and placed no cap on the total header-block size or the number of header fields per message. That made resource use unpredictable on requests with very many or very large headers, and there was no way for users to tune the limits for their workload.
### Modifications:
- Introduce a new public `NIOHTTPDecoderLimitConfiguration` exposing three parsing limits:
- maxHeaderFieldSize — maximum size of a single header field (name + value). Default: 80 KB.
- maxHeaderListSize — maximum total bytes of all header field names and values combined per message. Default: 2 MB.
- maxHeaderFieldCount — maximum number of header fields per message, including trailers. Default: 256.
- Plumb the configuration through `HTTPDecoder` / `HTTPRequestDecoder` / `HTTPResponseDecoder` initializers. The existing initializers continue to work unchanged via convenience overloads that fall back to
default limits.
- Expose the configuration on `NIOUpgradableHTTPServerPipelineConfiguration` and `NIOUpgradableHTTPClientPipelineConfiguration` so users of the typed pipeline setup can override the defaults.
- Track per-message totals in `BetterHTTPParser` and reject with `HTTPParserError.headerOverflow` when a limit is exceeded; counters reset at each new message so HTTP/1 pipelined connections behave
correctly.
- Add tests covering the success and error paths for each limit, the default behaviors, and that trailer fields count toward the field-count cap.
### Result:
Users can configure the HTTP/1 decoder's per-field-size, total-list-size, and field-count limits. Existing call sites continue to compile and run unchanged, now with bounded defaults across all three dimensions instead of just one.
### Motivation:
When connecting to services with multiple DNS records (e.g. Kubernetes
headless services), getaddrinfo returns addresses in a deterministic
order, causing all connections to go to the same backend. SwiftNIO now
provides a RandomizedDNSResolver that shuffles results.
### Modifications:
Add a dnsResolver property to HTTPClient.Configuration with two options:
.system (default, current behavior) and randomized (uses NIO's
RandomizedDNSResolver to shuffle DNS results). Apply the resolver to
ClientBootstrap during connection creation.
### Result:
Users can opt into randomized DNS resolution by setting
config.dnsResolver = .randomized, enabling load distribution across
multiple backend IPs while preserving the default behavior.
---------
Co-authored-by: Pavan sai kumar alladi <p_alladi@apple.com>
Allow concurrent calls of `_createDirectory()` for file paths with
shared ancestors.
### Motivation:
The current implementation of
`_createDirectory(withIntermediateDirectories: true)` does not catch and
continue during execution when the intermediate directory path it is
trying to create already exists.
The current loop looks like this:
```swift
// Successfully made a directory, construct its children.
while let subdirectory = droppedComponents.popLast() {
path.append(subdirectory)
switch Syscall.mkdir(at: path, permissions: permissions) {
case .success:
continue
case let .failure(errno):
return .failure(.mkdir(errno: errno, path: path, location: .here()))
}
}
```
If we are concurrently trying to create directories `/foo/bar/dir1` and
`foo/bar/dir2`, we can fail with an error like `directory /foo already
exists` because one of the two task's `mkdir` syscall on line 928
errored with a `fileExists` error.
### Modifications:
The code adds the same logic already present on lines 894-907 of
`FileSystem.swift` to the failure case while iterating over the
subdirectory paths:
If the syscall errors because the directory already exists, (but didn't
exist during the loop on lines 886-923), we can safely continue. Another
task must have beaten our task to creating the directory, but that is
ok.
### Result:
Without this change, it would be difficult to actually call the
`FileSystem.createDirectory(withIntermediateDirectories: true)` function
in concurrent tasks, because if you were creating directories with
common ancestors, at least one of the 2 tasks would error due to the
race condition on directory creation. With this change, the
`createDirectory()` function can now be called concurrently without this
race issue potentially causing an error. I added the change to both the
`NIOFS` and `_NIOFileSystem` directories since they seem to be copies of
each other.
Co-authored-by: David Stern <d_stern@apple.com>
Add missing helpers for reading length-prefixed strings and bytes with
customizable encodings for the length.
### Motivation:
There are already some APIs for writing length-prefixed strings and
bytes with a custom strategy for encoding the length, but there weren't
helpers to read them.
### Modifications:
- Add missing helpers for reading length-prefixed strings and bytes with
customizable encodings for the length
- Add tests for the new APIs
- Fix DocC comments and improve the related article
### Result:
New APIs are added for reading length-prefixed strings and bytes with a
custom strategy for encoding the length.
Strip Transfer-Encoding when Content-Length is present in HTTPEncoder
### Motivation
When `correctlyFrameTransportHeaders()` detected a `Content-Length`
header, it returned `.contentLength` without removing any existing
`Transfer-Encoding` header.
### Changes
- Remove `Transfer-Encoding` header, if a `Content-Length` header is
present
### Result
NIO sends either a `Content-Length` header or a `Transfer-Encoding`
header, but not both.
Translate `HTTPHeaderValidationTests` to Swift testing
### Motivation:
We want to add tests that use parameterized testing to
`HTTPHeaderValidationTests`. In order to allow this we first need to
translate this file to use Swift Testing instead of XCTest.
### Modifications:
- Mechanical translation of `HTTPHeaderValidationTests` from XCTest to
Swift testing.
### Result:
We can add parameterized tests to HTTPHeaderValidationTests.
As observed by @weissi https://github.com/apple/swift-nio/issues/3382
### Motivation:
When `getaddrinfo` fails, SwiftNIO throws `SocketAddressError.unknown`
which discards the error code. This makes it impossible for callers to
distinguish between different failure reasons (e.g., `EAI_NONAME` vs
`EAI_AGAIN`), which is needed for retry logic and diagnostics.
### Modifications:
- Add `SocketAddressError.UnknownHost` struct that carries `host`,
`port`, `errorCode` (from `getaddrinfo`), and `errorDescription` (from
`gai_strerror`).
- Update `SocketAddress.makeAddressResolvingHost` and
`GetaddrinfoResolver` to throw/fail with the new error type on both
POSIX and Windows paths.
- Update existing test catch blocks to use the new error type.
- Add `testGetaddrinfoErrorCodeIsPreserved` to verify the error code is
captured.
### Result:
Callers can now inspect the `getaddrinfo` error code when host
resolution fails, enabling more specific error handling. Resolves
https://github.com/apple/swift-nio/issues/3382
### Questions for reviewer
1. **Should `case unknown(host:port:)` be deprecated?** — This enum case
is no longer thrown after this PR. Callers catching `.unknown` will
silently stop matching. Should I add
`@available(*, deprecated, renamed: "UnknownHost")` to provide a
migration path?
2. **Should the doc comment on `makeAddressResolvingHost` be updated?**
— The `- Throws:` line still references `SocketAddressError.unknown`
instead of the new
`SocketAddressError.UnknownHost`.
---------
Co-authored-by: Si Beaumont <beaumont@apple.com>
### Motivation:
`testCanPinThreadsToCores` crashes with a precondition failure
(`pthread_setaffinity_np failed: 22`) on CI environments where the
container's available CPUs don't start from 0.
```console
% docker run --rm -v $PWD:/pwd -w /pwd swift:6.2 nproc
8
```
Running the test in an environment where the CPUs didn't start from 0
crashed:
```console
% docker run --rm -v $PWD:/pwd -w /pwd --cpuset-cpus="2-3" swift:6.2 nproc
2
```
```console
% docker run --rm -v $PWD:/pwd -w /pwd --cpuset-cpus="2-3" swift:6.2 swift test --filter testCanPinThreadsToCores
...
◇ Suite "NIOThreadPoolTest" started.
◇ Test testCanPinThreadsToCores() started.
NIOPosix/LinuxCPUSet.swift:78: Precondition failed: pthread_setaffinity_np failed: 22
*** Signal 5: Backtracing from 0xf358a1ceb140... done ***
*** Program crashed: System trap at 0x0000f358a1ceb140 ***
Platform: arm64 Linux (Ubuntu 24.04.4 LTS)
Thread 0 "TP-#0" crashed:
0 0x0000f358a1ceb140 _assertionFailure(_:_:file:line:flags:) + 164 in libswiftCore.so
1 [ra] 0x0000ba727f86c0a0 static NIOThread.currentAffinity.setter + 939 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/LinuxCPUSet.swift:78:13
2 [ra] 0x0000ba727f878b48 closure #2 in NIOThreadPool._start(threadNamePrefix:) + 295 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/NIOThreadPool.swift:365:47
3 [ra] [thunk] 0x0000ba727f8fc5a0 thunk for @escaping @callee_guaranteed (@guaranteed NIOThread) -> () + 23 in swift-nioPackageTests.xctest at //<compiler-generated>
4 [ra] 0x0000ba727f8ff5c8 closure #1 in closure #1 in static ThreadOpsPosix.run(handle:args:) + 767 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/ThreadPosix.swift:186:21
5 [ra] [thunk] 0x0000ba727f8ff678 @objc closure #1 in closure #1 in static ThreadOpsPosix.run(handle:args:) + 11 in swift-nioPackageTests.xctest at //<compiler-generated>
6 [ra] 0x0000f358a03d595c <unknown> in libc.so.6
...
```
Also, when there was just one CPU, this test would pass but wasn't
actually testing the pinning because it was using
`min(1, System.coreCount / 2)` instead of `max`, which clamped down to 0
for the loop.
### Modifications:
- Select from available CPU IDs using `NIOThread.currentAffinity.cpuIds`
- Use `max` instead of `min` to still run the test on single core
environments.
### Result:
The test no longer crashes on CPU-restricted environments:
```console
% docker run --rm -v $PWD:/pwd -w /pwd --cpuset-cpus="2-3" swift:6.2 swift test --filter testCanPinThreadsToCores
...
◇ Suite "NIOThreadPoolTest" started.
◇ Test testCanPinThreadsToCores() started.
✔ Test testCanPinThreadsToCores() passed after 0.001 seconds.
✔ Suite "NIOThreadPoolTest" passed after 0.001 seconds.
✔ Test run with 1 test in 1 suite passed after 0.001 seconds.
```
## Summary
- NIOFileSystem's `open` syscall error mapping only handled `EACCES`
(`.permissionDenied`) but not `EPERM` (`.notPermitted`), causing EPERM
errors (e.g., on network volumes) to be classified as "unknown" instead
of `permissionDenied`
- Added `.notPermitted` alongside `.permissionDenied` in the `open()`
switch case in `FileSystemError+Syscall.swift` (both `NIOFS` and
`_NIOFileSystem` modules)
- Added corresponding test expectation for the new errno mapping
## Motivation
Other syscall handlers in the same file (`remove`, `symlink`, `unlink`,
`futimens`) already correctly handle both `.permissionDenied` and
`.notPermitted` as `permissionDenied`. The `open` handler was missing
this treatment.
Fixes#3559
## Test plan
- [x] Updated `testErrnoMapping_open` to verify `.notPermitted` maps to
`.permissionDenied`
- [ ] CI will validate on all supported Swift versions
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Motivation:
Similar to MultiThreadedEventLoopGroup, it is useful in some NUMA
circumstances to be able to pin thread pools to specific CPUs. This can
minimise the overheads of moving memory around across NUMA nodes.
Modifications:
Added a pinned CPUs initializer to NIOThreadPool
Result:
Users have more flexibility.
### Motivation
*
`MTELGScheduledCallbackTests.testCancelAfterShutdownDoesNotCallCancellationCallbackAgain`
is failing on iOS simulator CI. It schedules a callback with a
`.milliseconds(1)` deadline, then shuts down, expecting shutdown to
cancel the callback. On the simulator the 1ms timer fires before
shutdown processes, so the callback executes instead of being cancelled.
* This is the same class of bug previously fixed for
`testScheduledCallbackNotExecutedBeforeDeadline` in dcecf0cb.
### Modifications
* Change the scheduled callback deadline from `.milliseconds(1)` to
`.hours(1)` in
`testCancelAfterShutdownDoesNotCallCancellationCallbackAgain` (the
observed failure).
* Speculatively apply the same fix to
`testCancelExecutesCancellationCallback`,
`testCancelAfterCancelDoesNotCallCancellationCallbackAgain`, and
`testShutdownDoesNotCancelCancelledCallbacksAgain` which have the same
pattern.
* The `EmbeddedEventLoop` and `NIOAsyncTestingEventLoop` subclasses use
virtual time so this does not extend test duration.
### Result
* Scheduled callback cancellation tests no longer depend on real-time
precision and should not flake on slow CI runners or simulators.
### Motivation
* `testFlatBlockingMapOnto` sets up a `flatMapBlocking` chain that
dispatches work to `DispatchQueue.global()`, but never waits for the
chain to complete before returning. The `defer` block calls
`syncShutdownGracefully()`, which shuts down the event loop while the
GCD dispatch is still in-flight. When the GCD work completes and tries
to deliver its result back to the event loop, it finds the loop already
shut down, causing a crash. On fast machines the GCD work completes
before shutdown, but on slow iOS simulators shutdown wins the race
consistently. This crash also kills whichever other test happens to be
running concurrently (typically
`testRepeatedTaskThatIsCancelledAfterRunningAtLeastTwiceNotifies`).
### Modifications
* Capture the `EventLoopFuture` from the `flatMapBlocking` chain and
call `.wait()` on it before the function returns, ensuring the GCD
dispatch delivers its result back to the event loop before shutdown
begins. Move the assertions from the `.whenSuccess` closure to after the
`.wait()`.
### Result
* The event loop is no longer shut down while GCD work is in-flight,
fixing the crash on iOS simulator CI.
### Motivation
`testCopyFileReplacingExistingFileSucceeds` (and
`testCopySymlinkReplacingExistingSymlinkSucceeds`) verify that no .tmp-
prefixed files are left behind after a `copyItem(replaceExisting: true)`
call on Linux. However, both tests create their files in the shared
system temp directory (e.g. /tmp) and then scan that entire directory
for .tmp- files. When other tests run in parallel, their in-flight
`copyItem(replaceExisting: true)` operations leave transient .tmp- files
in the same directory, causing spurious failures.
### Changes
- Both tests now create a dedicated subdirectory for their files, so the
temp file scan only sees files belonging to that specific test.
- Cleanup is handled via `addTeardownBlock` to ensure the subdirectory
is removed even if the test fails early.
### Results
The temp file assertions are no longer affected by concurrent test
activity or other processes writing to the shared temp directory,
eliminating the flakiness.
### Motivation
* `testHalfCloseOwnOutputWithPopulatedBuffer` asserts that writing to a
half-closed channel produces `ChannelError.outputClosed`. However, after
flushing the buffered write and the FIN, the remote peer can process
both and fully close the connection before the subsequent write is
processed. When this happens the channel is fully closed and the write
fails with `.ioOnClosedChannel` instead.
* This race seems to be more likely on iOS simulators in CI.
### Modifications
* Accept either `.outputClosed` or `.ioOnClosedChannel` as valid errors
from the post-half-close write.
### Result
* The test no longer flakes on iOS simulator CI runs.
### Motivation
*
`MTELGScheduledCallbackTests.testScheduledCallbackNotExecutedBeforeDeadline`
is flakey on macOS CI. It schedules a callback with a 1ms deadline,
sleeps for 1µs via `Task.sleep`, then asserts the callback hasn't fired.
On a loaded CI runner, `Task.sleep` can overshoot well past 1ms, causing
the callback to fire before the assertion.
### Modifications
* Increase the scheduled callback deadline from `.milliseconds(1)` to
`.hours(1)` in `_BaseScheduledCallbackTests`. This makes it impossible
for the short sleep to overshoot past the deadline. The
`EmbeddedEventLoop` and `NIOAsyncTestingEventLoop` subclasses use
virtual time so this change is harmless to them.
### Result
* The test reliably asserts that a callback is not executed before its
deadline without depending on real-time sleep precision.
…oopTest`
### Motivation
* `Task.sleep(for:)` and the `Duration` literals (`.milliseconds`,
`.seconds`) require iOS 16.0+, tvOS 16.0+, and watchOS 9.0+, so these
calls cause build failures on simulator test destinations in CI.
### Modifications
* Replaced all five `Task.sleep(for:)` calls in `EventLoopTest.swift`
with the universally available `Task.sleep(nanoseconds:)`.
### Result
* `EventLoopTest` compiles for iOS, tvOS, and watchOS simulator
destinations. Verified locally with `xcodebuild build-for-testing`.
### Motivation
* `.timeLimit` from Swift Testing requires iOS 16.0+, watchOS 9.0+, and
tvOS 16.0+, but the package's deployment targets are lower, causing
build failures on all iOS/watchOS/tvOS simulator test steps in CI.
### Modifications
* Removed `.timeLimit(.minutes(1))` from the `@Suite` attribute on
`MultiThreadedEventLoopGroupTests`.
* Removed `.timeLimit(.minutes(1))` from the `@Test` attribute on
`testRepeatedTaskThatCancelsItselfNotifiesOnlyWhenFinished`.
### Result
* Tests should compile on iOS, watchOS, and tvOS simulator destinations.
* The CI job timeout still guards against hung tests.
Port `EventLoopTest` to Swift Testing.
### Motivation:
Tests should use the latest Swift Testing framework when possible.
### Modifications:
- Ported `EventLoopTest ` from XCTest to Swift Testing
### Result:
All tests continue to pass, EventLoopTest now has more modern Swift
Testing syntax.
Motivation:
NIO has had support for CPU pinning for 8 years, but nobody has ever
used it. Ask me how I know?
Modifications:
- Make the CPU pinning constructor public.
Result:
Users can pin MTELG threads to specific CPU cores, _finally_.
Motivation:
System.udpMaxSegments purports to expose the value of UDP_MAX_SEGMENTS.
However this doesn't appear to be part of the UAPI so it always returns
nil.
Modifications:
- Deprecate `System.udpMaxSegments`
- Remove the C shim
- Update tests
Result:
After your change, what will change.
Extend timeout in testShutdownCancelsOutstandingScheduledCallbacks
### Motivation:
* `testShutdownCancelsOutstandingScheduledCallbacks` can be flaky,
particularly on slower systems like simulated devices in CI.
* In some circumstances the task can be executed before it has chance to
be cancelled.
### Modifications:
* Schedule the task for the far future so that it is available to be
cancelled even on slower systems.
### Result:
Less flaky tests.
### Motivation
`SocketAddress.init(ipAddress:port:)` uses `inet_pton` to parse IP
address strings. `inet_pton` does not support the `%scope` suffix used
in IPv6 link-local addresses (e.g., `fe80::1%eth0`), causing these
addresses to fail with `failedToParseIPString`. This forces downstream
consumers like grpc-swift-nio-transport to reimplement scoped IPv6
parsing using `getaddrinfo` themselves.
Related: https://github.com/grpc/grpc-swift-nio-transport/issues/147
### Modifications
When the IP address string contains a `%` character, fall back to
`getaddrinfo` with `AI_NUMERICHOST` instead of `inet_pton`. This
properly parses the `%scope` suffix and sets `sin6_scope_id` in the
resulting `sockaddr_in6`. The scoped path is extracted into a private
`_parseScopedIPv6` helper, guarded with `#if !os(Windows) && !os(WASI)`.
The non-scoped `inet_pton` path is completely unchanged.
Added 5 tests:
- Named scope (`fe80::1%lo`) — verifies `sin6_scope_id` matches
`if_nametoindex`
- Numeric scope (`fe80::1%1`) — verifies numeric index parsing
- Scoped vs non-scoped inequality — different `sin6_scope_id` means
different addresses
- Invalid scopes rejected — empty scope and nonexistent interface both
throw
- Non-scoped regression — `::1` still works with `scope_id == 0`
### Result
`SocketAddress(ipAddress: "fe80::1%eth0", port: 80)` now succeeds and
preserves the scope ID in `sin6_scope_id`. Non-scoped addresses continue
to work exactly as before.
### Context
This came up while working on IPv6 link-local support in
[grpc-swift-nio-transport#146](https://github.com/grpc/grpc-swift-nio-transport/pull/146),
where the workaround was to use `getaddrinfo` directly in the gRPC
layer. The reviewer suggested upstreaming this to swift-nio so the
workaround can be removed.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation
* Other libraries often have byte buffer storage with similar concepts
as NIO's `ByteBuffer`, linear storage with reader and writer indices -
it would be nice to have efficient conversion to and from these objects.
* Efficienct conversion would likely mean taking ownership of the byte
storage allocated by the other object and exposing `ByteBuffer`s
internals so that they may be owned by another object, there is no API
for this currently.
### Modifications
* Added new methods behind `CustomByteBufferAllocator` SPI.
* Added public `ByteBuffer` initializer for adopting
externally-allocated memory
* Made `ByteBufferAllocator` initializer public with custom
`malloc`/`realloc`/`free`/`memcpy` hooks
* Updated `realloc` signature to pass old capacity alongside new
capacity to allow implementations to copy over bytes
* Added `withVeryUnsafeMutableBytesWithStorageManagement` for mutable
storage access
* Updated all existing tests using internal allocator API to use the new
API
* Added tests for custom allocator functionality
### Result
* Custom allocators can manage `ByteBuffer` memory with full size
information
* External systems can transfer memory ownership to `ByteBuffer`
* System allocator maintains zero overhead due to inlining of the
wrapper
* API (SPI) is extensible for future allocation system integrations
Apple platform simulator CI failures
### Motivation
* Several tests failed when testing against simulators for Apple
platforms (iOS, tvOS, watchOS, visionOS)
### Modifications
* Added `@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)` to each
`@Test` method in `NIOThreadPoolTest`, `EventLoopFutureTest`, and
`NIOTransportAccessibleChannelCoreTests` to match the availability of
the APIs they use (`timeLimit` and `withUnsafeTransportIfAvailable`).
* Removed `.timeLimit(.minutes(1))` from the `@Suite` declarations on
`NIOThreadPoolTest` and `EventLoopFutureTest` - the `@Suite` macro
cannot be used with `@available`, so `timeLimit` cannot be used.
* Skip `testHomeDirectoryFromPasswd` on simulator targets via
`#if targetEnvironment(simulator)` / `XCTSkip`, since simulators retu>
success but nil information when invoking `getpwuid_r`.
### Result
* Apple simulator platform builds and test runs no longer fail due to
these issues. Some infrastructure issues remain to be resolved
separately.
Adds capability to NIOFS to copy regular files and symlink, allowing to
overwrite the destination.
### Motivation:
Per https://github.com/apple/swift-nio/issues/3403 and
https://github.com/apple/swift-nio/pull/3470 we want to add
`replaceExisting: bool` to `FileSystem.copyItem`.
### Modifications:
1. Adds `replaceExisting: bool` parameter to
`FileSystemProtocol.copyItem`.
2. Adds `replaceExisting: bool` parameter to `FileSystem.copyItem` and
implementation for regular files and symbolic links.
3. Adds tests.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
## Motivation
NIO channels abstract over an underlying transport mechanisms (sockets,
pipes, etc.), which users typically need not interact with. However,
there are scenarios where users need direct access to the underlying
transport for low-level operations that work outside NIOs abstraction.
One example is performing out out-of-band operations on the underlying
file descriptor for a socket-based channel.
This PR adds a structured way to access the underlying transport of a
channel, for channels that choose to implement it.
## Modifications
- Add a new `public protocol
NIOTransportAccessibleChannelCore<Transport>` which provides a scoped
`withUnsafeTransport(_:)`, used for channel implementations to opt-in.
- Add conformance to
`NIOTransportAccessibleChannel<NIOBSDSocket.Handle>` for
`BaseSocketChannel`, to make this API available for all socket-based
channels, including channels returned from the socket-based bootstrap
public APIs.
- Add public API
`ChannelPipeline.SynchronousOperations.withUnsafeTransportIfAvailable(_:)`
Note that not all channels need to or should their transport, which is
why this was added as an additional protocol that refines `ChannelCore`,
vs. extending `Channel` or `ChannelCore` with a default implementation.
The protocol uses a primary associated type allowing channels to provide
typed access to the transport. E.g. this could be used in NIO Transport
Services to expose the underlying `NWConnection`, if desired.
The method itself is spelled with "unsafe", uses scoped access, and has
clear documentation that users must not violated any of NIOs assumptions
about the state of the underlying transport. It's very much not intended
for every day use. It being on `ChannelCore` should defer users of the
low-level API, since `Channel._channelCore` is marked as for NIO
internal use, and the public `withUnsafeTransportIfAvailable(_:)` will
take care of the runtime checks for channels that have opted into this
API.
## Result
- New opt-in API for channel implementations to expose their underlying
transport
- All socket-based channels from NIOPosix now expose the underlying
socket file descriptor
- New API
`ChannelPipeline.SynchronousOperations.withUnsafeTransportIfAvailable(_:)`
for users
---------
Co-authored-by: Agam Dua <agam_dua@apple.com>
### Motivation
Issue #2773 reports a problem where channels can receive
`channelInactive` before `channelActive`. This breaks expectations and
should not happen. Instead of sending them in the wrong order, this PR
suppresses both of them in those cases.
### Modifications
* Add a test to reproduce the problematic behavior.
* Update the state machine to split the active state into two. This
decouples succeeding the promise from sending the signal. Transiting to
closing only sends `channelInactive` when originating from the state
that sent `channelActive`.
### Result
Address #2773.
Edit: Updated modifications to reflect latests commit.
Adds three new system call wrappers for the `symlinkat`, `renameatx_np`,
and `unlinkat` system calls.
### Motivation:
Related to https://github.com/apple/swift-nio/issues/3403 and
https://github.com/apple/swift-nio/pull/3470. This PR adds syscall
wrappers needed to atomically overwrite existing files or symlinks at
the destination during copy operations. On Linux, atomic overwrites
require a "copy to temp file, then rename" strategy. We use the `*at`
family of syscalls (which operate relative to directory file
descriptors) to avoid TOCTOU race conditions.
### Modifications:
1. Adds three system call wrappers for the `symlinkat`, `renameatx_np`,
and `unlinkat` system calls.
2. Adds related tests
3. Updates the `FileSystemError` for `symlink` and `unlink` to take in
the system call name to allow for the `*at` names to be passed.
Ports NIOThreadPoolTest in NIOPosix from XCTest to Swift Testing.
### Motivation:
Tests should use the latest Swift Testing framework when possible.
### Modifications:
- Ported `NIOThreadPoolTest` from XCTest to Swift Testing
- Updated test implementation from Dispatch to Swift Concurrency as
needed to support test functionality
### Result:
All tests continue to pass, NIOThreadPoolTest now has more modern Swift
Testing syntax.
Port `EventLoopFutureTest` to Swift Testing. Includes some adjustments
to ensure tests are ran from the event loop, among other minor changes
### Motivation:
Tests should use the latest Swift Testing framework when possible.
### Modifications:
- Ported `EventLoopFutureTest ` from XCTest to Swift Testing
- Consolidated instantiations of `EmbeddedEventLoop()` into a private
function called `makeEventLoop` to allow for easier injection of a
different loop from a single location.
- Migrated some `.wait` usages to `.get` to allow tests to run async.
### Result:
All tests continue to pass, EventLoopFutureTest now has more modern
Swift Testing syntax.
We have a number of copies of `UnsafeTransfer` and two copies of
`UnsafeMutableTransferBox` in our code base. Before introducing more of
those, lets centralize to just one using a `package` access modifier.
### Motivation:
Channels based on `BaseSocketChannel` throw in both `getOption` and
`setOption` if the channel has been closed, since the `setsockopt` will
fail. However, the current behavior of `EmbeddedChannel` is options
remain writable and readable on closed channels.
There are situations where we'd like to be able to model the runtime
behaviour of the real channel in tests, e.g. to test this fix:
https://github.com/apple/swift-nio-extras/pull/304.
### Modifications:
- Add API to enable throwing in `EmbeddedChannel.getOption` and
`.setOption` if channel is closed.
- Add a test for this new behavior.
### Result:
- New API to enable throwing in `EmbeddedChannel.getOption` and
`.setOption` if channel is closed.
- No observable change for existing users of `EmbeddedChannel`.
### Motivation:
In reviewing a copy of this file in swift-log, @czechboy0 noticed that
the call to `pthread_mutexattr_destroy` is missing. Since
pthread_mutexattr_t is like allocated on the stack rather than heap on
most platforms, this is likely not a memory leak. But for correctness
the missing destroy call should be added.
This change is the start of a resolution
[requested](https://github.com/apple/swift-log/pull/398#discussion_r2689459360)
in a corresponding Lock rollout in swift-log
### Modifications:
- Added missing call to `pthread_mutexattr_destroy`
- Duplicated test for `NIOLock` to also test `Lock`, as a sanity test.
### Result:
The new sanity test passes. If there are other ways this change can be
realistically verified as safe and proper, please feel free to provide
feedback in the PR.
`NIOTypedHTTPClientUpgradeHandler.handlerAdded` will write upgrade
request if the channel is already active
### Motivation:
This has been added to make it easier to implement a websocket client
that supports proxies. If the upgrade handler is added after the proxy
connect has been processed previously nothing would happen.
### Modifications:
- Added new function
`NIOTypedHTTPClientUpgradeHandler.writeUpgradeRequest()` function. Call
this from `channelActive` and also from `handlerAdded` if the channel is
already active.
- Added test `testUpgradeHappensAfterHandlerAdded`
### Result:
NIOTypedHTTPClientUpgradeHandler now also works if it is added to a
channel after the channel is active
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Add homeDirectory accessor to FileSystem
### Motivation:
Addresses #3381 by adding a `homeDirectory` property to FileSystem,
equivalent to `FileManager.default.homeDirectoryForCurrentUser`.
### Modifications:
- Added `homeDirectory` property to `FileSystemProtocol` and implemented
in `FileSystem`
- Implementation checks `HOME` environment variable first, falls back to
`USERPROFILE` on Windows, or uses `getpwuid_r(3)` on POSIX systems
- Added system call wrappers (`system_getuid`, `libc_getpwuid_r`) with
proper platform guards
- Added `FileSystemError.getpwuid_r()` error helper
### Result:
Users can now access the home directory via `FileSystem.homeDirectory`,
returning a `FilePath` asynchronously. Follows the same pattern as
`currentWorkingDirectory` and `temporaryDirectory`.
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
Currently, pending consumer closures remain in the
`{in}{out}boundBufferConsumer` queues of `EmbeddedChannelCore` even
after the channel closes. It is also possible to enqueue consumers
*after* the channel closes. In these cases, the consumer closures will
never be invoked and this can lead to unfavourable behaviour, as
observed in `NIOAsyncTestingChannel`'s `waitFor{In}{Out}boundWrite`
methods (the only places these queues are currently used).
`NIOAsyncTestingChannel`'s `waitFor{In}{Out}boundWrite` methods complete
a continuation *inside* the consumer closure. In the cases described
above, the continuation never completes and therefore
`waitFor{In}{Out}boundWrite` never returns.
### Modifications:
- Updated the element type in `EmbeddedChannelCore`'s
`{in}{out}boundBufferConsumer` from `(NIOAny) -> Void` to
`(Result<NIOAny, Error>) -> Void`.
- This is so that the `.failure` case can be used to notify the consumer
closure that the channel has closed.
- Changed the visibility of the `{in}{out}boundBufferConsumer`
properties from `internal` to `private` in order to prevent the queues
from being accessed and being appended to without the call site
considering whether the channel has been closed.
- Added new `internal` methods named
`enqueue{In}{Out}boundBufferConsumer(_:)` which take the consumer
closure as an argument and only append to the corresponding queue if the
channel isn't closed.
- If the channel is closed, the consumer closure is invoked immediately
with `.failure(ChannelError.ioOnClosedChannel)`.
- Updated `EmbeddedChannelCore`'s `close0` method to return a
`.failure(ChannelError.ioOnClosedChannel)` result to each closure in
`{in}{out}boundBufferConsumer` and empty both buffers.
- Updated `NIOAsyncTestingChannel`'s `waitFor{In}{Out}boundWrite` to
throw an error in the continuation upon receiving a `.failure` result.
- Added associated test cases.
### Result:
`EmbeddedChannelCore`'s `{in}{out}boundBufferConsumer` queues can be
used more safely: all pending closures will be invoked upon channel
close. As a result, `NIOAsyncTestingChannel`'s
`waitFor{In}{Out}boundWrite` no longer indefinitely blocks when the
channel closes.
Fix coreCount on Linux when using cgroup v2 with CFS throttling disabled
### Motivation:
When using `swift-nio` on Linux with cgroup v2 enabled, but with CFS
throttling disabled, it falls back to attempting to read the cpuset file
at the cgroup v1 path. This does not exist, which in turns falls back to
returning `_SC_NPROCESSORS_ONLN`, which will return the total number of
cores available (ignoring cgroup assignments).
This has unexpected effects, including the default behaviour of starting
the `MultiThreadedEventLoopGroup.singleton` with significantly more
event loops than cores available to the workload.
### Modifications:
- Adds `SystemCalls.statfs`, and associated constants, to determine the
cgroup version.
- Adds `Linux.cgroupVersion()` API to expose cgroup version.
- Adds `Linux.cgroupV2MountPoint` variable to determine the cgroup v2
mount point.
- Adds `Linux.cpuSetPathV1` & `Linux.cpuSetPathV2` (and
`Linux.cpuSetPath` convenience) variables to determine the correct cpu
set path.
- Alters `System.coreCount` to use the appropriate logic from above to
ensure that `cpuset.cpus` is parsed from the correct location.
### Result:
`Linux.coreCount` should correctly parse and return the core count on
Linux cgroup v2 enabled systems (when CFS throttling is disabled), while
maintaining correctness for other configurations.
---------
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Add ByteBuffer.readableBytesUInt8Span
### Motivation:
Provide access to readableBytes as a Span<UInt8>
### Modifications:
Added computed property `ByteBuffer.readableBytesUInt8Span`. I also
attempted to add `ByteBuffer.mutableReadableBytesUInt8Span` but due to
an apparently faulty exclusivity issue I couldn't get this to work. See
https://github.com/swiftlang/swift/issues/81218.
### Result:
You can access the readable bytes of a ByteBuffer as a Span<UInt8>
Motivation:
This is a follow up to 5bf841dd to handle the yield task being cancelled
between dropping the lock and re-acquiring it a moment later in the
'withContinuation' block.
Modifications:
- Add an extra cancellation check when yielding with a continuation.
Result:
Fewer issues
### Motivation:
`NIOAsyncTestingChannel` stored its `localAddress` and `remoteAddress`
in a locked storage on itself for thread safety, however in doing so
left us open to bugs because a handler grabbing the addresses of the
context had no visibility of the values.
### Modifications:
Reach into `EmbeddedChannelCore` for the addresses instead of storing
them on the `NIOAsyncTestinghannel`. I also considered a delegate
approach where the `EmbeddedChannelCore` could offload the
responsibility for storing the values back to the
`NIOAsyncTestingChannel` but it was complicated and of questionable
value.
### Result:
* The correct address values are seen no matter how they are obtained.
* We probably take a performance hit locking the values in this way but
this is testing code so probably not the end of the world.
When having a state machine inside the `NIOLoopBoundBox` we currently
check the EL when reading and writing. This is unnecessary. Because of
this, this PR introduces a new `withValue` method, that allows users to read and
write the value inside the NIOLoopBoundBox while only paying the cost
for the EL check once.
Motivation:
NIO has existing GRO support. This GRO support is applied at Channel
scope, which makes it somewhat less than ideal, as it forces the
datagram sizes to be accessed using socket options. In real applications
this is less desirable than being able to do this on a per-superbuffer
context.
Linux supports this already by using recvmsg/recvmmsg control data. We
just need to wire this up in NIO. We can re-use the existing metadata
fields on AddressedEnvelope.
Modifications:
- Add a new ChannelOption to extra metadata
- Reject setting this option on non-Linux devices.
- On Linux, use this to load the control data.
- Added new tests that validate the behaviour is correct.
Result:
Enable per-message GRO.
Motivation:
NIO has existing GSO support. This GSO support is applied at Channel
scope, which makes it somewhat less than ideal, as it forces the
datagram sizes to be known statically ahead of time. In real
applications this is less common than being able to do this on a
per-superbuffer
context.
Linux supports this already by using sendmsg/sendmmsg control data. We
just need to wire this up in NIO.
An extension to this is that we can also do per-message GRO in Linux.
I'll tackle this in a later patch to keep the diffs small.
Modifications:
- Adding a new field on AddressedEnvelope Metadata.
- Reject setting this field on non-Linux devices.
- On Linux, use this to set the control data.
- Added new tests that validate the behaviour is correct.
Result:
Enable per-message GSO.
Motivation:
Users would like to be able to access the underlying memory of a
ByteBuffer, as evidenced by the plethora of `withUnsafe*` methods that
ByteBuffer has. As Swift 6.2 has introduced some initial APIs for safe
memory access to underlying storage, we should offer similar APIs on
ByteBuffer to enable users to get safer access to that storage.
For now, the obvious APIs to be able to supplement are:
- withUnsafeReadableBytes
- withUnsafeMutableReadableBytes
- writeWithUnsafeMutableWritableBytes
We can also offer some new APIs to allow initializing a buffer directly
from an OutputSpan.
Note that we can only do this because the Language Steering Group has
pinky promised that they will not break the "Lifetimes" experimental
feature: see
https://forums.swift.org/t/experimental-support-for-lifetime-dependencies-in-swift-6-2-and-beyond/78638
for more details. We are taking them at their word, and so we are
enabling that feature.
Modifications:
Many new methods and tests.
Result:
Safer access.
Motivation:
'copyItem' can be used to copy files/directories from a source to a
destination address and fails if the destination already exists. The
parallel version of it can wedge if a directory is being copied and the
directory can't be created at the destination path (for example, if a
file already exists at the destination).
The parallel copy works by feeding tasks (e.g. "copy this item from here
to there") into an async sequence and processing each task in a separate
child task within a task group. When copying directories a new directory
is created at the destination path and then each file within the source
directory is emitted as a separate item to process. Another item is sent
on the async sequence to indicate when the source directory is finished
with which may result in finishing the async sequence.
However, if creating the destination directory fails then that event
isn't sent. This results in the calling code never terminating the async
sequence and causes 'copyItem' to wedge.
Modifications:
- Use non-idempotent directory creation (copy item should fail if the
destination already exists, this was a regression introduced in
7124f096).
- Check whether to continue when a dir can't be created but always emit
the end of dir event
- If terminating when the task group hasn't reached its width limit then
check child tasks for errors
Result:
Parallel copy doesn't wedge
On filesystems without symlink support for Windows, the symlinked test
helper at is materialized as a plain text file containing the relative
path, which breaks compilation with errors like:
```
expressions are not allowed at the top level
cannot find 'assertNoThrowWithValue' in scope
```
This change inlines the contents, restoring the intended shared test
utilities for the NIOHTTP1 test target. This helps Windows compile the
Test target