1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
|
//===----------------------------------------------------------------------===//
//
// 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
import NIOConcurrencyHelpers
import Dispatch
@testable import NIO
class EchoServerClientTest : XCTestCase {
func testEcho() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let numBytes = 16 * 1024
let countingHandler = ByteCountingHandler(numBytes: numBytes, promise: group.next().makePromise())
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.addHandler(countingHandler)
}.bind(host: "127.0.0.1", port: 0).wait())
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
.connect(to: serverChannel.localAddress!)
.wait())
defer {
XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed())
}
var buffer = clientChannel.allocator.buffer(capacity: numBytes)
for i in 0..<numBytes {
buffer.writeInteger(UInt8(i % 256))
}
try clientChannel.writeAndFlush(NIOAny(buffer)).wait()
try countingHandler.assertReceived(buffer: buffer)
}
func testLotsOfUnflushedWrites() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.addHandler(WriteALotHandler())
}.bind(host: "127.0.0.1", port: 0).wait())
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
let promise = group.next().makePromise(of: ByteBuffer.self)
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
.channelInitializer { channel in
channel.pipeline.addHandler(WriteOnConnectHandler(toWrite: "X")).flatMap { v2 in
channel.pipeline.addHandler(ByteCountingHandler(numBytes: 10000, promise: promise))
}
}
.connect(to: serverChannel.localAddress!).wait())
defer {
_ = clientChannel.close()
}
let bytes = try promise.futureResult.wait()
let expected = String(decoding: Array(repeating: "X".utf8.first!, count: 10000), as: Unicode.UTF8.self)
XCTAssertEqual(expected, bytes.getString(at: bytes.readerIndex, length: bytes.readableBytes))
}
func testEchoUnixDomainSocket() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
try withTemporaryUnixDomainSocketPathName { udsPath in
let numBytes = 16 * 1024
let countingHandler = ByteCountingHandler(numBytes: numBytes, promise: group.next().makePromise())
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
// Set the handlers that are appled to the accepted Channels
.childChannelInitializer { channel in
// Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline.
channel.pipeline.addHandler(countingHandler)
}.bind(unixDomainSocketPath: udsPath).wait())
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
.connect(to: serverChannel.localAddress!)
.wait())
defer {
XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed())
}
var buffer = clientChannel.allocator.buffer(capacity: numBytes)
for i in 0..<numBytes {
buffer.writeInteger(UInt8(i % 256))
}
XCTAssertNoThrow(try clientChannel.writeAndFlush(NIOAny(buffer)).wait())
XCTAssertNoThrow(try countingHandler.assertReceived(buffer: buffer))
}
}
func testConnectUnixDomainSocket() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
try withTemporaryUnixDomainSocketPathName { udsPath in
let numBytes = 16 * 1024
let countingHandler = ByteCountingHandler(numBytes: numBytes, promise: group.next().makePromise())
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
// Set the handlers that are appled to the accepted Channels
.childChannelInitializer { channel in
channel.pipeline.addHandler(countingHandler)
}.bind(unixDomainSocketPath: udsPath).wait())
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
.connect(unixDomainSocketPath: udsPath)
.wait())
defer {
XCTAssertNoThrow(try clientChannel.close().wait())
}
var buffer = clientChannel.allocator.buffer(capacity: numBytes)
for i in 0..<numBytes {
buffer.writeInteger(UInt8(i % 256))
}
try clientChannel.writeAndFlush(NIOAny(buffer)).wait()
try countingHandler.assertReceived(buffer: buffer)
}
}
func testCleanupUnixDomainSocket() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
try withTemporaryUnixDomainSocketPathName { udsPath in
let bootstrap = ServerBootstrap(group: group)
let serverChannel = try assertNoThrowWithValue(
bootstrap.bind(unixDomainSocketPath: udsPath).wait())
XCTAssertNoThrow(try serverChannel.close().wait())
let reusedPathServerChannel = try assertNoThrowWithValue(
bootstrap.bind(unixDomainSocketPath: udsPath,
cleanupExistingSocketFile: true).wait())
XCTAssertNoThrow(try reusedPathServerChannel.close().wait())
}
}
func testBootstrapUnixDomainSocketNameClash() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
try withTemporaryUnixDomainSocketPathName { udsPath in
// Bootstrap should not overwrite an existing file unless it is a socket
FileManager.default.createFile(atPath: udsPath, contents: nil, attributes: nil)
let bootstrap = ServerBootstrap(group: group)
XCTAssertThrowsError(
try bootstrap.bind(unixDomainSocketPath: udsPath).wait())
}
}
func testChannelActiveOnConnect() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let handler = ChannelActiveHandler()
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.bind(host: "127.0.0.1", port: 0).wait())
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
.channelInitializer { $0.pipeline.addHandler(handler) }
.connect(to: serverChannel.localAddress!).wait())
defer {
XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed())
}
XCTAssertNoThrow(try handler.assertChannelActiveFired())
}
func testWriteThenRead() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.addHandler(EchoServer())
}.bind(host: "127.0.0.1", port: 0).wait())
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
let numBytes = 16 * 1024
let countingHandler = ByteCountingHandler(numBytes: numBytes, promise: group.next().makePromise())
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
.channelInitializer { $0.pipeline.addHandler(countingHandler) }
.connect(to: serverChannel.localAddress!).wait())
defer {
XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed())
}
var buffer = clientChannel.allocator.buffer(capacity: numBytes)
for i in 0..<numBytes {
buffer.writeInteger(UInt8(i % 256))
}
XCTAssertNoThrow(try clientChannel.writeAndFlush(NIOAny(buffer)).wait())
XCTAssertNoThrow(try countingHandler.assertReceived(buffer: buffer))
}
private final class ChannelActiveHandler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
private var promise: EventLoopPromise<Void>! = nil
func handlerAdded(context: ChannelHandlerContext) {
promise = context.channel.eventLoop.makePromise()
}
func channelActive(context: ChannelHandlerContext) {
promise.succeed(())
context.fireChannelActive()
}
func assertChannelActiveFired() throws {
try promise.futureResult.wait()
}
}
private final class EchoServer: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
typealias OutboundOut = ByteBuffer
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
context.write(data, promise: nil)
}
func channelReadComplete(context: ChannelHandlerContext) {
context.flush()
}
}
private final class EchoAndEchoAgainAfterSomeTimeServer: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
typealias OutboundOut = ByteBuffer
private let timeAmount: TimeAmount
private let group = DispatchGroup()
private var numberOfReads: Int = 0
private let calloutQ = DispatchQueue(label: "EchoAndEchoAgainAfterSomeTimeServer callback queue")
public init(time: TimeAmount, secondWriteDoneHandler: @escaping () -> Void) {
self.timeAmount = time
self.group.enter()
self.group.notify(queue: self.calloutQ) {
secondWriteDoneHandler()
}
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
self.numberOfReads += 1
precondition(self.numberOfReads == 1, "\(self) is only ever allowed to read once")
_ = context.eventLoop.scheduleTask(in: self.timeAmount) {
context.writeAndFlush(data, promise: nil)
self.group.leave()
}.futureResult.recover { e in
XCTFail("we failed to schedule the task: \(e)")
self.group.leave()
}
context.writeAndFlush(data, promise: nil)
}
}
private final class WriteALotHandler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
typealias OutboundOut = ByteBuffer
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
for _ in 0..<10000 {
context.write(data, promise: nil)
}
}
func channelReadComplete(context: ChannelHandlerContext) {
context.flush()
}
}
private final class CloseInInActiveAndUnregisteredChannelHandler: ChannelInboundHandler {
typealias InboundIn = Never
let alreadyClosedInChannelInactive = NIOAtomic<Bool>.makeAtomic(value: false)
let alreadyClosedInChannelUnregistered = NIOAtomic<Bool>.makeAtomic(value: false)
let channelUnregisteredPromise: EventLoopPromise<Void>
let channelInactivePromise: EventLoopPromise<Void>
public init(channelUnregisteredPromise: EventLoopPromise<Void>,
channelInactivePromise: EventLoopPromise<Void>) {
self.channelUnregisteredPromise = channelUnregisteredPromise
self.channelInactivePromise = channelInactivePromise
}
public func channelActive(context: ChannelHandlerContext) {
context.close().whenFailure { error in
XCTFail("bad, initial close failed (\(error))")
}
}
public func channelInactive(context: ChannelHandlerContext) {
if alreadyClosedInChannelInactive.compareAndExchange(expected: false, desired: true) {
XCTAssertFalse(self.channelUnregisteredPromise.futureResult.isFulfilled,
"channelInactive should fire before channelUnregistered")
context.close().map {
XCTFail("unexpected success")
}.recover { err in
switch err {
case ChannelError.alreadyClosed:
// OK
()
default:
XCTFail("unexpected error: \(err)")
}
}.whenComplete { (_: Result<Void, Error>) in
self.channelInactivePromise.succeed(())
}
}
}
public func channelUnregistered(context: ChannelHandlerContext) {
if alreadyClosedInChannelUnregistered.compareAndExchange(expected: false, desired: true) {
XCTAssertTrue(self.channelInactivePromise.futureResult.isFulfilled,
"when channelUnregister fires, channelInactive should already have fired")
context.close().map {
XCTFail("unexpected success")
}.recover { err in
switch err {
case ChannelError.alreadyClosed:
// OK
()
default:
XCTFail("unexpected error: \(err)")
}
}.whenComplete { (_: Result<Void, Error>) in
self.channelUnregisteredPromise.succeed(())
}
}
}
}
/// A channel handler that calls write on connect.
private class WriteOnConnectHandler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
private let toWrite: String
init(toWrite: String) {
self.toWrite = toWrite
}
func channelActive(context: ChannelHandlerContext) {
let dataToWrite = context.channel.allocator.buffer(string: toWrite)
context.writeAndFlush(NIOAny(dataToWrite), promise: nil)
context.fireChannelActive()
}
}
func testCloseInInactive() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let inactivePromise = group.next().makePromise() as EventLoopPromise<Void>
let unregistredPromise = group.next().makePromise() as EventLoopPromise<Void>
let handler = CloseInInActiveAndUnregisteredChannelHandler(channelUnregisteredPromise: unregistredPromise,
channelInactivePromise: inactivePromise)
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.addHandler(handler)
}.bind(host: "127.0.0.1", port: 0).wait())
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
.connect(to: serverChannel.localAddress!)
.wait())
defer {
_ = clientChannel.close()
}
_ = try inactivePromise.futureResult.and(unregistredPromise.futureResult).wait()
XCTAssertTrue(handler.alreadyClosedInChannelInactive.load())
XCTAssertTrue(handler.alreadyClosedInChannelUnregistered.load())
}
func testFlushOnEmpty() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let writingBytes = "hello"
let bytesReceivedPromise = group.next().makePromise(of: ByteBuffer.self)
let byteCountingHandler = ByteCountingHandler(numBytes: writingBytes.utf8.count, promise: bytesReceivedPromise)
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
// When we've received all the bytes we know the connection is up. Remove the handler.
_ = bytesReceivedPromise.futureResult.flatMap { (_: ByteBuffer) in
channel.pipeline.removeHandler(byteCountingHandler)
}
return channel.pipeline.addHandler(byteCountingHandler)
}.bind(host: "127.0.0.1", port: 0).wait())
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
.connect(to: serverChannel.localAddress!)
.wait())
defer {
_ = clientChannel.close()
}
// First we confirm that the channel really is up by sending in the appropriate number of bytes.
let bytesToWrite = clientChannel.allocator.buffer(string: writingBytes)
let lastWriteFuture = clientChannel.writeAndFlush(NIOAny(bytesToWrite))
// When we've received all the bytes we know the connection is up.
_ = try bytesReceivedPromise.futureResult.wait()
// Now, with an empty write pipeline, we want to flush. This should complete immediately and without error.
clientChannel.flush()
lastWriteFuture.whenFailure { err in
XCTFail("\(err)")
}
try lastWriteFuture.wait()
}
func testWriteOnConnect() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.addHandler(EchoServer())
}.bind(host: "127.0.0.1", port: 0).wait())
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
let stringToWrite = "hello"
let promise = group.next().makePromise(of: ByteBuffer.self)
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
.channelInitializer { channel in
channel.pipeline.addHandler(WriteOnConnectHandler(toWrite: stringToWrite)).flatMap {
channel.pipeline.addHandler(ByteCountingHandler(numBytes: stringToWrite.utf8.count, promise: promise))
}
}
.connect(to: serverChannel.localAddress!).wait())
defer {
_ = clientChannel.close()
}
let bytes = try promise.futureResult.wait()
XCTAssertEqual(bytes.getString(at: bytes.readerIndex, length: bytes.readableBytes), stringToWrite)
}
func testWriteOnAccept() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let stringToWrite = "hello"
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.addHandler(WriteOnConnectHandler(toWrite: stringToWrite))
}.bind(host: "127.0.0.1", port: 0).wait())
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
let promise = group.next().makePromise(of: ByteBuffer.self)
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
.channelInitializer { channel in
channel.pipeline.addHandler(ByteCountingHandler(numBytes: stringToWrite.utf8.count, promise: promise))
}
.connect(to: serverChannel.localAddress!).wait())
defer {
XCTAssertNoThrow(try clientChannel.close().wait())
}
let bytes = try assertNoThrowWithValue(promise.futureResult.wait())
XCTAssertEqual(bytes.getString(at: bytes.readerIndex, length: bytes.readableBytes), stringToWrite)
}
func testWriteAfterChannelIsDead() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let dpGroup = DispatchGroup()
dpGroup.enter()
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.addHandler(EchoAndEchoAgainAfterSomeTimeServer(time: .seconds(1), secondWriteDoneHandler: {
dpGroup.leave()
}))
}.bind(host: "127.0.0.1", port: 0).wait())
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
let str = "hi there"
let countingHandler = ByteCountingHandler(numBytes: str.utf8.count, promise: group.next().makePromise())
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
.channelInitializer { $0.pipeline.addHandler(countingHandler) }
.connect(to: serverChannel.localAddress!).wait())
let buffer = clientChannel.allocator.buffer(string: str)
try clientChannel.writeAndFlush(NIOAny(buffer)).wait()
try countingHandler.assertReceived(buffer: buffer)
/* close the client channel so that the second write should fail */
try clientChannel.close().wait()
dpGroup.wait() /* make sure we stick around until the second write has happened */
}
func testPendingReadProcessedAfterWriteError() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let dpGroup = DispatchGroup()
dpGroup.enter()
let str = "hi there"
let countingHandler = ByteCountingHandler(numBytes: str.utf8.count * 4, promise: group.next().makePromise())
class WriteHandler : ChannelInboundHandler {
typealias InboundIn = ByteBuffer
private var writeFailed = false
func channelActive(context: ChannelHandlerContext) {
var buffer = context.channel.allocator.buffer(capacity: 4)
buffer.writeString("test")
writeUntilFailed(context, buffer)
}
private func writeUntilFailed(_ context: ChannelHandlerContext, _ buffer: ByteBuffer) {
context.writeAndFlush(NIOAny(buffer)).whenSuccess {
context.eventLoop.execute {
self.writeUntilFailed(context, buffer)
}
}
}
}
class WriteWhenActiveHandler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
let str: String
let dpGroup: DispatchGroup
init(_ str: String, _ dpGroup: DispatchGroup) {
self.str = str
self.dpGroup = dpGroup
}
func channelActive(context: ChannelHandlerContext) {
context.fireChannelActive()
let buffer = context.channel.allocator.buffer(string: str)
// write it four times and then close the connect.
context.writeAndFlush(NIOAny(buffer)).flatMap {
context.writeAndFlush(NIOAny(buffer))
}.flatMap {
context.writeAndFlush(NIOAny(buffer))
}.flatMap {
context.writeAndFlush(NIOAny(buffer))
}.flatMap {
context.close()
}.whenComplete { (_: Result<Void, Error>) in
self.dpGroup.leave()
}
}
}
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.addHandler(WriteWhenActiveHandler(str, dpGroup))
}.bind(host: "127.0.0.1", port: 0).wait())
defer {
XCTAssertNoThrow(try serverChannel.syncCloseAcceptingAlreadyClosed())
}
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
// We will only start reading once we wrote all data on the accepted channel.
//.channelOption(ChannelOptions.autoRead, value: false)
.channelOption(ChannelOptions.recvAllocator, value: FixedSizeRecvByteBufferAllocator(capacity: 2))
.channelInitializer { channel in
channel.pipeline.addHandler(WriteHandler()).flatMap {
channel.pipeline.addHandler(countingHandler)
}
}.connect(to: serverChannel.localAddress!).wait())
defer {
XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed())
}
dpGroup.wait()
var completeBuffer = clientChannel.allocator.buffer(capacity: str.utf8.count * 4)
completeBuffer.writeString(str)
completeBuffer.writeString(str)
completeBuffer.writeString(str)
completeBuffer.writeString(str)
try countingHandler.assertReceived(buffer: completeBuffer)
}
func testChannelErrorEOFNotFiredThroughPipeline() throws {
class ErrorHandler : ChannelInboundHandler {
typealias InboundIn = ByteBuffer
private let promise: EventLoopPromise<Void>
init(_ promise: EventLoopPromise<Void>) {
self.promise = promise
}
public func errorCaught(context: ChannelHandlerContext, error: Error) {
if let err = error as? ChannelError {
XCTAssertNotEqual(ChannelError.eof, err)
}
}
public func channelInactive(context: ChannelHandlerContext) {
self.promise.succeed(())
}
}
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let promise = group.next().makePromise(of: Void.self)
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.addHandler(ErrorHandler(promise))
}.bind(host: "127.0.0.1", port: 0).wait())
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
.connect(to: serverChannel.localAddress!).wait())
XCTAssertNoThrow(try clientChannel.close().wait())
XCTAssertNoThrow(try promise.futureResult.wait())
}
func testPortNumbers() throws {
var atLeastOneSucceeded = false
for host in ["127.0.0.1", "::1"] {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let acceptedRemotePort: NIOAtomic<Int> = .makeAtomic(value: -1)
let acceptedLocalPort: NIOAtomic<Int> = .makeAtomic(value: -2)
let sem = DispatchSemaphore(value: 0)
let serverChannel: Channel
do {
serverChannel = try ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
acceptedRemotePort.store(channel.remoteAddress?.port ?? -3)
acceptedLocalPort.store(channel.localAddress?.port ?? -4)
sem.signal()
return channel.eventLoop.makeSucceededFuture(())
}.bind(host: host, port: 0).wait()
} catch let e as SocketAddressError {
if case .unknown(host, port: 0) = e {
/* this can happen if the system isn't configured for both IPv4 and IPv6 */
continue
} else {
/* nope, that's a different socket error */
XCTFail("unexpected SocketAddressError: \(e)")
break
}
} catch {
/* other unknown error */
XCTFail("unexpected error: \(error)")
break
}
atLeastOneSucceeded = true
defer {
XCTAssertNoThrow(try serverChannel.syncCloseAcceptingAlreadyClosed())
}
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group).connect(host: host,
port: Int(serverChannel.localAddress!.port!)).wait())
defer {
XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed())
}
sem.wait()
XCTAssertEqual(serverChannel.localAddress?.port, clientChannel.remoteAddress?.port)
XCTAssertEqual(acceptedLocalPort.load(), clientChannel.remoteAddress?.port ?? -5)
XCTAssertEqual(acceptedRemotePort.load(), clientChannel.localAddress?.port ?? -6)
}
XCTAssertTrue(atLeastOneSucceeded)
}
func testConnectingToIPv4And6ButServerOnlyWaitsOnIPv4() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let numBytes = 16 * 1024
let promise = group.next().makePromise(of: ByteBuffer.self)
let countingHandler = ByteCountingHandler(numBytes: numBytes, promise: promise)
// we're binding to IPv4 only
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.addHandler(countingHandler)
}
.bind(host: "127.0.0.1", port: 0)
.wait())
defer {
XCTAssertNoThrow(try serverChannel.syncCloseAcceptingAlreadyClosed())
}
// but we're trying to connect to (depending on the system configuration and resolver) IPv4 and IPv6
let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group)
.connect(host: "localhost", port: Int(serverChannel.localAddress!.port!))
.flatMapError {
promise.fail($0)
return group.next().makeFailedFuture($0)
}
.wait())
defer {
XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed())
}
var buffer = clientChannel.allocator.buffer(capacity: numBytes)
for i in 0..<numBytes {
buffer.writeInteger(UInt8(i % 256))
}
try clientChannel.writeAndFlush(NIOAny(buffer)).wait()
try countingHandler.assertReceived(buffer: buffer)
}
}
|