Search in sources :

Example 41 with SofaResponse

use of com.alipay.sofa.rpc.core.response.SofaResponse in project httpx by httpx-sh.

the class SofaRpcExecutor method execute.

@SuppressWarnings("unused")
public List<byte[]> execute(HttpRequest httpRequest) {
    final URI sofaUri = httpRequest.getRequestTarget().getUri();
    final Map<String, String> params = queryToMap(sofaUri);
    String methodSignature = params.get("method");
    String serviceName = sofaUri.getPath().substring(1);
    if (serviceName.contains("/")) {
        final String[] parts = serviceName.split("/", 2);
        serviceName = parts[0];
        methodSignature = parts[1];
    }
    String methodName = methodSignature;
    String[] paramsTypeArray = new String[] {};
    Object[] arguments = new Object[] {};
    if (methodSignature.contains("(")) {
        methodName = methodSignature.substring(0, methodSignature.indexOf('('));
        final String parts = methodSignature.substring(methodSignature.indexOf('(') + 1, methodSignature.indexOf(')'));
        if (!parts.isEmpty()) {
            paramsTypeArray = parts.split(",");
        }
    }
    if (paramsTypeArray.length > 0) {
        final byte[] body = httpRequest.getBodyBytes();
        if (body == null || body.length == 0) {
            arguments = new Object[] { null };
        } else {
            String text = new String(body, StandardCharsets.UTF_8);
            if (!text.startsWith("[")) {
                // one object  and convert to array
                text = "[" + text + "]";
            }
            try {
                final List<?> items = JsonUtils.readValue(text, List.class);
                arguments = new Object[items.size()];
                for (int i = 0; i < items.size(); i++) {
                    final Object item = items.get(i);
                    arguments[i] = item;
                }
            } catch (Exception e) {
                log.error("HTX-106-408", text);
            }
        }
    }
    int port = sofaUri.getPort();
    if (port <= 0) {
        port = 12200;
    }
    System.out.println("SOFA " + sofaUri);
    System.out.println();
    try (SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(sofaUri.getHost(), port))) {
        SofaRpcInvocation invocation = new SofaRpcInvocation(serviceName, methodName, paramsTypeArray, arguments);
        final byte[] contentBytes = invocation.content();
        final byte[] frameBytes = invocation.frameBytes(contentBytes);
        socketChannel.write(ByteBuffer.wrap(frameBytes));
        final byte[] receivedBytes = extractData(socketChannel);
        final ByteBuffer in = ByteBuffer.wrap(receivedBytes);
        final byte protocol = in.get();
        byte type = in.get();
        short cmdCode = in.getShort();
        byte ver2 = in.get();
        int requestId = in.getInt();
        byte serializer = in.get();
        short status = in.getShort();
        short classLen = in.getShort();
        short headerLen = in.getShort();
        int contentLen = in.getInt();
        byte[] clazz = new byte[classLen];
        byte[] header = new byte[headerLen];
        byte[] content = new byte[contentLen];
        in.get(clazz);
        in.get(header);
        in.get(content);
        Hessian2Input input = new HessianSerializerInput(new ByteArrayInputStream(content));
        final SofaResponse response = (SofaResponse) input.readObject();
        if (!response.isError()) {
            final Object appResponse = response.getAppResponse();
            if (appResponse == null) {
                System.out.print("===No return value===");
            } else {
                String text = JsonUtils.writeValueAsPrettyString(appResponse);
                System.out.print(prettyJsonFormat(text));
                runJsTest(httpRequest, 200, Collections.emptyMap(), "application/json", text);
                return List.of(text.getBytes(StandardCharsets.UTF_8));
            }
        } else {
            System.out.println("Error:" + response.getErrorMsg());
        }
    } catch (Exception e) {
        log.error("HTX-103-408", sofaUri, e);
    }
    return Collections.emptyList();
}
Also used : SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) URI(java.net.URI) ByteBuffer(java.nio.ByteBuffer) Hessian2Input(com.caucho.hessian.io.Hessian2Input) ByteArrayInputStream(java.io.ByteArrayInputStream) HessianSerializerInput(com.caucho.hessian.io.HessianSerializerInput) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse)

Example 42 with SofaResponse

use of com.alipay.sofa.rpc.core.response.SofaResponse in project Sentinel by alibaba.

the class SentinelSofaRpcConsumerFilterTest method testInvokeSentinelWorks.

