From b7f4e494f3fa8a26b9d4365abab8fed208582341 Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Mon, 25 Feb 2019 14:25:31 +0000 Subject: [PATCH] introduce WriteObservingByteToMessageDecoder (#834) Motivation: Some B2MDs need to observe writes. Modifications: Make those B2MD's B2MHs ChannelOutboundHandlers and let the B2MDs observe the writes. Result: HTTPDecoder can be expressed as B2MD. --- Sources/NIO/Codec.swift | 60 +++++++++++- Tests/NIOTests/CodecTest+XCTest.swift | 2 + Tests/NIOTests/CodecTest.swift | 132 ++++++++++++++++++++++++++ 3 files changed, 193 insertions(+), 1 deletion(-) diff --git a/Sources/NIO/Codec.swift b/Sources/NIO/Codec.swift index 7ec20dd60..93a43e13e 100644 --- a/Sources/NIO/Codec.swift +++ b/Sources/NIO/Codec.swift @@ -89,6 +89,22 @@ public protocol ByteToMessageDecoder { mutating func shouldReclaimBytes(buffer: ByteBuffer) -> Bool } +/// Some `ByteToMessageDecoder`s need to observe `write`s (which are outbound events). `ByteToMessageDecoder`s which +/// implement the `WriteObservingByteToMessageDecoder` protocol will be notified about every outbound write. +/// +/// `WriteObservingByteToMessageDecoder` may only observe a `write` and must not try to transform or block it in any +/// way. After the `write` method returns the `write` will be forwarded to the next outbound handler. +public protocol WriteObservingByteToMessageDecoder: ByteToMessageDecoder { + /// The type of `write`s. + associatedtype OutboundIn + + /// `write` is called for every incoming `write` incoming to the corresponding `ByteToMessageHandler`. + /// + /// - parameters: + /// - data: The data that was written. + mutating func write(data: OutboundIn) +} + extension ByteToMessageDecoder { public mutating func decoderRemoved(ctx: ChannelHandlerContext) { } @@ -271,6 +287,7 @@ public class ByteToMessageHandler { } internal private(set) var decoder: Decoder? // only `nil` if we're already decoding (ie. we're re-entered) + private var queuedWrites = CircularBuffer(initialCapacity: 1) // queues writes received whilst we're already decoding (re-entrant write) private var state: State = .active private var removalState: RemovalState = .notBeingRemoved // sadly to construct a B2MDBuffer we need an empty ByteBuffer which we can only get from the allocator, so IUO. @@ -294,6 +311,20 @@ extension ByteToMessageHandler { } } +private protocol CanDequeueWrites { + func dequeueWrites() +} + +extension ByteToMessageHandler: CanDequeueWrites where Decoder: WriteObservingByteToMessageDecoder { + fileprivate func dequeueWrites() { + while self.queuedWrites.count > 0 { + // self.decoder can't be `nil`, this is only allowed to be called when we're not already on the stack + self.decoder!.write(data: self.unwrapOutboundIn(self.queuedWrites.removeFirst())) + } + } +} + + // MARK: ByteToMessageHandler's Main API extension ByteToMessageHandler { private func withNextBuffer(allowEmptyBuffer: Bool, _ body: (inout Decoder, inout ByteBuffer) throws -> DecodingState) rethrows -> B2MDBuffer.BufferProcessingResult { @@ -337,6 +368,13 @@ extension ByteToMessageHandler { } } + private func tryDecodeWrites() { + if self.queuedWrites.count > 0 { + // this must succeed because unless we implement `CanDequeueWrites`, `queuedWrites` must always be empty. + (self as! CanDequeueWrites).dequeueWrites() + } + } + private func decodeLoop(ctx: ChannelHandlerContext, decodeMode: DecodeMode) throws -> B2MDBuffer.BufferProcessingResult { var allowEmptyBuffer = decodeMode == .last while decodeMode == .last || self.removalState == .notBeingRemoved { @@ -350,9 +388,15 @@ extension ByteToMessageHandler { } switch result { case .didProcess(.continue): + self.tryDecodeWrites() continue case .didProcess(.needMoreData): - return .didProcess(.needMoreData) + if self.queuedWrites.count > 0 { + self.tryDecodeWrites() + continue // we might have received more, so let's spin once more + } else { + return .didProcess(.needMoreData) + } case .cannotProcessReentrantly: return .cannotProcessReentrantly } @@ -427,6 +471,20 @@ extension ByteToMessageHandler: ChannelInboundHandler { } } +extension ByteToMessageHandler: ChannelOutboundHandler, _ChannelOutboundHandler where Decoder: WriteObservingByteToMessageDecoder { + public typealias OutboundIn = Decoder.OutboundIn + public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + if self.decoder != nil { + let data = self.unwrapOutboundIn(data) + assert(self.queuedWrites.count == 0) + self.decoder!.write(data: data) + } else { + self.queuedWrites.append(data) + } + ctx.write(data, promise: promise) + } +} + /// `ChannelOutboundHandler` which allows users to encode custom messages to a `ByteBuffer` easily. public protocol MessageToByteEncoder: ChannelOutboundHandler where OutboundOut == ByteBuffer { diff --git a/Tests/NIOTests/CodecTest+XCTest.swift b/Tests/NIOTests/CodecTest+XCTest.swift index 7ac375d0e..3575bca82 100644 --- a/Tests/NIOTests/CodecTest+XCTest.swift +++ b/Tests/NIOTests/CodecTest+XCTest.swift @@ -46,6 +46,8 @@ extension ByteToMessageDecoderTest { ("testDecodeLastHasSeenEOFFalseOnHandlerRemoved", testDecodeLastHasSeenEOFFalseOnHandlerRemoved), ("testDecodeLastHasSeenEOFFalseOnHandlerRemovedEvenIfNoData", testDecodeLastHasSeenEOFFalseOnHandlerRemovedEvenIfNoData), ("testDecodeLastHasSeenEOFTrueOnChannelInactive", testDecodeLastHasSeenEOFTrueOnChannelInactive), + ("testWriteObservingByteToMessageDecoderBasic", testWriteObservingByteToMessageDecoderBasic), + ("testWriteObservingByteToMessageDecoderWhereWriteIsReentrantlyCalled", testWriteObservingByteToMessageDecoderWhereWriteIsReentrantlyCalled), ] } } diff --git a/Tests/NIOTests/CodecTest.swift b/Tests/NIOTests/CodecTest.swift index 88d3fcf64..113dda667 100644 --- a/Tests/NIOTests/CodecTest.swift +++ b/Tests/NIOTests/CodecTest.swift @@ -847,6 +847,138 @@ public class ByteToMessageDecoderTest: XCTestCase { XCTAssertNoThrow(XCTAssertFalse(try channel.finish())) XCTAssertEqual(1, decoder.decodeLastCalls) } + + func testWriteObservingByteToMessageDecoderBasic() { + class Decoder: WriteObservingByteToMessageDecoder { + typealias OutboundIn = Int + typealias InboundOut = String + + var allObservedWrites: [Int] = [] + + func write(data: Int) { + self.allObservedWrites.append(data) + } + + func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + if let string = buffer.readString(length: 1) { + ctx.fireChannelRead(self.wrapInboundOut(string)) + return .continue + } else { + return .needMoreData + } + } + + func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + while case .continue = try self.decode(ctx: ctx, buffer: &buffer) {} + return .needMoreData + } + } + + let decoder = Decoder() + let channel = EmbeddedChannel(handler: ByteToMessageHandler(decoder)) + XCTAssertNoThrow(try channel.connect(to: SocketAddress(ipAddress: "1.2.3.4", port: 5678)).wait()) + var buffer = channel.allocator.buffer(capacity: 3) + buffer.writeStaticString("abc") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + XCTAssertNoThrow(try channel.writeOutbound(1)) + XCTAssertNoThrow(try channel.writeOutbound(2)) + XCTAssertNoThrow(try channel.writeOutbound(3)) + XCTAssertEqual([1, 2, 3], decoder.allObservedWrites) + XCTAssertEqual("a", channel.readInbound()) + XCTAssertEqual("b", channel.readInbound()) + XCTAssertEqual("c", channel.readInbound()) + XCTAssertEqual(1, channel.readOutbound()) + XCTAssertEqual(2, channel.readOutbound()) + XCTAssertEqual(3, channel.readOutbound()) + XCTAssertNoThrow(XCTAssertFalse(try channel.finish())) + } + + func testWriteObservingByteToMessageDecoderWhereWriteIsReentrantlyCalled() { + class Decoder: WriteObservingByteToMessageDecoder { + typealias OutboundIn = String + typealias InboundOut = String + + var allObservedWrites: [String] = [] + var decodeRun = 0 + + func write(data: String) { + self.allObservedWrites.append(data) + } + + func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + self.decodeRun += 1 + if let string = buffer.readString(length: 1) { + ctx.fireChannelRead(self.wrapInboundOut("I: \(self.decodeRun): \(string)")) + XCTAssertNoThrow(try (ctx.channel as! EmbeddedChannel).writeOutbound("O: \(self.decodeRun): \(string)")) + if self.decodeRun == 1 { + var buffer = ctx.channel.allocator.buffer(capacity: 1) + buffer.writeStaticString("X") + XCTAssertNoThrow(try (ctx.channel as! EmbeddedChannel).writeInbound(buffer)) + } + return .continue + } else { + return .needMoreData + } + } + + func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + while case .continue = try self.decode(ctx: ctx, buffer: &buffer) {} + return .needMoreData + } + } + + class CheckStateOfDecoderHandler: ChannelOutboundHandler { + typealias OutboundIn = String + typealias OutboundOut = String + + private let decoder: Decoder + + init(decoder: Decoder) { + self.decoder = decoder + } + + func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + let string = self.unwrapOutboundIn(data) + ctx.write(self.wrapOutboundOut("\(string) @ \(decoder.decodeRun)"), promise: promise) + } + } + + let decoder = Decoder() + let channel = EmbeddedChannel(handler: ByteToMessageHandler(decoder)) + XCTAssertNoThrow(try channel.pipeline.addHandler(CheckStateOfDecoderHandler(decoder: decoder), position: .first).wait()) + XCTAssertNoThrow(try channel.connect(to: SocketAddress(ipAddress: "1.2.3.4", port: 5678)).wait()) + var buffer = channel.allocator.buffer(capacity: 3) + XCTAssertNoThrow(try channel.writeOutbound("before")) + buffer.writeStaticString("ab") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + buffer.clear() + buffer.writeStaticString("xyz") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + XCTAssertNoThrow(try channel.writeOutbound("after")) + XCTAssertEqual(["before", "O: 1: a", "O: 2: b", "O: 3: X", "O: 4: x", "O: 5: y", "O: 6: z", "after"], + decoder.allObservedWrites) + XCTAssertEqual("I: 1: a", channel.readInbound()) + XCTAssertEqual("I: 2: b", channel.readInbound()) + XCTAssertEqual("I: 3: X", channel.readInbound()) + XCTAssertEqual("I: 4: x", channel.readInbound()) + XCTAssertEqual("I: 5: y", channel.readInbound()) + XCTAssertEqual("I: 6: z", channel.readInbound()) + XCTAssertNil(channel.readInbound()) + XCTAssertEqual("before @ 0", channel.readOutbound()) + // in the next line, it's important that it ends in '@ 1' because that means the outbound write was forwarded + // when the Decoder was after decode run 1, ie. before it ever saw the 'b'. It's important we forward writes + // as soon as possible for correctness but also to keep as few queued writes as possible. + XCTAssertEqual("O: 1: a @ 1", channel.readOutbound()) + XCTAssertEqual("O: 2: b @ 2", channel.readOutbound()) + XCTAssertEqual("O: 3: X @ 3", channel.readOutbound()) + XCTAssertEqual("O: 4: x @ 4", channel.readOutbound()) + XCTAssertEqual("O: 5: y @ 5", channel.readOutbound()) + XCTAssertEqual("O: 6: z @ 6", channel.readOutbound()) + XCTAssertEqual("after @ 6", channel.readOutbound()) + XCTAssertNil(channel.readOutbound()) + XCTAssertNoThrow(XCTAssertFalse(try channel.finish())) + } + } public class MessageToByteEncoderTest: XCTestCase {