Commit Graph
2140 Commits
Author SHA1 Message Date
Gwynne Raskind e5a216ba89 Silence warning about missing include in macOS builds (#2741) 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 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
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
ser 196ceab4b2 Fix race in TCPThroughputBenchmark (#2724) 2024-05-20 09:52:05 -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
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.
2024-04-22 02:49:48 -07: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
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
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 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
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
Gregor Milos (Grzegorz Miłoś) 5e470773ca Track execute() and enqueue() tasks separately from scheduled tasks. (#2645) 2024-03-05 16:01:47 +00:00
finagolfin 53be20532e Build the new FileSystem module for Android (#2660)
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
2024-03-05 14:46:54 +00:00
Franz BuschandCory Benfield 63e8c4e1aa Migrate to syncOperations in more places (#2661)
# 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>
2024-03-01 15:05:22 +00:00
Gregor Milos (Grzegorz Miłoś) 325f762a8b Remove unreliable SchedulingBenchmark (#2650)
* 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.
2024-03-01 11:10:46 +00:00
Gregor Milos (Grzegorz Miłoś) c3b6f1f3f5 Fix CoW performance bug in NIOThreadPool work queue (#2669)
* 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.
2024-02-28 15:43:52 +00:00
Franz Busch 8a9a3b1db5 Introduce assumeIsolated() methods on EventLoop, EventLoopPromise and EventLoopFuture (#2657)
* 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
2024-02-19 18:09:26 +00:00
Franz Busch 0fbf6f1e42 Add some more Sendable annotations to NIOCore (#2656)
# 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.
2024-02-19 02:01:02 -08:00
Franz Busch 011b3df040 Conform NIOIPProtocol to Sendable (#2655)
# Motivation

We were missing a `Sendable` conformance on `NIOIPProtocol`
2024-02-17 11:47:54 -08:00
George Barnett 82fd942745 Don't drop bytes from the buffered reader when reading short (#2646)
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
2024-02-13 09:51:57 +00:00
Franz Busch e4102aecb5 Remove @unchecked Sendable conformance from ChannelOptions.Storage (#2638)
# 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`.
2024-02-12 09:48:54 +00:00
745c79246b fix: conditionally define RENAME_* macros (#2643)
When using `-Xcc -Werror` flags redefining macros results in a compilation
error. Instead we check if they are not defined before defining for the
musl case.

Fixes regression in https://github.com/apple/swift-nio/pull/2628.

Co-authored-by: Austin Payne <austin@passivelogic.com>
Co-authored-by: George Barnett <gbarnett@apple.com>
2024-02-09 01:56:25 -08:00
Yim Lee bb892d10b1 Pass initial offset to BufferedReader.init (#2642)
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.
2024-02-09 09:22:20 +00:00
George Barnett 53965cc348 Only compile FileSystem on some platforms (#2636)
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.
2024-02-01 13:24:21 +00:00
George Barnett 635b258949 no confstr on Android (#2627) 2024-01-19 10:43:19 +00:00
Alastair Houghton c14d7d6c9e More changes to support building with Musl. (#2628)
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.
2024-01-18 07:44:33 -08:00
Harish Yerra a0e0c68d71 [arch] Add arm64_32 to the 32-bit platform check (#2625)
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.
2024-01-17 05:34:01 -08:00
George Barnett f80c69f84b Add NIOFilesystem (#2615)
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
2024-01-16 03:30:26 -08:00
Franz Busch 826fce4fdb Fix NIOAsyncChannel allocation benchmarks (#2622)
# 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.
2024-01-12 14:23:54 +00:00