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

net.dongliu.prettypb.rpc.client.RpcClientHandler Maven / Gradle / Ivy

There is a newer version: 0.3.5
Show newest version
/**
 *   Copyright 2010-2014 Peter Klauser
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package net.dongliu.prettypb.rpc.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import net.dongliu.prettypb.rpc.exception.ServiceException;
import net.dongliu.prettypb.rpc.listener.TcpConnectionEventListener;
import net.dongliu.prettypb.rpc.protocol.*;
import net.dongliu.prettypb.runtime.ExtensionRegistry;
import net.dongliu.prettypb.runtime.ProtobufDeSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * Handles returning RpcResponse and RpcError messages in the IO-Layer
 *
 * @author Peter Klauser
 */
public class RpcClientHandler extends MessageToMessageDecoder {

    private static Logger logger = LoggerFactory.getLogger(RpcClientHandler.class);
    private final RpcClientChannel rpcClientChannel;

    private TcpConnectionEventListener eventListener;

    private final Map pendingRequestMap;

    private final ExtensionRegistry extensionRegistry;

    public RpcClientHandler(TcpConnectionEventListener eventListener,
                            Map pendingRequestMap,
                            RpcClientChannel rpcClientChannel,
                            ExtensionRegistry extensionRegistry) {
        this.pendingRequestMap = pendingRequestMap;
        this.extensionRegistry = extensionRegistry;
        if (eventListener == null) {
            throw new NullPointerException("eventListener is null");
        }
        this.eventListener = eventListener;
        this.rpcClientChannel = rpcClientChannel;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, WirePayload payload, List out)
            throws Exception {
        if (payload.hasRpcResponse()) {
            onResponse(payload.getRpcResponse());
        } else if (payload.hasRpcError()) {
            onError(payload.getRpcError());
        } else if (payload.hasOobResponse()) {
            onOobResponse(payload.getOobResponse());
        } else if (payload.hasOobMessage()) {
            onOobMessage(payload.getOobMessage());
        } else if (payload.hasTransparentMessage()) {
            // just so that it's not forgotten sometime...
            out.add(payload);
        } else {
            // rpcRequest, rpcCancel, clientMessage go further up to the RpcServerHandler
            // transparentMessage are also sent up but not handled anywhere explicitly
            out.add(payload);
        }
    }

    /**
     * receive rpc response
     *
     * @param rpcResponse
     */
    public void onResponse(RpcResponse rpcResponse) {
        ClientCallTask task = pendingRequestMap.remove(rpcResponse.getCorrelationId());
        if (task != null) {
            Object response;
            try {
                response = ProtobufDeSerializer.fromBytes(task.getMethodInfo().getResponseType(),
                        rpcResponse.getResponseBytes(), extensionRegistry);
                task.handleResponse(response);
            } catch (RuntimeException e) {
                task.handleFailure(e);
            }
        }
    }

    /**
     * Receipt of an RpcError reply from a remote Peer.
     *
     * @param rpcError
     */
    public void onError(RpcError rpcError) {
        ClientCallTask task = pendingRequestMap.remove(rpcError.getCorrelationId());
        if (task != null) {
            task.handleFailure(new ServiceException(rpcError.getErrorMessage()));
        }
    }


    /**
     * For use by RpcClientHandler to dispatch an Out-of-Band server response
     * message to client code.
     *
     * @param serverMessage
     */
    public void onOobResponse(OobResponse serverMessage) {
        ClientCallTask task = pendingRequestMap.remove(serverMessage.getCorrelationId());
    }

    public void onOobMessage(OobMessage oobMessage) {
        //TODO: to be implemented
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        handleClosure();
        notifyClosed();
    }

    private void handleClosure() {
        do {
            //Defect Nr.8 Race condition with new client onRequest being received on closure.
            List pendingCallIds = new ArrayList<>();
            pendingCallIds.addAll(pendingRequestMap.keySet());
            for (Integer correlationId : pendingCallIds) {
                ClientCallTask task = pendingRequestMap.remove(correlationId);
                if (task != null) {
                    task.handleFailure(new ServiceException("Rpc channel closed"));
                }
            }
        } while (pendingRequestMap.size() > 0);
    }

    public void notifyClosed() {
        eventListener.connectionClosed(rpcClientChannel);
    }

    public void notifyOpened() {
        eventListener.connectionOpened(rpcClientChannel);
    }
}