From 5a567709b2cc5b35bfb7464087a7fc839635546b Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Wed, 11 Dec 2019 18:41:51 +0000 Subject: [PATCH] remove phantom publics from EventLoop and Heap (#1298) Motivation: In SelectableEventloop, Heap, PriorityQueue, etc there were quite a few phantom publics left which cause issues with #1257 and are confusing. Modifications: - remove the phantom publics - move SelectableEventLoop to its own file Result: - clearer what's going on (public means public) --- Sources/NIO/EventLoop.swift | 468 +------------------------ Sources/NIO/Heap.swift | 52 +-- Sources/NIO/PriorityQueue.swift | 44 ++- Sources/NIO/SelectableEventLoop.swift | 472 ++++++++++++++++++++++++++ 4 files changed, 544 insertions(+), 492 deletions(-) create mode 100644 Sources/NIO/SelectableEventLoop.swift diff --git a/Sources/NIO/EventLoop.swift b/Sources/NIO/EventLoop.swift index e463f1e6b..f02a4ffb4 100644 --- a/Sources/NIO/EventLoop.swift +++ b/Sources/NIO/EventLoop.swift @@ -632,454 +632,6 @@ enum NIORegistration: Registration { } } -/// Execute the given closure and ensure we release all auto pools if needed. -private func withAutoReleasePool(_ execute: () throws -> T) rethrows -> T { - #if os(Linux) - return try execute() - #else - return try autoreleasepool { - try execute() - } - #endif -} - -/// `EventLoop` implementation that uses a `Selector` to get notified once there is more I/O or tasks to process. -/// The whole processing of I/O and tasks is done by a `NIOThread` that is tied to the `SelectableEventLoop`. This `NIOThread` -/// is guaranteed to never change! -@usableFromInline -internal final class SelectableEventLoop: EventLoop { - /// The different state in the lifecycle of an `EventLoop` seen from _outside_ the `EventLoop`. - private enum ExternalState { - /// `EventLoop` is open and so can process more work. - case open - /// `EventLoop` is currently in the process of closing. - case closing - /// `EventLoop` is closed. - case closed - /// `EventLoop` is closed and is currently trying to reclaim resources (such as the EventLoop thread). - case reclaimingResources - /// `EventLoop` is closed and all the resources (such as the EventLoop thread) have been reclaimed. - case resourcesReclaimed - } - - /// The different state in the lifecycle of an `EventLoop` seen from _inside_ the `EventLoop`. - private enum InternalState { - case runningAndAcceptingNewRegistrations - case runningButNotAcceptingNewRegistrations - case noLongerRunning - } - - private let selector: NIO.Selector - private let thread: NIOThread - private var scheduledTasks = PriorityQueue(ascending: true) - private var tasksCopy = ContiguousArray<() -> Void>() - - private let tasksLock = Lock() - private let _externalStateLock = Lock() - private var externalStateLock: Lock { - // The assert is here to check that we never try to read the external state on the EventLoop unless we're - // shutting down. - assert(!self.inEventLoop || self.internalState != .runningAndAcceptingNewRegistrations, - "lifecycle lock taken whilst up and running and in EventLoop") - return self._externalStateLock - } - private var internalState: InternalState = .runningAndAcceptingNewRegistrations // protected by the EventLoop thread - private var externalState: ExternalState = .open // protected by externalStateLock - - private let _iovecs: UnsafeMutablePointer - private let _storageRefs: UnsafeMutablePointer> - - let iovecs: UnsafeMutableBufferPointer - let storageRefs: UnsafeMutableBufferPointer> - - // Used for gathering UDP writes. - private let _msgs: UnsafeMutablePointer - private let _addresses: UnsafeMutablePointer - let msgs: UnsafeMutableBufferPointer - let addresses: UnsafeMutableBufferPointer - - /// Creates a new `SelectableEventLoop` instance that is tied to the given `pthread_t`. - - private let promiseCreationStoreLock = Lock() - private var _promiseCreationStore: [ObjectIdentifier: (file: StaticString, line: UInt)] = [:] - - @usableFromInline - internal func promiseCreationStoreAdd(future: EventLoopFuture, file: StaticString, line: UInt) { - precondition(_isDebugAssertConfiguration()) - self.promiseCreationStoreLock.withLock { - self._promiseCreationStore[ObjectIdentifier(future)] = (file: file, line: line) - } - } - - internal func promiseCreationStoreRemove(future: EventLoopFuture) -> (file: StaticString, line: UInt) { - precondition(_isDebugAssertConfiguration()) - return self.promiseCreationStoreLock.withLock { - self._promiseCreationStore.removeValue(forKey: ObjectIdentifier(future))! - } - } - - public init(thread: NIOThread) throws { - self.selector = try NIO.Selector() - self.thread = thread - self._iovecs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors) - self._storageRefs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors) - self.iovecs = UnsafeMutableBufferPointer(start: self._iovecs, count: Socket.writevLimitIOVectors) - self.storageRefs = UnsafeMutableBufferPointer(start: self._storageRefs, count: Socket.writevLimitIOVectors) - self._msgs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors) - self._addresses = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors) - self.msgs = UnsafeMutableBufferPointer(start: _msgs, count: Socket.writevLimitIOVectors) - self.addresses = UnsafeMutableBufferPointer(start: _addresses, count: Socket.writevLimitIOVectors) - // We will process 4096 tasks per while loop. - self.tasksCopy.reserveCapacity(4096) - } - - deinit { - assert(self.internalState == .noLongerRunning, - "illegal internal state on deinit: \(self.internalState)") - assert(self.externalState == .resourcesReclaimed, - "illegal external state on shutdown: \(self.externalState)") - _iovecs.deallocate() - _storageRefs.deallocate() - _msgs.deallocate() - _addresses.deallocate() - } - - /// Provide a valid `ClientBootstrap` to setup this `SelectableEventLoop` with a `SocketChannel`. - internal func makeTCPClientBootstrap() -> NIOTCPClientBootstrap { - return ClientBootstrap(group: self) - } - - /// Is this `SelectableEventLoop` still open (ie. not shutting down or shut down) - internal var isOpen: Bool { - self.assertInEventLoop() - switch self.internalState { - case .noLongerRunning, .runningButNotAcceptingNewRegistrations: - return false - case .runningAndAcceptingNewRegistrations: - return true - } - } - - /// Register the given `SelectableChannel` with this `SelectableEventLoop`. After this point all I/O for the `SelectableChannel` will be processed by this `SelectableEventLoop` until it - /// is deregistered by calling `deregister`. - public func register(channel: C) throws { - self.assertInEventLoop() - - // Don't allow registration when we're closed. - guard self.isOpen else { - throw EventLoopError.shutdown - } - - try channel.register(selector: self.selector, interested: channel.interestedEvent) - } - - /// Deregister the given `SelectableChannel` from this `SelectableEventLoop`. - public func deregister(channel: C, mode: CloseMode = .all) throws { - self.assertInEventLoop() - guard self.isOpen else { - // It's possible the EventLoop was closed before we were able to call deregister, so just return in this case as there is no harm. - return - } - - try channel.deregister(selector: self.selector, mode: mode) - } - - /// Register the given `SelectableChannel` with this `SelectableEventLoop`. This should be done whenever `channel.interestedEvents` has changed and it should be taken into account when - /// waiting for new I/O for the given `SelectableChannel`. - public func reregister(channel: C) throws { - self.assertInEventLoop() - - try channel.reregister(selector: self.selector, interested: channel.interestedEvent) - } - - /// - see: `EventLoop.inEventLoop` - public var inEventLoop: Bool { - return thread.isCurrent - } - - /// - see: `EventLoop.scheduleTask(deadline:_:)` - public func scheduleTask(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled { - let promise: EventLoopPromise = makePromise() - let task = ScheduledTask({ - do { - promise.succeed(try task()) - } catch let err { - promise.fail(err) - } - }, { error in - promise.fail(error) - }, deadline) - - let scheduled = Scheduled(promise: promise, cancellationTask: { - self.tasksLock.withLockVoid { - self.scheduledTasks.remove(task) - } - self.wakeupSelector() - }) - - schedule0(task) - return scheduled - } - - /// - see: `EventLoop.scheduleTask(in:_:)` - public func scheduleTask(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled { - return scheduleTask(deadline: .now() + `in`, task) - } - - // - see: `EventLoop.execute` - public func execute(_ task: @escaping () -> Void) { - schedule0(ScheduledTask(task, { error in - // do nothing - }, .now())) - } - - /// Add the `ScheduledTask` to be executed. - private func schedule0(_ task: ScheduledTask) { - tasksLock.withLockVoid { - scheduledTasks.push(task) - } - wakeupSelector() - } - - /// Wake the `Selector` which means `Selector.whenReady(...)` will unblock. - private func wakeupSelector() { - do { - try selector.wakeup() - } catch let err { - fatalError("Error during Selector.wakeup(): \(err)") - } - } - - /// Handle the given `SelectorEventSet` for the `SelectableChannel`. - internal final func handleEvent(_ ev: SelectorEventSet, channel: C) { - guard channel.isOpen else { - return - } - - // process resets first as they'll just cause the writes to fail anyway. - if ev.contains(.reset) { - channel.reset() - } else { - if ev.contains(.writeEOF) { - channel.writeEOF() - - guard channel.isOpen else { - return - } - } else if ev.contains(.write) { - channel.writable() - - guard channel.isOpen else { - return - } - } - - if ev.contains(.readEOF) { - channel.readEOF() - } else if ev.contains(.read) { - channel.readable() - } - } - } - - private func currentSelectorStrategy(nextReadyTask: ScheduledTask?) -> SelectorStrategy { - guard let sched = nextReadyTask else { - // No tasks to handle so just block. If any tasks were added in the meantime wakeup(...) was called and so this - // will directly unblock. - return .block - } - - let nextReady = sched.readyIn(.now()) - if nextReady <= .nanoseconds(0) { - // Something is ready to be processed just do a non-blocking select of events. - return .now - } else { - return .blockUntilTimeout(nextReady) - } - } - - /// Start processing I/O and tasks for this `SelectableEventLoop`. This method will continue running (and so block) until the `SelectableEventLoop` is closed. - public func run() throws { - self.preconditionInEventLoop() - defer { - var scheduledTasksCopy = ContiguousArray() - tasksLock.withLockVoid { - // reserve the correct capacity so we don't need to realloc later on. - scheduledTasksCopy.reserveCapacity(scheduledTasks.count) - while let sched = scheduledTasks.pop() { - scheduledTasksCopy.append(sched) - } - } - - // Fail all the scheduled tasks. - for task in scheduledTasksCopy { - task.fail(EventLoopError.shutdown) - } - } - var nextReadyTask: ScheduledTask? = nil - while self.internalState != .noLongerRunning { - // Block until there are events to handle or the selector was woken up - /* for macOS: in case any calls we make to Foundation put objects into an autoreleasepool */ - try withAutoReleasePool { - try selector.whenReady(strategy: currentSelectorStrategy(nextReadyTask: nextReadyTask)) { ev in - switch ev.registration { - case .serverSocketChannel(let chan, _): - self.handleEvent(ev.io, channel: chan) - case .socketChannel(let chan, _): - self.handleEvent(ev.io, channel: chan) - case .datagramChannel(let chan, _): - self.handleEvent(ev.io, channel: chan) - case .pipeChannel(let chan, let direction, _): - var ev = ev - if ev.io.contains(.reset) { - // .reset needs special treatment here because we're dealing with two separate pipes instead - // of one socket. So we turn .reset input .readEOF/.writeEOF. - ev.io.subtract([.reset]) - ev.io.formUnion([direction == .input ? .readEOF : .writeEOF]) - } - self.handleEvent(ev.io, channel: chan) - } - } - } - - // We need to ensure we process all tasks, even if a task added another task again - while true { - // TODO: Better locking - tasksLock.withLockVoid { - if !scheduledTasks.isEmpty { - // We only fetch the time one time as this may be expensive and is generally good enough as if we miss anything we will just do a non-blocking select again anyway. - let now: NIODeadline = .now() - - // Make a copy of the tasks so we can execute these while not holding the lock anymore - while tasksCopy.count < tasksCopy.capacity, let task = scheduledTasks.peek() { - if task.readyIn(now) <= .nanoseconds(0) { - scheduledTasks.pop() - tasksCopy.append(task.task) - } else { - nextReadyTask = task - break - } - } - } else { - // Reset nextReadyTask to nil which means we will do a blocking select. - nextReadyTask = nil - } - } - - // all pending tasks are set to occur in the future, so we can stop looping. - if tasksCopy.isEmpty { - break - } - - // Execute all the tasks that were summited - for task in tasksCopy { - /* for macOS: in case any calls we make to Foundation put objects into an autoreleasepool */ - withAutoReleasePool { - task() - } - } - // Drop everything (but keep the capacity) so we can fill it again on the next iteration. - tasksCopy.removeAll(keepingCapacity: true) - } - } - - // This EventLoop was closed so also close the underlying selector. - try self.selector.close() - } - - internal func initiateClose(queue: DispatchQueue, completionHandler: @escaping (Result) -> Void) { - func doClose() { - self.assertInEventLoop() - // There should only ever be one call into this function so we need to be up and running, ... - assert(self.internalState == .runningAndAcceptingNewRegistrations) - self.internalState = .runningButNotAcceptingNewRegistrations - - self.externalStateLock.withLock { - // ... but before this call happened, the lifecycle state should have been changed on some other thread. - assert(self.externalState == .closing) - } - - self.selector.closeGently(eventLoop: self).whenComplete { result in - self.assertInEventLoop() - assert(self.internalState == .runningButNotAcceptingNewRegistrations) - self.internalState = .noLongerRunning - self.execute {} // force a new event loop tick, so the event loop definitely stops looping very soon. - self.externalStateLock.withLock { - assert(self.externalState == .closing) - self.externalState = .closed - } - queue.async { - completionHandler(result) - } - } - } - if self.inEventLoop { - queue.async { - self.initiateClose(queue: queue, completionHandler: completionHandler) - } - } else { - let goAhead = self.externalStateLock.withLock { () -> Bool in - if self.externalState == .open { - self.externalState = .closing - return true - } else { - return false - } - } - guard goAhead else { - queue.async { - completionHandler(Result.failure(EventLoopError.shutdown)) - } - return - } - self.execute { - doClose() - } - } - } - - internal func syncFinaliseClose() { - let goAhead = self.externalStateLock.withLock { () -> Bool in - switch self.externalState { - case .closed: - self.externalState = .reclaimingResources - return true - case .resourcesReclaimed, .reclaimingResources: - return false - default: - preconditionFailure("illegal lifecycle state in syncFinaliseClose: \(self.externalState)") - } - } - guard goAhead else { - return - } - self.thread.join() - self.externalStateLock.withLock { - precondition(self.externalState == .reclaimingResources) - self.externalState = .resourcesReclaimed - } - } - - @usableFromInline - func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) { - // This function is never called legally because the only possibly owner of an `SelectableEventLoop` is - // `MultiThreadedEventLoopGroup` which calls `closeGently`. - queue.async { - callback(EventLoopError.unsupportedOperation) - } - } -} - -extension SelectableEventLoop: CustomStringConvertible { - @usableFromInline - var description: String { - return self.tasksLock.withLock { - return "SelectableEventLoop { selector = \(self.selector), scheduledTasks = \(self.scheduledTasks.description) }" - } - } -} - - /// Provides an endless stream of `EventLoop`s to use. public protocol EventLoopGroup: class { /// Returns the next `EventLoop` to use. @@ -1393,22 +945,25 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { } } -private final class ScheduledTask { +@usableFromInline +internal final class ScheduledTask { let task: () -> Void private let failFn: (Error) ->() - private let readyTime: NIODeadline + @usableFromInline + internal let _readyTime: NIODeadline + @usableFromInline init(_ task: @escaping () -> Void, _ failFn: @escaping (Error) -> Void, _ time: NIODeadline) { self.task = task self.failFn = failFn - self.readyTime = time + self._readyTime = time } func readyIn(_ t: NIODeadline) -> TimeAmount { - if readyTime < t { + if _readyTime < t { return .nanoseconds(0) } - return readyTime - t + return _readyTime - t } func fail(_ error: Error) { @@ -1417,16 +972,19 @@ private final class ScheduledTask { } extension ScheduledTask: CustomStringConvertible { + @usableFromInline var description: String { - return "ScheduledTask(readyTime: \(self.readyTime))" + return "ScheduledTask(readyTime: \(self._readyTime))" } } extension ScheduledTask: Comparable { + @usableFromInline static func < (lhs: ScheduledTask, rhs: ScheduledTask) -> Bool { - return lhs.readyTime < rhs.readyTime + return lhs._readyTime < rhs._readyTime } + @usableFromInline static func == (lhs: ScheduledTask, rhs: ScheduledTask) -> Bool { return lhs === rhs } diff --git a/Sources/NIO/Heap.swift b/Sources/NIO/Heap.swift index aa6c66781..894cf8228 100644 --- a/Sources/NIO/Heap.swift +++ b/Sources/NIO/Heap.swift @@ -12,11 +12,13 @@ // //===----------------------------------------------------------------------===// +@usableFromInline internal enum HeapType { case maxHeap case minHeap - public func comparator(type: T.Type) -> (T, T) -> Bool { + @inlinable + internal func comparator(type: T.Type) -> (T, T) -> Bool { switch self { case .maxHeap: return (>) @@ -26,13 +28,17 @@ internal enum HeapType { } } -internal struct Heap { +@usableFromInline +internal struct Heap { + @usableFromInline internal let type: HeapType - internal private(set) var storage: ContiguousArray = [] - internal let comparator: (T, T) -> Bool + @usableFromInline + internal private(set) var storage: ContiguousArray = [] + internal let comparator: (Element, Element) -> Bool - public init(type: HeapType) { - self.comparator = type.comparator(type: T.self) + @usableFromInline + internal init(type: HeapType) { + self.comparator = type.comparator(type: Element.self) self.type = type } @@ -74,7 +80,7 @@ internal struct Heap { } // named `HEAP-INCREASE-KEY` in CRLS - private mutating func heapRootify(index: Int, key: T) { + private mutating func heapRootify(index: Int, key: Element) { var index = index if self.comparator(storage[index], key) { fatalError("New key must be closer to the root than current key") @@ -87,7 +93,8 @@ internal struct Heap { } } - public mutating func append(_ value: T) { + @usableFromInline + internal mutating func append(_ value: Element) { var i = self.storage.count self.storage.append(value) while i > 0 && self.comparator(self.storage[i], self.storage[self.parentIndex(i)]) { @@ -97,12 +104,14 @@ internal struct Heap { } @discardableResult - public mutating func removeRoot() -> T? { + @usableFromInline + internal mutating func removeRoot() -> Element? { return self.remove(index: 0) } @discardableResult - public mutating func remove(value: T) -> Bool { + @usableFromInline + internal mutating func remove(value: Element) -> Bool { if let idx = self.storage.firstIndex(of: value) { self.remove(index: idx) return true @@ -112,7 +121,7 @@ internal struct Heap { } @discardableResult - private mutating func remove(index: Int) -> T? { + private mutating func remove(index: Int) -> Element? { guard self.storage.count > 0 else { return nil } @@ -133,6 +142,7 @@ internal struct Heap { } extension Heap: CustomDebugStringConvertible { + @usableFromInline var debugDescription: String { guard self.storage.count > 0 else { return "" @@ -190,35 +200,35 @@ extension Heap: CustomDebugStringConvertible { } } -struct HeapIterator: IteratorProtocol { - typealias Element = T +@usableFromInline +struct HeapIterator: IteratorProtocol { + private var heap: Heap - private var heap: Heap - - init(heap: Heap) { + init(heap: Heap) { self.heap = heap } - mutating func next() -> T? { + @usableFromInline + mutating func next() -> Element? { return self.heap.removeRoot() } } extension Heap: Sequence { - typealias Element = T - var startIndex: Int { return self.storage.startIndex } var endIndex: Int { return self.storage.endIndex } + @usableFromInline var underestimatedCount: Int { return self.storage.count } - func makeIterator() -> HeapIterator { + @usableFromInline + func makeIterator() -> HeapIterator { return HeapIterator(heap: self) } - subscript(position: Int) -> T { + subscript(position: Int) -> Element { return self.storage[position] } diff --git a/Sources/NIO/PriorityQueue.swift b/Sources/NIO/PriorityQueue.swift index 94a383281..876131119 100644 --- a/Sources/NIO/PriorityQueue.swift +++ b/Sources/NIO/PriorityQueue.swift @@ -12,46 +12,56 @@ // //===----------------------------------------------------------------------===// +@usableFromInline internal struct PriorityQueue { - private var heap: Heap + @usableFromInline + internal var _heap: Heap - public init(ascending: Bool = false) { - self.heap = Heap(type: ascending ? .minHeap : .maxHeap) + internal init(ascending: Bool = false) { + self._heap = Heap(type: ascending ? .minHeap : .maxHeap) } - public mutating func remove(_ key: Element) { - self.heap.remove(value: key) + @inlinable + internal mutating func remove(_ key: Element) { + self._heap.remove(value: key) } - public mutating func push(_ key: Element) { - self.heap.append(key) + @inlinable + internal mutating func push(_ key: Element) { + self._heap.append(key) } - public func peek() -> Element? { - return self.heap.storage.first + @inlinable + internal func peek() -> Element? { + return self._heap.storage.first } - public var isEmpty: Bool { - return self.heap.storage.isEmpty + @inlinable + internal var isEmpty: Bool { + return self._heap.storage.isEmpty } + @inlinable @discardableResult - public mutating func pop() -> Element? { - return self.heap.removeRoot() + internal mutating func pop() -> Element? { + return self._heap.removeRoot() } - public mutating func clear() { - self.heap = Heap(type: self.heap.type) + @inlinable + internal mutating func clear() { + self._heap = Heap(type: self._heap.type) } } extension PriorityQueue: Equatable { + @usableFromInline internal static func ==(lhs: PriorityQueue, rhs: PriorityQueue) -> Bool { return lhs.count == rhs.count && lhs.elementsEqual(rhs) } } extension PriorityQueue: Sequence { + @usableFromInline struct Iterator: IteratorProtocol { private var queue: PriorityQueue @@ -64,6 +74,7 @@ extension PriorityQueue: Sequence { } } + @usableFromInline func makeIterator() -> Iterator { return Iterator(queue: self) } @@ -71,11 +82,12 @@ extension PriorityQueue: Sequence { extension PriorityQueue { var count: Int { - return self.heap.count + return self._heap.count } } extension PriorityQueue: CustomStringConvertible { + @usableFromInline var description: String { return "PriorityQueue(count: \(self.underestimatedCount)): \(Array(self))" } diff --git a/Sources/NIO/SelectableEventLoop.swift b/Sources/NIO/SelectableEventLoop.swift new file mode 100644 index 000000000..0decf54e6 --- /dev/null +++ b/Sources/NIO/SelectableEventLoop.swift @@ -0,0 +1,472 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2019 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 Dispatch +import NIOConcurrencyHelpers + +/// Execute the given closure and ensure we release all auto pools if needed. +@inlinable +internal func withAutoReleasePool(_ execute: () throws -> T) rethrows -> T { + #if os(Linux) + return try execute() + #else + return try autoreleasepool { + try execute() + } + #endif +} + +/// `EventLoop` implementation that uses a `Selector` to get notified once there is more I/O or tasks to process. +/// The whole processing of I/O and tasks is done by a `NIOThread` that is tied to the `SelectableEventLoop`. This `NIOThread` +/// is guaranteed to never change! +@usableFromInline +internal final class SelectableEventLoop: EventLoop { + /// The different state in the lifecycle of an `EventLoop` seen from _outside_ the `EventLoop`. + private enum ExternalState { + /// `EventLoop` is open and so can process more work. + case open + /// `EventLoop` is currently in the process of closing. + case closing + /// `EventLoop` is closed. + case closed + /// `EventLoop` is closed and is currently trying to reclaim resources (such as the EventLoop thread). + case reclaimingResources + /// `EventLoop` is closed and all the resources (such as the EventLoop thread) have been reclaimed. + case resourcesReclaimed + } + + /// The different state in the lifecycle of an `EventLoop` seen from _inside_ the `EventLoop`. + private enum InternalState { + case runningAndAcceptingNewRegistrations + case runningButNotAcceptingNewRegistrations + case noLongerRunning + } + + private let selector: NIO.Selector + private let thread: NIOThread + @usableFromInline + internal var _scheduledTasks = PriorityQueue(ascending: true) + private var tasksCopy = ContiguousArray<() -> Void>() + + @usableFromInline + internal let _tasksLock = Lock() + private let _externalStateLock = Lock() + private var externalStateLock: Lock { + // The assert is here to check that we never try to read the external state on the EventLoop unless we're + // shutting down. + assert(!self.inEventLoop || self.internalState != .runningAndAcceptingNewRegistrations, + "lifecycle lock taken whilst up and running and in EventLoop") + return self._externalStateLock + } + private var internalState: InternalState = .runningAndAcceptingNewRegistrations // protected by the EventLoop thread + private var externalState: ExternalState = .open // protected by externalStateLock + + private let _iovecs: UnsafeMutablePointer + private let _storageRefs: UnsafeMutablePointer> + + let iovecs: UnsafeMutableBufferPointer + let storageRefs: UnsafeMutableBufferPointer> + + // Used for gathering UDP writes. + private let _msgs: UnsafeMutablePointer + private let _addresses: UnsafeMutablePointer + let msgs: UnsafeMutableBufferPointer + let addresses: UnsafeMutableBufferPointer + + /// Creates a new `SelectableEventLoop` instance that is tied to the given `pthread_t`. + + private let promiseCreationStoreLock = Lock() + private var _promiseCreationStore: [ObjectIdentifier: (file: StaticString, line: UInt)] = [:] + + @usableFromInline + internal func promiseCreationStoreAdd(future: EventLoopFuture, file: StaticString, line: UInt) { + precondition(_isDebugAssertConfiguration()) + self.promiseCreationStoreLock.withLock { + self._promiseCreationStore[ObjectIdentifier(future)] = (file: file, line: line) + } + } + + internal func promiseCreationStoreRemove(future: EventLoopFuture) -> (file: StaticString, line: UInt) { + precondition(_isDebugAssertConfiguration()) + return self.promiseCreationStoreLock.withLock { + self._promiseCreationStore.removeValue(forKey: ObjectIdentifier(future))! + } + } + + internal init(thread: NIOThread) throws { + self.selector = try NIO.Selector() + self.thread = thread + self._iovecs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors) + self._storageRefs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors) + self.iovecs = UnsafeMutableBufferPointer(start: self._iovecs, count: Socket.writevLimitIOVectors) + self.storageRefs = UnsafeMutableBufferPointer(start: self._storageRefs, count: Socket.writevLimitIOVectors) + self._msgs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors) + self._addresses = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors) + self.msgs = UnsafeMutableBufferPointer(start: _msgs, count: Socket.writevLimitIOVectors) + self.addresses = UnsafeMutableBufferPointer(start: _addresses, count: Socket.writevLimitIOVectors) + // We will process 4096 tasks per while loop. + self.tasksCopy.reserveCapacity(4096) + } + + deinit { + assert(self.internalState == .noLongerRunning, + "illegal internal state on deinit: \(self.internalState)") + assert(self.externalState == .resourcesReclaimed, + "illegal external state on shutdown: \(self.externalState)") + _iovecs.deallocate() + _storageRefs.deallocate() + _msgs.deallocate() + _addresses.deallocate() + } + + /// Provide a valid `ClientBootstrap` to setup this `SelectableEventLoop` with a `SocketChannel`. + internal func makeTCPClientBootstrap() -> NIOTCPClientBootstrap { + return ClientBootstrap(group: self) + } + + /// Is this `SelectableEventLoop` still open (ie. not shutting down or shut down) + internal var isOpen: Bool { + self.assertInEventLoop() + switch self.internalState { + case .noLongerRunning, .runningButNotAcceptingNewRegistrations: + return false + case .runningAndAcceptingNewRegistrations: + return true + } + } + + /// Register the given `SelectableChannel` with this `SelectableEventLoop`. After this point all I/O for the `SelectableChannel` will be processed by this `SelectableEventLoop` until it + /// is deregistered by calling `deregister`. + internal func register(channel: C) throws { + self.assertInEventLoop() + + // Don't allow registration when we're closed. + guard self.isOpen else { + throw EventLoopError.shutdown + } + + try channel.register(selector: self.selector, interested: channel.interestedEvent) + } + + /// Deregister the given `SelectableChannel` from this `SelectableEventLoop`. + internal func deregister(channel: C, mode: CloseMode = .all) throws { + self.assertInEventLoop() + guard self.isOpen else { + // It's possible the EventLoop was closed before we were able to call deregister, so just return in this case as there is no harm. + return + } + + try channel.deregister(selector: self.selector, mode: mode) + } + + /// Register the given `SelectableChannel` with this `SelectableEventLoop`. This should be done whenever `channel.interestedEvents` has changed and it should be taken into account when + /// waiting for new I/O for the given `SelectableChannel`. + internal func reregister(channel: C) throws { + self.assertInEventLoop() + + try channel.reregister(selector: self.selector, interested: channel.interestedEvent) + } + + /// - see: `EventLoop.inEventLoop` + @usableFromInline + internal var inEventLoop: Bool { + return thread.isCurrent + } + + /// - see: `EventLoop.scheduleTask(deadline:_:)` + @inlinable + internal func scheduleTask(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled { + let promise: EventLoopPromise = self.makePromise() + let task = ScheduledTask({ + do { + promise.succeed(try task()) + } catch let err { + promise.fail(err) + } + }, { error in + promise.fail(error) + }, deadline) + + let scheduled = Scheduled(promise: promise, cancellationTask: { + self._tasksLock.withLockVoid { + self._scheduledTasks.remove(task) + } + self._wakeupSelector() + }) + + self._schedule0(task) + return scheduled + } + + /// - see: `EventLoop.scheduleTask(in:_:)` + @inlinable + internal func scheduleTask(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled { + return scheduleTask(deadline: .now() + `in`, task) + } + + // - see: `EventLoop.execute` + @inlinable + internal func execute(_ task: @escaping () -> Void) { + self._schedule0(ScheduledTask(task, { error in + // do nothing + }, .now())) + } + + /// Add the `ScheduledTask` to be executed. + @usableFromInline + internal func _schedule0(_ task: ScheduledTask) { + self._tasksLock.withLockVoid { + self._scheduledTasks.push(task) + } + self._wakeupSelector() + } + + /// Wake the `Selector` which means `Selector.whenReady(...)` will unblock. + @usableFromInline + internal func _wakeupSelector() { + do { + try selector.wakeup() + } catch let err { + fatalError("Error during Selector.wakeup(): \(err)") + } + } + + /// Handle the given `SelectorEventSet` for the `SelectableChannel`. + internal final func handleEvent(_ ev: SelectorEventSet, channel: C) { + guard channel.isOpen else { + return + } + + // process resets first as they'll just cause the writes to fail anyway. + if ev.contains(.reset) { + channel.reset() + } else { + if ev.contains(.writeEOF) { + channel.writeEOF() + + guard channel.isOpen else { + return + } + } else if ev.contains(.write) { + channel.writable() + + guard channel.isOpen else { + return + } + } + + if ev.contains(.readEOF) { + channel.readEOF() + } else if ev.contains(.read) { + channel.readable() + } + } + } + + private func currentSelectorStrategy(nextReadyTask: ScheduledTask?) -> SelectorStrategy { + guard let sched = nextReadyTask else { + // No tasks to handle so just block. If any tasks were added in the meantime wakeup(...) was called and so this + // will directly unblock. + return .block + } + + let nextReady = sched.readyIn(.now()) + if nextReady <= .nanoseconds(0) { + // Something is ready to be processed just do a non-blocking select of events. + return .now + } else { + return .blockUntilTimeout(nextReady) + } + } + + /// Start processing I/O and tasks for this `SelectableEventLoop`. This method will continue running (and so block) until the `SelectableEventLoop` is closed. + internal func run() throws { + self.preconditionInEventLoop() + defer { + var scheduledTasksCopy = ContiguousArray() + _tasksLock.withLockVoid { + // reserve the correct capacity so we don't need to realloc later on. + scheduledTasksCopy.reserveCapacity(_scheduledTasks.count) + while let sched = _scheduledTasks.pop() { + scheduledTasksCopy.append(sched) + } + } + + // Fail all the scheduled tasks. + for task in scheduledTasksCopy { + task.fail(EventLoopError.shutdown) + } + } + var nextReadyTask: ScheduledTask? = nil + while self.internalState != .noLongerRunning { + // Block until there are events to handle or the selector was woken up + /* for macOS: in case any calls we make to Foundation put objects into an autoreleasepool */ + try withAutoReleasePool { + try selector.whenReady(strategy: currentSelectorStrategy(nextReadyTask: nextReadyTask)) { ev in + switch ev.registration { + case .serverSocketChannel(let chan, _): + self.handleEvent(ev.io, channel: chan) + case .socketChannel(let chan, _): + self.handleEvent(ev.io, channel: chan) + case .datagramChannel(let chan, _): + self.handleEvent(ev.io, channel: chan) + case .pipeChannel(let chan, let direction, _): + var ev = ev + if ev.io.contains(.reset) { + // .reset needs special treatment here because we're dealing with two separate pipes instead + // of one socket. So we turn .reset input .readEOF/.writeEOF. + ev.io.subtract([.reset]) + ev.io.formUnion([direction == .input ? .readEOF : .writeEOF]) + } + self.handleEvent(ev.io, channel: chan) + } + } + } + + // We need to ensure we process all tasks, even if a task added another task again + while true { + // TODO: Better locking + _tasksLock.withLockVoid { + if !_scheduledTasks.isEmpty { + // We only fetch the time one time as this may be expensive and is generally good enough as if we miss anything we will just do a non-blocking select again anyway. + let now: NIODeadline = .now() + + // Make a copy of the tasks so we can execute these while not holding the lock anymore + while tasksCopy.count < tasksCopy.capacity, let task = _scheduledTasks.peek() { + if task.readyIn(now) <= .nanoseconds(0) { + _scheduledTasks.pop() + tasksCopy.append(task.task) + } else { + nextReadyTask = task + break + } + } + } else { + // Reset nextReadyTask to nil which means we will do a blocking select. + nextReadyTask = nil + } + } + + // all pending tasks are set to occur in the future, so we can stop looping. + if tasksCopy.isEmpty { + break + } + + // Execute all the tasks that were summited + for task in tasksCopy { + /* for macOS: in case any calls we make to Foundation put objects into an autoreleasepool */ + withAutoReleasePool { + task() + } + } + // Drop everything (but keep the capacity) so we can fill it again on the next iteration. + tasksCopy.removeAll(keepingCapacity: true) + } + } + + // This EventLoop was closed so also close the underlying selector. + try self.selector.close() + } + + internal func initiateClose(queue: DispatchQueue, completionHandler: @escaping (Result) -> Void) { + func doClose() { + self.assertInEventLoop() + // There should only ever be one call into this function so we need to be up and running, ... + assert(self.internalState == .runningAndAcceptingNewRegistrations) + self.internalState = .runningButNotAcceptingNewRegistrations + + self.externalStateLock.withLock { + // ... but before this call happened, the lifecycle state should have been changed on some other thread. + assert(self.externalState == .closing) + } + + self.selector.closeGently(eventLoop: self).whenComplete { result in + self.assertInEventLoop() + assert(self.internalState == .runningButNotAcceptingNewRegistrations) + self.internalState = .noLongerRunning + self.execute {} // force a new event loop tick, so the event loop definitely stops looping very soon. + self.externalStateLock.withLock { + assert(self.externalState == .closing) + self.externalState = .closed + } + queue.async { + completionHandler(result) + } + } + } + if self.inEventLoop { + queue.async { + self.initiateClose(queue: queue, completionHandler: completionHandler) + } + } else { + let goAhead = self.externalStateLock.withLock { () -> Bool in + if self.externalState == .open { + self.externalState = .closing + return true + } else { + return false + } + } + guard goAhead else { + queue.async { + completionHandler(Result.failure(EventLoopError.shutdown)) + } + return + } + self.execute { + doClose() + } + } + } + + internal func syncFinaliseClose() { + let goAhead = self.externalStateLock.withLock { () -> Bool in + switch self.externalState { + case .closed: + self.externalState = .reclaimingResources + return true + case .resourcesReclaimed, .reclaimingResources: + return false + default: + preconditionFailure("illegal lifecycle state in syncFinaliseClose: \(self.externalState)") + } + } + guard goAhead else { + return + } + self.thread.join() + self.externalStateLock.withLock { + precondition(self.externalState == .reclaimingResources) + self.externalState = .resourcesReclaimed + } + } + + @usableFromInline + func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) { + // This function is never called legally because the only possibly owner of an `SelectableEventLoop` is + // `MultiThreadedEventLoopGroup` which calls `closeGently`. + queue.async { + callback(EventLoopError.unsupportedOperation) + } + } +} + +extension SelectableEventLoop: CustomStringConvertible { + @usableFromInline + var description: String { + return self._tasksLock.withLock { + return "SelectableEventLoop { selector = \(self.selector), scheduledTasks = \(self._scheduledTasks.description) }" + } + } +}