Commit Graph
2030 Commits
Author SHA1 Message Date
Rick Newton-Rogers ddbb053756 formatting 2025-04-11 12:01:15 +01:00
Rick Newton-Rogers 828a1130b1 Merge branch 'main' into queue_outbound_close 2025-04-11 09:29:11 +01:00
Rick Newton-Rogers e60b390aab PendingWritesManager returns close promise 2025-04-11 09:28:57 +01:00
Raghav Roy 8440498328 Add More Peek API Variants for ByteBuffer (#3174)
### Motivation:

Existing get APIs require passing an explicit index and can be misused,
leading to verbose and error-prone code. Adding peek variants that
automatically use the current readerIndex improves safety and clarity.
This aims to address issue #2034 and issue #2736, and is a continuation
of PR #3157

### Modifications:

Introduced peekSlice(), peekLengthPrefixedSlice(), peekData(),
peekUUIDBytes() and peekWebSocketErrorCode().
Added tests for each peek API covering normal, empty and repeated peek
scenarios.

### Result:

Developers can now use nonmutating peek APIs to inspect ByteBuffer
contents without altering the reader index.
2025-04-10 14:44:53 +00:00
Raghav RoyandCory Benfield 12d8a4c6d7 Add Peek API for Multiple Integers (#3175)
### Motivation:

The current readMultipleIntegers methods are used to consume multiple
integer values at once, but lack an equivalent nonmutating API. This can
lead to unnecessary complexity when users want to inspect values without
advancing readerIndex. THis patch introduces peekMultipleIntegers which
uses the current readerIndex, improving safety. This extends previous
work on peek methods (issue #2034, issue #2736).

### Modifications:

Updated the generation script (.sh file) to produce peekMultipleIntegers
variants for each arity of readMultipleIntegers.
    Added new tests mirroring the existing multi-read/write tests

### Result:

Users can now inspect multiple integer values in a ByteBuffer without
consuming them, enabling safer workflows.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-04-10 10:23:27 +00:00
Rick Newton-Rogers d41ef1ba4f Merge branch 'main' into queue_outbound_close 2025-04-10 06:18:00 +01:00
George BarnettandCory Benfield 69e8d39aa4 Expose the event loop from the loop bound boxes (#3179)
Motivation:

NIOLoopBound and NIOLoopBoundBox both have a public-but-underscored
event loop property, i.e. the loop to which the value is bound. It's
often very helpful to be able to access the event loop the value is
isolated to. Having access allows you to execute onto the event loop and
safely access the value.

Modifications:

- Make the property public and add a deprecated shim for the
public-but-underscored variant.

Result:

Can access the event loop of a loop bound value

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-04-09 13:47:34 +00:00
Marc Prud'hommeaux c626de9f4d Ignore return value of signal() on Android (#3181)
Fixes https://github.com/apple/swift-nio/issues/3180 by ignoring return
value of signal() on Android
2025-04-08 12:52:04 +00:00
George Barnett 4b7854daaa Strict concurrency for NIOPerformanceTester and NIOCrashTester (#3167) 2025-04-07 14:10:48 +00:00
Rick Newton-Rogers 92fa8204c4 Merge branch 'main' into queue_outbound_close 2025-04-02 13:58:53 +01:00
Rick Newton-Rogers e4395376d6 review comments 2025-04-02 10:23:48 +01:00
George Barnett 195bca151e Strict concurrency for websocket client/server demo and async demo (#3161) 2025-04-01 16:39:33 +00:00
Rick Newton-Rogers 32b232af17 review comments 2025-03-31 15:33:24 +01:00
Rick Newton-Rogers 081a205669 Merge branch 'main' into queue_outbound_close 2025-03-31 15:30:26 +01:00
Rick Newton-Rogers 1f0cf18b12 formatting 2025-03-31 15:30:15 +01:00
Rick Newton-Rogers 68397e0455 review comments 2025-03-31 13:53:20 +01:00
Raghav Roy 1d7a94655f Add Peek API variants for ByteBuffer (#3160)
### Motivation:
Existing get APIs require passing an explicit index and can be misused,
leading to verbose and error-prone code. Adding peek variants that
automatically use the current readerIndex improves safety and clarity.
This aims to address https://github.com/apple/swift-nio/issues/2034 and
https://github.com/apple/swift-nio/issues/2736, and is a continuation of
PR https://github.com/apple/swift-nio/pull/3157

### Modifications:
- Introduced peekBytes(), peekString(), peekNullTerminatedString(),
peekUTF8ValidatedString() and peekDispatchData().
- Added tests for each peek API covering normal, empty, repeated, and
partial read scenarios.

### Result:
Developers can now use nonmutating peek APIs to inspect ByteBuffer
contents without altering the reader index.

***PS**: I have focussed on the ByteBuffer-aux get\* implementations, so
I'm not sure if I am missing any other important/error-prone get\*
elsewhere, if so, please point me to them and I'll be happy to add
respective peek\*'s!*
2025-03-31 10:30:37 +01:00
Raghav RoyandGeorge Barnett e8260eb721 Add peekInteger API to ByteBuffer (#3157)
### Motivation:

The existing getInteger API is often used incorrectly, leading to
verbose or error-prone code as mentioned in
https://github.com/apple/swift-nio/issues/2034 and
https://github.com/apple/swift-nio/issues/2736. Users may
unintentionally access data without correctly managing the reader index.
To address this, I added a peekInteger API that reads integers using the
current readerIndex without modifying it.

### Modifications:

* Added a peekInteger method to ByteBuffer, which provides a nonmutating
way to read integers using the current readerIndex.
* Implemented peekInteger using the existing getInteger function.
* Added comprehensive unit tests to validate correct behavior, including
scenarios for different integer types, insufficient bytes, and
multi-write scenarios.

### Result:

* Users now have access to a safer API for inspecting integers in a
buffer without modifying state.
* Added tests for integer reading scenarios.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-03-27 09:54:07 +00:00
scottmarchantandScott Marchant 320fe4c406 fix: Fix NIOCore build for wasm targets (#3156)
Fixes NIOCore compiler errors for the `wasm32` architecture.

### Motivation:

When compiling NIOCore for a SwiftWasm target, several compilation
errors such as the following occur:

```
> swift build --swift-sdk wasm32-unknown-wasi --target NIOCore

.../swift-nio/Sources/NIOCore/FileHandle.swift:151:42: error: cannot find type 'TwoUInt32s' in scope
149 | public final class NIOFileHandle: FileDescriptor & Sendable {
150 |     private static let descriptorClosed: CInt = CInt.min
151 |     private let descriptor: UnsafeAtomic<TwoUInt32s>
    |                                          `- error: cannot find type 'TwoUInt32s' in scope
152 | 
153 |     public var isOpen: Bool {
.../swift-nio/Sources/NIOCore/FileHandle.swift:77:8: error: Unknown architecture
 75 | typealias TwoUInt32s = DoubleWord
 76 | #else
 77 | #error("Unknown architecture")
    |        `- error: Unknown architecture
 78 | #endif
 79 | 
 
…
```
The compilation errors were introduced with the following change: 


https://github.com/apple/swift-nio/pull/2598/files#diff-a041d0c0d50a8f4fcda2020eeb4450ea994920ef61653cc06014457ccdb3ba0cR70

### Modifications:

The fix is straight-forward and unlikely to affect any existing
compilation targets other than the `wasm32` target.

We simply need to add `arch(wasm32)` to compiler architecture condtions
for a new typedef on line, then NIOCore compiles to wasm32 again.

### Result:

Before: NIOCore wasm build fails ❌ 

After: NIOCore wasm build succeeds ✅

Co-authored-by: Scott Marchant <scottm@passivelogic.com>
2025-03-27 09:28:30 +00:00
Rafael CepedaandFranz Busch 050158c75a Changed NIOAsyncChannel.executeThenClose to accept actor-isolated parameter (#3121)
Improve usability of NIOAsyncChannel.executeThenClose function from an
Actor

### Motivation:

When calling executeThenClose from inside an actor, the closure which we
pass is not isolated to the same actor
This makes it hard to use

e.g. the following code won’t compile on Swift 6 because the closure is
`self-isolated` so can’t be passed

```
await withDiscardingTaskGroup { group in
            do {
                try await serverChannel.executeThenClose { inboundStream, _ in
                    try await self.handleInboundStream(inboundStream: inboundStream, group: &group)
                }
             } catch {}
}
```

Making the closure as @Sendable allows it to be passed, but then we
can’t access `group` anymore

### Modifications:

Added actor isolation parameter to the `executeThenClose` function. 

### Result:

`executeThenClose` will be able to be asynchronously called from inside
an Actor, as it will now be part of the Actor's isolation domain.

---------

Co-authored-by: Franz Busch <privat@franz-busch.de>
2025-03-25 13:31:39 +00:00
Johannes Weiss 40ee44c6b9 always @preconcurrency import Glibc/Musl/Android/Bionic/WASILibc (#3153)
### Motivation:

The non-`Darwin` libcs don't have the correct concurrency annotations.
But due to these Swift bugs, it's important that the _first_ importer
uses `@preconcurrency`:

- https://github.com/swiftlang/swift/issues/79414
- https://github.com/swiftlang/swift/issues/77866

### Modifications:

Much like the Foundation (& corelibs) PRs such as
https://github.com/swiftlang/swift-foundation/pull/1175 , use
`@preconcurrency import` for the non-`Darwin` libcs.

### Result:

Fewer bad warnings/errors in user code.
2025-03-21 15:35:05 +00:00
Rick Newton-Rogers 0e6ee4025e Merge branch 'main' into queue_outbound_close 2025-03-21 15:29:36 +00:00
Rick Newton-Rogers 716fc4767b formatting 2025-03-21 15:27:48 +00:00
Rick Newton-Rogers f762b29df4 DatagramWritesManager only supports full closure 2025-03-21 13:34:28 +00:00
Rick Newton-Rogers 2603614439 reverting unrelated changes 2025-03-21 11:22:45 +00:00
Rick Newton-Rogers 94f957387a use state machine instead of promise 2025-03-21 10:57:14 +00:00
George Barnett 6b00972ad9 Add make*Future methods to isolated event loop (#3152)
Motivation:

Creating a completed future of a non-sendable value when on the current
event loop is currently a little tedious. It requires you to create a
promise, succeed it using the isolated view, or fail it using the
non-isolated view. This is more tedious than it needs to be.

Modifications:

- Add `make{Succeeded,Failed,Completed}Future` methods to the isolated
event loop. These don't require the `Success` value to be `Sendable`.

Result:

It's easier to create completed futures of non sendable values from an
isolated event loop.
2025-03-20 16:00:04 +00:00
Rick Newton-Rogers a9d94041b1 BaseStreamSocketChannel half-close allows outstanding writes to complete
Motivation:

At the moment half-closes are actioned immediately and fails all outstanding writes.
We should refuse new writes but allow these writes to complete before
completing the close.

Modifications:

Modify the PendingWritesManager internal buffer to hold an enum of
either writes or close events. We use this to store the close and only
action it when the preceding writes have been handled.

Result:

Outbound close should no longer fail outstanding writes
2025-03-18 16:32:46 +00:00
hamzahrmalikandCory Benfield 69b63df3d9 Allow NIOLoopBoundBox to be initialized by sending in a value (#3138)
Allow NIOLoopBoundBox to be initialized by sending in a value
### Motivation:

It should be possible to initialize a loopbound box off-loop if the
initial value of the box is being moved onto the loop.

### Modifications:

Add another static function, to create a loopboundbox by `sending` a
value. This is safe because the compiler will not let the caller use the
value after putting it into the box. Only the box (or rather, the el
which the box is bound to) will be able to access the value thereafter.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-03-11 17:08:49 +00:00
Rick Newton-Rogers be266a94ed Downgrade NIOHTTP1TestServer handleChannel failure (#3137)
### Motivation:

We added a fatalError to report NIOHTTP1TestServer handleChannel
failures when doing the strict concurrency work which are now being hit.

We don't know if these failures are actually new or not because the
previous code just swallowed such errors.

### Modifications:

Print the errors but limp-on to see if the test goes on to pass, if so
this might not be a new error.

### Result:

Less severe response to NIOHTTP1TestServer handleChannel failure.
2025-03-10 11:46:44 +00:00
Rick Newton-Rogers 6adf682d16 Enable strict concurrency checking for NIOTestUtils (#3130)
### Motivation:

To ensure `NIOTestUtils` concurrency safety.

### Modifications:

* Enable strict concurrency checking in the package manifest.
* `NIOHTTP1TestServer` does pipeline configuration as synchronous
operations.

### Result:

`NIOTestUtils` does not warn of concurrency issues, builds will warn and
CI will fail if regressions are introduced.
2025-03-07 10:52:08 +00:00
Rick Newton-Rogers 5fe3d44328 Enable strict concurrency checking for NIOWebSocket (#3127)
Enable strict concurrency checking for NIOWebSocket

### Motivation:

To ensure NIOWebSocket concurrency safety.

### Modifications:

* Enable strict concurrency checking in the package manifest.
* `NIOWebSocketClientUpgrader._upgrade` private function generic return
type is marked as `Sendable` in line with the only method which calls
it.
* `NIOWebSocketServerUpgrader._upgrade` private function generic return
type is marked as `Sendable` in line with the only method which calls
it.
* `WebSocketOpcode.allCases` public computed variable is replaced with a
`let` which manually enumerates the cases instead

### Result:

`NIOWebSocket` does not warn of concurrency issues, builds will warn and
CI will fail if regressions are introduced.
2025-03-07 09:34:06 +00:00
Rick Newton-Rogers de47bf8ba5 Enable strict concurrency checking for NIOHTTP1Server (#3132)
### Motivation:

To ensure `NIOHTTP1Server` concurrency safety.

### Modifications:

* Enable strict concurrency checking in the package manifest.
* User synchronous operations in pipeline configurations

### Result:

Builds will warn and CI will fail if regressions are introduced.
2025-03-06 14:58:02 +00:00
Johannes Weiss 3de7a286c0 NIOSingletons docs: Clarify the set once-ness (#3128)
### Motivation:

The docs don't make it clear that the thread count suggestions for the
singletons are:

- set once
- privileged
- need to happen very early on to be effective

### Modifications:

Clarify that.

### Result:

Fewer surprises.
2025-03-05 17:39:05 +00:00
Tim Condon 6c44e2d605 Hashable SocketAddressError (#3119)
Make `SocketAddressError` `Equatable` and `Hashable`. This is useful when running tests
that you expect to throw this error as it allows you to write for
example
```swift
await #expect(throws: SocketAddressError.unknown(host: "127.0.0.1", port: Int.max)) {
    try await app.startup()
}
```
2025-02-23 21:23:06 +00:00
Rick Newton-Rogers 5f60ceeca0 Enable strict concurrency checking for NIOHTTP1 (#3115)
### Motivation:

To ensure NIOHTTP1 concurrency safety.

### Modifications:

* Enable strict concurrency checking in the package manifest.
* Mark several objects `Sendable` with `@preconcurrency` annotations
where they are returned in futures which may execute in arbitrary
concurrency domains.
  * `NIOTypedHTTPClientProtocolUpgrader`
  * `NIOTypedHTTPClientUpgradeConfiguration`
  * `NIOUpgradableHTTPServerPipelineConfiguration`
  * `NIOUpgradableHTTPClientPipelineConfiguration`
  * `NIOTypedHTTPServerProtocolUpgrader`
  * `NIOTypedHTTPServerUpgradeConfiguration`
* Mark handlers as explicitly not sendable
  * `NIOTypedHTTPClientUpgradeHandler`
  * `NIOTypedHTTPServerUpgradeHandler`
* Added new Sendable type aliases:
  * `NIOHTTPClientUpgradeSendableConfiguration`
  * `NIOHTTPServerUpgradeSendableConfiguration`

### Result:

No more concurrency warnings. Builds will warn and CI will fail if
regressions are introduced.
2025-02-19 15:04:51 +00:00
Cory BenfieldandGeorge Barnett f46998ce2d Make isolated execute on async testing eventloop actually run (#3116)
Motivation:

The isolated execute on async testing event loop wouldn't execute tasks
in the case of promise being nil

Modifications:

Rewrite the execute logic slightly.

Result:

Correct execution

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-02-18 19:03:24 +00:00
Rick Newton-Rogers 7789652b83 Add more methods to work with Isolated futures (#3117)
### Motivation:

Whilst working on the NIOHTTP1 strict concurrency work I encountered a
few gaps in the API where I needed isolated analogues of methods on
futures.

### Modifications:

* Add `makeSucceededIsolatedFuture`
* Add a new internal initializer for `EventLoopFuture` which does not
require the value to be Sendable for use in isolated contexts.
* Add a variant of `flatMapError` which can handle closures which return
isolated futures
* Add a `futureResult` computed property which allows us to avoid the
otherwise clumsy `future.nonIsolated().futureResult.assumeIsolated()`

### Result:

More ability to work with isolated futures.
2025-02-14 14:56:06 +00:00
Rick Newton-Rogers c51907a839 Enable strict concurrency checking for NIOTLS (#3112)
### Motivation:

To ensure NIOTLS concurrency safety.

### Modifications:

* Enable strict concurrency checking in the package manifest.
* Require `NegotiationResult` to be `Sendable`
* In `NIOTypedApplicationProtocolNegotiationHandler<NegotiationResult>`
the
result is used to fulfil promises and perform hops so we need it to be
sendable when accessed from these other concurrency domains.

### Result:

Builds will warn and CI will fail if regressions are introduced.
2025-02-07 16:52:40 +00:00
Johannes Weiss 73e83ab73f document known Structured Concurrency violations (#3108)
### Motivation:

Not all NIO APIs, particularly the async-bridge interfaces that use
`.get()` under the hood respect Structured Concurrency. That might be
okay, but it definitely ought to be documented.

Note: `NIOAsyncChannel` does follow Structured Concurrency.

### Modifications:

Annotate known Structured Concurrency violations.

### Result:

Better docs.
2025-02-05 11:12:57 +00:00
Tim CondonandCory Benfield ac79370dee Add ChannelPipeline.SynchronousOperations.Position (#3065)
Adds a new `ChannelPipeline.SynchronousOperations.Position` type to fill
a hole in the API that prevented non-sendable Channel handlers being
added at a position to the pipeline via the synchronous operations.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-02-04 10:31:29 +00:00
Cory Benfield 08b3b4f95e Make _NIOFileSystem strict concurrency compatible (#3098)
Motivation:

We're continuing out Strict Concurrency journey, making sure users of
NIO can write data-race-free code.

Modifications:

- Added some missing Sendable annotations in NIOAsyncSequenceProducer
- Made BufferedStream unconditionally Sendable, and required its Element
type to also be Sendable.

    The prior constraint wasn't actually correct. We always
    behaved as though the element types were Sendable, by passing
    them into continuations. This cleans things up.
- Made AnyAsyncSequence Sendable, which it needs to be.
- Made BufferedOrAnyStream Sendable, which it needs to be.
- Made DirectoryEntries explicitly Sendable, which it was.
- Made DirectoryEntries.Batched explicitly Sendable.

Result:

Better concurrency-safety
2025-02-03 17:56:57 +00:00
Cory BenfieldandRick Newton-Rogers 8f19d80751 Strict concurrency for the chat examples (#3104)
Motivation:

Our next suite of examples for strict concurrency are the chat ones.
These are very similar to the rest: either no violation at all, or just
a need to use the sync operations on pipeline setup.

Modifications:

- Use sync operations
- Lock in strict concurrency checking

Result:

We continue our march.

Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
2025-02-03 16:04:40 +00:00
Cory Benfield 9a181b3aae Update NIOUDPEchoClient for strict concurrency (#3102)
Motivation:

NIOUDPEchoClient should be strict concurrency clean.

Modifications:

Annotate one closure @Sendable to convince Swift it's ok.

Result:

Strict concurrency clean in NIOUDPEchoClient.
2025-02-03 14:22:56 +00:00
Cory Benfield d273f906fe Add strict concurrency to NIOUDPEchoServer (#3101)
Motivation:

Another strict concurrency change, another echo handler.

Modifications:

Move to sync operations.

Result:

Another step on strict concurrency.
2025-02-03 12:56:02 +00:00
Cory BenfieldandGeorge Barnett 8bf3316c37 Clean up concurrency in NIOEchoClient (#3099)
Motivation:

We're getting to the examples now! This patch updates NIOEchoClient to
be clean under strict concurrency.

Modifications:

Use the sync operations to add echo handler.

Result:

Another strict concurrency module.

Co-authored-by: George Barnett <gbarnett@apple.com>
2025-02-03 11:49:56 +00:00
Johannes Weiss dff45738d8 undo Xcode 13 GM workaround (#3092)
### Motivation:

Xcode 13 is really quite old (3 major releases and it was the GM release
anyway) and this workaround can cause other issues.

### Modifications:

- Remove the Xcode 13 GM workaround.
- 
### Result:

Better, possibly faster code.
2025-01-28 20:38:50 +00:00
1e900b4736 NIOFileSystem: Try ${TMPDIR} first for temporary directory (#3067)
### Motivation:

This PR aligns what temp directory NIOFileSystem will return first:
- First try `${TMPDIR}` as it's an expressed user preference
- On Darwin, try `_CS_DARWIN_USER_TMP_DIR` next. If it's set, return
that.
- Finally, fall back on `/tmp` on Darwin and Linux, and
`/data/local/tmp` on Android.

Closes #2861.

### Modifications:

- Reworks `NIOFileSystem.temporaryDirectory`.

### Result:

- NIOFileSystem will now try `${TMPDIR}` first for the temporary
directory.

### Caveats:

- We might want to align how Swift-NIO and FoundationEssentials resolve
temp directory, and [FoundationEssentials have a different
approach](https://github.com/swiftlang/swift-foundation/blob/9d57f36de757b3d5e3a2f7ffcf27aaec3033509f/Sources/FoundationEssentials/String/String%2BPath.swift#L484-L533).
But, I agree with [this
comment](https://github.com/apple/swift-nio/issues/2861#issuecomment-2327010713),
it feels like TMPDIR is an expected default.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: George Barnett <gbarnett@apple.com>
2025-01-27 08:45:46 +00:00
Cory Benfield 26d3fb9097 Make NIOPosix strict-concurrency clean (#3090)
Motivation

NIOPosix should be clean under strict concurrency

Modifications

- Fix newly-added issue in GetaddrinfoResolver
- Fix newly-added issue in SEL
- Lock in the win in Package.swift

Result

We did it!
2025-01-27 08:11:08 +00:00
Cory Benfield 85742bc559 Avoid using stderr explicitly (#3089)
Motivation

It's tempting for us to use the FILE * for stderr whenever we want to
print to it. However, the Linux libc modules aren't appropriately
annotated to call that field constant, and indeed it isn't. This causes
Swift to throw a fit if we even touch it.

Modifications

Introduce an awkward function that issues direct writes to stderr
instead of using the FILE *.

Result

Swift is happier.
2025-01-24 16:33:17 +00:00