package com.atlassian.bitbucket.mesh.rpc;

import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;

/**
 * Wrapper around a {@link ServerCallHandler} that calls {@link ZeroCopyStreamCloser#close()} after each callback
 * method to ensure that any streams that were detached by {@link ZeroCopyMarshaller} are closed after the system
 * has finished processing the parsed message.
 *
 * @param <ReqT> the RPC request type
 * @param <RespT> the RPC response type
 */
class ZeroCopyServerCallHandler<ReqT, RespT> implements ServerCallHandler<ReqT, RespT> {

    private final ServerCallHandler<ReqT, RespT> delegate;

    ZeroCopyServerCallHandler(ServerCallHandler<ReqT, RespT> delegate) {
        this.delegate = delegate;
    }

    @Override
    public ServerCall.Listener<ReqT> startCall(ServerCall<ReqT, RespT> call, Metadata headers) {
        return new ZeroCopyServerCallListener<>(delegate.startCall(call, headers));
    }
}
