swift-nio icon indicating copy to clipboard operation
swift-nio copied to clipboard

`withConnectedSocket(_:channelInitializer:)` in `ClientBootstrap` is not working

Open ktiays opened this issue 1 year ago • 0 comments

Expected behavior

withConnectedSocket(_:channelInitializer:) should create a channel and activate its handlers.

Actual behavior

withConnectedSocket(_:channelInitializer:) does not activate handlers of the channel it created, and further operations on it don't work.

Steps to reproduce

let fd = connectToSomewhere()

Task {
    do {
        let channel = try await bootstrap.withConnectedSocket(fd) { channel in
            channel.pipeline.addHandler(EchoHandler())
                .flatMap { _ in
                    return channel.eventLoop.makeSucceededFuture(channel)
                }
        }
        try await channel.closeFuture.get()
    } catch {
        // ...
    }
}

The code above will produce an error operationUnsupported.

SwiftNIO version/commit hash

2.75.0

System & version information

This issue is irrelevant to the operating system.

Possible reason

withConnectedSocket(_:channelInitializer:) will internally invoke withConnectedSocket(eventLoop:socket:channelInitializer:postRegisterTransformation:) method and it then invokes initializeAndRegisterChannel(channel:channelInitializer:registration:postRegisterTransformation:) method. The type of registration parameter is @escaping @Sendable (Channel) -> EventLoopFuture<Void>, which will take an any Channel as a parameter. The implementation closure is at https://github.com/apple/swift-nio/blob/ff98c93fe95c65cce6d160605b8e2efcfbe65f8e/Sources/NIOPosix/Bootstrap.swift#L1364

The real registerAlreadyConfigured0(promise:) implementation from SocketChannel is not called, however, the default implementation from Channel extension is called: https://github.com/apple/swift-nio/blob/ff98c93fe95c65cce6d160605b8e2efcfbe65f8e/Sources/NIOCore/Channel.swift#L205

This is an known issue of Swift: https://github.com/swiftlang/swift/issues/42725

ktiays avatar Oct 19 '24 06:10 ktiays