Commit Graph
2140 Commits
Author SHA1 Message Date
67dd9ca974 Issue-2748 - Add ByteBuffer Hex init & write (#2837)
Add ability for below two functions 
`ByteBuffer(hexEncodedBytes: "68 65 6c 6c 6f 20 77 6f 72 6c 64 0a")`
` buffer.writeHexEncodedBytes("68656c6c6f20776f726c640a")`

### Motivation:

https://github.com/apple/swift-nio/issues/2748

---------

Co-authored-by: Ali Ali <ali.ali@qantas.com.au>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-09-30 17:26:37 +00:00
Euan Harris 1b33db2dea Work around a type checking error when using the Static Linux SDK (#2898)
# Motivation

Building `swift-nio` with the Static Linux SDK

(https://www.swift.org/documentation/articles/static-linux-getting-started.html),
fails in `PosixSingletons+ConcurrencyTakeOver.swift`:

```
Building for debugging...
error: emit-module command failed with exit code 1 (use -v to see invocation)
/private/tmp/vaportest/.build/checkouts/swift-nio/Sources/NIOPosix/PosixSingletons+ConcurrencyTakeOver.swift:76:12: error: conflicting arguments to generic parameter 'T' ('Optional<UnsafeRawPointer>.AtomicRepresentation' vs. 'Optional<UnsafeRawPointer>.AtomicRepresentation')
 74 |             dlopen(nil, RTLD_NOW),
 75 |             "swift_task_enqueueGlobal_hook"
 76 |         )?.assumingMemoryBound(to: UnsafeRawPointer?.AtomicRepresentation.self)
    |            `- error: conflicting arguments to generic parameter 'T' ('Optional<UnsafeRawPointer>.AtomicRepresentation' vs. 'Optional<UnsafeRawPointer>.AtomicRepresentation')
 77 |         guard let concurrencyEnqueueGlobalHookPtr = concurrencyEnqueueGlobalHookPtr else {
 78 |             return false
```

This happens because `Foundation` and `swift-atomics` both define
`AtomicRepresentation`. A compiler problem (rdar://132885963) makes
these extensions globally visible, causing the two
`AtomicRepresentation`
types to collide.   This only affects non-Darwin platforms.

 # Modification

This PR works around the problem by using a local type alias which does
not collide with the other `AtomicRepresentation` types.

 # Result

It is now possible to build `swift-nio` with the Static Linux SDK.

Fixes: https://github.com/apple/swift-nio/issues/2893
Suggested-by: Alastair Houghton <ahoughton@apple.com>
2024-09-24 13:32:18 +01:00
Franz Busch aa25fdaf97 Add an AcceptBackoffHandler to the async server bootstraps (#2782)
# Motivation

When encountering a file descriptor limit we are currently closing the
server socket when using the async bootstraps since the error caught is
delivered via the `inbound` sequence of the server socket async
sequence.

# Modification

This PR adds the `AcceptBackoffHandler` in the async bootstrap case to
the pipeline to avoid us closing the server socket channel when we hit
the file descriptor limit.

# Result

We are now gracefully handling file descriptor limits.
2024-09-23 13:46:13 +01:00
John ZhouandCory Benfield ac6d905654 Add new ChannelOption to get the amount of buffered outbound data in the Channel (#2849)
Add ability to get the amount of buffered outbound data from `Channel`

### Motivation:
Right now, SwiftNIO does not have the API to answer the question "how
much data is buffered in the Channel". Applications focusing on
performance may need to fine-tune the amount of outbound data that will
be sent to optimize data throughput, adjust sending rate to avoid
overflow, and potentially reduce latency.

SwiftNIO currently provides some backpressure mechanism. This new API
will be a good addition. By knowing how much data is buffered directly,
applications can make informed decision to adjust for optimal buffer
sizes and send rates.

### Modifications:
- Expose current buffer size through ChannelOptions so that users can
read the value out. StreamSocketChannel, DatagramSocketChannel,
EmbeddedChannel, and AsyncTestingChannel have the same API interface.
- Various modifications to the existing tests to make sure the new API
is working correctly.
- Add a new `so_sndbuf` socket option so that users can easily adjust
the send buffer size.

### Result:

Users can get the amount of outbound bytes currently buffered in the
`Channel` through the new `BufferedWritableBytesOption` channel option.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-09-23 10:12:48 +00:00
Rick Newton-Rogers f66650595f Conditionally include linux/udp.h (#2894)
### Motivation:

To enable access to `UDP_MAX_SEGMENTS` we switched from including
`netinet/udp.h` to including `linux/udp.h` however the latter isn't
available in MUSL.

### Modifications:

if `linux/udp.h` is available then import it in favor of
`netinet/udp.h`. If we fall back to the latter then `UDP_MAX_SEGMENTS`
won't be defined but that will be caught by the existing paths which
account for this case.

### Result:

NIO should be able to build against a static MUSL SDK again.
2024-09-20 15:08:35 +00:00
aryan-25 4bf92d5b50 Add concrete description for EmbeddedEventLoop (#2890)
### Motivation:

We want to avoid going through `EventLoopGroup`'s [`String(describing:
self)`](https://github.com/apple/swift-nio/blob/8307ad610a358513b2190955379829d70f04b8c2/Sources/NIOCore/EventLoop.swift#L414)
when obtaining the description of an `EventLoopGroup` or `EventLoop`.

The concrete `MultiThreadedEventLoopGroup` and `SelectableEventLoop`
already implement a `description` property. `EmbeddedEventLoop` does
not.

### Modifications:

Added a concrete description property in `EmbeddedEventLoop`.

### Result:

The description of `EmbeddedEventLoop` can be obtained without going
through `String(describing: self)`.
2024-09-20 12:19:11 +00:00
Rick Newton-Rogers 0d3043e050 Revert "Adopt NIOThrowingAsyncSequenceProducer (#2879)" (#2892)
This reverts commit 282f5935cf.

### Motivation:

Repeated testing in linux containers has surfaced issues with the
implementation which require some rethinking of the code, let's revert
it for now and fix it up.

### Modifications:

Revert the adoption commit.

### Result:

The change is backed out.
2024-09-20 10:58:47 +00:00
Rick Newton-Rogers 9f6c011e08 Expose UDP_MAX_SEGMENTS via System (#2891)
### Motivation:

Linux kernels recently increased the value of `UDP_MAX_SEGMENTS` from 64
to 128 causing hardcoded assumptions in our tests to become invalid.

### Modifications:

Surface the value of `UDP_MAX_SEGMENTS` if it is defined on the platform
in use via new public API `System.udpMaxSegments()` (otherwise return
`nil`) and make use of it in `DatagramChannelTests`.

`System.udpMaxSegments()` is added as new public API in analogue to e.g.
`System.supportsUDPReceiveOffload`.

### Result:

`DatagramChannelTests` pass and new API.
2024-09-20 11:22:50 +01:00
8307ad610a Issue-2734 - Clamp buffer to maximum upon large write operation (#2745)
### Motivation:

Fix Issue 2734

### Modifications:
- Added a function to clamp storage by copying bytes and setting new
capacity of storage
- Adding a function to clamp the capacity of ByteBuffer
- Added the ability to specify he maxBufferCapacity to
MessageToByteHandler
### Result:


Once a write message that is larger than the capacity of the
MessageToByteHandler's maxBufferCapacity, it clamps the byteBuffer down.

---------

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Franz Busch <f.busch@apple.com>
Co-authored-by: Ali Ali <ali.ali@qantas.com.au>
2024-09-18 10:12:03 +00:00
Rick Newton-Rogers 282f5935cf Adopt NIOThrowingAsyncSequenceProducer (#2879)
### Motivation:

Adopt `NIOThrowingAsyncSequenceProducer` in NIOFileSystem to reduce code
duplication.

### Modifications:

Adopt `NIOThrowingAsyncSequenceProducer` in NIOFileSystem
`DirectoryEntryProducer` and `FileChunkProducer`

### Result:

No functional changes. Internal changes reduce code duplication.
2024-09-13 14:21:23 +01:00
Rick Newton-Rogers 530aa8d304 NIOSingleStepByteToMessageDecoder reentrancy safety (#2881)
### Motivation:

`NIOSingleStepByteToMessageDecoder` calls out part way through its
processing step to a user-provided closure which can cause re-entrant
behavior which violates the assumption made in the code that if the
buffer is non-empty at the start that will be true later in the method.

### Modifications:

`NIOSingleStepByteToMessageDecoder` no longer assumes a non-empty buffer
in its final phase of buffer management.

Further changes to protect against re-entrancy shouldn't be necessary
because the outside call to `messageReceiver` is the only one which is
permitted to be re-entrant (`decode` and `decodeLast` are not).

### Result:

`NIOSingleStepByteToMessageDecoder` can handle re-entrant processing
calls.
2024-09-13 11:43:44 +01:00
Max DesiatovandFranz Busch 730713e47f Add support for WASILibc (#2671)
Dispatch is not supported on WASI, and only Unix domain sockets are
supported, which means we have to exclude those APIs on this platform.

There's work in progress to enable tests for this on CI, but nothing I
can provide for this PR at the current moment.

---------

Co-authored-by: Franz Busch <f.busch@apple.com>
2024-09-12 13:18:25 +01:00
David NadobaandFranz Busch d2713abce5 Make ByteBuffer.debugDescription suitable for structural display (#2495)
### Motivation

`CustomDebugStringConvertible `/`debugDescription` name and
documentation is confusing and should be changed but it is today
expected to be suitable to be used as part of a structured display e.g.
to be printed as part of an `Array`s description, a `struct` or `enum`
with associated values. Therefore it should have no unpaired
parentheses, no unescaped quotes, no top-level commas and no new lines.

### Modifications
let `debugDescription` simply contain the same contents as
`description`. We can't remove the property or the conformance without
breaking API.

### Results
`ByteBuffer` has a proper string representation suitable for being
displayed in an `Array`, as the property of a `struct` or an associated
value of an `enum`.

We can add a new property/method once #2475 landed e.g.
```swift
extension ByteBuffer {
    struct PrintFormat {
        static let hex: Self
        static let decimal: Self
        ...
    }
    func descriptionWithContents(format: PrintFormat = .hex, maxBytes: Int = 1024) {
        ...
    }
}
```

Co-authored-by: Franz Busch <f.busch@apple.com>
2024-09-09 14:33:34 +00:00
Ali Ali 216975d27b Make FileChunks Sendable (#2871)
Motivation:

`FileChunks` is an `AsyncSequence` so should be `Sendable` otherwise
it's difficult to use.

Modifications:

- Conform `FileChunks` to `Sendable`

Result:

- Resolves https://github.com/apple/swift-nio/issues/2752
2024-09-09 10:23:34 +00:00
Mirza UčanbarlićandFranz Busch 06ff6e8c84 Improving description and adding debugDescription to NIOAny (#2866)
Improving `description` and adding `debugDescription` to `NIOAny`

### Motivation
As per:
https://github.com/apple/swift-nio/pull/2864#discussion_r1742192300 we
would like that the `description` of `NIOAny` prints the type of the
underlaying value that it wraps.

### Modification: 
Changing `description` and adding a conformance to
`CustomDebugStringConvertible`.

### Result:
A nicer `description` and `debugDescription` for `NIOAny`.

Co-authored-by: Franz Busch <f.busch@apple.com>
2024-09-09 10:05:51 +00:00
Mirza UčanbarlićandFranz Busch 74f7b1e675 Adding a nicer description for WebSocketFrame. (#2862)
### Motivation:

Resolving the following issue:
https://github.com/apple/swift-nio/issues/2828

### Modifications:

Making `WebSocketFrame` conform to `CustomStringConvertible`.

### Result:

A nicer description for `WebSocketFrame`.

---------

Co-authored-by: Franz Busch <f.busch@apple.com>
2024-09-04 11:06:54 +00:00
Mirza UčanbarlićandFranz Busch 3615f9cfa0 Making ByteBuffer's description more useful (#2864)
### Motivation:

Resolving the following issue:
https://github.com/apple/swift-nio/issues/2863

### Modifications:

Rewrote `description` and `debugDescription` on `ByteBuffer` to make it
more useful. Also fixed a bug in the in `hexDumpCompact`.

### Result:

A more useful `description` and `debugDescription`.

---------

Co-authored-by: Franz Busch <f.busch@apple.com>
2024-09-04 08:07:14 +00:00
Fabian Fett 9746cf80e2 Make assumeIsolated work with SerialExecutors that are backed by EventLoops (#2865)
Allow usage of `assumeIsolated` in SerialExecutors that are backed by
EventLoops.

### Motivation:

We want to support all new Swift 6 features in SerialExecutors.

### Modifications:

- Implement `isSameExclusiveExecutionContext`
- Implement `checkIsolated`

### Result:

We can use `assumeIsolated` in actors that use an `EventLoop` as their
`SerialExecutor`.
2024-09-03 14:41:34 +00:00
196928d0ce Add .compact format to ByteBuffer's hexdump method (#2856)
Add compact formatting option to ByteBuffer's hexdump method.

### Motivation:

Resolving the following issue:
https://github.com/apple/swift-nio/issues/2825.

### Modifications:

• Added a compact format for ByteBuffer's hexdump method

### Result:

A new format which is analog to the `.plain` but without whitespaces.

---------

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Si Beaumont <beaumont@apple.com>
2024-09-03 09:13:03 +00:00
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