From 00125aea2989cc1cb4299e366349e0fbd9e2c919 Mon Sep 17 00:00:00 2001 From: Franz Busch Date: Wed, 21 Oct 2026 13:16:04 +0200 Subject: [PATCH] [IO] Add `UDPConnection` and `withSplit` for UDP This PR introduces a new type `UDPConnection` that exchanges datagrams with one connected peer. It also adds `withSplit` APIs like `TCPConnection` to `UDPConnection` and `UDPSocket` --- .../IO/HighLevel/UDPConnection.swift | 156 ++++++++++++++ .../IO/HighLevel/UDPCore.swift | 194 ++++++++++++++++++ .../IO/HighLevel/UDPSocket.swift | 179 +++++++++------- .../UDPSocketOperationScheduler.swift | 41 ++++ .../PThreadExecutor+UDPSocketOperations.swift | 100 +++++++-- ...readTaskExecutor+UDPSocketOperations.swift | 21 ++ .../PThread/Internal/IO/SocketSyscall.swift | 28 ++- .../UDPSocketTests.swift | 124 +++++++++++ 8 files changed, 746 insertions(+), 97 deletions(-) create mode 100644 Sources/PlatformExecutors/IO/HighLevel/UDPConnection.swift create mode 100644 Sources/PlatformExecutors/IO/HighLevel/UDPCore.swift diff --git a/Sources/PlatformExecutors/IO/HighLevel/UDPConnection.swift b/Sources/PlatformExecutors/IO/HighLevel/UDPConnection.swift new file mode 100644 index 0000000..23ea446 --- /dev/null +++ b/Sources/PlatformExecutors/IO/HighLevel/UDPConnection.swift @@ -0,0 +1,156 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#if ExperimentalIO +/// A UDP socket that exchanges datagrams with one peer. +/// +/// A connection is created by connecting to a peer with ``connect(to:)``, or by connecting a bound +/// ``UDPSocket`` with ``UDPSocket/connect(to:)``. The platform drops the datagrams that other peers send to +/// it. +/// +/// A connection uniquely owns the underlying platform resource, so it cannot be copied. It must be closed +/// explicitly with ``close()`` since closing is an asynchronous operation, and destroying a connection +/// without closing it traps. +/// +/// ```swift +/// var connection = try await UDPConnection.connect(to: address) +/// try await connection.write(from: request) +/// let count = try await connection.read(into: &response) +/// try await connection.close() +/// ``` +@available(anyAppleOS 27.0, *) +public struct UDPConnection: ~Copyable, Sendable { + private var core: UDPCore + + init(core: consuming UDPCore) { + self.core = core + } + + /// Creates a new socket and connects it to the given address. + /// + /// The platform picks the local address of the socket, which ``localAddress`` reports afterwards. Connecting + /// does not send anything, so it succeeds even if nobody listens at the address. + /// + /// - Parameter address: The address of the peer. + /// - Returns: The connected socket. + public static func connect(to address: SocketAddress) async throws(IOError) -> UDPConnection { + UDPConnection(core: try await UDPCore.connect(to: address)) + } + + /// The address that the socket is bound to locally. + public var localAddress: SocketAddress { + get throws(IOError) { + try self.core.localAddress + } + } + + /// The address of the peer. + public var remoteAddress: SocketAddress { + get throws(IOError) { + try self.core.remoteAddress + } + } + + /// Reads one datagram from the peer into the free capacity of the given buffer. + /// + /// The bytes are appended to the buffer. A datagram that is larger than the free capacity of the buffer is + /// truncated, and its remaining bytes are discarded. + /// + /// - Parameter buffer: The buffer to read into. + /// - Returns: The number of bytes received. + @discardableResult + public mutating func read(into buffer: inout OutputRawSpan) async throws(IOError) -> Int { + try await UDPCore.read(into: &buffer, socket: self.core.socket, on: self.core.scheduler) + } + + /// Sends the bytes of the given buffer as one datagram to the peer. + /// + /// - Parameter buffer: The bytes of the datagram. + public mutating func write(from buffer: RawSpan) async throws(IOError) { + try await UDPCore.write(from: buffer, socket: self.core.socket, on: self.core.scheduler) + } + + /// Closes the connection. + public consuming func close() async throws(IOError) { + try await self.core.close() + } +} + +// MARK: - Reading and writing concurrently + +@available(anyAppleOS 27.0, *) +extension UDPConnection { + /// The read direction of a connection, lent out by ``UDPConnection/withSplit(_:)``. + public struct ReadHalf: ~Copyable, ~Escapable, Sendable { + /// The scheduler that services the socket. + private let scheduler: any UDPSocketOperationScheduler + + /// The scheduler's handle of the socket. + private let socket: (any Sendable)? + + @_lifetime(borrow owner) + fileprivate init(_ owner: borrowing UDPConnection) { + self.scheduler = owner.core.scheduler + self.socket = owner.core.socket + } + + /// Reads one datagram from the peer into the free capacity of the given buffer. + /// + /// - Parameter buffer: The buffer to read into. + /// - Returns: The number of bytes received. + @discardableResult + public mutating func read(into buffer: inout OutputRawSpan) async throws(IOError) -> Int { + try await UDPCore.read(into: &buffer, socket: self.socket, on: self.scheduler) + } + } + + /// The write direction of a connection, lent out by ``UDPConnection/withSplit(_:)``. + public struct WriteHalf: ~Copyable, ~Escapable, Sendable { + /// The scheduler that services the socket. + private let scheduler: any UDPSocketOperationScheduler + + /// The scheduler's handle of the socket. + private let socket: (any Sendable)? + + @_lifetime(borrow owner) + fileprivate init(_ owner: borrowing UDPConnection) { + self.scheduler = owner.core.scheduler + self.socket = owner.core.socket + } + + /// Sends the bytes of the given buffer as one datagram to the peer. + /// + /// - Parameter buffer: The bytes of the datagram. + public mutating func write(from buffer: RawSpan) async throws(IOError) { + try await UDPCore.write(from: buffer, socket: self.socket, on: self.scheduler) + } + } + + /// Lends the read and the write direction of the connection to the given closure. + /// + /// The halves can be used concurrently allowing protocols to send and receive independently. Their + /// methods are `mutating`, so that every half is only used by one task at a time. + /// + /// - Important: The halves cannot escape the closure, so the connection keeps owning the platform + /// resource and must still be closed afterwards. + /// + /// - Parameter body: The closure that the halves are lent to. + /// - Returns: The value that the closure returned. + public nonisolated(nonsending) func withSplit( + _ body: nonisolated(nonsending) (inout ReadHalf, inout WriteHalf) async throws(Failure) -> Return + ) async throws(Failure) -> Return { + var readHalf = ReadHalf(self) + var writeHalf = WriteHalf(self) + return try await body(&readHalf, &writeHalf) + } +} +#endif diff --git a/Sources/PlatformExecutors/IO/HighLevel/UDPCore.swift b/Sources/PlatformExecutors/IO/HighLevel/UDPCore.swift new file mode 100644 index 0000000..68cb32c --- /dev/null +++ b/Sources/PlatformExecutors/IO/HighLevel/UDPCore.swift @@ -0,0 +1,194 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#if ExperimentalIO +/// What ``UDPSocket`` and ``UDPConnection`` share. +@available(anyAppleOS 27.0, *) +struct UDPCore: ~Copyable, Sendable { + /// The scheduler that services the socket. + let scheduler: any UDPSocketOperationScheduler + + /// The scheduler's handle of the socket, or `nil` once the socket is closed. + var socket: (any Sendable)? + + init(scheduler: any UDPSocketOperationScheduler, socket: (any Sendable)?) { + self.scheduler = scheduler + self.socket = socket + } + + private init( + scheduler: Scheduler, + socket: Scheduler.UDPSocket + ) { + self.scheduler = scheduler + self.socket = socket + } + + /// Resolves the scheduler that services new sockets. + private static func resolveScheduler() -> any UDPSocketOperationScheduler { + guard + let scheduler = OperationSchedulerPreference.resolve(as: (any UDPSocketOperationScheduler).self) + else { + fatalError( + "No operation scheduler for UDP sockets found. Use withOperationScheduler or a task executor preference." + ) + } + return scheduler + } + + // MARK: - Creating + + static func bind(to address: SocketAddress) async throws(IOError) -> UDPCore { + try await Self.bind(to: address, on: Self.resolveScheduler()) + } + + private static func bind( + to address: SocketAddress, + on scheduler: Scheduler + ) async throws(IOError) -> UDPCore { + UDPCore(scheduler: scheduler, socket: try await scheduler.bind(to: address)) + } + + static func connect(to address: SocketAddress) async throws(IOError) -> UDPCore { + try await Self.connect(to: address, on: Self.resolveScheduler()) + } + + private static func connect( + to address: SocketAddress, + on scheduler: Scheduler + ) async throws(IOError) -> UDPCore { + UDPCore(scheduler: scheduler, socket: try await scheduler.connectUDP(to: address)) + } + + /// Connects the socket to the given address, and closes it if that fails. + consuming func connected(to address: SocketAddress) async throws(IOError) -> UDPCore { + let scheduler = self.scheduler + let socket = self.socket.take() + do { + try await Self.connect(socket, to: address, on: scheduler) + } catch { + try? await Self.close(socket, on: scheduler) + throw error + } + return UDPCore(scheduler: scheduler, socket: socket) + } + + private static func connect( + _ socket: (any Sendable)?, + to address: SocketAddress, + on scheduler: Scheduler + ) async throws(IOError) { + try await scheduler.connectUDP(socket: Self.socket(socket, of: scheduler), to: address) + } + + // MARK: - Addresses + + var localAddress: SocketAddress { + get throws(IOError) { + try Self.localAddress(socket: self.socket, on: self.scheduler) + } + } + + private static func localAddress( + socket: (any Sendable)?, + on scheduler: Scheduler + ) throws(IOError) -> SocketAddress { + try scheduler.localAddress(of: Self.socket(socket, of: scheduler)) + } + + var remoteAddress: SocketAddress { + get throws(IOError) { + try Self.remoteAddress(socket: self.socket, on: self.scheduler) + } + } + + private static func remoteAddress( + socket: (any Sendable)?, + on scheduler: Scheduler + ) throws(IOError) -> SocketAddress { + try scheduler.remoteAddress(of: Self.socket(socket, of: scheduler)) + } + + // MARK: - Datagrams + + static func receive( + into buffer: inout OutputRawSpan, + socket: (any Sendable)?, + on scheduler: Scheduler + ) async throws(IOError) -> (count: Int, sender: SocketAddress) { + try await scheduler.receive(socket: Self.socket(socket, of: scheduler), into: &buffer) + } + + static func send( + from buffer: RawSpan, + to address: SocketAddress, + socket: (any Sendable)?, + on scheduler: Scheduler + ) async throws(IOError) { + // A datagram is sent as a whole or not at all. + _ = try await scheduler.send(socket: Self.socket(socket, of: scheduler), from: buffer, to: address) + } + + static func read( + into buffer: inout OutputRawSpan, + socket: (any Sendable)?, + on scheduler: Scheduler + ) async throws(IOError) -> Int { + try await scheduler.read(socket: Self.socket(socket, of: scheduler), into: &buffer) + } + + static func write( + from buffer: RawSpan, + socket: (any Sendable)?, + on scheduler: Scheduler + ) async throws(IOError) { + // A datagram is sent as a whole or not at all. + _ = try await scheduler.write(socket: Self.socket(socket, of: scheduler), from: buffer) + } + + // MARK: - Closing + + consuming func close() async throws(IOError) { + try await Self.close(self.socket.take(), on: self.scheduler) + } + + private static func close( + _ socket: (any Sendable)?, + on scheduler: Scheduler + ) async throws(IOError) { + let socket = socket as! Scheduler.UDPSocket + try await withTaskCancellationShield { () async throws(IOError) -> Void in + try await scheduler.close(socket: socket) + } + } + + /// Returns the handle of the socket as the handle type of the given scheduler. + /// + /// - Parameters: + /// - socket: The erased handle of the socket. + /// - scheduler: The scheduler that services the socket. + private static func socket( + _ socket: (any Sendable)?, + of scheduler: Scheduler + ) -> Scheduler.UDPSocket { + // The handle was created by this scheduler, and it is only `nil` once + // the socket is closed, which consumes it. So the cast cannot fail. + socket as! Scheduler.UDPSocket + } + + deinit { + if self.socket != nil { + fatalError("A UDP socket was destroyed without being closed.") + } + } +} +#endif diff --git a/Sources/PlatformExecutors/IO/HighLevel/UDPSocket.swift b/Sources/PlatformExecutors/IO/HighLevel/UDPSocket.swift index 5491314..73cfba1 100644 --- a/Sources/PlatformExecutors/IO/HighLevel/UDPSocket.swift +++ b/Sources/PlatformExecutors/IO/HighLevel/UDPSocket.swift @@ -11,10 +11,10 @@ //===----------------------------------------------------------------------===// #if ExperimentalIO -/// A UDP socket. +/// A UDP socket that sends datagrams to, and receives datagrams from, any peer. /// -/// A socket sends and receives datagrams to and from any peer. It is created by binding it to a local -/// address with ``bind(to:)``. +/// A socket is created by binding it to a local address with ``bind(to:)``. To exchange datagrams with one +/// peer only, connect it with ``connect(to:)``, which turns it into a ``UDPConnection``. /// /// A socket uniquely owns the underlying platform resource, so it cannot be copied. It must be closed /// explicitly with ``close()`` since closing is an asynchronous operation, and destroying a socket without @@ -28,18 +28,10 @@ /// ``` @available(anyAppleOS 27.0, *) public struct UDPSocket: ~Copyable, Sendable { - /// The scheduler that services the socket. - private let scheduler: any UDPSocketOperationScheduler - - /// The scheduler's handle of the socket, or `nil` once the socket is closed. - private var socket: (any Sendable)? - - private init( - scheduler: Scheduler, - socket: Scheduler.UDPSocket - ) { - self.scheduler = scheduler - self.socket = socket + private var core: UDPCore + + private init(core: consuming UDPCore) { + self.core = core } /// Creates a new socket and binds it to the given address. @@ -48,37 +40,16 @@ public struct UDPSocket: ~Copyable, Sendable { /// which ``localAddress`` reports afterwards. /// - Returns: The bound socket. public static func bind(to address: SocketAddress) async throws(IOError) -> UDPSocket { - guard - let scheduler = OperationSchedulerPreference.resolve(as: (any UDPSocketOperationScheduler).self) - else { - fatalError( - "No operation scheduler for UDP sockets found. Use withOperationScheduler or a task executor preference." - ) - } - return try await Self.bind(to: address, on: scheduler) + UDPSocket(core: try await UDPCore.bind(to: address)) } - private static func bind( - to address: SocketAddress, - on scheduler: Scheduler - ) async throws(IOError) -> UDPSocket { - let socket = try await scheduler.bind(to: address) - return UDPSocket(scheduler: scheduler, socket: socket) - } - - /// The address that the socket is bound to. + /// The address that the socket is bound to locally. public var localAddress: SocketAddress { get throws(IOError) { - try self.localAddress(on: self.scheduler) + try self.core.localAddress } } - private func localAddress( - on scheduler: Scheduler - ) throws(IOError) -> SocketAddress { - try scheduler.localAddress(of: self.socket(of: scheduler)) - } - /// Receives one datagram into the free capacity of the given buffer. /// /// The bytes are appended to the buffer. A datagram that is larger than the free capacity of the buffer is @@ -90,14 +61,7 @@ public struct UDPSocket: ~Copyable, Sendable { public mutating func receive( into buffer: inout OutputRawSpan ) async throws(IOError) -> (count: Int, sender: SocketAddress) { - try await self.receive(into: &buffer, on: self.scheduler) - } - - private func receive( - into buffer: inout OutputRawSpan, - on scheduler: Scheduler - ) async throws(IOError) -> (count: Int, sender: SocketAddress) { - try await scheduler.receive(socket: self.socket(of: scheduler), into: &buffer) + try await UDPCore.receive(into: &buffer, socket: self.core.socket, on: self.core.scheduler) } /// Sends the bytes of the given buffer as one datagram to the given address. @@ -109,48 +73,111 @@ public struct UDPSocket: ~Copyable, Sendable { from buffer: RawSpan, to address: SocketAddress ) async throws(IOError) { - try await self.send(from: buffer, to: address, on: self.scheduler) + try await UDPCore.send(from: buffer, to: address, socket: self.core.socket, on: self.core.scheduler) } - private func send( - from buffer: RawSpan, - to address: SocketAddress, - on scheduler: Scheduler - ) async throws(IOError) { - // A datagram is sent as a whole or not at all. - _ = try await scheduler.send(socket: self.socket(of: scheduler), from: buffer, to: address) + /// Connects the socket to the given address, so that it only exchanges datagrams with that peer. + /// + /// The socket keeps its local address. Connecting does not send anything, so it succeeds even if nobody + /// listens at the address. The platform drops the datagrams of everyone else from then on. + /// + /// - Important: If connecting fails the socket is closed. + /// + /// - Parameter address: The address of the peer. + /// - Returns: The connected socket. + public consuming func connect(to address: SocketAddress) async throws(IOError) -> UDPConnection { + UDPConnection(core: try await self.core.connected(to: address)) } /// Closes the socket. public consuming func close() async throws(IOError) { - try await Self.close(self.socket.take(), on: self.scheduler) + try await self.core.close() } +} - private static func close( - _ socket: (any Sendable)?, - on scheduler: Scheduler - ) async throws(IOError) { - let socket = socket as! Scheduler.UDPSocket - try await withTaskCancellationShield { () async throws(IOError) -> Void in - try await scheduler.close(socket: socket) +// MARK: - Receiving and sending concurrently + +@available(anyAppleOS 27.0, *) +extension UDPSocket { + /// The receiving direction of a socket, lent out by ``UDPSocket/withSplit(_:)``. + public struct ReceiveHalf: ~Copyable, ~Escapable, Sendable { + /// The scheduler that services the socket. + private let scheduler: any UDPSocketOperationScheduler + + /// The scheduler's handle of the socket. + private let socket: (any Sendable)? + + @_lifetime(borrow owner) + fileprivate init(_ owner: borrowing UDPSocket) { + self.scheduler = owner.core.scheduler + self.socket = owner.core.socket } - } - /// Returns the handle of the socket as the handle type of the given scheduler. - /// - /// - Parameter scheduler: The scheduler that services the socket. - private func socket( - of scheduler: Scheduler - ) -> Scheduler.UDPSocket { - // The handle was created by this scheduler, and it is only `nil` once - // the socket is closed, which consumes it. So the cast cannot fail. - self.socket as! Scheduler.UDPSocket + /// Receives one datagram into the free capacity of the given buffer. + /// + /// The bytes are appended to the buffer. A datagram that is larger than the free capacity of the buffer + /// is truncated, and its remaining bytes are discarded. + /// + /// - Parameter buffer: The buffer to receive into. + /// - Returns: The number of bytes received and the address of the sender. + @discardableResult + public mutating func receive( + into buffer: inout OutputRawSpan + ) async throws(IOError) -> (count: Int, sender: SocketAddress) { + try await UDPCore.receive(into: &buffer, socket: self.socket, on: self.scheduler) + } } - deinit { - if self.socket != nil { - fatalError("A UDPSocket was destroyed without being closed.") + /// The sending direction of a socket, lent out by ``UDPSocket/withSplit(_:)``. + public struct SendHalf: ~Copyable, ~Escapable, Sendable { + /// The scheduler that services the socket. + private let scheduler: any UDPSocketOperationScheduler + + /// The scheduler's handle of the socket. + private let socket: (any Sendable)? + + @_lifetime(borrow owner) + fileprivate init(_ owner: borrowing UDPSocket) { + self.scheduler = owner.core.scheduler + self.socket = owner.core.socket } + + /// Sends the bytes of the given buffer as one datagram to the given address. + /// + /// - Parameters: + /// - buffer: The bytes of the datagram. + /// - address: The address to send the datagram to. + public mutating func send(from buffer: RawSpan, to address: SocketAddress) async throws(IOError) { + try await UDPCore.send(from: buffer, to: address, socket: self.socket, on: self.scheduler) + } + } + + /// Lends the receiving and the sending direction of the socket to the given closure. + /// + /// The halves can be used concurrently allowing protocols to send and receive independently. Their + /// methods are `mutating`, so that every half is only used by one task at a time. + /// + /// ```swift + /// try await socket.withSplit { receiveHalf, sendHalf in + /// try await withConcurrently { + /// try await receiveReplies(from: &receiveHalf) + /// } _: { + /// try await sendHalf.send(from: request, to: address) + /// } + /// } + /// ``` + /// + /// - Important: The halves cannot escape the closure, so the socket keeps owning the platform resource + /// and must still be closed afterwards. + /// + /// - Parameter body: The closure that the halves are lent to. + /// - Returns: The value that the closure returned. + public nonisolated(nonsending) func withSplit( + _ body: nonisolated(nonsending) (inout ReceiveHalf, inout SendHalf) async throws(Failure) -> Return + ) async throws(Failure) -> Return { + var receiveHalf = ReceiveHalf(self) + var sendHalf = SendHalf(self) + return try await body(&receiveHalf, &sendHalf) } } #endif diff --git a/Sources/PlatformExecutors/IO/LowLevel/UDPSocketOperationScheduler.swift b/Sources/PlatformExecutors/IO/LowLevel/UDPSocketOperationScheduler.swift index e754803..d642ad7 100644 --- a/Sources/PlatformExecutors/IO/LowLevel/UDPSocketOperationScheduler.swift +++ b/Sources/PlatformExecutors/IO/LowLevel/UDPSocketOperationScheduler.swift @@ -25,6 +25,22 @@ public protocol UDPSocketOperationScheduler: OperationScheduler { /// - Returns: The bound socket. func bind(to address: SocketAddress) async throws(IOError) -> UDPSocket + /// Creates a new socket and connects it to the given address. + /// + /// A connected socket sends to and receives from only that peer, which it reads from and writes to with + /// ``read(socket:into:)`` and ``write(socket:from:)``. + /// + /// - Parameter address: The address of the peer. + /// - Returns: The connected socket. + func connectUDP(to address: SocketAddress) async throws(IOError) -> UDPSocket + + /// Connects a bound socket to the given address. + /// + /// - Parameters: + /// - socket: The socket to connect. + /// - address: The address of the peer. + func connectUDP(socket: borrowing UDPSocket, to address: SocketAddress) async throws(IOError) + /// Receives one datagram into the free capacity of the given buffer. /// /// The bytes are appended to the buffer. A datagram that is larger than the free capacity of the buffer is @@ -52,6 +68,25 @@ public protocol UDPSocketOperationScheduler: OperationScheduler { to address: SocketAddress ) async throws(IOError) -> Int + /// Receives one datagram from the peer of a connected socket into the free capacity of the given buffer. + /// + /// The bytes are appended to the buffer. A datagram that is larger than the free capacity of the buffer is + /// truncated, and its remaining bytes are discarded. + /// + /// - Parameters: + /// - socket: The connected socket to read from. + /// - buffer: The buffer to read into. + /// - Returns: The number of bytes received. + func read(socket: borrowing UDPSocket, into buffer: inout OutputRawSpan) async throws(IOError) -> Int + + /// Sends the given buffer as one datagram to the peer of a connected socket. + /// + /// - Parameters: + /// - socket: The connected socket to write to. + /// - buffer: The bytes of the datagram. + /// - Returns: The number of bytes sent. + func write(socket: borrowing UDPSocket, from buffer: RawSpan) async throws(IOError) -> Int + /// Closes a socket. /// /// - Parameter socket: The socket to close. @@ -64,5 +99,11 @@ public protocol UDPSocketOperationScheduler: OperationScheduler { /// - Parameter socket: The socket to return the address of. /// - Returns: The address that the socket is bound to. func localAddress(of socket: borrowing UDPSocket) throws(IOError) -> SocketAddress + + /// Returns the address of the peer that a connected socket is connected to. + /// + /// - Parameter socket: The connected socket to return the peer of. + /// - Returns: The address of the peer. + func remoteAddress(of socket: borrowing UDPSocket) throws(IOError) -> SocketAddress } #endif diff --git a/Sources/PlatformExecutors/PThread/Internal/IO/PThreadExecutor+UDPSocketOperations.swift b/Sources/PlatformExecutors/PThread/Internal/IO/PThreadExecutor+UDPSocketOperations.swift index 1313b0d..cebb266 100644 --- a/Sources/PlatformExecutors/PThread/Internal/IO/PThreadExecutor+UDPSocketOperations.swift +++ b/Sources/PlatformExecutors/PThread/Internal/IO/PThreadExecutor+UDPSocketOperations.swift @@ -42,7 +42,8 @@ private nonisolated(nonsending) func withDatagramMessage( unsafe vector.iov_len = buffer.count return try await unsafe withUnsafeMutablePointer(to: &address) { address async throws(E) -> R in try await unsafe withUnsafeMutablePointer(to: &vector) { vector async throws(E) -> R in - unsafe header.msg_name = UnsafeMutableRawPointer(address) + // Some platforms reject a message that has a name of length zero so we use nil instead. + unsafe header.msg_name = addressLength == 0 ? nil : UnsafeMutableRawPointer(address) unsafe header.msg_namelen = addressLength unsafe header.msg_iov = vector unsafe header.msg_iovlen = 1 @@ -76,23 +77,75 @@ extension PThreadExecutor: UDPSocketOperationScheduler { return UDPSocket(fileDescriptor: socket) } + package func connectUDP(to address: SocketAddress) async throws(IOError) -> UDPSocket { + let socket = try SocketSyscall.makeSocket(family: address.family, kind: .udp) + do { + try Self.connect(socket, to: address) + } catch { + try? SocketSyscall.close(socket) + throw error + } + return UDPSocket(fileDescriptor: socket) + } + + package func connectUDP(socket: borrowing UDPSocket, to address: SocketAddress) async throws(IOError) { + try Self.connect(socket.fileDescriptor, to: address) + } + package func receive( socket: borrowing UDPSocket, into buffer: inout OutputRawSpan ) async throws(IOError) -> (count: Int, sender: SocketAddress) { + let (count, sender) = try await self.receiveDatagram( + on: socket.fileDescriptor, + into: &buffer, + addressCapacity: socklen_t(MemoryLayout.size) + ) + guard let sender = SocketAddress(sender) else { + throw IOError(errnoCode: EAFNOSUPPORT) + } + return (count, sender) + } + + package func read(socket: borrowing UDPSocket, into buffer: inout OutputRawSpan) async throws(IOError) -> Int { + try await self.receiveDatagram(on: socket.fileDescriptor, into: &buffer, addressCapacity: 0).count + } + + package func send( + socket: borrowing UDPSocket, + from buffer: RawSpan, + to address: SocketAddress + ) async throws(IOError) -> Int { + try await self.sendDatagram(on: socket.fileDescriptor, from: buffer, to: address) + } + + package func write(socket: borrowing UDPSocket, from buffer: RawSpan) async throws(IOError) -> Int { + try await self.sendDatagram(on: socket.fileDescriptor, from: buffer, to: nil) + } + + /// Receives one datagram into the free capacity of the buffer. + /// + /// - Parameters: + /// - fileDescriptor: The file descriptor of the socket. + /// - buffer: The buffer to receive into. + /// - addressCapacity: The capacity for the address of the sender, which is zero if it is not wanted. + private func receiveDatagram( + on fileDescriptor: CInt, + into buffer: inout OutputRawSpan, + addressCapacity: socklen_t + ) async throws(IOError) -> (count: Int, sender: sockaddr_storage) { // The bytes are received into the free capacity of the buffer, which stays // alive while we are suspended since we hold the access to it. let freeCapacity = unsafe buffer.withUnsafeMutableBytes { bytes, initializedCount in unsafe UnsafeMutableRawBufferPointer(rebasing: bytes[initializedCount...]) } - let fileDescriptor = socket.fileDescriptor // The kernel writes the sender's address while we are suspended. var sender = sockaddr_storage() let count = try await unsafe withDatagramMessage( buffer: freeCapacity, address: &sender, - addressLength: socklen_t(MemoryLayout.size) + addressLength: addressCapacity ) { header async throws(IOError) -> Int in try await unsafe self.perform( .receiveMessage(socket: fileDescriptor, message: header) @@ -106,39 +159,46 @@ extension PThreadExecutor: UDPSocketOperationScheduler { unsafe buffer.withUnsafeMutableBytes { _, initializedCount in initializedCount += count } - - guard let sender = SocketAddress(sender) else { - throw IOError(errnoCode: EAFNOSUPPORT) - } return (count, sender) } - package func send( - socket: borrowing UDPSocket, + /// Sends the buffer as one datagram. + /// + /// - Parameters: + /// - fileDescriptor: The file descriptor of the socket. + /// - buffer: The bytes of the datagram. + /// - address: The address to send to, or `nil` to send to the peer that the socket is connected to. + private func sendDatagram( + on fileDescriptor: CInt, from buffer: RawSpan, - to address: SocketAddress + to address: SocketAddress? ) async throws(IOError) -> Int { let bytes = buffer.withUnsafeBytes { unsafe $0 } - let fileDescriptor = socket.fileDescriptor var destination = sockaddr_storage() - let addressLength = address.write(into: &destination) + let addressLength = address?.write(into: &destination) ?? 0 return try await unsafe withDatagramMessage( buffer: UnsafeMutableRawBufferPointer(mutating: bytes), address: &destination, addressLength: addressLength ) { header async throws(IOError) -> Int in try await unsafe self.perform( - .sendMessage( - socket: fileDescriptor, - message: header - ) + .sendMessage(socket: fileDescriptor, message: header) ) { continuation in .byteCount(continuation) } } } + /// Connects the socket to the address. + /// + /// Connecting a datagram socket only records the peer, so it completes right away. + private static func connect(_ fileDescriptor: CInt, to address: SocketAddress) throws(IOError) { + try unsafe address.withUnsafeSockAddress { (sockAddr, length) throws(IOError) -> Void in + _ = try unsafe SocketSyscall.connect(fileDescriptor, to: sockAddr, addressLength: length) + } + } + package func close(socket: consuming UDPSocket) async throws(IOError) { let fileDescriptor = socket.takeFileDescriptor() try await unsafe self.perform(.close(fileDescriptor: fileDescriptor)) { continuation in @@ -155,6 +215,14 @@ extension PThreadExecutor: UDPSocketOperationScheduler { package func localAddress(of socket: borrowing UDPSocket) throws(IOError) -> SocketAddress { try SocketSyscall.localAddress(socket.fileDescriptor) } + + /// Returns the address of the peer that the connected socket is connected to. + /// + /// - Parameter socket: The connected socket to return the peer of. + /// - Returns: The address of the peer. + package func remoteAddress(of socket: borrowing UDPSocket) throws(IOError) -> SocketAddress { + try SocketSyscall.peerAddress(socket.fileDescriptor) + } } #endif #endif diff --git a/Sources/PlatformExecutors/PThread/Internal/IO/PThreadTaskExecutor+UDPSocketOperations.swift b/Sources/PlatformExecutors/PThread/Internal/IO/PThreadTaskExecutor+UDPSocketOperations.swift index 1de4c87..b8dead7 100644 --- a/Sources/PlatformExecutors/PThread/Internal/IO/PThreadTaskExecutor+UDPSocketOperations.swift +++ b/Sources/PlatformExecutors/PThread/Internal/IO/PThreadTaskExecutor+UDPSocketOperations.swift @@ -26,6 +26,15 @@ extension PThreadTaskExecutor: UDPSocketOperationScheduler { try await self.current().bind(to: address) } + public func connectUDP(to address: SocketAddress) async throws(IOError) -> UDPSocket { + try await self.current().connectUDP(to: address) + } + + public func connectUDP(socket: borrowing UDPSocket, to address: SocketAddress) async throws(IOError) { + // Connecting is a plain syscall that no executor has to perform. + try await unsafe self.executors[0].connectUDP(socket: socket, to: address) + } + public func receive( socket: borrowing UDPSocket, into buffer: inout OutputRawSpan @@ -41,6 +50,14 @@ extension PThreadTaskExecutor: UDPSocketOperationScheduler { try await self.current().send(socket: socket, from: buffer, to: address) } + public func read(socket: borrowing UDPSocket, into buffer: inout OutputRawSpan) async throws(IOError) -> Int { + try await self.current().read(socket: socket, into: &buffer) + } + + public func write(socket: borrowing UDPSocket, from buffer: RawSpan) async throws(IOError) -> Int { + try await self.current().write(socket: socket, from: buffer) + } + public func close(socket: consuming UDPSocket) async throws(IOError) { try await self.current().close(socket: socket) } @@ -48,6 +65,10 @@ extension PThreadTaskExecutor: UDPSocketOperationScheduler { public func localAddress(of socket: borrowing UDPSocket) throws(IOError) -> SocketAddress { try unsafe self.executors[0].localAddress(of: socket) } + + public func remoteAddress(of socket: borrowing UDPSocket) throws(IOError) -> SocketAddress { + try unsafe self.executors[0].remoteAddress(of: socket) + } } #endif #endif diff --git a/Sources/PlatformExecutors/PThread/Internal/IO/SocketSyscall.swift b/Sources/PlatformExecutors/PThread/Internal/IO/SocketSyscall.swift index b694078..ff694fc 100644 --- a/Sources/PlatformExecutors/PThread/Internal/IO/SocketSyscall.swift +++ b/Sources/PlatformExecutors/PThread/Internal/IO/SocketSyscall.swift @@ -325,12 +325,29 @@ enum SocketSyscall { /// - Returns: The address that the socket is bound to. @available(anyAppleOS 26.0, *) static func localAddress(_ fileDescriptor: CInt) throws(IOError) -> SocketAddress { + try unsafe Self.address(of: fileDescriptor) { unsafe getsockname($0, $1, $2) } + } + + /// Returns the address of the peer that the socket is connected to. + /// + /// - Parameter fileDescriptor: The file descriptor of the socket. + /// - Returns: The address of the peer. + @available(anyAppleOS 26.0, *) + static func peerAddress(_ fileDescriptor: CInt) throws(IOError) -> SocketAddress { + try unsafe Self.address(of: fileDescriptor) { unsafe getpeername($0, $1, $2) } + } + + /// Reads an address of the socket with the given function. + private static func address( + of fileDescriptor: CInt, + using function: (CInt, UnsafeMutablePointer, UnsafeMutablePointer) -> CInt + ) throws(IOError) -> SocketAddress { var storage = sockaddr_storage() var length = socklen_t(MemoryLayout.size) let outcome = withUnsafeMutablePointer(to: &storage) { storagePointer in unsafe storagePointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockAddr in - unsafe Self.getSocketName(fileDescriptor, into: sockAddr, length: &length) + unsafe Self.getAddress(fileDescriptor, into: sockAddr, length: &length, using: function) } } if case .failure(let error) = outcome { @@ -344,15 +361,16 @@ enum SocketSyscall { return address } - /// Reads the address that the socket is bound to into the given storage. - private static func getSocketName( + /// Reads an address of the socket into the given storage. + private static func getAddress( _ fileDescriptor: CInt, into address: UnsafeMutablePointer, - length: inout socklen_t + length: inout socklen_t, + using function: (CInt, UnsafeMutablePointer, UnsafeMutablePointer) -> CInt ) -> Swift.Result { do { try retryingIOSyscall(blocking: false) { - unsafe getsockname(fileDescriptor, address, &length) + unsafe function(fileDescriptor, address, &length) } return .success(()) } catch { diff --git a/Tests/PlatformExecutorsTests/UDPSocketTests.swift b/Tests/PlatformExecutorsTests/UDPSocketTests.swift index 86396a5..60c3912 100644 --- a/Tests/PlatformExecutorsTests/UDPSocketTests.swift +++ b/Tests/PlatformExecutorsTests/UDPSocketTests.swift @@ -157,6 +157,92 @@ struct UDPSocketTests { } } + @Test(arguments: PThreadIOBackend.tested, [1, 4]) + @available(anyAppleOS 27.0, *) + func connectedSocketExchangesWithItsPeer(ioBackend: PThreadIOBackend, poolSize: Int) async throws { + try await PThreadTaskExecutor.withExecutor(name: "UDPSocketTest", poolSize: poolSize, ioBackend: ioBackend) { + executor in + try await withTaskExecutorPreference(executor) { + var server = try await UDPSocket.bind(to: Self.loopbackV4) + var client = try await UDPConnection.connect(to: server.localAddress) + + try await client.write(Array("ping".utf8)) + let (request, requestSender) = try await server.receive(maxCount: 1024) + #expect(request == Array("ping".utf8)) + #expect(requestSender == (try client.localAddress)) + + try await server.send(Array("pong".utf8), to: requestSender) + let reply = try await client.read(maxCount: 1024) + #expect(reply == Array("pong".utf8)) + + try await client.close() + try await server.close() + } + } + } + + @Test(arguments: PThreadIOBackend.tested, [1, 4]) + @available(anyAppleOS 27.0, *) + func withSplitReceivesWhileSending(ioBackend: PThreadIOBackend, poolSize: Int) async throws { + try await PThreadTaskExecutor.withExecutor(name: "UDPSocketTest", poolSize: poolSize, ioBackend: ioBackend) { + executor in + try await withTaskExecutorPreference(executor) { + try await withThrowingTaskGroup { group in + let bound = try await UDPSocket.bind(to: Self.loopbackV4) + let serverAddress = try bound.localAddress + var serverBox: UDPSocket? = bound + + // The server echoes one datagram. + group.addTask { + var server = serverBox.take()! + let (datagram, sender) = try await server.receive(maxCount: 1024) + try await server.send(datagram, to: sender) + try await server.close() + } + + let client = try await UDPConnection.connect(to: serverAddress) + let payload = Array("Echo me".utf8) + let echoed = try await client.withSplit { readHalf, writeHalf in + let (echoed, _) = try await withConcurrently { + try await readHalf.read(maxCount: 1024) + } _: { + try await writeHalf.write(payload) + } + return echoed + } + try await client.close() + try await group.waitForAll() + #expect(echoed == payload) + } + } + } + } + + @Test(arguments: PThreadIOBackend.tested) + @available(anyAppleOS 27.0, *) + func connectingABoundSocketKeepsItsAddressAndReportsThePeer(ioBackend: PThreadIOBackend) async throws { + try await PThreadExecutor.withExecutor(name: "UDPSocketTest", ioBackend: ioBackend) { executor in + try await withOperationScheduler(executor) { + var server = try await UDPSocket.bind(to: Self.loopbackV4) + let serverAddress = try server.localAddress + + let bound = try await UDPSocket.bind(to: Self.loopbackV4) + let boundAddress = try bound.localAddress + var client = try await bound.connect(to: serverAddress) + #expect(try client.localAddress == boundAddress) + #expect(try client.remoteAddress == serverAddress) + + try await client.write(Array("ping".utf8)) + let (request, sender) = try await server.receive(maxCount: 1024) + #expect(request == Array("ping".utf8)) + #expect(sender == boundAddress) + + try await client.close() + try await server.close() + } + } + } + /// Sends a datagram to a socket, which sends a reply to the address it received the datagram from. @available(anyAppleOS 27.0, *) private static func exchange() async throws { @@ -197,5 +283,43 @@ extension UDPSocket { try await self.send(from: bytes.span.bytes, to: address) } } +@available(anyAppleOS 27.0, *) +extension UDPConnection { + /// Reads one datagram of at most `maxCount` bytes from the peer of a connected socket. + fileprivate mutating func read(maxCount: Int) async throws(IOError) -> [UInt8] { + var buffer = UniqueArray(minimumCapacity: maxCount) + _ = try await buffer.append(addingByteCount: maxCount) { + (output: inout OutputRawSpan) async throws(IOError) -> Int in + try await self.read(into: &output) + } + return (0.. [UInt8] { + var buffer = UniqueArray(minimumCapacity: maxCount) + _ = try await buffer.append(addingByteCount: maxCount) { + (output: inout OutputRawSpan) async throws(IOError) -> Int in + try await self.read(into: &output) + } + return (0..