`cmake_tests.yml` has a `cmake_version` input and passes it to
`scripts/cmake-build.sh` as `CMAKE_VERSION`, but the script does not use
that value, so the CMake from the image's apt is used instead.
With this patch, when `CMAKE_VERSION` is set, the script downloads the
release from Kitware's GitHub releases on Linux (x86_64/aarch64) and
uses it for the build.
This lets projects that need a newer CMake than the image's apt provides
use the shared workflow by setting `cmake_version`.
This is blocking https://github.com/apple/swift-certificates/pull/325.
### Motivation:
One of my project uses `NIOHTTP1TestServer` for testing and for
responses that contain the `content-length` header + `connection:
close`,
the test was flaky - failing intermittently, because the client closed
the connection before the test managed to submit `.end` to the test
server.
The cause was a race condition between the test and the client's and
server's threads hosting their respective event loops.
### Modifications:
Now `NIOHTTP1TestServer` captures the channel that sent the `.head`, and
even once `currentClientChannel` changes (but before the next `.head` is
sent),
when a call to send `.end` comes in, uses the channel associated with
the previous `.head`, rather than reading `currentClientChannel`.
This test is skipped on Darwin as it requires the platform to detect
early EOF.
### Result:
More reliable tests that involve two requests that come in at once (in a
deterministic order), when the second one is parked and ready right
after the first one finishes.
Create temporary directories with owner-only permissions.
### Motivation:
`FileSystem.createTemporaryDirectory(template:)` (and
`withTemporaryDirectory`, which uses it) creates the directory with
`FilePermissions.defaultsForDirectory`, i.e. 0755. When the template
points into a shared directory such as `/tmp`, other local users can
list the temporary directory and read anything written into it with the
default 0644 file permissions. `mkdtemp(3)`, Go's `os.MkdirTemp` and
Python's `tempfile.mkdtemp` all use 0700 for this reason.
Repro with a umask of 022:
```swift
let dir = try await FileSystem.shared.createTemporaryDirectory(template: "/tmp/nio-repro-XXXXXX")
try await FileSystem.shared.withFileHandle(forWritingAt: "\(dir)/secret", options: .newFile(replaceExisting: false)) { _ in }
// before: dir is drwxr-xr-x, secret is -rw-r--r--, readable by every local user
// after: dir is drwx------
```
### Modifications:
- Pass `.ownerReadWriteExecute` when `_createTemporaryDirectory` creates
the directory, in both `NIOFS` and `_NIOFileSystem`. Intermediary
directories created from the template get the same permissions, since
they are created by the same `_createDirectory` call.
- Document the permissions on `createTemporaryDirectory(template:)`.
- Add `testCreateTemporaryDirectoryIsOnlyAccessibleByOwner`.
### Result:
Temporary directories are only accessible by their owner.
I verified the before/after modes for both modules with a small
executable against this branch on macOS (`swift build` is clean). I
couldn't run the XCTest target locally because this machine only has the
Command Line Tools.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
We introduced a new configuration type in #3746 to make further
extensions to the server pipeline (#3745 for example) easier to
introduce.
The plan was to merge #3745 soon after #3746 was merged, because #3745
added a breaking change to the new config type.
However, #3745 needs some more consideration. We should therefore revert
the change in #3746 to unblock new releases from being made until we
come up with a better solution.
### Modifications:
A clean revert of PR #3746.
### Result:
Unblocks new releases.
Drop `@unchecked` from `TokenBucket`'s `Sendable` conformance.
### Motivation:
`TokenBucket` (in both `NIOFS` and `_NIOFileSystem`) is marked
`@unchecked Sendable`, but its only stored property is `private let
lock: NIOLockedValueBox<State>`, and `NIOLockedValueBox` is `Sendable`
when its value is (`State` holds an `Int` and a
`Deque<CheckedContinuation<Void, Never>>`). The compiler can verify this
conformance on its own, and keeping `@unchecked` means it would not
catch a future change that breaks sendability.
### Modifications:
- Replace `@unchecked Sendable` with `Sendable` on `TokenBucket` in
`NIOFS` and `_NIOFileSystem`.
### Result:
No behavior change; the conformance is now checked by the compiler.
Verified locally on macOS (Swift 6.4.2): `swift build --build-tests
-Xswiftc -strict-concurrency=complete` produces no new diagnostics, and
`NIOFSTests`, `NIOFSIntegrationTests` and `NIOFSFoundationCompatTests`
pass.
### Motivation:
`NIOHTTP1.HTTPPipelineSetup` contains helper methods which add HTTP/1
client/server handlers to the provided channel pipeline.
Over time, we have had to duplicate these methods when introducing a new
configuration option in order to not break API.
As a result, there is now lots of duplication in
`NIOHTTP1.HTTPPipelineSetup` and introducing more configuration options
is very cumbersome. We should instead add a configuration type to solve
this problem.
### Modifications:
- Added new configuration types named
`NIOHTTPServerPipelineConfiguration`, and
`NIOHTTPServerPipelineSynchronousConfiguration`.
- Added a new pipeline setup helper method on `ChannelPipeline` and
`ChannelPipeline.SynchronousOperations` that requires the configuration
type as an argument.
- Deprecated all existing helper methods on `ChannelPipeline` and
`ChannelPipeline.SynchronousOperations`.
### Result:
Better API.
## Motivation
`QUICBinaryEncodingStrategy.writeInteger(_:reservedCapacity:to:)`
switches on `max(reservedCapacity, bytesNeededForInteger(integer))` and
handles only 1, 2, 4 and 8, falling through to
`fatalError("Unreachable")` otherwise.
`bytesNeededForInteger` only ever returns those four values, but
`reservedCapacity` is guarded solely against being greater than 8. A
reserved capacity of 3, 5, 6 or 7 therefore reaches the unreachable case
and traps:
```swift
var buffer = ByteBuffer()
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
strategy.writeInteger(1, reservedCapacity: 3, to: &buffer)
// NIOCore/ByteBuffer-quicBinaryEncodingStrategy.swift:126: Fatal error: Unreachable
```
This is reachable without calling that method directly.
`requiredBytesHint` is a public `var Int` with no validation — the
initialiser takes the 1/2/4/8 `IntegerLength` enum, but the property can
be assigned any value afterwards, and
`writeLengthPrefixed(strategy:writeData:)` passes it straight through as
the reserved capacity:
```swift
var strategy = ByteBuffer.QUICBinaryEncodingStrategy(requiredBytesHint: .one)
strategy.requiredBytesHint = 3 // public var, accepted silently
var buffer = ByteBuffer()
buffer.writeLengthPrefixed(strategy: strategy) { $0.writeString("hi") }
// Fatal error: Unreachable
```
## Modifications
Round the length up to the next valid QUIC integer length rather than
trapping, which is what the surrounding comment already intends by "use
more space than necessary in order to fill the reserved space":
```diff
- case 4:
+ case 3, 4:
- case 8:
+ case 5, 6, 7, 8:
```
RFC 9000 § 16 permits encoding a value in more bytes than it strictly
requires, and `writeLengthPrefixed` already shifts the payload when the
integer turns out longer than was reserved (`case reservedCapacity...`),
so writing 4 bytes for a reservation of 3 is handled by existing code.
## Result
No trap for any `reservedCapacity` in `0...8`, and the encoded value
still round-trips.
I checked every combination of `reservedCapacity` in `0...8` against the
boundary values `0, 1, 63, 64, 16383, 16384, 1073741823, 1073741824,
4611686018427387903`: all 81 encode, decode back to the original value,
and leave no bytes behind. On `main` the same check traps.
## Testing
The existing `testRoundtripWithReservedCapacity` iterates over `[0, 1,
2, 4, 8]` — skipping exactly the values that trap, which is presumably
why this went unnoticed. I've added a companion
`testRoundtripWithNonPowerOfTwoReservedCapacity` covering 3, 5, 6 and 7,
asserting both the encoded length and that the value round-trips. It
fails on `main` and passes with this change.
Full test suite: **2455 tests, 0 failures.**
## A note on the alternative
Rounding *down* to the largest valid length that still fits the
reservation would also avoid the trap and waste fewer bytes — for
`reservedCapacity: 3` that would write 2 bytes rather than 4. I went
with rounding up because the existing comment says to use more space
rather than less, and because it keeps the guarantee that at least the
reserved number of bytes is written. Happy to switch if you'd prefer the
other behaviour.
If you would rather fix this at the source by validating
`requiredBytesHint` or changing its type to `IntegerLength`, that would
be source-breaking, so I left it alone — but the public setter is what
makes this reachable in ordinary use.
---------
Co-authored-by: Raphael Hiesgen <r_hiesgen@apple.com>
### Motivation:
Users may want to move a non-Sendable value into an EventLoopFuture.
This is safe if we take the value as `sending`
### Modifications:
Change functions whcih currently require Sendable parameters to instead
take the parameter as `sending` where possible. This seems to not break
API
Some functions take closures whcih return Sendable values, those ones
now take closures which return sending values. This has been done as an
overload, because a straight replacement seems to break API
### Motivation:
Stay up-to-date with the vendored llhttp version.
### Modifications:
* Update script to work with current releases.
* Run script to update vendored llhttp version.
### Result:
New llhttp version.
Add a configurable job timeout to `swift_test_matrix.yml`.
### Motivation:
Matrix jobs have no timeout, so a stalled nightly toolchain build runs
until the 6-hour limit. From Sep 27 to Oct 10, apple/swift-nio-quic had
139 such jobs (about 50,000 runner minutes), all on Linux nightly-main
legs.
### Modifications:
Add a `timeout_minutes` input (default 120) and use it as the
`execute-matrix` job timeout.
### Result:
Stalled jobs are cancelled after 2 hours instead of 6. The longest
successful matrix job I found was 81 minutes (grpc-swift-2 Examples), so
current callers fit, and they can raise the limit if needed.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Reenable 6.1 CI workflows by default.
### Motivation:
6.1 workflows were disabled by default in
https://github.com/apple/swift-nio/commit/d09ffc8ad6437bc278897279e33150d8e39ee3d5.
However, we haven't been able to drop 6.1 in all repos using these
workflows yet, so this PR temporarily reenables the 6.1 workflows until
we can land that work everywhere else.
### Modifications:
Reenable 6.1 CI workflows by default.
### Result:
6.1 workflows are enabled by default.
### Motivation
SwiftNIO provides convenience functions for a range of socket options.
This PR adds convenience options for fragmentation-related socket
options on Darwin and Linux. One particular use case is disabling
fragmentation when using QUIC, which disallows IP fragmentation of its
datagrams.
### Modifications
* Add `NIOBSDSocket.Option.ip_dontfrag` (Darwin).
* Add `NIOBSDSocket.Option.ipv6_dontfrag` (Darwin and Linux).
* Add `NIOBSDSocket.Option.ip_mtu_discover` and `.ipv6_mtu_discover`
(Linux). They set the path MTU discovery mode, which influences
fragmentation.
### Result
Adopters can easily configure IP fragmentation.
### Motivation
* Swift 6.4 has been released, so we should add it to our CI coverage.
### Modifications
* Update `apple/swift-nio/scripts/generate_matrix.sh`
* Update `apple/swift-nio/scripts/check-matrix-job.sh`
* Update reusable adopters of `swift_test_matrix.yml`
* Update end-user adopter workflows of `swift_test_matrix.yml`
* Add Swift 6.4 inputs to `macos_tests.yml` and `macos_benchmarks.yml`
* Add a 6.4 release job to `wasm_swift_sdk.yml`
* Enable the Windows 6.4 unit test job in `main.yml` and
`pull_request.yml`
* Copy benchmark thresholds from 6.3
### Result
* NIO runs Swift 6.4 CI, and downstream repositories can opt-in.
---
- Successful run (minus broken nightlies):
https://github.com/apple/swift-nio/actions/runs/36403423635?pr=3750
Corrected `compatability` to `compatibility` in the default
`RecvByteBufferAllocator` extension comment.
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation
Decoders are state machines and state machines are a natural fit for
non-copyable types. Today `ByteToMessageDecoder` and
`NIOSingleStepByteToMessageDecoder` require their conformers to be
copyable.
While we are here we also want `NIOSingleStepByteToMessageDecoder` to be
able to declare a concrete error type, so that callers can handle decode
errors without going through an existential.
### Changes
- Make `ByteToMessageDecoder` and `NIOSingleStepByteToMessageDecoder`
`~Copyable`.
- Add an `associatedtype DecodeError: Error = any Error` to
`NIOSingleStepByteToMessageDecoder` and spell decode and decodeLast as
`throws(DecodeError)`. Decoders that don't declare it keep behaving
exactly as before.
- Allow `~Copyable` `ByteToMessageDecoder` in `ByteToMessageHandler`.
- Since `~Copyable` types cannot be type erased into an existential
before macOS 15, we have to work around the existing `CanDequeueWrites`
dance: instead of casting `self` to `CanDequeueWrites` in
`handlerAdded`, ByteToMessageHandler gains an optional
`deliverQueuedWrite` closure. It is formed in the constrained
`ChannelOutboundHandler.write`, the only place where `Decoder`'s
`WriteObservingByteToMessageDecoder` conformance is statically known,
the first time a write arrives re-entrantly.
This has to be a closure rather than a protocol requirement on
`ByteToMessageDecoder`. `Decoders` may conform to
`WriteObservingByteToMessageDecoder` conditionally while conforming to
`ByteToMessageDecoder` unconditionally — `HTTPDecoder` does exactly this
— and all generic instantiations share one `ByteToMessageDecoder`
witness table, so such a requirement could only ever be witnessed by a
non-observing default and the write would be silently dropped.
- Split the delivery out of `tryDecodeWrites` into an `@inline(never)
dequeueWrites()`. `decodeLoop` calls `tryDecodeWrites` on every
iteration, so the empty-queue check has to stay cheap; keeping the
delivery inline tripled that function's size (50 → 141 instructions) and
showed up directly on the normal decode path.
- `ByteToMessageDecoderVerifier` allows `~Copyable`
`ByteToMessageDecoder`s.
- Added tests that use the newly lifted `~Copyable` restriction, plus
regression coverage for a decoder whose write-observing conformance is
conditional (the HTTPDecoder shape) and for constructing the handler in
a generic context.
### Result
Decoders may be non-copyable and may declare a concrete error type.
The normal decode path does not change performance. The re-entrant write
path costs one extra allocation per handler, but is meaningfully cheaper
in instructions. I'm happy to provide the benchmarks used to generate
those numbers in a separate pr – leaving them out here, as we would end
up with as many benchmarks as we have unit tests sooner or later.
Instructions, macOS arm64, per 1000 iterations, min of 5 interleaved
rounds:
```
┌──────────────────────────────┬────────────┬────────────┬───────────────────────────────────┐
│ │ main │ this PR │ │
├──────────────────────────────┼────────────┼────────────┼───────────────────────────────────┤
│ decode, no write observation │ 9,404,415 │ 9,360,896 │ −0.46% (noise ~0.8%, i.e. parity) │
├──────────────────────────────┼────────────┼────────────┼───────────────────────────────────┤
│ decode + re-entrant write │ 13,656,063 │ 12,541,951 │ −8.16% │
├──────────────────────────────┼────────────┼────────────┼───────────────────────────────────┤
│ handler add / remove │ 85,983,231 │ 83,361,791 │ −3.05% (noise ~2.2%) │
└──────────────────────────────┴────────────┴────────────┴───────────────────────────────────┘
```
Replacing the CanDequeueWrites existential with the closure is what
improves the reentrant write path: delivering a queued write is now a
direct closure call rather than a witness-table dispatch, and
handlerAdded no longer performs a runtime conditional-conformance
lookup.
The saving grows with the number of writes queued per decode — around
−16% with 8 queued writes, though that benchmark is noisier.
Allocations (nio-alloc-counter-tests, Swift 6.2):
```
┌────────────────────────────┬─────────┬─────────┬────────┐
│ │ main │ this PR │ │
├────────────────────────────┼─────────┼─────────┼────────┤
│ 1000_reqs_1_conn │ 27,341 │ 27,342 │ +1 │
├────────────────────────────┼─────────┼─────────┼────────┤
│ 1_reqs_1000_conn │ 368,000 │ 369,000 │ +1,000 │
├────────────────────────────┼─────────┼─────────┼────────┤
│ ping_pong_1000_reqs_1_conn │ 296 │ 296 │ — │
├────────────────────────────┼─────────┼─────────┼────────┤
│ decode_1000_ws_frames │ 2,000 │ 2,000 │ — │
└────────────────────────────┴─────────┴─────────┴────────┘
```
Forming the closure captures Decoder.OutboundIn's metadata, so it
allocates once per handler that actually queues a re-entrant write —
1_reqs_1000_conn builds 1000 such handlers, hence +1000. main's
existential cast did not allocate, so this is a new cost rather than
staying flat. The 1_reqs_1000_conn threshold is raised by 1000 for
6.1/6.2/6.3; the nightly toolchains are unchanged (10,000 on both — they
specialize the closure away entirely).
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
`EventLoopFuture.get()` violates Structured Concurrency in two ways:
1. It doesn't automatically propagate cancellation
2. It doesn't return control back on cancellation
(1) is unfixable without user help but (2) we can address.
### Modifications:
- Add `EventLoopFuture.getAbandoningOnCancel()`
### Result:
- Users now have a way to at least get back control.
Add channel options to read a vsock socket's local and remote addresses
### Motivation:
NIOPosix supports vsock via `VsockAddress`, `ServerBootstrap.bind(to:)`
and `ClientBootstrap.connect(to:)`, but `Channel.localAddress` and
`Channel.remoteAddress` are always `nil` on vsock channels because
`NIOCore.SocketAddress` has no vsock representation.
Two things are unreachable as a result:
- A server accepting a vsock connection cannot tell which context
connected. The peer's context ID is the only identity a vsock connection
carries, and it is supplied by the kernel rather than the peer, which
makes it a natural basis for authorization.
- A listener bound to `VsockAddress/Port/any` cannot learn the port the
kernel assigned, so callers are forced to hard-code ports and race for
them.
`ChannelOptions.localVsockContextID` already exists for the first half
of this problem, but it reports only the context ID, not the port.
Adding a `.vsock` case to `SocketAddress` would fix both, but it is
source-breaking for every exhaustive switch over that enum, in NIO and
downstream.
### Modifications:
- Add `ChannelOptions.Types.LocalVsockAddress` and `RemoteVsockAddress`,
both get-only with `Value == VsockAddress`, alongside the existing
`LocalVsockContextID`.
- Add `BaseSocket.getLocalVsockAddress()` and `getRemoteVsockAddress()`,
sharing a helper that reads into a `sockaddr_storage` via
`withMutableSockAddr` and `convert()`, mirroring `BaseSocket.get_addr`.
On a non-vsock socket `getsockname`/`getpeername` fill a different
`sockaddr`, and reinterpreting those bytes would yield a context ID
derived from unrelated data such as a peer's IP address and port, so the
helper checks the address family and throws
`SocketAddressError.unsupported` on a mismatch.
- Service both options in `SocketChannel.getOption0`, and
`LocalVsockAddress` in `ServerSocketChannel.getOption0`.
`RemoteVsockAddress` is not serviced on `ServerSocketChannel`: a
listener has no peer.
- Tests: both helpers reject non-vsock sockets; over vsock loopback the
client's peer port matches the port the listener bound and the accepted
channel reports the same CID the client saw; a `Port/any` listener
reports a concrete port and a CID of `.any`, matching the channel
option. The loopback tests are gated on `System.supportsVsockLoopback`
in the same way as `testGetLocalCID` and `testEchoVsock`, so they run in
the `vsock-tests` CI job and skip elsewhere.
This is purely additive: two new option types, four new static
accessors, and new arms in two internal switches. No existing
declaration changes.
### Result:
A vsock server can identify the connecting context, and a wildcard-bound
listener can report its port:
```swift
let peer = try await channel.getOption(.remoteVsockAddress).get()
peer.cid // the connecting context's CID
let local = try await listener.getOption(.localVsockAddress).get()
local.port // the port a `Port/any` bind was given
```
Reading either option on a channel that isn't backed by a vsock socket
throws `SocketAddressError.unsupported`.
Co-authored-by: George Barnett <gbarnett@apple.com>
### Motivation:
`NIOBSDSocket.Option` provides shorthand API for socket options, e.g.
`.so_reuseaddr` for `SO_REUSEADDR`. We don't have API for
`SO_REUSEPORT`.
`SO_REUSEPORT` is used to bind more than one socket to the same address
and port to spread accepts or datagrams over multiple sockets and
support hot restarts.
Users can already use it today, but must use `init(rawValue:)`, and
import the platform C lib, etc:
```swift
.channelOption(.socketOption(.init(rawValue: SO_REUSEPORT)), value: 1)
```
There's no reason not to provide a convenience for this option, like we
do for many others.
### Modifications:
This PR adds `NIOBSDSocket.Option.so_reuseport`, wrapping
`SO_REUSEPORT`, alongside the other options in `BSDSocketAPI.swift`.
It's not provided on Windows or WASI, which don't have `SO_REUSEPORT`,
but there was already precedent for other options like this, e.g.
`SO_TIMESTAMP`.
### Result:
Users can pass `.socketOption(.so_reuseport)` like other supported
socket options:
```swift
DatagramBootstrap(group: group)
.channelOption(.socketOption(.so_reuseport), value: 1)
.bind(host: "127.0.0.1", port: 12345)
```
### What's wrong
`Sources/NIOCore/DispatchQueue+WithFuture.swift:30`, the return-value
line of the
public `DispatchQueue.asyncWithFuture(eventLoop:_:)`:
```swift
/// - returns a new `EventLoopFuture<ReturnType>` with value returned by the `block` parameter.
```
There is no colon after `returns`, so DocC does not recognise it as a `-
Returns:`
callout. The method renders **no Return Value section**; the sentence
falls into the
Discussion as a stray bullet instead.
Two further identifiers in that same sentence do not exist on this
method:
- `ReturnType` — the generic parameter is `NewValue`
(`asyncWithFuture<NewValue: Sendable>`).
- `block` — the closure parameter is `callbackMayBlock`.
The `- Parameters:` block directly above it is correct and unaffected.
### Reproduction
I could not build NIO to render this page (see Testing below), so I
reproduced the
DocC behaviour on a standalone module carrying this method's doc comment
**verbatim**,
alongside a copy with only the colon restored. Same file, same DocC, so
the callout
spelling is the only variable:
```
broken(eventloop:_:).json
HEADING: Discussion
codeListing ...
unorderedList: "returns a new `EventLoopFuture<ReturnType>` with value returned by the `block` parameter."
fixed(eventloop:_:).json
HEADING: Return Value
paragraph: "A new `EventLoopFuture<NewValue>` with value returned by the `callbackMayBlock` parameter."
```
The broken form produces a `Discussion` heading with the text demoted to
a list item.
The fixed form produces a `Return Value` heading with a proper
paragraph.
Commands, if you want to confirm it against the real module:
```
swift build --target NIOCore \
-Xswiftc -emit-symbol-graph -Xswiftc -emit-symbol-graph-dir -Xswiftc /tmp/sg
xcrun docc convert --fallback-display-name NIOCore \
--fallback-bundle-identifier org.swift.NIOCore \
--additional-symbol-graph-dir /tmp/sg --output-path /tmp/out.doccarchive
```
then read
`data/documentation/niocore/dispatchqueue/asyncwithfuture(eventloop:_:).json`.
Worth noting: **DocC emits no diagnostic for this.** `docc convert`
exits 0 with an
empty warning list, so nothing in a normal build or docs check surfaces
it. The
rendered output is the only evidence.
### Scope, and a judgement call
One line. This is the only occurrence in the repository — I grepped all
of `Sources/`
for `- returns`/`- Returns` without a colon and for backticked parameter
names, and
there is nothing else.
**The judgement call is fixing `ReturnType` and `block` in the same
change.** The
narrower alternative is to add only the colon and leave the two names
for a separate
PR. I did not do that, because restoring the colon is exactly what
*promotes this
sentence from invisible to visible* — shipping the colon alone would put
two
identifiers that do not exist on the method onto the rendered page for
the first time.
Correcting them is what makes the fix an improvement rather than a
regression in
visible accuracy. If you would rather have the colon alone and handle
the names
separately, say so and I will split it.
### Testing
**I did not run NIO's test suite, and I want to be straightforward about
why rather
than imply a green run.** The machine I am working on is
disk-constrained and a NIO
build did not fit; that is a limitation on my side, not a judgement that
the suite is
unnecessary. What I did verify:
- The defect and its uniqueness by reading, against `main` at
`8c063f043d94c120d0f8d6303ef4fc7918e3561d`.
- The identifier mismatches against the actual declaration in the same
file.
- DocC's parsing behaviour, via the standalone reproduction above (real
output, not asserted).
- The new line is 110 characters, within the repository's configured
`lineLength` of 120.
This is a comment-only change to a doc comment; it cannot affect
compiled behaviour.
CI will confirm the build and the format check.
### Disclosure
This change was written with AI assistance. The DocC output above is
real output from
my machine, not generated text.
Co-authored-by: hxperl <16929288+hxperl@users.noreply.github.com>
### Motivation:
We started seeing issues in Swift Log with building for Android when
using types from the Concurrency module.
Folks from the Android workgroup suggested we don't build with static
stdlib, and I confirmed that removing it fixes the issue:
https://github.com/apple/swift-log/actions/runs/34365246956/job/102512196662?pr=509
### Modifications:
Links the stdlib dynamically (default) for Android.
### Result:
Unblock Swift Log's CI. This topic can be further discussed in the
ongoing GitHub Actions unification.
### Motivation:
In October 2025, the naming convention for the file name of the Android
Swift SDK changed to drop the version. Our script expected it however,
so all SDK bundles published after that were getting skipped, which has
now caused other problems.
### Modifications:
Fixed the Android SDK file suffix.
However, this is only an immediate fix. A proper fix, which is out of
scope of this PR, will be to adopt the explicit "download" parameter in
the API
(https://www.swift.org/openapi/openapi.html#/Toolchains/listAndroidSDKDevToolchains),
which gives us the filename and we don't have to guess.
### Result:
Projects start downloading up-to-date Android Swift SDKs again.
Fix static Linux SDK snapshot resolution falling back to outdated
versions.
### Motivation:
The `main` job of the static Linux SDK matrix has been resolving
snapshots from over a month ago instead of recent nightlies.
`scripts/install_swift_sdk.sh` hardcodes the static-sdk artifact suffix
as `_static-linux-0.0.1`, but swift.org now publishes it as `0.1.0`.
Every recent snapshot 404s on the SDK URL, so the discovery loop keeps
rejecting them until it lands on a December snapshot that still used the
old suffix.
Fixes#3711
### Modifications:
`scripts/install_swift_sdk.sh` now tries a small list of known
static-sdk suffixes (`0.1.0`, then `0.0.1`) for each candidate snapshot
instead of a single hardcoded value, and stops at the first one that
resolves. The existing snapshot/SDK return-code checks and logging are
unchanged.
### Result:
The `main` branch job picks up current nightly snapshots again instead
of falling back 40+ days. If Apple bumps the static SDK version again in
the future, adding it to the candidate list is a one-line fix.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
### Motivation
`ByteBuffer._Storage`'s `_capacity` and `_bytes` are only modified, if
the `ByteBuffer._Storage` is uniquely referenced. This is enforced by
the `isKnownUniquelyReferenced` checks in ByteBuffer itself. For this
reason unexclusive read and write access to these properties can never
happen.
Since the compiler sadly isn't able to spot this. Let's help it, by
marking the properties with `@exclusivity(unchecked)`
### Changes
- Mark ByteBuffer._Storage's _capacity and _bytes
`@exclusivity(unchecked)`
### Result
Significant reduction in instructions, which leads to faster ByteBuffer
code.
### Motivation
The new `NoUseUnstructuredThrowingTask` diagnostic on nightly-main flags
every `Task { try await ... }`
whose result is dropped. We have a few of those.
### Changes
- Use `async let _` instead of a fire-and-forget `Task` in
`NIOAsyncWriterTests` and
`NIOThrowingAsyncSequenceTests`.
- `NIOPerformanceTester`: rethrow the error from the `Task` in
`measureAndPrint` instead of
swallowing it.
- Name the `swift-nio` dependency explicitly in
`Benchmarks/Package.swift`; SwiftPM otherwise infers
it from the directory name, which breaks in git worktrees.
### Result
No warnings. Suspended yields in the tests are cancelled when the test
returns instead of leaking
past it, and async benchmarks fail loudly.
### Motivation:
Some CI is red that doesn't need to be red.
### Modifications:
- Update the nightly next thresholds for the integration tests – only
improvements.
### Result:
- Green CI for nightly next integration tests
### Motivation
We want to extend `ByteToMessageDecoderVerifierTest` with tests that
verify non-copyable decoders. Instead of adding more XCTests, lets first
move all existing tests to swift-testing.
### Changes
- Mechanical translation of `ByteToMessageDecoderVerifierTest` from
XCTest to Swift Testing.
### Result
No behaviour change. We can write the new tests in Swift Testing.
### Motivation
We want to extend `SingleStepByteToMessageDecoderTest` with tests for
non-copyable decoders and typed throws. Instead of adding more XCTests,
lets first move all existing tests to swift-testing.
### Changes
- Mechanical translation of `SingleStepByteToMessageDecoderTest` from
XCTest to Swift Testing.
### Result
No behaviour change. We can write the new tests in Swift Testing.
Fix the following warnings:
> setter for property 'xxx' is private and cannot be referenced from an
'@inlinable' function; this will be an error in a future Swift language
mode
### Motivation:
Eight doc comments name an argument that the declaration below them does
not have, so DocC has nothing to bind the description to and quietly
drops it. Nothing warns about this: Swift has no equivalent of
`-Wdocumentation`, and DocC stays silent rather than complaining, so
these sit until somebody reads the generated page and wonders where the
description went
| file | the comment says | the declaration says |
|---|---|---|
| `NIOPosix/ServerSocket.swift` | `descriptor` | `socket` |
| `NIOPosix/Socket.swift` ×2 | `descriptor` | `socket` |
| `NIOHTTP1/ByteCollectionUtils.swift` | `bytes` | `to` |
| `NIOHTTP1/HTTPTypes.swift` | `buffer` | `headers` |
| `NIOFS/BufferedStream.swift` ×2 | `sequence` | `element` |
| `NIOFS/SystemFileHandle.swift` | `executor` | `threadPool` |
The socket ones are worth a word. Each of those files has a pair: a
deprecated `init(descriptor:)` and its replacement `init(socket:)`, and
the rename is recorded right there in `@available(*, deprecated,
renamed: "init(socket:setNonBlocking:)")`. The replacement inherited the
wording of the one it replaced, so the doc still says `descriptor`. The
deprecated ones are correct and I left them alone
And the last two are the same defect in two copies of one module,
`NIOFS` and `_NIOFileSystem`, which is what a verbatim copy of a file
does to a mistake inside it. Fixing one and not the other would leave
them out of sync, so both are in here
### Modifications:
Renamed the documented argument to the one in the declaration, eleven
lines across eight files
One is slightly more than a rename: in `ByteBuffer.write(headers:)` the
entry described the buffer the method is called on rather than its
argument, so it now describes `headers` and keeps the note about the
writer index
### Result:
The parameter descriptions reach the generated documentation. No API
change, no behaviour change, comments only
btw these came out of a checker I wrote for exactly this, run over the
tree and then read by hand one by one. Six of the things it flagged
turned out to be my parser rather than your code, and those are fixed on
my side rather than sent to you 🙌🏼
all of it on a MacBook Air M3, of course
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
### 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>
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>
### 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.
### 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.
### 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>
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
### 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.
### 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>
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.
## 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>
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.
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