### 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:
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:
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:
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>
## 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:
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:
`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
`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>
### 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>
# Motivation
Our global concurrency hook was guarding against known Swift versions.
Since the nightly are now Swift 6.1 we need to adjust our compiler
guards.
# Modification
This PR adjusts our compiler guards for the concurrency hooks.
# Result
Concurrency hooks for everyone
### Motivation:
The NIOTooManyBytesError doesn't have any documentation for someone that
encounters this error. Also, they have no idea the magnitude of the
limit that was set to decide if the payload is an unreasonable size.
### Modifications:
Provide documentation that explains the situation when the error occurs,
which is the upTo limit of an AsyncSequence is exceeded. Describe one
potential action, which is to increase this limit.
Provide the maxBytes in the error so that the user can gauge whether the
upTo limit is already reasonable and the payload size is excessive, or
the limit needs to be increased to suit more situations.
### Result:
There will be documentation for the NIOTooManyBytesError so that if
someone looks it up they will have a better understanding of the
situation, and possible actions. The limit will be included in the error
to give them an idea of the scale of the payload limit that is in place,
or potentially the configuration value that they can change.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Sometimes users ask us why TSV isn't Sendable. We should explain
ourselves.
Modifications:
- Explain why TSV isn't Sendable.
Result:
Hopefully, more clarity.
Motivation:
Per @jakepetroules, swift-build copies symlinks as-is into resource
bundles. That means these symlinks are dead when built with swift-build.
There's sort of no point in that.
Modifications:
Remove symlinks, replace with files.
Result:
Privacy info works.
Motivation:
Another brick in the wall.
Modifications:
- Make Base64 an enum, not a struct, as it's a namespace.
- Make Base64 Sendable, which it trivially is.
Result:
Another pass, another success
Motivation:
We're slowly adopting strict concurrency in NIO. This is next.
Modifications:
- Make TinyArray's Iterator Sendable
- Add the stict concurrency flags
Result:
One small step for NIO, one giant leap for NIOkind.
Motivation:
This patch adds strict concurrency and Sendable support to
NIOConcurrencyHelpers. This is a useful first step in adding full
support across the ecosystem.
Modifications:
- Added some explicit Sendable conformances that were missing.
- Fixed some declarations to make them Strict Sendable safe.
Result:
One step towards strict concurrency
### Motivation:
Copying regular files on Darwin was taking more time than it needed to
because it was manually opening files and copying over bites rather than
making use of the system's ability to create CoW clones.
### Modifications:
The primary change is to switch `copyItem` to be backed by Darwin's
`copyfile` method rather than `fcopyfile`. `fcopyfile` ignores the flag
we were passing in to indicate that the file should be cloned if
possible, whereas `copyfile` is a higher-level API which takes this into
account.
This change exposes a `copyfile` wrapper method as a new public
function.
This change also adds a workaround to a seeming compiler bug on channel
options blocking building tests on more recent Xcodes.
### Result:
Copying files on Darwin will be faster.
FilesystemProtocol/copyItem has an overload providing the default CopyStrategy
Motivation:
Based on user feedback from #2806
This makes it easier to use, especially when copying files such that it is irrelevant.
Modifications:
Add overload providing (at:to:shouldProceedAfterError:shouldCopyItem:) with CopyStrategy.platformDefault
as the strategy.
Fix a cancellation bug which resulted in a test being flaky.
In addition made the test cover that case reliably to prevent it coming back.
Result:
A simpler and more robust to change API will exist for copyItem()
Motivation:
Since Swift 5.5 and [SE-0299](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0299-extend-generic-static-member-lookup.md) it is possible to add static members to protocols which are discoverable through the shorthand dot syntax.
This change reduces type repetition and improves call-site legibility.
Modifications:
Added extensions for ChannelOption with static members where Self is bound to a concrete type.
Result:
ChannelOption types can be used with the leading dot syntax. For eg:
```
//before
.channelOption(ChannelOptions.explicitCongestionNotification, value: true)
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
//after
.channelOption(.explicitCongestionNotification, value: true)
.channelOption(.socketOption(.so_reuseaddr), value: 1)
```
Motivation:
Using some limited parallelism can improved the speed of the copy for very limited increase in cpu use.
In circumstances where the source and/or destination are on a high latency device, such as a network file system,
the resulting speed up can be even more significant.
Providing conservative defaults, while allowing users the ability to control it directly if desired, provides for a faster default and access to user targeted gains in performance.
The use of parallel by default is considered in keeping with the swift-nio model of concurrent capabilities.
The parallelism used is restricted because the underlying limited resource for this is highly likely to be limited system file descriptors, rather than the limits of the underlying executor itself, especially on embedded devices with significantly more limited concurrent descriptors.
Modifications:
All copyItem overloads except ```copyItem(sourcePath:destinationPath:shouldProceedAfterError:shouldCopyFile)```
can, and likely will, use concurrent copies when copying directories.
A Newly type ```CopyStrategy``` controls the behaviour, allowing:
* ```parallel(maxDescriptors: Int)```
* Parallel limited to a maximum number of concurrently open file descriptors.
* ```sequential```
* The previous behaviour, still asynchronous but only one operation at a time
* ```platformDefault```
* Whatever the API determines the default should be from the prior options
The cancellation semantics of copyItem were previously unclear/undocumented.
These are now stated and cancellation is tested.
There were some aspects of naming/types on this API which were inconsistent/unclear. Those have been altered to aid clarity.
* Less duplication with the protocol docs
* Consistent use of `item` not `file`
* Use DirectoryEntry for the source in both ```shouldXxx``` callbacks
NIOFileSystem package status remains unchanged, it is still _NIOFileSystem with the semantics that entails.
Result:
For any use of the following functions on FileSystemProtocol, when backed by FileSystem:
- ```copyItem(*)```:
The shouldCopyItem check happens before the internal FileSystem "do I know how to copy this sort of FileType" check. This makes the code a little simpler, but the desire is to allow consuming code to filter out anything unexpected if they like without needing to trap errors.
- ```copyItem(sourcePath:destinationPath)```:
Depending on the platform this will become parallel, users on MacOS, Linux and Windows will have up to 4 concurrent file system operations at once.
Empirical testing on a MacBook pro with a significant dense directory hierarchy of 12 GiB had performance improvements of ~50% reduction in elapsed time for CPU usage increases below the noise floor of the testing
- ```copyItem(sourcePath:destinationPath:shouldProceedAfterError:shouldCopyFile)```:
When migrating from this to ```copyItem(sourcePath:destinationPath:copyStrategy:shouldProceedAfterError:shouldCopyItem)```care should be taken to ensure the should callbacks are safe to use in different concurrency domains, or that CopyStrategy.sequential is explicitly stated.
The backward compatibility shim provided does this by default.
# Motivation
We have quite a lot of shell scripts in our repo and want to make sure that they all pass `shellcheck`.
# Modification
This PR adds a GH action workflow to the soundness script for `shellcheck` and fixes up all errors and warnings.
# Result
No more shell/bash discussions
### Motivation:
The two testing event loops—`EmbeddedEventLoop` and `NIOAsyncTestingEventLoop`—have different semantics for outstanding work during shutdown, which are both different from the production `SelectableEventLoop`, specifically with newly scheduled tasks that result from running existing scheduled work at the time of shutdown.
There are three axes to consider:
1. Scheduled tasks that are at or past their deadline.
2. Scheduled tasks with a deadline in the future.
3. Newly scheduled work that result from either running or cancelling (1) and (2).
| | (1) | (2) | (3) |
|-|-|-|-|
| `SelectableEventLoop` | Run | Cancel | Quiesce over 1000 ticks, repeatedly run resulting (1) and cancel resulting (2) |
| `EmbeddedEventLoop` | Run | Cancel | Cancel resulting (1) and resulting (2) |
| `NIOAsyncTestingEventLoop` | Run | Run | Run resulting (1) and resulting (2) |
Note that `NIOAsyncTestingEventLoop` may never terminate because of this.
### Modifications:
This PR aligns `EmbeddedEventLoop` and `NIOTestingEventLoop` and makes them more similar to `SelectableEventLoop` and less surprising semantics.
### Result:
| | (1) | (2) | (3) |
|-|-|-|-|
| `SelectableEventLoop` | Run | Cancel | Quiesce over 1000 ticks, repeatedly run resulting (1) and cancel resulting (2) |
| `EmbeddedEventLoop` | Run | Cancel | Cancel resulting (1) and resulting (2) |
| `NIOAsyncTestingEventLoop` | Run | Cancel | Cancel resulting (1) and resulting (2) |
### Future work:
Given both the `EmbeddedEventLoop` and `NIOAsyncTestingEventLoop` are used in tests of NIO applications that run with `SelectableEventLoop` in production, it might be worth extending both to also support quiescing to give a more representative shutdown behaviour in tests.
# Motivation
In Swift 5.10 the usage of `unsafeDownCast` can lead to a miss-compile which will result in bad runtime behaviour.
# Modification
This PR changes the `unsafeDownCast` to use a `as!` instead. This is safe and should result in the same performance when done with `ManagedBuffer` which is inlinable.
# Result
No more miss compiles in 5.10