Skip to content

Commit

Permalink
Rebase Kitura-NIO on NIO2 (#176)
Browse files Browse the repository at this point in the history
* Adopt NIO 2

* Remove non-Swift 5 builds from Travis

* Update swift-nio to 2.0.0

* Remove TODO comment

* Update CI build images and .swift-version

* Remove explicit Int initialisation
  • Loading branch information
Pushkar N Kulkarni authored Apr 3, 2019
1 parent d403683 commit a20358f
Show file tree
Hide file tree
Showing 13 changed files with 135 additions and 142 deletions.
2 changes: 1 addition & 1 deletion .swift-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
4.2.3
5.0
32 changes: 7 additions & 25 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,43 +15,25 @@ matrix:
dist: xenial
sudo: required
services: docker
env: DOCKER_IMAGE=swift:4.0.3 SWIFT_SNAPSHOT=4.0.3 CUSTOM_TEST_SCRIPT=.kitura-test.sh DOCKER_PRIVILEGED=true
env: DOCKER_IMAGE=swift:5.0-xenial DOCKER_PRIVILEGED=true SWIFT_TEST_ARGS="--parallel"
- os: linux
dist: xenial
sudo: required
services: docker
env: DOCKER_IMAGE=swift:4.1.3 SWIFT_SNAPSHOT=4.1.3 CUSTOM_TEST_SCRIPT=.kitura-test.sh DOCKER_PRIVILEGED=true
env: DOCKER_IMAGE=swift:5.0 DOCKER_PRIVILEGED=true SWIFT_TEST_ARGS="--parallel"
- os: linux
dist: xenial
sudo: required
services: docker
env: DOCKER_IMAGE=swift:4.2.3 SWIFT_TEST_ARGS="--parallel" DOCKER_PRIVILEGED=true
- os: linux
dist: xenial
sudo: required
services: docker
env: DOCKER_IMAGE=swift:4.2.3 SWIFT_SNAPSHOT=$SWIFT_DEVELOPMENT_SNAPSHOT DOCKER_PRIVILEGED=true
- os: linux
dist: xenial
sudo: required
services: docker
env: DOCKER_IMAGE=ubuntu:18.04 DOCKER_PRIVILEGED=true
- os: osx
osx_image: xcode9.2
sudo: required
env: SWIFT_SNAPSHOT=4.0.3 BREW_INSTALL_PACKAGES="libressl" CUSTOM_TEST_SCRIPT=.kitura-test.sh
- os: osx
osx_image: xcode9.4
sudo: required
env: SWIFT_SNAPSHOT=4.1.2 JAZZY_ELIGIBLE=true CODECOV_ELIGIBLE=true BREW_INSTALL_PACKAGES="libressl"
env: DOCKER_IMAGE=swift:5.0 SWIFT_SNAPSHOT=$SWIFT_DEVELOPMENT_SNAPSHOT DOCKER_PRIVILEGED=true SWIFT_TEST_ARGS="--parallel"
- os: osx
osx_image: xcode10.1
osx_image: xcode10.2
sudo: required
env: SWIFT_TEST_ARGS="--parallel" BREW_INSTALL_PACKAGES="libressl"
env: JAZZY_ELIGIBLE=true SWIFT_TEST_ARGS="--parallel"
- os: osx
osx_image: xcode10.1
osx_image: xcode10.2
sudo: required
env: SWIFT_SNAPSHOT=$SWIFT_DEVELOPMENT_SNAPSHOT BREW_INSTALL_PACKAGES="libressl" CUSTOM_TEST_SCRIPT=.kitura-test.sh
env: SWIFT_SNAPSHOT=$SWIFT_DEVELOPMENT_SNAPSHOT SWIFT_TEST_ARGS="--parallel"

before_install:
- git clone https://github.com/IBM-Swift/Package-Builder.git
Expand Down
8 changes: 4 additions & 4 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// swift-tools-version:4.0
// swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
/*
* Copyright IBM Corporation 2016, 2017, 2018
Expand Down Expand Up @@ -28,8 +28,8 @@ let package = Package(
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/apple/swift-nio.git", from: "1.0.0"),
.package(url: "https://github.com/apple/swift-nio-ssl.git", from: "1.0.1"),
.package(url: "https://github.com/apple/swift-nio.git", from: "2.0.0"),
.package(url: "https://github.com/apple/swift-nio-ssl.git", from: "2.0.0"),
.package(url: "https://github.com/IBM-Swift/BlueSSLService.git", from: "1.0.0"),
.package(url: "https://github.com/IBM-Swift/LoggerAPI.git", from: "1.7.3")
],
Expand All @@ -41,7 +41,7 @@ let package = Package(
dependencies: []),
.target(
name: "KituraNet",
dependencies: ["NIO", "NIOFoundationCompat", "NIOHTTP1", "NIOOpenSSL", "SSLService", "LoggerAPI", "NIOWebSocket", "CLinuxHelpers"]),
dependencies: ["NIO", "NIOFoundationCompat", "NIOHTTP1", "NIOSSL", "SSLService", "LoggerAPI", "NIOWebSocket", "CLinuxHelpers"]),
.testTarget(
name: "KituraNetTests",
dependencies: ["KituraNet"])
Expand Down
4 changes: 2 additions & 2 deletions Sources/KituraNet/BufferList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public class BufferList {
*/
public func append(bytes: UnsafePointer<UInt8>, length: Int) {
byteBuffer.write(bytes: UnsafeBufferPointer(start: bytes, count: length))
byteBuffer.writeBytes(UnsafeBufferPointer(start: bytes, count: length))
}

/**
Expand All @@ -130,7 +130,7 @@ public class BufferList {
*/
public func append(data: Data) {
byteBuffer.write(bytes: data)
byteBuffer.writeBytes(data)
}

/**
Expand Down
24 changes: 12 additions & 12 deletions Sources/KituraNet/ClientRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import NIO
import NIOHTTP1
import Foundation
import NIOOpenSSL
import NIOSSL
import LoggerAPI
import Dispatch

Expand Down Expand Up @@ -159,7 +159,7 @@ public class ClientRequest {
/// The current redirection count
internal var redirectCount: Int = 0

private var sslContext: NIOOpenSSL.SSLContext?
private var sslContext: NIOSSLContext?

/// Should HTTP/2 protocol be used
private var useHTTP2 = false
Expand Down Expand Up @@ -608,7 +608,7 @@ public class ClientRequest {
private func initializeClientBootstrapWithSSL(eventLoopGroup: EventLoopGroup) {
if let sslConfig = self.sslConfig {
do {
sslContext = try SSLContext(configuration: sslConfig)
sslContext = try NIOSSLContext(configuration: sslConfig)
} catch let error {
Log.error("Failed to create SSLContext. Error: \(error)")
}
Expand All @@ -617,9 +617,9 @@ public class ClientRequest {
bootstrap = ClientBootstrap(group: eventLoopGroup)
.channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.channelInitializer { channel in
channel.pipeline.add(handler: try! OpenSSLClientHandler(context: self.sslContext!)).then {
channel.pipeline.addHTTPClientHandlers().then {
channel.pipeline.add(handler: HTTPClientHandler(request: self))
channel.pipeline.addHandler(try! NIOSSLClientHandler(context: self.sslContext!, serverHostname: nil)).flatMap {
channel.pipeline.addHTTPClientHandlers().flatMap {
channel.pipeline.addHandler(HTTPClientHandler(request: self))
}
}
}
Expand All @@ -629,8 +629,8 @@ public class ClientRequest {
bootstrap = ClientBootstrap(group: eventLoopGroup)
.channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.channelInitializer { channel in
channel.pipeline.addHTTPClientHandlers().then {
channel.pipeline.add(handler: HTTPClientHandler(request: self))
channel.pipeline.addHTTPClientHandlers().flatMap {
channel.pipeline.addHandler(HTTPClientHandler(request: self))
}
}
}
Expand Down Expand Up @@ -745,19 +745,19 @@ class HTTPClientHandler: ChannelInboundHandler {
typealias InboundIn = HTTPClientResponsePart

/// Read the header, body and trailer. Redirection is handled in the trailer case.
func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let response = self.unwrapInboundIn(data)
switch response {
case .head(let header):
clientResponse.httpHeaders = header.headers
clientResponse.httpVersionMajor = header.version.major
clientResponse.httpVersionMinor = header.version.minor
clientResponse.httpVersionMajor = UInt16(header.version.major)
clientResponse.httpVersionMinor = UInt16(header.version.minor)
clientResponse.statusCode = HTTPStatusCode(rawValue: Int(header.status.code))!
case .body(var buffer):
if clientResponse.buffer == nil {
clientResponse.buffer = BufferList(with: buffer)
} else {
clientResponse.buffer!.byteBuffer.write(buffer: &buffer)
clientResponse.buffer!.byteBuffer.writeBuffer(&buffer)
}
case .end:
// Handle redirection
Expand Down
36 changes: 19 additions & 17 deletions Sources/KituraNet/HTTP/HTTPRequestHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import LoggerAPI
import Foundation
import Dispatch

internal class HTTPRequestHandler: ChannelInboundHandler {
internal class HTTPRequestHandler: ChannelInboundHandler, RemovableChannelHandler {

/// The HTTPServer instance on which this handler is installed
var server: HTTPServer
Expand Down Expand Up @@ -70,7 +70,7 @@ internal class HTTPRequestHandler: ChannelInboundHandler {
public typealias InboundIn = HTTPServerRequestPart
public typealias OutboundOut = HTTPServerResponsePart

public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let request = self.unwrapInboundIn(data)
// If an error response was already sent, we'd want to spare running through this for now.
// If an upgrade to WebSocket fails, both `errorCaught` and `channelRead` are triggered.
Expand All @@ -79,7 +79,7 @@ internal class HTTPRequestHandler: ChannelInboundHandler {

switch request {
case .head(let header):
serverRequest = HTTPServerRequest(ctx: ctx, requestHead: header, enableSSL: enableSSLVerification)
serverRequest = HTTPServerRequest(ctx: context, requestHead: header, enableSSL: enableSSLVerification)
self.clientRequestedKeepAlive = header.isKeepAlive
case .body(var buffer):
guard let serverRequest = serverRequest else {
Expand All @@ -89,10 +89,10 @@ internal class HTTPRequestHandler: ChannelInboundHandler {
if serverRequest.buffer == nil {
serverRequest.buffer = BufferList(with: buffer)
} else {
serverRequest.buffer!.byteBuffer.write(buffer: &buffer)
serverRequest.buffer!.byteBuffer.writeBuffer(&buffer)
}
case .end:
serverResponse = HTTPServerResponse(channel: ctx.channel, handler: self)
serverResponse = HTTPServerResponse(channel: context.channel, handler: self)
//Make sure we use the latest delegate registered with the server
DispatchQueue.global().async {
guard let serverRequest = self.serverRequest, let serverResponse = self.serverResponse else { return }
Expand All @@ -104,17 +104,17 @@ internal class HTTPRequestHandler: ChannelInboundHandler {
}

//IdleStateEvents are received on this method
public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) {
public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
if event is IdleStateHandler.IdleStateEvent {
_ = ctx.close()
_ = context.close()
}
}

public func channelReadComplete(ctx: ChannelHandlerContext) {
ctx.flush()
public func channelReadComplete(context: ChannelHandlerContext) {
context.flush()
}

public func errorCaught(ctx: ChannelHandlerContext, error: Error) {
public func errorCaught(context: ChannelHandlerContext, error: Error) {
guard !errorResponseSent else { return }
var message: String?
switch error {
Expand All @@ -128,18 +128,20 @@ internal class HTTPRequestHandler: ChannelInboundHandler {
break
case KituraWebSocketUpgradeError.invalidVersionHeader(_):
message = "Only WebSocket protocol version 13 is supported"
case NIOWebSocketUpgradeError.unsupportedWebSocketTarget:
let target = server.latestWebSocketURI ?? "/<unknown>"
message = "No service has been registered for the path \(target)"
default:
// Don't handle any other errors, including `HTTPParserError`s.
// We could log an error message here.
ctx.close(promise: nil)
// Handle only NIOWebSocketUpgradeError here, nothing else
if let upgradeError = error as? NIOWebSocketUpgradeError, upgradeError == .unsupportedWebSocketTarget {
let target = server.latestWebSocketURI ?? "/<unknown>"
message = "No service has been registered for the path \(target)"
return
}
// TODO: Do we log an error message here?
context.close(promise: nil)
return
}

do {
serverResponse = HTTPServerResponse(channel: ctx.channel, handler: self)
serverResponse = HTTPServerResponse(channel: context.channel, handler: self)
errorResponseSent = true
try serverResponse?.end(with: .badRequest, message: message)
} catch {
Expand Down
Loading

0 comments on commit a20358f

Please sign in to comment.