# Motivation
The next GH action pipeline that we need is to add our API breaking change checker.
# Modification
This PR adds an API breaking change job to our pull request workflow.
# Motivation
We want to move our CI over to use GitHub Actions. We need to cover multiple different things like unit tests, benchmarks, soundness, API breaks, doc validation etc.
# Modification
This PR starts our journey to GitHub Actions by introducing the PR workflow. Right now this workflow only runs the Swift tests on our repository without any additional compiler flags like `-warnings-as-errors`. This aims to get us started and we will continue to modify them in subsequent PRs.
# Result
We got our first GH workflows running
### Motivation:
`NIOLoopBound` and `NIOLoopBoundBox` are important tools for making mutable types `Sendable`.
The power of `NIOLoopBoundBox` is that it allows correct mutation, whilst remaining `Sendable` without locks and without having to use `@unchecked` if the mutable class makes sure to have all accesses (reading & writing) run on one particular `EventLoop`. This is safe as `EventLoop`s guarantee sequentially consistent memory order across executions of different work items/events. Typically `EventLoop`s achieve this by just being thread-bound.
These types are well used already but there's a small and common pattern which is safe but unsupported as of yet:
Initialise a `NIOLoopBoundBox` with a `Sendable` value _off_ the loop. All further accesses (reads & writes) however happen _on_ the loop. That's safe because of Swift's Definitive Initialisation (DI) but `NIOLoopBoundBox` didn't support this pattern (apart from `makeEmptyBox` which always initialises with `nil`).
### Modifications:
- Allow `Sendable` values to be provided whilst creating the type off loop.
### Result:
- Even more types can be safely & correctly made `Sendable` without using `@unchecked.
# Motivation
Currently, when the channel closes and a user tries to write something the writer throws an `AlreadyFinished` error. This error can also be thrown when calling `finish` on the writer and then trying to call `write` again. This makes it hard to distinguish if the thrown error was due to the channel being closed or due to a business logic error in handling the writer.
# Modification
This PR finishes the writer with a `ChannelError.ioOnClosedChannel` if the writer gets finished to due a channel inactive or handler removed.
# Result
Users can now distinguish if they did something wrong with the writer or if the channel closed.
Motivation:
The existing link to NIOFileSystem docs 404's
Modifications:
Speculative fixes because getting any links to work locally is
challenging.
* rename `NIOFileSystem.md` -> `index.md` in line with other modules
* modify the link on the NIO index page to reference `_NIOFileSystem`
local experiments suggest it might change the form of the generated
URL to where the docs can be found
(https://swiftpackageindex.com/apple/swift-nio/2.67.0/documentation/_NIOFileSystem).
Result:
Hopefully the NIOFileSystem docs link will work
* 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:
MPTCP implementations are permitted to return `ENOPROTOOPT` if MPTCP has
been disabled. This should not report as a test failure.
Modifications:
Instead of failing the test, log the permitted error and return.
Result:
No more misleading testSimpleMPTCP test failures
Motivation:
On Darwin privacy manifests should be published as resources.
On other platforms they result in a warning if not excluded.
Modifications:
Alter Package.swift to exclude privacy manifests when not included.
Result:
Fewer warnings in non-darwin builds.
Motivation:
Allocation tests are slightly fragile to small changes.
Modifications:
Allow 50 extra allocations over the 1000 cycles.
Result:
Rst tests less flaky
Motivation:
Command line argument has not been needed for several swift version.
Modifications:
This causes warnings in recent swift versions.
Result:
No more warnings about swift command line when testing
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:
In some cases IPv6 loopback address resolution fails in tests. We should
tolerate this.
Modifications:
- Swallow SocketAddressError.unknown
Result:
Fewer flaky tests
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:
A couple of filesystem tests create directories but don't clean up after
themselves.
Modifications:
- Add teardown blocks to remove the temp directories
Result:
No leftover files after running tests
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>