Commit Graph
2945 Commits
Author SHA1 Message Date
Franz Busch 9d5d0b6007 [GHA] Add API breaking check (#2763)
# 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.
2024-07-04 03:27:38 -07:00
Franz Busch 304a238b09 [GHA] Fix docker images (#2762) 2024-07-02 07:58:07 -07:00
Franz Busch 2f99bc3fa5 [GHA] Introduce the first GitHub Action (#2760)
# 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
2024-07-02 05:26:56 -07:00
Johannes Weiss fc79798d5a NIOSendableBox: allow off-loop initialisation iff Value is Sendable (#2753)
### 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.
2.68.0
2024-06-27 07:51:24 -07:00
Franz Busch 5d7a9997e6 Throw an appropriate error from the writer when the channel closed (#2744)
# 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.
2024-06-24 07:11:36 -07:00
taylorswift ea6a8db87a put snippet code inside @available function (#2750) 2024-06-21 20:20:14 +01:00
Rick Newton-Rogers 41f66948e1 fix link to NIOFileSystem from NIO index page (#2747)
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
2024-06-21 16:59:46 +01:00
taylorswift 38f6b98c6a convert the NIOFileSystem example code to a Snippet (#2746)
* convert the NIOFileSystem example code to a Snippet

* fix compilation error

* add missing license header

* exclude snippets from soundness.sh
2024-06-21 10:23:18 +01:00
Gwynne Raskind e5a216ba89 Silence warning about missing include in macOS builds (#2741) 2.67.0 2024-06-13 11:24:28 -07:00
Dimitri Bouniol 72cab7d9a4 Correctly mark 304 as not having a response body (#2737)
* 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
2024-06-12 18:30:58 +01:00
Gustavo Cairo 2b5d277589 Update availability guard (#2739) 2024-06-11 10:55:26 -07:00
Gustavo Cairo bc161803bb Add API for setting last accessed and last modified file times (#2735)
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.
2024-06-10 16:58:21 +01:00
George Barnett 9428f62793 Add a fallback path if renameat2 fails (#2733)
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
2.66.0
2024-05-31 09:30:50 +01:00
Peter Adams e2aef20375 Release file handles back to caller on failure to take ownership (#2715)
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.
2024-05-30 10:57:36 +01:00
George Barnett d8bf55d693 Add a version of 'write' for 'ByteBuffer' (#2730)
* 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
2024-05-29 14:59:06 +01:00
George Barnett 9f63b12a05 Imrprove rename error (#2731)
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
2024-05-29 14:17:52 +01:00
George Barnett 4612941246 Remove storage indirection for FileSystemError (#2726)
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
2024-05-23 12:58:59 +01:00
Rick Newton-Rogers 7d1b76d27b testSimpleMPTCP should not fail for ENOPROTOOPT (#2725)
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
2024-05-23 10:07:45 +01:00
ser 196ceab4b2 Fix race in TCPThroughputBenchmark (#2724) 2024-05-20 09:52:05 -07:00
Peter Adams 609469f968 Exclude unused privacy manifests. (#2716)
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.
2024-05-16 12:58:17 +01:00
Peter Adams 6753556a85 Add slack to rst allocation tests (#2722)
Motivation:

Allocation tests are slightly fragile to small changes.

Modifications:

Allow 50 extra allocations over the 1000 cycles.

Result:

Rst tests less flaky
2024-05-14 07:42:01 -07:00
Johannes Weiss 5c378ed31c Document unsafeTryInstallSingletonPosixEventLoopGroupAsConcurrencyGlobalExecutor (#2721)
Document what unsafeTryInstallSingletonPosixEventLoopGroupAsConcurrencyGlobalExecutor's return value means
2024-05-14 11:12:13 +01:00
Johannes Weiss cd51717926 clean up @retroactive conformances (#2719) 2024-05-09 13:01:33 +01:00
Peter Adams a5cb713246 No longer need test discovery command line. (#2717)
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
2024-05-07 16:46:41 +01:00
Johannes Weiss 447b28105f concurrency takeover safe for 6.0 (#2710) 2024-04-29 04:11:24 -07:00
George Barnett 29e832adda Replace 'R' with 'Result' (#2709)
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
2024-04-29 11:01:17 +01:00
George Barnett 8c3135b7d4 Add 'withTemporaryDirectory' (#2708)
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
2024-04-26 01:39:06 -07:00
George Barnett f2f4ce8be7 Add ByteBuffer support to BufferedWriter (#2707)
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
2024-04-26 09:02:57 +01:00
Peter Adams d3bdffd5e4 Remove surplus Sendable requirements from FileSystem with methods (#2706)
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.
2024-04-24 10:36:03 +01:00
George Barnett 359c461e55 Retain a ref to NIOAsyncWriter until channel active (#2703)
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.
2.65.0
2024-04-22 02:49:48 -07:00
George Barnett bfc1a2cf6c Tolerate IPv6 address resolution failure (#2704)
Motivation:

In some cases IPv6 loopback address resolution fails in tests. We should
tolerate this.

Modifications:

- Swallow SocketAddressError.unknown

Result:

Fewer flaky tests
2024-04-22 08:55:06 +01:00
George Barnett fa540cf39b Add privacy manifest (#2695)
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.
2024-04-17 02:48:03 -07:00
Yuta Saito 8b43f703d4 Add support for SWIFTCI_USE_LOCAL_DEPS convention (#2699)
To use this package in utils/build-script pipeline
2024-04-10 08:57:21 -07:00
George Barnett b222c26b5b Add a helper for setting or cascading optional promises (#2697)
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.
2024-04-09 18:43:35 +01:00
hamzahrmalikandCory Benfield 082ac2186f Add delegate for collecting eventloop tick metrics (#2608)
* Add delegate for collecting eventloop tick metrics

* add warning to docc

* add missing headers

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-03-27 16:26:59 +00:00
Stefana-Ioana Dranca 05fbcace24 Added file and line to NIOAsyncWriterError description (#2693)
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
2024-03-26 06:53:14 -07:00
George Barnett 2d840c586f Use NIOThreadPool in NIOFileSystem (#2692)
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
2024-03-26 13:15:27 +00:00
Dave DeLongandCory Benfield 6b29fc3c2b Clarify Client/Server column headers (#2691)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-03-25 18:44:30 +00:00
George Barnett 1f5be716fe Add cancellation to NIOThreadPool's async runIfActive (#2679)
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.
2024-03-25 15:52:40 +00:00
George Barnett 10af7c92e7 Remove temp directories after tests (#2690)
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
2024-03-25 12:56:08 +00:00
George Barnett 778e3da621 Add a NIOFileSystem shim (#2689)
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`.
2024-03-22 07:20:08 -07:00
Gustavo Cairo d15793cd20 Change BufferedReader.read(while:) signature (#2688)
Return whether EOF read or predicate doesn't hold anymore in BufferedReader.read(while:)
2024-03-20 04:34:09 -07:00
Cory Benfield f8c5e02ec4 Remove DispatchGroup and replace with condvar (#2687)
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.
2024-03-20 10:31:46 +00:00
George Barnett 1e2b3e34af Handle 'atomically' created files more gracefully when detached (#2682)
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
2024-03-15 16:45:49 +00:00
George Barnett df5745d6be Underscore the NIOFileSystem module (#2683)
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
2024-03-14 08:16:36 -07:00
Konrad `ktoso` Malawski b92e058cf8 Update issue template link in SECURITY.md (#2680)
The link was incorrect since the file had moved.
2024-03-13 01:42:24 -07:00
Stefana-Ioana Dranca a40ad7c034 Prevent BufferedWriter from producing empty files (#2677)
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()'.
2024-03-12 04:09:24 -07:00
Rauhul Varma dc296f2ff7 Add NIOBSDSocket.Option for SO_BROADCAST (#2678)
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
2024-03-11 21:33:36 +00:00
Gregor Milos (Grzegorz Miłoś)andCory Benfield 887b2c1e38 Expose NIOThreadPool.numberOfThreads publicly. (#2676)
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>
2024-03-11 03:28:38 -07:00
George Barnett cc158ec6c7 Raise minimum Swift version to 5.8 (#2675) 2024-03-11 08:47:57 +00:00