Search in sources :

Example 1 with RpcContext

use of com.alipay.sofa.jraft.rpc.RpcContext in project sofa-jraft by sofastack.

the class FileServiceTest method testGetFileData.

@Test
public void testGetFileData() throws IOException {
    writeData();
    long readerId = FileService.getInstance().addReader(this.fileReader);
    RpcRequests.GetFileRequest request = RpcRequests.GetFileRequest.newBuilder().setCount(Integer.MAX_VALUE).setFilename("data").setOffset(0).setReaderId(readerId).build();
    RpcContext asyncContext = Mockito.mock(RpcContext.class);
    Message msg = FileService.getInstance().handleGetFile(request, new RpcRequestClosure(asyncContext));
    assertTrue(msg instanceof RpcRequests.GetFileResponse);
    RpcRequests.GetFileResponse response = (RpcRequests.GetFileResponse) msg;
    assertTrue(response.getEof());
    assertEquals("jraft is great!", new String(response.getData().toByteArray()));
    assertEquals(-1, response.getReadSize());
}
Also used : RpcContext(com.alipay.sofa.jraft.rpc.RpcContext) Message(com.google.protobuf.Message) RpcRequests(com.alipay.sofa.jraft.rpc.RpcRequests) RpcRequestClosure(com.alipay.sofa.jraft.rpc.RpcRequestClosure) Test(org.junit.Test)

Example 2 with RpcContext

use of com.alipay.sofa.jraft.rpc.RpcContext in project sofa-jraft by sofastack.

the class FileServiceTest method testGetFileNotFound.

@Test
public void testGetFileNotFound() {
    long readerId = FileService.getInstance().addReader(this.fileReader);
    RpcRequests.GetFileRequest request = RpcRequests.GetFileRequest.newBuilder().setCount(Integer.MAX_VALUE).setFilename("data").setOffset(0).setReaderId(readerId).build();
    RpcContext asyncContext = Mockito.mock(RpcContext.class);
    Message msg = FileService.getInstance().handleGetFile(request, new RpcRequestClosure(asyncContext));
    assertTrue(msg instanceof RpcRequests.ErrorResponse);
    RpcRequests.ErrorResponse response = (RpcRequests.ErrorResponse) msg;
    assertEquals(RaftError.EIO.getNumber(), response.getErrorCode());
    assertEquals(String.format("Fail to read from path=%s filename=data", this.path), response.getErrorMsg());
}
Also used : RpcContext(com.alipay.sofa.jraft.rpc.RpcContext) Message(com.google.protobuf.Message) RpcRequests(com.alipay.sofa.jraft.rpc.RpcRequests) RpcRequestClosure(com.alipay.sofa.jraft.rpc.RpcRequestClosure) Test(org.junit.Test)

Example 3 with RpcContext

use of com.alipay.sofa.jraft.rpc.RpcContext in project sofa-jraft by sofastack.

the class AppendEntriesRequestProcessorTest method testSendSequenceResponse.

@Test
public void testSendSequenceResponse() {
    mockNode();
    final AppendEntriesRequestProcessor processor = (AppendEntriesRequestProcessor) newProcessor();
    final PeerPair pair = processor.pairOf(this.peerIdStr, this.serverId);
    processor.getOrCreatePeerRequestContext(this.groupId, pair, this.conn);
    final PingRequest msg = TestUtils.createPingRequest();
    final RpcContext asyncContext = Mockito.mock(RpcContext.class);
    processor.sendSequenceResponse(this.groupId, pair, 1, asyncContext, msg);
    Mockito.verify(asyncContext, Mockito.never()).sendResponse(msg);
    processor.sendSequenceResponse(this.groupId, pair, 0, asyncContext, msg);
    Mockito.verify(asyncContext, Mockito.times(2)).sendResponse(msg);
}
Also used : RpcContext(com.alipay.sofa.jraft.rpc.RpcContext) PingRequest(com.alipay.sofa.jraft.rpc.RpcRequests.PingRequest) PeerPair(com.alipay.sofa.jraft.rpc.impl.core.AppendEntriesRequestProcessor.PeerPair) Test(org.junit.Test)

Example 4 with RpcContext

use of com.alipay.sofa.jraft.rpc.RpcContext in project sofa-jraft by sofastack.

the class GrpcServer method registerProcessor.

