From ea78d5aadcf96db47af1e63d044bf446c8147849 Mon Sep 17 00:00:00 2001 From: Si Beaumont Date: Thu, 3 Oct 2024 21:14:28 +0100 Subject: [PATCH] Add EventLoop APIs for simpler scheduling of callbacks (#2759) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Motivation The current `scheduleTask` APIs make use of _both_ callbacks and promises, which leads to confusing semantics. For example, on cancellation, users are notified in two ways: once via the promise and once via the callback. Additionally the way the API is structured results in unavoidable allocations—for the closures and the promise—which could be avoided if we structured the API differently. ## Modifications This PR introduces new protocol requirements on `EventLoop`: ```swift protocol EventLoop { // ... @discardableResult func scheduleCallback(at deadline: NIODeadline, handler: some NIOScheduledCallbackHandler) throws -> NIOScheduledCallback @discardableResult func scheduleCallback(in amount: TimeAmount, handler: some NIOScheduledCallbackHandler) throws -> NIOScheduledCallback func cancelScheduledCallback(_ scheduledCallback: NIOScheduledCallback) } ``` Default implementations have been provided that call through to `EventLoop.scheduleTask(in:_:)` to not break existing `EventLoop` implementations, although this implementation will be (at least) as slow as using `scheduleTask(in:_:)` directly. The API is structured to allow for `EventLoop` implementations to provide a custom implementation, as an optimization point and this PR provides a custom implementation for `SelectableEventLoop`, so that `MultiThreadedEventLoopGroup` can benefit from a faster implementation. Finally, this PR adds benchmarks to measure the performance of setting a simple timer using both `scheduleTask(in:_:)` and `scheduleCallback(in:_:)` APIs using a `MultiThreadedEventLoopGroup`. ## Result A simpler and more coherent API surface. There is also a small performance benefit for heavy users of this API, e.g. protocols that make extensive use of timers: when using MTELG to repeatedly set a timer with the same handler, switching from `scheduleTask(in:_:)` to `scheduleCallback(in:_:)` reduces almost all allocations (and amortizes to zero allocations) and is ~twice as fast. ``` MTELG.scheduleCallback(in:_:) ╒═══════════════════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╕ │ Metric │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │ ╞═══════════════════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╡ │ Malloc (total) * │ 0 │ 0 │ 0 │ 0 │ 0 │ 0 │ 0 │ 1109 │ ╘═══════════════════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╛ MTELG.scheduleTask(in:_:) ╒═══════════════════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╤═════════╕ │ Metric │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │ ╞═══════════════════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╡ │ Malloc (total) * │ 4 │ 4 │ 4 │ 4 │ 4 │ 4 │ 4 │ 576 │ ╘═══════════════════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╧═════════╛ ``` --- .../NIOPosixBenchmarks/Benchmarks.swift | 35 ++ Sources/NIOCore/EventLoop.swift | 25 ++ Sources/NIOCore/NIOScheduledCallback.swift | 166 +++++++++ .../NIOEmbedded/AsyncTestingEventLoop.swift | 32 ++ Sources/NIOEmbedded/Embedded.swift | 11 + .../MultiThreadedEventLoopGroup.swift | 22 +- Sources/NIOPosix/SelectableEventLoop.swift | 48 ++- Sources/_NIODataStructures/Heap.swift | 9 +- .../_NIODataStructures/PriorityQueue.swift | 3 +- .../AsyncChannelBootstrapTests.swift | 2 +- .../NIOScheduledCallbackTests.swift | 331 ++++++++++++++++++ 11 files changed, 669 insertions(+), 15 deletions(-) create mode 100644 Sources/NIOCore/NIOScheduledCallback.swift create mode 100644 Tests/NIOPosixTests/NIOScheduledCallbackTests.swift diff --git a/Benchmarks/Benchmarks/NIOPosixBenchmarks/Benchmarks.swift b/Benchmarks/Benchmarks/NIOPosixBenchmarks/Benchmarks.swift index 149c51dd4..3cc33b549 100644 --- a/Benchmarks/Benchmarks/NIOPosixBenchmarks/Benchmarks.swift +++ b/Benchmarks/Benchmarks/NIOPosixBenchmarks/Benchmarks.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import Benchmark +import NIOCore import NIOPosix private let eventLoop = MultiThreadedEventLoopGroup.singleton.next() @@ -66,4 +67,38 @@ let benchmarks = { ) } #endif + + Benchmark( + "MTELG.scheduleTask(in:_:)", + configuration: Benchmark.Configuration( + metrics: defaultMetrics, + scalingFactor: .mega, + maxDuration: .seconds(10_000_000), + maxIterations: 5 + ) + ) { benchmark in + for _ in benchmark.scaledIterations { + eventLoop.scheduleTask(in: .hours(1), {}) + } + } + + Benchmark( + "MTELG.scheduleCallback(in:_:)", + configuration: Benchmark.Configuration( + metrics: defaultMetrics, + scalingFactor: .mega, + maxDuration: .seconds(10_000_000), + maxIterations: 5 + ) + ) { benchmark in + final class Timer: NIOScheduledCallbackHandler { + func handleScheduledCallback(eventLoop: some EventLoop) {} + } + let timer = Timer() + + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + let handle = try! eventLoop.scheduleCallback(in: .hours(1), handler: timer) + } + } } diff --git a/Sources/NIOCore/EventLoop.swift b/Sources/NIOCore/EventLoop.swift index 7b9e0c68e..171a757ba 100644 --- a/Sources/NIOCore/EventLoop.swift +++ b/Sources/NIOCore/EventLoop.swift @@ -365,6 +365,31 @@ public protocol EventLoop: EventLoopGroup { /// It is valid for an `EventLoop` not to implement any of the two `_promise` functions. If either of them are implemented, /// however, both of them should be implemented. func _promiseCompleted(futureIdentifier: _NIOEventLoopFutureIdentifier) -> (file: StaticString, line: UInt)? + + /// Schedule a callback at a given time. + /// + /// - NOTE: Event loops that provide a custom scheduled callback implementation **must** also implement + /// `cancelScheduledCallback`. Failure to do so will result in a runtime error. + @discardableResult + func scheduleCallback( + at deadline: NIODeadline, + handler: some NIOScheduledCallbackHandler + ) throws -> NIOScheduledCallback + + /// Schedule a callback after given time. + /// + /// - NOTE: Event loops that provide a custom scheduled callback implementation **must** also implement + /// `cancelScheduledCallback`. Failure to do so will result in a runtime error. + @discardableResult + func scheduleCallback( + in amount: TimeAmount, + handler: some NIOScheduledCallbackHandler + ) throws -> NIOScheduledCallback + + /// Cancel a scheduled callback. + /// + /// - NOTE: Event loops only need to implemented this if they provide a custom scheduled callback implementation. + func cancelScheduledCallback(_ scheduledCallback: NIOScheduledCallback) } extension EventLoop { diff --git a/Sources/NIOCore/NIOScheduledCallback.swift b/Sources/NIOCore/NIOScheduledCallback.swift new file mode 100644 index 000000000..84c9f8d20 --- /dev/null +++ b/Sources/NIOCore/NIOScheduledCallback.swift @@ -0,0 +1,166 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2024 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 +// +//===----------------------------------------------------------------------===// + +/// A type that handles callbacks scheduled with `EventLoop.scheduleCallback(at:handler:)`. +/// +/// - Seealso: `EventLoop.scheduleCallback(at:handler:)`. +public protocol NIOScheduledCallbackHandler { + /// This function is called at the scheduled time, unless the scheduled callback is cancelled. + /// + /// - Parameter eventLoop: The event loop on which the callback was scheduled. + func handleScheduledCallback(eventLoop: some EventLoop) + + /// This function is called if the scheduled callback is cancelled. + /// + /// The callback could be cancelled explictily, by the user calling ``NIOScheduledCallback/cancel()``, or + /// implicitly, if it was still pending when the event loop was shut down. + /// + /// - Parameter eventLoop: The event loop on which the callback was scheduled. + func didCancelScheduledCallback(eventLoop: some EventLoop) +} + +extension NIOScheduledCallbackHandler { + /// Default implementation of `didCancelScheduledCallback(eventLoop:)`: does nothing. + public func didCancelScheduledCallback(eventLoop: some EventLoop) {} +} + +/// An opaque handle that can be used to cancel a scheduled callback. +/// +/// Users should not create an instance of this type; it is returned by `EventLoop.scheduleCallback(at:handler:)`. +/// +/// - Seealso: `EventLoop.scheduleCallback(at:handler:)`. +public struct NIOScheduledCallback: Sendable { + @usableFromInline + enum Backing: Sendable { + /// A task created using `EventLoop.scheduleTask(deadline:_:)` by the default implementation. + case `default`(_ task: Scheduled) + /// A custom callback identifier, used by event loops that provide a custom implementation. + case custom(id: UInt64) + } + + @usableFromInline + var eventLoop: any EventLoop + + @usableFromInline + var backing: Backing + + /// This initializer is only for the default implementation and is fileprivate to avoid use in EL implementations. + fileprivate init(_ eventLoop: any EventLoop, _ task: Scheduled) { + self.eventLoop = eventLoop + self.backing = .default(task) + } + + /// Create a handle for the scheduled callback with an opaque identifier managed by the event loop. + /// + /// - NOTE: This initializer is for event loop implementors only, end users should use `EventLoop.scheduleCallback`. + /// + /// - Seealso: `EventLoop.scheduleCallback(at:handler:)`. + @inlinable + public init(_ eventLoop: any EventLoop, id: UInt64) { + self.eventLoop = eventLoop + self.backing = .custom(id: id) + } + + /// Cancel the scheduled callback associated with this handle. + @inlinable + public func cancel() { + self.eventLoop.cancelScheduledCallback(self) + } + + /// The callback identifier, if the event loop uses a custom scheduled callback implementation; nil otherwise. + /// + /// - NOTE: This property is for event loop implementors only. + @inlinable + public var customCallbackID: UInt64? { + guard case .custom(let id) = self.backing else { return nil } + return id + } +} + +extension EventLoop { + // This could be package once we drop Swift 5.8. + public func _scheduleCallback( + at deadline: NIODeadline, + handler: some NIOScheduledCallbackHandler + ) -> NIOScheduledCallback { + let task = self.scheduleTask(deadline: deadline) { handler.handleScheduledCallback(eventLoop: self) } + task.futureResult.whenFailure { error in + if case .cancelled = error as? EventLoopError { + handler.didCancelScheduledCallback(eventLoop: self) + } + } + return NIOScheduledCallback(self, task) + } + + /// Default implementation of `scheduleCallback(at deadline:handler:)`: backed by `EventLoop.scheduleTask`. + /// + /// Ideally the scheduled callback handler should be called exactly once for each call to `scheduleCallback`: + /// either the callback handler, or the cancellation handler. + /// + /// In order to support cancellation in the default implementation, we hook the future of the scheduled task + /// backing the scheduled callback. This requires two calls to the event loop: `EventLoop.scheduleTask`, and + /// `EventLoopFuture.whenFailure`, both of which queue onto the event loop if called from off the event loop. + /// + /// This can present a challenge during event loop shutdown, where typically: + /// 1. Scheduled work that is past its deadline gets run. + /// 2. Scheduled future work gets cancelled. + /// 3. New work resulting from (1) and (2) gets handled differently depending on the EL: + /// a. `SelectableEventLoop` runs new work recursively and crashes if not quiesced in some number of ticks. + /// b. `EmbeddedEventLoop` and `NIOAsyncTestingEventLoop` will fail incoming work. + /// + /// `SelectableEventLoop` has a custom implementation for scheduled callbacks so warrants no further discussion. + /// + /// As a practical matter, the `EmbeddedEventLoop` is OK because it shares the thread of the caller, but for + /// other event loops (including any outside this repo), it's possible that the call to shutdown interleaves + /// with the call to create the scheduled task and the call to hook the task future. + /// + /// Because this API is synchronous and we cannot block the calling thread, users of event loops with this + /// default implementation will have cancellation callbacks delivered on a best-effort basis when the event loop + /// is shutdown and depends on how the event loop deals with newly scheduled tasks during shutdown. + /// + /// The implementation of this default conformance has been further factored out so we can use it in + /// `NIOAsyncTestingEventLoop`, where the use of `wait()` is _less bad_. + @discardableResult + public func scheduleCallback( + at deadline: NIODeadline, + handler: some NIOScheduledCallbackHandler + ) -> NIOScheduledCallback { + self._scheduleCallback(at: deadline, handler: handler) + } + + /// Default implementation of `scheduleCallback(in amount:handler:)`: calls `scheduleCallback(at deadline:handler:)`. + @discardableResult + @inlinable + public func scheduleCallback( + in amount: TimeAmount, + handler: some NIOScheduledCallbackHandler + ) throws -> NIOScheduledCallback { + try self.scheduleCallback(at: .now() + amount, handler: handler) + } + + /// Default implementation of `cancelScheduledCallback(_:)`: only cancels callbacks scheduled by the default implementation of `scheduleCallback`. + /// + /// - NOTE: Event loops that provide a custom scheduled callback implementation **must** implement _both_ + /// `sheduleCallback(at deadline:handler:)` _and_ `cancelScheduledCallback(_:)`. Failure to do so will + /// result in a runtime error. + @inlinable + public func cancelScheduledCallback(_ scheduledCallback: NIOScheduledCallback) { + switch scheduledCallback.backing { + case .default(let task): + task.cancel() + case .custom: + preconditionFailure("EventLoop missing custom implementation of cancelScheduledCallback(_:)") + } + } +} diff --git a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift index 9085e7864..959b4bb34 100644 --- a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift +++ b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift @@ -192,6 +192,38 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { self.scheduleTask(deadline: self.now + `in`, task) } + public func scheduleCallback( + at deadline: NIODeadline, + handler: some NIOScheduledCallbackHandler + ) throws -> NIOScheduledCallback { + /// The default implementation of `scheduledCallback(at:handler)` makes two calls to the event loop because it + /// needs to hook the future of the backing scheduled task, which can lead to lost cancellation callbacks when + /// callbacks are scheduled close to event loop shutdown. + /// + /// We work around this here by using a blocking `wait()` if we are not on the event loop, which would be very + /// bad in areal event loop, but _less bad_ for testing. + /// + /// For more details, see the documentation attached to the default implementation. + if self.inEventLoop { + return self._scheduleCallback(at: deadline, handler: handler) + } else { + return try self.submit { + self._scheduleCallback(at: deadline, handler: handler) + }.wait() + } + } + + @discardableResult + public func scheduleCallback( + in amount: TimeAmount, + handler: some NIOScheduledCallbackHandler + ) throws -> NIOScheduledCallback { + /// Even though this type does not implement a custom `scheduleCallback(at:handler)`, it uses a manual clock so + /// it cannot rely on the default implementation of `scheduleCallback(in:handler:)`, which computes the deadline + /// as an offset from `NIODeadline.now`. This event loop needs the deadline to be offset from `self.now`. + try self.scheduleCallback(at: self.now + amount, handler: handler) + } + /// On an `NIOAsyncTestingEventLoop`, `execute` will simply use `scheduleTask` with a deadline of _now_. Unlike with the other operations, this will /// immediately execute, to eliminate a common class of bugs. public func execute(_ task: @escaping () -> Void) { diff --git a/Sources/NIOEmbedded/Embedded.swift b/Sources/NIOEmbedded/Embedded.swift index 032b4a924..93e90bfe5 100644 --- a/Sources/NIOEmbedded/Embedded.swift +++ b/Sources/NIOEmbedded/Embedded.swift @@ -160,6 +160,17 @@ public final class EmbeddedEventLoop: EventLoop, CustomStringConvertible { scheduleTask(deadline: self._now + `in`, task) } + @discardableResult + public func scheduleCallback( + in amount: TimeAmount, + handler: some NIOScheduledCallbackHandler + ) -> NIOScheduledCallback { + /// Even though this type does not implement a custom `scheduleCallback(at:handler)`, it uses a manual clock so + /// it cannot rely on the default implementation of `scheduleCallback(in:handler:)`, which computes the deadline + /// as an offset from `NIODeadline.now`. This event loop needs the deadline to be offset from `self._now`. + self.scheduleCallback(at: self._now + amount, handler: handler) + } + /// On an `EmbeddedEventLoop`, `execute` will simply use `scheduleTask` with a deadline of _now_. This means that /// `task` will be run the next time you call `EmbeddedEventLoop.run`. public func execute(_ task: @escaping () -> Void) { diff --git a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift index 9f9266fa8..c188e8ef6 100644 --- a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift +++ b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift @@ -511,6 +511,15 @@ struct ErasedUnownedJob { @usableFromInline internal struct ScheduledTask { + @usableFromInline + enum Kind { + case task(task: () -> Void, failFn: (Error) -> Void) + case callback(any NIOScheduledCallbackHandler) + } + + @usableFromInline + let kind: Kind + /// The id of the scheduled task. /// /// - Important: This id has two purposes. First, it is used to give this struct an identity so that we can implement ``Equatable`` @@ -518,21 +527,22 @@ internal struct ScheduledTask { /// This means, the ids need to be unique for a given ``SelectableEventLoop`` and they need to be in ascending order. @usableFromInline let id: UInt64 - let task: () -> Void - private let failFn: (Error) -> Void + @usableFromInline internal let readyTime: NIODeadline @usableFromInline init(id: UInt64, _ task: @escaping () -> Void, _ failFn: @escaping (Error) -> Void, _ time: NIODeadline) { self.id = id - self.task = task - self.failFn = failFn self.readyTime = time + self.kind = .task(task: task, failFn: failFn) } - func fail(_ error: Error) { - failFn(error) + @usableFromInline + init(id: UInt64, _ handler: any NIOScheduledCallbackHandler, _ time: NIODeadline) { + self.id = id + self.readyTime = time + self.kind = .callback(handler) } } diff --git a/Sources/NIOPosix/SelectableEventLoop.swift b/Sources/NIOPosix/SelectableEventLoop.swift index c8f9204cf..79ba55b6c 100644 --- a/Sources/NIOPosix/SelectableEventLoop.swift +++ b/Sources/NIOPosix/SelectableEventLoop.swift @@ -497,6 +497,8 @@ internal final class SelectableEventLoop: EventLoop { fatalError("Tried to run an UnownedJob without runtime support") } #endif + case .callback(let handler): + handler.handleScheduledCallback(eventLoop: self) } } } @@ -591,7 +593,10 @@ internal final class SelectableEventLoop: EventLoop { if moreScheduledTasksToConsider, tasksCopy.count < tasksCopyBatchSize, let task = scheduledTasks.peek() { if task.readyTime.readyIn(now) <= .nanoseconds(0) { scheduledTasks.pop() - tasksCopy.append(.function(task.task)) + switch task.kind { + case .task(let task, _): tasksCopy.append(.function(task)) + case .callback(let handler): tasksCopy.append(.callback(handler)) + } } else { nextScheduledTaskDeadline = task.readyTime moreScheduledTasksToConsider = false @@ -690,9 +695,15 @@ internal final class SelectableEventLoop: EventLoop { for task in immediateTasksCopy { self.run(task) } - // Fail all the scheduled tasks. for task in scheduledTasksCopy { - task.fail(EventLoopError._shutdown) + switch task.kind { + // Fail all the scheduled tasks. + case .task(_, let failFn): + failFn(EventLoopError._shutdown) + // Call the cancellation handler for all the scheduled callbacks. + case .callback(let handler): + handler.didCancelScheduledCallback(eventLoop: self) + } } iterations += 1 @@ -901,6 +912,7 @@ enum UnderlyingTask { #if compiler(>=5.9) case unownedJob(ErasedUnownedJob) #endif + case callback(any NIOScheduledCallbackHandler) } @usableFromInline @@ -917,3 +929,33 @@ internal func assertExpression(_ body: () -> Bool) { }() ) } + +extension SelectableEventLoop { + @inlinable + func scheduleCallback( + at deadline: NIODeadline, + handler: some NIOScheduledCallbackHandler + ) throws -> NIOScheduledCallback { + let taskID = self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed) + let task = ScheduledTask(id: taskID, handler, deadline) + try self._schedule0(.scheduled(task)) + return NIOScheduledCallback(self, id: taskID) + } + + @inlinable + func cancelScheduledCallback(_ scheduledCallback: NIOScheduledCallback) { + guard let id = scheduledCallback.customCallbackID else { + preconditionFailure("No custom ID for callback") + } + self._tasksLock.withLock { + guard let scheduledTask = self._scheduledTasks.removeFirst(where: { $0.id == id }) else { + // Must have been cancelled already. + return + } + guard case .callback(let handler) = scheduledTask.kind else { + preconditionFailure("Incorrect task kind for callback") + } + handler.didCancelScheduledCallback(eventLoop: self) + } + } +} diff --git a/Sources/_NIODataStructures/Heap.swift b/Sources/_NIODataStructures/Heap.swift index 7fab52653..ac11e2bb4 100644 --- a/Sources/_NIODataStructures/Heap.swift +++ b/Sources/_NIODataStructures/Heap.swift @@ -126,17 +126,18 @@ internal struct Heap { } } + @discardableResult @inlinable - internal mutating func removeFirst(where shouldBeRemoved: (Element) throws -> Bool) rethrows { + internal mutating func removeFirst(where shouldBeRemoved: (Element) throws -> Bool) rethrows -> Element? { guard self.storage.count > 0 else { - return + return nil } guard let index = try self.storage.firstIndex(where: shouldBeRemoved) else { - return + return nil } - self._remove(index: index) + return self._remove(index: index) } @discardableResult diff --git a/Sources/_NIODataStructures/PriorityQueue.swift b/Sources/_NIODataStructures/PriorityQueue.swift index 765826166..21d0aa38b 100644 --- a/Sources/_NIODataStructures/PriorityQueue.swift +++ b/Sources/_NIODataStructures/PriorityQueue.swift @@ -26,8 +26,9 @@ public struct PriorityQueue { self._heap.remove(value: key) } + @discardableResult @inlinable - public mutating func removeFirst(where shouldBeRemoved: (Element) throws -> Bool) rethrows { + public mutating func removeFirst(where shouldBeRemoved: (Element) throws -> Bool) rethrows -> Element? { try self._heap.removeFirst(where: shouldBeRemoved) } diff --git a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift index c425de8d8..98d894359 100644 --- a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift +++ b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift @@ -1485,7 +1485,7 @@ final class AsyncChannelBootstrapTests: XCTestCase { @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension AsyncStream { - fileprivate static func makeStream( + static func makeStream( of elementType: Element.Type = Element.self, bufferingPolicy limit: Continuation.BufferingPolicy = .unbounded ) -> (stream: AsyncStream, continuation: AsyncStream.Continuation) { diff --git a/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift b/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift new file mode 100644 index 000000000..7038b7129 --- /dev/null +++ b/Tests/NIOPosixTests/NIOScheduledCallbackTests.swift @@ -0,0 +1,331 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2024 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 + +protocol ScheduledCallbackTestRequirements { + // Some ELs are backed by an ELG. + var loop: (any EventLoop) { get } + + // Some ELs have a manual time ratchet. + func advanceTime(by amount: TimeAmount) async throws + + // ELG-backed ELs need to be shutdown via the ELG. + func shutdownEventLoop() async throws + + // This is here for NIOAsyncTestingEventLoop only. + func maybeInContext(_ body: @escaping @Sendable () throws -> R) async throws -> R +} + +final class MTELGScheduledCallbackTests: _BaseScheduledCallbackTests { + struct Requirements: ScheduledCallbackTestRequirements { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + var loop: (any EventLoop) { self.group.next() } + + func advanceTime(by amount: TimeAmount) async throws { + try await Task.sleep(nanoseconds: UInt64(amount.nanoseconds)) + } + + func shutdownEventLoop() async throws { + try await self.group.shutdownGracefully() + } + + func maybeInContext(_ body: @escaping @Sendable () throws -> R) async throws -> R { + try body() + } + } + + override func setUp() async throws { + self.requirements = Requirements() + } +} + +final class EmbeddedScheduledCallbackTests: _BaseScheduledCallbackTests { + struct Requirements: ScheduledCallbackTestRequirements { + let _loop = EmbeddedEventLoop() + var loop: (any EventLoop) { self._loop } + + func advanceTime(by amount: TimeAmount) async throws { + self._loop.advanceTime(by: amount) + } + + func shutdownEventLoop() async throws { + try await self._loop.shutdownGracefully() + } + + func maybeInContext(_ body: @escaping @Sendable () throws -> R) async throws -> R { + try body() + } + } + + override func setUp() async throws { + self.requirements = Requirements() + } +} + +final class NIOAsyncTestingEventLoopScheduledCallbackTests: _BaseScheduledCallbackTests { + struct Requirements: ScheduledCallbackTestRequirements { + let _loop = NIOAsyncTestingEventLoop() + var loop: (any EventLoop) { self._loop } + + func advanceTime(by amount: TimeAmount) async throws { + await self._loop.advanceTime(by: amount) + } + + func shutdownEventLoop() async throws { + await self._loop.shutdownGracefully() + } + + func maybeInContext(_ body: @escaping @Sendable () throws -> R) async throws -> R { + try await self._loop.executeInContext(body) + } + } + + override func setUp() async throws { + self.requirements = Requirements() + } +} + +class _BaseScheduledCallbackTests: XCTestCase { + // EL-specific test requirements. + var requirements: (any ScheduledCallbackTestRequirements)! = nil + + override func setUp() async throws { + try XCTSkipIf(type(of: self) == _BaseScheduledCallbackTests.self, "This is the abstract base class") + preconditionFailure("Subclass should implement setup and initialise EL-specific `self.requirements`") + } +} + +// Provide pass through computed properties to the EL-specific test requirements. +extension _BaseScheduledCallbackTests { + var loop: (any EventLoop) { self.requirements.loop } + + func advanceTime(by amount: TimeAmount) async throws { + try await self.requirements.advanceTime(by: amount) + } + + func shutdownEventLoop() async throws { + try await self.requirements.shutdownEventLoop() + } + + func maybeInContext(_ body: @escaping @Sendable () throws -> R) async throws -> R { + try await self.requirements.maybeInContext(body) + } +} + +// The tests, abstracted over any of the event loops. +extension _BaseScheduledCallbackTests { + + func testScheduledCallbackNotExecutedBeforeDeadline() async throws { + let handler = MockScheduledCallbackHandler() + + _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) + try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 0) } + + try await self.advanceTime(by: .microseconds(1)) + try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 0) } + } + + func testSheduledCallbackExecutedAtDeadline() async throws { + let handler = MockScheduledCallbackHandler() + + _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) + try await self.advanceTime(by: .milliseconds(1)) + try await handler.waitForCallback(timeout: .seconds(1)) + try await self.maybeInContext { handler.assert(callbackCount: 1, cancelCount: 0) } + } + + func testMultipleSheduledCallbacksUsingSameHandler() async throws { + let handler = MockScheduledCallbackHandler() + + _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) + _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) + + try await self.advanceTime(by: .milliseconds(1)) + try await handler.waitForCallback(timeout: .seconds(1)) + try await handler.waitForCallback(timeout: .seconds(1)) + try await self.maybeInContext { handler.assert(callbackCount: 2, cancelCount: 0) } + + _ = try self.loop.scheduleCallback(in: .milliseconds(2), handler: handler) + _ = try self.loop.scheduleCallback(in: .milliseconds(3), handler: handler) + + try await self.advanceTime(by: .milliseconds(3)) + try await handler.waitForCallback(timeout: .seconds(1)) + try await handler.waitForCallback(timeout: .seconds(1)) + try await self.maybeInContext { handler.assert(callbackCount: 4, cancelCount: 0) } + } + + func testMultipleSheduledCallbacksUsingDifferentHandlers() async throws { + let handlerA = MockScheduledCallbackHandler() + let handlerB = MockScheduledCallbackHandler() + + _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handlerA) + _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handlerB) + + try await self.advanceTime(by: .milliseconds(1)) + try await handlerA.waitForCallback(timeout: .seconds(1)) + try await handlerB.waitForCallback(timeout: .seconds(1)) + try await self.maybeInContext { handlerA.assert(callbackCount: 1, cancelCount: 0) } + try await self.maybeInContext { handlerB.assert(callbackCount: 1, cancelCount: 0) } + } + + func testCancelExecutesCancellationCallback() async throws { + let handler = MockScheduledCallbackHandler() + + let scheduledCallback = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) + scheduledCallback.cancel() + try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + } + + func testCancelAfterDeadlineDoesNotExecutesCancellationCallback() async throws { + let handler = MockScheduledCallbackHandler() + + let scheduledCallback = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) + try await self.advanceTime(by: .milliseconds(1)) + try await handler.waitForCallback(timeout: .seconds(1)) + scheduledCallback.cancel() + try await self.maybeInContext { handler.assert(callbackCount: 1, cancelCount: 0) } + } + + func testCancelAfterCancelDoesNotCallCancellationCallbackAgain() async throws { + let handler = MockScheduledCallbackHandler() + + let scheduledCallback = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) + scheduledCallback.cancel() + scheduledCallback.cancel() + try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + } + + func testCancelAfterShutdownDoesNotCallCancellationCallbackAgain() async throws { + let handler = MockScheduledCallbackHandler() + + let scheduledCallback = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) + try await self.shutdownEventLoop() + try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + + scheduledCallback.cancel() + try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + } + + func testShutdownCancelsOutstandingScheduledCallbacks() async throws { + let handler = MockScheduledCallbackHandler() + + _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) + try await self.shutdownEventLoop() + try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + } + + func testShutdownDoesNotCancelCancelledCallbacksAgain() async throws { + let handler = MockScheduledCallbackHandler() + + let handle = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) + handle.cancel() + try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + + try await self.shutdownEventLoop() + try await self.maybeInContext { handler.assert(callbackCount: 0, cancelCount: 1) } + } + + func testShutdownDoesNotCancelPastCallbacks() async throws { + let handler = MockScheduledCallbackHandler() + + _ = try self.loop.scheduleCallback(in: .milliseconds(1), handler: handler) + try await self.advanceTime(by: .milliseconds(1)) + try await handler.waitForCallback(timeout: .seconds(1)) + try await self.maybeInContext { handler.assert(callbackCount: 1, cancelCount: 0) } + + try await self.shutdownEventLoop() + try await self.maybeInContext { handler.assert(callbackCount: 1, cancelCount: 0) } + } +} + +private final class MockScheduledCallbackHandler: NIOScheduledCallbackHandler { + var callbackCount = 0 + var cancelCount = 0 + + let callbackStream: AsyncStream + private let callbackStreamContinuation: AsyncStream.Continuation + + init() { + (self.callbackStream, self.callbackStreamContinuation) = AsyncStream.makeStream(of: Void.self) + } + + deinit { + self.callbackStreamContinuation.finish() + } + + func handleScheduledCallback(eventLoop: some EventLoop) { + self.callbackCount += 1 + self.callbackStreamContinuation.yield() + } + + func didCancelScheduledCallback(eventLoop: some EventLoop) { + self.cancelCount += 1 + } + + func assert(callbackCount: Int, cancelCount: Int, file: StaticString = #file, line: UInt = #line) { + XCTAssertEqual(self.callbackCount, callbackCount, "Unexpected callback count", file: file, line: line) + XCTAssertEqual(self.cancelCount, cancelCount, "Unexpected cancel count", file: file, line: line) + } + + func waitForCallback(timeout: TimeAmount, file: StaticString = #file, line: UInt = #line) async throws { + try await XCTWithTimeout(timeout, file: file, line: line) { await self.callbackStream.first { _ in true } } + } +} + +/// This function exists because there's no nice way of waiting in tests for something to happen in the handler +/// without an arbitrary sleep. +/// +/// Other options include setting `XCTestCase.allowedExecutionTime` in `setup()` but this doesn't work well because +/// (1), it rounds up to the nearest minute; and (2), it doesn't seem to work reliably. +/// +/// Another option is to install a timebomb in `XCTestCase.setup()` that will fail the test. This works, but you +/// don't get any information on where the test was when it fails. +/// +/// Alternatively, one can use expectations, but these cannot be awaited more than once so won't work for tests where +/// the same handler is used to schedule multiple callbacks. +/// +/// This function is probably a good balance of pragmatism and clarity. +func XCTWithTimeout( + _ timeout: TimeAmount, + file: StaticString = #file, + line: UInt = #line, + operation: @escaping @Sendable () async throws -> Result +) async throws -> Result where Result: Sendable { + do { + return try await withTimeout(timeout, operation: operation) + } catch is CancellationError { + XCTFail("Timed out after \(timeout)", file: file, line: line) + throw CancellationError() + } +} + +func withTimeout( + _ timeout: TimeAmount, + operation: @escaping @Sendable () async throws -> Result +) async throws -> Result where Result: Sendable { + try await withThrowingTaskGroup(of: Result.self) { group in + group.addTask { + try await Task.sleep(nanoseconds: UInt64(timeout.nanoseconds)) + throw CancellationError() + } + group.addTask(operation: operation) + let result = try await group.next()! + group.cancelAll() + return result + } +}