mirror of
https://github.com/apple/swift-nio
synced 2026-11-30 05:28:44 +00:00
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.
This commit is contained in:
1 parent
f720de3ae0
commit
b7f4e494f3
3 files changed
+193
-1
No files matched your search
+59
-1
@@ -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<Decoder: ByteToMessageDecoder> {
|
||||
}
|
||||
|
||||
internal private(set) var decoder: Decoder? // only `nil` if we're already decoding (ie. we're re-entered)
|
||||
private var queuedWrites = CircularBuffer<NIOAny>(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<Void>?) {
|
||||
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 {
|
||||
|
||||
|
||||
@@ -46,6 +46,8 @@ extension ByteToMessageDecoderTest {
|
||||
("testDecodeLastHasSeenEOFFalseOnHandlerRemoved", testDecodeLastHasSeenEOFFalseOnHandlerRemoved),
|
||||
("testDecodeLastHasSeenEOFFalseOnHandlerRemovedEvenIfNoData", testDecodeLastHasSeenEOFFalseOnHandlerRemovedEvenIfNoData),
|
||||
("testDecodeLastHasSeenEOFTrueOnChannelInactive", testDecodeLastHasSeenEOFTrueOnChannelInactive),
|
||||
("testWriteObservingByteToMessageDecoderBasic", testWriteObservingByteToMessageDecoderBasic),
|
||||
("testWriteObservingByteToMessageDecoderWhereWriteIsReentrantlyCalled", testWriteObservingByteToMessageDecoderWhereWriteIsReentrantlyCalled),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Void>?) {
|
||||
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 {
|
||||
|
||||
Reference in new issue
Block a user