From d94819283831e1237eaecb23f1678ab6ad0da4c7 Mon Sep 17 00:00:00 2001 From: Raphael Date: Wed, 11 Feb 2026 16:46:19 +0100 Subject: [PATCH] Don't send (in)active when channel closes directly (#3497) ### Motivation Issue #2773 reports a problem where channels can receive `channelInactive` before `channelActive`. This breaks expectations and should not happen. Instead of sending them in the wrong order, this PR suppresses both of them in those cases. ### Modifications * Add a test to reproduce the problematic behavior. * Update the state machine to split the active state into two. This decouples succeeding the promise from sending the signal. Transiting to closing only sends `channelInactive` when originating from the state that sent `channelActive`. ### Result Address #2773. Edit: Updated modifications to reflect latests commit. --- Sources/NIOPosix/BaseSocketChannel.swift | 95 ++++++++++++++----- .../ChannelNotificationTest.swift | 46 +++++++++ 2 files changed, 119 insertions(+), 22 deletions(-) diff --git a/Sources/NIOPosix/BaseSocketChannel.swift b/Sources/NIOPosix/BaseSocketChannel.swift index c54e03ffc..ba106cc23 100644 --- a/Sources/NIOPosix/BaseSocketChannel.swift +++ b/Sources/NIOPosix/BaseSocketChannel.swift @@ -24,12 +24,14 @@ private struct SocketChannelLifecycleManager { case fresh case preRegistered // register() has been run but the selector doesn't know about it yet case fullyRegistered // fully registered, ie. the selector knows about it - case activated + case preActivation // activated, but we have not fired channelActivated yet + case fullyActivated // fully activated, i.e., the signal has been fired case closed } private enum Event { - case activate + case beginActivation + case finishActivation case beginRegistration case finishRegistration case close @@ -52,9 +54,11 @@ private struct SocketChannelLifecycleManager { didSet { self.eventLoop.assertInEventLoop() switch (oldValue, self.currentState) { - case (_, .activated): + case (_, .preActivation): self.isActiveAtomic.store(true, ordering: .relaxed) - case (.activated, _): + case (.preActivation, .fullyActivated): + () // Stay active + case (.preActivation, _), (.fullyActivated, _): self.isActiveAtomic.store(false, ordering: .relaxed) default: () @@ -99,8 +103,13 @@ private struct SocketChannelLifecycleManager { // we need to return a closure here and to not suffer from a potential allocation for that this must be inlined @inline(__always) - internal mutating func activate() -> ((EventLoopPromise?, ChannelPipeline) -> Void) { - self.moveState(event: .activate) + internal mutating func beginActivation() -> ((EventLoopPromise?, ChannelPipeline) -> Void) { + self.moveState(event: .beginActivation) + } + + @inline(__always) + internal mutating func finishActivation() -> ((EventLoopPromise?, ChannelPipeline) -> Void) { + self.moveState(event: .finishActivation) } // MARK: private API @@ -132,11 +141,10 @@ private struct SocketChannelLifecycleManager { } // origin: .fullyRegistered - case (.fullyRegistered, .activate): - self.currentState = .activated + case (.fullyRegistered, .beginActivation): + self.currentState = .preActivation return { promise, pipeline in promise?.succeed(()) - pipeline.syncOperations.fireChannelActive() } // origin: .preRegistered || .fullyRegistered @@ -147,8 +155,29 @@ private struct SocketChannelLifecycleManager { pipeline.syncOperations.fireChannelUnregistered() } - // origin: .activated - case (.activated, .close): + // origin: .preActivation + case (.preActivation, .finishActivation): + self.currentState = .fullyActivated + return { promise, pipeline in + assert(promise == nil) + pipeline.syncOperations.fireChannelActive() + } + + case (.preActivation, .close): + self.currentState = .closed + return { promise, pipeline in + promise?.succeed(()) + // Don't fire channelInactive here. + pipeline.syncOperations.fireChannelUnregistered() + } + + case (.preActivation, .beginActivation) where self.supportsReconnect: + return { promise, pipeline in + promise?.succeed(()) + } + + // origin: .fullyActivated + case (.fullyActivated, .close): self.currentState = .closed return { promise, pipeline in promise?.succeed(()) @@ -156,20 +185,31 @@ private struct SocketChannelLifecycleManager { pipeline.syncOperations.fireChannelUnregistered() } - // origin: .activated - case (.activated, .activate) where self.supportsReconnect: + case (.fullyActivated, .beginActivation) where self.supportsReconnect: return { promise, pipeline in promise?.succeed(()) } + case (.fullyActivated, .finishActivation) where self.supportsReconnect: + return { promise, pipeline in + assert(promise == nil) + } + // bad transitions - case (.fresh, .activate), // should go through .registered first - (.preRegistered, .activate), // need to first be fully registered + case (.fresh, .beginActivation), // should go through .registered first + (.fresh, .finishActivation), // should go through .registerd first + (.preRegistered, .beginActivation), // need to first be fully registered + (.preRegistered, .finishActivation), // need to first be fully registered (.preRegistered, .beginRegistration), // already registered (.fullyRegistered, .beginRegistration), // already registered - (.activated, .activate), // already activated - (.activated, .beginRegistration), // already fully registered (and activated) - (.activated, .finishRegistration), // already fully registered (and activated) + (.fullyRegistered, .finishActivation), // need to activate first + (.preActivation, .beginActivation), // already activated + (.preActivation, .beginRegistration), // already fully registered (and activated) + (.preActivation, .finishRegistration), // already fully registered (and activated) + (.fullyActivated, .beginActivation), // need to activate first + (.fullyActivated, .beginRegistration), // already fully registered + (.fullyActivated, .finishRegistration), // already fully registered + (.fullyActivated, .finishActivation), // already signaled (.fullyRegistered, .finishRegistration), // already fully registered (.fresh, .finishRegistration), // need to register lazily first (.closed, _): // already closed @@ -184,7 +224,12 @@ private struct SocketChannelLifecycleManager { // MARK: convenience properties internal var isActive: Bool { self.eventLoop.assertInEventLoop() - return self.currentState == .activated + switch self.currentState { + case .preActivation, .fullyActivated: + return true + case .fresh, .preRegistered, .fullyRegistered, .closed: + return false + } } internal var isPreRegistered: Bool { @@ -192,7 +237,7 @@ private struct SocketChannelLifecycleManager { switch self.currentState { case .fresh, .closed: return false - case .preRegistered, .fullyRegistered, .activated: + case .preRegistered, .fullyRegistered, .preActivation, .fullyActivated: return true } } @@ -202,7 +247,7 @@ private struct SocketChannelLifecycleManager { switch self.currentState { case .fresh, .closed, .preRegistered: return false - case .fullyRegistered, .activated: + case .fullyRegistered, .preActivation, .fullyActivated: return true } } @@ -1366,7 +1411,13 @@ class BaseSocketChannel: SelectableChannel, Chan return } } - self.lifecycleManager.activate()(promise, self.pipeline) + self.lifecycleManager.beginActivation()(promise, self.pipeline) + guard self.lifecycleManager.isActive else { + // the channel got closed in the promise succeed closure + return + } + // if the channel wasn't closed, continue to fully activate + self.lifecycleManager.finishActivation()(nil, self.pipeline) guard self.lifecycleManager.isOpen else { // in the user callout for `channelActive` the channel got closed. return diff --git a/Tests/NIOPosixTests/ChannelNotificationTest.swift b/Tests/NIOPosixTests/ChannelNotificationTest.swift index ad7f1eaf6..fd57811ce 100644 --- a/Tests/NIOPosixTests/ChannelNotificationTest.swift +++ b/Tests/NIOPosixTests/ChannelNotificationTest.swift @@ -534,4 +534,50 @@ class ChannelNotificationTest: XCTestCase { XCTAssertNoThrow(try serverChannel.close().wait()) XCTAssertNoThrow(try serverChannel.closeFuture.wait()) } + + func testNoActiveInactiveNotificationsWhenDirectlyClosed() throws { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + defer { + XCTAssertNoThrow(try group.syncShutdownGracefully()) + } + + class OrderVerificationHandler: ChannelInboundHandler { + typealias InboundIn = ByteBuffer + + init() { + // nop + } + + public func channelActive(context: ChannelHandlerContext) { + XCTFail("There should be no events when the channel is closed directly.") + } + + public func channelInactive(context: ChannelHandlerContext) { + XCTFail("There should be no events when the channel is closed directly.") + } + } + + let serverChannel = try assertNoThrowWithValue( + ServerBootstrap(group: group) + .serverChannelOption(.socketOption(.so_reuseaddr), value: 1) + .bind(host: "127.0.0.1", port: 0).wait() + ) + + let connectFuture = ClientBootstrap(group: group) + .channelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(OrderVerificationHandler()) + } + } + .connect(to: serverChannel.localAddress!) + + // Close immediately in the promise callback. The channel must still become active before it becomes inactive! + let closeFuture = connectFuture.flatMap { channel in + channel.close() + } + + XCTAssertNoThrow(try closeFuture.wait()) + + XCTAssertNoThrow(try serverChannel.close().wait()) + } }