1871 Commits
Author SHA1 Message Date
Franz Busch b4fae75400 Fix global concurrency hook integration test (#2857)
# 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
2024-09-02 13:04:46 +02:00
Chris McGeeandCory Benfield e1b2a99d12 Provide documentation and context information for NIOTooManyBytesError (#2831)
### 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>
2024-08-28 20:37:39 +01:00
Cory Benfield a4e0a13c8b Explain why TSV isn't Sendable. (#2845)
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.
2024-08-16 15:58:35 +01:00
Cory Benfield 23e6139e45 Remove symlinks from resources (#2841)
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.
2024-08-13 08:14:22 +01:00
Cory Benfield 1f3dc9c530 Adopt strict concurrency in _NIOBase64 (#2838)
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
2024-08-12 13:01:28 +01:00
Cory Benfield e1b4235b7f Adopt strict concurrency in _NIODataStructures (#2835)
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.
2024-08-09 13:27:01 +00:00
Cory Benfield 4ea1f30406 Adopt strict concurrency and Sendable in NIOConcurrencyHelpers (#2832)
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
2024-08-08 12:57:49 +01:00
Rick Newton-Rogers bd12191411 Clone files on Darwin rather than copying them (#2823)
### 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.
2024-08-05 12:04:52 +01:00
Valeriy Van d62a876741 Fix typo in comment in WebSocketErrorCodes.swift (#2604) 2024-08-05 09:18:15 +00:00
Matt Hope f0451084bb Provide a default CopyStrategy overload for copyItem. (#2818)
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()
2024-08-01 09:13:47 +00:00
Gustavo Cairo de68e48d7e Make EventLoopPromise conform to Equatable (#2714) 2024-07-31 14:01:14 +00:00
Ayush Garg 7840b6b067 ChannelOption: Allow types to be accessed with leading dot syntax (#2816)
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)
```
2024-07-30 15:19:59 +00:00
Matt Hope 022ee1328b FileSystem.copyItem can parallelise directory copy (#2806)
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.
2024-07-29 11:14:10 +01:00
Franz Busch f17f7e5909 [CI] Add shellcheck and fix up warnings (#2809)
# 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
2024-07-25 14:55:44 +00:00
Si Beaumont 55d4c49334 Better align shutdown semantics of testing event loops (#2800)
### 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.
2024-07-25 14:38:36 +00:00
Franz Busch 6630cc6c6f Change unsafeDownCast to as! (#2802)
# 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
2024-07-24 09:35:35 +01:00
finagolfin 4feff3c2f6 Use the new Android overlay and Bionic module from Swift 6 (#2784)
Motivation:

Get this repo building again for Android with the new overlay

Modifications:

- Import the new module or overlay wherever `Glibc` is used
- Keep this repo building with Swift 5 by duplicating some declarations

Result:

All the same tests keep passing on my Android CI, finagolfin/swift-android-sdk#158
2024-07-22 09:58:09 +00:00
Franz Busch c9756e1083 Adopt swift-format (#2794)
* Apply formatting

* Apply no block comments rule

* Apply OmitExplicitReturns

* Apple OnlyOneTrailingClosureArgument

* Apply NoAssignmentInExpressions

* Fix up DontRepeatTypeInStaticProperties lint errors

* Apply `OrderedImports`

* Apply `ReplaceForEachWithForLoop`

* format file

* Enable the formatting pipeline

* Adopt `AmbiguousTrailingClosureOverload`

* Fix license header

* Fix format check

* Fix `EndOfLineComment`

* Fix CI

* Adapt CI script to check if changes when running formatting

* Separate lint and format into to steps

* Fix format

* Adopt `UseEarlyExits`

* Revert "Adopt `UseEarlyExits`"

This reverts commit d1ac5bbe12.
2024-07-19 11:48:17 +02:00
Johannes Weiss 7948ed2104 ChannelHandler: provide static (un)wrap(In|Out)bound(In|Out) (#2791) 2024-07-18 11:55:48 +01:00
George Barnett 223b0e8eac Add manual control to NIOLockedValueBox (#2786)
Motivation:

NIOLockedValueBox has a 'safer' API than NIOLock as it only provides
scoped access to its boxed value. NIOLock requires users to only access
protected state while the lock is acquired. As such NIOLockedValueBox
should be preferred where possible. However, there are cases where
manual control must be used (such as storing a continuation) and users
must use a NIOLock for this.

There are two downsides to this:

1. All other access to the protected state must use the NIOLock API
   putting the onus on the developer to only access the protected state
   while the lock is held.
2. NIOLock can't store its protected state inline which typically
   results in users storing it on a class.

Modifications:

- Add an 'unsafe' view to NIOLockedValueBox which allows users to
  manually control the lock and access its protected state
- Update NIOAsyncWriter and NIOThrowingAsyncSequenceProducer to use NIOLockedValueBox

Result:

- Safer locking API is used in more places
- Fewer allocations
2024-07-18 01:16:59 -07:00
Dimitri Bouniol 5e9a9ccc10 Improved documentation for HTTP Parts to clarify how often each part is received (#2775) 2024-07-12 02:20:14 -07:00
George Barnett 0f4c110bd7 Combine the two NIOAsyncChannel channel handlers (#2779)
Motivation:

The NIOAsyncChannel allocates 12 times on init. 4 of these allocations
come from creating two channel handlers and two channel handler
contexts. There's no inherent reason that these channel handlers can't
be combined to eliminate two allocations (one handler and one context).

Modifications:

- Combine `NIOAsyncChannelInboundStreamChannelHandler` and
  `NIOAsyncChannelOutboundWriterHandler` into a single
  `NIOAsyncChannelHandler`. Most of this was straightforward as only a
  few handler operations were duplicated across both.
- Add a 'NIOAsyncChannelHandlerWriterDelegate' in place of the
  'NIOAsyncChannelOutboundWriterHandler.Delegate'. One knock on from
  this is that the new delegate stores callbacks rather than the
  concrete type of the handler. This is necessary to prevent the
  generics from the new channel handler bubbling up to the outbound
  writer (which would break API and be somewhat odd).

Result:

Fewer allocations
2024-07-12 01:02:04 -07:00
George Barnett abbb144f66 Avoid creating a yield ID counter per async writer (#2768)
Motivation:

The NIOAsyncWriter uses an atomic to generate yield IDs. Each writer has
its own atomic. We can save an allocatiuon per writer but using a shared
atomic.

Each load then wrapping increment operation with relaxed ordering takes
approx 3ns on my machine. For a UInt64 this would take approx 188 years
to wrap around if run in a tight loop.

Modification:

- Share a single yield ID counter for NIOAsyncWriter

Result:

Fewer allocations
2024-07-09 05:27:35 -07:00
Franz Busch 5cc05490c4 [GHA] Unacceptable language check (#2766)
* [GHA] Unacceptable language check

# Motivation

Next up replacing part of our soundness script that checked for unacceptable language.

# Modification

This PR adds a new GH action that checks for unacceptable language.

# Result

One more script replaced

* PR review

* Change homepage link to repo
2024-07-09 07:56:26 +01:00
David Nadoba e947421dd8 Allow in-place mutation of NIOLoopBoundBox.value (#2771)
* Allow in-place mutation of `NIOLoopBoundBox.value`

* Fix typos in docs
2024-07-08 15:19:55 +01:00
George Barnett 9b86559506 Pre-box some errors to reduce allocations (#2765)
Motivation:

Existential errors (`any Error`) are unconditionally boxed. In NIO we
often create errors to fail promises. One place we do this is in the
head channel handler when the pipeline is closed. This error is created
regardless of whether there are actually any promises to fail. The
result is an unnecessary allocation when every channel is closed. This
is particuarly egregious when multiplexed protocols such as HTTP/2 are
used.

As the majority of errors in NIO carry no information beyond their
type/name we can declare these statically and pay the cost of each error
just once rather than once per use.

Modifications:

- Add internal static constants for `ChannelError` and `EventLoopError`
  and use them throughout NIOCore and NIOPosix where they would
  otherwise be boxed.

Result:

Fewer allocations
2024-07-05 08:01:29 -07:00
Franz Busch 9730938793 [GHA] Documentation check (#2764)
# Motivation

Next up replacing the documentation check.

# Modification

This moves the current approach of the script into a GH action. I tried just running the documentation check against all targets but that also results in warnings from downstream deps in their docs to show up.

I also fixed up some new errors that appeared since our current pipeline was running on 5.8.

# Result

Next CI job migrated to GHA
2024-07-04 16:21:18 +01: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.
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
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) 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