From 58d0883b2daf2ea81df6ebca650a1098d4e2d492 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Mon, 12 Jun 2017 13:44:10 +0200 Subject: [PATCH] Fork Future-Swift and adjust it to ensure callback execution is always done on the EventLoop. - Also remove all methods that use Dispatch for now as we not need these - Ensure we will detect if the user calls a blocking method while on the EventLoop and crash to guard against deadlock --- Sources/NIO/Bootstrap.swift | 1 - Sources/NIO/Channel.swift | 20 +- Sources/NIO/ChannelHandler.swift | 1 - Sources/NIO/ChannelHandlers.swift | 1 - Sources/NIO/ChannelOutboundInvoker.swift | 1 - Sources/NIO/ChannelPipeline.swift | 7 +- Sources/NIO/Concurrency.swift | 15 - Sources/NIO/Embedded.swift | 25 +- Sources/NIO/EventLoop.swift | 8 +- Sources/NIO/Future.swift | 830 ++++++++--------------- Sources/NIO/Futures.swift | 25 - Sources/NIOEchoServer/main.swift | 1 - Tests/NIOTests/ChannelWriteTests.swift | 9 +- 13 files changed, 322 insertions(+), 622 deletions(-) delete mode 100644 Sources/NIO/Concurrency.swift delete mode 100644 Sources/NIO/Futures.swift diff --git a/Sources/NIO/Bootstrap.swift b/Sources/NIO/Bootstrap.swift index 4fbc173c3..2165d0aa3 100644 --- a/Sources/NIO/Bootstrap.swift +++ b/Sources/NIO/Bootstrap.swift @@ -14,7 +14,6 @@ import Foundation import Sockets -import Future public final class ServerBootstrap { diff --git a/Sources/NIO/Channel.swift b/Sources/NIO/Channel.swift index 936c290c8..36593f0cb 100644 --- a/Sources/NIO/Channel.swift +++ b/Sources/NIO/Channel.swift @@ -13,7 +13,6 @@ //===----------------------------------------------------------------------===// import Foundation -import Future import Sockets #if os(Linux) @@ -553,12 +552,6 @@ public protocol ChannelCore : class{ var eventLoop: EventLoop { get } } -extension ChannelCore { - public func close0(promise: Promise = Promise()) { - close0(promise: promise, error: ChannelError.closed) - } -} - /* All methods exposed by Channel are thread-safe */ @@ -914,7 +907,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { } } - public final func close0(promise: Promise = Promise(), error: Error = ChannelError.closed) { + public final func close0(promise: Promise, error: Error) { assert(eventLoop.inEventLoop) guard !closed else { @@ -1037,8 +1030,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { // Call before triggering the close of the Channel. pipeline.fireChannelReadComplete0() - - close0(error: err) + close0(promise: eventLoop.newPromise(type: Void.self), error: err) return @@ -1094,7 +1086,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { try selectableEventLoop.deregister(channel: self) } catch let err { pipeline.fireErrorCaught0(error: err) - close0(error: err) + close0(promise: eventLoop.newPromise(type: Void.self), error: err) } } @@ -1112,7 +1104,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { try selectableEventLoop.reregister(channel: self) } catch let err { pipeline.fireErrorCaught0(error: err) - close0(error: err) + close0(promise: eventLoop.newPromise(type: Void.self), error: err) } } @@ -1128,7 +1120,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { return true } catch let err { pipeline.fireErrorCaught0(error: err) - close0(error: err) + close0(promise: eventLoop.newPromise(type: Void.self), error: err) return false } } @@ -1152,7 +1144,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { } } catch let err { - close0(error: err) + close0(promise: eventLoop.newPromise(type: Void.self), error: err) // we handled all writes return true diff --git a/Sources/NIO/ChannelHandler.swift b/Sources/NIO/ChannelHandler.swift index 27031ce46..3a1228e8d 100644 --- a/Sources/NIO/ChannelHandler.swift +++ b/Sources/NIO/ChannelHandler.swift @@ -13,7 +13,6 @@ //===----------------------------------------------------------------------===// import Foundation -import Future import Sockets public protocol ChannelHandler : class { diff --git a/Sources/NIO/ChannelHandlers.swift b/Sources/NIO/ChannelHandlers.swift index fcc33f3c6..a7ed7fefa 100644 --- a/Sources/NIO/ChannelHandlers.swift +++ b/Sources/NIO/ChannelHandlers.swift @@ -16,7 +16,6 @@ // import Foundation -import Future /** ChannelHandler implementation which enforces back-pressure by stop reading from the remote-peer when it can not write back fast-enough and start reading again diff --git a/Sources/NIO/ChannelOutboundInvoker.swift b/Sources/NIO/ChannelOutboundInvoker.swift index c8b60ea33..aa397b41e 100644 --- a/Sources/NIO/ChannelOutboundInvoker.swift +++ b/Sources/NIO/ChannelOutboundInvoker.swift @@ -13,7 +13,6 @@ //===----------------------------------------------------------------------===// import Foundation -import Future import Sockets public protocol OutboundData { } diff --git a/Sources/NIO/ChannelPipeline.swift b/Sources/NIO/ChannelPipeline.swift index 7cff13aaa..eb6b8fe84 100644 --- a/Sources/NIO/ChannelPipeline.swift +++ b/Sources/NIO/ChannelPipeline.swift @@ -13,7 +13,6 @@ //===----------------------------------------------------------------------===// import Foundation -import Future import Sockets @@ -73,7 +72,7 @@ public final class ChannelPipeline : ChannelInboundInvoker { } public func remove(handler: ChannelHandler) -> Future { - let promise = Promise() + let promise = eventLoop.newPromise(type: Bool.self) if eventLoop.inEventLoop { remove0(handler: handler, promise: promise) } else { @@ -112,7 +111,7 @@ public final class ChannelPipeline : ChannelInboundInvoker { } public func remove(name: String) -> Future { - let promise = Promise() + let promise = eventLoop.newPromise(type: Bool.self) if eventLoop.inEventLoop { remove0(name: name, promise: promise) } else { @@ -456,7 +455,7 @@ private final class HeadChannelHandler : ChannelHandler { } func close(ctx: ChannelHandlerContext, promise: Promise) { - ctx.channel!._unsafe.close0(promise: promise) + ctx.channel!._unsafe.close0(promise: promise, error: ChannelError.closed) } func read(ctx: ChannelHandlerContext) { diff --git a/Sources/NIO/Concurrency.swift b/Sources/NIO/Concurrency.swift deleted file mode 100644 index b3ddd4827..000000000 --- a/Sources/NIO/Concurrency.swift +++ /dev/null @@ -1,15 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftNIO open source project -// -// Copyright (c) 2017-2018 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 Foundation diff --git a/Sources/NIO/Embedded.swift b/Sources/NIO/Embedded.swift index 421007d24..17481e087 100644 --- a/Sources/NIO/Embedded.swift +++ b/Sources/NIO/Embedded.swift @@ -15,7 +15,6 @@ import Foundation import Dispatch import Sockets -import Future class EmbeddedEventLoop : EventLoop { @@ -26,6 +25,24 @@ class EmbeddedEventLoop : EventLoop { // Would be better to have this as a Queue var tasks: [() -> ()] = Array() + public func submit(task: @escaping () throws-> (T)) -> Future { + let promise = Promise(eventLoop: self, checkForPossibleDeadlock: false) + + execute(task: {() -> () in + do { + promise.succeed(result: try task()) + } catch let err { + promise.fail(error: err) + } + }) + + return promise.futureResult + } + + public func newPromise(type: T.Type) -> Promise { + return Promise(eventLoop: self, checkForPossibleDeadlock: false) + } + // We're not really running a loop here. Tasks aren't run until run() is called, // at which point we run everything that's been submitted. Anything newly submitted // either gets on that train if it's still moving or @@ -59,10 +76,14 @@ class EmbeddedEventLoop : EventLoop { class EmbeddedChannelCore : ChannelCore { var closed: Bool { return closePromise.futureResult.fulfilled } - var closePromise: Promise = Promise() var eventLoop: EventLoop = EmbeddedEventLoop() + var closePromise: Promise + init() { + closePromise = eventLoop.newPromise(type: Void.self) + } + deinit { closePromise.succeed(result: ()) } var outboundBuffer: [Any] = [] diff --git a/Sources/NIO/EventLoop.swift b/Sources/NIO/EventLoop.swift index 1651b9cf2..122df7c36 100644 --- a/Sources/NIO/EventLoop.swift +++ b/Sources/NIO/EventLoop.swift @@ -13,7 +13,6 @@ //===----------------------------------------------------------------------===// import Foundation -import Future import Sockets import ConcurrencyHelpers @@ -21,11 +20,14 @@ public protocol EventLoop: EventLoopGroup { var inEventLoop: Bool { get } func execute(task: @escaping () -> ()) func submit(task: @escaping () throws-> (T)) -> Future + func newPromise(type: T.Type) -> Promise + func newFailedFuture(type: T.Type, error: Error) -> Future + func newSucceedFuture(result: T) -> Future } extension EventLoop { public func submit(task: @escaping () throws-> (T)) -> Future { - let promise = Promise() + let promise = Promise(eventLoop: self, checkForPossibleDeadlock: true) execute(task: {() -> () in do { @@ -39,7 +41,7 @@ extension EventLoop { } public func newPromise(type: T.Type) -> Promise { - return Promise() + return Promise(eventLoop: self, checkForPossibleDeadlock: true) } public func newFailedFuture(type: T.Type, error: Error) -> Future { diff --git a/Sources/NIO/Future.swift b/Sources/NIO/Future.swift index 2957dcdc2..fb17168ab 100644 --- a/Sources/NIO/Future.swift +++ b/Sources/NIO/Future.swift @@ -13,18 +13,13 @@ //===----------------------------------------------------------------------===// import Foundation -import Dispatch -#if os(macOS) || os(tvOS) || os(iOS) -import Darwin -#endif -#if os(Linux) -import Glibc -#endif +import ConcurrencyHelpers + /** Private to avoid cluttering the public namespace. - -If/when a version of this is added to the Standard library, that should be used here. At that time, it may make sense to expose `resolve(FutureValue)`. -*/ + + If/when a version of this is added to the Standard library, that should be used here. At that time, it may make sense to expose `resolve(FutureValue)`. + */ private enum FutureValue { case success(T) case failure(Error) @@ -32,16 +27,16 @@ private enum FutureValue { } /** Internal list of callbacks. - -Most of these are closures that pull a value from one future, call a user callback, push the result into another, then return a list of callbacks from the target future that are now ready to be invoked. - -In particular, note that _run() here continues to obtain and execute lists of callbacks until it completes. This eliminates recursion when processing `then()` chains. -*/ + + Most of these are closures that pull a value from one future, call a user callback, push the result into another, then return a list of callbacks from the target future that are now ready to be invoked. + + In particular, note that _run() here continues to obtain and execute lists of callbacks until it completes. This eliminates recursion when processing `then()` chains. + */ private struct CallbackList: ExpressibleByArrayLiteral { typealias Element = () -> CallbackList var firstCallback: Element? var furtherCallbacks: [Element]? - + init() { firstCallback = nil furtherCallbacks = nil @@ -66,7 +61,7 @@ private struct CallbackList: ExpressibleByArrayLiteral { } } } - + private func allCallbacks() -> [Element] { switch (self.firstCallback, self.furtherCallbacks) { case (.none, _): @@ -77,7 +72,7 @@ private struct CallbackList: ExpressibleByArrayLiteral { return [first]+others } } - + func _run() { switch (self.firstCallback, self.furtherCallbacks) { case (.none, _): @@ -117,229 +112,164 @@ private struct CallbackList: ExpressibleByArrayLiteral { } } } - + } /** A promise to provide a result later. - -This is the provider API for Future. If you want to return an unfulfilled Future -- presumably because you are interfacing to some asynchronous service that will return a real result later, follow this pattern: - -``` -func someAsyncOperation(args) -> Future { - let promise = Promise() - someAsyncOperationWithACallback(args) { result -> () in - // when finished... - promise.succeed(result) - // if error... - promise.fail(result) - } - return promise.futureResult -} -``` - -Note that the future result is returned before the async process has provided a value. - -It's actually not very common to use this directly. Usually, you really want one of the following: - -* If you have a Future and want to do something else after it completes, use `.then()` -* If you just want to get a value back after running something on another thread, use `Future.async()` -* If you already have a value and need a Future<> object to plug into some other API, create an already-resolved object with `Future(result:)` -*/ + + This is the provider API for Future. If you want to return an unfulfilled Future -- presumably because you are interfacing to some asynchronous service that will return a real result later, follow this pattern: + + ``` + func someAsyncOperation(args) -> Future { + let promise = Promise() + someAsyncOperationWithACallback(args) { result -> () in + // when finished... + promise.succeed(result) + // if error... + promise.fail(result) + } + return promise.futureResult + } + ``` + + Note that the future result is returned before the async process has provided a value. + + It's actually not very common to use this directly. Usually, you really want one of the following: + + * If you have a Future and want to do something else after it completes, use `.then()` + * If you just want to get a value back after running something on another thread, use `Future.async()` + * If you already have a value and need a Future<> object to plug into some other API, create an already-resolved object with `Future(result:)` + */ public class Promise { - public let futureResult = Future() - - /** - Public initializer - */ - public init() {} - + public let futureResult: Future + /** - Deliver a successful result to the associated `Future` object. - */ + Public initializer + */ + init(eventLoop: EventLoop, checkForPossibleDeadlock: Bool) { + futureResult = Future(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock) + } + + /** + Deliver a successful result to the associated `Future` object. + */ public func succeed(result: T) { _resolve(value: .success(result)) } - + /** - Deliver an error to the associated `Future` object. - */ + Deliver an error to the associated `Future` object. + */ public func fail(error: Error) { _resolve(value: .failure(error)) } - + /** Internal only! */ fileprivate func _resolve(value: FutureValue) { // Set the value and then run all completed callbacks - _setValue(value: value)._run() + let list = _setValue(value: value) + if futureResult.eventLoop.inEventLoop { + list._run() + } else { + futureResult.eventLoop.execute { + list._run() + } + } } - + /** Internal only! */ fileprivate func _setValue(value: FutureValue) -> CallbackList { return futureResult._setValue(value: value) } - + deinit { - assert(futureResult.fulfilled, "leaking an unfulfilled Promise") + precondition(futureResult.fulfilled, "leaking an unfulfilled Promise") } } -fileprivate class ConditionLock { - private var _value: Int - fileprivate let mutexCond: UnsafeMutablePointer<(pthread_mutex_t, pthread_cond_t)> = UnsafeMutablePointer.allocate(capacity: 1) - - public init(value: Int) { - self._value = value - pthread_mutex_init(&mutexCond.pointee.0, nil) - pthread_cond_init(&mutexCond.pointee.1, nil) - } - - deinit { - mutexCond.deallocate(capacity: 1) - } - - public func lock() { - pthread_mutex_lock(&mutexCond.pointee.0) - } - - public func unlock() { - pthread_mutex_unlock(&mutexCond.pointee.0) - } - - public var value: Int { - lock() - defer { - unlock() - } - return self._value - } - - public func lock(whenValue wantedValue: Int) { - lock() - while true { - if self._value == wantedValue { - break - } - let err = pthread_cond_wait(&mutexCond.pointee.1, &mutexCond.pointee.0) - precondition(err == 0, "pthread_cond_wait error \(err)") - } - } - - public func lock(whenValue wantedValue: Int, timeoutSeconds: Double) -> Bool{ - let nsecPerSec: Double = 1000000000.0 - lock() - /* the timeout as a (seconds, nano seconds) pair */ - let timeout = (Int(timeoutSeconds), - Int((timeoutSeconds-Double(Int(timeoutSeconds))) * nsecPerSec)) - - var ts = timespec() - var tv = timeval() - gettimeofday(&tv, nil) - ts.tv_sec += tv.tv_sec + timeout.0 - ts.tv_nsec += Int(tv.tv_usec * 1000) + timeout.1 - - while true { - if self._value == wantedValue { - return true - } - switch pthread_cond_timedwait(&mutexCond.pointee.1, &mutexCond.pointee.0, &ts) { - case 0: - continue - case ETIMEDOUT: - unlock() - return false - case let e: - fatalError("caught error \(e) when calling pthread_cond_timedwait") - } - } - } - - public func unlock(withValue newValue: Int) { - self._value = newValue - unlock() - pthread_cond_signal(&mutexCond.pointee.1) - } -} /** Holder for a result that will be provided later. - -Functions that promise to do work asynchronously can return a Future. The recipient of such an object can then observe it to be notified when the operation completes. - -The provider of a `Future` can create and return a placeholder object before the actual result is available. For example: - -``` -func getNetworkData(args) -> Future { - let promise = Promise() - queue.async { - . . . do some work . . . - promise.succeed(response) - . . . if it fails, instead . . . - promise.fail(error) - } - return promise.futureResult -} -``` - -Note that this function returns immediately; the promise object will be given a value later on. This is also sometimes referred to as the "IOU Pattern". Similar structures occur in other programming languages, including Haskell's IO Monad, Scala's Future object, Python Deferred, and Javascript Promises. - -The above idiom is common enough that we've provided an `async()` method to encapsulate it. Note that with this wrapper, you simply return the desired response or `throw` an error; the wrapper will capture it and correctly propagate it to the Future that was returned earlier: - -``` -func getNetworkData(args) -> Future { - return Future.async(queue) { - . . . do some work . . . - return response // Return the NetworkResponse object - . . . if it fails . . . - throw error - } -} -``` - -If you receive a `Future` from another function, you have a number of options: The most common operation is to use `then()` to add a function that will be called with the eventual result. The `then()` method returns a new Future immediately that will receive the return value from your function. - -``` -let networkData = getNetworkData(args) - -// When network data is received, convert it -let processedResult: Future - = networkData.then { - (n: NetworkResponse) -> Processed in - ... parse network data .... - return processedResult - } -``` - -The function provided to `then()` can also return a new Future object. In this way, you can kick off another async operation at any time: - -``` -// When converted network data is available, -// begin the database operation. -let databaseResult: Future - = processedResult.then { - (p: Processed) -> Future in - return Future.async(queue) { - . . . perform DB operation . . . - return result - } - } -``` - -In essence, future chains created via `then()` provide a form of data-driven asynchronous programming that allows you to dynamically declare data dependencies for your various operations. - -Future chains created via `then()` are sufficient for most purposes. All of the registered functions will eventually run in order. If one of those functions throws an error, that error will bypass the remaining functions. You can use `thenIfError()` to handle and optionally recover from errors in the middle of a chain. - -At any point in the Future chain, you can use `whenSuccess()` or `whenFailure()` to add an observer callback that will be invoked with the result or error at that point. (Note: If you ever find yourself invoking `promise.succeed()` from inside a `whenSuccess()` callback, you probably should use `then()` instead.) - -Future objects are typically obtained by: -* Using `Future.async` or a similar wrapper function. -* Using `.then` on an existing future to create a new future for the next step in a series of operations. -* Initializing a Future that already has a value or an error - -TODO: Provide a tracing facility. It would be nice to be able to set '.debugTrace = true' on any Future or Promise and have every subsequent chained Future report the success result or failure error. That would simplify some debugging scenarios. -*/ + + Functions that promise to do work asynchronously can return a Future. The recipient of such an object can then observe it to be notified when the operation completes. + + The provider of a `Future` can create and return a placeholder object before the actual result is available. For example: + + ``` + func getNetworkData(args) -> Future { + let promise = Promise() + queue.async { + . . . do some work . . . + promise.succeed(response) + . . . if it fails, instead . . . + promise.fail(error) + } + return promise.futureResult + } + ``` + + Note that this function returns immediately; the promise object will be given a value later on. This is also sometimes referred to as the "IOU Pattern". Similar structures occur in other programming languages, including Haskell's IO Monad, Scala's Future object, Python Deferred, and Javascript Promises. + + The above idiom is common enough that we've provided an `async()` method to encapsulate it. Note that with this wrapper, you simply return the desired response or `throw` an error; the wrapper will capture it and correctly propagate it to the Future that was returned earlier: + + ``` + func getNetworkData(args) -> Future { + return Future.async(queue) { + . . . do some work . . . + return response // Return the NetworkResponse object + . . . if it fails . . . + throw error + } + } + ``` + + If you receive a `Future` from another function, you have a number of options: The most common operation is to use `then()` to add a function that will be called with the eventual result. The `then()` method returns a new Future immediately that will receive the return value from your function. + + ``` + let networkData = getNetworkData(args) + + // When network data is received, convert it + let processedResult: Future + = networkData.then { + (n: NetworkResponse) -> Processed in + ... parse network data .... + return processedResult + } + ``` + + The function provided to `then()` can also return a new Future object. In this way, you can kick off another async operation at any time: + + ``` + // When converted network data is available, + // begin the database operation. + let databaseResult: Future + = processedResult.then { + (p: Processed) -> Future in + return Future.async(queue) { + . . . perform DB operation . . . + return result + } + } + ``` + + In essence, future chains created via `then()` provide a form of data-driven asynchronous programming that allows you to dynamically declare data dependencies for your various operations. + + Future chains created via `then()` are sufficient for most purposes. All of the registered functions will eventually run in order. If one of those functions throws an error, that error will bypass the remaining functions. You can use `thenIfError()` to handle and optionally recover from errors in the middle of a chain. + + At any point in the Future chain, you can use `whenSuccess()` or `whenFailure()` to add an observer callback that will be invoked with the result or error at that point. (Note: If you ever find yourself invoking `promise.succeed()` from inside a `whenSuccess()` callback, you probably should use `then()` instead.) + + Future objects are typically obtained by: + * Using `Future.async` or a similar wrapper function. + * Using `.then` on an existing future to create a new future for the next step in a series of operations. + * Initializing a Future that already has a value or an error + + TODO: Provide a tracing facility. It would be nice to be able to set '.debugTrace = true' on any Future or Promise and have every subsequent chained Future report the success result or failure error. That would simplify some debugging scenarios. + */ public class Future: Hashable { fileprivate var value: FutureValue = .incomplete - + fileprivate let checkForPossibleDeadlock: Bool + public let eventLoop: EventLoop + public var result: T? { get { switch value { @@ -350,7 +280,7 @@ public class Future: Hashable { } } } - + public var error: Error? { get { switch value { @@ -361,35 +291,41 @@ public class Future: Hashable { } } } - + /// Callbacks that should be run when this Future<> gets a value. /// These callbacks may give values to other Futures; if that happens, they return any callbacks from those Futures so that we can run the entire chain from the top without recursing. fileprivate var callbacks: CallbackList = CallbackList() - + // Each instance gets a random hash value public lazy var hashValue = NSUUID().hashValue - + /// Becomes 1 when we have a value or an error - fileprivate let futureLock: ConditionLock - + fileprivate let futureLock: ConditionLock + public var fulfilled: Bool { return futureLock.value == 1 } - - fileprivate init() { + + fileprivate init(eventLoop: EventLoop, checkForPossibleDeadlock: Bool) { self.futureLock = ConditionLock(value: 0) + self.eventLoop = eventLoop + self.checkForPossibleDeadlock = checkForPossibleDeadlock } - + /// A Future that has already succeeded - public init(result: T) { + init(eventLoop: EventLoop, checkForPossibleDeadlock: Bool, result: T) { self.value = .success(result) self.futureLock = ConditionLock(value: 1) + self.eventLoop = eventLoop + self.checkForPossibleDeadlock = checkForPossibleDeadlock } - + /// A Future that has already failed - public init(error: Error) { + init(eventLoop: EventLoop, checkForPossibleDeadlock: Bool, error: Error) { self.value = .failure(error) self.futureLock = ConditionLock(value: 1) + self.eventLoop = eventLoop + self.checkForPossibleDeadlock = checkForPossibleDeadlock } } @@ -398,35 +334,35 @@ public func ==(lhs: Future, rhs: Future) -> Bool { } /** - 'then' implementations. This is really the key of the entire system. -*/ + 'then' implementations. This is really the key of the entire system. + */ public extension Future { /** - When the current `Future` is fulfilled, run the provided callback, which will provide a new `Future`. - - This allows you to dynamically dispatch new background tasks as phases in a longer series of processing steps. Note that you can use the results of the current `Future` when determining how to dispatch the next operation. - - This works well when you have APIs that already know how to return Futures. You can do something with the result of one and just return the next future: - - let d1 = networkRequest(args).future() - let d2 = d1.then { t -> Future in - . . . something with t . . . - return netWorkRequest(args) - } - d2.whenSuccess { u in - NSLog("Result of second request: \(u)") - } - - Technical trivia: `Future<>` is a monad, `then()` is the monadic bind operation. - - Note: In a sense, the `Future` is returned before it's created. - - - parameter callback: Function that will receive the value of this Future and return a new Future - - returns: A future that will receive the eventual value - */ - + When the current `Future` is fulfilled, run the provided callback, which will provide a new `Future`. + + This allows you to dynamically dispatch new background tasks as phases in a longer series of processing steps. Note that you can use the results of the current `Future` when determining how to dispatch the next operation. + + This works well when you have APIs that already know how to return Futures. You can do something with the result of one and just return the next future: + + let d1 = networkRequest(args).future() + let d2 = d1.then { t -> Future in + . . . something with t . . . + return netWorkRequest(args) + } + d2.whenSuccess { u in + NSLog("Result of second request: \(u)") + } + + Technical trivia: `Future<>` is a monad, `then()` is the monadic bind operation. + + Note: In a sense, the `Future` is returned before it's created. + + - parameter callback: Function that will receive the value of this Future and return a new Future + - returns: A future that will receive the eventual value + */ + public func then(callback: @escaping (T) throws -> Future) -> Future { - let next = Promise() + let next = Promise(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock) _whenComplete { switch self.value { case .success(let t): @@ -447,63 +383,54 @@ public extension Future { } return next.futureResult } - + /** Chainable transformation. - - ``` - let future1 = eventually() - let future2 = future1.then { T -> U in - ... stuff ... - return u - } - let future3 = future2.then { U -> V in - ... stuff ... - return v - } - - future3.whenSuccess { V in - ... handle final value ... - } - ``` - - If your callback throws an error, the resulting future will fail. - - Generally, a simple closure provided to `then()` should never block. If you need to do something time-consuming, your closure can schedule the operation on another queue and return another `Future<>` object instead. See `then(queue:callback:)` for a convenient way to do this. - */ + + ``` + let future1 = eventually() + let future2 = future1.then { T -> U in + ... stuff ... + return u + } + let future3 = future2.then { U -> V in + ... stuff ... + return v + } + + future3.whenSuccess { V in + ... handle final value ... + } + ``` + + If your callback throws an error, the resulting future will fail. + + Generally, a simple closure provided to `then()` should never block. If you need to do something time-consuming, your closure can schedule the operation on another queue and return another `Future<>` object instead. See `then(queue:callback:)` for a convenient way to do this. + */ + public func then(callback: @escaping (T) throws -> (U)) -> Future { - return then { return Future(result: try callback($0)) } - } - - - /** A variation of `then()` that runs the callback asynchronously on the provided queue. - */ - public func then(queue: DispatchQueue, callback: @escaping (T) throws -> U) -> Future { - return then { t -> Future in - return Future.async(queue: queue) { - return try callback(t) - } - } + return then { return Future(eventLoop: self.eventLoop, checkForPossibleDeadlock: self.checkForPossibleDeadlock, result: try callback($0)) } } + /** Recover from an error. - - This returns a new Future<> of the same type. If the original Future<> succeeds, so will the new one. But if the original Future<> fails, the callback will be executed with the error value. The callback can either: - * Throw an error, in which case the chained Future<> will fail with that error. The thrown error can be the same or different. - * Return a new result, in which case the chained Future<> will succeed with that value. - - Here is a simple example which simply converts any error into a default -1 value. Usually, of course, you would inspect the provided error and re-throw if the error was unexpected: - - ``` - let d: Future - let recover = d.thenIfError { error throws -> Int in - return -1 - } - ``` - - This supports the same overloads as `then()`, including allowing the callback to return a `Future`. - */ + + This returns a new Future<> of the same type. If the original Future<> succeeds, so will the new one. But if the original Future<> fails, the callback will be executed with the error value. The callback can either: + * Throw an error, in which case the chained Future<> will fail with that error. The thrown error can be the same or different. + * Return a new result, in which case the chained Future<> will succeed with that value. + + Here is a simple example which simply converts any error into a default -1 value. Usually, of course, you would inspect the provided error and re-throw if the error was unexpected: + + ``` + let d: Future + let recover = d.thenIfError { error throws -> Int in + return -1 + } + ``` + + This supports the same overloads as `then()`, including allowing the callback to return a `Future`. + */ public func thenIfError(callback: @escaping (Error) throws -> Future) -> Future { - let next = Promise() + let next = Promise(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock) _whenComplete { switch self.value { case .success(let t): @@ -521,21 +448,23 @@ public extension Future { assert(false) } return [] - } - return next.futureResult + } + return next.futureResult } - + public func thenIfError(callback: @escaping (Error) throws -> T) -> Future { - return thenIfError { return Future(result: try callback($0)) } + return thenIfError { return Future(eventLoop: self.eventLoop, checkForPossibleDeadlock: self.checkForPossibleDeadlock, result: try callback($0)) } } - + /** Block until either result or error is available. - - If the future already has a value, this will return immediately. If the future has failed, this will throw the error. - - In particular, note that this does behave correctly if you have callbacks registered to run on the same queue on which you call `wait()`. In that case, the `wait()` call will unblock as soon as the `Future` acquires a result, and the callbacks will be dispatched asynchronously to run at some later time. - */ + + If the future already has a value, this will return immediately. If the future has failed, this will throw the error. + + In particular, note that this does behave correctly if you have callbacks registered to run on the same queue on which you call `wait()`. In that case, the `wait()` call will unblock as soon as the `Future` acquires a result, and the callbacks will be dispatched asynchronously to run at some later time. + */ public func wait() throws -> T { + checkDeadlock() + futureLock.lock(whenValue: 1) // Wait for fulfillment futureLock.unlock() if let error = error { @@ -544,12 +473,14 @@ public extension Future { return result! } } - + /** Block until result or error becomes set, or until timeout. - - Returns a result if the future succeeds before the timeout, throws an error if it fails before the timeout. Otherwise, returns nil. - */ + + Returns a result if the future succeeds before the timeout, throws an error if it fails before the timeout. Otherwise, returns nil. + */ public func wait(timeoutSeconds: Double) throws -> T? { + checkDeadlock() + let succeeded = futureLock.lock(whenValue: 1, timeoutSeconds: timeoutSeconds) if succeeded { futureLock.unlock() @@ -559,10 +490,15 @@ public extension Future { return result } } else { - return nil + return nil + } + } + + private func checkDeadlock() { + if checkForPossibleDeadlock && eventLoop.inEventLoop { + fatalError("Called wait() in the EventLoop") } } - /// Add a callback. If there's already a value, invoke it and return the resulting list of new callback functions. fileprivate func _addCallback(callback: @escaping () -> CallbackList) -> CallbackList { futureLock.lock() @@ -576,12 +512,19 @@ public extension Future { return callback() } } - + /// Add a callback. If there's already a value, run as much of the chain as we can. fileprivate func _whenComplete(callback: @escaping () -> CallbackList) { - _addCallback(callback: callback)._run() + let list = _addCallback(callback: callback) + if eventLoop.inEventLoop { + list._run() + } else { + eventLoop.execute { + list._run() + } + } } - + public func whenSuccess(callback: @escaping (T) -> ()) { _whenComplete { if case .success(let t) = self.value { @@ -590,7 +533,7 @@ public extension Future { return CallbackList() } } - + public func whenFailure(callback: @escaping (Error) -> ()) { _whenComplete { if case .failure(let e) = self.value { @@ -599,7 +542,7 @@ public extension Future { return CallbackList() } } - + /// Internal: Set the value and return a list of callbacks that should be invoked as a result. fileprivate func _setValue(value: FutureValue) -> CallbackList { futureLock.lock() @@ -615,230 +558,8 @@ public extension Future { return CallbackList() } } - - /** - An easy way to run code on an async dispatch queue and get a result back: - - let future = Future.async { - () -> Int in - ... do some work ... - return int - } - - The provided function can also throw an error; it will be caught and cause the future return object to report a failure. - - By default, this runs the function on the global default concurrent queue. Success or failure will be dispatched onto the same queue. Note the various overloads of this function that allow you to control which queues are used. - */ - public static func async(function: @escaping () throws -> (T)) -> Future { - return async(qos: .default, function: function) - } - - /** - An overload for `async(function)` that runs the function on the global concurrent queue with the specified quality-of-service. Success or failure will be dispatched on the same queue. - */ - public static func async(qos: DispatchQoS.QoSClass, function: @escaping () throws -> (T)) -> Future { - let queue = DispatchQueue.global(qos: qos) - return async(queue: queue, function: function) - } - - /** - An overload for `async(function)` that runs the function on the provided dispatch queue. Success or failure will be dispatched on the same queue. This is most useful when you want to serialize a particular kind of request. - */ - public static func async(queue: DispatchQueue, function: @escaping () throws -> (T)) -> Future { - let promise = Promise() - queue.async { - do { - let t = try function() - promise.succeed(result: t) - } catch let error { - promise.fail(error: error) - } - } - return promise.futureResult - } - - /** Run code synchronously on a queue and return a Future result. - - This uses the same interface as `async()` except that it always waits for a result and then returns a Future that already holds a result or error. In particular, this allows you to easily switch between sync/async operation without changing your client code. - */ - public static func sync(queue: DispatchQueue, function: () throws -> (T)) -> Future { - let promise = Promise() - queue.sync { - do { - let t = try function() - promise.succeed(result: t) - } catch let error { - promise.fail(error: error) - } - } - return promise.futureResult - } - - /** Return a new `Future` that will deliver the first successful result from the array of `Future` or the last failure if all of the provided `Future` fail. - - Note: It does not wait for all of the provided `Future` to complete. - */ - public static func firstSuccess(futures: [Future]) -> Future { - assert(futures.count > 0) - let fslock = NSLock() - let promise = Promise() - var remaining = futures.count - - for d in futures { - d._whenComplete { - fslock.lock() - remaining -= 1 - let done = (remaining == 0) - fslock.unlock() - switch d.value { - case .failure(let error): - if done { - return promise._setValue(value: .failure(error)) - } - case .success(let t): - return promise._setValue(value: .success(t)) - case .incomplete: - assert(false) - } - return CallbackList() - } - } - return promise.futureResult - } - - /** Return a new `Future` that will fail on the first failure from the array of `Future` or succeed with the last success if none of the provided `Future` fail. - - Note: If there is a failure, it will not wait for any remaining `Future` to complete. - */ - public static func firstFailure(futures: [Future]) -> Future { - assert(futures.count > 0) - let fflock = NSLock() - let promise = Promise() - var remaining = futures.count - - for d in futures { - d._whenComplete { - fflock.lock() - remaining -= 1 - let done = (remaining == 0) - fflock.unlock() - switch d.value { - case .failure(let error): - return promise._setValue(value: .failure(error)) - case .success(let t): - if done { - return promise._setValue(value: .success(t)) - } - default: - assert(false) - } - return CallbackList() - } - } - return promise.futureResult - } - - /** Return a new `Future` that will complete only after all of the provided Future have completed. - - When it does complete, it will fail with the first error if any of the members failed. Otherwise, it will succeed with the first successful result. - */ - public static func allComplete(futures: [Future]) -> Future { - assert(futures.count > 0) - let aclock = NSLock() - let promise = Promise() - var firstError: Error? - var firstSuccess: T? - var remaining = futures.count - - func acquire() { - aclock.lock() - } - - func release() { - remaining -= 1 - if remaining == 0 { - aclock.unlock() - if let firstError = firstError { - promise.fail(error: firstError) - } else { - promise.succeed(result: firstSuccess!) - } - } else { - aclock.unlock() - } - } - - func failureCallback(error: Error) -> () { - acquire() - if firstError == nil { - firstError = error - } - release() - } - - func successCallback(t: T) -> () { - acquire() - if firstSuccess == nil { - firstSuccess = t - } - release() - } - - for d in futures { - d.whenSuccess(callback: successCallback) - d.whenFailure(callback: failureCallback) - } - return promise.futureResult - } } -public extension Future { - /** Return a new `Future<[T]>` that will collect the successes of the provided `Future`. - - If any of the provided Futures fail, the new Future will fail. Otherwise, it succeeds with an array of results in the same order as the provided Futures. - - Note: If there is an error, it will not wait for the remaining `Future` to complete. If you want to detect completion regardless of failure, look at `allComplete()` instead. - */ - public static func allSuccess(futures: [Future]) -> Future<[T]> { - let aslock = NSLock() - let promise = Promise<[T]>() - var results = [T]() - var i = 0 - - func callback(value: FutureValue) -> CallbackList { - switch value { - case .failure(let error): - return promise._setValue(value: .failure(error)) - case .success(let t): - aslock.lock() - results.append(t) - i += 1 - if i < futures.count { - let next = futures[i] - aslock.unlock() - return next._addCallback { - return callback(value: next.value) - } - } else { - aslock.unlock() - return promise._setValue(value: .success(results)) - } - default: - assert(false) - } - return [] - } - - if futures.count == 0 { - promise.succeed(result: []) - } else { - futures[0]._whenComplete { - return callback(value: futures[0].value) - } - } - return promise.futureResult - } -} public extension Future { /** @@ -848,10 +569,10 @@ public extension Future { */ public func and(_ other: Future) -> Future<(T,U)> { let andlock = NSLock() - let promise = Promise<(T,U)>() + let promise = Promise<(T,U)>(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock) var tvalue: T? var uvalue: U? - + _whenComplete { () -> CallbackList in switch self.value { case .failure(let error): @@ -870,7 +591,7 @@ public extension Future { } return CallbackList() } - + other._whenComplete { () -> CallbackList in switch other.value { case .failure(let error): @@ -889,16 +610,25 @@ public extension Future { } return CallbackList() } - + return promise.futureResult } - + /** * Return a new Future that contains this "and" another value. * This is just syntactic sugar for * future.and(Future(result: result)) */ public func and(result: U) -> Future<(T,U)> { - return and(Future(result:result)) + return and(Future(eventLoop: self.eventLoop, checkForPossibleDeadlock: self.checkForPossibleDeadlock, result:result)) + } +} + +extension Future { + + public func cascadeFailure(promise: Promise) { + self.whenFailure(callback: { err in + promise.fail(error: err) + }) } } diff --git a/Sources/NIO/Futures.swift b/Sources/NIO/Futures.swift deleted file mode 100644 index 0c9d87e7a..000000000 --- a/Sources/NIO/Futures.swift +++ /dev/null @@ -1,25 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftNIO open source project -// -// Copyright (c) 2017-2018 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 Foundation -import Future - -extension Future { - - public func cascadeFailure(promise: Promise) { - self.whenFailure(callback: { err in - promise.fail(error: err) - }) - } -} diff --git a/Sources/NIOEchoServer/main.swift b/Sources/NIOEchoServer/main.swift index fd5757c87..dd288e7b8 100644 --- a/Sources/NIOEchoServer/main.swift +++ b/Sources/NIOEchoServer/main.swift @@ -13,7 +13,6 @@ //===----------------------------------------------------------------------===// import Foundation import NIO -import Future public class EchoHandler: ChannelHandler { diff --git a/Tests/NIOTests/ChannelWriteTests.swift b/Tests/NIOTests/ChannelWriteTests.swift index 49a722c1f..b41f54fe0 100644 --- a/Tests/NIOTests/ChannelWriteTests.swift +++ b/Tests/NIOTests/ChannelWriteTests.swift @@ -19,30 +19,31 @@ import Foundation import XCTest -import Future import Sockets @testable import NIO class ChannelWriteTests: XCTestCase { func testWriteVIsTailRecursiveAndLoopifiedInReleaseMode() throws { if !_isDebugAssertConfiguration() { + let eventLoop = EmbeddedEventLoop() + let numberOfWritesToSmashTheStackIfNotTurnedIntoALoop = 500_000 let allocator = ByteBufferAllocator() let d = "Hello".data(using: .utf8)! let head: PendingWrite? = PendingWrite(buffer: ByteBuffer(allocator: allocator, data: d, offset: 0, length: 5, maxCapacity: 5), - promise: Promise()) + promise: eventLoop.newPromise(type: Void.self)) var tail: PendingWrite? = head for i in 0..<(numberOfWritesToSmashTheStackIfNotTurnedIntoALoop) { let len = (i % 5)+1 let new = PendingWrite(buffer: ByteBuffer(allocator: allocator, data: d, offset: 0, length: len, maxCapacity: 2*len), - promise: Promise()) + promise: eventLoop.newPromise(type: Void.self)) tail!.next = new tail = new } /* add a bogus one to check that the limit we pass in `count` later is respected. */ tail!.next = PendingWrite(buffer: ByteBuffer(allocator: allocator, data: "BOGUS".data(using: .utf8)!, offset: 0, length: 5, maxCapacity: 5), - promise: Promise()) + promise: eventLoop.newPromise(type: Void.self)) var iovecs_count = numberOfWritesToSmashTheStackIfNotTurnedIntoALoop + 1 /* doesn't include the bogus one */ var iovecs: UnsafeMutablePointer = UnsafeMutablePointer.allocate(capacity: iovecs_count) defer {