apple / swift-nio-extras

Useful code around SwiftNIO.
https://swiftpackageindex.com/apple/swift-nio-extras/main/documentation/nioextras
Apache License 2.0
202 stars 78 forks source link

How to get printable debug information out of Debug(In|Out)boundEventsHandler? #113

Open Bouke opened 3 years ago

Bouke commented 3 years ago

Expected behavior

I'd like to print/log plain text conversations between client and server. Using the Debug(In|Out)boundEventsHandler, I'm only getting "NIOAny { ... }", which I don't understand how to convert to plain text.

After making this change the following change to the handler I'm able to print the conversation. However this cannot be done in the callback, as it doesn't have access to self.unwrapOutboundIn.

    public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
+       let any = self.unwrapOutboundIn(data)
+       let io = any as! IOData
+       if case let IOData.byteBuffer(buffer) = io {
+           print(String(buffer: buffer))
+       }
        logger(.write(data: data), context)
        context.write(data, promise: promise)
    }

Actual behavior

Writing NIOAny { ByteBuffer { readerIndex: 0, writerIndex: 195, readableBytes: 195, capacity: 256, storageCapacity: 256, slice: _ByteBufferSlice { 0..<256 }, storage: 0x0000000102149370 (256 bytes) } } in handler1

SwiftNIO-Extras version

        .package(url: "https://github.com/apple/swift-nio.git", from: "2.25.1"),
        .package(url: "https://github.com/apple/swift-nio-extras.git", from: "1.7.0"),

Swift & OS version

Apple Swift version 5.3.2 (swiftlang-1200.0.45 clang-1200.0.32.28) Target: x86_64-apple-darwin20.2.0 Darwin MacBook-Pro.localdomain 20.2.0 Darwin Kernel Version 20.2.0: Wed Dec 2 20:39:59 PST 2020; root:xnu-7195.60.75~1/RELEASE_X86_64 x86_64

glbrntt commented 3 years ago

Unfortunately the debug event handlers aren't that helpful in this instance. NIOAny is an opaque type which isn't meant to -- and indeed can't -- be unwrapped manually with public API as it stands. The enum case for the read(data: NIOAny) event in the callback for these handlers should have been read(data: Any) which would have allowed you to cast the Any to the appropriate type (see also: https://github.com/apple/swift-nio-extras/pull/81).

Your best bet here is creating your own ChannelHandler which unwraps, logs, and then forward events.