Files
swift-nio/Sources/NIOTestUtils/ByteToMessageDecoderVerifier.swift
Fabian FettandCory Benfield f5b34b27cb Allow non-copyable ByteToMessageDecoders and typed throws (#3731)
### 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>
2026-09-17 13:44:37 +01:00

320 lines
14 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOEmbedded
public enum ByteToMessageDecoderVerifier: Sendable {
/// Verify `ByteToMessageDecoder`s with `String` inputs
///
/// - seealso: verifyDecoder(inputOutputPairs:decoderFactory:)
public static func verifyDecoder<Decoder: ByteToMessageDecoder>(
stringInputOutputPairs: [(String, [Decoder.InboundOut])],
decoderFactory: () -> Decoder
) throws where Decoder.InboundOut: Equatable {
try ByteToMessageDecoderVerifier.verifyDecoder(
inputOutputPairs: Self.byteBufferPairs(from: stringInputOutputPairs),
decoderFactory: decoderFactory
)
}
/// Verify non-copyable `ByteToMessageDecoder`s with `String` inputs.
///
/// - seealso: verifyDecoder(inputOutputPairs:decoderFactory:)
@available(macOS 15, iOS 18, tvOS 18, watchOS 11, visionOS 2, *)
public static func verifyDecoder<Decoder: ByteToMessageDecoder & ~Copyable>(
stringInputOutputPairs: [(String, [Decoder.InboundOut])],
decoderFactory: () -> Decoder
) throws where Decoder.InboundOut: Equatable {
try ByteToMessageDecoderVerifier.verifyDecoder(
inputOutputPairs: Self.byteBufferPairs(from: stringInputOutputPairs),
decoderFactory: decoderFactory
)
}
private static func byteBufferPairs<Out>(from pairs: [(String, [Out])]) -> [(ByteBuffer, [Out])] {
let alloc = ByteBufferAllocator()
return pairs.map { (ioPair: (String, [Out])) -> (ByteBuffer, [Out]) in
(alloc.buffer(string: ioPair.0), ioPair.1)
}
}
/// Verifies a `ByteToMessageDecoder` by performing a number of tests.
///
/// This method is mostly useful in unit tests for `ByteToMessageDecoder`s. It feeds the inputs from
/// `inputOutputPairs` into the decoder in various ways and expects the decoder to produce the outputs from
/// `inputOutputPairs`.
///
/// The verification performs various tests, for example:
///
/// - drip feeding the bytes, one by one
/// - sending many messages in one `ByteBuffer`
/// - sending each complete message in one `ByteBuffer`
///
/// For `ExampleDecoder` that produces `ExampleDecoderOutput`s you would use this method the following way:
/// ```swift
/// var exampleInput1 = channel.allocator.buffer(capacity: 16)
/// exampleInput1.writeString("example-in1")
/// var exampleInput2 = channel.allocator.buffer(capacity: 16)
/// exampleInput2.writeString("example-in2")
/// let expectedInOuts = [(exampleInput1, [ExampleDecoderOutput("1")]),
/// (exampleInput2, [ExampleDecoderOutput("2")])
/// ]
/// #expect(throws: Never.self) {
/// try ByteToMessageDecoderVerifier.verifyDecoder(
/// inputOutputPairs: expectedInOuts,
/// decoderFactory: { ExampleDecoder() }
/// )
/// }
/// ```
public static func verifyDecoder<Decoder: ByteToMessageDecoder>(
inputOutputPairs: [(ByteBuffer, [Decoder.InboundOut])],
decoderFactory: () -> Decoder
) throws where Decoder.InboundOut: Equatable {
let handler = ByteToMessageHandler(decoderFactory())
try self.verify(
inputOutputPairs: inputOutputPairs,
handler: handler,
erasedHandler: handler
)
}
/// Verifies a non-copyable `ByteToMessageDecoder`.
///
/// - seealso: verifyDecoder(inputOutputPairs:decoderFactory:)
@available(macOS 15, iOS 18, tvOS 18, watchOS 11, visionOS 2, *)
public static func verifyDecoder<Decoder: ByteToMessageDecoder & ~Copyable>(
inputOutputPairs: [(ByteBuffer, [Decoder.InboundOut])],
decoderFactory: () -> Decoder
) throws where Decoder.InboundOut: Equatable {
let handler = ByteToMessageHandler(decoderFactory())
try self.verify(
inputOutputPairs: inputOutputPairs,
handler: handler,
erasedHandler: handler
)
}
/// The decoder-agnostic core of the verification.
///
/// The handler is passed twice: once with its concrete type, so that we can inspect the bytes it has buffered,
/// and once erased to `any ChannelHandler`. The erasure has to happen in the callers because erasing a type with
/// a non-copyable generic argument requires a newer Swift runtime than the copyable entry point demands.
private static func verify<Out: Equatable, Decoder: ByteToMessageDecoder & ~Copyable>(
inputOutputPairs: [(ByteBuffer, [Out])],
handler: ByteToMessageHandler<Decoder>,
erasedHandler: any ChannelHandler
) throws {
func verifySimple(channel: RecordingChannel) throws {
for (input, expectedOutputs) in inputOutputPairs.shuffled() {
try channel.writeInbound(input)
for expectedOutput in expectedOutputs {
guard let actualOutput = try channel.readInbound(as: Out.self) else {
throw VerificationError<Out>(
inputs: channel.inboundWrites,
errorCode: .underProduction(expectedOutput)
)
}
guard actualOutput == expectedOutput else {
throw VerificationError<Out>(
inputs: channel.inboundWrites,
errorCode: .wrongProduction(
actual: actualOutput,
expected: expectedOutput
)
)
}
}
let actualExtraOutput = try channel.readInbound(as: Out.self)
guard actualExtraOutput == nil else {
throw VerificationError<Out>(
inputs: channel.inboundWrites,
errorCode: .overProduction(actualExtraOutput!)
)
}
}
}
func verifyDripFeed(channel: RecordingChannel) throws {
for _ in 0..<10 {
for (input, expectedOutputs) in inputOutputPairs.shuffled() {
for c in input.readableBytesView {
var buffer = channel.allocator.buffer(capacity: 12)
buffer.writeString("BEFORE")
buffer.writeInteger(c)
buffer.writeString("AFTER")
buffer.moveReaderIndex(forwardBy: 6)
buffer.moveWriterIndex(to: buffer.readerIndex + 1)
try channel.writeInbound(buffer)
}
for expectedOutput in expectedOutputs {
guard let actualOutput = try channel.readInbound(as: Out.self) else {
throw VerificationError<Out>(
inputs: channel.inboundWrites,
errorCode: .underProduction(expectedOutput)
)
}
guard actualOutput == expectedOutput else {
throw VerificationError<Out>(
inputs: channel.inboundWrites,
errorCode: .wrongProduction(
actual: actualOutput,
expected: expectedOutput
)
)
}
}
let actualExtraOutput = try channel.readInbound(as: Out.self)
guard actualExtraOutput == nil else {
throw VerificationError<Out>(
inputs: channel.inboundWrites,
errorCode: .overProduction(actualExtraOutput!)
)
}
}
}
}
func verifyManyAtOnce(channel: RecordingChannel) throws {
var overallBuffer = channel.allocator.buffer(capacity: 1024)
var overallExpecteds: [Out] = []
for _ in 0..<10 {
for (var input, expectedOutputs) in inputOutputPairs.shuffled() {
overallBuffer.writeBuffer(&input)
overallExpecteds.append(contentsOf: expectedOutputs)
}
}
try channel.writeInbound(overallBuffer)
for expectedOutput in overallExpecteds {
guard let actualOutput = try channel.readInbound(as: Out.self) else {
throw VerificationError<Out>(
inputs: channel.inboundWrites,
errorCode: .underProduction(expectedOutput)
)
}
guard actualOutput == expectedOutput else {
throw VerificationError<Out>(
inputs: channel.inboundWrites,
errorCode: .wrongProduction(
actual: actualOutput,
expected: expectedOutput
)
)
}
}
}
let channel = RecordingChannel(EmbeddedChannel(handler: erasedHandler))
try verifySimple(channel: channel)
try verifyDripFeed(channel: channel)
try verifyManyAtOnce(channel: channel)
if case .leftOvers(inbound: let ib, outbound: let ob, pendingOutbound: let pob) = try channel.finish() {
throw VerificationError<Out>(
inputs: channel.inboundWrites,
errorCode: .leftOversOnDeconstructingChannel(
inbound: ib,
outbound: ob,
pendingOutbound: pob
)
)
}
// Bytes the decoder never consumed are buffered inside `ByteToMessageHandler` and therefore invisible to
// `finish()` above, so they are reported separately with empty left overs.
let unprocessedBytes = handler.cumulationBuffer?.readableBytes ?? 0
if unprocessedBytes > 0 {
throw VerificationError<Out>(
inputs: channel.inboundWrites,
errorCode: .leftOversOnDeconstructingChannel(inbound: [], outbound: [], pendingOutbound: [])
)
}
}
}
extension ByteToMessageDecoderVerifier {
private class RecordingChannel {
private let actualChannel: EmbeddedChannel
private(set) var inboundWrites: [ByteBuffer] = []
init(_ actualChannel: EmbeddedChannel) {
self.actualChannel = actualChannel
}
func readInbound<T>(as type: T.Type = T.self) throws -> T? {
try self.actualChannel.readInbound()
}
@discardableResult public func writeInbound(_ data: ByteBuffer) throws -> EmbeddedChannel.BufferState {
self.inboundWrites.append(data)
return try self.actualChannel.writeInbound(data)
}
var allocator: ByteBufferAllocator {
self.actualChannel.allocator
}
func finish() throws -> EmbeddedChannel.LeftOverState {
try self.actualChannel.finish()
}
}
}
extension ByteToMessageDecoderVerifier {
/// A `VerificationError` is thrown when the verification of a `ByteToMessageDecoder` failed.
public struct VerificationError<OutputType: Equatable>: Error {
/// Contains the `inputs` that were passed to the `ByteToMessageDecoder` at the point where it failed
/// verification.
public var inputs: [ByteBuffer]
/// `errorCode` describes the concrete problem that was detected.
public var errorCode: ErrorCode
public enum ErrorCode {
/// The `errorCode` will be `wrongProduction` when the `expected` output didn't match the `actual`
/// output.
case wrongProduction(actual: OutputType, expected: OutputType)
/// The `errorCode` will be set to `overProduction` when a decoding result was yielded where
/// nothing was expected.
case overProduction(OutputType)
/// The `errorCode` will be set to `underProduction` when a decoder didn't yield output when output was
/// expected. The expected output is delivered as the associated value.
case underProduction(OutputType)
/// The `errorCode` will be set to `leftOversOnDeconstructionChannel` if there were left-over items
/// in the `Channel` on deconstruction. This usually means that your `ByteToMessageDecoder` did not process
/// certain items.
case leftOversOnDeconstructingChannel(inbound: [NIOAny], outbound: [NIOAny], pendingOutbound: [NIOAny])
}
}
}
@available(*, unavailable)
extension ByteToMessageDecoderVerifier.VerificationError.ErrorCode: Sendable {}
/// `VerificationError` conforms to `Error` and therefore needs to conform to `Sendable` too.
/// `VerificationError` has a stored property `errorCode` of type `ErrorCode` which can store `NIOAny` which is not and can not be `Sendable`.
/// In addtion, `ErrorCode` can also store a user defined `OutputType` which is not required to be `Sendable` but we could require it to be `Sendable`.
/// We have two choices:
/// - we could lie and conform `ErrorCode` to `Sendable` with `@unchecked`
/// - do the same but for `VerificationError`
/// As `VerificationError` already conforms to `Sendable` (because it conforms to `Error` and `Error` inherits from `Sendable`)
/// it sound like the best option to just stick to the conformances we already have and **not** lie twice by making `VerificationError` conform to `Sendable` too.
/// Note that this still allows us to adopt `Sendable` for `ErrorCode` later if we change our opinion.
extension ByteToMessageDecoderVerifier.VerificationError: @unchecked Sendable {}