* Fixed an issue where HTTP/2 connections would disconnect if response compression were used and a 304 Not Modified response was returned
* Added HTTP encoder tests for 304 Not Modified responses
This PR adds API to set a file's last accessed and last modified times, as well as a `touch()` shorthand that updates both to the current time.
Motivation:
Feature request: https://github.com/apple/swift-nio/issues/2712
Modifications:
This PR adds API to set a file's last accessed and last modified times, as well as a `touch()` shorthand that updates both to the current time.
Result:
Files' last accessed and last modified times can be updated.
Motivation:
'renameat2' can fail with EINVAL if the RENAME_NOREPLACE flag isn't
supported. However, not all kernel versions support this flag which can
result in an error when creating a file 'transactionally'.
Using 'renameat2' only happens on Linux as a fallback when O_TMPFILE
isn't available.
Modifications:
- On Linux, fallback to a combination of 'stat' and 'rename' if 'renameat2' fails with EINVAL.
- Add a couple of tests
Result:
Files can still be created exclusively
Motivation:
When taking ownership of input and output file descriptors in a bootstrap
the ownership of the file handles remains with the caller in the function
taking ownership fails. This is currently where _takingOwnershipOfDescriptors
uses NIOFileHandle to take ownership of descriptors but then experiences a later
failure.
Modifications:
If an exception is throw in _takingOwnershipOfDescriptors release file descriptors
from NIOFileHandle.
Result:
No crash on failure to close file handles before end of scoped usage.
* Add a version of 'write' for 'ByteBuffer'
Motivation:
At the moment 'WritableFileHandleProtocol' is in terms of
`some Sequence<UInt8>`. To use a `ByteBuffer` users must pass in the
readable view of the buffer, which is inconvenient.
Modifications:
- Add an extension to `WritableFileHandleProtocol` which takes a
`ByteBuffer`.
Result:
Easier to use API
* fix docs
Motivation:
The name of the syscall used in errors for all rename calls is "rename".
However, this isn't always correct, in some cases "renamex_np" is used,
and in others "renameat2" is used.
Modifications:
- Allow the name of the syscall to be provided to the rename error
- Use the correct syscall name
Result:
Better errors
Motivation:
Existentials are boxed if they are wider than 24 bytes. A number of
value types in NIO are implemented with storage classes so that the
alloaction is only paid for once. However, existential errors are
treated differently, they are unconditionally boxed. Implementing errors
with storage classes therefore introduces an unnecessary allocation.
Modifications:
- Remove the storage class for FileSystemError
- Remove the copy-on-write test
Result:
Fewer allocations
Motivation:
Single letter names are discouraged but are used in a handful of places
in NIOFileSystem.
Modifications:
- Replace 'R' with 'ReturnType' where appropriate
Result:
Clearer APIs
Motivation:
NIOFileSystem can create the path of a temporary directory but doesn't
offer any API to create and then remove a directory.
Modifications:
- Add `withTemporaryDirectory`
Result:
- Users can get scoped access to a temporary directory which is
subsequently removed for them
- Resolves#2664
Motivation:
The `BufferedWriter` in `NIOFileSystem` has API in terms
of `some Sequence<UInt8>`, meaning that you need to pass
`byteBuffer.readableBytesView` which is a bit inconvenient.
Modifications:
- Add overloads which allow you to pass `ByteBuffer` directly
- Remove redundant availability guards; they are already applied to the
type
Result:
- Better API for users
- Resolves#2662
Motivation:
Many of the filesystem with methods have a requirement that the
result type is sendable. In most cases this is not required as
the result is not shared or sent.
Modifications:
Remove sendable requirement for result types where it is not required.
Result:
Users will not have to make so many types sendable.
Motivation:
NIOAsyncChannel requires users to explicitly close it, this is typically
done by calling `executeThenClose`. If a `NIOAsyncChannel` isn't closed
then its outbound writer will hit a precondition failure on `deinit`.
Not calling `executeThenClose` is a programmer error.
However there are some sharp edges: if NIO never returns the
`NIOAsyncChannel` to the caller (e.g. if a connect attempt fails) then
nothing will finish the writer and precondition will fail in the deinit.
Working around this from a user perspective is non-obvious and requires
keep tracking of all `NIOAsyncChannel`s created from a connect attempt
and closing the unused ones.
We still want to maintain the precondition when users don't close the
channel, one way of achieving this is by defining a point in time at
which NIO hands responsibility of the channel to the user.
Modifications:
- Retain the writer in the outbound writer handler until channel active
- On successful connect attempts, the channel becomes active and the
connected channel is returned to the caller.
- On failed attempts channel active isn't called so the writer is
retained until the handler is removed from the pipeline at which point it is
finished.
Result:
Failed connect attempts don't result in precondition failures when using
NIOAsyncChannel.
Motivation:
NIOPosix and NIOFileSystem use stat(2) (or some variation of it). These
are "required reason APIs" meaning that their usage and reason must be
declared in a privacy manifest in order to be submitted to the App Store.
Modifications:
- Add a privacy manifest to NIOPosix and NIOFileSystem
Result:
Apps using NIO won't be rejected from App Store submission for missing
privacy manifests.
Motivation:
Many operations accept an optional promise. It's not uncommon to batch
operations (which may each have their own promise) and complete them
as a single operation. Combining these optional promises is slightly
tedious.
Modifications:
- Add an extension to `Optional` to set or cascade a promise
- If a promise exists, its result is cascaded to the provided promise.
Otherwise the optional is set to the provided promise.
Result:
It's easier to combine optional promises.
Motivation:
Even though NIOAsyncWriterError captures the file and line of the error they are internal and not printed in the
description.
Modifications:
- made the 2 properties public
- added them in the description
Result:
Users will be able to access and see the line number and file where a NIOAsyncWriterError occurred
Motivation:
There are two thread pools: one in NIOFileSystem and one in NIOPosix; we
should avoid the duplication.
Modifications:
- Switch to using NIOThreadPool
- Remove the old thread pool and associated code
- Add an init to FileSystem which takes a thread pool
Result:
Less duplication
Motivation:
To dedupe the thread pool from NIOFileSystem and NIOPosix, the one from
NIOPosix needs to gain support for cancellation for its async
`runIfActive` function.
Modification:
- Generate a work ID when submitting async work to the pool, add that ID
to a set in the cancellation handler
- Check the existence of the ID in the cancel set when dequeuing the
work
Result:
Queued NIOThreadPool tasks can be cancelled before they are run.
Motivation:
Renaming the `NIOFileSystem` module to `_NIOFileSystem` is a breaking
change (which is okay, it's documented to be unstable API). However,
users will be presented with a wall of build errors on updating to the
next version of NIO. We can make the transition slightly easier for
them.
Modifications:
Add back a `NIOFileSystem` module which re-exports `_NIOFileSystem` and
add it as a target to the `_NIOFileSystem` product. This makes both
modules available to users. We can then remove `NIOFileSystem` after a
grace period.
Result:
Users can still build using `NIOFileSystem` but can transition to
`_NIOFileSystem`.
Motivation:
DispatchGroup can cause thread performance checker warnings in
places we don't want them. We can avoid those warnings in some
cases by using a condition variable instead.
Modifications:
- Replaced a use of DispatchGroup with a condition variable
in NIOThreadPool setup.
- Removed an unnecessary DispatchGroup in the shutdown code
Result:
Fewer thread performance checker warnings.
Motivation:
When a file is created 'atomically' and the descriptor is detached from
its handle then the user is provided with the descriptor for a temporary
file, and the desired file is never created.
Modifications:
Where supported, atomically created files use a temporary unnamed file
which is then linked on close. Elsewhere a temporary named file is
created which is renamed on closed.
Temporary unnamed files are linked in detach but not closed. Temporary
named files are linked to the desired path before being unlinked.
- Break out the logic for materializing a file created using a temporary
unnamed file
- Add syscalls and error mappings for link(2) and unlink(2)
Result:
Atomically created files behave as expected when detached
Motivation:
The 'NIOFileSystem' target isn't yet stable API and is made available
via the '_NIOFileSystemModule' product. This doesn't make it obvious
enough that the module isn't yet considered stable.
Modifications:
- Rename 'NIOFileSystem' and 'NIOFileSystemFoundationCompat' such that
they are prefixed with '_'.
Result:
More obviously not stable API
Motivation:
In the current implementation, if the users forget to call 'flush()' on
the writer when creating a new file with 'withFileHandle(forWritingAt:options:execute)' the newly created file is empty.
Modifications:
- Added the 'withBufferedWriter()' method for the 'WritableFileHandleProtocol' and implemented it for
the WriteFileHandle and 'ReadWriteFilehandle'. The method calls flush on the bufferedWriter after
executing the closure that writes the contents to the file as indicated by the user.
Result:
Users can now use the 'withBufferedWriter' method instead of instantiating the bufferedWriter themselves,
reducing the possibility of omitting 'flush()'.
This change allows users to setup a broadcast socket using a NIO owned
constant instead of directly using a C constant.
```diff
- .channelOption(ChannelOptions.socket(SOL_SOCKET, SO_BROADCAST), value: 1)
+ .channelOption(ChannelOptions.socketOption(.so_broadcast), value: 1)
```
Fixes#2674
Motivation:
`numberOfThreads` is a required parameter to the public constructor, it's therefore known to the caller. Any use case that wants to optimise its logic for the parallelism offered by the particular `NIOThreadPool` needs to carry the number of threads separately from the `NIOThreadPool` itself. We should exposes `numberOfThreads` publicly from `NIOThreadPool` to avoid this complexity and possible bugs.
This is especially true for `NIOThreadPool.singleton` where the decision on the number of threads used is achieved through some complex and dynamic logic. It's therefore best not to second guess the result of those calculations.
Modifications:
Flip the visibility of `numberOfThreads` in `NIOThreadPool` to `public`.
Result:
Some complexity gets removed from client packages.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Get the new module building and tested on my Android CI again
Modifications:
- Add force unwraps where needed
- Update C types and account for nullability annotations in NDK 26
- Use /data/local/tmp for the `temporaryDirectory` and invoke it in the tests, instead of /tmp directly
- Don't copy over extended attributes
- Android doesn't support hard-linking on most partitions, so don't use it for materializing temporary files
Result:
Everything works again on Android
# Motivation
Adding a handler via the regular `pipeline.addHandler` APIs can lead to transferring the handler over isolation regions. To avoid running into `Sendable` warnings here we can use the `syncOperations` of the pipeline to avoid transferring the handlers.
# Modification
This PR is mostly changing code to avoid transferring handlers to and from the event loops in tests. This should be a no-op mostly.
Co-authored-by: Cory Benfield <lukasa@apple.com>
* Fix `SchedulingBenchmark` preheating logic.
Motivation:
At the moment `SchedulingBenchmark` preheats single EL to a specified number of tasks. However, the actual performance test runs number of times, and EL doesn't get drained in between the runs.
There are two problems with it:
* perf test will trigger task heap dublings, which the preheating aims to avoid
* each test run will be working with proportionally deeper heap, which means the run times are going to grow with each run
Modifications:
I plumbed through the # of runs to the `Benchmark.setUp`, and prepare ELG with # of ELs that match the expected number of runs.
Result:
Performance test will be more reliable.
* Revert "Fix `SchedulingBenchmark` preheating logic."
This reverts commit 859ba72c78.
* Remove SchedulingBenchmark. Deemed not valuable enough.
* Benchmark for measuring NIOThreadPool dispatch
* Avoid CoW cost for NIOThreadPool work queue
* Flip stray `var` to a `let`.
* Use .modifying state to prevent CoW, not a class
* Removing some obselete comment noise.
* Use Deque instead of CirclarBuffer in NIOThreadPool
* Ratchet down the # of allocs for read_10000_chunks_from_file. NIOTheadPool changes reduced the allocations required.
* Introduce `assumeIsolated()` methods on `EventLoop`, `EventLoopPromise` and `EventLoopFuture`
> All methods/types are currently `internal` so we don't have to bikeshed just yet but we can move forward to get `NIOCore` warning free under strict concurrency
# Motivation
Methods on the above types are often called from the same event loop; however, we cannot prove to the compiler that this is true so we had to mark many methods on those types with `@Sendable` or require the generic type to be `Sendable`. This leads to unnecessary usage of `NIOLoopBound` when instead we should just dynamically assert that we are on the event loop. @dnadoba opened a very similar PR https://github.com/apple/swift-nio/pull/2228.
# Modification
This PR provides a method called `assumeIsolated()` on the three types that returns a type which re-declaration of all methods of the wrapped typed that have `Sendable` annotations. This new type is asserting at runtime that we are on the right event loop; hence, we don't need a `Sendable` value.
# Result
This PR makes it easier for our adopters to avoid newly introduced `Sendable` warnings
* Review
# Motivation
We have a few more warnings left under strict concurrency checking in `NIOCore`. This fixes the bulk of them that are not tied to `ChannelHandler` or `ChannelPipeline`.
# Modification
Add more `Sendable` and `@Sendable` annotations and make sure to use types that are `Sendable` annotated.
Motivation:
When the `BufferedReader` reads short when filling its buffer during a
request for some bytes, it may avoid giving the caller all bytes
available. The bytes remain in the buffer and are available on the next
call but this appears to the caller as if the file has been read
completely as the returned bytes are less than those requested.
Modifications:
- Read the expected bytes or whatever is left in the buffer
- Add a test
Result:
Less unexpected behaviour
# Motivation
We currently have an unchecked `Sendable` conformance on `ChannelOptions.Storage` which is not necessary and in fact we are missing a proper `Sendable` requirement on the `ChannelOption.Value` protocol right now.
# Modification
This PR adds the `Sendable` requirement on the `ChannelOption.Value` and replaces the unchecked conformance on the storage with a regular one.
# Result
No more `Sendable` warnings in strict concurrency mode inside `ChannelOptions`.
Motivation:
There is a bug in `ReadableFileHandleProtocol.bufferedReader(startingAtAbsoluteOffset:capacity:)` where we are hardcoding initial offset to 0 instead of passing the actual param value.
Modifications:
Pass the actual param value.
Motivation:
SwiftNIO doesn't compile for visionOS because NIOFileSystem depends on
Swift System which doesn't yet support visionOS.
As NIOFileSystem isn't yet stable API we can define it out on some
platforms.
Modifications:
- Only define NIOFileSystem on macOS, iOS, tvOS, watchOS, Linux and
Android.
- Only include Swift System on the same platforms
Result:
SwiftNIO compiles on visionOS, albeit without NIOFileSystem.
Use direct syscall for `renameat2` because Musl doesn't include
a wrapper for it. Similarly, define the constants ourselves.
Add Musl imports in relevant places.
On watchOS, the arm64_32 bit architecture restricts software to ILP32 which means integers are 32-bit. This expands our existing 32-bit checks to include arm64_32.
Motivation:
I/O is typically blocking, but options for interacting with the
filesystem using `async` APIs are limited. This change adds a new module
to NIO, `NIOFileSystem`. At the moment this is exposed as the
`_NIOFileSystem` product while users get a chance to try it out and
provide feedback.
During this time the API of `NIOFileSystem` is subject to change.
Breaking changes will come in _minor_ NIO releases and additive changes
may come in _patch_ releases of NIO.
Modifications:
- Add `NIOFileSystem`, `NIOFileSystemFoundationCompat`,
`NIOFileSystemTests`, `NIOFileSystemIntegrationTests`, and
`NIOFileSystemFoundationCompatTests`.
- Update docs
- Update CNIOLinux and CNIODarwin shims
Result:
File system can be accessed via `async` APIs
# Motivation
We had to disable the benchmarks since they regressed without us noticing and they appear to be flaky.
# Modification
This PR fixes the allocation regression and tries to re-enable them.