Search in sources :

Example 1 with MutableContext

use of com.alibaba.rsocket.MutableContext in project alibaba-rsocket-broker by alibaba.

the class RSocketRequesterRpcProxy method invoke.

@Override
@RuntimeType
public Object invoke(@This Object proxy, @Origin Method method, @AllArguments Object[] allArguments) throws Throwable {
    // interface default method validation for JDK Proxy only, not necessary for ByteBuddy
    if (jdkProxy && method.isDefault()) {
        return DefaultMethodHandler.getMethodHandle(method, serviceInterface).bindTo(proxy).invokeWithArguments(allArguments);
    } else if (method.getDeclaringClass().equals(Object.class)) {
        // delegate hashCode, equals, or toString methods to this
        return method.invoke(this);
    }
    MutableContext mutableContext = new MutableContext();
    if (!methodMetadataMap.containsKey(method)) {
        methodMetadataMap.put(method, new ReactiveMethodMetadata(group, service, version, method, encodingType, this.acceptEncodingTypes, endpoint, sticky, sourceUri));
    }
    ReactiveMethodMetadata methodMetadata = methodMetadataMap.get(method);
    mutableContext.put(ReactiveMethodMetadata.class, methodMetadata);
    Object[] args = allArguments;
    if (methodMetadata.isKotlinSuspend()) {
        args = Arrays.copyOfRange(args, 0, args.length - 1);
        mutableContext.put(Continuation.class, allArguments[allArguments.length - 1]);
    }
    // ----- return type deal------
    if (methodMetadata.getRsocketFrameType() == FrameType.REQUEST_CHANNEL) {
        metrics(methodMetadata);
        Payload routePayload;
        Flux<Object> source;
        // 1 param or 2 params
        if (args.length == 1) {
            routePayload = ByteBufPayload.create(Unpooled.EMPTY_BUFFER, methodMetadata.getCompositeMetadataByteBuf().retainedDuplicate());
            source = methodMetadata.getReactiveAdapter().toFlux(args[0]);
        } else {
            ByteBuf bodyBuffer = encodingFacade.encodingResult(args[0], methodMetadata.getParamEncoding());
            routePayload = ByteBufPayload.create(bodyBuffer, methodMetadata.getCompositeMetadataByteBuf().retainedDuplicate());
            source = methodMetadata.getReactiveAdapter().toFlux(args[1]);
        }
        Flux<Payload> payloadFlux = source.startWith(routePayload).map(obj -> {
            if (obj instanceof Payload)
                return (Payload) obj;
            return ByteBufPayload.create(encodingFacade.encodingResult(obj, encodingType), methodMetadata.getCompositeMetadataByteBuf().retainedDuplicate());
        });
        Flux<Payload> payloads = upstreamManager.getRSocket(this.serviceId).requestChannel(payloadFlux);
        Flux<Object> fluxReturn = payloads.concatMap(payload -> {
            try {
                RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata());
                return Mono.justOrEmpty(encodingFacade.decodeResult(extractPayloadDataMimeType(compositeMetadata, encodingType), payload.data(), methodMetadata.getInferredClassForReturn()));
            } catch (Exception e) {
                return Flux.error(e);
            }
        }).subscriberContext(mutableContext::putAll);
        if (methodMetadata.isMonoChannel()) {
            return fluxReturn.last();
        } else {
            return methodMetadata.getReactiveAdapter().fromPublisher(fluxReturn, method.getReturnType());
        }
    } else {
        // body content
        ByteBuf bodyBuffer = encodingFacade.encodingParams(args, methodMetadata.getParamEncoding());
        Class<?> returnType = method.getReturnType();
        if (methodMetadata.getRsocketFrameType() == FrameType.REQUEST_RESPONSE) {
            metrics(methodMetadata);
            Mono<Payload> payloadMono = remoteRequestResponse(methodMetadata, methodMetadata.getCompositeMetadataByteBuf().retainedDuplicate(), bodyBuffer);
            Mono<Object> result = payloadMono.handle((payload, sink) -> {
                try {
                    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata());
                    Object obj = encodingFacade.decodeResult(extractPayloadDataMimeType(compositeMetadata, encodingType), payload.data(), methodMetadata.getInferredClassForReturn());
                    if (obj != null) {
                        sink.next(obj);
                    }
                    sink.complete();
                } catch (Exception e) {
                    sink.error(e);
                }
            });
            return methodMetadata.getReactiveAdapter().fromPublisher(result, returnType, mutableContext);
        } else if (methodMetadata.getRsocketFrameType() == FrameType.REQUEST_FNF) {
            metrics(methodMetadata);
            return remoteFireAndForget(methodMetadata, methodMetadata.getCompositeMetadataByteBuf().retainedDuplicate(), bodyBuffer);
        } else if (methodMetadata.getRsocketFrameType() == FrameType.REQUEST_STREAM) {
            metrics(methodMetadata);
            Flux<Payload> flux = remoteRequestStream(methodMetadata, methodMetadata.getCompositeMetadataByteBuf().retainedDuplicate(), bodyBuffer);
            Flux<Object> result = flux.concatMap((payload) -> {
                try {
                    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata());
                    return Mono.justOrEmpty(encodingFacade.decodeResult(extractPayloadDataMimeType(compositeMetadata, encodingType), payload.data(), methodMetadata.getInferredClassForReturn()));
                } catch (Exception e) {
                    return Mono.error(e);
                }
            });
            return methodMetadata.getReactiveAdapter().fromPublisher(result, returnType, mutableContext);
        } else {
            ReferenceCountUtil.safeRelease(bodyBuffer);
            return Mono.error(new Exception(RsocketErrorCode.message("RST-200405", methodMetadata.getRsocketFrameType())));
        }
    }
}
Also used : This(net.bytebuddy.implementation.bind.annotation.This) Continuation(kotlin.coroutines.Continuation) Arrays(java.util.Arrays) Origin(net.bytebuddy.implementation.bind.annotation.Origin) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) Metrics(io.micrometer.core.instrument.Metrics) Unpooled(io.netty.buffer.Unpooled) RuntimeType(net.bytebuddy.implementation.bind.annotation.RuntimeType) MessageMimeTypeMetadata(com.alibaba.rsocket.metadata.MessageMimeTypeMetadata) ByteBuf(io.netty.buffer.ByteBuf) AllArguments(net.bytebuddy.implementation.bind.annotation.AllArguments) MutableContext(com.alibaba.rsocket.MutableContext) Duration(java.time.Duration) Map(java.util.Map) URI(java.net.URI) Method(java.lang.reflect.Method) RSocketEncodingFacade(com.alibaba.rsocket.encoding.RSocketEncodingFacade) ByteBufPayload(io.rsocket.util.ByteBufPayload) RSocketMimeType(com.alibaba.rsocket.metadata.RSocketMimeType) FrameType(io.rsocket.frame.FrameType) Logger(org.slf4j.Logger) RsocketErrorCode(com.alibaba.rsocket.observability.RsocketErrorCode) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Mono(reactor.core.publisher.Mono) RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) Nullable(org.jetbrains.annotations.Nullable) Flux(reactor.core.publisher.Flux) Payload(io.rsocket.Payload) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) UpstreamManager(com.alibaba.rsocket.upstream.UpstreamManager) InvocationHandler(java.lang.reflect.InvocationHandler) NotNull(org.jetbrains.annotations.NotNull) ServiceLocator(com.alibaba.rsocket.ServiceLocator) RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) MutableContext(com.alibaba.rsocket.MutableContext) ByteBuf(io.netty.buffer.ByteBuf) TimeoutException(java.util.concurrent.TimeoutException) ByteBufPayload(io.rsocket.util.ByteBufPayload) Payload(io.rsocket.Payload) RuntimeType(net.bytebuddy.implementation.bind.annotation.RuntimeType)

