diff --git a/Sources/NIOCore/ChannelPipeline.swift b/Sources/NIOCore/ChannelPipeline.swift index 3db4a88ab..2aa8d6c62 100644 --- a/Sources/NIOCore/ChannelPipeline.swift +++ b/Sources/NIOCore/ChannelPipeline.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -2131,6 +2131,23 @@ extension ChannelHandlerContext { self.writeAndFlush(data, promise: promise) return promise.futureResult } + + /// Returns this `ChannelHandlerContext` as a `NIOLoopBound`, bound to `self.eventLoop`. + /// + /// This is a shorthand for `NIOLoopBound(self, eventLoop: self.eventLoop)`. + /// + /// Being able to capture `ChannelHandlerContext`s in `EventLoopFuture` callbacks is important in SwiftNIO programs. + /// Of course, this is not always safe because the `EventLoopFuture` callbacks may run on other threads. SwiftNIO + /// programmers therefore always had to manually arrange for those callbacks to run on the correct `EventLoop` + /// (i.e. `context.eventLoop`) which then made that construction safe. + /// + /// Newer Swift versions contain a static feature to automatically detect data races which of course can't detect + /// the only _dynamically_ ``EventLoop`` a ``EventLoopFuture`` callback is running on. ``NIOLoopBound`` can be used + /// to prove to the compiler that this is safe and in case it is not, ``NIOLoopBound`` will trap at runtime. This is + /// therefore dynamically enforce the correct behaviour. + public var loopBound: NIOLoopBound { + NIOLoopBound(self, eventLoop: self.eventLoop) + } } @available(*, unavailable) diff --git a/Sources/NIOFileSystem/Internal/BufferedStream.swift b/Sources/NIOFileSystem/Internal/BufferedStream.swift index d68ed6b61..d450b00b5 100644 --- a/Sources/NIOFileSystem/Internal/BufferedStream.swift +++ b/Sources/NIOFileSystem/Internal/BufferedStream.swift @@ -243,7 +243,6 @@ extension BufferedStream { } /// A type that indicates the result of writing elements to the source. - @frozen internal enum WriteResult: Sendable { /// A token that is returned when the asynchronous stream's backpressure strategy indicated that production should /// be suspended. Use this token to enqueue a callback by calling the ``enqueueCallback(_:)`` method. diff --git a/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift b/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift index c6626dd0e..1272adc1f 100644 --- a/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift +++ b/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -439,9 +439,11 @@ 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: + let loopBoundContext = context.loopBound self.lifecycleState = .quiescingCompleted context.write(data).flatMap { - context.close() + let context = loopBoundContext.value + return context.close() }.cascade(to: promise) case .acceptingEvents, .quiescingWaitingForRequestEnd: context.write(data, promise: promise) diff --git a/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift b/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift index cadaff37c..464baeec3 100644 --- a/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift +++ b/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -180,14 +180,16 @@ public final class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableCha // We'll attempt to upgrade. This may take a while, so while we're waiting more data can come in. self.upgradeState = .awaitingUpgrader + let eventLoop = context.eventLoop + let loopBoundContext = context.loopBound self.handleUpgrade(context: context, request: request, requestedProtocols: requestedProtocols) - .hop(to: context.eventLoop) // the user might return a future from another EventLoop. + .hop(to: eventLoop) // the user might return a future from another EventLoop. .whenSuccess { callback in - context.eventLoop.assertInEventLoop() + eventLoop.assertInEventLoop() if let callback = callback { self.gotUpgrader(upgrader: callback) } else { - self.notUpgrading(context: context, data: requestPart) + self.notUpgrading(context: loopBoundContext.value, data: requestPart) } } } @@ -253,6 +255,8 @@ public final class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableCha } let responseHeaders = self.buildUpgradeHeaders(protocol: proto) + let pipeline = context.pipeline + let loopBoundContext = context.loopBound return upgrader.buildUpgradeResponse( channel: context.channel, upgradeRequest: request, @@ -271,18 +275,20 @@ public final class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableCha // 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(context: context).flatMap { + self.removeExtraHandlers(pipeline: pipeline).flatMap { self.sendUpgradeResponse( - context: context, + context: loopBoundContext.value, upgradeRequest: request, responseHeaders: finalResponseHeaders ) }.flatMap { - context.pipeline.syncOperations.removeHandler(self.httpEncoder) + pipeline.syncOperations.removeHandler(self.httpEncoder) }.flatMap { () -> EventLoopFuture in + let context = loopBoundContext.value self.upgradeCompletionHandler(context) return upgrader.upgrade(context: context, upgradeRequest: request) }.whenComplete { result in + let context = loopBoundContext.value switch result { case .success: context.fireUserInboundEventTriggered( @@ -300,6 +306,7 @@ public final class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableCha } }.flatMapError { error in // No upgrade here. We want to fire the error down the pipeline, and then try another loop iteration. + let context = loopBoundContext.value context.fireErrorCaught(error) return self.handleUpgradeForProtocol( context: context, @@ -366,14 +373,14 @@ public final class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableCha } /// Removes any extra HTTP-related handlers from the channel pipeline. - private func removeExtraHandlers(context: ChannelHandlerContext) -> EventLoopFuture { + private func removeExtraHandlers(pipeline: ChannelPipeline) -> EventLoopFuture { guard self.extraHTTPHandlers.count > 0 else { - return context.eventLoop.makeSucceededFuture(()) + return pipeline.eventLoop.makeSucceededFuture(()) } return .andAllSucceed( - self.extraHTTPHandlers.map { context.pipeline.removeHandler($0) }, - on: context.eventLoop + self.extraHTTPHandlers.map { pipeline.removeHandler($0) }, + on: pipeline.eventLoop ) } } diff --git a/Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift b/Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift index dbc403f69..66a7b1a17 100644 --- a/Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift +++ b/Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2019-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2019-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -325,19 +325,22 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC // Once that's done, we call the internal handler, then call the upgrader code, and then finally when the // upgrader 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. - { + let pipeline = context.pipeline + let loopBoundContext = context.loopBound + return { self.upgradeState = .upgrading - self.removeHTTPHandlers(context: context) + self.removeHTTPHandlers(pipeline: pipeline) .map { // Let the other handlers be removed before continuing with upgrade. - self.upgradeCompletionHandler(context) + self.upgradeCompletionHandler(loopBoundContext.value) self.upgradeState = .upgradingAddingHandlers } .flatMap { - upgrader.upgrade(context: context, upgradeResponse: response) + upgrader.upgrade(context: loopBoundContext.value, upgradeResponse: response) } .map { + let context = loopBoundContext.value // We unbuffer any buffered data here. // If we received any, we fire readComplete. @@ -356,19 +359,20 @@ public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableC self.upgradeState = .upgradeComplete } .whenComplete { _ in + let context = loopBoundContext.value context.pipeline.syncOperations.removeHandler(context: context, promise: nil) } } } /// Removes any extra HTTP-related handlers from the channel pipeline. - private func removeHTTPHandlers(context: ChannelHandlerContext) -> EventLoopFuture { + private func removeHTTPHandlers(pipeline: ChannelPipeline) -> EventLoopFuture { guard self.httpHandlers.count > 0 else { - return context.eventLoop.makeSucceededFuture(()) + return pipeline.eventLoop.makeSucceededFuture(()) } - let removeFutures = self.httpHandlers.map { context.pipeline.removeHandler($0) } - return .andAllSucceed(removeFutures, on: context.eventLoop) + let removeFutures = self.httpHandlers.map { pipeline.removeHandler($0) } + return .andAllSucceed(removeFutures, on: pipeline.eventLoop) } private func gotUpgrader(upgrader: @escaping (() -> Void)) { diff --git a/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift index 30f168c4e..29764820a 100644 --- a/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift +++ b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2013 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -191,6 +191,7 @@ public final class NIOTypedHTTPClientUpgradeHandler: Ch } private func channelRead(context: ChannelHandlerContext, responsePart: HTTPClientResponsePart) { + let loopBoundContext = context.loopBound switch self.stateMachine.channelReadResponsePart(responsePart) { case .fireErrorCaughtAndRemoveHandler(let error): self.upgradeResultPromise.fail(error) @@ -201,6 +202,7 @@ public final class NIOTypedHTTPClientUpgradeHandler: Ch self.notUpgradingCompletionHandler(context.channel) .hop(to: context.eventLoop) .whenComplete { result in + let context = loopBoundContext.value self.upgradingHandlerCompleted(context: context, result) } @@ -223,11 +225,14 @@ public final class NIOTypedHTTPClientUpgradeHandler: Ch ) { // Before we start the upgrade we have to remove the HTTPEncoder and HTTPDecoder handlers from the // pipeline, to prevent them parsing any more data. We'll buffer the incoming data until that completes. - self.removeHTTPHandlers(context: context) + let channel = context.channel + let loopBoundContext = context.loopBound + self.removeHTTPHandlers(pipeline: context.pipeline) .flatMap { - upgrader.upgrade(channel: context.channel, upgradeResponse: responseHead) + upgrader.upgrade(channel: channel, upgradeResponse: responseHead) }.hop(to: context.eventLoop) .whenComplete { result in + let context = loopBoundContext.value self.upgradingHandlerCompleted(context: context, result) } } @@ -275,13 +280,13 @@ public final class NIOTypedHTTPClientUpgradeHandler: Ch } /// Removes any extra HTTP-related handlers from the channel pipeline. - private func removeHTTPHandlers(context: ChannelHandlerContext) -> EventLoopFuture { + private func removeHTTPHandlers(pipeline: ChannelPipeline) -> EventLoopFuture { guard self.httpHandlers.count > 0 else { - return context.eventLoop.makeSucceededFuture(()) + return pipeline.eventLoop.makeSucceededFuture(()) } - let removeFutures = self.httpHandlers.map { context.pipeline.removeHandler($0) } - return .andAllSucceed(removeFutures, on: context.eventLoop) + let removeFutures = self.httpHandlers.map { pipeline.removeHandler($0) } + return .andAllSucceed(removeFutures, on: pipeline.eventLoop) } } #endif diff --git a/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift b/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift index b430cf1be..77fb961b0 100644 --- a/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift +++ b/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2023-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -174,6 +174,7 @@ public final class NIOTypedHTTPServerUpgradeHandler: Ch } private func channelRead(context: ChannelHandlerContext, requestPart: HTTPServerRequestPart) { + let loopBoundContext = context.loopBound switch self.stateMachine.channelReadRequestPart(requestPart) { case .failUpgradePromise(let error): self.upgradeResultPromise.fail(error) @@ -182,6 +183,7 @@ public final class NIOTypedHTTPServerUpgradeHandler: Ch self.notUpgradingCompletionHandler(context.channel) .hop(to: context.eventLoop) .whenComplete { result in + let context = loopBoundContext.value self.upgradingHandlerCompleted(context: context, result, requestHeadAndProtocol: nil) } @@ -194,6 +196,7 @@ public final class NIOTypedHTTPServerUpgradeHandler: Ch allHeaderNames: allHeaderNames, connectionHeader: connectionHeader ).whenComplete { result in + let context = loopBoundContext.value context.eventLoop.assertInEventLoop() self.findingUpgradeCompleted(context: context, requestHead: head, result) } @@ -297,6 +300,7 @@ public final class NIOTypedHTTPServerUpgradeHandler: Ch ) } + let loopBoundContext = context.loopBound let responseHeaders = self.buildUpgradeHeaders(protocol: proto) return upgrader.buildUpgradeResponse( channel: context.channel, @@ -307,6 +311,7 @@ public final class NIOTypedHTTPServerUpgradeHandler: Ch .map { (upgrader, $0, proto) } .flatMapError { error in // No upgrade here. We want to fire the error down the pipeline, and then try another loop iteration. + let context = loopBoundContext.value context.fireErrorCaught(error) return self.handleUpgradeForProtocol( context: context, @@ -339,9 +344,11 @@ public final class NIOTypedHTTPServerUpgradeHandler: Ch ) case .runNotUpgradingInitializer: + let loopBoundContext = context.loopBound self.notUpgradingCompletionHandler(context.channel) .hop(to: context.eventLoop) .whenComplete { result in + let context = loopBoundContext.value self.upgradingHandlerCompleted(context: context, result, requestHeadAndProtocol: nil) } @@ -376,14 +383,19 @@ public final class NIOTypedHTTPServerUpgradeHandler: Ch // 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(context: context).flatMap { - self.sendUpgradeResponse(context: context, responseHeaders: responseHeaders) + let channel = context.channel + let pipeline = context.pipeline + let loopBoundContext = context.loopBound + self.removeExtraHandlers(pipeline: pipeline).flatMap { + let context = loopBoundContext.value + return self.sendUpgradeResponse(context: context, responseHeaders: responseHeaders) }.flatMap { - context.pipeline.syncOperations.removeHandler(self.httpEncoder) + pipeline.syncOperations.removeHandler(self.httpEncoder) }.flatMap { () -> EventLoopFuture in - upgrader.upgrade(channel: context.channel, upgradeRequest: requestHead) + upgrader.upgrade(channel: channel, upgradeRequest: requestHead) }.hop(to: context.eventLoop) .whenComplete { result in + let context = loopBoundContext.value self.upgradingHandlerCompleted(context: context, result, requestHeadAndProtocol: (requestHead, proto)) } } @@ -404,14 +416,14 @@ public final class NIOTypedHTTPServerUpgradeHandler: Ch } /// Removes any extra HTTP-related handlers from the channel pipeline. - private func removeExtraHandlers(context: ChannelHandlerContext) -> EventLoopFuture { + private func removeExtraHandlers(pipeline: ChannelPipeline) -> EventLoopFuture { guard self.extraHTTPHandlers.count > 0 else { - return context.eventLoop.makeSucceededFuture(()) + return pipeline.eventLoop.makeSucceededFuture(()) } return .andAllSucceed( - self.extraHTTPHandlers.map { context.pipeline.removeHandler($0) }, - on: context.eventLoop + self.extraHTTPHandlers.map { pipeline.removeHandler($0) }, + on: pipeline.eventLoop ) } diff --git a/Sources/NIOHTTP1Server/main.swift b/Sources/NIOHTTP1Server/main.swift index 2b662bcc3..d3b6ce133 100644 --- a/Sources/NIOHTTP1Server/main.swift +++ b/Sources/NIOHTTP1Server/main.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -207,7 +207,7 @@ private final class HTTPHandler: ChannelInboundHandler { () case .end: self.state.requestComplete() - let loopBoundContext = NIOLoopBound(context, eventLoop: context.eventLoop) + let loopBoundContext = context.loopBound let loopBoundSelf = NIOLoopBound(self, eventLoop: context.eventLoop) context.eventLoop.scheduleTask(in: delay) { () -> Void in let `self` = loopBoundSelf.value @@ -501,7 +501,7 @@ private final class HTTPHandler: ChannelInboundHandler { promise: EventLoopPromise? ) { self.state.responseComplete() - let loopBoundContext = NIOLoopBound(context, eventLoop: context.eventLoop) + let loopBoundContext = context.loopBound let promise = self.keepAlive ? promise : (promise ?? context.eventLoop.makePromise()) if !self.keepAlive { diff --git a/Sources/NIOPosix/Bootstrap.swift b/Sources/NIOPosix/Bootstrap.swift index ff2773a2c..fa117e857 100644 --- a/Sources/NIOPosix/Bootstrap.swift +++ b/Sources/NIOPosix/Bootstrap.swift @@ -431,6 +431,7 @@ public final class ServerBootstrap { final class AcceptHandler: ChannelInboundHandler { public typealias InboundIn = SocketChannel + public typealias InboundOut = SocketChannel private let childChannelInit: ((Channel) -> EventLoopFuture)? private let childChannelOptions: ChannelOptions.Storage @@ -445,7 +446,9 @@ public final class ServerBootstrap { func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { if event is ChannelShouldQuiesceEvent { + let loopBoundContext = context.loopBound context.channel.close().whenFailure { error in + let context = loopBoundContext.value context.fireErrorCaught(error) } } @@ -467,28 +470,33 @@ public final class ServerBootstrap { } @inline(__always) - func fireThroughPipeline(_ future: EventLoopFuture) { + func fireThroughPipeline(_ future: EventLoopFuture, context: ChannelHandlerContext) { ctxEventLoop.assertInEventLoop() + assert(ctxEventLoop === context.eventLoop) + let loopBoundContext = context.loopBound future.flatMap { (_) -> EventLoopFuture in + let context = loopBoundContext.value ctxEventLoop.assertInEventLoop() guard context.channel.isActive else { - return context.eventLoop.makeFailedFuture(ChannelError._ioOnClosedChannel) + return ctxEventLoop.makeFailedFuture(ChannelError._ioOnClosedChannel) } - context.fireChannelRead(data) + context.fireChannelRead(Self.wrapInboundOut(accepted)) return context.eventLoop.makeSucceededFuture(()) }.whenFailure { error in + let context = loopBoundContext.value ctxEventLoop.assertInEventLoop() self.closeAndFire(context: context, accepted: accepted, err: error) } } if childEventLoop === ctxEventLoop { - fireThroughPipeline(setupChildChannel()) + fireThroughPipeline(setupChildChannel(), context: context) } else { fireThroughPipeline( childEventLoop.flatSubmit { setupChildChannel() - }.hop(to: ctxEventLoop) + }.hop(to: ctxEventLoop), + context: context ) } } @@ -498,7 +506,9 @@ public final class ServerBootstrap { if context.eventLoop.inEventLoop { context.fireErrorCaught(err) } else { + let loopBoundContext = context.loopBound context.eventLoop.execute { + let context = loopBoundContext.value context.fireErrorCaught(err) } } @@ -998,7 +1008,8 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { let connectPromise = channel.eventLoop.makePromise(of: Void.self) channel.connect(to: address, promise: connectPromise) let cancelTask = channel.eventLoop.scheduleTask(in: self.connectTimeout) { - connectPromise.fail(ChannelError.connectTimeout(self.connectTimeout)) + [connectTimeout = self.connectTimeout] in + connectPromise.fail(ChannelError.connectTimeout(connectTimeout)) channel.close(promise: nil) } @@ -1147,8 +1158,8 @@ public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { @inline(__always) func setupChannel() -> EventLoopFuture { eventLoop.assertInEventLoop() - return channelOptions.applyAllChannelOptions(to: channel).flatMap { - if let bindTarget = self.bindTarget { + return channelOptions.applyAllChannelOptions(to: channel).flatMap { [bindTarget = self.bindTarget] in + if let bindTarget = bindTarget { return channel.bind(to: bindTarget).flatMap { channelInitializer(channel) } diff --git a/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift b/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift index 3d6859dec..71186337f 100644 --- a/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift +++ b/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -119,10 +119,12 @@ public final class ApplicationProtocolNegotiationHandler: ChannelInboundHandler, private func invokeUserClosure(context: ChannelHandlerContext, result: ALPNResult) { let switchFuture = self.completionHandler(result, context.channel) + let loopBoundSelfAndContext = NIOLoopBound((self, context), eventLoop: context.eventLoop) switchFuture .hop(to: context.eventLoop) .whenComplete { result in + let (`self`, context) = loopBoundSelfAndContext.value self.userFutureCompleted(context: context, result: result) } } diff --git a/Sources/NIOTLS/NIOTypedApplicationProtocolNegotiationHandler.swift b/Sources/NIOTLS/NIOTypedApplicationProtocolNegotiationHandler.swift index 4749be12e..75d95c5a4 100644 --- a/Sources/NIOTLS/NIOTypedApplicationProtocolNegotiationHandler.swift +++ b/Sources/NIOTLS/NIOTypedApplicationProtocolNegotiationHandler.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2023-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -125,10 +125,12 @@ public final class NIOTypedApplicationProtocolNegotiationHandler?) { + let loopBoundContext = context.loopBound switch Self.unwrapOutboundIn(data) { case .head(var head): head.headers.replaceOrAdd(name: "connection", value: "close") @@ -127,6 +128,7 @@ private final class WebServerHandler: ChannelDuplexHandler { context.write(data, promise: promise) case .end: context.write(data).map { + let context = loopBoundContext.value context.close(promise: nil) }.cascade(to: promise) } diff --git a/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift b/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift index 89714f4c9..e367184b6 100644 --- a/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift +++ b/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -25,6 +25,7 @@ public final class WebSocketProtocolErrorHandler: ChannelInboundHandler { public init() {} public func errorCaught(context: ChannelHandlerContext, error: Error) { + let loopBoundContext = context.loopBound if let error = error as? NIOWebSocketError { var data = context.channel.allocator.buffer(capacity: 2) data.write(webSocketErrorCode: WebSocketErrorCode(error)) @@ -34,6 +35,7 @@ public final class WebSocketProtocolErrorHandler: ChannelInboundHandler { data: data ) context.writeAndFlush(Self.wrapOutboundOut(frame)).whenComplete { (_: Result) in + let context = loopBoundContext.value context.close(promise: nil) } } diff --git a/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift b/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift index 56c09b67f..3c77ca624 100644 --- a/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift +++ b/Tests/NIOEmbeddedTests/EmbeddedChannelTest.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -478,7 +478,7 @@ class EmbeddedChannelTest: XCTestCase { func testFinishWithRecursivelyScheduledTasks() throws { let channel = EmbeddedChannel() - var tasks: [Scheduled] = [] + let tasks: NIOLoopBoundBox<[Scheduled]> = NIOLoopBoundBox([], eventLoop: channel.eventLoop) var invocations = 0 func recursivelyScheduleAndIncrement() { @@ -486,7 +486,7 @@ class EmbeddedChannelTest: XCTestCase { invocations += 1 recursivelyScheduleAndIncrement() } - tasks.append(task) + tasks.value.append(task) } recursivelyScheduleAndIncrement() @@ -497,11 +497,11 @@ class EmbeddedChannelTest: XCTestCase { XCTAssertEqual(invocations, 0) // Because the root task didn't run, it should be the onnly one scheduled. - XCTAssertEqual(tasks.count, 1) + XCTAssertEqual(tasks.value.count, 1) // Check the task was failed with cancelled error. let taskChecked = expectation(description: "task future fulfilled") - tasks.first?.futureResult.whenComplete { result in + tasks.value.first?.futureResult.whenComplete { result in switch result { case .success: XCTFail("Expected task to be cancelled, not run.") case .failure(let error): XCTAssertEqual(error as? EventLoopError, .cancelled) diff --git a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift index 537fa0740..43cfbb4c6 100644 --- a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2019-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2019-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -200,8 +200,8 @@ private final class UpgradeDelayClientUpgrader: TypedAndUntypedHTTPClientProtoco fileprivate func upgrade(context: ChannelHandlerContext, upgradeResponse: HTTPResponseHead) -> EventLoopFuture { self.upgradePromise = context.eventLoop.makePromise() - return self.upgradePromise!.futureResult.flatMap { - context.pipeline.addHandler(self.upgradedHandler) + return self.upgradePromise!.futureResult.flatMap { [pipeline = context.pipeline] in + pipeline.addHandler(self.upgradedHandler) } } @@ -1104,10 +1104,12 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase { handlerType: NIOTypedHTTPClientUpgradeHandler.self ) + let loopBoundContext = context.loopBound try channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 0)) .wait() upgradeResult.whenSuccess { result in if result { + let context = loopBoundContext.value upgradeCompletionHandler(context) } } diff --git a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift index da74c7685..ffb144e5c 100644 --- a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -251,8 +251,8 @@ class HTTPDecoderTest: XCTestCase { let part = Self.unwrapInboundIn(data) switch part { case .end: - _ = context.pipeline.removeHandler(self).flatMap { _ in - context.pipeline.addHandler(self.collector) + _ = context.pipeline.removeHandler(self).flatMap { [pipeline = context.pipeline] _ in + pipeline.addHandler(self.collector) } default: // ignore @@ -324,8 +324,8 @@ class HTTPDecoderTest: XCTestCase { let part = Self.unwrapInboundIn(data) switch part { case .end: - _ = context.pipeline.removeHandler(self).flatMap { _ in - context.pipeline.addHandler(ByteCollector()) + _ = context.pipeline.removeHandler(self).flatMap { [pipeline = context.pipeline] _ in + pipeline.addHandler(ByteCollector()) } break default: diff --git a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift index 28a42923a..c42e7c406 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift @@ -109,6 +109,7 @@ class HTTPServerClientTest: XCTestCase { } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { + let loopBoundContext = context.loopBound switch Self.unwrapInboundIn(data) { case .head(let req): switch req.uri { @@ -129,6 +130,7 @@ class HTTPServerClientTest: XCTestCase { context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in + let context = loopBoundContext.value self.sentEnd = true self.maybeClose(context: context) } @@ -154,6 +156,7 @@ class HTTPServerClientTest: XCTestCase { context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in + let context = loopBoundContext.value self.sentEnd = true self.maybeClose(context: context) } @@ -184,6 +187,7 @@ class HTTPServerClientTest: XCTestCase { context.write(Self.wrapOutboundOut(.end(trailers))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in + let context = loopBoundContext.value self.sentEnd = true self.maybeClose(context: context) } @@ -208,6 +212,7 @@ class HTTPServerClientTest: XCTestCase { context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in + let context = loopBoundContext.value self.sentEnd = true self.maybeClose(context: context) } @@ -221,6 +226,7 @@ class HTTPServerClientTest: XCTestCase { context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in + let context = loopBoundContext.value self.sentEnd = true self.maybeClose(context: context) } @@ -233,6 +239,7 @@ class HTTPServerClientTest: XCTestCase { context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in + let context = loopBoundContext.value self.sentEnd = true self.maybeClose(context: context) } @@ -251,6 +258,7 @@ class HTTPServerClientTest: XCTestCase { context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in + let context = loopBoundContext.value self.sentEnd = true self.maybeClose(context: context) } @@ -271,6 +279,7 @@ class HTTPServerClientTest: XCTestCase { context.write(Self.wrapOutboundOut(.end(nil))).recover { error in XCTFail("unexpected error \(error)") }.whenComplete { (_: Result) in + let context = loopBoundContext.value self.sentEnd = true self.maybeClose(context: context) } diff --git a/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift b/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift index 15144e8f2..f78cdff13 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -912,11 +912,13 @@ class HTTPServerPipelineHandlerTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { + let loopBoundContext = context.loopBound switch Self.unwrapInboundIn(data) { case .head: // We dispatch this to the event loop so that it doesn't happen immediately but rather can be // run from the driving test code whenever it wants by running the EmbeddedEventLoop. context.eventLoop.execute { + let context = loopBoundContext.value context.writeAndFlush( Self.wrapOutboundOut( .head( @@ -937,6 +939,7 @@ class HTTPServerPipelineHandlerTest: XCTestCase { // We dispatch this to the event loop so that it doesn't happen immediately but rather can be // run from the driving test code whenever it wants by running the EmbeddedEventLoop. context.eventLoop.execute { + let context = loopBoundContext.value context.writeAndFlush(Self.wrapOutboundOut(.end(nil)), promise: nil) } XCTAssertEqual(.reqEndExpected, self.state) diff --git a/Tests/NIOPosixTests/ChannelNotificationTest.swift b/Tests/NIOPosixTests/ChannelNotificationTest.swift index cf0b963d5..fe6fdf472 100644 --- a/Tests/NIOPosixTests/ChannelNotificationTest.swift +++ b/Tests/NIOPosixTests/ChannelNotificationTest.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -138,8 +138,8 @@ class ChannelNotificationTest: XCTestCase { XCTAssertNil(self.connectPromise) XCTAssertNil(self.closePromise) - promise!.futureResult.whenSuccess { - XCTAssertFalse(context.channel.isActive) + promise!.futureResult.whenSuccess { [channel = context.channel] in + XCTAssertFalse(channel.isActive) } self.registerPromise = promise @@ -157,8 +157,8 @@ class ChannelNotificationTest: XCTestCase { XCTAssertNil(self.connectPromise) XCTAssertNil(self.closePromise) - promise!.futureResult.whenSuccess { - XCTAssertTrue(context.channel.isActive) + promise!.futureResult.whenSuccess { [channel = context.channel] in + XCTAssertTrue(channel.isActive) } self.connectPromise = promise @@ -170,8 +170,8 @@ class ChannelNotificationTest: XCTestCase { XCTAssertNotNil(self.connectPromise) XCTAssertNil(self.closePromise) - promise!.futureResult.whenSuccess { - XCTAssertFalse(context.channel.isActive) + promise!.futureResult.whenSuccess { [channel = context.channel] in + XCTAssertFalse(channel.isActive) } self.closePromise = promise @@ -248,8 +248,8 @@ class ChannelNotificationTest: XCTestCase { XCTAssertNil(self.registerPromise) let p = promise ?? context.eventLoop.makePromise() - p.futureResult.whenSuccess { - XCTAssertFalse(context.channel.isActive) + p.futureResult.whenSuccess { [channel = context.channel] in + XCTAssertFalse(channel.isActive) } self.registerPromise = p @@ -354,8 +354,8 @@ class ChannelNotificationTest: XCTestCase { XCTAssertNil(self.closePromise) let p = promise ?? context.eventLoop.makePromise() - p.futureResult.whenSuccess { - XCTAssertFalse(context.channel.isActive) + p.futureResult.whenSuccess { [channel = context.channel] in + XCTAssertFalse(channel.isActive) } self.registerPromise = p @@ -373,8 +373,8 @@ class ChannelNotificationTest: XCTestCase { XCTAssertNil(self.bindPromise) XCTAssertNil(self.closePromise) - promise?.futureResult.whenSuccess { - XCTAssertTrue(context.channel.isActive) + promise?.futureResult.whenSuccess { [channel = context.channel] in + XCTAssertTrue(channel.isActive) } self.bindPromise = promise @@ -387,8 +387,8 @@ class ChannelNotificationTest: XCTestCase { XCTAssertNil(self.closePromise) let p = promise ?? context.eventLoop.makePromise() - p.futureResult.whenSuccess { - XCTAssertFalse(context.channel.isActive) + p.futureResult.whenSuccess { [channel = context.channel] in + XCTAssertFalse(channel.isActive) } self.closePromise = p diff --git a/Tests/NIOPosixTests/ChannelPipelineTest.swift b/Tests/NIOPosixTests/ChannelPipelineTest.swift index 9226d7a0a..130e39fd2 100644 --- a/Tests/NIOPosixTests/ChannelPipelineTest.swift +++ b/Tests/NIOPosixTests/ChannelPipelineTest.swift @@ -803,7 +803,9 @@ class ChannelPipelineTest: XCTestCase { buffer.writeStaticString("Hello, world!") let removalPromise = channel.eventLoop.makePromise(of: Void.self) + let loopBoundContext = context.loopBound removalPromise.futureResult.whenSuccess { + let context = loopBoundContext.value context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) } @@ -845,7 +847,9 @@ class ChannelPipelineTest: XCTestCase { XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound())) XCTAssertNoThrow(try channel.throwIfErrorCaught()) + let loopBoundContext = context.loopBound channel.pipeline.syncOperations.removeHandler(context: context).whenSuccess { + let context = loopBoundContext.value context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) } @@ -873,7 +877,9 @@ class ChannelPipelineTest: XCTestCase { buffer.writeStaticString("Hello, world!") let removalPromise = channel.eventLoop.makePromise(of: Void.self) + let loopBoundContext = context.loopBound removalPromise.futureResult.map { + let context = loopBoundContext._value context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) }.whenFailure { @@ -912,7 +918,9 @@ class ChannelPipelineTest: XCTestCase { XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound())) XCTAssertNoThrow(try channel.throwIfErrorCaught()) + let loopBoundContext = context.loopBound channel.pipeline.removeHandler(name: "TestHandler").whenSuccess { + let context = loopBoundContext.value context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) } @@ -941,7 +949,9 @@ class ChannelPipelineTest: XCTestCase { buffer.writeStaticString("Hello, world!") let removalPromise = channel.eventLoop.makePromise(of: Void.self) + let loopBoundContext = context.loopBound removalPromise.futureResult.whenSuccess { + let context = loopBoundContext.value context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) } @@ -979,7 +989,9 @@ class ChannelPipelineTest: XCTestCase { XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound())) XCTAssertNoThrow(try channel.throwIfErrorCaught()) + let loopBoundContext = context.loopBound channel.pipeline.removeHandler(handler).whenSuccess { + let context = loopBoundContext.value context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) } @@ -1403,7 +1415,9 @@ class ChannelPipelineTest: XCTestCase { self.removeHandlerCalls += 1 XCTAssertEqual(1, self.removeHandlerCalls) self.removalTriggeredPromise.succeed(()) + let loopBoundContext = context.loopBound self.continueRemovalFuture.whenSuccess { + let context = loopBoundContext.value context.leavePipeline(removalToken: removalToken) } } diff --git a/Tests/NIOPosixTests/ChannelTests.swift b/Tests/NIOPosixTests/ChannelTests.swift index 8774c4f6a..362260ebe 100644 --- a/Tests/NIOPosixTests/ChannelTests.swift +++ b/Tests/NIOPosixTests/ChannelTests.swift @@ -2953,7 +2953,9 @@ public final class ChannelTests: XCTestCase { func channelActive(context: ChannelHandlerContext) { var buffer = context.channel.allocator.buffer(capacity: 1) buffer.writeStaticString("X") - context.channel.writeAndFlush(buffer).map { context.channel }.cascade( + context.channel.writeAndFlush(buffer).map { [channel = context.channel] in + channel + }.cascade( to: self.channelAvailablePromise ) } @@ -3003,7 +3005,8 @@ public final class ChannelTests: XCTestCase { func channelActive(context: ChannelHandlerContext) { XCTAssert(serverChannel.eventLoop === context.eventLoop) - self.serverChannel.whenSuccess { serverChannel in + let loopBoundContext = context.loopBound + self.serverChannel.whenSuccess { [channel = context.channel] 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. var inSameStackFrame = true @@ -3014,9 +3017,10 @@ public final 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) - context.channel.setOption(.autoRead, value: true).flatMap { + channel.setOption(.autoRead, value: true).flatMap { + let context = loopBoundContext.value // let's trigger the write error - var buffer = context.channel.allocator.buffer(capacity: 16) + var buffer = 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 @@ -3025,7 +3029,7 @@ public final class ChannelTests: XCTestCase { // 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: context.channel) + try self.veryNasty_blockUntilReadBufferIsNonEmpty(channel: channel) ) } workaroundSR487() @@ -3489,8 +3493,10 @@ private final class FailRegistrationAndDelayCloseHandler: ChannelOutboundHandler } func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { + let loopBoundContext = context.loopBound // for extra nastiness, let's delay close. This makes sure the ChannelPipeline correctly retains the Channel _ = context.eventLoop.scheduleTask(in: .milliseconds(10)) { + let context = loopBoundContext.value context.close(mode: mode, promise: promise) } } @@ -3559,7 +3565,9 @@ final class ReentrantWritabilityChangingHandler: ChannelInboundHandler { // emitted. The flush for that write should result in the writability flipping back // again. let b1 = context.channel.allocator.buffer(repeating: 0, count: 50) + let loopBoundContext = context.loopBound context.write(Self.wrapOutboundOut(b1)).whenSuccess { _ in + let context = loopBoundContext.value // We should still be writable. XCTAssertTrue(context.channel.isWritable) XCTAssertEqual(self.isNotWritableCount, 0) diff --git a/Tests/NIOPosixTests/EchoServerClientTest.swift b/Tests/NIOPosixTests/EchoServerClientTest.swift index 2be0133d9..678f6da80 100644 --- a/Tests/NIOPosixTests/EchoServerClientTest.swift +++ b/Tests/NIOPosixTests/EchoServerClientTest.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -382,6 +382,7 @@ class EchoServerClientTest: XCTestCase { private final class EchoAndEchoAgainAfterSomeTimeServer: ChannelInboundHandler { typealias InboundIn = ByteBuffer + typealias InboundOut = ByteBuffer typealias OutboundOut = ByteBuffer private let timeAmount: TimeAmount @@ -398,10 +399,13 @@ class EchoServerClientTest: XCTestCase { } func channelRead(context: ChannelHandlerContext, data: NIOAny) { + let bytes = Self.unwrapInboundIn(data) self.numberOfReads += 1 precondition(self.numberOfReads == 1, "\(self) is only ever allowed to read once") + let loopBoundContext = context.loopBound _ = context.eventLoop.scheduleTask(in: self.timeAmount) { - context.writeAndFlush(data, promise: nil) + let context = loopBoundContext.value + context.writeAndFlush(Self.wrapInboundOut(bytes), promise: nil) self.group.leave() }.futureResult.recover { e in XCTFail("we failed to schedule the task: \(e)") @@ -753,8 +757,10 @@ class EchoServerClientTest: XCTestCase { } private func writeUntilFailed(_ context: ChannelHandlerContext, _ buffer: ByteBuffer) { - context.writeAndFlush(NIOAny(buffer)).whenSuccess { - context.eventLoop.execute { + let loopBoundContext = context.loopBound + context.writeAndFlush(NIOAny(buffer)).whenSuccess { [eventLoop = context.eventLoop] in + eventLoop.execute { + let context = loopBoundContext.value self.writeUntilFailed(context, buffer) } } @@ -776,14 +782,19 @@ class EchoServerClientTest: XCTestCase { let buffer = context.channel.allocator.buffer(string: str) // write it four times and then close the connect. + let loopBoundContext = context.loopBound context.writeAndFlush(NIOAny(buffer)).flatMap { - context.writeAndFlush(NIOAny(buffer)) + let context = loopBoundContext.value + return context.writeAndFlush(NIOAny(buffer)) }.flatMap { - context.writeAndFlush(NIOAny(buffer)) + let context = loopBoundContext.value + return context.writeAndFlush(NIOAny(buffer)) }.flatMap { - context.writeAndFlush(NIOAny(buffer)) + let context = loopBoundContext.value + return context.writeAndFlush(NIOAny(buffer)) }.flatMap { - context.close() + let context = loopBoundContext.value + return context.close() }.whenComplete { (_: Result) in self.dpGroup.leave() } diff --git a/Tests/NIOPosixTests/EventLoopTest.swift b/Tests/NIOPosixTests/EventLoopTest.swift index 4b0abd953..f14ba2dc4 100644 --- a/Tests/NIOPosixTests/EventLoopTest.swift +++ b/Tests/NIOPosixTests/EventLoopTest.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -542,7 +542,9 @@ public final class EventLoopTest: XCTestCase { } XCTAssertTrue(context.channel.isActive) self.closePromise = context.eventLoop.makePromise() + let loopBoundContext = context.loopBound self.closePromise!.futureResult.whenSuccess { + let context = loopBoundContext.value context.close(mode: mode, promise: promise) } promiseRegisterCallback(self.closePromise!) diff --git a/Tests/NIOPosixTests/IdleStateHandlerTest.swift b/Tests/NIOPosixTests/IdleStateHandlerTest.swift index 87ae3d8cd..04b81173c 100644 --- a/Tests/NIOPosixTests/IdleStateHandlerTest.swift +++ b/Tests/NIOPosixTests/IdleStateHandlerTest.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -37,7 +37,7 @@ class IdleStateHandlerTest: XCTestCase { } private func testIdle( - _ handler: IdleStateHandler, + _ handler: @escaping @Sendable @autoclosure () -> IdleStateHandler, _ writeToChannel: Bool, _ assertEventFn: @escaping (IdleStateHandler.IdleStateEvent) -> Bool ) throws { @@ -86,6 +86,7 @@ class IdleStateHandlerTest: XCTestCase { .serverChannelOption(.socketOption(.so_reuseaddr), value: 1) .childChannelInitializer { channel in channel.eventLoop.makeCompletedFuture { + let handler = handler() try channel.pipeline.syncOperations.addHandler(handler) try channel.pipeline.syncOperations.addHandler(TestWriteHandler(writeToChannel, assertEventFn)) } diff --git a/Tests/NIOPosixTests/NIOThreadPoolTest.swift b/Tests/NIOPosixTests/NIOThreadPoolTest.swift index a1969f620..ed39352df 100644 --- a/Tests/NIOPosixTests/NIOThreadPoolTest.swift +++ b/Tests/NIOPosixTests/NIOThreadPoolTest.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2020-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -79,15 +79,17 @@ class NIOThreadPoolTest: XCTestCase { // The lock here is arguably redundant with the dispatchgroup, but let's make // this test thread-safe even if I screw up. let lock = NIOLock() - var threadOne = Thread?.none - var threadTwo = Thread?.none + let threadOne: NIOLockedValueBox = NIOLockedValueBox(Thread?.none) + let threadTwo: NIOLockedValueBox = NIOLockedValueBox(Thread?.none) completionGroup.enter() pool.submit { s in precondition(s == .active) lock.withLock { () -> Void in - XCTAssertEqual(threadOne, nil) - threadOne = Thread.current + threadOne.withLockedValue { threadOne in + XCTAssertEqual(threadOne, nil) + threadOne = Thread.current + } } completionGroup.leave() } @@ -98,8 +100,10 @@ class NIOThreadPoolTest: XCTestCase { pool.submit { s in precondition(s == .active) lock.withLock { () -> Void in - XCTAssertEqual(threadTwo, nil) - threadTwo = Thread.current + threadTwo.withLockedValue { threadTwo in + XCTAssertEqual(threadTwo, nil) + threadTwo = Thread.current + } } completionGroup.leave() } @@ -109,7 +113,7 @@ class NIOThreadPoolTest: XCTestCase { lock.withLock { () -> Void in XCTAssertNotNil(threadOne) XCTAssertNotNil(threadTwo) - XCTAssertEqual(threadOne, threadTwo) + XCTAssertEqual(threadOne.withLockedValue { $0 }, threadTwo.withLockedValue { $0 }) } } diff --git a/Tests/NIOPosixTests/SocketChannelTest.swift b/Tests/NIOPosixTests/SocketChannelTest.swift index ebd478760..cb8161a7e 100644 --- a/Tests/NIOPosixTests/SocketChannelTest.swift +++ b/Tests/NIOPosixTests/SocketChannelTest.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -550,7 +550,9 @@ public final class SocketChannelTest: XCTestCase { XCTAssertEqual(.inactive, state) state = .removed + let loopBoundContext = context.loopBound context.channel.closeFuture.whenComplete { (_: Result) in + let context = loopBoundContext.value XCTAssertNil(context.localAddress) XCTAssertNil(context.remoteAddress) diff --git a/Tests/NIOPosixTests/StreamChannelsTest.swift b/Tests/NIOPosixTests/StreamChannelsTest.swift index 277b88594..072f35d41 100644 --- a/Tests/NIOPosixTests/StreamChannelsTest.swift +++ b/Tests/NIOPosixTests/StreamChannelsTest.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2019-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2019-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -486,9 +486,11 @@ class StreamChannelTest: XCTestCase { // raise the high water mark so we don't get another call straight away. var buffer = context.channel.allocator.buffer(capacity: 5) buffer.writeString("hello") + let loopBoundContext = context.loopBound context.channel.setOption(.writeBufferWaterMark, value: .init(low: 1024, high: 1024)) .flatMap { - context.writeAndFlush(Self.wrapOutboundOut(buffer)) + let context = loopBoundContext.value + return context.writeAndFlush(Self.wrapOutboundOut(buffer)) }.whenFailure { error in XCTFail("unexpected error: \(error)") } @@ -638,7 +640,9 @@ class StreamChannelTest: XCTestCase { XCTFail("unexpected error \(error)") } + let loopBoundContext = context.loopBound context.eventLoop.execute { + let context = loopBoundContext.value self.kickOff(context: context) } } @@ -648,26 +652,34 @@ class StreamChannelTest: XCTestCase { } func kickOff(context: ChannelHandlerContext) { - var buffer = context.channel.allocator.buffer(capacity: self.chunkSize) - buffer.writeBytes(Array(repeating: UInt8(ascii: "0"), count: chunkSize)) + let buffer = NIOLoopBoundBox( + context.channel.allocator.buffer(capacity: self.chunkSize), + eventLoop: context.eventLoop + ) + buffer.value.writeBytes(Array(repeating: UInt8(ascii: "0"), count: chunkSize)) + let loopBoundContext = context.loopBound + let loopBoundSelf = NIOLoopBound(self, eventLoop: context.eventLoop) func writeOneMore() { - self.bytesWritten += buffer.readableBytes - context.writeAndFlush(Self.wrapOutboundOut(buffer)).whenFailure { error in + let context = loopBoundContext.value + self.bytesWritten += buffer.value.readableBytes + context.writeAndFlush(Self.wrapOutboundOut(buffer.value)).whenFailure { error in XCTFail("unexpected error \(error)") } context.eventLoop.scheduleTask(in: .microseconds(100)) { + let context = loopBoundContext.value switch self.state { case .writingUntilFull: // We're just enqueuing another chunk. writeOneMore() case .writeSentinel: + let `self` = loopBoundSelf.value // We've seen the notification that the channel is unwritable, let's write one more byte. - buffer.clear() - buffer.writeString("1") + buffer.value.clear() + buffer.value.writeString("1") self.state = .done self.bytesWritten += 1 - context.writeAndFlush(Self.wrapOutboundOut(buffer)).whenFailure { error in + context.writeAndFlush(Self.wrapOutboundOut(buffer.value)).whenFailure { error in XCTFail("unexpected error \(error)") } self.wroteEnoughToBeStuckPromise.succeed(self.bytesWritten) @@ -692,7 +704,9 @@ class StreamChannelTest: XCTestCase { () // ignored, we're done } context.fireChannelWritabilityChanged() + let loopBoundContext = context.loopBound self.wroteEnoughToBeStuckPromise.futureResult.whenSuccess { _ in + let context = loopBoundContext.value context.pipeline.removeHandler(self).whenFailure { error in XCTFail("unexpected error \(error)") }