Fix race in ClientBootstrap (#870)

This commit is contained in:
Daniel Eggert authored and GitHub committed 2026-10-12 15:32:49 +02:00
1 parent 8283076ac2
commit 088b6eb105
5 files changed
+102 -46

No files matched your search

+1 -3
View File
@@ -74,8 +74,7 @@ import NIOIMAP
// Connect and wrap the channel so the handler's decoded `Response`s and the
// commands we write flow through async sequences.
let channel = try await ClientBootstrap(group: MultiThreadedEventLoopGroup.singleton)
.connect(host: "mail.example.com", port: 143)
.flatMap { channel in
.connect(host: "mail.example.com", port: 143) { channel in
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandler(IMAPClientHandler())
return try NIOAsyncChannel<Response, IMAPClientHandler.OutboundIn>(
@@ -83,7 +82,6 @@ let channel = try await ClientBootstrap(group: MultiThreadedEventLoopGroup.singl
)
}
}
.get()
try await channel.executeThenClose { inbound, outbound in
// Send a command.
+36 -40
View File
@@ -43,7 +43,7 @@ import Synchronization
/// untagged `Response` is delivered to _all_ in-flight command handlers (see
/// ``send(_:_:)``). Handlers must act only on the responses they care about.
public final class IMAPConnection: Sendable {
private init(
init(
configuration: Configuration
) {
self.configuration = configuration
@@ -494,38 +494,46 @@ public final class IMAPConnection: Sendable {
// MARK: -
extension IMAPConnection {
private func makeChannel(
logging: Configuration.Logging
) async throws -> NIOAsyncChannel<Response, IMAPClientHandler.OutboundIn> {
typealias AsyncChannel = NIOAsyncChannel<Response, IMAPClientHandler.OutboundIn>
/// - Parameter bootstrap: For testing.
func makeChannel(
logging: Configuration.Logging,
bootstrap: sending ClientBootstrap = ClientBootstrap(group: MultiThreadedEventLoopGroup.sharedEventLoopGroup)
) async throws -> AsyncChannel {
let configuration = self.configuration
return try await ClientBootstrap(group: MultiThreadedEventLoopGroup.sharedEventLoopGroup)
.connect(endpoint: configuration.endpoint)
.flatMap { [configuration, logger] channel in
channel.eventLoop.makeCompletedFuture {
var handlers: [ChannelHandler] = []
if configuration.useTLS {
handlers.append(
try NIOSSLClientHandler(
context: NIOSSLContext(configuration: .clientDefault),
serverHostname: configuration.endpoint.hostname
)
// Install handlers before registration. Added after `connect`, they can miss the greeting.
let initializer: @Sendable (Channel) -> EventLoopFuture<AsyncChannel> = { [logger] channel in
channel.eventLoop.makeCompletedFuture {
var handlers: [ChannelHandler] = []
if configuration.useTLS {
handlers.append(
try NIOSSLClientHandler(
context: NIOSSLContext(configuration: .clientDefault),
serverHostname: configuration.endpoint.hostname
)
}
switch logging {
case .noLogging:
break
case .logging:
handlers.append(makeInboundDebugHandler(logger: logger))
handlers.append(makeOutboundDebugHandler(logger: logger))
}
handlers.append(IMAPClientHandler())
try channel.pipeline.syncOperations.addHandlers(handlers)
return try NIOAsyncChannel<Response, IMAPClientHandler.OutboundIn>(
wrappingChannelSynchronously: channel
)
}
switch logging {
case .noLogging:
break
case .logging:
handlers.append(makeInboundDebugHandler(logger: logger))
handlers.append(makeOutboundDebugHandler(logger: logger))
}
handlers.append(IMAPClientHandler())
try channel.pipeline.syncOperations.addHandlers(handlers)
return try AsyncChannel(
wrappingChannelSynchronously: channel
)
}
.get()
}
switch configuration.endpoint {
case .hostname(let host, port: let port):
return try await bootstrap.connect(host: host, port: Int(port), channelInitializer: initializer)
case .unixDomainSocket(path: let path):
return try await bootstrap.connect(unixDomainSocketPath: path, channelInitializer: initializer)
}
}
private func run(
@@ -658,18 +666,6 @@ extension IMAPConnection {
}
}
extension ClientBootstrap {
/// Connects to the given configuration endpoint.
public func connect(endpoint: IMAPConnection.Configuration.Endpoint) -> EventLoopFuture<Channel> {
switch endpoint {
case .hostname(let host, port: let port):
connect(host: host, port: Int(port))
case .unixDomainSocket(path: let path):
connect(unixDomainSocketPath: path)
}
}
}
extension IMAPConnection {
/// A stream of responses from the server received while a specific command runs.
public struct ResponseStream: AsyncSequence, Sendable {
@@ -14,8 +14,7 @@ Connect to the server, add ``IMAPClientHandler`` to the pipeline, and wrap the c
import NIOIMAP
let channel = try await ClientBootstrap(group: MultiThreadedEventLoopGroup.singleton)
.connect(host: "mail.example.com", port: 143)
.flatMap { channel in
.connect(host: "mail.example.com", port: 143) { channel in
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandler(IMAPClientHandler())
return try NIOAsyncChannel<Response, IMAPClientHandler.OutboundIn>(
@@ -23,7 +22,6 @@ let channel = try await ClientBootstrap(group: MultiThreadedEventLoopGroup.singl
)
}
}
.get()
```
For a TLS connection (typically port 993), insert an `NIOSSLClientHandler` ahead of ``IMAPClientHandler`` in the pipeline.
@@ -14,6 +14,7 @@
import Logging
import NIO
import NIOIMAP
import Synchronization
// MARK: - Shared state
@@ -216,6 +217,37 @@ private final class GreetAndStayOpenHandler: ChannelInboundHandler {
}
}
// MARK: - Pipeline probe
/// Whether `IMAPClientHandler` was in the pipeline at registration.
final class RegistrationProbe: Sendable {
private let storage = Mutex<Bool?>(nil)
/// `nil` until registration.
var hadIMAPClientHandlerAtRegistration: Bool? {
storage.withLock { $0 }
}
var handler: some ChannelInboundHandler {
Handler(probe: self)
}
private final class Handler: ChannelInboundHandler {
typealias InboundIn = Any
let probe: RegistrationProbe
init(probe: RegistrationProbe) {
self.probe = probe
}
func channelRegistered(context: ChannelHandlerContext) {
let found = (try? context.pipeline.syncOperations.handler(type: IMAPClientHandler.self)) != nil
probe.storage.withLock { $0 = found }
context.fireChannelRegistered()
}
}
}
// MARK: - Log capture
/// Collects the log records written through the `RecordingLogHandler` it hands out.
@@ -392,4 +392,36 @@ enum IMAPConnectionLifecycleTests {
"Connection diagnostics should identify their connection: \(record.metadata)"
)
}
/// Handlers added after `connect` can miss the greeting, stalling `withConnection`.
@Test(.timeLimit(.minutes(3)))
static func handlersAreInstalledBeforeTheChannelIsRegistered() async throws {
let server = try await LoopbackServer.greetThenStayOpen()
defer { server.shutdown() }
let connection = IMAPConnection(
configuration: IMAPConnection.Configuration(
hostname: "127.0.0.1",
port: server.port,
useTLS: false,
logging: .noLogging
)
)
// Runs before `makeChannel`'s initializer, so the probe sees the pipeline at registration.
let probe = RegistrationProbe()
let bootstrap = ClientBootstrap(group: MultiThreadedEventLoopGroup.sharedEventLoopGroup)
.channelInitializer { channel in
channel.eventLoop.makeCompletedFuture {
try channel.pipeline.syncOperations.addHandler(probe.handler)
}
}
let channel = try await connection.makeChannel(logging: .noLogging, bootstrap: bootstrap)
try await channel.executeThenClose { _, _ in }
#expect(
probe.hadIMAPClientHandlerAtRegistration == true,
"IMAPClientHandler must be in the pipeline before the channel registers."
)
}
}