Aggregations

MutableContext (com.alibaba.rsocket.MutableContext)1 ServiceLocator (com.alibaba.rsocket.ServiceLocator)1 RSocketEncodingFacade (com.alibaba.rsocket.encoding.RSocketEncodingFacade)1 MessageMimeTypeMetadata (com.alibaba.rsocket.metadata.MessageMimeTypeMetadata)1 RSocketCompositeMetadata (com.alibaba.rsocket.metadata.RSocketCompositeMetadata)1 RSocketMimeType (com.alibaba.rsocket.metadata.RSocketMimeType)1 RsocketErrorCode (com.alibaba.rsocket.observability.RsocketErrorCode)1 UpstreamManager (com.alibaba.rsocket.upstream.UpstreamManager)1 Metrics (io.micrometer.core.instrument.Metrics)1 ByteBuf (io.netty.buffer.ByteBuf)1 Unpooled (io.netty.buffer.Unpooled)1 ReferenceCountUtil (io.netty.util.ReferenceCountUtil)1 Payload (io.rsocket.Payload)1 FrameType (io.rsocket.frame.FrameType)1 ByteBufPayload (io.rsocket.util.ByteBufPayload)1 InvocationHandler (java.lang.reflect.InvocationHandler)1 Method (java.lang.reflect.Method)1 URI (java.net.URI)1 Duration (java.time.Duration)1 Arrays (java.util.Arrays)1