Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions Sources/PlatformExecutors/IO/HighLevel/UDPConnection.swift
Original file line number Diff line number Diff line change
@@ -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<Return, Failure: Error>(
_ 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
194 changes: 194 additions & 0 deletions Sources/PlatformExecutors/IO/HighLevel/UDPCore.swift
Original file line number Diff line number Diff line change
@@ -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: UDPSocketOperationScheduler>(
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<Scheduler: UDPSocketOperationScheduler>(
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<Scheduler: UDPSocketOperationScheduler>(
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<Scheduler: UDPSocketOperationScheduler>(
_ 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<Scheduler: UDPSocketOperationScheduler>(
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<Scheduler: UDPSocketOperationScheduler>(
socket: (any Sendable)?,
on scheduler: Scheduler
) throws(IOError) -> SocketAddress {
try scheduler.remoteAddress(of: Self.socket(socket, of: scheduler))
}

// MARK: - Datagrams

static func receive<Scheduler: UDPSocketOperationScheduler>(
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<Scheduler: UDPSocketOperationScheduler>(
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<Scheduler: UDPSocketOperationScheduler>(
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<Scheduler: UDPSocketOperationScheduler>(
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<Scheduler: UDPSocketOperationScheduler>(
_ 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<Scheduler: UDPSocketOperationScheduler>(
_ 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
Loading
Loading