mirror of
https://github.com/apple/swift-nio
synced 2026-11-28 05:14:23 +00:00
2.102.0
3059
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
a931f2c1de |
docs: Document that ByteBuffer is a value type (#3676)
Fixes #3037 Co-authored-by: Wasim <wasim@example.com>2.102.0 |
||
|
|
7800d84cba |
Add API to get the result of an isolated ELF, if available (#3721)
Motivation: A number of NIO APIs are asynchronous and return futures but have synchronous implementations. If a caller wants to operate on this they need to register a callback with the future and then operate on the result. However, now that we have an isolated view on the event loop future we can provide a fast path: just check whether the result is already present. This is particularly helpful for channel initializers which are typically synchronous. Using the fast path means calls can avoid an escaping closure from registering a callback on the future. Modifications: Add three new APIs to the isolated event loop future: - `result` which returns the underlying `Result<Value, Error>` or `nil` if it hasn't been completed yet - `value` which call `try result.get()`, and - `isComplete` Result: APIs for accessing the result of an ELF from its isolated view if it's already completed |
||
|
|
385c1a7d48 |
[Windows] Implement sendmmsg (#3699)
### Motivation: `CNIOWindows_sendmmsg` was a stub that asserted and then called `abort()`, so any code path reaching it took the whole process down: ``` Assertion failed: !"sendmmsg not implemented", file Sources\CNIOWindows\shim.c, line 26 ``` ### Modifications: Winsock has no `sendmmsg`, so emulate it by sending the messages one at a time — exactly what the Darwin shim does for the same reason. Error semantics match the Darwin implementation: a failure on the first message is reported to the caller. ### Result: Further progress on windows. Windows-only; no other platform is affected. --------- Co-authored-by: Fabian Fett <fabianfett@apple.com> |
||
|
|
48119dbbd2 |
Simplify imports in SocketAddresses.swift (#3696)
Motivation: The module map for glibc is broken which can lead libc symbols being attributed to the wrong module. In NIO, SocketAddresses.swift imports CNIOLinux (and friends) but, as far as I can tell, doesn't use any of their symbols directly. The result is that various libc symbols incorrectly get attributed to CNIOLinux and compilation can fail for downstream packages with member import visibility checks enabled. See also: https://github.com/swiftlang/swift/issues/85427 Modifications: - Remove the CNIO* imports from SocketAddresses.swift as they appear to be unused - Simplify the imoport block Result: Can build grpc with member import visibility checks enabled. Co-authored-by: Cory Benfield <lukasa@apple.com> |
||
|
|
08b497c937 |
[Windows] Stop skipping the event loop tick metrics tests (#3687)
### Motivation: `EventLoopMetricsDelegateTests` is skipped in its entirety on Windows, on the grounds that the WSAPoll selector wakes far more often than epoll or kqueue and so the tick counts are unreliable and flaky. Measuring it does not bear that out. ### Modifications: Remove the skip. No source changes are needed. Evidence gathered on a Windows ARM64 VM (Swift 6.3.2): - `testMetricsDelegateTickInfo` observes `ticks=2`, `numberOfTasks` per tick `[2, 1]`. That is **identical** to what the same instrumentation reports on macOS, and it is the low end of the `2...5` range the test allows, so there are three spare ticks of headroom rather than a count pressed up against the limit. - Both tests pass in isolation across four consecutive runs, and in three separate full unfiltered runs of the entire test suite (2354 tests, 0 failures each). For completeness, while investigating I did find one real asymmetry, which turns out not to affect these tests: `whenReady0` converts its timeout with `Int32(clamping: timeAmount.nanoseconds / 1_000_000)`, so a sub-millisecond timeout truncates to `0` where epoll arms a nanosecond-precision `timerfd` and kqueue uses a `timespec`. Probing it showed the cost is at most one extra poll (a 500µs sleep scheduled from inside an idle loop produced 1 extra tick, not a spin), and these tests use 100ms and 1s delays so they never encounter it. Worth knowing about, but not a correctness problem and out of scope here. ### Result: Two more tests run on Windows. |
||
|
|
0be2d1a0af |
[Windows] Fix buffer sizing in System.enumerateDevices() (#3684)
### Motivation: `System.enumerateDevices()` crashes on Windows, which in turn makes `UtilitiesTest.testEnumeratingDevices` and the whole of `SocketOptionProviderTest` (whose `setUp` enumerates devices) unrunnable there; both are currently skipped. `GetAdaptersAddresses` reports the size its output requires in *bytes*, but the buffer was allocated as `Int(ulSize) / MemoryLayout<IP_ADAPTER_ADDRESSES>.stride` *elements*. That integer division truncates, so the buffer was always smaller than what the OS asked for, and the OS then wrote its linked list of variably sized records (adapter names, sockaddrs, unicast address entries) past the end of it, corrupting the heap. ### Modifications: - Size the allocation in bytes, starting from the 15KB initial allocation the [documentation](https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersaddresses) recommends, and retry on `ERROR_BUFFER_OVERFLOW` — the set of adapters can change between the sizing call and the filling call. - Remove the corresponding skips in `UtilitiesTest.testEnumeratingDevices` and `SocketOptionProviderTest`. - Running `SocketOptionProviderTest` for the first time on Windows showed that `testPassingInvalidSizeToSetComplexSocketOptionFails` needs a Windows-specific expectation. Winsock's `SO_RCVTIMEO` takes a `DWORD` rather than a `timeval`, so the `Int` the test passes is in fact large enough and `setsockopt` correctly accepts it. On Windows the test now passes a single byte, which is too small for any option, and asserts the `WSAEFAULT` that Winsock reports. No behaviour change on any other platform; everything is behind `#if os(Windows)`. ### Result: `System.enumerateDevices()` works on Windows, and 13 previously skipped tests run there. Verified on a Windows ARM64 VM (Swift 6.3.2): a full unfiltered `swift test` passes — 2354 tests, 0 failures. |
||
|
|
ec51fff05f |
Remove unused SelectorLifecycleState.closing (#3695)
### Motivation `SelectorLifecycleState.closing` is never used in code. ### Changes - Remove `SelectorLifecycleState.closing` ### Result Easier code. |
||
|
|
18670a7e97 |
[Windows] Deregister channels while the event loop is closing (#3685)
### Motivation:
The WSAPoll selector traps with `preconditionFailure("Invalid fd
supplied.")` whenever `WSAPoll` reports `POLLNVAL`, and that is
reachable from ordinary shutdown, so
`MultiThreadedEventLoopGroupTests.testShuttingDownFailsRegistration` is
currently skipped on Windows.
The root cause is not in the selector. `SelectableEventLoop.deregister`
guards on `isOpen`, which is false both when the loop is closed *and*
when it has merely stopped accepting **new** registrations. The latter
is precisely the state the loop is in during `Selector.closeGently`,
which closes each remaining channel — so those channels skip
deregistration entirely and then close their sockets anyway.
The epoll and kqueue backends tolerate that, because there a
registration lives in the kernel and is dropped along with the
descriptor. The WSAPoll backend keeps its registrations in an array of
its own, so it is left holding a stale entry for a closed socket, and
the next `WSAPoll` correctly reports `POLLNVAL` for it.
Traced on a Windows ARM64 VM by instrumenting the selector and the event
loop:
```
register0 fd=704 idx=1
EL.deregister SKIPPED state=runningButNotAcceptingNewRegistrations
EL.deregister SKIPPED state=runningButNotAcceptingNewRegistrations
POLLNVAL fd=704 i=1 revents=4 events=256 dereg=[] indexes=[704: 1, 712: 2, 728: 3]
Fatal error: Invalid fd supplied.
```
### Modifications:
- Guard `deregister` on the *selector's* lifecycle rather than on
`isOpen`. Deregistering an existing channel while the loop is closing is
valid, because the selector itself is still open at that point.
- Remove the skip on
`MultiThreadedEventLoopGroupTests.testShuttingDownFailsRegistration`.
`POLLNVAL` deliberately keeps trapping. Like `EBADF`, which NIO already
treats as an unacceptable errno, it means we have lost track of a
descriptor; Windows recycles `SOCKET` handles, so continuing against a
possibly-reused handle would misroute I/O to the wrong channel. An
earlier version of this patch mapped `POLLNVAL` to `.error` instead —
that silently retained the stale entry and gave up that guarantee, so it
was dropped in favour of fixing the cause.
**Note for reviewers:** unlike most of the Windows porting patches this
touches shared code rather than sitting behind `#if os(Windows)`. The
observable behaviour on Linux/Darwin is unchanged, but they will now
issue one `epoll_ctl(EPOLL_CTL_DEL)`/kevent delete per channel during
event loop shutdown where previously they issued none.
### Result:
The WSAPoll selector no longer traps during event loop shutdown, and
`testShuttingDownFailsRegistration` runs on Windows.
Verified:
- Windows ARM64 (Swift 6.3.2), full unfiltered `swift test`: 2354 tests,
0 failures.
- macOS, full `swift test` with and without this change: identical
results (2451 tests, same 28 pre-existing failures caused by the network
mount used for this port, none in NIOPosix).
Co-authored-by: Fabian Fett <fabianfett@apple.com>
|
||
|
|
8f5cd5fa9c |
NIOFileSystem: saturate ByteCount unit factories instead of trapping on overflow (#3611)
Saturate the `ByteCount` unit factories so large counts no longer trap on overflow. ### Motivation: `ByteCount` exposes unit factories such as `kilobytes`, `megabytes`, `gigabytes`, `kibibytes`, `mebibytes`, and `gibibytes`. Each one computed the byte total with a plain multiplication, for example `1024 * 1024 * 1024 * count` in `gibibytes`. When a caller passes a very large count, that multiplication overflows `Int64` and traps, crashing the process. This is exactly what issue #2877 reports: `ByteCount(contentsOf:maximumSizeAllowed: .gibibytes(.max))` crashes with an arithmetic overflow inside `gibibytes`, even though passing a huge value is a natural way to express "effectively no limit". ### Modifications: I added a small `fileprivate` saturating multiplication helper on `Int64` and routed every unit factory through it. The helper uses `multipliedReportingOverflow(by:)` and, on overflow, clamps to `Int64.max` for positive counts or `Int64.min` for negative counts. Counts that fit continue to produce the exact same value as before, so there is no behavior change for normal inputs. I extended `ByteCountTests` with positive and negative overflow cases, and applied the identical change to both copies of `ByteCount.swift` (`NIOFS` and `_NIOFileSystem`) to keep them in sync, matching the convention used by recent changes to those targets. ### Result: Passing extreme values such as `.gibibytes(.max)` saturates to `Int64.max` instead of trapping, so disabling a size limit via a large value no longer crashes. I verified this by running `swift test --filter ByteCountTests`, which passes after the change. To confirm the tests are load bearing I reverted the source fix and re-ran the new tests, which crashed with signal 5 (the overflow trap) exactly as the issue describes, and they pass again with the fix in place. `swift format lint --strict` reports no issues on the changed files. Fixes #2877 |
||
|
|
72973283d7 |
[Windows] Report the WSAPoll selector's descriptor in its description (#3686)
### Motivation: `Selector.description` prints `self.selectorFD`, which only the epoll, kqueue and io_uring backends ever assign. On Windows it therefore always reads `descriptor = -1` — the value that by convention means the selector has been closed — even while the selector is open and perfectly usable. That made `MultiThreadedEventLoopGroupTests.testStructuredConcurrencyMTELGStartStop` unrunnable on Windows, since it asserts that a running event loop does *not* describe itself as having descriptor -1, and that a shut down one does. ### Modifications: The WSAPoll backend has no single descriptor standing for the selector itself, but the read end of its wakeup socket pair has exactly the same lifetime: it is created in `initialiseState0` and reset to `NIOBSDSocket.invalidHandle` in `close0`, under the same `externalSelectorFDLock` that this description already takes. Report that on Windows, mapping the invalid handle to -1 so the established meaning of -1 is preserved. Remove the corresponding skip. The change is behind `#if os(Windows)`; other platforms keep printing `selectorFD` exactly as before. ### Result: A running event loop on Windows now describes its selector accurately, and `testStructuredConcurrencyMTELGStartStop` runs there. Verified on a Windows ARM64 VM (Swift 6.3.2): a full unfiltered `swift test` passes — 2354 tests, 0 failures. |
||
|
|
b07752c676 |
[Windows] Skip unsupported/flaky tests and run the Windows unit tests in CI (#3680)
### Motivation: All of the test targets now compile on Windows (#3663, #3665), but `swift test` doesn't yet pass: a number of tests exercise functionality that isn't supported or isn't yet functional on Windows, some crash or hang, and a few are flaky on the WSAPoll-based selector. Before the Windows unit tests can run in CI, those tests need to be skipped (with reasons) so a full `swift test` exits cleanly. ### Modifications: Skip the tests that don't pass on Windows, using `XCTSkip` / Swift Testing's `.disabled` / a gated `setUp` where a fixture itself traps, each with a reason. Broadly: - **Unsupported transports/APIs:** Unix domain sockets, datagram/UDP channels, pipe channels, raw sockets, vsock, pre-connected sockets, and `FileRegion` sends. - **Whole suites** for subsystems that aren't functional on Windows yet, including the **NIOFileSystem family** (`NIOFSTests`, `NIOFSIntegrationTests`, `NIOFSFoundationCompatTests`) whose Windows syscall shims are still stubbed, plus `EchoServerClientTest`, `ChannelTests`, `DatagramChannelTests`, `StreamChannelTest`, `FileRegionTest`, `PipeChannelTest`, `RawSocketBootstrapTests`, `ThreadTest`, and `SocketOptionProviderTest`. - **Real crashes surfaced by a full run:** `System.enumerateDevices()` (mis-sized `GetAdaptersAddresses` buffer), the WSAPoll selector trapping on an invalid fd and on schedule-after-shutdown, and a connection-reset promise leak. - **Flaky, timing-sensitive tests:** the event-loop tick-count metrics tests (the WSAPoll selector wakes far more often than epoll/kqueue). Then enable the Windows 6.3 + nightly jobs in the reusable unit-tests workflow (which runs `swift test`) in both the PR and push workflows, and drop the separate build-only Windows job (which only ran `swift build --build-tests`). Windows uses the default `swift test` arguments rather than the Linux `-Xswiftc -warnings-as-errors` override, because a `#warning` in the (skipped) stream-channel tests would otherwise fail the build. All skips are Windows-only; there is no behaviour change on other platforms. ### Result: `swift test` passes on Windows, and the Windows unit tests run in CI. --------- Co-authored-by: George Barnett <gbarnett@apple.com> |
||
|
|
cb487991d8 |
Clarify replaceItem moves the item (#3674)
This change clarifies the documentation of `replaceItem(at:withItemAt:)`. It explicitly states that this operation is identical to a move, and that the item at `existingPath` will be moved to the new location and no longer exist at its original path. |
||
|
|
15b77e6400 |
[Windows] Compile the remaining test targets (NIOPosixTests, NIOFoundationCompatTests) (#3665)
## Motivation Follow-up to #3663 (which got the "low-hanging" test targets compiling on Windows). This finishes the job by getting the **last two** test targets — `NIOPosixTests` and `NIOFoundationCompatTests` — compiling on Windows, so **all 16 test targets now build**, and switches Windows CI to `swift build --build-tests`. These are **compile-only** changes: the goal is compilation, not runtime pass. Verified by building on a Windows ARM64 VM with `swift build --build-tests`. ## What's here 1. **Compile `NIOFoundationCompatTests`** — the target imports the `NIO` umbrella (in `WaitSpinningRunLoopTests`, for `MultiThreadedEventLoopGroup`) but only declared `NIOCore`/`NIOFoundationCompat` as dependencies. `NIO` re-exports `NIOPosix`, which imports the `CNIOPosix` **C module**; Linux/macOS resolve that transitively, but on Windows the C-module map isn't in the target's search path unless declared, giving the opaque `<unknown>:0: error: missing required module 'CNIOPosix'`. Fix: declare the `NIO` dependency it actually uses. 2. **Compile `NIOPosixTests`** — the deeply-POSIX target. Gate-out-plus-minimal-shim: - `import WinSDK` where only `sockaddr`/`timeval`/`in_addr` field or type access was missing (`MemberImportVisibility`) — this alone cleared the two largest files (`SocketAddressTest`, `HappyEyeballsTest`). - Real fixes where cheap: `pipe` → `_pipe` (via `ucrt`), an `STDOUT_FILENO` shim, `Thread.sleep` instead of `sleep`, and letting `IOResult` type inference pick `ssize_t`. - `#if !os(Windows)` gating (per-method where possible, to preserve Windows-compilable coverage) for genuinely-unavailable APIs: `fcntl`/`O_NONBLOCK`/`O_ASYNC`/`F_GETFL`/`F_SETFL`, `Posix.fcntl`, `Posix.socketpair`, the integer socket-option API (`ChannelOptions.socket`, `SOL_SOCKET`, `SO_REUSEADDR`, `so_timestamp`), `poll`/`pollfd`, `cmsg`/`msghdr` construction, `NonBlockingFileIO.lstat`/`symlink`/`listDirectory`/`createDirectory`, vsock CID/connect tests, `/dev/null` syscall-wrapper perf tests, and socket-handle (`NIOBSDSocket.Handle` `UInt64` vs `CInt`) mismatches. - Whole-file gating only where a file is pervasively unsupported: the SAL mock harness and its dependents (`SyscallAbstractionLayer[Context]`, `SALChannelTests`, `SALEventLoopTests`) — it's built on `CInt` fds and can't compile against Windows's `UInt64` socket handles without a larger rework; `ControlMessageTests` (POSIX `msghdr`/control-message throughout); and `MulticastTest` (deprecated `enumerateInterfaces`/`NIONetworkInterface`). 3. **Build the test targets in CI** — change the Windows matrix command from `swift build` to `swift build --build-tests` in `main.yml` and `pull_request.yml`. ## Notes for reviewers - No behavior change off Windows: every edit is behind `#if os(Windows)` / `#if !os(Windows)`; the few shared-line changes (`Thread.sleep`, `IOResult` inference, an IUO force-unwrap of `msg_name`) are identical on POSIX. - The tests are **compiled, not run** on Windows yet. Running them needs real Winsock work (socket handle types, etc.) and is the natural next step. --------- Co-authored-by: George Barnett <gbarnett@apple.com> |
||
|
|
63018571c8 |
[perf] Do stack allocs instead of heap allocs for small fixed-size allocations (#3652)
For small fixed-size allocations, we can use stack instead of heap. ### Motivation: Allocations are costly. Stack allocations are much cheaper than heap allocations. ### Modifications: Use `withUnsafeTemporaryAllocation(of:capacity:_:)` instead of allocating an `Array`. `withUnsafeTemporaryAllocation` allocates on the stack for up to 1000 bytes. ### Result: Better performance. |
||
|
|
afc79dd083 |
Implement customisation point for scheduled callback on isolated EL (#3679)
Motivation: The schedule callback mechanism on `EventLoop` has an equivalent on an isolated `EventLoop`. The default isolated implementation puts the hander in a loop bound box and calls the non-isolated version. This is okay but introduces a number of additional "in event loop" checks which are required for correctness in the general case (i.e. not called from an isolated event loop). Modifications: - Implement the customisation point directly to avoid the additional checks (the are unecessary by definition of being on the isolated event loop). - Add benchmarks Result: On the isolated event loop, in micro benchmarks: - scheduleTask is ~1.6x faster - scheduleCallback is ~2x faster |
||
|
|
3777a70115 |
Fallback to non-positional read/write on ENXIO (#3671)
This PR addresses **#3613** where writing to `/dev/stdout` fails with `ENXIO (6) Device not configured` when running in a terminal environment instead of a pipe. Currently, `SystemFileHandle` checks for `errno == .illegalSeek` (ESPIPE) when deciding whether to fall back from positional `pwrite`/`pread` to non-positional `write`/`read` for unseekable files like pipes. However, macOS/Darwin returns `ENXIO` (`Errno.noSuchDeviceOrAddress`) instead of `ESPIPE` when attempting a positional write/read on a terminal device. **Changes:** - Added `.noSuchDeviceOrAddress` to the fallback conditions in `SystemFileHandle.swift` for both `readChunk` and `write`. - Updated `FileSystemError+Syscall.swift` to map `.noSuchDeviceOrAddress` to `.unsupported` alongside `.illegalSeek`. - Replicated these changes across both the `_NIOFileSystem` and `NIOFS` modules. This allows `FileSystem.shared.withFileHandle` and other APIs to work transparently with terminal devices like `/dev/stdout`! |
||
|
|
199ccb983c |
Add variants of flatMap which can return EventLoopFuture<NonSendable> (#3634)
### Motivation:
Currently, EventLoopFuture.flatMap requires the inner eventloop to have
a Sendable type. This makes sense, because the value might move between
eventloops, if the inner and outer future are not on the same EventLoop.
However, this makes it impossible for users to use non Sendable values
even when they _know_ they're on the right eventloop
### Modifications:
Add a new `flatMapIsolated` function which can be used in this case. It
requires users to return an EventLoopFuture.Isolated to prove that they
are on the same eventloop
### Example:
```swift
class T { // Not Sendable
init() {
}
}
func test(eventLoop: any EventLoop) -> EventLoopFuture<T> {
let a = eventLoop.submit { T() }
let b = eventLoop.submit { T() }
return a.flatMap { _ in b }
}
```
The above example gives a warning on the final line, because flatMap
requires the inner future (`b`) to have a Sendable type. That is because
it doesn't know that a and b are on the same EventLoop.
```swift
func test(eventLoop: any EventLoop) -> EventLoopFuture<T> {
let a = eventLoop.submit { T() }
let b = eventLoop.submit { T() }
return a.flatMapIsolated { _ in b.assumeIsolated() }
}
```
Here, it compiles without warnings. We can write assumeIsolated inside
the flatMapIsolated closure because we know that the eventloops are the
same. And therefore the new flatMapIsolated function does not have a
Sendable requirement on its value
Co-authored-by: Cory Benfield <lukasa@apple.com>
|
||
|
|
3bd6c86af3 |
[Windows] Compile the low-hanging test targets (#3663)
## Motivation Follow-up to #3649 (all non-test targets now build on Windows). This gets the bulk of the **test** targets compiling on Windows so we can start moving toward running them in CI. Of the 16 test targets, 6 already compiled unchanged. This brings **8 more** to a clean compile, leaving only two as dedicated follow-ups: - `NIOPosixTests` — large, many distinct Winsock/POSIX issues; deserves its own PR. - `NIOFoundationCompatTests` — a `missing required module 'CNIOPosix'` issue to investigate separately. The changes are **compile-only** — they don't aim to make the tests *pass* on Windows yet. Verified by building each target on a Windows ARM64 VM; not yet wired into CI (CI still builds products only, since the two deferred targets would fail `--build-tests`). ## What's here Three commits: 1. **Make `Posix.close` available on Windows** — it was gated out only because it sat inside the socket-syscalls `#if !os(Windows)` block (next to `shutdown`), even though its body already handled Windows. Define `sysClose = _close` and lift `close(descriptor:)` out of that block. No behavior change off Windows. 2. **Compile the low-hanging test targets** — a gate-out-plus-minimal-shim approach: - A tiny `#if os(Windows)` `usleep` shim (backed by `Sleep`), once per affected target, plus a Windows branch for the `#error` C-library check. - Real Windows implementations for the temp-file/pipe test helpers rather than stubs: `withPipe` → `_pipe`, `openTemporaryFile` → `_mktemp_s` + `_sopen_s`, `createTemporaryDirectory` → a GUID + `CreateDirectoryW`. - Gate out genuinely-unavailable test logic behind `#if !os(Windows)`: `System.enumerateInterfaces`, `ChannelOptions.socket(IPPROTO_IP, IP_TTL)`, `mkfifo`-based tests, the POSIX-`stat`-shaped `FileInfoTests`, the `S_IFSOCK`/`DT_*` conversion tests, and the `openat` oflag-bit test. - Two Windows-only shim tweaks make the NIOFS `OpenOptions` gap values and `Errno.noData` `@_spi(Testing) public`, matching how swift-system exposes the equivalents elsewhere (the tests reach them via an SPI import). - The `NIOHTTP1Tests` and `NIOPosixTests` copies of `TestUtils.swift` are intentional duplicates and get identical Windows helper implementations to stay in sync. 3. **Document why `SocketOption`'s integer API is unavailable on Windows** — comment-only: WinSDK imports the socket option level/name constants as enumeration cases, not plain integers, so they don't fit the integer `SocketOptionLevel`/`SocketOptionName` typealiases. ## Notes for reviewers - No behavior change off Windows: every change is behind `#if os(Windows)` / `#if !os(Windows)`; the one shared edit (a test buffer typed `CChar` instead of `CInterop.PlatformChar`) is identical on POSIX. - The `usleep` shim is duplicated per target rather than shared: there's no test-only support target these all depend on (the shared deps, `NIOCore`/`NIOTestUtils`, are shipping libraries). It can be centralised later if desired. --------- Co-authored-by: George Barnett <gbarnett@apple.com> |
||
|
|
590dd7b4bc |
[Windows] Compile the NIOFileSystem family (stubbed); all non-test targets now build (#3649)
## Motivation
This continues the incremental Windows port of SwiftNIO. `NIOPosix`
already builds on Windows (on Winsock2 with a POSIX-shim mapping); this
PR gets the **L4 NIOFileSystem family** to **compile** on Windows:
- `_NIOFileSystem`
- `NIOFS`
- `NIOFileSystem`
- `_NIOFileSystemFoundationCompat`
- `NIOFSFoundationCompat`
With these compiling, **all non-test targets now build on Windows**, so
the Windows CI job is simplified to a bare `swift build` (which builds
the whole non-test graph) rather than an explicit per-target list.
## Scope — compile-only
**This PR gets the targets compiling; it does not yet make them
functional.** The POSIX file-system syscalls that don't exist (or aren't
exposed by swift-system) on Windows are provided as `fatalError("…
unavailable on Windows")` **stubs** with the correct signatures, so the
library type-checks and links. Real Win32 implementations, and bringing
the test targets online in CI to validate them, are deliberately left to
follow-up PRs.
The intent is to land the smallest reviewable slice first and **get
feedback on the overall shape and organization** before building on it.
## What this does
All changes are behind `#if os(Windows)` / `#if defined(_WIN32)`, with
**zero behavior change on Darwin/Linux/BSD**:
- **`Sources/*/Internal/System Calls/SystemPackage+Windows.swift`**
(new, one per tree): a module-scope compatibility shim supplying the
pieces the rest of the target expects on Windows —
- the swift-system-gap extensions swift-system doesn't provide on
Windows
(`FileDescriptor.OpenOptions.{noFollow,closeOnExec,nonBlocking,directory}`,
`Errno.noData`);
- `CInterop.Stat`/`DirEnt`/`FTS`/`FTSEnt` Windows stand-ins and the
`S_IF*`/`DT_*`/`FTS_*`/`UTIME_*` constants the call sites reference;
- `fatalError` stubs for the bare-libc syscalls (`openat`,
`stat`/`lstat`/`fstat`, `readdir`/`fdopendir`/`closedir`, `fts_*`,
`futimens`, `rename`, `symlink`, xattr-adjacent helpers, `getcwd`,
pthread TLS keys, …), matching the exact signatures the existing
`system_*` / `libc_*` wrappers call, so those wrappers and their
non-Windows call sites need no changes.
- Small `#elseif os(Windows)` branches in the existing platform switches
(`FileInfo`, `FileType`, `Errno`, `Mocking`, `Syscall(s)`,
`SystemFileHandle`, `FileSystem`) — including `fatalError` stubs for
`_copyRegularFile` / `_copySymbolicLink` /
file-materialization-via-rename.
- A tiny `CNIOWindows` addition: `errno` accessors (`CNIOWindows_errno`
/ `CNIOWindows_set_errno`, typed `errno_t` via
`_get_errno`/`_set_errno`) so the Swift errno indirection can bridge the
CRT `errno` macro.
- `CNIOWindows` added to the `NIOFS` / `_NIOFileSystem` target
dependencies in `Package.swift`.
`NIOFS` and `_NIOFileSystem` are lockstep near-duplicates, so every
Windows change is applied identically to both.
## Verification
Verified by source review and by confirming a clean `swift build` on
`aarch64-unknown-windows-msvc`. Since the syscalls are stubbed, there is
no runtime behavior to test yet.
## What I'm looking for
Feedback on the **high-level organization and shape** of the NIOFS
Windows shim before the real implementations follow:
1. Is the layering right — a single module-scope
`SystemPackage+Windows.swift` gap-shim, with the upstream `system_*` /
`libc_*` call sites left untouched?
2. When the implementations land, is emulating the POSIX seams (a
`fts(3)`-shaped tree walk, POSIX directory streams) the right approach,
or should Windows fork at a higher layer (e.g. a Windows-specific
enumerator in `DirectoryEntries`) rather than reimplementing
`fts`/`readdir`?
3. Anything about the swift-system-gap extensions or the `CInterop.*`
Windows stand-ins that should be shaped differently.
## Next steps
Follow-up PRs will replace the stubs with real Win32 implementations,
then bring the NIOFileSystem **test targets** building and running in CI
— where these shims get real validation and we start gaining deeper
confidence in Windows support across the stack.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
|
||
|
|
01626145d0 | Fix the URL in the README for the badge (#3661) | ||
|
|
0b18836bd8 |
Don't write any bytes for H1 responses that shouldn't include a body (#3651)
### Motivation: On the server side, `HTTPResponseEncoder` chooses a response's body framing only from the response status (`HTTPResponseStatus.mayHaveResponseBody`): it has no knowledge of the request method as it's an outbound-only handler. But HTTP requires that a response to a HEAD request (and a 2xx response to CONNECT) carry no message body, regardless of status or framing headers. As a result, a response to a HEAD request with a status that allows a body (like 200) and no `Content-Length` gets framed as `Transfer-Encoding: chunked`, and the encoder emits the chunked terminator (`0\r\n\r\n`). This is illegal. A conformant client won't read those bytes when receiving a HEAD response, so on a keep-alive connection they get misinterpreted as the start of the next response, corrupting the connection. This surfaces as intermittent, hard-to-diagnose failures (e.g. "I/O on closed channel") on the following request. ### Modifications: Made the server response framing method-aware without changing any public API: - The request decoder now hands each decoded request's method to the response encoder. - `HTTPResponseEncoder` consults the method and, for responses to HEAD/CONNECT requests, omits the body and the terminator. - This is wired up in `configureHTTPServerPipeline`. When the encoder is constructed and used on its own, its behaviour is unchanged (framing is still derived solely from the status), so there is no behavioural or API change for users who may be creating this handler manually. ### Result: Responses to `HEAD` and `CONNECT` requests are no longer emitted with a message body, keeping keep-alive connections well-formed and RFC-compliant. No public API changes.2.101.3 |
||
|
|
53ac1ccab2 |
Document trapping behavior of ByteBuffer set*(at:) write APIs (#3659)
Motivation: GHSA-ffw9-jrfx-pfvc raised a question about whether `setBytes(_:at:)`, `setInteger(_:at:...)`, and `setString(_:at:)` correctly validate an out-of-range `index`. On review, this turned out to be working-as-intended: these APIs trap on an invalid index by design, unlike the `get*` family, which validates via `rangeWithinReadableBytes` and returns `nil` instead. That asymmetry wasn't previously called out in the doc comments, which made it easy to mistake for an unmitigated validation gap rather than documented behavior. Modifications: Added a `- Precondition:` note to the doc comments of `setBytes(_:at:)` (all overloads), `setInteger(_:at:...)`, and `setString(_:at:)` in NIOCore, making the trapping behavior explicit and noting that callers must validate any externally-derived `index` before use. Result: No behavior changes. The trapping contract on these `set*` write APIs is now documented, matching the existing convention used by `get*`'s optional-return documentation.One line description of your change |
||
|
|
b1f2dd18fc |
rewrite NIOCrashTester in Swift Testing (#3658)
### Motivation: The old NIOCrashTester doesn't work on Windows and would be hard to port. Also, Swift Testing has wonderful 'exit test' ability, let's use that! ### Modifications: - Rewrite all NIOCrashTester tests in Swift Testing ### Result: - Less code to maintain - (hopefully) works on Windows - fixes #3657 |
||
|
|
68631de6d8 |
[Windows] Build NIOPerformanceTester and NIOCrashTester in CI (#3646)
Add the two remaining non-test, non-NIOFS targets to the Windows CI build list. NIOPerformanceTester builds and runs on Windows. The only obstacle was the `setbuf(stdout, nil)` call: `stdout` is a macro on the Windows CRT that Swift cannot reference directly. Add a `CNIOWindows_setStdoutUnbuffered()` wrapper so the C compiler expands the macro (keeping us correct if its definition ever changes), and call it on Windows. NIOCrashTester cannot function on Windows: its OutputGrepper captures a child process's output through a pipe channel (`NIOPipeBootstrap`), which deliberately `fatalError`s on Windows, and relies on `Foundation.Pipe` fd conversion plus Unix-signal crash detection. Extend the existing `!canImport(Darwin) || os(macOS)` guard with `&& !os(Windows)` across the target so it compiles to a no-op on Windows, just as it already does on the non-macOS Darwin platforms. |
||
|
|
419f57f136 |
Winsock Fixes (#3433)
This PR gets TCP (Servers) on Windows mostly working. I'll annotate my
PR for clarity.
**The one bug:**
If you open a TCP client connection to a Windows TCP server, it doesn't
read/write yet until a second connection comes in. This happens because
`reregister0` is called after `WSAPoll` is called - but WSAPoll isn't
woken up to know this so it doesn't know the new socket requests
read/writes/...
Also the EventLoop cannot be woken up during `el.execute { .. }` because
`SleepEx` isn't running. WSAPoll doesn't respond to this signal it
seems.
This makes the TCP server functionality not yet usable, but I thought
with this draft we could figure out what I'm missing.
Alternative considered: We can make `WSAPoll` limited to wake up every 1
ms for example, that way we can still get to these events at _some_
point.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Fabian Fett <fabianfett@apple.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Oliver Drobnik <oliver@cocoanetics.com>
Co-authored-by: Jake Petroules <jake.petroules@apple.com>
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Gabriele Mondada <gab@ijk.ch>
|
||
|
|
a97b26909b |
EL takeover works on 6.4 & main (#3645)
### Motivation: EventLoop takeover of the Concurrency pool works fine on 6.4 & main. ### Modifications: Raise limit. ### Result: More speed. |
||
|
|
a6ffe7cf19 |
[Windows] Build currently-supported targets in CI (#3644)
Add a Windows PR/main CI job that builds the targets which compile cleanly today: _NIOBase64, _NIOConcurrency, _NIODataStructures, NIOConcurrencyHelpers, NIOCore, NIOEmbedded, NIOFoundationCompat, NIOFoundationEssentialsCompat, NIOHTTP1, NIOTLS, NIOWebSocket. The remaining targets (NIOPosix, NIO, NIOTestUtils, downstream tests, examples) still fail on Windows and are not yet covered. The existing unit-tests workflow path runs swift test, which does not accept --target, so flipping windows_6_3_enabled there would attempt to test the whole package and fail. Instead this is an inline job that runs swift build with explicit --target flags. As more targets come up on Windows we'll extend the list, then eventually retire this job in favor of windows_6_3_enabled when swift test of the whole package is green. Co-authored-by: George Barnett <gbarnett@apple.com> |
||
|
|
eeb20e7f95 |
HTTPDecoder: restore old limit of 80 kB headers (#3621)
### Motivation: NIO's historic limit was that the maximum header block was limited to 80 kB which is a sensible limit and originates from Nginx's http_parser.c. The history of the changes: - commit |
||
|
|
404f732619 |
Explicitly add ncurses to the dependency list. (#3640)
Motivation: We should be explicit about our dependencies, and not allow them to be satisfied by transitive deps. Modifications: Add ncurses Result: More explicitness |
||
|
|
cd3e115208 |
Avoid exit tests on iOS/tvOS/watchOS/visionOS (#3639)
Motivation: The exit tests fail to compile on these platforms. Modifications: Commented out the exit tests on those platforms. Result: Better testing2.101.2 |
||
|
|
74c924fd01 |
Apply an autoreleasepool around the task drop (#3638)
Motivation: Users can write arbitrary code in their deinits, and that arbitrary code _may_ end up hitting Objective-C autoreleases. We don't want to leak those objects into the per-thread autoreleasepool, as that may not be popped for a very long time, if ever, so we need to to ensure that deiniting the task objects has an autoreleasepool. Modifications: Add an autoreleasepool around the task drop, and tests to validate that we do things correctly. Result: Better memory management around deinit |
||
|
|
849ab561ae |
NFC: Move fileIO binding before use in childChannelInitializer (#3563)
I'm hoping to ban use-before-declarations at the top level of a `main.swift` (swiftlang/swift#88082), fix-up this case. |
||
|
|
a8e036cb86 |
Fix incorrect status lines in HTTPResponseEncoder fast paths (#3631)
### Motivation `HTTPResponseEncoder` writes hand-optimised status lines for the well-known `HTTPResponseStatus` values instead of going through the general `default` path that formats `HTTP/<version> <code> <reasonPhrase>`. Several of those fast paths had drifted out of sync with `HTTPResponseStatus.reasonPhrase`, so the exact bytes on the wire depended on whether a status happened to have a fast path: * **HTTP/1.0 + 511** emitted the wrong HTTP version (`HTTP/1.1 511 ...`) — a wire-format correctness bug, not just cosmetic. * **HTTP/1.1 + 431** emitted the reason phrase `Range Not Satisfiable` instead of `Request Header Fields Too Large`. * **HTTP/1.1 + 416** emitted `Request Range Not Satisified` (also misspelled) instead of `Range Not Satisfiable`. * **HTTP/1.0 and HTTP/1.1 + 307** emitted `Tempory Redirect` (misspelled) instead of `Temporary Redirect`. Resolves #3630. ### Modifications * Correct the five diverging status lines in `HTTPResponseEncoder` so they match `HTTPResponseStatus.reasonPhrase` and carry the correct HTTP version. * Add a regression test that, for every well-known status at both HTTP/1.0 and HTTP/1.1, asserts the encoded status line equals the canonical `HTTP/<version> <code> <reasonPhrase>` form, keeping the fast paths in lockstep with `reasonPhrase`. ### Result The encoder now produces correct, consistent status lines for all well-known statuses regardless of whether they use a fast path. The new test fails on the pre-fix code (the 511 case fails on the version, the 431/416/307 cases on the reason phrase) and passes after the fix. --------- Co-authored-by: George Barnett <gbarnett@apple.com>2.101.1 |
||
|
|
a863732fbc |
Fix benchmark diff scraping for path-qualified markers (#3609)
## Motivation `scripts/check_benchmark_thresholds.sh` started printing path-qualified diff markers in #3602 so multi-package benchmark runs can identify which package produced each diff. `dev/thresholds-from-benchmark-output.sh` still scrapes the old exact marker line, which means local threshold updates from CI logs can miss the diff entirely once the new marker format appears. ## Changes Relax the scraper to match the stable `=== BEGIN DIFF` prefix instead of the old exact line, preserving compatibility with both the original marker and the newer path-qualified form. ## Validation - `bash -n dev/thresholds-from-benchmark-output.sh` - Verified the scrape pipeline against both `=== BEGIN DIFF ===` and `=== BEGIN DIFF (Benchmarks) ===` sample log lines Co-authored-by: Cory Benfield <lukasa@apple.com> |
||
|
|
0b38af6217 |
fix off-by-one boundaries in QUIC bytesNeededForInteger (#3628)
Off-by-one in the QUIC variable-length integer length boundaries. ### Motivation: `bytesNeededForInteger` classifies an integer into the 1/2/4/8 byte QUIC encoding using half-open ranges (`0..<63`, `0..<16383`, `0..<1_073_741_823`, `0..<4_611_686_018_427_387_903`). Those upper bounds are the *largest* value each size can hold (2^6-1, 2^14-1, 2^30-1 and 2^62-1 per RFC 9000 § 16), so each maximum is wrongly excluded: - 63, 16383 and 2^30-1 report one byte too many, so the encoder writes them with a larger encoding than needed. - 2^62-1, the largest value the encoding can represent, falls through to the `fatalError` and crashes the encoder. The existing one-byte write test only iterates `0..<63`, so the 63 case was never exercised. ### Modifications: - Switch the four ranges in `bytesNeededForInteger` to inclusive bounds. - Extend the one-byte write test to include 63, and add boundary checks plus a 2^62-1 round-trip test. ### Result: Boundary values encode in the minimal number of bytes and 2^62-1 round-trips instead of crashing. Co-authored-by: Cory Benfield <lukasa@apple.com> |
||
|
|
0676c27260 |
[NFC] Remove trailing whitespaces from CNIOFreeBSD (#3632)
This PR is just a cleanup of the source code. ### Motivation: The `CNIOFreeBSD` source code contains inconsistent trailing whitespaces, which hinders future modifications. ### Modifications: Removed all trailing whitespaces from `CNIOFreeBSD`. ### Result: The source code remains exactly the same; only the trailing whitespace has been removed. Co-authored-by: Cory Benfield <lukasa@apple.com> |
||
|
|
fa87cfba3d |
Bump actions/checkout from 6.0.2 to 7.0.0 (#3633)
Bumps [actions/checkout](https://github.com/actions/checkout) from 6.0.2 to 7.0.0. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/actions/checkout/releases">actions/checkout's releases</a>.</em></p> <blockquote> <h2>v7.0.0</h2> <h2>What's Changed</h2> <ul> <li>block checking out fork pr for pull_request_target and workflow_run by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2454">actions/checkout#2454</a></li> <li>Bump actions/publish-immutable-action from 0.0.3 to 0.0.4 in the minor-actions-dependencies group across 1 directory by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2458">actions/checkout#2458</a></li> <li>Bump flatted from 3.3.1 to 3.4.2 by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2460">actions/checkout#2460</a></li> <li>Bump js-yaml from 4.1.0 to 4.2.0 by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2461">actions/checkout#2461</a></li> <li>Bump <code>@actions/core</code> and <code>@actions/tool-cache</code> and Remove uuid by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2459">actions/checkout#2459</a></li> <li>upgrade module to esm and update dependencies by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2463">actions/checkout#2463</a></li> <li>Bump the minor-npm-dependencies group across 1 directory with 3 updates by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2462">actions/checkout#2462</a></li> <li>getting ready for checkout v7 release by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2464">actions/checkout#2464</a></li> <li>update error wording by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2467">actions/checkout#2467</a></li> </ul> <h2>New Contributors</h2> <ul> <li><a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> made their first contribution in <a href="https://redirect.github.com/actions/checkout/pull/2454">actions/checkout#2454</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/actions/checkout/compare/v6.0.3...v7.0.0">https://github.com/actions/checkout/compare/v6.0.3...v7.0.0</a></p> <h2>v6.0.3</h2> <h2>What's Changed</h2> <ul> <li>Update changelog by <a href="https://github.com/ericsciple"><code>@ericsciple</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2357">actions/checkout#2357</a></li> <li>fix: expand merge commit SHA regex and add SHA-256 test cases by <a href="https://github.com/yaananth"><code>@yaananth</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2414">actions/checkout#2414</a></li> <li>Fix checkout init for SHA-256 repositories by <a href="https://github.com/yaananth"><code>@yaananth</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2439">actions/checkout#2439</a></li> <li>Update changelog for v6.0.3 by <a href="https://github.com/yaananth"><code>@yaananth</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2446">actions/checkout#2446</a></li> </ul> <h2>New Contributors</h2> <ul> <li><a href="https://github.com/yaananth"><code>@yaananth</code></a> made their first contribution in <a href="https://redirect.github.com/actions/checkout/pull/2414">actions/checkout#2414</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/actions/checkout/compare/v6...v6.0.3">https://github.com/actions/checkout/compare/v6...v6.0.3</a></p> </blockquote> </details> <details> <summary>Changelog</summary> <p><em>Sourced from <a href="https://github.com/actions/checkout/blob/main/CHANGELOG.md">actions/checkout's changelog</a>.</em></p> <blockquote> <h1>Changelog</h1> <h2>v7.0.0</h2> <ul> <li>Block checking out fork PR for pull_request_target and workflow_run by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2454">actions/checkout#2454</a></li> <li>Bump actions/publish-immutable-action from 0.0.3 to 0.0.4 in the minor-actions-dependencies group across 1 directory by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2458">actions/checkout#2458</a></li> <li>Bump flatted from 3.3.1 to 3.4.2 by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2460">actions/checkout#2460</a></li> <li>Bump js-yaml from 4.1.0 to 4.2.0 by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2461">actions/checkout#2461</a></li> <li>Bump <code>@actions/core</code> and <code>@actions/tool-cache</code> and Remove uuid by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2459">actions/checkout#2459</a></li> <li>upgrade module to esm and update dependencies by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2463">actions/checkout#2463</a></li> <li>Bump the minor-npm-dependencies group across 1 directory with 3 updates by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2462">actions/checkout#2462</a></li> </ul> <h2>v6.0.3</h2> <ul> <li>Fix checkout init for SHA-256 repositories by <a href="https://github.com/yaananth"><code>@yaananth</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2439">actions/checkout#2439</a></li> <li>fix: expand merge commit SHA regex and add SHA-256 test cases by <a href="https://github.com/yaananth"><code>@yaananth</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2414">actions/checkout#2414</a></li> </ul> <h2>v6.0.2</h2> <ul> <li>Fix tag handling: preserve annotations and explicit fetch-tags by <a href="https://github.com/ericsciple"><code>@ericsciple</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2356">actions/checkout#2356</a></li> </ul> <h2>v6.0.1</h2> <ul> <li>Add worktree support for persist-credentials includeIf by <a href="https://github.com/ericsciple"><code>@ericsciple</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2327">actions/checkout#2327</a></li> </ul> <h2>v6.0.0</h2> <ul> <li>Persist creds to a separate file by <a href="https://github.com/ericsciple"><code>@ericsciple</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2286">actions/checkout#2286</a></li> <li>Update README to include Node.js 24 support details and requirements by <a href="https://github.com/salmanmkc"><code>@salmanmkc</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2248">actions/checkout#2248</a></li> </ul> <h2>v5.0.1</h2> <ul> <li>Port v6 cleanup to v5 by <a href="https://github.com/ericsciple"><code>@ericsciple</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2301">actions/checkout#2301</a></li> </ul> <h2>v5.0.0</h2> <ul> <li>Update actions checkout to use node 24 by <a href="https://github.com/salmanmkc"><code>@salmanmkc</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2226">actions/checkout#2226</a></li> </ul> <h2>v4.3.1</h2> <ul> <li>Port v6 cleanup to v4 by <a href="https://github.com/ericsciple"><code>@ericsciple</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2305">actions/checkout#2305</a></li> </ul> <h2>v4.3.0</h2> <ul> <li>docs: update README.md by <a href="https://github.com/motss"><code>@motss</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/1971">actions/checkout#1971</a></li> <li>Add internal repos for checking out multiple repositories by <a href="https://github.com/mouismail"><code>@mouismail</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/1977">actions/checkout#1977</a></li> <li>Documentation update - add recommended permissions to Readme by <a href="https://github.com/benwells"><code>@benwells</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2043">actions/checkout#2043</a></li> <li>Adjust positioning of user email note and permissions heading by <a href="https://github.com/joshmgross"><code>@joshmgross</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2044">actions/checkout#2044</a></li> <li>Update README.md by <a href="https://github.com/nebuk89"><code>@nebuk89</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2194">actions/checkout#2194</a></li> <li>Update CODEOWNERS for actions by <a href="https://github.com/TingluoHuang"><code>@TingluoHuang</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2224">actions/checkout#2224</a></li> <li>Update package dependencies by <a href="https://github.com/salmanmkc"><code>@salmanmkc</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2236">actions/checkout#2236</a></li> </ul> <h2>v4.2.2</h2> <ul> <li><code>url-helper.ts</code> now leverages well-known environment variables by <a href="https://github.com/jww3"><code>@jww3</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/1941">actions/checkout#1941</a></li> <li>Expand unit test coverage for <code>isGhes</code> by <a href="https://github.com/jww3"><code>@jww3</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/1946">actions/checkout#1946</a></li> </ul> <h2>v4.2.1</h2> <ul> <li>Check out other refs/* by commit if provided, fall back to ref by <a href="https://github.com/orhantoy"><code>@orhantoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/1924">actions/checkout#1924</a></li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/actions/checkout/commit/9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0"><code>9c091bb</code></a> update error wording (<a href="https://redirect.github.com/actions/checkout/issues/2467">#2467</a>)</li> <li><a href="https://github.com/actions/checkout/commit/1044a6dea927916f2c38ba5aeffbc0a847b1221a"><code>1044a6d</code></a> getting ready for checkout v7 release (<a href="https://redirect.github.com/actions/checkout/issues/2464">#2464</a>)</li> <li><a href="https://github.com/actions/checkout/commit/f0282184c7ce73ab54c7e4ab5a617122602e575f"><code>f028218</code></a> Bump the minor-npm-dependencies group across 1 directory with 3 updates (<a href="https://redirect.github.com/actions/checkout/issues/2462">#2462</a>)</li> <li><a href="https://github.com/actions/checkout/commit/d914b262ffc244530a203ab40decab34c3abf34d"><code>d914b26</code></a> upgrade module to esm and update dependencies (<a href="https://redirect.github.com/actions/checkout/issues/2463">#2463</a>)</li> <li><a href="https://github.com/actions/checkout/commit/537c7ef99cef6e5ddb5e7ff5d16d14510503801d"><code>537c7ef</code></a> Bump <code>@actions/core</code> and <code>@actions/tool-cache</code> and Remove uuid (<a href="https://redirect.github.com/actions/checkout/issues/2459">#2459</a>)</li> <li><a href="https://github.com/actions/checkout/commit/130a169078a413d3a5246a393625e8e742f387f6"><code>130a169</code></a> Bump js-yaml from 4.1.0 to 4.2.0 (<a href="https://redirect.github.com/actions/checkout/issues/2461">#2461</a>)</li> <li><a href="https://github.com/actions/checkout/commit/7d09575332117a40b46e5e020664df234cd416f3"><code>7d09575</code></a> Bump flatted from 3.3.1 to 3.4.2 (<a href="https://redirect.github.com/actions/checkout/issues/2460">#2460</a>)</li> <li><a href="https://github.com/actions/checkout/commit/0f9f3aa320cb53abeb534aeb54048075d9697a0e"><code>0f9f3aa</code></a> Bump actions/publish-immutable-action (<a href="https://redirect.github.com/actions/checkout/issues/2458">#2458</a>)</li> <li><a href="https://github.com/actions/checkout/commit/f9e715a95fcd1f9253f77dd28f11e88d2d6460c7"><code>f9e715a</code></a> block checking out fork pr for pull_request_target and workflow_run (<a href="https://redirect.github.com/actions/checkout/issues/2454">#2454</a>)</li> <li><a href="https://github.com/actions/checkout/commit/df4cb1c069e1874edd31b4311f1884172cec0e10"><code>df4cb1c</code></a> Update changelog for v6.0.3 (<a href="https://redirect.github.com/actions/checkout/issues/2446">#2446</a>)</li> <li>Additional commits viewable in <a href="https://github.com/actions/checkout/compare/de0fac2e4500dabe0009e67214ff5f5447ce83dd...9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0">compare view</a></li> </ul> </details> <br /> [](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) </details> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> |
||
|
|
eb8ac41afd |
Xcode beta (#3627)
Enable Xcode betas by default now that they are available on runners again ### Motivation: Xcode betas are available on runners again ### Modifications: Enable Xcode betas by default now that they are available on runners again ### Result Downstream packages will run Xcode beta builds An example of this running https://github.com/apple/swift-nio/actions/runs/27679540593/job/81863193279?pr=3627 |
||
|
|
e5f46a7b51 |
Hello, QUIC and HTTP/3! (#3624)
Motivation: swift-nio-quic and swift-nio-http3 were recently open sourced, they should be listed in the README. Modifications: - Update README Result: - More NIO |
||
|
|
3263350c88 |
Drop unused SystemPackage import from FileSystemTests (#3623)
Drop unused SystemPackage import from FileSystemTests ### Motivation: swift-system 1.7.0 exposes a new type named `FileType`, which is ambiguous with `NIOFS.FileType` when both modules are imported in the same file. This causes a compile-time error when building `FileSystemTests.swift` in the `NIOFSIntegrationTests` target. Fixes #3622. ### Modifications: Drop the unused `SystemPackage` import in `FileSystemTests.swift`. ### Result: `NIOFSIntegrationTests` builds against swift-system 1.7.0 and later. |
||
|
|
7586225bc1 |
Bump nightly-next CI Linux and Windows pipelines to Swift 6.4 (#3619)
### Motivation: The CI pipelines offer the latest released Swift versions (which have included Swift 6.3 for some time now) and a nightly-main and nightly-next. Right now nightly-next pipelines are all still 6.3, which is a problem and folks are likely operating under the misguided assumption that they have 6.4 coverage in their pipelines. ### Modifications: - Update the nightly-next pipelines to use 6.4 nightly images ### Result: Nightly next pipelines moved to 6.4 |
||
|
|
77b84ac2cd |
[NIOFileSystem] Fallback to rename when renameat2 is not available (#3612)
We are running into some issues when doing:
```swift
let writeOptions: OpenOptions.Write =
byteOffset > 0 ? .modifyFile(createIfNecessary: true) : .newFile(replaceExisting: true)
try await FileSystem.shared.withFileHandle(
forWritingAt: FilePath(outputFilePath),
options: writeOptions
) { fileHandle in
```
which results in crashes on some Android devices where `renameat2` is
not available:
```
('renameat2' system call failed with '(38) Function not implemented'.)
```
This PR adds functionality similar to what is already done for `EINVAL`
on Linux, such that both lead to the same recovery: stat the
destination, then plain rename() if absent.
And for non-exclusive renames where it also fails to function not
implemented, it falls back to plain `rename`.
2.101.0
|
||
|
|
03848cb0cc |
NonBlockingFileIO: error instead of silently truncating oversized reads (#3607)
Error instead of silently truncating oversized `NonBlockingFileIO` reads. ### Motivation: A `ByteBuffer` can hold at most `UInt32.max` bytes, so a read for more than that can never be satisfied. Today the read functions clamp the requested `byteCount` to `Int32.max` and then read at most that many bytes, returning a short buffer with no error and no end-of-file. That silently breaks the documented contract that the returned `ByteBuffer` is only shorter than `byteCount` when end-of-file is reached. It also means a request between 2 GiB and 4 GiB returns fewer bytes than the caller asked for. Resolves #2591. ### Modifications: - `read0` (both the `EventLoopFuture` and the `async` overload) now fails with an `IOError` (`EINVAL`) when `byteCount` is larger than `UInt32.max` instead of clamping. The guard runs before any allocation. On 32-bit platforms `Int.max` is smaller than `UInt32.max` so the guard is never hit there, and behaviour is unchanged. - `readSync` now caps the size of each individual `read`/`pread` syscall at `Int32.max` rather than capping the total `byteCount`. The OS returns `EINVAL` for a single read larger than `Int32.max`, and the surrounding loop already reads repeatedly until the whole request is satisfied or end-of-file is reached, so a request up to `UInt32.max` is now read in full. - Added tests covering the future and async read variants for a `byteCount` larger than a `ByteBuffer` can hold. I went with `IOError(errnoCode: EINVAL, ...)` rather than a new `NonBlockingFileIO.Error` case to keep this non API-breaking, matching the existing `IOError(errnoCode: ENOTDIR, ...)` use in the same file. Happy to switch to a typed error case if you would prefer that. ### Result: A read that cannot fit in a `ByteBuffer` fails clearly, and reads between 2 GiB and 4 GiB are no longer truncated. No public API changes. |
||
|
|
9ebe69d269 |
Add get/setMultipleIntegers on ByteBuffer (#3606)
`ByteBuffer` exposes `read`, `write`, and (since the peek work landed) `peek` variants of `MultipleIntegers`, but not the absolute-index `get`/`set` pair that every other integer accessor on `ByteBuffer` has. This fills that gap, which is what #2736 originally asked for. The thread on #2736 settled on adding `peek*` first so that the common "look without consuming" use case has a non-mutating, index-free spelling, and that is now in place. `get`/`set` remain useful for the niche cases that genuinely need to address an arbitrary index, so this completes the set of four for `MultipleIntegers` to match `getInteger`/`setInteger`. Both methods are generated from `dev/generate-bytebuffer-multi-int.sh`, the same script that produces the read/write/peek variants, so they stay in lockstep with the rest of the file across all arities (2 through 15): - `getMultipleIntegers(at:endianness:as:)` reads at an explicit index without moving the reader index and returns `nil` when the requested bytes are not readable, exactly like `getInteger(at:)`. - `setMultipleIntegers(_:at:endianness:as:)` writes at an explicit index without moving the writer index and returns the number of bytes written, exactly like `setInteger(_:at:)`. The new tests mirror the existing read/write and peek tests: a round-trip across both endiannesses, a check that the bytes written by `set` are byte-for-byte identical to `writeMultipleIntegers`, coverage of every arity, a check that neither method moves the reader or writer index, and the out-of-bounds / before-reader-index cases that must return `nil`. Resolves #2736 |
||
|
|
4e370dc4d7 |
NIOWebSocket: reject 8-byte payload lengths that exceed Int.max (#3603)
RFC 6455 §5.2 specifies that when the payload length indicator byte is 127, the following 8 bytes hold a 64-bit unsigned integer and the most significant bit of that integer must be 0. The maximum legal value is therefore 0x7FFFFFFFFFFFFFFF, which equals Int.max on all 64-bit platforms Swift supports. WSParser.parseStep read the raw UInt64 and passed it directly to Int() without a bounds check. Swift's Int initializer performs a checked conversion and traps on overflow, so any remote peer that sends a single WebSocket frame with the MSB of the 8-byte length set will cause a fatal error in the receiving process. No authentication is required; the frame is processed before any application handler runs. The fix adds a guard that rejects the frame with NIOWebSocketError.invalidFrameLength before the conversion, which is the same error path used for frames that exceed maxFrameSize. The call site in decode() is updated to propagate the throw. A regression test covers the exact byte sequence that previously caused the fatal trap. Co-authored-by: g0w6y <g0w6y@users.noreply.github.com> Co-authored-by: Cory Benfield <lukasa@apple.com> |
||
|
|
d20fa05a64 |
Fix readInlineArray reading from the wrong index when readerIndex is non-zero (#3605)
ByteBuffer.readInlineArray reads each element through getInteger(at:). The index parameter of getInteger(at:) is an absolute index into the buffer, the same one readInteger passes self.readerIndex into. The loop in readInlineArray instead passed stride * index, which starts at zero and never accounts for the reader index. As long as the buffer has a reader index of zero this absolute index lines up with the bytes the caller expects, which is why the current tests pass: they all read from a freshly written buffer. On any buffer whose reader index has already moved (the normal case once some bytes have been consumed, for example reading a length prefix before the array), getInteger(at:) is given an index below the reader index. rangeWithinReadableBytes rejects it, getInteger returns nil, and the force-unwrap on the result traps. So a public read API crashes the process on entirely valid input. The fix snapshots the reader index before building the array and offsets each element index by it, so getInteger(at:) gets the correct absolute index. The multiplication stays bounded by bytesRequired as before, and adding the reader index cannot overflow because the result stays within the writer index. I added a regression test that writes a short prefix, reads it off so the reader index is non-zero, then reads an InlineArray and checks both the element values and the resulting reader index. It traps before this change and passes after it. The three existing InlineArray tests, the full ByteBufferTest suite (275 tests), and ByteBufferSpanTests all still pass. Reopening the change from #3604, which I closed inadvertently. The original branch and fork were deleted, so this is a fresh PR with the identical commit. |
||
|
|
9670fe1d68 |
Don't fatalError if NIOTypedHTTPServerUpgraderStateMachine is in state finished when finding upgrader (#3597)
Don't fatalError in NIOTypedHTTPServerUpgraderStateMachine.findingUpgraderCompleted` when the state is `.finished`. ### Motivation: There is a race where the connection can be closed and the NIOTypedHTTPServerUpgraderHandler can be removed setting the state to `.finished` while we are still finding upgraders. And then when `findingUpgraderCompleted` gets called it would fatalError. ### Modifications: - Return `nil` as an action if the state is `.finished` when `findingUpgraderCompleted` is called. - Added a new set of tests which test the `NIOTypedHTTPServerUpgraderStateMachine` directly instead of relying on `HTTPServerUpgraderTests`. I used Swift Testing for these, not sure what NIO policy on new tests are? ### Result: No more crashes and better testing for NIOTypedHTTPServerUpgraderStateMachine --------- Co-authored-by: Cory Benfield <lukasa@apple.com> |
||
|
|
158030ef53 |
Support multiple benchmark packages per macOS workflow invocation (#3602)
### Motivation * External callers of `macos_benchmarks.yml` (e.g. swift-log) currently invoke the reusable workflow once per benchmark package, paying self-hosted macOS runner-recycling cost for each invocation. ### Modifications * Add a new `benchmark_package_paths` input to `.github/workflows/macos_benchmarks.yml` and mark the singular `benchmark_package_path` as deprecated. The run step forwards both inputs straight to the script via `BENCHMARK_PACKAGE_PATH` and `BENCHMARK_PACKAGE_PATHS` environment variables; the workflow itself does no path parsing. * Teach `scripts/check_benchmark_thresholds.sh` to accept `BENCHMARK_PACKAGE_PATHS` as either a JSON array of strings (auto-detected by a leading `[`, requires `jq`) or a newline-separated list, falling back to the legacy `BENCHMARK_PACKAGE_PATH` when unset or when the JSON form is an empty array. * The script now loops over the resolved package list, wraps each iteration in a GitHub Actions `::group::`, and emits an `::error::` summary listing failed packages at the end, exiting non-zero if any failed. ### Result * A single workflow invocation runs all listed packages serially on each Swift/Xcode runner, paying runner-recycling cost once per Swift version instead of once per (version x package). * Existing single-package callers keep working unchanged. * Adopters of the script in other contexts (e.g. the Linux `benchmarks.yml`) can pick up multi-package support by passing `BENCHMARK_PACKAGE_PATHS` without reimplementing parsing or failure-collection logic. An example of this working https://github.com/apple/swift-log/pull/466 |
||
|
|
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.2.100.0 |
||
|
|
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. |