diff --git a/Sources/NIO/ByteBuffer-aux.swift b/Sources/NIO/ByteBuffer-aux.swift index 3146c967f..e5ac09364 100644 --- a/Sources/NIO/ByteBuffer-aux.swift +++ b/Sources/NIO/ByteBuffer-aux.swift @@ -126,25 +126,3 @@ extension ByteBuffer: Equatable { } } -// MARK: Compatibility -extension ByteBuffer { - public func withReadPointer(body: (UnsafePointer, Int) throws -> T) rethrows -> T { - return try self.withUnsafeReadableBytes { ptr in - try body(ptr.baseAddress!.assumingMemoryBound(to: UInt8.self), ptr.count) - } - } - - public mutating func withMutableWritePointer(body: (UnsafeMutablePointer, Int) throws -> Int?) rethrows -> Int? { - var maybeWritten: Int? = nil - _ = try self.writeWithUnsafeMutableBytes { ptr in - if let written = try body(ptr.baseAddress!.assumingMemoryBound(to: UInt8.self), ptr.count) { - maybeWritten = written - return written - } else { - maybeWritten = nil - return 0 - } - } - return maybeWritten - } -} diff --git a/Sources/NIO/Channel.swift b/Sources/NIO/Channel.swift index a9b040e90..be635fb66 100644 --- a/Sources/NIO/Channel.swift +++ b/Sources/NIO/Channel.swift @@ -65,7 +65,7 @@ func doPendingWriteVectorOperation(pending: PendingWrite?, count: Int, iovecs: UnsafeMutableBufferPointer, storageRefs: UnsafeMutableBufferPointer>, - _ fn: (UnsafeBufferPointer) -> Int) -> Int { + _ fn: (UnsafeBufferPointer) throws -> IOResult) throws -> IOResult { var next = pending for i in 0..(errorBuffer: inout Error?, input: I, _ fn: (I) throws -> Int?) -> Int { - do { - if let bytes = try fn(input) { - return bytes - } else { - return 0 - } - } catch let e { - errorBuffer = e - return -1 - } +private enum WriteResult { + case writtenCompletely + case writtenPartially + case nothingToBeWritten + case wouldBlock + case closed } final fileprivate class PendingWrites { @@ -152,15 +147,9 @@ final fileprivate class PendingWrites { /* Function that takes two closures and based on if there are more then one ByteBuffer pending calls either one or the other. */ - func consume(oneBody: (UnsafePointer, Int) throws -> Int?, multipleBody: (UnsafeBufferPointer) throws -> Int?) throws -> (consumedAll:Bool?, writable: Bool) { + func consume(oneBody: (UnsafePointer, Int) throws -> IOResult, multipleBody: (UnsafeBufferPointer) throws -> IOResult) throws -> (consumedAll: WriteResult, writable: Bool) { let wasWritable = writable - let result: Bool? - if hasMultiple { - // Holds multiple pending writes, use consumeMultiple which will allow us to us writev (a.k.a gathering writes) - result = try consumeMultiple(body: multipleBody) - } else { - result = try consumeOne(body: oneBody) - } + let result = try hasMultiple ? consumeMultiple(multipleBody) : consumeOne(oneBody) if !wasWritable { // Was not writable before so signal back to the caller the possible state change @@ -193,13 +182,14 @@ final fileprivate class PendingWrites { return flushCheckpoint != nil } - private func consumeOne(body: (UnsafePointer, Int) throws -> Int?) rethrows -> Bool? { + private func consumeOne(_ body: (UnsafePointer, Int) throws -> IOResult) rethrows -> WriteResult { if let pending = head, isFlushPending() { for _ in 0..) throws -> Int?) throws -> Bool? { + private func consumeMultiple(_ body: (UnsafeBufferPointer) throws -> IOResult) throws -> WriteResult { if var pending = head, isFlushPending() { writeLoop: for _ in 0.. 0 { + switch try doPendingWriteVectorOperation(pending: pending, + count: outstanding.chunks, + iovecs: self.iovecs, + storageRefs: self.storageRefs, + { pointer in + expected += pointer.count + return try body(pointer) + }) { + case .processed(let written): outstanding = (outstanding.chunks, outstanding.bytes - written) if !writable && outstanding.bytes < Int(waterMark.lowerBound) { @@ -298,20 +282,22 @@ final fileprivate class PendingWrites { if isEmpty || allFlushed { // return nil to signal to the caller that there are no more buffers to consume - return nil + return .nothingToBeWritten } // check if we were able to write everything or not assert(expected == written) - return true + return .writtenPartially + case .wouldBlock: + return .wouldBlock } } // could not write the complete buffer - return false + return .nothingToBeWritten } // empty or flushed everything that is marked to be flushable - return nil + return .nothingToBeWritten } @@ -353,6 +339,30 @@ final fileprivate class PendingWrites { } } +// MARK: Compatibility +extension ByteBuffer { + public func withReadPointer(body: (UnsafePointer, Int) throws -> T) rethrows -> T { + return try self.withUnsafeReadableBytes { ptr in + try body(ptr.baseAddress!.assumingMemoryBound(to: UInt8.self), ptr.count) + } + } + + public mutating func withMutableWritePointer(body: (UnsafeMutablePointer, Int) throws -> IOResult) rethrows -> IOResult { + var writeResult: IOResult! + _ = try self.writeWithUnsafeMutableBytes { ptr in + let localWriteResult = try body(ptr.baseAddress!.assumingMemoryBound(to: UInt8.self), ptr.count) + writeResult = localWriteResult + switch localWriteResult { + case .processed(let written): + return written + case .wouldBlock: + return 0 + } + } + return writeResult + } +} + /* All operations on SocketChannel are thread-safe */ @@ -382,7 +392,8 @@ final class SocketChannel : BaseSocketChannel { guard !closed else { return } - if let bytesRead = try buffer.withMutableWritePointer { try self.socket.read(pointer: $0, size: $1) } { + switch try buffer.withMutableWritePointer(body: self.socket.read(pointer:size:)) { + case .processed(let bytesRead): if bytesRead > 0 { recvAllocator.record(actualReadBytes: bytesRead) @@ -394,36 +405,36 @@ final class SocketChannel : BaseSocketChannel { // end-of-file throw ChannelError.eof } - } else { + case .wouldBlock: return } } } - override fileprivate func writeToSocket(pendingWrites: PendingWrites) throws -> Bool? { - let result = try pendingWrites.consume(oneBody: { - guard $1 > 0 else { + override fileprivate func writeToSocket(pendingWrites: PendingWrites) throws -> WriteResult { + let result = try pendingWrites.consume(oneBody: { ptr, length in + guard length > 0 else { // No need to call write if the buffer is empty. - return 0 + return .processed(0) } // normal write - return try self.socket.write(pointer: $0, size: $1) - }, multipleBody: { - switch $0.count { + return try self.socket.write(pointer: ptr, size: length) + }, multipleBody: { ptrs in + switch ptrs.count { case 0: // No need to call write if the buffer is empty. - return 0 + return .processed(0) case 1: - let p = $0[0] + let p = ptrs[0] return try self.socket.write(pointer: p.iov_base.assumingMemoryBound(to: UInt8.self), size: p.iov_len) default: // Gathering write - return try self.socket.writev(iovecs: $0) + return try self.socket.writev(iovecs: ptrs) } }) if result.writable { // writable again - pipeline.fireChannelWritabilityChanged0(writable: true) + self.pipeline.fireChannelWritabilityChanged0(writable: true) } return result.consumedAll } @@ -512,9 +523,9 @@ final class ServerSocketChannel : BaseSocketChannel { } } - override fileprivate func writeToSocket(pendingWrites: PendingWrites) throws -> Bool? { + override fileprivate func writeToSocket(pendingWrites: PendingWrites) throws -> WriteResult { pendingWrites.failAll(error: ChannelError.operationUnsupported) - return true + return .writtenCompletely } override public func channelRead0(data: IOData) { @@ -834,7 +845,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { pipeline.fireChannelWritabilityChanged0(writable: false) } } else { - // Only support ByteBuffer for now. + // Only support ByteBuffer for now. promise.fail(error: ChannelError.messageUnsupported) } } @@ -1067,7 +1078,7 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { } - fileprivate func writeToSocket(pendingWrites: PendingWrites) throws -> Bool? { + fileprivate func writeToSocket(pendingWrites: PendingWrites) throws -> WriteResult { fatalError("this must be overridden by sub class") } @@ -1127,18 +1138,19 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { private func flushNow() -> Bool { while !closed { do { - if let written = try writeToSocket(pendingWrites: pendingWrites) { - if !written { - // Could not write the next buffer(s) completely - return false - } - // Consume the next buffer(s). - } else { - - // we handled all pending writes + switch try self.writeToSocket(pendingWrites: pendingWrites) { + case .writtenPartially: + // Could not write the next buffer(s) completely + return false + case .wouldBlock: + return false + case .writtenCompletely: + return true + case .closed: + return true + case .nothingToBeWritten: return true } - } catch let err { close0(promise: eventLoop.newPromise(type: Void.self), error: err) diff --git a/Sources/NIO/ChannelHandlers.swift b/Sources/NIO/ChannelHandlers.swift index a7ed7fefa..cbd38273d 100644 --- a/Sources/NIO/ChannelHandlers.swift +++ b/Sources/NIO/ChannelHandlers.swift @@ -46,7 +46,7 @@ public class BackPressureHandler: ChannelHandler { ctx.flush() } - // Propergate the event as the user may still want to do something based on it. + // Propagate the event as the user may still want to do something based on it. ctx.fireChannelWritabilityChanged(writable: writable) } diff --git a/Sources/Sockets/IO.swift b/Sources/Sockets/IO.swift index 0c53107e3..315c0599b 100644 --- a/Sources/Sockets/IO.swift +++ b/Sources/Sockets/IO.swift @@ -64,13 +64,19 @@ func wrapSyscall(_ successCondition: (Int) -> Bool, return try wrapSyscall(function: function, successCondition, fn) } +public enum IOResult { + case wouldBlock + case processed(T) +} + + func wrapSyscallMayBlock(_ successCondition: (Int) -> Bool, - function: @autoclosure () -> String, _ fn: () -> Int) throws -> Int? { + function: @autoclosure () -> String, _ fn: () -> Int) throws -> IOResult { do { - return try withErrno(successCondition: successCondition, fn) + return try .processed(withErrno(successCondition: successCondition, fn)) } catch let e as Errno.POSIXError { if e.code == EWOULDBLOCK { - return nil; + return .wouldBlock } testForBlacklistedErrno(e.code) throw ioError(errno: e.code, function: function()) @@ -93,12 +99,12 @@ func wrapSyscall(_ successCondition: (Int32) -> Bool, } func wrapSyscallMayBlock(_ successCondition: (Int32) -> Bool, - function: @autoclosure () -> String, _ fn: () -> Int32) throws -> Int32? { + function: @autoclosure () -> String, _ fn: () -> Int32) throws -> IOResult { do { - return try withErrno(successCondition: successCondition, fn) + return try .processed(withErrno(successCondition: successCondition, fn)) } catch let e as Errno.POSIXError { if e.code == EWOULDBLOCK { - return nil; + return .wouldBlock } testForBlacklistedErrno(e.code) throw ioError(errno: e.code, function: function()) diff --git a/Sources/Sockets/ServerSocket.swift b/Sources/Sockets/ServerSocket.swift index 6ef6b3b05..af683e5b7 100644 --- a/Sources/Sockets/ServerSocket.swift +++ b/Sources/Sockets/ServerSocket.swift @@ -58,25 +58,26 @@ public final class ServerSocket: BaseSocket { } } - guard let fd = ret else { + switch ret { + case .wouldBlock: return nil - } - -#if os(Linux) - /* no SO_NOSIGPIPE on Linux :( */ - let old_sighandler: sighandler_t = Glibc.signal(SIGPIPE, SIG_IGN) - - let old_sighandler_ptr = unsafeBitCast(old_sighandler, to: UnsafeRawPointer.self) - let sig_err_ptr = unsafeBitCast(SIG_ERR, to: UnsafeRawPointer.self) + case .processed(let fd): + #if os(Linux) + /* no SO_NOSIGPIPE on Linux :( */ + let old_sighandler: sighandler_t = Glibc.signal(SIGPIPE, SIG_IGN) - if old_sighandler_ptr == sig_err_ptr { - return nil - } -#else - // TODO: Handle return code ? - _ = Darwin.fcntl(fd, F_SETNOSIGPIPE, 1); -#endif + let old_sighandler_ptr = unsafeBitCast(old_sighandler, to: UnsafeRawPointer.self) + let sig_err_ptr = unsafeBitCast(SIG_ERR, to: UnsafeRawPointer.self) + + if old_sighandler_ptr == sig_err_ptr { + return nil + } + #else + // TODO: Handle return code ? + _ = Darwin.fcntl(fd, F_SETNOSIGPIPE, 1); + #endif - return Socket(descriptor: fd) + return Socket(descriptor: fd) + } } } diff --git a/Sources/Sockets/Socket.swift b/Sources/Sockets/Socket.swift index c1f5ffe8f..77f3e9b4a 100644 --- a/Sources/Sockets/Socket.swift +++ b/Sources/Sockets/Socket.swift @@ -91,11 +91,11 @@ public final class Socket : BaseSocket { } } - public func write(data: Data) throws -> Int? { + public func write(data: Data) throws -> IOResult { return try data.withUnsafeBytes({ try write(pointer: $0, size: data.count) }) } - public func write(pointer: UnsafePointer, size: Int) throws -> Int? { + public func write(pointer: UnsafePointer, size: Int) throws -> IOResult { guard self.open else { throw IOError(errno: EBADF, reason: "can't write to socket as it's not open anymore.") } @@ -104,7 +104,7 @@ public final class Socket : BaseSocket { } } - public func writev(iovecs: UnsafeBufferPointer) throws -> Int? { + public func writev(iovecs: UnsafeBufferPointer) throws -> IOResult { guard self.open else { throw IOError(errno: EBADF, reason: "can't writev to socket as it's not open anymore.") } @@ -114,11 +114,11 @@ public final class Socket : BaseSocket { } } - public func read(data: inout Data) throws -> Int? { + public func read(data: inout Data) throws -> IOResult { return try data.withUnsafeMutableBytes({ try read(pointer: $0, size: data.count) }) } - public func read(pointer: UnsafeMutablePointer, size: Int) throws -> Int? { + public func read(pointer: UnsafeMutablePointer, size: Int) throws -> IOResult { guard self.open else { throw IOError(errno: EBADF, reason: "can't read from socket as it's not open anymore.") } diff --git a/Sources/SocketsEchoServer/main.swift b/Sources/SocketsEchoServer/main.swift index 2566263ed..cab73b160 100644 --- a/Sources/SocketsEchoServer/main.swift +++ b/Sources/SocketsEchoServer/main.swift @@ -73,10 +73,12 @@ while true { let s = ev.selectable as! Socket do { - if let read = try s.read(data: &buffer.data) { + switch try s.read(data: &buffer.data) { + case .processed(let read): buffer.limit = Int(read) - if let written = try s.write(data: buffer.data.subdata(in: buffer.offset..