@Test
public void testInvokeSentinelWorks() {
    SentinelSofaRpcConsumerFilter filter = new SentinelSofaRpcConsumerFilter();
    final String interfaceResourceName = "com.alibaba.csp.sentinel.adapter.sofa.rpc.service.DemoService";
    final String methodResourceName = "com.alibaba.csp.sentinel.adapter.sofa.rpc.service.DemoService#sayHello(java.lang.String,int)";
    SofaRequest request = mock(SofaRequest.class);
    when(request.getInvokeType()).thenReturn(RpcConstants.INVOKER_TYPE_SYNC);
    when(request.getInterfaceName()).thenReturn(interfaceResourceName);
    when(request.getMethodName()).thenReturn("sayHello");
    when(request.getMethodArgSigs()).thenReturn(new String[] { "java.lang.String", "int" });
    when(request.getMethodArgs()).thenReturn(new Object[] { "Sentinel", 2020 });
    FilterInvoker filterInvoker = mock(FilterInvoker.class);
    when(filterInvoker.invoke(request)).thenAnswer(new Answer<SofaResponse>() {

        @Override
        public SofaResponse answer(InvocationOnMock invocationOnMock) throws Throwable {
            verifyInvocationStructure(interfaceResourceName, methodResourceName);
            SofaResponse response = new SofaResponse();
            response.setAppResponse("Hello Sentinel 2020");
            return response;
        }
    });
    // Before invoke
    assertNull(ContextUtil.getContext());
    // Do invoke
    SofaResponse response = filter.invoke(filterInvoker, request);
    assertEquals("Hello Sentinel 2020", response.getAppResponse());
    verify(filterInvoker).invoke(request);
    // After invoke, make sure exit context
    assertNull(ContextUtil.getContext());
}
Also used : SofaRequest(com.alipay.sofa.rpc.core.request.SofaRequest) FilterInvoker(com.alipay.sofa.rpc.filter.FilterInvoker) InvocationOnMock(org.mockito.invocation.InvocationOnMock) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse) Test(org.junit.Test)

Example 43 with SofaResponse

use of com.alipay.sofa.rpc.core.response.SofaResponse in project Sentinel by alibaba.

the class SentinelSofaRpcProviderFilter method invoke.

@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {
    // Now only support sync invoke.
    if (request.getInvokeType() != null && !RpcConstants.INVOKER_TYPE_SYNC.equals(request.getInvokeType())) {
        return invoker.invoke(request);
    }
    String callerApp = getApplicationName(request);
    String interfaceResourceName = getInterfaceResourceName(request);
    String methodResourceName = getMethodResourceName(request);
    Entry interfaceEntry = null;
    Entry methodEntry = null;
    try {
        ContextUtil.enter(methodResourceName, callerApp);
        interfaceEntry = SphU.entry(interfaceResourceName, ResourceTypeConstants.COMMON_RPC, EntryType.IN);
        methodEntry = SphU.entry(methodResourceName, ResourceTypeConstants.COMMON_RPC, EntryType.IN, getMethodArguments(request));
        SofaResponse response = invoker.invoke(request);
        traceResponseException(response, interfaceEntry, methodEntry);
        return response;
    } catch (BlockException e) {
        return SofaRpcFallbackRegistry.getProviderFallback().handle(invoker, request, e);
    } catch (Throwable t) {
        throw traceOtherException(t, interfaceEntry, methodEntry);
    } finally {
        if (methodEntry != null) {
            methodEntry.exit(1, getMethodArguments(request));
        }
        if (interfaceEntry != null) {
            interfaceEntry.exit();
        }
        ContextUtil.exit();
    }
}
Also used : BlockException(com.alibaba.csp.sentinel.slots.block.BlockException) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse)

Example 44 with SofaResponse

use of com.alipay.sofa.rpc.core.response.SofaResponse in project httpx by servicex-sh.

the class SofaRpcExecutor method execute.

