Motivation:
ManagedBuffer is marked as explicitly not sendable on Swift nightly
builds. NIOLock and NIOLockedValueBox used a type derived from
ManagedBuffer and must be Sendable. Currently the derived type is marked
as `@unchecked Sendable`. However on nightly toolchains this now
conflicts with being explicitly not Sendable.
Modifications:
- Remove Sendable checking on NIOLock and NIOLockedValueBox
Result:
Fewer warnings
(cherry picked from commit 6d30ec4738)
Co-authored-by: George Barnett <gbarnett@apple.com>
Documentation checking catches more issues in Swift 6.0.
Adopt the Swift 6.0 image and fix the errors.
More accurate docs.
(cherry picked from commit adfd61adc5)
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
Motivation:
The contibuting guide gives an incorrect command to run to invoke the
formatting job locally.
Modifications:
- Change the job name to 'soundness'
- Add a note about setting the container architecture
Result:
Better docs
(cherry picked from commit 29490005ab)
Co-authored-by: George Barnett <gbarnett@apple.com>
Motivation:
Unfortunately the current script has a bug meaning it can never fail.
Modifications:
Change bracketing for output search.
Result:
Allocation tests will flag when failing
(cherry picked from commit e1d0d21391)
Co-authored-by: Peter Adams <63288215+PeterAdams-A@users.noreply.github.com>
Trying to fix swift format link in contributions.md
Someone please let me know what the process is for running `swift
format` locally now that the script has been moved out of the repo.
Co-authored-by: Franz Busch <f.busch@apple.com>
(cherry picked from commit 08af85ae4b)
Co-authored-by: Ali Ali <47680736+ali-ahsan-ali@users.noreply.github.com>
This is a backport of #2918.
Add new protocol to get buffered bytes from `ChannelHandler`s and
`ChannelPipeline` API to query the buffered bytes from `ChannelHandler`s
### Motivation:
In #2849, a new `ChannelOption` is introduced to retrieve the number of
buffered outbound bytes in a `Channel`. However, this solution does not
account for bytes that may be buffered within individual
`ChannelHandler`s. This PR builds on #2849 by adding functionality to
audit buffered bytes residing in `ChannelHandler`s and exposing this
information through new `ChannelPipeline` APIs.
### Modifications:
- Two new protocols for `ChannelHandler` to audit buffered bytes for
inbound and outbound.
- `NIOOutboundByteBufferingChannelHandler`
- `NIOInboundByteBufferingChannelHandler`
- New `ChannelPipeline` APIs
- outboundBufferedBytes()
- outboundBufferedBytes(in: ChannelHandlerContext) (only in
`syncOperations`)
- inboundBufferedBytes()
- inboundBufferedBytes(in: ChannelHandlerContext) (only in
`syncOperations`)
### Result:
Users can now easily query the amount of bytes buffered in
`ChannelHandler`s using the new `ChannelPipeline` APIs, enhancing the
visibility of `ChannelHandler` performance.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
(cherry picked from commit 935659883e)
Co-authored-by: John Zhou <37914490+johnnzhou@users.noreply.github.com>
### Motivation:
We could previously hit an assert do to a re-entrancy issue where
channel and buffered write state could change during a call-out leading
to invalid state.
### Modifications:
The decision on whether or not we should be registered for future writes
is now taken after the call outs to `fireChannelWritabilityChanged` and
`fireChannelReadComplete`. The new registration state is set to
`.unregister` if the channel is not open or if there are now flushed
pending writes.
### Result:
Scope for re-entrancy crashes is reduced.
Co-authored-by: Cory Benfield <lukasa@apple.com>
(cherry picked from commit fdc3a31a55)
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
# Motivation
It was currently possible that the producer's delegate is getting called
twice with `produceMore` even if no `yield` returned a `stopProducing`.
This could happen when we expected the producer to yield elements but
the consumer went below the low watermark again. Resulting in two
subsequent calls.
# Modification
This PR stores the current demand state in the strategy which let's us
avoid flipping the `hasOustandingDemand` state of the sequence.
# Result
Correctly, ensured the call order of `produceMore` and `stopProducing`.
### Motivation:
`EmbeddedChannel` & `EmbeddedEventLoop` currently violate `Sendable`.
They should store the current thread in `init` and then implement
`inEventLoop` and other functions with a check that the current thread
is correct.
Since NIO 1.0 `Embedded*` were always documented to not be thread-safe
but we should finally police this.
### Modifications:
- Implement the thread check
- For now, just warn (soon hopefully crash)
- Delete EmbeddedScheduledCallbackTests (#2950)
### Result:
- Less Embedded* abuse
- fixes#2949
Add Vision support
### Motivation:
https://github.com/apple/swift-nio/issues/2900 - close this
### Modifications:
- Bump SystemPackage to 1.4.0 and remove @preconcurrency
- remove `#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) ||
os(Linux) || os(Android)` to allow for visionOS support
- Remove conditional import for swift system
### Result:
Vision OS support
Motivation:
Some repos using this as their source of GitHub Actions logic have
submodules.
Modifications:
Change workflows to checkout submodules.
Result:
All CI will work cleanly
### Motivation:
`swift build --arch x64_64 --arch arm64` on at least Xcode 15.4 fails
with
```
/Users/johannes/devel/my-proj/.build/checkouts/swift-nio/Sources/NIOCore/NIOScheduledCallback.swift:93:18: error: '_scheduleCallback' has a package access level but no -package-name was specified: /Users/johannes/devel/tfai-swift/.build/checkouts/swift-nio/Sources/NIOCore/NIOScheduledCallback.swift
package func _scheduleCallback(
^
```
That's clearly an Xcode bug but that needs a workaround.
### Modifications:
- Don't use the `package` modifier for now
### Result:
SwiftNIO builds again.
### Motivation:
On Darwin, QoS (quality of service) of threads plays an important role,
especially on Apple Silicon machines with P-cores and E-cores. If you
spawn raw threads (like NIOPosix) and use a mechanism that doesn't
support QoS propagation (like reading/writing to networks -- like
NIOPosix does), it's recommended to default to the main thread's QoS.
Otherwise you'll always be at the default QoS for "legacy" threads which
means bad latencies, especially on Apple Silicon machines.
In a follow-up PR #2943 we're adding better configurability for thread
configuration.
### Modifications:
Default to main thread QoS on Darwin.
### Result:
Better latencies for applications with higher QoS classes.
# Motivation
Currently, the Windows 6.0 check name includes the matrix properties.
# Modification
This PR makes it dynamic with the swift version again.
# Result
Aligned CI check names across platforms.
This PR makes it possible to enable benchmarks and cxx interop checks on
Windows. By default they are turned off. This PR also fixes the job of
the Windows 6 pipeline which was broken since single configuration
matrix jobs seem to behave differently.
# Motivation
There were two small problems:
1. The CI for the nightlies wasn't properly skipped
2. The name for the matrix wasn't applied in the case where it was
skipped
# Modification
This PR hopefully fixes both issues.
# Motivation
In the long term we want to add support for Windows in our Swift
packages. To do this we need a CI setup to ensure that our packages are
building and the tests are passing.
# Modification
This PR adds a windows job to our swift matrix that installs Swift on
the runner and then uses Swift PM to build and test the package. Windows
jobs are disabled by default since most of our packages require some
work to add Windows support.
# Result
We have a Windows CI pipeline that allows us to verify that our packages
are working.
Motivation:
The async flavour of withConnectedSocket accidentally type-erased the
channel, which caused it to be unable to be used.
Modifications:
Un-erase the type of the channel.
Add a test.
Result:
withConnectedSocket works again
Resolves#2936
Motivation:
As requested in issues
[#2875](https://github.com/apple/swift-nio/issues/2875) and
[#2876](https://github.com/apple/swift-nio/issues/2876), it would be
convenient to be able to read the contents of a file into more data
types such as `Array`, `ArraySlice` & Foundation's `Data`.
Modifications:
- Extend `Array`, `ArraySlice` & `Data` to be initialisable with the
contents of a file.
Result:
The contents of a file can be read into more data types.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
Use `withLockPrimitive` to access the underlying lock.
### Motivation:
The current method of accessing the lock doesn't build.
This fixes bug #2934.
### Modifications:
Access the lock via `withLockPrimitive`.
### Result:
Now it builds! :)
# Motivation
We need to tackle the remaining strict concurrency checking related
`Sendable` warnings in NIO. The first place to start is making sure that
`EventLoopFuture` and `EventLoopPromise` are properly annotated.
# Modification
In a previous https://github.com/apple/swift-nio/pull/2496, @weissi
changed the `@unchecked Sendable` conformances of
`EventLoopFuture/Promise` to be conditional on the sendability of the
generic `Value` type. After having looked at all the APIs on the future
and promise types as well as reading the latest Concurrency evolution
proposals, specifically the [Region based
Isolation](https://github.com/apple/swift-evolution/blob/main/proposals/0414-region-based-isolation.md),
I came to the conclusion that the previous `@unchecked Sendable`
annotations were correct. The reasoning for this is:
1. An `EventLoopPromise` and `EventLoopFuture` pair are tied to a
specific `EventLoop`
2. An `EventLoop` represents an isolation region and values tied to its
isolation are not allowed to be shared outside of it unless they are
disconnected from the region
3. The `value` used to succeed a promise often come from outside the
isolation domain of the `EventLoop` hence they must be transferred into
the promise.
4. The isolation region of the event loop is enforced through
`@Sendable` annotations on all closures that receive the value in some
kind of transformation e.g. `map()` or `whenComplete()`
5. Any method on `EventLoopFuture` that combines itself with another
future must require `Sendable` of the other futures `Value` since we
cannot statically enforce that futures are bound to the same event loop
i.e. to the same isolation domain
Due to the above rules, this PR adds back the `@unchecked Sendable`
conformances to both types. Furthermore, this PR revisits every single
method on `EventLoopPromise/Future` and adds missing `Sendable` and
`@Sendable` annotation where necessary to uphold the above rules. A few
important things to call out:
- Since `transferring` is currently not available this PR requires a
`Sendable` conformance for some methods on `EventLoopPromise/Future`
that should rather take a `transffering` argument
- To enable the common case where a value from the same event loop is
used to succeed a promise I added two additional methods that take a
`eventLoopBoundResult` and enforce dynamic isolation checking. We might
have to do this for more methods once we adopt those changes in other
targets/packages.
# Result
After this PR has landed our lowest level building block should be
inline with what the rest of the language enforces in Concurrency. The
`EventLoopFuture.swift` produces no more warnings under strict
concurrency checking on the latest 5.10 snapshots.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
# 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.