@SuppressWarnings("unchecked")
@Override
public void registerProcessor(final RpcProcessor processor) {
    final String interest = processor.interest();
    final Message reqIns = Requires.requireNonNull(this.parserClasses.get(interest), "null default instance: " + interest);
    final MethodDescriptor<Message, Message> method = // 
    MethodDescriptor.<Message, Message>newBuilder().setType(// 
    MethodDescriptor.MethodType.UNARY).setFullMethodName(// 
    MethodDescriptor.generateFullMethodName(processor.interest(), GrpcRaftRpcFactory.FIXED_METHOD_NAME)).setRequestMarshaller(// 
    ProtoUtils.marshaller(reqIns)).setResponseMarshaller(// 
    ProtoUtils.marshaller(this.marshallerRegistry.findResponseInstanceByRequest(interest))).build();
    final ServerCallHandler<Message, Message> handler = ServerCalls.asyncUnaryCall((request, responseObserver) -> {
        final SocketAddress remoteAddress = RemoteAddressInterceptor.getRemoteAddress();
        final Connection conn = ConnectionInterceptor.getCurrentConnection(this.closedEventListeners);
        final RpcContext rpcCtx = new RpcContext() {

            @Override
            public void sendResponse(final Object responseObj) {
                try {
                    responseObserver.onNext((Message) responseObj);
                    responseObserver.onCompleted();
                } catch (final Throwable t) {
                    LOG.warn("[GRPC] failed to send response.", t);
                }
            }

            @Override
            public Connection getConnection() {
                if (conn == null) {
                    throw new IllegalStateException("fail to get connection");
                }
                return conn;
            }

            @Override
            public String getRemoteAddress() {
                // Rely on GRPC's capabilities, not magic (netty channel)
                return remoteAddress != null ? remoteAddress.toString() : null;
            }
        };
        final RpcProcessor.ExecutorSelector selector = processor.executorSelector();
        Executor executor;
        if (selector != null && request instanceof RpcRequests.AppendEntriesRequest) {
            final RpcRequests.AppendEntriesRequest req = (RpcRequests.AppendEntriesRequest) request;
            final RpcRequests.AppendEntriesRequestHeader.Builder header = // 
            RpcRequests.AppendEntriesRequestHeader.newBuilder().setGroupId(// 
            req.getGroupId()).setPeerId(// 
            req.getPeerId()).setServerId(req.getServerId());
            executor = selector.select(interest, header.build());
        } else {
            executor = processor.executor();
        }
        if (executor == null) {
            executor = this.defaultExecutor;
        }
        if (executor != null) {
            executor.execute(() -> processor.handleRequest(rpcCtx, request));
        } else {
            processor.handleRequest(rpcCtx, request);
        }
    });
    final ServerServiceDefinition serviceDef = // 
    ServerServiceDefinition.builder(// 
    interest).addMethod(method, // 
    handler).build();
    this.handlerRegistry.addService(ServerInterceptors.intercept(serviceDef, this.serverInterceptors.toArray(new ServerInterceptor[0])));
}
Also used : RpcProcessor(com.alipay.sofa.jraft.rpc.RpcProcessor) Message(com.google.protobuf.Message) Connection(com.alipay.sofa.jraft.rpc.Connection) RpcRequests(com.alipay.sofa.jraft.rpc.RpcRequests) RpcContext(com.alipay.sofa.jraft.rpc.RpcContext) Executor(java.util.concurrent.Executor) ServerServiceDefinition(io.grpc.ServerServiceDefinition) SocketAddress(java.net.SocketAddress)

Example 5 with RpcContext

use of com.alipay.sofa.jraft.rpc.RpcContext in project nacos by alibaba.

the class AbstractProcessorTest method testErrorThroughRpc.

@Test
public void testErrorThroughRpc() {
    final AtomicReference<Response> reference = new AtomicReference<>();
    RpcContext context = new RpcContext() {

        @Override
        public void sendResponse(Object responseObj) {
            reference.set((Response) responseObj);
        }

        @Override
        public Connection getConnection() {
            return null;
        }

        @Override
        public String getRemoteAddress() {
            return null;
        }
    };
    AbstractProcessor processor = new NacosLogProcessor(server, SerializeFactory.getDefault());
    processor.execute(server, context, WriteRequest.newBuilder().build(), new JRaftServer.RaftGroupTuple());
    Response response = reference.get();
    Assert.assertNotNull(response);
    Assert.assertEquals("Error message transmission", response.getErrMsg());
    Assert.assertFalse(response.getSuccess());
}
Also used : Response(com.alibaba.nacos.consistency.entity.Response) RpcContext(com.alipay.sofa.jraft.rpc.RpcContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) JRaftServer(com.alibaba.nacos.core.distributed.raft.JRaftServer) Test(org.junit.Test)

Aggregations

RpcContext (com.alipay.sofa.jraft.rpc.RpcContext)8 Test (org.junit.Test)7 RpcRequests (com.alipay.sofa.jraft.rpc.RpcRequests)5 Message (com.google.protobuf.Message)5 RpcRequestClosure (com.alipay.sofa.jraft.rpc.RpcRequestClosure)4 Connection (com.alipay.sofa.jraft.rpc.Connection)2 PingRequest (com.alipay.sofa.jraft.rpc.RpcRequests.PingRequest)2 PeerPair (com.alipay.sofa.jraft.rpc.impl.core.AppendEntriesRequestProcessor.PeerPair)2 Response (com.alibaba.nacos.consistency.entity.Response)1 JRaftServer (com.alibaba.nacos.core.distributed.raft.JRaftServer)1 PeerId (com.alipay.sofa.jraft.entity.PeerId)1 RpcProcessor (com.alipay.sofa.jraft.rpc.RpcProcessor)1 PeerRequestContext (com.alipay.sofa.jraft.rpc.impl.core.AppendEntriesRequestProcessor.PeerRequestContext)1 ServerServiceDefinition (io.grpc.ServerServiceDefinition)1 SocketAddress (java.net.SocketAddress)1 Executor (java.util.concurrent.Executor)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1