All Downloads are FREE. Search and download functionalities are using the official Maven repository.

goodmetrics.downstream.GrpcTrailerLogger.kt Maven / Gradle / Ivy

There is a newer version: 0.7.2
Show newest version
package goodmetrics.downstream

import io.grpc.CallOptions
import io.grpc.Channel
import io.grpc.ClientCall
import io.grpc.ClientInterceptor
import io.grpc.ForwardingClientCall.SimpleForwardingClientCall
import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener
import io.grpc.MethodDescriptor
import io.grpc.Status
import io.grpc.Metadata as GrpcMetadata

class GrpcTrailerLoggerInterceptor(
    private val onTrailers: (Status, GrpcMetadata) -> Unit
) : ClientInterceptor {
    override fun  interceptCall(
        method: MethodDescriptor,
        callOptions: CallOptions,
        next: Channel
    ): ClientCall {
        return TrailersLoggingClientCall(next.newCall(method, callOptions), onTrailers)
    }

    private class TrailersLoggingClientCall (
        call: ClientCall?,
        private val onTrailers: (Status, GrpcMetadata) -> Unit,
    ) : SimpleForwardingClientCall(call) {
        override fun start(responseListener: Listener, headers: GrpcMetadata) {
            super.start(MetadataCapturingClientCallListener(responseListener), headers)
        }

        private inner class MetadataCapturingClientCallListener(
            responseListener: Listener?
        ) :
            SimpleForwardingClientCallListener(responseListener) {
            override fun onHeaders(headers: GrpcMetadata) {
                super.onHeaders(headers)
            }

            override fun onClose(status: Status, trailers: GrpcMetadata?) {
                if (trailers != null && trailers.keys().isNotEmpty()) {
                    onTrailers(status, trailers)
                }
                super.onClose(status, trailers)
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy