Commit Graph
2167 Commits
Author SHA1 Message Date
Fabian Fett 57c0a08a33 Speed up the tests (#3601)
### 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.
2026-05-20 10:12:53 +00:00
Fabian Fett b24872d3aa Merge commit from fork
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.
2026-05-20 10:00:56 +01:00
Fabian Fett 87f935b70c Merge commit from fork
This patch adds additional validation that we don't overflow the ByteBuffers capacity (which is capped at UInt32.max).
2026-05-20 09:58:46 +01:00
Fabian Fett dd16365724 Merge commit from fork
- Ensure HTTP Request Uri and Method only contain allowed bytes
- Ensure HTTP Response Reasons only contain allowed bytes
2026-05-20 09:56:46 +01:00
Shaurya SinghandCory Benfield 6338e9fb5e Fix doubled 'the' in NIOAsyncChannel upgrade docs (#3600)
## Summary

Trivial typo fix in the Swift Concurrency user-facing documentation.

In
[`Sources/NIOCore/Docs.docc/swift-concurrency.md`](https://github.com/apple/swift-nio/blob/main/Sources/NIOCore/Docs.docc/swift-concurrency.md),
the NIOAsyncChannel websocket-upgrade walkthrough reads:

> switch over the the `upgradeResult`. Importantly, we have to `await`
the

Drops the duplicate "the".

## Test plan

- [x] `grep -rEn '\b(the the|of of|in in|and and|that that|is is|to
to)\b' --include='*.swift' --include='*.md' Sources` — exit 1 after the
fix (was the only hit before).

## Scope

One-character change in one Markdown file. No code, no behavior, no API.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-05-18 19:23:35 +00:00
Mads OdgaardandCory Benfield 0ee0fd1b38 [Android] Gate getifaddrs behind API 24 availability (#3506)
The `getifaddrs` is only available on Android API 24+. So, to make
`swift-nio` compile on API 23, we need to add `@available` annotations
to the functions that use it. Which are just the two interface enumerate
functions.

### Result:

`swift-nio` can be compiled for Android 23.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-05-18 12:25:24 +01:00
PAVANSAI KUMAR ALLADIandPavan sai kumar alladi 9f506606a9 Add dnsResolver configuration option for randomized DNS load balancing (#3577)
### 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>
2026-05-17 21:53:29 +00:00
David SternandDavid Stern c077074e9f Allow concurrent createDirectory calls with shared ancestor paths (#3598)
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>
2026-05-15 08:11:37 +00:00
Francesco Paolo Severino 32f395bc91 Add helpers for reading length-prefixed things (#3589)
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.
2026-05-12 11:53:10 +01:00
Rafael Cepeda ad37b30223 Makes NIOCore target compile on FreeBSD (#3587)
This PR is a step towards having full support for FreeBSD in SwiftNIO.
It builds on #3494 to enable full compilation of the NIOCore target.

### Motivation:

Currently, SwiftNIO doesn't not compile on FreeBSD. This PR ensures that
at least the **NIOCore** module compiles correctly on FreeBSD.

### Modifications:
* Make `swift build --target NIOCore` work on FreeBSD.

### Result:

Using the available Swift FreeBSD x86_64 toolchain, it is now possible
to run `swift build --target NIOCore` successfully.
2026-05-11 19:56:51 +01:00
Fabian Fett 37e191d35b Strip Transfer-Encoding when Content-Length is present in HTTPEncoder (#3583)
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.
2026-05-06 10:14:09 +00:00
Johannes Weiss 1c8b29ce10 make internal FTSInfo take CInt (#3586)
### Motivation:

Internally, `FTSInfo` always casted up to `CInt` from `UInt16` but for
some reason it only accepted `UInt16`. Let's add a `CInt` constructor
too.

### Modifications:

- Make internal `FTSInfo` constructible from `CInt` and `UInt16`.

### Result:

- Slightly better platform compatibility
- Possibly fewer casts
2026-05-05 15:09:00 +00:00
38000794f2 Split FoundationEssentials extensions from NIOFoundationCompat (#3567)
Split FoundationEssentials extensions from NIOFoundationCompat

### Motivation:

Resolves #3038 

### Modifications:

Split NIOFoundationCompat into two and only import FoundationEssentials
and NIOFoundationEssentialsCompat where appropriate.

### Result:

ByteBuffer/Codable extensions can be used without vendoring the code or
linking to Foundation.

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Fabian Fett <fabianfett@apple.com>
2026-04-21 18:58:43 +01:00
mananandSi Beaumont cd6710454f Preserve getaddrinfo error code in SocketAddressError (#3558)
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>
2026-04-15 13:08:59 +00:00
Alex TowellandClaude Opus 4.6 98f8824da0 Handle EPERM as permissionDenied in open syscall error mapping (#3560)
## 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>
2026-03-25 15:59:06 +00:00
Cory Benfield bdf004b44f Enable thread-pools to be pinned to CPUs (#3557)
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.
2026-03-23 08:20:33 +00:00
Kenta KuboandCory Benfield 795162f1bc Add partial support for FreeBSD (#3494)
This PR adds support for FreeBSD to the `CNIOSHA1` target and the
`NIOConcurrencyHelpers` target.

### Motivation:

This PR is partial because the `NIOCore` target still can't be built,
and the existing PR #3398 includes almost the same changes too.

However, #3398 is a little bit old. Besides, the source code in
`NIOConcurrencyHelpers` is used in other repositories now, for example:

- https://github.com/apple/swift-log/pull/398
- https://github.com/apple/swift-log/pull/387 was merged before
swift-nio is fixed.

So I think it's important to fix `NIOConcurrencyHelpers` first, even if
the entire swift-nio is yet to be fixed.

### Modifications:

- Make `swift build --target NIOConcurrencyHelpers` work on FreeBSD
- Make `swift build --target CNIOSHA1` work on FreeBSD

### Result:

The following commands finished successfully.

```shell
swift build --target NIOConcurrencyHelpers
swift build --target CNIOSHA1
```

Environment:

- FreeBSD 15.0-RELEASE-p1 x86_64
- [Swift on FreeBSD Preview
toolchain](https://forums.swift.org/t/swift-on-freebsd-preview/83064)
  ```
  Swift version 6.3-dev (LLVM b58b2a34d509492, Swift cf535d8b998d09b)
  Target: x86_64-unknown-freebsd14.3
  Build config: +assertions
  ```

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-03-18 10:30:06 +00:00
Cory Benfield b9d20d3476 Benchmarks for channel pipeline creation (#3531)
Motivation:

Creating channel pipelines is a fairly expensive operation. We should
try to know how expensive.

Modifications:

Add benchmarks for ChannelPipeline setup.

Result:

We'll know more.

Some results in a Linux VM on my M4 Max laptop:

```
=================
NIOCoreBenchmarks
=================

ChannelPipeline.init(0 handlers)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │         3 │         3 │         3 │         3 │         3 │         3 │         3 │      1000 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │       156 │       177 │       214 │       322 │       367 │       989 │      2148 │      1000 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

ChannelPipeline.init(1 handler)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │         5 │         5 │         5 │         5 │         5 │         5 │         5 │      1000 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │       269 │       290 │       301 │       463 │       501 │       583 │       611 │      1000 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

ChannelPipeline.init(3 handlers)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │         9 │         9 │         9 │         9 │         9 │         9 │         9 │      1000 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │       477 │       521 │       540 │       553 │       574 │       817 │       907 │      1000 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

ChannelPipeline.init(10 handlers)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │        23 │        23 │        23 │        23 │        23 │        23 │        23 │      1000 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │      1263 │      1363 │      1404 │      1679 │      2146 │      2482 │      3133 │      1000 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛
```
2026-03-16 11:23:45 +00:00
Cory Benfield 5b3cab2bb0 Make MTELG's support for CPU pinning public (#3543)
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_.
2026-03-09 16:58:55 +00:00
George Barnett 57a73c653b Deprecate System.udpMaxSegments (#3541)
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.
2026-03-09 15:46:31 +00:00
Stepan Ulyanin 182ae0b4f9 Add the replaceExisting to the _NIOFileSystem copyItem (#3535)
Adds the changes from https://github.com/apple/swift-nio/pull/3508 to
the `_NIOFileSystem`.
### Motivation:

We have added capability to overwrite regular files and symbolic links
to `NIOFS` `FileSystem.copyItem` in
https://github.com/apple/swift-nio/pull/3508. Now we want to port the
same logic to `_NIOFileSystem`.

### Modifications:

- Adds a new `FileSystemProtocol.copyItem` requirement with
`replaceExisting: bool` parameter along with a default implementation.
- Adds an implementation of the new `FileSystemProtocol.copyItem`
requirement to `_NIOFileSystem`'s `FileSystem` struct for regular files
and symbolic links.

### Notes

It seems that the tests for `FileSystem` are only in `NIOFS` - so no
tests are added in this PR.
2026-03-09 10:59:41 +00:00
Mihai ChioreanandCory Benfield acf9bbe0fd Support scoped IPv6 addresses in SocketAddress.init(ipAddress:port:) (#3525)
### 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>
2026-03-06 08:49:57 +00:00
Fabian Fett ada5f7690b Improve NIOAsyncChannel performance with UnsafeContinuations (#3521)
Let's improve NIOAsyncChannels performance, by using UnsafeContinuations
instead of CheckedContinuations.

### Motivation:

We want to improve the performance for our async APIs.

### Modifications:

- Introduce a new typealias `NIOUnsafeContinuation` that behaves like a
UnsafeContinuation in release mode and like a CheckedContinuation in
debug mode.
- Use the `NIOUnsafeContinuation` inside the `NIOAsyncWriter`
- Use the `NIOUnsafeContinuation` inside the
`NIOThrowingAsyncSequenceProducer`

### Result:

Fewer allocations
2026-03-04 11:09:34 +00:00
Rick Newton-Rogers 83509ed06d ByteBuffer custom allocator support (#3526)
### 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
2026-03-02 10:52:17 +00:00
Stepan Ulyanin fff2515d6e Add symlinkat, renameatx_np, and unlinkat system call wrappers to the _NIOFileSystem module (#3524)
Ports the added system calls from `NIOFS` (from
https://github.com/apple/swift-nio/pull/3505) to `_NIOFileSystem`:

> Adds three new system call wrappers for the `symlinkat`,
`renameatx_np`, and `unlinkat` system calls.

### Motivation:

`_NIOFileSystem` module is around for backward compatibility - hence, we
are porting the new feature to it.

### Modifications:

Exactly same as in https://github.com/apple/swift-nio/pull/3505 but
applied to the `_NIOFileSystem`:

> 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.
2026-03-02 10:00:35 +00:00
Cory Benfield d38344d14b Improve the performance of looking up the current SEL (#3530)
Motivation:

Right now we store our selectable event loop reference in a NIO
ThreadSpecificVariable. That's nice enough, but this has become a hot
code path in cases where users are using the complete concurrency
override. In those cases, the ThreadSpecificVariable forces us to both
call `pthread_getspecific` and to end up needing to perform a dynamic
cast to our expected type.

These dynamic casts are costly: in one sample project where we spent
fully 7.84% of the runtime in dispatching tasks onto the EL, the cost of
that dynamic cast _alone_ was 0.5% of the runtime, with
pthread_getspecific being another 0.2%. This is 10% of the cost of
dispatching a job, entirely unnecessarily.

Modifications:

- Use some fancy C thread-locals, which have much better performance:
see #3302 for more on that.
- Use Unamanged to pass the self reference into and out of the
thread-local, avoiding dynamic casts.

Result:

Further improved performance for concurrency takeover.

Before this change:

```
any() from event loop thread (fast path): 30.654833 ns/iteration
any() from outside (fallback path): 17.881084 ns/iteration
```

After this change:

```
any() from event loop thread (fast path): 11.571958 ns/iteration
any() from outside (fallback path): 17.52175 ns/iteration
```

Nearly a 3x speedup on that particular operation. Not so bad.

Note the irony that before this change it was actually more expensive to
call `any` from _on_ an EL thread than off it. Both calls had to call
pthread_getspecific, which means all of this cost was the runtime type
conversion.
2026-02-27 16:46:58 +00:00
Cory Benfield 41fc4a7aff Make concurrency take over cheaper (#3527)
Motivation:

When using concurrency takeover, we currently spend nearly half the
runtime checking if our SelectableEventLoop has an enqueue function. We
know it does, but we just haven't given the compiler enough evidence.
This patch rewrites the code to prove it to the compiler.

Modifications:

- Expose internal functions without erased types on MTELG
- Use these internal functions, and call directly to SEL, eliminiating
the as!.

Result:

Massive perf improvement in task enqueueing.
2026-02-27 13:58:35 +00:00
Stepan UlyaninandGeorge Barnett be8fdc13c0 Allow to copy files and symlinks while overwriting the destination (#3508)
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>
2026-02-18 08:57:33 +00:00
Si BeaumontandAgam Dua b0e024792a Add opt-in API for channels to expose their underlying transport (#3509)
## 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>
2026-02-17 16:12:58 +00:00
Fabian Fett 2fdda6c78e Fix benchmark succeeding – even though Benchmark build failed (#3502)
### Motivation:

Currently if there is an error in the Benchmark targets, that prevents
the Benchmark to build correctly, we still get a CI success.

### Modifications:

- Check for the threshold changed error

### Result:

- More reliable CI
2026-02-17 10:30:44 +00:00
Raphael d948192838 Don't send (in)active when channel closes directly (#3497)
### 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.
2026-02-11 15:46:19 +00:00
Kushal Pisavadia 9b92dcd5c2 Replace ConditionLock with wake-one signalling NIOThreadPoolWorkAvailable (#3507)
**TL;DR** This change leads to a ~90% reduction in observed system CPU
time for some use cases by waking a single thread, instead of all idle
threads.

# Changes

Inlining the commit messages here.

## Add NIOThreadPool submit throughput benchmarks

### Motivation

`NIOThreadPool` had no benchmarks measuring submit overhead. This makes
it difficult to evaluate the cost of signalling changes or to catch
latency regressions.

### Modifications

Add thread pool submit benchmarks, covering use cases with 4-thread and
16-thread pools.

### Result

`NIOThreadPool` submit throughput and context-switch overhead are now
tracked by benchmarks.

### Benchmark Results

<details>

```
NIOThreadPool.serial_wakeup(16 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        77 │        78 │        79 │        80 │        80 │        92 │        92 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │       106 │       107 │       108 │       109 │       110 │       116 │       116 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │      1649 │      1752 │      1768 │      1795 │      1826 │      1929 │      1929 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │      1701 │      1805 │      1821 │      1849 │      1879 │      1987 │      1987 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (ms) *   │        51 │        52 │        52 │        53 │        53 │        57 │        57 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │       167 │       177 │       178 │       181 │       183 │       200 │       200 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

NIOThreadPool.serial_wakeup(4 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        44 │        44 │        44 │        45 │        45 │        45 │        45 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │        65 │        65 │        65 │        66 │        66 │        67 │        67 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │       159 │       162 │       163 │       165 │       166 │       169 │       169 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │       178 │       182 │       183 │       185 │       186 │       190 │       190 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (ms) *   │        19 │        19 │        20 │        20 │        20 │        21 │        21 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │        76 │        79 │        79 │        80 │        80 │        82 │        82 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛
```

</details>

## Replace `ConditionLock` with wake-one signalling
`NIOThreadPoolWorkAvailable`

### Motivation

`NIOThreadPool` used `ConditionLock` which calls
`pthread_cond_broadcast` on every state change, waking all threads when
only one work item is enqueued. This causes a thundering-herd problem.

### Modifications

Add `NIOThreadPoolWorkAvailable` in NIOConcurrencyHelpers that uses
`pthread_cond_signal` (wake-one) for work submission and
`pthread_cond_broadcast` only for shutdown. Replace
`ConditionLock<_WorkState>` and the `_WorkState` enum in `NIOThreadPool`
with this new primitive.

### Result

Submitting a work item wakes exactly **one** thread instead of all
threads.

### Benchmark Results

<details>

```
NIOThreadPool.serial_wakeup(16 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        20 │        20 │        20 │        20 │        20 │        20 │        20 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │        40 │        40 │        40 │        40 │        40 │        40 │        40 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │        47 │        49 │        49 │        50 │        50 │        55 │        55 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │        57 │        58 │        59 │        60 │        61 │        67 │        67 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (ms) *   │        10 │        10 │        10 │        10 │        10 │        12 │        12 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │        54 │        55 │        56 │        56 │        57 │        65 │        65 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

NIOThreadPool.serial_wakeup(4 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        20 │        20 │        20 │        20 │        20 │        20 │        20 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │        40 │        40 │        40 │        40 │        40 │        40 │        40 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │        45 │        46 │        46 │        47 │        57 │        75 │        75 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │        54 │        55 │        56 │        57 │        68 │        87 │        87 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (μs) *   │      9055 │      9372 │      9478 │      9765 │     10887 │     12585 │     12585 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │        52 │        53 │        53 │        54 │        64 │       124 │       124 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛
```

</details>
2026-02-10 20:01:35 +00:00
Stepan Ulyanin db01d87942 Add symlinkat, renameatx_np, and unlinkat system call wrappers (#3505)
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.
2026-02-09 08:38:25 +00:00
Si Beaumont edad6d8a9b Clarify state and relationship of NIOFileSystem and _NIOFileSystem in API docs (#3504)
### Motivation:

`NIOFileSystem` currently exposes the same API as `_NIOFileSystem`,
which is not API stable. `NIOFileSystem`
was created in error, and its lack of underscore incorrectly implies API
stability. Users who are currently importing `NIOFileSystem` should
ideally move to `_NIOFileSystem`. However this isn't made clear in the
docs:

1. The README talks about the non-underscored `NIOFileSystem`.
2. There are no hosted API docs `NIOFileSystem`.
3. The hosted API docs for `NIO` point to the docs for `NIOFileSystem`
-- results in 404.

### Modifications:

- Update the README to refer to `_NIOFileSystem`.
- Update the hosted API docs for `NIO` to point to docs for
`_NIOFileSystem`.
- Add hosted API docs for `NIOFileSystem` with a statement explaining
the situation and pointing people to the docs
  for `_NIOFileSystem`.

### Result:

Clearer documentation on the state and relationship of the
`NIOFileSystem` and `_NIOFileSystem` modules.
2026-02-06 18:56:42 +00:00
Fabian Fett 6a6f7d7c33 Centralize UnsafeTransfer in NIOCore (#3492)
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.
2026-02-03 10:27:30 +00:00
Si Beaumont 37ffc4b8d5 Add API to enable throwing in EmbeddedChannel.getOption and .setOption if channel is closed (#3495)
### 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`.
2026-01-27 12:06:55 +00:00
scottmarchant 5bf0267df4 build: Elide NIOPosix for WASI platforms only (#3485)
### Motivation:

Packages that consume NIOPosix should be able to compile to WASI
platforms without special configurations. This change elides the
NIOPosix source from WASI platforms to simplify configuration.

Without this change:

```swift
dependencies: [
    // Without this PR, downstream packages must maintain exhaustive platform list to exclude `.wasi`:
    .product(
        name: "NIOPosix",
        package: "swift-nio",
        condition: .when(platforms: [
            .macOS,
            .macCatalyst,
            .iOS,
            .tvOS,
            .watchOS,
            .visionOS,
            .driverKit,
            .linux,
            .windows,
            .android,
            .openbsd,
            // .wasi // <-- Need to exclude this, because there is no exclusion list api for SPM conditionals
        ])
    ),
]
```

With this change:

```swift
dependencies: [
    // Without this PR, downstream packages can consume NIOPosix simply:
    .product(name: "NIOPosix", package: "swift-nio"),
]
```

### Modifications:

- Add compiler directives (`#if !os(WASI)`) to all source files in
NIOPosix

### Result:

Downstream packages can compile to wasm without manually excluding the
NIOPosix dependency.

### Testing performed

- Verified `swift build --swift-sdk wasm32-unknown-wasip1 --target
NIOPosix` compiles, which demonstrates proper elision of source files in
NIOPosix that aren't wasm-ready.
- Confirmed GitHub [checks
pass](https://github.com/PassiveLogic/swift-nio/actions/runs/21151341738).
2026-01-23 16:39:32 +00:00
scottmarchant 3f80264185 build: Elide NIOEmbedded for WASI platforms only (#3484)
### Motivation:

Packages that consume NIOEmbedded should be able to compile to WASI
platforms without special configurations. This change elides the
NIOEmbedded source from WASI platforms to simplify configuration.

Without this change:

```swift
dependencies: [
    // Without this PR, downstream packages must maintain exhaustive platform list to exclude `.wasi`:
    .product(
        name: "NIOEmbedded",
        package: "swift-nio",
        condition: .when(platforms: [
            .macOS,
            .macCatalyst,
            .iOS,
            .tvOS,
            .watchOS,
            .visionOS,
            .driverKit,
            .linux,
            .windows,
            .android,
            .openbsd,
            // .wasi // <-- Need to exclude this, because there is no exclusion list api for SPM conditionals
        ])
    ),
]
```

With this change:

```swift
dependencies: [
    // Without this PR, downstream packages can consume NIOEmbedded simply:
    .product(name: "NIOEmbedded", package: "swift-nio"),
]
```

### Modifications:

- Fix compiler directive using in AsyncTestingChannel.swift to include
an extension

### Result:

Packages can compile to wasm without manually excluding the NIOEmbedded
dependency.

### Testing performed

- Verified `swift build --swift-sdk wasm32-unknown-wasip1 --target
NIOEmbedded` compiles, which demonstrates proper elision of source files
in NIOEmbedded that aren't wasm-ready.
- Confirmed GitHub [checks
pass](https://github.com/PassiveLogic/swift-nio/actions/runs/21151287289).
2026-01-22 18:58:24 +00:00
scottmarchant c337170d91 chore: Elide mutex variable from Lock class when it is unused (#3483)
### Motivation:

In reviewing a copy of this file in swift-log, @czechboy0
[noticed](https://github.com/apple/swift-log/pull/398#discussion_r2685605800)
that the `mutex` variable is essentially unused and unnecessarily
allocated for certain conditions. It is possible the compiler elided
usage. But given the unconditional variable reference in the `deinit`,
the compiler may not be able to.

This change ensures the `mutex` property is completely elided except in
the conditions where it is used.

### Modifications:

- Adjusted compiler directive pattern to completely elide the `mutex`
property for conditions where it would be unused.
- Adjusted `deinit` to avoid referencing `mutex` unless it is compiled
into the `Lock` class

### Result:

The `mutex` property is no longer allocated or even compiled into the
`Lock` class for unsupported configurations. All unit tests and checks
pass.

### Research:

The `deinit` used to have a blanket call to `mutex.deallocate()`. This
has been moved into the platform-specific checks within the `deinit`.
This allows complete elision of the `mutex` property altogether. The
`_runtime(_multithreaded)` condition [appears to be rooted to this
implementation](https://github.com/swiftlang/swift/blob/ffc51b914602765c5d680241796dbd3c3711fa6b/lib/Basic/LangOptions.cpp#L490).
Diving deeper, all [operating systems in this
list](https://github.com/swiftlang/swift/blob/ffc51b914602765c5d680241796dbd3c3711fa6b/lib/Basic/LangOptions.cpp#L554)
except for UnknownOS and WASI result in `_runtime(_multithreaded)`
returning true. That means that `OpenBSD` (and many other operating
systems besides windows) were almost certainly using the `#elseif
(compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) &&
_runtime(_multithreaded))` condition in the `deinit`. In conclusion,
moving `mutex.deallocate()` up into the conditional clauses inside
`deinit` should be identical to the previous implementation for all
operating systems except `llvm::Triple::UnknownOS`. And
`llvm::Triple::UnknownOS` is likely not to have every compiled anyways
due to the [check on line
32](https://github.com/apple/swift-nio/blob/main/Sources/NIOConcurrencyHelpers/lock.swift#L32).

So in summary, it is expected that this clean up will compile identical
to the previous implementation for all platforms except WASI platforms
that don't have pthread support. For non-pthread WASI platforms, the
unused `mutex` is properly elided from compilation altogether.

### Testing Done:

- Confirmed that unit tests pass locally using Xcode
- Verified [PR checks
pass](https://github.com/PassiveLogic/swift-nio/actions/runs/21149729751)
2026-01-22 17:57:10 +00:00
3405691582 233f61bc2c Initialize the mutexattr before use. (#3482)
As observed by @kkebo, this was missing from the implementation.

### Motivation:

Correct pthread API usage. 

### Modifications:

Initialize the pthread_mutexattr_t with pthread_mutexattr_init before
passed to pthread_mutex_init.

### Result:

Even though this lock API appears to be deprecated, we'll correct the
usage anyway. The non-deprecated NIOLock class doesn't have this
problem.
2026-01-19 18:18:38 +00:00
scottmarchant 6ce9173261 fix: Ensure pthread_mutexattr_t is properly cleaned up with pthread_mutexattr_destroy in Lock (#3480)
### 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.
2026-01-19 08:13:02 +00:00
Adam FowlerandCory Benfield 61053a00bb NIOTypedHTTPClientUpgradeHandler will write Upgrade request on handlerAdded if active (#3473)
`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>
2026-01-14 11:40:00 +00:00
Joseph HeckandCory Benfield 6b33489e64 Updates to present docs on _NIOFileSystem (#3477)
This re-enables documentation lost during refactoring work, under the
target _NIOFileSystem

resolves #3474 

### Motivation:

During the refactoring of NIOFileSystem and recent Swift updates, the
mechanism to "shadow" symbols using `@_exported import` has stopped
working for documentation and imports for symbols, which means that
_NIOFileSystem is the target that needs to host the documentation for
this (for now)

### Modifications:

Moves DocC catalog into _NIOFileSystem target, and updates
disambiguation hashes on overloaded symbols in order to verify no
warnings are presented while generating documentation.
Updates .spi.yml to present _NIOFileSystem instead of NIOFileSystem

### Result:

Previous documentation should be available again, although at a slightly
different URI structure within Swift Package Index.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-01-13 14:22:46 +00:00
Karan LokchandaniandCory Benfield 608e511d7a Add homeDirectory accessor to FileSystem (#3471)
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>
2026-01-12 15:10:25 +00:00
Karan Lokchandani 4a9a971110 docs: String(buffer:) needs to mention that it will always succeed (#3476)
### Motivation:
The documentation for String(buffer:) initializer does not clearly
indicate
that this operation will always succeed, which may leave developers
uncertain
about error handling requirements.
fixes: https://github.com/apple/swift-nio/issues/3449

### Modifications:
Updated the documentation for String(buffer:) to explicitly mention that
the initialization will always succeed.

### Result:
Developers will have clearer understanding that String(buffer:) is a
safe
operation that does not require error handling.

Signed-off-by: Karan <karanlokchandani@protonmail.com>
2026-01-08 15:58:15 +00:00
aryan-25 5dc3b4ba4a Cancel pending in/outbound consumers in EmbeddedChannelCore upon channel close (#3464)
### 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.
2026-01-06 17:52:06 +00:00
e3d5c560e0 Fix coreCount on Linux when using cgroup v2 with CFS throttling disabled (#3462)
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>
2026-01-05 14:26:21 +00:00
Johannes Weiss 1268babbc1 Allowlist 6.3 to be allowable for Swift Concurrency takeover (#3467)
Make 6.3 fast
2025-12-19 13:19:04 +00:00
aryan-25 a1605a3303 Use explicit class name in all Self.[un]wrap{In}{Out}bound{In}{Out} calls (#3463)
### Motivation:

Swift does not currently generic specialize static methods on final
classes that have no parent classes when the method is implemented in a
protocol. This means that calling such methods through `Self` will not
involve a generic specialization, whereas using the explicit type name
will.

This pattern manifests in the `[un]wrap{In}{Out}bound{In}{Out}` static
methods defined in the
[`ChannelInboundHandler`](https://github.com/apple/swift-nio/blob/27146d484478b1bb0f150e848758f3a34ed9cbd0/Sources/NIOCore/TypeAssistedChannelHandler.swift#L60)
and
[`ChannelOutboundHandler`](https://github.com/apple/swift-nio/blob/27146d484478b1bb0f150e848758f3a34ed9cbd0/Sources/NIOCore/TypeAssistedChannelHandler.swift#L95)
protocols and their use from all channel handler classes. As such, we
should replace the `Self` part in all
`Self.[un]wrap{In}{Out}bound{In}{Out}` calls with the explicit class
name.

### Modifications:

Replaced all `Self.[un]wrap{In}{Out}bound{In}{Out}` calls to use the
explicit class name.

### Result:

Eliminates unnecessary overhead.
2025-12-15 17:36:11 +00:00
Adam Fowler 888f4affd6 Add ByteBuffer.readableBytesUInt8Span (#3458)
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>
2025-12-05 15:32:17 +00:00