From 223b0e8eac242485495a662f8345f199f739e12c Mon Sep 17 00:00:00 2001 From: George Barnett Date: Thu, 18 Jul 2024 09:16:59 +0100 Subject: [PATCH 1/3] Add manual control to NIOLockedValueBox (#2786) Motivation: NIOLockedValueBox has a 'safer' API than NIOLock as it only provides scoped access to its boxed value. NIOLock requires users to only access protected state while the lock is acquired. As such NIOLockedValueBox should be preferred where possible. However, there are cases where manual control must be used (such as storing a continuation) and users must use a NIOLock for this. There are two downsides to this: 1. All other access to the protected state must use the NIOLock API putting the onus on the developer to only access the protected state while the lock is held. 2. NIOLock can't store its protected state inline which typically results in users storing it on a class. Modifications: - Add an 'unsafe' view to NIOLockedValueBox which allows users to manually control the lock and access its protected state - Update NIOAsyncWriter and NIOThrowingAsyncSequenceProducer to use NIOLockedValueBox Result: - Safer locking API is used in more places - Fewer allocations --- ...reBenchmarks.NIOAsyncChannel.init.p90.json | 2 +- ...reBenchmarks.NIOAsyncChannel.init.p90.json | 2 +- ...reBenchmarks.NIOAsyncChannel.init.p90.json | 2 +- ...reBenchmarks.NIOAsyncChannel.init.p90.json | 2 +- ...reBenchmarks.NIOAsyncChannel.init.p90.json | 2 +- .../NIOLockedValueBox.swift | 40 +++++ .../AsyncSequences/NIOAsyncWriter.swift | 117 ++++++++------ .../NIOThrowingAsyncSequenceProducer.swift | 149 +++++++++++------- .../NIOAsyncSequenceTests.swift | 10 +- .../AsyncSequences/NIOAsyncWriterTests.swift | 2 +- .../NIOThrowingAsyncSequenceTests.swift | 30 ++-- 11 files changed, 228 insertions(+), 130 deletions(-) diff --git a/Benchmarks/Thresholds/5.10/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json b/Benchmarks/Thresholds/5.10/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json index 2554cd2c39..882a60c306 100644 --- a/Benchmarks/Thresholds/5.10/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json +++ b/Benchmarks/Thresholds/5.10/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 10 + "mallocCountTotal" : 8 } diff --git a/Benchmarks/Thresholds/5.8/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json b/Benchmarks/Thresholds/5.8/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json index 2554cd2c39..882a60c306 100644 --- a/Benchmarks/Thresholds/5.8/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json +++ b/Benchmarks/Thresholds/5.8/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 10 + "mallocCountTotal" : 8 } diff --git a/Benchmarks/Thresholds/5.9/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json b/Benchmarks/Thresholds/5.9/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json index 2554cd2c39..882a60c306 100644 --- a/Benchmarks/Thresholds/5.9/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json +++ b/Benchmarks/Thresholds/5.9/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 10 + "mallocCountTotal" : 8 } diff --git a/Benchmarks/Thresholds/nightly-6.0/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json b/Benchmarks/Thresholds/nightly-6.0/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json index 2554cd2c39..882a60c306 100644 --- a/Benchmarks/Thresholds/nightly-6.0/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json +++ b/Benchmarks/Thresholds/nightly-6.0/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 10 + "mallocCountTotal" : 8 } diff --git a/Benchmarks/Thresholds/nightly-main/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json b/Benchmarks/Thresholds/nightly-main/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json index 2554cd2c39..882a60c306 100644 --- a/Benchmarks/Thresholds/nightly-main/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json +++ b/Benchmarks/Thresholds/nightly-main/NIOCoreBenchmarks.NIOAsyncChannel.init.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 10 + "mallocCountTotal" : 8 } diff --git a/Sources/NIOConcurrencyHelpers/NIOLockedValueBox.swift b/Sources/NIOConcurrencyHelpers/NIOLockedValueBox.swift index 2c57e01d33..06cf88529f 100644 --- a/Sources/NIOConcurrencyHelpers/NIOLockedValueBox.swift +++ b/Sources/NIOConcurrencyHelpers/NIOLockedValueBox.swift @@ -37,6 +37,46 @@ public struct NIOLockedValueBox { public func withLockedValue(_ mutate: (inout Value) throws -> T) rethrows -> T { return try self._storage.withLockedValue(mutate) } + + /// Provides an unsafe view over the lock and its value. + /// + /// This can be beneficial when you require fine grained control over the lock in some + /// situations but don't want lose the benefits of ``withLockedValue(_:)`` in others by + /// switching to ``NIOLock``. + public var unsafe: Unsafe { + Unsafe(_storage: self._storage) + } + + /// Provides an unsafe view over the lock and its value. + public struct Unsafe { + @usableFromInline + let _storage: LockStorage + + /// Manually acquire the lock. + @inlinable + public func lock() { + self._storage.lock() + } + + /// Manually release the lock. + @inlinable + public func unlock() { + self._storage.unlock() + } + + /// Mutate the value, assuming the lock has been acquired manually. + /// + /// - Parameter mutate: A closure with scoped access to the value. + /// - Returns: The result of the `mutate` closure. + @inlinable + public func withValueAssumingLockIsAcquired( + _ mutate: (_ value: inout Value) throws -> Result + ) rethrows -> Result { + return try self._storage.withUnsafeMutablePointerToHeader { value in + try mutate(&value.pointee) + } + } + } } extension NIOLockedValueBox: Sendable where Value: Sendable {} diff --git a/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift b/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift index fe7e6af235..163dcaf076 100644 --- a/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift +++ b/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift @@ -414,12 +414,12 @@ extension NIOAsyncWriter { extension NIOAsyncWriter { /// This is the underlying storage of the writer. The goal of this is to synchronize the access to all state. @usableFromInline - /* fileprivate */ internal final class Storage: @unchecked Sendable { + /* fileprivate */ internal struct Storage: Sendable { /// Internal type to generate unique yield IDs. /// /// This type has reference semantics. @usableFromInline - struct YieldIDGenerator { + struct YieldIDGenerator: Sendable { /// A struct representing a unique yield ID. @usableFromInline struct YieldID: Equatable, Sendable { @@ -445,27 +445,43 @@ extension NIOAsyncWriter { } } - /// The lock that protects our state. - @usableFromInline - /* private */ internal let _lock = NIOLock() /// The counter used to assign an ID to all our yields. @usableFromInline /* private */ internal let _yieldIDGenerator = YieldIDGenerator() /// The state machine. @usableFromInline - /* private */ internal var _stateMachine: StateMachine + /* private */ internal let _state: NIOLockedValueBox + + @usableFromInline + struct State: Sendable { + @usableFromInline + var stateMachine: StateMachine + @usableFromInline + var didSuspend: (@Sendable () -> Void)? + + @inlinable + init(stateMachine: StateMachine) { + self.stateMachine = stateMachine + self.didSuspend = nil + } + } + /// Hook used in testing. @usableFromInline - internal var _didSuspend: (() -> Void)? + internal func _setDidSuspend(_ didSuspend: (@Sendable () -> Void)?) { + self._state.withLockedValue { + $0.didSuspend = didSuspend + } + } @inlinable internal var isWriterFinished: Bool { - self._lock.withLock { self._stateMachine.isWriterFinished } + self._state.withLockedValue { $0.stateMachine.isWriterFinished } } @inlinable internal var isSinkFinished: Bool { - self._lock.withLock { self._stateMachine.isSinkFinished } + self._state.withLockedValue { $0.stateMachine.isSinkFinished } } @inlinable @@ -473,10 +489,8 @@ extension NIOAsyncWriter { isWritable: Bool, delegate: Delegate ) { - self._stateMachine = .init( - isWritable: isWritable, - delegate: delegate - ) + let state = State(stateMachine: StateMachine(isWritable: isWritable, delegate: delegate)) + self._state = NIOLockedValueBox(state) } @inlinable @@ -484,8 +498,8 @@ extension NIOAsyncWriter { // We must not resume the continuation while holding the lock // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler - let action = self._lock.withLock { - self._stateMachine.setWritability(to: writability) + let action = self._state.withLockedValue { + $0.stateMachine.setWritability(to: writability) } switch action { @@ -516,39 +530,42 @@ extension NIOAsyncWriter { return try await withTaskCancellationHandler { // We are manually locking here to hold the lock across the withCheckedContinuation call - self._lock.lock() + let unsafe = self._state.unsafe + unsafe.lock() - let action = self._stateMachine.yield(yieldID: yieldID) + let action = unsafe.withValueAssumingLockIsAcquired { + $0.stateMachine.yield(yieldID: yieldID) + } switch action { case .callDidYield(let delegate): // We are allocating a new Deque for every write here - self._lock.unlock() + unsafe.unlock() delegate.didYield(contentsOf: Deque(sequence)) self.unbufferQueuedEvents() return .yielded case .throwError(let error): - self._lock.unlock() + unsafe.unlock() throw error case .suspendTask: return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - self._stateMachine.yield( - continuation: continuation, - yieldID: yieldID - ) + let didSuspend = unsafe.withValueAssumingLockIsAcquired { + $0.stateMachine.yield(continuation: continuation, yieldID: yieldID) + return $0.didSuspend + } - self._lock.unlock() - self._didSuspend?() + unsafe.unlock() + didSuspend?() } } } onCancel: { // We must not resume the continuation while holding the lock // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler - let action = self._lock.withLock { - self._stateMachine.cancel(yieldID: yieldID) + let action = self._state.withLockedValue { + $0.stateMachine.cancel(yieldID: yieldID) } switch action { @@ -580,39 +597,41 @@ extension NIOAsyncWriter { return try await withTaskCancellationHandler { // We are manually locking here to hold the lock across the withCheckedContinuation call - self._lock.lock() + let unsafe = self._state.unsafe + unsafe.lock() - let action = self._stateMachine.yield(yieldID: yieldID) + let action = unsafe.withValueAssumingLockIsAcquired { + $0.stateMachine.yield(yieldID: yieldID) + } switch action { case .callDidYield(let delegate): // We are allocating a new Deque for every write here - self._lock.unlock() + unsafe.unlock() delegate.didYield(element) self.unbufferQueuedEvents() return .yielded case .throwError(let error): - self._lock.unlock() + unsafe.unlock() throw error case .suspendTask: return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - self._stateMachine.yield( - continuation: continuation, - yieldID: yieldID - ) - - self._lock.unlock() - self._didSuspend?() + let didSuspend = unsafe.withValueAssumingLockIsAcquired { + $0.stateMachine.yield(continuation: continuation, yieldID: yieldID) + return $0.didSuspend + } + unsafe.unlock() + didSuspend?() } } } onCancel: { // We must not resume the continuation while holding the lock - // because it can deadlock in combination with the underlying ulock + // because it can deadlock in combination with the underlying lock // in cases where we race with a cancellation handler - let action = self._lock.withLock { - self._stateMachine.cancel(yieldID: yieldID) + let action = self._state.withLockedValue { + $0.stateMachine.cancel(yieldID: yieldID) } switch action { @@ -630,8 +649,8 @@ extension NIOAsyncWriter { // We must not resume the continuation while holding the lock // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler - let action = self._lock.withLock { - self._stateMachine.writerFinish(error: error) + let action = self._state.withLockedValue { + $0.stateMachine.writerFinish(error: error) } switch action { @@ -651,8 +670,8 @@ extension NIOAsyncWriter { // We must not resume the continuation while holding the lock // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler - let action = self._lock.withLock { - self._stateMachine.sinkFinish(error: error) + let action = self._state.withLockedValue { + $0.stateMachine.sinkFinish(error: error) } switch action { @@ -667,7 +686,7 @@ extension NIOAsyncWriter { @inlinable /* fileprivate */ internal func unbufferQueuedEvents() { - while let action = self._lock.withLock({ self._stateMachine.unbufferQueuedEvents()}) { + while let action = self._state.withLockedValue({ $0.stateMachine.unbufferQueuedEvents()}) { switch action { case .callDidTerminate(let delegate, let error): delegate.didTerminate(error: error) @@ -684,12 +703,12 @@ extension NIOAsyncWriter { @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension NIOAsyncWriter { @usableFromInline - /* private */ internal struct StateMachine { + /* private */ internal struct StateMachine: Sendable { @usableFromInline typealias YieldID = Storage.YieldIDGenerator.YieldID /// This is a small helper struct to encapsulate the two different values for a suspended yield. @usableFromInline - /* private */ internal struct SuspendedYield { + /* private */ internal struct SuspendedYield: Sendable { /// The yield's ID. @usableFromInline var yieldID: YieldID @@ -715,7 +734,7 @@ extension NIOAsyncWriter { /// The current state of our ``NIOAsyncWriter``. @usableFromInline - /* private */ internal enum State: CustomStringConvertible { + /* private */ internal enum State: Sendable, CustomStringConvertible { /// The initial state before either a call to ``NIOAsyncWriter/yield(contentsOf:)`` or /// ``NIOAsyncWriter/finish(completion:)`` happened. case initial( diff --git a/Sources/NIOCore/AsyncSequences/NIOThrowingAsyncSequenceProducer.swift b/Sources/NIOCore/AsyncSequences/NIOThrowingAsyncSequenceProducer.swift index 7b852dd6b6..0477c01969 100644 --- a/Sources/NIOCore/AsyncSequences/NIOThrowingAsyncSequenceProducer.swift +++ b/Sources/NIOCore/AsyncSequences/NIOThrowingAsyncSequenceProducer.swift @@ -388,23 +388,41 @@ extension NIOThrowingAsyncSequenceProducer { extension NIOThrowingAsyncSequenceProducer { /// This is the underlying storage of the sequence. The goal of this is to synchronize the access to all state. @usableFromInline - /* fileprivate */ internal final class Storage: @unchecked Sendable { - /// The lock that protects our state. + /* fileprivate */ internal struct Storage: Sendable { @usableFromInline - /* private */ internal let _lock = NIOLock() - /// The state machine. - @usableFromInline - /* private */ internal var _stateMachine: StateMachine - /// The delegate. + struct State: Sendable { + @usableFromInline + var stateMachine: StateMachine + @usableFromInline + var delegate: Delegate? + @usableFromInline + var didSuspend: (@Sendable () -> Void)? + + @inlinable + init( + stateMachine: StateMachine, + delegate: Delegate? = nil, + didSuspend: (@Sendable () -> Void)? = nil + ) { + self.stateMachine = stateMachine + self.delegate = delegate + self.didSuspend = didSuspend + } + } + @usableFromInline - /* private */ internal var _delegate: Delegate? - /// Hook used in testing. + internal let _state: NIOLockedValueBox + @usableFromInline - internal var _didSuspend: (() -> Void)? + internal func _setDidSuspend(_ didSuspend: (@Sendable () -> Void)?) { + self._state.withLockedValue { + $0.didSuspend = didSuspend + } + } @inlinable var isFinished: Bool { - self._lock.withLock { self._stateMachine.isFinished } + self._state.withLockedValue { $0.stateMachine.isFinished } } @usableFromInline @@ -412,19 +430,22 @@ extension NIOThrowingAsyncSequenceProducer { backPressureStrategy: Strategy, delegate: Delegate ) { - self._stateMachine = .init(backPressureStrategy: backPressureStrategy) - self._delegate = delegate + let state = State( + stateMachine: .init(backPressureStrategy: backPressureStrategy), + delegate: delegate + ) + self._state = NIOLockedValueBox(state) } @inlinable /* fileprivate */ internal func sequenceDeinitialized() { - let delegate: Delegate? = self._lock.withLock { - let action = self._stateMachine.sequenceDeinitialized() + let delegate: Delegate? = self._state.withLockedValue { + let action = $0.stateMachine.sequenceDeinitialized() switch action { case .callDidTerminate: - let delegate = self._delegate - self._delegate = nil + let delegate = $0.delegate + $0.delegate = nil return delegate case .none: @@ -437,20 +458,20 @@ extension NIOThrowingAsyncSequenceProducer { @inlinable /* fileprivate */ internal func iteratorInitialized() { - self._lock.withLock { - self._stateMachine.iteratorInitialized() + self._state.withLockedValue { + $0.stateMachine.iteratorInitialized() } } @inlinable /* fileprivate */ internal func iteratorDeinitialized() { - let delegate: Delegate? = self._lock.withLock { - let action = self._stateMachine.iteratorDeinitialized() + let delegate: Delegate? = self._state.withLockedValue { + let action = $0.stateMachine.iteratorDeinitialized() switch action { case .callDidTerminate: - let delegate = self._delegate - self._delegate = nil + let delegate = $0.delegate + $0.delegate = nil return delegate @@ -467,8 +488,8 @@ extension NIOThrowingAsyncSequenceProducer { // We must not resume the continuation while holding the lock // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler - let action = self._lock.withLock { - self._stateMachine.yield(sequence) + let action = self._state.withLockedValue { + $0.stateMachine.yield(sequence) } switch action { @@ -498,13 +519,13 @@ extension NIOThrowingAsyncSequenceProducer { // We must not resume the continuation while holding the lock // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler - let (delegate, action): (Delegate?, NIOThrowingAsyncSequenceProducer.StateMachine.FinishAction) = self._lock.withLock { - let action = self._stateMachine.finish(failure) - + let (delegate, action): (Delegate?, NIOThrowingAsyncSequenceProducer.StateMachine.FinishAction) = self._state.withLockedValue { + let action = $0.stateMachine.finish(failure) + switch action { case .resumeContinuationWithFailureAndCallDidTerminate: - let delegate = self._delegate - self._delegate = nil + let delegate = $0.delegate + $0.delegate = nil return (delegate, action) case .none: @@ -530,28 +551,36 @@ extension NIOThrowingAsyncSequenceProducer { @inlinable /* fileprivate */ internal func next() async throws -> Element? { - try await withTaskCancellationHandler { - self._lock.lock() + try await withTaskCancellationHandler { () async throws -> Element? in + let unsafe = self._state.unsafe + unsafe.lock() - let action = self._stateMachine.next() + let action = unsafe.withValueAssumingLockIsAcquired { + $0.stateMachine.next() + } switch action { case .returnElement(let element): - self._lock.unlock() + unsafe.unlock() return element case .returnElementAndCallProduceMore(let element): - let delegate = self._delegate - self._lock.unlock() + let delegate = unsafe.withValueAssumingLockIsAcquired { + $0.delegate + } + unsafe.unlock() delegate?.produceMore() return element case .returnFailureAndCallDidTerminate(let failure): - let delegate = self._delegate - self._delegate = nil - self._lock.unlock() + let delegate = unsafe.withValueAssumingLockIsAcquired { + let delegate = $0.delegate + $0.delegate = nil + return delegate + } + unsafe.unlock() delegate?.didTerminate() @@ -564,7 +593,7 @@ extension NIOThrowingAsyncSequenceProducer { } case .returnCancellationError: - self._lock.unlock() + unsafe.unlock() // We have deprecated the generic Failure type in the public API and Failure should // now be `Swift.Error`. However, if users have not migrated to the new API they could // still use a custom generic Error type and this cast might fail. @@ -579,45 +608,55 @@ extension NIOThrowingAsyncSequenceProducer { return nil case .returnNil: - self._lock.unlock() + unsafe.unlock() return nil case .suspendTask: // It is safe to hold the lock across this method // since the closure is guaranteed to be run straight away - return try await withCheckedThrowingContinuation { continuation in - let action = self._stateMachine.next(for: continuation) + return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + let (action, callDidSuspend) = unsafe.withValueAssumingLockIsAcquired { + let action = $0.stateMachine.next(for: continuation) + let callDidSuspend = $0.didSuspend != nil + return (action, callDidSuspend) + } switch action { case .callProduceMore: - let delegate = _delegate - self._lock.unlock() + let delegate = unsafe.withValueAssumingLockIsAcquired { + $0.delegate + } + unsafe.unlock() delegate?.produceMore() case .none: - self._lock.unlock() + unsafe.unlock() + } + + if callDidSuspend { + let didSuspend = self._state.withLockedValue { $0.didSuspend } + didSuspend?() } - self._didSuspend?() } } } onCancel: { // We must not resume the continuation while holding the lock // because it can deadlock in combination with the underlying ulock // in cases where we race with a cancellation handler - let (delegate, action): (Delegate?, NIOThrowingAsyncSequenceProducer.StateMachine.CancelledAction) = self._lock.withLock { - let action = self._stateMachine.cancelled() + let (delegate, action): (Delegate?, NIOThrowingAsyncSequenceProducer.StateMachine.CancelledAction) = self._state.withLockedValue { + let action = $0.stateMachine.cancelled() switch action { case .callDidTerminate: - let delegate = self._delegate - self._delegate = nil + let delegate = $0.delegate + $0.delegate = nil return (delegate, action) case .resumeContinuationWithCancellationErrorAndCallDidTerminate: - let delegate = self._delegate - self._delegate = nil + let delegate = $0.delegate + $0.delegate = nil return (delegate, action) @@ -658,9 +697,9 @@ extension NIOThrowingAsyncSequenceProducer { @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension NIOThrowingAsyncSequenceProducer { @usableFromInline - /* private */ internal struct StateMachine { + /* private */ internal struct StateMachine: Sendable { @usableFromInline - /* private */ internal enum State { + /* private */ internal enum State: Sendable { /// The initial state before either a call to `yield()` or a call to `next()` happened case initial( backPressureStrategy: Strategy, diff --git a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncSequenceTests.swift b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncSequenceTests.swift index db2471c43b..4f7b9ec361 100644 --- a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncSequenceTests.swift +++ b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncSequenceTests.swift @@ -269,7 +269,7 @@ final class NIOAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._throwingSequence._storage._didSuspend = { suspended.fulfill() } + sequence._throwingSequence._storage._setDidSuspend { suspended.fulfill() } async let element = sequence.first { _ in true } @@ -351,7 +351,7 @@ final class NIOAsyncSequenceProducerTests: XCTestCase { let element: Int? = try await withThrowingTaskGroup(of: Int?.self) { group in let suspended = expectation(description: "task suspended") - sequence!._throwingSequence._storage._didSuspend = { suspended.fulfill() } + sequence!._throwingSequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { let element = await sequence!.first { _ in true } @@ -439,7 +439,7 @@ final class NIOAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._throwingSequence._storage._didSuspend = { suspended.fulfill() } + sequence._throwingSequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { @@ -462,7 +462,7 @@ final class NIOAsyncSequenceProducerTests: XCTestCase { let resumed = expectation(description: "task resumed") let cancelled = expectation(description: "task cancelled") - sequence._throwingSequence._storage._didSuspend = { suspended.fulfill() } + sequence._throwingSequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { let iterator = sequence.makeAsyncIterator() @@ -490,7 +490,7 @@ final class NIOAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._throwingSequence._storage._didSuspend = { suspended.fulfill() } + sequence._throwingSequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { let iterator = sequence.makeAsyncIterator() diff --git a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift index 9b93841252..5787068510 100644 --- a/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift +++ b/Tests/NIOCoreTests/AsyncSequences/NIOAsyncWriterTests.swift @@ -77,7 +77,7 @@ final class NIOAsyncWriterTests: XCTestCase { ) self.writer = newWriter.writer self.sink = newWriter.sink - self.sink._storage._didSuspend = self.delegate.didSuspend + self.sink._storage._setDidSuspend { self.delegate.didSuspend() } } override func tearDown() { diff --git a/Tests/NIOCoreTests/AsyncSequences/NIOThrowingAsyncSequenceTests.swift b/Tests/NIOCoreTests/AsyncSequences/NIOThrowingAsyncSequenceTests.swift index 237be2c28b..0d9acc1018 100644 --- a/Tests/NIOCoreTests/AsyncSequences/NIOThrowingAsyncSequenceTests.swift +++ b/Tests/NIOCoreTests/AsyncSequences/NIOThrowingAsyncSequenceTests.swift @@ -107,7 +107,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let element: Int? = try await withThrowingTaskGroup(of: Int?.self) { group in let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { try await sequence.first { _ in true } @@ -135,7 +135,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let element: Int? = try await withThrowingTaskGroup(of: Int?.self) { group in let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { try await sequence.first { _ in true } @@ -163,7 +163,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { await withThrowingTaskGroup(of: Void.self) { group in let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { _ = try await sequence.first { _ in true } @@ -188,7 +188,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { await withThrowingTaskGroup(of: Void.self) { group in let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { _ = try await sequence.first { _ in true } @@ -247,7 +247,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let element: Int? = try await withThrowingTaskGroup(of: Int?.self) { group in let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { let element = try await sequence.first { _ in true } @@ -330,7 +330,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { await XCTAssertThrowsError(try await withThrowingTaskGroup(of: Void.self) { group in let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } group.addTask { _ = try await sequence.first { _ in true } @@ -442,7 +442,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let element: Int? = try await withThrowingTaskGroup(of: Int?.self) { group in let suspended = expectation(description: "task suspended") - sequence!._storage._didSuspend = { suspended.fulfill() } + sequence!._storage._setDidSuspend { suspended.fulfill() } group.addTask { let element = try await sequence!.first { _ in true } @@ -532,7 +532,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { let iterator = sequence.makeAsyncIterator() @@ -563,7 +563,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = new.sequence let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { let iterator = sequence.makeAsyncIterator() @@ -587,7 +587,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let resumed = expectation(description: "task resumed") let cancelled = expectation(description: "task cancelled") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { let iterator = sequence.makeAsyncIterator() @@ -615,7 +615,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } let task: Task = Task { let iterator = sequence.makeAsyncIterator() @@ -689,7 +689,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } Task { // Would prefer to use async let _ here but that is not allowed yet @@ -707,7 +707,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } Task { // Would prefer to use async let _ here but that is not allowed yet @@ -727,7 +727,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } Task { // Would prefer to use async let _ here but that is not allowed yet @@ -747,7 +747,7 @@ final class NIOThrowingAsyncSequenceProducerTests: XCTestCase { let sequence = try XCTUnwrap(self.sequence) let suspended = expectation(description: "task suspended") - sequence._storage._didSuspend = { suspended.fulfill() } + sequence._storage._setDidSuspend { suspended.fulfill() } Task { // Would prefer to use async let _ here but that is not allowed yet From 7948ed21044668078e2afc8e70cee087234398ea Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Thu, 18 Jul 2024 11:55:48 +0100 Subject: [PATCH 2/3] ChannelHandler: provide static (un)wrap(In|Out)bound(In|Out) (#2791) --- .../NIOPosixBenchmarks/TCPEcho.swift | 2 +- .../test_01_resources/shared.swift | 16 +++--- .../test_1000_tcpconnections.swift | 2 +- .../test_1000_udp_reqs.swift | 2 +- .../test_decode_1000_ws_frames.swift | 4 +- .../test_ping_pong_1000_reqs_1_conn.swift | 10 ++-- .../FullRequestResponse.swift | 12 ++-- Sources/NIOChatClient/main.swift | 2 +- Sources/NIOChatServer/main.swift | 6 +- .../AsyncChannel/AsyncChannelHandler.swift | 6 +- Sources/NIOCore/Codec.swift | 18 ++++-- Sources/NIOCore/NIOAny.swift | 6 +- .../SingleStepByteToMessageDecoder.swift | 20 +++---- .../NIOCore/TypeAssistedChannelHandler.swift | 20 +++++++ Sources/NIOCrashTester/OutputGrepper.swift | 4 +- Sources/NIOEchoClient/main.swift | 4 +- Sources/NIOHTTP1/HTTPEncoder.swift | 16 +++--- Sources/NIOHTTP1/HTTPHeaderValidator.swift | 4 +- .../NIOHTTP1/HTTPServerPipelineHandler.swift | 10 ++-- .../HTTPServerProtocolErrorHandler.swift | 6 +- .../NIOHTTP1/HTTPServerUpgradeHandler.swift | 8 +-- .../NIOHTTPClientUpgradeHandler.swift | 12 ++-- .../NIOHTTP1/NIOHTTPObjectAggregator.swift | 8 +-- .../NIOTypedHTTPClientUpgradeHandler.swift | 8 +-- .../NIOTypedHTTPServerUpgradeHandler.swift | 2 +- Sources/NIOHTTP1Client/main.swift | 8 +-- Sources/NIOHTTP1Server/main.swift | 56 +++++++++---------- Sources/NIOMulticastChat/main.swift | 6 +- .../TCPThroughputBenchmark.swift | 4 +- .../NIOPerformanceTester/UDPBenchmark.swift | 2 +- Sources/NIOPerformanceTester/main.swift | 20 +++---- Sources/NIOPosix/Bootstrap.swift | 2 +- Sources/NIOTCPEchoClient/Client.swift | 2 +- Sources/NIOTCPEchoServer/Server.swift | 2 +- Sources/NIOTestUtils/NIOHTTP1TestServer.swift | 10 ++-- Sources/NIOUDPEchoClient/main.swift | 4 +- .../NIOWebSocketFrameAggregator.swift | 6 +- .../NIOWebSocket/WebSocketFrameDecoder.swift | 2 +- .../NIOWebSocket/WebSocketFrameEncoder.swift | 8 +-- .../WebSocketProtocolErrorHandler.swift | 2 +- Sources/NIOWebSocketServer/Server.swift | 8 +-- .../SingleStepByteToMessageDecoderTest.swift | 4 +- .../HTTPClientUpgradeTests.swift | 6 +- .../NIOHTTP1Tests/HTTPDecoderLengthTest.swift | 4 +- Tests/NIOHTTP1Tests/HTTPDecoderTest.swift | 20 +++---- .../NIOHTTP1Tests/HTTPServerClientTest.swift | 50 ++++++++--------- .../HTTPServerPipelineHandlerTest.swift | 16 +++--- .../HTTPServerProtocolErrorHandlerTest.swift | 4 +- .../HTTPServerUpgradeTests.swift | 8 +-- Tests/NIOHTTP1Tests/HTTPTest.swift | 2 +- .../NIOHTTPObjectAggregatorTest.swift | 4 +- .../AsyncChannelBootstrapTests.swift | 34 +++++------ Tests/NIOPosixTests/BootstrapTest.swift | 2 +- Tests/NIOPosixTests/ChannelPipelineTest.swift | 42 +++++++------- Tests/NIOPosixTests/ChannelTests.swift | 22 ++++---- Tests/NIOPosixTests/CodecTest.swift | 52 ++++++++--------- .../NIOPosixTests/DatagramChannelTests.swift | 16 +++--- Tests/NIOPosixTests/EventLoopTest.swift | 2 +- .../NIOPosixTests/IdleStateHandlerTest.swift | 2 +- Tests/NIOPosixTests/MulticastTest.swift | 2 +- Tests/NIOPosixTests/SALChannelTests.swift | 4 +- Tests/NIOPosixTests/SelectorTest.swift | 2 +- Tests/NIOPosixTests/SocketChannelTest.swift | 10 ++-- Tests/NIOPosixTests/StreamChannelsTest.swift | 24 ++++---- Tests/NIOPosixTests/TestUtils.swift | 2 +- .../UniversalBootstrapSupportTest.swift | 2 +- ...ationProtocolNegotiationHandlerTests.swift | 2 +- .../ByteToMessageDecoderVerifierTest.swift | 6 +- .../NIOHTTP1TestServerTest.swift | 6 +- .../WebSocketClientEndToEndTests.swift | 8 +-- .../WebSocketFrameDecoderTest.swift | 2 +- .../WebSocketServerEndToEndTests.swift | 2 +- 72 files changed, 369 insertions(+), 343 deletions(-) diff --git a/Benchmarks/Benchmarks/NIOPosixBenchmarks/TCPEcho.swift b/Benchmarks/Benchmarks/NIOPosixBenchmarks/TCPEcho.swift index a1ca7a5df4..762ab260f4 100644 --- a/Benchmarks/Benchmarks/NIOPosixBenchmarks/TCPEcho.swift +++ b/Benchmarks/Benchmarks/NIOPosixBenchmarks/TCPEcho.swift @@ -46,7 +46,7 @@ private final class EchoRequestChannelHandler: ChannelInboundHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) self.receivedData += buffer.readableBytes if self.receivedData == self.numberOfWrites * self.messageSize { diff --git a/IntegrationTests/tests_04_performance/test_01_resources/shared.swift b/IntegrationTests/tests_04_performance/test_01_resources/shared.swift index 2b2605d774..239cd0bad7 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/shared.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/shared.swift @@ -51,14 +51,14 @@ final class RepeatedRequests: ChannelInboundHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let respPart = self.unwrapInboundIn(data) + let respPart = Self.unwrapInboundIn(data) if case .end(nil) = respPart { if self.remainingNumberOfRequests <= 0 { context.channel.close().map { self.numberOfRequests - self.remainingNumberOfRequests }.cascade(to: self.isDonePromise) } else { self.remainingNumberOfRequests -= 1 - context.write(self.wrapOutboundOut(.head(RepeatedRequests.requestHead)), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(RepeatedRequests.requestHead)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } } } @@ -94,10 +94,10 @@ private final class SimpleHTTPServer: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - if case .head(let req) = self.unwrapInboundIn(data), req.uri == "/allocation-test-1" { - context.write(self.wrapOutboundOut(.head(self.responseHead)), promise: nil) - context.write(self.wrapOutboundOut(.body(.byteBuffer(self.responseBody(allocator: context.channel.allocator)))), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + if case .head(let req) = Self.unwrapInboundIn(data), req.uri == "/allocation-test-1" { + context.write(Self.wrapOutboundOut(.head(self.responseHead)), promise: nil) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(self.responseBody(allocator: context.channel.allocator)))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } } } @@ -200,7 +200,7 @@ enum UDPShared { // Forward the data. let envolope = AddressedEnvelope(remoteAddress: remoteAddress, data: buffer) - context.writeAndFlush(self.wrapOutboundOut(envolope), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(envolope), promise: nil) } else { // We're all done - hurrah! context.close(promise: nil) diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_1000_tcpconnections.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_1000_tcpconnections.swift index d43e5b21eb..3367fef147 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/test_1000_tcpconnections.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_1000_tcpconnections.swift @@ -20,7 +20,7 @@ fileprivate final class ReceiveAndCloseHandler: ChannelInboundHandler { public typealias OutboundOut = ByteBuffer func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let byteBuffer = self.unwrapInboundIn(data) + let byteBuffer = Self.unwrapInboundIn(data) precondition(byteBuffer.readableBytes == 1) context.channel.close(promise: nil) } diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_1000_udp_reqs.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_1000_udp_reqs.swift index b6fd21725e..619b746823 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/test_1000_udp_reqs.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_1000_udp_reqs.swift @@ -73,7 +73,7 @@ fileprivate final class ClientHandler: ChannelInboundHandler { // Send the data with ECN let metadata = AddressedEnvelope.Metadata(ecnState: .transportCapableFlag1) let envelope = AddressedEnvelope(remoteAddress: remoteAddress, data: buffer, metadata: metadata) - clientChannel.writeAndFlush(self.wrapOutboundOut(envelope), promise: nil) + clientChannel.writeAndFlush(Self.wrapOutboundOut(envelope), promise: nil) } func sendBytesAndWaitForReply(clientChannel: Channel) -> Int { diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_decode_1000_ws_frames.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_decode_1000_ws_frames.swift index 1b886c75b6..7c9d6ab239 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/test_decode_1000_ws_frames.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_decode_1000_ws_frames.swift @@ -21,8 +21,8 @@ class UnboxingChannelHandler: ChannelInboundHandler { typealias InboundOut = WebSocketFrame func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let data = self.unwrapInboundIn(data) - context.fireChannelRead(self.wrapInboundOut(data)) + let data = Self.unwrapInboundIn(data) + context.fireChannelRead(Self.wrapInboundOut(data)) } } diff --git a/IntegrationTests/tests_04_performance/test_01_resources/test_ping_pong_1000_reqs_1_conn.swift b/IntegrationTests/tests_04_performance/test_01_resources/test_ping_pong_1000_reqs_1_conn.swift index cc5404a46e..99fb379001 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/test_ping_pong_1000_reqs_1_conn.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/test_ping_pong_1000_reqs_1_conn.swift @@ -28,7 +28,7 @@ private final class PongDecoder: ByteToMessageDecoder { public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { if let ping = buffer.readInteger(as: UInt8.self) { - context.fireChannelRead(self.wrapInboundOut(ping)) + context.fireChannelRead(Self.wrapInboundOut(ping)) return .continue } else { return .needMoreData @@ -65,16 +65,16 @@ private final class PingHandler: ChannelInboundHandler { self.pingBuffer = context.channel.allocator.buffer(capacity: 1) self.pingBuffer.writeInteger(PingHandler.pingCode) - context.writeAndFlush(self.wrapOutboundOut(self.pingBuffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(self.pingBuffer), promise: nil) } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buf = self.unwrapInboundIn(data) + var buf = Self.unwrapInboundIn(data) if buf.readableBytes == 1 && buf.readInteger(as: UInt8.self) == PongHandler.pongCode { if self.remainingNumberOfRequests > 0 { self.remainingNumberOfRequests -= 1 - context.writeAndFlush(self.wrapOutboundOut(self.pingBuffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(self.pingBuffer), promise: nil) } else { context.close(promise: self.allDone) } @@ -102,7 +102,7 @@ private final class PongHandler: ChannelInboundHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let data = self.unwrapInboundIn(data) + let data = Self.unwrapInboundIn(data) if data == PingHandler.pingCode { context.writeAndFlush(NIOAny(self.pongBuffer), promise: nil) } else { diff --git a/Sources/NIOAsyncAwaitDemo/FullRequestResponse.swift b/Sources/NIOAsyncAwaitDemo/FullRequestResponse.swift index 33842eb896..944e132b49 100644 --- a/Sources/NIOAsyncAwaitDemo/FullRequestResponse.swift +++ b/Sources/NIOAsyncAwaitDemo/FullRequestResponse.swift @@ -22,10 +22,10 @@ public final class MakeFullRequestHandler: ChannelOutboundHandler { public typealias OutboundIn = HTTPRequestHead public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let req = self.unwrapOutboundIn(data) + let req = Self.unwrapOutboundIn(data) - context.write(self.wrapOutboundOut(.head(req)), promise: nil) - context.write(self.wrapOutboundOut(.end(nil)), promise: promise) + context.write(Self.wrapOutboundOut(.head(req)), promise: nil) + context.write(Self.wrapOutboundOut(.end(nil)), promise: promise) } } @@ -97,7 +97,7 @@ public final class RequestResponseHandler: ChannelDuplexHandl return } - let response = self.unwrapInboundIn(data) + let response = Self.unwrapInboundIn(data) let promise = self.promiseBuffer.removeFirst() promise.succeed(response) @@ -118,7 +118,7 @@ public final class RequestResponseHandler: ChannelDuplexHandl } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let (request, responsePromise) = self.unwrapOutboundIn(data) + let (request, responsePromise) = Self.unwrapOutboundIn(data) switch self.state { case .error(let error): assert(self.promiseBuffer.count == 0) @@ -126,7 +126,7 @@ public final class RequestResponseHandler: ChannelDuplexHandl promise?.fail(error) case .operational: self.promiseBuffer.append(responsePromise) - context.write(self.wrapOutboundOut(request), promise: promise) + context.write(Self.wrapOutboundOut(request), promise: promise) } } } diff --git a/Sources/NIOChatClient/main.swift b/Sources/NIOChatClient/main.swift index 016b4c37f0..1251b11fa9 100644 --- a/Sources/NIOChatClient/main.swift +++ b/Sources/NIOChatClient/main.swift @@ -27,7 +27,7 @@ private final class ChatHandler: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buffer = self.unwrapInboundIn(data) + var buffer = Self.unwrapInboundIn(data) while let byte: UInt8 = buffer.readInteger() { printByte(byte) } diff --git a/Sources/NIOChatServer/main.swift b/Sources/NIOChatServer/main.swift index 6e73625afa..e45af00e7d 100644 --- a/Sources/NIOChatServer/main.swift +++ b/Sources/NIOChatServer/main.swift @@ -27,7 +27,7 @@ final class LineDelimiterCodec: ByteToMessageDecoder { public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { let readable = buffer.withUnsafeReadableBytes { $0.firstIndex(of: newLine) } if let r = readable { - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: r + 1)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: r + 1)!)) return .continue } return .needMoreData @@ -64,7 +64,7 @@ final class ChatHandler: ChannelInboundHandler { var buffer = channel.allocator.buffer(capacity: 64) buffer.writeString("(ChatServer) - Welcome to: \(context.localAddress!)\n") - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) } public func channelInactive(context: ChannelHandlerContext) { @@ -79,7 +79,7 @@ final class ChatHandler: ChannelInboundHandler { public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let id = ObjectIdentifier(context.channel) - var read = self.unwrapInboundIn(data) + var read = Self.unwrapInboundIn(data) // 64 should be good enough for the ipaddress var buffer = context.channel.allocator.buffer(capacity: read.readableBytes + 64) diff --git a/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift b/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift index af0f659c38..5f76313a73 100644 --- a/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift +++ b/Sources/NIOCore/AsyncChannel/AsyncChannelHandler.swift @@ -176,7 +176,7 @@ extension NIOAsyncChannelHandler: ChannelInboundHandler { @inlinable func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let unwrapped = self.unwrapInboundIn(data) + let unwrapped = Self.unwrapInboundIn(data) switch self.transformation { case .syncWrapping(let transformation): @@ -477,7 +477,7 @@ extension NIOAsyncChannelHandler { @inlinable func _doOutboundWrites(context: ChannelHandlerContext, writes: Deque) { for write in writes { - context.write(self.wrapOutboundOut(write), promise: nil) + context.write(Self.wrapOutboundOut(write), promise: nil) } context.flush() @@ -485,7 +485,7 @@ extension NIOAsyncChannelHandler { @inlinable func _doOutboundWrite(context: ChannelHandlerContext, write: OutboundOut) { - context.write(self.wrapOutboundOut(write), promise: nil) + context.write(Self.wrapOutboundOut(write), promise: nil) context.flush() } } diff --git a/Sources/NIOCore/Codec.swift b/Sources/NIOCore/Codec.swift index caedccfd17..a67e840fa6 100644 --- a/Sources/NIOCore/Codec.swift +++ b/Sources/NIOCore/Codec.swift @@ -235,10 +235,16 @@ extension ByteToMessageDecoder { return buffer.storageCapacity > 1024 && (buffer.storageCapacity - buffer.readerIndex) < buffer.readerIndex } + @inlinable public func wrapInboundOut(_ value: InboundOut) -> NIOAny { return NIOAny(value) } - + + @inlinable + public static func wrapInboundOut(_ value: InboundOut) -> NIOAny { + return NIOAny(value) + } + public mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { while try self.decode(context: context, buffer: &buffer) == .continue {} return .needMoreData @@ -503,7 +509,7 @@ extension ByteToMessageHandler: CanDequeueWrites where Decoder: WriteObservingBy fileprivate func dequeueWrites() { while self.queuedWrites.count > 0 { // self.decoder can't be `nil`, this is only allowed to be called when we're not already on the stack - self.decoder!.write(data: self.unwrapOutboundIn(self.queuedWrites.removeFirst())) + self.decoder!.write(data: Self.unwrapOutboundIn(self.queuedWrites.removeFirst())) } } } @@ -639,7 +645,7 @@ extension ByteToMessageHandler: ChannelInboundHandler { /// Calls `decode` until there is nothing left to decode. public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) if case .error(let error) = self.state { context.fireErrorCaught(ByteToMessageDecoderError.dataReceivedInErrorState(error, buffer)) return @@ -696,7 +702,7 @@ extension ByteToMessageHandler: ChannelOutboundHandler, _ChannelOutboundHandler public typealias OutboundIn = Decoder.OutboundIn public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { if self.decoder != nil { - let data = self.unwrapOutboundIn(data) + let data = Self.unwrapOutboundIn(data) assert(self.queuedWrites.isEmpty) self.decoder!.write(data: data) } else { @@ -805,12 +811,12 @@ extension MessageToByteHandler { // there's actually some work to do here break } - let data = self.unwrapOutboundIn(data) + let data = Self.unwrapOutboundIn(data) do { self.buffer!.clear() try self.encoder.encode(data: data, out: &self.buffer!) - context.write(self.wrapOutboundOut(self.buffer!), promise: promise) + context.write(Self.wrapOutboundOut(self.buffer!), promise: promise) } catch { self.state = .error(error) promise?.fail(error) diff --git a/Sources/NIOCore/NIOAny.swift b/Sources/NIOCore/NIOAny.swift index 824e23b712..c489e2b7de 100644 --- a/Sources/NIOCore/NIOAny.swift +++ b/Sources/NIOCore/NIOAny.swift @@ -37,9 +37,9 @@ /// dynamically at run-time. Yet, we assert that in any configuration the channel handler before /// `SandwichHandler` does actually send us a stream of `Bacon`. /// */ -/// let bacon = self.unwrapInboundIn(data) /* `Bacon` or crash */ +/// let bacon = Self.unwrapInboundIn(data) /* `Bacon` or crash */ /// let sandwich = makeSandwich(bacon) -/// context.fireChannelRead(self.wrapInboundOut(sandwich)) /* as promised we deliver a wrapped `Sandwich` */ +/// context.fireChannelRead(Self.wrapInboundOut(sandwich)) /* as promised we deliver a wrapped `Sandwich` */ /// } /// } public struct NIOAny { @@ -48,7 +48,7 @@ public struct NIOAny { /// Wrap a value in a `NIOAny`. In most cases you should not create a `NIOAny` directly using this constructor. /// The abstraction that accepts values of type `NIOAny` must also provide a mechanism to do the wrapping. An - /// example is a `ChannelInboundHandler` which provides `self.wrapInboundOut(aValueOfTypeInboundOut)`. + /// example is a `ChannelInboundHandler` which provides `Self.wrapInboundOut(aValueOfTypeInboundOut)`. @inlinable public init(_ value: T) { self._storage = _NIOAny(value) diff --git a/Sources/NIOCore/SingleStepByteToMessageDecoder.swift b/Sources/NIOCore/SingleStepByteToMessageDecoder.swift index 2341a0550e..467b44ab2b 100644 --- a/Sources/NIOCore/SingleStepByteToMessageDecoder.swift +++ b/Sources/NIOCore/SingleStepByteToMessageDecoder.swift @@ -56,7 +56,7 @@ public protocol NIOSingleStepByteToMessageDecoder: ByteToMessageDecoder { extension NIOSingleStepByteToMessageDecoder { public mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let message = try self.decode(buffer: &buffer) { - context.fireChannelRead(self.wrapInboundOut(message)) + context.fireChannelRead(Self.wrapInboundOut(message)) return .continue } else { return .needMoreData @@ -65,7 +65,7 @@ extension NIOSingleStepByteToMessageDecoder { public mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { if let message = try self.decodeLast(buffer: &buffer, seenEOF: seenEOF) { - context.fireChannelRead(self.wrapInboundOut(message)) + context.fireChannelRead(Self.wrapInboundOut(message)) return .continue } else { return .needMoreData @@ -110,12 +110,12 @@ extension NIOSingleStepByteToMessageDecoder { /// private var messageProcessor: NIOSingleStepByteToMessageProcessor? = nil /// /// func channelRead(context: ChannelHandlerContext, data: NIOAny) { -/// let req = self.unwrapInboundIn(data) +/// let req = Self.unwrapInboundIn(data) /// do { /// switch req { /// case .head(let head): /// // simply forward on the head -/// context.fireChannelRead(self.wrapInboundOut(.head(head))) +/// context.fireChannelRead(Self.wrapInboundOut(.head(head))) /// case .body(let body): /// if self.messageProcessor == nil { /// self.messageProcessor = NIOSingleStepByteToMessageProcessor(TwoByteStringCodec()) @@ -128,7 +128,7 @@ extension NIOSingleStepByteToMessageDecoder { /// try self.messageProcessor?.finishProcessing(seenEOF: false) { message in /// self.channelReadMessage(context: context, message: message) /// } -/// context.fireChannelRead(self.wrapInboundOut(.end(trailers))) +/// context.fireChannelRead(Self.wrapInboundOut(.end(trailers))) /// } /// } catch { /// context.fireErrorCaught(error) @@ -137,7 +137,7 @@ extension NIOSingleStepByteToMessageDecoder { /// /// // Forward on the body messages as whole messages /// func channelReadMessage(context: ChannelHandlerContext, message: String) { -/// context.fireChannelRead(self.wrapInboundOut(.body(message))) +/// context.fireChannelRead(Self.wrapInboundOut(.body(message))) /// } /// } /// @@ -148,7 +148,7 @@ extension NIOSingleStepByteToMessageDecoder { /// var msgs: [String] = [] /// /// func channelRead(context: ChannelHandlerContext, data: NIOAny) { -/// let message = self.unwrapInboundIn(data) +/// let message = Self.unwrapInboundIn(data) /// /// switch message { /// case .head(let head): @@ -165,13 +165,13 @@ extension NIOSingleStepByteToMessageDecoder { /// var headers = HTTPHeaders() /// headers.add(name: "content-length", value: String(responseBuffer.readableBytes)) /// -/// context.write(self.wrapOutboundOut(HTTPServerResponsePart.head( +/// context.write(Self.wrapOutboundOut(HTTPServerResponsePart.head( /// HTTPResponseHead(version: .http1_1, /// status: .ok, headers: headers))), promise: nil) /// -/// context.write(self.wrapOutboundOut(HTTPServerResponsePart.body( +/// context.write(Self.wrapOutboundOut(HTTPServerResponsePart.body( /// .byteBuffer(responseBuffer))), promise: nil) -/// context.writeAndFlush(self.wrapOutboundOut(HTTPServerResponsePart.end(nil)), promise: nil) +/// context.writeAndFlush(Self.wrapOutboundOut(HTTPServerResponsePart.end(nil)), promise: nil) /// } /// } /// } diff --git a/Sources/NIOCore/TypeAssistedChannelHandler.swift b/Sources/NIOCore/TypeAssistedChannelHandler.swift index 00c09d5192..ce0a055d90 100644 --- a/Sources/NIOCore/TypeAssistedChannelHandler.swift +++ b/Sources/NIOCore/TypeAssistedChannelHandler.swift @@ -30,6 +30,11 @@ extension _EmittingChannelHandler { public func wrapOutboundOut(_ value: OutboundOut) -> NIOAny { return NIOAny(value) } + + @inlinable + public static func wrapOutboundOut(_ value: OutboundOut) -> NIOAny { + return NIOAny(value) + } } /// `ChannelHandler` which handles inbound I/O events for a `Channel`. @@ -62,6 +67,16 @@ extension ChannelInboundHandler { public func wrapInboundOut(_ value: InboundOut) -> NIOAny { return NIOAny(value) } + + @inlinable + public static func unwrapInboundIn(_ value: NIOAny) -> InboundIn { + return value.forceAs() + } + + @inlinable + public static func wrapInboundOut(_ value: InboundOut) -> NIOAny { + return NIOAny(value) + } } /// `ChannelHandler` which handles outbound I/O events or intercept an outbound I/O operation for a `Channel`. @@ -82,6 +97,11 @@ extension ChannelOutboundHandler { public func unwrapOutboundIn(_ value: NIOAny) -> OutboundIn { return value.forceAs() } + + @inlinable + public static func unwrapOutboundIn(_ value: NIOAny) -> OutboundIn { + return value.forceAs() + } } /// A combination of `ChannelInboundHandler` and `ChannelOutboundHandler`. diff --git a/Sources/NIOCrashTester/OutputGrepper.swift b/Sources/NIOCrashTester/OutputGrepper.swift index b40a329bbf..56dfb68a79 100644 --- a/Sources/NIOCrashTester/OutputGrepper.swift +++ b/Sources/NIOCrashTester/OutputGrepper.swift @@ -62,7 +62,7 @@ private final class GrepHandler: ChannelInboundHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let line = self.unwrapInboundIn(data) + let line = Self.unwrapInboundIn(data) if line.lowercased().contains("fatal error") || line.lowercased().contains("precondition failed") || line.lowercased().contains("assertion failed") { @@ -89,7 +89,7 @@ private struct NewlineFramer: ByteToMessageDecoder { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let firstNewline = buffer.readableBytesView.firstIndex(of: UInt8(ascii: "\n")) { let length = firstNewline - buffer.readerIndex + 1 - context.fireChannelRead(self.wrapInboundOut(String(buffer.readString(length: length)!.dropLast()))) + context.fireChannelRead(Self.wrapInboundOut(String(buffer.readString(length: length)!.dropLast()))) return .continue } else { return .needMoreData diff --git a/Sources/NIOEchoClient/main.swift b/Sources/NIOEchoClient/main.swift index f55df6d28d..ed22302eaf 100644 --- a/Sources/NIOEchoClient/main.swift +++ b/Sources/NIOEchoClient/main.swift @@ -29,11 +29,11 @@ private final class EchoHandler: ChannelInboundHandler { // We are connected. It's time to send the message to the server to initialize the ping-pong sequence. let buffer = context.channel.allocator.buffer(string: line) self.sendBytes = buffer.readableBytes - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var unwrappedInboundData = self.unwrapInboundIn(data) + var unwrappedInboundData = Self.unwrapInboundIn(data) self.sendBytes -= unwrappedInboundData.readableBytes receiveBuffer.writeBuffer(&unwrappedInboundData) diff --git a/Sources/NIOHTTP1/HTTPEncoder.swift b/Sources/NIOHTTP1/HTTPEncoder.swift index c79283ef87..90146aa974 100644 --- a/Sources/NIOHTTP1/HTTPEncoder.swift +++ b/Sources/NIOHTTP1/HTTPEncoder.swift @@ -177,7 +177,7 @@ public final class HTTPRequestEncoder: ChannelOutboundHandler, RemovableChannelH public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - switch self.unwrapOutboundIn(data) { + switch Self.unwrapOutboundIn(data) { case .head(var request): assert(!(request.headers.contains(name: "content-length") && request.headers[canonicalForm: "transfer-encoding"].contains("chunked"[...])), @@ -189,13 +189,13 @@ public final class HTTPRequestEncoder: ChannelOutboundHandler, RemovableChannelH self.isChunked = messageIsChunked(headers: request.headers, version: request.version) } - writeHead(wrapOutboundOut: self.wrapOutboundOut, writeStartLine: { buffer in + writeHead(wrapOutboundOut: Self.wrapOutboundOut, writeStartLine: { buffer in buffer.write(request: request) }, context: context, headers: request.headers, promise: promise) case .body(let bodyPart): - writeChunk(wrapOutboundOut: self.wrapOutboundOut, context: context, isChunked: self.isChunked, chunk: bodyPart, promise: promise) + writeChunk(wrapOutboundOut: Self.wrapOutboundOut, context: context, isChunked: self.isChunked, chunk: bodyPart, promise: promise) case .end(let trailers): - writeTrailers(wrapOutboundOut: self.wrapOutboundOut, context: context, isChunked: self.isChunked, trailers: trailers, promise: promise) + writeTrailers(wrapOutboundOut: Self.wrapOutboundOut, context: context, isChunked: self.isChunked, trailers: trailers, promise: promise) } } } @@ -243,7 +243,7 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - switch self.unwrapOutboundIn(data) { + switch Self.unwrapOutboundIn(data) { case .head(var response): assert(!(response.headers.contains(name: "content-length") && response.headers[canonicalForm: "transfer-encoding"].contains("chunked"[...])), @@ -256,13 +256,13 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel self.isChunked = messageIsChunked(headers: response.headers, version: response.version) } - writeHead(wrapOutboundOut: self.wrapOutboundOut, writeStartLine: { buffer in + writeHead(wrapOutboundOut: Self.wrapOutboundOut, writeStartLine: { buffer in buffer.write(response: response) }, context: context, headers: response.headers, promise: promise) case .body(let bodyPart): - writeChunk(wrapOutboundOut: self.wrapOutboundOut, context: context, isChunked: self.isChunked, chunk: bodyPart, promise: promise) + writeChunk(wrapOutboundOut: Self.wrapOutboundOut, context: context, isChunked: self.isChunked, chunk: bodyPart, promise: promise) case .end(let trailers): - writeTrailers(wrapOutboundOut: self.wrapOutboundOut, context: context, isChunked: self.isChunked, trailers: trailers, promise: promise) + writeTrailers(wrapOutboundOut: Self.wrapOutboundOut, context: context, isChunked: self.isChunked, trailers: trailers, promise: promise) } } } diff --git a/Sources/NIOHTTP1/HTTPHeaderValidator.swift b/Sources/NIOHTTP1/HTTPHeaderValidator.swift index 157475fff0..74bc677599 100644 --- a/Sources/NIOHTTP1/HTTPHeaderValidator.swift +++ b/Sources/NIOHTTP1/HTTPHeaderValidator.swift @@ -29,7 +29,7 @@ public final class NIOHTTPRequestHeadersValidator: ChannelOutboundHandler, Remov public init() { } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - switch self.unwrapOutboundIn(data) { + switch Self.unwrapOutboundIn(data) { case .head(let head): guard head.headers.areValidToSend else { promise?.fail(HTTPParserError.invalidHeaderToken) @@ -67,7 +67,7 @@ public final class NIOHTTPResponseHeadersValidator: ChannelOutboundHandler, Remo public init() { } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - switch self.unwrapOutboundIn(data) { + switch Self.unwrapOutboundIn(data) { case .head(let head): guard head.headers.areValidToSend else { promise?.fail(HTTPParserError.invalidHeaderToken) diff --git a/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift b/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift index 1e68af848b..110a34e7d9 100644 --- a/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift +++ b/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift @@ -301,7 +301,7 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha self.checkAssertion(self.lifecycleState != .quiescingLastRequestEndReceived && self.lifecycleState != .quiescingCompleted, "deliverOneMessage called in lifecycle illegal state \(self.lifecycleState)") - let msg = self.unwrapInboundIn(data) + let msg = Self.unwrapInboundIn(data) debugOnly { switch msg { @@ -403,7 +403,7 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha self.checkAssertion(self.state != .requestEndPending, "Received second response while waiting for first one to complete") debugOnly { - let res = self.unwrapOutboundIn(data) + let res = Self.unwrapOutboundIn(data) switch res { case .head(let head) where head.isInformational: self.checkAssertion(self.nextExpectedOutboundMessage == .head) @@ -420,12 +420,12 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha var startReadingAgain = false - switch self.unwrapOutboundIn(data) { + switch Self.unwrapOutboundIn(data) { case .head(var head) where self.lifecycleState != .acceptingEvents: if head.isKeepAlive { head.headers.replaceOrAdd(name: "connection", value: "close") } - context.write(self.wrapOutboundOut(.head(head)), promise: promise) + context.write(Self.wrapOutboundOut(.head(head)), promise: promise) case .end: startReadingAgain = true @@ -643,7 +643,7 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha let maybeFirstHead = self.eventBuffer.firstIndex(where: { element in switch element { case .channelRead(let read): - switch self.unwrapInboundIn(read) { + switch Self.unwrapInboundIn(read) { case .head: return true case .body, .end: diff --git a/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift b/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift index eb985eec11..e3ad137410 100644 --- a/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift +++ b/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift @@ -46,8 +46,8 @@ public final class HTTPServerProtocolErrorHandler: ChannelDuplexHandler, Removab if !self.hasUnterminatedResponse { let headers = HTTPHeaders([("Connection", "close"), ("Content-Length", "0")]) let head = HTTPResponseHead(version: .http1_1, status: .badRequest, headers: headers) - context.write(self.wrapOutboundOut(.head(head)), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(head)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } // Now pass the error on in case someone else wants to see it. @@ -55,7 +55,7 @@ public final class HTTPServerProtocolErrorHandler: ChannelDuplexHandler, Removab } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let res = self.unwrapOutboundIn(data) + let res = Self.unwrapOutboundIn(data) switch res { case .head(let head) where head.isInformational: precondition(!self.hasUnterminatedResponse) diff --git a/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift b/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift index c84b4ed508..535a008288 100644 --- a/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift +++ b/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift @@ -110,7 +110,7 @@ public final class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableCha return } - let requestPart = unwrapInboundIn(data) + let requestPart = Self.unwrapInboundIn(data) switch self.upgradeState { case .idle: @@ -289,14 +289,14 @@ public final class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableCha // We haven't seen the first request .end. That means we're not buffering anything, and we can // just deliver data. assert(self.receivedMessages.isEmpty) - context.fireChannelRead(self.wrapInboundOut(data)) + context.fireChannelRead(Self.wrapInboundOut(data)) } else { // This is trickier. We've seen the first request .end, so we now need to deliver the .head we // got passed, as well as the .end we swallowed, and any buffered parts. While we're doing this // we may be re-entrantly called, which will cause us to buffer new parts. To make that safe, we // must ensure we aren't holding the buffer mutably, so no for loop for us. - context.fireChannelRead(self.wrapInboundOut(data)) - context.fireChannelRead(self.wrapInboundOut(.end(nil))) + context.fireChannelRead(Self.wrapInboundOut(data)) + context.fireChannelRead(Self.wrapInboundOut(.end(nil))) } context.fireChannelReadComplete() diff --git a/Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift b/Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift index 14ec0cf59c..2cb96824a6 100644 --- a/Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift +++ b/Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift @@ -169,7 +169,7 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC private func addHeadersToOutboundOut(data: NIOAny) -> NIOAny { - let interceptedOutgoingRequest = self.unwrapOutboundIn(data) + let interceptedOutgoingRequest = Self.unwrapOutboundIn(data) if case .head(var requestHead) = interceptedOutgoingRequest { @@ -177,7 +177,7 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC self.addConnectionHeaders(to: &requestHead) self.addUpgradeHeaders(to: &requestHead) - return self.wrapOutboundOut(.head(requestHead)) + return Self.wrapOutboundOut(.head(requestHead)) } return data @@ -207,9 +207,9 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC self.receivedMessages.append(data) return } - - let responsePart = unwrapInboundIn(data) - + + let responsePart = Self.unwrapInboundIn(data) + switch self.upgradeState { case .awaitingConfirmationResponse: self.firstResponseHeadReceived(context: context, responsePart: responsePart) @@ -371,7 +371,7 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC } assert(self.receivedMessages.isEmpty) - context.fireChannelRead(self.wrapInboundOut(data)) + context.fireChannelRead(Self.wrapInboundOut(data)) // We've delivered the data. We can now remove ourselves, which should happen synchronously. context.pipeline.removeHandler(context: context, promise: nil) diff --git a/Sources/NIOHTTP1/NIOHTTPObjectAggregator.swift b/Sources/NIOHTTP1/NIOHTTPObjectAggregator.swift index d999296163..0e9f4895ba 100644 --- a/Sources/NIOHTTP1/NIOHTTPObjectAggregator.swift +++ b/Sources/NIOHTTP1/NIOHTTPObjectAggregator.swift @@ -199,7 +199,7 @@ public final class NIOHTTPServerRequestAggregator: ChannelInboundHandler, Remova } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let msg = self.unwrapInboundIn(data) + let msg = Self.unwrapInboundIn(data) var serverResponse: HTTPResponseHead? = nil do { @@ -225,8 +225,8 @@ public final class NIOHTTPServerRequestAggregator: ChannelInboundHandler, Remova // Generated a server response to send back if let response = serverResponse { - context.write(self.wrapOutboundOut(.head(response)), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) if response.status == .payloadTooLarge { // If indicated content length is too large self.state.handlingOversizeMessage() @@ -335,7 +335,7 @@ public final class NIOHTTPClientResponseAggregator: ChannelInboundHandler, Remov } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let msg = self.unwrapInboundIn(data) + let msg = Self.unwrapInboundIn(data) do { switch msg { diff --git a/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift index c683b61b3e..a2be0227b8 100644 --- a/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift +++ b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift @@ -139,9 +139,9 @@ public final class NIOTypedHTTPClientUpgradeHandler: Ch public func channelActive(context: ChannelHandlerContext) { switch self.stateMachine.channelActive() { case .writeUpgradeRequest: - context.write(self.wrapOutboundOut(.head(self.upgradeRequestHead)), promise: nil) - context.write(self.wrapOutboundOut(.body(.byteBuffer(.init()))), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(self.upgradeRequestHead)), promise: nil) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(.init()))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) case .none: break @@ -177,7 +177,7 @@ public final class NIOTypedHTTPClientUpgradeHandler: Ch public func channelRead(context: ChannelHandlerContext, data: NIOAny) { switch self.stateMachine.channelReadData(data) { case .unwrapData: - let responsePart = self.unwrapInboundIn(data) + let responsePart = Self.unwrapInboundIn(data) self.channelRead(context: context, responsePart: responsePart) case .fireChannelRead: diff --git a/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift b/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift index 4467aecad6..2ca3395890 100644 --- a/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift +++ b/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift @@ -141,7 +141,7 @@ public final class NIOTypedHTTPServerUpgradeHandler: Ch public func channelRead(context: ChannelHandlerContext, data: NIOAny) { switch self.stateMachine.channelReadData(data) { case .unwrapData: - let requestPart = self.unwrapInboundIn(data) + let requestPart = Self.unwrapInboundIn(data) self.channelRead(context: context, requestPart: requestPart) case .fireChannelRead: diff --git a/Sources/NIOHTTP1Client/main.swift b/Sources/NIOHTTP1Client/main.swift index f78bd51d65..03ef928066 100644 --- a/Sources/NIOHTTP1Client/main.swift +++ b/Sources/NIOHTTP1Client/main.swift @@ -42,16 +42,16 @@ private final class HTTPEchoHandler: ChannelInboundHandler { uri: "/dynamic/echo", headers: headers) - context.write(self.wrapOutboundOut(.head(requestHead)), promise: nil) + context.write(Self.wrapOutboundOut(.head(requestHead)), promise: nil) - context.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let clientResponse = self.unwrapInboundIn(data) + let clientResponse = Self.unwrapInboundIn(data) switch clientResponse { case .head(let responseHead): diff --git a/Sources/NIOHTTP1Server/main.swift b/Sources/NIOHTTP1Server/main.swift index 5b98a3e52c..75b182ae8f 100644 --- a/Sources/NIOHTTP1Server/main.swift +++ b/Sources/NIOHTTP1Server/main.swift @@ -128,8 +128,8 @@ private final class HTTPHandler: ChannelInboundHandler { self.buffer.writeString(response) var headers = HTTPHeaders() headers.add(name: "Content-Length", value: "\(response.utf8.count)") - context.write(self.wrapOutboundOut(.head(httpResponseHead(request: self.infoSavedRequestHead!, status: .ok, headers: headers))), promise: nil) - context.write(self.wrapOutboundOut(.body(.byteBuffer(self.buffer))), promise: nil) + context.write(Self.wrapOutboundOut(.head(httpResponseHead(request: self.infoSavedRequestHead!, status: .ok, headers: headers))), promise: nil) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(self.buffer))), promise: nil) self.completeResponse(context, trailers: nil, promise: nil) } } @@ -147,21 +147,21 @@ private final class HTTPHandler: ChannelInboundHandler { if balloonInMemory { self.buffer.clear() } else { - context.writeAndFlush(self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), promise: nil) } case .body(buffer: var buf): if balloonInMemory { self.buffer.writeBuffer(&buf) } else { - context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(buf))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(buf))), promise: nil) } case .end: self.state.requestComplete() if balloonInMemory { var headers = HTTPHeaders() headers.add(name: "Content-Length", value: "\(self.buffer.readableBytes)") - context.write(self.wrapOutboundOut(.head(httpResponseHead(request: self.infoSavedRequestHead!, status: .ok, headers: headers))), promise: nil) - context.write(self.wrapOutboundOut(.body(.byteBuffer(self.buffer))), promise: nil) + context.write(Self.wrapOutboundOut(.head(httpResponseHead(request: self.infoSavedRequestHead!, status: .ok, headers: headers))), promise: nil) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(self.buffer))), promise: nil) self.completeResponse(context, trailers: nil, promise: nil) } else { self.completeResponse(context, trailers: nil, promise: nil) @@ -174,7 +174,7 @@ private final class HTTPHandler: ChannelInboundHandler { case .head(let request): self.keepAlive = request.isKeepAlive self.state.requestReceived() - context.writeAndFlush(self.wrapOutboundOut(.head(httpResponseHead(request: request, status: statusCode))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: statusCode))), promise: nil) case .body(buffer: _): () case .end: @@ -182,7 +182,7 @@ private final class HTTPHandler: ChannelInboundHandler { context.eventLoop.scheduleTask(in: delay) { () -> Void in var buf = context.channel.allocator.buffer(capacity: string.utf8.count) buf.writeString(string) - context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(buf))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(buf))), promise: nil) var trailers: HTTPHeaders? = nil if let trailer = trailer { trailers = HTTPHeaders() @@ -204,13 +204,13 @@ private final class HTTPHandler: ChannelInboundHandler { self.buffer.clear() self.continuousCount += 1 self.buffer.writeString("line \(self.continuousCount)\n") - context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(self.buffer)))).map { + context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(self.buffer)))).map { context.eventLoop.scheduleTask(in: .milliseconds(400), doNext) }.whenFailure { (_: Error) in self.completeResponse(context, trailers: nil, promise: nil) } } - context.writeAndFlush(self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), promise: nil) doNext() case .end: self.state.requestComplete() @@ -229,7 +229,7 @@ private final class HTTPHandler: ChannelInboundHandler { self.buffer.clear() self.buffer.writeString(strings[self.continuousCount]) self.continuousCount += 1 - context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(self.buffer)))).whenSuccess { + context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(self.buffer)))).whenSuccess { if self.continuousCount < strings.count { context.eventLoop.scheduleTask(in: delay, doNext) } else { @@ -237,7 +237,7 @@ private final class HTTPHandler: ChannelInboundHandler { } } } - context.writeAndFlush(self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.head(httpResponseHead(request: request, status: .ok))), promise: nil) doNext() case .end: self.state.requestComplete() @@ -301,9 +301,9 @@ private final class HTTPHandler: ChannelInboundHandler { }() body.writeString("\(error)") body.writeStaticString("\r\n") - context.write(self.wrapOutboundOut(.head(response)), promise: nil) - context.write(self.wrapOutboundOut(.body(.byteBuffer(body))), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(body))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) context.channel.close(promise: nil) } @@ -320,7 +320,7 @@ private final class HTTPHandler: ChannelInboundHandler { self.state.requestReceived() guard !request.uri.containsDotDot() else { let response = httpResponseHead(request: request, status: .forbidden) - context.write(self.wrapOutboundOut(.head(response)), promise: nil) + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) self.completeResponse(context, trailers: nil, promise: nil) return } @@ -336,7 +336,7 @@ private final class HTTPHandler: ChannelInboundHandler { let response = responseHead(request: request, fileRegion: region) if region.readableBytes == 0 { responseStarted = true - context.write(self.wrapOutboundOut(.head(response)), promise: nil) + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) } return self.fileIO.readChunked(fileRegion: region, chunkSize: 32 * 1024, @@ -344,9 +344,9 @@ private final class HTTPHandler: ChannelInboundHandler { eventLoop: context.eventLoop) { buffer in if !responseStarted { responseStarted = true - context.write(self.wrapOutboundOut(.head(response)), promise: nil) + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) } - return context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(buffer)))) + return context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(buffer)))) }.flatMap { () -> EventLoopFuture in let p = context.eventLoop.makePromise(of: Void.self) self.completeResponse(context, trailers: nil, promise: p) @@ -354,12 +354,12 @@ private final class HTTPHandler: ChannelInboundHandler { }.flatMapError { error in if !responseStarted { let response = httpResponseHead(request: request, status: .ok) - context.write(self.wrapOutboundOut(.head(response)), promise: nil) + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) var buffer = context.channel.allocator.buffer(capacity: 100) buffer.writeString("fail: \(error)") - context.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) self.state.responseComplete() - return context.writeAndFlush(self.wrapOutboundOut(.end(nil))) + return context.writeAndFlush(Self.wrapOutboundOut(.end(nil))) } else { return context.close() } @@ -368,8 +368,8 @@ private final class HTTPHandler: ChannelInboundHandler { } case .sendfile: let response = responseHead(request: request, fileRegion: region) - context.write(self.wrapOutboundOut(.head(response)), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.body(.fileRegion(region)))).flatMap { + context.write(Self.wrapOutboundOut(.head(response)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.body(.fileRegion(region)))).flatMap { let p = context.eventLoop.makePromise(of: Void.self) self.completeResponse(context, trailers: nil, promise: p) return p.futureResult @@ -396,11 +396,11 @@ private final class HTTPHandler: ChannelInboundHandler { } self.handler = nil - context.writeAndFlush(self.wrapOutboundOut(.end(trailers)), promise: promise) + context.writeAndFlush(Self.wrapOutboundOut(.end(trailers)), promise: promise) } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let reqPart = self.unwrapInboundIn(data) + let reqPart = Self.unwrapInboundIn(data) if let handler = self.handler { handler(context, reqPart) return @@ -430,13 +430,13 @@ private final class HTTPHandler: ChannelInboundHandler { self.buffer.writeString(self.defaultResponse) responseHead.headers.add(name: "content-length", value: "\(self.buffer!.readableBytes)") let response = HTTPServerResponsePart.head(responseHead) - context.write(self.wrapOutboundOut(response), promise: nil) + context.write(Self.wrapOutboundOut(response), promise: nil) case .body: break case .end: self.state.requestComplete() let content = HTTPServerResponsePart.body(.byteBuffer(buffer!.slice())) - context.write(self.wrapOutboundOut(content), promise: nil) + context.write(Self.wrapOutboundOut(content), promise: nil) self.completeResponse(context, trailers: nil, promise: nil) } } diff --git a/Sources/NIOMulticastChat/main.swift b/Sources/NIOMulticastChat/main.swift index 72047f6dbf..60cf45486d 100644 --- a/Sources/NIOMulticastChat/main.swift +++ b/Sources/NIOMulticastChat/main.swift @@ -19,7 +19,7 @@ private final class ChatMessageDecoder: ChannelInboundHandler { public typealias InboundIn = AddressedEnvelope public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let envelope = self.unwrapInboundIn(data) + let envelope = Self.unwrapInboundIn(data) var buffer = envelope.data // To begin with, the chat messages are simply whole datagrams, no other length. @@ -38,9 +38,9 @@ private final class ChatMessageEncoder: ChannelOutboundHandler { public typealias OutboundOut = AddressedEnvelope func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let message = self.unwrapOutboundIn(data) + let message = Self.unwrapOutboundIn(data) let buffer = context.channel.allocator.buffer(string: message.data) - context.write(self.wrapOutboundOut(AddressedEnvelope(remoteAddress: message.remoteAddress, data: buffer)), promise: promise) + context.write(Self.wrapOutboundOut(AddressedEnvelope(remoteAddress: message.remoteAddress, data: buffer)), promise: promise) } } diff --git a/Sources/NIOPerformanceTester/TCPThroughputBenchmark.swift b/Sources/NIOPerformanceTester/TCPThroughputBenchmark.swift index 6886267df7..b661bcf57b 100644 --- a/Sources/NIOPerformanceTester/TCPThroughputBenchmark.swift +++ b/Sources/NIOPerformanceTester/TCPThroughputBenchmark.swift @@ -52,7 +52,7 @@ final class TCPThroughputBenchmark: Benchmark { public func send(_ message: ByteBuffer, times count: Int) { for _ in 0.. DecodingState { if let messageSize = buffer.getInteger(at: buffer.readerIndex, as: UInt16.self) { if buffer.readableBytes >= messageSize { - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: Int(messageSize))!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: Int(messageSize))!)) return .continue } } diff --git a/Sources/NIOPerformanceTester/UDPBenchmark.swift b/Sources/NIOPerformanceTester/UDPBenchmark.swift index 22b39864b6..a3840b50ad 100644 --- a/Sources/NIOPerformanceTester/UDPBenchmark.swift +++ b/Sources/NIOPerformanceTester/UDPBenchmark.swift @@ -252,7 +252,7 @@ extension UDPBenchmark { () case let .write(flush): let envolope = AddressedEnvelope(remoteAddress: self.config.remoteAddress, data: self.config.request) - context.write(self.wrapOutboundOut(envolope), promise: nil) + context.write(Self.wrapOutboundOut(envolope), promise: nil) if flush { context.flush() } diff --git a/Sources/NIOPerformanceTester/main.swift b/Sources/NIOPerformanceTester/main.swift index a25f36fd4c..e0408e7f15 100644 --- a/Sources/NIOPerformanceTester/main.swift +++ b/Sources/NIOPerformanceTester/main.swift @@ -124,14 +124,14 @@ private final class SimpleHTTPServer: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - if case .head(let req) = self.unwrapInboundIn(data) { + if case .head(let req) = Self.unwrapInboundIn(data) { switch req.uri { case "/perf-test-1": var buffer = context.channel.allocator.buffer(capacity: self.cachedBody.count) buffer.writeBytes(self.cachedBody) - context.write(self.wrapOutboundOut(.head(self.cachedHead)), promise: nil) - context.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(self.cachedHead)), promise: nil) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) return case "/perf-test-2": var req = HTTPResponseHead(version: .http1_1, status: .ok) @@ -139,8 +139,8 @@ private final class SimpleHTTPServer: ChannelInboundHandler { req.headers.add(name: "X-ResponseHeader-\(i)", value: "foo") } req.headers.add(name: "content-length", value: "0") - context.write(self.wrapOutboundOut(.head(req)), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(req)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) return default: fatalError("unknown uri \(req.uri)") @@ -197,7 +197,7 @@ final class RepeatedRequests: ChannelInboundHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let reqPart = self.unwrapInboundIn(data) + let reqPart = Self.unwrapInboundIn(data) if case .end(nil) = reqPart { if self.remainingNumberOfRequests <= 0 { context.channel.close().map { self.doneRequests }.cascade(to: self.isDonePromise) @@ -205,8 +205,8 @@ final class RepeatedRequests: ChannelInboundHandler { self.doneRequests += 1 self.remainingNumberOfRequests -= 1 - context.write(self.wrapOutboundOut(.head(head)), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.head(head)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } } } @@ -597,7 +597,7 @@ try measureAndPrint(desc: "no-net_http1_1k_reqs_1_conn") { } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - var buf = self.unwrapOutboundIn(data) + var buf = Self.unwrapOutboundIn(data) if self.expectedResponseBuffer == nil { self.expectedResponseBuffer = buf } diff --git a/Sources/NIOPosix/Bootstrap.swift b/Sources/NIOPosix/Bootstrap.swift index c7c1f18dd4..b06c8ced4d 100644 --- a/Sources/NIOPosix/Bootstrap.swift +++ b/Sources/NIOPosix/Bootstrap.swift @@ -410,7 +410,7 @@ public final class ServerBootstrap { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let accepted = self.unwrapInboundIn(data) + let accepted = Self.unwrapInboundIn(data) let ctxEventLoop = context.eventLoop let childEventLoop = accepted.eventLoop let childChannelInit = self.childChannelInit ?? { (_: Channel) in childEventLoop.makeSucceededFuture(()) } diff --git a/Sources/NIOTCPEchoClient/Client.swift b/Sources/NIOTCPEchoClient/Client.swift index 16f2d5da4e..e624a78667 100644 --- a/Sources/NIOTCPEchoClient/Client.swift +++ b/Sources/NIOTCPEchoClient/Client.swift @@ -100,7 +100,7 @@ private final class NewlineDelimiterCoder: ByteToMessageDecoder, MessageToByteEn if let firstLine = readableBytes.firstIndex(of: self.newLine).map({ readableBytes[..<$0] }) { buffer.moveReaderIndex(forwardBy: firstLine.count + 1) // Fire a read without a newline - context.fireChannelRead(self.wrapInboundOut(String(buffer: ByteBuffer(firstLine)))) + context.fireChannelRead(Self.wrapInboundOut(String(buffer: ByteBuffer(firstLine)))) return .continue } else { return .needMoreData diff --git a/Sources/NIOTCPEchoServer/Server.swift b/Sources/NIOTCPEchoServer/Server.swift index 1ccfccc33e..b2635b25d6 100644 --- a/Sources/NIOTCPEchoServer/Server.swift +++ b/Sources/NIOTCPEchoServer/Server.swift @@ -111,7 +111,7 @@ private final class NewlineDelimiterCoder: ByteToMessageDecoder, MessageToByteEn if let firstLine = readableBytes.firstIndex(of: self.newLine).map({ readableBytes[..<$0] }) { buffer.moveReaderIndex(forwardBy: firstLine.count + 1) // Fire a read without a newline - context.fireChannelRead(self.wrapInboundOut(String(buffer: ByteBuffer(firstLine)))) + context.fireChannelRead(Self.wrapInboundOut(String(buffer: ByteBuffer(firstLine)))) return .continue } else { return .needMoreData diff --git a/Sources/NIOTestUtils/NIOHTTP1TestServer.swift b/Sources/NIOTestUtils/NIOHTTP1TestServer.swift index c787c3e7d5..ec4133bb8a 100644 --- a/Sources/NIOTestUtils/NIOHTTP1TestServer.swift +++ b/Sources/NIOTestUtils/NIOHTTP1TestServer.swift @@ -66,15 +66,15 @@ private final class WebServerHandler: ChannelDuplexHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.webServer.pushChannelRead(self.unwrapInboundIn(data)) + self.webServer.pushChannelRead(Self.unwrapInboundIn(data)) } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - switch self.unwrapOutboundIn(data) { + switch Self.unwrapOutboundIn(data) { case .head(var head): head.headers.replaceOrAdd(name: "connection", value: "close") head.headers.remove(name: "keep-alive") - context.write(self.wrapOutboundOut(.head(head)), promise: promise) + context.write(Self.wrapOutboundOut(.head(head)), promise: promise) case .body: context.write(data, promise: promise) case .end: @@ -92,14 +92,14 @@ private final class AggregateBodyHandler: ChannelInboundHandler { var receivedSoFar: ByteBuffer? = nil func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head: context.fireChannelRead(data) case .body(var buffer): self.receivedSoFar.setOrWriteBuffer(&buffer) case .end: if let receivedSoFar = self.receivedSoFar { - context.fireChannelRead(self.wrapInboundOut(.body(receivedSoFar))) + context.fireChannelRead(Self.wrapInboundOut(.body(receivedSoFar))) } context.fireChannelRead(data) } diff --git a/Sources/NIOUDPEchoClient/main.swift b/Sources/NIOUDPEchoClient/main.swift index 795efb2322..d4b05f4e46 100644 --- a/Sources/NIOUDPEchoClient/main.swift +++ b/Sources/NIOUDPEchoClient/main.swift @@ -43,7 +43,7 @@ private final class EchoHandler: ChannelInboundHandler { // Forward the data. let envelope = AddressedEnvelope(remoteAddress: remoteAddress, data: buffer) - context.writeAndFlush(self.wrapOutboundOut(envelope), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(envelope), promise: nil) } catch { print("Could not resolve remote address") @@ -51,7 +51,7 @@ private final class EchoHandler: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let envelope = self.unwrapInboundIn(data) + let envelope = Self.unwrapInboundIn(data) let byteBuffer = envelope.data self.numBytes -= byteBuffer.readableBytes diff --git a/Sources/NIOWebSocket/NIOWebSocketFrameAggregator.swift b/Sources/NIOWebSocket/NIOWebSocketFrameAggregator.swift index c02093cbc4..6f2447007e 100644 --- a/Sources/NIOWebSocket/NIOWebSocketFrameAggregator.swift +++ b/Sources/NIOWebSocket/NIOWebSocketFrameAggregator.swift @@ -53,10 +53,10 @@ public final class NIOWebSocketFrameAggregator: ChannelInboundHandler { self.maxAccumulatedFrameCount = maxAccumulatedFrameCount self.maxAccumulatedFrameSize = maxAccumulatedFrameSize } - - + + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let frame = unwrapInboundIn(data) + let frame = Self.unwrapInboundIn(data) do { switch frame.opcode { case .continuation: diff --git a/Sources/NIOWebSocket/WebSocketFrameDecoder.swift b/Sources/NIOWebSocket/WebSocketFrameDecoder.swift index 2f36402189..b517186df7 100644 --- a/Sources/NIOWebSocket/WebSocketFrameDecoder.swift +++ b/Sources/NIOWebSocket/WebSocketFrameDecoder.swift @@ -258,7 +258,7 @@ public final class WebSocketFrameDecoder: ByteToMessageDecoder { while true { switch parser.parseStep(&buffer) { case .result(let frame): - context.fireChannelRead(self.wrapInboundOut(frame)) + context.fireChannelRead(Self.wrapInboundOut(frame)) return .continue case .continueParsing: try self.parser.validateState(maxFrameSize: self.maxFrameSize) diff --git a/Sources/NIOWebSocket/WebSocketFrameEncoder.swift b/Sources/NIOWebSocket/WebSocketFrameEncoder.swift index 67dd071971..3e78c86132 100644 --- a/Sources/NIOWebSocket/WebSocketFrameEncoder.swift +++ b/Sources/NIOWebSocket/WebSocketFrameEncoder.swift @@ -59,7 +59,7 @@ public final class WebSocketFrameEncoder: ChannelOutboundHandler { } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let data = self.unwrapOutboundIn(data) + let data = Self.unwrapOutboundIn(data) // First, we explode the frame structure and apply the mask. let frameHeader = FrameHeader(frame: data) @@ -73,13 +73,13 @@ public final class WebSocketFrameEncoder: ChannelOutboundHandler { if !unwrappedExtensionData.prependFrameHeaderIfPossible(frameHeader) { self.writeSeparateHeaderBuffer(frameHeader, context: context) } - context.write(self.wrapOutboundOut(unwrappedExtensionData), promise: nil) + context.write(Self.wrapOutboundOut(unwrappedExtensionData), promise: nil) } else if !applicationData.prependFrameHeaderIfPossible(frameHeader) { self.writeSeparateHeaderBuffer(frameHeader, context: context) } // Ok, now we need to write the application data buffer. - context.write(self.wrapOutboundOut(applicationData), promise: promise) + context.write(Self.wrapOutboundOut(applicationData), promise: promise) } /// Applies the websocket masking operation based on the passed byte buffers. @@ -111,7 +111,7 @@ public final class WebSocketFrameEncoder: ChannelOutboundHandler { // Ok, frame header away! Before we send it we save it back onto ourselves in case we get recursively called. self.headerBuffer = buffer - context.write(self.wrapOutboundOut(buffer), promise: nil) + context.write(Self.wrapOutboundOut(buffer), promise: nil) } } diff --git a/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift b/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift index 0ae103f0d5..a9913f7eaa 100644 --- a/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift +++ b/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift @@ -32,7 +32,7 @@ public final class WebSocketProtocolErrorHandler: ChannelInboundHandler { let frame = WebSocketFrame(fin: true, opcode: .connectionClose, data: data) - context.writeAndFlush(self.wrapOutboundOut(frame)).whenComplete { (_: Result) in + context.writeAndFlush(Self.wrapOutboundOut(frame)).whenComplete { (_: Result) in context.close(promise: nil) } } diff --git a/Sources/NIOWebSocketServer/Server.swift b/Sources/NIOWebSocketServer/Server.swift index 560fe16e39..1af63e29d5 100644 --- a/Sources/NIOWebSocketServer/Server.swift +++ b/Sources/NIOWebSocketServer/Server.swift @@ -269,14 +269,14 @@ final class HTTPByteBufferResponsePartHandler: ChannelOutboundHandler { typealias OutboundOut = HTTPServerResponsePart func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let part = self.unwrapOutboundIn(data) + let part = Self.unwrapOutboundIn(data) switch part { case .head(let head): - context.write(self.wrapOutboundOut(.head(head)), promise: promise) + context.write(Self.wrapOutboundOut(.head(head)), promise: promise) case .body(let buffer): - context.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: promise) + context.write(Self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: promise) case .end(let trailers): - context.write(self.wrapOutboundOut(.end(trailers)), promise: promise) + context.write(Self.wrapOutboundOut(.end(trailers)), promise: promise) } } } diff --git a/Tests/NIOCoreTests/SingleStepByteToMessageDecoderTest.swift b/Tests/NIOCoreTests/SingleStepByteToMessageDecoderTest.swift index 97476cda43..80dbefca0f 100644 --- a/Tests/NIOCoreTests/SingleStepByteToMessageDecoderTest.swift +++ b/Tests/NIOCoreTests/SingleStepByteToMessageDecoderTest.swift @@ -404,14 +404,14 @@ public final class NIOSingleStepByteToMessageDecoderTest: XCTestCase { self.processor = NIOSingleStepByteToMessageProcessor(OneByteStringDecoder()) } do { - try self.processor!.process(buffer: self.unwrapInboundIn(data)) { message in + try self.processor!.process(buffer: Self.unwrapInboundIn(data)) { message in self.produced += 1 // Produce an extra write the first time we are called to test reentrancy if self.produced == 1 { let buf = ByteBuffer(string: "X") XCTAssertNoThrow(try (context.channel as! EmbeddedChannel).writeInbound(buf)) } - context.fireChannelRead(self.wrapInboundOut(message)) + context.fireChannelRead(Self.wrapInboundOut(message)) } } catch { context.fireErrorCaught(error) diff --git a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift index a0cda42f73..81c0822b6a 100644 --- a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift @@ -229,13 +229,13 @@ extension ChannelInboundHandler where OutboundOut == HTTPClientRequestPart { uri: "/", headers: headers) - context.write(self.wrapOutboundOut(.head(requestHead)), promise: nil) + context.write(Self.wrapOutboundOut(.head(requestHead)), promise: nil) let emptyBuffer = context.channel.allocator.buffer(capacity: 0) let body = HTTPClientRequestPart.body(.byteBuffer(emptyBuffer)) - context.write(self.wrapOutboundOut(body), promise: nil) + context.write(Self.wrapOutboundOut(body), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } } diff --git a/Tests/NIOHTTP1Tests/HTTPDecoderLengthTest.swift b/Tests/NIOHTTP1Tests/HTTPDecoderLengthTest.swift index 1c321df694..d33e87453d 100644 --- a/Tests/NIOHTTP1Tests/HTTPDecoderLengthTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPDecoderLengthTest.swift @@ -25,7 +25,7 @@ private class MessageEndHandler: ChannelInboun var seenHead = false func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head: XCTAssertFalse(self.seenHead) self.seenHead = true @@ -84,7 +84,7 @@ class HTTPDecoderLengthTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head(let h): self.response = h case .end: diff --git a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift index 023d57a7cc..b6d726808a 100644 --- a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift @@ -139,7 +139,7 @@ class HTTPDecoderTest: XCTestCase { typealias InboundIn = HTTPServerRequestPart func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .head(let h): XCTAssertEqual("/SomeURL", h.uri) @@ -182,7 +182,7 @@ class HTTPDecoderTest: XCTestCase { typealias InboundIn = HTTPServerRequestPart func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .end: // ignore @@ -212,7 +212,7 @@ class HTTPDecoderTest: XCTestCase { var called: Bool = false func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buffer = self.unwrapInboundIn(data) + var buffer = Self.unwrapInboundIn(data) XCTAssertEqual("XXXX", buffer.readString(length: buffer.readableBytes)!) self.called = true } @@ -236,7 +236,7 @@ class HTTPDecoderTest: XCTestCase { let collector = ByteCollector() func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .end: _ = context.pipeline.removeHandler(self).flatMap { _ in @@ -271,7 +271,7 @@ class HTTPDecoderTest: XCTestCase { var called: Bool = false func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buffer = self.unwrapInboundIn(data) + var buffer = Self.unwrapInboundIn(data) XCTAssertEqual("XXXX", buffer.readString(length: buffer.readableBytes)!) self.called = true } @@ -300,7 +300,7 @@ class HTTPDecoderTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .end: _ = context.pipeline.removeHandler(self).flatMap { _ in @@ -550,7 +550,7 @@ class HTTPDecoderTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .head(let head): XCTAssertEqual(.OPTIONS, head.method) @@ -580,7 +580,7 @@ class HTTPDecoderTest: XCTestCase { typealias InboundIn = HTTPServerRequestPart func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .head(let head): XCTAssertEqual(.OPTIONS, head.method) @@ -617,7 +617,7 @@ class HTTPDecoderTest: XCTestCase { typealias InboundIn = HTTPServerRequestPart func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .head(let head): XCTAssertEqual(.OPTIONS, head.method) @@ -661,7 +661,7 @@ class HTTPDecoderTest: XCTestCase { typealias InboundIn = HTTPServerRequestPart func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let part = self.unwrapInboundIn(data) + let part = Self.unwrapInboundIn(data) switch part { case .head(let head): XCTAssertEqual(.OPTIONS, head.method) diff --git a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift index dc6b82fdfb..f3ab3977c5 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift @@ -49,7 +49,7 @@ internal class ArrayAccumulationHandler: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.receiveds.append(self.unwrapInboundIn(data)) + self.receiveds.append(Self.unwrapInboundIn(data)) } public func channelUnregistered(context: ChannelHandlerContext) { @@ -106,7 +106,7 @@ class HTTPServerClientTest : XCTestCase { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head(let req): switch req.uri { case "/helloworld": @@ -115,15 +115,15 @@ class HTTPServerClientTest : XCTestCase { head.headers.add(name: "Content-Length", value: "\(replyString.utf8.count)") head.headers.add(name: "Connection", value: "close") let r = HTTPServerResponsePart.head(head) - context.write(self.wrapOutboundOut(r), promise: nil) + context.write(Self.wrapOutboundOut(r), promise: nil) var b = context.channel.allocator.buffer(capacity: replyString.count) b.writeString(replyString) let outbound = self.outboundBody(b) - context.write(self.wrapOutboundOut(outbound.body)).whenComplete { (_: Result) in + context.write(Self.wrapOutboundOut(outbound.body)).whenComplete { (_: Result) in outbound.destructor() } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -133,7 +133,7 @@ class HTTPServerClientTest : XCTestCase { var head = HTTPResponseHead(version: req.version, status: .ok) head.headers.add(name: "Connection", value: "close") let r = HTTPServerResponsePart.head(head) - context.write(self.wrapOutboundOut(r)).whenFailure { error in + context.write(Self.wrapOutboundOut(r)).whenFailure { error in XCTFail("unexpected error \(error)") } var b = context.channel.allocator.buffer(capacity: 1024) @@ -142,13 +142,13 @@ class HTTPServerClientTest : XCTestCase { b.writeString("\(i)") let outbound = self.outboundBody(b) - context.write(self.wrapOutboundOut(outbound.body)).recover { error in + context.write(Self.wrapOutboundOut(outbound.body)).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in outbound.destructor() } } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -159,7 +159,7 @@ class HTTPServerClientTest : XCTestCase { head.headers.add(name: "Connection", value: "close") head.headers.add(name: "Transfer-Encoding", value: "chunked") let r = HTTPServerResponsePart.head(head) - context.write(self.wrapOutboundOut(r)).whenFailure { error in + context.write(Self.wrapOutboundOut(r)).whenFailure { error in XCTFail("unexpected error \(error)") } var b = context.channel.allocator.buffer(capacity: 1024) @@ -168,7 +168,7 @@ class HTTPServerClientTest : XCTestCase { b.writeString("\(i)") let outbound = self.outboundBody(b) - context.write(self.wrapOutboundOut(outbound.body)).recover { error in + context.write(Self.wrapOutboundOut(outbound.body)).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in outbound.destructor() @@ -178,7 +178,7 @@ class HTTPServerClientTest : XCTestCase { var trailers = HTTPHeaders() trailers.add(name: "X-URL-Path", value: "/trailers") trailers.add(name: "X-Should-Trail", value: "sure") - context.write(self.wrapOutboundOut(.end(trailers))).recover { error in + context.write(Self.wrapOutboundOut(.end(trailers))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -193,16 +193,16 @@ class HTTPServerClientTest : XCTestCase { head.headers.add(name: "Connection", value: "close") head.headers.add(name: "Content-Length", value: "\(HTTPServerClientTest.massiveResponseLength)") let r = HTTPServerResponsePart.head(head) - context.write(self.wrapOutboundOut(r)).whenFailure { error in + context.write(Self.wrapOutboundOut(r)).whenFailure { error in XCTFail("unexpected error \(error)") } let outbound = self.outboundBody(buf) - context.writeAndFlush(self.wrapOutboundOut(outbound.body)).recover { error in + context.writeAndFlush(Self.wrapOutboundOut(outbound.body)).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in outbound.destructor() } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -212,10 +212,10 @@ class HTTPServerClientTest : XCTestCase { var head = HTTPResponseHead(version: req.version, status: .ok) head.headers.add(name: "Connection", value: "close") head.headers.add(name: "Content-Length", value: "5000") - context.write(self.wrapOutboundOut(.head(head))).whenFailure { error in + context.write(Self.wrapOutboundOut(.head(head))).whenFailure { error in XCTFail("unexpected error \(error)") } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -224,10 +224,10 @@ class HTTPServerClientTest : XCTestCase { case "/204": var head = HTTPResponseHead(version: req.version, status: .noContent) head.headers.add(name: "Connection", value: "keep-alive") - context.write(self.wrapOutboundOut(.head(head))).whenFailure { error in + context.write(Self.wrapOutboundOut(.head(head))).whenFailure { error in XCTFail("unexpected error \(error)") } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -237,15 +237,15 @@ class HTTPServerClientTest : XCTestCase { let replyString = "Hello World!\r\n" let head = HTTPResponseHead(version: req.version, status: .ok) let r = HTTPServerResponsePart.head(head) - context.write(self.wrapOutboundOut(r), promise: nil) + context.write(Self.wrapOutboundOut(r), promise: nil) var b = context.channel.allocator.buffer(capacity: replyString.count) b.writeString(replyString) let outbound = self.outboundBody(b) - context.write(self.wrapOutboundOut(outbound.body)).whenComplete { (_: Result) in + context.write(Self.wrapOutboundOut(outbound.body)).whenComplete { (_: Result) in outbound.destructor() } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true @@ -254,17 +254,17 @@ class HTTPServerClientTest : XCTestCase { case "/zero-length-body-part": let r = HTTPServerResponsePart.head(.init(version: req.version, status: .ok)) - context.write(self.wrapOutboundOut(r)).whenFailure { error in + context.write(Self.wrapOutboundOut(r)).whenFailure { error in XCTFail("unexpected error \(error)") } - context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(ByteBuffer())))).whenFailure { error in + context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(ByteBuffer())))).whenFailure { error in XCTFail("unexpected error \(error)") } - context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(ByteBuffer(string: "Hello World"))))).whenFailure { error in + context.writeAndFlush(Self.wrapOutboundOut(.body(.byteBuffer(ByteBuffer(string: "Hello World"))))).whenFailure { error in XCTFail("unexpected error \(error)") } - context.write(self.wrapOutboundOut(.end(nil))).recover { error in + context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in self.sentEnd = true diff --git a/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift b/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift index d66f360808..1298ab2ee7 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift @@ -39,7 +39,7 @@ private final class ReadRecorder: ChannelInboundHandler { public var reads: [Event] = [] func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.reads.append(.channelRead(self.unwrapInboundIn(data))) + self.reads.append(.channelRead(Self.unwrapInboundIn(data))) context.fireChannelRead(data) } @@ -59,7 +59,7 @@ private final class WriteRecorder: ChannelOutboundHandler { public var writes: [HTTPServerResponsePart] = [] func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - self.writes.append(self.unwrapOutboundIn(data)) + self.writes.append(Self.unwrapOutboundIn(data)) context.write(data, promise: promise) } @@ -442,7 +442,7 @@ class HTTPServerPipelineHandlerTest: XCTestCase { var state: State = .req1HeadExpected func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let req = self.unwrapInboundIn(data) + let req = Self.unwrapInboundIn(data) switch req { case .head(let head): // except for "req_1", we always send the .end straight away @@ -465,9 +465,9 @@ class HTTPServerPipelineHandlerTest: XCTestCase { default: XCTFail("didn't expect \(head)") } - context.write(self.wrapOutboundOut(.head(HTTPResponseHead(version: .http1_1, status: .ok))), promise: nil) + context.write(Self.wrapOutboundOut(.head(HTTPResponseHead(version: .http1_1, status: .ok))), promise: nil) if sendEnd { - context.write(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(Self.wrapOutboundOut(.end(nil)), promise: nil) } context.flush() case .end: @@ -798,12 +798,12 @@ class HTTPServerPipelineHandlerTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head: // We dispatch this to the event loop so that it doesn't happen immediately but rather can be // run from the driving test code whenever it wants by running the EmbeddedEventLoop. context.eventLoop.execute { - context.writeAndFlush(self.wrapOutboundOut(.head(.init(version: .http1_1, + context.writeAndFlush(Self.wrapOutboundOut(.head(.init(version: .http1_1, status: .ok))), promise: nil) } @@ -815,7 +815,7 @@ class HTTPServerPipelineHandlerTest: XCTestCase { // We dispatch this to the event loop so that it doesn't happen immediately but rather can be // run from the driving test code whenever it wants by running the EmbeddedEventLoop. context.eventLoop.execute { - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } XCTAssertEqual(.reqEndExpected, self.state) self.state = .errorExpected diff --git a/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift b/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift index 81caf55dda..cd39f43450 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift @@ -109,7 +109,7 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase { private var nextExpected: NextExpectedState = .head func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let req = self.unwrapInboundIn(data) + let req = Self.unwrapInboundIn(data) switch req { case .head: XCTAssertEqual(.head, self.nextExpected) @@ -117,7 +117,7 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase { let res = HTTPServerResponsePart.head(.init(version: .http1_1, status: .ok, headers: .init([("Content-Length", "0")]))) - context.writeAndFlush(self.wrapOutboundOut(res), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(res), promise: nil) default: XCTAssertEqual(.end, self.nextExpected) self.nextExpected = .none diff --git a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift index e559d293ce..e94669b25f 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift @@ -138,7 +138,7 @@ private class SingleHTTPResponseAccumulator: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) self.receiveds.append(buffer) if let finalBytes = buffer.getBytes(at: buffer.writerIndex - 4, length: 4), finalBytes == [0x0D, 0x0A, 0x0D, 0x0A] { self.allDoneBlock(self.receiveds) @@ -411,7 +411,7 @@ private class DataRecorder: ChannelInboundHandler { private var data: [T] = [] public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let datum = self.unwrapInboundIn(data) + let datum = Self.unwrapInboundIn(data) self.data.append(datum) } @@ -1186,7 +1186,7 @@ class HTTPServerUpgradeTestCase: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buf = self.unwrapInboundIn(data) + var buf = Self.unwrapInboundIn(data) XCTAssertEqual(1, buf.readableBytes) let stringRead = buf.readString(length: buf.readableBytes) switch self.state { @@ -1860,7 +1860,7 @@ final class TypedHTTPServerUpgradeTestCase: HTTPServerUpgradeTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buf = self.unwrapInboundIn(data) + var buf = Self.unwrapInboundIn(data) XCTAssertEqual(1, buf.readableBytes) let stringRead = buf.readString(length: buf.readableBytes) switch self.state { diff --git a/Tests/NIOHTTP1Tests/HTTPTest.swift b/Tests/NIOHTTP1Tests/HTTPTest.swift index 8dfaac930c..fe08510b81 100644 --- a/Tests/NIOHTTP1Tests/HTTPTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPTest.swift @@ -28,7 +28,7 @@ private final class TestChannelInboundHandler: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - context.fireChannelRead(self.wrapInboundOut(self.body(self.unwrapInboundIn(data)))) + context.fireChannelRead(Self.wrapInboundOut(self.body(Self.unwrapInboundIn(data)))) } } diff --git a/Tests/NIOHTTP1Tests/NIOHTTPObjectAggregatorTest.swift b/Tests/NIOHTTP1Tests/NIOHTTPObjectAggregatorTest.swift index 7b221323b3..fdd532d285 100644 --- a/Tests/NIOHTTP1Tests/NIOHTTPObjectAggregatorTest.swift +++ b/Tests/NIOHTTP1Tests/NIOHTTPObjectAggregatorTest.swift @@ -44,7 +44,7 @@ private final class ReadRecorder: ChannelInboundHandler, Removable public var reads: [Event] = [] func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.reads.append(.channelRead(self.unwrapInboundIn(data))) + self.reads.append(.channelRead(Self.unwrapInboundIn(data))) context.fireChannelRead(data) } @@ -70,7 +70,7 @@ private final class WriteRecorder: ChannelOutboundHandler, RemovableChannelHandl public var writes: [HTTPServerResponsePart] = [] func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - self.writes.append(self.unwrapOutboundIn(data)) + self.writes.append(Self.unwrapOutboundIn(data)) context.write(data, promise: promise) } diff --git a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift index 91941cb8ae..c267c83704 100644 --- a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift +++ b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift @@ -23,9 +23,9 @@ private final class IPHeaderRemoverHandler: ChannelInboundHandler { typealias InboundOut = AddressedEnvelope func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var data = self.unwrapInboundIn(data) + var data = Self.unwrapInboundIn(data) assert(data.data.readIPv4Header() != nil) - context.fireChannelRead(self.wrapInboundOut(data)) + context.fireChannelRead(Self.wrapInboundOut(data)) } } @@ -51,11 +51,11 @@ private final class LineDelimiterCoder: ByteToMessageDecoder, MessageToByteEncod buffer.moveReaderIndex(forwardBy: 1) if id == inboundID { - context.fireChannelRead(self.wrapInboundOut(data)) + context.fireChannelRead(Self.wrapInboundOut(data)) } return .continue } else { - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: readable)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: readable)!)) buffer.moveReaderIndex(forwardBy: 1) return .continue } @@ -109,7 +109,7 @@ private final class TLSUserEventHandler: ChannelInboundHandler, RemovableChannel } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) let string = String(buffer: buffer) if string.hasPrefix("negotiate-alpn:") { @@ -133,12 +133,12 @@ private final class ByteBufferToStringHandler: ChannelDuplexHandler { typealias OutboundOut = ByteBuffer func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) - context.fireChannelRead(self.wrapInboundOut(String(buffer: buffer))) + let buffer = Self.unwrapInboundIn(data) + context.fireChannelRead(Self.wrapInboundOut(String(buffer: buffer))) } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let buffer = ByteBuffer(string: self.unwrapOutboundIn(data)) + let buffer = ByteBuffer(string: Self.unwrapOutboundIn(data)) context.write(.init(buffer), promise: promise) } } @@ -150,13 +150,13 @@ private final class ByteBufferToByteHandler: ChannelDuplexHandler { typealias OutboundOut = ByteBuffer func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buffer = self.unwrapInboundIn(data) + var buffer = Self.unwrapInboundIn(data) let byte = buffer.readInteger(as: UInt8.self)! - context.fireChannelRead(self.wrapInboundOut(byte)) + context.fireChannelRead(Self.wrapInboundOut(byte)) } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let buffer = ByteBuffer(integer: self.unwrapOutboundIn(data)) + let buffer = ByteBuffer(integer: Self.unwrapOutboundIn(data)) context.write(.init(buffer), promise: promise) } } @@ -174,20 +174,20 @@ private final class AddressedEnvelopingHandler: ChannelDuplexHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let envelope = self.unwrapInboundIn(data) + let envelope = Self.unwrapInboundIn(data) self.remoteAddress = envelope.remoteAddress - context.fireChannelRead(self.wrapInboundOut(envelope.data)) + context.fireChannelRead(Self.wrapInboundOut(envelope.data)) } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let buffer = self.unwrapOutboundIn(data) + let buffer = Self.unwrapOutboundIn(data) if let remoteAddress = self.remoteAddress { - context.write(self.wrapOutboundOut(AddressedEnvelope(remoteAddress: remoteAddress, data: buffer)), promise: promise) + context.write(Self.wrapOutboundOut(AddressedEnvelope(remoteAddress: remoteAddress, data: buffer)), promise: promise) return } - context.write(self.wrapOutboundOut(buffer), promise: promise) + context.write(Self.wrapOutboundOut(buffer), promise: promise) } } @@ -477,7 +477,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let channel = self.unwrapInboundIn(data) + let channel = Self.unwrapInboundIn(data) self.channels.withLockedValue { $0.append(channel) } diff --git a/Tests/NIOPosixTests/BootstrapTest.swift b/Tests/NIOPosixTests/BootstrapTest.swift index 931f244c81..0351bb73c3 100644 --- a/Tests/NIOPosixTests/BootstrapTest.swift +++ b/Tests/NIOPosixTests/BootstrapTest.swift @@ -719,7 +719,7 @@ private final class WriteStringOnChannelActive: ChannelInboundHandler { func channelActive(context: ChannelHandlerContext) { var buffer = context.channel.allocator.buffer(capacity: self.string.utf8.count) buffer.writeString(string) - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) } } diff --git a/Tests/NIOPosixTests/ChannelPipelineTest.swift b/Tests/NIOPosixTests/ChannelPipelineTest.swift index 8d17f29a9f..67ca3a8d96 100644 --- a/Tests/NIOPosixTests/ChannelPipelineTest.swift +++ b/Tests/NIOPosixTests/ChannelPipelineTest.swift @@ -32,15 +32,15 @@ private final class IndexWritingHandler: ChannelDuplexHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buf = self.unwrapInboundIn(data) + var buf = Self.unwrapInboundIn(data) buf.writeInteger(UInt8(self.index)) - context.fireChannelRead(self.wrapInboundOut(buf)) + context.fireChannelRead(Self.wrapInboundOut(buf)) } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - var buf = self.unwrapOutboundIn(data) + var buf = Self.unwrapOutboundIn(data) buf.writeInteger(UInt8(self.index)) - context.write(self.wrapOutboundOut(buf), promise: promise) + context.write(Self.wrapOutboundOut(buf), promise: promise) } } @@ -241,7 +241,7 @@ class ChannelPipelineTest: XCTestCase { public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { do { - context.write(self.wrapOutboundOut(try body(self.unwrapOutboundIn(data))), promise: promise) + context.write(Self.wrapOutboundOut(try body(Self.unwrapOutboundIn(data))), promise: promise) } catch let err { promise!.fail(err) } @@ -266,7 +266,7 @@ class ChannelPipelineTest: XCTestCase { typealias InboundOut = Int public func handlerRemoved(context: ChannelHandlerContext) { - context.fireChannelRead(self.wrapInboundOut(1)) + context.fireChannelRead(Self.wrapInboundOut(1)) } } @@ -328,8 +328,8 @@ class ChannelPipelineTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let data = self.unwrapInboundIn(data) - context.fireChannelRead(self.wrapInboundOut(data + [self.no])) + let data = Self.unwrapInboundIn(data) + context.fireChannelRead(Self.wrapInboundOut(data + [self.no])) } } @@ -345,8 +345,8 @@ class ChannelPipelineTest: XCTestCase { } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let data = self.unwrapOutboundIn(data) - context.write(self.wrapOutboundOut(data + [self.no]), promise: promise) + let data = Self.unwrapOutboundIn(data) + context.write(Self.wrapOutboundOut(data + [self.no]), promise: promise) } } @@ -357,9 +357,9 @@ class ChannelPipelineTest: XCTestCase { typealias OutboundOut = [Int] func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let data = self.unwrapInboundIn(data) - context.writeAndFlush(self.wrapOutboundOut(data.map { $0 * -1 }), promise: nil) - context.fireChannelRead(self.wrapInboundOut(data)) + let data = Self.unwrapInboundIn(data) + context.writeAndFlush(Self.wrapOutboundOut(data.map { $0 * -1 }), promise: nil) + context.fireChannelRead(Self.wrapInboundOut(data)) } } @@ -369,10 +369,10 @@ class ChannelPipelineTest: XCTestCase { typealias OutboundOut = ByteBuffer func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let data = self.unwrapOutboundIn(data) + let data = Self.unwrapOutboundIn(data) var buf = context.channel.allocator.buffer(capacity: 123) buf.writeString(String(describing: data)) - context.write(self.wrapOutboundOut(buf), promise: promise) + context.write(Self.wrapOutboundOut(buf), promise: promise) } } @@ -503,7 +503,7 @@ class ChannelPipelineTest: XCTestCase { func channelRead(context: ChannelHandlerContext, data: NIOAny) { if let dataString = data.tryAs(type: String.self) { - context.fireChannelRead(self.wrapInboundOut(dataString.count)) + context.fireChannelRead(Self.wrapInboundOut(dataString.count)) } } } @@ -514,7 +514,7 @@ class ChannelPipelineTest: XCTestCase { func channelRead(context: ChannelHandlerContext, data: NIOAny) { if var buffer = data.tryAs(type: ByteBuffer.self) { - context.fireChannelRead(self.wrapInboundOut(buffer.readString(length: buffer.readableBytes)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readString(length: buffer.readableBytes)!)) } } } @@ -944,7 +944,7 @@ class ChannelPipelineTest: XCTestCase { typealias InboundOut = () func channelInactive(context: ChannelHandlerContext) { - context.fireChannelRead(self.wrapInboundOut(())) + context.fireChannelRead(Self.wrapInboundOut(())) } } let handler = FireWhenInactiveHandler() @@ -1191,12 +1191,12 @@ class ChannelPipelineTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let step = self.unwrapInboundIn(data) + let step = Self.unwrapInboundIn(data) self.state.next() XCTAssertEqual(self.state, step) // just to communicate to the outside where we are in our state machine - context.fireChannelRead(self.wrapInboundOut(self.state)) + context.fireChannelRead(Self.wrapInboundOut(self.state)) switch step { case .triggerEventRead: @@ -1231,7 +1231,7 @@ class ChannelPipelineTest: XCTestCase { XCTAssertEqual(.handlerRemovedCalled, self.state) // just to communicate to the outside where we are in our state machine - context.fireChannelRead(self.wrapInboundOut(self.state)) + context.fireChannelRead(Self.wrapInboundOut(self.state)) // Step 4: This happens when the pipeline is being torn down, so let's now also finish the manual // removal process. diff --git a/Tests/NIOPosixTests/ChannelTests.swift b/Tests/NIOPosixTests/ChannelTests.swift index f947ad14f3..0780b637e8 100644 --- a/Tests/NIOPosixTests/ChannelTests.swift +++ b/Tests/NIOPosixTests/ChannelTests.swift @@ -1638,7 +1638,7 @@ public final class ChannelTests: XCTestCase { if !self.expectingData { XCTFail("Received data before we expected it.") } else { - let data = self.unwrapInboundIn(data) + let data = Self.unwrapInboundIn(data) XCTAssertEqual(data.getString(at: data.readerIndex, length: data.readableBytes), "test") } } @@ -1691,10 +1691,10 @@ public final class ChannelTests: XCTestCase { public 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))") + XCTFail("Should not be called before seeing the EOF as autoRead is false and we did not call read(), but received \(Self.unwrapInboundIn(data))") } self.numberOfChannelReads += 1 - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) XCTAssertLessThanOrEqual(buffer.readableBytes, 8) XCTAssertEqual(1, self.numberOfChannelReads) context.close(mode: .all, promise: nil) @@ -2141,7 +2141,7 @@ public final class ChannelTests: XCTestCase { func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTAssertEqual(.active, self.state) self.state = .read - var buffer = self.unwrapInboundIn(data) + var buffer = Self.unwrapInboundIn(data) XCTAssertEqual(1, buffer.readableBytes) XCTAssertEqual([0xff], buffer.readBytes(length: 1)!) } @@ -2503,14 +2503,14 @@ public final class ChannelTests: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) XCTFail("unexpected read: \(String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))") } func channelActive(context: ChannelHandlerContext) { var buffer = context.channel.allocator.buffer(capacity: 1) buffer.writeStaticString("X") - context.channel.writeAndFlush(self.wrapOutboundOut(buffer)).map { context.channel }.cascade(to: self.channelAvailablePromise) + context.channel.writeAndFlush(Self.wrapOutboundOut(buffer)).map { context.channel }.cascade(to: self.channelAvailablePromise) } } @@ -2581,7 +2581,7 @@ public final class ChannelTests: XCTestCase { } workaroundSR487() - return context.writeAndFlush(self.wrapOutboundOut(buffer)) + return context.writeAndFlush(Self.wrapOutboundOut(buffer)) }.map { XCTFail("this should have failed") }.whenFailure { error in @@ -2594,7 +2594,7 @@ public final class ChannelTests: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) XCTAssertEqual("X", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self)) context.close(promise: nil) } @@ -2996,7 +2996,7 @@ final class ReentrantWritabilityChangingHandler: ChannelInboundHandler { // emitted. The flush for that write should result in the writability flipping back // again. let b1 = context.channel.allocator.buffer(repeating: 0, count: 50) - context.write(self.wrapOutboundOut(b1)).whenSuccess { _ in + context.write(Self.wrapOutboundOut(b1)).whenSuccess { _ in // We should still be writable. XCTAssertTrue(context.channel.isWritable) XCTAssertEqual(self.isNotWritableCount, 0) @@ -3005,7 +3005,7 @@ final class ReentrantWritabilityChangingHandler: ChannelInboundHandler { // Write again. But now breach high water mark. This should cause us to become // unwritable. let b2 = context.channel.allocator.buffer(repeating: 0, count: 250) - context.write(self.wrapOutboundOut(b2), promise: nil) + context.write(Self.wrapOutboundOut(b2), promise: nil) XCTAssertFalse(context.channel.isWritable) XCTAssertEqual(self.isNotWritableCount, 1) XCTAssertEqual(self.isWritableCount, 0) @@ -3015,7 +3015,7 @@ final class ReentrantWritabilityChangingHandler: ChannelInboundHandler { } // Queue another write and flush. - context.writeAndFlush(self.wrapOutboundOut(b1), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(b1), promise: nil) } func channelWritabilityChanged(context: ChannelHandlerContext) { diff --git a/Tests/NIOPosixTests/CodecTest.swift b/Tests/NIOPosixTests/CodecTest.swift index c29f8b98fa..b72b7c01b1 100644 --- a/Tests/NIOPosixTests/CodecTest.swift +++ b/Tests/NIOPosixTests/CodecTest.swift @@ -60,7 +60,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { guard buffer.readableBytes >= MemoryLayout.size else { return .needMoreData } - context.fireChannelRead(self.wrapInboundOut(buffer.readInteger()!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readInteger()!)) return .continue } @@ -93,7 +93,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { return .needMoreData } - context.fireChannelRead(self.wrapInboundOut(buffer)) + context.fireChannelRead(Self.wrapInboundOut(buffer)) return .continue } @@ -114,7 +114,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { return .needMoreData } - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 2048)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: 2048)!)) return .continue } @@ -366,13 +366,13 @@ public final class ByteToMessageDecoderTest: XCTestCase { self.hasReentranced = true reentrantWriteBuffer.clear() reentrantWriteBuffer.writeStaticString("3") - context.channel.pipeline.fireChannelRead(self.wrapInboundOut(reentrantWriteBuffer)) + context.channel.pipeline.fireChannelRead(Self.wrapInboundOut(reentrantWriteBuffer)) } - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 1)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: 1)!)) if self.numberOfDecodeCalls == 2 { reentrantWriteBuffer.clear() reentrantWriteBuffer.writeStaticString("4") - context.channel.pipeline.fireChannelRead(self.wrapInboundOut(reentrantWriteBuffer)) + context.channel.pipeline.fireChannelRead(Self.wrapInboundOut(reentrantWriteBuffer)) } return .continue } @@ -436,7 +436,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { let originalBuffer = buffer - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: buffer.readableBytes)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: buffer.readableBytes)!)) if originalBuffer.readableBytesView.last == "0".utf8.last { context.close().whenFailure { error in XCTFail("unexpected error: \(error)") @@ -581,7 +581,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { defer { self.state += 1 } - context.fireChannelRead(self.wrapInboundOut(self.state)) + context.fireChannelRead(Self.wrapInboundOut(self.state)) return .continue } else { return .needMoreData @@ -590,7 +590,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) - context.fireChannelRead(self.wrapInboundOut(buffer.readableBytes * -1)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readableBytes * -1)) return .needMoreData } } @@ -632,7 +632,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { for i in 0.. DecodingState { if let slice = buffer.readSlice(length: 16) { - context.fireChannelRead(self.wrapInboundOut(slice)) + context.fireChannelRead(Self.wrapInboundOut(slice)) context.channel.close().whenFailure { error in XCTFail("unexpected error: \(error)") } @@ -675,7 +675,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) - context.fireChannelRead(self.wrapInboundOut(buffer)) + context.fireChannelRead(Self.wrapInboundOut(buffer)) return .needMoreData } } @@ -695,7 +695,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let slice = buffer.readSlice(length: 16) { - context.fireChannelRead(self.wrapInboundOut(slice)) + context.fireChannelRead(Self.wrapInboundOut(slice)) context.pipeline.removeHandler(context: context).whenFailure { error in XCTFail("unexpected error: \(error)") } @@ -707,7 +707,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertFalse(seenEOF) - context.fireChannelRead(self.wrapInboundOut(buffer)) + context.fireChannelRead(Self.wrapInboundOut(buffer)) return .needMoreData } } @@ -732,7 +732,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let slice = buffer.readSlice(length: 16) { - context.fireChannelRead(self.wrapInboundOut(slice)) + context.fireChannelRead(Self.wrapInboundOut(slice)) context.close().whenFailure { error in XCTFail("unexpected error: \(error)") } @@ -778,7 +778,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { XCTAssertEqual(9, buffer.readableBytes) self.callsToDecode += 1 XCTAssertEqual(1, self.callsToDecode) - context.fireChannelRead(self.wrapInboundOut(String(decoding: buffer.readBytes(length: 1)!, + context.fireChannelRead(Self.wrapInboundOut(String(decoding: buffer.readBytes(length: 1)!, as: Unicode.UTF8.self))) context.pipeline.removeHandler(context: context).whenFailure { error in XCTFail("unexpected error: \(error)") @@ -790,7 +790,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { XCTAssertFalse(seenEOF) self.callsToDecodeLast += 1 XCTAssertLessThanOrEqual(self.callsToDecodeLast, 2) - context.fireChannelRead(self.wrapInboundOut(String(decoding: buffer.readBytes(length: 4) ?? + context.fireChannelRead(Self.wrapInboundOut(String(decoding: buffer.readBytes(length: 4) ?? [ /* "no bytes" */ 0x6e, 0x6f, 0x20, 0x62, 0x79, 0x74, 0x65, 0x73], @@ -834,7 +834,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { self.decodeLastCalls += 1 XCTAssertEqual(1, self.decodeLastCalls) XCTAssertEqual(0, buffer.readableBytes) - context.fireChannelRead(self.wrapInboundOut(())) + context.fireChannelRead(Self.wrapInboundOut(())) return .needMoreData } } @@ -867,7 +867,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { self.decodeLastCalls += 1 XCTAssertEqual(1, self.decodeLastCalls) XCTAssertEqual(0, buffer.readableBytes) - context.fireChannelRead(self.wrapInboundOut(())) + context.fireChannelRead(Self.wrapInboundOut(())) return .needMoreData } } @@ -995,7 +995,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let string = buffer.readString(length: 1) { - context.fireChannelRead(self.wrapInboundOut(string)) + context.fireChannelRead(Self.wrapInboundOut(string)) return .continue } else { return .needMoreData @@ -1042,7 +1042,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { self.decodeRun += 1 if let string = buffer.readString(length: 1) { - context.fireChannelRead(self.wrapInboundOut("I: \(self.decodeRun): \(string)")) + context.fireChannelRead(Self.wrapInboundOut("I: \(self.decodeRun): \(string)")) XCTAssertNoThrow(try (context.channel as! EmbeddedChannel).writeOutbound("O: \(self.decodeRun): \(string)")) if self.decodeRun == 1 { var buffer = context.channel.allocator.buffer(capacity: 1) @@ -1072,8 +1072,8 @@ public final class ByteToMessageDecoderTest: XCTestCase { } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let string = self.unwrapOutboundIn(data) - context.write(self.wrapOutboundOut("\(string) @ \(decoder.decodeRun)"), promise: promise) + let string = Self.unwrapOutboundIn(data) + context.write(Self.wrapOutboundOut("\(string) @ \(decoder.decodeRun)"), promise: promise) } } @@ -1253,7 +1253,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { self.decodeCalls += 1 XCTAssert(buffer.readableBytes > 0) - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 1)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: 1)!)) if self.decodeCalls == 3 { context.close(promise: nil) } @@ -1304,7 +1304,7 @@ public final class ByteToMessageDecoderTest: XCTestCase { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { self.decodeCalls += 1 XCTAssert(buffer.readableBytes > 0) - context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 1)!)) + context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: 1)!)) if self.decodeCalls == 3 { context.channel.pipeline.fireUserInboundEventTriggered(ChannelEvent.inputClosed) } @@ -1703,7 +1703,7 @@ private class PairOfBytesDecoder: ByteToMessageDecoder { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let slice = buffer.readSlice(length: 2) { - context.fireChannelRead(self.wrapInboundOut(slice)) + context.fireChannelRead(Self.wrapInboundOut(slice)) return .continue } else { return .needMoreData diff --git a/Tests/NIOPosixTests/DatagramChannelTests.swift b/Tests/NIOPosixTests/DatagramChannelTests.swift index b8694e786b..50ac967dac 100644 --- a/Tests/NIOPosixTests/DatagramChannelTests.swift +++ b/Tests/NIOPosixTests/DatagramChannelTests.swift @@ -80,14 +80,14 @@ final class DatagramReadRecorder: ChannelInboundHandler { func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTAssertEqual(.active, self.state) - let data = self.unwrapInboundIn(data) + let data = Self.unwrapInboundIn(data) reads.append(data) if let promise = readWaiters.removeValue(forKey: reads.count) { promise.succeed(reads) } - context.fireChannelRead(self.wrapInboundOut(data)) + context.fireChannelRead(Self.wrapInboundOut(data)) } func channelReadComplete(context: ChannelHandlerContext) { @@ -377,7 +377,7 @@ class DatagramChannelTests: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - XCTFail("Should not receive data but got \(self.unwrapInboundIn(data))") + XCTFail("Should not receive data but got \(Self.unwrapInboundIn(data))") } func errorCaught(context: ChannelHandlerContext, error: Error) { @@ -457,7 +457,7 @@ class DatagramChannelTests: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - XCTFail("Should not receive data but got \(self.unwrapInboundIn(data))") + XCTFail("Should not receive data but got \(Self.unwrapInboundIn(data))") } func errorCaught(context: ChannelHandlerContext, error: Error) { @@ -803,8 +803,8 @@ class DatagramChannelTests: XCTestCase { typealias OutboundOut = AddressedEnvelope func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - let buffer = self.unwrapOutboundIn(data) - context.write(self.wrapOutboundOut(AddressedEnvelope(remoteAddress: context.channel.localAddress!, data: buffer)), promise: promise) + let buffer = Self.unwrapOutboundIn(data) + context.write(Self.wrapOutboundOut(AddressedEnvelope(remoteAddress: context.channel.localAddress!, data: buffer)), promise: promise) } } @@ -996,11 +996,11 @@ class DatagramChannelTests: XCTestCase { data: buffer ) - context.writeAndFlush(self.wrapOutboundOut(envelope)).cascadeFailure(to: self.completePromise) + context.writeAndFlush(Self.wrapOutboundOut(envelope)).cascadeFailure(to: self.completePromise) } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let envelope = self.unwrapInboundIn(data) + let envelope = Self.unwrapInboundIn(data) // Complete with the payload. self.completePromise.succeed(envelope.data) diff --git a/Tests/NIOPosixTests/EventLoopTest.swift b/Tests/NIOPosixTests/EventLoopTest.swift index 575e1827ac..0791e24b63 100644 --- a/Tests/NIOPosixTests/EventLoopTest.swift +++ b/Tests/NIOPosixTests/EventLoopTest.swift @@ -1346,7 +1346,7 @@ public final class EventLoopTest : XCTestCase { self.readCalls += 1 XCTAssertEqual(1, self.readCalls) - var data = self.unwrapInboundIn(data) + var data = Self.unwrapInboundIn(data) XCTAssertEqual(1, data.readableBytes) XCTAssertNil(self.received) diff --git a/Tests/NIOPosixTests/IdleStateHandlerTest.swift b/Tests/NIOPosixTests/IdleStateHandlerTest.swift index 5995c6f514..53d8830463 100644 --- a/Tests/NIOPosixTests/IdleStateHandlerTest.swift +++ b/Tests/NIOPosixTests/IdleStateHandlerTest.swift @@ -71,7 +71,7 @@ class IdleStateHandlerTest : XCTestCase { if writeToChannel { var buffer = context.channel.allocator.buffer(capacity: 4) buffer.writeStaticString("test") - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) } } } diff --git a/Tests/NIOPosixTests/MulticastTest.swift b/Tests/NIOPosixTests/MulticastTest.swift index 3ef73183db..c8a6717695 100644 --- a/Tests/NIOPosixTests/MulticastTest.swift +++ b/Tests/NIOPosixTests/MulticastTest.swift @@ -27,7 +27,7 @@ final class PromiseOnReadHandler: ChannelInboundHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.promise.succeed(self.unwrapInboundIn(data)) + self.promise.succeed(Self.unwrapInboundIn(data)) _ = context.pipeline.removeHandler(context: context) } } diff --git a/Tests/NIOPosixTests/SALChannelTests.swift b/Tests/NIOPosixTests/SALChannelTests.swift index 785d7d0d28..66addc970d 100644 --- a/Tests/NIOPosixTests/SALChannelTests.swift +++ b/Tests/NIOPosixTests/SALChannelTests.swift @@ -101,7 +101,7 @@ final class SALChannelTest: XCTestCase, SALTest { // We expect another channelWritabilityChanged notification XCTAssertTrue(self.writableNotificationStepExpectation.compareExchange(expected: 2, desired: 3, ordering: .relaxed).exchanged) - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) case 3: // Next, we should go to false because we never send all the bytes. XCTAssertFalse(context.channel.isWritable) @@ -208,7 +208,7 @@ final class SALChannelTest: XCTestCase, SALTest { func channelRead(context: ChannelHandlerContext, data: NIOAny) { self.numberOfCalls += 1 XCTAssertEqual("hello", - String(decoding: self.unwrapInboundIn(data).readableBytesView, as: Unicode.UTF8.self)) + String(decoding: Self.unwrapInboundIn(data).readableBytesView, as: Unicode.UTF8.self)) if self.numberOfCalls == 1 { self.group.leave() } diff --git a/Tests/NIOPosixTests/SelectorTest.swift b/Tests/NIOPosixTests/SelectorTest.swift index 9c2ab28d72..6de983bb6e 100644 --- a/Tests/NIOPosixTests/SelectorTest.swift +++ b/Tests/NIOPosixTests/SelectorTest.swift @@ -170,7 +170,7 @@ class SelectorTest: XCTestCase { XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value) XCTAssertFalse(self.didRead) - var buf = self.unwrapInboundIn(data) + var buf = Self.unwrapInboundIn(data) XCTAssertEqual(1, buf.readableBytes) XCTAssertEqual("H", buf.readString(length: 1)!) self.didRead = true diff --git a/Tests/NIOPosixTests/SocketChannelTest.swift b/Tests/NIOPosixTests/SocketChannelTest.swift index c309302631..8937537ccd 100644 --- a/Tests/NIOPosixTests/SocketChannelTest.swift +++ b/Tests/NIOPosixTests/SocketChannelTest.swift @@ -135,7 +135,7 @@ public final class SocketChannelTest : XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - XCTFail("Should not accept a Channel but got \(self.unwrapInboundIn(data))") + XCTFail("Should not accept a Channel but got \(Self.unwrapInboundIn(data))") } func errorCaught(context: ChannelHandlerContext, error: Error) { @@ -562,7 +562,7 @@ public final class SocketChannelTest : XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - XCTFail("Should not accept a Channel but got \(self.unwrapInboundIn(data))") + XCTFail("Should not accept a Channel but got \(Self.unwrapInboundIn(data))") self.promise.fail(ChannelError.inappropriateOperationForState) // any old error will do } @@ -687,7 +687,7 @@ public final class SocketChannelTest : XCTestCase { typealias InboundIn = Channel func channelRead(context: ChannelHandlerContext, data: NIOAny) { - self.unwrapInboundIn(data).close(promise: nil) + Self.unwrapInboundIn(data).close(promise: nil) } func errorCaught(context: ChannelHandlerContext, error: Error) { @@ -872,7 +872,7 @@ public final class SocketChannelTest : XCTestCase { func channelActive(context: ChannelHandlerContext) { var buffer = context.channel.allocator.buffer(capacity: 128) buffer.writeString(String(repeating: "x", count: 517)) - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) } func channelInactive(context: ChannelHandlerContext) { @@ -995,7 +995,7 @@ class DropAllReadsOnTheFloorHandler: ChannelDuplexHandler { // the connection is fully closed but because we support half-closure, we need to write to 'learn' that the // other side has actually fully closed the socket. func writeUntilError() { - context.writeAndFlush(self.wrapOutboundOut(buffer)).map { + context.writeAndFlush(Self.wrapOutboundOut(buffer)).map { writeUntilError() }.whenFailure { (_: Error) in self.waitUntilWriteFailedPromise.succeed(()) diff --git a/Tests/NIOPosixTests/StreamChannelsTest.swift b/Tests/NIOPosixTests/StreamChannelsTest.swift index 6269027154..02f62054f6 100644 --- a/Tests/NIOPosixTests/StreamChannelsTest.swift +++ b/Tests/NIOPosixTests/StreamChannelsTest.swift @@ -150,11 +150,11 @@ class StreamChannelTest: XCTestCase { var buffer = context.channel.allocator.buffer(capacity: chunkSize) buffer.writeBytes(repeatElement(UInt8(ascii: "x"), count: chunkSize)) for _ in 0 ..< (totalAmount / chunkSize) { - context.write(self.wrapOutboundOut(buffer)).whenFailure { error in + context.write(Self.wrapOutboundOut(buffer)).whenFailure { error in XCTFail("unexpected error \(error)") } } - context.write(self.wrapOutboundOut(buffer)).map { + context.write(Self.wrapOutboundOut(buffer)).map { XCTAssertEqual(self.state, .thenTrueAgain) }.recover { error in XCTFail("unexpected error \(error)") @@ -317,7 +317,7 @@ class StreamChannelTest: XCTestCase { func channelRead(context: ChannelHandlerContext, data: NIOAny) { guard self.areReadsOkayNow.load(ordering: .relaxed) else { - XCTFail("unexpected read of \(self.unwrapInboundIn(data))") + XCTFail("unexpected read of \(Self.unwrapInboundIn(data))") return } } @@ -395,7 +395,7 @@ class StreamChannelTest: XCTestCase { func channelRead(context: ChannelHandlerContext, data: NIOAny) { // The two writes could be coalesced, so we add up the bytes and not always the number of read calls. - self.numberOfBytes += self.unwrapInboundIn(data).readableBytes + self.numberOfBytes += Self.unwrapInboundIn(data).readableBytes if self.numberOfBytes == 2 { self.allDonePromise.succeed(()) } @@ -445,7 +445,7 @@ class StreamChannelTest: XCTestCase { var buffer = context.channel.allocator.buffer(capacity: 5) buffer.writeString("hello") context.channel.setOption(ChannelOptions.writeBufferWaterMark, value: .init(low: 1024, high: 1024)).flatMap { - context.writeAndFlush(self.wrapOutboundOut(buffer)) + context.writeAndFlush(Self.wrapOutboundOut(buffer)) }.whenFailure { error in XCTFail("unexpected error: \(error)") } @@ -469,7 +469,7 @@ class StreamChannelTest: XCTestCase { func channelRead(context: ChannelHandlerContext, data: NIOAny) { // The two writes could be coalesced, so we add up the bytes and not always the number of read calls. - self.numberOfReads += self.unwrapInboundIn(data).readableBytes + self.numberOfReads += Self.unwrapInboundIn(data).readableBytes if self.numberOfReads >= self.expectedNumberOfBytes { self.allDonePromise.succeed(()) } @@ -599,7 +599,7 @@ class StreamChannelTest: XCTestCase { func writeOneMore() { self.bytesWritten += buffer.readableBytes - context.writeAndFlush(self.wrapOutboundOut(buffer)).whenFailure { error in + context.writeAndFlush(Self.wrapOutboundOut(buffer)).whenFailure { error in XCTFail("unexpected error \(error)") } context.eventLoop.scheduleTask(in: .microseconds(100)) { @@ -613,7 +613,7 @@ class StreamChannelTest: XCTestCase { buffer.writeString("1") self.state = .done self.bytesWritten += 1 - context.writeAndFlush(self.wrapOutboundOut(buffer)).whenFailure { error in + context.writeAndFlush(Self.wrapOutboundOut(buffer)).whenFailure { error in XCTFail("unexpected error \(error)") } self.wroteEnoughToBeStuckPromise.succeed(self.bytesWritten) @@ -679,7 +679,7 @@ class StreamChannelTest: XCTestCase { self.state = .done var buffer = context.channel.allocator.buffer(capacity: 10 * 1024 * 1024) buffer.writeBytes(Array(repeating: UInt8(ascii: "X"), count: buffer.capacity - 1)) - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: self.finishedBigWritePromise) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: self.finishedBigWritePromise) self.beganBigWritePromise.succeed(()) case .done: () // ignored @@ -710,7 +710,7 @@ class StreamChannelTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let buffer = self.unwrapInboundIn(data) + let buffer = Self.unwrapInboundIn(data) switch self.state { case .waitingForInitialOutsideReadCall: XCTFail("unexpected \(#function)") @@ -836,7 +836,7 @@ class StreamChannelTest: XCTestCase { // Let's send another 2 bytes, ... var buffer = context.channel.allocator.buffer(capacity: amount) buffer.writeBytes(Array(repeating: UInt8(ascii: "X"), count: amount)) - context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(buffer), promise: nil) // ... and let's close context.close(promise: nil) @@ -876,7 +876,7 @@ final class AccumulateAllReads: ChannelInboundHandler { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var buffer = self.unwrapInboundIn(data) + var buffer = Self.unwrapInboundIn(data) let closeAfter = buffer.readableBytesView.last == UInt8(ascii: "$") self.accumulator.writeBuffer(&buffer) if closeAfter { diff --git a/Tests/NIOPosixTests/TestUtils.swift b/Tests/NIOPosixTests/TestUtils.swift index 0c38f94d8f..f4e2d4cda3 100644 --- a/Tests/NIOPosixTests/TestUtils.swift +++ b/Tests/NIOPosixTests/TestUtils.swift @@ -280,7 +280,7 @@ final class ByteCountingHandler : ChannelInboundHandler, RemovableChannelHandler } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - var currentBuffer = self.unwrapInboundIn(data) + var currentBuffer = Self.unwrapInboundIn(data) buffer.writeBuffer(¤tBuffer) if buffer.readableBytes == numBytes { diff --git a/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift b/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift index 04ed2deb2f..1844ebde02 100644 --- a/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift +++ b/Tests/NIOPosixTests/UniversalBootstrapSupportTest.swift @@ -64,7 +64,7 @@ class UniversalBootstrapSupportTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let channel = self.unwrapInboundIn(data) + let channel = Self.unwrapInboundIn(data) self.acceptedChannels.append(channel) if self.acceptedChannels.count == 1 { self.firstArrived.succeed(()) diff --git a/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift index b12bef6373..b19cd64108 100644 --- a/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift +++ b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift @@ -45,7 +45,7 @@ final class DuplicatingReadHandler: ChannelInboundHandler { func channelRead(context: ChannelHandlerContext, data: NIOAny) { if !self.hasDuplicatedRead { self.hasDuplicatedRead = true - try! self.channel.writeInbound(self.unwrapInboundIn(data)) + try! self.channel.writeInbound(Self.unwrapInboundIn(data)) } context.fireChannelRead(data) } diff --git a/Tests/NIOTestUtilsTests/ByteToMessageDecoderVerifierTest.swift b/Tests/NIOTestUtilsTests/ByteToMessageDecoderVerifierTest.swift index 05df869e63..3d26956355 100644 --- a/Tests/NIOTestUtilsTests/ByteToMessageDecoderVerifierTest.swift +++ b/Tests/NIOTestUtilsTests/ByteToMessageDecoderVerifierTest.swift @@ -26,7 +26,7 @@ class ByteToMessageDecoderVerifierTest: XCTestCase { func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { buffer.moveReaderIndex(to: buffer.writerIndex) - context.fireChannelRead(self.wrapInboundOut("Y")) + context.fireChannelRead(Self.wrapInboundOut("Y")) return .needMoreData } @@ -97,7 +97,7 @@ class ByteToMessageDecoderVerifierTest: XCTestCase { typealias InboundOut = String func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { - context.fireChannelRead(self.wrapInboundOut("Y")) + context.fireChannelRead(Self.wrapInboundOut("Y")) return .needMoreData } @@ -139,7 +139,7 @@ class ByteToMessageDecoderVerifierTest: XCTestCase { seenEOF: Bool) throws -> DecodingState { while try self.decode(context: context, buffer: &buffer) == .continue {} if buffer.readableBytes > 0 { - context.fireChannelRead(self.wrapInboundOut("leftover")) + context.fireChannelRead(Self.wrapInboundOut("leftover")) } return .needMoreData } diff --git a/Tests/NIOTestUtilsTests/NIOHTTP1TestServerTest.swift b/Tests/NIOTestUtilsTests/NIOHTTP1TestServerTest.swift index 10741197b1..b567a41009 100644 --- a/Tests/NIOTestUtilsTests/NIOHTTP1TestServerTest.swift +++ b/Tests/NIOTestUtilsTests/NIOHTTP1TestServerTest.swift @@ -368,7 +368,7 @@ private final class TestHTTPHandler: ChannelInboundHandler { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head(let responseHead): guard case .ok = responseHead.status else { self.responsePromise.fail(ResponseError.badStatus) @@ -429,14 +429,14 @@ private final class AggregateBodyHandler: ChannelInboundHandler { var receivedSoFar: ByteBuffer? = nil func channelRead(context: ChannelHandlerContext, data: NIOAny) { - switch self.unwrapInboundIn(data) { + switch Self.unwrapInboundIn(data) { case .head: context.fireChannelRead(data) case .body(var buffer): self.receivedSoFar.setOrWriteBuffer(&buffer) case .end: if let receivedSoFar = self.receivedSoFar { - context.fireChannelRead(self.wrapInboundOut(.body(receivedSoFar))) + context.fireChannelRead(Self.wrapInboundOut(.body(receivedSoFar))) } context.fireChannelRead(data) } diff --git a/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift b/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift index 5ce872655b..08e1504518 100644 --- a/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift +++ b/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift @@ -116,13 +116,13 @@ extension ChannelInboundHandler where OutboundOut == HTTPClientRequestPart { uri: "/", headers: headers) - context.write(self.wrapOutboundOut(.head(requestHead)), promise: nil) + context.write(Self.wrapOutboundOut(.head(requestHead)), promise: nil) let emptyBuffer = context.channel.allocator.buffer(capacity: 0) let body = HTTPClientRequestPart.body(.byteBuffer(emptyBuffer)) - context.write(self.wrapOutboundOut(body), promise: nil) + context.write(Self.wrapOutboundOut(body), promise: nil) - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } } @@ -136,7 +136,7 @@ private class WebSocketRecorderHandler: ChannelInboundHandler, ChannelOutboundHa public var errors: [Error] = [] func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let frame = self.unwrapInboundIn(data) + let frame = Self.unwrapInboundIn(data) self.frames.append(frame) } diff --git a/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift b/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift index 5160b8938f..716291d3a0 100644 --- a/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift +++ b/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift @@ -43,7 +43,7 @@ private final class SynchronousCloser: ChannelInboundHandler { private var closeFrame: WebSocketFrame? func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let frame = self.unwrapInboundIn(data) + let frame = Self.unwrapInboundIn(data) guard case .connectionClose = frame.opcode else { context.fireChannelRead(data) return diff --git a/Tests/NIOWebSocketTests/WebSocketServerEndToEndTests.swift b/Tests/NIOWebSocketTests/WebSocketServerEndToEndTests.swift index d04e21ae85..607f387992 100644 --- a/Tests/NIOWebSocketTests/WebSocketServerEndToEndTests.swift +++ b/Tests/NIOWebSocketTests/WebSocketServerEndToEndTests.swift @@ -102,7 +102,7 @@ private class WebSocketRecorderHandler: ChannelInboundHandler { fileprivate var errors: [Error] = [] func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let frame = self.unwrapInboundIn(data) + let frame = Self.unwrapInboundIn(data) self.frames.append(frame) } From 980bd3e630765214ab0f99908bd3a396f694c974 Mon Sep 17 00:00:00 2001 From: George Barnett Date: Thu, 18 Jul 2024 13:10:50 +0100 Subject: [PATCH 3/3] Disable warnings as errors on Swift 6 and main (#2793) Motivation: The Swift 6 compiler emits a number of warnings about sendability which we haven't dealt with yet. The CI failing on warnings may mask other compilation issues or test failures. Modifications: - Disable warnings as errors on Swift 6 and main Result: Swift 6 and main CI should pass --- .github/workflows/pull_request.yml | 7 +- .../Thresholds/nightly-6.0.json | 23 +++-- .../Thresholds/nightly-main.json | 96 +++++++++---------- 3 files changed, 64 insertions(+), 62 deletions(-) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 5acac0de03..568f12a6db 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -2,8 +2,8 @@ name: Pull Request on: pull_request: - types: [opened, reopened, synchronize, ready_for_review] - + types: [opened, reopened, synchronize] + jobs: call-pull-request-soundness-workflow: name: Soundness @@ -18,6 +18,9 @@ jobs: with: name: "Unit tests" matrix_linux_command: "swift test -Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" + # Disable warnings as errors: Swift 6 emits sendability warnings that haven't been dealt with yet. + matrix_linux_nightly_main_command_override: "swift test --explicit-target-dependency-import-check error" + matrix_linux_nightly_6_0_command_override: "swift test --explicit-target-dependency-import-check error" call-pull-request-benchmark-workflow: name: Benchmarks diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json index b3d660a648..32f5d6112d 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-6.0.json @@ -1,8 +1,8 @@ { - "10000000_asyncsequenceproducer": 21, + "10000000_asyncsequenceproducer": 19, "1000000_asyncwriter": 1000050, - "1000_addHandlers": 45050, - "1000_addHandlers_sync": 38050, + "1000_addHandlers": 44050, + "1000_addHandlers_sync": 37050, "1000_addRemoveHandlers_handlercontext": 8050, "1000_addRemoveHandlers_handlername": 8050, "1000_addRemoveHandlers_handlertype": 8050, @@ -11,15 +11,15 @@ "1000_copying_bytebufferview_to_array": 1050, "1000_copying_circularbuffer_to_array": 1050, "1000_getHandlers": 8050, - "1000_getHandlers_sync": 36, + "1000_getHandlers_sync": 35, "1000_reqs_1_conn": 26400, - "1000_rst_connections": 147000, + "1000_rst_connections": 145050, "1000_tcpbootstraps": 3050, - "1000_tcpconnections": 155050, + "1000_tcpconnections": 152050, "1000_udp_reqs": 6050, "1000_udpbootstraps": 2050, - "1000_udpconnections": 76050, - "1_reqs_1000_conn": 393000, + "1000_udpconnections": 75050, + "1_reqs_1000_conn": 389050, "bytebuffer_lots_of_rw": 2050, "creating_10000_headers": 0, "decode_1000_ws_frames": 2050, @@ -42,10 +42,9 @@ "modifying_byte_buffer_view": 6050, "ping_pong_1000_reqs_1_conn": 343, "read_10000_chunks_from_file": 110200, - "schedule_10000_tasks": 50100, + "schedule_10000_tasks": 40100, "schedule_and_run_10000_tasks": 50050, "scheduling_10000_executions": 89, "udp_1000_reqs_1_conn": 6200, - "udp_1_reqs_1000_conn": 165050 - } - \ No newline at end of file + "udp_1_reqs_1000_conn": 162050 +} diff --git a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json index 5792388db3..32f5d6112d 100644 --- a/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json +++ b/IntegrationTests/tests_04_performance/Thresholds/nightly-main.json @@ -1,50 +1,50 @@ { - "10000000_asyncsequenceproducer": 21, - "1000000_asyncwriter": 1000050, - "1000_addHandlers": 45050, - "1000_addHandlers_sync": 38050, - "1000_addRemoveHandlers_handlercontext": 8050, - "1000_addRemoveHandlers_handlername": 8050, - "1000_addRemoveHandlers_handlertype": 8050, - "1000_autoReadGetAndSet": 18050, - "1000_autoReadGetAndSet_sync": 0, - "1000_copying_bytebufferview_to_array": 1050, - "1000_copying_circularbuffer_to_array": 1050, - "1000_getHandlers": 8050, - "1000_getHandlers_sync": 36, - "1000_reqs_1_conn": 26400, - "1000_rst_connections": 147000, - "1000_tcpbootstraps": 3050, - "1000_tcpconnections": 155050, - "1000_udp_reqs": 6050, - "1000_udpbootstraps": 2050, - "1000_udpconnections": 76050, - "1_reqs_1000_conn": 393000, - "bytebuffer_lots_of_rw": 2050, - "creating_10000_headers": 0, - "decode_1000_ws_frames": 2050, - "encode_1000_ws_frames_holding_buffer": 3, - "encode_1000_ws_frames_holding_buffer_with_mask": 2050, - "encode_1000_ws_frames_holding_buffer_with_space": 3, - "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050, - "encode_1000_ws_frames_new_buffer": 3050, - "encode_1000_ws_frames_new_buffer_with_mask": 5050, - "encode_1000_ws_frames_new_buffer_with_space": 3050, - "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, - "execute_hop_10000_tasks": 0, - "future_erase_result": 4050, - "future_lots_of_callbacks": 53050, - "get_100000_headers_canonical_form": 700050, - "get_100000_headers_canonical_form_trimming_whitespace": 700050, - "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, - "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, - "modifying_1000_circular_buffer_elements": 0, - "modifying_byte_buffer_view": 6050, - "ping_pong_1000_reqs_1_conn": 343, - "read_10000_chunks_from_file": 110200, - "schedule_10000_tasks": 50100, - "schedule_and_run_10000_tasks": 50050, - "scheduling_10000_executions": 89, - "udp_1000_reqs_1_conn": 6200, - "udp_1_reqs_1000_conn": 165050 + "10000000_asyncsequenceproducer": 19, + "1000000_asyncwriter": 1000050, + "1000_addHandlers": 44050, + "1000_addHandlers_sync": 37050, + "1000_addRemoveHandlers_handlercontext": 8050, + "1000_addRemoveHandlers_handlername": 8050, + "1000_addRemoveHandlers_handlertype": 8050, + "1000_autoReadGetAndSet": 18050, + "1000_autoReadGetAndSet_sync": 0, + "1000_copying_bytebufferview_to_array": 1050, + "1000_copying_circularbuffer_to_array": 1050, + "1000_getHandlers": 8050, + "1000_getHandlers_sync": 35, + "1000_reqs_1_conn": 26400, + "1000_rst_connections": 145050, + "1000_tcpbootstraps": 3050, + "1000_tcpconnections": 152050, + "1000_udp_reqs": 6050, + "1000_udpbootstraps": 2050, + "1000_udpconnections": 75050, + "1_reqs_1000_conn": 389050, + "bytebuffer_lots_of_rw": 2050, + "creating_10000_headers": 0, + "decode_1000_ws_frames": 2050, + "encode_1000_ws_frames_holding_buffer": 3, + "encode_1000_ws_frames_holding_buffer_with_mask": 2050, + "encode_1000_ws_frames_holding_buffer_with_space": 3, + "encode_1000_ws_frames_holding_buffer_with_space_with_mask": 2050, + "encode_1000_ws_frames_new_buffer": 3050, + "encode_1000_ws_frames_new_buffer_with_mask": 5050, + "encode_1000_ws_frames_new_buffer_with_space": 3050, + "encode_1000_ws_frames_new_buffer_with_space_with_mask": 5050, + "execute_hop_10000_tasks": 0, + "future_erase_result": 4050, + "future_lots_of_callbacks": 53050, + "get_100000_headers_canonical_form": 700050, + "get_100000_headers_canonical_form_trimming_whitespace": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_long_string": 700050, + "get_100000_headers_canonical_form_trimming_whitespace_from_short_string": 700050, + "modifying_1000_circular_buffer_elements": 0, + "modifying_byte_buffer_view": 6050, + "ping_pong_1000_reqs_1_conn": 343, + "read_10000_chunks_from_file": 110200, + "schedule_10000_tasks": 40100, + "schedule_and_run_10000_tasks": 50050, + "scheduling_10000_executions": 89, + "udp_1000_reqs_1_conn": 6200, + "udp_1_reqs_1000_conn": 162050 }