Commit Graph
2537 Commits
Author SHA1 Message Date
Franz Busch 4b9cfec93a Fix SemVer major label check (#2970)
(cherry picked from commit 2139438dda)
2024-11-22 09:52:50 +00:00
Cory BenfieldandGeorge Barnett fc5e8460af Backport: Remove sendable checking from NIOLock and NIOLockedValueBox (#2968) (#2992)
Motivation:

ManagedBuffer is marked as explicitly not sendable on Swift nightly
builds. NIOLock and NIOLockedValueBox used a type derived from
ManagedBuffer and must be Sendable. Currently the derived type is marked
as `@unchecked Sendable`. However on nightly toolchains this now
conflicts with being explicitly not Sendable.

Modifications:

- Remove Sendable checking on NIOLock and NIOLockedValueBox

Result:

Fewer warnings

(cherry picked from commit 6d30ec4738)

Co-authored-by: George Barnett <gbarnett@apple.com>
2024-11-22 09:41:38 +00:00
Cory BenfieldandRick Newton-Rogers 653da4d987 Backport: Use Swift 6.0 docs pipeline (#2966) (#2991)
Documentation checking catches more issues in Swift 6.0.

Adopt the Swift 6.0 image and fix the errors.

More accurate docs.

(cherry picked from commit adfd61adc5)

Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
2024-11-22 09:24:33 +00:00
Cory BenfieldandGeorge Barnett 4d5eb6bb15 Backport: Improve docs around running act for formatting (#2965) (#2990)
Motivation:

The contibuting guide gives an incorrect command to run to invoke the
formatting job locally.

Modifications:

- Change the job name to 'soundness'
- Add a note about setting the container architecture

Result:

Better docs

(cherry picked from commit 29490005ab)

Co-authored-by: George Barnett <gbarnett@apple.com>
2024-11-21 17:30:38 +00:00
Cory BenfieldandPhilip Brown 04ef7b4cb3 Fix leaking technique (#2963) (#2989)
Using `Unmanaged.passRetained` is correct and therefore safe under all
compiler optimizations

(cherry picked from commit 3fda9430aa)

Co-authored-by: Philip Brown <122590765+asdf-bro@users.noreply.github.com>
2024-11-21 17:13:40 +00:00
Cory BenfieldandPeter Adams aa098667d3 Backport: Remove unused dockerfiles and allocation limit scripts (#2957) (#2988)
Motivation:

Remove unused clutter

Modifications:

Remove dockerfiles and scripts to update allocation limits.

Result:

Cleaner repo

Co-authored-by: Cory Benfield <lukasa@apple.com>
(cherry picked from commit e25bf7ecfe)

Co-authored-by: Peter Adams <63288215+PeterAdams-A@users.noreply.github.com>
2024-11-21 16:56:30 +00:00
Cory BenfieldandPeter Adams 89b3141037 Correct allocation test script (#2956) (#2986)
Motivation:

Unfortunately the current script has a bug meaning it can never fail.

Modifications:

Change bracketing for output search.

Result:

Allocation tests will flag when failing

(cherry picked from commit e1d0d21391)

Co-authored-by: Peter Adams <63288215+PeterAdams-A@users.noreply.github.com>
2024-11-21 15:32:58 +00:00
Cory BenfieldandAli Ali 62729f845d Backport: Fix broken swift format link (#2948) (#2983)
Trying to fix swift format link in contributions.md

Someone please let me know what the process is for running `swift
format` locally now that the script has been moved out of the repo.

Co-authored-by: Franz Busch <f.busch@apple.com>
(cherry picked from commit 08af85ae4b)

Co-authored-by: Ali Ali <47680736+ali-ahsan-ali@users.noreply.github.com>
2024-11-21 14:23:02 +01:00
Cory BenfieldandJohn Zhou d48b9dd04b Backport: Add new protocol for ChannelHandler to get buffered bytes in the channel handler (#2918) (#2982)
This is a backport of #2918.

Add new protocol to get buffered bytes from `ChannelHandler`s and
`ChannelPipeline` API to query the buffered bytes from `ChannelHandler`s

### Motivation:

In #2849, a new `ChannelOption` is introduced to retrieve the number of
buffered outbound bytes in a `Channel`. However, this solution does not
account for bytes that may be buffered within individual
`ChannelHandler`s. This PR builds on #2849 by adding functionality to
audit buffered bytes residing in `ChannelHandler`s and exposing this
information through new `ChannelPipeline` APIs.

### Modifications:

- Two new protocols for `ChannelHandler` to audit buffered bytes for
inbound and outbound.
    - `NIOOutboundByteBufferingChannelHandler`
    - `NIOInboundByteBufferingChannelHandler`
- New `ChannelPipeline` APIs
    - outboundBufferedBytes()
- outboundBufferedBytes(in: ChannelHandlerContext) (only in
`syncOperations`)
    - inboundBufferedBytes()
- inboundBufferedBytes(in: ChannelHandlerContext) (only in
`syncOperations`)

### Result:

Users can now easily query the amount of bytes buffered in
`ChannelHandler`s using the new `ChannelPipeline` APIs, enhancing the
visibility of `ChannelHandler` performance.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
(cherry picked from commit 935659883e)

Co-authored-by: John Zhou <37914490+johnnzhou@users.noreply.github.com>
2024-11-21 11:14:11 +00:00
Cory BenfieldandRick Newton-Rogers 7bb2d554cc Backport: BaseSocketChannel flushNow IONotificationState changes (#2954) (#2981)
### Motivation:

We could previously hit an assert do to a re-entrancy issue where
channel and buffered write state could change during a call-out leading
to invalid state.

### Modifications:

The decision on whether or not we should be registered for future writes
is now taken after the call outs to `fireChannelWritabilityChanged` and
`fireChannelReadComplete`. The new registration state is set to
`.unregister` if the channel is not open or if there are now flushed
pending writes.

### Result:

Scope for re-entrancy crashes is reduced.

Co-authored-by: Cory Benfield <lukasa@apple.com>
(cherry picked from commit fdc3a31a55)

Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
2024-11-21 10:55:14 +00:00
Franz Busch 02906a6c08 Fix NIOAsyncSequenceProducer watermark strategy. (#2952)
# Motivation

It was currently possible that the producer's delegate is getting called
twice with `produceMore` even if no `yield` returned a `stopProducing`.
This could happen when we expected the producer to yield elements but
the consumer went below the low watermark again. Resulting in two
subsequent calls.

# Modification

This PR stores the current demand state in the strategy which let's us
avoid flipping the `hasOustandingDemand` state of the sequence.

# Result

Correctly, ensured the call order of `produceMore` and `stopProducing`.
2024-10-28 16:14:37 +01:00
Johannes Weiss 1ff5fd585c EmbeddedEventLoop/Channel: check correct thread (#2951)
### Motivation:

`EmbeddedChannel` & `EmbeddedEventLoop` currently violate `Sendable`.
They should store the current thread in `init` and then implement
`inEventLoop` and other functions with a check that the current thread
is correct.
Since NIO 1.0 `Embedded*` were always documented to not be thread-safe
but we should finally police this.

### Modifications:

- Implement the thread check
- For now, just warn (soon hopefully crash)
- Delete EmbeddedScheduledCallbackTests (#2950)

### Result:

- Less Embedded* abuse
- fixes #2949
2024-10-25 08:55:01 +01:00
Ali Ali 9140817010 Issue-2900 - Add VisionOS support (#2947)
Add Vision support

### Motivation:
https://github.com/apple/swift-nio/issues/2900 - close this

### Modifications:
- Bump SystemPackage to 1.4.0 and remove @preconcurrency 
- remove `#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) ||
os(Linux) || os(Android)` to allow for visionOS support
- Remove conditional import for swift system

### Result:

Vision OS support
2.76.1
2024-10-24 10:26:32 +00:00
Peter Adams 062b28eeb0 Checkout any submodules when running Actions (#2946)
Motivation:

Some repos using this as their source of GitHub Actions logic have
submodules.

Modifications:

Change workflows to checkout submodules.

Result:

All CI will work cleanly
2024-10-24 10:38:16 +01:00
Johannes Weiss c4a6cdea3a workaround Xcode 15.4 bug with swift build --arch x86_64 --arch arm64 (#2945)
### Motivation:

`swift build --arch x64_64 --arch arm64` on at least Xcode 15.4 fails
with

```
/Users/johannes/devel/my-proj/.build/checkouts/swift-nio/Sources/NIOCore/NIOScheduledCallback.swift:93:18: error: '_scheduleCallback' has a package access level but no -package-name was specified: /Users/johannes/devel/tfai-swift/.build/checkouts/swift-nio/Sources/NIOCore/NIOScheduledCallback.swift
    package func _scheduleCallback(
                 ^
```

That's clearly an Xcode bug but that needs a workaround.

### Modifications:

- Don't use the `package` modifier for now

### Result:

SwiftNIO builds again.
2024-10-24 08:50:47 +01:00
Johannes Weiss f6230d3708 NIOPosix on Darwin: inherit main thread QoS (#2944)
### Motivation:

On Darwin, QoS (quality of service) of threads plays an important role,
especially on Apple Silicon machines with P-cores and E-cores. If you
spawn raw threads (like NIOPosix) and use a mechanism that doesn't
support QoS propagation (like reading/writing to networks -- like
NIOPosix does), it's recommended to default to the main thread's QoS.

Otherwise you'll always be at the default QoS for "legacy" threads which
means bad latencies, especially on Apple Silicon machines.

In a follow-up PR #2943 we're adding better configurability for thread
configuration.

### Modifications:

Default to main thread QoS on Darwin.

### Result:

Better latencies for applications with higher QoS classes.
2.76.0
2024-10-23 17:14:35 +01:00
Franz Busch be823e6d1e [CI] Fix the Windows 6.0 check name (#2941)
# Motivation

Currently, the Windows 6.0 check name includes the matrix properties.

# Modification

This PR makes it dynamic with the swift version again.

# Result

Aligned CI check names across platforms.
2024-10-23 08:39:34 +00:00
Franz Busch 6d24ab0222 [CI] Enable benchmarks & cxx Windows CI (#2940)
This PR makes it possible to enable benchmarks and cxx interop checks on
Windows. By default they are turned off. This PR also fixes the job of
the Windows 6 pipeline which was broken since single configuration
matrix jobs seem to behave differently.
2024-10-23 09:38:21 +02:00
Franz Busch ecbb5ea78a [CI] Small adjustments to the Windows actions (#2939)
# Motivation

There were two small problems:
1. The CI for the nightlies wasn't properly skipped
2. The name for the matrix wasn't applied in the case where it was
skipped

# Modification

This PR hopefully fixes both issues.
2024-10-22 10:36:48 +01:00
Franz Busch ff6dea9d11 [CI] Add Windows matrix build (#2929)
# Motivation

In the long term we want to add support for Windows in our Swift
packages. To do this we need a CI setup to ensure that our packages are
building and the tests are passing.

# Modification

This PR adds a windows job to our swift matrix that installs Swift on
the runner and then uses Swift PM to build and test the package. Windows
jobs are disabled by default since most of our packages require some
work to add Windows support.

# Result

We have a Windows CI pipeline that allows us to verify that our packages
are working.
2024-10-22 08:53:24 +00:00
Jeff 8666af5d5f Fix Windows build for NIOCore. (#2938)
Fix build failures in `NIOCore` on Windows.

### Motivation:

I'd like it to build on Windows. 

### Modifications:

* Add missing `WinSDK` imports.
* Add missing `#elseif os(Windows)` branch for UDP.

### Result:

```
c:\users\jeff\src\swift-nio> swift build -Xcc -DBYTE_ORDER=LITTLE_ENDIAN --target NIOCore
Building for debugging...
[1/1] Write auxiliary file c:\users\jeff\src\swift-nio\.build\x86_64-unknown-windows-msvc\debug\swift-version--15FA6356563A8EA6.txt
Build of target: 'NIOCore' complete! (1.14s)
```
2024-10-22 07:09:28 +00:00
Cory Benfield 49cd78bb76 Fix withConnectedSocket in async mode (#2937)
Motivation:

The async flavour of withConnectedSocket accidentally type-erased the
channel, which caused it to be unable to be used.

Modifications:

Un-erase the type of the channel.
Add a test.

Result:

withConnectedSocket works again
Resolves #2936
2024-10-21 15:52:31 +01:00
Clinton NkwochaandGeorge Barnett cc1c57c291 Provide APIs to read file into more data types (#2923)
Motivation:

As requested in issues
[#2875](https://github.com/apple/swift-nio/issues/2875) and
[#2876](https://github.com/apple/swift-nio/issues/2876), it would be
convenient to be able to read the contents of a file into more data
types such as `Array`, `ArraySlice` & Foundation's `Data`.

Modifications:

- Extend `Array`, `ArraySlice` & `Data` to be initialisable with the
contents of a file.

Result:

The contents of a file can be read into more data types.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2024-10-21 08:41:10 +00:00
Jeff 8b66b22895 Fix Windows build break. (#2935)
Use `withLockPrimitive` to access the underlying lock.

### Motivation:

The current method of accessing the lock doesn't build.
This fixes bug #2934.

### Modifications:

Access the lock via `withLockPrimitive`.

### Result:

Now it builds! :)
2024-10-19 09:25:51 +00:00
ff98c93fe9 Fix EventLoopFuture and EventLoopPromise under strict concurrency checking (#2654)
# Motivation

We need to tackle the remaining strict concurrency checking related
`Sendable` warnings in NIO. The first place to start is making sure that
`EventLoopFuture` and `EventLoopPromise` are properly annotated.

# Modification

In a previous https://github.com/apple/swift-nio/pull/2496, @weissi
changed the `@unchecked Sendable` conformances of
`EventLoopFuture/Promise` to be conditional on the sendability of the
generic `Value` type. After having looked at all the APIs on the future
and promise types as well as reading the latest Concurrency evolution
proposals, specifically the [Region based
Isolation](https://github.com/apple/swift-evolution/blob/main/proposals/0414-region-based-isolation.md),
I came to the conclusion that the previous `@unchecked Sendable`
annotations were correct. The reasoning for this is:

1. An `EventLoopPromise` and `EventLoopFuture` pair are tied to a
specific `EventLoop`
2. An `EventLoop` represents an isolation region and values tied to its
isolation are not allowed to be shared outside of it unless they are
disconnected from the region
3. The `value` used to succeed a promise often come from outside the
isolation domain of the `EventLoop` hence they must be transferred into
the promise.
4. The isolation region of the event loop is enforced through
`@Sendable` annotations on all closures that receive the value in some
kind of transformation e.g. `map()` or `whenComplete()`
5. Any method on `EventLoopFuture` that combines itself with another
future must require `Sendable` of the other futures `Value` since we
cannot statically enforce that futures are bound to the same event loop
i.e. to the same isolation domain

Due to the above rules, this PR adds back the `@unchecked Sendable`
conformances to both types. Furthermore, this PR revisits every single
method on `EventLoopPromise/Future` and adds missing `Sendable` and
`@Sendable` annotation where necessary to uphold the above rules. A few
important things to call out:

- Since `transferring` is currently not available this PR requires a
`Sendable` conformance for some methods on `EventLoopPromise/Future`
that should rather take a `transffering` argument
- To enable the common case where a value from the same event loop is
used to succeed a promise I added two additional methods that take a
`eventLoopBoundResult` and enforce dynamic isolation checking. We might
have to do this for more methods once we adopt those changes in other
targets/packages.

# Result

After this PR has landed our lowest level building block should be
inline with what the rest of the language enforces in Concurrency. The
`EventLoopFuture.swift` produces no more warnings under strict
concurrency checking on the latest 5.10 snapshots.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-10-18 16:59:17 +01:00
Rick Newton-Rogers 19da487ef2 clean up 5.8 thresholds (#2932)
clean up 5.8 thresholds

### Motivation:

GitHub's merge retained files we don't need now we've dropped 5.8

### Modifications:

remove 5.8 thresholds

### Result:

no unused files
2024-10-17 15:46:55 +02:00
Franz Busch 2fe3d92cf5 Drop support for Swift 5.8 (#2924)
# Motivation

We only support the last three Swift released versions which are at this
time 5.9, 5.10 and 6.

# Modification

This PR drops anything related to Swift 5.8.

# Result

Version support aligned.
2024-10-17 12:22:10 +00:00
Rick Newton-Rogers 06c16b1a26 Add future wait benchmark to catch memory leaks (#2931)
### Motivation:

In the past we introduced a memory leak around the creation of and
waiting on futures - we should protect against leaks in this fundamental
operation.

### Modifications:

Add a new benchmark which would have failed with the previous bug

### Result:

Regression protection for this type of memory leak.
2024-10-17 13:03:52 +01:00
Franz Busch 290b349e2c [CI] Fix python lint (#2925)
# Motivation

Fix the python lint check.

# Modification

This PR fixes all the warnings related to the new python lint check.

# Result

Only green CI.
2024-10-17 09:57:40 +00:00
Rick Newton-Rogers efe445d307 Disable semver label check locally (#2928)
Disable semver-label-check locally when run via `act`.

### Motivation:

This check makes no sense when run locally.

### Modifications:

Disable semver-label-check locally when run via `act`.

### Result:

The label check should no longer run and fail locally.
2024-10-15 13:32:12 +00:00
Rick Newton-Rogers fcdb6c3bf3 Adopt NIOThrowingAsyncSequenceProducer 2nd try (#2917)
### Motivation:

Adopt `NIOThrowingAsyncSequenceProducer` in NIOFileSystem to reduce code
duplication.

### Modifications:

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

This change was previously merged and then backed out due to issues
(#2879). The original change is in the first commit, the second commit
contains additional changes.

In the original adoption of `NIOThrowingAsyncSequenceProducer` the code
did not deal with backpressure being applied very well, in some cases
causes hangs.

A key bug was that it was not protected against re-entrant calls to
`produceMore`. Such calls may happen e.g. when the producer has been
asked to pause producing and then resume again before the initial read
had completed. This resulted in overlapping reads and re-ordered data.

This change introduces a new activity state which is protected by a lock
and keeps track of if we are in the critical section to serialize
access.

`DirectoryEntryProducer` performs most of its logic within a lock and so
doesn't seem to be impacted in the same way.

### Result:

No functional changes. Internal changes reduce code duplication.
2024-10-15 10:14:21 +00:00
Franz Busch c16420c4a7 [CI] Migrate to Swift 6.0 and drop 5.8 (#2920)
# Motivation

Our support strategy includes the last three released Swift versions.
After the recent release of Swift 6 this means we now support 5.9, 5.10
and 6.0.

# Modification

This PR updates our CI configuration and scripts to align with our
supported Swift versions.

# Result

Up to date CI coverage.
2024-10-14 16:07:49 +01:00
Peter Adams f7dc3f5275 Re-add CXX compat check script (#2919)
Motivation:

It's still referenced from CI.

Modifications:

Re-add script removed in a previous commit.

Result:

CXX checks on PRs should work again.
2.75.0
2024-10-14 11:09:35 +01:00
Franz Busch 689e94aac0 [CI] Add back matrix CI script (#2916)
Adds back the matrix CI script which I accidentally deleted in a
previous PR.
2024-10-11 16:24:56 +01:00
Franz Busch 50fd74c66d [CI] Fix unit test yaml file (#2915)
I messed up the indention of the `unit_tests.yml` file in a previous PR.
This fixes it.
2024-10-11 14:51:07 +01:00
Franz Busch 8bcc35d062 [CI] Switch to reusable soundness (#2913)
# Motivation

Switch to the reusable workflows from the swiftlang organization for
soundness.

# Modification

This PR moves over to the new reusable soundness workflow. Additionally,
it also deletes all files in this repo for the soundness checks since
they are no longer needed.
2024-10-11 12:53:16 +01:00
Clinton Nkwocha 17ebfcd99d [NIOFileSystem] Provide an API to specify allowing unlimited sized reads (#2914)
Motivation:

As described in issue
[#2877](https://github.com/apple/swift-nio/issues/2877), there is no API
available to specify allowing a read of unlimited size.

Modifications:

- Add a new `public static` property, `unlimited`, to `ByteCount`
representing an unlimited amount of bytes.
- Adapt
`ReadableFileHandleProtocol.readToEnd(fromAbsoluteOffset:maximumSizeAllowed:)`
to work with `maximumSizeAllowed` being `ByteCount.unlimited`.

Result:

An API to specify allowing a read of an unlimited size will be
available.
2024-10-11 09:25:17 +00:00
Mirza UčanbarlićandFranz Busch f6b8f1f94d Add removeHandler(context: ChannelHandlerContext) to SynchronousOperations of ChannelPipeline (#2912)
### Motivation:

As per https://github.com/apple/swift-nio/issues/2906.

### Modifications:

Added a method to SynchrounousOperations of ChannelPipeline.

### Result:

Now we are able to remove channel handlers by context.

---------

Co-authored-by: Franz Busch <f.busch@apple.com>
2024-10-10 11:50:48 +00:00
Clinton Nkwocha 611fa094dc Throw error when the max read amount is greater than ByteBuffer can tolerate (#2911)
Motivation:

As described in issue
[#2878](https://github.com/apple/swift-nio/issues/2878), NIOFileSystem
crashes when reading more than `ByteBuffer` capacity.

Modifications:

- Add a new static property, `byteBufferCapacity`, to `ByteCount`
representing the maximum amount of bytes that can be written to
`ByteBuffer`.
- Throw a `FileSystemError` in
`ReadableFileHandleProtocol.readToEnd(fromAbsoluteOffset:maximumSizeAllowed:)`
when `maximumSizeAllowed` is more than `ByteCount.byteBufferCapacity`.

Result:

NIOFileSystem will `throw` instead of crashing.
2024-10-10 09:32:50 +00:00
Clinton NkwochaandGeorge Barnett 9ff5fddb3d Add convenience conformances to ByteCount (#2909)
Motivation:

Several arithmetic and comparison operations are done with `ByteCount`
using the `bytes` property. Operating on the `ByteCount` type directly
will be more convenient.

Modifications:

- Add `AdditiveArithmetic` and `Comparable` conformances to `ByteCount`.

Result:

The `ByteCount` type can undergo arithmetic and comparison operations.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2024-10-09 14:22:05 +00:00
Paul LeMarquand b812b1b731 Fix broken link to swift-server performance documentation (#2907) 2024-10-07 13:37:58 +00:00
hamzahrmalik 752abd759c Make ByteBufferQUICBinaryEncodingStrategyTests compatible with 32-bit systems (#2904)
This is a followup to #2867

Some of the literals used in the test cases were too big to fit in an
Int32
This is fine on 64-bit systems, because the literals are considered as
`Int`, which is Int64 on those systems
However, on 32-bit systems, those literals are considered as Int64

Change: Add `as Int64` where needed, to tell the compiler we want these
literals to be treated as Int64, which should allow these tests to run
on 32 bit systems too
2024-10-07 07:18:20 +00:00
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