package com.atlassian.bitbucket.mesh.request;

import com.google.protobuf.MessageLite;
import io.grpc.ForwardingServerCallListener;
import io.grpc.ServerCall;

/**
 * Wraps a {@link ServerCall.Listener} to track the number and size of messages received.
 *
 * @param <ReqT> the request type
 */
class RequestServerCallListener<ReqT> extends ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT> {

    private final GrpcRequestDescriptor descriptor;

    RequestServerCallListener(ServerCall.Listener<ReqT> delegate, GrpcRequestDescriptor descriptor) {
        super(delegate);

        this.descriptor = descriptor;
    }

    @Override
    public void onMessage(ReqT message) {
        descriptor.onMessageReceived();
        if (message instanceof MessageLite) {
            descriptor.onBytesReceived(((MessageLite) message).getSerializedSize());
        }

        super.onMessage(message);
    }
}
