Merge branch 'main' into queue_outbound_close

This commit is contained in:
Rick Newton-Rogers authored and GitHub committed 2025-04-10 06:18:00 +01:00
commit d41ef1ba4f
40 files changed
+1563 -1060

No files matched your search

+37 -11
View File
@@ -13,8 +13,8 @@ on:
default: ""
xcode_16_0_enabled:
type: boolean
description: "Boolean to enable the Xcode version 16.0 jobs. Defaults to true."
default: true
description: "Boolean to enable the Xcode version 16.0 jobs. Defaults to false."
default: false
xcode_16_0_build_arguments_override:
type: string
description: "The arguments passed to swift build in the macOS 5.10 Swift version matrix job."
@@ -37,7 +37,7 @@ on:
default: ""
xcode_16_2_enabled:
type: boolean
description: "Boolean to enable the Xcode version 16.1 jobs. Defaults to true."
description: "Boolean to enable the Xcode version 16.2 jobs. Defaults to true."
default: true
xcode_16_2_build_arguments_override:
type: string
@@ -47,6 +47,18 @@ on:
type: string
description: "The arguments passed to swift test in the Xcode version 16.2 job."
default: ""
xcode_16_3_enabled:
type: boolean
description: "Boolean to enable the Xcode version 16.3 jobs. Defaults to true."
default: true
xcode_16_3_build_arguments_override:
type: string
description: "The arguments passed to swift build in the Xcode version 16.3 job."
default: ""
xcode_16_3_test_arguments_override:
type: string
description: "The arguments passed to swift test in the Xcode version 16.3 job."
default: ""
build_scheme:
type: string
@@ -89,8 +101,8 @@ on:
default: false
visionos_xcode_build_enabled:
type: boolean
description: "Boolean to enable the Xcode build targeting visionOS. Defaults to true."
default: true
description: "Boolean to enable the Xcode build targeting visionOS. Defaults to false."
default: false
visionos_xcode_test_enabled:
type: boolean
description: "Boolean to enable the Xcode test targeting visionOS. Defaults to false."
@@ -129,6 +141,9 @@ jobs:
xcode_16_2_enabled="${MATRIX_MACOS_16_2_ENABLED:=true}"
xcode_16_2_build_arguments_override="${MATRIX_MACOS_16_2_BUILD_ARGUMENTS_OVERRIDE:=""}"
xcode_16_2_test_arguments_override="${MATRIX_MACOS_16_2_TEST_ARGUMENTS_OVERRIDE:=""}"
xcode_16_3_enabled="${MATRIX_MACOS_16_3_ENABLED:=true}"
xcode_16_3_build_arguments_override="${MATRIX_MACOS_16_3_BUILD_ARGUMENTS_OVERRIDE:=""}"
xcode_16_3_test_arguments_override="${MATRIX_MACOS_16_3_TEST_ARGUMENTS_OVERRIDE:=""}"
# Create matrix from inputs
matrix='{"config": []}'
@@ -165,6 +180,14 @@ jobs:
'.config[.config| length] |= . + { "name": "Xcode 16.2", "xcode_version": "16.2", "build_arguments_override": $build_arguments_override, "test_arguments_override": $test_arguments_override, "os": "sequoia", "arch": "ARM64", "pool": $runner_pool }')
fi
if [[ "$xcode_16_3_enabled" == "true" ]]; then
matrix=$(echo "$matrix" | jq -c \
--arg build_arguments_override "$xcode_16_3_build_arguments_override" \
--arg test_arguments_override "$xcode_16_3_test_arguments_override" \
--arg runner_pool "$runner_pool" \
'.config[.config| length] |= . + { "name": "Xcode 16.3", "xcode_version": "16.3", "build_arguments_override": $build_arguments_override, "test_arguments_override": $test_arguments_override, "os": "sequoia", "arch": "ARM64", "pool": $runner_pool }')
fi
echo "$matrix" | jq -c
)"
EOM
@@ -182,6 +205,9 @@ jobs:
MATRIX_MACOS_16_2_ENABLED: ${{ inputs.xcode_16_2_enabled }}
MATRIX_MACOS_16_2_BUILD_ARGUMENTS_OVERRIDE: ${{ inputs.xcode_16_2_build_arguments_override }}
MATRIX_MACOS_16_2_TEST_ARGUMENTS_OVERRIDE: ${{ inputs.xcode_16_2_test_arguments_override }}
MATRIX_MACOS_16_3_ENABLED: ${{ inputs.xcode_16_3_enabled }}
MATRIX_MACOS_16_3_BUILD_ARGUMENTS_OVERRIDE: ${{ inputs.xcode_16_3_build_arguments_override }}
MATRIX_MACOS_16_3_TEST_ARGUMENTS_OVERRIDE: ${{ inputs.xcode_16_3_test_arguments_override }}
darwin-job:
name: ${{ matrix.config.name }}
@@ -242,12 +268,12 @@ jobs:
- name: tvOS test
if: '!cancelled() && inputs.tvos_xcode_test_enabled'
run: /usr/bin/xcodebuild -quiet -scheme ${BUILD_SCHEME} -destination "name=Apple TV 4K (3rd generation)" test
# - name: visionOS build # arm only # TODO: disabled due to issue
# if: '!cancelled() && inputs.visionos_xcode_build_enabled'
# run: /usr/bin/xcodebuild -quiet -scheme ${BUILD_SCHEME} -destination "generic/platform=visionos" build
# - name: visionOS test # arm only # TODO: disabled due to issue
# if: '!cancelled() && inputs.visionos_xcode_test_enabled'
# run: /usr/bin/xcodebuild -quiet -scheme ${BUILD_SCHEME} -destination "name=Apple Vision Pro" test
- name: visionOS build # arm only
if: '!cancelled() && inputs.visionos_xcode_build_enabled'
run: /usr/bin/xcodebuild -quiet -scheme ${BUILD_SCHEME} -destination "generic/platform=visionos" build
- name: visionOS test # arm only
if: '!cancelled() && inputs.visionos_xcode_test_enabled'
run: /usr/bin/xcodebuild -quiet -scheme ${BUILD_SCHEME} -destination "name=Apple Vision Pro" test
env:
XCODE_VERSION: ${{ matrix.config.xcode_version }}
DEVELOPER_DIR: "/Applications/Xcode_${{ matrix.config.xcode_version }}.app"
+2 -2
View File
@@ -19,7 +19,7 @@ jobs:
"platform":"Linux",
"runner":"ubuntu-latest",
"image":"ubuntu:jammy",
"setup_command":"apt-get update -y -q && apt-get install -y -q curl && curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/install_static_sdk.sh | INSTALL_SWIFT_STATIC_SDK_VERSION=latest INSTALL_SWIFT_STATIC_SDK_ARCH=x86_64 bash && hash -r",
"setup_command":"apt update -q && apt install -y -q curl jq tar && curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/install_swift_prerequisites.sh | bash && curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/install_static_sdk.sh | INSTALL_SWIFT_STATIC_SDK_VERSION=latest INSTALL_SWIFT_STATIC_SDK_ARCH=x86_64 bash && hash -r",
"command":"swift build",
"command_arguments":"--swift-sdk x86_64-swift-linux-musl"
},
@@ -29,7 +29,7 @@ jobs:
"platform":"Linux",
"runner":"ubuntu-latest",
"image":"ubuntu:jammy",
"setup_command":"apt-get update -y -q && apt-get install -y -q curl && curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/install_static_sdk.sh | INSTALL_SWIFT_STATIC_SDK_BRANCH=main INSTALL_SWIFT_STATIC_SDK_ARCH=x86_64 bash && hash -r",
"setup_command":"apt update -q && apt install -y -q curl jq tar && curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/install_swift_prerequisites.sh | bash && curl -s https://raw.githubusercontent.com/apple/swift-nio/main/scripts/install_static_sdk.sh | INSTALL_SWIFT_STATIC_SDK_BRANCH=main INSTALL_SWIFT_STATIC_SDK_ARCH=x86_64 bash && hash -r",
"command":"swift build",
"command_arguments":"--swift-sdk x86_64-swift-linux-musl"
}
@@ -20,7 +20,9 @@ private let eventLoop = MultiThreadedEventLoopGroup.singleton.next()
let benchmarks = {
let defaultMetrics: [BenchmarkMetric] = [
.mallocCountTotal
.mallocCountTotal,
.contextSwitches,
.wallClock,
]
Benchmark(
@@ -38,9 +40,6 @@ let benchmarks = {
)
}
// This benchmark is only available above 5.9 since our EL conformance
// to serial executor is also gated behind 5.9.
#if compiler(>=5.9)
Benchmark(
"TCPEchoAsyncChannel",
configuration: .init(
@@ -66,7 +65,6 @@ let benchmarks = {
eventLoop: eventLoop
)
}
#endif
Benchmark(
"MTELG.scheduleTask(in:_:)",
@@ -101,4 +99,45 @@ let benchmarks = {
let handle = try! eventLoop.scheduleCallback(in: .hours(1), handler: timer)
}
}
Benchmark(
"Jump to EL and back using execute and unsafecontinuation",
configuration: .init(
metrics: defaultMetrics,
scalingFactor: .kilo
)
) { benchmark in
for _ in benchmark.scaledIterations {
await withUnsafeContinuation { (continuation: UnsafeContinuation<Void, Never>) in
eventLoop.execute {
continuation.resume()
}
}
}
}
final actor Foo {
nonisolated public let unownedExecutor: UnownedSerialExecutor
init(eventLoop: any EventLoop) {
self.unownedExecutor = eventLoop.executor.asUnownedSerialExecutor()
}
func foo() {
blackHole(Void())
}
}
Benchmark(
"Jump to EL and back using actor with EL executor",
configuration: .init(
metrics: defaultMetrics,
scalingFactor: .kilo
)
) { benchmark in
let actor = Foo(eventLoop: eventLoop)
for _ in benchmark.scaledIterations {
await actor.foo()
}
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
// swift-tools-version: 5.7
// swift-tools-version:5.9
import PackageDescription
@@ -1,3 +1,3 @@
{
"mallocCountTotal" : 164371
}
"mallocCountTotal": 82000
}
+13 -6
View File
@@ -19,7 +19,7 @@ function fail() {
function assert_equal() {
if [[ "$1" != "$2" ]]; then
fail "expected '$1', got '$2' ${3-}"
fail "expected '$1', got '$2'${3+: }${3-}"
fi
}
@@ -33,31 +33,38 @@ function assert_equal_files() {
echo "--- SNIP ($2, size=$(wc "$2"), SHA=$(shasum "$2")) ---"
cat "$2"
echo "--- SNAP ($2) ---"
fail "file '$1' not equal to '$2'"
fail "file '$1' not equal to '$2'${3+: }${3-}"
fi
}
function assert_less_than() {
if [[ ! "$1" -lt "$2" ]]; then
fail "assertion '$1' < '$2' failed"
fail "assertion '$1' < '$2' failed${3+: }${3-}"
fi
}
function assert_less_than_or_equal() {
if [[ ! "$1" -le "$2" ]]; then
fail "assertion '$1' <= '$2' failed"
fail "assertion '$1' <= '$2' failed${3+: }${3-}"
fi
}
function assert_greater_than() {
if [[ ! "$1" -gt "$2" ]]; then
fail "assertion '$1' > '$2' failed"
fail "assertion '$1' > '$2' failed${3+: }${3-}"
fi
}
function assert_greater_than_or_equal() {
if [[ ! "$1" -ge "$2" ]]; then
fail "assertion '$1' >= '$2' failed"
fail "assertion '$1' >= '$2' failed${3+: }${3-}"
fi
}
function assert_is_number() {
re='^[0-9]+$'
if ! [[ $1 =~ $re ]]; then
fail "$1 is not a number${2+: }${2-}"
fi
}
@@ -55,14 +55,16 @@ for test in "${all_tests[@]}"; do
leaked_fds=$(grep "^test_$test_case.leaked_fds:" "$tmp/output" | cut -d: -f2 | sed 's/ //g')
max_allowed_env_name="MAX_ALLOCS_ALLOWED_$test_case"
max_allowed=$(jq '.'\""$test_case"\" "$here/Thresholds/$SWIFT_VERSION.json")
assert_is_number "$max_allowed" "Malformed or nonexistent ${SWIFT_VERSION}.json thresholds file"
info "$test_case: allocations not freed: $not_freed_allocations"
info "$test_case: total number of mallocs: $total_allocations"
info "$test_case: leaked fds: $leaked_fds"
assert_less_than "$not_freed_allocations" 5 # allow some slack
assert_greater_than "$not_freed_allocations" -5 # allow some slack
assert_less_than "$leaked_fds" 1 # No slack allowed here though
assert_less_than "$not_freed_allocations" 5 "Allocations not freed are greater than expected" # allow some slack
assert_greater_than "$not_freed_allocations" -5 "Allocations not freed are less than expected" # allow some slack
assert_less_than "$leaked_fds" 1 "There are leaked file descriptors" # No slack allowed here though
if [[ -z "${!max_allowed_env_name+x}" ]] && [ -z "${max_allowed}" ]; then
if [[ -z "${!max_allowed_env_name+x}" ]]; then
warn "no reference number of allocations set (set to \$$max_allowed_env_name)"
@@ -74,8 +76,8 @@ for test in "${all_tests[@]}"; do
if [ -z "${max_allowed}" ]; then
max_allowed=${!max_allowed_env_name}
fi
assert_less_than_or_equal "$total_allocations" "$max_allowed"
assert_greater_than "$total_allocations" "$(( max_allowed - 1000))"
assert_less_than_or_equal "$total_allocations" "$max_allowed" "Total allocations exceed the max allowed"
assert_greater_than "$total_allocations" "$(( max_allowed - 1000))" "Total allocations are less than expected"
fi
done < <(grep "^test_${test}[^\W]*.total_allocations:" "$tmp/output" | cut -d: -f1 | cut -d. -f1 | sort | uniq)
done
+6 -3
View File
@@ -424,7 +424,8 @@ let package = Package(
"NIOHTTP1",
"NIOFoundationCompat",
"NIOWebSocket",
]
],
swiftSettings: strictConcurrencySettings
),
.executableTarget(
name: "NIOCrashTester",
@@ -435,7 +436,8 @@ let package = Package(
"NIOHTTP1",
"NIOWebSocket",
"NIOFoundationCompat",
]
],
swiftSettings: strictConcurrencySettings
),
.testTarget(
name: "NIOCoreTests",
@@ -498,7 +500,8 @@ let package = Package(
"NIOHTTP1",
"NIOFoundationCompat",
"NIOTestUtils",
]
],
swiftSettings: strictConcurrencySettings
),
.testTarget(
name: "NIOTLSTests",
+20 -8
View File
@@ -25,7 +25,13 @@
/// or constructing it from any other place will crash your program with a precondition as it would be undefined
/// behaviour to do so.
public struct NIOLoopBound<Value>: @unchecked Sendable {
public let _eventLoop: EventLoop
/// The ``EventLoop`` that the value is bound to.
public let eventLoop: EventLoop
@available(*, deprecated, renamed: "eventLoop")
public var _eventLoop: EventLoop {
self.eventLoop
}
@usableFromInline
var _value: Value
@@ -34,7 +40,7 @@ public struct NIOLoopBound<Value>: @unchecked Sendable {
@inlinable
public init(_ value: Value, eventLoop: EventLoop) {
eventLoop.preconditionInEventLoop()
self._eventLoop = eventLoop
self.eventLoop = eventLoop
self._value = value
}
@@ -44,11 +50,11 @@ public struct NIOLoopBound<Value>: @unchecked Sendable {
@inlinable
public var value: Value {
get {
self._eventLoop.preconditionInEventLoop()
self.eventLoop.preconditionInEventLoop()
return self._value
}
_modify {
self._eventLoop.preconditionInEventLoop()
self.eventLoop.preconditionInEventLoop()
yield &self._value
}
}
@@ -72,14 +78,20 @@ public struct NIOLoopBound<Value>: @unchecked Sendable {
/// whilst off the ``EventLoop`` by using ``NIOLoopBoundBox/makeEmptyBox(valueType:eventLoop:)``. Any read/write access to ``value``
/// afterwards will require you to be on `eventLoop`.
public final class NIOLoopBoundBox<Value>: @unchecked Sendable {
public let _eventLoop: EventLoop
/// The ``EventLoop`` that the value is bound to.
public let eventLoop: EventLoop
@available(*, deprecated, renamed: "eventLoop")
public var _eventLoop: EventLoop {
self.eventLoop
}
@usableFromInline
var _value: Value
@inlinable
internal init(_value value: Value, uncheckedEventLoop eventLoop: EventLoop) {
self._eventLoop = eventLoop
self.eventLoop = eventLoop
self._value = value
}
@@ -155,11 +167,11 @@ public final class NIOLoopBoundBox<Value>: @unchecked Sendable {
@inlinable
public var value: Value {
get {
self._eventLoop.preconditionInEventLoop()
self.eventLoop.preconditionInEventLoop()
return self._value
}
_modify {
self._eventLoop.preconditionInEventLoop()
self.eventLoop.preconditionInEventLoop()
yield &self._value
}
}
+10 -8
View File
@@ -13,12 +13,14 @@
//===----------------------------------------------------------------------===//
#if !canImport(Darwin) || os(macOS)
let crashTestSuites: [String: Any] = [
"EventLoopCrashTests": EventLoopCrashTests(),
"ByteBufferCrashTests": ByteBufferCrashTests(),
"SystemCrashTests": SystemCrashTests(),
"HTTPCrashTests": HTTPCrashTests(),
"StrictCrashTests": StrictCrashTests(),
"LoopBoundTests": LoopBoundTests(),
]
func makeCrashTestSuites() -> [String: Any] {
[
"EventLoopCrashTests": EventLoopCrashTests(),
"ByteBufferCrashTests": ByteBufferCrashTests(),
"SystemCrashTests": SystemCrashTests(),
"HTTPCrashTests": HTTPCrashTests(),
"StrictCrashTests": StrictCrashTests(),
"LoopBoundTests": LoopBoundTests(),
]
}
#endif
@@ -82,9 +82,9 @@ struct EventLoopCrashTests {
exit(2)
}
func f() {
el.scheduleTask(in: .nanoseconds(0)) { [f] in
el.assumeIsolated().scheduleTask(in: .nanoseconds(0)) { [f] in
f()
}.futureResult.whenFailure { [f] error in
}.futureResult.assumeIsolated().whenFailure { [f] error in
guard case .some(.shutdown) = error as? EventLoopError else {
exit(3)
}
+6 -2
View File
@@ -76,7 +76,8 @@ func main() throws {
}
func allTestsForSuite(_ testSuite: String) -> [(String, CrashTest)] {
crashTestSuites[testSuite].map { testSuiteObject in
let crashTestSuites = makeCrashTestSuites()
return crashTestSuites[testSuite].map { testSuiteObject in
Mirror(reflecting: testSuiteObject)
.children
.filter { $0.label?.starts(with: "test") ?? false }
@@ -136,7 +137,9 @@ func main() throws {
defer {
try! group.syncShutdownGracefully()
}
signal(SIGPIPE, SIG_IGN)
// explicit return type needed due to https://github.com/apple/swift-nio/issues/3180
let _: ((Int32) -> Void)? = signal(SIGPIPE, SIG_IGN)
func runCrashTest(_ name: String, suite: String, binary: String) throws -> InterpretedRunResult {
guard let crashTest = findCrashTest(name, suite: suite) else {
@@ -199,6 +202,7 @@ func main() throws {
switch CommandLine.arguments.dropFirst().first {
case .some("run-all"):
let crashTestSuites = makeCrashTestSuites()
for testSuite in crashTestSuites {
for test in allTestsForSuite(testSuite.key) {
try runAndEval(test.0, suite: testSuite.key)
@@ -15,10 +15,10 @@ import NIOCore
import NIOEmbedded
final class ChannelPipelineBenchmark: Benchmark {
private final class NoOpHandler: ChannelInboundHandler, RemovableChannelHandler {
private final class NoOpHandler: ChannelInboundHandler, RemovableChannelHandler, Sendable {
typealias InboundIn = Any
}
private final class ConsumingHandler: ChannelInboundHandler, RemovableChannelHandler {
private final class ConsumingHandler: ChannelInboundHandler, RemovableChannelHandler, Sendable {
typealias InboundIn = Any
func channelReadComplete(context: ChannelHandlerContext) {
@@ -28,7 +28,7 @@ final class ChannelPipelineBenchmark: Benchmark {
private let channel: EmbeddedChannel
private let runCount: Int
private let extraHandlers = 4
private var handlers: [RemovableChannelHandler] = []
private var handlers: [RemovableChannelHandler & Sendable] = []
init(runCount: Int) {
self.channel = EmbeddedChannel()
@@ -20,7 +20,6 @@ final class ExecuteBenchmark: Benchmark {
private var group: MultiThreadedEventLoopGroup!
private var loop: EventLoop!
private var dg: DispatchGroup!
private var counter = 0
private let numTasks: Int
init(numTasks: Int) {
@@ -34,10 +33,10 @@ final class ExecuteBenchmark: Benchmark {
// We are preheating the EL to avoid growing the `ScheduledTask` `PriorityQueue`
// during the actual test
try! self.loop.submit {
try! self.loop.submit { [loop, numTasks] in
var counter: Int = 0
for _ in 0..<self.numTasks {
self.loop.scheduleTask(in: .nanoseconds(0)) {
for _ in 0..<numTasks {
loop!.assumeIsolatedUnsafeUnchecked().scheduleTask(in: .nanoseconds(0)) {
counter &+= 1
}
}
@@ -47,19 +46,21 @@ final class ExecuteBenchmark: Benchmark {
func tearDown() {}
func run() -> Int {
try! self.loop.submit {
for _ in 0..<self.numTasks {
self.dg.enter()
let counter = try! self.loop.submit { [dg, loop, numTasks] in
var counter = 0
for _ in 0..<numTasks {
dg!.enter()
self.loop.execute {
self.counter &+= 1
self.dg.leave()
loop!.assumeIsolatedUnsafeUnchecked().execute {
counter &+= 1
dg!.leave()
}
}
return counter
}.wait()
self.dg.wait()
return self.counter
return counter
}
}
@@ -17,7 +17,9 @@ import NIOConcurrencyHelpers
import NIOCore
import NIOPosix
final class NIOLockBenchmark: Benchmark {
final class NIOLockBenchmark: Benchmark, @unchecked Sendable {
// mutable state is protected by the lock
private let numberOfThreads: Int
private let lockOperationsPerThread: Int
private let threadPool: NIOThreadPool
@@ -20,7 +20,6 @@ final class SchedulingAndRunningBenchmark: Benchmark {
private var group: MultiThreadedEventLoopGroup!
private var loop: EventLoop!
private var dg: DispatchGroup!
private var counter = 0
private let numTasks: Int
init(numTasks: Int) {
@@ -34,10 +33,10 @@ final class SchedulingAndRunningBenchmark: Benchmark {
// We are preheating the EL to avoid growing the `ScheduledTask` `PriorityQueue`
// during the actual test
try! self.loop.submit {
try! self.loop.submit { [loop, numTasks] in
var counter: Int = 0
for _ in 0..<self.numTasks {
self.loop.scheduleTask(in: .nanoseconds(0)) {
for _ in 0..<numTasks {
loop!.assumeIsolatedUnsafeUnchecked().scheduleTask(in: .nanoseconds(0)) {
counter &+= 1
}
}
@@ -47,15 +46,17 @@ final class SchedulingAndRunningBenchmark: Benchmark {
func tearDown() {}
func run() -> Int {
try! self.loop.submit {
for _ in 0..<self.numTasks {
self.dg.enter()
let counter = try! self.loop.submit { [dg, loop, numTasks] in
var counter: Int = 0
for _ in 0..<numTasks {
dg!.enter()
self.loop.scheduleTask(in: .nanoseconds(0)) {
self.counter &+= 1
self.dg.leave()
loop!.assumeIsolatedUnsafeUnchecked().scheduleTask(in: .nanoseconds(0)) {
counter &+= 1
dg!.leave()
}
}
return counter
}.wait()
self.dg.wait()
@@ -28,7 +28,7 @@ final class TCPThroughputBenchmark: Benchmark {
private var group: EventLoopGroup!
private var serverChannel: Channel!
private var serverHandler: ServerHandler!
private var serverHandler: NIOLoopBound<ServerHandler>!
private var clientChannel: Channel!
private var message: ByteBuffer!
@@ -39,10 +39,12 @@ final class TCPThroughputBenchmark: Benchmark {
public typealias OutboundOut = ByteBuffer
private let connectionEstablishedPromise: EventLoopPromise<EventLoop>
private let eventLoop: EventLoop
private var context: ChannelHandlerContext!
init(_ connectionEstablishedPromise: EventLoopPromise<EventLoop>) {
init(_ connectionEstablishedPromise: EventLoopPromise<EventLoop>, eventLoop: EventLoop) {
self.connectionEstablishedPromise = connectionEstablishedPromise
self.eventLoop = eventLoop
}
public func channelActive(context: ChannelHandlerContext) {
@@ -114,14 +116,20 @@ final class TCPThroughputBenchmark: Benchmark {
let connectionEstablishedPromise: EventLoopPromise<EventLoop> = self.group.next().makePromise()
let promise = self.group.next().makePromise(of: NIOLoopBound<ServerHandler>.self)
self.serverChannel = try ServerBootstrap(group: self.group)
.childChannelInitializer { channel in
self.serverHandler = ServerHandler(connectionEstablishedPromise)
return channel.pipeline.addHandler(self.serverHandler)
channel.eventLoop.makeCompletedFuture {
let serverHandler = ServerHandler(connectionEstablishedPromise, eventLoop: channel.eventLoop)
promise.succeed(NIOLoopBound(serverHandler, eventLoop: channel.eventLoop))
try channel.pipeline.syncOperations.addHandler(serverHandler)
}
}
.bind(host: "127.0.0.1", port: 0)
.wait()
self.serverHandler = try promise.futureResult.wait()
self.clientChannel = try ClientBootstrap(group: group)
.channelInitializer { channel in
channel.eventLoop.makeCompletedFuture {
@@ -165,7 +173,7 @@ final class TCPThroughputBenchmark: Benchmark {
let messages = self.messages
self.serverEventLoop.execute {
serverHandler.send(message, times: messages)
serverHandler.value.send(message, times: messages)
}
try isDonePromise.futureResult.wait()
return 0
+35 -18
View File
@@ -28,7 +28,7 @@ final class UDPBenchmark {
private var group: EventLoopGroup!
private var server: Channel!
private var client: Channel!
private var clientHandler: EchoHandlerClient!
private var clientHandler: EchoHandlerClient.SendableView!
init(data: ByteBuffer, numberOfRequests: Int, vectorReads: Int, vectorWrites: Int) {
self.data = data
@@ -57,22 +57,25 @@ extension UDPBenchmark: Benchmark {
self.client = try DatagramBootstrap(group: group)
// zero is the same as not applying the option.
.channelOption(.datagramVectorReadMessageCount, value: self.vectorReads)
.channelInitializer { channel in
let handler = EchoHandlerClient(
eventLoop: channel.eventLoop,
config: .init(
remoteAddress: remoteAddress,
request: self.data,
requests: self.numberOfRequests,
writesPerFlush: self.vectorWrites
.channelInitializer { [data, numberOfRequests, vectorWrites] channel in
channel.eventLoop.makeCompletedFuture {
let handler = EchoHandlerClient(
eventLoop: channel.eventLoop,
config: .init(
remoteAddress: remoteAddress,
request: data,
requests: numberOfRequests,
writesPerFlush: vectorWrites
)
)
)
return channel.pipeline.addHandler(handler)
try channel.pipeline.syncOperations.addHandler(handler)
}
}
.bind(to: address)
.wait()
self.clientHandler = try self.client.pipeline.handler(type: EchoHandlerClient.self).wait()
self.clientHandler = try self.client.pipeline.handler(type: EchoHandlerClient.self).map { $0.sendableView }
.wait()
}
func tearDown() {
@@ -87,7 +90,7 @@ extension UDPBenchmark: Benchmark {
}
extension UDPBenchmark {
final class EchoHandler: ChannelInboundHandler {
final class EchoHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = AddressedEnvelope<ByteBuffer>
typealias OutboundOut = AddressedEnvelope<ByteBuffer>
@@ -232,12 +235,26 @@ extension UDPBenchmark {
self.context = nil
}
func run() -> EventLoopFuture<Void> {
let p = self.eventLoop.makePromise(of: Void.self)
self.eventLoop.execute {
self._run(promise: p)
var sendableView: SendableView {
SendableView(handler: self, eventLoop: self.eventLoop)
}
struct SendableView: Sendable {
private let handler: NIOLoopBound<EchoHandlerClient>
private let eventLoop: EventLoop
init(handler: EchoHandlerClient, eventLoop: EventLoop) {
self.handler = NIOLoopBound(handler, eventLoop: eventLoop)
self.eventLoop = eventLoop
}
func run() -> EventLoopFuture<Void> {
let p = self.eventLoop.makePromise(of: Void.self)
self.eventLoop.execute {
self.handler.value._run(promise: p)
}
return p.futureResult
}
return p.futureResult
}
private func _run(promise: EventLoopPromise<Void>) {
@@ -67,9 +67,9 @@ extension WebSocketFrameEncoderBenchmark {
extension WebSocketFrameEncoderBenchmark: Benchmark {
func setUp() throws {
// We want the pipeline walk to have some cost.
try! self.channel.pipeline.addHandler(WriteConsumingHandler()).wait()
try! self.channel.pipeline.syncOperations.addHandler(WriteConsumingHandler())
for _ in 0..<3 {
try! self.channel.pipeline.addHandler(NoOpOutboundHandler()).wait()
try! self.channel.pipeline.syncOperations.addHandler(NoOpOutboundHandler())
}
try! self.channel.pipeline.syncOperations.addHandler(WebSocketFrameEncoder())
self.frame = WebSocketFrame(opcode: .binary, maskKey: self.maskingKey, data: self.data, extensionData: nil)
+56 -34
View File
@@ -14,6 +14,15 @@
// swift-format-ignore: AmbiguousTrailingClosureOverload
// swift-format-ignore: OrderedImports
// Required due to https://github.com/swiftlang/swift/issues/76842
#if canImport(Glibc)
@preconcurrency import Glibc
#elseif canImport(Musl)
@preconcurrency import Musl
#endif
import Dispatch
import NIOCore
import NIOEmbedded
@@ -27,16 +36,21 @@ setbuf(stdout, nil)
// MARK: Test Harness
var warning: String = ""
assert(
{
print("======================================================")
print("= YOU ARE RUNNING NIOPerformanceTester IN DEBUG MODE =")
print("======================================================")
warning = " <<< DEBUG MODE >>>"
return true
}()
)
func makeWarning() -> String {
var warning = ""
assert(
{
print("======================================================")
print("= YOU ARE RUNNING NIOPerformanceTester IN DEBUG MODE =")
print("======================================================")
warning = " <<< DEBUG MODE >>>"
return true
}()
)
return warning
}
let warning = makeWarning()
public func measure(_ fn: () throws -> Int) rethrows -> [Double] {
func measureOne(_ fn: () throws -> Int) rethrows -> Double {
@@ -162,8 +176,9 @@ defer {
let serverChannel = try ServerBootstrap(group: group)
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: true).flatMap {
channel.pipeline.addHandler(SimpleHTTPServer())
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.configureHTTPServerPipeline(withPipeliningAssistance: true)
try channel.pipeline.syncOperations.addHandler(SimpleHTTPServer())
}
}.bind(host: "127.0.0.1", port: 0).wait()
@@ -171,8 +186,7 @@ defer {
try! serverChannel.close().wait()
}
var head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/perf-test-1")
head.headers.add(name: "Host", value: "localhost")
let head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/perf-test-1", headers: ["Host": "localhost"])
final class RepeatedRequests: ChannelInboundHandler {
typealias InboundIn = HTTPClientResponsePart
@@ -183,10 +197,10 @@ final class RepeatedRequests: ChannelInboundHandler {
private var doneRequests = 0
private let isDonePromise: EventLoopPromise<Int>
init(numberOfRequests: Int, eventLoop: EventLoop) {
init(numberOfRequests: Int, isDonePromise: EventLoopPromise<Int>) {
self.remainingNumberOfRequests = numberOfRequests
self.numberOfRequests = numberOfRequests
self.isDonePromise = eventLoop.makePromise()
self.isDonePromise = isDonePromise
}
func wait() throws -> Int {
@@ -204,7 +218,9 @@ final class RepeatedRequests: ChannelInboundHandler {
let reqPart = Self.unwrapInboundIn(data)
if case .end(nil) = reqPart {
if self.remainingNumberOfRequests <= 0 {
context.channel.close().map { self.doneRequests }.cascade(to: self.isDonePromise)
context.channel.close().assumeIsolated().map {
self.doneRequests
}.nonisolated().cascade(to: self.isDonePromise)
} else {
self.doneRequests += 1
self.remainingNumberOfRequests -= 1
@@ -622,7 +638,7 @@ try measureAndPrint(desc: "no-net_http1_1k_reqs_1_conn") {
let channel = context.channel
self.remainingNumberOfRequests -= 1
if self.remainingNumberOfRequests > 0 {
context.eventLoop.execute {
context.eventLoop.assumeIsolated().execute {
self.kickOff(channel: channel)
}
} else {
@@ -644,14 +660,15 @@ try measureAndPrint(desc: "no-net_http1_1k_reqs_1_conn") {
requestsDone = reqs
done = true
}
try channel.pipeline.configureHTTPServerPipeline(
let sync = channel.pipeline.syncOperations
try sync.configureHTTPServerPipeline(
withPipeliningAssistance: true,
withErrorHandling: true
).flatMap {
channel.pipeline.addHandler(SimpleHTTPServer())
}.flatMap {
channel.pipeline.addHandler(measuringHandler, position: .first)
}.wait()
)
try sync.addHandler(SimpleHTTPServer())
try sync.addHandler(measuringHandler, position: .first)
measuringHandler.kickOff(channel: channel)
@@ -664,12 +681,14 @@ try measureAndPrint(desc: "no-net_http1_1k_reqs_1_conn") {
}
measureAndPrint(desc: "http1_1k_reqs_1_conn") {
let repeatedRequestsHandler = RepeatedRequests(numberOfRequests: 1_000, eventLoop: group.next())
let isDone = group.next().makePromise(of: Int.self)
let clientChannel = try! ClientBootstrap(group: group)
.channelInitializer { channel in
channel.pipeline.addHTTPClientHandlers().flatMap {
channel.pipeline.addHandler(repeatedRequestsHandler)
channel.eventLoop.makeCompletedFuture {
let repeatedRequestsHandler = RepeatedRequests(numberOfRequests: 1_000, isDonePromise: isDone)
let sync = channel.pipeline.syncOperations
try sync.addHTTPClientHandlers()
try sync.addHandler(repeatedRequestsHandler)
}
}
.connect(to: serverChannel.localAddress!)
@@ -681,7 +700,7 @@ measureAndPrint(desc: "http1_1k_reqs_1_conn") {
clientChannel.pipeline.syncOperations.writeAndFlush(NIOAny(HTTPClientRequestPart.end(nil)), promise: promise)
return promise.futureResult
}.wait()
return try! repeatedRequestsHandler.wait()
return try! isDone.futureResult.wait()
}
measureAndPrint(desc: "http1_1k_reqs_100_conns") {
@@ -691,12 +710,15 @@ measureAndPrint(desc: "http1_1k_reqs_100_conns") {
let reqsPerConn = numReqs / numConns
reqs.reserveCapacity(reqsPerConn)
for _ in 0..<numConns {
let repeatedRequestsHandler = RepeatedRequests(numberOfRequests: reqsPerConn, eventLoop: group.next())
let isDone = group.next().makePromise(of: Int.self)
let clientChannel = try! ClientBootstrap(group: group)
.channelInitializer { channel in
channel.pipeline.addHTTPClientHandlers().flatMap {
channel.pipeline.addHandler(repeatedRequestsHandler)
channel.eventLoop.makeCompletedFuture {
let repeatedRequestsHandler = RepeatedRequests(numberOfRequests: reqsPerConn, isDonePromise: isDone)
let sync = channel.pipeline.syncOperations
try sync.addHTTPClientHandlers()
try sync.addHandler(repeatedRequestsHandler)
}
}
.connect(to: serverChannel.localAddress!)
@@ -711,7 +733,7 @@ measureAndPrint(desc: "http1_1k_reqs_100_conns") {
)
return promise.futureResult
}.wait()
reqs.append(try! repeatedRequestsHandler.wait())
reqs.append(try! isDone.futureResult.wait())
}
return reqs.reduce(0, +) / numConns
}
@@ -806,7 +828,7 @@ measureAndPrint(desc: "future_reduce_10k_futures") {
let el1 = group.next()
let futures = (1...10_000).map { i in el1.makeSucceededFuture(i) }
return try! EventLoopFuture<Int>.reduce(0, futures, on: el1, +).wait()
return try! EventLoopFuture<Int>.reduce(0, futures, on: el1, { $0 + $1 }).wait()
}
measureAndPrint(desc: "future_reduce_into_10k_futures") {
+160 -81
View File
@@ -13,6 +13,7 @@
//===----------------------------------------------------------------------===//
import Dispatch
import NIOConcurrencyHelpers
import NIOEmbedded
import XCTest
@@ -48,9 +49,25 @@ private final class SuccessfulClientUpgrader: TypedAndUntypedHTTPClientProtocolU
fileprivate let requiredUpgradeHeaders: [String]
fileprivate let upgradeHeaders: [(String, String)]
private(set) var addCustomUpgradeRequestHeadersCallCount = 0
private(set) var shouldAllowUpgradeCallCount = 0
private(set) var upgradeContextResponseCallCount = 0
private struct Counts {
var addCustomUpgradeRequestHeadersCallCount = 0
var shouldAllowUpgradeCallCount = 0
var upgradeContextResponseCallCount = 0
}
private let counts = NIOLockedValueBox(Counts())
var addCustomUpgradeRequestHeadersCallCount: Int {
self.counts.withLockedValue { $0.addCustomUpgradeRequestHeadersCallCount }
}
var shouldAllowUpgradeCallCount: Int {
self.counts.withLockedValue { $0.shouldAllowUpgradeCallCount }
}
var upgradeContextResponseCallCount: Int {
self.counts.withLockedValue { $0.upgradeContextResponseCallCount }
}
fileprivate init(
forProtocol `protocol`: String,
@@ -63,25 +80,33 @@ private final class SuccessfulClientUpgrader: TypedAndUntypedHTTPClientProtocolU
}
fileprivate func addCustom(upgradeRequestHeaders: inout HTTPHeaders) {
self.addCustomUpgradeRequestHeadersCallCount += 1
self.counts.withLockedValue {
$0.addCustomUpgradeRequestHeadersCallCount += 1
}
for (name, value) in self.upgradeHeaders {
upgradeRequestHeaders.replaceOrAdd(name: name, value: value)
}
}
fileprivate func shouldAllowUpgrade(upgradeResponse: HTTPResponseHead) -> Bool {
self.shouldAllowUpgradeCallCount += 1
self.counts.withLockedValue {
$0.shouldAllowUpgradeCallCount += 1
}
return true
}
fileprivate func upgrade(context: ChannelHandlerContext, upgradeResponse: HTTPResponseHead) -> EventLoopFuture<Void>
{
self.upgradeContextResponseCallCount += 1
self.counts.withLockedValue {
$0.upgradeContextResponseCallCount += 1
}
return context.channel.eventLoop.makeSucceededFuture(())
}
func upgrade(channel: any Channel, upgradeResponse: HTTPResponseHead) -> EventLoopFuture<Bool> {
self.upgradeContextResponseCallCount += 1
self.counts.withLockedValue {
$0.upgradeContextResponseCallCount += 1
}
return channel.eventLoop.makeSucceededFuture(true)
}
}
@@ -131,7 +156,11 @@ private final class DenyingClientUpgrader: TypedAndUntypedHTTPClientProtocolUpgr
fileprivate let requiredUpgradeHeaders: [String]
fileprivate let upgradeHeaders: [(String, String)]
private(set) var addCustomUpgradeRequestHeadersCallCount = 0
private let _addCustomUpgradeRequestHeadersCallCount = NIOLockedValueBox(0)
var addCustomUpgradeRequestHeadersCallCount: Int {
self._addCustomUpgradeRequestHeadersCallCount.withLockedValue { $0 }
}
fileprivate init(
forProtocol `protocol`: String,
@@ -145,7 +174,7 @@ private final class DenyingClientUpgrader: TypedAndUntypedHTTPClientProtocolUpgr
}
fileprivate func addCustom(upgradeRequestHeaders: inout HTTPHeaders) {
self.addCustomUpgradeRequestHeadersCallCount += 1
self._addCustomUpgradeRequestHeadersCallCount.withLockedValue { $0 += 1 }
for (name, value) in self.upgradeHeaders {
upgradeRequestHeaders.replaceOrAdd(name: name, value: value)
}
@@ -175,7 +204,7 @@ private final class UpgradeDelayClientUpgrader: TypedAndUntypedHTTPClientProtoco
fileprivate let upgradedHandler = SimpleUpgradedHandler()
private var upgradePromise: EventLoopPromise<Void>?
private let upgradePromise: NIOLockedValueBox<EventLoopPromise<Void>?>
fileprivate init(
forProtocol `protocol`: String,
@@ -185,6 +214,7 @@ private final class UpgradeDelayClientUpgrader: TypedAndUntypedHTTPClientProtoco
self.supportedProtocol = `protocol`
self.requiredUpgradeHeaders = requiredUpgradeHeaders
self.upgradeHeaders = upgradeHeaders
self.upgradePromise = NIOLockedValueBox(nil)
}
fileprivate func addCustom(upgradeRequestHeaders: inout HTTPHeaders) {
@@ -199,37 +229,61 @@ private final class UpgradeDelayClientUpgrader: TypedAndUntypedHTTPClientProtoco
fileprivate func upgrade(context: ChannelHandlerContext, upgradeResponse: HTTPResponseHead) -> EventLoopFuture<Void>
{
self.upgradePromise = context.eventLoop.makePromise()
return self.upgradePromise!.futureResult.flatMap { [pipeline = context.pipeline] in
let promise = context.eventLoop.makePromise(of: Void.self)
self.upgradePromise.withLockedValue {
assert($0 == nil)
$0 = promise
}
return promise.futureResult.flatMap { [pipeline = context.pipeline] in
pipeline.addHandler(self.upgradedHandler)
}
}
func upgrade(channel: any Channel, upgradeResponse: HTTPResponseHead) -> EventLoopFuture<Bool> {
self.upgradePromise = channel.eventLoop.makePromise()
return self.upgradePromise!.futureResult.flatMap {
let promise = channel.eventLoop.makePromise(of: Void.self)
self.upgradePromise.withLockedValue {
assert($0 == nil)
$0 = promise
}
return promise.futureResult.flatMap {
channel.pipeline.addHandler(self.upgradedHandler)
}.map { _ in true }
}
fileprivate func unblockUpgrade() {
self.upgradePromise!.succeed(())
let promise = self.upgradePromise.withLockedValue { $0 }
promise!.succeed()
}
}
private final class SimpleUpgradedHandler: ChannelInboundHandler {
private final class SimpleUpgradedHandler: ChannelInboundHandler, Sendable {
fileprivate typealias InboundIn = ByteBuffer
fileprivate typealias OutboundOut = ByteBuffer
fileprivate var handlerAddedContextCallCount = 0
fileprivate var channelReadContextDataCallCount = 0
private struct Counts {
var handlerAddedContextCallCount = 0
var channelReadContextDataCallCount = 0
}
private let counts = NIOLockedValueBox(Counts())
fileprivate var handlerAddedContextCallCount: Int {
self.counts.withLockedValue { $0.handlerAddedContextCallCount }
}
fileprivate var channelReadContextDataCallCount: Int {
self.counts.withLockedValue { $0.channelReadContextDataCallCount }
}
fileprivate func handlerAdded(context: ChannelHandlerContext) {
self.handlerAddedContextCallCount += 1
self.counts.withLockedValue {
$0.handlerAddedContextCallCount += 1
}
}
fileprivate func channelRead(context: ChannelHandlerContext, data: NIOAny) {
self.channelReadContextDataCallCount += 1
self.counts.withLockedValue {
$0.channelReadContextDataCallCount += 1
}
}
}
@@ -260,7 +314,7 @@ extension ChannelInboundHandler where OutboundOut == HTTPClientRequestPart {
// A HTTP handler that will send a request and then fail if it receives a response or an error.
// It can be used when there is a successful upgrade as the handler should be removed by the upgrader.
private final class ExplodingHTTPHandler: ChannelInboundHandler, RemovableChannelHandler {
private final class ExplodingHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, Sendable {
fileprivate typealias InboundIn = HTTPClientResponsePart
fileprivate typealias OutboundOut = HTTPClientRequestPart
@@ -280,13 +334,27 @@ private final class ExplodingHTTPHandler: ChannelInboundHandler, RemovableChanne
// A HTTP handler that will send an initial request which can be augmented by the upgrade handler.
// It will record which error or response calls it receives so that they can be measured at a later time.
private final class RecordingHTTPHandler: ChannelInboundHandler, RemovableChannelHandler {
private final class RecordingHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, Sendable {
fileprivate typealias InboundIn = HTTPClientResponsePart
fileprivate typealias OutboundOut = HTTPClientRequestPart
fileprivate var channelReadChannelHandlerContextDataCallCount = 0
fileprivate var errorCaughtChannelHandlerContextCallCount = 0
fileprivate var errorCaughtChannelHandlerLatestError: Error?
private struct State {
fileprivate var channelReadChannelHandlerContextDataCallCount = 0
fileprivate var errorCaughtChannelHandlerContextCallCount = 0
fileprivate var errorCaughtChannelHandlerLatestError: Error?
}
private let state = NIOLockedValueBox(State())
fileprivate var channelReadChannelHandlerContextDataCallCount: Int {
self.state.withLockedValue { $0.channelReadChannelHandlerContextDataCallCount }
}
fileprivate var errorCaughtChannelHandlerContextCallCount: Int {
self.state.withLockedValue { $0.errorCaughtChannelHandlerContextCallCount }
}
fileprivate var errorCaughtChannelHandlerLatestError: Error? {
self.state.withLockedValue { $0.errorCaughtChannelHandlerLatestError }
}
fileprivate func channelActive(context: ChannelHandlerContext) {
// We are connected. It's time to send the message to the server to initialise the upgrade dance.
@@ -294,12 +362,16 @@ private final class RecordingHTTPHandler: ChannelInboundHandler, RemovableChanne
}
fileprivate func channelRead(context: ChannelHandlerContext, data: NIOAny) {
self.channelReadChannelHandlerContextDataCallCount += 1
self.state.withLockedValue {
$0.channelReadChannelHandlerContextDataCallCount += 1
}
}
fileprivate func errorCaught(context: ChannelHandlerContext, error: Error) {
self.errorCaughtChannelHandlerContextCallCount += 1
self.errorCaughtChannelHandlerLatestError = error
self.state.withLockedValue {
$0.errorCaughtChannelHandlerContextCallCount += 1
$0.errorCaughtChannelHandlerLatestError = error
}
}
}
@@ -320,7 +392,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
func setUpClientChannel(
clientHTTPHandler: RemovableChannelHandler & Sendable,
clientUpgraders: [any TypedAndUntypedHTTPClientProtocolUpgrader],
_ upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void
_ upgradeCompletionHandler: @escaping @Sendable (ChannelHandlerContext) -> Void
) throws -> EmbeddedChannel {
let channel = EmbeddedChannel()
@@ -352,7 +424,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
let addedUpgradeHeader = "myUpgradeHeader"
let addedUpgradeValue = "upgradeHeader"
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
// This header is not required by the server but we will validate its receipt.
let clientHeaders = [(addedUpgradeHeader, addedUpgradeValue)]
@@ -369,7 +441,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
) { _ in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -416,7 +488,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
XCTAssertEqual(1, clientUpgrader.shouldAllowUpgradeCallCount)
XCTAssertEqual(1, clientUpgrader.upgradeContextResponseCallCount)
XCTAssert(upgradeHandlerCallbackFired)
XCTAssert(upgradeHandlerCallbackFired.withLockedValue { $0 })
}
func testUpgradeWithRequiredHeadersShowsInRequest() throws {
@@ -469,7 +541,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
let addedUpgradeHeader = "myUpgradeHeader"
let addedUpgradeValue = "upgradeHeaderValue"
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
// These headers are not required by the server but we will validate their receipt.
let unusedClientHeaders = [(unusedUpgradeHeader, unusedUpgradeValue)]
@@ -494,7 +566,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
) { (context) in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -526,7 +598,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
XCTAssertEqual(1, clientUpgrader.shouldAllowUpgradeCallCount)
XCTAssertEqual(1, clientUpgrader.upgradeContextResponseCallCount)
XCTAssert(upgradeHandlerCallbackFired)
XCTAssert(upgradeHandlerCallbackFired.withLockedValue { $0 })
XCTAssertNoThrow(
try clientChannel.pipeline
@@ -535,20 +607,26 @@ class HTTPClientUpgradeTestCase: XCTestCase {
}
func testUpgradeCompleteFlush() throws {
final class ChannelReadWriteHandler: ChannelDuplexHandler {
final class ChannelReadWriteHandler: ChannelDuplexHandler, Sendable {
typealias OutboundIn = Any
typealias InboundIn = Any
typealias OutboundOut = Any
var messagesReceived = 0
private let _messagesReceived = NIOLockedValueBox(0)
var messagesReceived: Int {
self._messagesReceived.withLockedValue { $0 }
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
self.messagesReceived += 1
self._messagesReceived.withLockedValue { $0 += 1 }
context.writeAndFlush(data, promise: nil)
}
}
final class AddHandlerClientUpgrader<T: ChannelInboundHandler>: TypedAndUntypedHTTPClientProtocolUpgrader {
final class AddHandlerClientUpgrader<T: ChannelInboundHandler & Sendable>:
TypedAndUntypedHTTPClientProtocolUpgrader, Sendable
{
fileprivate let requiredUpgradeHeaders: [String] = []
fileprivate let supportedProtocol: String
fileprivate let handler: T
@@ -573,7 +651,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
}
}
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
let handler = ChannelReadWriteHandler()
let upgrader = AddHandlerClientUpgrader(forProtocol: "myproto", addingHandler: handler)
let clientChannel = try setUpClientChannel(
@@ -581,7 +659,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
clientUpgraders: [upgrader]
) { (context) in
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -606,7 +684,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
clientChannel.embeddedEventLoop.run()
XCTAssert(upgradeHandlerCallbackFired)
XCTAssert(upgradeHandlerCallbackFired.withLockedValue { $0 })
XCTAssertEqual(handler.messagesReceived, 1)
@@ -621,7 +699,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
func testNoUpgradeAsNoServerUpgrade() throws {
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
let clientUpgrader = ExplodingClientUpgrader(forProtocol: "myProto")
let clientHandler = RecordingHTTPHandler()
@@ -633,7 +711,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
) { _ in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -653,7 +731,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
// Is not an error, just silently remove as there is no upgrade.
XCTAssertEqual(0, clientHandler.errorCaughtChannelHandlerContextCallCount)
XCTAssertFalse(upgradeHandlerCallbackFired)
XCTAssertFalse(upgradeHandlerCallbackFired.withLockedValue { $0 })
XCTAssertNoThrow(
try clientChannel.pipeline
@@ -663,7 +741,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
func testFirstResponseReturnsServerError() throws {
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
let clientUpgrader = ExplodingClientUpgrader(forProtocol: "myProto")
let clientHandler = RecordingHTTPHandler()
@@ -675,7 +753,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
) { _ in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -698,7 +776,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
// Check a separate error is not reported, the error response will be forwarded on.
XCTAssertEqual(0, clientHandler.errorCaughtChannelHandlerContextCallCount)
XCTAssertFalse(upgradeHandlerCallbackFired)
XCTAssertFalse(upgradeHandlerCallbackFired.withLockedValue { $0 })
XCTAssertNoThrow(
try clientChannel.pipeline
@@ -708,7 +786,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
func testUpgradeResponseMissingAllProtocols() throws {
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
let clientUpgrader = ExplodingClientUpgrader(forProtocol: "myProto")
let clientHandler = RecordingHTTPHandler()
@@ -720,7 +798,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
) { _ in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -745,7 +823,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
let reportedError = clientHandler.errorCaughtChannelHandlerLatestError! as! NIOHTTPClientUpgradeError
XCTAssertEqual(NIOHTTPClientUpgradeError.responseProtocolNotFound, reportedError)
XCTAssertFalse(upgradeHandlerCallbackFired)
XCTAssertFalse(upgradeHandlerCallbackFired.withLockedValue { $0 })
XCTAssertNoThrow(
try clientChannel.pipeline
@@ -755,7 +833,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
func testUpgradeOnlyHandlesKnownProtocols() throws {
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
let clientUpgrader = ExplodingClientUpgrader(forProtocol: "myProto")
let clientHandler = RecordingHTTPHandler()
@@ -767,7 +845,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
) { _ in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -792,7 +870,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
let reportedError = clientHandler.errorCaughtChannelHandlerLatestError! as! NIOHTTPClientUpgradeError
XCTAssertEqual(NIOHTTPClientUpgradeError.responseProtocolNotFound, reportedError)
XCTAssertFalse(upgradeHandlerCallbackFired)
XCTAssertFalse(upgradeHandlerCallbackFired.withLockedValue { $0 })
XCTAssertNoThrow(
try clientChannel.pipeline
@@ -804,7 +882,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
let upgradeProtocol = "myProto"
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
let clientUpgrader = DenyingClientUpgrader(forProtocol: upgradeProtocol)
let clientHandler = RecordingHTTPHandler()
@@ -816,7 +894,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
) { _ in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -843,7 +921,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
let reportedError = clientHandler.errorCaughtChannelHandlerLatestError! as! NIOHTTPClientUpgradeError
XCTAssertEqual(NIOHTTPClientUpgradeError.upgraderDeniedUpgrade, reportedError)
XCTAssertFalse(upgradeHandlerCallbackFired)
XCTAssertFalse(upgradeHandlerCallbackFired.withLockedValue { $0 })
XCTAssertNoThrow(
try clientChannel.pipeline
@@ -854,7 +932,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
func testUpgradeIsCaseInsensitive() throws {
let upgradeProtocol = "mYPrOtO123"
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
let clientUpgrader = SuccessfulClientUpgrader(forProtocol: upgradeProtocol)
@@ -865,7 +943,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
) { _ in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -893,7 +971,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
XCTAssertEqual(1, clientUpgrader.shouldAllowUpgradeCallCount)
XCTAssertEqual(1, clientUpgrader.upgradeContextResponseCallCount)
XCTAssert(upgradeHandlerCallbackFired)
XCTAssert(upgradeHandlerCallbackFired.withLockedValue { $0 })
XCTAssertNoThrow(
try clientChannel.pipeline
@@ -906,7 +984,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
func testBuffersInboundDataDuringAddingHandlers() throws {
let upgradeProtocol = "myProto"
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
let clientUpgrader = UpgradeDelayClientUpgrader(forProtocol: upgradeProtocol)
@@ -916,7 +994,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
) { (context) in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -950,7 +1028,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
.assertDoesNotContain(handlerType: ByteToMessageHandler<HTTPResponseDecoder>.self)
)
XCTAssert(upgradeHandlerCallbackFired)
XCTAssert(upgradeHandlerCallbackFired.withLockedValue { $0 })
// Check that the data gets fired to the new handler once it is added.
XCTAssertEqual(1, clientUpgrader.upgradedHandler.handlerAddedContextCallCount)
@@ -966,7 +1044,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
let upgradeProtocol = "myProto"
var errorOnAdditionalChannelWrite: Error?
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
let clientUpgrader = UpgradeDelayClientUpgrader(forProtocol: upgradeProtocol)
let clientHandler = RecordingHTTPHandler()
@@ -977,7 +1055,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
) { (context) in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -989,7 +1067,8 @@ class HTTPClientUpgradeTestCase: XCTestCase {
let promise = clientChannel.eventLoop.makePromise(of: Void.self)
promise.futureResult.whenFailure { error in
// Okay: uses embedded EL.
promise.futureResult.assumeIsolated().whenFailure { error in
errorOnAdditionalChannelWrite = error
}
@@ -1014,7 +1093,7 @@ class HTTPClientUpgradeTestCase: XCTestCase {
clientChannel.embeddedEventLoop.run()
// Check that the upgrade was still successful, despite the interruption.
XCTAssert(upgradeHandlerCallbackFired)
XCTAssert(upgradeHandlerCallbackFired.withLockedValue { $0 })
XCTAssertEqual(1, clientUpgrader.upgradedHandler.handlerAddedContextCallCount)
}
@@ -1107,7 +1186,7 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase {
let loopBoundContext = context.loopBound
try channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 0))
.wait()
upgradeResult.whenSuccess { result in
upgradeResult.assumeIsolated().whenSuccess { result in
if result {
let context = loopBoundContext.value
upgradeCompletionHandler(context)
@@ -1120,7 +1199,7 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase {
// - MARK: The following tests are all overridden from the base class since they slightly differ in behaviour
override func testUpgradeOnlyHandlesKnownProtocols() throws {
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
let clientUpgrader = ExplodingClientUpgrader(forProtocol: "myProto")
let clientHandler = RecordingHTTPHandler()
@@ -1132,7 +1211,7 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase {
) { _ in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -1157,7 +1236,7 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase {
// Check an error is reported
XCTAssertEqual(0, clientHandler.errorCaughtChannelHandlerContextCallCount)
XCTAssertFalse(upgradeHandlerCallbackFired)
XCTAssertFalse(upgradeHandlerCallbackFired.withLockedValue { $0 })
XCTAssertNoThrow(
try clientChannel.pipeline
@@ -1168,7 +1247,7 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase {
override func testUpgradeResponseCanBeRejectedByClientUpgrader() throws {
let upgradeProtocol = "myProto"
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
let clientUpgrader = DenyingClientUpgrader(forProtocol: upgradeProtocol)
let clientHandler = RecordingHTTPHandler()
@@ -1180,7 +1259,7 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase {
) { _ in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -1208,7 +1287,7 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase {
// Check an error is reported
XCTAssertEqual(0, clientHandler.errorCaughtChannelHandlerContextCallCount)
XCTAssertFalse(upgradeHandlerCallbackFired)
XCTAssertFalse(upgradeHandlerCallbackFired.withLockedValue { $0 })
XCTAssertNoThrow(
try clientChannel.pipeline
@@ -1219,7 +1298,7 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase {
override func testFiresOutboundErrorDuringAddingHandlers() throws {
let upgradeProtocol = "myProto"
var errorOnAdditionalChannelWrite: Error?
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
let clientUpgrader = UpgradeDelayClientUpgrader(forProtocol: upgradeProtocol)
let clientHandler = RecordingHTTPHandler()
@@ -1230,7 +1309,7 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase {
) { (context) in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -1242,7 +1321,7 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase {
let promise = clientChannel.eventLoop.makePromise(of: Void.self)
promise.futureResult.whenFailure { error in
promise.futureResult.assumeIsolated().whenFailure { error in
errorOnAdditionalChannelWrite = error
}
@@ -1264,12 +1343,12 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase {
clientChannel.embeddedEventLoop.run()
// Check that the upgrade was still successful, despite the interruption.
XCTAssert(upgradeHandlerCallbackFired)
XCTAssert(upgradeHandlerCallbackFired.withLockedValue { $0 })
XCTAssertEqual(1, clientUpgrader.upgradedHandler.handlerAddedContextCallCount)
}
override func testUpgradeResponseMissingAllProtocols() throws {
var upgradeHandlerCallbackFired = false
let upgradeHandlerCallbackFired = NIOLockedValueBox(false)
let clientUpgrader = ExplodingClientUpgrader(forProtocol: "myProto")
let clientHandler = RecordingHTTPHandler()
@@ -1281,7 +1360,7 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase {
) { _ in
// This is called before the upgrader gets called.
upgradeHandlerCallbackFired = true
upgradeHandlerCallbackFired.withLockedValue { $0 = true }
}
defer {
XCTAssertNoThrow(try clientChannel.finish())
@@ -1306,7 +1385,7 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase {
// Check an error is reported
XCTAssertEqual(0, clientHandler.errorCaughtChannelHandlerContextCallCount)
XCTAssertFalse(upgradeHandlerCallbackFired)
XCTAssertFalse(upgradeHandlerCallbackFired.withLockedValue { $0 })
XCTAssertNoThrow(
try clientChannel.pipeline
@@ -125,7 +125,7 @@ class HTTPDecoderLengthTest: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(HTTPResponseDecoder())))
let handler = ChannelInactiveHandler(eofMechanism)
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler))
// Prime the decoder with a GET and consume it.
XCTAssertTrue(
@@ -197,7 +197,7 @@ class HTTPDecoderLengthTest: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(decoder)))
let handler = MessageEndHandler<HTTPResponseHead, ByteBuffer>()
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler))
// Prime the decoder with a request and consume it.
XCTAssertTrue(
@@ -351,7 +351,7 @@ class HTTPDecoderLengthTest: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(HTTPRequestDecoder())))
let handler = MessageEndHandler<HTTPRequestHead, ByteBuffer>()
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler))
// Send a GET with the appropriate Transfer Encoding header.
XCTAssertThrowsError(
@@ -369,7 +369,7 @@ class HTTPDecoderLengthTest: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(HTTPRequestDecoder())))
let handler = MessageEndHandler<HTTPRequestHead, ByteBuffer>()
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler))
// Send a GET with the appropriate Transfer Encoding header.
XCTAssertNoThrow(
@@ -402,7 +402,7 @@ class HTTPDecoderLengthTest: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(HTTPResponseDecoder())))
let handler = MessageEndHandler<HTTPResponseHead, ByteBuffer>()
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler))
// Prime the decoder with a request and consume it.
XCTAssertTrue(
@@ -458,7 +458,7 @@ class HTTPDecoderLengthTest: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(HTTPResponseDecoder())))
let handler = MessageEndHandler<HTTPResponseHead, ByteBuffer>()
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler))
// Prime the decoder with a request and consume it.
XCTAssertTrue(
@@ -665,7 +665,7 @@ class HTTPDecoderLengthTest: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(HTTPRequestDecoder())))
let handler = MessageEndHandler<HTTPRequestHead, ByteBuffer>()
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler))
// Send a POST without a length field of any kind. This should be a zero-length request,
// so .end should come immediately.
+11 -9
View File
@@ -202,7 +202,7 @@ class HTTPDecoderTest: XCTestCase {
name: "decoder"
)
)
XCTAssertNoThrow(try channel.pipeline.addHandler(Receiver()).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(Receiver()))
var buffer = channel.allocator.buffer(capacity: 64)
buffer.writeStaticString(
@@ -251,8 +251,9 @@ class HTTPDecoderTest: XCTestCase {
let part = Self.unwrapInboundIn(data)
switch part {
case .end:
_ = context.pipeline.removeHandler(self).flatMap { [pipeline = context.pipeline] _ in
pipeline.addHandler(self.collector)
_ = context.pipeline.syncOperations.removeHandler(self).assumeIsolated().flatMapThrowing {
[pipeline = context.pipeline] _ in
try pipeline.syncOperations.addHandler(self.collector)
}
default:
// ignore
@@ -266,7 +267,7 @@ class HTTPDecoderTest: XCTestCase {
name: "decoder"
)
)
XCTAssertNoThrow(try channel.pipeline.addHandler(Receiver()).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(Receiver()))
// This connect call is semantically wrong, but it's how you
// active embedded channels properly right now.
@@ -324,8 +325,9 @@ class HTTPDecoderTest: XCTestCase {
let part = Self.unwrapInboundIn(data)
switch part {
case .end:
_ = context.pipeline.removeHandler(self).flatMap { [pipeline = context.pipeline] _ in
pipeline.addHandler(ByteCollector())
_ = context.pipeline.syncOperations.removeHandler(self).assumeIsolated().flatMapThrowing {
[pipeline = context.pipeline] _ in
try pipeline.syncOperations.addHandler(ByteCollector())
}
break
default:
@@ -341,7 +343,7 @@ class HTTPDecoderTest: XCTestCase {
name: "decoder"
)
)
XCTAssertNoThrow(try channel.pipeline.addHandler(Receiver()).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(Receiver()))
XCTAssertNoThrow(try channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 8888)).wait())
@@ -665,7 +667,7 @@ class HTTPDecoderTest: XCTestCase {
let decoder = HTTPRequestDecoder(leftOverBytesStrategy: leftOverBytesStrategy)
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(decoder)))
XCTAssertNoThrow(try channel.pipeline.addHandler(Receiver()).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(Receiver()))
XCTAssertNoThrow(try channel.writeInbound(buffer))
XCTAssertNoThrow(XCTAssert(try channel.finish().isClean))
}
@@ -695,7 +697,7 @@ class HTTPDecoderTest: XCTestCase {
let receiver = Receiver()
let decoder = ByteToMessageHandler(HTTPRequestDecoder(leftOverBytesStrategy: .forwardBytes))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(decoder))
XCTAssertNoThrow(try channel.pipeline.addHandler(receiver).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(receiver))
XCTAssertNoThrow(try channel.writeInbound(buffer))
let removalFutures = [
channel.pipeline.syncOperations.removeHandler(receiver),
+82 -54
View File
@@ -38,26 +38,29 @@ extension Array where Array.Element == ByteBuffer {
}
}
internal class ArrayAccumulationHandler<T>: ChannelInboundHandler {
// Must be unchecked because of inheritance.
internal class ArrayAccumulationHandler<T>: ChannelInboundHandler, @unchecked Sendable {
typealias InboundIn = T
private var receiveds: [T] = []
private var allDoneBlock: DispatchWorkItem! = nil
private let received: NIOLockedValueBox<[T]>
private let allDoneBlock: DispatchWorkItem
public init(completion: @escaping ([T]) -> Void) {
self.allDoneBlock = DispatchWorkItem { [unowned self] () -> Void in
completion(self.receiveds)
init(completion: @escaping ([T]) -> Void) {
let received = NIOLockedValueBox<[T]>([])
self.received = received
self.allDoneBlock = DispatchWorkItem {
completion(received.withLockedValue { $0 })
}
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
self.receiveds.append(Self.unwrapInboundIn(data))
final func channelRead(context: ChannelHandlerContext, data: NIOAny) {
self.received.withLockedValue { $0.append(Self.unwrapInboundIn(data)) }
}
public func channelUnregistered(context: ChannelHandlerContext) {
final func channelUnregistered(context: ChannelHandlerContext) {
self.allDoneBlock.perform()
}
public func syncWaitForCompletion() {
final func syncWaitForCompletion() {
self.allDoneBlock.wait()
}
}
@@ -124,12 +127,13 @@ class HTTPServerClientTest: XCTestCase {
b.writeString(replyString)
let outbound = self.outboundBody(b)
context.write(Self.wrapOutboundOut(outbound.body)).whenComplete { (_: Result<Void, Error>) in
context.write(Self.wrapOutboundOut(outbound.body)).assumeIsolated().whenComplete {
(_: Result<Void, Error>) in
outbound.destructor()
}
context.write(Self.wrapOutboundOut(.end(nil))).recover { error in
XCTFail("unexpected error \(error)")
}.whenComplete { (_: Result<Void, Error>) in
}.assumeIsolated().whenComplete { (_: Result<Void, Error>) in
let context = loopBoundContext.value
self.sentEnd = true
self.maybeClose(context: context)
@@ -149,13 +153,13 @@ class HTTPServerClientTest: XCTestCase {
let outbound = self.outboundBody(b)
context.write(Self.wrapOutboundOut(outbound.body)).recover { error in
XCTFail("unexpected error \(error)")
}.whenComplete { (_: Result<Void, Error>) in
}.assumeIsolated().whenComplete { (_: Result<Void, Error>) in
outbound.destructor()
}
}
context.write(Self.wrapOutboundOut(.end(nil))).recover { error in
XCTFail("unexpected error \(error)")
}.whenComplete { (_: Result<Void, Error>) in
}.assumeIsolated().whenComplete { (_: Result<Void, Error>) in
let context = loopBoundContext.value
self.sentEnd = true
self.maybeClose(context: context)
@@ -176,7 +180,7 @@ class HTTPServerClientTest: XCTestCase {
let outbound = self.outboundBody(b)
context.write(Self.wrapOutboundOut(outbound.body)).recover { error in
XCTFail("unexpected error \(error)")
}.whenComplete { (_: Result<Void, Error>) in
}.assumeIsolated().whenComplete { (_: Result<Void, Error>) in
outbound.destructor()
}
}
@@ -186,7 +190,7 @@ class HTTPServerClientTest: XCTestCase {
trailers.add(name: "X-Should-Trail", value: "sure")
context.write(Self.wrapOutboundOut(.end(trailers))).recover { error in
XCTFail("unexpected error \(error)")
}.whenComplete { (_: Result<Void, Error>) in
}.assumeIsolated().whenComplete { (_: Result<Void, Error>) in
let context = loopBoundContext.value
self.sentEnd = true
self.maybeClose(context: context)
@@ -206,12 +210,12 @@ class HTTPServerClientTest: XCTestCase {
let outbound = self.outboundBody(buf)
context.writeAndFlush(Self.wrapOutboundOut(outbound.body)).recover { error in
XCTFail("unexpected error \(error)")
}.whenComplete { (_: Result<Void, Error>) in
}.assumeIsolated().whenComplete { (_: Result<Void, Error>) in
outbound.destructor()
}
context.write(Self.wrapOutboundOut(.end(nil))).recover { error in
XCTFail("unexpected error \(error)")
}.whenComplete { (_: Result<Void, Error>) in
}.assumeIsolated().whenComplete { (_: Result<Void, Error>) in
let context = loopBoundContext.value
self.sentEnd = true
self.maybeClose(context: context)
@@ -225,7 +229,7 @@ class HTTPServerClientTest: XCTestCase {
}
context.write(Self.wrapOutboundOut(.end(nil))).recover { error in
XCTFail("unexpected error \(error)")
}.whenComplete { (_: Result<Void, Error>) in
}.assumeIsolated().whenComplete { (_: Result<Void, Error>) in
let context = loopBoundContext.value
self.sentEnd = true
self.maybeClose(context: context)
@@ -238,7 +242,7 @@ class HTTPServerClientTest: XCTestCase {
}
context.write(Self.wrapOutboundOut(.end(nil))).recover { error in
XCTFail("unexpected error \(error)")
}.whenComplete { (_: Result<Void, Error>) in
}.assumeIsolated().whenComplete { (_: Result<Void, Error>) in
let context = loopBoundContext.value
self.sentEnd = true
self.maybeClose(context: context)
@@ -252,12 +256,13 @@ class HTTPServerClientTest: XCTestCase {
b.writeString(replyString)
let outbound = self.outboundBody(b)
context.write(Self.wrapOutboundOut(outbound.body)).whenComplete { (_: Result<Void, Error>) in
context.write(Self.wrapOutboundOut(outbound.body)).assumeIsolated().whenComplete {
(_: Result<Void, Error>) in
outbound.destructor()
}
context.write(Self.wrapOutboundOut(.end(nil))).recover { error in
XCTFail("unexpected error \(error)")
}.whenComplete { (_: Result<Void, Error>) in
}.assumeIsolated().whenComplete { (_: Result<Void, Error>) in
let context = loopBoundContext.value
self.sentEnd = true
self.maybeClose(context: context)
@@ -278,7 +283,7 @@ class HTTPServerClientTest: XCTestCase {
}
context.write(Self.wrapOutboundOut(.end(nil))).recover { error in
XCTFail("unexpected error \(error)")
}.whenComplete { (_: Result<Void, Error>) in
}.assumeIsolated().whenComplete { (_: Result<Void, Error>) in
let context = loopBoundContext.value
self.sentEnd = true
self.maybeClose(context: context)
@@ -318,7 +323,10 @@ class HTTPServerClientTest: XCTestCase {
try testSimpleGet(.fileRegion)
}
private class HTTPClientResponsePartAssertHandler: ArrayAccumulationHandler<HTTPClientResponsePart> {
// @unchecked because of inheritance.
private final class HTTPClientResponsePartAssertHandler: ArrayAccumulationHandler<HTTPClientResponsePart>,
@unchecked Sendable
{
public init(
_ expectedVersion: HTTPVersion,
_ expectedStatus: HTTPResponseStatus,
@@ -375,9 +383,7 @@ class HTTPServerClientTest: XCTestCase {
}
let expectedHeaders = maybeExpectedHeaders ?? HTTPHeaders([("content-length", "14"), ("connection", "close")])
let accumulation = HTTPClientResponsePartAssertHandler(httpVersion, .ok, expectedHeaders, "Hello World!\r\n")
let httpHandler = SimpleHTTPServer(mode)
let serverChannel = try assertNoThrowWithValue(
ServerBootstrap(group: group)
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
@@ -385,8 +391,11 @@ class HTTPServerClientTest: XCTestCase {
// Set the handlers that are appled to the accepted Channels
.childChannelInitializer { channel in
// Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline.
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).flatMap {
channel.pipeline.addHandler(httpHandler)
channel.eventLoop.makeCompletedFuture {
let sync = channel.pipeline.syncOperations
try sync.configureHTTPServerPipeline(withPipeliningAssistance: false)
let httpHandler = SimpleHTTPServer(mode)
try sync.addHandlers(httpHandler)
}
}.bind(host: "127.0.0.1", port: 0).wait()
)
@@ -395,11 +404,14 @@ class HTTPServerClientTest: XCTestCase {
XCTAssertNoThrow(try serverChannel.syncCloseAcceptingAlreadyClosed())
}
let accumulation = HTTPClientResponsePartAssertHandler(httpVersion, .ok, expectedHeaders, "Hello World!\r\n")
let clientChannel = try assertNoThrowWithValue(
ClientBootstrap(group: group)
.channelInitializer { channel in
channel.pipeline.addHTTPClientHandlers().flatMap {
channel.pipeline.addHandler(accumulation)
channel.eventLoop.makeCompletedFuture {
let sync = channel.pipeline.syncOperations
try sync.addHTTPClientHandlers()
try sync.addHandler(accumulation)
}
}
.connect(to: serverChannel.localAddress!)
@@ -410,8 +422,7 @@ class HTTPServerClientTest: XCTestCase {
XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed())
}
var head = HTTPRequestHead(version: httpVersion, method: .GET, uri: uri)
head.headers.add(name: "Host", value: "apple.com")
let head = HTTPRequestHead(version: httpVersion, method: .GET, uri: uri, headers: ["Host": "apple.com"])
try clientChannel.eventLoop.flatSubmit {
let promise = clientChannel.eventLoop.makePromise(of: Void.self)
clientChannel.pipeline.syncOperations.write(NIOAny(HTTPClientRequestPart.head(head)), promise: nil)
@@ -445,7 +456,6 @@ class HTTPServerClientTest: XCTestCase {
let accumulation = HTTPClientResponsePartAssertHandler(.http1_1, .ok, expectedHeaders, "12345678910")
let httpHandler = SimpleHTTPServer(mode)
let serverChannel = try assertNoThrowWithValue(
ServerBootstrap(group: group)
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
@@ -454,7 +464,10 @@ class HTTPServerClientTest: XCTestCase {
.childChannelInitializer { channel in
// Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline.
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).flatMap {
channel.pipeline.addHandler(httpHandler)
channel.eventLoop.makeCompletedFuture {
let httpHandler = SimpleHTTPServer(mode)
return try channel.pipeline.syncOperations.addHandler(httpHandler)
}
}
}.bind(host: "127.0.0.1", port: 0).wait()
)
@@ -478,8 +491,12 @@ class HTTPServerClientTest: XCTestCase {
XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed())
}
var head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/count-to-ten")
head.headers.add(name: "Host", value: "apple.com")
let head = HTTPRequestHead(
version: .http1_1,
method: .GET,
uri: "/count-to-ten",
headers: ["Host": "apple.com"]
)
try clientChannel.eventLoop.flatSubmit {
let promise = clientChannel.eventLoop.makePromise(of: Void.self)
clientChannel.pipeline.syncOperations.write(NIOAny(HTTPClientRequestPart.head(head)), promise: nil)
@@ -511,7 +528,6 @@ class HTTPServerClientTest: XCTestCase {
let accumulation = HTTPClientResponsePartAssertHandler(.http1_1, .ok, expectedHeaders, "Hello World")
let httpHandler = SimpleHTTPServer(.byteBuffer)
let serverChannel = try assertNoThrowWithValue(
ServerBootstrap(group: group)
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
@@ -520,7 +536,10 @@ class HTTPServerClientTest: XCTestCase {
.childChannelInitializer { channel in
// Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline.
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: true).flatMap {
channel.pipeline.addHandler(httpHandler)
channel.eventLoop.makeCompletedFuture {
let httpHandler = SimpleHTTPServer(.byteBuffer)
return try channel.pipeline.syncOperations.addHandler(httpHandler)
}
}
}.bind(host: "127.0.0.1", port: 0).wait()
)
@@ -544,8 +563,12 @@ class HTTPServerClientTest: XCTestCase {
XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed())
}
var head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/zero-length-body-part")
head.headers.add(name: "Host", value: "apple.com")
let head = HTTPRequestHead(
version: .http1_1,
method: .GET,
uri: "/zero-length-body-part",
headers: ["Host": "apple.com"]
)
try clientChannel.eventLoop.flatSubmit {
let promise = clientChannel.eventLoop.makePromise(of: Void.self)
clientChannel.pipeline.syncOperations.write(NIOAny(HTTPClientRequestPart.head(head)), promise: nil)
@@ -580,13 +603,15 @@ class HTTPServerClientTest: XCTestCase {
expectedTrailers
)
let httpHandler = SimpleHTTPServer(mode)
let serverChannel = try assertNoThrowWithValue(
ServerBootstrap(group: group)
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).flatMap {
channel.pipeline.addHandler(httpHandler)
channel.eventLoop.makeCompletedFuture {
let httpHandler = SimpleHTTPServer(mode)
return try channel.pipeline.syncOperations.addHandler(httpHandler)
}
}
}.bind(host: "127.0.0.1", port: 0).wait()
)
@@ -609,8 +634,7 @@ class HTTPServerClientTest: XCTestCase {
XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed())
}
var head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/trailers")
head.headers.add(name: "Host", value: "apple.com")
let head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/trailers", headers: ["Host": "apple.com"])
try clientChannel.eventLoop.flatSubmit {
let promise = clientChannel.eventLoop.makePromise(of: Void.self)
clientChannel.pipeline.syncOperations.write(NIOAny(HTTPClientRequestPart.head(head)), promise: nil)
@@ -647,7 +671,6 @@ class HTTPServerClientTest: XCTestCase {
XCTAssert(expectedSuffix.elementsEqual(actualSuffix))
}
let numBytes = 16 * 1024
let httpHandler = SimpleHTTPServer(mode)
let serverChannel = try assertNoThrowWithValue(
ServerBootstrap(group: group)
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
@@ -656,7 +679,10 @@ class HTTPServerClientTest: XCTestCase {
.childChannelInitializer { channel in
// Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline.
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).flatMap {
channel.pipeline.addHandler(httpHandler)
channel.eventLoop.makeCompletedFuture {
let httpHandler = SimpleHTTPServer(mode)
return try channel.pipeline.syncOperations.addHandler(httpHandler)
}
}
}.bind(host: "127.0.0.1", port: 0).wait()
)
@@ -693,13 +719,15 @@ class HTTPServerClientTest: XCTestCase {
let accumulation = HTTPClientResponsePartAssertHandler(.http1_1, .ok, expectedHeaders, "")
let httpHandler = SimpleHTTPServer(.byteBuffer)
let serverChannel = try assertNoThrowWithValue(
ServerBootstrap(group: group)
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).flatMap {
channel.pipeline.addHandler(httpHandler)
channel.eventLoop.makeCompletedFuture {
let httpHandler = SimpleHTTPServer(.byteBuffer)
return try channel.pipeline.syncOperations.addHandler(httpHandler)
}
}
}.bind(host: "127.0.0.1", port: 0).wait()
)
@@ -722,8 +750,7 @@ class HTTPServerClientTest: XCTestCase {
XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed())
}
var head = HTTPRequestHead(version: .http1_1, method: .HEAD, uri: "/head")
head.headers.add(name: "Host", value: "apple.com")
let head = HTTPRequestHead(version: .http1_1, method: .HEAD, uri: "/head", headers: ["Host": "apple.com"])
try clientChannel.eventLoop.flatSubmit {
let promise = clientChannel.eventLoop.makePromise(of: Void.self)
clientChannel.pipeline.syncOperations.write(NIOAny(HTTPClientRequestPart.head(head)), promise: nil)
@@ -748,13 +775,15 @@ class HTTPServerClientTest: XCTestCase {
let accumulation = HTTPClientResponsePartAssertHandler(.http1_1, .noContent, expectedHeaders, "")
let httpHandler = SimpleHTTPServer(.byteBuffer)
let serverChannel = try assertNoThrowWithValue(
ServerBootstrap(group: group)
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).flatMap {
channel.pipeline.addHandler(httpHandler)
channel.eventLoop.makeCompletedFuture {
let httpHandler = SimpleHTTPServer(.byteBuffer)
return try channel.pipeline.syncOperations.addHandler(httpHandler)
}
}
}.bind(host: "127.0.0.1", port: 0).wait()
)
@@ -776,8 +805,7 @@ class HTTPServerClientTest: XCTestCase {
XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed())
}
var head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/204")
head.headers.add(name: "Host", value: "apple.com")
let head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/204", headers: ["Host": "apple.com"])
try clientChannel.eventLoop.flatSubmit {
let promise = clientChannel.eventLoop.makePromise(of: Void.self)
clientChannel.pipeline.syncOperations.write(NIOAny(HTTPClientRequestPart.head(head)), promise: nil)
@@ -544,7 +544,7 @@ class HTTPServerPipelineHandlerTest: XCTestCase {
}
let handler = VerifyOrderHandler()
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler))
for f in 1...3 {
XCTAssertNoThrow(
@@ -19,7 +19,7 @@ import XCTest
class HTTPServerProtocolErrorHandlerTest: XCTestCase {
func testHandlesBasicErrors() throws {
class CloseOnHTTPErrorHandler: ChannelInboundHandler {
final class CloseOnHTTPErrorHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = Never
func errorCaught(context: ChannelHandlerContext, error: Error) {
@@ -139,11 +139,8 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase {
}
let channel = EmbeddedChannel()
XCTAssertNoThrow(
try channel.pipeline.configureHTTPServerPipeline(withErrorHandling: true).flatMap {
channel.pipeline.addHandler(DelayWriteHandler())
}.wait()
)
XCTAssertNoThrow(try channel.pipeline.syncOperations.configureHTTPServerPipeline(withErrorHandling: true))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(DelayWriteHandler()))
var buffer = channel.allocator.buffer(capacity: 1024)
buffer.writeStaticString("GET / HTTP/1.1\r\n\r\nGET / HTTP/1.1\r\n\r\nGET / HT")
+138 -105
View File
@@ -12,6 +12,7 @@
//
//===----------------------------------------------------------------------===//
import NIOConcurrencyHelpers
import NIOCore
import NIOEmbedded
import XCTest
@@ -115,7 +116,7 @@ private func serverHTTPChannelWithAutoremoval(
group: EventLoopGroup,
pipelining: Bool,
upgraders: [any TypedAndUntypedHTTPServerProtocolUpgrader],
extraHandlers: [ChannelHandler],
extraHandlers: [ChannelHandler & Sendable],
_ upgradeCompletionHandler: @escaping UpgradeCompletionHandler
) throws -> (Channel, EventLoopFuture<Channel>) {
let p = group.next().makePromise(of: Channel.self)
@@ -141,11 +142,11 @@ private class SingleHTTPResponseAccumulator: ChannelInboundHandler {
private var receiveds: [InboundIn] = []
private let allDoneBlock: ([InboundIn]) -> Void
public init(completion: @escaping ([InboundIn]) -> Void) {
init(completion: @escaping ([InboundIn]) -> Void) {
self.allDoneBlock = completion
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let buffer = Self.unwrapInboundIn(data)
self.receiveds.append(buffer)
if let finalBytes = buffer.getBytes(at: buffer.writerIndex - 4, length: 4),
@@ -159,7 +160,7 @@ private class SingleHTTPResponseAccumulator: ChannelInboundHandler {
private class ExplodingHandler: ChannelInboundHandler {
typealias InboundIn = Any
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
XCTFail("Received unexpected read")
}
}
@@ -203,7 +204,7 @@ where UpgradeResult == Bool {}
protocol TypedAndUntypedHTTPServerProtocolUpgrader: HTTPServerProtocolUpgrader {}
#endif
private class ExplodingUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader {
private final class ExplodingUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader, Sendable {
let supportedProtocol: String
let requiredUpgradeHeaders: [String]
@@ -211,12 +212,12 @@ private class ExplodingUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader {
case KABOOM
}
public init(forProtocol `protocol`: String, requiringHeaders: [String] = []) {
init(forProtocol `protocol`: String, requiringHeaders: [String] = []) {
self.supportedProtocol = `protocol`
self.requiredUpgradeHeaders = requiringHeaders
}
public func buildUpgradeResponse(
func buildUpgradeResponse(
channel: Channel,
upgradeRequest: HTTPRequestHead,
initialResponseHeaders: HTTPHeaders
@@ -225,7 +226,7 @@ private class ExplodingUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader {
return channel.eventLoop.makeFailedFuture(Explosion.KABOOM)
}
public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
XCTFail("upgrade called")
return context.eventLoop.makeSucceededFuture(())
}
@@ -236,19 +237,19 @@ private class ExplodingUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader {
}
}
private class UpgraderSaysNo: TypedAndUntypedHTTPServerProtocolUpgrader {
private final class UpgraderSaysNo: TypedAndUntypedHTTPServerProtocolUpgrader, Sendable {
let supportedProtocol: String
let requiredUpgradeHeaders: [String] = []
public enum No: Error {
enum No: Error {
case no
}
public init(forProtocol `protocol`: String) {
init(forProtocol `protocol`: String) {
self.supportedProtocol = `protocol`
}
public func buildUpgradeResponse(
func buildUpgradeResponse(
channel: Channel,
upgradeRequest: HTTPRequestHead,
initialResponseHeaders: HTTPHeaders
@@ -256,7 +257,7 @@ private class UpgraderSaysNo: TypedAndUntypedHTTPServerProtocolUpgrader {
channel.eventLoop.makeFailedFuture(No.no)
}
public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
XCTFail("upgrade called")
return context.eventLoop.makeSucceededFuture(())
}
@@ -267,17 +268,17 @@ private class UpgraderSaysNo: TypedAndUntypedHTTPServerProtocolUpgrader {
}
}
private class SuccessfulUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader {
private final class SuccessfulUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader, Sendable {
let supportedProtocol: String
let requiredUpgradeHeaders: [String]
private let onUpgradeComplete: (HTTPRequestHead) -> Void
private let buildUpgradeResponseFuture: (Channel, HTTPHeaders) -> EventLoopFuture<HTTPHeaders>
private let onUpgradeComplete: @Sendable (HTTPRequestHead) -> Void
private let buildUpgradeResponseFuture: @Sendable (Channel, HTTPHeaders) -> EventLoopFuture<HTTPHeaders>
public init(
init(
forProtocol `protocol`: String,
requiringHeaders headers: [String],
buildUpgradeResponseFuture: @escaping (Channel, HTTPHeaders) -> EventLoopFuture<HTTPHeaders>,
onUpgradeComplete: @escaping (HTTPRequestHead) -> Void
buildUpgradeResponseFuture: @escaping @Sendable (Channel, HTTPHeaders) -> EventLoopFuture<HTTPHeaders>,
onUpgradeComplete: @escaping @Sendable (HTTPRequestHead) -> Void
) {
self.supportedProtocol = `protocol`
self.requiredUpgradeHeaders = headers
@@ -285,10 +286,10 @@ private class SuccessfulUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader {
self.buildUpgradeResponseFuture = buildUpgradeResponseFuture
}
public convenience init(
convenience init(
forProtocol `protocol`: String,
requiringHeaders headers: [String],
onUpgradeComplete: @escaping (HTTPRequestHead) -> Void
onUpgradeComplete: @escaping @Sendable (HTTPRequestHead) -> Void
) {
self.init(
forProtocol: `protocol`,
@@ -298,7 +299,7 @@ private class SuccessfulUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader {
)
}
public func buildUpgradeResponse(
func buildUpgradeResponse(
channel: Channel,
upgradeRequest: HTTPRequestHead,
initialResponseHeaders: HTTPHeaders
@@ -308,7 +309,7 @@ private class SuccessfulUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader {
return self.buildUpgradeResponseFuture(channel, headers)
}
public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
self.onUpgradeComplete(upgradeRequest)
return context.eventLoop.makeSucceededFuture(())
}
@@ -319,14 +320,15 @@ private class SuccessfulUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader {
}
}
private class DelayedUnsuccessfulUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader {
private final class DelayedUnsuccessfulUpgrader: TypedAndUntypedHTTPServerProtocolUpgrader, Sendable {
let supportedProtocol: String
let requiredUpgradeHeaders: [String]
private var upgradePromise: EventLoopPromise<Bool>?
private let upgradePromise: EventLoopPromise<Bool>
init(forProtocol `protocol`: String) {
init(forProtocol `protocol`: String, eventLoop: EventLoop) {
self.supportedProtocol = `protocol`
self.upgradePromise = eventLoop.makePromise()
self.requiredUpgradeHeaders = []
}
@@ -339,36 +341,35 @@ private class DelayedUnsuccessfulUpgrader: TypedAndUntypedHTTPServerProtocolUpgr
}
func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
self.upgradePromise = context.eventLoop.makePromise()
return self.upgradePromise!.futureResult.map { _ in }
self.upgradePromise.futureResult.map { _ in }
}
func unblockUpgrade(withError error: Error) {
self.upgradePromise!.fail(error)
self.upgradePromise.fail(error)
}
func upgrade(channel: Channel, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Bool> {
self.upgradePromise = channel.eventLoop.makePromise(of: Bool.self)
return self.upgradePromise!.futureResult
self.upgradePromise.futureResult
}
}
private class UpgradeDelayer: TypedAndUntypedHTTPServerProtocolUpgrader {
private final class UpgradeDelayer: TypedAndUntypedHTTPServerProtocolUpgrader, Sendable {
let supportedProtocol: String
let requiredUpgradeHeaders: [String] = []
private var upgradePromise: EventLoopPromise<Bool>?
private let upgradePromise: EventLoopPromise<Bool>
private let upgradeRequestedPromise: EventLoopPromise<Void>
/// - Parameters:
/// - protocol: The protocol this upgrader knows how to support.
/// - upgradeRequestedPromise: Will be fulfilled when upgrade() is called
init(forProtocol `protocol`: String, upgradeRequestedPromise: EventLoopPromise<Void>) {
init(forProtocol `protocol`: String, upgradeRequestedPromise: EventLoopPromise<Void>, eventLoop: any EventLoop) {
self.supportedProtocol = `protocol`
self.upgradePromise = eventLoop.makePromise()
self.upgradeRequestedPromise = upgradeRequestedPromise
}
public func buildUpgradeResponse(
func buildUpgradeResponse(
channel: Channel,
upgradeRequest: HTTPRequestHead,
initialResponseHeaders: HTTPHeaders
@@ -378,36 +379,36 @@ private class UpgradeDelayer: TypedAndUntypedHTTPServerProtocolUpgrader {
return channel.eventLoop.makeSucceededFuture(headers)
}
public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
self.upgradePromise = context.eventLoop.makePromise()
func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
upgradeRequestedPromise.succeed()
return self.upgradePromise!.futureResult.map { _ in }
return self.upgradePromise.futureResult.map { _ in }
}
public func unblockUpgrade() {
self.upgradePromise!.succeed(true)
func unblockUpgrade() {
self.upgradePromise.succeed(true)
}
func upgrade(channel: Channel, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Bool> {
self.upgradePromise = channel.eventLoop.makePromise()
self.upgradeRequestedPromise.succeed()
return self.upgradePromise!.futureResult
return self.upgradePromise.futureResult
}
}
private class UpgradeResponseDelayer: HTTPServerProtocolUpgrader {
private final class UpgradeResponseDelayer: HTTPServerProtocolUpgrader, Sendable {
let supportedProtocol: String
let requiredUpgradeHeaders: [String] = []
private var context: ChannelHandlerContext?
private let buildUpgradeResponseHandler: () -> EventLoopFuture<Void>
private let buildUpgradeResponseHandler: @Sendable () -> EventLoopFuture<Void>
public init(forProtocol `protocol`: String, buildUpgradeResponseHandler: @escaping () -> EventLoopFuture<Void>) {
init(
forProtocol `protocol`: String,
buildUpgradeResponseHandler: @escaping @Sendable () -> EventLoopFuture<Void>
) {
self.supportedProtocol = `protocol`
self.buildUpgradeResponseHandler = buildUpgradeResponseHandler
}
public func buildUpgradeResponse(
func buildUpgradeResponse(
channel: Channel,
upgradeRequest: HTTPRequestHead,
initialResponseHeaders: HTTPHeaders
@@ -419,44 +420,55 @@ private class UpgradeResponseDelayer: HTTPServerProtocolUpgrader {
}
}
public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
context.eventLoop.makeSucceededFuture(())
}
}
private class UserEventSaver<EventType>: ChannelInboundHandler {
public typealias InboundIn = Any
public var events: [EventType] = []
private final class UserEventSaver<EventType: Sendable>: ChannelInboundHandler, Sendable {
typealias InboundIn = Any
public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
events.append(event as! EventType)
private let _events = NIOLockedValueBox<[EventType]>([])
var events: [EventType] {
self._events.withLockedValue { $0 }
}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
self._events.withLockedValue { $0.append(event as! EventType) }
context.fireUserInboundEventTriggered(event)
}
}
private class ErrorSaver: ChannelInboundHandler {
public typealias InboundIn = Any
public typealias InboundOut = Any
public var errors: [Error] = []
private final class ErrorSaver: ChannelInboundHandler, Sendable {
typealias InboundIn = Any
typealias InboundOut = Any
public func errorCaught(context: ChannelHandlerContext, error: Error) {
errors.append(error)
private let _errors = NIOLockedValueBox<[any Error]>([])
var errors: [Error] {
self._errors.withLockedValue { $0 }
}
func errorCaught(context: ChannelHandlerContext, error: Error) {
self._errors.withLockedValue { $0.append(error) }
context.fireErrorCaught(error)
}
}
private class DataRecorder<T>: ChannelInboundHandler {
public typealias InboundIn = T
private var data: [T] = []
private final class DataRecorder<T: Sendable>: ChannelInboundHandler, Sendable {
typealias InboundIn = T
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
private let data = NIOLockedValueBox<[T]>([])
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let datum = Self.unwrapInboundIn(data)
self.data.append(datum)
self.data.withLockedValue { $0.append(datum) }
}
// Must be called from inside the event loop on pain of death!
public func receivedData() -> [T] {
self.data
func receivedData() -> [T] {
self.data.withLockedValue { $0 }
}
}
@@ -487,7 +499,7 @@ class HTTPServerUpgradeTestCase: XCTestCase {
fileprivate func setUpTestWithAutoremoval(
pipelining: Bool = false,
upgraders: [any TypedAndUntypedHTTPServerProtocolUpgrader],
extraHandlers: [ChannelHandler],
extraHandlers: [ChannelHandler & Sendable],
notUpgradingHandler: (@Sendable (Channel) -> EventLoopFuture<Bool>)? = nil,
upgradeErrorHandler: (@Sendable (Error) -> Void)? = nil,
_ upgradeCompletionHandler: @escaping UpgradeCompletionHandler
@@ -904,25 +916,34 @@ class HTTPServerUpgradeTestCase: XCTestCase {
func testDelayedUpgradeBehaviour() throws {
let upgradeRequestPromise = Self.eventLoop.makePromise(of: Void.self)
let upgrader = UpgradeDelayer(forProtocol: "myproto", upgradeRequestedPromise: upgradeRequestPromise)
let upgrader = UpgradeDelayer(
forProtocol: "myproto",
upgradeRequestedPromise: upgradeRequestPromise,
eventLoop: Self.eventLoop
)
let (server, client, connectedServer) = try setUpTestWithAutoremoval(
upgraders: [upgrader],
extraHandlers: []
) { context in }
let completePromise = Self.eventLoop.makePromise(of: Void.self)
let clientHandler = SingleHTTPResponseAccumulator { buffers in
let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(
separator: ""
)
assertResponseIs(
response: resultString,
expectedResponseLine: "HTTP/1.1 101 Switching Protocols",
expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]
)
completePromise.succeed(())
let clientHandlerAdded = client.pipeline.eventLoop.submit {
let clientHandler = SingleHTTPResponseAccumulator { buffers in
let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(
separator: ""
)
assertResponseIs(
response: resultString,
expectedResponseLine: "HTTP/1.1 101 Switching Protocols",
expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]
)
completePromise.succeed(())
}
return try client.pipeline.syncOperations.addHandler(clientHandler)
}
XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait())
XCTAssertNoThrow(try clientHandlerAdded.wait())
// This request is safe to upgrade.
let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nConnection: upgrade\r\n\r\n"
@@ -945,7 +966,11 @@ class HTTPServerUpgradeTestCase: XCTestCase {
func testBuffersInboundDataDuringDelayedUpgrade() throws {
let upgradeRequestPromise = Self.eventLoop.makePromise(of: Void.self)
let upgrader = UpgradeDelayer(forProtocol: "myproto", upgradeRequestedPromise: upgradeRequestPromise)
let upgrader = UpgradeDelayer(
forProtocol: "myproto",
upgradeRequestedPromise: upgradeRequestPromise,
eventLoop: Self.eventLoop
)
let dataRecorder = DataRecorder<ByteBuffer>()
let (server, client, _) = try setUpTestWithAutoremoval(
@@ -1000,12 +1025,12 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertNoThrow(try channel.finish())
}
var upgradeRequested = false
let upgradeRequested = NIOLockedValueBox(false)
let delayedPromise = channel.eventLoop.makePromise(of: Void.self)
let delayedUpgrader = UpgradeResponseDelayer(forProtocol: "myproto") {
XCTAssertFalse(upgradeRequested)
upgradeRequested = true
XCTAssertFalse(upgradeRequested.withLockedValue { $0 })
upgradeRequested.withLockedValue { $0 = true }
return delayedPromise.futureResult
}
@@ -1021,7 +1046,7 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertNoThrow(try channel.writeInbound(channel.allocator.buffer(string: request)))
// Upgrade has been requested but not proceeded.
XCTAssertTrue(upgradeRequested)
XCTAssertTrue(upgradeRequested.withLockedValue { $0 })
channel.pipeline.assertContainsUpgrader()
XCTAssertNoThrow(try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)))
@@ -1052,19 +1077,19 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertTrue(try channel.finish().isClean)
}
var upgradingProtocol = ""
let upgradingProtocol = NIOLockedValueBox("")
let failingProtocolPromise = channel.eventLoop.makePromise(of: Void.self)
let failingProtocolUpgrader = UpgradeResponseDelayer(forProtocol: "failingProtocol") {
XCTAssertEqual(upgradingProtocol, "")
upgradingProtocol = "failingProtocol"
XCTAssertEqual(upgradingProtocol.withLockedValue { $0 }, "")
upgradingProtocol.withLockedValue { $0 = "failingProtocol" }
return failingProtocolPromise.futureResult
}
let myprotoPromise = channel.eventLoop.makePromise(of: Void.self)
let myprotoUpgrader = UpgradeResponseDelayer(forProtocol: "myproto") {
XCTAssertEqual(upgradingProtocol, "failingProtocol")
upgradingProtocol = "myproto"
XCTAssertEqual(upgradingProtocol.withLockedValue { $0 }, "failingProtocol")
upgradingProtocol.withLockedValue { $0 = "myproto" }
return myprotoPromise.futureResult
}
@@ -1082,14 +1107,14 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertNoThrow(try channel.writeInbound(channel.allocator.buffer(string: request)))
// Upgrade has been requested but not proceeded for the failing protocol.
XCTAssertEqual(upgradingProtocol, "failingProtocol")
XCTAssertEqual(upgradingProtocol.withLockedValue { $0 }, "failingProtocol")
channel.pipeline.assertContainsUpgrader()
XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound(as: ByteBuffer.self)))
XCTAssertNoThrow(try channel.throwIfErrorCaught())
// Ok, now we'll fail the promise. This will catch an error, but the upgrade won't happen: instead, the second handler will be fired.
failingProtocolPromise.fail(No.no)
XCTAssertEqual(upgradingProtocol, "myproto")
XCTAssertEqual(upgradingProtocol.withLockedValue { $0 }, "myproto")
channel.pipeline.assertContainsUpgrader()
XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound(as: ByteBuffer.self)))
@@ -1118,12 +1143,12 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertTrue(try channel.finish().isClean)
}
var upgradeRequested = false
let upgradeRequested = NIOLockedValueBox(false)
let delayedPromise = channel.eventLoop.makePromise(of: Void.self)
let delayedUpgrader = UpgradeResponseDelayer(forProtocol: "myproto") {
XCTAssertFalse(upgradeRequested)
upgradeRequested = true
XCTAssertFalse(upgradeRequested.withLockedValue { $0 })
upgradeRequested.withLockedValue { $0 = true }
return delayedPromise.futureResult
}
@@ -1139,7 +1164,7 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertNoThrow(try channel.writeInbound(channel.allocator.buffer(string: request)))
// Upgrade has been requested but not proceeded.
XCTAssertTrue(upgradeRequested)
XCTAssertTrue(upgradeRequested.withLockedValue { $0 })
channel.pipeline.assertContainsUpgrader()
XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound(as: ByteBuffer.self)))
XCTAssertNoThrow(try channel.throwIfErrorCaught())
@@ -1182,12 +1207,12 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertTrue(try channel.finish().isClean)
}
var upgradeRequested = false
let upgradeRequested = NIOLockedValueBox(false)
let delayedPromise = channel.eventLoop.makePromise(of: Void.self)
let delayedUpgrader = UpgradeResponseDelayer(forProtocol: "myproto") {
XCTAssertFalse(upgradeRequested)
upgradeRequested = true
XCTAssertFalse(upgradeRequested.withLockedValue { $0 })
upgradeRequested.withLockedValue { $0 = true }
return delayedPromise.futureResult
}
@@ -1205,7 +1230,7 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertNoThrow(try channel.writeInbound(channel.allocator.buffer(string: request)))
// Upgrade has been requested but not proceeded.
XCTAssertTrue(upgradeRequested)
XCTAssertTrue(upgradeRequested.withLockedValue { $0 })
channel.pipeline.assertContainsUpgrader()
XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound(as: ByteBuffer.self)))
XCTAssertNoThrow(try channel.throwIfErrorCaught())
@@ -1446,7 +1471,11 @@ class HTTPServerUpgradeTestCase: XCTestCase {
}
let upgradeRequestPromise = Self.eventLoop.makePromise(of: Void.self)
let delayer = UpgradeDelayer(forProtocol: "myproto", upgradeRequestedPromise: upgradeRequestPromise)
let delayer = UpgradeDelayer(
forProtocol: "myproto",
upgradeRequestedPromise: upgradeRequestPromise,
eventLoop: Self.eventLoop
)
defer {
delayer.unblockUpgrade()
}
@@ -1504,7 +1533,11 @@ class HTTPServerUpgradeTestCase: XCTestCase {
}
let upgradeRequestPromise = Self.eventLoop.makePromise(of: Void.self)
let delayer = UpgradeDelayer(forProtocol: "myproto", upgradeRequestedPromise: upgradeRequestPromise)
let delayer = UpgradeDelayer(
forProtocol: "myproto",
upgradeRequestedPromise: upgradeRequestPromise,
eventLoop: Self.eventLoop
)
defer {
delayer.unblockUpgrade()
}
@@ -1542,7 +1575,7 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertNoThrow(try XCTAssertNil(channel.readInbound(as: ByteBuffer.self)))
// Ok, now we put in a special handler that does a weird readComplete hook thing.
XCTAssertNoThrow(try channel.pipeline.addHandler(ReentrantReadOnChannelReadCompleteHandler()).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ReentrantReadOnChannelReadCompleteHandler()))
// Now we're going to remove the upgrade handler.
XCTAssertNoThrow(try channel.pipeline.removeUpgrader())
@@ -1648,7 +1681,7 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.addHandler(dataRecorder).wait())
// Remove one of the extra handlers.
XCTAssertNoThrow(try channel.pipeline.removeHandler(handlers.last!).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.removeHandler(handlers.last!).wait())
let head = HTTPServerRequestPart.head(
.init(version: .http1_1, method: .GET, uri: "/foo", headers: ["upgrade": "myproto"])
@@ -1723,7 +1756,7 @@ class HTTPServerUpgradeTestCase: XCTestCase {
struct ImAfraidICantDoThatDave: Error {}
let upgrader = DelayedUnsuccessfulUpgrader(forProtocol: "myproto")
let upgrader = DelayedUnsuccessfulUpgrader(forProtocol: "myproto", eventLoop: channel.eventLoop)
let encoder = HTTPResponseEncoder()
let handler = HTTPServerUpgradeHandler(
upgraders: [upgrader],
@@ -1769,7 +1802,7 @@ final class TypedHTTPServerUpgradeTestCase: HTTPServerUpgradeTestCase {
fileprivate override func setUpTestWithAutoremoval(
pipelining: Bool = false,
upgraders: [any TypedAndUntypedHTTPServerProtocolUpgrader],
extraHandlers: [ChannelHandler],
extraHandlers: [ChannelHandler & Sendable],
notUpgradingHandler: (@Sendable (Channel) -> EventLoopFuture<Bool>)? = nil,
upgradeErrorHandler: (@Sendable (Error) -> Void)? = nil,
_ upgradeCompletionHandler: @escaping UpgradeCompletionHandler
+5 -5
View File
@@ -87,7 +87,7 @@ class HTTPTest: XCTestCase {
try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(HTTPRequestDecoder()))
var bodyData: [UInt8]? = nil
var allBodyDatas: [[UInt8]] = []
try channel.pipeline.addHandler(
try channel.pipeline.syncOperations.addHandler(
TestChannelInboundHandler { reqPart in
switch reqPart {
case .head(var req):
@@ -109,7 +109,7 @@ class HTTPTest: XCTestCase {
}
return reqPart
}
).wait()
)
var writeFutures: [EventLoopFuture<Void>] = []
for expected in expecteds {
@@ -143,9 +143,9 @@ class HTTPTest: XCTestCase {
body: body,
trailers: trailers,
sendStrategy: { (reqString, chan) in
var buf = chan.allocator.buffer(capacity: 1024)
buf.writeString(reqString)
return chan.eventLoop.makeSucceededFuture(()).flatMapThrowing {
chan.eventLoop.makeSucceededFuture(()).flatMapThrowing {
var buf = chan.allocator.buffer(capacity: 1024)
buf.writeString(reqString)
try chan.writeInbound(buf)
}
}
@@ -20,7 +20,11 @@ import XCTest
@testable import NIOPosix
public final class AcceptBackoffHandlerTest: XCTestCase {
final class AcceptBackoffHandlerTest: XCTestCase {
@Sendable
static func defaultBackoffProvider(error: IOError) -> TimeAmount? {
AcceptBackoffHandler.defaultBackoffProvider(error: error)
}
private let acceptHandlerName = "AcceptBackoffHandler"
@@ -46,13 +50,17 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
private func assertBackoffRead(error: Int32) throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next() as! SelectableEventLoop
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let readCountHandler = ReadCountHandler()
// Only used from EL
let readCountHandler = try! loop.submit {
NIOLoopBound(ReadCountHandler(), eventLoop: loop)
}.wait()
let serverChannel = try setupChannel(
group: group,
eventLoop: loop,
readCountHandler: readCountHandler,
backoffProvider: { _ in .milliseconds(100) },
errors: [error]
@@ -62,7 +70,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
try serverChannel.eventLoop.submit {
serverChannel.readable()
serverChannel.read()
return readCountHandler.readCount
return readCountHandler.value.readCount
}.wait()
)
@@ -70,7 +78,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
XCTAssertEqual(
1,
try serverChannel.eventLoop.scheduleTask(in: .milliseconds(100)) {
readCountHandler.readCount
readCountHandler.value.readCount
}.futureResult.wait()
)
@@ -79,7 +87,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
2,
try serverChannel.eventLoop.submit {
serverChannel.read()
return readCountHandler.readCount
return readCountHandler.value.readCount
}.wait()
)
@@ -96,13 +104,16 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
private func assertRemoval(read: Bool) throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next() as! SelectableEventLoop
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let readCountHandler = ReadCountHandler()
let readCountHandler = try! loop.submit {
NIOLoopBound(ReadCountHandler(), eventLoop: loop)
}.wait()
let serverChannel = try setupChannel(
group: group,
eventLoop: loop,
readCountHandler: readCountHandler,
backoffProvider: { err in
.hours(1)
@@ -116,7 +127,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
if read {
serverChannel.read()
}
return readCountHandler.readCount
return readCountHandler.value.readCount
}.wait()
)
@@ -127,7 +138,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
XCTAssertEqual(
1,
try serverChannel.eventLoop.submit {
readCountHandler.readCount
readCountHandler.value.readCount
}.wait()
)
} else {
@@ -135,7 +146,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
XCTAssertEqual(
0,
try serverChannel.eventLoop.submit {
readCountHandler.readCount
readCountHandler.value.readCount
}.wait()
)
}
@@ -144,13 +155,16 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
public func testNotScheduleReadIfAlreadyScheduled() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next() as! SelectableEventLoop
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let readCountHandler = ReadCountHandler()
let readCountHandler = try! loop.submit {
NIOLoopBound(ReadCountHandler(), eventLoop: loop)
}.wait()
let serverChannel = try setupChannel(
group: group,
eventLoop: loop,
readCountHandler: readCountHandler,
backoffProvider: { err in
.milliseconds(10)
@@ -163,7 +177,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
serverChannel.readable()
serverChannel.read()
serverChannel.read()
return readCountHandler.readCount
return readCountHandler.value.readCount
}.wait()
)
@@ -172,7 +186,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
XCTAssertEqual(
1,
try serverChannel.eventLoop.scheduleTask(in: .milliseconds(500)) {
readCountHandler.readCount
readCountHandler.value.readCount
}.futureResult.wait()
)
@@ -181,7 +195,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
2,
try serverChannel.eventLoop.submit {
serverChannel.read()
return readCountHandler.readCount
return readCountHandler.value.readCount
}.wait()
)
@@ -190,6 +204,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
public func testChannelInactiveCancelScheduled() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next() as! SelectableEventLoop
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
@@ -212,9 +227,12 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
}
}
let readCountHandler = ReadCountHandler()
let readCountHandler = try! loop.submit {
NIOLoopBound(ReadCountHandler(), eventLoop: loop)
}.wait()
let serverChannel = try setupChannel(
group: group,
eventLoop: loop,
readCountHandler: readCountHandler,
backoffProvider: { err in
.milliseconds(10)
@@ -222,8 +240,12 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
errors: [ENFILE]
)
let inactiveVerificationHandler = InactiveVerificationHandler(promise: serverChannel.eventLoop.makePromise())
XCTAssertNoThrow(try serverChannel.pipeline.addHandler(inactiveVerificationHandler).wait())
let inactivePromise = serverChannel.eventLoop.makePromise(of: Void.self)
let configured = loop.submit {
let inactiveVerificationHandler = InactiveVerificationHandler(promise: inactivePromise)
try serverChannel.pipeline.syncOperations.addHandler(inactiveVerificationHandler)
}
XCTAssertNoThrow(try configured.wait())
XCTAssertEqual(
0,
@@ -232,7 +254,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
serverChannel.read()
// Close the channel, this should also take care of cancel the scheduled read.
serverChannel.close(promise: nil)
return readCountHandler.readCount
return readCountHandler.value.readCount
}.wait()
)
@@ -240,24 +262,27 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
XCTAssertEqual(
0,
try serverChannel.eventLoop.scheduleTask(in: .milliseconds(500)) {
readCountHandler.readCount
readCountHandler.value.readCount
}.futureResult.wait()
)
XCTAssertNoThrow(try inactiveVerificationHandler.waitForInactive())
XCTAssertNoThrow(try inactivePromise.futureResult.wait())
}
public func testSecondErrorUpdateScheduledRead() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next() as! SelectableEventLoop
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let readCountHandler = ReadCountHandler()
let readCountHandler = try! loop.submit {
NIOLoopBound(ReadCountHandler(), eventLoop: loop)
}.wait()
let backoffProviderCalled = ManagedAtomic(0)
let serverChannel = try setupChannel(
group: group,
eventLoop: loop,
readCountHandler: readCountHandler,
backoffProvider: { err in
if backoffProviderCalled.loadThenWrappingIncrement(ordering: .relaxed) == 0 {
@@ -273,7 +298,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
try serverChannel.eventLoop.submit {
serverChannel.readable()
serverChannel.read()
let readCount = readCountHandler.readCount
let readCount = readCountHandler.value.readCount
// Directly trigger a read again without going through the pipeline. This will allow us to use serverChannel.readable()
serverChannel._channelCore.read0()
serverChannel.readable()
@@ -285,7 +310,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
XCTAssertEqual(
0,
try serverChannel.eventLoop.scheduleTask(in: .seconds(1)) {
readCountHandler.readCount
readCountHandler.value.readCount
}.futureResult.wait()
)
@@ -293,7 +318,7 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
XCTAssertEqual(
1,
try serverChannel.eventLoop.scheduleTask(in: .seconds(1)) {
readCountHandler.readCount
readCountHandler.value.readCount
}.futureResult.wait()
)
@@ -327,30 +352,32 @@ public final class AcceptBackoffHandlerTest: XCTestCase {
}
private func setupChannel(
group: EventLoopGroup,
readCountHandler: ReadCountHandler,
backoffProvider: @escaping (IOError) -> TimeAmount? = AcceptBackoffHandler.defaultBackoffProvider,
eventLoop: SelectableEventLoop,
readCountHandler: NIOLoopBound<ReadCountHandler>,
backoffProvider: @escaping @Sendable (IOError) -> TimeAmount? = AcceptBackoffHandlerTest.defaultBackoffProvider,
errors: [Int32]
) throws -> ServerSocketChannel {
let eventLoop = group.next() as! SelectableEventLoop
let socket = try NonAcceptingServerSocket(errors: errors)
let serverChannel = try assertNoThrowWithValue(
ServerSocketChannel(
serverSocket: socket,
eventLoop: eventLoop,
group: group
group: eventLoop
)
)
XCTAssertNoThrow(try serverChannel.setOption(.autoRead, value: false).wait())
XCTAssertNoThrow(
try serverChannel.pipeline.addHandler(readCountHandler).flatMapThrowing { _ in
try serverChannel.pipeline.syncOperations.addHandler(
AcceptBackoffHandler(backoffProvider: backoffProvider),
name: self.acceptHandlerName
)
}.wait()
)
let configured = eventLoop.submit { [acceptHandlerName = self.acceptHandlerName] in
let sync = serverChannel.pipeline.syncOperations
try sync.addHandler(readCountHandler.value)
try sync.addHandler(
AcceptBackoffHandler(backoffProvider: backoffProvider),
name: acceptHandlerName
)
}
XCTAssertNoThrow(try configured.wait())
XCTAssertNoThrow(
try eventLoop.flatSubmit {
+73 -48
View File
@@ -20,41 +20,66 @@ import XCTest
@testable import NIOPosix
class BootstrapTest: XCTestCase {
var group: MultiThreadedEventLoopGroup!
var groupBag: [MultiThreadedEventLoopGroup]? = nil // protected by `self.lock`
let lock = NIOLock()
var group: MultiThreadedEventLoopGroup {
self.state.withLockedValue {
$0.group!
}
}
var groupBag: [MultiThreadedEventLoopGroup]? {
self.state.withLockedValue {
$0.groupBag
}
}
struct State {
var group: MultiThreadedEventLoopGroup?
var groupBag: [MultiThreadedEventLoopGroup]?
init() {
self.group = nil
self.groupBag = nil
}
}
private let state = NIOLockedValueBox<State>(State())
override func setUp() {
XCTAssertNil(self.group)
self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
self.lock.withLock {
XCTAssertNil(self.groupBag)
self.groupBag = []
self.state.withLockedValue {
XCTAssertNil($0.group)
XCTAssertNil($0.groupBag)
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
$0.group = group
$0.groupBag = []
}
}
override func tearDown() {
XCTAssertNoThrow(
try self.lock.withLock {
guard let groupBag = self.groupBag else {
let group = try? assertNoThrowWithValue(
try self.state.withLockedValue { state -> MultiThreadedEventLoopGroup? in
guard let groupBag = state.groupBag else {
XCTFail()
return
return nil
}
for group in groupBag {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
self.groupBag = nil
XCTAssertNotNil(self.group)
state.groupBag = nil
let group = state.group
state.group = nil
XCTAssertNotNil(group)
return group
}
)
XCTAssertNoThrow(try self.group?.syncShutdownGracefully())
self.group = nil
XCTAssertNoThrow(try group?.syncShutdownGracefully())
}
func freshEventLoop() -> EventLoop {
static func freshEventLoop(_ state: NIOLockedValueBox<State>) -> EventLoop {
let group: MultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
self.lock.withLock {
self.groupBag!.append(group)
state.withLockedValue {
$0.groupBag!.append(group)
}
return group.next()
}
@@ -111,23 +136,23 @@ class BootstrapTest: XCTestCase {
}
func testTCPBootstrapsTolerateFuturesFromDifferentEventLoopsReturnedInInitializers() throws {
let childChannelDone = self.freshEventLoop().makePromise(of: Void.self)
let serverChannelDone = self.freshEventLoop().makePromise(of: Void.self)
let childChannelDone = Self.freshEventLoop(self.state).makePromise(of: Void.self)
let serverChannelDone = Self.freshEventLoop(self.state).makePromise(of: Void.self)
let serverChannel = try assertNoThrowWithValue(
ServerBootstrap(group: self.freshEventLoop())
.childChannelInitializer { channel in
ServerBootstrap(group: Self.freshEventLoop(self.state))
.childChannelInitializer { [state] channel in
XCTAssert(channel.eventLoop.inEventLoop)
defer {
childChannelDone.succeed(())
}
return self.freshEventLoop().makeSucceededFuture(())
return Self.freshEventLoop(state).makeSucceededFuture(())
}
.serverChannelInitializer { channel in
.serverChannelInitializer { [state] channel in
XCTAssert(channel.eventLoop.inEventLoop)
defer {
serverChannelDone.succeed(())
}
return self.freshEventLoop().makeSucceededFuture(())
return Self.freshEventLoop(state).makeSucceededFuture(())
}
.bind(host: "127.0.0.1", port: 0)
.wait()
@@ -137,10 +162,10 @@ class BootstrapTest: XCTestCase {
}
let client = try assertNoThrowWithValue(
ClientBootstrap(group: self.freshEventLoop())
.channelInitializer { channel in
ClientBootstrap(group: Self.freshEventLoop(self.state))
.channelInitializer { [state] channel in
XCTAssert(channel.eventLoop.inEventLoop)
return self.freshEventLoop().makeSucceededFuture(())
return Self.freshEventLoop(state).makeSucceededFuture(())
}
.connect(to: serverChannel.localAddress!)
.wait()
@@ -154,10 +179,10 @@ class BootstrapTest: XCTestCase {
func testUDPBootstrapToleratesFuturesFromDifferentEventLoopsReturnedInInitializers() throws {
XCTAssertNoThrow(
try DatagramBootstrap(group: self.freshEventLoop())
.channelInitializer { channel in
try DatagramBootstrap(group: Self.freshEventLoop(self.state))
.channelInitializer { [state] channel in
XCTAssert(channel.eventLoop.inEventLoop)
return self.freshEventLoop().makeSucceededFuture(())
return Self.freshEventLoop(state).makeSucceededFuture(())
}
.bind(host: "127.0.0.1", port: 0)
.wait()
@@ -182,10 +207,10 @@ class BootstrapTest: XCTestCase {
}
XCTAssertNoThrow(
try ClientBootstrap(group: self.freshEventLoop())
.channelInitializer { channel in
try ClientBootstrap(group: Self.freshEventLoop(self.state))
.channelInitializer { [state] channel in
XCTAssert(channel.eventLoop.inEventLoop)
return self.freshEventLoop().makeSucceededFuture(())
return Self.freshEventLoop(state).makeSucceededFuture(())
}
.withConnectedSocket(socketFDs[0])
.wait()
@@ -207,33 +232,33 @@ class BootstrapTest: XCTestCase {
)
}
let childChannelDone = self.freshEventLoop().next().makePromise(of: Void.self)
let serverChannelDone = self.freshEventLoop().next().makePromise(of: Void.self)
let childChannelDone = Self.freshEventLoop(self.state).next().makePromise(of: Void.self)
let serverChannelDone = Self.freshEventLoop(self.state).next().makePromise(of: Void.self)
let serverChannel = try assertNoThrowWithValue(
try ServerBootstrap(group: self.freshEventLoop())
.childChannelInitializer { channel in
try ServerBootstrap(group: Self.freshEventLoop(self.state))
.childChannelInitializer { [state] channel in
XCTAssert(channel.eventLoop.inEventLoop)
defer {
childChannelDone.succeed(())
}
return self.freshEventLoop().makeSucceededFuture(())
return Self.freshEventLoop(state).makeSucceededFuture(())
}
.serverChannelInitializer { channel in
.serverChannelInitializer { [state] channel in
XCTAssert(channel.eventLoop.inEventLoop)
defer {
serverChannelDone.succeed(())
}
return self.freshEventLoop().makeSucceededFuture(())
return Self.freshEventLoop(state).makeSucceededFuture(())
}
.withBoundSocket(socket)
.wait()
)
let client = try assertNoThrowWithValue(
ClientBootstrap(group: self.freshEventLoop())
.channelInitializer { channel in
ClientBootstrap(group: Self.freshEventLoop(self.state))
.channelInitializer { [state] channel in
XCTAssert(channel.eventLoop.inEventLoop)
return self.freshEventLoop().makeSucceededFuture(())
return Self.freshEventLoop(state).makeSucceededFuture(())
}
.connect(to: serverChannel.localAddress!)
.wait()
@@ -452,13 +477,13 @@ class BootstrapTest: XCTestCase {
let eventLoop = self.group.next()
XCTAssertNoThrow(
try eventLoop.submit {
try eventLoop.submit { [group = self.group] in
let pipe = Pipe()
defer {
XCTAssertNoThrow(try pipe.fileHandleForReading.close())
XCTAssertNoThrow(try pipe.fileHandleForWriting.close())
}
return NIOPipeBootstrap(group: self.group)
return NIOPipeBootstrap(group: group)
.takingOwnershipOfDescriptors(
input: dup(pipe.fileHandleForReading.fileDescriptor),
output: dup(pipe.fileHandleForWriting.fileDescriptor)
@@ -817,7 +842,7 @@ private final class WriteStringOnChannelActive: ChannelInboundHandler {
}
}
private final class MakeSureAutoReadIsOffInChannelInitializer: ChannelInboundHandler {
private final class MakeSureAutoReadIsOffInChannelInitializer: ChannelInboundHandler, Sendable {
typealias InboundIn = Channel
func channelActive(context: ChannelHandlerContext) {
+116 -104
View File
@@ -14,6 +14,7 @@
import Atomics
import CNIOLinux
import NIOConcurrencyHelpers
import NIOEmbedded
import NIOPosix
import NIOTestUtils
@@ -76,13 +77,13 @@ extension EmbeddedChannel {
class ChannelPipelineTest: XCTestCase {
class SimpleTypedHandler1: ChannelInboundHandler {
final class SimpleTypedHandler1: ChannelInboundHandler, Sendable {
typealias InboundIn = NIOAny
}
class SimpleTypedHandler2: ChannelInboundHandler {
final class SimpleTypedHandler2: ChannelInboundHandler, Sendable {
typealias InboundIn = NIOAny
}
class SimpleTypedHandler3: ChannelInboundHandler {
final class SimpleTypedHandler3: ChannelInboundHandler, Sendable {
typealias InboundIn = NIOAny
}
@@ -178,7 +179,7 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertFalse(handler.handlerAddedCalled.load(ordering: .relaxed))
XCTAssertFalse(handler.handlerRemovedCalled.load(ordering: .relaxed))
}
XCTAssertThrowsError(try channel.pipeline.addHandler(handler).wait()) { error in
XCTAssertThrowsError(try channel.pipeline.syncOperations.addHandler(handler)) { error in
XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError)
}
}
@@ -203,19 +204,19 @@ class ChannelPipelineTest: XCTestCase {
var buf = channel.allocator.buffer(capacity: 1024)
buf.writeString("hello")
_ = try channel.pipeline.addHandler(
try channel.pipeline.syncOperations.addHandler(
TestChannelOutboundHandler<Int, ByteBuffer> { data in
XCTAssertEqual(1, data)
return buf
}
).wait()
)
_ = try channel.pipeline.addHandler(
try channel.pipeline.syncOperations.addHandler(
TestChannelOutboundHandler<String, Int> { data in
XCTAssertEqual("msg", data)
return 1
}
).wait()
)
XCTAssertNoThrow(try channel.writeAndFlush("msg").wait() as Void)
if let data = try channel.readOutbound(as: ByteBuffer.self) {
@@ -237,13 +238,13 @@ class ChannelPipelineTest: XCTestCase {
ipv4SocketAddress.sin_port = (12345 as in_port_t).bigEndian
let sa = SocketAddress(ipv4SocketAddress, host: "foobar.com")
XCTAssertNoThrow(try channel.pipeline.addHandler(NoBindAllowed()).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(NoBindAllowed()))
XCTAssertNoThrow(
try channel.pipeline.addHandler(
try channel.pipeline.syncOperations.addHandler(
TestChannelOutboundHandler<ByteBuffer, ByteBuffer> { data in
data
}
).wait()
)
)
XCTAssertNoThrow(try channel.connect(to: sa).wait())
@@ -294,9 +295,8 @@ class ChannelPipelineTest: XCTestCase {
let channel = EmbeddedChannel()
let h = FireChannelReadOnRemoveHandler()
_ = try channel.pipeline.addHandler(h).flatMap {
channel.pipeline.removeHandler(h)
}.wait()
try channel.pipeline.syncOperations.addHandler(h)
try channel.pipeline.syncOperations.removeHandler(h).wait()
XCTAssertNoThrow(XCTAssertEqual(Optional<Int>.some(1), try channel.readInbound()))
XCTAssertTrue(try channel.finish().isClean)
@@ -397,16 +397,16 @@ class ChannelPipelineTest: XCTestCase {
}
let channel = EmbeddedChannel()
let loop = channel.eventLoop as! EmbeddedEventLoop
let loop = channel.embeddedEventLoop
loop.run()
try channel.pipeline.addHandler(PrintOutboundAsByteBufferHandler()).wait()
try channel.pipeline.addHandler(MarkingInboundHandler(number: 2)).wait()
try channel.pipeline.addHandler(WriteOnReadHandler()).wait()
try channel.pipeline.addHandler(MarkingOutboundHandler(number: 4)).wait()
try channel.pipeline.addHandler(WriteOnReadHandler()).wait()
try channel.pipeline.addHandler(MarkingInboundHandler(number: 6)).wait()
try channel.pipeline.addHandler(WriteOnReadHandler()).wait()
try channel.pipeline.syncOperations.addHandler(PrintOutboundAsByteBufferHandler())
try channel.pipeline.syncOperations.addHandler(MarkingInboundHandler(number: 2))
try channel.pipeline.syncOperations.addHandler(WriteOnReadHandler())
try channel.pipeline.syncOperations.addHandler(MarkingOutboundHandler(number: 4))
try channel.pipeline.syncOperations.addHandler(WriteOnReadHandler())
try channel.pipeline.syncOperations.addHandler(MarkingInboundHandler(number: 6))
try channel.pipeline.syncOperations.addHandler(WriteOnReadHandler())
try channel.writeInbound([Int]())
loop.run()
@@ -476,11 +476,8 @@ class ChannelPipelineTest: XCTestCase {
weakHandlerContext2 = context
}
weakHandler2 = handler2
XCTAssertNoThrow(
try channel.pipeline.addHandler(handler1).flatMap {
channel.pipeline.addHandler(handler2)
}.wait()
)
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler1))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler2))
}()
XCTAssertNotNil(weakHandler1)
@@ -488,7 +485,7 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertNotNil(weakHandlerContext1)
XCTAssertNotNil(weakHandlerContext2)
XCTAssertNoThrow(try channel.pipeline.removeHandler(weakHandler1!).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.removeHandler(weakHandler1!).wait())
XCTAssertNil(weakHandler1)
XCTAssertNotNil(weakHandler2)
@@ -550,15 +547,15 @@ class ChannelPipelineTest: XCTestCase {
var buffer = channel.allocator.buffer(capacity: 12)
buffer.writeStaticString("hello, world")
XCTAssertNoThrow(try channel.pipeline.addHandler(countHandler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(countHandler))
XCTAssertTrue(try channel.writeInbound(buffer).isEmpty)
XCTAssertEqual(countHandler.intReadCount, 0)
try channel.pipeline.addHandlers(
try channel.pipeline.syncOperations.addHandlers(
TransformByteBufferToStringHandler(),
TransformStringToIntHandler(),
position: .first
).wait()
)
XCTAssertTrue(try channel.writeInbound(buffer).isEmpty)
XCTAssertEqual(countHandler.intReadCount, 1)
}
@@ -570,13 +567,13 @@ class ChannelPipelineTest: XCTestCase {
}
let firstHandler = IndexWritingHandler(1)
XCTAssertNoThrow(try channel.pipeline.addHandler(firstHandler).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(IndexWritingHandler(2)).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(firstHandler))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(IndexWritingHandler(2)))
XCTAssertNoThrow(
try channel.pipeline.addHandler(
try channel.pipeline.syncOperations.addHandler(
IndexWritingHandler(3),
position: .after(firstHandler)
).wait()
)
)
channel.assertReadIndexOrder([1, 3, 2])
@@ -590,13 +587,13 @@ class ChannelPipelineTest: XCTestCase {
}
let secondHandler = IndexWritingHandler(2)
XCTAssertNoThrow(try channel.pipeline.addHandler(IndexWritingHandler(1)).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(secondHandler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(IndexWritingHandler(1)))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(secondHandler))
XCTAssertNoThrow(
try channel.pipeline.addHandler(
try channel.pipeline.syncOperations.addHandler(
IndexWritingHandler(3),
position: .before(secondHandler)
).wait()
)
)
channel.assertReadIndexOrder([1, 3, 2])
@@ -610,13 +607,13 @@ class ChannelPipelineTest: XCTestCase {
}
let secondHandler = IndexWritingHandler(2)
XCTAssertNoThrow(try channel.pipeline.addHandler(IndexWritingHandler(1)).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(secondHandler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(IndexWritingHandler(1)))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(secondHandler))
XCTAssertNoThrow(
try channel.pipeline.addHandler(
try channel.pipeline.syncOperations.addHandler(
IndexWritingHandler(3),
position: .after(secondHandler)
).wait()
)
)
channel.assertReadIndexOrder([1, 2, 3])
@@ -630,13 +627,13 @@ class ChannelPipelineTest: XCTestCase {
}
let firstHandler = IndexWritingHandler(1)
XCTAssertNoThrow(try channel.pipeline.addHandler(firstHandler).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(IndexWritingHandler(2)).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(firstHandler))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(IndexWritingHandler(2)))
XCTAssertNoThrow(
try channel.pipeline.addHandler(
try channel.pipeline.syncOperations.addHandler(
IndexWritingHandler(3),
position: .before(firstHandler)
).wait()
)
)
channel.assertReadIndexOrder([3, 1, 2])
@@ -652,15 +649,15 @@ class ChannelPipelineTest: XCTestCase {
}
let handler = IndexWritingHandler(1)
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler))
XCTAssertNoThrow(try channel.close().wait())
channel.embeddedEventLoop.run()
XCTAssertThrowsError(
try channel.pipeline.addHandler(
try channel.pipeline.syncOperations.addHandler(
IndexWritingHandler(2),
position: .after(handler)
).wait()
)
) { error in
XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError)
}
@@ -675,15 +672,15 @@ class ChannelPipelineTest: XCTestCase {
}
let handler = IndexWritingHandler(1)
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler))
XCTAssertNoThrow(try channel.close().wait())
channel.embeddedEventLoop.run()
XCTAssertThrowsError(
try channel.pipeline.addHandler(
try channel.pipeline.syncOperations.addHandler(
IndexWritingHandler(2),
position: .before(handler)
).wait()
)
) { error in
XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError)
}
@@ -712,8 +709,8 @@ class ChannelPipelineTest: XCTestCase {
let h1 = TypeAHandler()
let h2 = TypeBHandler()
XCTAssertNoThrow(try channel.pipeline.addHandler(h1).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(h2).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(h1))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(h2))
XCTAssertTrue(try h1 === channel.pipeline.syncOperations.context(handlerType: TypeAHandler.self).handler)
XCTAssertTrue(try h2 === channel.pipeline.syncOperations.context(handlerType: TypeBHandler.self).handler)
@@ -736,8 +733,8 @@ class ChannelPipelineTest: XCTestCase {
let h1 = TestHandler()
let h2 = TestHandler()
XCTAssertNoThrow(try channel.pipeline.addHandler(h1).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(h2).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(h1))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(h2))
XCTAssertTrue(try h1 === channel.pipeline.syncOperations.context(handlerType: TestHandler.self).handler)
XCTAssertFalse(try h2 === channel.pipeline.syncOperations.context(handlerType: TestHandler.self).handler)
@@ -788,7 +785,7 @@ class ChannelPipelineTest: XCTestCase {
class NoOpHandler: ChannelInboundHandler, RemovableChannelHandler {
typealias InboundIn = Never
}
class DummyError: Error {}
struct DummyError: Error {}
let channel = EmbeddedChannel()
defer {
@@ -796,7 +793,7 @@ class ChannelPipelineTest: XCTestCase {
_ = try? channel.finish()
}
XCTAssertNoThrow(try channel.pipeline.addHandler(NoOpHandler()).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(NoOpHandler()))
let context = try assertNoThrowWithValue(channel.pipeline.syncOperations.context(handlerType: NoOpHandler.self))
@@ -805,7 +802,7 @@ class ChannelPipelineTest: XCTestCase {
let removalPromise = channel.eventLoop.makePromise(of: Void.self)
let loopBoundContext = context.loopBound
removalPromise.futureResult.whenSuccess {
removalPromise.futureResult.assumeIsolated().whenSuccess {
let context = loopBoundContext.value
context.writeAndFlush(NIOAny(buffer), promise: nil)
context.fireErrorCaught(DummyError())
@@ -828,10 +825,10 @@ class ChannelPipelineTest: XCTestCase {
}
func testRemovingByContextWithFutureNotInChannel() throws {
class NoOpHandler: ChannelInboundHandler {
final class NoOpHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = Never
}
class DummyError: Error {}
struct DummyError: Error {}
let channel = EmbeddedChannel()
defer {
@@ -849,7 +846,7 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound()))
XCTAssertNoThrow(try channel.throwIfErrorCaught())
let loopBoundContext = context.loopBound
channel.pipeline.syncOperations.removeHandler(context: context).whenSuccess {
channel.pipeline.syncOperations.removeHandler(context: context).assumeIsolated().whenSuccess {
let context = loopBoundContext.value
context.writeAndFlush(NIOAny(buffer), promise: nil)
context.fireErrorCaught(DummyError())
@@ -862,7 +859,7 @@ class ChannelPipelineTest: XCTestCase {
class NoOpHandler: ChannelInboundHandler, RemovableChannelHandler {
typealias InboundIn = Never
}
class DummyError: Error {}
struct DummyError: Error {}
let channel = EmbeddedChannel()
defer {
@@ -870,7 +867,7 @@ class ChannelPipelineTest: XCTestCase {
_ = try? channel.finish()
}
XCTAssertNoThrow(try channel.pipeline.addHandler(NoOpHandler(), name: "TestHandler").wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(NoOpHandler(), name: "TestHandler"))
let context = try assertNoThrowWithValue(channel.pipeline.syncOperations.context(handlerType: NoOpHandler.self))
@@ -879,7 +876,7 @@ class ChannelPipelineTest: XCTestCase {
let removalPromise = channel.eventLoop.makePromise(of: Void.self)
let loopBoundContext = context.loopBound
removalPromise.futureResult.map {
removalPromise.futureResult.assumeIsolated().map {
let context = loopBoundContext._value
context.writeAndFlush(NIOAny(buffer), promise: nil)
context.fireErrorCaught(DummyError())
@@ -902,7 +899,7 @@ class ChannelPipelineTest: XCTestCase {
class NoOpHandler: ChannelInboundHandler {
typealias InboundIn = Never
}
class DummyError: Error {}
struct DummyError: Error {}
let channel = EmbeddedChannel()
defer {
@@ -910,7 +907,7 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertTrue(try channel.finish().isClean)
}
XCTAssertNoThrow(try channel.pipeline.addHandler(NoOpHandler(), name: "TestHandler").wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(NoOpHandler(), name: "TestHandler"))
let context = try assertNoThrowWithValue(channel.pipeline.syncOperations.context(handlerType: NoOpHandler.self))
@@ -920,7 +917,7 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound()))
XCTAssertNoThrow(try channel.throwIfErrorCaught())
let loopBoundContext = context.loopBound
channel.pipeline.removeHandler(name: "TestHandler").whenSuccess {
channel.pipeline.removeHandler(name: "TestHandler").assumeIsolated().whenSuccess {
let context = loopBoundContext.value
context.writeAndFlush(NIOAny(buffer), promise: nil)
context.fireErrorCaught(DummyError())
@@ -933,7 +930,7 @@ class ChannelPipelineTest: XCTestCase {
class NoOpHandler: ChannelInboundHandler, RemovableChannelHandler {
typealias InboundIn = Never
}
class DummyError: Error {}
struct DummyError: Error {}
let channel = EmbeddedChannel()
defer {
@@ -942,7 +939,7 @@ class ChannelPipelineTest: XCTestCase {
}
let handler = NoOpHandler()
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler))
let context = try assertNoThrowWithValue(channel.pipeline.syncOperations.context(handlerType: NoOpHandler.self))
@@ -951,7 +948,7 @@ class ChannelPipelineTest: XCTestCase {
let removalPromise = channel.eventLoop.makePromise(of: Void.self)
let loopBoundContext = context.loopBound
removalPromise.futureResult.whenSuccess {
removalPromise.futureResult.assumeIsolated().whenSuccess {
let context = loopBoundContext.value
context.writeAndFlush(NIOAny(buffer), promise: nil)
context.fireErrorCaught(DummyError())
@@ -959,7 +956,7 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound()))
XCTAssertNoThrow(try channel.throwIfErrorCaught())
channel.pipeline.removeHandler(handler, promise: removalPromise)
channel.pipeline.syncOperations.removeHandler(handler, promise: removalPromise)
XCTAssertNoThrow(XCTAssertEqual(try channel.readOutbound(), buffer))
@@ -972,7 +969,7 @@ class ChannelPipelineTest: XCTestCase {
class NoOpHandler: ChannelInboundHandler, RemovableChannelHandler {
typealias InboundIn = Never
}
class DummyError: Error {}
struct DummyError: Error {}
let channel = EmbeddedChannel()
defer {
@@ -981,7 +978,7 @@ class ChannelPipelineTest: XCTestCase {
}
let handler = NoOpHandler()
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler))
let context = try assertNoThrowWithValue(channel.pipeline.syncOperations.context(handlerType: NoOpHandler.self))
@@ -991,7 +988,7 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound()))
XCTAssertNoThrow(try channel.throwIfErrorCaught())
let loopBoundContext = context.loopBound
channel.pipeline.removeHandler(handler).whenSuccess {
channel.pipeline.syncOperations.removeHandler(handler).assumeIsolated().whenSuccess {
let context = loopBoundContext.value
context.writeAndFlush(NIOAny(buffer), promise: nil)
context.fireErrorCaught(DummyError())
@@ -1001,7 +998,7 @@ class ChannelPipelineTest: XCTestCase {
}
func testFireChannelReadInInactiveChannelDoesNotCrash() throws {
class FireWhenInactiveHandler: ChannelInboundHandler {
final class FireWhenInactiveHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = ()
typealias InboundOut = ()
@@ -1116,14 +1113,16 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertNoThrow(XCTAssertTrue(try channel.finish().isClean))
}
let allHandlers = [Handler(), Handler(), Handler()]
XCTAssertNoThrow(try channel.pipeline.addHandler(allHandlers[0], name: "the first one to remove").wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(allHandlers[1]).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(allHandlers[2], name: "the last one to remove").wait())
XCTAssertNoThrow(
try channel.pipeline.syncOperations.addHandler(allHandlers[0], name: "the first one to remove")
)
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(allHandlers[1]))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(allHandlers[2], name: "the last one to remove"))
let lastContext = try! channel.pipeline.syncOperations.context(name: "the last one to remove")
XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "the first one to remove").wait())
XCTAssertNoThrow(try channel.pipeline.removeHandler(allHandlers[1]).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.removeHandler(allHandlers[1]).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.removeHandler(context: lastContext).wait())
for handler in allHandlers {
@@ -1159,9 +1158,13 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertNoThrow(XCTAssertTrue(try channel.finish().isClean))
}
let allHandlers = [Handler(), Handler(), Handler()]
XCTAssertNoThrow(try channel.pipeline.addHandler(allHandlers[0], name: "the first one to remove").wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(allHandlers[1], name: "the second one to remove").wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(allHandlers[2], name: "the last one to remove").wait())
XCTAssertNoThrow(
try channel.pipeline.syncOperations.addHandler(allHandlers[0], name: "the first one to remove")
)
XCTAssertNoThrow(
try channel.pipeline.syncOperations.addHandler(allHandlers[1], name: "the second one to remove")
)
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(allHandlers[2], name: "the last one to remove"))
let firstContext = try! channel.pipeline.syncOperations.context(name: "the first one to remove")
let secondContext = try! channel.pipeline.syncOperations.context(name: "the second one to remove")
@@ -1188,8 +1191,8 @@ class ChannelPipelineTest: XCTestCase {
}
let allHandlers = [NonRemovableHandler(), NonRemovableHandler(), NonRemovableHandler()]
XCTAssertNoThrow(try channel.pipeline.addHandler(allHandlers[0], name: "1").wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(allHandlers[1], name: "2").wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(allHandlers[0], name: "1"))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(allHandlers[1], name: "2"))
let lastContext = try! channel.pipeline.syncOperations.context(name: "1")
@@ -1226,12 +1229,12 @@ class ChannelPipelineTest: XCTestCase {
let i = Handler()
let j = Handler()
XCTAssertNoThrow(try channel.pipeline.addHandler(c).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(h).wait())
XCTAssertNoThrow(try channel.pipeline.addHandlers([d, e], position: .after(c)).wait())
XCTAssertNoThrow(try channel.pipeline.addHandlers([f, g], position: .before(h)).wait())
XCTAssertNoThrow(try channel.pipeline.addHandlers([a, b], position: .first).wait())
XCTAssertNoThrow(try channel.pipeline.addHandlers([i, j], position: .last).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(c))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(h))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandlers([d, e], position: .after(c)))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandlers([f, g], position: .before(h)))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandlers([a, b], position: .first))
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandlers([i, j], position: .last))
Handler.allHandlers = []
channel.pipeline.fireUserInboundEventTriggered(())
@@ -1264,7 +1267,7 @@ class ChannelPipelineTest: XCTestCase {
<no handlers>
"""
)
XCTAssertNoThrow(try channel.pipeline.addHandlers([parser, serializer, handler]).wait())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandlers([parser, serializer, handler]))
XCTAssertEqual(
channel.pipeline.debugDescription,
"""
@@ -1326,10 +1329,10 @@ class ChannelPipelineTest: XCTestCase {
switch step {
case .triggerEventRead:
// Step 1: Okay, let's kick off the manual removal (it won't complete)
context.pipeline.removeHandler(self).map {
context.pipeline.syncOperations.removeHandler(self).assumeIsolated().map {
// When the manual removal completes, we advance the state.
self.state.next()
}.cascade(to: self.allDonePromise)
}.nonisolated().cascade(to: self.allDonePromise)
default:
XCTFail("channelRead called in state \(self.state)")
}
@@ -1432,16 +1435,16 @@ class ChannelPipelineTest: XCTestCase {
removalTriggeredPromise: removalTriggeredPromise,
continueRemovalFuture: continueRemovalPromise.futureResult
)
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
let removal1Future = channel.pipeline.removeHandler(handler)
XCTAssertThrowsError(try channel.pipeline.removeHandler(handler).wait()) { error in
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(handler))
let removal1Future = channel.pipeline.syncOperations.removeHandler(handler)
XCTAssertThrowsError(try channel.pipeline.syncOperations.removeHandler(handler).wait()) { error in
XCTAssert(
error is NIOAttemptedToRemoveHandlerMultipleTimesError,
"unexpected error: \(error)"
)
}
continueRemovalPromise.succeed(())
XCTAssertThrowsError(try channel.pipeline.removeHandler(handler).wait()) { error in
XCTAssertThrowsError(try channel.pipeline.syncOperations.removeHandler(handler).wait()) { error in
XCTAssertEqual(.notFound, error as? ChannelPipelineError, "unexpected error: \(error)")
}
XCTAssertNoThrow(try removal1Future.wait())
@@ -1899,7 +1902,7 @@ class ChannelPipelineTest: XCTestCase {
for (expectedBufferedByte, handler) in zip(expectedBufferedBytes, handlers) {
let expectedRemaining = total - expectedBufferedByte
channel.pipeline.removeHandler(handler).flatMap { _ in
channel.pipeline.syncOperations.removeHandler(handler).flatMap { _ in
channel.pipeline.inboundBufferedBytes()
}.and(value: expectedRemaining).whenSuccess { (remaining, expectedRemaining) in
XCTAssertEqual(remaining, expectedRemaining)
@@ -1955,7 +1958,7 @@ class ChannelPipelineTest: XCTestCase {
for (expectedBufferedByte, handler) in zip(expectedBufferedBytes, handlers) {
let expectedRemaining = total - expectedBufferedByte
channel.pipeline.removeHandler(handler).flatMap { _ in
channel.pipeline.syncOperations.removeHandler(handler).flatMap { _ in
channel.pipeline.outboundBufferedBytes()
}.and(value: expectedRemaining).whenSuccess { (remaining, expectedRemaining) in
XCTAssertEqual(remaining, expectedRemaining)
@@ -2823,16 +2826,25 @@ class ChannelPipelineTest: XCTestCase {
}
// this should be within `testAddMultipleHandlers` but https://bugs.swift.org/browse/SR-9956
final class TestAddMultipleHandlersHandlerWorkingAroundSR9956: ChannelDuplexHandler, Equatable {
final class TestAddMultipleHandlersHandlerWorkingAroundSR9956: ChannelDuplexHandler, Equatable, Sendable {
typealias InboundIn = Never
typealias OutboundIn = Never
static var allHandlers: [TestAddMultipleHandlersHandlerWorkingAroundSR9956] = []
static let _allHandlers = NIOLockedValueBox<[TestAddMultipleHandlersHandlerWorkingAroundSR9956]>([])
static var allHandlers: [TestAddMultipleHandlersHandlerWorkingAroundSR9956] {
get {
Self._allHandlers.withLockedValue { $0 }
}
set {
Self._allHandlers.withLockedValue { $0 = newValue }
}
}
init() {}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
TestAddMultipleHandlersHandlerWorkingAroundSR9956.allHandlers.append(self)
Self.allHandlers.append(self)
context.fireUserInboundEventTriggered(event)
}
+180 -130
View File
@@ -73,28 +73,39 @@ class ChannelLifecycleHandler: ChannelInboundHandler {
}
}
public final class ChannelTests: XCTestCase {
final class ChannelTests: XCTestCase {
func testBasicLifecycle() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next()
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let serverAcceptedChannelPromise = group.next().makePromise(of: Channel.self)
let serverLifecycleHandler = ChannelLifecycleHandler()
let serverAcceptedChannelPromise = loop.makePromise(of: Channel.self)
let serverLifecycleHandler = try loop.submit {
NIOLoopBound(ChannelLifecycleHandler(), eventLoop: loop)
}.wait()
let serverChannel = try assertNoThrowWithValue(
ServerBootstrap(group: group)
ServerBootstrap(group: loop)
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
serverAcceptedChannelPromise.succeed(channel)
return channel.pipeline.addHandler(serverLifecycleHandler)
return channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandler(serverLifecycleHandler.value)
}
}.bind(host: "127.0.0.1", port: 0).wait()
)
let clientLifecycleHandler = ChannelLifecycleHandler()
let clientLifecycleHandler = try loop.submit {
NIOLoopBound(ChannelLifecycleHandler(), eventLoop: loop)
}.wait()
let clientChannel = try assertNoThrowWithValue(
ClientBootstrap(group: group)
.channelInitializer({ (channel: Channel) in channel.pipeline.addHandler(clientLifecycleHandler) })
ClientBootstrap(group: loop)
.channelInitializer { channel in
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandler(clientLifecycleHandler.value)
}
}
.connect(to: serverChannel.localAddress!).wait()
)
@@ -114,16 +125,16 @@ public final class ChannelTests: XCTestCase {
clientChannel.closeFuture,
serverAcceptedChannel.closeFuture,
],
on: group.next()
on: loop
).map {
XCTAssertEqual(clientLifecycleHandler.currentState, .unregistered)
XCTAssertEqual(serverLifecycleHandler.currentState, .unregistered)
XCTAssertEqual(clientLifecycleHandler.value.currentState, .unregistered)
XCTAssertEqual(serverLifecycleHandler.value.currentState, .unregistered)
XCTAssertEqual(
clientLifecycleHandler.stateHistory,
clientLifecycleHandler.value.stateHistory,
[.unregistered, .registered, .active, .inactive, .unregistered]
)
XCTAssertEqual(
serverLifecycleHandler.stateHistory,
serverLifecycleHandler.value.stateHistory,
[.unregistered, .registered, .active, .inactive, .unregistered]
)
}.wait()
@@ -1247,7 +1258,7 @@ public final class ChannelTests: XCTestCase {
_ = pwm.add(data: .byteBuffer(buffer), promise: ps[2])
XCTAssertEqual(Int64(buffer.readableBytes * 3), pwm.bufferedBytes)
ps[0].futureResult.whenComplete { (_: Result<Void, Error>) in
ps[0].futureResult.assumeIsolated().whenComplete { (_: Result<Void, Error>) in
pwm.failAll(error: ChannelError.inputClosed, close: true)
}
@@ -1415,15 +1426,19 @@ public final class ChannelTests: XCTestCase {
try server.bind(to: SocketAddress.makeAddressResolvingHost("127.0.0.1", port: 0))
try server.listen()
let byteCountingHandler = ByteCountingHandler(numBytes: 4, promise: group.next().makePromise())
let verificationHandler = ShutdownVerificationHandler(
shutdownEvent: .output,
promise: group.next().makePromise()
)
let shutdownPromise = group.next().makePromise(of: Void.self)
let receivedPromise = group.next().makePromise(of: ByteBuffer.self)
let future = ClientBootstrap(group: group)
.channelInitializer { channel in
channel.pipeline.addHandler(verificationHandler).flatMap {
channel.pipeline.addHandler(byteCountingHandler)
channel.eventLoop.makeCompletedFuture {
let verificationHandler = ShutdownVerificationHandler(
shutdownEvent: .output,
promise: shutdownPromise
)
try channel.pipeline.syncOperations.addHandler(verificationHandler)
let byteCountingHandler = ByteCountingHandler(numBytes: 4, promise: receivedPromise)
try channel.pipeline.syncOperations.addHandler(byteCountingHandler)
}
}
.connect(to: try! server.localAddress())
@@ -1443,7 +1458,7 @@ public final class ChannelTests: XCTestCase {
try channel.writeAndFlush(buffer).wait()
try channel.close(mode: .output).wait()
verificationHandler.waitForEvent()
try shutdownPromise.futureResult.wait()
XCTAssertThrowsError(try channel.writeAndFlush(buffer).wait()) { error in
XCTAssertEqual(.outputClosed, error as? ChannelError)
}
@@ -1455,7 +1470,9 @@ public final class ChannelTests: XCTestCase {
} else {
XCTFail()
}
try byteCountingHandler.assertReceived(buffer: buffer)
let received = try receivedPromise.futureResult.wait()
XCTAssertEqual(received, buffer)
}
func testCloseInput() throws {
@@ -1471,7 +1488,7 @@ public final class ChannelTests: XCTestCase {
try server.bind(to: SocketAddress.makeAddressResolvingHost("127.0.0.1", port: 0))
try server.listen()
class VerifyNoReadHandler: ChannelInboundHandler {
final class VerifyNoReadHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = ByteBuffer
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
@@ -1479,14 +1496,15 @@ public final class ChannelTests: XCTestCase {
}
}
let verificationHandler = ShutdownVerificationHandler(
shutdownEvent: .input,
promise: group.next().makePromise()
)
let promise = group.next().makePromise(of: Void.self)
let future = ClientBootstrap(group: group)
.channelInitializer { channel in
channel.pipeline.addHandler(VerifyNoReadHandler()).flatMap {
channel.pipeline.addHandler(verificationHandler)
channel.pipeline.addHandler(VerifyNoReadHandler()).flatMapThrowing {
let verificationHandler = ShutdownVerificationHandler(
shutdownEvent: .input,
promise: promise
)
return try channel.pipeline.syncOperations.addHandler(verificationHandler)
}
}
.channelOption(.allowRemoteHalfClosure, value: true)
@@ -1503,7 +1521,7 @@ public final class ChannelTests: XCTestCase {
try channel.close(mode: .input).wait()
verificationHandler.waitForEvent()
try promise.futureResult.wait()
var buffer = channel.allocator.buffer(capacity: 12)
buffer.writeString("1234")
@@ -1537,14 +1555,16 @@ public final class ChannelTests: XCTestCase {
try server.bind(to: SocketAddress.makeAddressResolvingHost("127.0.0.1", port: 0))
try server.listen()
let verificationHandler = ShutdownVerificationHandler(
shutdownEvent: .input,
promise: group.next().makePromise()
)
let shutdownPromise = group.next().makePromise(of: Void.self)
let future = ClientBootstrap(group: group)
.channelInitializer { channel in
channel.pipeline.addHandler(verificationHandler)
channel.eventLoop.makeCompletedFuture {
let verificationHandler = ShutdownVerificationHandler(
shutdownEvent: .input,
promise: shutdownPromise
)
try channel.pipeline.syncOperations.addHandler(verificationHandler)
}
}
.channelOption(.allowRemoteHalfClosure, value: true)
.connect(to: try! server.localAddress())
@@ -1560,7 +1580,7 @@ public final class ChannelTests: XCTestCase {
try accepted.shutdown(how: .WR)
verificationHandler.waitForEvent()
try shutdownPromise.futureResult.wait()
var buffer = channel.allocator.buffer(capacity: 12)
buffer.writeString("1234")
@@ -1569,7 +1589,7 @@ public final class ChannelTests: XCTestCase {
}
func testInputAndOutputClosedResultsInFullClosure() throws {
final class PromiseOnChildChannelInitHandler: ChannelInboundHandler {
final class PromiseOnChildChannelInitHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = ByteBuffer
private let promise: EventLoopPromise<Channel>
@@ -1583,7 +1603,7 @@ public final class ChannelTests: XCTestCase {
}
}
final class ChannelInactiveHandler: ChannelInboundHandler {
final class ChannelInactiveHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = ByteBuffer
private let promise: EventLoopPromise<Void>
@@ -1723,7 +1743,7 @@ public final class ChannelTests: XCTestCase {
}
func testWeDontCrashIfChannelReleasesBeforePipeline() throws {
final class StuffHandler: ChannelInboundHandler {
final class StuffHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = Never
let promise: EventLoopPromise<ChannelPipeline>
@@ -1853,7 +1873,7 @@ public final class ChannelTests: XCTestCase {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
class AddressVerificationHandler: ChannelInboundHandler {
final class AddressVerificationHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = Never
public func channelActive(context: ChannelHandlerContext) {
@@ -1898,12 +1918,12 @@ public final class ChannelTests: XCTestCase {
self.readCountPromise = context.eventLoop.makePromise()
}
public func expectRead(loop: EventLoop) -> EventLoopFuture<Void> {
loop.submit {
func expectRead(loop: EventLoop) -> EventLoopFuture<Void> {
loop.assumeIsolated().submit {
self.waitingForReadPromise = loop.makePromise()
}.flatMap {
}.assumeIsolated().flatMap {
self.waitingForReadPromise!.futureResult
}
}.nonisolated()
}
func channelReadComplete(context: ChannelHandlerContext) {
@@ -1920,22 +1940,25 @@ public final class ChannelTests: XCTestCase {
}
}
public func issueDelayedRead() {
func issueDelayedRead() {
self.context.read()
}
}
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next()
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let readDelayer = ReadDelayer()
let loopBoundDelayer = try loop.next().submit { NIOLoopBound(ReadDelayer(), eventLoop: loop) }.wait()
let serverChannel = try assertNoThrowWithValue(
ServerBootstrap(group: group)
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer {
$0.pipeline.addHandler(readDelayer)
.childChannelInitializer { channel in
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandlers(loopBoundDelayer.value)
}
}
.bind(host: "127.0.0.1", port: 0).wait()
)
@@ -1947,23 +1970,27 @@ public final class ChannelTests: XCTestCase {
// We send a first write and expect it to arrive.
var buffer = clientChannel.allocator.buffer(capacity: 12)
let firstReadPromise = readDelayer.expectRead(loop: serverChannel.eventLoop)
let firstReadFuture = try loop.submit {
loopBoundDelayer.value.expectRead(loop: loop)
}.wait()
buffer.writeStaticString("hello, world")
XCTAssertNoThrow(try clientChannel.writeAndFlush(buffer).wait())
XCTAssertNoThrow(try firstReadPromise.wait())
XCTAssertNoThrow(try firstReadFuture.wait())
// We send a second write. This won't arrive immediately.
XCTAssertNoThrow(try clientChannel.writeAndFlush(buffer).wait())
let readFuture = readDelayer.expectRead(loop: serverChannel.eventLoop)
let readFuture = try loop.submit {
loopBoundDelayer.value.expectRead(loop: loop)
}.wait()
try serverChannel.eventLoop.scheduleTask(in: .milliseconds(100)) {
XCTAssertFalse(readFuture.isFulfilled)
}.futureResult.wait()
// Ok, now let it proceed.
XCTAssertNoThrow(
try serverChannel.eventLoop.submit {
XCTAssertEqual(readDelayer.reads, 2)
readDelayer.issueDelayedRead()
try loop.submit {
XCTAssertEqual(loopBoundDelayer.value.reads, 2)
loopBoundDelayer.value.issueDelayedRead()
}.wait()
)
@@ -1973,11 +2000,12 @@ public final class ChannelTests: XCTestCase {
func testNoChannelReadBeforeEOFIfNoAutoRead() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let loop = group.next()
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
class VerifyNoReadBeforeEOFHandler: ChannelInboundHandler {
final class VerifyNoReadBeforeEOFHandler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
var expectingData: Bool = false
@@ -1992,13 +2020,18 @@ public final class ChannelTests: XCTestCase {
}
}
let handler = VerifyNoReadBeforeEOFHandler()
let loopBoundVerifyHandler = try loop.submit {
NIOLoopBound(VerifyNoReadBeforeEOFHandler(), eventLoop: loop)
}.wait()
let serverChannel = try assertNoThrowWithValue(
ServerBootstrap(group: group)
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
.childChannelOption(.autoRead, value: false)
.childChannelInitializer { ch in
ch.pipeline.addHandler(handler)
ch.eventLoop.makeCompletedFuture {
try ch.pipeline.syncOperations.addHandler(loopBoundVerifyHandler.value)
}
}
.bind(host: "127.0.0.1", port: 0).wait()
)
@@ -2015,8 +2048,8 @@ public final class ChannelTests: XCTestCase {
usleep(100 * 1000)
// Now we send close. This should deliver data.
try clientChannel.eventLoop.flatSubmit { () -> EventLoopFuture<Void> in
handler.expectingData = true
try loop.flatSubmit {
loopBoundVerifyHandler.value.expectingData = true
return clientChannel.close()
}.wait()
try serverChannel.close().wait()
@@ -2028,20 +2061,20 @@ public final class ChannelTests: XCTestCase {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
class VerifyEOFReadOrderingAndCloseInChannelReadHandler: ChannelInboundHandler {
final class VerifyEOFReadOrderingAndCloseInChannelReadHandler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
private var seenEOF: Bool = false
private var numberOfChannelReads: Int = 0
public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
if case .some(ChannelEvent.inputClosed) = event as? ChannelEvent {
self.seenEOF = true
}
context.fireUserInboundEventTriggered(event)
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
if self.seenEOF {
XCTFail(
"Should not be called before seeing the EOF as autoRead is false and we did not call read(), but received \(self.unwrapInboundIn(data))"
@@ -2060,7 +2093,9 @@ public final class ChannelTests: XCTestCase {
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
.childChannelOption(.autoRead, value: false)
.childChannelInitializer { ch in
ch.pipeline.addHandler(VerifyEOFReadOrderingAndCloseInChannelReadHandler())
ch.eventLoop.makeCompletedFuture {
try ch.pipeline.syncOperations.addHandler(VerifyEOFReadOrderingAndCloseInChannelReadHandler())
}
}
.childChannelOption(.maxMessagesPerRead, value: 1)
.childChannelOption(.recvAllocator, value: FixedSizeRecvByteBufferAllocator(capacity: 8))
@@ -2122,7 +2157,9 @@ public final class ChannelTests: XCTestCase {
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
.childChannelOption(.autoRead, value: false)
.childChannelInitializer { ch in
ch.pipeline.addHandler(CloseWhenWeGetEOFHandler(allDone: allDone))
ch.eventLoop.makeCompletedFuture {
try ch.pipeline.syncOperations.addHandler(CloseWhenWeGetEOFHandler(allDone: allDone))
}
}
// maxMessagesPerRead is large so that we definitely spin and seen the EOF
.childChannelOption(.maxMessagesPerRead, value: 10)
@@ -2159,7 +2196,7 @@ public final class ChannelTests: XCTestCase {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
class ChannelInactiveVerificationHandler: ChannelDuplexHandler {
final class ChannelInactiveVerificationHandler: ChannelDuplexHandler, Sendable {
typealias InboundIn = ByteBuffer
typealias OutboundIn = ByteBuffer
@@ -2203,30 +2240,29 @@ public final class ChannelTests: XCTestCase {
}
func testAcceptsAfterCloseDontCauseIssues() throws {
class ChannelCollector {
let q = DispatchQueue(label: "q")
var channels: [ObjectIdentifier: Channel] = [:]
final class ChannelCollector: Sendable {
private let channels: NIOLockedValueBox<[ObjectIdentifier: Channel]> = NIOLockedValueBox([:])
deinit {
XCTAssertTrue(channels.isEmpty, "\(channels)")
XCTAssertTrue(self.channels.withLockedValue { $0.isEmpty })
}
func add(_ channel: Channel) {
self.q.sync {
assert(self.channels[ObjectIdentifier(channel)] == nil)
channels[ObjectIdentifier(channel)] = channel
}
let key = ObjectIdentifier(channel)
let old = self.channels.withLockedValue { $0.updateValue(channel, forKey: key) }
assert(old == nil)
}
func remove(_ channel: Channel) {
let removed: Channel? = self.q.sync {
self.channels.removeValue(forKey: ObjectIdentifier(channel))
let removed = self.channels.withLockedValue {
$0.removeValue(forKey: ObjectIdentifier(channel))
}
XCTAssertTrue(removed != nil)
}
func closeAll() -> [EventLoopFuture<Void>] {
q.sync { self.channels.values }.map { channel in
let channels = self.channels.withLockedValue { $0.values }
return channels.map { channel in
channel.close()
}
}
@@ -2270,7 +2306,11 @@ public final class ChannelTests: XCTestCase {
let collector = ChannelCollector()
let serverBoot = ServerBootstrap(group: group)
.childChannelInitializer { channel in
channel.pipeline.addHandler(CheckActiveHandler(channelCollector: collector))
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandler(
CheckActiveHandler(channelCollector: collector)
)
}
}
let listeningChannel = try serverBoot.bind(host: "127.0.0.1", port: 0).wait()
let clientBoot = ClientBootstrap(group: group)
@@ -2361,7 +2401,7 @@ public final class ChannelTests: XCTestCase {
eventLoop: clientEL as! SelectableEventLoop
)
class WriteImmediatelyHandler: ChannelInboundHandler {
final class WriteImmediatelyHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = Any
typealias OutboundOut = ByteBuffer
@@ -2398,13 +2438,15 @@ public final class ChannelTests: XCTestCase {
// again which our special `Socket` subclass will let succeed.
_ = try sc.socket.connect(to: bootstrap.localAddress!)
try serverWriteHappenedPromise.futureResult.wait()
try sc.pipeline.addHandler(
ReadDoesNotHappen(
hasRegisteredPromise: clientHasRegistered,
hasUnregisteredPromise: clientHasUnregistered,
hasReadPromise: clientHasRead
try sc.eventLoop.submit {
try sc.pipeline.syncOperations.addHandler(
ReadDoesNotHappen(
hasRegisteredPromise: clientHasRegistered,
hasUnregisteredPromise: clientHasUnregistered,
hasReadPromise: clientHasRead
)
)
).flatMap {
}.flatMap {
// this will succeed and should not cause the socket to be read even though there'll be something
// available to be read immediately
sc.register()
@@ -2599,8 +2641,8 @@ public final class ChannelTests: XCTestCase {
// send us `EPOLLHUP`. To have it run synchronously, we need to invoke the `flatMap` on the eventloop that the
// `register` will succeed.
sc.register().flatMap {
sc.pipeline.addHandler(VerifyThingsAreRightHandler(allDone: allDone))
sc.register().flatMapThrowing {
try sc.pipeline.syncOperations.addHandler(VerifyThingsAreRightHandler(allDone: allDone))
}.flatMap {
sc.connect(to: serverChannel.localAddress!)
}
@@ -2645,10 +2687,9 @@ public final class ChannelTests: XCTestCase {
let allDone = group.next().makePromise(of: Void.self)
let cf = try! sc.eventLoop.submit {
sc.pipeline.addHandler(VerifyConnectionFailureHandler(allDone: allDone)).flatMap {
sc.register().flatMap {
sc.connect(to: serverChannel.localAddress!)
}
try sc.pipeline.syncOperations.addHandler(VerifyConnectionFailureHandler(allDone: allDone))
return sc.register().flatMap {
sc.connect(to: serverChannel.localAddress!)
}
}.wait()
XCTAssertThrowsError(try cf.wait()) { error in
@@ -2688,10 +2729,9 @@ public final class ChannelTests: XCTestCase {
let allDone = group.next().makePromise(of: Void.self)
try! sc.eventLoop.submit {
let f = sc.pipeline.addHandler(VerifyConnectionFailureHandler(allDone: allDone)).flatMap {
sc.register().flatMap {
sc.connect(to: serverChannel.localAddress!)
}
try sc.pipeline.syncOperations.addHandler(VerifyConnectionFailureHandler(allDone: allDone))
let f = sc.register().flatMap {
sc.connect(to: serverChannel.localAddress!)
}
f.whenSuccess {
XCTFail("Must not succeed")
@@ -2935,7 +2975,7 @@ public final class ChannelTests: XCTestCase {
}
func testCloseInReadTriggeredByDrainingTheReceiveBufferBecauseOfWriteError() throws {
final class WriteWhenActiveHandler: ChannelInboundHandler {
final class WriteWhenActiveHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = ByteBuffer
typealias OutboundOut = ByteBuffer
@@ -2975,7 +3015,7 @@ public final class ChannelTests: XCTestCase {
}
}
final class MakeChannelInactiveInReadCausedByWriteErrorHandler: ChannelInboundHandler {
final class MakeChannelInactiveInReadCausedByWriteErrorHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = ByteBuffer
typealias OutboundOut = ByteBuffer
@@ -2990,23 +3030,10 @@ public final class ChannelTests: XCTestCase {
self.allDonePromise = allDonePromise
}
private func veryNasty_blockUntilReadBufferIsNonEmpty(channel: Channel) throws {
struct ThisIsNotASocketChannelError: Error {}
guard let channel = channel as? SocketChannel else {
throw ThisIsNotASocketChannelError()
}
try channel.socket.withUnsafeHandle { fd in
var pollFd: pollfd = .init(fd: fd, events: Int16(POLLIN), revents: 0)
let nfds =
try NIOBSDSocket.poll(fds: &pollFd, nfds: 1, timeout: -1)
XCTAssertEqual(1, nfds)
}
}
func channelActive(context: ChannelHandlerContext) {
XCTAssert(serverChannel.eventLoop === context.eventLoop)
let loopBoundContext = context.loopBound
self.serverChannel.whenSuccess { [channel = context.channel] serverChannel in
self.serverChannel.whenSuccess { [channel = context.channel, allDonePromise] serverChannel in
// all of the following futures need to complete synchronously for this test to test the correct
// thing. Therefore we keep track if we're still on the same stack frame.
var inSameStackFrame = true
@@ -3017,7 +3044,7 @@ public final class ChannelTests: XCTestCase {
XCTAssertTrue(serverChannel.isActive)
// we allow auto-read again to make sure that the socket buffer is drained on write error
// (cf. https://github.com/apple/swift-nio/issues/593)
channel.setOption(.autoRead, value: true).flatMap {
channel.setOption(.autoRead, value: true).assumeIsolated().flatMap {
let context = loopBoundContext.value
// let's trigger the write error
var buffer = channel.allocator.buffer(capacity: 16)
@@ -3029,7 +3056,7 @@ public final class ChannelTests: XCTestCase {
// arrived at the time the write fails. So this is a hack that makes sure they do have arrived.
// (https://github.com/apple/swift-nio/issues/657)
XCTAssertNoThrow(
try self.veryNasty_blockUntilReadBufferIsNonEmpty(channel: channel)
try veryNasty_blockUntilReadBufferIsNonEmpty(channel: channel)
)
}
workaroundSR487()
@@ -3044,7 +3071,7 @@ public final class ChannelTests: XCTestCase {
"unexpected error: \(error)"
)
XCTAssertTrue(inSameStackFrame)
self.allDonePromise.succeed(())
allDonePromise.succeed(())
}
}
}
@@ -3106,7 +3133,8 @@ public final class ChannelTests: XCTestCase {
defer {
XCTAssertNoThrow(try singleThreadedELG.syncShutdownGracefully())
}
var numberOfAcceptedChannel = 0
let numberOfAcceptedChannel = NIOLockedValueBox(0)
let acceptedChannels: [EventLoopPromise<Channel>] = [
singleThreadedELG.next().makePromise(),
singleThreadedELG.next().makePromise(),
@@ -3119,8 +3147,8 @@ public final class ChannelTests: XCTestCase {
.childChannelOption(.socketOption(.so_keepalive), value: 1)
.childChannelOption(.tcpOption(.tcp_nodelay), value: 0)
.childChannelInitializer { channel in
acceptedChannels[numberOfAcceptedChannel].succeed(channel)
numberOfAcceptedChannel += 1
acceptedChannels[numberOfAcceptedChannel.withLockedValue { $0 }].succeed(channel)
numberOfAcceptedChannel.withLockedValue { $0 += 1 }
return channel.eventLoop.makeSucceededFuture(())
}
.bind(host: "127.0.0.1", port: 0)
@@ -3234,7 +3262,12 @@ public final class ChannelTests: XCTestCase {
let channel = try! assertNoThrowWithValue(
ServerBootstrap(group: group).serverChannelInitializer { channel in
channel.pipeline.addHandler(MakeFirstCloseFailAndDontActuallyCloseHandler(), position: .first)
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandler(
MakeFirstCloseFailAndDontActuallyCloseHandler(),
position: .first
)
}
}.bind(host: "localhost", port: 0).wait()
)
defer {
@@ -3391,15 +3424,19 @@ public final class ChannelTests: XCTestCase {
}
let loop = group.next()
let handler = ReentrantWritabilityChangingHandler(
becameUnwritable: loop.makePromise(),
becameWritable: loop.makePromise()
)
let becameUnwritable = loop.makePromise(of: Void.self)
let becameWritable = loop.makePromise(of: Void.self)
let serverFuture = ServerBootstrap(group: group)
.childChannelOption(.writeBufferWaterMark, value: handler.watermark)
.childChannelOption(.writeBufferWaterMark, value: ReentrantWritabilityChangingHandler.watermark)
.childChannelInitializer { channel in
channel.pipeline.addHandler(handler)
channel.eventLoop.makeCompletedFuture {
let handler = ReentrantWritabilityChangingHandler(
becameUnwritable: becameUnwritable,
becameWritable: becameWritable
)
return try channel.pipeline.syncOperations.addHandler(handler)
}
}
.bind(host: "localhost", port: 0)
@@ -3416,8 +3453,8 @@ public final class ChannelTests: XCTestCase {
XCTAssertNoThrow(try client.close().wait())
}
XCTAssertNoThrow(try handler.becameUnwritable.futureResult.wait())
XCTAssertNoThrow(try handler.becameWritable.futureResult.wait())
XCTAssertNoThrow(try becameUnwritable.futureResult.wait())
XCTAssertNoThrow(try becameWritable.futureResult.wait())
}
func testChannelCanReportWritableBufferedBytes() throws {
@@ -3483,7 +3520,7 @@ public final class ChannelTests: XCTestCase {
}
}
private final class FailRegistrationAndDelayCloseHandler: ChannelOutboundHandler {
private final class FailRegistrationAndDelayCloseHandler: ChannelOutboundHandler, Sendable {
enum RegistrationFailedError: Error { case error }
typealias OutboundIn = Never
@@ -3545,7 +3582,7 @@ final class ReentrantWritabilityChangingHandler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
typealias OutboundOut = ByteBuffer
let watermark = ChannelOptions.Types.WriteBufferWaterMark(low: 100, high: 200)
static let watermark = ChannelOptions.Types.WriteBufferWaterMark(low: 100, high: 200)
let becameWritable: EventLoopPromise<Void>
let becameUnwritable: EventLoopPromise<Void>
@@ -3566,7 +3603,7 @@ final class ReentrantWritabilityChangingHandler: ChannelInboundHandler {
// again.
let b1 = context.channel.allocator.buffer(repeating: 0, count: 50)
let loopBoundContext = context.loopBound
context.write(Self.wrapOutboundOut(b1)).whenSuccess { _ in
context.write(Self.wrapOutboundOut(b1)).assumeIsolated().whenSuccess { _ in
let context = loopBoundContext.value
// We should still be writable.
XCTAssertTrue(context.channel.isWritable)
@@ -3599,3 +3636,16 @@ final class ReentrantWritabilityChangingHandler: ChannelInboundHandler {
}
}
}
private func veryNasty_blockUntilReadBufferIsNonEmpty(channel: Channel) throws {
struct ThisIsNotASocketChannelError: Error {}
guard let channel = channel as? SocketChannel else {
throw ThisIsNotASocketChannelError()
}
try channel.socket.withUnsafeHandle { fd in
var pollFd: pollfd = .init(fd: fd, events: Int16(POLLIN), revents: 0)
let nfds =
try NIOBSDSocket.poll(fds: &pollFd, nfds: 1, timeout: -1)
XCTAssertEqual(1, nfds)
}
}
@@ -914,7 +914,7 @@ class DatagramChannelTests: XCTestCase {
}
let channel2Future = DatagramBootstrap(group: self.group)
.channelOption(.writeBufferWaterMark, value: handler.watermark)
.channelOption(.writeBufferWaterMark, value: ReentrantWritabilityChangingHandler.watermark)
.channelInitializer { channel in
channel.pipeline.addHandlers([EnvelopingHandler(), handler])
}
+128 -108
View File
@@ -21,15 +21,15 @@ import XCTest
@testable import NIOCore
@testable import NIOPosix
public final class EventLoopTest: XCTestCase {
final class EventLoopTest: XCTestCase {
public func testSchedule() throws {
func testSchedule() throws {
let eventLoop = EmbeddedEventLoop()
let scheduled = eventLoop.scheduleTask(in: .seconds(1)) { true }
var result: Bool?
scheduled.futureResult.whenSuccess { result = $0 }
scheduled.futureResult.assumeIsolated().whenSuccess { result = $0 }
eventLoop.run() // run without time advancing should do nothing
XCTAssertFalse(scheduled.futureResult.isFulfilled)
@@ -42,7 +42,7 @@ public final class EventLoopTest: XCTestCase {
XCTAssertTrue(result == true)
}
public func testFlatSchedule() throws {
func testFlatSchedule() throws {
let eventLoop = EmbeddedEventLoop()
let scheduled = eventLoop.flatScheduleTask(in: .seconds(1)) {
@@ -50,7 +50,7 @@ public final class EventLoopTest: XCTestCase {
}
var result: Bool?
scheduled.futureResult.whenSuccess { result = $0 }
scheduled.futureResult.assumeIsolated().whenSuccess { result = $0 }
eventLoop.run() // run without time advancing should do nothing
XCTAssertFalse(scheduled.futureResult.isFulfilled)
@@ -63,7 +63,7 @@ public final class EventLoopTest: XCTestCase {
XCTAssertTrue(result == true)
}
public func testScheduleWithDelay() throws {
func testScheduleWithDelay() throws {
let smallAmount: TimeAmount = .milliseconds(100)
let longAmount: TimeAmount = .seconds(1)
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
@@ -104,15 +104,15 @@ public final class EventLoopTest: XCTestCase {
XCTAssertTrue(NIODeadline.now() - nanos >= longAmount)
}
public func testScheduleCancelled() throws {
func testScheduleCancelled() throws {
let eventLoop = EmbeddedEventLoop()
let scheduled = eventLoop.scheduleTask(in: .seconds(1)) { true }
var result: Bool?
var error: Error?
scheduled.futureResult.whenSuccess { result = $0 }
scheduled.futureResult.whenFailure { error = $0 }
scheduled.futureResult.assumeIsolated().whenSuccess { result = $0 }
scheduled.futureResult.assumeIsolated().whenFailure { error = $0 }
eventLoop.advanceTime(by: .milliseconds(500)) // advance halfway to firing time
scheduled.cancel()
@@ -123,7 +123,7 @@ public final class EventLoopTest: XCTestCase {
XCTAssertEqual(error as? EventLoopError, .cancelled)
}
public func testFlatScheduleCancelled() throws {
func testFlatScheduleCancelled() throws {
let eventLoop = EmbeddedEventLoop()
let scheduled = eventLoop.flatScheduleTask(in: .seconds(1)) {
@@ -132,8 +132,8 @@ public final class EventLoopTest: XCTestCase {
var result: Bool?
var error: Error?
scheduled.futureResult.whenSuccess { result = $0 }
scheduled.futureResult.whenFailure { error = $0 }
scheduled.futureResult.assumeIsolated().whenSuccess { result = $0 }
scheduled.futureResult.assumeIsolated().whenFailure { error = $0 }
eventLoop.advanceTime(by: .milliseconds(500)) // advance halfway to firing time
scheduled.cancel()
@@ -144,7 +144,7 @@ public final class EventLoopTest: XCTestCase {
XCTAssertEqual(error as? EventLoopError, .cancelled)
}
public func testScheduleRepeatedTask() throws {
func testScheduleRepeatedTask() throws {
let nanos: NIODeadline = .now()
let initialDelay: TimeAmount = .milliseconds(5)
let delay: TimeAmount = .milliseconds(10)
@@ -176,14 +176,14 @@ public final class EventLoopTest: XCTestCase {
XCTAssertTrue(NIODeadline.now() - nanos >= initialDelay + Int64(count) * delay)
}
public func testScheduledTaskThatIsImmediatelyCancelledNeverFires() throws {
func testScheduledTaskThatIsImmediatelyCancelledNeverFires() throws {
let eventLoop = EmbeddedEventLoop()
let scheduled = eventLoop.scheduleTask(in: .seconds(1)) { true }
var result: Bool?
var error: Error?
scheduled.futureResult.whenSuccess { result = $0 }
scheduled.futureResult.whenFailure { error = $0 }
scheduled.futureResult.assumeIsolated().whenSuccess { result = $0 }
scheduled.futureResult.assumeIsolated().whenFailure { error = $0 }
scheduled.cancel()
eventLoop.advanceTime(by: .seconds(1))
@@ -193,7 +193,7 @@ public final class EventLoopTest: XCTestCase {
XCTAssertEqual(error as? EventLoopError, .cancelled)
}
public func testScheduledTasksAreOrdered() throws {
func testScheduledTasksAreOrdered() throws {
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
@@ -202,18 +202,18 @@ public final class EventLoopTest: XCTestCase {
let eventLoop = eventLoopGroup.next()
let now = NIODeadline.now()
var result = [Int]()
let result = NIOLockedValueBox([Int]())
var lastScheduled: Scheduled<Void>?
for i in 0...100 {
lastScheduled = eventLoop.scheduleTask(deadline: now) {
result.append(i)
result.withLockedValue { $0.append(i) }
}
}
try lastScheduled?.futureResult.wait()
XCTAssertEqual(result, Array(0...100))
XCTAssertEqual(result.withLockedValue { $0 }, Array(0...100))
}
public func testFlatScheduledTaskThatIsImmediatelyCancelledNeverFires() throws {
func testFlatScheduledTaskThatIsImmediatelyCancelledNeverFires() throws {
let eventLoop = EmbeddedEventLoop()
let scheduled = eventLoop.flatScheduleTask(in: .seconds(1)) {
eventLoop.makeSucceededFuture(true)
@@ -221,8 +221,8 @@ public final class EventLoopTest: XCTestCase {
var result: Bool?
var error: Error?
scheduled.futureResult.whenSuccess { result = $0 }
scheduled.futureResult.whenFailure { error = $0 }
scheduled.futureResult.assumeIsolated().whenSuccess { result = $0 }
scheduled.futureResult.assumeIsolated().whenFailure { error = $0 }
scheduled.cancel()
eventLoop.advanceTime(by: .seconds(1))
@@ -232,7 +232,7 @@ public final class EventLoopTest: XCTestCase {
XCTAssertEqual(error as? EventLoopError, .cancelled)
}
public func testRepeatedTaskThatIsImmediatelyCancelledNeverFires() throws {
func testRepeatedTaskThatIsImmediatelyCancelledNeverFires() throws {
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
@@ -248,7 +248,7 @@ public final class EventLoopTest: XCTestCase {
Thread.sleep(until: .init(timeIntervalSinceNow: 0.1))
}
public func testScheduleRepeatedTaskCancelFromDifferentThread() throws {
func testScheduleRepeatedTaskCancelFromDifferentThread() throws {
let nanos: NIODeadline = .now()
let initialDelay: TimeAmount = .milliseconds(5)
// this will actually force the race from issue #554 to happen frequently
@@ -263,24 +263,29 @@ public final class EventLoopTest: XCTestCase {
let loop = eventLoopGroup.next()
hasFiredGroup.enter()
isCancelledGroup.enter()
var isAllowedToFire = true // read/write only on `loop`
var hasFired = false // read/write only on `loop`
let (isAllowedToFire, hasFired) = try! loop.submit {
let isAllowedToFire = NIOLoopBoundBox(true, eventLoop: loop)
let hasFired = NIOLoopBoundBox(false, eventLoop: loop)
return (isAllowedToFire, hasFired)
}.wait()
let repeatedTask = loop.scheduleRepeatedTask(initialDelay: initialDelay, delay: delay) {
(_: RepeatedTask) -> Void in
XCTAssertTrue(loop.inEventLoop)
if !hasFired {
if !hasFired.value {
// we can only do this once as we can only leave the DispatchGroup once but we might lose a race and
// the timer might fire more than once (until `shouldNoLongerFire` becomes true).
hasFired = true
hasFired.value = true
hasFiredGroup.leave()
}
XCTAssertTrue(isAllowedToFire)
XCTAssertTrue(isAllowedToFire.value)
}
hasFiredGroup.notify(queue: DispatchQueue.global()) {
repeatedTask.cancel()
loop.execute {
// only now do we know that the `cancel` must have gone through
isAllowedToFire = false
isAllowedToFire.value = false
isCancelledGroup.leave()
}
}
@@ -290,7 +295,7 @@ public final class EventLoopTest: XCTestCase {
isCancelledGroup.wait()
}
public func testScheduleRepeatedTaskToNotRetainRepeatedTask() throws {
func testScheduleRepeatedTaskToNotRetainRepeatedTask() throws {
let initialDelay: TimeAmount = .milliseconds(5)
let delay: TimeAmount = .milliseconds(10)
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
@@ -308,7 +313,7 @@ public final class EventLoopTest: XCTestCase {
assert(weakRepeated == nil, within: .seconds(1))
}
public func testScheduleRepeatedTaskToNotRetainEventLoop() throws {
func testScheduleRepeatedTaskToNotRetainEventLoop() throws {
weak var weakEventLoop: EventLoop? = nil
try {
let initialDelay: TimeAmount = .milliseconds(5)
@@ -327,12 +332,12 @@ public final class EventLoopTest: XCTestCase {
func testScheduledRepeatedAsyncTask() {
let eventLoop = EmbeddedEventLoop()
var counter = 0
let counter = NIOLoopBoundBox(0, eventLoop: eventLoop)
let repeatedTask = eventLoop.scheduleRepeatedAsyncTask(
initialDelay: .milliseconds(10),
delay: .milliseconds(10)
) { (_: RepeatedTask) in
counter += 1
counter.value += 1
let p = eventLoop.makePromise(of: Void.self)
eventLoop.scheduleTask(in: .milliseconds(10)) {
p.succeed(())
@@ -344,59 +349,59 @@ public final class EventLoopTest: XCTestCase {
eventLoop.run()
}
// t == 0: nothing
XCTAssertEqual(0, counter)
XCTAssertEqual(0, counter.value)
// t == 5: nothing
eventLoop.advanceTime(by: .milliseconds(5))
XCTAssertEqual(0, counter)
XCTAssertEqual(0, counter.value)
// t == 10: once
eventLoop.advanceTime(by: .milliseconds(5))
XCTAssertEqual(1, counter)
XCTAssertEqual(1, counter.value)
// t == 15: still once
eventLoop.advanceTime(by: .milliseconds(5))
XCTAssertEqual(1, counter)
XCTAssertEqual(1, counter.value)
// t == 20: still once (because the task takes 10ms to execute)
eventLoop.advanceTime(by: .milliseconds(5))
XCTAssertEqual(1, counter)
XCTAssertEqual(1, counter.value)
// t == 25: still once (because the task takes 10ms to execute)
eventLoop.advanceTime(by: .milliseconds(5))
XCTAssertEqual(1, counter)
XCTAssertEqual(1, counter.value)
// t == 30: twice
eventLoop.advanceTime(by: .milliseconds(5))
XCTAssertEqual(2, counter)
XCTAssertEqual(2, counter.value)
// t == 40: twice
eventLoop.advanceTime(by: .milliseconds(10))
XCTAssertEqual(2, counter)
XCTAssertEqual(2, counter.value)
// t == 50: three times
eventLoop.advanceTime(by: .milliseconds(10))
XCTAssertEqual(3, counter)
XCTAssertEqual(3, counter.value)
// t == 60: three times
eventLoop.advanceTime(by: .milliseconds(10))
XCTAssertEqual(3, counter)
XCTAssertEqual(3, counter.value)
// t == 89: four times
eventLoop.advanceTime(by: .milliseconds(29))
XCTAssertEqual(4, counter)
XCTAssertEqual(4, counter.value)
// t == 90: five times
eventLoop.advanceTime(by: .milliseconds(1))
XCTAssertEqual(5, counter)
XCTAssertEqual(5, counter.value)
repeatedTask.cancel()
eventLoop.run()
XCTAssertEqual(5, counter)
XCTAssertEqual(5, counter.value)
eventLoop.advanceTime(by: .hours(10))
XCTAssertEqual(5, counter)
XCTAssertEqual(5, counter.value)
}
func testScheduledRepeatedAsyncTaskIsJittered() throws {
@@ -437,7 +442,7 @@ public final class EventLoopTest: XCTestCase {
XCTAssertTrue((minNumberOfExecutedTasks...maxNumberOfExecutedTasks).contains(counter.load(ordering: .relaxed)))
}
public func testEventLoopGroupMakeIterator() throws {
func testEventLoopGroupMakeIterator() throws {
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
defer {
XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
@@ -456,7 +461,7 @@ public final class EventLoopTest: XCTestCase {
XCTAssertEqual(innerCounter, System.coreCount)
}
public func testEventLoopMakeIterator() throws {
func testEventLoopMakeIterator() throws {
let eventLoop = EmbeddedEventLoop()
let iterator = eventLoop.makeIterator()
defer {
@@ -472,7 +477,7 @@ public final class EventLoopTest: XCTestCase {
XCTAssertEqual(counter, 1)
}
public func testMultipleShutdown() throws {
func testMultipleShutdown() throws {
// This test catches a regression that causes it to intermittently fail: it reveals bugs in synchronous shutdown.
// Do not ignore intermittent failures in this test!
let threads = 8
@@ -507,7 +512,7 @@ public final class EventLoopTest: XCTestCase {
try group.syncShutdownGracefully()
}
public func testShuttingDownFailsRegistration() throws {
func testShuttingDownFailsRegistration() throws {
// This test catches a regression where the selectable event loop would allow a socket registration while
// it was nominally "shutting down". To do this, we take advantage of the fact that the event loop attempts
// to cleanly shut down all the channels before it actually closes. We add a custom channel that we can use
@@ -551,8 +556,7 @@ public final class EventLoopTest: XCTestCase {
}
}
let promiseQueue = DispatchQueue(label: "promiseQueue")
var promises: [EventLoopPromise<Void>] = []
let promises = NIOLockedValueBox<[EventLoopPromise<Void>]>([])
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
@@ -566,11 +570,13 @@ public final class EventLoopTest: XCTestCase {
let serverChannel = try assertNoThrowWithValue(
ServerBootstrap(group: group)
.childChannelInitializer { channel in
channel.pipeline.addHandler(
WedgeOpenHandler(channelActivePromise: serverChannelUp) { promise in
promiseQueue.sync { promises.append(promise) }
}
)
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandler(
WedgeOpenHandler(channelActivePromise: serverChannelUp) { promise in
promises.withLockedValue { $0.append(promise) }
}
)
}
}
.bind(host: "127.0.0.1", port: 0).wait()
)
@@ -580,12 +586,14 @@ public final class EventLoopTest: XCTestCase {
let connectPromise = loop.makePromise(of: Void.self)
// We're going to create and register a channel, but not actually attempt to do anything with it.
let wedgeHandler = WedgeOpenHandler { promise in
promiseQueue.sync { promises.append(promise) }
}
let channel = try SocketChannel(eventLoop: loop, protocolFamily: .inet)
try channel.eventLoop.submit {
channel.pipeline.addHandler(wedgeHandler).flatMap {
channel.eventLoop.makeCompletedFuture {
let wedgeHandler = WedgeOpenHandler { promise in
promises.withLockedValue { $0.append(promise) }
}
try channel.pipeline.syncOperations.addHandler(wedgeHandler)
}.flatMap {
channel.register()
}.flatMap {
// connecting here to stop epoll from throwing EPOLLHUP at us
@@ -621,15 +629,14 @@ public final class EventLoopTest: XCTestCase {
XCTAssertEqual(.timedOut, g.wait(timeout: .now()))
// Now let it close.
promiseQueue.sync {
for promise in promises {
promise.succeed(())
}
let promisesToSucceed = promises.withLockedValue { $0 }
for promise in promisesToSucceed {
promise.succeed(())
}
XCTAssertNoThrow(g.wait())
}
public func testEventLoopThreads() throws {
func testEventLoopThreads() throws {
var counter = 0
let body: ThreadInitializer = { t in
counter += 1
@@ -642,7 +649,7 @@ public final class EventLoopTest: XCTestCase {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
public func testEventLoopPinned() throws {
func testEventLoopPinned() throws {
#if os(Linux) || os(Android)
let target = NIOThread.current.affinity.cpuIds.first!
let body: ThreadInitializer = { t in
@@ -658,7 +665,7 @@ public final class EventLoopTest: XCTestCase {
#endif
}
public func testEventLoopPinnedCPUIdsConstructor() throws {
func testEventLoopPinnedCPUIdsConstructor() throws {
#if os(Linux) || os(Android)
let target = NIOThread.current.affinity.cpuIds.first!
let group = MultiThreadedEventLoopGroup(pinnedCPUIds: [target])
@@ -672,7 +679,7 @@ public final class EventLoopTest: XCTestCase {
#endif
}
public func testCurrentEventLoop() throws {
func testCurrentEventLoop() throws {
class EventLoopHolder {
weak var loop: EventLoop?
init(_ loop: EventLoop) {
@@ -716,21 +723,21 @@ public final class EventLoopTest: XCTestCase {
}
}
public func testShutdownWhileScheduledTasksNotReady() throws {
func testShutdownWhileScheduledTasksNotReady() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let eventLoop = group.next()
_ = eventLoop.scheduleTask(in: .hours(1)) {}
try group.syncShutdownGracefully()
}
public func testCloseFutureNotifiedBeforeUnblock() throws {
class AssertHandler: ChannelInboundHandler {
func testCloseFutureNotifiedBeforeUnblock() throws {
final class AssertHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = Any
let groupIsShutdown = ManagedAtomic(false)
let removed = ManagedAtomic(false)
public func handlerRemoved(context: ChannelHandlerContext) {
func handlerRemoved(context: ChannelHandlerContext) {
XCTAssertFalse(groupIsShutdown.load(ordering: .relaxed))
XCTAssertTrue(removed.compareExchange(expected: false, desired: true, ordering: .relaxed).exchanged)
}
@@ -774,26 +781,30 @@ public final class EventLoopTest: XCTestCase {
XCTAssertTrue(closeFutureFulfilledEventually.load(ordering: .relaxed))
}
public func testScheduleMultipleTasks() throws {
func testScheduleMultipleTasks() throws {
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
}
var array = [(Int, NIODeadline)]()
let scheduled1 = eventLoopGroup.next().scheduleTask(in: .milliseconds(500)) {
array.append((1, .now()))
let eventLoop = eventLoopGroup.next()
let array = try! eventLoop.submit {
NIOLoopBoundBox([(Int, NIODeadline)](), eventLoop: eventLoop)
}.wait()
let scheduled1 = eventLoop.scheduleTask(in: .milliseconds(500)) {
array.value.append((1, .now()))
}
let scheduled2 = eventLoopGroup.next().scheduleTask(in: .milliseconds(100)) {
array.append((2, .now()))
let scheduled2 = eventLoop.scheduleTask(in: .milliseconds(100)) {
array.value.append((2, .now()))
}
let scheduled3 = eventLoopGroup.next().scheduleTask(in: .milliseconds(1000)) {
array.append((3, .now()))
let scheduled3 = eventLoop.scheduleTask(in: .milliseconds(1000)) {
array.value.append((3, .now()))
}
var result = try eventLoopGroup.next().scheduleTask(in: .milliseconds(1000)) {
array
var result = try eventLoop.scheduleTask(in: .milliseconds(1000)) {
array.value
}.futureResult.wait()
XCTAssertTrue(scheduled1.futureResult.isFulfilled)
@@ -811,10 +822,9 @@ public final class EventLoopTest: XCTestCase {
XCTAssertTrue(second.1 < third.1)
XCTAssertTrue(result.isEmpty)
}
public func testRepeatedTaskThatIsImmediatelyCancelledNotifies() throws {
func testRepeatedTaskThatIsImmediatelyCancelledNotifies() throws {
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
@@ -842,7 +852,7 @@ public final class EventLoopTest: XCTestCase {
XCTAssertEqual(res, .completed)
}
public func testRepeatedTaskThatIsCancelledAfterRunningAtLeastTwiceNotifies() throws {
func testRepeatedTaskThatIsCancelledAfterRunningAtLeastTwiceNotifies() throws {
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
@@ -869,7 +879,7 @@ public final class EventLoopTest: XCTestCase {
XCTAssertEqual(XCTWaiter.wait(for: [expect1, expect2], timeout: 1.0), .completed)
}
public func testRepeatedTaskThatCancelsItselfNotifiesOnlyWhenFinished() throws {
func testRepeatedTaskThatCancelsItselfNotifiesOnlyWhenFinished() throws {
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
@@ -974,7 +984,7 @@ public final class EventLoopTest: XCTestCase {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
class Thing {
final class Thing: Sendable {
private let deallocated: ConditionLock<Int>
init(_ deallocated: ConditionLock<Int>) {
@@ -1258,7 +1268,7 @@ public final class EventLoopTest: XCTestCase {
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
context.eventLoop.execute {
context.eventLoop.assumeIsolated().execute {
self.groupToNotify.leave()
}
}
@@ -1280,7 +1290,9 @@ public final class EventLoopTest: XCTestCase {
.serverChannelOption(.autoRead, value: false)
.serverChannelOption(.maxMessagesPerRead, value: 1)
.childChannelInitializer { channel in
channel.pipeline.addHandler(ExecuteSomethingOnEventLoop(groupToNotify: g))
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandler(ExecuteSomethingOnEventLoop(groupToNotify: g))
}
}
.bind(to: .init(ipAddress: "127.0.0.1", port: 0))
.wait()
@@ -1397,8 +1409,7 @@ public final class EventLoopTest: XCTestCase {
func testTakeOverThreadAndAlsoTakeItBack() {
let currentNIOThread = NIOThread.current
let currentNSThread = Thread.current
let lock = NIOLock()
var hasBeenShutdown = false
let hasBeenShutdown = NIOLockedValueBox(false)
let allDoneGroup = DispatchGroup()
allDoneGroup.enter()
MultiThreadedEventLoopGroup.withCurrentThreadAsEventLoop { loop in
@@ -1407,14 +1418,14 @@ public final class EventLoopTest: XCTestCase {
XCTAssert(loop === MultiThreadedEventLoopGroup.currentEventLoop)
loop.shutdownGracefully(queue: DispatchQueue.global()) { error in
XCTAssertNil(error)
lock.withLock {
hasBeenShutdown = error == nil
hasBeenShutdown.withLockedValue {
$0 = error == nil
}
allDoneGroup.leave()
}
}
allDoneGroup.wait()
XCTAssertTrue(lock.withLock { hasBeenShutdown })
XCTAssertTrue(hasBeenShutdown.withLockedValue { $0 })
}
func testThreadTakeoverUnsetsCurrentEventLoop() {
@@ -1434,8 +1445,12 @@ public final class EventLoopTest: XCTestCase {
final class SaveReceivedByte: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
init(received: NIOLockedValueBox<UInt8?>) {
self.received = received
}
// For once, we don't need thread-safety as we're taking the calling thread :)
var received: UInt8? = nil
let received: NIOLockedValueBox<UInt8?>
var readCalls: Int = 0
var allDonePromise: EventLoopPromise<Void>? = nil
@@ -1446,8 +1461,8 @@ public final class EventLoopTest: XCTestCase {
var data = Self.unwrapInboundIn(data)
XCTAssertEqual(1, data.readableBytes)
XCTAssertNil(self.received)
self.received = data.readInteger()
XCTAssertNil(self.received.withLockedValue { $0 })
self.received.withLockedValue { $0 = data.readInteger() }
self.allDonePromise?.succeed(())
@@ -1455,12 +1470,17 @@ public final class EventLoopTest: XCTestCase {
}
}
let receiveHandler = SaveReceivedByte() // There'll be just one connection, we can share.
let received = NIOLockedValueBox<UInt8?>(nil)
MultiThreadedEventLoopGroup.withCurrentThreadAsEventLoop { loop in
// There'll be just one connection, we can share.
let receiveHandler = NIOLoopBound(SaveReceivedByte(received: received), eventLoop: loop)
ServerBootstrap(group: loop)
.serverChannelOption(ChannelOptions.socket(.init(SOL_SOCKET), .init(SO_REUSEADDR)), value: 1)
.childChannelInitializer { accepted in
accepted.pipeline.addHandler(receiveHandler)
accepted.eventLoop.makeCompletedFuture {
try accepted.pipeline.syncOperations.addHandler(receiveHandler.value)
}
}
.bind(host: "127.0.0.1", port: 0)
.flatMap { serverChannel in
@@ -1469,9 +1489,9 @@ public final class EventLoopTest: XCTestCase {
buffer.writeString("J")
return clientChannel.writeAndFlush(buffer)
}.flatMap {
XCTAssertNil(receiveHandler.allDonePromise)
receiveHandler.allDonePromise = loop.makePromise()
return receiveHandler.allDonePromise!.futureResult
XCTAssertNil(receiveHandler.value.allDonePromise)
receiveHandler.value.allDonePromise = loop.makePromise()
return receiveHandler.value.allDonePromise!.futureResult
}.flatMap {
serverChannel.close()
}
@@ -1489,7 +1509,7 @@ public final class EventLoopTest: XCTestCase {
}
// All done, the EventLoop is terminated so we should be able to check the results.
XCTAssertEqual(UInt8(ascii: "J"), receiveHandler.received)
XCTAssertEqual(UInt8(ascii: "J"), received.withLockedValue { $0 })
}
func testWeFailOutstandingScheduledTasksOnELShutdown() {
@@ -1558,7 +1578,7 @@ public final class EventLoopTest: XCTestCase {
// (Crashing resulted from an EINVAL/IOException thrown by the kevent
// syscall when the timeout value exceeded the maximum supported by
// the Darwin kernel #1056).
public func testScheduleMaximum() {
func testScheduleMaximum() {
let eventLoop = EmbeddedEventLoop()
let maxAmount: TimeAmount = .nanoseconds(.max)
let scheduled = eventLoop.scheduleTask(in: maxAmount) { true }
+121 -93
View File
@@ -14,6 +14,7 @@
import Atomics
import CNIOLinux
import NIOConcurrencyHelpers
import NIOCore
import XCTest
@@ -47,6 +48,27 @@ class NonBlockingFileIOTest: XCTestCase {
super.tearDown()
}
struct Counter: Sendable {
private let _value: NIOLockedValueBox<Int>
init(_ initialValue: Int) {
self._value = NIOLockedValueBox(initialValue)
}
var value: Int {
get {
self._value.withLockedValue { $0 }
}
nonmutating set {
self._value.withLockedValue { $0 = newValue }
}
}
func increment(by delta: Int = 1) {
self._value.withLockedValue { $0 += delta }
}
}
func testBasicFileIOWorks() throws {
let content = "hello"
try withTemporaryFile(content: content) { (fileHandle, _) -> Void in
@@ -166,7 +188,7 @@ class NonBlockingFileIOTest: XCTestCase {
func testChunkReadingWorks() throws {
let content = "hello"
let contentBytes = Array(content.utf8)
var numCalls = 0
let numCalls = Counter(0)
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: 5)
try self.fileIO.readChunked(
@@ -174,23 +196,23 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 1,
allocator: self.allocator,
eventLoop: self.eventLoop
) { buf in
) { [eventLoop = self.eventLoop] buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
XCTAssertTrue(eventLoop!.inEventLoop)
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual(contentBytes[numCalls], buf.readBytes(length: 1)?.first!)
numCalls += 1
return self.eventLoop.makeSucceededFuture(())
XCTAssertEqual(contentBytes[numCalls.value], buf.readBytes(length: 1)?.first!)
numCalls.increment()
return eventLoop!.makeSucceededFuture(())
}.wait()
}
XCTAssertEqual(content.utf8.count, numCalls)
XCTAssertEqual(content.utf8.count, numCalls.value)
}
func testChunkReadingCanBeAborted() throws {
enum DummyError: Error { case dummy }
let content = "hello"
let contentBytes = Array(content.utf8)
var numCalls = 0
let numCalls = Counter(0)
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: 5)
XCTAssertThrowsError(
@@ -199,24 +221,24 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 1,
allocator: self.allocator,
eventLoop: self.eventLoop
) { buf in
) { [eventLoop = self.eventLoop] buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
XCTAssertTrue(eventLoop!.inEventLoop)
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual(contentBytes[numCalls], buf.readBytes(length: 1)?.first!)
numCalls += 1
return self.eventLoop.makeFailedFuture(DummyError.dummy)
XCTAssertEqual(contentBytes[numCalls.value], buf.readBytes(length: 1)?.first!)
numCalls.increment()
return eventLoop!.makeFailedFuture(DummyError.dummy)
}.wait()
) { error in
XCTAssertEqual(.dummy, error as? DummyError)
}
}
XCTAssertEqual(1, numCalls)
XCTAssertEqual(1, numCalls.value)
}
func testChunkReadingWorksForIncrediblyLongChain() throws {
let content = String(repeating: "X", count: 20 * 1024)
var numCalls = 0
let numCalls = Counter(0)
let expectedByte = content.utf8.first!
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
try self.fileIO.readChunked(
@@ -226,20 +248,20 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 1,
allocator: self.allocator,
eventLoop: self.eventLoop
) { buf in
XCTAssertTrue(self.eventLoop.inEventLoop)
) { [eventLoop = self.eventLoop] buf in
XCTAssertTrue(eventLoop!.inEventLoop)
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual(expectedByte, buf.readableBytesView.first)
numCalls += 1
return self.eventLoop.makeSucceededFuture(())
numCalls.increment()
return eventLoop!.makeSucceededFuture(())
}.wait()
}
XCTAssertEqual(content.utf8.count, numCalls)
XCTAssertEqual(content.utf8.count, numCalls.value)
}
func testReadingDifferentChunkSize() throws {
let content = "0123456789"
var numCalls = 0
let numCalls = Counter(0)
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: content.utf8.count)
try self.fileIO.readChunked(
@@ -247,16 +269,17 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 2,
allocator: self.allocator,
eventLoop: self.eventLoop
) { buf in
) { [eventLoop = self.eventLoop] buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
XCTAssertTrue(eventLoop!.inEventLoop)
XCTAssertEqual(2, buf.readableBytes)
XCTAssertEqual(Array("\(numCalls*2)\(numCalls*2 + 1)".utf8), buf.readBytes(length: 2)!)
numCalls += 1
return self.eventLoop.makeSucceededFuture(())
let calls = numCalls.value
XCTAssertEqual(Array("\(calls*2)\(calls*2 + 1)".utf8), buf.readBytes(length: 2)!)
numCalls.increment()
return eventLoop!.makeSucceededFuture(())
}.wait()
}
XCTAssertEqual(content.utf8.count / 2, numCalls)
XCTAssertEqual(content.utf8.count / 2, numCalls.value)
}
func testReadDoesNotReadShort() throws {
@@ -292,9 +315,9 @@ class NonBlockingFileIOTest: XCTestCase {
func testChunkReadingWhereByteCountIsNotAChunkSizeMultiplier() throws {
let content = "prefix-12345-suffix"
var allBytesActual = ""
let allBytesActual = NIOLockedValueBox("")
let allBytesExpected = String(content.dropFirst(7).dropLast(7))
var numCalls = 0
let numCalls = Counter(0)
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 7, endIndex: 12)
try self.fileIO.readChunked(
@@ -302,16 +325,18 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 3,
allocator: self.allocator,
eventLoop: self.eventLoop
) { buf in
) { [eventLoop = self.eventLoop] buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
allBytesActual += buf.readString(length: buf.readableBytes) ?? "WRONG"
numCalls += 1
return self.eventLoop.makeSucceededFuture(())
XCTAssertTrue(eventLoop!.inEventLoop)
allBytesActual.withLockedValue {
$0 += buf.readString(length: buf.readableBytes) ?? "WRONG"
}
numCalls.increment()
return eventLoop!.makeSucceededFuture(())
}.wait()
}
XCTAssertEqual(allBytesExpected, allBytesActual)
XCTAssertEqual(2, numCalls)
XCTAssertEqual(allBytesExpected, allBytesActual.withLockedValue { $0 })
XCTAssertEqual(2, numCalls.value)
}
func testReadMoreThanIntMaxBytesDoesntThrow() throws {
@@ -337,22 +362,25 @@ class NonBlockingFileIOTest: XCTestCase {
func testChunkedReadDoesNotReadShort() throws {
var innerError: Error? = nil
try withPipe { readFH, writeFH in
var allBytes = ""
let allBytes = NIOLockedValueBox("")
let f = self.fileIO.readChunked(
fileHandle: readFH,
byteCount: 10,
chunkSize: 3,
allocator: self.allocator,
eventLoop: self.eventLoop
) { buf in
) { [eventLoop = self.eventLoop] buf in
var buf = buf
if allBytes.utf8.count == 9 {
let byteCount = allBytes.withLockedValue { $0.utf8.count }
if byteCount == 9 {
XCTAssertEqual(1, buf.readableBytes)
} else {
XCTAssertEqual(3, buf.readableBytes)
}
allBytes.append(buf.readString(length: buf.readableBytes) ?? "THIS IS WRONG")
return self.eventLoop.makeSucceededFuture(())
allBytes.withLockedValue {
$0.append(buf.readString(length: buf.readableBytes) ?? "THIS IS WRONG")
}
return eventLoop!.makeSucceededFuture(())
}
do {
@@ -367,7 +395,7 @@ class NonBlockingFileIOTest: XCTestCase {
try writeFH.close()
try f.wait()
XCTAssertEqual("0123456789", allBytes)
XCTAssertEqual("0123456789", allBytes.withLockedValue { $0 })
} catch {
innerError = error
}
@@ -378,7 +406,7 @@ class NonBlockingFileIOTest: XCTestCase {
func testChunkSizeMoreThanTotal() throws {
let content = "0123456789"
var numCalls = 0
let numCalls = Counter(0)
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: 5)
try self.fileIO.readChunked(
@@ -386,16 +414,16 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 10,
allocator: self.allocator,
eventLoop: self.eventLoop
) { buf in
) { [eventLoop = self.eventLoop] buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
XCTAssertTrue(eventLoop!.inEventLoop)
XCTAssertEqual(5, buf.readableBytes)
XCTAssertEqual("01234", buf.readString(length: buf.readableBytes) ?? "bad")
numCalls += 1
return self.eventLoop.makeSucceededFuture(())
numCalls.increment()
return eventLoop!.makeSucceededFuture(())
}.wait()
}
XCTAssertEqual(1, numCalls)
XCTAssertEqual(1, numCalls.value)
}
func testFileRegionReadFromPipeFails() throws {
@@ -410,9 +438,9 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 10,
allocator: self.allocator,
eventLoop: self.eventLoop
) { buf in
) { [eventLoop = self.eventLoop] buf in
XCTFail("this shouldn't have been called")
return self.eventLoop.makeSucceededFuture(())
return eventLoop!.makeSucceededFuture(())
}.wait()
) { error in
XCTAssertEqual(ESPIPE, (error as? IOError)?.errnoCode)
@@ -435,9 +463,9 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 10,
allocator: self.allocator,
eventLoop: self.eventLoop
) { buf in
) { [eventLoop = self.eventLoop] buf in
XCTFail("this shouldn't have been called")
return self.eventLoop.makeSucceededFuture(())
return eventLoop!.makeSucceededFuture(())
}.wait()
XCTFail("succeeded and shouldn't have")
} catch let e as NonBlockingFileIO.Error where e == NonBlockingFileIO.Error.descriptorSetToNonBlocking {
@@ -451,7 +479,7 @@ class NonBlockingFileIOTest: XCTestCase {
func testSeekPointerIsSetToFront() throws {
let content = "0123456789"
var numCalls = 0
let numCalls = Counter(0)
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
try self.fileIO.readChunked(
fileHandle: fileHandle,
@@ -459,21 +487,21 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 9,
allocator: self.allocator,
eventLoop: self.eventLoop
) { buf in
) { [eventLoop = self.eventLoop] buf in
var buf = buf
numCalls += 1
XCTAssertTrue(self.eventLoop.inEventLoop)
if numCalls == 1 {
numCalls.increment()
XCTAssertTrue(eventLoop!.inEventLoop)
if numCalls.value == 1 {
XCTAssertEqual(9, buf.readableBytes)
XCTAssertEqual("012345678", buf.readString(length: buf.readableBytes) ?? "bad")
} else {
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual("9", buf.readString(length: buf.readableBytes) ?? "bad")
}
return self.eventLoop.makeSucceededFuture(())
return eventLoop!.makeSucceededFuture(())
}.wait()
}
XCTAssertEqual(2, numCalls)
XCTAssertEqual(2, numCalls.value)
}
func testReadingFileSize() throws {
@@ -911,7 +939,7 @@ class NonBlockingFileIOTest: XCTestCase {
func testReadChunkedFromOffset() {
XCTAssertNoThrow(
try withTemporaryFile(content: "hello world") { (fileHandle, path) in
var numberOfCalls = 0
let numberOfCalls = Counter(0)
try self.fileIO.readChunked(
fileHandle: fileHandle,
fromOffset: 6,
@@ -919,9 +947,9 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 2,
allocator: .init(),
eventLoop: self.eventLoop
) { buffer in
numberOfCalls += 1
switch numberOfCalls {
) { [eventLoop = self.eventLoop] buffer in
numberOfCalls.increment()
switch numberOfCalls.value {
case 1:
XCTAssertEqual("wo", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))
case 2:
@@ -931,14 +959,14 @@ class NonBlockingFileIOTest: XCTestCase {
default:
XCTFail()
}
return self.eventLoop.makeSucceededFuture(())
return eventLoop!.makeSucceededFuture(())
}.wait()
}
)
}
func testReadChunkedFromOffsetAfterEOFDeliversExactlyOneChunk() {
var numberOfCalls = 0
let numberOfCalls = Counter(0)
XCTAssertNoThrow(
try withTemporaryFile(content: "hello world") { (fileHandle, path) in
try self.fileIO.readChunked(
@@ -948,18 +976,18 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 2,
allocator: .init(),
eventLoop: self.eventLoop
) { buffer in
numberOfCalls += 1
XCTAssertEqual(1, numberOfCalls)
) { [eventLoop = self.eventLoop] buffer in
numberOfCalls.increment()
XCTAssertEqual(1, numberOfCalls.value)
XCTAssertEqual(0, buffer.readableBytes)
return self.eventLoop.makeSucceededFuture(())
return eventLoop!.makeSucceededFuture(())
}.wait()
}
)
}
func testReadChunkedFromEOFDeliversExactlyOneChunk() {
var numberOfCalls = 0
let numberOfCalls = Counter(0)
XCTAssertNoThrow(
try withTemporaryFile(content: "") { (fileHandle, path) in
try self.fileIO.readChunked(
@@ -968,11 +996,11 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 2,
allocator: .init(),
eventLoop: self.eventLoop
) { buffer in
numberOfCalls += 1
XCTAssertEqual(1, numberOfCalls)
) { [eventLoop = self.eventLoop] buffer in
numberOfCalls.increment()
XCTAssertEqual(1, numberOfCalls.value)
XCTAssertEqual(0, buffer.readableBytes)
return self.eventLoop.makeSucceededFuture(())
return eventLoop!.makeSucceededFuture(())
}.wait()
}
)
@@ -1014,16 +1042,16 @@ class NonBlockingFileIOTest: XCTestCase {
func testReadChunkedFromOffsetFileRegion() {
XCTAssertNoThrow(
try withTemporaryFile(content: "hello world") { (fileHandle, path) in
var numberOfCalls = 0
let numberOfCalls = Counter(0)
let fileRegion = FileRegion(fileHandle: fileHandle, readerIndex: 6, endIndex: 11)
try self.fileIO.readChunked(
fileRegion: fileRegion,
chunkSize: 2,
allocator: .init(),
eventLoop: self.eventLoop
) { buffer in
numberOfCalls += 1
switch numberOfCalls {
) { [eventLoop = self.eventLoop] buffer in
numberOfCalls.increment()
switch numberOfCalls.value {
case 1:
XCTAssertEqual("wo", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))
case 2:
@@ -1033,7 +1061,7 @@ class NonBlockingFileIOTest: XCTestCase {
default:
XCTFail()
}
return self.eventLoop.makeSucceededFuture(())
return eventLoop!.makeSucceededFuture(())
}.wait()
}
)
@@ -1057,11 +1085,11 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 1,
allocator: self.allocator,
eventLoop: self.eventLoop
) { buffer in
) { [eventLoop = self.eventLoop] buffer in
numberOfCalls.wrappingIncrement(ordering: .relaxed)
XCTAssertEqual(1, buffer.readableBytes)
XCTAssertEqual(UInt8(ascii: "X"), buffer.readableBytesView.first)
return self.eventLoop.makeSucceededFuture(())
return eventLoop!.makeSucceededFuture(())
}.wait()
)
XCTAssertEqual(numberOfChunks, numberOfCalls.load(ordering: .relaxed))
@@ -1242,7 +1270,7 @@ class NonBlockingFileIOTest: XCTestCase {
func testChunkedReadingToleratesChunkHandlersWithForeignEventLoops() throws {
let content = "hello"
let contentBytes = Array(content.utf8)
var numCalls = 0
let numCalls = Counter(0)
let otherGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
try! otherGroup.syncShutdownGracefully()
@@ -1254,16 +1282,16 @@ class NonBlockingFileIOTest: XCTestCase {
chunkSize: 1,
allocator: self.allocator,
eventLoop: self.eventLoop
) { buf in
) { [eventLoop = self.eventLoop] buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
XCTAssertTrue(eventLoop!.inEventLoop)
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual(contentBytes[numCalls], buf.readBytes(length: 1)?.first!)
numCalls += 1
XCTAssertEqual(contentBytes[numCalls.value], buf.readBytes(length: 1)?.first!)
numCalls.increment()
return otherGroup.next().makeSucceededFuture(())
}.wait()
}
XCTAssertEqual(content.utf8.count, numCalls)
XCTAssertEqual(content.utf8.count, numCalls.value)
}
}
@@ -1334,11 +1362,11 @@ extension NonBlockingFileIOTest {
}
func testAsyncDoesNotBlockTheThreadOrEventLoop() async throws {
try await withPipe { readFH, writeFH in
async let byteBufferTask = try await self.fileIO.read(
try await withPipe { [fileIO, allocator] readFH, writeFH in
async let byteBufferTask = try await fileIO!.read(
fileHandle: readFH,
byteCount: 10,
allocator: self.allocator
allocator: allocator!
)
do {
try await self.threadPool.runIfActive {
@@ -1374,11 +1402,11 @@ extension NonBlockingFileIOTest {
}
func testAsyncReadDoesNotReadShort() async throws {
try await withPipe { readFH, writeFH in
async let bufferTask = try await self.fileIO.read(
try await withPipe { [fileIO, allocator] readFH, writeFH in
async let bufferTask = try await fileIO!.read(
fileHandle: readFH,
byteCount: 10,
allocator: self.allocator
allocator: allocator!
)
for i in 0..<10 {
try await Task.sleep(nanoseconds: 5_000_000)
+34 -27
View File
@@ -13,6 +13,7 @@
//===----------------------------------------------------------------------===//
import Atomics
import NIOConcurrencyHelpers
import NIOCore
import XCTest
@@ -122,7 +123,7 @@ class SelectorTest: XCTestCase {
func testWeDoNotDeliverEventsForPreviouslyClosedChannels() {
/// We use this class to box mutable values, generally in this test anything boxed should only be read/written
/// on the event loop `el`.
class Box<T> {
final class Box<T>: @unchecked Sendable {
init(_ value: T) {
self._value = value
}
@@ -254,12 +255,12 @@ class SelectorTest: XCTestCase {
// 1. let's close half the channels
// 2. then re-connect (must be synchronous) the same number of channels and we'll get fd number re-use
context.channel.eventLoop.execute {
context.channel.eventLoop.execute { [hasReConnectEventLoopTickFinished] in
// this will be run immediately after we processed all `Selector` events so when
// `self.hasReConnectEventLoopTickFinished.value` becomes true, we're out of the event loop
// tick that is interesting.
XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value)
self.hasReConnectEventLoopTickFinished.value = true
XCTAssertFalse(hasReConnectEventLoopTickFinished.value)
hasReConnectEventLoopTickFinished.value = true
}
XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value)
@@ -279,24 +280,26 @@ class SelectorTest: XCTestCase {
// some new ones
var reconnectedChannelsHaveRead: [EventLoopFuture<Void>] = []
for _ in everyOtherIndex {
var hasBeenAdded: Bool = false
let hasBeenAdded = NIOLockedValueBox(false)
let p = context.channel.eventLoop.makePromise(of: Void.self)
reconnectedChannelsHaveRead.append(p.futureResult)
let newChannel = ClientBootstrap(group: context.eventLoop)
.channelInitializer { channel in
channel.pipeline.addHandler(
HappyWhenReadHandler(
hasReConnectEventLoopTickFinished: self.hasReConnectEventLoopTickFinished,
didReadPromise: p
.channelInitializer { [hasReConnectEventLoopTickFinished] channel in
channel.eventLoop.assumeIsolated().makeCompletedFuture {
let sync = channel.pipeline.syncOperations
try sync.addHandler(
HappyWhenReadHandler(
hasReConnectEventLoopTickFinished: hasReConnectEventLoopTickFinished,
didReadPromise: p
)
)
).map {
hasBeenAdded = true
hasBeenAdded.withLockedValue { $0 = true }
}
}
.connect(to: self.serverAddress)
.map { (channel: Channel) -> Void in
.map { [hasReConnectEventLoopTickFinished] (channel: Channel) -> Void in
XCTAssertFalse(
self.hasReConnectEventLoopTickFinished.value,
hasReConnectEventLoopTickFinished.value,
"""
This is bad: the connect of the channels to be re-connected has not
completed synchronously.
@@ -316,7 +319,7 @@ class SelectorTest: XCTestCase {
// just to make sure we got `newChannel` synchronously and we could add our handler to the
// pipeline synchronously too.
XCTAssertTrue(newChannel.isFulfilled)
XCTAssertTrue(hasBeenAdded)
XCTAssertTrue(hasBeenAdded.withLockedValue { $0 })
}
// if all the new re-connected channels have read, then we're happy here.
@@ -379,12 +382,14 @@ class SelectorTest: XCTestCase {
try withTemporaryUnixDomainSocketPathName { udsPath in
let secondServerChannel = try! ServerBootstrap(group: el)
.childChannelInitializer { channel in
channel.pipeline.addHandler(
ServerHandler(
allServerChannels: allServerChannels,
numberOfConnectedChannels: numberOfConnectedChannels
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandler(
ServerHandler(
allServerChannels: allServerChannels,
numberOfConnectedChannels: numberOfConnectedChannels
)
)
)
}
}
.bind(to: SocketAddress(unixDomainSocketPath: udsPath))
.wait()
@@ -396,14 +401,16 @@ class SelectorTest: XCTestCase {
ClientBootstrap(group: el)
.channelOption(.allowRemoteHalfClosure, value: true)
.channelInitializer { channel in
channel.pipeline.addHandler(
CloseEveryOtherAndOpenNewOnesHandler(
allChannels: allChannels,
hasReConnectEventLoopTickFinished: hasReConnectEventLoopTickFinished,
serverAddress: secondServerChannel.localAddress!,
everythingWasReadPromise: everythingWasReadPromise
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandler(
CloseEveryOtherAndOpenNewOnesHandler(
allChannels: allChannels,
hasReConnectEventLoopTickFinished: hasReConnectEventLoopTickFinished,
serverAddress: secondServerChannel.localAddress!,
everythingWasReadPromise: everythingWasReadPromise
)
)
)
}
}
.connect(to: secondServerChannel.localAddress!)
.map { channel in
+79 -54
View File
@@ -32,7 +32,7 @@ class StreamChannelTest: XCTestCase {
}
func testEchoBasic() throws {
class EchoHandler: ChannelInboundHandler {
final class EchoHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = ByteBuffer
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
@@ -48,7 +48,12 @@ class StreamChannelTest: XCTestCase {
var everythingBuffer = chan1.allocator.buffer(capacity: 300000)
let allDonePromise = chan1.eventLoop.makePromise(of: ByteBuffer.self)
XCTAssertNoThrow(try chan1.pipeline.addHandler(EchoHandler()).wait())
XCTAssertNoThrow(try chan2.pipeline.addHandler(AccumulateAllReads(allDonePromise: allDonePromise)).wait())
let configuredChannel2 = chan2.eventLoop.submit {
let handler = AccumulateAllReads(allDonePromise: allDonePromise)
try chan2.pipeline.syncOperations.addHandler(handler)
}
XCTAssertNoThrow(try configuredChannel2.wait())
for f in [1, 10, 100, 1_000, 10_000, 300_000] {
let from = everythingBuffer.writerIndex
@@ -72,7 +77,7 @@ class StreamChannelTest: XCTestCase {
}
func testSyncChannelOptions() throws {
class GetAndSetAutoReadHandler: ChannelInboundHandler {
final class GetAndSetAutoReadHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = Any
func handlerAdded(context: ChannelHandlerContext) {
@@ -96,17 +101,17 @@ class StreamChannelTest: XCTestCase {
}
func testChannelReturnsNilForDefaultSyncOptionsImplementation() throws {
class TestChannel: Channel {
final class TestChannel: Channel {
var allocator: ByteBufferAllocator { fatalError() }
var closeFuture: EventLoopFuture<Void> { fatalError() }
var pipeline: ChannelPipeline { fatalError() }
var localAddress: SocketAddress? = nil
var remoteAddress: SocketAddress? = nil
var parent: Channel? = nil
let localAddress: SocketAddress? = nil
let remoteAddress: SocketAddress? = nil
let parent: Channel? = nil
var _channelCore: ChannelCore { fatalError() }
var eventLoop: EventLoop { fatalError() }
var isWritable: Bool = false
var isActive: Bool = false
let isWritable: Bool = false
let isActive: Bool = false
func setOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> EventLoopFuture<Void> {
fatalError()
@@ -164,11 +169,11 @@ class StreamChannelTest: XCTestCase {
XCTFail("unexpected error \(error)")
}
}
context.write(Self.wrapOutboundOut(buffer)).map {
context.write(Self.wrapOutboundOut(buffer)).assumeIsolated().map {
XCTAssertEqual(self.state, .thenTrueAgain)
}.recover { error in
XCTFail("unexpected error \(error)")
}.cascade(to: self.writeFullyDonePromise)
}.nonisolated().cascade(to: self.writeFullyDonePromise)
context.flush()
}
@@ -178,7 +183,7 @@ class StreamChannelTest: XCTestCase {
XCTAssertEqual(State(rawValue: self.channelWritabilityChangedCalls), self.state)
if let newState = State(rawValue: self.channelWritabilityChangedCalls + 1) {
if self.state == .thenFalse {
context.eventLoop.scheduleTask(in: .microseconds(100)) {
context.eventLoop.assumeIsolated().scheduleTask(in: .microseconds(100)) {
// Let's delay this a tiny little bit just so we get a higher chance to actually exhaust all
// the buffers. The delay is not necessary for this test to work but it makes the tests a
// little bit harder.
@@ -195,15 +200,21 @@ class StreamChannelTest: XCTestCase {
let writabilityFalsePromise = chan1.eventLoop.makePromise(of: Void.self)
let writeFullyDonePromise = chan1.eventLoop.makePromise(of: Void.self)
XCTAssertNoThrow(try chan2.setOption(.autoRead, value: false).wait())
XCTAssertNoThrow(try chan2.pipeline.addHandler(AccumulateAllReads(allDonePromise: allDonePromise)).wait())
XCTAssertNoThrow(
try chan1.pipeline.addHandler(
let chan2Configured = chan2.eventLoop.submit {
try chan2.pipeline.syncOperations.addHandler(AccumulateAllReads(allDonePromise: allDonePromise))
}
XCTAssertNoThrow(try chan2Configured.wait())
let chan1Configured = chan1.eventLoop.submit {
try chan1.pipeline.syncOperations.addHandler(
WritabilityTrackerStateMachine(
writabilityNowFalsePromise: writabilityFalsePromise,
writeFullyDonePromise: writeFullyDonePromise
)
).wait()
)
)
}
XCTAssertNoThrow(try chan1Configured.wait())
// Writability should turn false because we're writing lots of data and we aren't reading.
XCTAssertNoThrow(try writabilityFalsePromise.futureResult.wait())
@@ -369,7 +380,7 @@ class StreamChannelTest: XCTestCase {
func testLotsOfWritesWhilstOtherSideNotReading() {
// This is a regression test for a problem where we would spin on EVFILT_EXCEPT despite the fact that there
// was no EOF or any other exceptional event present. So this is a regression test for rdar://53656794 and https://github.com/apple/swift-nio/pull/526.
class FailOnReadHandler: ChannelInboundHandler {
final class FailOnReadHandler: ChannelInboundHandler, Sendable {
typealias InboundIn = ByteBuffer
let areReadsOkayNow: ManagedAtomic<Bool>
@@ -409,11 +420,12 @@ class StreamChannelTest: XCTestCase {
let receiveBufferSize = Int(
(try? receiver.getOption(ChannelOptions.socketOption(.so_rcvbuf)).wait()) ?? 8192
)
var buffer = sender.allocator.buffer(capacity: receiveBufferSize)
buffer.writeBytes(Array(repeating: UInt8(ascii: "X"), count: receiveBufferSize))
let buffer = sender.allocator.buffer(repeating: UInt8(ascii: "X"), count: receiveBufferSize)
XCTAssertNoThrow(
try sender.eventLoop.submit {
@Sendable
func send() {
var allBuffer = buffer
// When we run through this for the first time, we send exactly the receive buffer size, after that
@@ -484,11 +496,13 @@ class StreamChannelTest: XCTestCase {
func runTest(receiver: Channel, sender: Channel) throws {
let allDonePromise = receiver.eventLoop.makePromise(of: Void.self)
XCTAssertNoThrow(try sender.setOption(.writeSpin, value: 0).wait())
XCTAssertNoThrow(
try receiver.pipeline.addHandler(WaitForTwoBytesHandler(allDonePromise: allDonePromise)).wait()
)
var buffer = sender.allocator.buffer(capacity: 1)
buffer.writeString("X")
let receiverConfigured = receiver.eventLoop.submit {
try receiver.pipeline.syncOperations.addHandler(
WaitForTwoBytesHandler(allDonePromise: allDonePromise)
)
}
XCTAssertNoThrow(try receiverConfigured.wait())
let buffer = sender.allocator.buffer(string: "X")
XCTAssertNoThrow(
try sender.eventLoop.flatSubmit { () -> EventLoopFuture<Void> in
let writePromise = sender.eventLoop.makePromise(of: Void.self)
@@ -525,8 +539,7 @@ class StreamChannelTest: XCTestCase {
// Now, let's trigger another write which should cause flushNow to be re-entered. But first, let's
// raise the high water mark so we don't get another call straight away.
var buffer = context.channel.allocator.buffer(capacity: 5)
buffer.writeString("hello")
let buffer = context.channel.allocator.buffer(string: "hello")
let loopBoundContext = context.loopBound
context.channel.setOption(.writeBufferWaterMark, value: .init(low: 1024, high: 1024))
.flatMap {
@@ -575,18 +588,22 @@ class StreamChannelTest: XCTestCase {
)
let sevenBytesReceived = receiver.eventLoop.makePromise(of: Void.self)
XCTAssertNoThrow(
try receiver.pipeline.addHandler(
WaitForNumberOfBytes(
numberOfBytes: 7,
allDonePromise: sevenBytesReceived
)
).wait()
)
let receiverConfigured = receiver.eventLoop.submit {
let handler = WaitForNumberOfBytes(
numberOfBytes: 7,
allDonePromise: sevenBytesReceived
)
try receiver.pipeline.syncOperations.addHandler(handler)
}
XCTAssertNoThrow(try receiverConfigured.wait())
let eventCounterHandler = EventCounterHandler()
XCTAssertNoThrow(try sender.pipeline.addHandler(EventCounterHandler()).wait())
XCTAssertNoThrow(try sender.pipeline.addHandler(WriteWhenWritabilityGoesToTrue()).wait())
let senderConfigured = sender.eventLoop.submit {
let sync = sender.pipeline.syncOperations
try sync.addHandler(eventCounterHandler)
try sync.addHandler(WriteWhenWritabilityGoesToTrue())
}
XCTAssertNoThrow(try senderConfigured.wait())
var buffer = sender.allocator.buffer(capacity: 5)
buffer.writeString("XX") // 2 bytes, exceeds the high water mark
@@ -682,7 +699,7 @@ class StreamChannelTest: XCTestCase {
}
let loopBoundContext = context.loopBound
context.eventLoop.execute {
context.eventLoop.assumeIsolated().execute {
let context = loopBoundContext.value
self.kickOff(context: context)
}
@@ -707,7 +724,7 @@ class StreamChannelTest: XCTestCase {
context.writeAndFlush(Self.wrapOutboundOut(buffer.value)).whenFailure { error in
XCTFail("unexpected error \(error)")
}
context.eventLoop.scheduleTask(in: .microseconds(100)) {
context.eventLoop.assumeIsolated().scheduleTask(in: .microseconds(100)) {
let context = loopBoundContext.value
switch self.state {
case .writingUntilFull:
@@ -729,7 +746,7 @@ class StreamChannelTest: XCTestCase {
}
}
}
context.eventLoop.execute {
context.eventLoop.assumeIsolated().execute {
writeOneMore() // this kicks everything off
}
}
@@ -746,9 +763,9 @@ class StreamChannelTest: XCTestCase {
}
context.fireChannelWritabilityChanged()
let loopBoundContext = context.loopBound
self.wroteEnoughToBeStuckPromise.futureResult.whenSuccess { _ in
self.wroteEnoughToBeStuckPromise.futureResult.assumeIsolated().whenSuccess { _ in
let context = loopBoundContext.value
context.pipeline.removeHandler(self).whenFailure { error in
context.pipeline.syncOperations.removeHandler(self).whenFailure { error in
XCTFail("unexpected error \(error)")
}
}
@@ -856,7 +873,7 @@ class StreamChannelTest: XCTestCase {
}
}
final class FailOnError: ChannelInboundHandler {
final class FailOnError: ChannelInboundHandler, Sendable {
typealias InboundIn = Never
func errorCaught(context: ChannelHandlerContext, error: Error) {
@@ -880,29 +897,34 @@ class StreamChannelTest: XCTestCase {
// We need to not read automatically from the receiving end to be able to force writability notifications
// for the sender.
XCTAssertNoThrow(try receiver.setOption(.autoRead, value: false).wait())
let receiverConfigured = receiver.eventLoop.submit {
try receiver.pipeline.syncOperations.addHandler(ReadChunksUntilWeSee1Handler())
}
XCTAssertNoThrow(try receiverConfigured.wait())
XCTAssertNoThrow(try receiver.pipeline.addHandler(ReadChunksUntilWeSee1Handler()).wait())
XCTAssertNoThrow(
try sender.pipeline.addHandler(
let senderConfigured1 = sender.eventLoop.submit {
try sender.pipeline.syncOperations.addHandler(
WriteWhenChannelBecomesWritableAgain(
beganBigWritePromise: beganBigWritePromise,
finishedBigWritePromise: finishedBigWritePromise
)
).wait()
)
)
}
XCTAssertNoThrow(try senderConfigured1.wait())
XCTAssertNoThrow(try sender.pipeline.addHandler(FailOnError()).wait())
XCTAssertNoThrow(try receiver.pipeline.addHandler(FailOnError()).wait())
XCTAssertNoThrow(
try sender.pipeline.addHandler(
let senderConfigured2 = sender.eventLoop.submit {
try sender.pipeline.syncOperations.addHandler(
WriteUntilWriteDoesNotCompletelyInstantlyHandler(
chunkSize: chunkSize,
wroteEnoughToBeStuckPromise: wroteEnoughToBeStuckPromise
),
position: .first
).wait()
)
)
}
XCTAssertNoThrow(try senderConfigured2.wait())
var howManyBytes: Int? = nil
XCTAssertNoThrow(howManyBytes = try wroteEnoughToBeStuckPromise.futureResult.wait())
@@ -974,7 +996,10 @@ class StreamChannelTest: XCTestCase {
}
let amount = 2
XCTAssertNoThrow(try sender.pipeline.addHandler(CloseInWritabilityChanged(amount: amount)).wait())
let senderConfigured = sender.eventLoop.submit {
try sender.pipeline.syncOperations.addHandler(CloseInWritabilityChanged(amount: amount))
}
XCTAssertNoThrow(try senderConfigured.wait())
XCTAssertNoThrow(
try sender.setOption(
.writeBufferWaterMark,
+6 -7
View File
@@ -440,7 +440,7 @@ func assertFailure<Value>(_ result: Result<Value, Error>, file: StaticString = #
/// Fulfills the promise when the respective event is first received.
///
/// - Note: Once this is used more widely and shows value, we might want to put it into `NIOTestUtils`.
final class FulfillOnFirstEventHandler: ChannelDuplexHandler {
final class FulfillOnFirstEventHandler: ChannelDuplexHandler, Sendable {
typealias InboundIn = Any
typealias OutboundIn = Any
@@ -837,25 +837,24 @@ extension EventLoopFuture {
// Easy, we're on the EventLoop. Let's just use our knowledge that we run completed future callbacks
// immediately.
var fulfilled = false
self.whenComplete { _ in
self.assumeIsolated().whenComplete { _ in
fulfilled = true
}
return fulfilled
} else {
let lock = NIOLock()
let fulfilledBox = NIOLockedValueBox(false)
let group = DispatchGroup()
var fulfilled = false // protected by lock
group.enter()
self.eventLoop.execute {
let isFulfilled = self.isFulfilled // This will now enter the above branch.
lock.withLock {
fulfilled = isFulfilled
fulfilledBox.withLockedValue {
$0 = isFulfilled
}
group.leave()
}
group.wait() // this is very nasty but this is for tests only, so...
return lock.withLock { fulfilled }
return fulfilledBox.withLockedValue { $0 }
}
}
}
+15 -40
View File
@@ -29,17 +29,11 @@ if [[ ! ( -n "$branch" && -z "$version" ) && ! ( -z "$branch" && -n "$version")
fatal "Exactly one of build or version must be defined."
fi
log "Installing tools for this script"
if command -v apt-get >/dev/null; then
package_manager="apt-get"
apt-get update > /dev/null
elif command -v yum >/dev/null; then
package_manager="yum"
else
fatal "Cannot find either 'apt' or 'yum'"
fi
CURL_BIN="${CURL_BIN:-$(which curl 2> /dev/null)}"; test -n "$CURL_BIN" || fatal "CURL_BIN unset and no curl on PATH"
TAR_BIN="${TAR_BIN:-$(which tar 2> /dev/null)}"; test -n "$TAR_BIN" || fatal "TAR_BIN unset and no tar on PATH"
JQ_BIN="${JQ_BIN:-$(which jq 2> /dev/null)}"; test -n "$JQ_BIN" || fatal "JQ_BIN unset and no jq on PATH"
SED_BIN="${SED_BIN:-$(which sed 2> /dev/null)}"; test -n "$SED_BIN" || fatal "SED_BIN unset and no sed on PATH"
"$package_manager" install -y curl rsync jq tar > /dev/null
case "$arch" in
"aarch64")
arch_suffix="-$arch" ;;
@@ -54,14 +48,17 @@ os_image_sanitized="${os_image//./}"
if [[ -n "$branch" ]]; then
# Some snapshots may not have all the artefacts we require
log "Discovering branch snapshot for branch $branch"
snapshots="$(curl -s "https://www.swift.org/api/v1/install/dev/main/${os_image_sanitized}.json" | jq -r --arg arch "$arch" '.[$arch] | unique | reverse | .[].dir')"
# shellcheck disable=SC2016 # Our use of JQ_BIN means that shellcheck can't tell this is a `jq` invocation
snapshots="$("$CURL_BIN" -s "https://www.swift.org/api/v1/install/dev/main/${os_image_sanitized}.json" | "$JQ_BIN" -r --arg arch "$arch" '.[$arch] | unique | reverse | .[].dir')"
for snapshot in $snapshots; do
snapshot_url="https://download.swift.org/development/${os_image_sanitized}${arch_suffix}/${snapshot}/${snapshot}-${os_image}${arch_suffix}.tar.gz"
static_sdk_url="https://download.swift.org/development/static-sdk/${snapshot}/${snapshot}_static-linux-0.0.1.artifactbundle.tar.gz"
# check that the files exist
curl -sILXGET --fail "$snapshot_url" > /dev/null; snapshot_return_code=$?
curl -sILXGET --fail "$static_sdk_url" > /dev/null; static_sdk_return_code=$?
"$CURL_BIN" -sILXGET --fail "$snapshot_url" > /dev/null; snapshot_return_code=$?
"$CURL_BIN" -sILXGET --fail "$static_sdk_url" > /dev/null; static_sdk_return_code=$?
if [[ ("$snapshot_return_code" -eq 0) && ("$static_sdk_return_code" -eq 0) ]]; then
log "Discovered branch snapshot: $snapshot"
@@ -78,7 +75,7 @@ if [[ -n "$branch" ]]; then
elif [[ -n "$version" ]]; then
if [[ "$version" == "latest" ]]; then
log "Discovering latest version"
version=$(curl -s https://www.swift.org/api/v1/install/releases.json | jq -r '.[-1].tag' | sed -E 's/swift-([0-9]+\.[0-9]+\.?[0-9]*)-RELEASE/\1/')
version=$("$CURL_BIN" -s https://www.swift.org/api/v1/install/releases.json | "$JQ_BIN" -r '.[-1].tag' | "$SED_BIN" -E 's/swift-([0-9]+\.[0-9]+\.?[0-9]*)-RELEASE/\1/')
if [[ -z "$version" ]]; then
fatal "Failed to discover latest Swift version"
fi
@@ -89,44 +86,22 @@ elif [[ -n "$version" ]]; then
static_sdk_url="https://download.swift.org/swift-${version}-release/static-sdk/swift-${version}-RELEASE/swift-${version}-RELEASE_static-linux-0.0.1.artifactbundle.tar.gz"
fi
log "Installing standard Swift pre-requisites" # pre-reqs list taken from swift.org
DEBIAN_FRONTEND=noninteractive "$package_manager" install -y\
binutils\
git\
gnupg2\
libc6-dev\
libcurl4-openssl-dev\
libedit2\
libgcc-11-dev\
libpython3-dev\
libsqlite3-0\
libstdc++-11-dev\
libxml2-dev\
libz3-dev\
pkg-config\
python3-lldb-13\
tzdata\
unzip\
zlib1g-dev\
> /dev/null
log "Obtaining Swift toolchain"
log "Snapshot URL: $snapshot_url"
snapshot_path="/tmp/$(basename "$snapshot_url")"
curl -sL "$snapshot_url" -o "$snapshot_path"
"$CURL_BIN" -sfL "$snapshot_url" -o "$snapshot_path" || fatal "Failed to download Swift toolchain"
log "Installing Swift toolchain"
mkdir -p /tmp/snapshot
tar xfz "$snapshot_path" --strip-components 1 -C /tmp/snapshot
rsync -a /tmp/snapshot/* /
"$TAR_BIN" xfz "$snapshot_path" --strip-components 1 -C /
log "Obtaining Static SDK"
log "Static SDK URL: $static_sdk_url"
static_sdk_path="/tmp/$(basename "$static_sdk_url")"
curl -sL "$static_sdk_url" -o "$static_sdk_path"
"$CURL_BIN" -sfL "$static_sdk_url" -o "$static_sdk_path" || fatal "Failed to download Static SDK"
log "Looking for swift"
which swift
which swift || fatal "Failed to locate installed Swift"
log "Checking swift"
swift --version
+50
View File
@@ -0,0 +1,50 @@
#!/bin/bash
##===----------------------------------------------------------------------===##
##
## This source file is part of the SwiftNIO open source project
##
## Copyright (c) 2025 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
##
##===----------------------------------------------------------------------===##
set -uo pipefail
log() { printf -- "** %s\n" "$*" >&2; }
error() { printf -- "** ERROR: %s\n" "$*" >&2; }
fatal() { error "$@"; exit 1; }
if command -v apt-get >/dev/null; then
PACKAGE_MANAGER_BIN="apt"
apt-get update > /dev/null
elif command -v yum >/dev/null; then
PACKAGE_MANAGER_BIN="yum"
else
fatal "Cannot find either 'apt' or 'yum'"
fi
log "Installing standard Swift pre-requisites" # pre-reqs list taken from swift.org
DEBIAN_FRONTEND=noninteractive "$PACKAGE_MANAGER_BIN" install -y\
binutils\
git\
gnupg2\
libc6-dev\
libcurl4-openssl-dev\
libedit2\
libgcc-11-dev\
libpython3-dev\
libsqlite3-0\
libstdc++-11-dev\
libxml2-dev\
libz3-dev\
pkg-config\
python3-lldb-13\
tzdata\
unzip\
zlib1g-dev\
> /dev/null