From a41280919e92137273572b0364a2cce2dfb178d2 Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Mon, 25 Feb 2019 18:20:22 +0000 Subject: [PATCH] rename ctx to context (#842) Motivation: `ctx` was always an abbreviation was 'context` and in Swift we don't really use abbreviations, so let's fix it. Modifications: - rename all instances of `ctx` to `context` Result: - fixes #483 --- .../Sources/SwiftBootstrap/SwiftMain.swift | 44 ++-- Sources/NIO/Bootstrap.swift | 30 +-- Sources/NIO/ChannelHandler.swift | 196 +++++++++--------- Sources/NIO/ChannelHandlers.swift | 138 ++++++------ Sources/NIO/ChannelPipeline.swift | 174 ++++++++-------- Sources/NIO/Codec.swift | 94 ++++----- Sources/NIO/Embedded.swift | 2 +- Sources/NIO/NIOAny.swift | 4 +- Sources/NIOChatClient/main.swift | 6 +- Sources/NIOChatServer/main.swift | 34 +-- Sources/NIOEchoClient/main.swift | 16 +- Sources/NIOEchoServer/main.swift | 12 +- Sources/NIOHTTP1/HTTPDecoder.swift | 84 ++++---- Sources/NIOHTTP1/HTTPEncoder.swift | 48 ++--- Sources/NIOHTTP1/HTTPResponseCompressor.swift | 40 ++-- .../NIOHTTP1/HTTPServerPipelineHandler.swift | 64 +++--- .../HTTPServerProtocolErrorHandler.swift | 14 +- Sources/NIOHTTP1/HTTPUpgradeHandler.swift | 64 +++--- Sources/NIOHTTP1Server/main.swift | 170 +++++++-------- Sources/NIOMulticastChat/main.swift | 8 +- Sources/NIOPerformanceTester/main.swift | 36 ++-- ...pplicationProtocolNegotiationHandler.swift | 12 +- Sources/NIOTLS/SNIHandler.swift | 16 +- .../NIOWebSocket/WebSocketFrameDecoder.swift | 18 +- .../NIOWebSocket/WebSocketFrameEncoder.swift | 14 +- .../WebSocketProtocolErrorHandler.swift | 10 +- Sources/NIOWebSocket/WebSocketUpgrader.swift | 10 +- Sources/NIOWebSocketServer/main.swift | 80 +++---- Sources/_NIO1APIShims/NIO1APIShims.swift | 12 +- .../NIOHTTP1Tests/HTTPDecoderLengthTest.swift | 10 +- Tests/NIOHTTP1Tests/HTTPDecoderTest.swift | 40 ++-- .../NIOHTTP1Tests/HTTPServerClientTest.swift | 66 +++--- .../HTTPServerPipelineHandlerTest.swift | 44 ++-- .../HTTPServerProtocolErrorHandlerTest.swift | 4 +- Tests/NIOHTTP1Tests/HTTPTest.swift | 4 +- Tests/NIOHTTP1Tests/HTTPUpgradeTests.swift | 74 +++---- ...ationProtocolNegotiationHandlerTests.swift | 2 +- Tests/NIOTests/AcceptBackoffHandlerTest.swift | 6 +- Tests/NIOTests/ChannelNotificationTest.swift | 150 +++++++------- Tests/NIOTests/ChannelPipelineTest.swift | 92 ++++---- Tests/NIOTests/ChannelTests.swift | 164 +++++++-------- Tests/NIOTests/CodecTest.swift | 190 ++++++++--------- Tests/NIOTests/DatagramChannelTests.swift | 14 +- Tests/NIOTests/EchoServerClientTest.swift | 86 ++++---- Tests/NIOTests/EmbeddedChannelTest.swift | 10 +- Tests/NIOTests/EventLoopTest.swift | 12 +- Tests/NIOTests/HappyEyeballsTest.swift | 14 +- Tests/NIOTests/IdleStateHandlerTest.swift | 30 +-- Tests/NIOTests/MulticastTest.swift | 4 +- Tests/NIOTests/SelectorTest.swift | 36 ++-- Tests/NIOTests/SocketChannelTest.swift | 38 ++-- Tests/NIOTests/TestUtils.swift | 6 +- Tests/NIOWebSocketTests/EndToEndTests.swift | 8 +- .../WebSocketFrameDecoderTest.swift | 16 +- docs/public-api-changes-NIO1-to-NIO2.md | 2 + 55 files changed, 1287 insertions(+), 1285 deletions(-) diff --git a/IntegrationTests/tests_04_performance/test_01_resources/template/Sources/SwiftBootstrap/SwiftMain.swift b/IntegrationTests/tests_04_performance/test_01_resources/template/Sources/SwiftBootstrap/SwiftMain.swift index 521a0f8ca..3355861ad 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/template/Sources/SwiftBootstrap/SwiftMain.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/template/Sources/SwiftBootstrap/SwiftMain.swift @@ -42,11 +42,11 @@ private final class SimpleHTTPServer: ChannelInboundHandler { return buffer } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { if case .head(let req) = self.unwrapInboundIn(data), req.uri == "/allocation-test-1" { - ctx.write(self.wrapOutboundOut(.head(self.responseHead)), promise: nil) - ctx.write(self.wrapOutboundOut(.body(.byteBuffer(self.responseBody(allocator: ctx.channel.allocator)))), promise: nil) - ctx.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + 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) } } } @@ -75,25 +75,25 @@ private final class PingHandler: ChannelInboundHandler { self.allDone = eventLoop.makePromise() } - public func channelActive(ctx: ChannelHandlerContext) { - self.pingBuffer = ctx.channel.allocator.buffer(capacity: 1) + public func channelActive(context: ChannelHandlerContext) { + self.pingBuffer = context.channel.allocator.buffer(capacity: 1) self.pingBuffer.writeInteger(PingHandler.pingCode) - ctx.writeAndFlush(self.wrapOutboundOut(self.pingBuffer), promise: nil) + context.writeAndFlush(self.wrapOutboundOut(self.pingBuffer), promise: nil) } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { var buf = self.unwrapInboundIn(data) if buf.readableBytes == 1 && buf.readInteger(as: UInt8.self) == PongHandler.pongCode { if self.remainingNumberOfRequests > 0 { self.remainingNumberOfRequests -= 1 - ctx.writeAndFlush(self.wrapOutboundOut(self.pingBuffer), promise: nil) + context.writeAndFlush(self.wrapOutboundOut(self.pingBuffer), promise: nil) } else { - ctx.close(promise: self.allDone) + context.close(promise: self.allDone) } } else { - ctx.close(promise: nil) + context.close(promise: nil) self.allDone.fail(PingPongFailure(problem: "wrong buffer received: \(buf.debugDescription)")) } } @@ -110,18 +110,18 @@ private final class PongHandler: ChannelInboundHandler { private var pongBuffer: ByteBuffer! public static let pongCode: UInt8 = 0xef - public func channelActive(ctx: ChannelHandlerContext) { - self.pongBuffer = ctx.channel.allocator.buffer(capacity: 1) + public func channelActive(context: ChannelHandlerContext) { + self.pongBuffer = context.channel.allocator.buffer(capacity: 1) self.pongBuffer.writeInteger(PongHandler.pongCode) } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { var buf = self.unwrapInboundIn(data) if buf.readableBytes == 1 && buf.readInteger(as: UInt8.self) == PingHandler.pingCode { - ctx.writeAndFlush(self.wrapOutboundOut(self.pongBuffer), promise: nil) + context.writeAndFlush(self.wrapOutboundOut(self.pongBuffer), promise: nil) } else { - ctx.close(promise: nil) + context.close(promise: nil) } } } @@ -163,20 +163,20 @@ public func swiftMain() -> Int { return reqs } - func errorCaught(ctx: ChannelHandlerContext, error: Error) { - ctx.channel.close(promise: nil) + func errorCaught(context: ChannelHandlerContext, error: Error) { + context.channel.close(promise: nil) self.isDonePromise.fail(error) } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let respPart = self.unwrapInboundIn(data) if case .end(nil) = respPart { if self.remainingNumberOfRequests <= 0 { - ctx.channel.close().map { self.numberOfRequests - self.remainingNumberOfRequests }.cascade(to: self.isDonePromise) + context.channel.close().map { self.numberOfRequests - self.remainingNumberOfRequests }.cascade(to: self.isDonePromise) } else { self.remainingNumberOfRequests -= 1 - ctx.write(self.wrapOutboundOut(.head(RepeatedRequests.requestHead)), promise: nil) - ctx.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(self.wrapOutboundOut(.head(RepeatedRequests.requestHead)), promise: nil) + context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) } } } diff --git a/Sources/NIO/Bootstrap.swift b/Sources/NIO/Bootstrap.swift index 9f06f96c6..d8bcaba07 100644 --- a/Sources/NIO/Bootstrap.swift +++ b/Sources/NIO/Bootstrap.swift @@ -247,16 +247,16 @@ public final class ServerBootstrap { self.childChannelOptions = childChannelOptions } - func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { if event is ChannelShouldQuiesceEvent { - ctx.channel.close(promise: nil) + context.channel.close(promise: nil) } - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let accepted = self.unwrapInboundIn(data) - let ctxEventLoop = ctx.eventLoop + let ctxEventLoop = context.eventLoop let childEventLoop = accepted.eventLoop let childChannelInit = self.childChannelInit ?? { (_: Channel) in childEventLoop.makeSucceededFuture(()) } @@ -273,14 +273,14 @@ public final class ServerBootstrap { ctxEventLoop.assertInEventLoop() future.flatMap { (_) -> EventLoopFuture in ctxEventLoop.assertInEventLoop() - guard !ctx.pipeline.destroyed else { - return ctx.eventLoop.makeFailedFuture(ChannelError.ioOnClosedChannel) + guard !context.pipeline.destroyed else { + return context.eventLoop.makeFailedFuture(ChannelError.ioOnClosedChannel) } - ctx.fireChannelRead(data) - return ctx.eventLoop.makeSucceededFuture(()) + context.fireChannelRead(data) + return context.eventLoop.makeSucceededFuture(()) }.whenFailure { error in ctxEventLoop.assertInEventLoop() - self.closeAndFire(ctx: ctx, accepted: accepted, err: error) + self.closeAndFire(context: context, accepted: accepted, err: error) } } @@ -293,13 +293,13 @@ public final class ServerBootstrap { } } - private func closeAndFire(ctx: ChannelHandlerContext, accepted: SocketChannel, err: Error) { + private func closeAndFire(context: ChannelHandlerContext, accepted: SocketChannel, err: Error) { accepted.close(promise: nil) - if ctx.eventLoop.inEventLoop { - ctx.fireErrorCaught(err) + if context.eventLoop.inEventLoop { + context.fireErrorCaught(err) } else { - ctx.eventLoop.execute { - ctx.fireErrorCaught(err) + context.eventLoop.execute { + context.fireErrorCaught(err) } } } diff --git a/Sources/NIO/ChannelHandler.swift b/Sources/NIO/ChannelHandler.swift index 341260cd4..f459258f3 100644 --- a/Sources/NIO/ChannelHandler.swift +++ b/Sources/NIO/ChannelHandler.swift @@ -21,14 +21,14 @@ public protocol ChannelHandler: class { /// Called when this `ChannelHandler` is added to the `ChannelPipeline`. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. - func handlerAdded(ctx: ChannelHandlerContext) + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + func handlerAdded(context: ChannelHandlerContext) /// Called when this `ChannelHandler` is removed from the `ChannelPipeline`. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. - func handlerRemoved(ctx: ChannelHandlerContext) + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + func handlerRemoved(context: ChannelHandlerContext) } /// Untyped `ChannelHandler` which handles outbound I/O events or intercept an outbound I/O operation. @@ -42,89 +42,89 @@ public protocol ChannelHandler: class { public protocol _ChannelOutboundHandler: ChannelHandler { /// Called to request that the `Channel` register itself for I/O events with its `EventLoop`. - /// This should call `ctx.register` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or + /// This should call `context.register` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or /// complete the `EventLoopPromise` to let the caller know that the operation completed. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. - func register(ctx: ChannelHandlerContext, promise: EventLoopPromise?) + func register(context: ChannelHandlerContext, promise: EventLoopPromise?) /// Called to request that the `Channel` bind to a specific `SocketAddress`. /// - /// This should call `ctx.bind` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or + /// This should call `context.bind` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or /// complete the `EventLoopPromise` to let the caller know that the operation completed. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. /// - to: The `SocketAddress` to which this `Channel` should bind. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. - func bind(ctx: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise?) + func bind(context: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise?) /// Called to request that the `Channel` connect to a given `SocketAddress`. /// - /// This should call `ctx.connect` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or + /// This should call `context.connect` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or /// complete the `EventLoopPromise` to let the caller know that the operation completed. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. /// - to: The `SocketAddress` to which the the `Channel` should connect. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. - func connect(ctx: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise?) + func connect(context: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise?) /// Called to request a write operation. The write operation will write the messages through the /// `ChannelPipeline`. Those are then ready to be flushed to the actual `Channel` when /// `Channel.flush` or `ChannelHandlerContext.flush` is called. /// - /// This should call `ctx.write` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or + /// This should call `context.write` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or /// complete the `EventLoopPromise` to let the caller know that the operation completed. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. /// - data: The data to write through the `Channel`, wrapped in a `NIOAny`. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. - func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) + func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) /// Called to request that the `Channel` flush all pending writes. The flush operation will try to flush out all previous written messages /// that are pending. /// - /// This should call `ctx.flush` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or just + /// This should call `context.flush` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or just /// discard it if the flush should be suppressed. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. - func flush(ctx: ChannelHandlerContext) + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + func flush(context: ChannelHandlerContext) /// Called to request that the `Channel` perform a read when data is ready. The read operation will signal that we are ready to read more data. /// - /// This should call `ctx.read` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or just + /// This should call `context.read` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or just /// discard it if the flush should be suppressed. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. - func read(ctx: ChannelHandlerContext) + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + func read(context: ChannelHandlerContext) /// Called to request that the `Channel` close itself down`. /// - /// This should call `ctx.close` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or + /// This should call `context.close` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or /// complete the `EventLoopPromise` to let the caller know that the operation completed. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. /// - mode: The `CloseMode` to apply /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. - func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) + func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) /// Called when an user outbound event is triggered. /// - /// This should call `ctx.triggerUserOutboundEvent` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or + /// This should call `context.triggerUserOutboundEvent` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or /// complete the `EventLoopPromise` to let the caller know that the operation completed. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. /// - event: The triggered event. /// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place. - func triggerUserOutboundEvent(ctx: ChannelHandlerContext, event: Any, promise: EventLoopPromise?) + func triggerUserOutboundEvent(context: ChannelHandlerContext, event: Any, promise: EventLoopPromise?) } /// Untyped `ChannelHandler` which handles inbound I/O events. @@ -139,173 +139,173 @@ public protocol _ChannelInboundHandler: ChannelHandler { /// Called when the `Channel` has successfully registered with its `EventLoop` to handle I/O. /// - /// This should call `ctx.fireChannelRegistered` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. + /// This should call `context.fireChannelRegistered` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. - func channelRegistered(ctx: ChannelHandlerContext) + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + func channelRegistered(context: ChannelHandlerContext) /// Called when the `Channel` has unregistered from its `EventLoop`, and so will no longer be receiving I/O events. /// - /// This should call `ctx.fireChannelUnregistered` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. + /// This should call `context.fireChannelUnregistered` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. - func channelUnregistered(ctx: ChannelHandlerContext) + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + func channelUnregistered(context: ChannelHandlerContext) /// Called when the `Channel` has become active, and is able to send and receive data. /// - /// This should call `ctx.fireChannelActive` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. + /// This should call `context.fireChannelActive` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. - func channelActive(ctx: ChannelHandlerContext) + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + func channelActive(context: ChannelHandlerContext) /// Called when the `Channel` has become inactive and is no longer able to send and receive data`. /// - /// This should call `ctx.fireChannelInactive` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. + /// This should call `context.fireChannelInactive` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. - func channelInactive(ctx: ChannelHandlerContext) + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + func channelInactive(context: ChannelHandlerContext) /// Called when some data has been read from the remote peer. /// - /// This should call `ctx.fireChannelRead` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. + /// This should call `context.fireChannelRead` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. /// - data: The data read from the remote peer, wrapped in a `NIOAny`. - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) + func channelRead(context: ChannelHandlerContext, data: NIOAny) /// Called when the `Channel` has completed its current read loop, either because no more data is available to read from the transport at this time, or because the `Channel` needs to yield to the event loop to process other I/O events for other `Channel`s. /// If `ChannelOptions.autoRead` is `false` no further read attempt will be made until `ChannelHandlerContext.read` or `Channel.read` is explicitly called. /// - /// This should call `ctx.fireChannelReadComplete` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. + /// This should call `context.fireChannelReadComplete` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. - func channelReadComplete(ctx: ChannelHandlerContext) + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + func channelReadComplete(context: ChannelHandlerContext) /// The writability state of the `Channel` has changed, either because it has buffered more data than the writability high water mark, or because the amount of buffered data has dropped below the writability low water mark. /// You can check the state with `Channel.isWritable`. /// - /// This should call `ctx.fireChannelWritabilityChanged` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. + /// This should call `context.fireChannelWritabilityChanged` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. - func channelWritabilityChanged(ctx: ChannelHandlerContext) + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + func channelWritabilityChanged(context: ChannelHandlerContext) /// Called when a user inbound event has been triggered. /// - /// This should call `ctx.fireUserInboundEventTriggered` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. + /// This should call `context.fireUserInboundEventTriggered` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. /// - event: The event. - func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) + func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) /// An error was encountered earlier in the inbound `ChannelPipeline`. /// - /// This should call `ctx.fireErrorCaught` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the error. + /// This should call `context.fireErrorCaught` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the error. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. + /// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to. /// - error: The `Error` that was encountered. - func errorCaught(ctx: ChannelHandlerContext, error: Error) + func errorCaught(context: ChannelHandlerContext, error: Error) } // Default implementations for the ChannelHandler protocol extension ChannelHandler { /// Do nothing by default. - public func handlerAdded(ctx: ChannelHandlerContext) { + public func handlerAdded(context: ChannelHandlerContext) { } /// Do nothing by default. - public func handlerRemoved(ctx: ChannelHandlerContext) { + public func handlerRemoved(context: ChannelHandlerContext) { } } /// Provides default implementations for all methods defined by `_ChannelOutboundHandler`. /// -/// These default implementations will just call `ctx.methodName` to forward to the next `_ChannelOutboundHandler` in +/// These default implementations will just call `context.methodName` to forward to the next `_ChannelOutboundHandler` in /// the `ChannelPipeline` until the operation is handled by the `Channel` itself. extension _ChannelOutboundHandler { - public func register(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { - ctx.register(promise: promise) + public func register(context: ChannelHandlerContext, promise: EventLoopPromise?) { + context.register(promise: promise) } - public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { - ctx.bind(to: address, promise: promise) + public func bind(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + context.bind(to: address, promise: promise) } - public func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { - ctx.connect(to: address, promise: promise) + public func connect(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + context.connect(to: address, promise: promise) } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - ctx.write(data, promise: promise) + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + context.write(data, promise: promise) } - public func flush(ctx: ChannelHandlerContext) { - ctx.flush() + public func flush(context: ChannelHandlerContext) { + context.flush() } - public func read(ctx: ChannelHandlerContext) { - ctx.read() + public func read(context: ChannelHandlerContext) { + context.read() } - public func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { - ctx.close(mode: mode, promise: promise) + public func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { + context.close(mode: mode, promise: promise) } - public func triggerUserOutboundEvent(ctx: ChannelHandlerContext, event: Any, promise: EventLoopPromise?) { - ctx.triggerUserOutboundEvent(event, promise: promise) + public func triggerUserOutboundEvent(context: ChannelHandlerContext, event: Any, promise: EventLoopPromise?) { + context.triggerUserOutboundEvent(event, promise: promise) } } /// Provides default implementations for all methods defined by `_ChannelInboundHandler`. /// -/// These default implementations will just `ctx.fire*` to forward to the next `_ChannelInboundHandler` in +/// These default implementations will just `context.fire*` to forward to the next `_ChannelInboundHandler` in /// the `ChannelPipeline` until the operation is handled by the `Channel` itself. extension _ChannelInboundHandler { - public func channelRegistered(ctx: ChannelHandlerContext) { - ctx.fireChannelRegistered() + public func channelRegistered(context: ChannelHandlerContext) { + context.fireChannelRegistered() } - public func channelUnregistered(ctx: ChannelHandlerContext) { - ctx.fireChannelUnregistered() + public func channelUnregistered(context: ChannelHandlerContext) { + context.fireChannelUnregistered() } - public func channelActive(ctx: ChannelHandlerContext) { - ctx.fireChannelActive() + public func channelActive(context: ChannelHandlerContext) { + context.fireChannelActive() } - public func channelInactive(ctx: ChannelHandlerContext) { - ctx.fireChannelInactive() + public func channelInactive(context: ChannelHandlerContext) { + context.fireChannelInactive() } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { - ctx.fireChannelRead(data) + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { + context.fireChannelRead(data) } - public func channelReadComplete(ctx: ChannelHandlerContext) { - ctx.fireChannelReadComplete() + public func channelReadComplete(context: ChannelHandlerContext) { + context.fireChannelReadComplete() } - public func channelWritabilityChanged(ctx: ChannelHandlerContext) { - ctx.fireChannelWritabilityChanged() + public func channelWritabilityChanged(context: ChannelHandlerContext) { + context.fireChannelWritabilityChanged() } - public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { - ctx.fireUserInboundEventTriggered(event) + public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { + context.fireUserInboundEventTriggered(event) } - public func errorCaught(ctx: ChannelHandlerContext, error: Error) { - ctx.fireErrorCaught(error) + public func errorCaught(context: ChannelHandlerContext, error: Error) { + context.fireErrorCaught(error) } } @@ -328,18 +328,18 @@ public protocol RemovableChannelHandler: ChannelHandler { /// remove a `RemovableChannelHandler` from the `ChannelPipeline`, use `ChannelPipeline.remove`. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` of the `RemovableChannelHandler` to be removed from the `ChannelPipeline`. + /// - context: The `ChannelHandlerContext` of the `RemovableChannelHandler` to be removed from the `ChannelPipeline`. /// - removalToken: The removal token to hand to `ChannelHandlerContext.removeHandler` to trigger the actual /// removal from the `ChannelPipeline`. - func removeHandler(ctx: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) + func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) } extension RemovableChannelHandler { // Implements the default behaviour which is to synchronously remove the handler from the pipeline. Thanks to this, // stateless `ChannelHandler`s can just use `RemovableChannelHandler` as a marker-protocol and declare themselves // as removable without writing any extra code. - public func removeHandler(ctx: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { - precondition(ctx.handler === self) - ctx.leavePipeline(removalToken: removalToken) + public func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { + precondition(context.handler === self) + context.leavePipeline(removalToken: removalToken) } } diff --git a/Sources/NIO/ChannelHandlers.swift b/Sources/NIO/ChannelHandlers.swift index bd151297b..1d59f282c 100644 --- a/Sources/NIO/ChannelHandlers.swift +++ b/Sources/NIO/ChannelHandlers.swift @@ -39,7 +39,7 @@ public final class AcceptBackoffHandler: ChannelDuplexHandler, RemovableChannelH self.backoffProvider = backoffProvider } - public func read(ctx: ChannelHandlerContext) { + public func read(context: ChannelHandlerContext) { // If we already have a read scheduled there is no need to schedule another one. guard scheduledRead == nil else { return } @@ -47,59 +47,59 @@ public final class AcceptBackoffHandler: ChannelDuplexHandler, RemovableChannelH let now = NIODeadline.now() if now >= deadline { // The backoff already expired, just do a read. - doRead(ctx) + doRead(context) } else { // Schedule the read to be executed after the backoff time elapsed. - scheduleRead(at: deadline, ctx: ctx) + scheduleRead(at: deadline, context: context) } } else { - ctx.read() + context.read() } } - public func errorCaught(ctx: ChannelHandlerContext, error: Error) { + public func errorCaught(context: ChannelHandlerContext, error: Error) { if let ioError = error as? IOError { if let amount = backoffProvider(ioError) { self.nextReadDeadlineNS = .now() + amount if let scheduled = self.scheduledRead { scheduled.cancel() - scheduleRead(at: self.nextReadDeadlineNS!, ctx: ctx) + scheduleRead(at: self.nextReadDeadlineNS!, context: context) } } } - ctx.fireErrorCaught(error) + context.fireErrorCaught(error) } - public func channelInactive(ctx: ChannelHandlerContext) { + public func channelInactive(context: ChannelHandlerContext) { if let scheduled = self.scheduledRead { scheduled.cancel() self.scheduledRead = nil } self.nextReadDeadlineNS = nil - ctx.fireChannelInactive() + context.fireChannelInactive() } - public func handlerRemoved(ctx: ChannelHandlerContext) { + public func handlerRemoved(context: ChannelHandlerContext) { if let scheduled = self.scheduledRead { // Cancel the previous scheduled read and trigger a read directly. This is needed as otherwise we may never read again. scheduled.cancel() self.scheduledRead = nil - ctx.read() + context.read() } self.nextReadDeadlineNS = nil } - private func scheduleRead(at: NIODeadline, ctx: ChannelHandlerContext) { - self.scheduledRead = ctx.eventLoop.scheduleTask(deadline: at) { - self.doRead(ctx) + private func scheduleRead(at: NIODeadline, context: ChannelHandlerContext) { + self.scheduledRead = context.eventLoop.scheduleTask(deadline: at) { + self.doRead(context) } } - private func doRead(_ ctx: ChannelHandlerContext) { + private func doRead(_ context: ChannelHandlerContext) { /// Reset the backoff time and read. self.nextReadDeadlineNS = nil self.scheduledRead = nil - ctx.read() + context.read() } } @@ -118,34 +118,34 @@ public class BackPressureHandler: ChannelDuplexHandler, RemovableChannelHandler public init() { } - public func read(ctx: ChannelHandlerContext) { + public func read(context: ChannelHandlerContext) { if writable { - ctx.read() + context.read() } else { pendingRead = true } } - public func channelWritabilityChanged(ctx: ChannelHandlerContext) { - self.writable = ctx.channel.isWritable + public func channelWritabilityChanged(context: ChannelHandlerContext) { + self.writable = context.channel.isWritable if writable { - mayRead(ctx: ctx) + mayRead(context: context) } else { - ctx.flush() + context.flush() } // Propagate the event as the user may still want to do something based on it. - ctx.fireChannelWritabilityChanged() + context.fireChannelWritabilityChanged() } - public func handlerRemoved(ctx: ChannelHandlerContext) { - mayRead(ctx: ctx) + public func handlerRemoved(context: ChannelHandlerContext) { + mayRead(context: context) } - private func mayRead(ctx: ChannelHandlerContext) { + private func mayRead(context: ChannelHandlerContext) { if pendingRead { pendingRead = false - ctx.read() + context.read() } } } @@ -184,83 +184,83 @@ public class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandler { self.allTimeout = allTimeout } - public func handlerAdded(ctx: ChannelHandlerContext) { - if ctx.channel.isActive { - initIdleTasks(ctx) + public func handlerAdded(context: ChannelHandlerContext) { + if context.channel.isActive { + initIdleTasks(context) } } - public func handlerRemoved(ctx: ChannelHandlerContext) { - cancelIdleTasks(ctx) + public func handlerRemoved(context: ChannelHandlerContext) { + cancelIdleTasks(context) } - public func channelActive(ctx: ChannelHandlerContext) { - initIdleTasks(ctx) - ctx.fireChannelActive() + public func channelActive(context: ChannelHandlerContext) { + initIdleTasks(context) + context.fireChannelActive() } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { if readTimeout != nil || allTimeout != nil { reading = true } - ctx.fireChannelRead(data) + context.fireChannelRead(data) } - public func channelReadComplete(ctx: ChannelHandlerContext) { + public func channelReadComplete(context: ChannelHandlerContext) { if (readTimeout != nil || allTimeout != nil) && reading { lastReadTime = .now() reading = false } - ctx.fireChannelReadComplete() + context.fireChannelReadComplete() } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { if writeTimeout == nil && allTimeout == nil { - ctx.write(data, promise: promise) + context.write(data, promise: promise) return } - let writePromise = promise ?? ctx.eventLoop.makePromise() + let writePromise = promise ?? context.eventLoop.makePromise() writePromise.futureResult.whenComplete { (_: Result) in self.lastWriteCompleteTime = .now() } - ctx.write(data, promise: writePromise) + context.write(data, promise: writePromise) } - private func shouldReschedule(_ ctx: ChannelHandlerContext) -> Bool { - if ctx.channel.isActive { + private func shouldReschedule(_ context: ChannelHandlerContext) -> Bool { + if context.channel.isActive { return true } return false } - private func makeReadTimeoutTask(_ ctx: ChannelHandlerContext, _ timeout: TimeAmount) -> (() -> Void) { + private func makeReadTimeoutTask(_ context: ChannelHandlerContext, _ timeout: TimeAmount) -> (() -> Void) { return { - guard self.shouldReschedule(ctx) else { + guard self.shouldReschedule(context) else { return } if self.reading { - self.scheduledReaderTask = ctx.eventLoop.scheduleTask(in: timeout, self.makeReadTimeoutTask(ctx, timeout)) + self.scheduledReaderTask = context.eventLoop.scheduleTask(in: timeout, self.makeReadTimeoutTask(context, timeout)) return } let diff = .now() - self.lastReadTime if diff >= timeout { // Reader is idle - set a new timeout and trigger an event through the pipeline - self.scheduledReaderTask = ctx.eventLoop.scheduleTask(in: timeout, self.makeReadTimeoutTask(ctx, timeout)) + self.scheduledReaderTask = context.eventLoop.scheduleTask(in: timeout, self.makeReadTimeoutTask(context, timeout)) - ctx.fireUserInboundEventTriggered(IdleStateEvent.read) + context.fireUserInboundEventTriggered(IdleStateEvent.read) } else { // Read occurred before the timeout - set a new timeout with shorter delay. - self.scheduledReaderTask = ctx.eventLoop.scheduleTask(deadline: self.lastReadTime + timeout, self.makeReadTimeoutTask(ctx, timeout)) + self.scheduledReaderTask = context.eventLoop.scheduleTask(deadline: self.lastReadTime + timeout, self.makeReadTimeoutTask(context, timeout)) } } } - private func makeWriteTimeoutTask(_ ctx: ChannelHandlerContext, _ timeout: TimeAmount) -> (() -> Void) { + private func makeWriteTimeoutTask(_ context: ChannelHandlerContext, _ timeout: TimeAmount) -> (() -> Void) { return { - guard self.shouldReschedule(ctx) else { + guard self.shouldReschedule(context) else { return } @@ -269,24 +269,24 @@ public class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandler { if diff >= timeout { // Writer is idle - set a new timeout and notify the callback. - self.scheduledWriterTask = ctx.eventLoop.scheduleTask(in: timeout, self.makeWriteTimeoutTask(ctx, timeout)) + self.scheduledWriterTask = context.eventLoop.scheduleTask(in: timeout, self.makeWriteTimeoutTask(context, timeout)) - ctx.fireUserInboundEventTriggered(IdleStateEvent.write) + context.fireUserInboundEventTriggered(IdleStateEvent.write) } else { // Write occurred before the timeout - set a new timeout with shorter delay. - self.scheduledWriterTask = ctx.eventLoop.scheduleTask(deadline: self.lastWriteCompleteTime + timeout, self.makeWriteTimeoutTask(ctx, timeout)) + self.scheduledWriterTask = context.eventLoop.scheduleTask(deadline: self.lastWriteCompleteTime + timeout, self.makeWriteTimeoutTask(context, timeout)) } } } - private func makeAllTimeoutTask(_ ctx: ChannelHandlerContext, _ timeout: TimeAmount) -> (() -> Void) { + private func makeAllTimeoutTask(_ context: ChannelHandlerContext, _ timeout: TimeAmount) -> (() -> Void) { return { - guard self.shouldReschedule(ctx) else { + guard self.shouldReschedule(context) else { return } if self.reading { - self.scheduledReaderTask = ctx.eventLoop.scheduleTask(in: timeout, self.makeAllTimeoutTask(ctx, timeout)) + self.scheduledReaderTask = context.eventLoop.scheduleTask(in: timeout, self.makeAllTimeoutTask(context, timeout)) return } let lastRead = self.lastReadTime @@ -296,33 +296,33 @@ public class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandler { let diff = .now() - latestLast if diff >= timeout { // Reader is idle - set a new timeout and trigger an event through the pipeline - self.scheduledReaderTask = ctx.eventLoop.scheduleTask(in: timeout, self.makeAllTimeoutTask(ctx, timeout)) + self.scheduledReaderTask = context.eventLoop.scheduleTask(in: timeout, self.makeAllTimeoutTask(context, timeout)) - ctx.fireUserInboundEventTriggered(IdleStateEvent.all) + context.fireUserInboundEventTriggered(IdleStateEvent.all) } else { // Read occurred before the timeout - set a new timeout with shorter delay. - self.scheduledReaderTask = ctx.eventLoop.scheduleTask(deadline: latestLast + timeout, self.makeAllTimeoutTask(ctx, timeout)) + self.scheduledReaderTask = context.eventLoop.scheduleTask(deadline: latestLast + timeout, self.makeAllTimeoutTask(context, timeout)) } } } - private func schedule(_ ctx: ChannelHandlerContext, _ amount: TimeAmount?, _ body: @escaping (ChannelHandlerContext, TimeAmount) -> (() -> Void) ) -> Scheduled? { + private func schedule(_ context: ChannelHandlerContext, _ amount: TimeAmount?, _ body: @escaping (ChannelHandlerContext, TimeAmount) -> (() -> Void) ) -> Scheduled? { if let timeout = amount { - return ctx.eventLoop.scheduleTask(in: timeout, body(ctx, timeout)) + return context.eventLoop.scheduleTask(in: timeout, body(context, timeout)) } return nil } - private func initIdleTasks(_ ctx: ChannelHandlerContext) { + private func initIdleTasks(_ context: ChannelHandlerContext) { let now = NIODeadline.now() lastReadTime = now lastWriteCompleteTime = now - scheduledReaderTask = schedule(ctx, readTimeout, makeReadTimeoutTask) - scheduledWriterTask = schedule(ctx, writeTimeout, makeWriteTimeoutTask) - scheduledAllTask = schedule(ctx, allTimeout, makeAllTimeoutTask) + scheduledReaderTask = schedule(context, readTimeout, makeReadTimeoutTask) + scheduledWriterTask = schedule(context, writeTimeout, makeWriteTimeoutTask) + scheduledAllTask = schedule(context, allTimeout, makeAllTimeoutTask) } - private func cancelIdleTasks(_ ctx: ChannelHandlerContext) { + private func cancelIdleTasks(_ context: ChannelHandlerContext) { scheduledReaderTask?.cancel() scheduledWriterTask?.cancel() scheduledAllTask?.cancel() diff --git a/Sources/NIO/ChannelPipeline.swift b/Sources/NIO/ChannelPipeline.swift index ddb35e577..631af4887 100644 --- a/Sources/NIO/ChannelPipeline.swift +++ b/Sources/NIO/ChannelPipeline.swift @@ -240,12 +240,12 @@ public final class ChannelPipeline: ChannelInvoker { return } - guard let ctx = self.contextForPredicate0({ $0.handler === relativeHandler }) else { + guard let context = self.contextForPredicate0({ $0.handler === relativeHandler }) else { promise.fail(ChannelPipelineError.notFound) return } - self.add0(name: name, handler: handler, relativeContext: ctx, operation: operation, promise: promise) + self.add0(name: name, handler: handler, relativeContext: context, operation: operation, promise: promise) } /// Synchronously add a `ChannelHandler` to the pipeline, relative to a `ChannelHandlerContext`, @@ -277,14 +277,14 @@ public final class ChannelPipeline: ChannelInvoker { return } - let ctx = ChannelHandlerContext(name: name ?? nextName(), handler: handler, pipeline: self) - operation(ctx, relativeContext) + let context = ChannelHandlerContext(name: name ?? nextName(), handler: handler, pipeline: self) + operation(context, relativeContext) do { - try ctx.invokeHandlerAdded() + try context.invokeHandlerAdded() promise.succeed(()) } catch let err { - removeHandlerFromPipeline(ctx: ctx, promise: nil) + removeHandlerFromPipeline(context: context, promise: nil) promise.fail(err) } } @@ -352,11 +352,11 @@ public final class ChannelPipeline: ChannelInvoker { /// Remove a `ChannelHandler` from the `ChannelPipeline`. /// /// - parameters: - /// - ctx: the `ChannelHandlerContext` that belongs to `ChannelHandler` that should be removed. + /// - context: the `ChannelHandlerContext` that belongs to `ChannelHandler` that should be removed. /// - returns: the `EventLoopFuture` which will be notified once the `ChannelHandler` was removed. - public func removeHandler(ctx: ChannelHandlerContext) -> EventLoopFuture { + public func removeHandler(context: ChannelHandlerContext) -> EventLoopFuture { let promise = self.eventLoop.makePromise(of: Void.self) - self.removeHandler(ctx: ctx, promise: promise) + self.removeHandler(context: context, promise: promise) return promise.futureResult } @@ -368,8 +368,8 @@ public final class ChannelPipeline: ChannelInvoker { public func removeHandler(_ handler: RemovableChannelHandler, promise: EventLoopPromise?) { let contextFuture = self.context0 { return $0.handler === handler - }.map { ctx in - self.removeHandler(ctx: ctx, promise: promise) + }.map { context in + self.removeHandler(context: context, promise: promise) } contextFuture.cascadeFailure(to: promise) @@ -383,8 +383,8 @@ public final class ChannelPipeline: ChannelInvoker { public func removeHandler(name: String, promise: EventLoopPromise?) { let contextFuture = self.context0 { $0.name == name - }.map { ctx in - self.removeHandler(ctx: ctx, promise: promise) + }.map { context in + self.removeHandler(context: context, promise: promise) } contextFuture.cascadeFailure(to: promise) @@ -393,18 +393,18 @@ public final class ChannelPipeline: ChannelInvoker { /// Remove a `ChannelHandler` from the `ChannelPipeline`. /// /// - parameters: - /// - ctx: the `ChannelHandlerContext` that belongs to `ChannelHandler` that should be removed. + /// - context: the `ChannelHandlerContext` that belongs to `ChannelHandler` that should be removed. /// - promise: An `EventLoopPromise` that will complete when the `ChannelHandler` is removed. - public func removeHandler(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { - guard let handler = ctx.handler as? RemovableChannelHandler else { + public func removeHandler(context: ChannelHandlerContext, promise: EventLoopPromise?) { + guard let handler = context.handler as? RemovableChannelHandler else { promise?.fail(ChannelError.unremovableHandler) return } if self.eventLoop.inEventLoop { - handler.removeHandler(ctx: ctx, removalToken: .init(promise: promise)) + handler.removeHandler(context: context, removalToken: .init(promise: promise)) } else { self.eventLoop.execute { - handler.removeHandler(ctx: ctx, removalToken: .init(promise: promise)) + handler.removeHandler(context: context, removalToken: .init(promise: promise)) } } } @@ -444,8 +444,8 @@ public final class ChannelPipeline: ChannelInvoker { let promise = eventLoop.makePromise(of: ChannelHandlerContext.self) func _context0() { - if let ctx = self.contextForPredicate0(body) { - promise.succeed(ctx) + if let context = self.contextForPredicate0(body) { + promise.succeed(context) } else { promise.fail(ChannelPipelineError.notFound) } @@ -470,11 +470,11 @@ public final class ChannelPipeline: ChannelInvoker { /// -returns: The first `ChannelHandlerContext` that matches or `nil` if none did. private func contextForPredicate0(_ body: @escaping((ChannelHandlerContext) -> Bool)) -> ChannelHandlerContext? { var curCtx: ChannelHandlerContext? = self.head?.next - while let ctx = curCtx, ctx !== self.tail { - if body(ctx) { - return ctx + while let context = curCtx, context !== self.tail { + if body(context) { + return context } - curCtx = ctx.next + curCtx = context.next } return nil @@ -483,11 +483,11 @@ public final class ChannelPipeline: ChannelInvoker { /// Remove a `ChannelHandlerContext` from the `ChannelPipeline` directly without going through the /// `RemovableChannelHandler` API. This must only be used to clear the pipeline on `Channel` tear down and /// as a result of the `leavePipeline` call in the `RemovableChannelHandler` API. - internal func removeHandlerFromPipeline(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { + internal func removeHandlerFromPipeline(context: ChannelHandlerContext, promise: EventLoopPromise?) { self.eventLoop.assertInEventLoop() - let nextCtx = ctx.next - let prevCtx = ctx.prev + let nextCtx = context.next + let prevCtx = context.prev if let prevCtx = prevCtx { prevCtx.next = nextCtx } @@ -496,15 +496,15 @@ public final class ChannelPipeline: ChannelInvoker { } do { - try ctx.invokeHandlerRemoved() + try context.invokeHandlerRemoved() promise?.succeed(()) } catch let err { promise?.fail(err) } // We need to keep the current node alive until after the callout in case the user uses the context. - ctx.next = nil - ctx.prev = nil + context.next = nil + context.prev = nil } /// Returns the next name to use for a `ChannelHandler`. @@ -524,10 +524,10 @@ public final class ChannelPipeline: ChannelInvoker { self.eventLoop.assertInEventLoop() if let head = self.head { - while let ctx = head.next { - removeHandlerFromPipeline(ctx: ctx, promise: nil) + while let context = head.next { + removeHandlerFromPipeline(context: context, promise: nil) } - removeHandlerFromPipeline(ctx: self.head!, promise: nil) + removeHandlerFromPipeline(context: self.head!, promise: nil) } self.head = nil self.tail = nil @@ -939,36 +939,36 @@ extension ChannelPipeline { private init() { } - func register(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { - ctx.channel._channelCore.register0(promise: promise) + func register(context: ChannelHandlerContext, promise: EventLoopPromise?) { + context.channel._channelCore.register0(promise: promise) } - func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { - ctx.channel._channelCore.bind0(to: address, promise: promise) + func bind(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + context.channel._channelCore.bind0(to: address, promise: promise) } - func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { - ctx.channel._channelCore.connect0(to: address, promise: promise) + func connect(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + context.channel._channelCore.connect0(to: address, promise: promise) } - func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - ctx.channel._channelCore.write0(data, promise: promise) + func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + context.channel._channelCore.write0(data, promise: promise) } - func flush(ctx: ChannelHandlerContext) { - ctx.channel._channelCore.flush0() + func flush(context: ChannelHandlerContext) { + context.channel._channelCore.flush0() } - func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { - ctx.channel._channelCore.close0(error: mode.error, mode: mode, promise: promise) + func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { + context.channel._channelCore.close0(error: mode.error, mode: mode, promise: promise) } - func read(ctx: ChannelHandlerContext) { - ctx.channel._channelCore.read0() + func read(context: ChannelHandlerContext) { + context.channel._channelCore.read0() } - func triggerUserOutboundEvent(ctx: ChannelHandlerContext, event: Any, promise: EventLoopPromise?) { - ctx.channel._channelCore.triggerUserOutboundEvent0(event, promise: promise) + func triggerUserOutboundEvent(context: ChannelHandlerContext, event: Any, promise: EventLoopPromise?) { + context.channel._channelCore.triggerUserOutboundEvent0(event, promise: promise) } } @@ -995,40 +995,40 @@ private extension CloseMode { private init() { } - func channelRegistered(ctx: ChannelHandlerContext) { + func channelRegistered(context: ChannelHandlerContext) { // Discard } - func channelUnregistered(ctx: ChannelHandlerContext) { + func channelUnregistered(context: ChannelHandlerContext) { // Discard } - func channelActive(ctx: ChannelHandlerContext) { + func channelActive(context: ChannelHandlerContext) { // Discard } - func channelInactive(ctx: ChannelHandlerContext) { + func channelInactive(context: ChannelHandlerContext) { // Discard } - func channelReadComplete(ctx: ChannelHandlerContext) { + func channelReadComplete(context: ChannelHandlerContext) { // Discard } - func channelWritabilityChanged(ctx: ChannelHandlerContext) { + func channelWritabilityChanged(context: ChannelHandlerContext) { // Discard } - func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { // Discard } - func errorCaught(ctx: ChannelHandlerContext, error: Error) { - ctx.channel._channelCore.errorCaught0(error: error) + func errorCaught(context: ChannelHandlerContext, error: Error) { + context.channel._channelCore.errorCaught0(error: error) } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { - ctx.channel._channelCore.channelRead0(data) + func channelRead(context: ChannelHandlerContext, data: NIOAny) { + context.channel._channelCore.channelRead0(data) } } @@ -1285,7 +1285,7 @@ public final class ChannelHandlerContext: ChannelInvoker { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { - inboundHandler.channelRegistered(ctx: self) + inboundHandler.channelRegistered(context: self) } else { self.next?.invokeChannelRegistered() } @@ -1295,7 +1295,7 @@ public final class ChannelHandlerContext: ChannelInvoker { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { - inboundHandler.channelUnregistered(ctx: self) + inboundHandler.channelUnregistered(context: self) } else { self.next?.invokeChannelUnregistered() } @@ -1305,7 +1305,7 @@ public final class ChannelHandlerContext: ChannelInvoker { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { - inboundHandler.channelActive(ctx: self) + inboundHandler.channelActive(context: self) } else { self.next?.invokeChannelActive() } @@ -1315,7 +1315,7 @@ public final class ChannelHandlerContext: ChannelInvoker { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { - inboundHandler.channelInactive(ctx: self) + inboundHandler.channelInactive(context: self) } else { self.next?.invokeChannelInactive() } @@ -1325,7 +1325,7 @@ public final class ChannelHandlerContext: ChannelInvoker { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { - inboundHandler.channelRead(ctx: self, data: data) + inboundHandler.channelRead(context: self, data: data) } else { self.next?.invokeChannelRead(data) } @@ -1335,7 +1335,7 @@ public final class ChannelHandlerContext: ChannelInvoker { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { - inboundHandler.channelReadComplete(ctx: self) + inboundHandler.channelReadComplete(context: self) } else { self.next?.invokeChannelReadComplete() } @@ -1345,7 +1345,7 @@ public final class ChannelHandlerContext: ChannelInvoker { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { - inboundHandler.channelWritabilityChanged(ctx: self) + inboundHandler.channelWritabilityChanged(context: self) } else { self.next?.invokeChannelWritabilityChanged() } @@ -1355,7 +1355,7 @@ public final class ChannelHandlerContext: ChannelInvoker { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { - inboundHandler.errorCaught(ctx: self, error: error) + inboundHandler.errorCaught(context: self, error: error) } else { self.next?.invokeErrorCaught(error) } @@ -1365,7 +1365,7 @@ public final class ChannelHandlerContext: ChannelInvoker { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { - inboundHandler.userInboundEventTriggered(ctx: self, event: event) + inboundHandler.userInboundEventTriggered(context: self, event: event) } else { self.next?.invokeUserInboundEventTriggered(event) } @@ -1376,7 +1376,7 @@ public final class ChannelHandlerContext: ChannelInvoker { assert(promise.map { !$0.futureResult.isFulfilled } ?? true, "Promise \(promise!) already fulfilled") if let outboundHandler = self.outboundHandler { - outboundHandler.register(ctx: self, promise: promise) + outboundHandler.register(context: self, promise: promise) } else { self.prev?.invokeRegister(promise: promise) } @@ -1387,7 +1387,7 @@ public final class ChannelHandlerContext: ChannelInvoker { assert(promise.map { !$0.futureResult.isFulfilled } ?? true, "Promise \(promise!) already fulfilled") if let outboundHandler = self.outboundHandler { - outboundHandler.bind(ctx: self, to: address, promise: promise) + outboundHandler.bind(context: self, to: address, promise: promise) } else { self.prev?.invokeBind(to: address, promise: promise) } @@ -1398,7 +1398,7 @@ public final class ChannelHandlerContext: ChannelInvoker { assert(promise.map { !$0.futureResult.isFulfilled } ?? true, "Promise \(promise!) already fulfilled") if let outboundHandler = self.outboundHandler { - outboundHandler.connect(ctx: self, to: address, promise: promise) + outboundHandler.connect(context: self, to: address, promise: promise) } else { self.prev?.invokeConnect(to: address, promise: promise) } @@ -1409,7 +1409,7 @@ public final class ChannelHandlerContext: ChannelInvoker { assert(promise.map { !$0.futureResult.isFulfilled } ?? true, "Promise \(promise!) already fulfilled") if let outboundHandler = self.outboundHandler { - outboundHandler.write(ctx: self, data: data, promise: promise) + outboundHandler.write(context: self, data: data, promise: promise) } else { self.prev?.invokeWrite(data, promise: promise) } @@ -1419,7 +1419,7 @@ public final class ChannelHandlerContext: ChannelInvoker { self.eventLoop.assertInEventLoop() if let outboundHandler = self.outboundHandler { - outboundHandler.flush(ctx: self) + outboundHandler.flush(context: self) } else { self.prev?.invokeFlush() } @@ -1430,8 +1430,8 @@ public final class ChannelHandlerContext: ChannelInvoker { assert(promise.map { !$0.futureResult.isFulfilled } ?? true, "Promise \(promise!) already fulfilled") if let outboundHandler = self.outboundHandler { - outboundHandler.write(ctx: self, data: data, promise: promise) - outboundHandler.flush(ctx: self) + outboundHandler.write(context: self, data: data, promise: promise) + outboundHandler.flush(context: self) } else { self.prev?.invokeWriteAndFlush(data, promise: promise) } @@ -1441,7 +1441,7 @@ public final class ChannelHandlerContext: ChannelInvoker { self.eventLoop.assertInEventLoop() if let outboundHandler = self.outboundHandler { - outboundHandler.read(ctx: self) + outboundHandler.read(context: self) } else { self.prev?.invokeRead() } @@ -1452,7 +1452,7 @@ public final class ChannelHandlerContext: ChannelInvoker { assert(promise.map { !$0.futureResult.isFulfilled } ?? true, "Promise \(promise!) already fulfilled") if let outboundHandler = self.outboundHandler { - outboundHandler.close(ctx: self, mode: mode, promise: promise) + outboundHandler.close(context: self, mode: mode, promise: promise) } else { self.prev?.invokeClose(mode: mode, promise: promise) } @@ -1463,7 +1463,7 @@ public final class ChannelHandlerContext: ChannelInvoker { assert(promise.map { !$0.futureResult.isFulfilled } ?? true, "Promise \(promise!) already fulfilled") if let outboundHandler = self.outboundHandler { - outboundHandler.triggerUserOutboundEvent(ctx: self, event: event, promise: promise) + outboundHandler.triggerUserOutboundEvent(context: self, event: event, promise: promise) } else { self.prev?.invokeTriggerUserOutboundEvent(event, promise: promise) } @@ -1472,13 +1472,13 @@ public final class ChannelHandlerContext: ChannelInvoker { fileprivate func invokeHandlerAdded() throws { self.eventLoop.assertInEventLoop() - handler.handlerAdded(ctx: self) + handler.handlerAdded(context: self) } fileprivate func invokeHandlerRemoved() throws { self.eventLoop.assertInEventLoop() - handler.handlerRemoved(ctx: self) + handler.handlerRemoved(context: self) } } @@ -1499,7 +1499,7 @@ extension ChannelHandlerContext { /// - removalToken: The removal token received from `RemovableChannelHandler.removeHandler` public func leavePipeline(removalToken: RemovalToken) { self.eventLoop.preconditionInEventLoop() - self.pipeline.removeHandlerFromPipeline(ctx: self, promise: removalToken.promise) + self.pipeline.removeHandlerFromPipeline(context: self, promise: removalToken.promise) } } @@ -1507,11 +1507,11 @@ extension ChannelPipeline: CustomDebugStringConvertible { public var debugDescription: String { var desc = "ChannelPipeline (\(ObjectIdentifier(self))):\n" var node = self.head?.next - while let ctx = node, ctx !== self.tail { - let inboundStr = ctx.handler is _ChannelInboundHandler ? "I" : "" - let outboundStr = ctx.handler is _ChannelOutboundHandler ? "O" : "" - desc += " \(ctx.name) (\(type(of: ctx.handler))) [\(inboundStr)\(outboundStr)]\n" - node = ctx.next + while let context = node, context !== self.tail { + let inboundStr = context.handler is _ChannelInboundHandler ? "I" : "" + let outboundStr = context.handler is _ChannelOutboundHandler ? "O" : "" + desc += " \(context.name) (\(type(of: context.handler))) [\(inboundStr)\(outboundStr)]\n" + node = context.next } return desc } diff --git a/Sources/NIO/Codec.swift b/Sources/NIO/Codec.swift index d009bdce0..78051eca7 100644 --- a/Sources/NIO/Codec.swift +++ b/Sources/NIO/Codec.swift @@ -65,33 +65,33 @@ public protocol ByteToMessageDecoder { /// `ByteBuffer` has nothing to read left or `DecodingState.needMoreData` is returned. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. + /// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. /// - buffer: The `ByteBuffer` from which we decode. /// - returns: `DecodingState.continue` if we should continue calling this method or `DecodingState.needMoreData` if it should be called // again once more data is present in the `ByteBuffer`. - mutating func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState + mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState /// This method is called once, when the `ChannelHandlerContext` goes inactive (i.e. when `channelInactive` is fired) /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. + /// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. /// - buffer: The `ByteBuffer` from which we decode. /// - seenEOF: `true` if EOF has been seen. Usually if this is `false` the handler has been removed. /// - returns: `DecodingState.continue` if we should continue calling this method or `DecodingState.needMoreData` if it should be called // again when more data is present in the `ByteBuffer`. - mutating func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState + mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState /// Called once this `ByteToMessageDecoder` is removed from the `ChannelPipeline`. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. - mutating func decoderRemoved(ctx: ChannelHandlerContext) + /// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. + mutating func decoderRemoved(context: ChannelHandlerContext) /// Called when this `ByteToMessageDecoder` is added to the `ChannelPipeline`. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. - mutating func decoderAdded(ctx: ChannelHandlerContext) + /// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. + mutating func decoderAdded(context: ChannelHandlerContext) /// Determine if the read bytes in the given `ByteBuffer` should be reclaimed and their associated memory freed. /// Be aware that reclaiming memory may involve memory copies and so is not free. @@ -119,10 +119,10 @@ public protocol WriteObservingByteToMessageDecoder: ByteToMessageDecoder { } extension ByteToMessageDecoder { - public mutating func decoderRemoved(ctx: ChannelHandlerContext) { + public mutating func decoderRemoved(context: ChannelHandlerContext) { } - public mutating func decoderAdded(ctx: ChannelHandlerContext) { + public mutating func decoderAdded(context: ChannelHandlerContext) { } /// Default implementation to detect once bytes should be reclaimed. @@ -394,14 +394,14 @@ extension ByteToMessageHandler { } } - private func processLeftovers(ctx: ChannelHandlerContext) { + private func processLeftovers(context: ChannelHandlerContext) { guard self.state.isActive else { // we are processing or have already processed the leftovers return } do { - switch try self.decodeLoop(ctx: ctx, decodeMode: .last) { + switch try self.decodeLoop(context: context, decodeMode: .last) { case .didProcess: self.state = .done case .cannotProcessReentrantly: @@ -409,7 +409,7 @@ extension ByteToMessageHandler { } } catch { self.state = .error(error) - ctx.fireErrorCaught(error) + context.fireErrorCaught(error) } } @@ -420,16 +420,16 @@ extension ByteToMessageHandler { } } - private func decodeLoop(ctx: ChannelHandlerContext, decodeMode: DecodeMode) throws -> B2MDBuffer.BufferProcessingResult { + private func decodeLoop(context: ChannelHandlerContext, decodeMode: DecodeMode) throws -> B2MDBuffer.BufferProcessingResult { assert(!self.state.isError) var allowEmptyBuffer = decodeMode == .last while decodeMode == .last || self.removalState == .notBeingRemoved { let result = try self.withNextBuffer(allowEmptyBuffer: allowEmptyBuffer) { decoder, buffer in if decodeMode == .normal { - return try decoder.decode(ctx: ctx, buffer: &buffer) + return try decoder.decode(context: context, buffer: &buffer) } else { allowEmptyBuffer = false - return try decoder.decodeLast(ctx: ctx, buffer: &buffer, seenEOF: self.seenEOF) + return try decoder.decodeLast(context: context, buffer: &buffer, seenEOF: self.seenEOF) } } switch result { @@ -454,14 +454,14 @@ extension ByteToMessageHandler { // MARK: ByteToMessageHandler: ChannelInboundHandler extension ByteToMessageHandler: ChannelInboundHandler { - public func handlerAdded(ctx: ChannelHandlerContext) { - self.buffer = B2MDBuffer(emptyByteBuffer: ctx.channel.allocator.buffer(capacity: 0)) + public func handlerAdded(context: ChannelHandlerContext) { + self.buffer = B2MDBuffer(emptyByteBuffer: context.channel.allocator.buffer(capacity: 0)) // here we can force it because we know that the decoder isn't in use if we're just adding this handler - self.decoder!.decoderAdded(ctx: ctx) + self.decoder!.decoderAdded(context: context) } - public func handlerRemoved(ctx: ChannelHandlerContext) { + public func handlerRemoved(context: ChannelHandlerContext) { // very likely, the removal state is `.notBeingRemoved` or `.removalCompleted` here but we can't assert it // because the pipeline might be torn down during the formal removal process. self.removalState = .removalCompleted @@ -471,15 +471,15 @@ extension ByteToMessageHandler: ChannelInboundHandler { } /// Calls `decode` until there is nothing left to decode. - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let buffer = self.unwrapInboundIn(data) if case .error(let error) = self.state { - ctx.fireErrorCaught(ByteToMessageDecoderError.dataReceivedInErrorState(error, buffer)) + context.fireErrorCaught(ByteToMessageDecoderError.dataReceivedInErrorState(error, buffer)) return } self.buffer.append(buffer: buffer) do { - switch try self.decodeLoop(ctx: ctx, decodeMode: .normal) { + switch try self.decodeLoop(context: context, decodeMode: .normal) { case .didProcess: switch self.state { case .active: @@ -491,7 +491,7 @@ extension ByteToMessageHandler: ChannelInboundHandler { defer { self.state = .done } - switch try self.decodeLoop(ctx: ctx, decodeMode: .last) { + switch try self.decodeLoop(context: context, decodeMode: .last) { case .didProcess: () // expected and cool case .cannotProcessReentrantly: @@ -504,32 +504,32 @@ extension ByteToMessageHandler: ChannelInboundHandler { } } catch { self.state = .error(error) - ctx.fireErrorCaught(error) + context.fireErrorCaught(error) } } /// Call `decodeLast` before forward the event through the pipeline. - public func channelInactive(ctx: ChannelHandlerContext) { + public func channelInactive(context: ChannelHandlerContext) { self.seenEOF = true - self.processLeftovers(ctx: ctx) + self.processLeftovers(context: context) - ctx.fireChannelInactive() + context.fireChannelInactive() } - public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { if event as? ChannelEvent == .some(.inputClosed) { self.seenEOF = true - self.processLeftovers(ctx: ctx) + self.processLeftovers(context: context) } - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) } } extension ByteToMessageHandler: ChannelOutboundHandler, _ChannelOutboundHandler where Decoder: WriteObservingByteToMessageDecoder { public typealias OutboundIn = Decoder.OutboundIn - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { if self.decoder != nil { let data = self.unwrapOutboundIn(data) assert(self.queuedWrites.count == 0) @@ -537,7 +537,7 @@ extension ByteToMessageHandler: ChannelOutboundHandler, _ChannelOutboundHandler } else { self.queuedWrites.append(data) } - ctx.write(data, promise: promise) + context.write(data, promise: promise) } } @@ -547,49 +547,49 @@ public protocol MessageToByteEncoder: ChannelOutboundHandler where OutboundOut = /// Called once there is data to encode. The used `ByteBuffer` is allocated by `allocateOutBuffer`. /// /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. + /// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. /// - data: The data to encode into a `ByteBuffer`. /// - out: The `ByteBuffer` into which we want to encode. - func encode(ctx: ChannelHandlerContext, data: OutboundIn, out: inout ByteBuffer) throws + func encode(context: ChannelHandlerContext, data: OutboundIn, out: inout ByteBuffer) throws /// Returns a `ByteBuffer` to be used by `encode`. /// - parameters: - /// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. + /// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. /// - data: The data to encode into a `ByteBuffer` by `encode`. /// - return: A `ByteBuffer` to use. - func allocateOutBuffer(ctx: ChannelHandlerContext, data: OutboundIn) throws -> ByteBuffer + func allocateOutBuffer(context: ChannelHandlerContext, data: OutboundIn) throws -> ByteBuffer } extension MessageToByteEncoder { /// Encodes the data into a `ByteBuffer` and writes it. - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { do { let data = self.unwrapOutboundIn(data) - var buffer: ByteBuffer = try allocateOutBuffer(ctx: ctx, data: data) - try encode(ctx: ctx, data: data, out: &buffer) - ctx.write(self.wrapOutboundOut(buffer), promise: promise) + var buffer: ByteBuffer = try allocateOutBuffer(context: context, data: data) + try encode(context: context, data: data, out: &buffer) + context.write(self.wrapOutboundOut(buffer), promise: promise) } catch let err { promise?.fail(err) } } /// Default implementation which just allocates a `ByteBuffer` with capacity of `256`. - public func allocateOutBuffer(ctx: ChannelHandlerContext, data: OutboundIn) throws -> ByteBuffer { - return ctx.channel.allocator.buffer(capacity: 256) + public func allocateOutBuffer(context: ChannelHandlerContext, data: OutboundIn) throws -> ByteBuffer { + return context.channel.allocator.buffer(capacity: 256) } } extension ByteToMessageHandler: RemovableChannelHandler { - public func removeHandler(ctx: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { + public func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { precondition(self.removalState == .notBeingRemoved) self.removalState = .removalStarted - ctx.eventLoop.execute { - self.processLeftovers(ctx: ctx) + context.eventLoop.execute { + self.processLeftovers(context: context) assert(!self.state.isLeftoversNeedProcessing, "illegal state: \(self.state)") assert(self.removalState == .removalStarted, "illegal removal state: \(self.removalState)") self.removalState = .removalCompleted - ctx.leavePipeline(removalToken: removalToken) + context.leavePipeline(removalToken: removalToken) } } } diff --git a/Sources/NIO/Embedded.swift b/Sources/NIO/Embedded.swift index 32b8a21fc..163f4c17b 100644 --- a/Sources/NIO/Embedded.swift +++ b/Sources/NIO/Embedded.swift @@ -279,7 +279,7 @@ class EmbeddedChannelCore: ChannelCore { /// to collect outbound data that is not `IOData` you can create a custom /// `ChannelOutboundHandler`, insert it at the very beginning of the /// `ChannelPipeline` and collect the outbound data there. Just don't forward -/// it using `ctx.write`. +/// it using `context.write`. /// - note: `EmbeddedChannel` is currently only compatible with /// `EmbeddedEventLoop`s and cannot be used with `SelectableEventLoop`s from /// for example `MultiThreadedEventLoopGroup`. diff --git a/Sources/NIO/NIOAny.swift b/Sources/NIO/NIOAny.swift index 779609281..9c62e2326 100644 --- a/Sources/NIO/NIOAny.swift +++ b/Sources/NIO/NIOAny.swift @@ -31,7 +31,7 @@ /// typealias InboundIn = Bacon /* we expected to be delivered `Bacon` ... */ /// typealias InboundOut = Sandwich /* ... and we will make and deliver a `Sandwich` from that */ /// -/// func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { +/// func channelRead(context: ChannelHandlerContext, data: NIOAny) { /// /* we receive the `Bacon` as a `NIOAny` as at compile-time the exact configuration of the channel /// pipeline can't be computed. The pipeline can't be computed at compile time as it can change /// dynamically at run-time. Yet, we assert that in any configuration the channel handler before @@ -39,7 +39,7 @@ /// */ /// let bacon = self.unwrapInboundIn(data) /* `Bacon` or crash */ /// let sandwich = makeSandwich(bacon) -/// ctx.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 { diff --git a/Sources/NIOChatClient/main.swift b/Sources/NIOChatClient/main.swift index f4490cb0b..b03af9ea3 100644 --- a/Sources/NIOChatClient/main.swift +++ b/Sources/NIOChatClient/main.swift @@ -25,19 +25,19 @@ private final class ChatHandler: ChannelInboundHandler { #endif } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { var buffer = self.unwrapInboundIn(data) while let byte: UInt8 = buffer.readInteger() { printByte(byte) } } - public func errorCaught(ctx: ChannelHandlerContext, error: Error) { + public func errorCaught(context: ChannelHandlerContext, error: Error) { print("error: ", error) // As we are not really interested getting notified on success or failure we just pass nil as promise to // reduce allocations. - ctx.close(promise: nil) + context.close(promise: nil) } } diff --git a/Sources/NIOChatServer/main.swift b/Sources/NIOChatServer/main.swift index 9dc5f2bb5..98982e03e 100644 --- a/Sources/NIOChatServer/main.swift +++ b/Sources/NIOChatServer/main.swift @@ -23,17 +23,17 @@ final class LineDelimiterCodec: ByteToMessageDecoder { public var cumulationBuffer: ByteBuffer? - public func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { let readable = buffer.withUnsafeReadableBytes { $0.firstIndex(of: newLine) } if let r = readable { - ctx.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: r + 1)!)) + context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: r + 1)!)) return .continue } return .needMoreData } - public func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { - return try self.decode(ctx: ctx, buffer: &buffer) + public func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + return try self.decode(context: context, buffer: &buffer) } } @@ -55,13 +55,13 @@ final class ChatHandler: ChannelInboundHandler { private let channelsSyncQueue = DispatchQueue(label: "channelsQueue") private var channels: [ObjectIdentifier: Channel] = [:] - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { - let id = ObjectIdentifier(ctx.channel) + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { + let id = ObjectIdentifier(context.channel) var read = self.unwrapInboundIn(data) // 64 should be good enough for the ipaddress - var buffer = ctx.channel.allocator.buffer(capacity: read.readableBytes + 64) - buffer.writeString("(\(ctx.remoteAddress!)) - ") + var buffer = context.channel.allocator.buffer(capacity: read.readableBytes + 64) + buffer.writeString("(\(context.remoteAddress!)) - ") buffer.writeBuffer(&read) self.channelsSyncQueue.async { // broadcast the message to all the connected clients except the one that wrote it. @@ -69,17 +69,17 @@ final class ChatHandler: ChannelInboundHandler { } } - public func errorCaught(ctx: ChannelHandlerContext, error: Error) { + public func errorCaught(context: ChannelHandlerContext, error: Error) { print("error: ", error) // As we are not really interested getting notified on success or failure we just pass nil as promise to // reduce allocations. - ctx.close(promise: nil) + context.close(promise: nil) } - public func channelActive(ctx: ChannelHandlerContext) { - let remoteAddress = ctx.remoteAddress! - let channel = ctx.channel + public func channelActive(context: ChannelHandlerContext) { + let remoteAddress = context.remoteAddress! + let channel = context.channel self.channelsSyncQueue.async { // broadcast the message to all the connected clients except the one that just became active. self.writeToAll(channels: self.channels, allocator: channel.allocator, message: "(ChatServer) - New client connected with address: \(remoteAddress)\n") @@ -88,12 +88,12 @@ final class ChatHandler: ChannelInboundHandler { } var buffer = channel.allocator.buffer(capacity: 64) - buffer.writeString("(ChatServer) - Welcome to: \(ctx.localAddress!)\n") - ctx.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + buffer.writeString("(ChatServer) - Welcome to: \(context.localAddress!)\n") + context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) } - public func channelInactive(ctx: ChannelHandlerContext) { - let channel = ctx.channel + public func channelInactive(context: ChannelHandlerContext) { + let channel = context.channel self.channelsSyncQueue.async { if self.channels.removeValue(forKey: ObjectIdentifier(channel)) != nil { // Broadcast the message to all the connected clients except the one that just was disconnected. diff --git a/Sources/NIOEchoClient/main.swift b/Sources/NIOEchoClient/main.swift index 7f0feed35..3c20f1590 100644 --- a/Sources/NIOEchoClient/main.swift +++ b/Sources/NIOEchoClient/main.swift @@ -21,7 +21,7 @@ private final class EchoHandler: ChannelInboundHandler { public typealias OutboundOut = ByteBuffer private var numBytes = 0 - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { var byteBuffer = self.unwrapInboundIn(data) numBytes -= byteBuffer.readableBytes @@ -33,26 +33,26 @@ private final class EchoHandler: ChannelInboundHandler { } else { print("Received the line back from the server, closing channel") } - ctx.close(promise: nil) + context.close(promise: nil) } } - public func errorCaught(ctx: ChannelHandlerContext, error: Error) { + public func errorCaught(context: ChannelHandlerContext, error: Error) { print("error: ", error) // As we are not really interested getting notified on success or failure we just pass nil as promise to // reduce allocations. - ctx.close(promise: nil) + context.close(promise: nil) } - public func channelActive(ctx: ChannelHandlerContext) { - print("Client connected to \(ctx.remoteAddress!)") + public func channelActive(context: ChannelHandlerContext) { + print("Client connected to \(context.remoteAddress!)") // We are connected. It's time to send the message to the server to initialize the ping-pong sequence. - var buffer = ctx.channel.allocator.buffer(capacity: line.utf8.count) + var buffer = context.channel.allocator.buffer(capacity: line.utf8.count) buffer.writeString(line) self.numBytes = buffer.readableBytes - ctx.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) } } diff --git a/Sources/NIOEchoServer/main.swift b/Sources/NIOEchoServer/main.swift index 885e4cbd5..8b6397996 100644 --- a/Sources/NIOEchoServer/main.swift +++ b/Sources/NIOEchoServer/main.swift @@ -17,23 +17,23 @@ private final class EchoHandler: ChannelInboundHandler { public typealias InboundIn = ByteBuffer public typealias OutboundOut = ByteBuffer - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { // As we are not really interested getting notified on success or failure we just pass nil as promise to // reduce allocations. - ctx.write(data, promise: nil) + context.write(data, promise: nil) } // Flush it out. This can make use of gathering writes if multiple buffers are pending - public func channelReadComplete(ctx: ChannelHandlerContext) { - ctx.flush() + public func channelReadComplete(context: ChannelHandlerContext) { + context.flush() } - public func errorCaught(ctx: ChannelHandlerContext, error: Error) { + public func errorCaught(context: ChannelHandlerContext, error: Error) { print("error: ", error) // As we are not really interested getting notified on success or failure we just pass nil as promise to // reduce allocations. - ctx.close(promise: nil) + context.close(promise: nil) } } let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) diff --git a/Sources/NIOHTTP1/HTTPDecoder.swift b/Sources/NIOHTTP1/HTTPDecoder.swift index e60a49dde..9e55a44fa 100644 --- a/Sources/NIOHTTP1/HTTPDecoder.swift +++ b/Sources/NIOHTTP1/HTTPDecoder.swift @@ -35,7 +35,7 @@ private struct HTTPParserState { var seenEOF = false var headerStartIndex: Int? - // Holds the data we need to forward via ctx.fireChannelRead(...) after invoking the parser. + // Holds the data we need to forward via context.fireChannelRead(...) after invoking the parser. var pendingInOut: NIOAny? = nil enum DataAwaitingState { @@ -186,12 +186,12 @@ public final class HTTPResponseDecoder: HTTPDecoder, Cha self.init(type: HTTPClientResponsePart.self, leftOverBytesStrategy: leftOverBytesStrategy) } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { if case .head(let head) = unwrapOutboundIn(data) { methods.append(head.method) } - ctx.write(data, promise: promise) + context.write(data, promise: promise) } } @@ -255,8 +255,8 @@ public class HTTPDecoder: ChannelInboundHandler, AnyHTTPDecoder { return response } - private func bytesToForwardOnRemoval(ctx: ChannelHandlerContext) -> ByteBuffer? { - guard self.leftOverBytesStrategy == .forwardBytes && self.parser.upgrade == 1 && ctx.channel.isActive else { + private func bytesToForwardOnRemoval(context: ChannelHandlerContext) -> ByteBuffer? { + guard self.leftOverBytesStrategy == .forwardBytes && self.parser.upgrade == 1 && context.channel.isActive else { return nil } // We take a slice of the cumulationBuffer so the next handler in the pipeline will just see the readable portion of the buffer. @@ -267,14 +267,14 @@ public class HTTPDecoder: ChannelInboundHandler, AnyHTTPDecoder { return nil } - public func handlerRemoved(ctx: ChannelHandlerContext) { - if let buffer = self.bytesToForwardOnRemoval(ctx: ctx) { - ctx.fireChannelRead(NIOAny(buffer)) + public func handlerRemoved(context: ChannelHandlerContext) { + if let buffer = self.bytesToForwardOnRemoval(context: context) { + context.fireChannelRead(NIOAny(buffer)) } self.cumulationBuffer = nil } - public func handlerAdded(ctx: ChannelHandlerContext) { + public func handlerAdded(context: ChannelHandlerContext) { if HTTPMessageT.self == HTTPServerRequestPart.self { c_nio_http_parser_init(&self.parser, HTTP_REQUEST) } else if HTTPMessageT.self == HTTPClientResponsePart.self { @@ -283,7 +283,7 @@ public class HTTPDecoder: ChannelInboundHandler, AnyHTTPDecoder { fatalError("the impossible happened: MsgT neither HTTPClientRequestPart nor HTTPClientResponsePart but \(HTTPMessageT.self)") } - self.parser.data = Unmanaged.passUnretained(ctx).toOpaque() + self.parser.data = Unmanaged.passUnretained(context).toOpaque() c_nio_http_parser_settings_init(&self.settings) @@ -295,8 +295,8 @@ public class HTTPDecoder: ChannelInboundHandler, AnyHTTPDecoder { } self.settings.on_headers_complete = { parser in - let ctx = evacuateChannelHandlerContext(parser) - let handler = ctx.handler as! AnyHTTPDecoder + let context = evacuateChannelHandlerContext(parser) + let handler = context.handler as! AnyHTTPDecoder // Ensure we pause the parser after this callback is complete so we can safely callout // to the pipeline. @@ -363,8 +363,8 @@ public class HTTPDecoder: ChannelInboundHandler, AnyHTTPDecoder { } self.settings.on_body = { parser, data, len in - let ctx = evacuateChannelHandlerContext(parser) - let handler = ctx.handler as! AnyHTTPDecoder + let context = evacuateChannelHandlerContext(parser) + let handler = context.handler as! AnyHTTPDecoder assert(handler.state.dataAwaitingState == .body) // Ensure we pause the parser after this callback is complete so we can safely callout @@ -435,8 +435,8 @@ public class HTTPDecoder: ChannelInboundHandler, AnyHTTPDecoder { } self.settings.on_message_complete = { parser in - let ctx = evacuateChannelHandlerContext(parser) - let handler = ctx.handler as! AnyHTTPDecoder + let context = evacuateChannelHandlerContext(parser) + let handler = context.handler as! AnyHTTPDecoder // Ensure we pause the parser after this callback is complete so we can safely callout // to the pipeline. @@ -474,7 +474,7 @@ public class HTTPDecoder: ChannelInboundHandler, AnyHTTPDecoder { } // Decode HTTP until there is nothing more to decode. - private func decodeHTTP(ctx: ChannelHandlerContext) throws { + private func decodeHTTP(context: ChannelHandlerContext) throws { // We need to refetch the cumulationBuffer on each loop as it may has changed due re-entrance calls of channelRead(...) while let bufferSlice = self.cumulationBuffer, bufferSlice.readableBytes > 0 { // we need to get `readerIndex` and `readableBytes` now because `withVeryUnsafeBytes` owns the @@ -501,19 +501,19 @@ public class HTTPDecoder: ChannelInboundHandler, AnyHTTPDecoder { // Update readerIndex of the cumulationBuffer itself as we will refetch it in the next loop run if needed. self.cumulationBuffer?.moveReaderIndex(forwardBy: result) - self.firePendingInOut(ctx: ctx) + self.firePendingInOut(context: context) } if self.state.seenEOF { // We need to notify the parser about the EOF as we received it while in http_parser_execute. - self.notifyParserEOF(ctx: ctx) + self.notifyParserEOF(context: context) } } - private func firePendingInOut(ctx: ChannelHandlerContext) { + private func firePendingInOut(context: ChannelHandlerContext) { if let pending = self.state.pendingInOut { self.state.pendingInOut = nil - ctx.fireChannelRead(pending) + context.fireChannelRead(pending) } } @@ -599,7 +599,7 @@ public class HTTPDecoder: ChannelInboundHandler, AnyHTTPDecoder { self.cumulationBuffer!.moveReaderIndex(to: self.cumulationBuffer!.writerIndex) } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { var buffer = self.unwrapInboundIn(data) // Either use the received buffer directly or merge it into the already existing cumulationBuffer. @@ -610,44 +610,44 @@ public class HTTPDecoder: ChannelInboundHandler, AnyHTTPDecoder { } do { - try self.decodeHTTP(ctx: ctx) + try self.decodeHTTP(context: context) self.discardDecodedBytes() } catch { self.cumulationBuffer = nil - ctx.fireErrorCaught(error) - ctx.close(promise: nil) + context.fireErrorCaught(error) + context.close(promise: nil) } } /// This method should not be called and will be removed in the future - public func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { return DecodingState.needMoreData } - public func channelReadComplete(ctx: ChannelHandlerContext) { - ctx.fireChannelReadComplete() + public func channelReadComplete(context: ChannelHandlerContext) { + context.fireChannelReadComplete() } - public func channelInactive(ctx: ChannelHandlerContext) { - self.readEOF(ctx: ctx) - ctx.fireChannelInactive() + public func channelInactive(context: ChannelHandlerContext) { + self.readEOF(context: context) + context.fireChannelInactive() } - public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { if case .some(.inputClosed) = event as? ChannelEvent { - self.readEOF(ctx: ctx) + self.readEOF(context: context) } - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) } - public func errorCaught(ctx: ChannelHandlerContext, error: Error) { - ctx.fireErrorCaught(error) + public func errorCaught(context: ChannelHandlerContext, error: Error) { + context.fireErrorCaught(error) if error is HTTPParserError { - ctx.close(promise: nil) + context.close(promise: nil) } } - private func readEOF(ctx: ChannelHandlerContext) { + private func readEOF(context: ChannelHandlerContext) { guard self.state.currentError == nil else { // We're in readEOF because we hit an error and closed the connection. // No need to do this dance again, just return. @@ -670,24 +670,24 @@ public class HTTPDecoder: ChannelInboundHandler, AnyHTTPDecoder { // let us enter this function again. self.state.seenEOF = true - self.notifyParserEOF(ctx: ctx) + self.notifyParserEOF(context: context) } - private func notifyParserEOF(ctx: ChannelHandlerContext) { + private func notifyParserEOF(context: ChannelHandlerContext) { self.state.baseAddress = nil _ = c_nio_http_parser_execute(&self.parser, &self.settings, nil, 0) // We don't need the cumulation buffer, if we're holding it. self.cumulationBuffer = nil - self.firePendingInOut(ctx: ctx) + self.firePendingInOut(context: context) // No check to state.currentError because, if we hit it before, we already threw that // error. This never calls any of the callbacks that set that field anyway. Instead we // just check if the errno is set and throw. if let parserError = self.currentParserError() { self.state.currentError = parserError - ctx.fireErrorCaught(parserError) + context.fireErrorCaught(parserError) } } diff --git a/Sources/NIOHTTP1/HTTPEncoder.swift b/Sources/NIOHTTP1/HTTPEncoder.swift index 90698a0ab..766c26b5a 100644 --- a/Sources/NIOHTTP1/HTTPEncoder.swift +++ b/Sources/NIOHTTP1/HTTPEncoder.swift @@ -14,13 +14,13 @@ import NIO -private func writeChunk(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHandlerContext, isChunked: Bool, chunk: IOData, promise: EventLoopPromise?) { +private func writeChunk(wrapOutboundOut: (IOData) -> NIOAny, context: ChannelHandlerContext, isChunked: Bool, chunk: IOData, promise: EventLoopPromise?) { let (mW1, mW2, mW3): (EventLoopPromise?, EventLoopPromise?, EventLoopPromise?) switch (isChunked, promise) { case (true, .some(let p)): /* chunked encoding and the user's interested: we need three promises and need to cascade into the users promise */ - let (w1, w2, w3) = (ctx.eventLoop.makePromise() as EventLoopPromise, ctx.eventLoop.makePromise() as EventLoopPromise, ctx.eventLoop.makePromise() as EventLoopPromise) + let (w1, w2, w3) = (context.eventLoop.makePromise() as EventLoopPromise, context.eventLoop.makePromise() as EventLoopPromise, context.eventLoop.makePromise() as EventLoopPromise) w1.futureResult.and(w2.futureResult).and(w3.futureResult).map { (_: ((((), ()), ()))) in }.cascade(to: p) (mW1, mW2, mW3) = (w1, w2, w3) case (false, .some(let p)): @@ -35,40 +35,40 @@ 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 = context.channel.allocator.buffer(capacity: 32) let len = String(readableBytes, radix: 16) buffer.writeString(len) buffer.writeStaticString("\r\n") - ctx.write(wrapOutboundOut(.byteBuffer(buffer)), promise: mW1) + context.write(wrapOutboundOut(.byteBuffer(buffer)), promise: mW1) - ctx.write(wrapOutboundOut(chunk), promise: mW2) + context.write(wrapOutboundOut(chunk), promise: mW2) // Just move the buffers readerIndex to only make the \r\n readable and depend on COW semantics. buffer.moveReaderIndex(forwardBy: buffer.readableBytes - 2) - ctx.write(wrapOutboundOut(.byteBuffer(buffer)), promise: mW3) + context.write(wrapOutboundOut(.byteBuffer(buffer)), promise: mW3) } else { - ctx.write(wrapOutboundOut(chunk), promise: mW2) + context.write(wrapOutboundOut(chunk), promise: mW2) } } -private func writeTrailers(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHandlerContext, isChunked: Bool, trailers: HTTPHeaders?, promise: EventLoopPromise?) { +private func writeTrailers(wrapOutboundOut: (IOData) -> NIOAny, context: ChannelHandlerContext, isChunked: Bool, trailers: HTTPHeaders?, promise: EventLoopPromise?) { switch (isChunked, promise) { case (true, let p): var buffer: ByteBuffer if let trailers = trailers { - buffer = ctx.channel.allocator.buffer(capacity: 256) + buffer = context.channel.allocator.buffer(capacity: 256) buffer.writeStaticString("0\r\n") buffer.write(headers: trailers) // Includes trailing CRLF. } else { - buffer = ctx.channel.allocator.buffer(capacity: 8) + buffer = context.channel.allocator.buffer(capacity: 8) buffer.writeStaticString("0\r\n\r\n") } - ctx.write(wrapOutboundOut(.byteBuffer(buffer)), promise: p) + context.write(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) - ctx.write(wrapOutboundOut(.byteBuffer(buf)), promise: p) + let buf = context.channel.allocator.buffer(capacity: 0) + context.write(wrapOutboundOut(.byteBuffer(buf)), promise: p) case (false, .none): break } @@ -77,12 +77,12 @@ private func writeTrailers(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHand // starting about swift-5.0-DEVELOPMENT-SNAPSHOT-2019-01-20-a, this doesn't get automatically inlined, which costs // 2 extra allocations so we need to help the optimiser out. @inline(__always) -private func writeHead(wrapOutboundOut: (IOData) -> NIOAny, writeStartLine: (inout ByteBuffer) -> Void, ctx: ChannelHandlerContext, headers: HTTPHeaders, promise: EventLoopPromise?) { +private func writeHead(wrapOutboundOut: (IOData) -> NIOAny, writeStartLine: (inout ByteBuffer) -> Void, context: ChannelHandlerContext, headers: HTTPHeaders, promise: EventLoopPromise?) { - var buffer = ctx.channel.allocator.buffer(capacity: 256) + var buffer = context.channel.allocator.buffer(capacity: 256) writeStartLine(&buffer) buffer.write(headers: headers) - ctx.write(wrapOutboundOut(.byteBuffer(buffer)), promise: promise) + context.write(wrapOutboundOut(.byteBuffer(buffer)), promise: promise) } /// The type of framing that is used to mark the end of the body. @@ -140,7 +140,7 @@ public final class HTTPRequestEncoder: ChannelOutboundHandler { public init () { } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { switch self.unwrapOutboundIn(data) { case .head(var request): @@ -148,11 +148,11 @@ public final class HTTPRequestEncoder: ChannelOutboundHandler { writeHead(wrapOutboundOut: self.wrapOutboundOut, writeStartLine: { buffer in buffer.write(request: request) - }, ctx: ctx, headers: request.headers, promise: promise) + }, context: context, headers: request.headers, promise: promise) case .body(let bodyPart): - writeChunk(wrapOutboundOut: self.wrapOutboundOut, ctx: ctx, 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, ctx: ctx, isChunked: self.isChunked, trailers: trailers, promise: promise) + writeTrailers(wrapOutboundOut: self.wrapOutboundOut, context: context, isChunked: self.isChunked, trailers: trailers, promise: promise) } } } @@ -169,7 +169,7 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel public init () { } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { switch self.unwrapOutboundIn(data) { case .head(var response): @@ -177,11 +177,11 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel writeHead(wrapOutboundOut: self.wrapOutboundOut, writeStartLine: { buffer in buffer.write(response: response) - }, ctx: ctx, headers: response.headers, promise: promise) + }, context: context, headers: response.headers, promise: promise) case .body(let bodyPart): - writeChunk(wrapOutboundOut: self.wrapOutboundOut, ctx: ctx, 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, ctx: ctx, 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/HTTPResponseCompressor.swift b/Sources/NIOHTTP1/HTTPResponseCompressor.swift index 44f75d132..061c62652 100644 --- a/Sources/NIOHTTP1/HTTPResponseCompressor.swift +++ b/Sources/NIOHTTP1/HTTPResponseCompressor.swift @@ -89,12 +89,12 @@ public final class HTTPResponseCompressor: ChannelDuplexHandler { self.initialByteBufferCapacity = initialByteBufferCapacity } - public func handlerAdded(ctx: ChannelHandlerContext) { - pendingResponse = PartialHTTPResponse(bodyBuffer: ctx.channel.allocator.buffer(capacity: initialByteBufferCapacity)) - pendingWritePromise = ctx.eventLoop.makePromise() + public func handlerAdded(context: ChannelHandlerContext) { + pendingResponse = PartialHTTPResponse(bodyBuffer: context.channel.allocator.buffer(capacity: initialByteBufferCapacity)) + pendingWritePromise = context.eventLoop.makePromise() } - public func handlerRemoved(ctx: ChannelHandlerContext) { + public func handlerRemoved(context: ChannelHandlerContext) { pendingWritePromise?.fail(CompressionError.uncompressedWritesPending) if algorithm != nil { deinitializeEncoder() @@ -102,21 +102,21 @@ public final class HTTPResponseCompressor: ChannelDuplexHandler { } } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { if case .head(let requestHead) = unwrapInboundIn(data) { acceptQueue.append(requestHead.headers[canonicalForm: "accept-encoding"]) } - ctx.fireChannelRead(data) + context.fireChannelRead(data) } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { let httpData = unwrapOutboundIn(data) switch httpData { case .head(var responseHead): algorithm = compressionAlgorithm() guard algorithm != nil else { - ctx.write(wrapOutboundOut(.head(responseHead)), promise: promise) + context.write(wrapOutboundOut(.head(responseHead)), promise: promise) return } // Previous handlers in the pipeline might have already set this header even though @@ -130,27 +130,27 @@ public final class HTTPResponseCompressor: ChannelDuplexHandler { pendingResponse.bufferBodyPart(body) pendingWritePromise.futureResult.cascade(to: promise) } else { - ctx.write(data, promise: promise) + context.write(data, promise: promise) } case .end: // This compress is not done in flush because we need to be done with the // compressor now. guard algorithm != nil else { - ctx.write(data, promise: promise) + context.write(data, promise: promise) return } pendingResponse.bufferResponseEnd(httpData) pendingWritePromise.futureResult.cascade(to: promise) - emitPendingWrites(ctx: ctx) + emitPendingWrites(context: context) algorithm = nil deinitializeEncoder() } } - public func flush(ctx: ChannelHandlerContext) { - emitPendingWrites(ctx: ctx) - ctx.flush() + public func flush(context: ChannelHandlerContext) { + emitPendingWrites(context: context) + context.flush() } /// Determines the compression algorithm to use for the next response. @@ -216,22 +216,22 @@ public final class HTTPResponseCompressor: ChannelDuplexHandler { /// data. Resets the pending write buffer and promise. /// /// 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) + private func emitPendingWrites(context: ChannelHandlerContext) { + let writesToEmit = pendingResponse.flush(compressor: &stream, allocator: context.channel.allocator) var pendingPromise = pendingWritePromise if let writeHead = writesToEmit.0 { - ctx.write(wrapOutboundOut(.head(writeHead)), promise: pendingPromise) + context.write(wrapOutboundOut(.head(writeHead)), promise: pendingPromise) pendingPromise = nil } if let writeBody = writesToEmit.1 { - ctx.write(wrapOutboundOut(.body(.byteBuffer(writeBody))), promise: pendingPromise) + context.write(wrapOutboundOut(.body(.byteBuffer(writeBody))), promise: pendingPromise) pendingPromise = nil } if let writeEnd = writesToEmit.2 { - ctx.write(wrapOutboundOut(writeEnd), promise: pendingPromise) + context.write(wrapOutboundOut(writeEnd), promise: pendingPromise) pendingPromise = nil } @@ -242,7 +242,7 @@ public final class HTTPResponseCompressor: ChannelDuplexHandler { } // Reset the pending promise. - pendingWritePromise = ctx.eventLoop.makePromise() + pendingWritePromise = context.eventLoop.makePromise() } } /// A buffer object that allows us to keep track of how much of a HTTP response we've seen before diff --git a/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift b/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift index 195a7d81a..afd778a2f 100644 --- a/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift +++ b/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift @@ -173,7 +173,7 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha // always `nil` in release builds, never `nil` in debug builds private var nextExpectedOutboundMessage: NextExpectedMessageType? - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { guard self.lifecycleState != .quiescingLastRequestEndReceived else { return } @@ -182,11 +182,11 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha self.eventBuffer.append(.channelRead(data)) return } else { - self.deliverOneMessage(ctx: ctx, data: data) + self.deliverOneMessage(context: context, data: data) } } - private func deliverOneMessage(ctx: ChannelHandlerContext, data: NIOAny) { + private func deliverOneMessage(context: ChannelHandlerContext, data: NIOAny) { assert(self.lifecycleState != .quiescingLastRequestEndReceived, "deliverOneMessage called in lifecycle illegal state \(self.lifecycleState)") let msg = self.unwrapInboundIn(data) @@ -216,16 +216,16 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha self.eventBuffer.removeAll() } if self.lifecycleState == .quiescingLastRequestEndReceived && self.state == .idle { - ctx.close(promise: nil) + context.close(promise: nil) } case .body: () } - ctx.fireChannelRead(data) + context.fireChannelRead(data) } - private func deliverOneError(ctx: ChannelHandlerContext, error: Error) { + private func deliverOneError(context: ChannelHandlerContext, error: Error) { // there is one interesting case in this error sending logic: If we receive a `HTTPParserError` and we haven't // received a full request nor the beginning of a response we should treat this as a full request. The reason // is that what the user will probably do is send a `.badRequest` response and we should be in a state which @@ -233,10 +233,10 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha if (self.state == .idle || self.state == .requestEndPending) && error is HTTPParserError { self.state = .responseEndPending } - ctx.fireErrorCaught(error) + context.fireErrorCaught(error) } - public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { switch event { case is ChannelShouldQuiesceEvent: assert(self.lifecycleState == .acceptingEvents, @@ -250,7 +250,7 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha // we're completely idle, let's just close self.lifecycleState = .quiescingLastRequestEndReceived self.eventBuffer.removeAll() - ctx.close(promise: nil) + context.close(promise: nil) case .requestEndPending, .requestAndResponseEndPending: // we're in the middle of a request, we'll need to keep accepting events until we see the .end self.lifecycleState = .quiescingWaitingForRequestEnd @@ -261,26 +261,26 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha if case .responseEndPending = self.state, self.eventBuffer.count > 0 { self.eventBuffer.append(.halfClose) } else { - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) } default: - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) } } - public func errorCaught(ctx: ChannelHandlerContext, error: Error) { + public func errorCaught(context: ChannelHandlerContext, error: Error) { guard let httpError = error as? HTTPParserError else { - self.deliverOneError(ctx: ctx, error: error) + self.deliverOneError(context: context, error: error) return } if case .responseEndPending = self.state { self.eventBuffer.append(.error(httpError)) return } - self.deliverOneError(ctx: ctx, error: error) + self.deliverOneError(context: context, error: error) } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { assert(self.state != .requestEndPending, "Received second response while waiting for first one to complete") debugOnly { @@ -304,7 +304,7 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha if head.isKeepAlive { head.headers.replaceOrAdd(name: "connection", value: "close") } - ctx.write(self.wrapOutboundOut(.head(head)), promise: promise) + context.write(self.wrapOutboundOut(.head(head)), promise: promise) case .end: startReadingAgain = true @@ -313,29 +313,29 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha // we just received the .end that we're missing so we can fall through to closing the connection fallthrough case .quiescingLastRequestEndReceived: - ctx.write(data).flatMap { - ctx.close() + context.write(data).flatMap { + context.close() }.cascade(to: promise) case .acceptingEvents, .quiescingWaitingForRequestEnd: - ctx.write(data, promise: promise) + context.write(data, promise: promise) } case .body, .head: - ctx.write(data, promise: promise) + context.write(data, promise: promise) } if startReadingAgain { self.state.responseEndReceived() - self.deliverPendingRequests(ctx: ctx) - self.startReading(ctx: ctx) + self.deliverPendingRequests(context: context) + self.startReading(context: context) } } - public func read(ctx: ChannelHandlerContext) { + public func read(context: ChannelHandlerContext) { if self.lifecycleState != .quiescingLastRequestEndReceived { if case .responseEndPending = self.state { self.readPending = true } else { - ctx.read() + context.read() } } } @@ -343,16 +343,16 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha /// A response has been sent: we can now start passing reads through /// again if there are no further pending requests, and send any read() /// call we may have swallowed. - private func startReading(ctx: ChannelHandlerContext) { + private func startReading(context: ChannelHandlerContext) { if self.readPending && self.state != .responseEndPending && self.lifecycleState != .quiescingLastRequestEndReceived { self.readPending = false - ctx.read() + context.read() } } /// A response has been sent: deliver all pending requests and /// mark the channel ready to handle more requests. - private func deliverPendingRequests(ctx: ChannelHandlerContext) { + private func deliverPendingRequests(context: ChannelHandlerContext) { var deliveredRead = false while self.state != .responseEndPending, let event = self.eventBuffer.first { @@ -360,21 +360,21 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha switch event { case .channelRead(let read): - self.deliverOneMessage(ctx: ctx, data: read) + self.deliverOneMessage(context: context, data: read) deliveredRead = true case .error(let error): - self.deliverOneError(ctx: ctx, error: error) + self.deliverOneError(context: context, error: error) case .halfClose: // When we fire the half-close, we want to forget all prior reads. // They will just trigger further half-close notifications we don't // need. self.readPending = false - ctx.fireUserInboundEventTriggered(ChannelEvent.inputClosed) + context.fireUserInboundEventTriggered(ChannelEvent.inputClosed) } } if deliveredRead { - ctx.fireChannelReadComplete() + context.fireChannelReadComplete() } // We need to quickly check whether there is an EOF waiting here, because @@ -386,7 +386,7 @@ public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableCha if case .some(.halfClose) = self.eventBuffer.first { self.eventBuffer.removeFirst() self.readPending = false - ctx.fireUserInboundEventTriggered(ChannelEvent.inputClosed) + context.fireUserInboundEventTriggered(ChannelEvent.inputClosed) } } } diff --git a/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift b/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift index 7aeaa05a6..f118ccde5 100644 --- a/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift +++ b/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift @@ -31,9 +31,9 @@ public final class HTTPServerProtocolErrorHandler: ChannelDuplexHandler, Removab public init() {} - public func errorCaught(ctx: ChannelHandlerContext, error: Error) { + public func errorCaught(context: ChannelHandlerContext, error: Error) { guard error is HTTPParserError else { - ctx.fireErrorCaught(error) + context.fireErrorCaught(error) return } @@ -47,15 +47,15 @@ public final class HTTPServerProtocolErrorHandler: ChannelDuplexHandler, Removab if !self.hasUnterminatedResponse { let headers = HTTPHeaders([("Connection", "close"), ("Content-Length", "0")]) let head = HTTPResponseHead(version: .init(major: 1, minor: 1), status: .badRequest, headers: headers) - ctx.write(self.wrapOutboundOut(.head(head)), promise: nil) - ctx.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. - ctx.fireErrorCaught(error) + context.fireErrorCaught(error) } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { let res = self.unwrapOutboundIn(data) switch res { case .head: @@ -67,6 +67,6 @@ public final class HTTPServerProtocolErrorHandler: ChannelDuplexHandler, Removab precondition(self.hasUnterminatedResponse) self.hasUnterminatedResponse = false } - ctx.write(data, promise: promise) + context.write(data, promise: promise) } } diff --git a/Sources/NIOHTTP1/HTTPUpgradeHandler.swift b/Sources/NIOHTTP1/HTTPUpgradeHandler.swift index d47449cc0..e4c6f7250 100644 --- a/Sources/NIOHTTP1/HTTPUpgradeHandler.swift +++ b/Sources/NIOHTTP1/HTTPUpgradeHandler.swift @@ -47,7 +47,7 @@ public protocol HTTPServerProtocolUpgrader { /// Called when the upgrade response has been flushed. At this time it is safe to mutate the channel pipeline /// to add whatever channel handlers are required. Until the returned `EventLoopFuture` succeeds, all received /// data will be buffered. - func upgrade(ctx: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture + func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture } /// A server-side channel handler that receives HTTP requests and optionally performs a HTTP-upgrade. @@ -99,7 +99,7 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa self.extraHTTPHandlers = extraHTTPHandlers } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { guard !self.seenFirstRequest else { // We're waiting for upgrade to complete: buffer this data. self.receivedMessages.append(data) @@ -111,8 +111,8 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa if let upgrade = self.upgrade { switch requestPart { case .head: - ctx.fireErrorCaught(HTTPServerUpgradeErrors.invalidHTTPOrdering) - notUpgrading(ctx: ctx, data: data) + context.fireErrorCaught(HTTPServerUpgradeErrors.invalidHTTPOrdering) + notUpgrading(context: context, data: data) return case .body: // TODO: In the future way may want to add some API to also allow special handling of the body during the @@ -129,8 +129,8 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa // by the time the body comes in we should be out of the pipeline. That means that if we don't think we're // upgrading, the only thing we should see is a request head. Anything else in an error. guard case .head(let request) = requestPart else { - ctx.fireErrorCaught(HTTPServerUpgradeErrors.invalidHTTPOrdering) - notUpgrading(ctx: ctx, data: data) + context.fireErrorCaught(HTTPServerUpgradeErrors.invalidHTTPOrdering) + notUpgrading(context: context, data: data) return } @@ -138,21 +138,21 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa // from the channel pipeline. let requestedProtocols = request.headers[canonicalForm: "upgrade"] guard requestedProtocols.count > 0 else { - notUpgrading(ctx: ctx, data: data) + notUpgrading(context: context, data: data) return } // Cool, this is an upgrade! Let's go. - if let upgrade = handleUpgrade(ctx: ctx, request: request, requestedProtocols: requestedProtocols) { + if let upgrade = handleUpgrade(context: context, request: request, requestedProtocols: requestedProtocols) { self.upgrade = upgrade } else { - notUpgrading(ctx: ctx, data: data) + notUpgrading(context: context, data: data) } } } /// The core of the upgrade handling logic. - private func handleUpgrade(ctx: ChannelHandlerContext, request: HTTPRequestHead, requestedProtocols: [String]) -> (() -> Void)? { + private func handleUpgrade(context: ChannelHandlerContext, request: HTTPRequestHead, requestedProtocols: [String]) -> (() -> Void)? { let connectionHeader = Set(request.headers[canonicalForm: "connection"].map { $0.lowercased() }) let allHeaderNames = Set(request.headers.map { $0.name.lowercased() }) @@ -171,7 +171,7 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa responseHeaders = try upgrader.buildUpgradeResponse(upgradeRequest: request, initialResponseHeaders: responseHeaders) } catch { // We should fire this error so the user can log it, but keep going. - ctx.fireErrorCaught(error) + context.fireErrorCaught(error) continue } @@ -185,16 +185,16 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa // internal handler, then call the user code, and then finally when the user code is done we do // our final cleanup steps, namely we replay the received data we buffered in the meantime and // then remove ourselves from the pipeline. - self.removeExtraHandlers(ctx: ctx).flatMap { - self.sendUpgradeResponse(ctx: ctx, upgradeRequest: request, responseHeaders: responseHeaders) + self.removeExtraHandlers(context: context).flatMap { + self.sendUpgradeResponse(context: context, upgradeRequest: request, responseHeaders: responseHeaders) }.flatMap { - self.removeHandler(ctx: ctx, handler: self.httpEncoder) + self.removeHandler(context: context, handler: self.httpEncoder) }.map { - self.upgradeCompletionHandler(ctx) + self.upgradeCompletionHandler(context) }.flatMap { - upgrader.upgrade(ctx: ctx, upgradeRequest: request) + upgrader.upgrade(context: context, upgradeRequest: request) }.map { - ctx.fireUserInboundEventTriggered(HTTPServerUpgradeEvents.upgradeComplete(toProtocol: proto, upgradeRequest: request)) + context.fireUserInboundEventTriggered(HTTPServerUpgradeEvents.upgradeComplete(toProtocol: proto, upgradeRequest: request)) self.upgrade = nil @@ -202,12 +202,12 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa // we also fire readComplete. let bufferedMessages = self.receivedMessages self.receivedMessages = [] - bufferedMessages.forEach { ctx.fireChannelRead($0) } + bufferedMessages.forEach { context.fireChannelRead($0) } if bufferedMessages.count > 0 { - ctx.fireChannelReadComplete() + context.fireChannelReadComplete() } }.whenComplete { (_: Result) in - ctx.pipeline.removeHandler(ctx: ctx, promise: nil) + context.pipeline.removeHandler(context: context, promise: nil) } } } @@ -216,17 +216,17 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa } /// Sends the 101 Switching Protocols response for the pipeline. - private func sendUpgradeResponse(ctx: ChannelHandlerContext, upgradeRequest: HTTPRequestHead, responseHeaders: HTTPHeaders) -> EventLoopFuture { + private func sendUpgradeResponse(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead, responseHeaders: HTTPHeaders) -> EventLoopFuture { var response = HTTPResponseHead(version: HTTPVersion(major: 1, minor: 1), status: .switchingProtocols) response.headers = responseHeaders - return ctx.writeAndFlush(wrapOutboundOut(HTTPServerResponsePart.head(response))) + return context.writeAndFlush(wrapOutboundOut(HTTPServerResponsePart.head(response))) } /// 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) { + private func notUpgrading(context: ChannelHandlerContext, data: NIOAny) { assert(self.receivedMessages.count == 0) - ctx.fireChannelRead(data) - ctx.pipeline.removeHandler(ctx: ctx, promise: nil) + context.fireChannelRead(data) + context.pipeline.removeHandler(context: context, promise: nil) } /// Builds the initial mandatory HTTP headers for HTTP ugprade responses. @@ -235,21 +235,21 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa } /// Removes the given channel handler from the channel pipeline. - private func removeHandler(ctx: ChannelHandlerContext, handler: RemovableChannelHandler?) -> EventLoopFuture { + private func removeHandler(context: ChannelHandlerContext, handler: RemovableChannelHandler?) -> EventLoopFuture { if let handler = handler { - return ctx.pipeline.removeHandler(handler) + return context.pipeline.removeHandler(handler) } else { - return ctx.eventLoop.makeSucceededFuture(()) + return context.eventLoop.makeSucceededFuture(()) } } /// Removes any extra HTTP-related handlers from the channel pipeline. - private func removeExtraHandlers(ctx: ChannelHandlerContext) -> EventLoopFuture { + private func removeExtraHandlers(context: ChannelHandlerContext) -> EventLoopFuture { guard self.extraHTTPHandlers.count > 0 else { - return ctx.eventLoop.makeSucceededFuture(()) + return context.eventLoop.makeSucceededFuture(()) } - return .andAllSucceed(self.extraHTTPHandlers.map { ctx.pipeline.removeHandler($0) }, - on: ctx.eventLoop) + return .andAllSucceed(self.extraHTTPHandlers.map { context.pipeline.removeHandler($0) }, + on: context.eventLoop) } } diff --git a/Sources/NIOHTTP1Server/main.swift b/Sources/NIOHTTP1Server/main.swift index 210a7722a..a0d870933 100644 --- a/Sources/NIOHTTP1Server/main.swift +++ b/Sources/NIOHTTP1Server/main.swift @@ -104,7 +104,7 @@ private final class HTTPHandler: ChannelInboundHandler { self.fileIO = fileIO } - func handleInfo(ctx: ChannelHandlerContext, request: HTTPServerRequestPart) { + func handleInfo(context: ChannelHandlerContext, request: HTTPServerRequestPart) { switch request { case .head(let request): self.infoSavedRequestHead = request @@ -120,24 +120,24 @@ private final class HTTPHandler: ChannelInboundHandler { URL: \(self.infoSavedRequestHead!.uri)\r body length: \(self.infoSavedBodyBytes)\r headers: \(self.infoSavedRequestHead!.headers)\r - client: \(ctx.remoteAddress?.description ?? "zombie")\r + client: \(context.remoteAddress?.description ?? "zombie")\r IO: SwiftNIO Electric Boogaloo™️\r\n """ self.buffer.clear() self.buffer.writeString(response) var headers = HTTPHeaders() headers.add(name: "Content-Length", value: "\(response.utf8.count)") - ctx.write(self.wrapOutboundOut(.head(httpResponseHead(request: self.infoSavedRequestHead!, status: .ok, headers: headers))), promise: nil) - ctx.write(self.wrapOutboundOut(.body(.byteBuffer(self.buffer))), promise: nil) - self.completeResponse(ctx, trailers: nil, 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) } } - func handleEcho(ctx: ChannelHandlerContext, request: HTTPServerRequestPart) { - self.handleEcho(ctx: ctx, request: request, balloonInMemory: false) + func handleEcho(context: ChannelHandlerContext, request: HTTPServerRequestPart) { + self.handleEcho(context: context, request: request, balloonInMemory: false) } - func handleEcho(ctx: ChannelHandlerContext, request: HTTPServerRequestPart, balloonInMemory: Bool = false) { + func handleEcho(context: ChannelHandlerContext, request: HTTPServerRequestPart, balloonInMemory: Bool = false) { switch request { case .head(let request): self.keepAlive = request.isKeepAlive @@ -146,54 +146,54 @@ private final class HTTPHandler: ChannelInboundHandler { if balloonInMemory { self.buffer.clear() } else { - ctx.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 { - ctx.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)") - ctx.write(self.wrapOutboundOut(.head(httpResponseHead(request: self.infoSavedRequestHead!, status: .ok, headers: headers))), promise: nil) - ctx.write(self.wrapOutboundOut(.body(.byteBuffer(self.buffer))), promise: nil) - self.completeResponse(ctx, trailers: nil, 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(ctx, trailers: nil, promise: nil) + self.completeResponse(context, trailers: nil, promise: nil) } } } - func handleJustWrite(ctx: ChannelHandlerContext, request: HTTPServerRequestPart, statusCode: HTTPResponseStatus = .ok, string: String, trailer: (String, String)? = nil, delay: TimeAmount = .nanoseconds(0)) { + func handleJustWrite(context: ChannelHandlerContext, request: HTTPServerRequestPart, statusCode: HTTPResponseStatus = .ok, string: String, trailer: (String, String)? = nil, delay: TimeAmount = .nanoseconds(0)) { switch request { case .head(let request): self.keepAlive = request.isKeepAlive self.state.requestReceived() - ctx.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: self.state.requestComplete() - ctx.eventLoop.scheduleTask(in: delay) { () -> Void in - var buf = ctx.channel.allocator.buffer(capacity: string.utf8.count) + context.eventLoop.scheduleTask(in: delay) { () -> Void in + var buf = context.channel.allocator.buffer(capacity: string.utf8.count) buf.writeString(string) - ctx.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() trailers?.add(name: trailer.0, value: trailer.1) } - self.completeResponse(ctx, trailers: trailers, promise: nil) + self.completeResponse(context, trailers: trailers, promise: nil) } } } - func handleContinuousWrites(ctx: ChannelHandlerContext, request: HTTPServerRequestPart) { + func handleContinuousWrites(context: ChannelHandlerContext, request: HTTPServerRequestPart) { switch request { case .head(let request): self.keepAlive = request.isKeepAlive @@ -203,13 +203,13 @@ private final class HTTPHandler: ChannelInboundHandler { self.buffer.clear() self.continuousCount += 1 self.buffer.writeString("line \(self.continuousCount)\n") - ctx.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(self.buffer)))).map { - ctx.eventLoop.scheduleTask(in: .milliseconds(400), doNext) + context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(self.buffer)))).map { + context.eventLoop.scheduleTask(in: .milliseconds(400), doNext) }.whenFailure { (_: Error) in - self.completeResponse(ctx, trailers: nil, promise: nil) + self.completeResponse(context, trailers: nil, promise: nil) } } - ctx.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() @@ -218,7 +218,7 @@ private final class HTTPHandler: ChannelInboundHandler { } } - func handleMultipleWrites(ctx: ChannelHandlerContext, request: HTTPServerRequestPart, strings: [String], delay: TimeAmount) { + func handleMultipleWrites(context: ChannelHandlerContext, request: HTTPServerRequestPart, strings: [String], delay: TimeAmount) { switch request { case .head(let request): self.keepAlive = request.isKeepAlive @@ -228,15 +228,15 @@ private final class HTTPHandler: ChannelInboundHandler { self.buffer.clear() self.buffer.writeString(strings[self.continuousCount]) self.continuousCount += 1 - ctx.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(self.buffer)))).whenSuccess { + context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(self.buffer)))).whenSuccess { if self.continuousCount < strings.count { - ctx.eventLoop.scheduleTask(in: delay, doNext) + context.eventLoop.scheduleTask(in: delay, doNext) } else { - self.completeResponse(ctx, trailers: nil, promise: nil) + self.completeResponse(context, trailers: nil, promise: nil) } } } - ctx.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() @@ -247,8 +247,8 @@ private final class HTTPHandler: ChannelInboundHandler { func dynamicHandler(request reqHead: HTTPRequestHead) -> ((ChannelHandlerContext, HTTPServerRequestPart) -> Void)? { if let howLong = reqHead.uri.chopPrefix("/dynamic/write-delay/") { - return { ctx, req in - self.handleJustWrite(ctx: ctx, + return { context, req in + self.handleJustWrite(context: context, request: req, string: self.defaultResponse, delay: TimeAmount.Value(howLong).map { .milliseconds($0) } ?? .seconds(0)) } @@ -258,31 +258,31 @@ private final class HTTPHandler: ChannelInboundHandler { case "/dynamic/echo": return self.handleEcho case "/dynamic/echo_balloon": - return { self.handleEcho(ctx: $0, request: $1, balloonInMemory: true) } + return { self.handleEcho(context: $0, request: $1, balloonInMemory: true) } case "/dynamic/pid": - return { ctx, req in self.handleJustWrite(ctx: ctx, request: req, string: "\(getpid())") } + return { context, req in self.handleJustWrite(context: context, request: req, string: "\(getpid())") } case "/dynamic/write-delay": - return { ctx, req in self.handleJustWrite(ctx: ctx, request: req, string: self.defaultResponse, delay: .milliseconds(100)) } + return { context, req in self.handleJustWrite(context: context, request: req, string: self.defaultResponse, delay: .milliseconds(100)) } case "/dynamic/info": return self.handleInfo case "/dynamic/trailers": - return { ctx, req in self.handleJustWrite(ctx: ctx, request: req, string: "\(getpid())\r\n", trailer: ("Trailer-Key", "Trailer-Value")) } + return { context, req in self.handleJustWrite(context: context, request: req, string: "\(getpid())\r\n", trailer: ("Trailer-Key", "Trailer-Value")) } case "/dynamic/continuous": return self.handleContinuousWrites case "/dynamic/count-to-ten": - return { self.handleMultipleWrites(ctx: $0, request: $1, strings: (1...10).map { "\($0)" }, delay: .milliseconds(100)) } + return { self.handleMultipleWrites(context: $0, request: $1, strings: (1...10).map { "\($0)" }, delay: .milliseconds(100)) } case "/dynamic/client-ip": - return { ctx, req in self.handleJustWrite(ctx: ctx, request: req, string: "\(ctx.remoteAddress.debugDescription)") } + return { context, req in self.handleJustWrite(context: context, request: req, string: "\(context.remoteAddress.debugDescription)") } default: - return { ctx, req in self.handleJustWrite(ctx: ctx, request: req, statusCode: .notFound, string: "not found") } + return { context, req in self.handleJustWrite(context: context, request: req, statusCode: .notFound, string: "not found") } } } - private func handleFile(ctx: ChannelHandlerContext, request: HTTPServerRequestPart, ioMethod: FileIOMethod, path: String) { + private func handleFile(context: ChannelHandlerContext, request: HTTPServerRequestPart, ioMethod: FileIOMethod, path: String) { self.buffer.clear() func sendErrorResponse(request: HTTPRequestHead, _ error: Error) { - var body = ctx.channel.allocator.buffer(capacity: 128) + var body = context.channel.allocator.buffer(capacity: 128) let response = { () -> HTTPResponseHead in switch error { case let e as IOError where e.errnoCode == ENOENT: @@ -300,10 +300,10 @@ private final class HTTPHandler: ChannelInboundHandler { }() body.writeString("\(error)") body.writeStaticString("\r\n") - ctx.write(self.wrapOutboundOut(.head(response)), promise: nil) - ctx.write(self.wrapOutboundOut(.body(.byteBuffer(body))), promise: nil) - ctx.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) - ctx.channel.close(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) } func responseHead(request: HTTPRequestHead, fileRegion region: FileRegion) -> HTTPResponseHead { @@ -319,12 +319,12 @@ private final class HTTPHandler: ChannelInboundHandler { self.state.requestReceived() guard !request.uri.containsDotDot() else { let response = httpResponseHead(request: request, status: .forbidden) - ctx.write(self.wrapOutboundOut(.head(response)), promise: nil) - self.completeResponse(ctx, trailers: nil, promise: nil) + context.write(self.wrapOutboundOut(.head(response)), promise: nil) + self.completeResponse(context, trailers: nil, promise: nil) return } let path = self.htdocsPath + "/" + path - let fileHandleAndRegion = self.fileIO.openFile(path: path, eventLoop: ctx.eventLoop) + let fileHandleAndRegion = self.fileIO.openFile(path: path, eventLoop: context.eventLoop) fileHandleAndRegion.whenFailure { sendErrorResponse(request: request, $0) } @@ -335,41 +335,41 @@ private final class HTTPHandler: ChannelInboundHandler { let response = responseHead(request: request, fileRegion: region) return self.fileIO.readChunked(fileRegion: region, chunkSize: 32 * 1024, - allocator: ctx.channel.allocator, - eventLoop: ctx.eventLoop) { buffer in + allocator: context.channel.allocator, + eventLoop: context.eventLoop) { buffer in if !responseStarted { responseStarted = true - ctx.write(self.wrapOutboundOut(.head(response)), promise: nil) + context.write(self.wrapOutboundOut(.head(response)), promise: nil) } - return ctx.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(buffer)))) + return context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(buffer)))) }.flatMap { () -> EventLoopFuture in - let p = ctx.eventLoop.makePromise(of: Void.self) - self.completeResponse(ctx, trailers: nil, promise: p) + let p = context.eventLoop.makePromise(of: Void.self) + self.completeResponse(context, trailers: nil, promise: p) return p.futureResult }.flatMapError { error in if !responseStarted { let response = httpResponseHead(request: request, status: .ok) - ctx.write(self.wrapOutboundOut(.head(response)), promise: nil) - var buffer = ctx.channel.allocator.buffer(capacity: 100) + context.write(self.wrapOutboundOut(.head(response)), promise: nil) + var buffer = context.channel.allocator.buffer(capacity: 100) buffer.writeString("fail: \(error)") - ctx.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) + context.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) self.state.responseComplete() - return ctx.writeAndFlush(self.wrapOutboundOut(.end(nil))) + return context.writeAndFlush(self.wrapOutboundOut(.end(nil))) } else { - return ctx.close() + return context.close() } }.whenComplete { (_: Result) in _ = try? file.close() } case .sendfile: let response = responseHead(request: request, fileRegion: region) - ctx.write(self.wrapOutboundOut(.head(response)), promise: nil) - ctx.writeAndFlush(self.wrapOutboundOut(.body(.fileRegion(region)))).flatMap { - let p = ctx.eventLoop.makePromise(of: Void.self) - self.completeResponse(ctx, trailers: nil, promise: p) + 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 }.flatMapError { (_: Error) in - ctx.close() + context.close() }.whenComplete { (_: Result) in _ = try? file.close() } @@ -382,22 +382,22 @@ private final class HTTPHandler: ChannelInboundHandler { } } - private func completeResponse(_ ctx: ChannelHandlerContext, trailers: HTTPHeaders?, promise: EventLoopPromise?) { + private func completeResponse(_ context: ChannelHandlerContext, trailers: HTTPHeaders?, promise: EventLoopPromise?) { self.state.responseComplete() - let promise = self.keepAlive ? promise : (promise ?? ctx.eventLoop.makePromise()) + let promise = self.keepAlive ? promise : (promise ?? context.eventLoop.makePromise()) if !self.keepAlive { - promise!.futureResult.whenComplete { (_: Result) in ctx.close(promise: nil) } + promise!.futureResult.whenComplete { (_: Result) in context.close(promise: nil) } } self.handler = nil - ctx.writeAndFlush(self.wrapOutboundOut(.end(trailers)), promise: promise) + context.writeAndFlush(self.wrapOutboundOut(.end(trailers)), promise: promise) } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let reqPart = self.unwrapInboundIn(data) if let handler = self.handler { - handler(ctx, reqPart) + handler(context, reqPart) return } @@ -405,15 +405,15 @@ private final class HTTPHandler: ChannelInboundHandler { case .head(let request): if request.uri.unicodeScalars.starts(with: "/dynamic".unicodeScalars) { self.handler = self.dynamicHandler(request: request) - self.handler!(ctx, reqPart) + self.handler!(context, reqPart) return } else if let path = request.uri.chopPrefix("/sendfile/") { - self.handler = { self.handleFile(ctx: $0, request: $1, ioMethod: .sendfile, path: path) } - self.handler!(ctx, reqPart) + self.handler = { self.handleFile(context: $0, request: $1, ioMethod: .sendfile, path: path) } + self.handler!(context, reqPart) return } else if let path = request.uri.chopPrefix("/fileio/") { - self.handler = { self.handleFile(ctx: $0, request: $1, ioMethod: .nonblockingFileIO, path: path) } - self.handler!(ctx, reqPart) + self.handler = { self.handleFile(context: $0, request: $1, ioMethod: .nonblockingFileIO, path: path) } + self.handler!(context, reqPart) return } @@ -425,26 +425,26 @@ private final class HTTPHandler: ChannelInboundHandler { self.buffer.writeString(defaultResponse) responseHead.headers.add(name: "content-length", value: "\(self.buffer!.readableBytes)") let response = HTTPServerResponsePart.head(responseHead) - ctx.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())) - ctx.write(self.wrapOutboundOut(content), promise: nil) - self.completeResponse(ctx, trailers: nil, promise: nil) + context.write(self.wrapOutboundOut(content), promise: nil) + self.completeResponse(context, trailers: nil, promise: nil) } } - func channelReadComplete(ctx: ChannelHandlerContext) { - ctx.flush() + func channelReadComplete(context: ChannelHandlerContext) { + context.flush() } - func handlerAdded(ctx: ChannelHandlerContext) { - self.buffer = ctx.channel.allocator.buffer(capacity: 0) + func handlerAdded(context: ChannelHandlerContext) { + self.buffer = context.channel.allocator.buffer(capacity: 0) } - func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { switch event { case let evt as ChannelEvent where evt == ChannelEvent.inputClosed: // The remote peer half-closed the channel. At this time, any @@ -453,12 +453,12 @@ private final class HTTPHandler: ChannelInboundHandler { // will close the channel immediately. switch self.state { case .idle, .waitingForRequestBody: - ctx.close(promise: nil) + context.close(promise: nil) case .sendingResponse: self.keepAlive = false } default: - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) } } } diff --git a/Sources/NIOMulticastChat/main.swift b/Sources/NIOMulticastChat/main.swift index f2e6add0c..e12cdcbef 100644 --- a/Sources/NIOMulticastChat/main.swift +++ b/Sources/NIOMulticastChat/main.swift @@ -18,7 +18,7 @@ import NIO private final class ChatMessageDecoder: ChannelInboundHandler { public typealias InboundIn = AddressedEnvelope - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let envelope = self.unwrapInboundIn(data) var buffer = envelope.data @@ -37,11 +37,11 @@ private final class ChatMessageEncoder: ChannelOutboundHandler { public typealias OutboundIn = AddressedEnvelope public typealias OutboundOut = AddressedEnvelope - func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { let message = self.unwrapOutboundIn(data) - var buffer = ctx.channel.allocator.buffer(capacity: message.data.utf8.count) + var buffer = context.channel.allocator.buffer(capacity: message.data.utf8.count) buffer.writeString(message.data) - ctx.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/main.swift b/Sources/NIOPerformanceTester/main.swift index 3e9a39a8d..e7dd71e49 100644 --- a/Sources/NIOPerformanceTester/main.swift +++ b/Sources/NIOPerformanceTester/main.swift @@ -90,15 +90,15 @@ private final class SimpleHTTPServer: ChannelInboundHandler { self.cachedBody = body } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { if case .head(let req) = self.unwrapInboundIn(data) { switch req.uri { case "/perf-test-1": - var buffer = ctx.channel.allocator.buffer(capacity: self.cachedBody.count) + var buffer = context.channel.allocator.buffer(capacity: self.cachedBody.count) buffer.writeBytes(self.cachedBody) - ctx.write(self.wrapOutboundOut(.head(self.cachedHead)), promise: nil) - ctx.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) - ctx.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: HTTPVersion(major: 1, minor: 1), status: .ok) @@ -106,8 +106,8 @@ private final class SimpleHTTPServer: ChannelInboundHandler { req.headers.add(name: "X-ResponseHeader-\(i)", value: "foo") } req.headers.add(name: "content-length", value: "0") - ctx.write(self.wrapOutboundOut(.head(req)), promise: nil) - ctx.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)") @@ -159,22 +159,22 @@ final class RepeatedRequests: ChannelInboundHandler { return reqs } - func errorCaught(ctx: ChannelHandlerContext, error: Error) { - ctx.channel.close(promise: nil) + func errorCaught(context: ChannelHandlerContext, error: Error) { + context.channel.close(promise: nil) self.isDonePromise.fail(error) } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let reqPart = self.unwrapInboundIn(data) if case .end(nil) = reqPart { if self.remainingNumberOfRequests <= 0 { - ctx.channel.close().map { self.doneRequests }.cascade(to: self.isDonePromise) + context.channel.close().map { self.doneRequests }.cascade(to: self.isDonePromise) } else { self.doneRequests += 1 self.remainingNumberOfRequests -= 1 - ctx.write(self.wrapOutboundOut(.head(head)), promise: nil) - ctx.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(self.wrapOutboundOut(.head(head)), promise: nil) + context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) } } } @@ -511,8 +511,8 @@ try measureAndPrint(desc: "no-net_http1_10k_reqs_1_conn") { self.remainingNumberOfRequests = numberOfRequests } - func handlerAdded(ctx: ChannelHandlerContext) { - self.requestBuffer = ctx.channel.allocator.buffer(capacity: 512) + func handlerAdded(context: ChannelHandlerContext) { + self.requestBuffer = context.channel.allocator.buffer(capacity: 512) self.requestBuffer.writeString(""" GET /perf-test-2 HTTP/1.1\r Host: example.com\r @@ -527,16 +527,16 @@ try measureAndPrint(desc: "no-net_http1_10k_reqs_1_conn") { """) } - func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { var buf = self.unwrapOutboundIn(data) if self.expectedResponseBuffer == nil { self.expectedResponseBuffer = buf } precondition(buf == self.expectedResponseBuffer, "got \(buf.readString(length: buf.readableBytes)!)") - let channel = ctx.channel + let channel = context.channel self.remainingNumberOfRequests -= 1 if self.remainingNumberOfRequests > 0 { - ctx.eventLoop.execute { + context.eventLoop.execute { self.kickOff(channel: channel) } } else { diff --git a/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift b/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift index 1b17c2f3d..22afd6ffc 100644 --- a/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift +++ b/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift @@ -75,24 +75,24 @@ public class ApplicationProtocolNegotiationHandler: ChannelInboundHandler, Remov self.eventBuffer = [] } - public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { guard let tlsEvent = event as? TLSUserEvent else { - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) return } if case .handshakeCompleted(let p) = tlsEvent { - handshakeCompleted(context: ctx, negotiatedProtocol: p) + handshakeCompleted(context: context, negotiatedProtocol: p) } else { - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) } } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { if waitingForUser { eventBuffer.append(data) } else { - ctx.fireChannelRead(data) + context.fireChannelRead(data) } } diff --git a/Sources/NIOTLS/SNIHandler.swift b/Sources/NIOTLS/SNIHandler.swift index 092af9df6..82e67d279 100644 --- a/Sources/NIOTLS/SNIHandler.swift +++ b/Sources/NIOTLS/SNIHandler.swift @@ -107,13 +107,13 @@ public class SNIHandler: ByteToMessageDecoder { self.waitingForUser = false } - public func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { - ctx.fireChannelRead(NIOAny(buffer)) + public func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + context.fireChannelRead(NIOAny(buffer)) return .needMoreData } // A note to maintainers: this method *never* returns `.continue`. - public func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { + public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { // If we've asked the user to mutate the pipeline already, we're not interested in // this data. Keep waiting. if waitingForUser { @@ -129,14 +129,14 @@ public class SNIHandler: ByteToMessageDecoder { } catch { // Some error occurred. Fall back and let the TLS stack // handle it. - sniComplete(result: .fallback, ctx: ctx) + sniComplete(result: .fallback, context: context) return .needMoreData } if let serverName = serverName { - sniComplete(result: .hostname(serverName), ctx: ctx) + sniComplete(result: .hostname(serverName), context: context) } else { - sniComplete(result: .fallback, ctx: ctx) + sniComplete(result: .fallback, context: context) } return .needMoreData } @@ -418,10 +418,10 @@ public class SNIHandler: ByteToMessageDecoder { /// 3. When the user completes, remove ourselves from the pipeline. This will trigger the /// ByteToMessageDecoder to automatically deliver the buffered bytes to the next handler /// in the pipeline, which is now responsible for the work. - private func sniComplete(result: SNIResult, ctx: ChannelHandlerContext) { + private func sniComplete(result: SNIResult, context: ChannelHandlerContext) { waitingForUser = true completionHandler(result).whenSuccess { - ctx.pipeline.removeHandler(ctx: ctx, promise: nil) + context.pipeline.removeHandler(context: context, promise: nil) } } } diff --git a/Sources/NIOWebSocket/WebSocketFrameDecoder.swift b/Sources/NIOWebSocket/WebSocketFrameDecoder.swift index 1e6569c20..11fd465bb 100644 --- a/Sources/NIOWebSocket/WebSocketFrameDecoder.swift +++ b/Sources/NIOWebSocket/WebSocketFrameDecoder.swift @@ -258,19 +258,19 @@ public final class WebSocketFrameDecoder: ByteToMessageDecoder { self.automaticErrorHandling = automaticErrorHandling } - public func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { + public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { // Even though the calling code will loop around calling us in `decode`, we can't quite // rely on that: sometimes we have zero-length elements to parse, and the caller doesn't // guarantee to call us with zero-length bytes. parseLoop: while self.shouldKeepParsing { switch parser.parseStep(&buffer) { case .result(let frame): - ctx.fireChannelRead(self.wrapInboundOut(frame)) + context.fireChannelRead(self.wrapInboundOut(frame)) case .continueParsing: do { try self.parser.validateState(maxFrameSize: self.maxFrameSize) } catch { - self.handleError(error, ctx: ctx) + self.handleError(error, context: context) } case .insufficientData: break parseLoop @@ -281,7 +281,7 @@ public final class WebSocketFrameDecoder: ByteToMessageDecoder { return .needMoreData } - public func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + public func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { // EOF is not semantic in WebSocket, so ignore this. return .needMoreData } @@ -295,7 +295,7 @@ public final class WebSocketFrameDecoder: ByteToMessageDecoder { /// A clean websocket shutdown is not really supposed to have an immediate close, /// but we're doing that because the remote peer has prevented us from doing /// further frame parsing, so we can't really wait for the next frame. - private func handleError(_ error: Error, ctx: ChannelHandlerContext) { + private func handleError(_ error: Error, context: ChannelHandlerContext) { guard let error = error as? NIOWebSocketError else { fatalError("Can only handle NIOWebSocketErrors") } @@ -304,16 +304,16 @@ public final class WebSocketFrameDecoder: ByteToMessageDecoder { // If we've been asked to handle the errors here, we should. // TODO(cory): Remove this in 2.0, in favour of `WebSocketProtocolErrorHandler`. if self.automaticErrorHandling { - var data = ctx.channel.allocator.buffer(capacity: 2) + var data = context.channel.allocator.buffer(capacity: 2) data.write(webSocketErrorCode: WebSocketErrorCode(error)) let frame = WebSocketFrame(fin: true, opcode: .connectionClose, data: data) - ctx.writeAndFlush(self.wrapInboundOut(frame)).whenComplete { (_: Result) in - ctx.close(promise: nil) + context.writeAndFlush(self.wrapInboundOut(frame)).whenComplete { (_: Result) in + context.close(promise: nil) } } - ctx.fireErrorCaught(error) + context.fireErrorCaught(error) } } diff --git a/Sources/NIOWebSocket/WebSocketFrameEncoder.swift b/Sources/NIOWebSocket/WebSocketFrameEncoder.swift index 07c42b49f..37a504c05 100644 --- a/Sources/NIOWebSocket/WebSocketFrameEncoder.swift +++ b/Sources/NIOWebSocket/WebSocketFrameEncoder.swift @@ -41,7 +41,7 @@ public final class WebSocketFrameEncoder: ChannelOutboundHandler { public init() { } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { let data = self.unwrapOutboundIn(data) var maskSize: Int @@ -63,16 +63,16 @@ public final class WebSocketFrameEncoder: ChannelOutboundHandler { var buffer: ByteBuffer switch data.length { case 0...maxOneByteSize: - buffer = ctx.channel.allocator.buffer(capacity: baseLength) + buffer = context.channel.allocator.buffer(capacity: baseLength) buffer.writeInteger(data.firstByte) buffer.writeInteger(UInt8(data.length) | maskBitMask) case (maxOneByteSize + 1)...maxTwoByteSize: - buffer = ctx.channel.allocator.buffer(capacity: baseLength + 2) + buffer = context.channel.allocator.buffer(capacity: baseLength + 2) buffer.writeInteger(data.firstByte) buffer.writeInteger(UInt8(126) | maskBitMask) buffer.writeInteger(UInt16(data.length)) case (maxTwoByteSize + 1)...maxNIOFrameSize: - buffer = ctx.channel.allocator.buffer(capacity: baseLength + 8) + buffer = context.channel.allocator.buffer(capacity: baseLength + 8) buffer.writeInteger(data.firstByte) buffer.writeInteger(UInt8(127) | maskBitMask) buffer.writeInteger(UInt64(data.length)) @@ -85,7 +85,7 @@ public final class WebSocketFrameEncoder: ChannelOutboundHandler { } // Ok, frame header away! - ctx.write(self.wrapOutboundOut(buffer), promise: nil) + context.write(self.wrapOutboundOut(buffer), promise: nil) // Next, let's mask the extension and application data and send // them too. @@ -94,9 +94,9 @@ public final class WebSocketFrameEncoder: ChannelOutboundHandler { // Now we can send our byte buffers out. We attach the write promise to the last // of the frame data. if let extensionData = extensionData { - ctx.write(self.wrapOutboundOut(extensionData), promise: nil) + context.write(self.wrapOutboundOut(extensionData), promise: nil) } - ctx.write(self.wrapOutboundOut(applicationData), promise: promise) + context.write(self.wrapOutboundOut(applicationData), promise: promise) } /// Applies the websocket masking operation based on the passed byte buffers. diff --git a/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift b/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift index bc9e63bb6..20335d4af 100644 --- a/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift +++ b/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift @@ -25,20 +25,20 @@ public final class WebSocketProtocolErrorHandler: ChannelInboundHandler { public init() { } - public func errorCaught(ctx: ChannelHandlerContext, error: Error) { + public func errorCaught(context: ChannelHandlerContext, error: Error) { if let error = error as? NIOWebSocketError { - var data = ctx.channel.allocator.buffer(capacity: 2) + var data = context.channel.allocator.buffer(capacity: 2) data.write(webSocketErrorCode: WebSocketErrorCode(error)) let frame = WebSocketFrame(fin: true, opcode: .connectionClose, data: data) - ctx.writeAndFlush(self.wrapOutboundOut(frame)).whenComplete { (_: Result) in - ctx.close(promise: nil) + context.writeAndFlush(self.wrapOutboundOut(frame)).whenComplete { (_: Result) in + context.close(promise: nil) } } // Regardless of whether this is an error we want to handle or not, we always // forward the error on to let others see it. - ctx.fireErrorCaught(error) + context.fireErrorCaught(error) } } diff --git a/Sources/NIOWebSocket/WebSocketUpgrader.swift b/Sources/NIOWebSocket/WebSocketUpgrader.swift index 94c030cbd..aeb325349 100644 --- a/Sources/NIOWebSocket/WebSocketUpgrader.swift +++ b/Sources/NIOWebSocket/WebSocketUpgrader.swift @@ -144,19 +144,19 @@ public final class WebSocketUpgrader: HTTPServerProtocolUpgrader { return extraHeaders } - public func upgrade(ctx: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { + public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { /// We never use the automatic error handling feature of the WebSocketFrameDecoder: we always use the separate channel /// handler. - var upgradeFuture = ctx.pipeline.addHandler(WebSocketFrameEncoder()).flatMap { - ctx.pipeline.addHandler(ByteToMessageHandler(WebSocketFrameDecoder(maxFrameSize: self.maxFrameSize, automaticErrorHandling: false))) + var upgradeFuture = context.pipeline.addHandler(WebSocketFrameEncoder()).flatMap { + context.pipeline.addHandler(ByteToMessageHandler(WebSocketFrameDecoder(maxFrameSize: self.maxFrameSize, automaticErrorHandling: false))) } if self.automaticErrorHandling { - upgradeFuture = upgradeFuture.flatMap { ctx.pipeline.addHandler(WebSocketProtocolErrorHandler())} + upgradeFuture = upgradeFuture.flatMap { context.pipeline.addHandler(WebSocketProtocolErrorHandler())} } return upgradeFuture.flatMap { - self.upgradePipelineHandler(ctx.channel, upgradeRequest) + self.upgradePipelineHandler(context.channel, upgradeRequest) } } } diff --git a/Sources/NIOWebSocketServer/main.swift b/Sources/NIOWebSocketServer/main.swift index c5f7fb5c0..463f1a7e9 100644 --- a/Sources/NIOWebSocketServer/main.swift +++ b/Sources/NIOWebSocketServer/main.swift @@ -46,17 +46,17 @@ private final class HTTPHandler: ChannelInboundHandler, RemovableChannelHandler private var responseBody: ByteBuffer! - func channelRegistered(ctx: ChannelHandlerContext) { - var buffer = ctx.channel.allocator.buffer(capacity: websocketResponse.utf8.count) + func channelRegistered(context: ChannelHandlerContext) { + var buffer = context.channel.allocator.buffer(capacity: websocketResponse.utf8.count) buffer.writeString(websocketResponse) self.responseBody = buffer } - func channelUnregistered(ctx: ChannelHandlerContext) { + func channelUnregistered(context: ChannelHandlerContext) { self.responseBody = nil } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let reqPart = self.unwrapInboundIn(data) // We're not interested in request bodies here: we're just serving up GET responses @@ -67,7 +67,7 @@ private final class HTTPHandler: ChannelInboundHandler, RemovableChannelHandler // GETs only. guard case .GET = head.method else { - self.respond405(ctx: ctx) + self.respond405(context: context) return } @@ -78,26 +78,26 @@ private final class HTTPHandler: ChannelInboundHandler, RemovableChannelHandler let responseHead = HTTPResponseHead(version: .init(major: 1, minor: 1), status: .ok, headers: headers) - ctx.write(self.wrapOutboundOut(.head(responseHead)), promise: nil) - ctx.write(self.wrapOutboundOut(.body(.byteBuffer(self.responseBody))), promise: nil) - ctx.write(self.wrapOutboundOut(.end(nil))).whenComplete { (_: Result) in - ctx.close(promise: nil) + context.write(self.wrapOutboundOut(.head(responseHead)), promise: nil) + context.write(self.wrapOutboundOut(.body(.byteBuffer(self.responseBody))), promise: nil) + context.write(self.wrapOutboundOut(.end(nil))).whenComplete { (_: Result) in + context.close(promise: nil) } - ctx.flush() + context.flush() } - private func respond405(ctx: ChannelHandlerContext) { + private func respond405(context: ChannelHandlerContext) { var headers = HTTPHeaders() headers.add(name: "Connection", value: "close") headers.add(name: "Content-Length", value: "0") let head = HTTPResponseHead(version: .init(major: 1, minor: 1), status: .methodNotAllowed, headers: headers) - ctx.write(self.wrapOutboundOut(.head(head)), promise: nil) - ctx.write(self.wrapOutboundOut(.end(nil))).whenComplete { (_: Result) in - ctx.close(promise: nil) + context.write(self.wrapOutboundOut(.head(head)), promise: nil) + context.write(self.wrapOutboundOut(.end(nil))).whenComplete { (_: Result) in + context.close(promise: nil) } - ctx.flush() + context.flush() } } @@ -107,18 +107,18 @@ private final class WebSocketTimeHandler: ChannelInboundHandler { private var awaitingClose: Bool = false - public func handlerAdded(ctx: ChannelHandlerContext) { - self.sendTime(ctx: ctx) + public func handlerAdded(context: ChannelHandlerContext) { + self.sendTime(context: context) } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let frame = self.unwrapInboundIn(data) switch frame.opcode { case .connectionClose: - self.receivedClose(ctx: ctx, frame: frame) + self.receivedClose(context: context, frame: frame) case .ping: - self.pong(ctx: ctx, frame: frame) + self.pong(context: context, frame: frame) case .text: var data = frame.unmaskedData let text = data.readString(length: data.readableBytes) ?? "" @@ -128,16 +128,16 @@ private final class WebSocketTimeHandler: ChannelInboundHandler { break default: // Unknown frames are errors. - self.closeOnError(ctx: ctx) + self.closeOnError(context: context) } } - public func channelReadComplete(ctx: ChannelHandlerContext) { - ctx.flush() + public func channelReadComplete(context: ChannelHandlerContext) { + context.flush() } - private func sendTime(ctx: ChannelHandlerContext) { - guard ctx.channel.isActive else { return } + private func sendTime(context: ChannelHandlerContext) { + guard context.channel.isActive else { return } // We can't send if we sent a close message. guard !self.awaitingClose else { return } @@ -145,37 +145,37 @@ private final class WebSocketTimeHandler: ChannelInboundHandler { // We can't really check for error here, but it's also not the purpose of the // example so let's not worry about it. let theTime = NIODeadline.now().uptimeNanoseconds - var buffer = ctx.channel.allocator.buffer(capacity: 12) + var buffer = context.channel.allocator.buffer(capacity: 12) buffer.writeString("\(theTime)") let frame = WebSocketFrame(fin: true, opcode: .text, data: buffer) - ctx.writeAndFlush(self.wrapOutboundOut(frame)).map { - ctx.eventLoop.scheduleTask(in: .seconds(1), { self.sendTime(ctx: ctx) }) + context.writeAndFlush(self.wrapOutboundOut(frame)).map { + context.eventLoop.scheduleTask(in: .seconds(1), { self.sendTime(context: context) }) }.whenFailure { (_: Error) in - ctx.close(promise: nil) + context.close(promise: nil) } } - private func receivedClose(ctx: ChannelHandlerContext, frame: WebSocketFrame) { + private func receivedClose(context: ChannelHandlerContext, frame: WebSocketFrame) { // Handle a received close frame. In websockets, we're just going to send the close // frame and then close, unless we already sent our own close frame. if awaitingClose { // Cool, we started the close and were waiting for the user. We're done. - ctx.close(promise: nil) + context.close(promise: nil) } else { // This is an unsolicited close. We're going to send a response frame and // then, when we've sent it, close up shop. We should send back the close code the remote // peer sent us, unless they didn't send one at all. var data = frame.unmaskedData - let closeDataCode = data.readSlice(length: 2) ?? ctx.channel.allocator.buffer(capacity: 0) + let closeDataCode = data.readSlice(length: 2) ?? context.channel.allocator.buffer(capacity: 0) let closeFrame = WebSocketFrame(fin: true, opcode: .connectionClose, data: closeDataCode) - _ = ctx.write(self.wrapOutboundOut(closeFrame)).map { () in - ctx.close(promise: nil) + _ = context.write(self.wrapOutboundOut(closeFrame)).map { () in + context.close(promise: nil) } } } - private func pong(ctx: ChannelHandlerContext, frame: WebSocketFrame) { + private func pong(context: ChannelHandlerContext, frame: WebSocketFrame) { var frameData = frame.data let maskingKey = frame.maskKey @@ -184,17 +184,17 @@ private final class WebSocketTimeHandler: ChannelInboundHandler { } let responseFrame = WebSocketFrame(fin: true, opcode: .pong, data: frameData) - ctx.write(self.wrapOutboundOut(responseFrame), promise: nil) + context.write(self.wrapOutboundOut(responseFrame), promise: nil) } - private func closeOnError(ctx: ChannelHandlerContext) { + private func closeOnError(context: ChannelHandlerContext) { // We have hit an error, we want to close. We do that by sending a close frame and then // shutting down the write side of the connection. - var data = ctx.channel.allocator.buffer(capacity: 2) + var data = context.channel.allocator.buffer(capacity: 2) data.write(webSocketErrorCode: .protocolError) let frame = WebSocketFrame(fin: true, opcode: .connectionClose, data: data) - ctx.write(self.wrapOutboundOut(frame)).whenComplete { (_: Result) in - ctx.close(mode: .output, promise: nil) + context.write(self.wrapOutboundOut(frame)).whenComplete { (_: Result) in + context.close(mode: .output, promise: nil) } awaitingClose = true } diff --git a/Sources/_NIO1APIShims/NIO1APIShims.swift b/Sources/_NIO1APIShims/NIO1APIShims.swift index eff785a59..839e5a060 100644 --- a/Sources/_NIO1APIShims/NIO1APIShims.swift +++ b/Sources/_NIO1APIShims/NIO1APIShims.swift @@ -111,9 +111,9 @@ extension ChannelPipeline { return self.removeHandler(name: name) } - @available(*, deprecated, renamed: "removeHandler(ctx:)") - public func remove(ctx: ChannelHandlerContext) -> EventLoopFuture { - return self.removeHandler(ctx: ctx) + @available(*, deprecated, renamed: "removeHandler(context:)") + public func remove(context: ChannelHandlerContext) -> EventLoopFuture { + return self.removeHandler(context: context) } @available(*, deprecated, renamed: "removeHandler(_:promise:)") @@ -126,9 +126,9 @@ extension ChannelPipeline { return self.removeHandler(name: name, promise: promise) } - @available(*, deprecated, renamed: "removeHandler(ctx:promise:)") - public func remove(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { - return self.removeHandler(ctx: ctx, promise: promise) + @available(*, deprecated, renamed: "removeHandler(context:promise:)") + public func remove(context: ChannelHandlerContext, promise: EventLoopPromise?) { + return self.removeHandler(context: context, promise: promise) } } diff --git a/Tests/NIOHTTP1Tests/HTTPDecoderLengthTest.swift b/Tests/NIOHTTP1Tests/HTTPDecoderLengthTest.swift index 7950b761b..c346635a9 100644 --- a/Tests/NIOHTTP1Tests/HTTPDecoderLengthTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPDecoderLengthTest.swift @@ -30,7 +30,7 @@ private class MessageEndHandler: ChannelInboun var seenBody = false var seenHead = false - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { switch self.unwrapInboundIn(data) { case .head: XCTAssertFalse(self.seenHead) @@ -88,7 +88,7 @@ class HTTPDecoderLengthTest: XCTestCase { self.eofMechanism = eofMechanism } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { switch self.unwrapInboundIn(data) { case .head(let h): self.response = h @@ -100,7 +100,7 @@ class HTTPDecoderLengthTest: XCTestCase { } } - func channelInactive(ctx: ChannelHandlerContext) { + func channelInactive(context: ChannelHandlerContext) { if case .channelInactive = self.eofMechanism { XCTAssert(self.receivedEnd, "Received channelInactive before response end!") self.eof = true @@ -109,14 +109,14 @@ class HTTPDecoderLengthTest: XCTestCase { } } - func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { guard case .halfClosure = self.eofMechanism else { XCTFail("Got half closure when not expecting it") return } guard let evt = event as? ChannelEvent, case .inputClosed = evt else { - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) return } diff --git a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift index 741e2b006..acce5be07 100644 --- a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift @@ -193,7 +193,7 @@ class HTTPDecoderTest: XCTestCase { class Receiver: ChannelInboundHandler { typealias InboundIn = HTTPServerRequestPart - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let part = self.unwrapInboundIn(data) switch part { case .head(let h): @@ -236,12 +236,12 @@ class HTTPDecoderTest: XCTestCase { class Receiver: ChannelInboundHandler { typealias InboundIn = HTTPServerRequestPart - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let part = self.unwrapInboundIn(data) switch part { case .end: // ignore - _ = ctx.pipeline.removeHandler(name: "decoder") + _ = context.pipeline.removeHandler(name: "decoder") default: break } @@ -263,17 +263,17 @@ class HTTPDecoderTest: XCTestCase { typealias InboundIn = ByteBuffer var called: Bool = false - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { var buffer = self.unwrapInboundIn(data) XCTAssertEqual("XXXX", buffer.readString(length: buffer.readableBytes)!) self.called = true } - func handlerAdded(ctx: ChannelHandlerContext) { - _ = ctx.pipeline.removeHandler(name: "decoder") + func handlerAdded(context: ChannelHandlerContext) { + _ = context.pipeline.removeHandler(name: "decoder") } - func handlerRemoved(ctx: ChannelHandlerContext) { + func handlerRemoved(context: ChannelHandlerContext) { XCTAssertTrue(self.called) } } @@ -282,12 +282,12 @@ class HTTPDecoderTest: XCTestCase { typealias InboundIn = HTTPServerRequestPart let collector = ByteCollector() - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let part = self.unwrapInboundIn(data) switch part { case .end: - _ = ctx.pipeline.removeHandler(self).flatMap { _ in - ctx.pipeline.addHandler(self.collector) + _ = context.pipeline.removeHandler(self).flatMap { _ in + context.pipeline.addHandler(self.collector) } default: // ignore @@ -315,17 +315,17 @@ class HTTPDecoderTest: XCTestCase { typealias InboundIn = ByteBuffer var called: Bool = false - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { var buffer = self.unwrapInboundIn(data) XCTAssertEqual("XXXX", buffer.readString(length: buffer.readableBytes)!) self.called = true } - func handlerAdded(ctx: ChannelHandlerContext) { - _ = ctx.pipeline.removeHandler(name: "decoder") + func handlerAdded(context: ChannelHandlerContext) { + _ = context.pipeline.removeHandler(name: "decoder") } - func handlerRemoved(ctx: ChannelHandlerContext) { + func handlerRemoved(context: ChannelHandlerContext) { XCTAssert(self.called) } } @@ -335,21 +335,21 @@ class HTTPDecoderTest: XCTestCase { typealias InboundOut = HTTPClientResponsePart typealias OutboundOut = HTTPClientRequestPart - func channelActive(ctx: ChannelHandlerContext) { + func channelActive(context: ChannelHandlerContext) { var upgradeReq = HTTPRequestHead(version: .init(major: 1, minor: 1), method: .GET, uri: "/") upgradeReq.headers.add(name: "Connection", value: "Upgrade") upgradeReq.headers.add(name: "Upgrade", value: "myprot") upgradeReq.headers.add(name: "Host", value: "localhost") - ctx.write(wrapOutboundOut(.head(upgradeReq)), promise: nil) - ctx.writeAndFlush(wrapOutboundOut(.end(nil)), promise: nil) + context.write(wrapOutboundOut(.head(upgradeReq)), promise: nil) + context.writeAndFlush(wrapOutboundOut(.end(nil)), promise: nil) } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let part = self.unwrapInboundIn(data) switch part { case .end: - _ = ctx.pipeline.removeHandler(self).flatMap { _ in - ctx.pipeline.addHandler(ByteCollector()) + _ = context.pipeline.removeHandler(self).flatMap { _ in + context.pipeline.addHandler(ByteCollector()) } break default: diff --git a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift index 35eea9fe8..b9f37a164 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift @@ -47,11 +47,11 @@ internal class ArrayAccumulationHandler: ChannelInboundHandler { } } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { self.receiveds.append(self.unwrapInboundIn(data)) } - public func channelUnregistered(ctx: ChannelHandlerContext) { + public func channelUnregistered(context: ChannelHandlerContext) { self.allDoneBlock.perform() } @@ -109,7 +109,7 @@ class HTTPServerClientTest : XCTestCase { } } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { switch self.unwrapInboundIn(data) { case .head(let req): switch req.uri { @@ -119,60 +119,60 @@ 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) - ctx.write(self.wrapOutboundOut(r), promise: nil) - var b = ctx.channel.allocator.buffer(capacity: replyString.count) + context.write(self.wrapOutboundOut(r), promise: nil) + var b = context.channel.allocator.buffer(capacity: replyString.count) b.writeString(replyString) let outbound = self.outboundBody(b) - ctx.write(self.wrapOutboundOut(outbound.body)).whenComplete { (_: Result) in + context.write(self.wrapOutboundOut(outbound.body)).whenComplete { (_: Result) in outbound.destructor() } - ctx.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 - self.maybeClose(ctx: ctx) + self.maybeClose(context: context) } case "/count-to-ten": var head = HTTPResponseHead(version: req.version, status: .ok) head.headers.add(name: "Connection", value: "close") let r = HTTPServerResponsePart.head(head) - ctx.write(self.wrapOutboundOut(r)).whenFailure { error in + context.write(self.wrapOutboundOut(r)).whenFailure { error in XCTFail("unexpected error \(error)") } - var b = ctx.channel.allocator.buffer(capacity: 1024) + var b = context.channel.allocator.buffer(capacity: 1024) for i in 1...10 { b.clear() b.writeString("\(i)") let outbound = self.outboundBody(b) - ctx.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() } } - ctx.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 - self.maybeClose(ctx: ctx) + self.maybeClose(context: context) } case "/trailers": var head = HTTPResponseHead(version: req.version, status: .ok) head.headers.add(name: "Connection", value: "close") head.headers.add(name: "Transfer-Encoding", value: "chunked") let r = HTTPServerResponsePart.head(head) - ctx.write(self.wrapOutboundOut(r)).whenFailure { error in + context.write(self.wrapOutboundOut(r)).whenFailure { error in XCTFail("unexpected error \(error)") } - var b = ctx.channel.allocator.buffer(capacity: 1024) + var b = context.channel.allocator.buffer(capacity: 1024) for i in 1...10 { b.clear() b.writeString("\(i)") let outbound = self.outboundBody(b) - ctx.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() @@ -182,15 +182,15 @@ class HTTPServerClientTest : XCTestCase { var trailers = HTTPHeaders() trailers.add(name: "X-URL-Path", value: "/trailers") trailers.add(name: "X-Should-Trail", value: "sure") - ctx.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 - self.maybeClose(ctx: ctx) + self.maybeClose(context: context) } case "/massive-response": - var buf = ctx.channel.allocator.buffer(capacity: HTTPServerClientTest.massiveResponseLength) + var buf = context.channel.allocator.buffer(capacity: HTTPServerClientTest.massiveResponseLength) buf.writeWithUnsafeMutableBytes { targetPtr in return HTTPServerClientTest.massiveResponseBytes.withUnsafeBytes { srcPtr in precondition(targetPtr.count >= srcPtr.count) @@ -203,45 +203,45 @@ class HTTPServerClientTest : XCTestCase { head.headers.add(name: "Connection", value: "close") head.headers.add(name: "Content-Length", value: "\(HTTPServerClientTest.massiveResponseLength)") let r = HTTPServerResponsePart.head(head) - ctx.write(self.wrapOutboundOut(r)).whenFailure { error in + context.write(self.wrapOutboundOut(r)).whenFailure { error in XCTFail("unexpected error \(error)") } let outbound = self.outboundBody(buf) - ctx.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() } - ctx.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 - self.maybeClose(ctx: ctx) + self.maybeClose(context: context) } case "/head": var head = HTTPResponseHead(version: req.version, status: .ok) head.headers.add(name: "Connection", value: "close") head.headers.add(name: "Content-Length", value: "5000") - ctx.write(self.wrapOutboundOut(.head(head))).whenFailure { error in + context.write(self.wrapOutboundOut(.head(head))).whenFailure { error in XCTFail("unexpected error \(error)") } - ctx.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 - self.maybeClose(ctx: ctx) + self.maybeClose(context: context) } case "/204": var head = HTTPResponseHead(version: req.version, status: .noContent) head.headers.add(name: "Connection", value: "keep-alive") - ctx.write(self.wrapOutboundOut(.head(head))).whenFailure { error in + context.write(self.wrapOutboundOut(.head(head))).whenFailure { error in XCTFail("unexpected error \(error)") } - ctx.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 - self.maybeClose(ctx: ctx) + self.maybeClose(context: context) } default: XCTFail("received request to unknown URI \(req.uri)") @@ -254,16 +254,16 @@ class HTTPServerClientTest : XCTestCase { } } - public func channelReadComplete(ctx: ChannelHandlerContext) { - ctx.flush() + public func channelReadComplete(context: ChannelHandlerContext) { + context.flush() } // We should only close the connection when the remote peer has sent the entire request // and we have sent our entire response. - private func maybeClose(ctx: ChannelHandlerContext) { + private func maybeClose(context: ChannelHandlerContext) { if sentEnd && seenEnd && self.isOpen { self.isOpen = false - ctx.close().whenFailure { error in + context.close().whenFailure { error in XCTFail("unexpected error \(error)") } } diff --git a/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift b/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift index 0a84c9996..908e289df 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift @@ -43,17 +43,17 @@ private final class ReadRecorder: ChannelInboundHandler { public var reads: [Event] = [] - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { self.reads.append(.channelRead(self.unwrapInboundIn(data))) - ctx.fireChannelRead(data) + context.fireChannelRead(data) } - func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { switch event { case let evt as ChannelEvent where evt == ChannelEvent.inputClosed: self.reads.append(.halfClose) default: - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) } } } @@ -63,10 +63,10 @@ private final class WriteRecorder: ChannelOutboundHandler { public var writes: [HTTPServerResponsePart] = [] - func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { self.writes.append(self.unwrapOutboundIn(data)) - ctx.write(data, promise: promise) + context.write(data, promise: promise) } } @@ -76,9 +76,9 @@ private final class ReadCountingHandler: ChannelOutboundHandler { public var readCount = 0 - func read(ctx: ChannelHandlerContext) { + func read(context: ChannelHandlerContext) { self.readCount += 1 - ctx.read() + context.read() } } @@ -407,7 +407,7 @@ class HTTPServerPipelineHandlerTest: XCTestCase { } var state: State = .req1HeadExpected - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let req = self.unwrapInboundIn(data) switch req { case .head(let head): @@ -431,11 +431,11 @@ class HTTPServerPipelineHandlerTest: XCTestCase { default: XCTFail("didn't expect \(head)") } - ctx.write(self.wrapOutboundOut(.head(HTTPResponseHead(version: .init(major: 1, minor: 1), status: .ok))), promise: nil) + context.write(self.wrapOutboundOut(.head(HTTPResponseHead(version: .init(major: 1, minor: 1), status: .ok))), promise: nil) if sendEnd { - ctx.write(self.wrapOutboundOut(.end(nil)), promise: nil) + context.write(self.wrapOutboundOut(.end(nil)), promise: nil) } - ctx.flush() + context.flush() case .end: switch self.state { case .req1EndExpected: @@ -444,8 +444,8 @@ class HTTPServerPipelineHandlerTest: XCTestCase { self.state = .req3HeadExpected // this will cause `channelRead` to be recursively called and we need to make sure everything then still works - try! (ctx.channel as! EmbeddedChannel).writeInbound(HTTPServerRequestPart.head(HTTPRequestHead(version: .init(major: 1, minor: 1), method: .GET, uri: "/req_boom"))) - try! (ctx.channel as! EmbeddedChannel).writeInbound(HTTPServerRequestPart.end(nil)) + try! (context.channel as! EmbeddedChannel).writeInbound(HTTPServerRequestPart.head(HTTPRequestHead(version: .init(major: 1, minor: 1), method: .GET, uri: "/req_boom"))) + try! (context.channel as! EmbeddedChannel).writeInbound(HTTPServerRequestPart.end(nil)) case .req3EndExpected: self.state = .reqBoomHeadExpected case .reqBoomEndExpected: @@ -718,13 +718,13 @@ class HTTPServerPipelineHandlerTest: XCTestCase { } var state: State = .errorExpected - func errorCaught(ctx: ChannelHandlerContext, error: Error) { + func errorCaught(context: ChannelHandlerContext, error: Error) { XCTAssertEqual(HTTPParserError.headerOverflow, error as? HTTPParserError) XCTAssertEqual(.errorExpected, self.state) self.state = .done } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTFail("no requests expected") } } @@ -757,19 +757,19 @@ class HTTPServerPipelineHandlerTest: XCTestCase { } var state: State = .reqHeadExpected - func errorCaught(ctx: ChannelHandlerContext, error: Error) { + func errorCaught(context: ChannelHandlerContext, error: Error) { XCTAssertEqual(HTTPParserError.closedConnection, error as? HTTPParserError) XCTAssertEqual(.errorExpected, self.state) self.state = .done } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { 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. - ctx.eventLoop.execute { - ctx.writeAndFlush(self.wrapOutboundOut(.head(.init(version: HTTPVersion(major: 1, minor: 1), + context.eventLoop.execute { + context.writeAndFlush(self.wrapOutboundOut(.head(.init(version: HTTPVersion(major: 1, minor: 1), status: .ok))), promise: nil) } @@ -780,8 +780,8 @@ class HTTPServerPipelineHandlerTest: XCTestCase { case .end: // 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. - ctx.eventLoop.execute { - ctx.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + context.eventLoop.execute { + 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 3d2c58eb7..2e12dca5f 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerProtocolErrorHandlerTest.swift @@ -94,7 +94,7 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase { private var nextExpected: NextExpectedState = .head - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let req = self.unwrapInboundIn(data) switch req { case .head: @@ -103,7 +103,7 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase { let res = HTTPServerResponsePart.head(.init(version: HTTPVersion(major: 1, minor: 1), status: .ok, headers: .init([("Content-Length", "0")]))) - ctx.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/HTTPTest.swift b/Tests/NIOHTTP1Tests/HTTPTest.swift index 70bf3f424..aea3b2675 100644 --- a/Tests/NIOHTTP1Tests/HTTPTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPTest.swift @@ -26,8 +26,8 @@ private final class TestChannelInboundHandler: ChannelInboundHandler { self.body = body } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { - ctx.fireChannelRead(self.wrapInboundOut(self.body(self.unwrapInboundIn(data)))) + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { + context.fireChannelRead(self.wrapInboundOut(self.body(self.unwrapInboundIn(data)))) } } diff --git a/Tests/NIOHTTP1Tests/HTTPUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPUpgradeTests.swift index 5f055da9a..42e542ec6 100644 --- a/Tests/NIOHTTP1Tests/HTTPUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPUpgradeTests.swift @@ -101,7 +101,7 @@ private class SingleHTTPResponseAccumulator: ChannelInboundHandler { self.allDoneBlock = completion } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let buffer = self.unwrapInboundIn(data) self.receiveds.append(buffer) if let finalBytes = buffer.getBytes(at: buffer.writerIndex - 4, length: 4), finalBytes == [0x0D, 0x0A, 0x0D, 0x0A] { @@ -113,7 +113,7 @@ private class SingleHTTPResponseAccumulator: ChannelInboundHandler { private class ExplodingHandler: ChannelInboundHandler { typealias InboundIn = Any - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTFail("Received unexpected read") } } @@ -180,9 +180,9 @@ private class ExplodingUpgrader: HTTPServerProtocolUpgrader { throw Explosion.KABOOM } - public func upgrade(ctx: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { + public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { XCTFail("upgrade called") - return ctx.eventLoop.makeSucceededFuture(()) + return context.eventLoop.makeSucceededFuture(()) } } @@ -202,9 +202,9 @@ private class UpgraderSaysNo: HTTPServerProtocolUpgrader { throw No.no } - public func upgrade(ctx: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { + public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { XCTFail("upgrade called") - return ctx.eventLoop.makeSucceededFuture(()) + return context.eventLoop.makeSucceededFuture(()) } } @@ -225,9 +225,9 @@ private class SuccessfulUpgrader: HTTPServerProtocolUpgrader { return headers } - public func upgrade(ctx: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { + public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { self.onUpgradeComplete(upgradeRequest) - return ctx.eventLoop.makeSucceededFuture(()) + return context.eventLoop.makeSucceededFuture(()) } } @@ -236,7 +236,7 @@ private class UpgradeDelayer: HTTPServerProtocolUpgrader { let requiredUpgradeHeaders: [String] = [] private var upgradePromise: EventLoopPromise? - private var ctx: ChannelHandlerContext? + private var context: ChannelHandlerContext? public init(forProtocol `protocol`: String) { self.supportedProtocol = `protocol` @@ -248,9 +248,9 @@ private class UpgradeDelayer: HTTPServerProtocolUpgrader { return headers } - public func upgrade(ctx: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { - self.upgradePromise = ctx.eventLoop.makePromise() - self.ctx = ctx + public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { + self.upgradePromise = context.eventLoop.makePromise() + self.context = context return self.upgradePromise!.futureResult } @@ -263,9 +263,9 @@ private class UserEventSaver: ChannelInboundHandler { public typealias InboundIn = Any public var events: [EventType] = [] - public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { events.append(event as! EventType) - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) } } @@ -274,9 +274,9 @@ private class ErrorSaver: ChannelInboundHandler { public typealias InboundOut = Any public var errors: [Error] = [] - public func errorCaught(ctx: ChannelHandlerContext, error: Error) { + public func errorCaught(context: ChannelHandlerContext, error: Error) { errors.append(error) - ctx.fireErrorCaught(error) + context.fireErrorCaught(error) } } @@ -284,7 +284,7 @@ private class DataRecorder: ChannelInboundHandler { public typealias InboundIn = T private var data: [T] = [] - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let datum = self.unwrapInboundIn(data) self.data.append(datum) } @@ -382,13 +382,13 @@ class HTTPUpgradeTestCase: XCTestCase { } let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader], - extraHandlers: []) { (ctx) in + extraHandlers: []) { (context) in // This is called before the upgrader gets called. XCTAssertNil(upgradeRequest) upgradeHandlerCbFired = true // We're closing the connection now. - ctx.close(promise: nil) + context.close(promise: nil) } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) @@ -487,13 +487,13 @@ class HTTPUpgradeTestCase: XCTestCase { } let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [explodingUpgrader, successfulUpgrader], - extraHandlers: []) { ctx in + extraHandlers: []) { context in // This is called before the upgrader gets called. XCTAssertNil(upgradeRequest) upgradeHandlerCbFired = true // We're closing the connection now. - ctx.close(promise: nil) + context.close(promise: nil) } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) @@ -535,9 +535,9 @@ class HTTPUpgradeTestCase: XCTestCase { } let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader], - extraHandlers: [eventSaver]) { ctx in + extraHandlers: [eventSaver]) { context in XCTAssertEqual(eventSaver.events.count, 0) - ctx.close(promise: nil) + context.close(promise: nil) } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) @@ -592,13 +592,13 @@ class HTTPUpgradeTestCase: XCTestCase { let errorCatcher = ErrorSaver() let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [explodingUpgrader, successfulUpgrader], - extraHandlers: [errorCatcher]) { ctx in + extraHandlers: [errorCatcher]) { context in // This is called before the upgrader gets called. XCTAssertNil(upgradeRequest) upgradeHandlerCbFired = true // We're closing the connection now. - ctx.close(promise: nil) + context.close(promise: nil) } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) @@ -643,8 +643,8 @@ class HTTPUpgradeTestCase: XCTestCase { func testUpgradeIsCaseInsensitive() throws { let upgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: ["WeIrDcAsE"]) { req in } let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader], - extraHandlers: []) { ctx in - ctx.close(promise: nil) + extraHandlers: []) { context in + context.close(promise: nil) } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) @@ -677,7 +677,7 @@ class HTTPUpgradeTestCase: XCTestCase { let upgrader = UpgradeDelayer(forProtocol: "myproto") let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader], - extraHandlers: []) { ctx in + extraHandlers: []) { context in g.leave() } defer { @@ -720,7 +720,7 @@ class HTTPUpgradeTestCase: XCTestCase { let upgrader = UpgradeDelayer(forProtocol: "myproto") let dataRecorder = DataRecorder() - let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader], extraHandlers: [dataRecorder]) { ctx in + let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader], extraHandlers: [dataRecorder]) { context in g.leave() } defer { @@ -770,7 +770,7 @@ class HTTPUpgradeTestCase: XCTestCase { let upgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: []) { req in } let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(pipelining: true, upgraders: [upgrader], - extraHandlers: []) { ctx in } + extraHandlers: []) { context in } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } @@ -825,12 +825,12 @@ class HTTPUpgradeTestCase: XCTestCase { self.allDonePromise = allDonePromise } - func handlerAdded(ctx: ChannelHandlerContext) { + func handlerAdded(context: ChannelHandlerContext) { XCTAssertEqual(.fresh, self.state) self.state = .added } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let buf = self.unwrapInboundIn(data) XCTAssertEqual(1, buf.readableBytes) let stringRead = buf.getString(at: 0, length: buf.readableBytes) @@ -846,7 +846,7 @@ class HTTPUpgradeTestCase: XCTestCase { case .inlineDataRead: XCTAssertEqual("B", stringRead) self.state = .extraDataRead - ctx.channel.close(promise: nil) + context.channel.close(promise: nil) if stringRead == .some("B") { self.secondByteDonePromise.succeed(()) } else { @@ -857,10 +857,10 @@ class HTTPUpgradeTestCase: XCTestCase { } } - func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { + func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { XCTAssertEqual(.extraDataRead, self.state) self.state = .closed - ctx.close(mode: mode, promise: promise) + context.close(mode: mode, promise: promise) self.allDonePromise.succeed(()) } @@ -880,12 +880,12 @@ class HTTPUpgradeTestCase: XCTestCase { let secondByteDonePromise = promiseGroup.next().makePromise(of: Void.self) let allDonePromise = promiseGroup.next().makePromise(of: Void.self) let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader], - extraHandlers: []) { (ctx) in + extraHandlers: []) { (context) in // This is called before the upgrader gets called. XCTAssertNil(upgradeRequest) upgradeHandlerCbFired = true - _ = ctx.channel.pipeline.addHandler(CheckWeReadInlineAndExtraData(firstByteDonePromise: firstByteDonePromise, + _ = context.channel.pipeline.addHandler(CheckWeReadInlineAndExtraData(firstByteDonePromise: firstByteDonePromise, secondByteDonePromise: secondByteDonePromise, allDonePromise: allDonePromise)) } diff --git a/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift index 64f575eba..66d30cf56 100644 --- a/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift +++ b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift @@ -24,7 +24,7 @@ private class ReadCompletedHandler: ChannelInboundHandler { readCompleteCount = 0 } - public func channelReadComplete(ctx: ChannelHandlerContext) { + public func channelReadComplete(context: ChannelHandlerContext) { readCompleteCount += 1 } } diff --git a/Tests/NIOTests/AcceptBackoffHandlerTest.swift b/Tests/NIOTests/AcceptBackoffHandlerTest.swift index 191ff0256..e041077a3 100644 --- a/Tests/NIOTests/AcceptBackoffHandlerTest.swift +++ b/Tests/NIOTests/AcceptBackoffHandlerTest.swift @@ -159,7 +159,7 @@ public class AcceptBackoffHandlerTest: XCTestCase { self.promise = promise } - public func channelInactive(ctx: ChannelHandlerContext) { + public func channelInactive(context: ChannelHandlerContext) { promise.succeed(()) } @@ -239,9 +239,9 @@ public class AcceptBackoffHandlerTest: XCTestCase { var readCount = 0 - func read(ctx: ChannelHandlerContext) { + func read(context: ChannelHandlerContext) { readCount += 1 - ctx.read() + context.read() } } diff --git a/Tests/NIOTests/ChannelNotificationTest.swift b/Tests/NIOTests/ChannelNotificationTest.swift index db01e4d39..bd0eee260 100644 --- a/Tests/NIOTests/ChannelNotificationTest.swift +++ b/Tests/NIOTests/ChannelNotificationTest.swift @@ -35,88 +35,88 @@ class ChannelNotificationTest: XCTestCase { private var closePromise: EventLoopPromise? - public func channelActive(ctx: ChannelHandlerContext) { - XCTAssertTrue(ctx.channel.isActive) + public func channelActive(context: ChannelHandlerContext) { + XCTAssertTrue(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelActive", setter: "register") assertFulfilled(promise: self.connectPromise, promiseName: "connectPromise", trigger: "channelActive", setter: "connect") XCTAssertNil(self.closePromise) - XCTAssertFalse(ctx.channel.closeFuture.isFulfilled) + XCTAssertFalse(context.channel.closeFuture.isFulfilled) } - public func channelInactive(ctx: ChannelHandlerContext) { - XCTAssertFalse(ctx.channel.isActive) + public func channelInactive(context: ChannelHandlerContext) { + XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelInactive", setter: "register") assertFulfilled(promise: self.connectPromise, promiseName: "connectPromise", trigger: "channelInactive", setter: "connect") assertFulfilled(promise: self.closePromise, promiseName: "closePromise", trigger: "channelInactive", setter: "close") - XCTAssertFalse(ctx.channel.closeFuture.isFulfilled) + XCTAssertFalse(context.channel.closeFuture.isFulfilled) } - public func channelRegistered(ctx: ChannelHandlerContext) { - XCTAssertFalse(ctx.channel.isActive) + public func channelRegistered(context: ChannelHandlerContext) { + XCTAssertFalse(context.channel.isActive) XCTAssertNil(self.connectPromise) XCTAssertNil(self.closePromise) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelRegistered", setter: "register") - XCTAssertFalse(ctx.channel.closeFuture.isFulfilled) + XCTAssertFalse(context.channel.closeFuture.isFulfilled) } - public func channelUnregistered(ctx: ChannelHandlerContext) { - XCTAssertFalse(ctx.channel.isActive) + public func channelUnregistered(context: ChannelHandlerContext) { + XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelInactive", setter: "register") assertFulfilled(promise: self.connectPromise, promiseName: "connectPromise", trigger: "channelInactive", setter: "connect") assertFulfilled(promise: self.closePromise, promiseName: "closePromise", trigger: "channelInactive", setter: "close") - XCTAssertFalse(ctx.channel.closeFuture.isFulfilled) + XCTAssertFalse(context.channel.closeFuture.isFulfilled) } - public func register(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { + public func register(context: ChannelHandlerContext, promise: EventLoopPromise?) { XCTAssertNil(self.registerPromise) XCTAssertNil(self.connectPromise) XCTAssertNil(self.closePromise) promise!.futureResult.whenSuccess { - XCTAssertFalse(ctx.channel.isActive) + XCTAssertFalse(context.channel.isActive) } self.registerPromise = promise - ctx.register(promise: promise) + context.register(promise: promise) } - public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + public func bind(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { XCTFail("bind(...) should not be called") - ctx.bind(to: address, promise: promise) + context.bind(to: address, promise: promise) } - public func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + public func connect(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { XCTAssertNotNil(self.registerPromise) XCTAssertNil(self.connectPromise) XCTAssertNil(self.closePromise) promise!.futureResult.whenSuccess { - XCTAssertTrue(ctx.channel.isActive) + XCTAssertTrue(context.channel.isActive) } self.connectPromise = promise - ctx.connect(to: address, promise: promise) + context.connect(to: address, promise: promise) } - public func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { + public func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { XCTAssertNotNil(self.registerPromise) XCTAssertNotNil(self.connectPromise) XCTAssertNil(self.closePromise) promise!.futureResult.whenSuccess { - XCTAssertFalse(ctx.channel.isActive) + XCTAssertFalse(context.channel.isActive) } self.closePromise = promise - ctx.close(mode: mode, promise: promise) + context.close(mode: mode, promise: promise) } } @@ -131,65 +131,65 @@ class ChannelNotificationTest: XCTestCase { self.activeChannelPromise = activeChannelPromise } - public func channelActive(ctx: ChannelHandlerContext) { - XCTAssertTrue(ctx.channel.isActive) + public func channelActive(context: ChannelHandlerContext) { + XCTAssertTrue(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelActive", setter: "register") - XCTAssertFalse(ctx.channel.closeFuture.isFulfilled) + XCTAssertFalse(context.channel.closeFuture.isFulfilled) XCTAssertFalse(self.activeChannelPromise.futureResult.isFulfilled) - self.activeChannelPromise.succeed(ctx.channel) + self.activeChannelPromise.succeed(context.channel) } - public func channelInactive(ctx: ChannelHandlerContext) { - XCTAssertFalse(ctx.channel.isActive) + public func channelInactive(context: ChannelHandlerContext) { + XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelInactive", setter: "register") - XCTAssertFalse(ctx.channel.closeFuture.isFulfilled) + XCTAssertFalse(context.channel.closeFuture.isFulfilled) } - public func channelRegistered(ctx: ChannelHandlerContext) { - XCTAssertFalse(ctx.channel.isActive) + public func channelRegistered(context: ChannelHandlerContext) { + XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelRegistered", setter: "register") - XCTAssertFalse(ctx.channel.closeFuture.isFulfilled) + XCTAssertFalse(context.channel.closeFuture.isFulfilled) } - public func channelUnregistered(ctx: ChannelHandlerContext) { - XCTAssertFalse(ctx.channel.isActive) + public func channelUnregistered(context: ChannelHandlerContext) { + XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelUnregistered", setter: "register") - XCTAssertFalse(ctx.channel.closeFuture.isFulfilled) + XCTAssertFalse(context.channel.closeFuture.isFulfilled) } - public func register(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { + public func register(context: ChannelHandlerContext, promise: EventLoopPromise?) { XCTAssertNil(self.registerPromise) - let p = promise ?? ctx.eventLoop.makePromise() + let p = promise ?? context.eventLoop.makePromise() p.futureResult.whenSuccess { - XCTAssertFalse(ctx.channel.isActive) + XCTAssertFalse(context.channel.isActive) } self.registerPromise = p - ctx.register(promise: p) + context.register(promise: p) } - public func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + public func connect(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { XCTFail("connect(...) should not be called") - ctx.connect(to: address, promise: promise) + context.connect(to: address, promise: promise) } - public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + public func bind(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { XCTFail("bind(...) should not be called") - ctx.bind(to: address, promise: promise) + context.bind(to: address, promise: promise) } - public func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { + public func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { XCTFail("close(...) should not be called") - ctx.close(mode: mode, promise: promise) + context.close(mode: mode, promise: promise) } } @@ -202,86 +202,86 @@ class ChannelNotificationTest: XCTestCase { private var closePromise: EventLoopPromise? - public func channelActive(ctx: ChannelHandlerContext) { - XCTAssertTrue(ctx.channel.isActive) + public func channelActive(context: ChannelHandlerContext) { + XCTAssertTrue(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelActive", setter: "register") XCTAssertNil(self.closePromise) - XCTAssertFalse(ctx.channel.closeFuture.isFulfilled) + XCTAssertFalse(context.channel.closeFuture.isFulfilled) } - public func channelInactive(ctx: ChannelHandlerContext) { - XCTAssertFalse(ctx.channel.isActive) + public func channelInactive(context: ChannelHandlerContext) { + XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelInactive", setter: "register") assertFulfilled(promise: self.closePromise, promiseName: "closePromise", trigger: "channelInactive", setter: "close") - XCTAssertFalse(ctx.channel.closeFuture.isFulfilled) + XCTAssertFalse(context.channel.closeFuture.isFulfilled) } - public func channelRegistered(ctx: ChannelHandlerContext) { - XCTAssertFalse(ctx.channel.isActive) + public func channelRegistered(context: ChannelHandlerContext) { + XCTAssertFalse(context.channel.isActive) XCTAssertNil(closePromise) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelRegistered", setter: "register") - XCTAssertFalse(ctx.channel.closeFuture.isFulfilled) + XCTAssertFalse(context.channel.closeFuture.isFulfilled) } - public func channelUnregistered(ctx: ChannelHandlerContext) { - XCTAssertFalse(ctx.channel.isActive) + public func channelUnregistered(context: ChannelHandlerContext) { + XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelUnregistered", setter: "register") assertFulfilled(promise: self.closePromise, promiseName: "closePromise", trigger: "channelInactive", setter: "close") - XCTAssertFalse(ctx.channel.closeFuture.isFulfilled) + XCTAssertFalse(context.channel.closeFuture.isFulfilled) } - public func register(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { + public func register(context: ChannelHandlerContext, promise: EventLoopPromise?) { XCTAssertNil(self.registerPromise) XCTAssertNil(self.bindPromise) XCTAssertNil(self.closePromise) - let p = promise ?? ctx.eventLoop.makePromise() + let p = promise ?? context.eventLoop.makePromise() p.futureResult.whenSuccess { - XCTAssertFalse(ctx.channel.isActive) + XCTAssertFalse(context.channel.isActive) } self.registerPromise = p - ctx.register(promise: p) + context.register(promise: p) } - public func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + public func connect(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { XCTFail("connect(...) should not be called") - ctx.connect(to: address, promise: promise) + context.connect(to: address, promise: promise) } - public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + public func bind(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { XCTAssertNotNil(self.registerPromise) XCTAssertNil(self.bindPromise) XCTAssertNil(self.closePromise) promise?.futureResult.whenSuccess { - XCTAssertTrue(ctx.channel.isActive) + XCTAssertTrue(context.channel.isActive) } self.bindPromise = promise - ctx.bind(to: address, promise: promise) + context.bind(to: address, promise: promise) } - public func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { + public func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { XCTAssertNotNil(self.registerPromise) XCTAssertNotNil(self.bindPromise) XCTAssertNil(self.closePromise) - let p = promise ?? ctx.eventLoop.makePromise() + let p = promise ?? context.eventLoop.makePromise() p.futureResult.whenSuccess { - XCTAssertFalse(ctx.channel.isActive) + XCTAssertFalse(context.channel.isActive) } self.closePromise = p - ctx.close(mode: mode, promise: p) + context.close(mode: mode, promise: p) } } @@ -351,22 +351,22 @@ class ChannelNotificationTest: XCTestCase { self.promise = promise } - public func channelActive(ctx: ChannelHandlerContext) { + public func channelActive(context: ChannelHandlerContext) { XCTAssertEqual(.`init`, state) state = .active } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTAssertEqual(.active, state) state = .read } - public func channelReadComplete(ctx: ChannelHandlerContext) { + public func channelReadComplete(context: ChannelHandlerContext) { XCTAssertTrue(.read == state || .readComplete == state, "State should either be .read or .readComplete but was \(state)") state = .readComplete } - public func channelInactive(ctx: ChannelHandlerContext) { + public func channelInactive(context: ChannelHandlerContext) { XCTAssertEqual(.readComplete, state) state = .inactive diff --git a/Tests/NIOTests/ChannelPipelineTest.swift b/Tests/NIOTests/ChannelPipelineTest.swift index 23a0ecaea..cdac6f738 100644 --- a/Tests/NIOTests/ChannelPipelineTest.swift +++ b/Tests/NIOTests/ChannelPipelineTest.swift @@ -28,16 +28,16 @@ private final class IndexWritingHandler: ChannelDuplexHandler { self.index = index } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { var buf = self.unwrapInboundIn(data) buf.writeInteger(UInt8(self.index)) - ctx.fireChannelRead(self.wrapInboundOut(buf)) + context.fireChannelRead(self.wrapInboundOut(buf)) } - func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { var buf = self.unwrapOutboundIn(data) buf.writeInteger(UInt8(self.index)) - ctx.write(self.wrapOutboundOut(buf), promise: promise) + context.write(self.wrapOutboundOut(buf), promise: promise) } } @@ -85,11 +85,11 @@ class ChannelPipelineTest: XCTestCase { let handlerAddedCalled = Atomic(value: false) let handlerRemovedCalled = Atomic(value: false) - public func handlerAdded(ctx: ChannelHandlerContext) { + public func handlerAdded(context: ChannelHandlerContext) { handlerAddedCalled.store(true) } - public func handlerRemoved(ctx: ChannelHandlerContext) { + public func handlerRemoved(context: ChannelHandlerContext) { handlerRemovedCalled.store(true) } } @@ -149,9 +149,9 @@ class ChannelPipelineTest: XCTestCase { self.body = body } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { do { - ctx.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) } @@ -166,7 +166,7 @@ class ChannelPipelineTest: XCTestCase { case CalledBind } - public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + public func bind(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { promise!.fail(TestFailureError.CalledBind) } } @@ -175,8 +175,8 @@ class ChannelPipelineTest: XCTestCase { typealias InboundIn = Never typealias InboundOut = Int - public func handlerRemoved(ctx: ChannelHandlerContext) { - ctx.fireChannelRead(self.wrapInboundOut(1)) + public func handlerRemoved(context: ChannelHandlerContext) { + context.fireChannelRead(self.wrapInboundOut(1)) } } @@ -234,9 +234,9 @@ class ChannelPipelineTest: XCTestCase { self.no = number } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let data = self.unwrapInboundIn(data) - ctx.fireChannelRead(self.wrapInboundOut(data + [self.no])) + context.fireChannelRead(self.wrapInboundOut(data + [self.no])) } } @@ -251,9 +251,9 @@ class ChannelPipelineTest: XCTestCase { self.no = number } - func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { let data = self.unwrapOutboundIn(data) - ctx.write(self.wrapOutboundOut(data + [self.no]), promise: promise) + context.write(self.wrapOutboundOut(data + [self.no]), promise: promise) } } @@ -263,10 +263,10 @@ class ChannelPipelineTest: XCTestCase { typealias InboundOut = [Int] typealias OutboundOut = [Int] - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let data = self.unwrapInboundIn(data) - ctx.writeAndFlush(self.wrapOutboundOut(data.map { $0 * -1 }), promise: nil) - ctx.fireChannelRead(self.wrapInboundOut(data)) + context.writeAndFlush(self.wrapOutboundOut(data.map { $0 * -1 }), promise: nil) + context.fireChannelRead(self.wrapInboundOut(data)) } } @@ -275,11 +275,11 @@ class ChannelPipelineTest: XCTestCase { typealias OutboundIn = [Int] typealias OutboundOut = ByteBuffer - func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { let data = self.unwrapOutboundIn(data) - var buf = ctx.channel.allocator.buffer(capacity: 123) + var buf = context.channel.allocator.buffer(capacity: 123) buf.writeString(String(describing: data)) - ctx.write(self.wrapOutboundOut(buf), promise: promise) + context.write(self.wrapOutboundOut(buf), promise: promise) } } @@ -339,8 +339,8 @@ class ChannelPipelineTest: XCTestCase { self.body = body } - func handlerAdded(ctx: ChannelHandlerContext) { - self.body(ctx) + func handlerAdded(context: ChannelHandlerContext) { + self.body(context) } } try { @@ -355,12 +355,12 @@ class ChannelPipelineTest: XCTestCase { () /* needed because Swift's grammar is so ambiguous that you can't remove this :\ */ try { - let handler1 = SomeHandler { ctx in - weakHandlerContext1 = ctx + let handler1 = SomeHandler { context in + weakHandlerContext1 = context } weakHandler1 = handler1 - let handler2 = SomeHandler { ctx in - weakHandlerContext2 = ctx + let handler2 = SomeHandler { context in + weakHandlerContext2 = context } weakHandler2 = handler2 XCTAssertNoThrow(try channel.pipeline.addHandler(handler1).flatMap { @@ -397,7 +397,7 @@ class ChannelPipelineTest: XCTestCase { var intReadCount = 0 - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { if data.tryAs(type: Int.self) != nil { self.intReadCount += 1 } @@ -408,9 +408,9 @@ class ChannelPipelineTest: XCTestCase { typealias InboundIn = String typealias InboundOut = Int - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { if let dataString = data.tryAs(type: String.self) { - ctx.fireChannelRead(self.wrapInboundOut(dataString.count)) + context.fireChannelRead(self.wrapInboundOut(dataString.count)) } } } @@ -419,9 +419,9 @@ class ChannelPipelineTest: XCTestCase { typealias InboundIn = ByteBuffer typealias InboundOut = String - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { if var buffer = data.tryAs(type: ByteBuffer.self) { - ctx.fireChannelRead(self.wrapInboundOut(buffer.readString(length: buffer.readableBytes)!)) + context.fireChannelRead(self.wrapInboundOut(buffer.readString(length: buffer.readableBytes)!)) } } } @@ -710,7 +710,7 @@ class ChannelPipelineTest: XCTestCase { XCTAssertNil(channel.readOutbound()) XCTAssertNoThrow(try channel.throwIfErrorCaught()) - channel.pipeline.removeHandler(ctx: context, promise: removalPromise) + channel.pipeline.removeHandler(context: context, promise: removalPromise) XCTAssertNoThrow(try removalPromise.futureResult.wait()) guard case .some(.byteBuffer(let receivedBuffer)) = channel.readOutbound(as: IOData.self) else { @@ -750,7 +750,7 @@ class ChannelPipelineTest: XCTestCase { XCTAssertNil(channel.readOutbound()) XCTAssertNoThrow(try channel.throwIfErrorCaught()) - channel.pipeline.removeHandler(ctx: context).whenSuccess { + channel.pipeline.removeHandler(context: context).whenSuccess { context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) } @@ -907,8 +907,8 @@ class ChannelPipelineTest: XCTestCase { typealias InboundIn = () typealias InboundOut = () - func channelInactive(ctx: ChannelHandlerContext) { - ctx.fireChannelRead(self.wrapInboundOut(())) + func channelInactive(context: ChannelHandlerContext) { + context.fireChannelRead(self.wrapInboundOut(())) } } let handler = FireWhenInactiveHandler() @@ -942,11 +942,11 @@ class ChannelPipelineTest: XCTestCase { self.handlerRemovedPromise = handlerRemovedPromise } - func handlerRemoved(ctx: ChannelHandlerContext) { + func handlerRemoved(context: ChannelHandlerContext) { self.handlerRemovedPromise.succeed(()) } - func removeHandler(ctx: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { + func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { self.removalTokenPromise.succeed(removalToken) } } @@ -964,7 +964,7 @@ class ChannelPipelineTest: XCTestCase { // let's trigger the removal process XCTAssertNoThrow(try channel.pipeline.context(handlerType: NeverCompleteRemovalHandler.self).map { handler in - channel.pipeline.removeHandler(ctx: handler, promise: nil) + channel.pipeline.removeHandler(context: handler, promise: nil) }.wait()) XCTAssertNoThrow(try removalTokenPromise.futureResult.map { removalToken in @@ -986,16 +986,16 @@ class ChannelPipelineTest: XCTestCase { var removeHandlerCalled = false var withinRemoveHandler = false - func removeHandler(ctx: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { + func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { self.removeHandlerCalled = true self.withinRemoveHandler = true defer { self.withinRemoveHandler = false } - ctx.leavePipeline(removalToken: removalToken) + context.leavePipeline(removalToken: removalToken) } - func handlerRemoved(ctx: ChannelHandlerContext) { + func handlerRemoved(context: ChannelHandlerContext) { XCTAssertTrue(self.removeHandlerCalled) XCTAssertTrue(self.withinRemoveHandler) } @@ -1011,7 +1011,7 @@ class ChannelPipelineTest: XCTestCase { XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "the first one to remove").wait()) XCTAssertNoThrow(try channel.pipeline.removeHandler(allHandlers[1]).wait()) - XCTAssertNoThrow(try channel.pipeline.removeHandler(ctx: lastContext).wait()) + XCTAssertNoThrow(try channel.pipeline.removeHandler(context: lastContext).wait()) allHandlers.forEach { XCTAssertTrue($0.removeHandlerCalled) @@ -1038,7 +1038,7 @@ class ChannelPipelineTest: XCTestCase { XCTFail("unexpected error: \(error)") } } - XCTAssertThrowsError(try channel.pipeline.removeHandler(ctx: lastContext).wait()) { error in + XCTAssertThrowsError(try channel.pipeline.removeHandler(context: lastContext).wait()) { error in if let error = error as? ChannelError { XCTAssertEqual(ChannelError.unremovableHandler, error) } else { @@ -1084,9 +1084,9 @@ final class TestAddMultipleHandlersHandlerWorkingAroundSR9956: ChannelDuplexHand init() {} - func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { TestAddMultipleHandlersHandlerWorkingAroundSR9956.allHandlers.append(self) - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) } public static func == (lhs: TestAddMultipleHandlersHandlerWorkingAroundSR9956, diff --git a/Tests/NIOTests/ChannelTests.swift b/Tests/NIOTests/ChannelTests.swift index b480eeaa8..b8f564d9f 100644 --- a/Tests/NIOTests/ChannelTests.swift +++ b/Tests/NIOTests/ChannelTests.swift @@ -40,32 +40,32 @@ class ChannelLifecycleHandler: ChannelInboundHandler { stateHistory.append(state) } - public func channelRegistered(ctx: ChannelHandlerContext) { + public func channelRegistered(context: ChannelHandlerContext) { XCTAssertEqual(currentState, .unregistered) - XCTAssertFalse(ctx.channel.isActive) + XCTAssertFalse(context.channel.isActive) updateState(.registered) - ctx.fireChannelRegistered() + context.fireChannelRegistered() } - public func channelActive(ctx: ChannelHandlerContext) { + public func channelActive(context: ChannelHandlerContext) { XCTAssertEqual(currentState, .registered) - XCTAssertTrue(ctx.channel.isActive) + XCTAssertTrue(context.channel.isActive) updateState(.active) - ctx.fireChannelActive() + context.fireChannelActive() } - public func channelInactive(ctx: ChannelHandlerContext) { + public func channelInactive(context: ChannelHandlerContext) { XCTAssertEqual(currentState, .active) - XCTAssertFalse(ctx.channel.isActive) + XCTAssertFalse(context.channel.isActive) updateState(.inactive) - ctx.fireChannelInactive() + context.fireChannelInactive() } - public func channelUnregistered(ctx: ChannelHandlerContext) { + public func channelUnregistered(context: ChannelHandlerContext) { XCTAssertEqual(currentState, .inactive) - XCTAssertFalse(ctx.channel.isActive) + XCTAssertFalse(context.channel.isActive) updateState(.unregistered) - ctx.fireChannelUnregistered() + context.fireChannelUnregistered() } } @@ -1173,7 +1173,7 @@ public class ChannelTests: XCTestCase { class VerifyNoReadHandler : ChannelInboundHandler { typealias InboundIn = ByteBuffer - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTFail("Received data: \(data)") } } @@ -1279,7 +1279,7 @@ public class ChannelTests: XCTestCase { self.shutdownEvent = shutdownEvent } - public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { switch event { case let ev as ChannelEvent: switch ev { @@ -1301,7 +1301,7 @@ public class ChannelTests: XCTestCase { fallthrough default: - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) } } @@ -1310,7 +1310,7 @@ public class ChannelTests: XCTestCase { try! promise.futureResult.wait() } - public func channelInactive(ctx: ChannelHandlerContext) { + public func channelInactive(context: ChannelHandlerContext) { switch shutdownEvent { case .input: XCTAssertTrue(inputShutdownEventReceived) @@ -1357,8 +1357,8 @@ public class ChannelTests: XCTestCase { self.promise = promise } - func channelRegistered(ctx: ChannelHandlerContext) { - self.promise.succeed(ctx.channel.pipeline) + func channelRegistered(context: ChannelHandlerContext) { + self.promise.succeed(context.channel.pipeline) } } weak var weakClientChannel: Channel? = nil @@ -1467,10 +1467,10 @@ public class ChannelTests: XCTestCase { class AddressVerificationHandler : ChannelInboundHandler { typealias InboundIn = Never - public func channelActive(ctx: ChannelHandlerContext) { - XCTAssertNotNil(ctx.channel.localAddress) - XCTAssertNotNil(ctx.channel.remoteAddress) - ctx.channel.close(promise: nil) + public func channelActive(context: ChannelHandlerContext) { + XCTAssertNotNil(context.channel.localAddress) + XCTAssertNotNil(context.channel.remoteAddress) + context.channel.close(promise: nil) } } @@ -1496,13 +1496,13 @@ public class ChannelTests: XCTestCase { typealias OutboundOut = Any public var reads = 0 - private var ctx: ChannelHandlerContext! + private var context: ChannelHandlerContext! private var readCountPromise: EventLoopPromise! private var waitingForReadPromise: EventLoopPromise? - func handlerAdded(ctx: ChannelHandlerContext) { - self.ctx = ctx - self.readCountPromise = ctx.eventLoop.makePromise() + func handlerAdded(context: ChannelHandlerContext) { + self.context = context + self.readCountPromise = context.eventLoop.makePromise() } public func expectRead(loop: EventLoop) -> EventLoopFuture { @@ -1513,22 +1513,22 @@ public class ChannelTests: XCTestCase { } } - func channelReadComplete(ctx: ChannelHandlerContext) { + func channelReadComplete(context: ChannelHandlerContext) { self.waitingForReadPromise?.succeed(()) self.waitingForReadPromise = nil } - func read(ctx: ChannelHandlerContext) { + func read(context: ChannelHandlerContext) { self.reads += 1 // Allow the first read through. if self.reads == 1 { - self.ctx.read() + self.context.read() } } public func issueDelayedRead() { - self.ctx.read() + self.context.read() } } @@ -1583,7 +1583,7 @@ public class ChannelTests: XCTestCase { var expectingData: Bool = false - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { if !self.expectingData { XCTFail("Received data before we expected it.") } else { @@ -1631,14 +1631,14 @@ public class ChannelTests: XCTestCase { private var seenEOF: Bool = false private var numberOfChannelReads: Int = 0 - public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { if case .some(ChannelEvent.inputClosed) = event as? ChannelEvent { self.seenEOF = true } - ctx.fireUserInboundEventTriggered(event) + context.fireUserInboundEventTriggered(event) } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + 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))") } @@ -1646,7 +1646,7 @@ public class ChannelTests: XCTestCase { let buffer = self.unwrapInboundIn(data) XCTAssertLessThanOrEqual(buffer.readableBytes, 8) XCTAssertEqual(1, self.numberOfChannelReads) - ctx.close(mode: .all, promise: nil) + context.close(mode: .all, promise: nil) } } @@ -1689,13 +1689,13 @@ public class ChannelTests: XCTestCase { self.allDone = allDone } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { if !self.didRead { self.didRead = true // closing this here causes an interesting situation: // in readFromSocket we will spin one more iteration until we see the EOF but when we then return // to `BaseSocketChannel.readable0`, we deliver EOF with the channel already deactivated. - ctx.close(mode: .all, promise: self.allDone) + context.close(mode: .all, promise: self.allDone) } } } @@ -1742,11 +1742,11 @@ public class ChannelTests: XCTestCase { self.promise = promise } - public func read(ctx: ChannelHandlerContext) { + public func read(context: ChannelHandlerContext) { XCTFail("shouldn't read") } - public func channelInactive(ctx: ChannelHandlerContext) { + public func channelInactive(context: ChannelHandlerContext) { promise.succeed(()) } } @@ -1821,18 +1821,18 @@ public class ChannelTests: XCTestCase { XCTAssertFalse(self.isActive) } - func channelActive(ctx: ChannelHandlerContext) { + func channelActive(context: ChannelHandlerContext) { XCTAssertFalse(self.isActive) self.isActive = true - self.channelCollector.add(ctx.channel) - ctx.fireChannelActive() + self.channelCollector.add(context.channel) + context.fireChannelActive() } - func channelInactive(ctx: ChannelHandlerContext) { + func channelInactive(context: ChannelHandlerContext) { XCTAssertTrue(self.isActive) self.isActive = false - self.channelCollector.remove(ctx.channel) - ctx.fireChannelInactive() + self.channelCollector.remove(context.channel) + context.fireChannelInactive() } } @@ -1899,21 +1899,21 @@ public class ChannelTests: XCTestCase { self.hasUnregisteredPromise = hasUnregisteredPromise self.hasReadPromise = hasReadPromise } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTAssertEqual(.active, self.state) self.state = .read self.hasReadPromise.succeed(()) } - func channelActive(ctx: ChannelHandlerContext) { + func channelActive(context: ChannelHandlerContext) { XCTAssertEqual(.registered, self.state) self.state = .active } - func channelRegistered(ctx: ChannelHandlerContext) { + func channelRegistered(context: ChannelHandlerContext) { XCTAssertEqual(.start, self.state) self.state = .registered self.hasRegisteredPromise.succeed(()) } - func channelUnregistered(ctx: ChannelHandlerContext) { + func channelUnregistered(context: ChannelHandlerContext) { self.hasUnregisteredPromise.succeed(()) } } @@ -1937,10 +1937,10 @@ public class ChannelTests: XCTestCase { self.writeDonePromise = writeDonePromise } - func channelActive(ctx: ChannelHandlerContext) { - var buffer = ctx.channel.allocator.buffer(capacity: 4) + func channelActive(context: ChannelHandlerContext) { + var buffer = context.channel.allocator.buffer(capacity: 4) buffer.writeString("foo") - ctx.writeAndFlush(NIOAny(buffer), promise: self.writeDonePromise) + context.writeAndFlush(NIOAny(buffer), promise: self.writeDonePromise) } } @@ -2073,12 +2073,12 @@ public class ChannelTests: XCTestCase { init(allDone: EventLoopPromise) { self.allDone = allDone } - func channelActive(ctx: ChannelHandlerContext) { + func channelActive(context: ChannelHandlerContext) { XCTAssertEqual(.fresh, self.state) self.state = .active } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTAssertEqual(.active, self.state) self.state = .read var buffer = self.unwrapInboundIn(data) @@ -2086,18 +2086,18 @@ public class ChannelTests: XCTestCase { XCTAssertEqual([0xff], buffer.readBytes(length: 1)!) } - func channelReadComplete(ctx: ChannelHandlerContext) { + func channelReadComplete(context: ChannelHandlerContext) { XCTAssertEqual(.read, self.state) self.state = .readComplete } - func errorCaught(ctx: ChannelHandlerContext, error: Error) { + func errorCaught(context: ChannelHandlerContext, error: Error) { XCTAssertEqual(.readComplete, self.state) self.state = .error - ctx.close(promise: nil) + context.close(promise: nil) } - func channelInactive(ctx: ChannelHandlerContext) { + func channelInactive(context: ChannelHandlerContext) { XCTAssertEqual(.error, self.state) self.state = .inactive self.allDone.succeed(()) @@ -2467,15 +2467,15 @@ public class ChannelTests: XCTestCase { self.channelAvailablePromise = channelAvailablePromise } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let buffer = self.unwrapInboundIn(data) XCTFail("unexpected read: \(String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))") } - func channelActive(ctx: ChannelHandlerContext) { - var buffer = ctx.channel.allocator.buffer(capacity: 1) + func channelActive(context: ChannelHandlerContext) { + var buffer = context.channel.allocator.buffer(capacity: 1) buffer.writeStaticString("X") - ctx.channel.writeAndFlush(self.wrapOutboundOut(buffer)).map { ctx.channel }.cascade(to: self.channelAvailablePromise) + context.channel.writeAndFlush(self.wrapOutboundOut(buffer)).map { context.channel }.cascade(to: self.channelAvailablePromise) } } @@ -2518,8 +2518,8 @@ public class ChannelTests: XCTestCase { } } - func channelActive(ctx: ChannelHandlerContext) { - XCTAssert(serverChannel.eventLoop === ctx.eventLoop) + func channelActive(context: ChannelHandlerContext) { + XCTAssert(serverChannel.eventLoop === context.eventLoop) self.serverChannel.whenSuccess { serverChannel in // all of the following futures need to complete synchronously for this test to test the correct // thing. Therefore we keep track if we're still on the same stack frame. @@ -2531,9 +2531,9 @@ public class ChannelTests: XCTestCase { XCTAssertTrue(serverChannel.isActive) // we allow auto-read again to make sure that the socket buffer is drained on write error // (cf. https://github.com/apple/swift-nio/issues/593) - ctx.channel.setOption(ChannelOptions.autoRead, value: true).flatMap { + context.channel.setOption(ChannelOptions.autoRead, value: true).flatMap { // let's trigger the write error - var buffer = ctx.channel.allocator.buffer(capacity: 16) + var buffer = context.channel.allocator.buffer(capacity: 16) buffer.writeStaticString("THIS WILL FAIL ANYWAY") // this needs to be in a function as otherwise the Swift compiler believes this is throwing @@ -2541,11 +2541,11 @@ public class ChannelTests: XCTestCase { // this test only tests the correct condition if the bytes sent from the other side have already // arrived at the time the write fails. So this is a hack that makes sure they do have arrived. // (https://github.com/apple/swift-nio/issues/657) - XCTAssertNoThrow(try self.veryNasty_blockUntilReadBufferIsNonEmpty(channel: ctx.channel)) + XCTAssertNoThrow(try self.veryNasty_blockUntilReadBufferIsNonEmpty(channel: context.channel)) } workaroundSR487() - return ctx.writeAndFlush(self.wrapOutboundOut(buffer)) + return context.writeAndFlush(self.wrapOutboundOut(buffer)) }.map { XCTFail("this should have failed") }.whenFailure { error in @@ -2557,10 +2557,10 @@ public class ChannelTests: XCTestCase { } } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let buffer = self.unwrapInboundIn(data) XCTAssertEqual("X", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self)) - ctx.close(promise: nil) + context.close(promise: nil) } } @@ -2678,14 +2678,14 @@ fileprivate final class FailRegistrationAndDelayCloseHandler: ChannelOutboundHan typealias OutboundIn = Never - func register(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { + func register(context: ChannelHandlerContext, promise: EventLoopPromise?) { promise!.fail(RegistrationFailedError.error) } - func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { + func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { /* for extra nastiness, let's delay close. This makes sure the ChannelPipeline correctly retains the Channel */ - _ = ctx.eventLoop.scheduleTask(in: .milliseconds(10)) { - ctx.close(mode: mode, promise: promise) + _ = context.eventLoop.scheduleTask(in: .milliseconds(10)) { + context.close(mode: mode, promise: promise) } } } @@ -2705,24 +2705,24 @@ fileprivate class VerifyConnectionFailureHandler: ChannelInboundHandler { } deinit { XCTAssertEqual(.unregistered, self.state) } - func channelActive(ctx: ChannelHandlerContext) { XCTFail("should never become active") } + func channelActive(context: ChannelHandlerContext) { XCTFail("should never become active") } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { XCTFail("should never read") } + func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTFail("should never read") } - func channelReadComplete(ctx: ChannelHandlerContext) { XCTFail("should never readComplete") } + func channelReadComplete(context: ChannelHandlerContext) { XCTFail("should never readComplete") } - func errorCaught(ctx: ChannelHandlerContext, error: Error) { XCTFail("pipeline shouldn't be told about connect error") } + func errorCaught(context: ChannelHandlerContext, error: Error) { XCTFail("pipeline shouldn't be told about connect error") } - func channelRegistered(ctx: ChannelHandlerContext) { + func channelRegistered(context: ChannelHandlerContext) { XCTAssertEqual(.fresh, self.state) self.state = .registered - ctx.fireChannelRegistered() + context.fireChannelRegistered() } - func channelUnregistered(ctx: ChannelHandlerContext) { + func channelUnregistered(context: ChannelHandlerContext) { XCTAssertEqual(.registered, self.state) self.state = .unregistered self.allDone.succeed(()) - ctx.fireChannelUnregistered() + context.fireChannelUnregistered() } } diff --git a/Tests/NIOTests/CodecTest.swift b/Tests/NIOTests/CodecTest.swift index 4ce197bc9..baf9d6455 100644 --- a/Tests/NIOTests/CodecTest.swift +++ b/Tests/NIOTests/CodecTest.swift @@ -45,7 +45,7 @@ private final class ChannelInactivePromiser: ChannelInboundHandler { channelInactivePromise = channel.eventLoop.makePromise() } - func channelInactive(ctx: ChannelHandlerContext) { + func channelInactive(context: ChannelHandlerContext) { channelInactivePromise.succeed(()) } } @@ -55,17 +55,17 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundIn = ByteBuffer typealias InboundOut = Int32 - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { + func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { guard buffer.readableBytes >= MemoryLayout.size else { return .needMoreData } - ctx.fireChannelRead(self.wrapInboundOut(buffer.readInteger()!)) + context.fireChannelRead(self.wrapInboundOut(buffer.readInteger()!)) return .continue } - func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) - return self.decode(ctx: ctx, buffer: &buffer) + return self.decode(context: context, buffer: &buffer) } } @@ -73,13 +73,13 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundIn = ByteBuffer typealias InboundOut = Never - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { + func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { return .needMoreData } - func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) - return self.decode(ctx: ctx, buffer: &buffer) + return self.decode(context: context, buffer: &buffer) } } @@ -87,18 +87,18 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundIn = ByteBuffer typealias InboundOut = ByteBuffer - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { + func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { guard case .some(let buffer) = buffer.readSlice(length: 512) else { return .needMoreData } - ctx.fireChannelRead(self.wrapInboundOut(buffer)) + context.fireChannelRead(self.wrapInboundOut(buffer)) return .continue } - func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) - return self.decode(ctx: ctx, buffer: &buffer) + return self.decode(context: context, buffer: &buffer) } } @@ -108,18 +108,18 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundIn = ByteBuffer typealias InboundOut = ByteBuffer - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { + func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { guard buffer.readableBytes >= 5120 else { return .needMoreData } - ctx.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 2048)!)) + context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 2048)!)) return .continue } - func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) - return self.decode(ctx: ctx, buffer: &buffer) + return self.decode(context: context, buffer: &buffer) } } @@ -263,27 +263,27 @@ public class ByteToMessageDecoderTest: XCTestCase { var numberOfDecodeCalls = 0 var hasReentranced = false - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { self.numberOfDecodeCalls += 1 print("\(numberOfDecodeCalls): \(String(decoding: buffer.readableBytesView, as: UTF8.self))") - var reentrantWriteBuffer = ctx.channel.allocator.buffer(capacity: 1) + var reentrantWriteBuffer = context.channel.allocator.buffer(capacity: 1) if self.numberOfDecodeCalls == 2 { // this is the first time, let's fireChannelRead self.hasReentranced = true reentrantWriteBuffer.clear() reentrantWriteBuffer.writeStaticString("3") - ctx.channel.pipeline.fireChannelRead(self.wrapInboundOut(reentrantWriteBuffer)) + context.channel.pipeline.fireChannelRead(self.wrapInboundOut(reentrantWriteBuffer)) } - ctx.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 1)!)) + context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 1)!)) if self.numberOfDecodeCalls == 2 { reentrantWriteBuffer.clear() reentrantWriteBuffer.writeStaticString("4") - ctx.channel.pipeline.fireChannelRead(self.wrapInboundOut(reentrantWriteBuffer)) + context.channel.pipeline.fireChannelRead(self.wrapInboundOut(reentrantWriteBuffer)) } return .continue } - func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) return .needMoreData } @@ -335,18 +335,18 @@ public class ByteToMessageDecoderTest: XCTestCase { var decodeLastCalls = 0 - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { let originalBuffer = buffer - ctx.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: buffer.readableBytes)!)) + context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: buffer.readableBytes)!)) if originalBuffer.readableBytesView.last == "0".utf8.last { - ctx.close().whenFailure { error in + context.close().whenFailure { error in XCTFail("unexpected error: \(error)") } } return .needMoreData } - func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) self.decodeLastCalls += 1 XCTAssertEqual(1, self.decodeLastCalls) @@ -426,8 +426,8 @@ public class ByteToMessageDecoderTest: XCTestCase { buffer.writeStaticString("4567890x") XCTAssertNoThrow(try channel.writeInbound(buffer)) - channel.pipeline.context(handlerType: ByteToMessageHandler.self).flatMap { ctx in - return channel.pipeline.removeHandler(ctx: ctx) + channel.pipeline.context(handlerType: ByteToMessageHandler.self).flatMap { context in + return channel.pipeline.removeHandler(context: context) }.whenFailure { error in XCTFail("unexpected error: \(error)") } @@ -451,21 +451,21 @@ public class ByteToMessageDecoderTest: XCTestCase { var state: Int = 1 - mutating func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let slice = buffer.readSlice(length: self.state) { defer { self.state += 1 } - ctx.fireChannelRead(self.wrapInboundOut(self.state)) + context.fireChannelRead(self.wrapInboundOut(self.state)) return .continue } else { return .needMoreData } } - mutating func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) - ctx.fireChannelRead(self.wrapInboundOut(buffer.readableBytes * -1)) + context.fireChannelRead(self.wrapInboundOut(buffer.readableBytes * -1)) return .needMoreData } } @@ -500,23 +500,23 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundOut = String var state = 16 - mutating func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { XCTAssertGreaterThan(self.state, 0) if let slice = buffer.readSlice(length: self.state) { self.state >>= 1 for i in 0.. DecodingState { + mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) - return try self.decode(ctx: ctx, buffer: &buffer) + return try self.decode(context: context, buffer: &buffer) } } let channel = EmbeddedChannel(handler: ByteToMessageHandler(ProcessAndReentrantylyProcessExponentiallyLessStuffDecoder())) @@ -536,10 +536,10 @@ public class ByteToMessageDecoderTest: XCTestCase { struct Take16BytesThenCloseAndPassOnDecoder: ByteToMessageDecoder { typealias InboundOut = ByteBuffer - mutating func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let slice = buffer.readSlice(length: 16) { - ctx.fireChannelRead(self.wrapInboundOut(slice)) - ctx.channel.close().whenFailure { error in + context.fireChannelRead(self.wrapInboundOut(slice)) + context.channel.close().whenFailure { error in XCTFail("unexpected error: \(error)") } return .continue @@ -548,9 +548,9 @@ public class ByteToMessageDecoderTest: XCTestCase { } } - mutating func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) - ctx.fireChannelRead(self.wrapInboundOut(buffer)) + context.fireChannelRead(self.wrapInboundOut(buffer)) return .needMoreData } } @@ -568,10 +568,10 @@ public class ByteToMessageDecoderTest: XCTestCase { struct Take16BytesThenCloseAndPassOnDecoder: ByteToMessageDecoder { typealias InboundOut = ByteBuffer - mutating func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let slice = buffer.readSlice(length: 16) { - ctx.fireChannelRead(self.wrapInboundOut(slice)) - ctx.pipeline.removeHandler(ctx: ctx).whenFailure { error in + context.fireChannelRead(self.wrapInboundOut(slice)) + context.pipeline.removeHandler(context: context).whenFailure { error in XCTFail("unexpected error: \(error)") } return .continue @@ -580,9 +580,9 @@ public class ByteToMessageDecoderTest: XCTestCase { } } - mutating func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertFalse(seenEOF) - ctx.fireChannelRead(self.wrapInboundOut(buffer)) + context.fireChannelRead(self.wrapInboundOut(buffer)) return .needMoreData } } @@ -601,10 +601,10 @@ public class ByteToMessageDecoderTest: XCTestCase { struct Take16BytesThenCloseAndPassOnDecoder: ByteToMessageDecoder { typealias InboundOut = ByteBuffer - mutating func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let slice = buffer.readSlice(length: 16) { - ctx.fireChannelRead(self.wrapInboundOut(slice)) - ctx.close().whenFailure { error in + context.fireChannelRead(self.wrapInboundOut(slice)) + context.close().whenFailure { error in XCTFail("unexpected error: \(error)") } return .continue @@ -613,7 +613,7 @@ public class ByteToMessageDecoderTest: XCTestCase { } } - mutating func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) return .needMoreData } @@ -621,7 +621,7 @@ public class ByteToMessageDecoderTest: XCTestCase { class DoNotForwardChannelInactiveHandler: ChannelInboundHandler { typealias InboundIn = Never - func channelInactive(ctx: ChannelHandlerContext) { + func channelInactive(context: ChannelHandlerContext) { // just eat this event } } @@ -643,23 +643,23 @@ public class ByteToMessageDecoderTest: XCTestCase { var callsToDecode = 0 var callsToDecodeLast = 0 - mutating func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { XCTAssertEqual(9, buffer.readableBytes) self.callsToDecode += 1 XCTAssertEqual(1, self.callsToDecode) - ctx.fireChannelRead(self.wrapInboundOut(String(decoding: buffer.readBytes(length: 1)!, + context.fireChannelRead(self.wrapInboundOut(String(decoding: buffer.readBytes(length: 1)!, as: Unicode.UTF8.self))) - ctx.pipeline.removeHandler(ctx: ctx).whenFailure { error in + context.pipeline.removeHandler(context: context).whenFailure { error in XCTFail("unexpected error: \(error)") } return .continue } - mutating func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertFalse(seenEOF) self.callsToDecodeLast += 1 XCTAssertLessThanOrEqual(self.callsToDecodeLast, 2) - ctx.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], @@ -690,17 +690,17 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundOut = () var decodeLastCalls = 0 - public func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { XCTFail("did not expect to see decode called") return .needMoreData } - public func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + public func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) self.decodeLastCalls += 1 XCTAssertEqual(1, self.decodeLastCalls) XCTAssertEqual(0, buffer.readableBytes) - ctx.fireChannelRead(self.wrapInboundOut(())) + context.fireChannelRead(self.wrapInboundOut(())) return .needMoreData } } @@ -723,17 +723,17 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundOut = () var decodeLastCalls = 0 - public func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { XCTFail("did not expect to see decode called") return .needMoreData } - public func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + public func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertTrue(seenEOF) self.decodeLastCalls += 1 XCTAssertEqual(1, self.decodeLastCalls) XCTAssertEqual(0, buffer.readableBytes) - ctx.fireChannelRead(self.wrapInboundOut(())) + context.fireChannelRead(self.wrapInboundOut(())) return .needMoreData } } @@ -761,12 +761,12 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundOut = () var decodeLastCalls = 0 - public func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { XCTAssertEqual(1, buffer.readableBytes) return .needMoreData } - public func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + public func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { self.decodeLastCalls += 1 XCTAssertEqual(1, buffer.readableBytes) XCTAssertEqual(1, self.decodeLastCalls) @@ -782,7 +782,7 @@ public class ByteToMessageDecoderTest: XCTestCase { buffer.writeString("x") XCTAssertNoThrow(try channel.writeInbound(buffer)) let removalFuture = channel.pipeline.context(handlerType: ByteToMessageHandler.self).flatMap { - channel.pipeline.removeHandler(ctx: $0) + channel.pipeline.removeHandler(context: $0) } (channel.eventLoop as! EmbeddedEventLoop).run() XCTAssertNoThrow(try removalFuture.wait()) @@ -794,12 +794,12 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundOut = () var decodeLastCalls = 0 - public func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { XCTFail("shouldn't have been called") return .needMoreData } - public func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + public func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { self.decodeLastCalls += 1 XCTAssertEqual(0, buffer.readableBytes) XCTAssertEqual(1, self.decodeLastCalls) @@ -812,7 +812,7 @@ public class ByteToMessageDecoderTest: XCTestCase { let channel = EmbeddedChannel(handler: ByteToMessageHandler(decoder)) XCTAssertNoThrow(try channel.connect(to: SocketAddress(ipAddress: "1.2.3.4", port: 5678)).wait()) let removalFuture = channel.pipeline.context(handlerType: ByteToMessageHandler.self).flatMap { - channel.pipeline.removeHandler(ctx: $0) + channel.pipeline.removeHandler(context: $0) } (channel.eventLoop as! EmbeddedEventLoop).run() XCTAssertNoThrow(try removalFuture.wait()) @@ -824,12 +824,12 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundOut = () var decodeLastCalls = 0 - public func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { XCTAssertEqual(1, buffer.readableBytes) return .needMoreData } - public func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + public func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { self.decodeLastCalls += 1 XCTAssertEqual(1, buffer.readableBytes) XCTAssertEqual(1, self.decodeLastCalls) @@ -859,17 +859,17 @@ public class ByteToMessageDecoderTest: XCTestCase { self.allObservedWrites.append(data) } - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let string = buffer.readString(length: 1) { - ctx.fireChannelRead(self.wrapInboundOut(string)) + context.fireChannelRead(self.wrapInboundOut(string)) return .continue } else { return .needMoreData } } - func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { - while case .continue = try self.decode(ctx: ctx, buffer: &buffer) {} + func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + while case .continue = try self.decode(context: context, buffer: &buffer) {} return .needMoreData } } @@ -905,15 +905,15 @@ public class ByteToMessageDecoderTest: XCTestCase { self.allObservedWrites.append(data) } - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { self.decodeRun += 1 if let string = buffer.readString(length: 1) { - ctx.fireChannelRead(self.wrapInboundOut("I: \(self.decodeRun): \(string)")) - XCTAssertNoThrow(try (ctx.channel as! EmbeddedChannel).writeOutbound("O: \(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 = ctx.channel.allocator.buffer(capacity: 1) + var buffer = context.channel.allocator.buffer(capacity: 1) buffer.writeStaticString("X") - XCTAssertNoThrow(try (ctx.channel as! EmbeddedChannel).writeInbound(buffer)) + XCTAssertNoThrow(try (context.channel as! EmbeddedChannel).writeInbound(buffer)) } return .continue } else { @@ -921,8 +921,8 @@ public class ByteToMessageDecoderTest: XCTestCase { } } - func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { - while case .continue = try self.decode(ctx: ctx, buffer: &buffer) {} + func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + while case .continue = try self.decode(context: context, buffer: &buffer) {} return .needMoreData } } @@ -937,9 +937,9 @@ public class ByteToMessageDecoderTest: XCTestCase { self.decoder = decoder } - func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { let string = self.unwrapOutboundIn(data) - ctx.write(self.wrapOutboundOut("\(string) @ \(decoder.decodeRun)"), promise: promise) + context.write(self.wrapOutboundOut("\(string) @ \(decoder.decodeRun)"), promise: promise) } } @@ -987,13 +987,13 @@ public class ByteToMessageDecoderTest: XCTestCase { private var errorThrownAlready = false - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { XCTAssertFalse(self.errorThrownAlready) self.errorThrownAlready = true throw DecodeError() } - func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTFail("decodeLast should never be called") return .needMoreData } @@ -1032,13 +1032,13 @@ public class ByteToMessageDecoderTest: XCTestCase { private var errorThrownAlready = false private var decodeCalls = 0 - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { self.decodeCalls += 1 XCTAssertEqual(1, self.decodeCalls) return .needMoreData } - func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { XCTAssertFalse(self.errorThrownAlready) self.errorThrownAlready = true throw DecodeError() @@ -1068,13 +1068,13 @@ public class MessageToByteEncoderTest: XCTestCase { typealias OutboundIn = Int32 typealias OutboundOut = ByteBuffer - public func encode(ctx: ChannelHandlerContext, data value: Int32, out: inout ByteBuffer) throws { + public func encode(context: ChannelHandlerContext, data value: Int32, out: inout ByteBuffer) throws { XCTAssertEqual(MemoryLayout.size, out.writableBytes) out.writeInteger(value) } - public func allocateOutBuffer(ctx: ChannelHandlerContext, data: Int32) throws -> ByteBuffer { - return ctx.channel.allocator.buffer(capacity: MemoryLayout.size) + public func allocateOutBuffer(context: ChannelHandlerContext, data: Int32) throws -> ByteBuffer { + return context.channel.allocator.buffer(capacity: MemoryLayout.size) } } @@ -1082,7 +1082,7 @@ public class MessageToByteEncoderTest: XCTestCase { typealias OutboundIn = Int32 typealias OutboundOut = ByteBuffer - public func encode(ctx: ChannelHandlerContext, data value: Int32, out: inout ByteBuffer) throws { + public func encode(context: ChannelHandlerContext, data value: Int32, out: inout ByteBuffer) throws { XCTAssertEqual(MemoryLayout.size, 256) out.writeInteger(value) } @@ -1125,16 +1125,16 @@ private class PairOfBytesDecoder: ByteToMessageDecoder { self.lastPromise = lastPromise } - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { if let slice = buffer.readSlice(length: 2) { - ctx.fireChannelRead(self.wrapInboundOut(slice)) + context.fireChannelRead(self.wrapInboundOut(slice)) return .continue } else { return .needMoreData } } - func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { self.decodeLastCalls += 1 XCTAssertEqual(1, self.decodeLastCalls) self.lastPromise.succeed(buffer) diff --git a/Tests/NIOTests/DatagramChannelTests.swift b/Tests/NIOTests/DatagramChannelTests.swift index 37a5b42f8..7e1619ba3 100644 --- a/Tests/NIOTests/DatagramChannelTests.swift +++ b/Tests/NIOTests/DatagramChannelTests.swift @@ -48,18 +48,18 @@ private class DatagramReadRecorder: ChannelInboundHandler { var readWaiters: [Int: EventLoopPromise<[AddressedEnvelope]>] = [:] - func channelRegistered(ctx: ChannelHandlerContext) { + func channelRegistered(context: ChannelHandlerContext) { XCTAssertEqual(.fresh, self.state) self.state = .registered - self.loop = ctx.eventLoop + self.loop = context.eventLoop } - func channelActive(ctx: ChannelHandlerContext) { + func channelActive(context: ChannelHandlerContext) { XCTAssertEqual(.registered, self.state) self.state = .active } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTAssertEqual(.active, self.state) let data = self.unwrapInboundIn(data) reads.append(data) @@ -68,7 +68,7 @@ private class DatagramReadRecorder: ChannelInboundHandler { promise.succeed(reads) } - ctx.fireChannelRead(self.wrapInboundOut(data)) + context.fireChannelRead(self.wrapInboundOut(data)) } func notifyForDatagrams(_ count: Int) -> EventLoopFuture<[AddressedEnvelope]> { @@ -370,11 +370,11 @@ final class DatagramChannelTests: XCTestCase { self.promise = promise } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTFail("Should not receive data but got \(self.unwrapInboundIn(data))") } - func errorCaught(ctx: ChannelHandlerContext, error: Error) { + func errorCaught(context: ChannelHandlerContext, error: Error) { if let ioError = error as? IOError { self.promise.succeed(ioError) } diff --git a/Tests/NIOTests/EchoServerClientTest.swift b/Tests/NIOTests/EchoServerClientTest.swift index 3aad34065..85cfb9ccb 100644 --- a/Tests/NIOTests/EchoServerClientTest.swift +++ b/Tests/NIOTests/EchoServerClientTest.swift @@ -244,13 +244,13 @@ class EchoServerClientTest : XCTestCase { private var promise: EventLoopPromise! = nil - func handlerAdded(ctx: ChannelHandlerContext) { - promise = ctx.channel.eventLoop.makePromise() + func handlerAdded(context: ChannelHandlerContext) { + promise = context.channel.eventLoop.makePromise() } - func channelActive(ctx: ChannelHandlerContext) { + func channelActive(context: ChannelHandlerContext) { promise.succeed(()) - ctx.fireChannelActive() + context.fireChannelActive() } func assertChannelActiveFired() throws { @@ -262,12 +262,12 @@ class EchoServerClientTest : XCTestCase { typealias InboundIn = ByteBuffer typealias OutboundOut = ByteBuffer - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { - ctx.write(data, promise: nil) + func channelRead(context: ChannelHandlerContext, data: NIOAny) { + context.write(data, promise: nil) } - func channelReadComplete(ctx: ChannelHandlerContext) { - ctx.flush() + func channelReadComplete(context: ChannelHandlerContext) { + context.flush() } } @@ -288,17 +288,17 @@ class EchoServerClientTest : XCTestCase { } } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { self.numberOfReads += 1 precondition(self.numberOfReads == 1, "\(self) is only ever allowed to read once") - _ = ctx.eventLoop.scheduleTask(in: self.timeAmount) { - ctx.writeAndFlush(data, promise: nil) + _ = context.eventLoop.scheduleTask(in: self.timeAmount) { + context.writeAndFlush(data, promise: nil) self.group.leave() }.futureResult.recover { e in XCTFail("we failed to schedule the task: \(e)") self.group.leave() } - ctx.writeAndFlush(data, promise: nil) + context.writeAndFlush(data, promise: nil) } } @@ -306,14 +306,14 @@ class EchoServerClientTest : XCTestCase { typealias InboundIn = ByteBuffer typealias OutboundOut = ByteBuffer - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { for _ in 0..<10000 { - ctx.write(data, promise: nil) + context.write(data, promise: nil) } } - func channelReadComplete(ctx: ChannelHandlerContext) { - ctx.flush() + func channelReadComplete(context: ChannelHandlerContext) { + context.flush() } } @@ -330,17 +330,17 @@ class EchoServerClientTest : XCTestCase { self.channelInactivePromise = channelInactivePromise } - public func channelActive(ctx: ChannelHandlerContext) { - ctx.close().whenFailure { error in + public func channelActive(context: ChannelHandlerContext) { + context.close().whenFailure { error in XCTFail("bad, initial close failed (\(error))") } } - public func channelInactive(ctx: ChannelHandlerContext) { + public func channelInactive(context: ChannelHandlerContext) { if alreadyClosedInChannelInactive.compareAndExchange(expected: false, desired: true) { XCTAssertFalse(self.channelUnregisteredPromise.futureResult.isFulfilled, "channelInactive should fire before channelUnregistered") - ctx.close().map { + context.close().map { XCTFail("unexpected success") }.recover { err in switch err { @@ -356,11 +356,11 @@ class EchoServerClientTest : XCTestCase { } } - public func channelUnregistered(ctx: ChannelHandlerContext) { + public func channelUnregistered(context: ChannelHandlerContext) { if alreadyClosedInChannelUnregistered.compareAndExchange(expected: false, desired: true) { XCTAssertTrue(self.channelInactivePromise.futureResult.isFulfilled, "when channelUnregister fires, channelInactive should already have fired") - ctx.close().map { + context.close().map { XCTFail("unexpected success") }.recover { err in switch err { @@ -387,11 +387,11 @@ class EchoServerClientTest : XCTestCase { self.toWrite = toWrite } - func channelActive(ctx: ChannelHandlerContext) { - var dataToWrite = ctx.channel.allocator.buffer(capacity: toWrite.utf8.count) + func channelActive(context: ChannelHandlerContext) { + var dataToWrite = context.channel.allocator.buffer(capacity: toWrite.utf8.count) dataToWrite.writeString(toWrite) - ctx.writeAndFlush(NIOAny(dataToWrite), promise: nil) - ctx.fireChannelActive() + context.writeAndFlush(NIOAny(dataToWrite), promise: nil) + context.fireChannelActive() } } @@ -596,16 +596,16 @@ class EchoServerClientTest : XCTestCase { private var writeFailed = false - func channelActive(ctx: ChannelHandlerContext) { - var buffer = ctx.channel.allocator.buffer(capacity: 4) + func channelActive(context: ChannelHandlerContext) { + var buffer = context.channel.allocator.buffer(capacity: 4) buffer.writeString("test") - writeUntilFailed(ctx, buffer) + writeUntilFailed(context, buffer) } - private func writeUntilFailed(_ ctx: ChannelHandlerContext, _ buffer: ByteBuffer) { - ctx.writeAndFlush(NIOAny(buffer)).whenComplete { (_: Result) in - ctx.eventLoop.execute { - self.writeUntilFailed(ctx, buffer) + private func writeUntilFailed(_ context: ChannelHandlerContext, _ buffer: ByteBuffer) { + context.writeAndFlush(NIOAny(buffer)).whenComplete { (_: Result) in + context.eventLoop.execute { + self.writeUntilFailed(context, buffer) } } } @@ -621,20 +621,20 @@ class EchoServerClientTest : XCTestCase { self.dpGroup = dpGroup } - func channelActive(ctx: ChannelHandlerContext) { - ctx.fireChannelActive() - var buffer = ctx.channel.allocator.buffer(capacity: str.utf8.count) + func channelActive(context: ChannelHandlerContext) { + context.fireChannelActive() + var buffer = context.channel.allocator.buffer(capacity: str.utf8.count) buffer.writeString(str) // write it four times and then close the connect. - ctx.writeAndFlush(NIOAny(buffer)).flatMap { - ctx.writeAndFlush(NIOAny(buffer)) + context.writeAndFlush(NIOAny(buffer)).flatMap { + context.writeAndFlush(NIOAny(buffer)) }.flatMap { - ctx.writeAndFlush(NIOAny(buffer)) + context.writeAndFlush(NIOAny(buffer)) }.flatMap { - ctx.writeAndFlush(NIOAny(buffer)) + context.writeAndFlush(NIOAny(buffer)) }.flatMap { - ctx.close() + context.close() }.whenComplete { (_: Result) in self.dpGroup.leave() } @@ -687,13 +687,13 @@ class EchoServerClientTest : XCTestCase { self.promise = promise } - public func errorCaught(ctx: ChannelHandlerContext, error: Error) { + public func errorCaught(context: ChannelHandlerContext, error: Error) { if let err = error as? ChannelError { XCTAssertNotEqual(ChannelError.eof, err) } } - public func channelInactive(ctx: ChannelHandlerContext) { + public func channelInactive(context: ChannelHandlerContext) { self.promise.succeed(()) } } diff --git a/Tests/NIOTests/EmbeddedChannelTest.swift b/Tests/NIOTests/EmbeddedChannelTest.swift index d54dbd717..87f062987 100644 --- a/Tests/NIOTests/EmbeddedChannelTest.swift +++ b/Tests/NIOTests/EmbeddedChannelTest.swift @@ -108,8 +108,8 @@ class EmbeddedChannelTest: XCTestCase { private final class ExceptionThrowingInboundHandler : ChannelInboundHandler { typealias InboundIn = String - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { - ctx.fireErrorCaught(ChannelError.operationUnsupported) + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { + context.fireErrorCaught(ChannelError.operationUnsupported) } } @@ -118,7 +118,7 @@ class EmbeddedChannelTest: XCTestCase { typealias OutboundIn = String typealias OutboundOut = Never - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { promise!.fail(ChannelError.operationUnsupported) } } @@ -127,9 +127,9 @@ class EmbeddedChannelTest: XCTestCase { typealias InboundIn = ByteBuffer public var inactiveNotifications = 0 - public func channelInactive(ctx: ChannelHandlerContext) { + public func channelInactive(context: ChannelHandlerContext) { inactiveNotifications += 1 - ctx.close(promise: nil) + context.close(promise: nil) } } diff --git a/Tests/NIOTests/EventLoopTest.swift b/Tests/NIOTests/EventLoopTest.swift index c3c647f9c..3a10887ed 100644 --- a/Tests/NIOTests/EventLoopTest.swift +++ b/Tests/NIOTests/EventLoopTest.swift @@ -313,19 +313,19 @@ public class EventLoopTest : XCTestCase { self.channelActivePromise = channelActivePromise } - func channelActive(ctx: ChannelHandlerContext) { + func channelActive(context: ChannelHandlerContext) { self.channelActivePromise?.succeed(()) } - func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { + func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { guard self.closePromise == nil else { XCTFail("Attempted to create duplicate close promise") return } - XCTAssertTrue(ctx.channel.isActive) - self.closePromise = ctx.eventLoop.makePromise() + XCTAssertTrue(context.channel.isActive) + self.closePromise = context.eventLoop.makePromise() self.closePromise!.futureResult.whenSuccess { - ctx.close(mode: mode, promise: promise) + context.close(mode: mode, promise: promise) } promiseRegisterCallback(self.closePromise!) } @@ -502,7 +502,7 @@ public class EventLoopTest : XCTestCase { let groupIsShutdown = Atomic(value: false) let removed = Atomic(value: false) - public func handlerRemoved(ctx: ChannelHandlerContext) { + public func handlerRemoved(context: ChannelHandlerContext) { XCTAssertFalse(groupIsShutdown.load()) XCTAssertTrue(removed.compareAndExchange(expected: false, desired: true)) } diff --git a/Tests/NIOTests/HappyEyeballsTest.swift b/Tests/NIOTests/HappyEyeballsTest.swift index e72f31685..7373d9e95 100644 --- a/Tests/NIOTests/HappyEyeballsTest.swift +++ b/Tests/NIOTests/HappyEyeballsTest.swift @@ -61,21 +61,21 @@ private class ConnectRecorder: ChannelOutboundHandler { var targetHost: String? var state: State = .idle - public func connect(ctx: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise?) { + public func connect(context: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise?) { self.targetHost = to.toString() - let connectPromise = promise ?? ctx.eventLoop.makePromise() + let connectPromise = promise ?? context.eventLoop.makePromise() connectPromise.futureResult.whenSuccess { self.state = .connected } - ctx.connect(to: to, promise: connectPromise) + context.connect(to: to, promise: connectPromise) } - public func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { - let connectPromise = promise ?? ctx.eventLoop.makePromise() + public func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { + let connectPromise = promise ?? context.eventLoop.makePromise() connectPromise.futureResult.whenComplete { (_: Result) in self.state = .closed } - ctx.close(promise: connectPromise) + context.close(promise: connectPromise) } } @@ -85,7 +85,7 @@ private class ConnectionDelayer: ChannelOutboundHandler { public var connectPromise: EventLoopPromise? - public func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + public func connect(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { self.connectPromise = promise } } diff --git a/Tests/NIOTests/IdleStateHandlerTest.swift b/Tests/NIOTests/IdleStateHandlerTest.swift index 6850a9f60..14f055cdf 100644 --- a/Tests/NIOTests/IdleStateHandlerTest.swift +++ b/Tests/NIOTests/IdleStateHandlerTest.swift @@ -52,24 +52,24 @@ class IdleStateHandlerTest : XCTestCase { self.assertEventFn = assertEventFn } - public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { self.read = true } - public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { if !self.writeToChannel { XCTAssertTrue(self.read) } XCTAssertTrue(assertEventFn(event as! IdleStateHandler.IdleStateEvent)) - ctx.close(promise: nil) + context.close(promise: nil) } - public func channelActive(ctx: ChannelHandlerContext) { + public func channelActive(context: ChannelHandlerContext) { if writeToChannel { - var buffer = ctx.channel.allocator.buffer(capacity: 4) + var buffer = context.channel.allocator.buffer(capacity: 4) buffer.writeStaticString("test") - ctx.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) + context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) } } } @@ -111,39 +111,39 @@ class IdleStateHandlerTest : XCTestCase { var registered = false var unregistered = false - func channelActive(ctx: ChannelHandlerContext) { + func channelActive(context: ChannelHandlerContext) { self.active = true } - func channelInactive(ctx: ChannelHandlerContext) { + func channelInactive(context: ChannelHandlerContext) { self.inactive = true } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { self.read = true } - func channelReadComplete(ctx: ChannelHandlerContext) { + func channelReadComplete(context: ChannelHandlerContext) { self.readComplete = true } - func channelWritabilityChanged(ctx: ChannelHandlerContext) { + func channelWritabilityChanged(context: ChannelHandlerContext) { self.writabilityChanged = true } - func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { self.eventTriggered = true } - func errorCaught(ctx: ChannelHandlerContext, error: Error) { + func errorCaught(context: ChannelHandlerContext, error: Error) { self.errorCaught = true } - func channelRegistered(ctx: ChannelHandlerContext) { + func channelRegistered(context: ChannelHandlerContext) { self.registered = true } - func channelUnregistered(ctx: ChannelHandlerContext) { + func channelUnregistered(context: ChannelHandlerContext) { self.unregistered = true } diff --git a/Tests/NIOTests/MulticastTest.swift b/Tests/NIOTests/MulticastTest.swift index f1a96816b..cea99d41b 100644 --- a/Tests/NIOTests/MulticastTest.swift +++ b/Tests/NIOTests/MulticastTest.swift @@ -25,9 +25,9 @@ final class PromiseOnReadHandler: ChannelInboundHandler { self.promise = promise } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { self.promise.succeed(self.unwrapInboundIn(data)) - _ = ctx.pipeline.removeHandler(ctx: ctx) + _ = context.pipeline.removeHandler(context: context) } } diff --git a/Tests/NIOTests/SelectorTest.swift b/Tests/NIOTests/SelectorTest.swift index 0a01300cd..ffec5f9fd 100644 --- a/Tests/NIOTests/SelectorTest.swift +++ b/Tests/NIOTests/SelectorTest.swift @@ -146,22 +146,22 @@ class SelectorTest: XCTestCase { self.hasReConnectEventLoopTickFinished = hasReConnectEventLoopTickFinished } - func channelActive(ctx: ChannelHandlerContext) { + func channelActive(context: ChannelHandlerContext) { // we expect these channels to be connected within the re-connect event loop tick XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value) } - func channelInactive(ctx: ChannelHandlerContext) { + func channelInactive(context: ChannelHandlerContext) { // we expect these channels to be close a while after the re-connect event loop tick XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value) XCTAssertTrue(self.didRead) if !self.didRead { self.didReadPromise.fail(DidNotReadError.didNotReadGotInactive) - ctx.close(promise: nil) + context.close(promise: nil) } } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { // we expect these channels to get data only a while after the re-connect event loop tick as it's // impossible to get a read notification in the very same event loop tick that you got registered XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value) @@ -174,14 +174,14 @@ class SelectorTest: XCTestCase { self.didReadPromise.succeed(()) } - func channelReadComplete(ctx: ChannelHandlerContext) { + func channelReadComplete(context: ChannelHandlerContext) { // we expect these channels to get data only a while after the re-connect event loop tick as it's // impossible to get a read notification in the very same event loop tick that you got registered XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value) XCTAssertTrue(self.didRead) if !self.didRead { self.didReadPromise.fail(DidNotReadError.didNotReadGotReadComplete) - ctx.close(promise: nil) + context.close(promise: nil) } } } @@ -210,16 +210,16 @@ class SelectorTest: XCTestCase { self.hasReConnectEventLoopTickFinished = hasReConnectEventLoopTickFinished } - func channelActive(ctx: ChannelHandlerContext) { + func channelActive(context: ChannelHandlerContext) { // collect all the channels - ctx.channel.getOption(ChannelOptions.allowRemoteHalfClosure).whenSuccess { halfClosureAllowed in + context.channel.getOption(ChannelOptions.allowRemoteHalfClosure).whenSuccess { halfClosureAllowed in precondition(halfClosureAllowed, "the test configuration is bogus: half-closure is dis-allowed which breaks the setup of this test") } - self.allChannels.value.append(ctx.channel) + self.allChannels.value.append(context.channel) } - func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { // this is the `.readEOF` that is triggered by the `ServerHandler`'s `close` calls because our channel // supports half-closure guard self.allChannels.value.count == SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse else { @@ -229,7 +229,7 @@ class SelectorTest: XCTestCase { // 1. let's close half the channels // 2. then re-connect (must be synchronous) the same number of channels and we'll get fd number re-use - ctx.channel.eventLoop.execute { + context.channel.eventLoop.execute { // this will be run immediately after we processed all `Selector` events so when // `self.hasReConnectEventLoopTickFinished.value` becomes true, we're out of the event loop // tick that is interesting. @@ -251,9 +251,9 @@ class SelectorTest: XCTestCase { var reconnectedChannelsHaveRead: [EventLoopFuture] = [] for _ in everyOtherIndex { var hasBeenAdded: Bool = false - let p = ctx.channel.eventLoop.makePromise(of: Void.self) + let p = context.channel.eventLoop.makePromise(of: Void.self) reconnectedChannelsHaveRead.append(p.futureResult) - let newChannel = ClientBootstrap(group: ctx.eventLoop) + let newChannel = ClientBootstrap(group: context.eventLoop) .channelInitializer { channel in channel.pipeline.addHandler(HappyWhenReadHandler(hasReConnectEventLoopTickFinished: self.hasReConnectEventLoopTickFinished, didReadPromise: p)).map { @@ -285,7 +285,7 @@ class SelectorTest: XCTestCase { } // if all the new re-connected channels have read, then we're happy here. - EventLoopFuture.andAllSucceed(reconnectedChannelsHaveRead, on: ctx.eventLoop) + EventLoopFuture.andAllSucceed(reconnectedChannelsHaveRead, on: context.eventLoop) .cascade(to: self.everythingWasReadPromise) // let's also remove all the channels so this code will not be triggered again. self.allChannels.value.removeAll() @@ -315,12 +315,12 @@ class SelectorTest: XCTestCase { self.numberOfConnectedChannels = numberOfConnectedChannels } - func channelActive(ctx: ChannelHandlerContext) { - var buf = ctx.channel.allocator.buffer(capacity: 1) + func channelActive(context: ChannelHandlerContext) { + var buf = context.channel.allocator.buffer(capacity: 1) buf.writeString("H") - ctx.channel.writeAndFlush(buf, promise: nil) + context.channel.writeAndFlush(buf, promise: nil) self.number += 1 - self.allServerChannels.value.append(ctx.channel) + self.allServerChannels.value.append(context.channel) if self.allServerChannels.value.count == SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse { // just to be sure all of the client channels have connected XCTAssertEqual(SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse, numberOfConnectedChannels.value) diff --git a/Tests/NIOTests/SocketChannelTest.swift b/Tests/NIOTests/SocketChannelTest.swift index 966c237de..758acd29d 100644 --- a/Tests/NIOTests/SocketChannelTest.swift +++ b/Tests/NIOTests/SocketChannelTest.swift @@ -132,11 +132,11 @@ public class SocketChannelTest : XCTestCase { self.promise = promise } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTFail("Should not accept a Channel but got \(self.unwrapInboundIn(data))") } - func errorCaught(ctx: ChannelHandlerContext, error: Error) { + func errorCaught(context: ChannelHandlerContext, error: Error) { if let ioError = error as? IOError { self.promise.succeed(ioError) } @@ -205,7 +205,7 @@ public class SocketChannelTest : XCTestCase { self.promise = promise } - func channelActive(ctx: ChannelHandlerContext) { + func channelActive(context: ChannelHandlerContext) { promise.succeed(()) } } @@ -387,7 +387,7 @@ public class SocketChannelTest : XCTestCase { private var connectPromise: EventLoopPromise? - public func channelInactive(ctx: ChannelHandlerContext) { + public func channelInactive(context: ChannelHandlerContext) { if let connectPromise = self.connectPromise { XCTAssertTrue(connectPromise.futureResult.isFulfilled) } else { @@ -395,17 +395,17 @@ public class SocketChannelTest : XCTestCase { } } - public func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + public func connect(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { XCTAssertNil(self.connectPromise) self.connectPromise = promise - ctx.connect(to: address, promise: promise) + context.connect(to: address, promise: promise) } - func handlerAdded(ctx: ChannelHandlerContext) { + func handlerAdded(context: ChannelHandlerContext) { XCTAssertNil(self.connectPromise) } - func handlerRemoved(ctx: ChannelHandlerContext) { + func handlerRemoved(context: ChannelHandlerContext) { if let connectPromise = self.connectPromise { XCTAssertTrue(connectPromise.futureResult.isFulfilled) } else { @@ -496,22 +496,22 @@ public class SocketChannelTest : XCTestCase { self.promise = promise } - func channelInactive(ctx: ChannelHandlerContext) { - XCTAssertNotNil(ctx.localAddress) - XCTAssertNotNil(ctx.remoteAddress) + func channelInactive(context: ChannelHandlerContext) { + XCTAssertNotNil(context.localAddress) + XCTAssertNotNil(context.remoteAddress) XCTAssertEqual(.created, state) state = .inactive } - func handlerRemoved(ctx: ChannelHandlerContext) { - XCTAssertNotNil(ctx.localAddress) - XCTAssertNotNil(ctx.remoteAddress) + func handlerRemoved(context: ChannelHandlerContext) { + XCTAssertNotNil(context.localAddress) + XCTAssertNotNil(context.remoteAddress) XCTAssertEqual(.inactive, state) state = .removed - ctx.channel.closeFuture.whenComplete { (_: Result) in - XCTAssertNil(ctx.localAddress) - XCTAssertNil(ctx.remoteAddress) + context.channel.closeFuture.whenComplete { (_: Result) in + XCTAssertNil(context.localAddress) + XCTAssertNil(context.remoteAddress) self.promise.succeed(()) } @@ -575,12 +575,12 @@ public class SocketChannelTest : XCTestCase { self.promise = promise } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTFail("Should not accept a Channel but got \(self.unwrapInboundIn(data))") self.promise.fail(ChannelError.inappropriateOperationForState) // any old error will do } - func errorCaught(ctx: ChannelHandlerContext, error: Error) { + func errorCaught(context: ChannelHandlerContext, error: Error) { if let ioError = error as? IOError, ioError.errnoCode == EINVAL { self.promise.succeed(ioError) } else { diff --git a/Tests/NIOTests/TestUtils.swift b/Tests/NIOTests/TestUtils.swift index ea70a18f0..946e3ba88 100644 --- a/Tests/NIOTests/TestUtils.swift +++ b/Tests/NIOTests/TestUtils.swift @@ -122,14 +122,14 @@ final class ByteCountingHandler : ChannelInboundHandler, RemovableChannelHandler self.promise = promise } - func handlerAdded(ctx: ChannelHandlerContext) { - buffer = ctx.channel.allocator.buffer(capacity: numBytes) + func handlerAdded(context: ChannelHandlerContext) { + buffer = context.channel.allocator.buffer(capacity: numBytes) if self.numBytes == 0 { self.promise.succeed(buffer) } } - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { var currentBuffer = self.unwrapInboundIn(data) buffer.writeBuffer(¤tBuffer) diff --git a/Tests/NIOWebSocketTests/EndToEndTests.swift b/Tests/NIOWebSocketTests/EndToEndTests.swift index c7a720105..693e01915 100644 --- a/Tests/NIOWebSocketTests/EndToEndTests.swift +++ b/Tests/NIOWebSocketTests/EndToEndTests.swift @@ -99,14 +99,14 @@ private class WebSocketRecorderHandler: ChannelInboundHandler { public var frames: [WebSocketFrame] = [] public var errors: [Error] = [] - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let frame = self.unwrapInboundIn(data) self.frames.append(frame) } - func errorCaught(ctx: ChannelHandlerContext, error: Error) { + func errorCaught(context: ChannelHandlerContext, error: Error) { self.errors.append(error) - ctx.fireErrorCaught(error) + context.fireErrorCaught(error) } } @@ -114,7 +114,7 @@ class EndToEndTests: XCTestCase { func createTestFixtures(upgraders: [WebSocketUpgrader]) -> (loop: EmbeddedEventLoop, serverChannel: EmbeddedChannel, clientChannel: EmbeddedChannel) { let loop = EmbeddedEventLoop() let serverChannel = EmbeddedChannel(loop: loop) - let upgradeConfig = (upgraders: upgraders as [HTTPServerProtocolUpgrader], completionHandler: { (ctx: ChannelHandlerContext) in } ) + let upgradeConfig = (upgraders: upgraders as [HTTPServerProtocolUpgrader], completionHandler: { (context: ChannelHandlerContext) in } ) XCTAssertNoThrow(try serverChannel.pipeline.configureHTTPServerPipeline(withServerUpgrade: upgradeConfig).wait()) let clientChannel = EmbeddedChannel(loop: loop) return (loop: loop, serverChannel: serverChannel, clientChannel: clientChannel) diff --git a/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift b/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift index 561d70ae3..2efb78a16 100644 --- a/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift +++ b/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift @@ -21,29 +21,29 @@ private class CloseSwallower: ChannelOutboundHandler, RemovableChannelHandler { typealias OutboundOut = Any private var closePromise: EventLoopPromise? = nil - private var ctx: ChannelHandlerContext? = nil + private var context: ChannelHandlerContext? = nil public func allowClose() { - self.ctx!.close(promise: self.closePromise) + self.context!.close(promise: self.closePromise) } - func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { + func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { self.closePromise = promise - self.ctx = ctx + self.context = context } } -/// A class that calls ctx.close() when it receives a decoded websocket frame, and validates that it does +/// A class that calls context.close() when it receives a decoded websocket frame, and validates that it does /// not receive two. private final class SynchronousCloser: ChannelInboundHandler { typealias InboundIn = WebSocketFrame private var closeFrame: WebSocketFrame? - func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + func channelRead(context: ChannelHandlerContext, data: NIOAny) { let frame = self.unwrapInboundIn(data) guard case .connectionClose = frame.opcode else { - ctx.fireChannelRead(data) + context.fireChannelRead(data) return } @@ -52,7 +52,7 @@ private final class SynchronousCloser: ChannelInboundHandler { self.closeFrame = frame // Now we're going to call close. - ctx.close(promise: nil) + context.close(promise: nil) } } diff --git a/docs/public-api-changes-NIO1-to-NIO2.md b/docs/public-api-changes-NIO1-to-NIO2.md index b0616f73c..3fcba67c7 100644 --- a/docs/public-api-changes-NIO1-to-NIO2.md +++ b/docs/public-api-changes-NIO1-to-NIO2.md @@ -1,5 +1,7 @@ # Changes in the Public API from NIO 1 to NIO 2 +- renamed all instances of `ctx` to `context`. Your `ChannelHandler` methods now + need to take a `context` parameter and no longer `ctx`. Example: `func channelRead(context: ChannelHandlerContext, data: NIOAny)` - removed all previously deprecated functions, types and modules. - renamed `SniResult` to `SNIResult` - renamed `SniHandler` to `SNIHandler`