diff --git a/Sources/NIO/Bootstrap.swift b/Sources/NIO/Bootstrap.swift index 652fec35f..0120260e6 100644 --- a/Sources/NIO/Bootstrap.swift +++ b/Sources/NIO/Bootstrap.swift @@ -50,7 +50,7 @@ public final class ServerBootstrap { return self } - public func bind(to host: String, on port: Int32) -> Future { + public func bind(to host: String, on port: Int32) -> EventLoopFuture { let evGroup = group do { let address = try SocketAddress.newAddressResolving(host: host, port: port) @@ -60,11 +60,11 @@ public final class ServerBootstrap { } } - public func bind(to address: SocketAddress) -> Future { + public func bind(to address: SocketAddress) -> EventLoopFuture { return bind0(evGroup: group, to: address) } - public func bind(unixDomainSocket path: String) -> Future { + public func bind(unixDomainSocket path: String) -> EventLoopFuture { let evGroup = group do { let address = try SocketAddress.unixDomainSocketAddress(path: path) @@ -74,7 +74,7 @@ public final class ServerBootstrap { } } - private func bind0(evGroup: EventLoopGroup, to address: SocketAddress) -> Future { + private func bind0(evGroup: EventLoopGroup, to address: SocketAddress) -> EventLoopFuture { let chEvGroup = childGroup let opts = options let eventLoop = evGroup.next() @@ -82,7 +82,7 @@ public final class ServerBootstrap { let chHandler = childHandler let chOptions = childOptions - let promise: Promise = eventLoop.newPromise() + let promise: EventLoopPromise = eventLoop.newPromise() do { let serverChannel = try ServerSocketChannel(eventLoop: eventLoop as! SelectableEventLoop, group: chEvGroup, @@ -91,7 +91,7 @@ public final class ServerBootstrap { func finishServerSetup() { do { try opts.applyAll(channel: serverChannel) - let f = serverChannel.register().then(callback: { (_) -> Future<()> in serverChannel.bind(to: address) }) + let f = serverChannel.register().then(callback: { (_) -> EventLoopFuture<()> in serverChannel.bind(to: address) }) f.whenComplete(callback: { v in switch v { case .failure(let err): @@ -210,7 +210,7 @@ public final class ClientBootstrap { return self } - public func bind(protocolFamily: Int32, to host: String, on port: Int32) -> Future { + public func bind(protocolFamily: Int32, to host: String, on port: Int32) -> EventLoopFuture { let evGroup = group do { @@ -223,13 +223,13 @@ public final class ClientBootstrap { } } - public func bind(to address: SocketAddress) -> Future { + public func bind(to address: SocketAddress) -> EventLoopFuture { return execute(evGroup: group, protocolFamily: address.protocolFamily) { channel in return channel.bind(to: address) } } - public func connect(to host: String, on port: Int32) -> Future { + public func connect(to host: String, on port: Int32) -> EventLoopFuture { let evGroup = group do { @@ -242,13 +242,13 @@ public final class ClientBootstrap { } } - public func connect(to address: SocketAddress) -> Future { + public func connect(to address: SocketAddress) -> EventLoopFuture { return execute(evGroup: group, protocolFamily: address.protocolFamily) { channel in return channel.connect(to: address) } } - public func connect(to unixDomainSocket: String) -> Future { + public func connect(to unixDomainSocket: String) -> EventLoopFuture { do { let address = try SocketAddress.unixDomainSocketAddress(path: unixDomainSocket) return connect(to: address) @@ -259,19 +259,19 @@ public final class ClientBootstrap { private func execute(evGroup: EventLoopGroup, protocolFamily: Int32, - fn: @escaping (Channel) -> Future) -> Future { + fn: @escaping (Channel) -> EventLoopFuture) -> EventLoopFuture { let eventLoop = evGroup.next() let h = handler let opts = options - let promise: Promise = eventLoop.newPromise() + let promise: EventLoopPromise = eventLoop.newPromise() do { let channel = try SocketChannel(eventLoop: eventLoop as! SelectableEventLoop, protocolFamily: protocolFamily) func finishClientSetup() { do { try opts.applyAll(channel: channel) - let f = channel.register().then { (_) -> Future in + let f = channel.register().then { (_) -> EventLoopFuture in fn(channel) } f.whenComplete(callback: { v in diff --git a/Sources/NIO/Channel.swift b/Sources/NIO/Channel.swift index 984f0bc79..2c47b21b5 100644 --- a/Sources/NIO/Channel.swift +++ b/Sources/NIO/Channel.swift @@ -31,7 +31,7 @@ private extension IOData { } } } -private typealias PendingWrite = (data: IOData, promise: Promise?) +private typealias PendingWrite = (data: IOData, promise: EventLoopPromise?) // We need to know the maximum value of a 32-bit int, but in Swift's regular int size. Store it here. private let maxInt = Int(INT32_MAX) @@ -111,7 +111,7 @@ private final class PendingWrites { return self.pendingWrites.isEmpty } - func add(data: IOData, promise: Promise?) -> Bool { + func add(data: IOData, promise: EventLoopPromise?) -> Bool { assert(!closed) self.pendingWrites.append((data: data, promise: promise)) @@ -136,7 +136,7 @@ private final class PendingWrites { return false } - func markFlushCheckpoint(promise: Promise?) { + func markFlushCheckpoint(promise: EventLoopPromise?) { self.pendingWrites.mark() let checkpointIdx = self.pendingWrites.markedElementIndex() if let promise = promise, let checkpoint = checkpointIdx { @@ -525,7 +525,7 @@ final class ServerSocketChannel : BaseSocketChannel { return try super.getOption0(option: option) } - override public func bind0(to address: SocketAddress, promise: Promise?) { + override public func bind0(to address: SocketAddress, promise: EventLoopPromise?) { assert(eventLoop.inEventLoop) do { try socket.bind(to: address) @@ -594,14 +594,14 @@ final class ServerSocketChannel : BaseSocketChannel { All methods must be called from the EventLoop thread */ public protocol ChannelCore : class { - func register0(promise: Promise?) - func bind0(to: SocketAddress, promise: Promise?) - func connect0(to: SocketAddress, promise: Promise?) - func write0(data: IOData, promise: Promise?) - func flush0(promise: Promise?) - func read0(promise: Promise?) - func close0(error: Error, promise: Promise?) - func triggerUserOutboundEvent0(event: Any, promise: Promise?) + func register0(promise: EventLoopPromise?) + func bind0(to: SocketAddress, promise: EventLoopPromise?) + func connect0(to: SocketAddress, promise: EventLoopPromise?) + func write0(data: IOData, promise: EventLoopPromise?) + func flush0(promise: EventLoopPromise?) + func read0(promise: EventLoopPromise?) + func close0(error: Error, promise: EventLoopPromise?) + func triggerUserOutboundEvent0(event: Any, promise: EventLoopPromise?) func channelRead0(data: NIOAny) func errorCaught0(error: Error) } @@ -612,7 +612,7 @@ public protocol ChannelCore : class { public protocol Channel : class, ChannelOutboundInvoker { var allocator: ByteBufferAllocator { get } - var closeFuture: Future { get } + var closeFuture: EventLoopFuture { get } var pipeline: ChannelPipeline { get } var localAddress: SocketAddress? { get } @@ -646,42 +646,42 @@ extension Channel { return !closeFuture.fulfilled } - public func bind(to address: SocketAddress, promise: Promise?) { + public func bind(to address: SocketAddress, promise: EventLoopPromise?) { pipeline.bind(to: address, promise: promise) } // Methods invoked from the HeadHandler of the ChannelPipeline // By default, just pass through to pipeline - public func connect(to address: SocketAddress, promise: Promise?) { + public func connect(to address: SocketAddress, promise: EventLoopPromise?) { pipeline.connect(to: address, promise: promise) } - public func write(data: NIOAny, promise: Promise?) { + public func write(data: NIOAny, promise: EventLoopPromise?) { pipeline.write(data: data, promise: promise) } - public func flush(promise: Promise?) { + public func flush(promise: EventLoopPromise?) { pipeline.flush(promise: promise) } - public func writeAndFlush(data: NIOAny, promise: Promise?) { + public func writeAndFlush(data: NIOAny, promise: EventLoopPromise?) { pipeline.writeAndFlush(data: data, promise: promise) } - public func read(promise: Promise?) { + public func read(promise: EventLoopPromise?) { pipeline.read(promise: promise) } - public func close(promise: Promise?) { + public func close(promise: EventLoopPromise?) { pipeline.close(promise: promise) } - public func register(promise: Promise?) { + public func register(promise: EventLoopPromise?) { pipeline.register(promise: promise) } - public func triggerUserOutboundEvent(event: Any, promise: Promise?) { + public func triggerUserOutboundEvent(event: Any, promise: EventLoopPromise?) { pipeline.triggerUserOutboundEvent(event: event, promise: promise) } } @@ -710,8 +710,8 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { private let pendingWrites: PendingWrites fileprivate var readPending = false private var neverRegistered = true - private var pendingConnect: Promise? - private let closePromise: Promise + private var pendingConnect: EventLoopPromise? + private let closePromise: EventLoopPromise private var active: Atomic = Atomic(value: false) public var isActive: Bool { return active.load() @@ -719,7 +719,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { public var parent: Channel? = nil - public final var closeFuture: Future { + public final var closeFuture: EventLoopFuture { return closePromise.futureResult } @@ -845,7 +845,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { } // Methods invoked from the HeadHandler of the ChannelPipeline - public func bind0(to address: SocketAddress, promise: Promise?) { + public func bind0(to address: SocketAddress, promise: EventLoopPromise?) { assert(eventLoop.inEventLoop) do { @@ -856,7 +856,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { } } - public func write0(data: IOData, promise: Promise?) { + public func write0(data: IOData, promise: EventLoopPromise?) { assert(eventLoop.inEventLoop) if closed { @@ -891,7 +891,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { } } - public final func flush0(promise: Promise?) { + public final func flush0(promise: EventLoopPromise?) { assert(eventLoop.inEventLoop) if closed { @@ -907,7 +907,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { } } - public final func read0(promise: Promise?) { + public final func read0(promise: EventLoopPromise?) { assert(eventLoop.inEventLoop) @@ -953,7 +953,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { } } - public final func close0(error: Error, promise: Promise?) { + public final func close0(error: Error, promise: EventLoopPromise?) { assert(eventLoop.inEventLoop) if closed { @@ -998,7 +998,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { } - public final func register0(promise: Promise?) { + public final func register0(promise: EventLoopPromise?) { assert(eventLoop.inEventLoop) // Was not registered yet so do it now. @@ -1011,7 +1011,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { } } - public final func triggerUserOutboundEvent0(event: Any, promise: Promise?) { + public final func triggerUserOutboundEvent0(event: Any, promise: EventLoopPromise?) { promise?.succeed(result: ()) } @@ -1087,7 +1087,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { fatalError("this must be overridden by sub class") } - public final func connect0(to address: SocketAddress, promise: Promise?) { + public final func connect0(to address: SocketAddress, promise: EventLoopPromise?) { assert(eventLoop.inEventLoop) guard pendingConnect == nil else { diff --git a/Sources/NIO/ChannelHandler.swift b/Sources/NIO/ChannelHandler.swift index a002654ce..45a2bf013 100644 --- a/Sources/NIO/ChannelHandler.swift +++ b/Sources/NIO/ChannelHandler.swift @@ -18,15 +18,15 @@ public protocol ChannelHandler : class { } public protocol _ChannelOutboundHandler : ChannelHandler { - func register(ctx: ChannelHandlerContext, promise: Promise?) - func bind(ctx: ChannelHandlerContext, to: SocketAddress, promise: Promise?) - func connect(ctx: ChannelHandlerContext, to: SocketAddress, promise: Promise?) - func write(ctx: ChannelHandlerContext, data: NIOAny, promise: Promise?) - func flush(ctx: ChannelHandlerContext, promise: Promise?) + func register(ctx: ChannelHandlerContext, promise: EventLoopPromise?) + func bind(ctx: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise?) + func connect(ctx: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise?) + func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) + func flush(ctx: ChannelHandlerContext, promise: EventLoopPromise?) // TODO: Think about make this more flexible in terms of influence the allocation that is used to read the next amount of data - func read(ctx: ChannelHandlerContext, promise: Promise?) - func close(ctx: ChannelHandlerContext, promise: Promise?) - func triggerUserOutboundEvent(ctx: ChannelHandlerContext, event: Any, promise: Promise?) + func read(ctx: ChannelHandlerContext, promise: EventLoopPromise?) + func close(ctx: ChannelHandlerContext, promise: EventLoopPromise?) + func triggerUserOutboundEvent(ctx: ChannelHandlerContext, event: Any, promise: EventLoopPromise?) } public protocol _ChannelInboundHandler : ChannelHandler { @@ -55,35 +55,35 @@ extension ChannelHandler { extension _ChannelOutboundHandler { - public func register(ctx: ChannelHandlerContext, promise: Promise?) { + public func register(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { ctx.register(promise: promise) } - public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: Promise?) { + public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { ctx.bind(to: address, promise: promise) } - public func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: Promise?) { + public func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { ctx.connect(to: address, promise: promise) } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: Promise?) { + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { ctx.write(data: data, promise: promise) } - public func flush(ctx: ChannelHandlerContext, promise: Promise?) { + public func flush(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { ctx.flush(promise: promise) } - public func read(ctx: ChannelHandlerContext, promise: Promise?) { + public func read(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { ctx.read(promise: promise) } - public func close(ctx: ChannelHandlerContext, promise: Promise?) { + public func close(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { ctx.close(promise: promise) } - public func triggerUserOutboundEvent(ctx: ChannelHandlerContext, event: Any, promise: Promise?) { + public func triggerUserOutboundEvent(ctx: ChannelHandlerContext, event: Any, promise: EventLoopPromise?) { ctx.triggerUserOutboundEvent(event: event, promise: promise) } } diff --git a/Sources/NIO/ChannelHandlers.swift b/Sources/NIO/ChannelHandlers.swift index ee0619d7a..a6315a1ac 100644 --- a/Sources/NIO/ChannelHandlers.swift +++ b/Sources/NIO/ChannelHandlers.swift @@ -26,7 +26,7 @@ public class BackPressureHandler: ChannelInboundHandler, _ChannelOutboundHandler private enum PendingRead { case none - case promise(promise: Promise?) + case promise(promise: EventLoopPromise?) } private var pendingRead: PendingRead = .none @@ -34,7 +34,7 @@ public class BackPressureHandler: ChannelInboundHandler, _ChannelOutboundHandler public init() { } - public func read(ctx: ChannelHandlerContext, promise: Promise?) { + public func read(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { if writable { ctx.read(promise: promise) } else { @@ -78,9 +78,9 @@ public class BackPressureHandler: ChannelInboundHandler, _ChannelOutboundHandler } public class ChannelInitializer: _ChannelInboundHandler { - private let initChannel: (Channel) -> (Future) + private let initChannel: (Channel) -> (EventLoopFuture) - public init(initChannel: @escaping (Channel) -> (Future)) { + public init(initChannel: @escaping (Channel) -> (EventLoopFuture)) { self.initChannel = initChannel } @@ -167,7 +167,7 @@ public class IdleStateHandler : ChannelInboundHandler, ChannelOutboundHandler { ctx.fireChannelReadComplete() } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: Promise?) { + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { if writeTimeout == nil && allTimeout == nil { ctx.write(data: data, promise: promise) return diff --git a/Sources/NIO/ChannelInvoker.swift b/Sources/NIO/ChannelInvoker.swift index 46164918e..2e9823fcd 100644 --- a/Sources/NIO/ChannelInvoker.swift +++ b/Sources/NIO/ChannelInvoker.swift @@ -12,92 +12,92 @@ // //===----------------------------------------------------------------------===// public protocol ChannelOutboundInvoker { - func register() -> Future - func register(promise: Promise?) + func register() -> EventLoopFuture + func register(promise: EventLoopPromise?) - func bind(to: SocketAddress) -> Future - func bind(to: SocketAddress, promise: Promise?) + func bind(to: SocketAddress) -> EventLoopFuture + func bind(to: SocketAddress, promise: EventLoopPromise?) - func connect(to: SocketAddress) -> Future - func connect(to: SocketAddress, promise: Promise?) + func connect(to: SocketAddress) -> EventLoopFuture + func connect(to: SocketAddress, promise: EventLoopPromise?) - func write(data: NIOAny) -> Future - func write(data: NIOAny, promise: Promise?) + func write(data: NIOAny) -> EventLoopFuture + func write(data: NIOAny, promise: EventLoopPromise?) - func flush() -> Future - func flush(promise: Promise?) + func flush() -> EventLoopFuture + func flush(promise: EventLoopPromise?) - func writeAndFlush(data: NIOAny) -> Future - func writeAndFlush(data: NIOAny, promise: Promise?) + func writeAndFlush(data: NIOAny) -> EventLoopFuture + func writeAndFlush(data: NIOAny, promise: EventLoopPromise?) - func read() -> Future - func read(promise: Promise?) + func read() -> EventLoopFuture + func read(promise: EventLoopPromise?) - func close() -> Future - func close(promise: Promise?) + func close() -> EventLoopFuture + func close(promise: EventLoopPromise?) - func triggerUserOutboundEvent(event: Any) -> Future - func triggerUserOutboundEvent(event: Any, promise: Promise?) + func triggerUserOutboundEvent(event: Any) -> EventLoopFuture + func triggerUserOutboundEvent(event: Any, promise: EventLoopPromise?) var eventLoop: EventLoop { get } } extension ChannelOutboundInvoker { - public func register() -> Future { + public func register() -> EventLoopFuture { let promise = newPromise() register(promise: promise) return promise.futureResult } - public func bind(to address: SocketAddress) -> Future { + public func bind(to address: SocketAddress) -> EventLoopFuture { let promise = newPromise() bind(to: address, promise: promise) return promise.futureResult } - public func connect(to address: SocketAddress) -> Future { + public func connect(to address: SocketAddress) -> EventLoopFuture { let promise = newPromise() connect(to: address, promise: promise) return promise.futureResult } - public func write(data: NIOAny) -> Future { + public func write(data: NIOAny) -> EventLoopFuture { let promise = newPromise() write(data: data, promise: promise) return promise.futureResult } - public func read() -> Future { + public func read() -> EventLoopFuture { let promise = newPromise() read(promise: promise) return promise.futureResult } - public func flush() -> Future { + public func flush() -> EventLoopFuture { let promise = newPromise() flush(promise: promise) return promise.futureResult } - public func writeAndFlush(data: NIOAny) -> Future { + public func writeAndFlush(data: NIOAny) -> EventLoopFuture { let promise = newPromise() writeAndFlush(data: data, promise: promise) return promise.futureResult } - public func close() -> Future { + public func close() -> EventLoopFuture { let promise = newPromise() close(promise: promise) return promise.futureResult } - public func triggerUserOutboundEvent(event: Any) -> Future { + public func triggerUserOutboundEvent(event: Any) -> EventLoopFuture { let promise = newPromise() triggerUserOutboundEvent(event: event, promise: promise) return promise.futureResult } - private func newPromise() -> Promise { + private func newPromise() -> EventLoopPromise { return eventLoop.newPromise() } } diff --git a/Sources/NIO/ChannelPipeline.swift b/Sources/NIO/ChannelPipeline.swift index fb911dd6a..7f9a3451a 100644 --- a/Sources/NIO/ChannelPipeline.swift +++ b/Sources/NIO/ChannelPipeline.swift @@ -29,8 +29,8 @@ public final class ChannelPipeline : ChannelInvoker { public unowned let channel: Channel - public func add(name: String? = nil, handler: ChannelHandler, first: Bool = false) -> Future { - let promise: Promise = eventLoop.newPromise() + public func add(name: String? = nil, handler: ChannelHandler, first: Bool = false) -> EventLoopFuture { + let promise: EventLoopPromise = eventLoop.newPromise() if eventLoop.inEventLoop { add0(name: name, handler: handler, first: first, promise: promise) } else { @@ -41,7 +41,7 @@ public final class ChannelPipeline : ChannelInvoker { return promise.futureResult } - public func add0(name: String?, handler: ChannelHandler, first: Bool, promise: Promise) { + public func add0(name: String?, handler: ChannelHandler, first: Bool, promise: EventLoopPromise) { assert(eventLoop.inEventLoop) if destroyed { @@ -118,32 +118,32 @@ public final class ChannelPipeline : ChannelInvoker { } } - public func remove(handler: ChannelHandler) -> Future { + public func remove(handler: ChannelHandler) -> EventLoopFuture { return remove0({ $0.handler === handler }) } - public func remove(name: String) -> Future { + public func remove(name: String) -> EventLoopFuture { return remove0({ $0.name == name }) } - public func remove(ctx: ChannelHandlerContext) -> Future { + public func remove(ctx: ChannelHandlerContext) -> EventLoopFuture { return remove0({ $0 === ctx }) } - public func context(handler: ChannelHandler) -> Future { + public func context(handler: ChannelHandler) -> EventLoopFuture { return context0({ $0.handler === handler }) } - public func context(name: String) -> Future { + public func context(name: String) -> EventLoopFuture { return context0({ $0.name == name }) } - public func context(ctx: ChannelHandlerContext) -> Future { + public func context(ctx: ChannelHandlerContext) -> EventLoopFuture { return context0({ $0 === ctx }) } - private func context0(_ fn: @escaping ((ChannelHandlerContext) -> Bool)) -> Future { - let promise: Promise = eventLoop.newPromise() + private func context0(_ fn: @escaping ((ChannelHandlerContext) -> Bool)) -> EventLoopFuture { + let promise: EventLoopPromise = eventLoop.newPromise() func _context0() { guard let ctx = contexts.first(where: fn) else { @@ -162,8 +162,8 @@ public final class ChannelPipeline : ChannelInvoker { return promise.futureResult } - private func remove0(_ fn: @escaping ((ChannelHandlerContext) -> Bool)) -> Future { - let promise: Promise = eventLoop.newPromise() + private func remove0(_ fn: @escaping ((ChannelHandlerContext) -> Bool)) -> EventLoopFuture { + let promise: EventLoopPromise = eventLoop.newPromise() if eventLoop.inEventLoop { remove0(ctx: contexts.first(where: fn), promise: promise) } else { @@ -212,7 +212,7 @@ public final class ChannelPipeline : ChannelInvoker { assert(outboundChain != nil) } - private func remove0(ctx: ChannelHandlerContext?, promise: Promise) { + private func remove0(ctx: ChannelHandlerContext?, promise: EventLoopPromise) { assert(eventLoop.inEventLoop) guard let context = ctx else { @@ -350,7 +350,7 @@ public final class ChannelPipeline : ChannelInvoker { } } - public func close(promise: Promise?) { + public func close(promise: EventLoopPromise?) { if eventLoop.inEventLoop { close0(promise: promise) } else { @@ -360,7 +360,7 @@ public final class ChannelPipeline : ChannelInvoker { } } - public func flush(promise: Promise?) { + public func flush(promise: EventLoopPromise?) { if eventLoop.inEventLoop { flush0(promise: promise) } else { @@ -370,7 +370,7 @@ public final class ChannelPipeline : ChannelInvoker { } } - public func read(promise: Promise?) { + public func read(promise: EventLoopPromise?) { if eventLoop.inEventLoop { read0(promise: promise) } else { @@ -380,7 +380,7 @@ public final class ChannelPipeline : ChannelInvoker { } } - public func write(data: NIOAny, promise: Promise?) { + public func write(data: NIOAny, promise: EventLoopPromise?) { if eventLoop.inEventLoop { write0(data: data, promise: promise) } else { @@ -390,7 +390,7 @@ public final class ChannelPipeline : ChannelInvoker { } } - public func writeAndFlush(data: NIOAny, promise: Promise?) { + public func writeAndFlush(data: NIOAny, promise: EventLoopPromise?) { if eventLoop.inEventLoop { writeAndFlush0(data: data, promise: promise) } else { @@ -400,7 +400,7 @@ public final class ChannelPipeline : ChannelInvoker { } } - public func bind(to address: SocketAddress, promise: Promise?) { + public func bind(to address: SocketAddress, promise: EventLoopPromise?) { if eventLoop.inEventLoop { bind0(to: address, promise: promise) } else { @@ -410,7 +410,7 @@ public final class ChannelPipeline : ChannelInvoker { } } - public func connect(to address: SocketAddress, promise: Promise?) { + public func connect(to address: SocketAddress, promise: EventLoopPromise?) { if eventLoop.inEventLoop { connect0(to: address, promise: promise) } else { @@ -420,7 +420,7 @@ public final class ChannelPipeline : ChannelInvoker { } } - public func register(promise: Promise?) { + public func register(promise: EventLoopPromise?) { if eventLoop.inEventLoop { register0(promise: promise) } else { @@ -430,7 +430,7 @@ public final class ChannelPipeline : ChannelInvoker { } } - public func triggerUserOutboundEvent(event: Any, promise: Promise?) { + public func triggerUserOutboundEvent(event: Any, promise: EventLoopPromise?) { if eventLoop.inEventLoop { triggerUserOutboundEvent0(event: event, promise: promise) } else { @@ -450,39 +450,39 @@ public final class ChannelPipeline : ChannelInvoker { return inboundChain! } - func close0(promise: Promise?) { + func close0(promise: EventLoopPromise?) { firstOutboundCtx.invokeClose(promise: promise) } - func flush0(promise: Promise?) { + func flush0(promise: EventLoopPromise?) { firstOutboundCtx.invokeFlush(promise: promise) } - func read0(promise: Promise?) { + func read0(promise: EventLoopPromise?) { firstOutboundCtx.invokeRead(promise: promise) } - func write0(data: NIOAny, promise: Promise?) { + func write0(data: NIOAny, promise: EventLoopPromise?) { firstOutboundCtx.invokeWrite(data: data, promise: promise) } - func writeAndFlush0(data: NIOAny, promise: Promise?) { + func writeAndFlush0(data: NIOAny, promise: EventLoopPromise?) { firstOutboundCtx.invokeWriteAndFlush(data: data, promise: promise) } - func bind0(to address: SocketAddress, promise: Promise?) { + func bind0(to address: SocketAddress, promise: EventLoopPromise?) { firstOutboundCtx.invokeBind(to: address, promise: promise) } - func connect0(to address: SocketAddress, promise: Promise?) { + func connect0(to address: SocketAddress, promise: EventLoopPromise?) { firstOutboundCtx.invokeConnect(to: address, promise: promise) } - func register0(promise: Promise?) { + func register0(promise: EventLoopPromise?) { firstOutboundCtx.invokeRegister(promise: promise) } - func triggerUserOutboundEvent0(event: Any, promise: Promise?) { + func triggerUserOutboundEvent0(event: Any, promise: EventLoopPromise?) { firstOutboundCtx.invokeTriggerUserOutboundEvent(event: event, promise: promise) } @@ -543,7 +543,7 @@ private final class HeadChannelHandler : _ChannelOutboundHandler { private init() { } - func register(ctx: ChannelHandlerContext, promise: Promise?) { + func register(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { if let channel = ctx.channel { channel._unsafe.register0(promise: promise) } else { @@ -551,7 +551,7 @@ private final class HeadChannelHandler : _ChannelOutboundHandler { } } - func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: Promise?) { + func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { if let channel = ctx.channel { channel._unsafe.bind0(to: address, promise: promise) } else { @@ -559,7 +559,7 @@ private final class HeadChannelHandler : _ChannelOutboundHandler { } } - func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: Promise?) { + func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { if let channel = ctx.channel { channel._unsafe.connect0(to: address, promise: promise) } else { @@ -567,7 +567,7 @@ private final class HeadChannelHandler : _ChannelOutboundHandler { } } - func write(ctx: ChannelHandlerContext, data: NIOAny, promise: Promise?) { + func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { if let channel = ctx.channel { channel._unsafe.write0(data: data.forceAsIOData(), promise: promise) } else { @@ -575,7 +575,7 @@ private final class HeadChannelHandler : _ChannelOutboundHandler { } } - func flush(ctx: ChannelHandlerContext, promise: Promise?) { + func flush(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { if let channel = ctx.channel { channel._unsafe.flush0(promise: promise) } else { @@ -583,7 +583,7 @@ private final class HeadChannelHandler : _ChannelOutboundHandler { } } - func close(ctx: ChannelHandlerContext, promise: Promise?) { + func close(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { if let channel = ctx.channel { channel._unsafe.close0(error: ChannelError.alreadyClosed, promise: promise) } else { @@ -591,7 +591,7 @@ private final class HeadChannelHandler : _ChannelOutboundHandler { } } - func read(ctx: ChannelHandlerContext, promise: Promise?) { + func read(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { if let channel = ctx.channel { channel._unsafe.read0(promise: promise) } else { @@ -599,7 +599,7 @@ private final class HeadChannelHandler : _ChannelOutboundHandler { } } - func triggerUserOutboundEvent(ctx: ChannelHandlerContext, event: Any, promise: Promise?) { + func triggerUserOutboundEvent(ctx: ChannelHandlerContext, event: Any, promise: EventLoopPromise?) { if let channel = ctx.channel { channel._unsafe.triggerUserOutboundEvent0(event: event, promise: promise) } else { @@ -749,7 +749,7 @@ public final class ChannelHandlerContext : ChannelInvoker { } } - public func register(promise: Promise?) { + public func register(promise: EventLoopPromise?) { if let outboundNext = outboundNext { outboundNext.invokeRegister(promise: promise) } else { @@ -757,7 +757,7 @@ public final class ChannelHandlerContext : ChannelInvoker { } } - public func bind(to address: SocketAddress, promise: Promise?) { + public func bind(to address: SocketAddress, promise: EventLoopPromise?) { if let outboundNext = outboundNext { outboundNext.invokeBind(to: address, promise: promise) } else { @@ -765,7 +765,7 @@ public final class ChannelHandlerContext : ChannelInvoker { } } - public func connect(to address: SocketAddress, promise: Promise?) { + public func connect(to address: SocketAddress, promise: EventLoopPromise?) { if let outboundNext = outboundNext { outboundNext.invokeConnect(to: address, promise: promise) } else { @@ -773,7 +773,7 @@ public final class ChannelHandlerContext : ChannelInvoker { } } - public func write(data: NIOAny, promise: Promise?) { + public func write(data: NIOAny, promise: EventLoopPromise?) { if let outboundNext = outboundNext { outboundNext.invokeWrite(data: data, promise: promise) } else { @@ -781,7 +781,7 @@ public final class ChannelHandlerContext : ChannelInvoker { } } - public func flush(promise: Promise?) { + public func flush(promise: EventLoopPromise?) { if let outboundNext = outboundNext { outboundNext.invokeFlush(promise: promise) } else { @@ -789,7 +789,7 @@ public final class ChannelHandlerContext : ChannelInvoker { } } - public func writeAndFlush(data: NIOAny, promise: Promise?) { + public func writeAndFlush(data: NIOAny, promise: EventLoopPromise?) { if let outboundNext = outboundNext { outboundNext.invokeWriteAndFlush(data: data, promise: promise) } else { @@ -797,7 +797,7 @@ public final class ChannelHandlerContext : ChannelInvoker { } } - public func read(promise: Promise?) { + public func read(promise: EventLoopPromise?) { if let outboundNext = outboundNext { outboundNext.invokeRead(promise: promise) } else { @@ -805,7 +805,7 @@ public final class ChannelHandlerContext : ChannelInvoker { } } - public func close(promise: Promise?) { + public func close(promise: EventLoopPromise?) { if let outboundNext = outboundNext { outboundNext.invokeClose(promise: promise) } else { @@ -813,7 +813,7 @@ public final class ChannelHandlerContext : ChannelInvoker { } } - public func triggerUserOutboundEvent(event: Any, promise: Promise?) { + public func triggerUserOutboundEvent(event: Any, promise: EventLoopPromise?) { if let outboundNext = outboundNext { outboundNext.invokeTriggerUserOutboundEvent(event: event, promise: promise) } else { @@ -912,47 +912,47 @@ public final class ChannelHandlerContext : ChannelInvoker { } } - fileprivate func invokeRegister(promise: Promise?) { + fileprivate func invokeRegister(promise: EventLoopPromise?) { assert(inEventLoop) assert(promise.map { !$0.futureResult.fulfilled } ?? true, "Promise \(promise!) already fulfilled") self.outboundHandler.register(ctx: self, promise: promise) } - fileprivate func invokeBind(to address: SocketAddress, promise: Promise?) { + fileprivate func invokeBind(to address: SocketAddress, promise: EventLoopPromise?) { assert(inEventLoop) assert(promise.map { !$0.futureResult.fulfilled } ?? true, "Promise \(promise!) already fulfilled") self.outboundHandler.bind(ctx: self, to: address, promise: promise) } - fileprivate func invokeConnect(to address: SocketAddress, promise: Promise?) { + fileprivate func invokeConnect(to address: SocketAddress, promise: EventLoopPromise?) { assert(inEventLoop) assert(promise.map { !$0.futureResult.fulfilled } ?? true, "Promise \(promise!) already fulfilled") self.outboundHandler.connect(ctx: self, to: address, promise: promise) } - fileprivate func invokeWrite(data: NIOAny, promise: Promise?) { + fileprivate func invokeWrite(data: NIOAny, promise: EventLoopPromise?) { assert(inEventLoop) assert(promise.map { !$0.futureResult.fulfilled } ?? true, "Promise \(promise!) already fulfilled") self.outboundHandler.write(ctx: self, data: data, promise: promise) } - fileprivate func invokeFlush(promise: Promise?) { + fileprivate func invokeFlush(promise: EventLoopPromise?) { assert(inEventLoop) self.outboundHandler.flush(ctx: self, promise: promise) } - fileprivate func invokeWriteAndFlush(data: NIOAny, promise: Promise?) { + fileprivate func invokeWriteAndFlush(data: NIOAny, promise: EventLoopPromise?) { assert(inEventLoop) assert(promise.map { !$0.futureResult.fulfilled } ?? true, "Promise \(promise!) already fulfilled") if let promise = promise { var counter = 2 - let callback: (FutureValue) -> Void = { v in + let callback: (EventLoopFutureValue) -> Void = { v in switch v { case .failure(let err): promise.fail(error: err) @@ -965,8 +965,8 @@ public final class ChannelHandlerContext : ChannelInvoker { } } - let writePromise: Promise = eventLoop.newPromise() - let flushPromise: Promise = eventLoop.newPromise() + let writePromise: EventLoopPromise = eventLoop.newPromise() + let flushPromise: EventLoopPromise = eventLoop.newPromise() self.outboundHandler.write(ctx: self, data: data, promise: writePromise) self.outboundHandler.flush(ctx: self, promise: flushPromise) @@ -979,20 +979,20 @@ public final class ChannelHandlerContext : ChannelInvoker { } } - fileprivate func invokeRead(promise: Promise?) { + fileprivate func invokeRead(promise: EventLoopPromise?) { assert(inEventLoop) self.outboundHandler.read(ctx: self, promise: promise) } - fileprivate func invokeClose(promise: Promise?) { + fileprivate func invokeClose(promise: EventLoopPromise?) { assert(inEventLoop) assert(promise.map { !$0.futureResult.fulfilled } ?? true, "Promise \(promise!) already fulfilled") self.outboundHandler.close(ctx: self, promise: promise) } - fileprivate func invokeTriggerUserOutboundEvent(event: Any, promise: Promise?) { + fileprivate func invokeTriggerUserOutboundEvent(event: Any, promise: EventLoopPromise?) { assert(inEventLoop) assert(promise.map { !$0.futureResult.fulfilled } ?? true, "Promise \(promise!) already fulfilled") diff --git a/Sources/NIO/Codec.swift b/Sources/NIO/Codec.swift index 5ae7dfea3..706a49d6f 100644 --- a/Sources/NIO/Codec.swift +++ b/Sources/NIO/Codec.swift @@ -93,7 +93,7 @@ public protocol MessageToByteEncoder : ChannelOutboundHandler where OutboundOut } extension MessageToByteEncoder { - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: Promise?) { + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { do { let data = self.unwrapOutboundIn(data) var buffer: ByteBuffer = try allocateOutBuffer(ctx: ctx, data: data) diff --git a/Sources/NIO/Embedded.swift b/Sources/NIO/Embedded.swift index cc02ab8c3..443c6132b 100644 --- a/Sources/NIO/Embedded.swift +++ b/Sources/NIO/Embedded.swift @@ -23,20 +23,20 @@ class EmbeddedEventLoop : EventLoop { // Would be better to have this as a Queue var tasks: [() -> ()] = Array() - public func newPromise() -> Promise { - return Promise(eventLoop: self, checkForPossibleDeadlock: false) + public func newPromise() -> EventLoopPromise { + return EventLoopPromise(eventLoop: self, checkForPossibleDeadlock: false) } - public func newFailedFuture(error: Error) -> Future { - return Future(eventLoop: self, checkForPossibleDeadlock: false, error: error) + public func newFailedFuture(error: Error) -> EventLoopFuture { + return EventLoopFuture(eventLoop: self, checkForPossibleDeadlock: false, error: error) } - public func newSucceedFuture(result: T) -> Future { - return Future(eventLoop: self, checkForPossibleDeadlock: false, result: result) + public func newSucceedFuture(result: T) -> EventLoopFuture { + return EventLoopFuture(eventLoop: self, checkForPossibleDeadlock: false, result: result) } func scheduleTask(in: TimeAmount, _ task: @escaping () throws-> (T)) -> Scheduled { - let promise: Promise = newPromise() + let promise: EventLoopPromise = newPromise() promise.fail(error: EventLoopError.unsupportedOperation) return Scheduled(promise: promise, cancellationTask: { // Nothing to do as we fail the promise before @@ -83,7 +83,7 @@ class EmbeddedChannelCore : ChannelCore { var eventLoop: EventLoop = EmbeddedEventLoop() - var closePromise: Promise + var closePromise: EventLoopPromise var error: Error? private unowned let pipeline: ChannelPipeline @@ -101,7 +101,7 @@ class EmbeddedChannelCore : ChannelCore { var outboundBuffer: [IOData] = [] var inboundBuffer: [NIOAny] = [] - func close0(error: Error, promise: Promise?) { + func close0(error: Error, promise: EventLoopPromise?) { if closed { promise?.fail(error: ChannelError.alreadyClosed) return @@ -121,27 +121,27 @@ class EmbeddedChannelCore : ChannelCore { } } - func bind0(to address: SocketAddress, promise: Promise?) { + func bind0(to address: SocketAddress, promise: EventLoopPromise?) { promise?.succeed(result: ()) } - func connect0(to address: SocketAddress, promise: Promise?) { + func connect0(to address: SocketAddress, promise: EventLoopPromise?) { promise?.succeed(result: ()) pipeline.fireChannelRegistered0() isActive = true pipeline.fireChannelActive0() } - func register0(promise: Promise?) { + func register0(promise: EventLoopPromise?) { promise?.succeed(result: ()) } - func write0(data: IOData, promise: Promise?) { + func write0(data: IOData, promise: EventLoopPromise?) { addToBuffer(buffer: &outboundBuffer, data: data) promise?.succeed(result: ()) } - func flush0(promise: Promise?) { + func flush0(promise: EventLoopPromise?) { if closed { promise?.fail(error: ChannelError.ioOnClosedChannel) return @@ -149,7 +149,7 @@ class EmbeddedChannelCore : ChannelCore { promise?.succeed(result: ()) } - func read0(promise: Promise?) { + func read0(promise: EventLoopPromise?) { if closed { promise?.fail(error: ChannelError.ioOnClosedChannel) return @@ -157,7 +157,7 @@ class EmbeddedChannelCore : ChannelCore { promise?.succeed(result: ()) } - public final func triggerUserOutboundEvent0(event: Any, promise: Promise?) { + public final func triggerUserOutboundEvent0(event: Any, promise: EventLoopPromise?) { promise?.succeed(result: ()) } @@ -178,7 +178,7 @@ class EmbeddedChannelCore : ChannelCore { public class EmbeddedChannel : Channel { public var isActive: Bool { return channelcore.isActive } - public var closeFuture: Future { return channelcore.closePromise.futureResult } + public var closeFuture: EventLoopFuture { return channelcore.closePromise.futureResult } private lazy var channelcore: EmbeddedChannelCore = EmbeddedChannelCore(pipeline: self._pipeline) diff --git a/Sources/NIO/EventLoop.swift b/Sources/NIO/EventLoop.swift index 56cab2f54..d153c8136 100644 --- a/Sources/NIO/EventLoop.swift +++ b/Sources/NIO/EventLoop.swift @@ -23,10 +23,10 @@ import SwiftPriorityQueue #endif public struct Scheduled { - private let promise: Promise + private let promise: EventLoopPromise private let cancellationTask: () -> () - init(promise: Promise, cancellationTask: @escaping () -> ()) { + init(promise: EventLoopPromise, cancellationTask: @escaping () -> ()) { self.promise = promise promise.futureResult.whenFailure(callback: { error in guard let err = error as? EventLoopError else { @@ -43,7 +43,7 @@ public struct Scheduled { promise.fail(error: EventLoopError.cancelled) } - public var futureResult: Future { + public var futureResult: EventLoopFuture { return promise.futureResult } } @@ -51,11 +51,11 @@ public struct Scheduled { public protocol EventLoop: EventLoopGroup { var inEventLoop: Bool { get } func execute(task: @escaping () -> ()) - func submit(task: @escaping () throws-> (T)) -> Future + func submit(task: @escaping () throws-> (T)) -> EventLoopFuture func scheduleTask(in: TimeAmount, _ task: @escaping () throws-> (T)) -> Scheduled - func newPromise() -> Promise - func newFailedFuture(error: Error) -> Future - func newSucceedFuture(result: T) -> Future + func newPromise() -> EventLoopPromise + func newFailedFuture(error: Error) -> EventLoopFuture + func newSucceedFuture(result: T) -> EventLoopFuture } public struct TimeAmount { @@ -104,8 +104,8 @@ extension TimeAmount: Comparable { } extension EventLoop { - public func submit(task: @escaping () throws-> (T)) -> Future { - let promise: Promise = newPromise() + public func submit(task: @escaping () throws-> (T)) -> EventLoopFuture { + let promise: EventLoopPromise = newPromise() execute(task: {() -> () in do { @@ -118,16 +118,16 @@ extension EventLoop { return promise.futureResult } - public func newPromise() -> Promise { - return Promise(eventLoop: self, checkForPossibleDeadlock: true) + public func newPromise() -> EventLoopPromise { + return EventLoopPromise(eventLoop: self, checkForPossibleDeadlock: true) } - public func newFailedFuture(error: Error) -> Future { - return Future(eventLoop: self, checkForPossibleDeadlock: true, error: error) + public func newFailedFuture(error: Error) -> EventLoopFuture { + return EventLoopFuture(eventLoop: self, checkForPossibleDeadlock: true, error: error) } - public func newSucceedFuture(result: T) -> Future { - return Future(eventLoop: self, checkForPossibleDeadlock: true, result: result) + public func newSucceedFuture(result: T) -> EventLoopFuture { + return EventLoopFuture(eventLoop: self, checkForPossibleDeadlock: true, result: result) } public func next() -> EventLoop { @@ -230,7 +230,7 @@ internal final class SelectableEventLoop : EventLoop { } public func scheduleTask(in: TimeAmount, _ task: @escaping () throws-> (T)) -> Scheduled { - let promise: Promise = newPromise() + let promise: EventLoopPromise = newPromise() let task = ScheduledTask({ do { promise.succeed(result: try task()) @@ -421,8 +421,8 @@ internal final class SelectableEventLoop : EventLoop { } } - public func closeGently() -> Future { - func closeGently0() -> Future { + public func closeGently() -> EventLoopFuture { + func closeGently0() -> EventLoopFuture { guard self.lifecycleState == .open else { return self.newFailedFuture(error: ChannelError.alreadyClosed) } @@ -432,7 +432,7 @@ internal final class SelectableEventLoop : EventLoop { if self.inEventLoop { return closeGently0() } else { - let p: Promise = self.newPromise() + let p: EventLoopPromise = self.newPromise() _ = self.submit { closeGently0().cascade(promise: p) } @@ -469,7 +469,7 @@ public protocol EventLoopGroup { func next() -> EventLoop /// Shuts down the eventloop gracefully. This function is clearly an outlier in that it uses a completion - /// callback instead of a Future. The reason for that is that NIO's Futures will call back on an event loop. + /// callback instead of an EventLoopFuture. The reason for that is that NIO's EventLoopFutures will call back on an event loop. /// The virtue of this function is to shut the event loop down. To work around that we call back on a DispatchQueue /// instead. func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) @@ -559,7 +559,7 @@ final public class MultiThreadedEventLoopGroup : EventLoopGroup { } public func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) { - // This method cannot perform its final cleanup using Futures, because it requires that all + // This method cannot perform its final cleanup using EventLoopFutures, because it requires that all // our event loops still be alive, and they may not be. Instead, we use Dispatch to manage // our shutdown signaling, and then do our cleanup once the DispatchQueue is empty. let g = DispatchGroup() diff --git a/Sources/NIO/Future.swift b/Sources/NIO/EventLoopFuture.swift similarity index 65% rename from Sources/NIO/Future.swift rename to Sources/NIO/EventLoopFuture.swift index 4bc805e6d..21e204f2d 100644 --- a/Sources/NIO/Future.swift +++ b/Sources/NIO/EventLoopFuture.swift @@ -15,11 +15,7 @@ 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)`. - */ -public enum FutureValue { +public enum EventLoopFutureValue { case success(T) case failure(Error) } @@ -115,11 +111,11 @@ 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: + This is the provider API for EventLoopFuture. If you want to return an unfulfilled EventLoopFuture -- 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() + func someAsyncOperation(args) -> EventLoopFuture { + let promise = EventLoopPromise() someAsyncOperationWithACallback(args) { result -> () in // when finished... promise.succeed(result) @@ -134,36 +130,36 @@ private struct CallbackList: ExpressibleByArrayLiteral { 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:)` + * If you have an EventLoopFuture 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 `EventLoopFuture.async()` + * If you already have a value and need an EventLoopFuture<> object to plug into some other API, create an already-resolved object with `EventLoopFuture(result:)` */ -public struct Promise { - public let futureResult: Future +public struct EventLoopPromise { + public let futureResult: EventLoopFuture /** Public initializer */ init(eventLoop: EventLoop, checkForPossibleDeadlock: Bool) { - futureResult = Future(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock) + futureResult = EventLoopFuture(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock) } /** - Deliver a successful result to the associated `Future` object. + Deliver a successful result to the associated `EventLoopFuture` object. */ public func succeed(result: T) { _resolve(value: .success(result)) } /** - Deliver an error to the associated `Future` object. + Deliver an error to the associated `EventLoopFuture` object. */ public func fail(error: Error) { _resolve(value: .failure(error)) } /** Internal only! */ - private func _resolve(value: FutureValue) { + private func _resolve(value: EventLoopFutureValue) { if futureResult.eventLoop.inEventLoop { _setValue(value: value)._run() } else { @@ -174,7 +170,7 @@ public struct Promise { } /** Internal only! */ - fileprivate func _setValue(value: FutureValue) -> CallbackList { + fileprivate func _setValue(value: EventLoopFutureValue) -> CallbackList { return futureResult._setValue(value: value) } } @@ -182,13 +178,13 @@ public struct Promise { /** 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. + Functions that promise to do work asynchronously can return an EventLoopFuture. 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: + The provider of a `EventLoopFuture` can create and return a placeholder object before the actual result is available. For example: ``` - func getNetworkData(args) -> Future { - let promise = Promise() + func getNetworkData(args) -> EventLoopFuture { + let promise = EventLoopPromise() queue.async { . . . do some work . . . promise.succeed(response) @@ -199,13 +195,13 @@ public struct Promise { } ``` - 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. + 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 EventLoopFuture object, Python Deferred, and Javascript EventLoopPromises. - 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: + 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 EventLoopFuture that was returned earlier: ``` - func getNetworkData(args) -> Future { - return Future.async(queue) { + func getNetworkData(args) -> EventLoopFuture { + return EventLoopFuture.async(queue) { . . . do some work . . . return response // Return the NetworkResponse object . . . if it fails . . . @@ -214,13 +210,13 @@ public struct Promise { } ``` - 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. + If you receive a `EventLoopFuture` 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 EventLoopFuture immediately that will receive the return value from your function. ``` let networkData = getNetworkData(args) // When network data is received, convert it - let processedResult: Future + let processedResult: EventLoopFuture = networkData.then { (n: NetworkResponse) -> Processed in ... parse network data .... @@ -228,15 +224,15 @@ public struct Promise { } ``` - 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: + The function provided to `then()` can also return a new EventLoopFuture 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 + let databaseResult: EventLoopFuture = processedResult.then { - (p: Processed) -> Future in - return Future.async(queue) { + (p: Processed) -> EventLoopFuture in + return EventLoopFuture.async(queue) { . . . perform DB operation . . . return result } @@ -245,20 +241,20 @@ public struct Promise { 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. + EventLoopFuture 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.) + At any point in the EventLoopFuture 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. + EventLoopFuture objects are typically obtained by: + * Using `EventLoopFuture.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 + * Initializing an EventLoopFuture 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. + TODO: Provide a tracing facility. It would be nice to be able to set '.debugTrace = true' on any EventLoopFuture or EventLoopPromise and have every subsequent chained EventLoopFuture report the success result or failure error. That would simplify some debugging scenarios. */ -public final class Future { - fileprivate var value: FutureValue? { +public final class EventLoopFuture { + fileprivate var value: EventLoopFutureValue? { didSet { _fulfilled.store(true) } @@ -271,11 +267,11 @@ public final class Future { return _fulfilled.load() } - /// 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. + /// Callbacks that should be run when this EventLoopFuture<> gets a value. + /// These callbacks may give values to other EventLoopFutures; if that happens, they return any callbacks from those EventLoopFutures so that we can run the entire chain from the top without recursing. fileprivate var callbacks: CallbackList = CallbackList() - private init(eventLoop: EventLoop, checkForPossibleDeadlock: Bool, value: FutureValue?, file: StaticString = #file, line: Int = #line) { + private init(eventLoop: EventLoop, checkForPossibleDeadlock: Bool, value: EventLoopFutureValue?, file: StaticString = #file, line: Int = #line) { self.eventLoop = eventLoop self.checkForPossibleDeadlock = checkForPossibleDeadlock self.value = value @@ -287,38 +283,38 @@ public final class Future { self.init(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock, value: nil, file: file, line: line) } - /// A Future that has already succeeded + /// A EventLoopFuture that has already succeeded convenience init(eventLoop: EventLoop, checkForPossibleDeadlock: Bool, result: T, file: StaticString = #file, line: Int = #line) { self.init(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock, value: .success(result), file: file, line: line) } - /// A Future that has already failed + /// A EventLoopFuture that has already failed convenience init(eventLoop: EventLoop, checkForPossibleDeadlock: Bool, error: Error, file: StaticString = #file, line: Int = #line) { self.init(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock, value: .failure(error), file: file, line: line) } deinit { - precondition(fulfilled, "leaking an unfulfilled Promise") + precondition(fulfilled, "leaking an unfulfilled EventLoopPromise") } } -public func ==(lhs: Future, rhs: Future) -> Bool { +public func ==(lhs: EventLoopFuture, rhs: EventLoopFuture) -> Bool { return lhs === rhs } /** 'then' implementations. This is really the key of the entire system. */ -extension Future { +extension EventLoopFuture { /** - When the current `Future` is fulfilled, run the provided callback, which will provide a new `Future`. + When the current `EventLoopFuture` is fulfilled, run the provided callback, which will provide a new `EventLoopFuture`. - 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 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 `EventLoopFuture` 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: + This works well when you have APIs that already know how to return EventLoopFutures. 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 + let d2 = d1.then { t -> EventLoopFuture in . . . something with t . . . return netWorkRequest(args) } @@ -326,16 +322,16 @@ extension Future { NSLog("Result of second request: \(u)") } - Technical trivia: `Future<>` is a monad, `then()` is the monadic bind operation. + Technical trivia: `EventLoopFuture<>` is a monad, `then()` is the monadic bind operation. - Note: In a sense, the `Future` is returned before it's created. + Note: In a sense, the `EventLoopFuture` is returned before it's created. - - parameter callback: Function that will receive the value of this Future and return a new Future + - parameter callback: Function that will receive the value of this EventLoopFuture and return a new EventLoopFuture - returns: A future that will receive the eventual value */ - public func then(callback: @escaping (T) throws -> Future) -> Future { - let next = Promise(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock) + public func then(callback: @escaping (T) throws -> EventLoopFuture) -> EventLoopFuture { + let next = EventLoopPromise(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock) _whenComplete { switch self.value! { case .success(let t): @@ -374,33 +370,33 @@ extension Future { 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. + 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 `EventLoopFuture<>` 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(eventLoop: self.eventLoop, checkForPossibleDeadlock: self.checkForPossibleDeadlock, result: try callback($0)) } + public func then(callback: @escaping (T) throws -> (U)) -> EventLoopFuture { + return then { return EventLoopFuture(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. + This returns a new EventLoopFuture<> of the same type. If the original EventLoopFuture<> succeeds, so will the new one. But if the original EventLoopFuture<> fails, the callback will be executed with the error value. The callback can either: + * Throw an error, in which case the chained EventLoopFuture<> will fail with that error. The thrown error can be the same or different. + * Return a new result, in which case the chained EventLoopFuture<> 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 d: EventLoopFuture 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 supports the same overloads as `then()`, including allowing the callback to return a `EventLoopFuture`. */ - public func thenIfError(callback: @escaping (Error) throws -> Future) -> Future { - let next = Promise(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock) + public func thenIfError(callback: @escaping (Error) throws -> EventLoopFuture) -> EventLoopFuture { + let next = EventLoopPromise(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock) _whenComplete { switch self.value! { case .success(let t): @@ -419,8 +415,8 @@ extension Future { return next.futureResult } - public func thenIfError(callback: @escaping (Error) throws -> T) -> Future { - return thenIfError { return Future(eventLoop: self.eventLoop, checkForPossibleDeadlock: self.checkForPossibleDeadlock, result: try callback($0)) } + public func thenIfError(callback: @escaping (Error) throws -> T) -> EventLoopFuture { + return thenIfError { return EventLoopFuture(eventLoop: self.eventLoop, checkForPossibleDeadlock: self.checkForPossibleDeadlock, result: try callback($0)) } } @@ -463,7 +459,7 @@ extension Future { } } - public func whenComplete(callback: @escaping (FutureValue) -> ()) { + public func whenComplete(callback: @escaping (EventLoopFutureValue) -> ()) { _whenComplete { callback(self.value!) return CallbackList() @@ -472,7 +468,7 @@ extension Future { /// Internal: Set the value and return a list of callbacks that should be invoked as a result. - fileprivate func _setValue(value: FutureValue) -> CallbackList { + fileprivate func _setValue(value: EventLoopFutureValue) -> CallbackList { assert(eventLoop.inEventLoop) if self.value == nil { self.value = value @@ -485,15 +481,15 @@ extension Future { } -extension Future { +extension EventLoopFuture { /** - * Return a new Future that succeeds when this "and" another - * provided Future both succeed. It then provides the pair - * of results. If either one fails, the combined Future will fail. + * Return a new EventLoopFuture that succeeds when this "and" another + * provided EventLoopFuture both succeed. It then provides the pair + * of results. If either one fails, the combined EventLoopFuture will fail. */ - public func and(_ other: Future) -> Future<(T,U)> { + public func and(_ other: EventLoopFuture) -> EventLoopFuture<(T,U)> { let andlock = Lock() - let promise = Promise<(T,U)>(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock) + let promise = EventLoopPromise<(T,U)>(eventLoop: eventLoop, checkForPossibleDeadlock: checkForPossibleDeadlock) var tvalue: T? var uvalue: U? @@ -535,18 +531,18 @@ extension Future { } /** - * Return a new Future that contains this "and" another value. + * Return a new EventLoopFuture 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(eventLoop: self.eventLoop, checkForPossibleDeadlock: self.checkForPossibleDeadlock, result:result)) + public func and(result: U) -> EventLoopFuture<(T,U)> { + return and(EventLoopFuture(eventLoop: self.eventLoop, checkForPossibleDeadlock: self.checkForPossibleDeadlock, result:result)) } } -extension Future { +extension EventLoopFuture { - public func cascade(promise: Promise) { + public func cascade(promise: EventLoopPromise) { whenComplete(callback: { v in switch v { case .failure(let err): @@ -557,20 +553,20 @@ extension Future { }) } - public func cascadeFailure(promise: Promise) { + public func cascadeFailure(promise: EventLoopPromise) { self.whenFailure(callback: { err in promise.fail(error: err) }) } } -extension Future { +extension EventLoopFuture { public func wait() throws -> T { if self.checkForPossibleDeadlock { precondition(!eventLoop.inEventLoop, "wait() must not be called when on the EventLoop") } - var v: FutureValue ? = nil + var v: EventLoopFutureValue ? = nil let lock = ConditionLock(value: 0) _whenComplete { () -> CallbackList in lock.lock() @@ -590,15 +586,15 @@ extension Future { } } -extension Future { - public static func andAll(_ futures: [Future], eventLoop: EventLoop) -> Future { - let p0: Promise = eventLoop.newPromise() +extension EventLoopFuture { + public static func andAll(_ futures: [EventLoopFuture], eventLoop: EventLoop) -> EventLoopFuture { + let p0: EventLoopPromise = eventLoop.newPromise() guard futures.count > 0 else { p0.succeed(result: ()) return p0.futureResult } - let fn: Future = futures.reduce(p0.futureResult, { (f1: Future, f2: Future) in f1.and(f2).then(callback: { _ in return () }) }) + let fn: EventLoopFuture = futures.reduce(p0.futureResult, { (f1: EventLoopFuture, f2: EventLoopFuture) in f1.and(f2).then(callback: { _ in return () }) }) p0.succeed(result: ()) return fn } diff --git a/Sources/NIO/Selector.swift b/Sources/NIO/Selector.swift index f6d23efc6..d9f85692f 100644 --- a/Sources/NIO/Selector.swift +++ b/Sources/NIO/Selector.swift @@ -433,14 +433,14 @@ struct SelectorEvent { } internal extension Selector where R == NIORegistration { - internal func closeGently(eventLoop: EventLoop) -> Future { - let p0: Promise = eventLoop.newPromise() + internal func closeGently(eventLoop: EventLoop) -> EventLoopFuture { + let p0: EventLoopPromise = eventLoop.newPromise() guard self.lifecycleState == .open else { p0.fail(error: IOError(errnoCode: EBADF, reason: "can't close selector gently as it's \(self.lifecycleState).")) return p0.futureResult } - let futures: [Future] = self.registrations.map { (_, reg: NIORegistration) -> Future in + let futures: [EventLoopFuture] = self.registrations.map { (_, reg: NIORegistration) -> EventLoopFuture in switch reg { case .serverSocketChannel(let chan, _): return chan.close() @@ -455,7 +455,7 @@ internal extension Selector where R == NIORegistration { } p0.succeed(result: ()) - return Future.andAll(futures, eventLoop: eventLoop) + return EventLoopFuture.andAll(futures, eventLoop: eventLoop) } } diff --git a/Sources/NIOHTTP1/HTTPEncoder.swift b/Sources/NIOHTTP1/HTTPEncoder.swift index 564a1e01d..194ef5329 100644 --- a/Sources/NIOHTTP1/HTTPEncoder.swift +++ b/Sources/NIOHTTP1/HTTPEncoder.swift @@ -15,13 +15,13 @@ import NIO import Foundation // TODO(JW): investigate linker errors if this is missing -private func writeChunk(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHandlerContext, isChunked: Bool, chunk: IOData, promise: Promise?) { - let (mW1, mW2, mW3): (Promise<()>?, Promise<()>?, Promise<()>?) +private func writeChunk(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHandlerContext, isChunked: Bool, chunk: IOData, promise: EventLoopPromise?) { + let (mW1, mW2, mW3): (EventLoopPromise<()>?, EventLoopPromise<()>?, EventLoopPromise<()>?) switch (isChunked, promise) { case (true, .some(let p)): /* chunked encoding and the user's interested: we need three promises and need to cascade into the users promise */ - let (w1, w2, w3) = (ctx.eventLoop.newPromise() as Promise<()>, ctx.eventLoop.newPromise() as Promise<()>, ctx.eventLoop.newPromise() as Promise<()>) + let (w1, w2, w3) = (ctx.eventLoop.newPromise() as EventLoopPromise<()>, ctx.eventLoop.newPromise() as EventLoopPromise<()>, ctx.eventLoop.newPromise() as EventLoopPromise<()>) w1.futureResult.and(w2.futureResult).and(w3.futureResult).then { _ in () }.cascade(promise: p) (mW1, mW2, mW3) = (w1, w2, w3) case (false, .some(let p)): @@ -52,7 +52,7 @@ private func writeChunk(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHandler } } -private func writeTrailers(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHandlerContext, isChunked: Bool, trailers: HTTPHeaders?, promise: Promise?) { +private func writeTrailers(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHandlerContext, isChunked: Bool, trailers: HTTPHeaders?, promise: EventLoopPromise?) { switch (isChunked, promise) { case (true, let p): var buffer: ByteBuffer @@ -75,7 +75,7 @@ private func writeTrailers(wrapOutboundOut: (IOData) -> NIOAny, ctx: ChannelHand } } -private func writeHead(wrapOutboundOut: (IOData) -> NIOAny, writeStartLine: (inout ByteBuffer) -> (), ctx: ChannelHandlerContext, headers: HTTPHeaders, promise: Promise?) { +private func writeHead(wrapOutboundOut: (IOData) -> NIOAny, writeStartLine: (inout ByteBuffer) -> (), ctx: ChannelHandlerContext, headers: HTTPHeaders, promise: EventLoopPromise?) { var buffer = ctx.channel!.allocator.buffer(capacity: 256) writeStartLine(&buffer) @@ -113,7 +113,7 @@ public final class HTTPRequestEncoder : ChannelOutboundHandler { public init () { } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: Promise?) { + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { switch self.tryUnwrapOutboundIn(data) { case .some(.head(var request)): sanitizeTransportHeaders(mayHaveBody: request.method.mayHaveRequestBody, headers: &request.headers, version: request.version) @@ -146,7 +146,7 @@ public final class HTTPResponseEncoder : ChannelOutboundHandler { public init () { } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: Promise?) { + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { switch self.tryUnwrapOutboundIn(data) { case .some(.head(var response)): sanitizeTransportHeaders(mayHaveBody: response.status.mayHaveResponseBody, headers: &response.headers, version: response.version) diff --git a/Sources/NIOHTTP1/HTTPUpgradeHandler.swift b/Sources/NIOHTTP1/HTTPUpgradeHandler.swift index 65341f74c..7ac78dd75 100644 --- a/Sources/NIOHTTP1/HTTPUpgradeHandler.swift +++ b/Sources/NIOHTTP1/HTTPUpgradeHandler.swift @@ -143,7 +143,7 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler { } /// Sends the 101 Switching Protocols response for the pipeline. - private func sendUpgradeResponse(ctx: ChannelHandlerContext, upgradeRequest: HTTPRequestHead, responseHeaders: HTTPHeaders) -> Future { + private func sendUpgradeResponse(ctx: ChannelHandlerContext, upgradeRequest: HTTPRequestHead, responseHeaders: HTTPHeaders) -> EventLoopFuture { var response = HTTPResponseHead(version: HTTPVersion(major: 1, minor: 1), status: .switchingProtocols) response.headers = responseHeaders return ctx.writeAndFlush(data: wrapOutboundOut(HTTPServerResponsePart.head(response))) diff --git a/Sources/NIOHTTP1Server/main.swift b/Sources/NIOHTTP1Server/main.swift index 0b7cba925..09535e474 100644 --- a/Sources/NIOHTTP1Server/main.swift +++ b/Sources/NIOHTTP1Server/main.swift @@ -41,7 +41,7 @@ private final class HTTPHandler: ChannelInboundHandler { private var continuousCount: Int = 0 private var handler: ((ChannelHandlerContext, HTTPServerRequestPart) -> Void)? = nil - private var handlerFuture: Future<()>? + private var handlerFuture: EventLoopFuture<()>? public init(htdocsPath: String) { self.htdocsPath = htdocsPath diff --git a/Sources/NIOOpenSSL/OpenSSLHandler.swift b/Sources/NIOOpenSSL/OpenSSLHandler.swift index 2463c9e60..f8b968789 100644 --- a/Sources/NIOOpenSSL/OpenSSLHandler.swift +++ b/Sources/NIOOpenSSL/OpenSSLHandler.swift @@ -42,7 +42,7 @@ public class OpenSSLHandler : ChannelInboundHandler, ChannelOutboundHandler { private var state: ConnectionState = .idle private var connection: SSLConnection private var bufferedWrites: MarkedCircularBuffer - private var closePromise: Promise? + private var closePromise: EventLoopPromise? private var didDeliverData: Bool = false private let expectedHostname: String? @@ -122,16 +122,16 @@ public class OpenSSLHandler : ChannelInboundHandler, ChannelOutboundHandler { } } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: Promise?) { + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { bufferWrite(data: unwrapOutboundIn(data), promise: promise) } - public func flush(ctx: ChannelHandlerContext, promise: Promise?) { + public func flush(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { bufferFlush(promise: promise) doUnbufferWrites(ctx: ctx) } - public func close(ctx: ChannelHandlerContext, promise: Promise?) { + public func close(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { switch state { case .closing: // We're in the process of TLS shutdown, so let's let that happen. However, @@ -235,7 +235,7 @@ public class OpenSSLHandler : ChannelInboundHandler, ChannelOutboundHandler { } } - private func writeDataToNetwork(ctx: ChannelHandlerContext, promise: Promise?) { + private func writeDataToNetwork(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { // There may be no data to write, in which case we can just exit early. guard let dataToWrite = connection.getDataForNetwork(allocator: ctx.channel!.allocator) else { promise?.succeed(result: ()) @@ -288,22 +288,22 @@ public class OpenSSLHandler : ChannelInboundHandler, ChannelOutboundHandler { extension OpenSSLHandler { private enum BufferedEvent { case write(BufferedWrite) - case flush(Promise?) + case flush(EventLoopPromise?) } - private typealias BufferedWrite = (data: ByteBuffer, promise: Promise?) + private typealias BufferedWrite = (data: ByteBuffer, promise: EventLoopPromise?) - private func bufferWrite(data: ByteBuffer, promise: Promise?) { + private func bufferWrite(data: ByteBuffer, promise: EventLoopPromise?) { bufferedWrites.append(.write((data: data, promise: promise))) } - private func bufferFlush(promise: Promise?) { + private func bufferFlush(promise: EventLoopPromise?) { bufferedWrites.append(.flush(promise)) bufferedWrites.mark() } private func discardBufferedWrites(reason: Error) { while bufferedWrites.count > 0 { - let promise: Promise? + let promise: EventLoopPromise? switch bufferedWrites.removeFirst() { case .write(_, let p): promise = p @@ -324,10 +324,10 @@ extension OpenSSLHandler { // These are some annoying variables we use to persist state across invocations of // our closures. A better version of this code might be able to simplify this somewhat. var writeCount = 0 - var promises: [Promise] = [] + var promises: [EventLoopPromise] = [] /// Given a byte buffer to encode, passes it to OpenSSL and handles the result. - func encodeWrite(buf: inout ByteBuffer, promise: Promise?) throws -> Bool { + func encodeWrite(buf: inout ByteBuffer, promise: EventLoopPromise?) throws -> Bool { let result = connection.writeDataToNetwork(&buf) switch result { @@ -348,10 +348,10 @@ extension OpenSSLHandler { } /// Given a flush request, grabs the data from OpenSSL and flushes it to the network. - func flushData(userFlushPromise: Promise?) throws -> Bool { + func flushData(userFlushPromise: EventLoopPromise?) throws -> Bool { // This is a flush. We can go ahead and flush now. if let promise = userFlushPromise { promises.append(promise) } - let ourPromise: Promise = ctx.eventLoop.newPromise() + let ourPromise: EventLoopPromise = ctx.eventLoop.newPromise() promises.forEach { ourPromise.futureResult.cascade(promise: $0) } writeDataToNetwork(ctx: ctx, promise: ourPromise) return true diff --git a/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift b/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift index 98915ef9c..372dc87d4 100644 --- a/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift +++ b/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift @@ -35,11 +35,11 @@ public class ApplicationProtocolNegotiationHandler: ChannelInboundHandler { public typealias InboundOut = Any public typealias InboundUserEventIn = TLSUserEvent - private let completionHandler: (ALPNResult) -> Future + private let completionHandler: (ALPNResult) -> EventLoopFuture private var waitingForUser: Bool private var eventBuffer: [NIOAny] - public init(alpnCompleteHandler: @escaping (ALPNResult) -> Future) { + public init(alpnCompleteHandler: @escaping (ALPNResult) -> EventLoopFuture) { self.completionHandler = alpnCompleteHandler self.waitingForUser = false self.eventBuffer = [] diff --git a/Sources/NIOTLS/SNIHandler.swift b/Sources/NIOTLS/SNIHandler.swift index e271173a6..6bfb3ab20 100644 --- a/Sources/NIOTLS/SNIHandler.swift +++ b/Sources/NIOTLS/SNIHandler.swift @@ -92,10 +92,10 @@ public class SniHandler: ByteToMessageDecoder { public typealias InboundIn = ByteBuffer public typealias InboundOut = ByteBuffer - private let completionHandler: (SniResult) -> Future + private let completionHandler: (SniResult) -> EventLoopFuture private var waitingForUser: Bool - public init(sniCompleteHandler: @escaping (SniResult) -> Future) { + public init(sniCompleteHandler: @escaping (SniResult) -> EventLoopFuture) { self.cumulationBuffer = nil self.completionHandler = sniCompleteHandler self.waitingForUser = false diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index 35883364b..4ac7cdd75 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -40,9 +40,9 @@ import XCTest testCase(ClientSNITests.allTests), testCase(EchoServerClientTest.allTests), testCase(EmbeddedChannelTest.allTests), + testCase(EventLoopFutureTest.allTests), testCase(EventLoopTest.allTests), testCase(FileRegionTest.allTests), - testCase(FutureTest.allTests), testCase(HTTPHeadersTest.allTests), testCase(HTTPRequestEncoderTests.allTests), testCase(HTTPResponseEncoderTests.allTests), diff --git a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift index a23a2f914..773919ac6 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift @@ -18,7 +18,7 @@ import NIO import Dispatch @testable import NIOHTTP1 -private func assertSuccess(_ f: FutureValue<()>, file: StaticString = #file, line: Int = #line) { +private func assertSuccess(_ f: EventLoopFutureValue<()>, file: StaticString = #file, line: Int = #line) { switch f { case .success(()): () diff --git a/Tests/NIOHTTP1Tests/HTTPUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPUpgradeTests.swift index 00ff46f11..b7517d819 100644 --- a/Tests/NIOHTTP1Tests/HTTPUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPUpgradeTests.swift @@ -34,7 +34,7 @@ private func serverHTTPChannel(group: EventLoopGroup, handlers: [ChannelHandler] channel.pipeline.add(handler: HTTPRequestDecoder()).then { channel.pipeline.add(handler: HTTPResponseEncoder()).then { let futureResults = handlers.map { channel.pipeline.add(handler: $0) } - return Future.andAll(futureResults, eventLoop: channel.eventLoop) + return EventLoopFuture.andAll(futureResults, eventLoop: channel.eventLoop) } } })).bind(to: "127.0.0.1", on: 0).wait() @@ -262,7 +262,7 @@ class HTTPUpgradeTestCase: XCTestCase { try! group.syncShutdownGracefully() } - let completePromise: Promise = group.next().newPromise() + let completePromise: EventLoopPromise = group.next().newPromise() let clientHandler = ArrayAccumulationHandler { buffers in let resultString = buffers.map { $0.string(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") assertResponseIs(response: resultString, @@ -367,7 +367,7 @@ class HTTPUpgradeTestCase: XCTestCase { try! group.syncShutdownGracefully() } - let completePromise: Promise = group.next().newPromise() + let completePromise: EventLoopPromise = group.next().newPromise() let clientHandler = ArrayAccumulationHandler { buffers in let resultString = buffers.map { $0.string(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") assertResponseIs(response: resultString, @@ -411,7 +411,7 @@ class HTTPUpgradeTestCase: XCTestCase { try! group.syncShutdownGracefully() } - let completePromise: Promise = group.next().newPromise() + let completePromise: EventLoopPromise = group.next().newPromise() let clientHandler = ArrayAccumulationHandler { buffers in let resultString = buffers.map { $0.string(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") assertResponseIs(response: resultString, @@ -472,7 +472,7 @@ class HTTPUpgradeTestCase: XCTestCase { try! group.syncShutdownGracefully() } - let completePromise: Promise = group.next().newPromise() + let completePromise: EventLoopPromise = group.next().newPromise() let clientHandler = ArrayAccumulationHandler { buffers in let resultString = buffers.map { $0.string(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") assertResponseIs(response: resultString, diff --git a/Tests/NIOOpenSSLTests/ClientSNITests.swift b/Tests/NIOOpenSSLTests/ClientSNITests.swift index f339b9d89..98ea56b05 100644 --- a/Tests/NIOOpenSSLTests/ClientSNITests.swift +++ b/Tests/NIOOpenSSLTests/ClientSNITests.swift @@ -45,7 +45,7 @@ class ClientSNITests: XCTestCase { try! group.syncShutdownGracefully() } - let sniPromise: Promise = group.next().newPromise() + let sniPromise: EventLoopPromise = group.next().newPromise() let sniHandler = SniHandler { sniPromise.succeed(result: $0) return group.next().newSucceedFuture(result: ()) diff --git a/Tests/NIOOpenSSLTests/OpenSSLALPNTest.swift b/Tests/NIOOpenSSLTests/OpenSSLALPNTest.swift index 121b361fc..359080ea1 100644 --- a/Tests/NIOOpenSSLTests/OpenSSLALPNTest.swift +++ b/Tests/NIOOpenSSLTests/OpenSSLALPNTest.swift @@ -45,7 +45,7 @@ class OpenSSLALPNTest: XCTestCase { try! group.syncShutdownGracefully() } - let completionPromise: Promise = group.next().newPromise() + let completionPromise: EventLoopPromise = group.next().newPromise() let serverHandler = EventRecorderHandler() let serverChannel = try serverTLSChannel(withContext: serverContext, diff --git a/Tests/NIOOpenSSLTests/OpenSSLIntegrationTest.swift b/Tests/NIOOpenSSLTests/OpenSSLIntegrationTest.swift index 1a6c0067c..562a4f57c 100644 --- a/Tests/NIOOpenSSLTests/OpenSSLIntegrationTest.swift +++ b/Tests/NIOOpenSSLTests/OpenSSLIntegrationTest.swift @@ -40,10 +40,10 @@ internal final class PromiseOnReadHandler: ChannelInboundHandler { public typealias OutboundOut = ByteBuffer public typealias InboundUserEventIn = TLSUserEvent - private let promise: Promise + private let promise: EventLoopPromise private var data: NIOAny? = nil - init(promise: Promise) { + init(promise: EventLoopPromise) { self.promise = promise } @@ -64,7 +64,7 @@ private final class WriteCountingHandler: ChannelOutboundHandler { public var writeCount = 0 - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: Promise?) { + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { writeCount += 1 ctx.write(data: data, promise: promise) } @@ -153,9 +153,9 @@ public final class EventRecorderHandler: ChannelInboundHandler wh private class ChannelActiveWaiter: ChannelInboundHandler { public typealias InboundIn = Any - private var activePromise: Promise + private var activePromise: EventLoopPromise - public init(promise: Promise) { + public init(promise: EventLoopPromise) { activePromise = promise } @@ -177,10 +177,10 @@ internal func serverTLSChannel(withContext: NIOOpenSSL.SSLContext, preHandlers: .option(option: ChannelOptions.Socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) .handler(childHandler: ChannelInitializer(initChannel: { channel in let results = preHandlers.map { channel.pipeline.add(handler: $0) } - return Future.andAll(results, eventLoop: results.first?.eventLoop ?? onGroup.next()).then { + return EventLoopFuture.andAll(results, eventLoop: results.first?.eventLoop ?? onGroup.next()).then { return channel.pipeline.add(handler: try! OpenSSLServerHandler(context: withContext)).then(callback: { v2 in let results = postHandlers.map { channel.pipeline.add(handler: $0) } - return Future.andAll(results, eventLoop: results.first?.eventLoop ?? onGroup.next()) + return EventLoopFuture.andAll(results, eventLoop: results.first?.eventLoop ?? onGroup.next()) }) } })).bind(to: "127.0.0.1", on: 0).wait() @@ -195,10 +195,10 @@ internal func clientTLSChannel(withContext: NIOOpenSSL.SSLContext, return try ClientBootstrap(group: onGroup) .handler(handler: ChannelInitializer(initChannel: { channel in let results = preHandlers.map { channel.pipeline.add(handler: $0) } - return Future.andAll(results, eventLoop: results.first?.eventLoop ?? onGroup.next()).then(callback: { v2 in + return EventLoopFuture.andAll(results, eventLoop: results.first?.eventLoop ?? onGroup.next()).then(callback: { v2 in return channel.pipeline.add(handler: try! OpenSSLClientHandler(context: withContext, serverHostname: serverHostname)).then(callback: { v2 in let results = postHandlers.map { channel.pipeline.add(handler: $0) } - return Future.andAll(results, eventLoop: results.first?.eventLoop ?? onGroup.next()) + return EventLoopFuture.andAll(results, eventLoop: results.first?.eventLoop ?? onGroup.next()) }) }) })).connect(to: connectingTo).wait() @@ -236,7 +236,7 @@ class OpenSSLIntegrationTest: XCTestCase { try! group.syncShutdownGracefully() } - let completionPromise: Promise = group.next().newPromise() + let completionPromise: EventLoopPromise = group.next().newPromise() let serverChannel = try serverTLSChannel(withContext: ctx, andHandlers: [SimpleEchoServer()], onGroup: group) defer { @@ -268,7 +268,7 @@ class OpenSSLIntegrationTest: XCTestCase { try! group.syncShutdownGracefully() } - let readComplete: Promise = group.next().newPromise() + let readComplete: EventLoopPromise = group.next().newPromise() let serverHandler: EventRecorderHandler = EventRecorderHandler() let serverChannel = try serverTLSChannel(withContext: ctx, andHandlers: [serverHandler, PromiseOnReadHandler(promise: readComplete)], @@ -315,7 +315,7 @@ class OpenSSLIntegrationTest: XCTestCase { try! group.syncShutdownGracefully() } - let readComplete: Promise = group.next().newPromise() + let readComplete: EventLoopPromise = group.next().newPromise() let serverHandler: EventRecorderHandler = EventRecorderHandler() let serverChannel = try serverTLSChannel(withContext: ctx, andHandlers: [serverHandler, PromiseOnReadHandler(promise: readComplete)], @@ -361,7 +361,7 @@ class OpenSSLIntegrationTest: XCTestCase { try! group.syncShutdownGracefully() } - let completionPromise: Promise = group.next().newPromise() + let completionPromise: EventLoopPromise = group.next().newPromise() let serverChannel = try serverTLSChannel(withContext: ctx, andHandlers: [SimpleEchoServer()], onGroup: group) defer { @@ -393,7 +393,7 @@ class OpenSSLIntegrationTest: XCTestCase { // To avoid the risk of the I/O loop actually closing the connection before we're done, we need to hijack the // I/O loop and issue all the closes on that thread. Otherwise, the channel will probably pull off the TLS shutdown // before we get to the third call to close(). - let promises: [Promise] = [group.next().newPromise(), group.next().newPromise(), group.next().newPromise()] + let promises: [EventLoopPromise] = [group.next().newPromise(), group.next().newPromise(), group.next().newPromise()] group.next().execute { for promise in promises { serverChannel.close(promise: promise) @@ -423,7 +423,7 @@ class OpenSSLIntegrationTest: XCTestCase { } let writeCounter = WriteCountingHandler() - let readPromise: Promise = group.next().newPromise() + let readPromise: EventLoopPromise = group.next().newPromise() let clientChannel = try clientTLSChannel(withContext: ctx, preHandlers: [writeCounter], postHandlers: [PromiseOnReadHandler(promise: readPromise)], @@ -483,7 +483,7 @@ class OpenSSLIntegrationTest: XCTestCase { var originalBuffer = clientChannel.allocator.buffer(capacity: 1) originalBuffer.write(string: "A") for index in 0..<5 { - let promise: Promise = group.next().newPromise() + let promise: EventLoopPromise = group.next().newPromise() promise.futureResult.whenComplete { result in switch result { case .success: @@ -496,7 +496,7 @@ class OpenSSLIntegrationTest: XCTestCase { clientChannel.write(data: NIOAny(originalBuffer), promise: promise) } - let flushPromise: Promise = group.next().newPromise() + let flushPromise: EventLoopPromise = group.next().newPromise() flushPromise.futureResult.whenComplete { result in switch result { case .success: @@ -519,7 +519,7 @@ class OpenSSLIntegrationTest: XCTestCase { try channel.connect(to: SocketAddress.unixDomainSocketAddress(path: "/tmp/doesntmatter")).wait() // Now call close. This should immediately close, satisfying the promise. - let closePromise: Promise = channel.eventLoop.newPromise() + let closePromise: EventLoopPromise = channel.eventLoop.newPromise() channel.close(promise: closePromise) XCTAssertTrue(closePromise.futureResult.fulfilled) @@ -542,7 +542,7 @@ class OpenSSLIntegrationTest: XCTestCase { } // Create a client channel without TLS in it, and connect it. - let readPromise: Promise = group.next().newPromise() + let readPromise: EventLoopPromise = group.next().newPromise() let promiseOnReadHandler = PromiseOnReadHandler(promise: readPromise) let clientChannel = try ClientBootstrap(group: group) .handler(handler: promiseOnReadHandler) @@ -599,7 +599,7 @@ class OpenSSLIntegrationTest: XCTestCase { var originalBuffer = clientChannel.allocator.buffer(capacity: 5) originalBuffer.write(string: "Hello") let writeFuture = clientChannel.writeAndFlush(data: NIOAny(originalBuffer)) - let errorsFuture: Future<[NIOOpenSSLError]> = writeFuture.thenIfError { _ in + let errorsFuture: EventLoopFuture<[NIOOpenSSLError]> = writeFuture.thenIfError { _ in // We're swallowing errors here, on purpose, because we'll definitely // hit them. return () diff --git a/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift index 64ccc9efb..4002070ce 100644 --- a/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift +++ b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift @@ -56,7 +56,7 @@ class ApplicationProtocolNegotiationHandlerTests: XCTestCase { private func negotiateTest(event: TLSUserEvent, expectedResult: ALPNResult) throws { let channel = EmbeddedChannel() let loop = channel.eventLoop as! EmbeddedEventLoop - let continuePromise: Promise = loop.newPromise() + let continuePromise: EventLoopPromise = loop.newPromise() let expectedResult: ALPNResult = .negotiated("h2") var called = false @@ -111,7 +111,7 @@ class ApplicationProtocolNegotiationHandlerTests: XCTestCase { func testBufferingWhileWaitingForFuture() throws { let channel = EmbeddedChannel() let loop = channel.eventLoop as! EmbeddedEventLoop - let continuePromise: Promise = loop.newPromise() + let continuePromise: EventLoopPromise = loop.newPromise() let handler = ApplicationProtocolNegotiationHandler { result in return continuePromise.futureResult @@ -140,7 +140,7 @@ class ApplicationProtocolNegotiationHandlerTests: XCTestCase { func testNothingBufferedDoesNotFireReadCompleted() throws { let channel = EmbeddedChannel() let loop = channel.eventLoop as! EmbeddedEventLoop - let continuePromise: Promise = loop.newPromise() + let continuePromise: EventLoopPromise = loop.newPromise() let handler = ApplicationProtocolNegotiationHandler { result in return continuePromise.futureResult @@ -165,7 +165,7 @@ class ApplicationProtocolNegotiationHandlerTests: XCTestCase { func testUnbufferingFiresReadCompleted() throws { let channel = EmbeddedChannel() let loop = channel.eventLoop as! EmbeddedEventLoop - let continuePromise: Promise = loop.newPromise() + let continuePromise: EventLoopPromise = loop.newPromise() let handler = ApplicationProtocolNegotiationHandler { result in return continuePromise.futureResult diff --git a/Tests/NIOTLSTests/SNIHandlerTests.swift b/Tests/NIOTLSTests/SNIHandlerTests.swift index c66656912..15f29a3f3 100644 --- a/Tests/NIOTLSTests/SNIHandlerTests.swift +++ b/Tests/NIOTLSTests/SNIHandlerTests.swift @@ -264,7 +264,7 @@ class SniHandlerTest: XCTestCase { var buffer = bufferForBase64String(string: clientHello) let channel = EmbeddedChannel() let loop = channel.eventLoop as! EmbeddedEventLoop - let continuePromise: Promise = loop.newPromise() + let continuePromise: EventLoopPromise = loop.newPromise() let handler = SniHandler { result in XCTAssertEqual(expectedResult, result) @@ -313,7 +313,7 @@ class SniHandlerTest: XCTestCase { let buffer = bufferForBase64String(string: clientHello) let channel = EmbeddedChannel() let loop = channel.eventLoop as! EmbeddedEventLoop - let continuePromise: Promise = loop.newPromise() + let continuePromise: EventLoopPromise = loop.newPromise() let handler = SniHandler { result in XCTAssertEqual(expectedResult, result) diff --git a/Tests/NIOTests/ChannelPipelineTest.swift b/Tests/NIOTests/ChannelPipelineTest.swift index 692d9c6a1..6ef637480 100644 --- a/Tests/NIOTests/ChannelPipelineTest.swift +++ b/Tests/NIOTests/ChannelPipelineTest.swift @@ -107,7 +107,7 @@ class ChannelPipelineTest: XCTestCase { self.fn = fn } - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: Promise?) { + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { do { ctx.write(data: self.wrapOutboundOut(try fn(self.unwrapOutboundIn(data))), promise: promise) } catch let err { @@ -124,7 +124,7 @@ class ChannelPipelineTest: XCTestCase { case CalledBind } - public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: Promise?) { + public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { promise!.fail(error: TestFailureError.CalledBind) } } diff --git a/Tests/NIOTests/ChannelTests.swift b/Tests/NIOTests/ChannelTests.swift index 3ee444f46..0399e71a7 100644 --- a/Tests/NIOTests/ChannelTests.swift +++ b/Tests/NIOTests/ChannelTests.swift @@ -95,7 +95,7 @@ public class ChannelTests: XCTestCase { try clientChannel.close().wait() // Wait for the close promises. These fire last. - try Future.andAll([clientChannel.closeFuture, serverAcceptedChannel!.closeFuture], eventLoop: group.next()).then { _ in + try EventLoopFuture.andAll([clientChannel.closeFuture, serverAcceptedChannel!.closeFuture], eventLoop: group.next()).then { _ in XCTAssertEqual(clientLifecycleHandler.currentState, .unregistered) XCTAssertEqual(serverLifecycleHandler.currentState, .unregistered) XCTAssertEqual(clientLifecycleHandler.stateHistory, [.unregistered, .inactive, .active, .inactive, .unregistered]) @@ -170,7 +170,7 @@ public class ChannelTests: XCTestCase { try! group.syncShutdownGracefully() } - let childChannelPromise: Promise = group.next().newPromise() + let childChannelPromise: EventLoopPromise = group.next().newPromise() let serverChannel = try ServerBootstrap(group: group) .option(option: ChannelOptions.Socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) .handler(childHandler: ChannelInitializer(initChannel: { channel in diff --git a/Tests/NIOTests/EchoServerClientTest.swift b/Tests/NIOTests/EchoServerClientTest.swift index d18d46d54..88e6f9fff 100644 --- a/Tests/NIOTests/EchoServerClientTest.swift +++ b/Tests/NIOTests/EchoServerClientTest.swift @@ -88,7 +88,7 @@ class EchoServerClientTest : XCTestCase { _ = try! serverChannel.close().wait() } - let promise: Promise = group.next().newPromise() + let promise: EventLoopPromise = group.next().newPromise() let clientChannel = try ClientBootstrap(group: group) .handler(handler: ChannelInitializer(initChannel: { channel in return channel.pipeline.add(handler: WriteOnConnectHandler(toWrite: "X")).then { v2 in @@ -256,10 +256,10 @@ class EchoServerClientTest : XCTestCase { typealias InboundIn = ByteBuffer private let numBytes: Int - private let promise: Promise + private let promise: EventLoopPromise private var buffer: ByteBuffer! - init(numBytes: Int, promise: Promise) { + init(numBytes: Int, promise: EventLoopPromise) { self.numBytes = numBytes self.promise = promise } @@ -287,7 +287,7 @@ class EchoServerClientTest : XCTestCase { private final class ChannelActiveHandler: ChannelInboundHandler { typealias InboundIn = ByteBuffer - private var promise: Promise! = nil + private var promise: EventLoopPromise! = nil func handlerAdded(ctx: ChannelHandlerContext) { promise = ctx.channel!.eventLoop.newPromise() @@ -371,11 +371,11 @@ class EchoServerClientTest : XCTestCase { typealias InboundIn = Never let alreadyClosedInChannelInactive = Atomic(value: false) let alreadyClosedInChannelUnregistered = Atomic(value: false) - let channelUnregisteredPromise: Promise<()> - let channelInactivePromise: Promise<()> + let channelUnregisteredPromise: EventLoopPromise<()> + let channelInactivePromise: EventLoopPromise<()> - public init(channelUnregisteredPromise: Promise<()>, - channelInactivePromise: Promise<()>) { + public init(channelUnregisteredPromise: EventLoopPromise<()>, + channelInactivePromise: EventLoopPromise<()>) { self.channelUnregisteredPromise = channelUnregisteredPromise self.channelInactivePromise = channelInactivePromise } @@ -453,8 +453,8 @@ class EchoServerClientTest : XCTestCase { try! group.syncShutdownGracefully() } - let inactivePromise = group.next().newPromise() as Promise<()> - let unregistredPromise = group.next().newPromise() as Promise<()> + let inactivePromise = group.next().newPromise() as EventLoopPromise<()> + let unregistredPromise = group.next().newPromise() as EventLoopPromise<()> let handler = CloseInInActiveAndUnregisteredChannelHandler(channelUnregisteredPromise: unregistredPromise, channelInactivePromise: inactivePromise) @@ -490,7 +490,7 @@ class EchoServerClientTest : XCTestCase { } let writingBytes = "hello" - let bytesReceivedPromise: Promise = group.next().newPromise() + let bytesReceivedPromise: EventLoopPromise = group.next().newPromise() let byteCountingHandler = ByteCountingHandler(numBytes: writingBytes.utf8.count, promise: bytesReceivedPromise) let serverChannel = try ServerBootstrap(group: group) .option(option: ChannelOptions.Socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) @@ -548,7 +548,7 @@ class EchoServerClientTest : XCTestCase { } let stringToWrite = "hello" - let promise: Promise = group.next().newPromise() + let promise: EventLoopPromise = group.next().newPromise() let clientChannel = try ClientBootstrap(group: group) .handler(handler: ChannelInitializer(initChannel: { channel in return channel.pipeline.add(handler: WriteOnConnectHandler(toWrite: stringToWrite)).then { v2 in @@ -581,7 +581,7 @@ class EchoServerClientTest : XCTestCase { _ = try! serverChannel.close().wait() } - let promise: Promise = group.next().newPromise() + let promise: EventLoopPromise = group.next().newPromise() let clientChannel = try ClientBootstrap(group: group) .handler(handler: ChannelInitializer(initChannel: { channel in return channel.pipeline.add(handler: ByteCountingHandler(numBytes: stringToWrite.utf8.count, promise: promise)) diff --git a/Tests/NIOTests/EmbeddedChannelTest.swift b/Tests/NIOTests/EmbeddedChannelTest.swift index d5bf18054..3887fa50f 100644 --- a/Tests/NIOTests/EmbeddedChannelTest.swift +++ b/Tests/NIOTests/EmbeddedChannelTest.swift @@ -118,7 +118,7 @@ class EmbeddedChannelTest: XCTestCase { typealias OutboundIn = String typealias OutboundOut = Never - public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: Promise?) { + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { promise!.fail(error: ChannelError.messageUnsupported) } } diff --git a/Tests/NIOTests/FutureTest+XCTest.swift b/Tests/NIOTests/EventLoopFutureTest+XCTest.swift similarity index 87% rename from Tests/NIOTests/FutureTest+XCTest.swift rename to Tests/NIOTests/EventLoopFutureTest+XCTest.swift index 70ec60008..a1ed8aa68 100644 --- a/Tests/NIOTests/FutureTest+XCTest.swift +++ b/Tests/NIOTests/EventLoopFutureTest+XCTest.swift @@ -12,7 +12,7 @@ // //===----------------------------------------------------------------------===// /// -/// FutureTest+XCTest.swift +/// EventLoopFutureTest+XCTest.swift /// import XCTest @@ -22,9 +22,9 @@ import XCTest /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// -extension FutureTest { +extension EventLoopFutureTest { - static var allTests : [(String, (FutureTest) -> () throws -> Void)] { + static var allTests : [(String, (EventLoopFutureTest) -> () throws -> Void)] { return [ ("testFutureFulfilledIfHasResult", testFutureFulfilledIfHasResult), ("testFutureFulfilledIfHasError", testFutureFulfilledIfHasError), diff --git a/Tests/NIOTests/FutureTest.swift b/Tests/NIOTests/EventLoopFutureTest.swift similarity index 67% rename from Tests/NIOTests/FutureTest.swift rename to Tests/NIOTests/EventLoopFutureTest.swift index 714b3a913..ba72a1c33 100644 --- a/Tests/NIOTests/FutureTest.swift +++ b/Tests/NIOTests/EventLoopFutureTest.swift @@ -15,29 +15,29 @@ import XCTest @testable import NIO -enum FutureTestError : Error { +enum EventLoopFutureTestError : Error { case example } -class FutureTest : XCTestCase { +class EventLoopFutureTest : XCTestCase { func testFutureFulfilledIfHasResult() throws { let eventLoop = EmbeddedEventLoop() - let f = Future(eventLoop: eventLoop, checkForPossibleDeadlock: true, result: 5) + let f = EventLoopFuture(eventLoop: eventLoop, checkForPossibleDeadlock: true, result: 5) XCTAssertTrue(f.fulfilled) } func testFutureFulfilledIfHasError() throws { let eventLoop = EmbeddedEventLoop() - let f = Future(eventLoop: eventLoop, checkForPossibleDeadlock: true, error: FutureTestError.example) + let f = EventLoopFuture(eventLoop: eventLoop, checkForPossibleDeadlock: true, error: EventLoopFutureTestError.example) XCTAssertTrue(f.fulfilled) } func testAndAllWithAllSuccesses() throws { let eventLoop = EmbeddedEventLoop() - let promises: [Promise] = (0..<100).map { _ in eventLoop.newPromise() } + let promises: [EventLoopPromise] = (0..<100).map { _ in eventLoop.newPromise() } let futures = promises.map { $0.futureResult } - let fN: Future = Future.andAll(futures, eventLoop: eventLoop) + let fN: EventLoopFuture = EventLoopFuture.andAll(futures, eventLoop: eventLoop) _ = promises.map { $0.succeed(result: ()) } () = try fN.wait() } @@ -45,10 +45,10 @@ class FutureTest : XCTestCase { func testAndAllWithAllFailures() throws { struct E: Error {} let eventLoop = EmbeddedEventLoop() - let promises: [Promise] = (0..<100).map { _ in eventLoop.newPromise() } + let promises: [EventLoopPromise] = (0..<100).map { _ in eventLoop.newPromise() } let futures = promises.map { $0.futureResult } - let fN: Future = Future.andAll(futures, eventLoop: eventLoop) + let fN: EventLoopFuture = EventLoopFuture.andAll(futures, eventLoop: eventLoop) _ = promises.map { $0.fail(error: E()) } do { () = try fN.wait() @@ -63,15 +63,15 @@ class FutureTest : XCTestCase { func testAndAllWithOneFailure() throws { struct E: Error {} let eventLoop = EmbeddedEventLoop() - var promises: [Promise] = (0..<100).map { _ in eventLoop.newPromise() } + var promises: [EventLoopPromise] = (0..<100).map { _ in eventLoop.newPromise() } _ = promises.map { $0.succeed(result: ()) } - let failedPromise: Promise<()> = eventLoop.newPromise() + let failedPromise: EventLoopPromise<()> = eventLoop.newPromise() failedPromise.fail(error: E()) promises.append(failedPromise) let futures = promises.map { $0.futureResult } - let fN: Future = Future.andAll(futures, eventLoop: eventLoop) + let fN: EventLoopFuture = EventLoopFuture.andAll(futures, eventLoop: eventLoop) do { () = try fN.wait() XCTFail("should've thrown an error") diff --git a/Tests/NIOTests/FileRegionTest.swift b/Tests/NIOTests/FileRegionTest.swift index 8c929c405..01812a5e8 100644 --- a/Tests/NIOTests/FileRegionTest.swift +++ b/Tests/NIOTests/FileRegionTest.swift @@ -73,10 +73,10 @@ class FileRegionTest : XCTestCase { typealias InboundIn = ByteBuffer private let numBytes: Int - private let promise: Promise + private let promise: EventLoopPromise private var buffer: ByteBuffer! - init(numBytes: Int, promise: Promise) { + init(numBytes: Int, promise: EventLoopPromise) { self.numBytes = numBytes self.promise = promise }