From eab7d314f304224706b78c4abae57a3faab0b4da Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Tue, 30 Jan 2018 12:03:51 +0000 Subject: [PATCH] make Channel non optional in ChannelHandlerContext --- Sources/NIO/ChannelHandlers.swift | 6 +- Sources/NIO/ChannelPipeline.swift | 62 ++++------------ Sources/NIO/Codec.swift | 4 +- Sources/NIO/Embedded.swift | 4 ++ Sources/NIO/SocketChannel.swift | 25 +++++++ Sources/NIOHTTP1/HTTPEncoder.swift | 10 +-- Sources/NIOHTTP1/HTTPResponseCompressor.swift | 4 +- Sources/NIOHTTP1/HTTPUpgradeHandler.swift | 4 +- Sources/NIOHTTP1Server/main.swift | 8 +-- ...pplicationProtocolNegotiationHandler.swift | 2 +- Sources/NIOTLS/SNIHandler.swift | 2 +- Tests/NIOHTTP1Tests/HTTPHeadersTest.swift | 2 + .../HTTPResponseCompressorTest.swift | 32 ++++----- .../NIOHTTP1Tests/HTTPServerClientTest.swift | 8 +-- Tests/NIOHTTP1Tests/HTTPTest.swift | 15 ++-- ...ationProtocolNegotiationHandlerTests.swift | 12 ++++ Tests/NIOTLSTests/SNIHandlerTests.swift | 4 ++ .../NIOTests/ChannelPipelineTest+XCTest.swift | 1 + Tests/NIOTests/ChannelPipelineTest.swift | 72 +++++++++++++++++-- Tests/NIOTests/ChannelTests.swift | 10 +-- Tests/NIOTests/CodecTest.swift | 10 ++- Tests/NIOTests/EchoServerClientTest.swift | 12 ++-- Tests/NIOTests/EmbeddedChannelTest.swift | 9 ++- Tests/NIOTests/IdleStateHandlerTest.swift | 2 +- Tests/NIOTests/TestUtils.swift | 2 +- 25 files changed, 205 insertions(+), 117 deletions(-) diff --git a/Sources/NIO/ChannelHandlers.swift b/Sources/NIO/ChannelHandlers.swift index 778fd1446..217202f69 100644 --- a/Sources/NIO/ChannelHandlers.swift +++ b/Sources/NIO/ChannelHandlers.swift @@ -56,7 +56,7 @@ public class BackPressureHandler: ChannelInboundHandler, _ChannelOutboundHandler } public func channelWritabilityChanged(ctx: ChannelHandlerContext) { - self.writable = ctx.channel!.isWritable + self.writable = ctx.channel.isWritable if writable { mayRead(ctx: ctx) } else { @@ -113,7 +113,7 @@ public class IdleStateHandler : ChannelInboundHandler, ChannelOutboundHandler { } public func handlerAdded(ctx: ChannelHandlerContext) { - if let channel = ctx.channel, channel.isActive { + if ctx.channel.isActive { initIdleTasks(ctx) } } @@ -155,7 +155,7 @@ public class IdleStateHandler : ChannelInboundHandler, ChannelOutboundHandler { } private func shouldReschedule(_ ctx: ChannelHandlerContext) -> Bool { - if let channel = ctx.channel, channel.isActive { + if ctx.channel.isActive { return true } return false diff --git a/Sources/NIO/ChannelPipeline.swift b/Sources/NIO/ChannelPipeline.swift index 4a527ddbe..beb9ec298 100644 --- a/Sources/NIO/ChannelPipeline.swift +++ b/Sources/NIO/ChannelPipeline.swift @@ -138,7 +138,7 @@ public final class ChannelPipeline : ChannelInvoker { private var tail: ChannelHandlerContext? private var idx: Int = 0 - private var destroyed: Bool = false + internal private(set) var destroyed: Bool = false /// The `EventLoop` that is used by the underlying `Channel`. public var eventLoop: EventLoop { @@ -293,8 +293,6 @@ public final class ChannelPipeline : ChannelInvoker { private func remove0(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { assert(self.eventLoop.inEventLoop) - ctx.pipeline = nil - let nextCtx = ctx.next let prevCtx = ctx.prev if let prevCtx = prevCtx { @@ -683,67 +681,35 @@ private final class HeadChannelHandler : _ChannelOutboundHandler { private init() { } func register(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { - if let channel = ctx.channel { - channel._unsafe.register0(promise: promise) - } else { - promise?.fail(error: ChannelError.ioOnClosedChannel) - } + ctx.channel._unsafe.register0(promise: promise) } func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { - if let channel = ctx.channel { - channel._unsafe.bind0(to: address, promise: promise) - } else { - promise?.fail(error: ChannelError.ioOnClosedChannel) - } + ctx.channel._unsafe.bind0(to: address, promise: promise) } func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { - if let channel = ctx.channel { - channel._unsafe.connect0(to: address, promise: promise) - } else { - promise?.fail(error: ChannelError.ioOnClosedChannel) - } + ctx.channel._unsafe.connect0(to: address, promise: promise) } func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - if let channel = ctx.channel { - channel._unsafe.write0(data: data, promise: promise) - } else { - promise?.fail(error: ChannelError.ioOnClosedChannel) - } + ctx.channel._unsafe.write0(data: data, promise: promise) } func flush(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { - if let channel = ctx.channel { - channel._unsafe.flush0(promise: promise) - } else { - promise?.fail(error: ChannelError.ioOnClosedChannel) - } + ctx.channel._unsafe.flush0(promise: promise) } func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { - if let channel = ctx.channel { - channel._unsafe.close0(error: mode.error, mode: mode, promise: promise) - } else { - promise?.fail(error: ChannelError.alreadyClosed) - } + ctx.channel._unsafe.close0(error: mode.error, mode: mode, promise: promise) } func read(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { - if let channel = ctx.channel { - channel._unsafe.read0(promise: promise) - } else { - promise?.fail(error: ChannelError.ioOnClosedChannel) - } + ctx.channel._unsafe.read0(promise: promise) } func triggerUserOutboundEvent(ctx: ChannelHandlerContext, event: Any, promise: EventLoopPromise?) { - if let channel = ctx.channel { - channel._unsafe.triggerUserOutboundEvent0(event: event, promise: promise) - } else { - promise?.fail(error: ChannelError.ioOnClosedChannel) - } + ctx.channel._unsafe.triggerUserOutboundEvent0(event: event, promise: promise) } } @@ -797,11 +763,11 @@ private final class TailChannelHandler : _ChannelInboundHandler, _ChannelOutboun } func errorCaught(ctx: ChannelHandlerContext, error: Error) { - ctx.channel!._unsafe.errorCaught0(error: error) + ctx.channel._unsafe.errorCaught0(error: error) } func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { - ctx.channel!._unsafe.channelRead0(data: data) + ctx.channel._unsafe.channelRead0(data: data) } } @@ -828,10 +794,10 @@ public final class ChannelHandlerContext : ChannelInvoker { fileprivate var next: ChannelHandlerContext? fileprivate var prev: ChannelHandlerContext? - public fileprivate(set) var pipeline: ChannelPipeline? + public let pipeline: ChannelPipeline - public var channel: Channel? { - return pipeline?.channel + public var channel: Channel { + return pipeline.channel } public var handler: ChannelHandler { diff --git a/Sources/NIO/Codec.swift b/Sources/NIO/Codec.swift index 49a422f60..b0a7b1da0 100644 --- a/Sources/NIO/Codec.swift +++ b/Sources/NIO/Codec.swift @@ -28,7 +28,7 @@ extension ByteToMessageDecoder { var buffer = self.unwrapInboundIn(data) if var cum = cumulationBuffer { - var buf = ctx.channel!.allocator.buffer(capacity: cum.readableBytes + buffer.readableBytes) + var buf = ctx.channel.allocator.buffer(capacity: cum.readableBytes + buffer.readableBytes) buf.write(buffer: &cum) buf.write(buffer: &buffer) cumulationBuffer = buf @@ -106,6 +106,6 @@ extension MessageToByteEncoder { } public func allocateOutBuffer(ctx: ChannelHandlerContext, data: OutboundIn) throws -> ByteBuffer { - return ctx.channel!.allocator.buffer(capacity: 256) + return ctx.channel.allocator.buffer(capacity: 256) } } diff --git a/Sources/NIO/Embedded.swift b/Sources/NIO/Embedded.swift index cf5e44112..45a12e6aa 100644 --- a/Sources/NIO/Embedded.swift +++ b/Sources/NIO/Embedded.swift @@ -241,6 +241,9 @@ class EmbeddedChannelCore : ChannelCore { } public class EmbeddedChannel : Channel { + deinit { + assert(self.pipeline.destroyed, "leaked an open EmbeddedChannel, maybe forgot to call channel.finish()?") + } public var isActive: Bool { return channelcore.isActive } public var closeFuture: EventLoopFuture { return channelcore.closePromise.futureResult } @@ -260,6 +263,7 @@ public class EmbeddedChannel : Channel { public func finish() throws -> Bool { try close().wait() + (self.eventLoop as! EmbeddedEventLoop).run() try throwIfErrorCaught() return !channelcore.outboundBuffer.isEmpty || !channelcore.inboundBuffer.isEmpty } diff --git a/Sources/NIO/SocketChannel.swift b/Sources/NIO/SocketChannel.swift index 87e62000f..e63ccf737 100644 --- a/Sources/NIO/SocketChannel.swift +++ b/Sources/NIO/SocketChannel.swift @@ -257,6 +257,11 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { public func bind0(to address: SocketAddress, promise: EventLoopPromise?) { assert(eventLoop.inEventLoop) + guard !self.closed else { + promise?.fail(error: ChannelError.ioOnClosedChannel) + return + } + executeAndComplete(promise) { try socket.bind(to: address) } @@ -419,6 +424,11 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { public final func register0(promise: EventLoopPromise?) { assert(eventLoop.inEventLoop) + guard !self.closed else { + promise?.fail(error: ChannelError.ioOnClosedChannel) + return + } + // Was not registered yet so do it now. if safeRegister(interested: .read) { neverRegistered = false @@ -504,6 +514,11 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { public final func connect0(to address: SocketAddress, promise: EventLoopPromise?) { assert(eventLoop.inEventLoop) + guard !self.closed else { + promise?.fail(error: ChannelError.ioOnClosedChannel) + return + } + guard pendingConnect == nil else { promise?.fail(error: ChannelError.connectPending) return @@ -592,6 +607,10 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { active.store(false) self._pipeline = ChannelPipeline(channel: self) } + + deinit { + assert(self._closed, "leak of open Channel") + } } /// A `Channel` for a client socket. @@ -971,6 +990,12 @@ final class ServerSocketChannel : BaseSocketChannel { override public func bind0(to address: SocketAddress, promise: EventLoopPromise?) { assert(eventLoop.inEventLoop) + + guard !self.closed else { + promise?.fail(error: ChannelError.ioOnClosedChannel) + return + } + let p: EventLoopPromise = eventLoop.newPromise() p.futureResult.whenComplete { v in switch v { diff --git a/Sources/NIOHTTP1/HTTPEncoder.swift b/Sources/NIOHTTP1/HTTPEncoder.swift index e833faf93..b69e03eab 100644 --- a/Sources/NIOHTTP1/HTTPEncoder.swift +++ b/Sources/NIOHTTP1/HTTPEncoder.swift @@ -36,7 +36,7 @@ private func writeChunk(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHandler /* we don't want to copy the chunk unnecessarily and therefore call write an annoyingly large number of times */ if isChunked { - var buffer = ctx.channel!.allocator.buffer(capacity: 32) + var buffer = ctx.channel.allocator.buffer(capacity: 32) let len = String(readableBytes, radix: 16) buffer.write(string: len) buffer.write(staticString: "\r\n") @@ -57,18 +57,18 @@ private func writeTrailers(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHand case (true, let p): var buffer: ByteBuffer if let trailers = trailers { - buffer = ctx.channel!.allocator.buffer(capacity: 256) + buffer = ctx.channel.allocator.buffer(capacity: 256) buffer.write(staticString: "0\r\n") trailers.write(buffer: &buffer) // Includes trailing CRLF. } else { - buffer = ctx.channel!.allocator.buffer(capacity: 8) + buffer = ctx.channel.allocator.buffer(capacity: 8) buffer.write(staticString: "0\r\n\r\n") } ctx.write(data: wrapOutboundOut(.byteBuffer(buffer)), promise: p) case (false, .some(let p)): // Not chunked so we have nothing to write. However, we don't want to satisfy this promise out-of-order // so we issue a zero-length write down the chain. - let buf = ctx.channel!.allocator.buffer(capacity: 0) + let buf = ctx.channel.allocator.buffer(capacity: 0) ctx.write(data: wrapOutboundOut(.byteBuffer(buf)), promise: p) case (false, .none): break @@ -77,7 +77,7 @@ private func writeTrailers(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHand private func writeHead(wrapOutboundOut: (IOData) -> NIOAny, writeStartLine: (inout ByteBuffer) -> (), ctx: ChannelHandlerContext, headers: HTTPHeaders, promise: EventLoopPromise?) { - var buffer = ctx.channel!.allocator.buffer(capacity: 256) + var buffer = ctx.channel.allocator.buffer(capacity: 256) writeStartLine(&buffer) headers.write(buffer: &buffer) ctx.write(data: wrapOutboundOut(.byteBuffer(buffer)), promise: promise) diff --git a/Sources/NIOHTTP1/HTTPResponseCompressor.swift b/Sources/NIOHTTP1/HTTPResponseCompressor.swift index 1eb119548..290c04a31 100644 --- a/Sources/NIOHTTP1/HTTPResponseCompressor.swift +++ b/Sources/NIOHTTP1/HTTPResponseCompressor.swift @@ -77,7 +77,7 @@ public final class HTTPResponseCompressor: ChannelInboundHandler, ChannelOutboun } public func handlerAdded(ctx: ChannelHandlerContext) { - pendingResponse = PartialHTTPResponse(bodyBuffer: ctx.channel!.allocator.buffer(capacity: initialByteBufferCapacity)) + pendingResponse = PartialHTTPResponse(bodyBuffer: ctx.channel.allocator.buffer(capacity: initialByteBufferCapacity)) pendingWritePromise = ctx.eventLoop.newPromise() } @@ -212,7 +212,7 @@ public final class HTTPResponseCompressor: ChannelInboundHandler, ChannelOutboun /// /// Called either when a HTTP end message is received or our flush() method is called. private func emitPendingWrites(ctx: ChannelHandlerContext) { - let writesToEmit = pendingResponse.flush(compressor: &stream, allocator: ctx.channel!.allocator) + let writesToEmit = pendingResponse.flush(compressor: &stream, allocator: ctx.channel.allocator) var pendingPromise = pendingWritePromise if let writeHead = writesToEmit.0 { diff --git a/Sources/NIOHTTP1/HTTPUpgradeHandler.swift b/Sources/NIOHTTP1/HTTPUpgradeHandler.swift index 197bd58c2..274f10a5b 100644 --- a/Sources/NIOHTTP1/HTTPUpgradeHandler.swift +++ b/Sources/NIOHTTP1/HTTPUpgradeHandler.swift @@ -143,7 +143,7 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler { self.upgradeCompletionHandler(ctx) upgrader.upgrade(ctx: ctx, upgradeRequest: request) ctx.fireUserInboundEventTriggered(event: HTTPUpgradeEvents.upgradeComplete(toProtocol: proto, upgradeRequest: request)) - let _ = ctx.pipeline!.remove(ctx: ctx) + let _ = ctx.pipeline.remove(ctx: ctx) } return true @@ -162,7 +162,7 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler { /// Called when we know we're not upgrading. Passes the data on and then removes this object from the pipeline. private func notUpgrading(ctx: ChannelHandlerContext, data: NIOAny) { ctx.fireChannelRead(data: data) - let _ = ctx.pipeline!.remove(ctx: ctx) + let _ = ctx.pipeline.remove(ctx: ctx) } /// Builds the initial mandatory HTTP headers for HTTP ugprade responses. diff --git a/Sources/NIOHTTP1Server/main.swift b/Sources/NIOHTTP1Server/main.swift index c118e40c4..ee5352fee 100644 --- a/Sources/NIOHTTP1Server/main.swift +++ b/Sources/NIOHTTP1Server/main.swift @@ -58,7 +58,7 @@ private final class HTTPHandler: ChannelInboundHandler { URL: \(self.infoSavedRequestHead!.uri)\r body length: \(self.infoSavedBodyBytes)\r headers: \(self.infoSavedRequestHead!.headers)\r - client: \(ctx.channel!.remoteAddress?.description ?? "zombie")\r + client: \(ctx.channel.remoteAddress?.description ?? "zombie")\r IO: SwiftNIO Electric Boogaloo™️\r\n """ self.buffer.clear() @@ -110,7 +110,7 @@ private final class HTTPHandler: ChannelInboundHandler { () case .end(_): let _ = ctx.eventLoop.scheduleTask(in: delay) { () -> Void in - var buf = ctx.channel!.allocator.buffer(capacity: string.utf8.count) + var buf = ctx.channel.allocator.buffer(capacity: string.utf8.count) buf.write(string: string) ctx.writeAndFlush(data: self.wrapOutboundOut(.body(.byteBuffer(buf))), promise: nil) var trailers: HTTPHeaders? = nil @@ -194,7 +194,7 @@ private final class HTTPHandler: ChannelInboundHandler { case "/dynamic/count-to-ten": return { self.handleMultipleWrites(ctx: $0, request: $1, strings: (1...10).map { "\($0)\r\n" }, delay: .milliseconds(100)) } case "/dynamic/client-ip": - return { ctx, req in self.handleJustWrite(ctx: ctx, request: req, string: "\(ctx.channel!.remoteAddress.debugDescription)") } + return { ctx, req in self.handleJustWrite(ctx: ctx, request: req, string: "\(ctx.channel.remoteAddress.debugDescription)") } default: return { ctx, req in self.handleJustWrite(ctx: ctx, request: req, statusCode: .notFound, string: "not found") } } @@ -281,7 +281,7 @@ private final class HTTPHandler: ChannelInboundHandler { } func handlerAdded(ctx: ChannelHandlerContext) throws { - self.buffer = ctx.channel!.allocator.buffer(capacity: 12) + self.buffer = ctx.channel.allocator.buffer(capacity: 12) self.buffer.write(staticString: "Hello World!") } } diff --git a/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift b/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift index 04e86ddfe..4777b8080 100644 --- a/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift +++ b/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift @@ -121,7 +121,7 @@ public class ApplicationProtocolNegotiationHandler: ChannelInboundHandler { let switchFuture = completionHandler(result) switchFuture.whenComplete { _ in self.unbuffer(context: context) - _ = context.pipeline?.remove(handler: self) + _ = context.pipeline.remove(handler: self) } } diff --git a/Sources/NIOTLS/SNIHandler.swift b/Sources/NIOTLS/SNIHandler.swift index 21341bbc4..035150753 100644 --- a/Sources/NIOTLS/SNIHandler.swift +++ b/Sources/NIOTLS/SNIHandler.swift @@ -402,7 +402,7 @@ public class SniHandler: ByteToMessageDecoder { private func sniComplete(result: SniResult, ctx: ChannelHandlerContext) { waitingForUser = true _ = completionHandler(result).then { - ctx.pipeline!.remove(handler: self) + ctx.pipeline.remove(handler: self) } } } diff --git a/Tests/NIOHTTP1Tests/HTTPHeadersTest.swift b/Tests/NIOHTTP1Tests/HTTPHeadersTest.swift index 844597f87..6dda88a8f 100644 --- a/Tests/NIOHTTP1Tests/HTTPHeadersTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPHeadersTest.swift @@ -69,6 +69,8 @@ class HTTPHeadersTest : XCTestCase { XCTAssertTrue(writtenBytes.contains("x-something: 3,4\r\n")) XCTAssertTrue(writtenBytes.contains("set-cookie: foo=bar\r\n")) XCTAssertTrue(writtenBytes.contains("set-cookie: buz=cux\r\n")) + + XCTAssertFalse(try channel.finish()) } func testRevealHeadersSeparately() { diff --git a/Tests/NIOHTTP1Tests/HTTPResponseCompressorTest.swift b/Tests/NIOHTTP1Tests/HTTPResponseCompressorTest.swift index 4ad2ef18f..2bc66fba2 100644 --- a/Tests/NIOHTTP1Tests/HTTPResponseCompressorTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPResponseCompressorTest.swift @@ -191,7 +191,7 @@ class HTTPResponseCompressorTest: XCTestCase { // HTTP request to avoid this exploding. let clientChannel = clientParsingChannel() defer { - _ = clientChannel.close() + _ = try! clientChannel.finish() } var requestHead = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/") requestHead.headers.add(name: "host", value: "apple.com") @@ -343,7 +343,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testCanCompressSimpleBodies() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: "deflate", channel: channel) @@ -353,7 +353,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testCanCompressSimpleBodiesGzip() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: "gzip", channel: channel) @@ -363,7 +363,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testCanCompressDeflateWithAwkwardFlushes() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: "deflate", channel: channel) @@ -373,7 +373,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testCanCompressGzipWithAwkwardFlushes() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: "gzip", channel: channel) @@ -383,7 +383,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testDoesNotCompressWithoutAcceptEncodingHeader() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: nil, channel: channel) @@ -393,7 +393,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testHandlesPipelinedRequestsProperly() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } // Three requests: one for deflate, one for gzip, one for nothing. @@ -409,7 +409,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testHandlesBasicQValues() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: "gzip, deflate;q=0.5", channel: channel) @@ -419,7 +419,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testAlwaysPrefersHighestQValue() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: "deflate;q=0.5, gzip;q=0.8, *;q=0.3", channel: channel) @@ -429,7 +429,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testAsteriskMeansGzip() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: "*", channel: channel) @@ -439,7 +439,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testIgnoresUnknownAlgorithms() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: "br", channel: channel) @@ -449,7 +449,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testNonNumericQValuePreventsChoice() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: "deflate;q=fish=fish, gzip;q=0.3", channel: channel) @@ -459,7 +459,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testNaNQValuePreventsChoice() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: "deflate;q=NaN, gzip;q=0.3", channel: channel) @@ -469,7 +469,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testInfinityQValuePreventsChoice() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: "deflate;q=Inf, gzip;q=0.3", channel: channel) @@ -479,7 +479,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testNegativeInfinityQValuePreventsChoice() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: "deflate;q=-Inf, gzip;q=0.3", channel: channel) @@ -489,7 +489,7 @@ class HTTPResponseCompressorTest: XCTestCase { func testOutOfRangeQValuePreventsChoice() throws { let channel = try compressionChannel() defer { - XCTAssertNoThrow(try channel.close().wait()) + XCTAssertNoThrow(try channel.finish()) } try sendRequest(acceptEncoding: "deflate;q=2.2, gzip;q=0.3", channel: channel) diff --git a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift index 63be749e9..f46e1354e 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift @@ -152,7 +152,7 @@ class HTTPServerClientTest : XCTestCase { head.headers.add(name: "Connection", value: "close") let r = HTTPServerResponsePart.head(head) ctx.write(data: self.wrapOutboundOut(r), promise: nil) - var b = ctx.channel!.allocator.buffer(capacity: replyString.count) + var b = ctx.channel.allocator.buffer(capacity: replyString.count) b.write(string: replyString) ctx.write(data: self.wrapOutboundOut(self.outboundBody(b)), promise: nil) @@ -168,7 +168,7 @@ class HTTPServerClientTest : XCTestCase { ctx.write(data: self.wrapOutboundOut(r)).whenComplete { r in assertSuccess(r) } - var b = ctx.channel!.allocator.buffer(capacity: 1024) + var b = ctx.channel.allocator.buffer(capacity: 1024) for i in 1...10 { b.clear() b.write(string: "\(i)") @@ -190,7 +190,7 @@ class HTTPServerClientTest : XCTestCase { ctx.write(data: self.wrapOutboundOut(r)).whenComplete { r in assertSuccess(r) } - var b = ctx.channel!.allocator.buffer(capacity: 1024) + var b = ctx.channel.allocator.buffer(capacity: 1024) for i in 1...10 { b.clear() b.write(string: "\(i)") @@ -210,7 +210,7 @@ class HTTPServerClientTest : XCTestCase { } case "/massive-response": - var buf = ctx.channel!.allocator.buffer(capacity: HTTPServerClientTest.massiveResponseLength) + var buf = ctx.channel.allocator.buffer(capacity: HTTPServerClientTest.massiveResponseLength) buf.writeWithUnsafeMutableBytes { targetPtr in return HTTPServerClientTest.massiveResponseBytes.withUnsafeBytes { srcPtr in precondition(targetPtr.count >= srcPtr.count) diff --git a/Tests/NIOHTTP1Tests/HTTPTest.swift b/Tests/NIOHTTP1Tests/HTTPTest.swift index 07b40fca6..509ceb5dd 100644 --- a/Tests/NIOHTTP1Tests/HTTPTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPTest.swift @@ -75,9 +75,12 @@ class HTTPTest: XCTestCase { var step = 0 var index = 0 let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } try channel.pipeline.add(handler: HTTPRequestDecoder()).wait() - var bodyData: Data? = nil - var allBodyDatas: [Data] = [] + var bodyData: [UInt8]? = nil + var allBodyDatas: [[UInt8]] = [] try channel.pipeline.add(handler: TestChannelInboundHandler { reqPart in switch reqPart { case .head(var req): @@ -88,9 +91,9 @@ class HTTPTest: XCTestCase { step += 1 case .body(var buffer): if bodyData == nil { - bodyData = buffer.readData(length: buffer.readableBytes)! + bodyData = buffer.readBytes(length: buffer.readableBytes)! } else { - bodyData!.append(buffer.readData(length: buffer.readableBytes)!) + bodyData!.append(contentsOf: buffer.readBytes(length: buffer.readableBytes)!) } case .end(let receivedTrailers): XCTAssertEqual(trailers, receivedTrailers) @@ -117,9 +120,9 @@ class HTTPTest: XCTestCase { for bodyData in allBodyDatas { XCTAssertEqual(firstBodyData, bodyData) } - return String(bytes: firstBodyData, encoding: .utf8)! + return String(decoding: firstBodyData, as: UTF8.self) } else { - XCTAssertEqual([], allBodyDatas) + XCTAssertEqual(0, allBodyDatas.count, "left with \(allBodyDatas)") return nil } } diff --git a/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift index 4002070ce..bcbfc90bf 100644 --- a/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift +++ b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift @@ -51,6 +51,8 @@ class ApplicationProtocolNegotiationHandlerTests: XCTestCase { // The channel handler should still be in the pipeline. try channel.pipeline.assertContains(handler: handler) + + XCTAssertFalse(try channel.finish()) } private func negotiateTest(event: TLSUserEvent, expectedResult: ALPNResult) throws { @@ -82,6 +84,8 @@ class ApplicationProtocolNegotiationHandlerTests: XCTestCase { // Now the handler should have removed itself from the pipeline. try channel.pipeline.assertDoesNotContain(handler: handler) + + XCTAssertFalse(try channel.finish()) } func testCallbackReflectsNotificationResult() throws { @@ -106,6 +110,8 @@ class ApplicationProtocolNegotiationHandlerTests: XCTestCase { // The data we write should not be buffered. try channel.writeInbound(data: "hello") XCTAssertEqual(channel.readInbound()!, "hello") + + XCTAssertFalse(try channel.finish()) } func testBufferingWhileWaitingForFuture() throws { @@ -135,6 +141,8 @@ class ApplicationProtocolNegotiationHandlerTests: XCTestCase { XCTAssertEqual(channel.readInbound()!, "writes") XCTAssertEqual(channel.readInbound()!, "are") XCTAssertEqual(channel.readInbound()!, "buffered") + + XCTAssertFalse(try channel.finish()) } func testNothingBufferedDoesNotFireReadCompleted() throws { @@ -160,6 +168,8 @@ class ApplicationProtocolNegotiationHandlerTests: XCTestCase { // readComplete should not be fired. continuePromise.succeed(result: ()) XCTAssertEqual(readCompleteHandler.readCompleteCount, 0) + + XCTAssertFalse(try channel.finish()) } func testUnbufferingFiresReadCompleted() throws { @@ -189,5 +199,7 @@ class ApplicationProtocolNegotiationHandlerTests: XCTestCase { XCTAssertEqual(channel.readInbound()!, "a write") XCTAssertEqual(readCompleteHandler.readCompleteCount, 2) + + XCTAssertFalse(try channel.finish()) } } diff --git a/Tests/NIOTLSTests/SNIHandlerTests.swift b/Tests/NIOTLSTests/SNIHandlerTests.swift index 4009f3f3c..b29c189df 100644 --- a/Tests/NIOTLSTests/SNIHandlerTests.swift +++ b/Tests/NIOTLSTests/SNIHandlerTests.swift @@ -301,6 +301,8 @@ class SniHandlerTest: XCTestCase { XCTAssertEqual(writtenData, expectedData) try channel.pipeline.assertDoesNotContain(handler: handler) + + XCTAssertFalse(try channel.finish()) } /// Blasts the client hello in as a single string. This is not expected to reveal bugs @@ -368,6 +370,8 @@ class SniHandlerTest: XCTestCase { // and no data should have been written. XCTAssertNil(channel.readInbound() as ByteBuffer?) try channel.pipeline.assertContains(handler: handler) + + XCTAssertNoThrow(try channel.finish()) } func testLibre227NoSniDripFeed() throws { diff --git a/Tests/NIOTests/ChannelPipelineTest+XCTest.swift b/Tests/NIOTests/ChannelPipelineTest+XCTest.swift index 235ee79b7..22f3099ea 100644 --- a/Tests/NIOTests/ChannelPipelineTest+XCTest.swift +++ b/Tests/NIOTests/ChannelPipelineTest+XCTest.swift @@ -33,6 +33,7 @@ extension ChannelPipelineTest { ("testEmptyPipelineWorks", testEmptyPipelineWorks), ("testWriteAfterClose", testWriteAfterClose), ("testOutboundNextForInboundOnlyIsCorrect", testOutboundNextForInboundOnlyIsCorrect), + ("testChannelInfrastructureIsNotLeaked", testChannelInfrastructureIsNotLeaked), ] } } diff --git a/Tests/NIOTests/ChannelPipelineTest.swift b/Tests/NIOTests/ChannelPipelineTest.swift index 95e0743c6..d823f1f51 100644 --- a/Tests/NIOTests/ChannelPipelineTest.swift +++ b/Tests/NIOTests/ChannelPipelineTest.swift @@ -76,6 +76,8 @@ class ChannelPipelineTest: XCTestCase { XCTFail("couldn't read from channel") } XCTAssertNil(channel.readOutbound()) + + XCTAssertFalse(try channel.finish()) } func testConnectingDoesntCallBind() throws { @@ -90,9 +92,9 @@ class ChannelPipelineTest: XCTestCase { }).wait() _ = try channel.connect(to: sa).wait() - _ = try channel.close().wait() - - return + defer { + XCTAssertFalse(try channel.finish()) + } } private final class TestChannelOutboundHandler: ChannelOutboundHandler { @@ -227,7 +229,7 @@ class ChannelPipelineTest: XCTestCase { func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { let data = self.unwrapOutboundIn(data) - var buf = ctx.channel!.allocator.buffer(capacity: 123) + var buf = ctx.channel.allocator.buffer(capacity: 123) buf.write(string: String(describing: data)) ctx.write(data: self.wrapOutboundOut(buf), promise: promise) } @@ -281,4 +283,66 @@ class ChannelPipelineTest: XCTestCase { XCTAssertFalse(try channel.finish()) } + + func testChannelInfrastructureIsNotLeaked() throws { + class SomeHandler: ChannelInboundHandler { + typealias InboundIn = Never + + let fn: (ChannelHandlerContext) -> Void + + init(_ fn: @escaping (ChannelHandlerContext) -> Void) { + self.fn = fn + } + + func handlerAdded(ctx: ChannelHandlerContext) { + self.fn(ctx) + } + } + try { + let channel = EmbeddedChannel() + let loop = channel.eventLoop as! EmbeddedEventLoop + + weak var weakHandler1: ChannelHandler? + weak var weakHandler2: ChannelHandler? + weak var weakHandlerContext1: ChannelHandlerContext? + weak var weakHandlerContext2: ChannelHandlerContext? + + () /* needed because Swift's grammar is so ambiguous that you can't remove this :\ */ + + try { + let handler1 = SomeHandler { ctx in + weakHandlerContext1 = ctx + } + weakHandler1 = handler1 + let handler2 = SomeHandler { ctx in + weakHandlerContext2 = ctx + } + weakHandler2 = handler2 + XCTAssertNoThrow(try channel.pipeline.add(handler: handler1).then { _ in + channel.pipeline.add(handler: handler2) + }.wait()) + }() + + XCTAssertNotNil(weakHandler1) + XCTAssertNotNil(weakHandler2) + XCTAssertNotNil(weakHandlerContext1) + XCTAssertNotNil(weakHandlerContext2) + + XCTAssertNoThrow(try channel.pipeline.remove(handler: weakHandler1!).wait()) + + XCTAssertNil(weakHandler1) + XCTAssertNotNil(weakHandler2) + XCTAssertNil(weakHandlerContext1) + XCTAssertNotNil(weakHandlerContext2) + + XCTAssertFalse(try channel.finish()) + + XCTAssertNil(weakHandler1) + XCTAssertNil(weakHandler2) + XCTAssertNil(weakHandlerContext1) + XCTAssertNil(weakHandlerContext2) + + XCTAssertNoThrow(try loop.syncShutdownGracefully()) + }() + } } diff --git a/Tests/NIOTests/ChannelTests.swift b/Tests/NIOTests/ChannelTests.swift index 0f3131758..25fe9d4b7 100644 --- a/Tests/NIOTests/ChannelTests.swift +++ b/Tests/NIOTests/ChannelTests.swift @@ -35,7 +35,7 @@ class ChannelLifecycleHandler: ChannelInboundHandler { public func channelRegistered(ctx: ChannelHandlerContext) { XCTAssertEqual(currentState, .unregistered) - XCTAssertFalse(ctx.channel!.isActive) + XCTAssertFalse(ctx.channel.isActive) currentState = .inactive stateHistory.append(.inactive) ctx.fireChannelRegistered() @@ -43,7 +43,7 @@ class ChannelLifecycleHandler: ChannelInboundHandler { public func channelActive(ctx: ChannelHandlerContext) { XCTAssertEqual(currentState, .inactive) - XCTAssertTrue(ctx.channel!.isActive) + XCTAssertTrue(ctx.channel.isActive) currentState = .active stateHistory.append(.active) ctx.fireChannelActive() @@ -51,7 +51,7 @@ class ChannelLifecycleHandler: ChannelInboundHandler { public func channelInactive(ctx: ChannelHandlerContext) { XCTAssertEqual(currentState, .active) - XCTAssertFalse(ctx.channel!.isActive) + XCTAssertFalse(ctx.channel.isActive) currentState = .inactive stateHistory.append(.inactive) ctx.fireChannelInactive() @@ -59,7 +59,7 @@ class ChannelLifecycleHandler: ChannelInboundHandler { public func channelUnregistered(ctx: ChannelHandlerContext) { XCTAssertEqual(currentState, .inactive) - XCTAssertFalse(ctx.channel!.isActive) + XCTAssertFalse(ctx.channel.isActive) currentState = .unregistered stateHistory.append(.unregistered) ctx.fireChannelUnregistered() @@ -1150,7 +1150,7 @@ public class ChannelTests: XCTestCase { func testHalfClosure() throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { - try! group.syncShutdownGracefully() + XCTAssertNoThrow(try group.syncShutdownGracefully()) } let server = try ServerSocket(protocolFamily: PF_INET) diff --git a/Tests/NIOTests/CodecTest.swift b/Tests/NIOTests/CodecTest.swift index 2aaf3dfd2..92c98160c 100644 --- a/Tests/NIOTests/CodecTest.swift +++ b/Tests/NIOTests/CodecTest.swift @@ -67,7 +67,7 @@ public class ByteToMessageDecoderTest: XCTestCase { buffer2.write(integer: Int32(3)) channel.pipeline.fireChannelRead(data: NIOAny(buffer2)) - try channel.close().wait() + XCTAssertNoThrow(try channel.finish()) XCTAssertEqual(Int32(1), channel.readInbound()) XCTAssertEqual(Int32(2), channel.readInbound()) @@ -77,6 +77,9 @@ public class ByteToMessageDecoderTest: XCTestCase { func testDecoderPropagatesChannelInactive() throws { let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } let inactivePromiser = ChannelInactivePromiser(channel: channel) _ = try channel.pipeline.add(handler: ByteToInt32Decoder()).wait() _ = try channel.pipeline.add(handler: inactivePromiser).wait() @@ -105,7 +108,7 @@ public class MessageToByteEncoderTest: XCTestCase { } public func allocateOutBuffer(ctx: ChannelHandlerContext, data: Int32) throws -> ByteBuffer { - return ctx.channel!.allocator.buffer(capacity: MemoryLayout.size) + return ctx.channel.allocator.buffer(capacity: MemoryLayout.size) } } @@ -141,6 +144,7 @@ public class MessageToByteEncoderTest: XCTestCase { XCTFail("couldn't read ByteBuffer from channel") } - try channel.close().wait() + XCTAssertFalse(try channel.finish()) + } } diff --git a/Tests/NIOTests/EchoServerClientTest.swift b/Tests/NIOTests/EchoServerClientTest.swift index 0047d7a62..ec3e0e52f 100644 --- a/Tests/NIOTests/EchoServerClientTest.swift +++ b/Tests/NIOTests/EchoServerClientTest.swift @@ -258,7 +258,7 @@ class EchoServerClientTest : XCTestCase { private var promise: EventLoopPromise! = nil func handlerAdded(ctx: ChannelHandlerContext) { - promise = ctx.channel!.eventLoop.newPromise() + promise = ctx.channel.eventLoop.newPromise() } func channelActive(ctx: ChannelHandlerContext) { @@ -407,7 +407,7 @@ class EchoServerClientTest : XCTestCase { } func channelActive(ctx: ChannelHandlerContext) { - var dataToWrite = ctx.channel!.allocator.buffer(capacity: toWrite.utf8.count) + var dataToWrite = ctx.channel.allocator.buffer(capacity: toWrite.utf8.count) dataToWrite.write(string: toWrite) ctx.writeAndFlush(data: NIOAny(dataToWrite), promise: nil) ctx.fireChannelActive() @@ -600,7 +600,7 @@ class EchoServerClientTest : XCTestCase { dpGroup.wait() /* make sure we stick around until the second write has happened */ - try! group.syncShutdownGracefully() + XCTAssertNoThrow(try group.syncShutdownGracefully()) } func testPendingReadProcessedAfterWriteError() throws { @@ -619,7 +619,7 @@ class EchoServerClientTest : XCTestCase { private var writeFailed = false func channelActive(ctx: ChannelHandlerContext) { - var buffer = ctx.channel!.allocator.buffer(capacity: 4) + var buffer = ctx.channel.allocator.buffer(capacity: 4) buffer.write(string: "test") writeUntilFailed(ctx, buffer) } @@ -645,7 +645,7 @@ class EchoServerClientTest : XCTestCase { func channelActive(ctx: ChannelHandlerContext) { ctx.fireChannelActive() - var buffer = ctx.channel!.allocator.buffer(capacity: str.utf8.count) + var buffer = ctx.channel.allocator.buffer(capacity: str.utf8.count) buffer.write(string: str) // write it four times and then close the connect. @@ -695,6 +695,6 @@ class EchoServerClientTest : XCTestCase { try countingHandler.assertReceived(buffer: completeBuffer) - try! group.syncShutdownGracefully() + XCTAssertNoThrow(try group.syncShutdownGracefully()) } } diff --git a/Tests/NIOTests/EmbeddedChannelTest.swift b/Tests/NIOTests/EmbeddedChannelTest.swift index 18415e8c3..d26585191 100644 --- a/Tests/NIOTests/EmbeddedChannelTest.swift +++ b/Tests/NIOTests/EmbeddedChannelTest.swift @@ -66,7 +66,7 @@ class EmbeddedChannelTest: XCTestCase { func testCloseMultipleTimesThrows() throws { let channel = EmbeddedChannel() - _ = try channel.close().wait() + XCTAssertFalse(try channel.finish()) // Close a second time. This must fail. do { @@ -81,7 +81,7 @@ class EmbeddedChannelTest: XCTestCase { let channel = EmbeddedChannel() let inactiveHandler = CloseInChannelInactiveHandler() _ = try channel.pipeline.add(handler: inactiveHandler).wait() - _ = try channel.close().wait() + XCTAssertFalse(try channel.finish()) // channelInactive should fire only once. XCTAssertEqual(inactiveHandler.inactiveNotifications, 1) @@ -100,7 +100,7 @@ class EmbeddedChannelTest: XCTestCase { XCTAssertEqual(handler.currentState, .active) XCTAssertTrue(channel.isActive) - _ = try channel.close().wait() + XCTAssertFalse(try channel.finish()) XCTAssertEqual(handler.currentState, .unregistered) XCTAssertFalse(channel.isActive) } @@ -138,6 +138,7 @@ class EmbeddedChannelTest: XCTestCase { let pipelineEventLoop = channel.pipeline.eventLoop XCTAssert(pipelineEventLoop === channel.eventLoop) XCTAssert(pipelineEventLoop === (channel._unsafe as! EmbeddedChannelCore).eventLoop) + XCTAssertFalse(try channel.finish()) } func testSendingIncorrectDataOnEmbeddedChannel() { @@ -151,5 +152,7 @@ class EmbeddedChannelTest: XCTestCase { } catch { XCTFail("Got \(error)") } + + XCTAssertFalse(try channel.finish()) } } diff --git a/Tests/NIOTests/IdleStateHandlerTest.swift b/Tests/NIOTests/IdleStateHandlerTest.swift index 73eb0b351..d597a75f8 100644 --- a/Tests/NIOTests/IdleStateHandlerTest.swift +++ b/Tests/NIOTests/IdleStateHandlerTest.swift @@ -67,7 +67,7 @@ class IdleStateHandlerTest : XCTestCase { public func channelActive(ctx: ChannelHandlerContext) { if writeToChannel { - var buffer = ctx.channel!.allocator.buffer(capacity: 4) + var buffer = ctx.channel.allocator.buffer(capacity: 4) buffer.write(staticString: "test") ctx.writeAndFlush(data: self.wrapOutboundOut(buffer), promise: nil) } diff --git a/Tests/NIOTests/TestUtils.swift b/Tests/NIOTests/TestUtils.swift index becc60357..55de58fdd 100644 --- a/Tests/NIOTests/TestUtils.swift +++ b/Tests/NIOTests/TestUtils.swift @@ -28,7 +28,7 @@ final class ByteCountingHandler : ChannelInboundHandler { } func handlerAdded(ctx: ChannelHandlerContext) { - buffer = ctx.channel!.allocator.buffer(capacity: numBytes) + buffer = ctx.channel.allocator.buffer(capacity: numBytes) if self.numBytes == 0 { self.promise.succeed(result: buffer) }