# Motivation
We only support the last three Swift released versions which are at this
time 5.9, 5.10 and 6.
# Modification
This PR drops anything related to Swift 5.8.
# Result
Version support aligned.
### Motivation:
In the past we introduced a memory leak around the creation of and
waiting on futures - we should protect against leaks in this fundamental
operation.
### Modifications:
Add a new benchmark which would have failed with the previous bug
### Result:
Regression protection for this type of memory leak.
Disable semver-label-check locally when run via `act`.
### Motivation:
This check makes no sense when run locally.
### Modifications:
Disable semver-label-check locally when run via `act`.
### Result:
The label check should no longer run and fail locally.
### Motivation:
Adopt `NIOThrowingAsyncSequenceProducer` in NIOFileSystem to reduce code
duplication.
### Modifications:
Adopt `NIOThrowingAsyncSequenceProducer` in NIOFileSystem
`DirectoryEntryProducer` and `FileChunkProducer`.
This change was previously merged and then backed out due to issues
(#2879). The original change is in the first commit, the second commit
contains additional changes.
In the original adoption of `NIOThrowingAsyncSequenceProducer` the code
did not deal with backpressure being applied very well, in some cases
causes hangs.
A key bug was that it was not protected against re-entrant calls to
`produceMore`. Such calls may happen e.g. when the producer has been
asked to pause producing and then resume again before the initial read
had completed. This resulted in overlapping reads and re-ordered data.
This change introduces a new activity state which is protected by a lock
and keeps track of if we are in the critical section to serialize
access.
`DirectoryEntryProducer` performs most of its logic within a lock and so
doesn't seem to be impacted in the same way.
### Result:
No functional changes. Internal changes reduce code duplication.
# Motivation
Our support strategy includes the last three released Swift versions.
After the recent release of Swift 6 this means we now support 5.9, 5.10
and 6.0.
# Modification
This PR updates our CI configuration and scripts to align with our
supported Swift versions.
# Result
Up to date CI coverage.
# Motivation
Switch to the reusable workflows from the swiftlang organization for
soundness.
# Modification
This PR moves over to the new reusable soundness workflow. Additionally,
it also deletes all files in this repo for the soundness checks since
they are no longer needed.
Motivation:
As described in issue
[#2877](https://github.com/apple/swift-nio/issues/2877), there is no API
available to specify allowing a read of unlimited size.
Modifications:
- Add a new `public static` property, `unlimited`, to `ByteCount`
representing an unlimited amount of bytes.
- Adapt
`ReadableFileHandleProtocol.readToEnd(fromAbsoluteOffset:maximumSizeAllowed:)`
to work with `maximumSizeAllowed` being `ByteCount.unlimited`.
Result:
An API to specify allowing a read of an unlimited size will be
available.
### Motivation:
As per https://github.com/apple/swift-nio/issues/2906.
### Modifications:
Added a method to SynchrounousOperations of ChannelPipeline.
### Result:
Now we are able to remove channel handlers by context.
---------
Co-authored-by: Franz Busch <f.busch@apple.com>
Motivation:
As described in issue
[#2878](https://github.com/apple/swift-nio/issues/2878), NIOFileSystem
crashes when reading more than `ByteBuffer` capacity.
Modifications:
- Add a new static property, `byteBufferCapacity`, to `ByteCount`
representing the maximum amount of bytes that can be written to
`ByteBuffer`.
- Throw a `FileSystemError` in
`ReadableFileHandleProtocol.readToEnd(fromAbsoluteOffset:maximumSizeAllowed:)`
when `maximumSizeAllowed` is more than `ByteCount.byteBufferCapacity`.
Result:
NIOFileSystem will `throw` instead of crashing.
Motivation:
Several arithmetic and comparison operations are done with `ByteCount`
using the `bytes` property. Operating on the `ByteCount` type directly
will be more convenient.
Modifications:
- Add `AdditiveArithmetic` and `Comparable` conformances to `ByteCount`.
Result:
The `ByteCount` type can undergo arithmetic and comparison operations.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
This is a followup to #2867
Some of the literals used in the test cases were too big to fit in an
Int32
This is fine on 64-bit systems, because the literals are considered as
`Int`, which is Int64 on those systems
However, on 32-bit systems, those literals are considered as Int64
Change: Add `as Int64` where needed, to tell the compiler we want these
literals to be treated as Int64, which should allow these tests to run
on 32 bit systems too
### Motivation:
In
`DatagramChannelTests.testChannelCanReportWritableBufferedBytesWithDataLargerThanSendBuffer`
we assert that there are no buffered writable bytes immediately after a
flush, however in some cases tests fail as this is not true.
We suspect that this is because in some situations the kernel can be
slow to drain the write buffer leading to racey behavior.
### Modifications:
Wait for writes to complete before asserting that the buffer is emptied.
### Result:
Tests should be more deterministic.
Co-authored-by: Cory Benfield <lukasa@apple.com>
## Motivation
The current `scheduleTask` APIs make use of _both_ callbacks and
promises, which leads to confusing semantics. For example, on
cancellation, users are notified in two ways: once via the promise and
once via the callback. Additionally the way the API is structured
results in unavoidable allocations—for the closures and the
promise—which could be avoided if we structured the API differently.
## Modifications
This PR introduces new protocol requirements on `EventLoop`:
```swift
protocol EventLoop {
// ...
@discardableResult
func scheduleCallback(at deadline: NIODeadline, handler: some NIOScheduledCallbackHandler) throws -> NIOScheduledCallback
@discardableResult
func scheduleCallback(in amount: TimeAmount, handler: some NIOScheduledCallbackHandler) throws -> NIOScheduledCallback
func cancelScheduledCallback(_ scheduledCallback: NIOScheduledCallback)
}
```
Default implementations have been provided that call through to
`EventLoop.scheduleTask(in:_:)` to not break existing `EventLoop`
implementations, although this implementation will be (at least) as slow
as using `scheduleTask(in:_:)` directly.
The API is structured to allow for `EventLoop` implementations to
provide a custom implementation, as an optimization point and this PR
provides a custom implementation for `SelectableEventLoop`, so that
`MultiThreadedEventLoopGroup` can benefit from a faster implementation.
Finally, this PR adds benchmarks to measure the performance of setting a
simple timer using both `scheduleTask(in:_:)` and
`scheduleCallback(in:_:)` APIs using a `MultiThreadedEventLoopGroup`.
## Result
A simpler and more coherent API surface.
There is also a small performance benefit for heavy users of this API,
e.g. protocols that make extensive use of timers: when using MTELG to
repeatedly set a timer with the same handler, switching from
`scheduleTask(in:_:)` to `scheduleCallback(in:_:)` reduces almost all
allocations (and amortizes to zero allocations) and is ~twice as fast.
```
MTELG.scheduleCallback(in:_:)
╒═══════════════════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╕
│ Metric │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │
╞═══════════════════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╡
│ Malloc (total) * │ 0 │ 0 │ 0 │ 0 │ 0 │ 0 │ 0 │ 1109 │
╘═══════════════════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╛
MTELG.scheduleTask(in:_:)
╒═══════════════════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╕
│ Metric │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │
╞═══════════════════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╡
│ Malloc (total) * │ 4 │ 4 │ 4 │ 4 │ 4 │ 4 │ 4 │ 576 │
╘═══════════════════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╛
```
### Motivation:
Recently we changed the init and deinit behavior of `ConditionLock`, at
that time the `UnsafeMutablePointer` allocation of the held
`pthread_cond_t` was put behind a conditional compiler and runtime
check. The deallocation of the same object was also put behind a
conditional, however the conditions were mismatched leading to a leak on
some platforms. Notably this surfaced when `wait`ing on an event loop
future.
### Modifications:
`ConditionLock.deinit` now deallocs the held `pthread_cond_t` under the
same conditions in which it allocs it.
### Result:
Creating a `ConditionLock` no longer leaks memory.
Add functions for reading and writing length-prefixed data with
customizable encodings for the length, particularly for quic
variable-length integers (RFC 9000)
### Motivation:
Many protocols require us to write data and then prefix that data with
its length. But each protocol has a different way of encoding the
length. This PR introduces general purpose functions which can be
extended for different encoding strategies
### Modifications:
Create a new protocol which defines how to encode an integer
Implement this protocol for QUIC
Provide functions on bytebuffer for writing length-prefixed buffers,
strings or bytes
# Motivation
Building `swift-nio` with the Static Linux SDK
(https://www.swift.org/documentation/articles/static-linux-getting-started.html),
fails in `PosixSingletons+ConcurrencyTakeOver.swift`:
```
Building for debugging...
error: emit-module command failed with exit code 1 (use -v to see invocation)
/private/tmp/vaportest/.build/checkouts/swift-nio/Sources/NIOPosix/PosixSingletons+ConcurrencyTakeOver.swift:76:12: error: conflicting arguments to generic parameter 'T' ('Optional<UnsafeRawPointer>.AtomicRepresentation' vs. 'Optional<UnsafeRawPointer>.AtomicRepresentation')
74 | dlopen(nil, RTLD_NOW),
75 | "swift_task_enqueueGlobal_hook"
76 | )?.assumingMemoryBound(to: UnsafeRawPointer?.AtomicRepresentation.self)
| `- error: conflicting arguments to generic parameter 'T' ('Optional<UnsafeRawPointer>.AtomicRepresentation' vs. 'Optional<UnsafeRawPointer>.AtomicRepresentation')
77 | guard let concurrencyEnqueueGlobalHookPtr = concurrencyEnqueueGlobalHookPtr else {
78 | return false
```
This happens because `Foundation` and `swift-atomics` both define
`AtomicRepresentation`. A compiler problem (rdar://132885963) makes
these extensions globally visible, causing the two
`AtomicRepresentation`
types to collide. This only affects non-Darwin platforms.
# Modification
This PR works around the problem by using a local type alias which does
not collide with the other `AtomicRepresentation` types.
# Result
It is now possible to build `swift-nio` with the Static Linux SDK.
Fixes: https://github.com/apple/swift-nio/issues/2893
Suggested-by: Alastair Houghton <ahoughton@apple.com>
# Motivation
When encountering a file descriptor limit we are currently closing the
server socket when using the async bootstraps since the error caught is
delivered via the `inbound` sequence of the server socket async
sequence.
# Modification
This PR adds the `AcceptBackoffHandler` in the async bootstrap case to
the pipeline to avoid us closing the server socket channel when we hit
the file descriptor limit.
# Result
We are now gracefully handling file descriptor limits.
Add ability to get the amount of buffered outbound data from `Channel`
### Motivation:
Right now, SwiftNIO does not have the API to answer the question "how
much data is buffered in the Channel". Applications focusing on
performance may need to fine-tune the amount of outbound data that will
be sent to optimize data throughput, adjust sending rate to avoid
overflow, and potentially reduce latency.
SwiftNIO currently provides some backpressure mechanism. This new API
will be a good addition. By knowing how much data is buffered directly,
applications can make informed decision to adjust for optimal buffer
sizes and send rates.
### Modifications:
- Expose current buffer size through ChannelOptions so that users can
read the value out. StreamSocketChannel, DatagramSocketChannel,
EmbeddedChannel, and AsyncTestingChannel have the same API interface.
- Various modifications to the existing tests to make sure the new API
is working correctly.
- Add a new `so_sndbuf` socket option so that users can easily adjust
the send buffer size.
### Result:
Users can get the amount of outbound bytes currently buffered in the
`Channel` through the new `BufferedWritableBytesOption` channel option.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
To enable access to `UDP_MAX_SEGMENTS` we switched from including
`netinet/udp.h` to including `linux/udp.h` however the latter isn't
available in MUSL.
### Modifications:
if `linux/udp.h` is available then import it in favor of
`netinet/udp.h`. If we fall back to the latter then `UDP_MAX_SEGMENTS`
won't be defined but that will be caught by the existing paths which
account for this case.
### Result:
NIO should be able to build against a static MUSL SDK again.
### Motivation:
This repo contains reusable workflows, intended for use in _other_
repos. Right now, some of these reusable workflows are nested, i.e. some
of the YAML files refer to other YAML files in the repo by a relative
path.
Unfortunately, this makes them currently unusable locally with `act`
because of https://github.com/nektos/act/issues/1875.
For now, it appears the only workaround is to have these referred to
without the local, relative path.
### Modifications:
Use the remote syntax for referencing nested workflows.
### Result:
Commands like `act -j unit-tests` will work in repos that aren't NIO
itself.
---------
Co-authored-by: Franz Busch <privat@franz-busch.de>
### Motivation:
We want to avoid going through `EventLoopGroup`'s [`String(describing:
self)`](https://github.com/apple/swift-nio/blob/8307ad610a358513b2190955379829d70f04b8c2/Sources/NIOCore/EventLoop.swift#L414)
when obtaining the description of an `EventLoopGroup` or `EventLoop`.
The concrete `MultiThreadedEventLoopGroup` and `SelectableEventLoop`
already implement a `description` property. `EmbeddedEventLoop` does
not.
### Modifications:
Added a concrete description property in `EmbeddedEventLoop`.
### Result:
The description of `EmbeddedEventLoop` can be obtained without going
through `String(describing: self)`.
This reverts commit 282f5935cf.
### Motivation:
Repeated testing in linux containers has surfaced issues with the
implementation which require some rethinking of the code, let's revert
it for now and fix it up.
### Modifications:
Revert the adoption commit.
### Result:
The change is backed out.
### Motivation:
Linux kernels recently increased the value of `UDP_MAX_SEGMENTS` from 64
to 128 causing hardcoded assumptions in our tests to become invalid.
### Modifications:
Surface the value of `UDP_MAX_SEGMENTS` if it is defined on the platform
in use via new public API `System.udpMaxSegments()` (otherwise return
`nil`) and make use of it in `DatagramChannelTests`.
`System.udpMaxSegments()` is added as new public API in analogue to e.g.
`System.supportsUDPReceiveOffload`.
### Result:
`DatagramChannelTests` pass and new API.
### Motivation:
Fix Issue 2734
### Modifications:
- Added a function to clamp storage by copying bytes and setting new
capacity of storage
- Adding a function to clamp the capacity of ByteBuffer
- Added the ability to specify he maxBufferCapacity to
MessageToByteHandler
### Result:
Once a write message that is larger than the capacity of the
MessageToByteHandler's maxBufferCapacity, it clamps the byteBuffer down.
---------
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Franz Busch <f.busch@apple.com>
Co-authored-by: Ali Ali <ali.ali@qantas.com.au>
### Motivation:
This repo is providing a reusable workflow for checking API breaks but
it has two shortcomings:
1. It presumes the target branch name for the PR to be `main`.
2. It presumes the remote is named `origin`.
(2) is always the case in CI, but isn't always locally. My remote is
named `upstream` so cannot run this using `act`. (1) is worse, because
it's not actually testing against the target branch of the PR—consider
if someone was enabling this reusable workflow on a feature branch or
other-named branch.
Fortunately, Github Actions makes the target ref of the pull request
available in the `GITHUB_BASE_REF` environment variable[^0].
### Modifications:
Use `GITHUB_BASE_REF` as the argument to `swift package
diagnose-api-breaking-changes`.
### Result:
This can now be run locally.
[^0]:
https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables#default-environment-variables
### Motivation:
We want to be able to run the soundness checks locally, and our current
guidance for this is to use `act`. However, there is a documented[^0]
difference in the runner images it uses and those used by Github Actions
proper. One such difference is a lack of `shellcheck` in both the small
and medium runners, which _is_ present in Github's image for the
`ubuntu-latest` platform.
### Modifications:
There are official images for `shellcheck`: both a single binary and an
alpine-based image, which are very small. Neither of these has `bash`,
nor `git`, which are dependencies of the script.
This PR updates the workflow to use a container for this job and uses
the same image used in some other jobs, along with a step to install
`shellcheck`, which is in keeping with what we do for other jobs in the
soundness workflow already to e.g. install `yq`.
### Result:
Can run the soundness job locally using `act`. No change in CI.
[^0]:
https://nektosact.com/usage/runners.html#default-runners-are-intentionally-incomplete
### Motivation:
`NIOSingleStepByteToMessageDecoder` calls out part way through its
processing step to a user-provided closure which can cause re-entrant
behavior which violates the assumption made in the code that if the
buffer is non-empty at the start that will be true later in the method.
### Modifications:
`NIOSingleStepByteToMessageDecoder` no longer assumes a non-empty buffer
in its final phase of buffer management.
Further changes to protect against re-entrancy shouldn't be necessary
because the outside call to `messageReceiver` is the only one which is
permitted to be re-entrant (`decode` and `decodeLast` are not).
### Result:
`NIOSingleStepByteToMessageDecoder` can handle re-entrant processing
calls.
Dispatch is not supported on WASI, and only Unix domain sockets are
supported, which means we have to exclude those APIs on this platform.
There's work in progress to enable tests for this on CI, but nothing I
can provide for this PR at the current moment.
---------
Co-authored-by: Franz Busch <f.busch@apple.com>
### Motivation:
We're seeing some very rare failures from this test in CI runs but I
cannot reproduce locally. The test relies on timing to some degree and
the interaction of scheduling tasks at shutdown.
### Modifications:
The `AsyncTestingEventLoop` has an `executeInContext` function which
puts the closure on the backing dispatch queue and blocks. In this
instance it might be a good way to make sure that all the previous work
has happened.
### Result:
(Hopefully) less flakey test.
### Motivation
`CustomDebugStringConvertible `/`debugDescription` name and
documentation is confusing and should be changed but it is today
expected to be suitable to be used as part of a structured display e.g.
to be printed as part of an `Array`s description, a `struct` or `enum`
with associated values. Therefore it should have no unpaired
parentheses, no unescaped quotes, no top-level commas and no new lines.
### Modifications
let `debugDescription` simply contain the same contents as
`description`. We can't remove the property or the conformance without
breaking API.
### Results
`ByteBuffer` has a proper string representation suitable for being
displayed in an `Array`, as the property of a `struct` or an associated
value of an `enum`.
We can add a new property/method once #2475 landed e.g.
```swift
extension ByteBuffer {
struct PrintFormat {
static let hex: Self
static let decimal: Self
...
}
func descriptionWithContents(format: PrintFormat = .hex, maxBytes: Int = 1024) {
...
}
}
```
Co-authored-by: Franz Busch <f.busch@apple.com>
Motivation:
`FileChunks` is an `AsyncSequence` so should be `Sendable` otherwise
it's difficult to use.
Modifications:
- Conform `FileChunks` to `Sendable`
Result:
- Resolves https://github.com/apple/swift-nio/issues/2752
Improving `description` and adding `debugDescription` to `NIOAny`
### Motivation
As per:
https://github.com/apple/swift-nio/pull/2864#discussion_r1742192300 we
would like that the `description` of `NIOAny` prints the type of the
underlaying value that it wraps.
### Modification:
Changing `description` and adding a conformance to
`CustomDebugStringConvertible`.
### Result:
A nicer `description` and `debugDescription` for `NIOAny`.
Co-authored-by: Franz Busch <f.busch@apple.com>
Two NIOFileSystem tests are still a bit flaky after (mostly) fixing them
in https://github.com/apple/swift-nio/pull/2842.
```
Test Case 'FileHandleTests.testSetLastAccessAndLastDataModificationTimesToNil' started at 2024-09-06 10:12:54.006
/__w/swift-nio/swift-nio/Tests/NIOFileSystemIntegrationTests/FileHandleTests.swift:1265: error: FileHandleTests.testSetLastAccessAndLastDataModificationTimesToNil : XCTAssertEqual failed: ("1725617573.0") is not equal to ("1725617574.006952") +/- ("1.0") -
Test Case 'FileHandleTests.testSetLastAccessAndLastDataModificationTimesToNil' failed (0.001 seconds)
```
This is because we were dropping the nanoseconds when comparing the
timestamps, which means that sometimes the two timestamps were off by
just over a second. This change includes the nanoseconds to avoid this
problem.
# Motivation
Some of repos have `.in` and `.cmake` files including header license
comments.
# Modification
This PR adds support to the license check for those type of files.
# Result
Even more license headers.
# Motivation
We want to get green check marks on our commits to main. To do this we
have to run part of our CI jobs when a new commit is pushed.
# Modification
This PR adds a new workflow trigger to run our CI when a commit is
pushed to the main branch.
# Result
Green checkmarks on our commits.
### Motivation:
Resolving the following issue:
https://github.com/apple/swift-nio/issues/2828
### Modifications:
Making `WebSocketFrame` conform to `CustomStringConvertible`.
### Result:
A nicer description for `WebSocketFrame`.
---------
Co-authored-by: Franz Busch <f.busch@apple.com>
### Motivation:
Resolving the following issue:
https://github.com/apple/swift-nio/issues/2863
### Modifications:
Rewrote `description` and `debugDescription` on `ByteBuffer` to make it
more useful. Also fixed a bug in the in `hexDumpCompact`.
### Result:
A more useful `description` and `debugDescription`.
---------
Co-authored-by: Franz Busch <f.busch@apple.com>
Allow usage of `assumeIsolated` in SerialExecutors that are backed by
EventLoops.
### Motivation:
We want to support all new Swift 6 features in SerialExecutors.
### Modifications:
- Implement `isSameExclusiveExecutionContext`
- Implement `checkIsolated`
### Result:
We can use `assumeIsolated` in actors that use an `EventLoop` as their
`SerialExecutor`.
Add compact formatting option to ByteBuffer's hexdump method.
### Motivation:
Resolving the following issue:
https://github.com/apple/swift-nio/issues/2825.
### Modifications:
• Added a compact format for ByteBuffer's hexdump method
### Result:
A new format which is analog to the `.plain` but without whitespaces.
---------
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Si Beaumont <beaumont@apple.com>