# Motivation
We were setting `self.sink = nil` in the `NIOAsyncChannelOutboundWriterHandler` twice in the same call stack which is an exclusivity violation. This happens because the first `self.sink = nil` triggers the `didTerminate` delegate call which again triggered `self.sink = nil`.
# Modification
This PR changes the code to only call `self.sink?.finish()` and only sets the `sink` to `nil` in the `didTerminate` implementation. This follows what we do for the inbound handler implementation. I also added a test that triggers this exclusivity violation.
# Result
No more exclusivity violations in our code.
# Motivation
We got reports in https://github.com/apple/swift-nio/issues/2574 that our new typed HTTP upgrader are hitting a Swift compiler bug which manifests in a runtime crash on older iOS/macOS/etc.
# Modification
This PR backs out the new typed HTTP protocol upgrader APIs so that we can unblock our users until the Swift compiler bug is fixed.
# Result
No more crashes for our users.
* Add async version of NIOThreadPool.runIfActive
* Changes from comments in PR
Remove no longer supported code
Add tests for errors being thrown, and the thread pool not being active
* Collapse async runIfActive into one function
* remove whitespace
* Make T Sendable
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Several thread-safety issues were missed in code review. This patch fixes them.
Modifications:
- Removed the use of an unstructured Task, replaced with eventLoop.execute to
ServerHandler's EventLoop.
- Stopped ClientHandler reaching into the benchmark object without any
synchronization, used promises and event loop hops instead.
Result:
Thread safety is back
* Add support for unidirectional `NIOPipeBootstrap`
# Motivation
In some scenarios, it is useful to only have either an input or output side for a `PipeChannel`. This fixes https://github.com/apple/swift-nio/issues/2444.
# Modification
This PR adds new methods to `NIOPipeBootstrap` that make either the input or the output optional. Furthermore, I am intentionally breaking the API for the new async methods since those haven't shipped yet to reflect the same API there.
# Result
It is now possible to bootstrap a `PipeChannel` with either the input or output side closed.
* Docs and naming
* Add support for async VSock bootstrap methods
# Motivation
We are about to release our new async bootstrap methods that retain the type information of the various initializers. While developing those we also added support for VSock in NIO; however, we missed adding support for the async bootstrap methods.
# Modification
This PR adds new async bootstrap methods that take a `VSockAddress` and a test for it.
# Result
Support for async VSock bootstrap.
* Update docs
The rest of the functions on `NonBlockingFileIO` are explicit in the fact that they count buffer length in bytes. `readFileSize` should be explicit in its documentation too.
Motivation:
In nightly Swift, we now need to mark retroactive conformances when
they are intentional. These conformances are safe for us, so we can
safely suppress the warnings.
Modifications:
- Mark NIOFoundationCompat retroactive conformances.
Result:
Nightly builds work again
* Avoid terminating when a precondition is not met in HTTPServerPipelineHandler
* Address review comments
* rename precondition to assertion
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Whilst investigating deadlocking code elsewhere we discovered that
resuming a continuation inside a lock can call deadlocks.
The reason is that
- `withTaskCancellationHandler` takes a sequence's
underlying runtime lock then executes the cancellation handler.
- The task cancellation handler then does work which requires taking the
NIO-level lock
- If a NIO method on a separate thread then takes the NIO-level lock and
within it resumes a continuation e.g. in `yield` we will deadlock
because the resumption attempts to obtain the underlying runtime lock.
Modifications:
Do not resume continuations within locks.
Result:
Fewer deadlock opportunities
# Motivation
Over the past months, we have been working on new async bridges to make using NIO's `Channel` from Swift Concurrency possible. Since this work was far reaching we have opted to land all of it as SPI. Now the time has come and we feel confident enough to make the SPI official API. This comes after testing the new APIs in various scenarios such as HTTP 1&2, HTTP upgrades, protocol negotiation and in benchmarks.
# Modification
This PR removes the SPI from the `NIOAsyncChannel`, the bootstrap methods, protocol negotiation and HTTP upgrade.
# Result
Everyone can use the our new APIs🚀
# Motivation
After playing around more with the new async bootstrap methods, I came to the conclusion that the `NIOProtocolNegotiationResult` isn't carrying its weight. The `NIOProtocolNegotiationResult` is a glorified `EventLoopFuture` with an easy way to recursively resolve nested futures. Furthermore, it forces any nested protocol negotiation to use the same generic type for the end result.
# Modification
This PR removes the `NIOProtocolNegotiationResult` and changes all the tests to be solely based on `EventLoopFuture`s.
# Result
Less code to support the async bootstrap and better composition of nested protocol negotiation handlers.
# Motivation
The latest nightly toolchains have merged the patch that removes `Sendable` conformance from the various `Unsafe*Pointer` APIs. Our `Lock` type was using such a type internally and had a `Sendable` conformance. This conformance was now failing since the pointer was no longer `Sendable`.
# Modification
This PR changes the `Sendable` conformance of `Lock` to `@unchecked Sendable`.
# Result
No more `Sendable` warnings in non-strict mode on nightly toolchains
* Call `NIOAsyncWriterSinkDelegate` outside of the lock
# Motivation
The current `NIOAsyncWriter` implementation expects that the delegate is called while holding the lock to avoid reentrancy issues. However, this prevents us from executing the delegate calls directly on the `EventLoop` if we are on it already.
# Modification
This moves all of the delegate calls outside of the locks and adds protection against reentrancy into the state machine.
# Result
Less allocations.
Clarify the reentrancy problems in docs and protect against them in the writer
* Code review
* Implement fast paths for `AsyncChannelInboundStreamChannelHandler`
* Add `_TinyArray` from `swift-certificates`
* Implement single element customization point in `NIOAsyncChannelOutboundWriterHandler`
* Call the single element optimization more often and store suspended producers in `_TinyArray`.
* Update thresholds
* Fix compiler warning
# Motivation
Currently, the NIO's EventLoop conformance to the `SerialExecutor` protocol always uses `execute` to schedule the actual job. However, the closure for `execute` has to close over the job and the `EventLoop` itself; hence, it always allocates. Since jobs are a very fine grained object in Concurrency that are created a lot this lead to millions of allocations in even small benchmarks.
# Modification
This PR provides a customization point for `EventLoop`s to execute `ExecutorJob`s directly. For `SelectableEventLoop` we store a type erased `UnownedJob` in our `ScheduledTask` and just run it right away.
# Result
No more allocations when NIO's EL is used as a `SerialExecutor`.
* Introduce new typed `HTTPClientUpgrader` and `WebSocketClientUpgrader`
# Motivation
In my previous PR https://github.com/apple/swift-nio/pull/2517, I added a new typed `HTTPServerUpgrader` and corresponding implementation for the `WebSocketServerUpgrader`. The goal of those is to carry type information across HTTP upgrades which allows us to build fully typed pipelines.
# Modification
This PR adds a few things:
1. A new `NIOTypedHttpClientUpgradeHandler` + `NIOTypedHttpClientProtocolUpgrader`. I also moved the state handling to a separate state machine. Similar to the server PR I did not unify the state machine between the newly typed and untyped upgrade handlers since they differ in logic.
2. A new `NIOTypedWebSocketClientUpgrader`
3. An overhauled WebSocket client example.
# Result
This is the last missing piece of dynamic pipeline changing where we did not carry around the type information. After this PR lands, we can finalize the `AsyncChannel` and async typed NIO pieces.
* Remove availability on the protocols
# Motivation
We have done quite some changes on the new async interfaces and our documentation needs some updating.
# Modification
This PR updates the concurrency interop documentation to reflect the latest APIs.
* Tolerate empty HTTP response body parts
### Motivation
Empty HTTP response body parts currently eagerly end a response. This is unexpected and against NIOs documented behaviour.
### Modification
- add test which send an empty response body part and would previously fail
- skip empty response body parts
### Result
Users can send empty body parts without ending the response.
* add comment explaining why we do it here instead of fixing it at the source
* move empty body part logic to `writeChunk`
# Motivation
To reduce allocations when wrapping a channel into a `NIOAsyncChannel` we should make the `NIOAsyncChannel` a struct instead of a class.
# Modification
This PR changes the `NIOAsyncChannel` to a struct.
# Motivation
We spelled back pressure a few different ways throughout our async interfaces.
# Modification
This PR aligns to `backPressure` everywhere and uses `back pressure` in comments.
# Motivation
We were accessing `self` in a `@Sendable` function in the `NIOPipeBoostrap`. The 5.10 compiler correctly diagnoses this as a Sendable violation since the bootstrap is in-fact not Sendable.
# Modification
Store the `channelOptions` in a local variable outside of the `@Sendable` function.
# Result
No more Sendable warnings on 5.10
* Introduce new typed `HTTPServerUpgrader` and `WebSocketServerUpgrader`
# Motivation
With our new `NIOAsyncChannel` and typed bootstrap APIs we want to be able to let users spell out their pipeline in a typed way. Pipelines can contain handlers that have to make a forking decision such as HTTP upgrading. Our current `HTTPServerUpgradeHandler` is one of those handlers but it lacks strict typing. To interact nicely with our new typed APIs we need to have a new variant of the `HTTPServerUpgradeHandler` that can carry type information.
# Modification
This PR adds a few things:
1. A new `NIOTypedHTTPServerUpgradeHandler` + `NIOTypedHTTPServeProtocolUpgrader`. I also moved the state handling logic to a separate state machine. I thought about unifying the state machines of the _old_ handler and the new one but they differ in behaviour which makes the state machine more complicated.
2. A new `NIOTypedWebSocketServerUpgrader` that conforms to `NIOTypedHTTPServerProtocolUpgrader`
3. An overhauled WebSocket server example that fully uses Concurrency.
# Result
We now have a way to fully type the server side of HTTP protocol upgrading.
Code review
Update parameter names for new API and fix example
* Introduce new configuration struct and rename to `UpgradablePipeline`
* Review comments
* Bump minimum Swift version to 5.7
Motivation:
Now that Swift 5.9 is GM we should update the supported versions and
remove 5.6
Modifications:
* Update `Package.swift`
* Remove `#if swift(>=5.7)` guards
* Delete the 5.6 docker compose file and make a 5.10 one
* Update integration test script
* Update docs
Result:
Remove support for Swift 5.6, add 5.10
* fix indentation issues
* 5.9 docker image use release image
Motivation:
On c++ compile, we get 'error: unknown type name '_Bool' DECLARE_ATOMIC_OPERATIONS(_Bool, _Bool)'
The c++ compile is happening when SwiftPM builds a module
with swiftSettings: [.interoperabilityMode(.Cxx)] set and
where nio is a dependency.
Modifications:
* Sources/CNIOAtomics/include/CNIOAtomics.h
Conditionally, if __cplusplus, use bool type instead of
_Bool (a c-type only) for booleans.
Result:
Compiles where previous it error'd.
After your change, what will change.
No change other than now it compiles under c++.
Co-authored-by: Cory Benfield <lukasa@apple.com>
# Motivation
When we created the first round of new async bootstrap APIs we added a `ProtocolNegotiationHandler` protocol to identify handlers that are doing protocol negotiation. Since then, we have changed the way how the async bootstraps work and we no longer need this protocol.
# Modification
Remove the `ProtocolNegotiationHandler` protocol
Motivation
This patch adds support for custom protocol families to
DatagramBootstrap. In most cases this isn't useful, and will fail, but
in many OSes it's a recognised system for non-root processes to get a
way to send ICMP echo requests. This is worth supporting.
Modifications
- Expose the `ProtocolSubtype` type publicly.
- Add a `protocolSubtype` setter on `DatagramBootstrap`
- Write a test that actually does ICMP as non-root
Results
Users can send ICMP echo requests without root privileges.
This commit adds Codable to ByteBuffer. It encodes in Base64 into a singleValue
container.
- Base64 implementation moved into _NIODataStructures
- Base64 now supports decoding.
Motivation:
Right now we always set the framing headers in HTTP requests and
responses that we send. This is a good practice for most users, but
it can cause issues, most notably in responses to CONNECT requests
which requires that we do not set framing headers.
Unfortunately, in NIO's current HTTP/1.1 design it is not possible
for us to suppress these headers. This is because the HTTP encoders
come _earlier_ in the pipeline than the decoders, so the HTTP
encoders do not know structurally what requests they are responding
to.
While we could merge the encoders/decoders, that's a fairly
substantial change. A better short-term change is to offer users
the ability to turn off the NIO header manipulation feature. In
this circumstance, users take on full responsibility for
appropriately framing their HTTP messages.
Modifications
- Add config to HTTPRequestEncoder and HTTPResponseEncoder.
- Plumb this config through.
- Add a bunch of tests.
Result
Users have way more control of HTTP/1.1 messages.
* Initial implementation of hexdump for ByteBuffer
* Put that iff back there
* Reword hexDumpShort(): naming, tests, offset and full length support
* Use writerIndex to figure out the convinience end of useful content in the buffer
* hexDumpLong(offset:) — supports offset, and reads full buffer slice, not just readableBytes
* hexDumpLong() extra line failing test
* Using ByteBuffer(string:) instead of the allocator
* Move hexDumps code into ByteBuffer-hexdump.swift
* Optimized String(byte: poadding:)
* Avoid using storage.dumpBytes in hexDumpShort()
* Implemented a cleaner long hexdump
* Implemented the public hexdump API
* Revert ByteBuffer-core.swift to main
* Addressed review feedback!
* hexdump long format with clipped length
* reserve capacity in hexDumpLines
* Addressing review feedback
* String(_ value, radix, padding) and the final test case
* Make the hexDump(format: .detailed) format cleaner
* Spell out if let for Swift 5.8
* Fixed a formatting bug in multiline maxBytes detailed format
* Apply suggestions from code review
Co-authored-by: George Barnett <gbarnett@apple.com>
* Cleaner way to dump a line in .detailed format
* Cleaner generic argument type for String(_, radix:, padding:)
* Revert _storage.dumpBytes test to match previous format
* Simplify printable bytes closure to a single expression so Swift 5.6 is happy
---------
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
# Motivation
Fixes https://github.com/apple/swift-nio/issues/2494
# Modification
This PR avoids using `deinit` to fulfil the protocol negotiation promise and opts to trap instead when it is being accessed before the handler is added. This allows us to use `handlerAdded` and `handlerRemoved`.
# Result
No more `deinit` usage that can be observed.
# Motivation
We recently provided testing utilities for the `NIOAsyncChannelInboundStream`. On thing that was missing is a way to finish the stream with an error.
# Modification
This PR provides a `finish()` method that takes an error which is thrown from the inbound stream.
# Result
Better way to test code relying on the AsyncChannel work.
# Motivation
We sometimes leaked a promise in the `NIOTypedApplicationProtocolNegotiationHandler` when the handler was created and immediately deinited.
# Modification
This PR makes sure we always complete the negotiation promise of the handler.
# Result
No more leaked promises.
* Support NIO Event Loops as actor executors
Motivation
Swift Concurrency supports having actors opt in to executing
within a "custom executor". This requires being able to be strictly
serial, a constraint that NIO's EventLoops natively meet. It is
useful to have actors be able to express a "tie" to an EventLoop
in order to efficiently access objects that are tied to specific ELs.
Modifications
- Extend EventLoop to expose an executor property
- Provide a simple best-effort default using NIODefaultSerialEventLoopExecutor
- Expose NIOSerialEventLoopExecutor protocol that makes it easy
for adopters to get a better implementation
- Crash if EmbeddedEventLoop is used
- Add tests
Result
Adopters can use ELs as serial executors
* Prefer #if compiler