Initial impl of EmbeddedChannel

This commit is contained in:
Kevin Clark committed 2017-06-05 16:59:51 -07:00
1 parent bec8f64a13
commit 329b474f45
7 files changed
+411 -82

No files matched your search

+17 -2
View File
@@ -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,
+120 -27
View File
@@ -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<Void>) {
override public func bind0(local: SocketAddress, promise: Promise<Void>) {
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<Void>)
func bind0(local: SocketAddress, promise: Promise<Void>)
func connect0(remote: SocketAddress, promise: Promise<Void>)
func write0(data: Any, promise: Promise<Void>)
func flush0()
func readIfNeeded0()
func startReading0()
func stopReading0()
func close0(promise: Promise<Void>, error: Error)
var closePromise: Promise<Void> { get }
var closed: Bool { get }
}
extension ChannelCore {
public func close0(promise: Promise<Void> = Promise<Void>()) {
close0(promise: promise, error: ChannelError.closed)
}
}
public protocol Channel : class, ChannelOutboundInvoker {
var allocator: ByteBufferAllocator { get }
var closeFuture: Future<Void> { get }
var pipeline: ChannelPipeline { get }
var localAddress: SocketAddress? { get }
var remoteAddress: SocketAddress? { get }
func setOption<T: ChannelOption>(option: T, value: T.OptionType) throws
func getOption<T: ChannelOption>(option: T) throws -> T.OptionType
@discardableResult func bind(local: SocketAddress, promise: Promise<Void>) -> Future<Void>
@discardableResult func connect(remote: SocketAddress, promise: Promise<Void>) -> Future<Void>
func read()
func channelRead(data: Any)
@discardableResult func write(data: Any, promise: Promise<Void>) -> Future<Void>
func flush()
@discardableResult func writeAndFlush(data: Any, promise: Promise<Void>) -> Future<Void>
@discardableResult func close(promise: Promise<Void>) -> Future<Void>
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<Void>) -> Future<Void> {
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<Void>) -> Future<Void> {
return pipeline.connect(remote: remote, promise: promise)
}
@discardableResult public func write(data: Any, promise: Promise<Void>) -> Future<Void> {
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<Void>) -> Future<Void> {
return pipeline.writeAndFlush(data: data, promise: promise)
}
@discardableResult public func close(promise: Promise<Void>) -> Future<Void> {
return pipeline.close(promise: promise)
}
@discardableResult public func register(promise: Promise<Void>) -> Future<Void> {
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<Void>?
private let closePromise: Promise<Void>
public let closePromise: Promise<Void>
public var closeFuture: Future<Void> {
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<T: ChannelOption>(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<Void> ) {
public func bind0(local: SocketAddress, promise: Promise<Void> ) {
assert(eventLoop.inEventLoop)
do {
@@ -665,7 +758,7 @@ public class Channel : ChannelOutboundInvoker {
}
}
func write0(data: Any, promise: Promise<Void>) {
public func write0(data: Any, promise: Promise<Void>) {
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<Void> = Promise<Void>(), error: Error = ChannelError.closed) {
public func close0(promise: Promise<Void> = Promise<Void>(), error: Error = ChannelError.closed) {
assert(eventLoop.inEventLoop)
guard !closed else {
@@ -787,7 +880,7 @@ public class Channel : ChannelOutboundInvoker {
}
func register0(promise: Promise<Void>) {
public func register0(promise: Promise<Void>) {
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<Void>) {
public func connect0(remote: SocketAddress, promise: Promise<Void>) {
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
}
+8 -8
View File
@@ -434,31 +434,31 @@ private class HeadChannelHandler : ChannelHandler {
private init() { }
func register(ctx: ChannelHandlerContext, promise: Promise<Void>) {
ctx.channel!.register0(promise: promise)
ctx.channel!._unsafe.register0(promise: promise)
}
func bind(ctx: ChannelHandlerContext, local: SocketAddress, promise: Promise<Void>) {
ctx.channel!.bind0(local: local, promise: promise)
ctx.channel!._unsafe.bind0(local: local, promise: promise)
}
func connect(ctx: ChannelHandlerContext, remote: SocketAddress, promise: Promise<Void>) {
ctx.channel!.connect0(remote: remote, promise: promise)
ctx.channel!._unsafe.connect0(remote: remote, promise: promise)
}
func write(ctx: ChannelHandlerContext, data: Any, promise: Promise<Void>) {
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<Void>) {
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()
}
}
+149
View File
@@ -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<Void> = Promise<Void>()
deinit { closePromise.succeed(result: ()) }
var outboundBuffer: [Any] = []
func close0(promise: Promise<Void>, error: Error) {
closePromise.succeed(result: ())
promise.succeed(result: ())
}
func bind0(local: SocketAddress, promise: Promise<Void>) {
promise.succeed(result: ())
}
func connect0(remote: SocketAddress, promise: Promise<Void>) {
promise.succeed(result: ())
}
func register0(promise: Promise<Void>) {
promise.succeed(result: ())
}
func write0(data: Any, promise: Promise<Void>) {
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<Void> { 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<T>(option: T, value: T.OptionType) throws where T : ChannelOption {
// No options supported
}
public func getOption<T>(option: T) throws -> T.OptionType where T : ChannelOption {
fatalError("option \(option) not supported")
}
public func read() {
pipeline.read()
}
public func channelRead(data: Any) { }
}
+71 -44
View File
@@ -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<T>(task: @escaping () throws-> (T)) -> Future<T>
func run() throws
func close() throws
}
extension EventLoop {
public func submit<T>(task: @escaping () throws-> (T)) -> Future<T> {
let promise = Promise<T>()
execute(task: {() -> () in
do {
promise.succeed(result: try task())
} catch let err {
promise.fail(error: err)
}
})
return promise.futureResult
}
public func newPromise<T>(type: T.Type) -> Promise<T> {
return Promise<T>()
}
public func newFailedFuture<T>(type: T.Type, error: Error) -> Future<T> {
let promise = newPromise(type: type)
promise.fail(error: error)
return promise.futureResult
}
public func newSucceedFuture<T>(result: T) -> Future<T> {
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<T>(task: @escaping () throws-> (T)) -> Future<T> {
let promise = Promise<T>()
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<T>(type: T.Type) -> Promise<T> {
return Promise<T>()
}
public func newFailedFuture<T>(type: T.Type, error: Error) -> Future<T> {
let promise = newPromise(type: type)
promise.fail(error: error)
return promise.futureResult
}
public func newSucceedFuture<T>(result: T) -> Future<T> {
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<Int>(value: 0)
@@ -190,7 +217,7 @@ public class MultiThreadedEventLoopGroup : EventLoopGroup {
public init(numThreads: Int) throws {
var loops: [EventLoop] = []
for _ in 0..<numThreads {
let loop = try EventLoop()
let loop = try SelectableEventLoop()
loops.append(loop)
}
+11 -1
View File
@@ -24,7 +24,17 @@ class ByteBufferTest: XCTestCase {
super.setUp()
buf = try! allocator.buffer(capacity: 1024)
}
func testEqualsComparesReadBuffersOnly() throws {
// Only cares about the read buffer
buf.writeInteger(value: Int8.max)
buf.writeString(value: "oh hi")
let _: Int8 = buf.readInteger()! // Just getting rid of it from the read buffer
var otherBuffer = try! allocator.buffer(capacity: 32)
otherBuffer.writeString(value: "oh hi")
XCTAssertEqual(otherBuffer, buf)
}
func testWrappedData() {
let data = "Test".data(using: .utf8)!
let buffer = allocator.buffer(wrapped: data)
+35
View File
@@ -0,0 +1,35 @@
//===----------------------------------------------------------------------===//
//
// 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 XCTest
@testable import NIO
class EmbeddedChannelTest: XCTestCase {
func testWriteByteBuffer() throws {
let channel = EmbeddedChannel()
var buf = try channel.allocator.buffer(capacity: 1024)
buf.writeString(value: "hello")
let f = channel.write(data: buf, promise:channel.eventLoop.newPromise(type: Void.self))
var ranBlock = false
f.whenSuccess {
XCTAssertEqual(buf, channel.outboundBuffer[0] as! ByteBuffer)
ranBlock = true
}
try f.wait()
XCTAssert(ranBlock)
}
}