@SuppressWarnings("unused")
public List<byte[]> execute(HttpRequest httpRequest) {
    final URI sofaUri = httpRequest.getRequestTarget().getUri();
    final Map<String, String> params = queryToMap(sofaUri);
    String methodSignature = params.get("method");
    String serviceName = sofaUri.getPath().substring(1);
    if (serviceName.contains("/")) {
        final String[] parts = serviceName.split("/", 2);
        serviceName = parts[0];
        methodSignature = parts[1];
    }
    String methodName = methodSignature;
    String[] paramsTypeArray = new String[] {};
    Object[] arguments = new Object[] {};
    if (methodSignature.contains("(")) {
        methodName = methodSignature.substring(0, methodSignature.indexOf('('));
        final String parts = methodSignature.substring(methodSignature.indexOf('(') + 1, methodSignature.indexOf(')'));
        if (!parts.isEmpty()) {
            paramsTypeArray = Arrays.stream(parts.split(",")).map(typeName -> DubboExecutor.SHORT_TYPE_MAPPING.getOrDefault(typeName, typeName)).toArray(String[]::new);
        }
    }
    if (paramsTypeArray.length > 0) {
        final byte[] body = httpRequest.getBodyBytes();
        if (body == null || body.length == 0) {
            arguments = new Object[] { null };
        } else {
            String text = new String(body, StandardCharsets.UTF_8);
            if (!text.startsWith("[")) {
                // one object  and convert to array
                text = "[" + text + "]";
            }
            try {
                final List<?> items = JsonUtils.readValue(text, List.class);
                arguments = new Object[items.size()];
                for (int i = 0; i < items.size(); i++) {
                    final Object item = items.get(i);
                    arguments[i] = item;
                }
            } catch (Exception e) {
                log.error("HTX-106-408", text);
            }
        }
    }
    int port = sofaUri.getPort();
    if (port <= 0) {
        port = 12200;
    }
    System.out.println("SOFA " + sofaUri);
    System.out.println();
    try (SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(sofaUri.getHost(), port))) {
        SofaRpcInvocation invocation = new SofaRpcInvocation(serviceName, methodName, paramsTypeArray, arguments);
        final byte[] contentBytes = invocation.content();
        final byte[] frameBytes = invocation.frameBytes(contentBytes);
        socketChannel.write(ByteBuffer.wrap(frameBytes));
        final byte[] receivedBytes = extractData(socketChannel);
        final ByteBuffer in = ByteBuffer.wrap(receivedBytes);
        final byte protocol = in.get();
        byte type = in.get();
        short cmdCode = in.getShort();
        byte ver2 = in.get();
        int requestId = in.getInt();
        byte serializer = in.get();
        short status = in.getShort();
        short classLen = in.getShort();
        short headerLen = in.getShort();
        int contentLen = in.getInt();
        byte[] clazz = new byte[classLen];
        byte[] header = new byte[headerLen];
        byte[] content = new byte[contentLen];
        in.get(clazz);
        in.get(header);
        in.get(content);
        Hessian2Input input = new HessianSerializerInput(new ByteArrayInputStream(content));
        final SofaResponse response = (SofaResponse) input.readObject();
        if (!response.isError()) {
            final Object appResponse = response.getAppResponse();
            if (appResponse == null) {
                System.out.print("===No return value===");
            } else {
                String text = JsonUtils.writeValueAsPrettyString(appResponse);
                System.out.print(prettyJsonFormat(text));
                runJsTest(httpRequest, 200, Collections.emptyMap(), "application/json", text);
                return List.of(text.getBytes(StandardCharsets.UTF_8));
            }
        } else {
            System.out.println("Error:" + response.getErrorMsg());
        }
    } catch (Exception e) {
        log.error("HTX-103-408", sofaUri, e);
    }
    return Collections.emptyList();
}
Also used : SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) URI(java.net.URI) ByteBuffer(java.nio.ByteBuffer) Hessian2Input(com.caucho.hessian.io.Hessian2Input) ByteArrayInputStream(java.io.ByteArrayInputStream) HessianSerializerInput(com.caucho.hessian.io.HessianSerializerInput) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse)

Example 45 with SofaResponse

use of com.alipay.sofa.rpc.core.response.SofaResponse in project sofa-rpc by sofastack.

the class ProtobufSerializerTest method testSofaResponse.

