From 5d7a9997e67c180d1f9cf53995ac1ff9694700a0 Mon Sep 17 00:00:00 2001 From: Franz Busch Date: Mon, 24 Jun 2024 15:11:36 +0100 Subject: [PATCH] Throw an appropriate error from the writer when the channel closed (#2744) # Motivation Currently, when the channel closes and a user tries to write something the writer throws an `AlreadyFinished` error. This error can also be thrown when calling `finish` on the writer and then trying to call `write` again. This makes it hard to distinguish if the thrown error was due to the channel being closed or due to a business logic error in handling the writer. # Modification This PR finishes the writer with a `ChannelError.ioOnClosedChannel` if the writer gets finished to due a channel inactive or handler removed. # Result Users can now distinguish if they did something wrong with the writer or if the channel closed. --- .../AsyncChannelOutboundWriterHandler.swift | 4 ++-- .../AsyncChannel/AsyncChannelTests.swift | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/Sources/NIOCore/AsyncChannel/AsyncChannelOutboundWriterHandler.swift b/Sources/NIOCore/AsyncChannel/AsyncChannelOutboundWriterHandler.swift index daa35fd63..8fa211127 100644 --- a/Sources/NIOCore/AsyncChannel/AsyncChannelOutboundWriterHandler.swift +++ b/Sources/NIOCore/AsyncChannel/AsyncChannelOutboundWriterHandler.swift @@ -137,7 +137,7 @@ internal final class NIOAsyncChannelOutboundWriterHandler @inlinable func handlerRemoved(context: ChannelHandlerContext) { self.context = nil - self.sink?.finish() + self.sink?.finish(error: ChannelError.ioOnClosedChannel) self.writer = nil } @@ -150,7 +150,7 @@ internal final class NIOAsyncChannelOutboundWriterHandler @inlinable func channelInactive(context: ChannelHandlerContext) { - self.sink?.finish() + self.sink?.finish(error: ChannelError.ioOnClosedChannel) context.fireChannelInactive() } diff --git a/Tests/NIOCoreTests/AsyncChannel/AsyncChannelTests.swift b/Tests/NIOCoreTests/AsyncChannel/AsyncChannelTests.swift index cafddee30..cbaec0664 100644 --- a/Tests/NIOCoreTests/AsyncChannel/AsyncChannelTests.swift +++ b/Tests/NIOCoreTests/AsyncChannel/AsyncChannelTests.swift @@ -81,6 +81,24 @@ final class AsyncChannelTests: XCTestCase { } } + func testAsyncChannelThrowsWhenChannelClosed() async throws { + let channel = NIOAsyncTestingChannel() + let wrapped = try await channel.testingEventLoop.executeInContext { + return try NIOAsyncChannel(wrappingChannelSynchronously: channel) + } + + try await channel.close(mode: .all) + + do { + try await wrapped.executeThenClose { _, outbound in + try await outbound.write("Test") + } + XCTFail("Expected an error to be thrown") + } catch { + XCTAssertEqual(error as? ChannelError, ChannelError.ioOnClosedChannel) + } + } + func testFinishingTheWriterClosesTheWriteSideOfTheChannel() async throws { let channel = NIOAsyncTestingChannel() let closeRecorder = CloseRecorder()