diff --git a/Sources/NIOPosix/Bootstrap.swift b/Sources/NIOPosix/Bootstrap.swift index 785213f6c..c27fd8325 100644 --- a/Sources/NIOPosix/Bootstrap.swift +++ b/Sources/NIOPosix/Bootstrap.swift @@ -1617,7 +1617,6 @@ extension ClientBootstrap { } ) } - } // MARK: Async connect methods with arbitrary payload @@ -1968,7 +1967,7 @@ public final class DatagramBootstrap { func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel { return try DatagramChannel(eventLoop: eventLoop, socket: socket) } - return withNewChannel(makeChannel: makeChannel) { (eventLoop, channel) in + return withNewChannel(makeChannel: makeChannel) { eventLoop, channel in let promise = eventLoop.makePromise(of: Void.self) channel.registerAlreadyConfigured0(promise: promise) return promise.futureResult @@ -2034,7 +2033,7 @@ public final class DatagramBootstrap { protocolFamily: address.protocol, protocolSubtype: .default) } - return withNewChannel(makeChannel: makeChannel) { (eventLoop, channel) in + return withNewChannel(makeChannel: makeChannel) { _, channel in channel.register().flatMap { channel.bind(to: address) } @@ -2082,7 +2081,7 @@ public final class DatagramBootstrap { protocolFamily: address.protocol, protocolSubtype: .default) } - return withNewChannel(makeChannel: makeChannel) { (eventLoop, channel) in + return withNewChannel(makeChannel: makeChannel) { _, channel in channel.register().flatMap { channel.connect(to: address) } @@ -2125,10 +2124,772 @@ public final class DatagramBootstrap { } } +// MARK: Async connect/bin methods with arbitrary payload + +extension DatagramBootstrap { + /// Use the existing bound socket file descriptor. + /// + /// - Parameters: + /// - socket: The _Unix file descriptor_ representing the bound stream socket. + /// - channelInitializer: A closure to initialize the channel. The return value of this closure is returned from the `connect` + /// method. + /// - Returns: The result of the channel initializer. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func withBoundSocket( + _ socket: NIOBSDSocket.Handle, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Output { + func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel { + return try DatagramChannel(eventLoop: eventLoop, socket: socket) + } + return try await self.makeConfiguredChannel( + makeChannel: makeChannel(_:), + channelInitializer: channelInitializer, + registration: { channel in + let promise = channel.eventLoop.makePromise(of: Void.self) + channel.registerAlreadyConfigured0(promise: promise) + return promise.futureResult + }, + postRegisterTransformation: { output, eventLoop in + eventLoop.makeSucceededFuture(output) + } + ).get() + } + + /// Bind the `DatagramChannel` to `host` and `port`. + /// + /// - Parameters: + /// - host: The host to bind on. + /// - port: The port to bind on. + /// - channelInitializer: A closure to initialize the channel. The return value of this closure is returned from the `connect` + /// method. + /// - Returns: The result of the channel initializer. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func bind( + host: String, + port: Int, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Output { + return try await self.bind0( + makeSocketAddress: { + try SocketAddress.makeAddressResolvingHost(host, port: port) + }, + channelInitializer: channelInitializer, + postRegisterTransformation: { output, eventLoop in + eventLoop.makeSucceededFuture(output) + } + ) + } + + /// Bind the `DatagramChannel` to the `address`. + /// + /// - Parameters: + /// - address: The `SocketAddress` to bind on. + /// - channelInitializer: A closure to initialize the channel. The return value of this closure is returned from the `connect` + /// method. + /// - Returns: The result of the channel initializer. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func bind( + to address: SocketAddress, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Output { + return try await self.bind0( + makeSocketAddress: { + address + }, + channelInitializer: channelInitializer, + postRegisterTransformation: { output, eventLoop in + eventLoop.makeSucceededFuture(output) + } + ) + } + + /// Bind the `DatagramChannel` to the `unixDomainSocketPath`. + /// + /// - Parameters: + /// - unixDomainSocketPath: The path of the UNIX Domain Socket to bind on. The`unixDomainSocketPath` must not exist, + /// unless `cleanupExistingSocketFile`is set to `true`. + /// - cleanupExistingSocketFile: Whether to cleanup an existing socket file at `unixDomainSocketPath`. + /// - channelInitializer: A closure to initialize the channel. The return value of this closure is returned from the `connect` + /// method. + /// - Returns: The result of the channel initializer. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func bind( + unixDomainSocketPath: String, + cleanupExistingSocketFile: Bool = false, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Output { + if cleanupExistingSocketFile { + try BaseSocket.cleanupSocket(unixDomainSocketPath: unixDomainSocketPath) + } + + return try await self.bind0( + makeSocketAddress: { + try SocketAddress(unixDomainSocketPath: unixDomainSocketPath) + }, + channelInitializer: channelInitializer, + postRegisterTransformation: { output, eventLoop in + eventLoop.makeSucceededFuture(output) + } + ) + } + + /// Connect the `DatagramChannel` to `host` and `port`. + /// + /// - Parameters: + /// - host: The host to connect to. + /// - port: The port to connect to. + /// - channelInitializer: A closure to initialize the channel. The return value of this closure is returned from the `connect` + /// method. + /// - Returns: The result of the channel initializer. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func connect( + host: String, + port: Int, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Output { + return try await self.connect0( + makeSocketAddress: { + try SocketAddress.makeAddressResolvingHost(host, port: port) + }, + channelInitializer: channelInitializer, + postRegisterTransformation: { output, eventLoop in + eventLoop.makeSucceededFuture(output) + } + ) + } + + /// Connect the `DatagramChannel` to the `address`. + /// + /// - Parameters: + /// - address: The `SocketAddress` to connect to. + /// - channelInitializer: A closure to initialize the channel. The return value of this closure is returned from the `connect` + /// method. + /// - Returns: The result of the channel initializer. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func connect( + to address: SocketAddress, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Output { + return try await self.connect0( + makeSocketAddress: { + address + }, + channelInitializer: channelInitializer, + postRegisterTransformation: { output, eventLoop in + eventLoop.makeSucceededFuture(output) + } + ) + } + + /// Connect the `DatagramChannel` to the `unixDomainSocketPath`. + /// + /// - Parameters: + /// - unixDomainSocketPath: The path of the UNIX Domain Socket to connect to. `path` must not exist, it will be created by the system. + /// - channelInitializer: A closure to initialize the channel. The return value of this closure is returned from the `connect` + /// method. + /// - Returns: The result of the channel initializer. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func connect( + unixDomainSocketPath: String, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Output { + return try await self.connect0( + makeSocketAddress: { + try SocketAddress(unixDomainSocketPath: unixDomainSocketPath) + }, + channelInitializer: channelInitializer, + postRegisterTransformation: { output, eventLoop in + eventLoop.makeSucceededFuture(output) + } + ) + } + + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + private func connect0( + makeSocketAddress: () throws -> SocketAddress, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, + postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture + ) async throws -> PostRegistrationTransformationResult { + let address = try makeSocketAddress() + + func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel { + return try DatagramChannel( + eventLoop: eventLoop, + protocolFamily: address.protocol, + protocolSubtype: .default + ) + } + + return try await self.makeConfiguredChannel( + makeChannel: makeChannel(_:), + channelInitializer: channelInitializer, + registration: { channel in + channel.register().flatMap { + channel.connect(to: address) + } + }, + postRegisterTransformation: postRegisterTransformation + ).get() + } + + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + private func bind0( + makeSocketAddress: () throws -> SocketAddress, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, + postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture + ) async throws -> PostRegistrationTransformationResult { + let address = try makeSocketAddress() + + func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel { + return try DatagramChannel( + eventLoop: eventLoop, + protocolFamily: address.protocol, + protocolSubtype: .default + ) + } + + return try await self.makeConfiguredChannel( + makeChannel: makeChannel(_:), + channelInitializer: channelInitializer, + registration: { channel in + channel.register().flatMap { + channel.bind(to: address) + } + }, + postRegisterTransformation: postRegisterTransformation + ).get() + } + + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + private func makeConfiguredChannel( + makeChannel: (_ eventLoop: SelectableEventLoop) throws -> DatagramChannel, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture, + registration: @escaping @Sendable (Channel) -> EventLoopFuture, + postRegisterTransformation: @escaping @Sendable (ChannelInitializerResult, EventLoop) -> EventLoopFuture + ) -> EventLoopFuture { + let eventLoop = self.group.next() + let channelInitializer = { (channel: Channel) -> EventLoopFuture in + let initializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) } + return initializer(channel).flatMap { channelInitializer(channel) } + } + let channelOptions = self._channelOptions + + let channel: DatagramChannel + do { + channel = try makeChannel(eventLoop as! SelectableEventLoop) + } catch { + return eventLoop.makeFailedFuture(error) + } + + func setupChannel() -> EventLoopFuture { + eventLoop.assertInEventLoop() + return channelOptions.applyAllChannelOptions(to: channel).flatMap { + channelInitializer(channel) + }.flatMap { (result: ChannelInitializerResult) in + eventLoop.assertInEventLoop() + return registration(channel).map { + result + } + }.flatMap { (result: ChannelInitializerResult) -> EventLoopFuture in + postRegisterTransformation(result, eventLoop) + }.flatMapError { error in + eventLoop.assertInEventLoop() + channel.close0(error: error, mode: .all, promise: nil) + return channel.eventLoop.makeFailedFuture(error) + } + } + + if eventLoop.inEventLoop { + return setupChannel() + } else { + return eventLoop.flatSubmit { + setupChannel() + } + } + } +} + +// MARK: Async connect methods with NIOAsyncChannel + +extension DatagramBootstrap { + /// Use the existing bound socket file descriptor. + /// + /// - Parameters: + /// - socket: The _Unix file descriptor_ representing the bound stream socket. + /// - backpressureStrategy: The back pressure strategy used by the channel. + /// - isOutboundHalfClosureEnabled: Indicates if half closure is enabled on the channel. If half closure is enabled + /// then finishing the `NIOAsyncChannelWriter` will lead to half closure. + /// - inboundType: The channel's inbound type. + /// - outboundType: The channel's outbound type. + /// - Returns: A `NIOAsyncChannel` for the bound connection. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func withBoundSocket( + _ socket: NIOBSDSocket.Handle, + backpressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark? = nil, + isOutboundHalfClosureEnabled: Bool = false, + inboundType: Inbound.Type = Inbound.self, + outboundType: Outbound.Type = Outbound.self + ) async throws -> NIOAsyncChannel { + func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel { + return try DatagramChannel(eventLoop: eventLoop, socket: socket) + } + return try await self.makeConfiguredChannel( + makeChannel: makeChannel(_:), + channelInitializer: { channel in + channel.eventLoop.makeCompletedFuture { + try NIOAsyncChannel( + synchronouslyWrapping: channel, + backpressureStrategy: backpressureStrategy, + isOutboundHalfClosureEnabled: isOutboundHalfClosureEnabled, + inboundType: inboundType, + outboundType: outboundType + ) + } + }, + registration: { channel in + let promise = channel.eventLoop.makePromise(of: Void.self) + channel.registerAlreadyConfigured0(promise: promise) + return promise.futureResult + }, + postRegisterTransformation: { output, eventLoop in + eventLoop.makeSucceededFuture(output) + } + ).get() + } + + /// Bind the `DatagramChannel` to `host` and `port`. + /// + /// - Parameters: + /// - host: The host to bind on. + /// - port: The port to bind on. + /// - backpressureStrategy: The back pressure strategy used by the channel. + /// - isOutboundHalfClosureEnabled: Indicates if half closure is enabled on the channel. If half closure is enabled + /// then finishing the `NIOAsyncChannelWriter` will lead to half closure. + /// - inboundType: The channel's inbound type. + /// - outboundType: The channel's outbound type. + /// - Returns: A `NIOAsyncChannel` for the bound connection. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func bind( + host: String, + port: Int, + backpressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark? = nil, + isOutboundHalfClosureEnabled: Bool = false, + inboundType: Inbound.Type = Inbound.self, + outboundType: Outbound.Type = Outbound.self + ) async throws -> NIOAsyncChannel { + return try await self.bind( + host: host, + port: port, + channelInitializer: { channel in + channel.eventLoop.makeCompletedFuture { + try NIOAsyncChannel( + synchronouslyWrapping: channel, + backpressureStrategy: backpressureStrategy, + isOutboundHalfClosureEnabled: isOutboundHalfClosureEnabled, + inboundType: inboundType, + outboundType: outboundType + ) + } + } + ) + } + + /// Bind the `DatagramChannel` to the `address`. + /// + /// - Parameters: + /// - address: The `SocketAddress` to bind on. + /// - backpressureStrategy: The back pressure strategy used by the channel. + /// - isOutboundHalfClosureEnabled: Indicates if half closure is enabled on the channel. If half closure is enabled + /// then finishing the `NIOAsyncChannelWriter` will lead to half closure. + /// - inboundType: The channel's inbound type. + /// - outboundType: The channel's outbound type. + /// - Returns: A `NIOAsyncChannel` for the bound connection. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func bind( + to address: SocketAddress, + backpressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark? = nil, + isOutboundHalfClosureEnabled: Bool = false, + inboundType: Inbound.Type = Inbound.self, + outboundType: Outbound.Type = Outbound.self + ) async throws -> NIOAsyncChannel { + return try await self.bind( + to: address, + channelInitializer: { channel in + channel.eventLoop.makeCompletedFuture { + try NIOAsyncChannel( + synchronouslyWrapping: channel, + backpressureStrategy: backpressureStrategy, + isOutboundHalfClosureEnabled: isOutboundHalfClosureEnabled, + inboundType: inboundType, + outboundType: outboundType + ) + } + } + ) + } + + /// Bind the `DatagramChannel` to the `unixDomainSocketPath`. + /// + /// - Parameters: + /// - unixDomainSocketPath: The path of the UNIX Domain Socket to bind on. The`unixDomainSocketPath` must not exist, + /// unless `cleanupExistingSocketFile`is set to `true`. + /// - cleanupExistingSocketFile: Whether to cleanup an existing socket file at `unixDomainSocketPath`. + /// - backpressureStrategy: The back pressure strategy used by the channel. + /// - isOutboundHalfClosureEnabled: Indicates if half closure is enabled on the channel. If half closure is enabled + /// then finishing the `NIOAsyncChannelWriter` will lead to half closure. + /// - inboundType: The channel's inbound type. + /// - outboundType: The channel's outbound type. + /// - Returns: A `NIOAsyncChannel` for the bound connection. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func bind( + unixDomainSocketPath: String, + cleanupExistingSocketFile: Bool = false, + backpressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark? = nil, + isOutboundHalfClosureEnabled: Bool = false, + inboundType: Inbound.Type = Inbound.self, + outboundType: Outbound.Type = Outbound.self + ) async throws -> NIOAsyncChannel { + return try await self.bind( + unixDomainSocketPath: unixDomainSocketPath, + cleanupExistingSocketFile: cleanupExistingSocketFile, + channelInitializer: { channel in + channel.eventLoop.makeCompletedFuture { + try NIOAsyncChannel( + synchronouslyWrapping: channel, + backpressureStrategy: backpressureStrategy, + isOutboundHalfClosureEnabled: isOutboundHalfClosureEnabled, + inboundType: inboundType, + outboundType: outboundType + ) + } + } + ) + } + + /// Specify the `host` and `port` to connect to for the TCP `Channel` that will be established. + /// + /// - Parameters: + /// - host: The host to connect to. + /// - port: The port to connect to. + /// - backpressureStrategy: The back pressure strategy used by the channel. + /// - isOutboundHalfClosureEnabled: Indicates if half closure is enabled on the channel. If half closure is enabled + /// then finishing the `NIOAsyncChannelWriter` will lead to half closure. + /// - inboundType: The channel's inbound type. + /// - outboundType: The channel's outbound type. + /// - Returns: A `NIOAsyncChannel` for the established connection. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func connect( + host: String, + port: Int, + backpressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark? = nil, + isOutboundHalfClosureEnabled: Bool = false, + inboundType: Inbound.Type = Inbound.self, + outboundType: Outbound.Type = Outbound.self + ) async throws -> NIOAsyncChannel { + return try await self.connect( + host: host, + port: port + ) { channel in + channel.eventLoop.makeCompletedFuture { + return try NIOAsyncChannel( + synchronouslyWrapping: channel, + backpressureStrategy: backpressureStrategy, + isOutboundHalfClosureEnabled: isOutboundHalfClosureEnabled, + inboundType: inboundType, + outboundType: outboundType + ) + } + } + } + + /// Specify the `address` to connect to for the TCP `Channel` that will be established. + /// + /// - Parameters: + /// - address: The address to connect to. + /// - backpressureStrategy: The back pressure strategy used by the channel. + /// - isOutboundHalfClosureEnabled: Indicates if half closure is enabled on the channel. If half closure is enabled + /// then finishing the `NIOAsyncChannelWriter` will lead to half closure. + /// - inboundType: The channel's inbound type. + /// - outboundType: The channel's outbound type. + /// - Returns: A `NIOAsyncChannel` for the established connection. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func connect( + to address: SocketAddress, + backpressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark? = nil, + isOutboundHalfClosureEnabled: Bool = false, + inboundType: Inbound.Type = Inbound.self, + outboundType: Outbound.Type = Outbound.self + ) async throws -> NIOAsyncChannel { + return try await self.connect( + to: address + ) { channel in + channel.eventLoop.makeCompletedFuture { + return try NIOAsyncChannel( + synchronouslyWrapping: channel, + backpressureStrategy: backpressureStrategy, + isOutboundHalfClosureEnabled: isOutboundHalfClosureEnabled, + inboundType: inboundType, + outboundType: outboundType + ) + } + } + } + + /// Specify the `unixDomainSocket` path to connect to for the UDS `Channel` that will be established. + /// + /// - Parameters: + /// - unixDomainSocketPath: The _Unix domain socket_ path to connect to. + /// - backpressureStrategy: The back pressure strategy used by the channel. + /// - isOutboundHalfClosureEnabled: Indicates if half closure is enabled on the channel. If half closure is enabled + /// then finishing the `NIOAsyncChannelWriter` will lead to half closure. + /// - inboundType: The channel's inbound type. + /// - outboundType: The channel's outbound type. + /// - Returns: A `NIOAsyncChannel` for the established connection. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func connect( + unixDomainSocketPath: String, + backpressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark? = nil, + isOutboundHalfClosureEnabled: Bool = false, + inboundType: Inbound.Type = Inbound.self, + outboundType: Outbound.Type = Outbound.self + ) async throws -> NIOAsyncChannel { + return try await self.connect( + unixDomainSocketPath: unixDomainSocketPath + ) { channel in + channel.eventLoop.makeCompletedFuture { + return try NIOAsyncChannel( + synchronouslyWrapping: channel, + backpressureStrategy: backpressureStrategy, + isOutboundHalfClosureEnabled: isOutboundHalfClosureEnabled, + inboundType: inboundType, + outboundType: outboundType + ) + } + } + } +} + +// MARK: Async connect/bind methods with protocol negotiation + +extension DatagramBootstrap { + /// Use the existing bound socket file descriptor. + /// + /// - Parameters: + /// - socket: The _Unix file descriptor_ representing the bound stream socket. + /// - channelInitializer: A closure to initialize the channel which must return the handler that is used for negotiating + /// the protocol. + /// - Returns: The protocol negotiation result. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func withBoundSocket( + _ socket: NIOBSDSocket.Handle, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Handler.NegotiationResult { + func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel { + return try DatagramChannel(eventLoop: eventLoop, socket: socket) + } + return try await self.makeConfiguredChannel( + makeChannel: makeChannel(_:), + channelInitializer: channelInitializer, + registration: { channel in + let promise = channel.eventLoop.makePromise(of: Void.self) + channel.registerAlreadyConfigured0(promise: promise) + return promise.futureResult + }, + postRegisterTransformation: { handler, eventLoop in + handler.protocolNegotiationResult.flatMap { result in + result.resolve(on: eventLoop) + } + } + ).get() + } + + /// Bind the `DatagramChannel` to `host` and `port`. + /// + /// - Parameters: + /// - host: The host to bind on. + /// - port: The port to bind on. + /// - channelInitializer: A closure to initialize the channel which must return the handler that is used for negotiating + /// the protocol. + /// - Returns: The protocol negotiation result. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func bind( + host: String, + port: Int, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Handler.NegotiationResult { + return try await self.bind0( + makeSocketAddress: { + try SocketAddress.makeAddressResolvingHost(host, port: port) + }, + channelInitializer: channelInitializer, + postRegisterTransformation: { handler, eventLoop in + handler.protocolNegotiationResult.flatMap { result in + result.resolve(on: eventLoop) + } + } + ) + } + + /// Bind the `DatagramChannel` to the `address`. + /// + /// - Parameters: + /// - address: The `SocketAddress` to bind on. + /// - channelInitializer: A closure to initialize the channel which must return the handler that is used for negotiating + /// the protocol. + /// - Returns: The protocol negotiation result. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func bind( + to address: SocketAddress, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Handler.NegotiationResult { + return try await self.bind0( + makeSocketAddress: { + address + }, + channelInitializer: channelInitializer, + postRegisterTransformation: { handler, eventLoop in + handler.protocolNegotiationResult.flatMap { result in + result.resolve(on: eventLoop) + } + } + ) + } + + /// Bind the `DatagramChannel` to the `unixDomainSocketPath`. + /// + /// - Parameters: + /// - unixDomainSocketPath: The path of the UNIX Domain Socket to bind on. The`unixDomainSocketPath` must not exist, + /// unless `cleanupExistingSocketFile`is set to `true`. + /// - cleanupExistingSocketFile: Whether to cleanup an existing socket file at `unixDomainSocketPath`. + /// - channelInitializer: A closure to initialize the channel which must return the handler that is used for negotiating + /// the protocol. + /// - Returns: The protocol negotiation result. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func bind( + unixDomainSocketPath: String, + cleanupExistingSocketFile: Bool = false, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Handler.NegotiationResult { + if cleanupExistingSocketFile { + try BaseSocket.cleanupSocket(unixDomainSocketPath: unixDomainSocketPath) + } + + return try await self.bind0( + makeSocketAddress: { + try SocketAddress(unixDomainSocketPath: unixDomainSocketPath) + }, + channelInitializer: channelInitializer, + postRegisterTransformation: { handler, eventLoop in + handler.protocolNegotiationResult.flatMap { result in + result.resolve(on: eventLoop) + } + } + ) + } + + /// Specify the `host` and `port` to connect to for the TCP `Channel` that will be established. + /// + /// - Parameters: + /// - host: The host to connect to. + /// - port: The port to connect to. + /// - channelInitializer: A closure to initialize the channel which must return the handler that is used for negotiating + /// the protocol. + /// - Returns: The protocol negotiation result. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func connect( + host: String, + port: Int, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Handler.NegotiationResult { + return try await self.connect0( + makeSocketAddress: { + try SocketAddress.makeAddressResolvingHost(host, port: port) + }, + channelInitializer: channelInitializer, + postRegisterTransformation: { handler, eventLoop in + handler.protocolNegotiationResult.flatMap { result in + result.resolve(on: eventLoop) + } + } + ) + } + + /// Specify the `address` to connect to for the TCP `Channel` that will be established. + /// + /// - Parameters: + /// - address: The address to connect to. + /// - channelInitializer: A closure to initialize the channel which must return the handler that is used for negotiating + /// the protocol. + /// - Returns: The protocol negotiation result. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func connect( + to address: SocketAddress, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Handler.NegotiationResult { + return try await self.connect0( + makeSocketAddress: { + address + }, + channelInitializer: channelInitializer, + postRegisterTransformation: { handler, eventLoop in + handler.protocolNegotiationResult.flatMap { result in + result.resolve(on: eventLoop) + } + } + ) + } + + /// Specify the `unixDomainSocket` path to connect to for the UDS `Channel` that will be established. + /// + /// - Parameters: + /// - unixDomainSocketPath: The _Unix domain socket_ path to connect to. + /// - channelInitializer: A closure to initialize the channel which must return the handler that is used for negotiating + /// the protocol. + /// - Returns: The protocol negotiation result. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(AsyncChannel) + public func connect( + unixDomainSocketPath: String, + channelInitializer: @escaping @Sendable (Channel) -> EventLoopFuture + ) async throws -> Handler.NegotiationResult { + return try await self.connect0( + makeSocketAddress: { + try SocketAddress(unixDomainSocketPath: unixDomainSocketPath) + }, + channelInitializer: channelInitializer, + postRegisterTransformation: { handler, eventLoop in + handler.protocolNegotiationResult.flatMap { result in + result.resolve(on: eventLoop) + } + } + ) + } +} + @available(*, unavailable) extension DatagramBootstrap: Sendable {} - /// A `NIOPipeBootstrap` is an easy way to bootstrap a `PipeChannel` which uses two (uni-directional) UNIX pipes /// and makes a `Channel` out of them. /// diff --git a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift index 9784b816c..86854c780 100644 --- a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift +++ b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift @@ -129,6 +129,32 @@ private final class ByteBufferToByteHandler: ChannelDuplexHandler { } } +private final class AddressedEnvelopingHandler: ChannelDuplexHandler { + typealias InboundIn = AddressedEnvelope + typealias InboundOut = ByteBuffer + typealias OutboundIn = ByteBuffer + typealias OutboundOut = Any + + var remoteAddress: SocketAddress? + + func channelRead(context: ChannelHandlerContext, data: NIOAny) { + let envelope = self.unwrapInboundIn(data) + self.remoteAddress = envelope.remoteAddress + + context.fireChannelRead(self.wrapInboundOut(envelope.data)) + } + + func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + let buffer = self.unwrapOutboundIn(data) + if let remoteAddress = self.remoteAddress { + context.write(self.wrapOutboundOut(AddressedEnvelope(remoteAddress: remoteAddress, data: buffer)), promise: promise) + return + } + + context.write(self.wrapOutboundOut(buffer), promise: promise) + } +} + final class AsyncChannelBootstrapTests: XCTestCase { enum NegotiationResult { case string(NIOAsyncChannel) @@ -142,9 +168,14 @@ final class AsyncChannelBootstrapTests: XCTestCase { case byte(UInt8) } - func testAsyncChannel() throws { + // MARK: Server/Client Bootstrap + + func testServerClientBootstrap_withAsyncChannel_andHostPort() throws { XCTAsyncTest { let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) + defer { + try! eventLoopGroup.syncShutdownGracefully() + } let channel = try await ServerBootstrap(group: eventLoopGroup) .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) @@ -190,6 +221,9 @@ final class AsyncChannelBootstrapTests: XCTestCase { func testAsyncChannelProtocolNegotiation() throws { XCTAsyncTest { let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) + defer { + try! eventLoopGroup.syncShutdownGracefully() + } let channel: NIOAsyncChannel = try await ServerBootstrap(group: eventLoopGroup) .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) @@ -265,6 +299,9 @@ final class AsyncChannelBootstrapTests: XCTestCase { func testAsyncChannelNestedProtocolNegotiation() throws { XCTAsyncTest { let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) + defer { + try! eventLoopGroup.syncShutdownGracefully() + } let channel: NIOAsyncChannel = try await ServerBootstrap(group: eventLoopGroup) .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) @@ -388,6 +425,9 @@ final class AsyncChannelBootstrapTests: XCTestCase { } XCTAsyncTest { let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) + defer { + try! eventLoopGroup.syncShutdownGracefully() + } let channels = NIOLockedValueBox<[Channel]>([Channel]()) let channel: NIOAsyncChannel = try await ServerBootstrap(group: eventLoopGroup) @@ -470,6 +510,90 @@ final class AsyncChannelBootstrapTests: XCTestCase { } } + // MARK: Datagram Bootstrap + + func testDatagramBootstrap_withAsyncChannel_andHostPort() throws { + XCTAsyncTest { + let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) + defer { + try! eventLoopGroup.syncShutdownGracefully() + } + + let serverChannel = try await self.makeUDPServerChannel(eventLoopGroup: eventLoopGroup) + let clientChannel = try await self.makeUDPClientChannel( + eventLoopGroup: eventLoopGroup, + port: serverChannel.channel.localAddress!.port! + ) + var serverInboundIterator = serverChannel.inboundStream.makeAsyncIterator() + var clientInboundIterator = clientChannel.inboundStream.makeAsyncIterator() + + try await clientChannel.outboundWriter.write("request") + try await XCTAsyncAssertEqual(try await serverInboundIterator.next(), "request") + + try await serverChannel.outboundWriter.write("response") + try await XCTAsyncAssertEqual(try await clientInboundIterator.next(), "response") + } + } + + func testDatagramBootstrap_withProtocolNegotiation_andHostPort() throws { + XCTAsyncTest { + let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) + defer { + try! eventLoopGroup.syncShutdownGracefully() + } + + // We are creating a channel here to get a random port from the system + let channel = try await DatagramBootstrap(group: eventLoopGroup) + .bind( + to: .init(ipAddress: "127.0.0.1", port: 0), + channelInitializer: { channel -> EventLoopFuture in channel.eventLoop.makeSucceededFuture(channel) } + ) + + let port = channel.localAddress!.port! + try await channel.close() + + try await withThrowingTaskGroup(of: NegotiationResult.self) { group in + group.addTask { + // We have to use a fixed port here since we only get the channel once protocol negotiation is done + try await self.makeUDPServerChannelWithProtocolNegotiation( + eventLoopGroup: eventLoopGroup, + port: port + ) + } + + // We need to sleep here since we can only connect the client after the server started. + try await Task.sleep(nanoseconds: 100000000) + + group.addTask { + // We have to use a fixed port here since we only get the channel once protocol negotiation is done + try await self.makeUDPClientChannelWithProtocolNegotiation( + eventLoopGroup: eventLoopGroup, + port: port, + proposedALPN: .string + ) + } + + let firstNegotiationResult = try await group.next() + let secondNegotiationResult = try await group.next() + + switch (firstNegotiationResult, secondNegotiationResult) { + case (.string(let firstChannel), .string(let secondChannel)): + var firstInboundIterator = firstChannel.inboundStream.makeAsyncIterator() + var secondInboundIterator = secondChannel.inboundStream.makeAsyncIterator() + + try await firstChannel.outboundWriter.write("request") + try await XCTAsyncAssertEqual(try await secondInboundIterator.next(), "request") + + try await secondChannel.outboundWriter.write("response") + try await XCTAsyncAssertEqual(try await firstInboundIterator.next(), "response") + + default: + preconditionFailure() + } + } + } + } + // MARK: - Test Helpers private func makeClientChannel(eventLoopGroup: EventLoopGroup, port: Int) async throws -> NIOAsyncChannel { @@ -523,6 +647,76 @@ final class AsyncChannelBootstrapTests: XCTestCase { } } + private func makeUDPServerChannel(eventLoopGroup: EventLoopGroup) async throws -> NIOAsyncChannel { + try await DatagramBootstrap(group: eventLoopGroup) + .channelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(AddressedEnvelopingHandler()) + try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(LineDelimiterCoder())) + try channel.pipeline.syncOperations.addHandler(MessageToByteHandler(LineDelimiterCoder())) + try channel.pipeline.syncOperations.addHandler(ByteBufferToStringHandler()) + } + } + .bind( + host: "127.0.0.1", + port: 0, + inboundType: String.self, + outboundType: String.self + ) + } + + private func makeUDPServerChannelWithProtocolNegotiation( + eventLoopGroup: EventLoopGroup, + port: Int, + proposedALPN: TLSUserEventHandler.ALPN? = nil + ) async throws -> NegotiationResult { + try await DatagramBootstrap(group: eventLoopGroup) + .bind( + host: "127.0.0.1", + port: port + ) { channel -> EventLoopFuture> in + return channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(AddressedEnvelopingHandler()) + return try self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) + } + } + } + + private func makeUDPClientChannel(eventLoopGroup: EventLoopGroup, port: Int) async throws -> NIOAsyncChannel { + try await DatagramBootstrap(group: eventLoopGroup) + .channelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(AddressedEnvelopingHandler()) + try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(LineDelimiterCoder())) + try channel.pipeline.syncOperations.addHandler(MessageToByteHandler(LineDelimiterCoder())) + try channel.pipeline.syncOperations.addHandler(ByteBufferToStringHandler()) + } + } + .connect( + host: "127.0.0.1", + port: port, + inboundType: String.self, + outboundType: String.self + ) + } + + private func makeUDPClientChannelWithProtocolNegotiation( + eventLoopGroup: EventLoopGroup, + port: Int, + proposedALPN: TLSUserEventHandler.ALPN + ) async throws -> NegotiationResult { + try await DatagramBootstrap(group: eventLoopGroup) + .connect( + host: "127.0.0.1", + port: port + ) { channel -> EventLoopFuture> in + return channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(AddressedEnvelopingHandler()) + return try self.configureProtocolNegotiationHandlers(channel: channel, proposedALPN: proposedALPN) + } + } + } + @discardableResult private func configureProtocolNegotiationHandlers( channel: Channel, diff --git a/docker/docker-compose.2004.56.yaml b/docker/docker-compose.2004.56.yaml index c2a23fa8a..d980ab3bf 100644 --- a/docker/docker-compose.2004.56.yaml +++ b/docker/docker-compose.2004.56.yaml @@ -35,7 +35,7 @@ services: - MAX_ALLOCS_ALLOWED_1000_getHandlers=8050 - MAX_ALLOCS_ALLOWED_1000_getHandlers_sync=36 - MAX_ALLOCS_ALLOWED_1000_reqs_1_conn=26400 - - MAX_ALLOCS_ALLOWED_1000_rst_connections=146000 + - MAX_ALLOCS_ALLOWED_1000_rst_connections=146050 - MAX_ALLOCS_ALLOWED_1000_tcpbootstraps=4050 - MAX_ALLOCS_ALLOWED_1000_tcpconnections=151050 - MAX_ALLOCS_ALLOWED_1000_udp_reqs=6050 diff --git a/docker/docker-compose.2204.58.yaml b/docker/docker-compose.2204.58.yaml index de114b7a3..50bba2145 100644 --- a/docker/docker-compose.2204.58.yaml +++ b/docker/docker-compose.2204.58.yaml @@ -35,7 +35,7 @@ services: - MAX_ALLOCS_ALLOWED_1000_getHandlers=8050 - MAX_ALLOCS_ALLOWED_1000_getHandlers_sync=36 - MAX_ALLOCS_ALLOWED_1000_reqs_1_conn=26400 - - MAX_ALLOCS_ALLOWED_1000_rst_connections=147000 + - MAX_ALLOCS_ALLOWED_1000_rst_connections=147050 - MAX_ALLOCS_ALLOWED_1000_tcpbootstraps=4050 - MAX_ALLOCS_ALLOWED_1000_tcpconnections=154050 - MAX_ALLOCS_ALLOWED_1000_udp_reqs=6050