Commit Graph
2945 Commits
Author SHA1 Message Date
Rick Newton-RogersandCory Benfield bee38dffe9 A DatagramChannelTest now waits for writes (#2905)
### Motivation:

In
`DatagramChannelTests.testChannelCanReportWritableBufferedBytesWithDataLargerThanSendBuffer`
we assert that there are no buffered writable bytes immediately after a
flush, however in some cases tests fail as this is not true.

We suspect that this is because in some situations the kernel can be
slow to drain the write buffer leading to racey behavior.

### Modifications:

Wait for writes to complete before asserting that the buffer is emptied.

### Result:

Tests should be more deterministic.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-10-04 10:34:07 +00:00
Si Beaumont ea78d5aadc Add EventLoop APIs for simpler scheduling of callbacks (#2759)
## Motivation

The current `scheduleTask` APIs make use of _both_ callbacks and
promises, which leads to confusing semantics. For example, on
cancellation, users are notified in two ways: once via the promise and
once via the callback. Additionally the way the API is structured
results in unavoidable allocations—for the closures and the
promise—which could be avoided if we structured the API differently.

## Modifications

This PR introduces new protocol requirements on `EventLoop`:

```swift
protocol EventLoop {
    // ...
    @discardableResult
    func scheduleCallback(at deadline: NIODeadline, handler: some NIOScheduledCallbackHandler) throws -> NIOScheduledCallback

    @discardableResult
    func scheduleCallback(in amount: TimeAmount, handler: some NIOScheduledCallbackHandler) throws -> NIOScheduledCallback

    func cancelScheduledCallback(_ scheduledCallback: NIOScheduledCallback)
}
```

Default implementations have been provided that call through to
`EventLoop.scheduleTask(in:_:)` to not break existing `EventLoop`
implementations, although this implementation will be (at least) as slow
as using `scheduleTask(in:_:)` directly.

The API is structured to allow for `EventLoop` implementations to
provide a custom implementation, as an optimization point and this PR
provides a custom implementation for `SelectableEventLoop`, so that
`MultiThreadedEventLoopGroup` can benefit from a faster implementation.

Finally, this PR adds benchmarks to measure the performance of setting a
simple timer using both `scheduleTask(in:_:)` and
`scheduleCallback(in:_:)` APIs using a `MultiThreadedEventLoopGroup`.

## Result

A simpler and more coherent API surface.

There is also a small performance benefit for heavy users of this API,
e.g. protocols that make extensive use of timers: when using MTELG to
repeatedly set a timer with the same handler, switching from
`scheduleTask(in:_:)` to `scheduleCallback(in:_:)` reduces almost all
allocations (and amortizes to zero allocations) and is ~twice as fast.

```
MTELG.scheduleCallback(in:_:)
╒═══════════════════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╕
│ Metric                │      p0 │     p25 │     p50 │     p75 │     p90 │     p99 │    p100 │ Samples │
╞═══════════════════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╡
│ Malloc (total) *      │       0 │       0 │       0 │       0 │       0 │       0 │       0 │    1109 │
╘═══════════════════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╛

MTELG.scheduleTask(in:_:)
╒═══════════════════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╕
│ Metric                │      p0 │     p25 │     p50 │     p75 │     p90 │     p99 │    p100 │ Samples │
╞═══════════════════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╡
│ Malloc (total) *      │       4 │       4 │       4 │       4 │       4 │       4 │       4 │     576 │
╘═══════════════════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╛
```
2024-10-03 20:14:28 +00:00
Rick Newton-Rogers 665206000b ConditionLock deallocs its pthread_cond_t in more cases (#2901)
### Motivation:

Recently we changed the init and deinit behavior of `ConditionLock`, at
that time the `UnsafeMutablePointer` allocation of the held
`pthread_cond_t` was put behind a conditional compiler and runtime
check. The deallocation of the same object was also put behind a
conditional, however the conditions were mismatched leading to a leak on
some platforms. Notably this surfaced when `wait`ing on an event loop
future.

### Modifications:

`ConditionLock.deinit` now deallocs the held `pthread_cond_t` under the
same conditions in which it allocs it.

### Result:

Creating a `ConditionLock` no longer leaks memory.
2.74.0
2024-10-02 14:21:48 +01:00
hamzahrmalik fb87d5e49e Add functions for reading and writing length-prefixed data with customizable encodings for the length (#2867)
Add functions for reading and writing length-prefixed data with
customizable encodings for the length, particularly for quic
variable-length integers (RFC 9000)

### Motivation:

Many protocols require us to write data and then prefix that data with
its length. But each protocol has a different way of encoding the
length. This PR introduces general purpose functions which can be
extended for different encoding strategies

### Modifications:

Create a new protocol which defines how to encode an integer
Implement this protocol for QUIC

Provide functions on bytebuffer for writing length-prefixed buffers,
strings or bytes
2024-10-02 09:54:42 +00:00
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>
2.73.0
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
Franz Busch 15618e1e7c [CI] Fix pull request label workflow (#2885)
The workflow was hard coded to use `apple/swift-nio`. If we want to
adopt this in other repos we need to extract the event from the github
context.
2024-09-23 10:58:39 +00: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
Si BeaumontandFranz Busch 1109474e9d ci: Refer to nested reusable workflows using remote variant (#2884)
### Motivation:

This repo contains reusable workflows, intended for use in _other_
repos. Right now, some of these reusable workflows are nested, i.e. some
of the YAML files refer to other YAML files in the repo by a relative
path.

Unfortunately, this makes them currently unusable locally with `act`
because of https://github.com/nektos/act/issues/1875.

For now, it appears the only workaround is to have these referred to
without the local, relative path.

### Modifications:

Use the remote syntax for referencing nested workflows.

### Result:

Commands like `act -j unit-tests` will work in repos that aren't NIO
itself.

---------

Co-authored-by: Franz Busch <privat@franz-busch.de>
2024-09-20 14:32:49 +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
Si Beaumont c9781cf7da ci: Use ${GITHUB_BASE_REF} as treeish for checking API break (#2883)
### Motivation:

This repo is providing a reusable workflow for checking API breaks but
it has two shortcomings:

1. It presumes the target branch name for the PR to be `main`.
2. It presumes the remote is named `origin`.

(2) is always the case in CI, but isn't always locally. My remote is
named `upstream` so cannot run this using `act`. (1) is worse, because
it's not actually testing against the target branch of the PR—consider
if someone was enabling this reusable workflow on a feature branch or
other-named branch.

Fortunately, Github Actions makes the target ref of the pull request
available in the `GITHUB_BASE_REF` environment variable[^0].

### Modifications:

Use `GITHUB_BASE_REF` as the argument to `swift package
diagnose-api-breaking-changes`.

### Result:

This can now be run locally.

[^0]:
https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables#default-environment-variables
2024-09-16 16:54:59 +02:00
Si Beaumont 1851ae6e7d ci: Install shellcheck if not present in CI runner (#2882)
### Motivation:

We want to be able to run the soundness checks locally, and our current
guidance for this is to use `act`. However, there is a documented[^0]
difference in the runner images it uses and those used by Github Actions
proper. One such difference is a lack of `shellcheck` in both the small
and medium runners, which _is_ present in Github's image for the
`ubuntu-latest` platform.

### Modifications:

There are official images for `shellcheck`: both a single binary and an
alpine-based image, which are very small. Neither of these has `bash`,
nor `git`, which are dependencies of the script.

This PR updates the workflow to use a container for this job and uses
the same image used in some other jobs, along with a step to install
`shellcheck`, which is in keeping with what we do for other jobs in the
soundness workflow already to e.g. install `yq`.

### Result:

Can run the soundness job locally using `act`. No change in CI.

[^0]:
https://nektosact.com/usage/runners.html#default-runners-are-intentionally-incomplete
2024-09-16 11:46:54 +02: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
Si Beaumont a26c6dc55c Speculative fix for flakey AsyncTestingEventLoop test (#2873)
### Motivation:

We're seeing some very rare failures from this test in CI runs but I
cannot reproduce locally. The test relies on timing to some degree and
the interaction of scheduling tasks at shutdown.

### Modifications:

The `AsyncTestingEventLoop` has an `executeInContext` function which
puts the closure on the backing dispatch queue and blocks. In this
instance it might be a good way to make sure that all the previous work
has happened.

### Result:

(Hopefully) less flakey test.
2024-09-09 19:07:17 +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
LamTrinh.Dev 393eb06b4d Correct the link of sswg-security at SECURITY.md (#2872)
### Motivation:
Correct the link of sswg-security at SECURITY.md. Currently it is
showing "Not Found".

### Modifications:
+
https://github.com/swift-server/sswg/blob/main/process/incubation.md#security-best-practices
=> https://www.swift.org/sswg/security/

### Result:
Correct the link of sswg-security
2024-09-09 09:38:05 +00:00
Gus Cairo 5d26ac6a04 Include nanoseconds in assertion of timestamp for NIOFileSystem tests (#2869)
Two NIOFileSystem tests are still a bit flaky after (mostly) fixing them
in https://github.com/apple/swift-nio/pull/2842.

```
Test Case 'FileHandleTests.testSetLastAccessAndLastDataModificationTimesToNil' started at 2024-09-06 10:12:54.006
/__w/swift-nio/swift-nio/Tests/NIOFileSystemIntegrationTests/FileHandleTests.swift:1265: error: FileHandleTests.testSetLastAccessAndLastDataModificationTimesToNil : XCTAssertEqual failed: ("1725617573.0") is not equal to ("1725617574.006952") +/- ("1.0") -
Test Case 'FileHandleTests.testSetLastAccessAndLastDataModificationTimesToNil' failed (0.001 seconds)
```

This is because we were dropping the nanoseconds when comparing the
timestamps, which means that sometimes the two timestamps were off by
just over a second. This change includes the nanoseconds to avoid this
problem.
2024-09-06 16:14:43 +00:00
Franz Busch aa5c72f80c [CI] License header support .in and .cmake files (#2870)
# Motivation

Some of repos have `.in` and `.cmake` files including header license
comments.

# Modification

This PR adds support to the license check for those type of files.

# Result

Even more license headers.
2024-09-06 14:41:13 +00:00
Franz Busch ff9492cbbf [CI] Run tests on push to main (#2868)
# Motivation

We want to get green check marks on our commits to main. To do this we
have to run part of our CI jobs when a new commit is pushed.

# Modification

This PR adds a new workflow trigger to run our CI when a commit is
pushed to the main branch.

# Result

Green checkmarks on our commits.
2024-09-06 13:51:29 +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`.
2.72.0
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 30df8551f4 Update release.yml (#2850) 2.71.0 2024-09-02 12:32:16 +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
Franz Busch 76f39c1cdb [CI] Make container images configurable in soundness and matrix jobs … (#2851)
…and remove docc plugin

# Motivation

Some repositories might want to run their soundness and matrix jobs
checks on different container images e.g. a repo might build against the
nightly toolchains only so their soundness jobs should also use nightly
images. Other repos might want to build against a different linux
distribution since their usual deployment target is not Ubuntu based.

Additionally, we currently require our repos to depend on the docc
plugin for building documentation which adds an unnecessary dependency
to all of our packages.

# Modification

This PR makes the container images for the soundness and matrix jobs
configurable. Furthermore, it modifies the docs check script to add the
docc-plugin dependency and removes the current dependency from our
manifest.

# Result

Our workflows can be adopted by more repositories.
2024-08-29 09:15:58 +01: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 0851091621 Pin DocC to below 1.4 (#2854)
Motivation:

Unfortunately, the DocC plugin no longer builds on 5.8:
https://github.com/swiftlang/swift-docc-plugin/issues/94. We need to
keep building.

Modifications:

- Forcefully pin the DocC plugin down.

Result:

CI works now.
2024-08-28 16:05:06 +00:00
Franz Busch 65db2dbfcb [CI] Mark the workspace as safe for the matrix job (#2848)
# Motivation

Some scripts that run as part of a matrix job may want to call git
commands and the workspace needs to be marked as safe.

# Modification

This PR adds a step to mark the workspace as safe
2024-08-20 09:50:03 +01:00
Franz Busch 837a1ddf57 [CI] Don't persist git credentials in CI (#2847)
# Motivation


https://yossarian.net/til/post/actions-checkout-can-leak-github-credentials
shows a common way to leak git credentials in CI. While we are not
publishing artifacts right now, we can harden our security here by
disabling the persistence of git credentials as much as possible.

# Modification

Don't persist git credentials when not needed.

# Result

Less likely to leak credentials.
2024-08-19 18:42:23 +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
Franz Busch e59009da9b Align benchmark scaling and minimum samples (#2839)
# Motivation

We want to have an aligned strategy across all of our benchmarks in how
we use the scaling factor and samples.

# Modification

This PR makes sure that any inner loop is scaled by the scaling factor.
Moreover, we want to run more than 1 iteration. To do this we set an
almost infinite maximum duration and a maximum iteration count.

# Result

More consistent benchmarks
2024-08-15 09:51:52 +00:00
George Barnett 286834dff9 Improve testTasksScheduledDuringShutdownAreAutomaticallyCancelled (#2843)
Motivation:


NIOAsyncTestingEventLoopTests.testTasksScheduledDuringShutdownAreAutomaticallyCancelled
is flaky.

The recursivesly schedules tasks to run on the event loop and then,
after a small pause, shuts down the event loop. It then asserts that
more then 1 task was scheduled (i.e. at least 1 recursive task was run).
This assertion occasionally fails as exactly 1 task was run.

I haven't been able to reproduce this locally but I believe the root of
the flakiness is that the child tasks to shutdown the loop and advance
the time (to trigger the recursive scheduling) can race. If the shutdown
wins then only the root task will run.

Modifications:

- Remove the array of scheduled tasks, it wasn't being used
- Fix atomic ordering
- Increase sleep time before shutting down
- Advance time in the task group rather than a child task

Result:

Less flaky test (hopefully)
2024-08-14 13:08:54 +01:00
Gustavo Cairo e0deef8db0 Fix NIOFileSystem flaky tests (#2842) 2024-08-13 15:09:40 +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 4ef9ce3c6c Strict concurrency the early tests (#2840)
Motivation:

I've moved three targets to strict concurrency mode, now we should move
their tests.

Modifications:

Mostly nothing. Some minor tweaks to the concurrency helpers tests for
their deprecated function.

Result:

A rising tide lifts all targets.
2024-08-12 17:57:52 +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
George Barnett ce524be1b9 Fix text availability (#2836)
Motivation:

022ee1328b uses `Task.sleep(for:)` which isn't available in older SDKs.

Modifications:

- Use `Task.sleep(nanoseconds:)`

Result:

Tests compile with older SDKs
2024-08-09 15:53:11 +00: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
Franz Busch 4e090a37fb Add .editorconfig file (#2829)
# Motivation

[EditorConfig](https://editorconfig.org) helps maintain consistent
coding styles for multiple developers working on the same project across
various editors and IDEs. It will be helpful to add one of these files
to swift-testing so that all contributors use the whitespace conventions
described in our [style
guide](https://github.com/swiftlang/swift-testing/blob/main/Documentation/StyleGuide.md)
automatically when using a supported IDE/editor.

Note that Xcode 16 Beta has added support for EditorConfig files — see
20796230 in the [release
notes](https://developer.apple.com/documentation/xcode-release-notes/xcode-16-release-notes).

# Modification

This PR adds the `.editorconfig` file.

# Result

Easier to maintain a consistent style
2024-08-08 12:43:37 +00:00
Franz Busch 80af56f805 Update the triggers for the Semantic Version label check (#2833)
# Motivation

The checks get cleared when the PR state changes however we weren't
re-running the label workflow.

# Modification

This PR modifiers the triggers for the label workflow to also run on the
triggers when the other workflow runs

# Result

Always correct label checks
2024-08-08 12:15:11 +00:00