### Motivation
Decoders are state machines and state machines are a natural fit for
non-copyable types. Today `ByteToMessageDecoder` and
`NIOSingleStepByteToMessageDecoder` require their conformers to be
copyable.
While we are here we also want `NIOSingleStepByteToMessageDecoder` to be
able to declare a concrete error type, so that callers can handle decode
errors without going through an existential.
### Changes
- Make `ByteToMessageDecoder` and `NIOSingleStepByteToMessageDecoder`
`~Copyable`.
- Add an `associatedtype DecodeError: Error = any Error` to
`NIOSingleStepByteToMessageDecoder` and spell decode and decodeLast as
`throws(DecodeError)`. Decoders that don't declare it keep behaving
exactly as before.
- Allow `~Copyable` `ByteToMessageDecoder` in `ByteToMessageHandler`.
- Since `~Copyable` types cannot be type erased into an existential
before macOS 15, we have to work around the existing `CanDequeueWrites`
dance: instead of casting `self` to `CanDequeueWrites` in
`handlerAdded`, ByteToMessageHandler gains an optional
`deliverQueuedWrite` closure. It is formed in the constrained
`ChannelOutboundHandler.write`, the only place where `Decoder`'s
`WriteObservingByteToMessageDecoder` conformance is statically known,
the first time a write arrives re-entrantly.
This has to be a closure rather than a protocol requirement on
`ByteToMessageDecoder`. `Decoders` may conform to
`WriteObservingByteToMessageDecoder` conditionally while conforming to
`ByteToMessageDecoder` unconditionally — `HTTPDecoder` does exactly this
— and all generic instantiations share one `ByteToMessageDecoder`
witness table, so such a requirement could only ever be witnessed by a
non-observing default and the write would be silently dropped.
- Split the delivery out of `tryDecodeWrites` into an `@inline(never)
dequeueWrites()`. `decodeLoop` calls `tryDecodeWrites` on every
iteration, so the empty-queue check has to stay cheap; keeping the
delivery inline tripled that function's size (50 → 141 instructions) and
showed up directly on the normal decode path.
- `ByteToMessageDecoderVerifier` allows `~Copyable`
`ByteToMessageDecoder`s.
- Added tests that use the newly lifted `~Copyable` restriction, plus
regression coverage for a decoder whose write-observing conformance is
conditional (the HTTPDecoder shape) and for constructing the handler in
a generic context.
### Result
Decoders may be non-copyable and may declare a concrete error type.
The normal decode path does not change performance. The re-entrant write
path costs one extra allocation per handler, but is meaningfully cheaper
in instructions. I'm happy to provide the benchmarks used to generate
those numbers in a separate pr – leaving them out here, as we would end
up with as many benchmarks as we have unit tests sooner or later.
Instructions, macOS arm64, per 1000 iterations, min of 5 interleaved
rounds:
```
┌──────────────────────────────┬────────────┬────────────┬───────────────────────────────────┐
│ │ main │ this PR │ │
├──────────────────────────────┼────────────┼────────────┼───────────────────────────────────┤
│ decode, no write observation │ 9,404,415 │ 9,360,896 │ −0.46% (noise ~0.8%, i.e. parity) │
├──────────────────────────────┼────────────┼────────────┼───────────────────────────────────┤
│ decode + re-entrant write │ 13,656,063 │ 12,541,951 │ −8.16% │
├──────────────────────────────┼────────────┼────────────┼───────────────────────────────────┤
│ handler add / remove │ 85,983,231 │ 83,361,791 │ −3.05% (noise ~2.2%) │
└──────────────────────────────┴────────────┴────────────┴───────────────────────────────────┘
```
Replacing the CanDequeueWrites existential with the closure is what
improves the reentrant write path: delivering a queued write is now a
direct closure call rather than a witness-table dispatch, and
handlerAdded no longer performs a runtime conditional-conformance
lookup.
The saving grows with the number of writes queued per decode — around
−16% with 8 queued writes, though that benchmark is noisier.
Allocations (nio-alloc-counter-tests, Swift 6.2):
```
┌────────────────────────────┬─────────┬─────────┬────────┐
│ │ main │ this PR │ │
├────────────────────────────┼─────────┼─────────┼────────┤
│ 1000_reqs_1_conn │ 27,341 │ 27,342 │ +1 │
├────────────────────────────┼─────────┼─────────┼────────┤
│ 1_reqs_1000_conn │ 368,000 │ 369,000 │ +1,000 │
├────────────────────────────┼─────────┼─────────┼────────┤
│ ping_pong_1000_reqs_1_conn │ 296 │ 296 │ — │
├────────────────────────────┼─────────┼─────────┼────────┤
│ decode_1000_ws_frames │ 2,000 │ 2,000 │ — │
└────────────────────────────┴─────────┴─────────┴────────┘
```
Forming the closure captures Decoder.OutboundIn's metadata, so it
allocates once per handler that actually queues a re-entrant write —
1_reqs_1000_conn builds 1000 such handlers, hence +1000. main's
existential cast did not allocate, so this is a new cost rather than
staying flat. The 1_reqs_1000_conn threshold is raised by 1000 for
6.1/6.2/6.3; the nightly toolchains are unchanged (10,000 on both — they
specialize the closure away entirely).
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation
We want to extend `ByteToMessageDecoderVerifierTest` with tests that
verify non-copyable decoders. Instead of adding more XCTests, lets first
move all existing tests to swift-testing.
### Changes
- Mechanical translation of `ByteToMessageDecoderVerifierTest` from
XCTest to Swift Testing.
### Result
No behaviour change. We can write the new tests in Swift Testing.
* Apply formatting
* Apply no block comments rule
* Apply OmitExplicitReturns
* Apple OnlyOneTrailingClosureArgument
* Apply NoAssignmentInExpressions
* Fix up DontRepeatTypeInStaticProperties lint errors
* Apply `OrderedImports`
* Apply `ReplaceForEachWithForLoop`
* format file
* Enable the formatting pipeline
* Adopt `AmbiguousTrailingClosureOverload`
* Fix license header
* Fix format check
* Fix `EndOfLineComment`
* Fix CI
* Adapt CI script to check if changes when running formatting
* Separate lint and format into to steps
* Fix format
* Adopt `UseEarlyExits`
* Revert "Adopt `UseEarlyExits`"
This reverts commit d1ac5bbe12.
Motivation:
The remaining NIO code really conceptually belongs in a module called
NIOPosix, and NIOCore should really be called NIO. We can't really do
that last step, but we can prepare by pushing the bulk of the remaining
code into a module called NIOPosix.
Modifications:
- Move NIO to NIOPosix
- Make NIO an umbrella module.
Result:
NIOPosix exists.
Motivation:
The most important API surface area in NIO are the Channel abstractions.
These are shared in all NIO programs, and are also used by several
projects to implement their I/O abstraction. There are several moving
parts to this abstraction, all of which are moving:
- Channel itself
- ChannelPipeline
- ChannelHandler
As these all move, they force several other pieces of API to move with
them. Most notably they force us to move NIOAny, which also forces us to
move FileHandle and FileRegion. That also forces us to bring over part
of our syscall abstraction. This duplication is acceptable due to its
minimal surface area, but it is definitely a flaw in our abstraction
design that we had to do that at all.
We also need to move the channel option abstraction, AddressedEnvelope,
and the DeadChannel.
Modifications:
- Moved a bunch of the Channel abstraction over.
- Moved Channel-associated types.
Result:
Channel will be part of NIOCore.
Motivation:
When writing B2MDs, there are a couple of scenarios that always need to
be tested: firehose feeding, drip feeding, many messages, ...
It's tedious writing those tests over and over again for every B2MD.
Modifications:
- Add a simple B2MD verifier that users can use in unit tests.
- Add a new, public `NIOTestUtils` module which contains utilities
mostly useful for testing. Crucially however, it does not depend on
`XCTest` so it can be used it all targets.
Result:
Hopefully fewer bugs in B2MDs.