@Test
public void testSofaResponse() throws Exception {
    SofaResponse response = new SofaResponse();
    response.setAppResponse("1233");
    AbstractByteBuf data = serializer.encode(response, null);
    boolean error = false;
    try {
        serializer.decode(data, SofaResponse.class, null);
    } catch (Exception e) {
        error = true;
    }
    Assert.assertTrue(error);
    error = false;
    try {
        serializer.decode(data, null, null);
    } catch (Exception e) {
        error = true;
    }
    Assert.assertTrue(error);
    error = false;
    try {
        serializer.decode(data, new SofaResponse(), null);
    } catch (Exception e) {
        error = true;
    }
    Assert.assertTrue(error);
    // success response
    Map<String, String> head = new HashMap<String, String>();
    head.put(RemotingConstants.HEAD_TARGET_SERVICE, ProtoService.class.getCanonicalName() + ":1.0");
    head.put(RemotingConstants.HEAD_METHOD_NAME, "echoStr");
    head.put(RemotingConstants.HEAD_TARGET_APP, "targetApp");
    head.put(RemotingConstants.RPC_TRACE_NAME + ".a", "xxx");
    head.put(RemotingConstants.RPC_TRACE_NAME + ".b", "yyy");
    response = new SofaResponse();
    response.setAppResponse(EchoStrRes.newBuilder().setS("result").build());
    data = serializer.encode(response, null);
    SofaResponse newResponse = new SofaResponse();
    serializer.decode(data, newResponse, head);
    Assert.assertFalse(newResponse.isError());
    Assert.assertEquals(response.getAppResponse(), newResponse.getAppResponse());
    Assert.assertEquals("result", ((EchoStrRes) newResponse.getAppResponse()).getS());
    // null response
    head = new HashMap<String, String>();
    head.put(RemotingConstants.HEAD_TARGET_SERVICE, ProtoService.class.getCanonicalName() + ":1.0");
    head.put(RemotingConstants.HEAD_METHOD_NAME, "echoStr");
    head.put(RemotingConstants.RPC_TRACE_NAME + ".a", "xxx");
    head.put(RemotingConstants.RPC_TRACE_NAME + ".b", "yyy");
    newResponse = new SofaResponse();
    serializer.decode(new ByteArrayWrapperByteBuf(new byte[0]), newResponse, head);
    Assert.assertFalse(newResponse.isError());
    Assert.assertNotNull(newResponse.getAppResponse());
    Assert.assertEquals("", ((EchoStrRes) newResponse.getAppResponse()).getS());
    // error response
    head = new HashMap<String, String>();
    head.put(RemotingConstants.HEAD_TARGET_SERVICE, ProtoService.class.getCanonicalName() + ":1.0");
    head.put(RemotingConstants.HEAD_METHOD_NAME, "echoStr");
    head.put(RemotingConstants.RPC_TRACE_NAME + ".a", "xxx");
    head.put(RemotingConstants.RPC_TRACE_NAME + ".b", "yyy");
    head.put(RemotingConstants.HEAD_RESPONSE_ERROR, "true");
    response = new SofaResponse();
    response.setErrorMsg("1233");
    data = serializer.encode(response, null);
    newResponse = new SofaResponse();
    serializer.decode(data, newResponse, head);
    Assert.assertTrue(newResponse.isError());
    Assert.assertEquals(response.getErrorMsg(), newResponse.getErrorMsg());
}
Also used : AbstractByteBuf(com.alipay.sofa.rpc.transport.AbstractByteBuf) HashMap(java.util.HashMap) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse) ByteArrayWrapperByteBuf(com.alipay.sofa.rpc.transport.ByteArrayWrapperByteBuf) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) Test(org.junit.Test)

Aggregations

SofaResponse (com.alipay.sofa.rpc.core.response.SofaResponse)85 SofaRpcException (com.alipay.sofa.rpc.core.exception.SofaRpcException)25 Test (org.junit.Test)21 SofaRequest (com.alipay.sofa.rpc.core.request.SofaRequest)19 RpcInternalContext (com.alipay.sofa.rpc.context.RpcInternalContext)12 Method (java.lang.reflect.Method)10 AbstractByteBuf (com.alipay.sofa.rpc.transport.AbstractByteBuf)9 HashMap (java.util.HashMap)9 ProviderConfig (com.alipay.sofa.rpc.config.ProviderConfig)6 ClientEndInvokeEvent (com.alipay.sofa.rpc.event.ClientEndInvokeEvent)6 ByteArrayWrapperByteBuf (com.alipay.sofa.rpc.transport.ByteArrayWrapperByteBuf)6 ProviderInfo (com.alipay.sofa.rpc.client.ProviderInfo)5 ClientAsyncReceiveEvent (com.alipay.sofa.rpc.event.ClientAsyncReceiveEvent)5 ClientSyncReceiveEvent (com.alipay.sofa.rpc.event.ClientSyncReceiveEvent)5 Serializer (com.alipay.sofa.rpc.codec.Serializer)4 ConsumerConfig (com.alipay.sofa.rpc.config.ConsumerConfig)4 FilterChain (com.alipay.sofa.rpc.filter.FilterChain)4 Hessian2Input (com.caucho.hessian.io.Hessian2Input)4 BlockException (com.alibaba.csp.sentinel.slots.block.BlockException)3 DeserializationException (com.alipay.remoting.exception.DeserializationException)3