diff --git a/Sources/NIO/ByteBuffer.swift b/Sources/NIO/ByteBuffer.swift index b7ec2f4d9..f169de5ea 100644 --- a/Sources/NIO/ByteBuffer.swift +++ b/Sources/NIO/ByteBuffer.swift @@ -81,8 +81,23 @@ public enum Endianess { case Little } -public struct ByteBuffer { // TODO: Equatable, Comparable - +public struct ByteBuffer : Equatable { // TODO: Comparable + + public static func ==(lhs: ByteBuffer, rhs: ByteBuffer) -> Bool { + guard lhs.readableBytes == rhs.readableBytes else { + return false + } + + return lhs.readableBytes == rhs.readableBytes && + lhs.withReadPointer { lhsPtr, lhsSize in + rhs.withReadPointer { rhsPtr, rhsSize in + // Shouldn't get here otherwise because of readableBytes check + assert(rhsSize == lhsSize) + return memcmp(lhsPtr, rhsPtr, lhsSize) == 0 + } + } + } + private static func reallocatedData(minimumCapacity: Int, source: Data?, allocator: ByteBufferAllocator) -> Data { let newCapacity = Int(UInt64(minimumCapacity).nextPowerOf2()) var newData = Data(bytesNoCopy: UnsafeMutableRawPointer.allocate(bytes: newCapacity, diff --git a/Sources/NIO/Channel.swift b/Sources/NIO/Channel.swift index dcfedaac8..764d679b1 100644 --- a/Sources/NIO/Channel.swift +++ b/Sources/NIO/Channel.swift @@ -338,7 +338,7 @@ fileprivate class PendingWrites { /* All operations on SocketChannel are thread-safe */ -public class SocketChannel : Channel { +final public class SocketChannel : BaseSocketChannel { public init(eventLoop: EventLoop) throws { let socket = try Socket() @@ -405,7 +405,7 @@ public class SocketChannel : Channel { /* All operations on ServerSocketChannel are thread-safe */ -public class ServerSocketChannel : Channel { +final public class ServerSocketChannel : BaseSocketChannel { private var backlog: Int32 = 128 private let group: EventLoopGroup @@ -439,7 +439,7 @@ public class ServerSocketChannel : Channel { return try super.getOption0(option: option) } - override func bind0(local: SocketAddress, promise: Promise) { + override public func bind0(local: SocketAddress, promise: Promise) { assert(eventLoop.inEventLoop) do { try socket.bind(local: local) @@ -476,7 +476,7 @@ public class ServerSocketChannel : Channel { return true } - override func channelRead(data: Any) { + override public func channelRead(data: Any) { assert(eventLoop.inEventLoop) if let ch = data as? Channel { @@ -491,23 +491,121 @@ public class ServerSocketChannel : Channel { } } + +public protocol ChannelCore { + func register0(promise: Promise) + func bind0(local: SocketAddress, promise: Promise) + func connect0(remote: SocketAddress, promise: Promise) + func write0(data: Any, promise: Promise) + func flush0() + func readIfNeeded0() + func startReading0() + func stopReading0() + func close0(promise: Promise, error: Error) + var closePromise: Promise { get } + var closed: Bool { get } +} + +extension ChannelCore { + public func close0(promise: Promise = Promise()) { + close0(promise: promise, error: ChannelError.closed) + } +} + +public protocol Channel : class, ChannelOutboundInvoker { + var allocator: ByteBufferAllocator { get } + + var closeFuture: Future { get } + + var pipeline: ChannelPipeline { get } + var localAddress: SocketAddress? { get } + var remoteAddress: SocketAddress? { get } + + + func setOption(option: T, value: T.OptionType) throws + func getOption(option: T) throws -> T.OptionType + + @discardableResult func bind(local: SocketAddress, promise: Promise) -> Future + @discardableResult func connect(remote: SocketAddress, promise: Promise) -> Future + func read() + func channelRead(data: Any) + @discardableResult func write(data: Any, promise: Promise) -> Future + func flush() + @discardableResult func writeAndFlush(data: Any, promise: Promise) -> Future + @discardableResult func close(promise: Promise) -> Future + + var _unsafe: ChannelCore { get } +} + +protocol SelectableChannel : Channel { + var selectable: Selectable { get } + var interestedEvent: InterestedEvent { get } + + func writable() + func readable() +} + +extension Channel { + var closed: Bool { return _unsafe.closed } + + @discardableResult public func bind(local: SocketAddress, promise: Promise) -> Future { + return pipeline.bind(local: local, promise: promise) + } + + // Methods invoked from the HeadHandler of the ChannelPipeline + // By default, just pass through to pipeline + + @discardableResult public func connect(remote: SocketAddress, promise: Promise) -> Future { + return pipeline.connect(remote: remote, promise: promise) + } + + @discardableResult public func write(data: Any, promise: Promise) -> Future { + return pipeline.write(data: data, promise: promise) + } + + public func flush() { + pipeline.flush() + } + + public func read() { + pipeline.read() + } + + @discardableResult public func writeAndFlush(data: Any, promise: Promise) -> Future { + return pipeline.writeAndFlush(data: data, promise: promise) + } + + @discardableResult public func close(promise: Promise) -> Future { + return pipeline.close(promise: promise) + } + + + @discardableResult public func register(promise: Promise) -> Future { + return pipeline.register(promise: promise) + } +} + /* All operations on Channel are thread-safe */ -public class Channel : ChannelOutboundInvoker { +public class BaseSocketChannel : SelectableChannel, ChannelCore { + public var selectable: Selectable { return socket } + + public var _unsafe: ChannelCore { return self } + public let eventLoop: EventLoop // Visible to access from EventLoop directly let socket: BaseSocket - var interestedEvent: InterestedEvent = .none - var closed = false + public var interestedEvent: InterestedEvent = .none + public private(set) var closed = false private let pendingWrites: PendingWrites = PendingWrites() private var readPending = false private var neverRegistered = true private var pendingConnect: Promise? - private let closePromise: Promise + public let closePromise: Promise public var closeFuture: Future { return closePromise.futureResult @@ -516,7 +614,7 @@ public class Channel : ChannelOutboundInvoker { public var open: Bool { return !closeFuture.fulfilled } - + public var allocator: ByteBufferAllocator { if eventLoop.inEventLoop { return bufferAllocator @@ -530,12 +628,7 @@ public class Channel : ChannelOutboundInvoker { fileprivate var autoRead: Bool = true fileprivate var maxMessagesPerRead: UInt = 1 - // We don't use lazy var here as this is more expensive then doing this :/ - public var pipeline: ChannelPipeline { - return _pipeline - } - - private var _pipeline: ChannelPipeline! + public lazy var pipeline: ChannelPipeline! = ChannelPipeline(channel: self) public func setOption(option: T, value: T.OptionType) throws { if eventLoop.inEventLoop { @@ -619,7 +712,7 @@ public class Channel : ChannelOutboundInvoker { } } - func readIfNeeded() { + public func readIfNeeded0() { if autoRead { pipeline.read0() } @@ -654,7 +747,7 @@ public class Channel : ChannelOutboundInvoker { } // Methods invoked from the HeadHandler of the ChannelPipeline - func bind0(local: SocketAddress, promise: Promise ) { + public func bind0(local: SocketAddress, promise: Promise ) { assert(eventLoop.inEventLoop) do { @@ -665,7 +758,7 @@ public class Channel : ChannelOutboundInvoker { } } - func write0(data: Any, promise: Promise) { + public func write0(data: Any, promise: Promise) { assert(eventLoop.inEventLoop) guard !closed else { @@ -692,7 +785,7 @@ public class Channel : ChannelOutboundInvoker { } } - func flush0() { + public func flush0() { assert(eventLoop.inEventLoop) guard !isWritePending() else { @@ -710,7 +803,7 @@ public class Channel : ChannelOutboundInvoker { } } - func startReading0() { + public func startReading0() { assert(eventLoop.inEventLoop) guard !closed else { @@ -721,7 +814,7 @@ public class Channel : ChannelOutboundInvoker { registerForReadable() } - func stopReading0() { + public func stopReading0() { assert(eventLoop.inEventLoop) guard !closed else { @@ -752,7 +845,7 @@ public class Channel : ChannelOutboundInvoker { } } - func close0(promise: Promise = Promise(), error: Error = ChannelError.closed) { + public func close0(promise: Promise = Promise(), error: Error = ChannelError.closed) { assert(eventLoop.inEventLoop) guard !closed else { @@ -787,7 +880,7 @@ public class Channel : ChannelOutboundInvoker { } - func register0(promise: Promise) { + public func register0(promise: Promise) { assert(eventLoop.inEventLoop) // Was not registered yet so do it now. @@ -806,7 +899,7 @@ public class Channel : ChannelOutboundInvoker { // Methods invoked from the EventLoop itself - func writable() { + public func writable() { assert(eventLoop.inEventLoop) assert(!closed) @@ -854,7 +947,7 @@ public class Channel : ChannelOutboundInvoker { } } - func readable() { + public func readable() { assert(eventLoop.inEventLoop) assert(!closed) @@ -902,7 +995,7 @@ public class Channel : ChannelOutboundInvoker { fatalError("this must be overridden by sub class") } - func connect0(remote: SocketAddress, promise: Promise) { + public func connect0(remote: SocketAddress, promise: Promise) { assert(eventLoop.inEventLoop) guard pendingConnect == nil else { @@ -927,7 +1020,7 @@ public class Channel : ChannelOutboundInvoker { fatalError("this must be overridden by sub class") } - func channelRead(data: Any) { + public func channelRead(data: Any) { // Do nothing by default } diff --git a/Sources/NIO/ChannelPipeline.swift b/Sources/NIO/ChannelPipeline.swift index dc637c1b8..f4b585341 100644 --- a/Sources/NIO/ChannelPipeline.swift +++ b/Sources/NIO/ChannelPipeline.swift @@ -434,31 +434,31 @@ private class HeadChannelHandler : ChannelHandler { private init() { } func register(ctx: ChannelHandlerContext, promise: Promise) { - ctx.channel!.register0(promise: promise) + ctx.channel!._unsafe.register0(promise: promise) } func bind(ctx: ChannelHandlerContext, local: SocketAddress, promise: Promise) { - ctx.channel!.bind0(local: local, promise: promise) + ctx.channel!._unsafe.bind0(local: local, promise: promise) } func connect(ctx: ChannelHandlerContext, remote: SocketAddress, promise: Promise) { - ctx.channel!.connect0(remote: remote, promise: promise) + ctx.channel!._unsafe.connect0(remote: remote, promise: promise) } func write(ctx: ChannelHandlerContext, data: Any, promise: Promise) { - ctx.channel!.write0(data: data, promise: promise) + ctx.channel!._unsafe.write0(data: data, promise: promise) } func flush(ctx: ChannelHandlerContext) { - ctx.channel!.flush0() + ctx.channel!._unsafe.flush0() } func close(ctx: ChannelHandlerContext, promise: Promise) { - ctx.channel!.close0(promise: promise) + ctx.channel!._unsafe.close0(promise: promise) } func read(ctx: ChannelHandlerContext) { - ctx.channel!.startReading0() + ctx.channel!._unsafe.startReading0() } func channelActive(ctx: ChannelHandlerContext) { @@ -480,7 +480,7 @@ private class HeadChannelHandler : ChannelHandler { } private func readIfNeeded(ctx: ChannelHandlerContext) { - ctx.channel!.readIfNeeded() + ctx.channel!._unsafe.readIfNeeded0() } } diff --git a/Sources/NIO/Embedded.swift b/Sources/NIO/Embedded.swift new file mode 100644 index 000000000..c74b603cb --- /dev/null +++ b/Sources/NIO/Embedded.swift @@ -0,0 +1,149 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Foundation +import Dispatch +import Sockets +import Future + +class EmbeddedEventLoop : EventLoop { + + let queue = DispatchQueue(label: "embeddedEventLoopQueue", qos: .utility) + var inEventLoop: Bool = true + var isRunning: Bool = false + + // Would be better to have this as a Queue + var tasks: [() -> ()] = Array() + + func register(channel: Channel) throws { + let _ = channel.register() + } + + func deregister(channel: Channel) throws { + // Doesn't apply + } + + func reregister(channel: Channel) throws { + // Doesn't apply + } + + // We're not really running a loop here. Tasks aren't run until run() is called, + // at which point we run everything that's been submitted. Anything newly submitted + // either gets on that train if it's still moving or + func execute(task: @escaping () -> ()) { + queue.sync { + if isRunning && tasks.isEmpty { + task() + } else { + tasks.append(task) + } + } + } + + func run() throws { + queue.sync { + isRunning = true + while !tasks.isEmpty { + tasks[0]() + tasks = Array(tasks.dropFirst(1)) // TODO: Seriously, get a queue + } + } + } + + func close() throws { + // Nothing to do here + } + + +} + +class EmbeddedChannelCore : ChannelCore { + var closed: Bool { return closePromise.futureResult.fulfilled } + + var closePromise: Promise = Promise() + + deinit { closePromise.succeed(result: ()) } + + var outboundBuffer: [Any] = [] + + func close0(promise: Promise, error: Error) { + closePromise.succeed(result: ()) + promise.succeed(result: ()) + } + + func bind0(local: SocketAddress, promise: Promise) { + promise.succeed(result: ()) + } + + func connect0(remote: SocketAddress, promise: Promise) { + promise.succeed(result: ()) + } + + func register0(promise: Promise) { + promise.succeed(result: ()) + } + + func write0(data: Any, promise: Promise) { + outboundBuffer.append(data as! ByteBuffer) + promise.succeed(result: ()) + } + + func flush0() { + // No need + } + + func startReading0() { + } + + func stopReading0() { + } + + func readIfNeeded0() { + } +} + +public class EmbeddedChannel : Channel { + public var closeFuture: Future { return _unsafe.closePromise.futureResult } + + public var _unsafe: ChannelCore = EmbeddedChannelCore() + public var pipeline: ChannelPipeline { + return _pipeline + } + + private var _pipeline: ChannelPipeline! + public let allocator: ByteBufferAllocator = ByteBufferAllocator() + public var eventLoop: EventLoop = EmbeddedEventLoop() + + public var localAddress: SocketAddress? = nil + public var remoteAddress: SocketAddress? = nil + var outboundBuffer: [Any] { return (_unsafe as! EmbeddedChannelCore).outboundBuffer } + + init() { + _pipeline = ChannelPipeline(channel: self) + } + + public func setOption(option: T, value: T.OptionType) throws where T : ChannelOption { + // No options supported + } + + public func getOption(option: T) throws -> T.OptionType where T : ChannelOption { + fatalError("option \(option) not supported") + } + + public func read() { + pipeline.read() + } + + public func channelRead(data: Any) { } +} diff --git a/Sources/NIO/EventLoop.swift b/Sources/NIO/EventLoop.swift index 04d902ff3..e38d28e31 100644 --- a/Sources/NIO/EventLoop.swift +++ b/Sources/NIO/EventLoop.swift @@ -17,9 +17,54 @@ import Future import Sockets import ConcurrencyHelpers +public protocol EventLoop { + var inEventLoop: Bool { get } + + func register(channel: Channel) throws + func deregister(channel: Channel) throws + func reregister(channel: Channel) throws + func execute(task: @escaping () -> ()) + func submit(task: @escaping () throws-> (T)) -> Future + func run() throws + func close() throws + +} + +extension EventLoop { + public func submit(task: @escaping () throws-> (T)) -> Future { + let promise = Promise() + + execute(task: {() -> () in + do { + promise.succeed(result: try task()) + } catch let err { + promise.fail(error: err) + } + }) + + return promise.futureResult + } + + public func newPromise(type: T.Type) -> Promise { + return Promise() + } + + public func newFailedFuture(type: T.Type, error: Error) -> Future { + let promise = newPromise(type: type) + promise.fail(error: error) + return promise.futureResult + } + + public func newSucceedFuture(result: T) -> Future { + let promise = newPromise(type: type(of: result)) + promise.succeed(result: result) + return promise.futureResult + } +} + // TODO: Implement scheduling tasks in the future (a.k.a ScheduledExecutoreService -public class EventLoop : EventLoopGroup { +final class SelectableEventLoop : EventLoop, EventLoopGroup { private let selector: Sockets.Selector private var thread: Thread? private var tasks: [() -> ()] @@ -31,26 +76,38 @@ public class EventLoop : EventLoopGroup { self.tasks = Array() } + func register(channel: SelectableChannel) throws { + assert(inEventLoop) + try selector.register(selectable: channel.selectable, interested: channel.interestedEvent, attachment: channel) + } + func register(channel: Channel) throws { - assert(inEventLoop) - try selector.register(selectable: channel.socket, interested: channel.interestedEvent, attachment: channel) + try register(channel: channel as! SelectableChannel) } + func deregister(channel: SelectableChannel) throws { + assert(inEventLoop) + try selector.deregister(selectable: channel.selectable) + } + func deregister(channel: Channel) throws { - assert(inEventLoop) - try selector.deregister(selectable: channel.socket) + try deregister(channel: channel as! SelectableChannel) } + func reregister(channel: SelectableChannel) throws { + assert(inEventLoop) + try selector.reregister(selectable: channel.selectable, interested: channel.interestedEvent) + } + func reregister(channel: Channel) throws { - assert(inEventLoop) - try selector.reregister(selectable: channel.socket, interested: channel.interestedEvent) + try reregister(channel: channel as! SelectableChannel) } - public var inEventLoop: Bool { + var inEventLoop: Bool { return Thread.current.isEqual(thread) } - public func execute(task: @escaping () -> ()) { + func execute(task: @escaping () -> ()) { tasksLock.lock() tasks.append(task) tasksLock.unlock() @@ -59,20 +116,6 @@ public class EventLoop : EventLoopGroup { _ = try? selector.wakeup() } - public func submit(task: @escaping () throws-> (T)) -> Future { - let promise = Promise() - - execute(task: {() -> () in - do { - promise.succeed(result: try task()) - } catch let err { - promise.fail(error: err) - } - }) - - return promise.futureResult - } - func run() throws { thread = Thread.current defer { @@ -83,7 +126,7 @@ public class EventLoop : EventLoopGroup { // Block until there are events to handle or the selector was woken up try selector.whenReady(strategy: .block) { ev in - guard let channel = ev.attachment as? Channel else { + guard let channel = ev.attachment as? SelectableChannel else { fatalError("ev.attachment has type \(type(of: ev.attachment)), expected Channel") } @@ -136,7 +179,7 @@ public class EventLoop : EventLoopGroup { return false } - fileprivate func close() throws { + func close() throws { if inEventLoop { try self.selector.close() } else { @@ -147,23 +190,7 @@ public class EventLoop : EventLoopGroup { } } - public func newPromise(type: T.Type) -> Promise { - return Promise() - } - - public func newFailedFuture(type: T.Type, error: Error) -> Future { - let promise = newPromise(type: type) - promise.fail(error: error) - return promise.futureResult - } - - public func newSucceedFuture(result: T) -> Future { - let promise = newPromise(type: type(of: result)) - promise.succeed(result: result) - return promise.futureResult - } - - public func next() -> EventLoop { + func next() -> EventLoop { return self } } @@ -181,7 +208,7 @@ public protocol EventLoopGroup { /* An `EventLoopGroup` which will create multiple `EventLoop`s, each tight to its own `Thread`. */ -public class MultiThreadedEventLoopGroup : EventLoopGroup { +final public class MultiThreadedEventLoopGroup : EventLoopGroup { private let index = Atomic(value: 0) @@ -190,7 +217,7 @@ public class MultiThreadedEventLoopGroup : EventLoopGroup { public init(numThreads: Int) throws { var loops: [EventLoop] = [] for _ in 0..