From 5be5ccb5a74269b179c3b482da55870c3b93e8b5 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 31 Jul 2023 15:19:49 +0100 Subject: [PATCH] Initial PoC of Custom Actor Executor support (#2388) * Support NIO Event Loops as actor executors Motivation Swift Concurrency supports having actors opt in to executing within a "custom executor". This requires being able to be strictly serial, a constraint that NIO's EventLoops natively meet. It is useful to have actors be able to express a "tie" to an EventLoop in order to efficiently access objects that are tied to specific ELs. Modifications - Extend EventLoop to expose an executor property - Provide a simple best-effort default using NIODefaultSerialEventLoopExecutor - Expose NIOSerialEventLoopExecutor protocol that makes it easy for adopters to get a better implementation - Crash if EmbeddedEventLoop is used - Add tests Result Adopters can use ELs as serial executors * Prefer #if compiler --- Sources/NIOCore/ActorExecutor.swift | 82 +++++++++++++++++++ Sources/NIOCore/EventLoop.swift | 20 +++++ .../NIOEmbedded/AsyncTestingEventLoop.swift | 6 ++ Sources/NIOEmbedded/Embedded.swift | 7 ++ Sources/NIOPosix/SelectableEventLoop.swift | 6 ++ Tests/NIOPosixTests/SerialExecutorTests.swift | 75 +++++++++++++++++ 6 files changed, 196 insertions(+) create mode 100644 Sources/NIOCore/ActorExecutor.swift create mode 100644 Tests/NIOPosixTests/SerialExecutorTests.swift diff --git a/Sources/NIOCore/ActorExecutor.swift b/Sources/NIOCore/ActorExecutor.swift new file mode 100644 index 000000000..2842181e4 --- /dev/null +++ b/Sources/NIOCore/ActorExecutor.swift @@ -0,0 +1,82 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +#if compiler(>=5.9) +/// A helper protocol that can be mixed in to a NIO ``EventLoop`` to provide an +/// automatic conformance to `SerialExecutor`. +/// +/// Implementers of `EventLoop` should consider conforming to this protocol as +/// well on Swift 5.9 and later. +@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) +public protocol NIOSerialEventLoopExecutor: EventLoop, SerialExecutor { } + +@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) +extension NIOSerialEventLoopExecutor { + @inlinable + public func enqueue(_ job: consuming ExecutorJob) { + let unownedJob = UnownedJob(job) + self.execute { + unownedJob.runSynchronously(on: self.asUnownedSerialExecutor()) + } + } + + @inlinable + public func asUnownedSerialExecutor() -> UnownedSerialExecutor { + UnownedSerialExecutor(ordinary: self) + } + + @inlinable + public var executor: any SerialExecutor { + self + } +} + +/// A type that wraps a NIO ``EventLoop`` into a `SerialExecutor` +/// for use with Swift concurrency. +/// +/// This type is not recommended for use because it risks problems with unowned +/// executors. Adopters are recommended to conform their own event loop +/// types to `SerialExecutor`. +final class NIODefaultSerialEventLoopExecutor { + @usableFromInline + let loop: EventLoop + + @inlinable + init(_ loop: EventLoop) { + self.loop = loop + } +} + +@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) +extension NIODefaultSerialEventLoopExecutor: SerialExecutor { + @inlinable + public func enqueue(_ job: consuming ExecutorJob) { + let unownedJob = UnownedJob(job) + self.loop.execute { + unownedJob.runSynchronously(on: self.asUnownedSerialExecutor()) + } + } + + @inlinable + public func asUnownedSerialExecutor() -> UnownedSerialExecutor { + UnownedSerialExecutor(complexEquality: self) + + } + + @inlinable + public func isSameExclusiveExecutionContext(other: NIODefaultSerialEventLoopExecutor) -> Bool { + self.loop === other.loop + } +} +#endif diff --git a/Sources/NIOCore/EventLoop.swift b/Sources/NIOCore/EventLoop.swift index 445bb8117..6675f118f 100644 --- a/Sources/NIOCore/EventLoop.swift +++ b/Sources/NIOCore/EventLoop.swift @@ -373,6 +373,17 @@ public protocol EventLoop: EventLoopGroup { /// allows `EventLoop`s to cache a pre-succeeded `Void` future to prevent superfluous allocations. func makeSucceededVoidFuture() -> EventLoopFuture + #if compiler(>=5.9) + /// Returns a `SerialExecutor` corresponding to this ``EventLoop``. + /// + /// This executor can be used to isolate an actor to a given ``EventLoop``. Implementers are encouraged to customise + /// this implementation by conforming their ``EventLoop`` to ``NIOSerialEventLoopExecutor`` which will provide an + /// optimised implementation of this method, and will conform their type to `SerialExecutor`. The default + /// implementation returns a ``NIODefaultSerialEventLoopExecutor`` instead, which provides suboptimal performance. + @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) + var executor: any SerialExecutor { get } + #endif + /// Must crash if it is not safe to call `wait()` on an `EventLoopFuture`. /// /// This method is a debugging hook that can be used to override the behaviour of `EventLoopFuture.wait()` when called. @@ -429,6 +440,15 @@ extension EventLoop { } } +extension EventLoop { + #if compiler(>=5.9) + @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) + public var executor: any SerialExecutor { + NIODefaultSerialEventLoopExecutor(self) + } + #endif +} + extension EventLoopGroup { public var description: String { return String(describing: self) diff --git a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift index 745059c94..bdc9423c8 100644 --- a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift +++ b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift @@ -349,6 +349,12 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { } } +// MARK: SerialExecutor conformance +#if compiler(>=5.9) +@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) +extension NIOAsyncTestingEventLoop: NIOSerialEventLoopExecutor { } +#endif + /// This is a thread-safe promise creation store. /// /// We use this to keep track of where promises come from in the `NIOAsyncTestingEventLoop`. diff --git a/Sources/NIOEmbedded/Embedded.swift b/Sources/NIOEmbedded/Embedded.swift index 3a91a526f..4a8ce0d21 100644 --- a/Sources/NIOEmbedded/Embedded.swift +++ b/Sources/NIOEmbedded/Embedded.swift @@ -233,6 +233,13 @@ public final class EmbeddedEventLoop: EventLoop { deinit { precondition(scheduledTasks.isEmpty, "Embedded event loop freed with unexecuted scheduled tasks!") } + + #if compiler(>=5.9) + @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) + public var executor: any SerialExecutor { + fatalError("EmbeddedEventLoop is not thread safe and cannot be used as a SerialExecutor. Use NIOAsyncTestingEventLoop instead.") + } + #endif } @usableFromInline diff --git a/Sources/NIOPosix/SelectableEventLoop.swift b/Sources/NIOPosix/SelectableEventLoop.swift index bc80ae736..52339ecce 100644 --- a/Sources/NIOPosix/SelectableEventLoop.swift +++ b/Sources/NIOPosix/SelectableEventLoop.swift @@ -661,3 +661,9 @@ extension SelectableEventLoop: CustomStringConvertible, CustomDebugStringConvert } } } + +// MARK: SerialExecutor conformance +#if compiler(>=5.9) +@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) +extension SelectableEventLoop: NIOSerialEventLoopExecutor { } +#endif diff --git a/Tests/NIOPosixTests/SerialExecutorTests.swift b/Tests/NIOPosixTests/SerialExecutorTests.swift new file mode 100644 index 000000000..84f524922 --- /dev/null +++ b/Tests/NIOPosixTests/SerialExecutorTests.swift @@ -0,0 +1,75 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import NIOCore +import NIOEmbedded +import NIOPosix +import XCTest + +#if compiler(>=5.9) +@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) +actor EventLoopBoundActor { + nonisolated let unownedExecutor: UnownedSerialExecutor + + init(loop: EventLoop) { + self.unownedExecutor = loop.executor.asUnownedSerialExecutor() + } + + func assertInLoop(_ loop: EventLoop) { + loop.assertInEventLoop() + XCTAssertTrue(loop.inEventLoop) + } + + func assertNotInLoop(_ loop: EventLoop) { + loop.assertNotInEventLoop() + XCTAssertFalse(loop.inEventLoop) + } +} +#endif + +final class SerialExecutorTests: XCTestCase { + private func _testBasicExecutorFitsOnEventLoop(loop1: EventLoop, loop2: EventLoop) async throws { + #if compiler(<5.9) + throw XCTSkip("Custom executors are only supported in 5.9") + #else + guard #available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) else { + throw XCTSkip("Custom executors not available on this platform") + } + + let testActor = EventLoopBoundActor(loop: loop1) + await testActor.assertInLoop(loop1) + await testActor.assertNotInLoop(loop2) + #endif + } + + func testBasicExecutorFitsOnEventLoop_MTELG() async throws { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 2) + defer { + try! group.syncShutdownGracefully() + } + let loops = Array(group.makeIterator()) + try await self._testBasicExecutorFitsOnEventLoop(loop1: loops[0], loop2: loops[1]) + } + + func testBasicExecutorFitsOnEventLoop_AsyncTestingEventLoop() async throws { + let loop1 = NIOAsyncTestingEventLoop() + let loop2 = NIOAsyncTestingEventLoop() + defer { + try? loop1.syncShutdownGracefully() + try? loop2.syncShutdownGracefully() + } + + try await self._testBasicExecutorFitsOnEventLoop(loop1: loop1, loop2: loop2) + } +} +