From 66e4fdfbba78cf329d5578f3a4de3fa1c4e10c8b Mon Sep 17 00:00:00 2001 From: Matt Eaton Date: Tue, 3 Apr 2018 05:44:14 -0500 Subject: [PATCH] Fixed a few minor typos and some force unwraps (#259) fix some typos, force unwraps and inconsistencies Motivation: Reviewing the code I found a few typos that hindered readability, some unnecessary force unwraps and inconsistencies in the codebase. Modifications: - The main file in NIOWebSocketServer now accepts command line arguments and binds to a passed in host and port like the other server examples do. - Minor typo fixes - removed one force unwrap Result: - The result of my change will bring the NIOWebSocketServer more inline with how the NIOHTTP1 and NIOChat servers examples are setup. - less force unwrapping - fewer typos [message edited by @weissi] --- Sources/NIO/Bootstrap.swift | 2 +- Sources/NIO/ByteBuffer-core.swift | 2 +- Sources/NIO/Codec.swift | 2 +- Sources/NIO/CompositeError.swift | 2 +- Sources/NIO/EventLoop.swift | 2 +- Sources/NIO/EventLoopFuture.swift | 4 +- Sources/NIO/FileRegion.swift | 2 +- Sources/NIO/LinuxCPUSet.swift | 2 +- Sources/NIO/MarkedCircularBuffer.swift | 2 +- .../NIO/PendingDatagramWritesManager.swift | 2 +- Sources/NIO/Selector.swift | 2 +- Sources/NIO/Thread.swift | 2 +- Sources/NIOChatServer/main.swift | 10 ++-- Sources/NIOHTTP1Server/main.swift | 6 ++- Sources/NIOWebSocketServer/main.swift | 46 ++++++++++++++++++- 15 files changed, 69 insertions(+), 19 deletions(-) diff --git a/Sources/NIO/Bootstrap.swift b/Sources/NIO/Bootstrap.swift index 3b4c4ce7f..6de45c702 100644 --- a/Sources/NIO/Bootstrap.swift +++ b/Sources/NIO/Bootstrap.swift @@ -23,7 +23,7 @@ /// .serverChannelOption(ChannelOptions.backlog, value: 256) /// .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) /// -/// // Set the handlers that are appled to the accepted child `Channel`s. +/// // Set the handlers that are applied to the accepted child `Channel`s. /// .childChannelInitializer { channel in /// // Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline. /// channel.pipeline.add(handler: BackPressureHandler()).then { () in diff --git a/Sources/NIO/ByteBuffer-core.swift b/Sources/NIO/ByteBuffer-core.swift index 6affd28f4..a5f39eff9 100644 --- a/Sources/NIO/ByteBuffer-core.swift +++ b/Sources/NIO/ByteBuffer-core.swift @@ -145,7 +145,7 @@ private func toIndex(_ value: Int) -> Index { /// The 'discardable bytes' are usually bytes that have already been read, they can however still be accessed using /// the random access methods. 'Readable bytes' are the bytes currently available to be read using the sequential /// access interface (`read`/`write`). Getting `writableBytes` (bytes beyond the writer index) is undefined -/// behaviour and might yield aribitrary bytes (_not_ `0` initialised). +/// behaviour and might yield arbitrary bytes (_not_ `0` initialised). /// /// ### Slicing /// `ByteBuffer` supports slicing a `ByteBuffer` without copying the underlying storage. diff --git a/Sources/NIO/Codec.swift b/Sources/NIO/Codec.swift index cd973583c..d71658579 100644 --- a/Sources/NIO/Codec.swift +++ b/Sources/NIO/Codec.swift @@ -99,7 +99,7 @@ extension ByteToMessageDecoder { /// Calls `decode` until there is nothing left to decode. public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { var buffer = self.unwrapInboundIn(data) - + if self.cumulationBuffer != nil { self.cumulationBuffer!.write(buffer: &buffer) buffer = self.cumulationBuffer! diff --git a/Sources/NIO/CompositeError.swift b/Sources/NIO/CompositeError.swift index 2b5d715c4..13cd53000 100644 --- a/Sources/NIO/CompositeError.swift +++ b/Sources/NIO/CompositeError.swift @@ -14,7 +14,7 @@ /// An `Error` that represents multiple errors that occurred during an operation. /// -/// Because SwiftNIO frequently does multiple jobs at once, it is possible some operatons out +/// Because SwiftNIO frequently does multiple jobs at once, it is possible some operations out /// of a set of operations may fail. This is most noticeable with `Channel.flush` on the /// `DatagramChannel`, where some, but not all, of the datagram writes may fail. In this case /// the `flush` should accurately represent that set of possibilities. The `NIOCompositeError` diff --git a/Sources/NIO/EventLoop.swift b/Sources/NIO/EventLoop.swift index c1338e62c..84ddfe1cc 100644 --- a/Sources/NIO/EventLoop.swift +++ b/Sources/NIO/EventLoop.swift @@ -86,7 +86,7 @@ public protocol EventLoop: EventLoopGroup { /// Submit a given task to be executed by the `EventLoop`. Once the execution is complete the returned `EventLoopFuture` is notified. /// /// - parameters: - /// - task: The closure that will be submited to the `EventLoop` for execution. + /// - task: The closure that will be submitted to the `EventLoop` for execution. /// - returns: `EventLoopFuture` that is notified once the task was executed. func submit(_ task: @escaping () throws -> T) -> EventLoopFuture diff --git a/Sources/NIO/EventLoopFuture.swift b/Sources/NIO/EventLoopFuture.swift index 3acdfa43d..482d20e84 100644 --- a/Sources/NIO/EventLoopFuture.swift +++ b/Sources/NIO/EventLoopFuture.swift @@ -322,7 +322,7 @@ public struct EventLoopPromise { /// /// This means that for any `EventLoopFuture` that your code did not create itself (via /// `EventLoopPromise.futureResult`), use of `hopTo` is **strongly encouraged** to help guarantee thread-safety. It -/// should only be elided when thread-safety is provably not needed. +/// should only be elided when thread-safety is proved to be not needed. /// /// The "thread affinity" of `EventLoopFuture`s is critical to writing safe, performant concurrent code without /// boilerplate. It allows you to avoid needing to write or use locks in your own code, instead using the natural @@ -734,7 +734,7 @@ extension EventLoopFuture { /// Fulfill the given `EventLoopPromise` with the results from this `EventLoopFuture`. /// /// This is useful when allowing users to provide promises for you to fulfill, but - /// when you are calling functions that return their own proimses. They allow you to + /// when you are calling functions that return their own promises. They allow you to /// tidy up your computational pipelines. For example: /// /// ``` diff --git a/Sources/NIO/FileRegion.swift b/Sources/NIO/FileRegion.swift index 9e7e7730b..664af8431 100644 --- a/Sources/NIO/FileRegion.swift +++ b/Sources/NIO/FileRegion.swift @@ -17,7 +17,7 @@ /// Usually a `FileRegion` will allow the underlying transport to use `sendfile` to transfer its content and so allows transferring /// the file content without copying it into user-space at all. If the actual transport implementation really can make use of sendfile /// or if it will need to copy the content to user-space first and use `write` / `writev` is an implementation detail. That said -/// using `FileRegion` is the recommend way to transfer file content if possible. +/// using `FileRegion` is the recommended way to transfer file content if possible. /// /// One important note, depending your `ChannelPipeline` setup it may not be possible to use a `FileRegion` as a `ChannelHandler` may /// need access to the bytes (in a `ByteBuffer`) to transform these. diff --git a/Sources/NIO/LinuxCPUSet.swift b/Sources/NIO/LinuxCPUSet.swift index 367d25c52..28bb881de 100644 --- a/Sources/NIO/LinuxCPUSet.swift +++ b/Sources/NIO/LinuxCPUSet.swift @@ -20,7 +20,7 @@ import CNIOLinux /// The ids of all the cpus. let cpuIds: Set - /// Create a new instace + /// Create a new instance /// /// - arguments: /// - cpuIds: The `Set` of CPU ids. It must be non-empty and can not contain invalid ids. diff --git a/Sources/NIO/MarkedCircularBuffer.swift b/Sources/NIO/MarkedCircularBuffer.swift index 405b09b66..45bf7063c 100644 --- a/Sources/NIO/MarkedCircularBuffer.swift +++ b/Sources/NIO/MarkedCircularBuffer.swift @@ -89,7 +89,7 @@ public struct MarkedCircularBuffer: CustomStringConvertible, AppendableCollec // MARK: Marking - /// Marks the buffer at the current index, making the last idex in the buffer marked. + /// Marks the buffer at the current index, making the last index in the buffer marked. public mutating func mark() { let count = self.buffer.count if count > 0 { diff --git a/Sources/NIO/PendingDatagramWritesManager.swift b/Sources/NIO/PendingDatagramWritesManager.swift index e608f4b34..88e352f54 100644 --- a/Sources/NIO/PendingDatagramWritesManager.swift +++ b/Sources/NIO/PendingDatagramWritesManager.swift @@ -339,7 +339,7 @@ extension PendingDatagramWritesState { /// value. The most important purpose of this object is to call `sendto` or `sendmmsg` depending on the writes held and /// the availability of the functions. final class PendingDatagramWritesManager: PendingWritesManager { - /// Storage for mmsghdr strutures. Only present on Linux because Darwin does not support + /// Storage for mmsghdr structures. Only present on Linux because Darwin does not support /// gathering datagram writes. private var msgs: UnsafeMutableBufferPointer diff --git a/Sources/NIO/Selector.swift b/Sources/NIO/Selector.swift index 135cad6fe..08fd8cb7d 100644 --- a/Sources/NIO/Selector.swift +++ b/Sources/NIO/Selector.swift @@ -127,7 +127,7 @@ final class Selector { /* this is technically a bad idea as we're abusing ARC to deallocate scarce resources (a file descriptor) for us. However, this is used for the event loop so there shouldn't be much churn. - The reson we do this is because `self.wakeup()` may (and will!) be called on arbitrary threads. To not + The reason we do this is because `self.wakeup()` may (and will!) be called on arbitrary threads. To not suffer from race conditions we would need to protect waking the selector up and closing the selector. That is likely to cause performance problems. By abusing ARC, we get the guarantee that there won't be any future wakeup calls as there are no references to this selector left. 💁 diff --git a/Sources/NIO/Thread.swift b/Sources/NIO/Thread.swift index 5dd7e077b..4eca22058 100644 --- a/Sources/NIO/Thread.swift +++ b/Sources/NIO/Thread.swift @@ -77,7 +77,7 @@ final class Thread { /// - name: The name of the `Thread` or `nil` if no specific name should be set. /// - body: The function to execute within the spawned `Thread`. static func spawnAndRun(name: String? = nil, body: @escaping (Thread) -> Void) { - // Unfortunally the pthread_create method take a different first argument depending on if its on linux or macOS, so ensure we use the correct one. + // Unfortunately the pthread_create method take a different first argument depending on if its on linux or macOS, so ensure we use the correct one. #if os(Linux) var pt: pthread_t = pthread_t() #else diff --git a/Sources/NIOChatServer/main.swift b/Sources/NIOChatServer/main.swift index 200efdf83..cbfb4a2d0 100644 --- a/Sources/NIOChatServer/main.swift +++ b/Sources/NIOChatServer/main.swift @@ -40,7 +40,7 @@ final class LineDelimiterCodec: ByteToMessageDecoder { /// /// As we are using an `MultiThreadedEventLoopGroup` that uses more then 1 thread we need to ensure proper /// synchronization on the shared state in the `ChatHandler` (as the same instance is shared across -/// child `Channel`s). For this a serial `DispatchQueue` is used when we modify the shared state (the `Dictonary`). +/// child `Channel`s). For this a serial `DispatchQueue` is used when we modify the shared state (the `Dictionary`). /// As `ChannelHandlerContext` is not thread-safe we need to ensure we only operate on the `Channel` itself while /// `Dispatch` executed the submitted block. final class ChatHandler: ChannelInboundHandler { @@ -119,7 +119,7 @@ let bootstrap = ServerBootstrap(group: group) .serverChannelOption(ChannelOptions.backlog, value: 256) .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) - // Set the handlers that are appled to the accepted Channels + // Set the handlers that are applied to the accepted Channels .childChannelInitializer { channel in // Add handler that will buffer data until a \n is received channel.pipeline.add(handler: LineDelimiterCodec()).then { v in @@ -177,7 +177,11 @@ let channel = try { () -> Channel in } }() -print("ChatServer started and listening on \(channel.localAddress!)") +if let localAddress = channel.localAddress { + print("ChatServer started and listening on \(localAddress)") +} else { + print("ChatServer started but the address could not be determined.") +} // This will never unblock as we don't close the ServerChannel. try channel.closeFuture.wait() diff --git a/Sources/NIOHTTP1Server/main.swift b/Sources/NIOHTTP1Server/main.swift index e2873eb8a..0830860c6 100644 --- a/Sources/NIOHTTP1Server/main.swift +++ b/Sources/NIOHTTP1Server/main.swift @@ -498,7 +498,11 @@ let channel = try { () -> Channel in } }() -print("Server started and listening on \(channel.localAddress!), htdocs path \(htdocs)") +if let localAddress = channel.localAddress { + print("Server started and listening on \(localAddress), htdocs path \(htdocs)") +} else { + print("Server started but the address could not be determined, htdocs path \(htdocs)") +} // This will never unblock as we don't close the ServerChannel try channel.closeFuture.wait() diff --git a/Sources/NIOWebSocketServer/main.swift b/Sources/NIOWebSocketServer/main.swift index 93ec87f56..83131f765 100644 --- a/Sources/NIOWebSocketServer/main.swift +++ b/Sources/NIOWebSocketServer/main.swift @@ -224,9 +224,51 @@ defer { try! group.syncShutdownGracefully() } +// First argument is the program path +let arguments = CommandLine.arguments +let arg1 = arguments.dropFirst().first +let arg2 = arguments.dropFirst(2).first -let channel = try! bootstrap.bind(host: "localhost", port: 8888).wait() -print("Server started and listening on \(channel.localAddress!)") +let defaultHost = "localhost" +let defaultPort = 8888 + +enum BindTo { + case ip(host: String, port: Int) + case unixDomainSocket(path: String) +} + +let bindTarget: BindTo +switch (arg1, arg1.flatMap(Int.init), arg2.flatMap(Int.init)) { +case (.some(let h), _ , .some(let p)): + /* we got two arguments, let's interpret that as host and port */ + bindTarget = .ip(host: h, port: p) + +case (let portString?, .none, _): + // Couldn't parse as number, expecting unix domain socket path. + bindTarget = .unixDomainSocket(path: portString) + +case (_, let p?, _): + // Only one argument --> port. + bindTarget = .ip(host: defaultHost, port: p) + +default: + bindTarget = .ip(host: defaultHost, port: defaultPort) +} + +let channel = try { () -> Channel in + switch bindTarget { + case .ip(let host, let port): + return try bootstrap.bind(host: host, port: port).wait() + case .unixDomainSocket(let path): + return try bootstrap.bind(unixDomainSocketPath: path).wait() + } +}() + +if let localAddress = channel.localAddress { + print("Server started and listening on \(localAddress)") +} else { + print("Server started but the address could not be determined.") +} // This will never unblock as we don't close the ServerChannel try channel.closeFuture.wait()