Search in sources :

Example 6 with RSocketCompositeMetadata

use of com.alibaba.rsocket.metadata.RSocketCompositeMetadata in project rsocket-graphql-gateway by alibaba-rsocket-broker.

the class MainController method executeRequest.

private Mono<ResponseEntity<ByteBuf>> executeRequest(String clusterName, GraphQLInvocationData invocationData, String authorizationValue) {
    boolean authenticated;
    if (!authRequired) {
        authenticated = true;
    } else {
        authenticated = authAuthorizationValue(authorizationValue);
    }
    if (!authenticated) {
        return Mono.error(new Exception(RsocketErrorCode.message("RST-500403")));
    }
    try {
        GSVRoutingMetadata routingMetadata = new GSVRoutingMetadata(clusterName, GRAPHQL_SERVICE_NAME, "execute", "");
        RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(routingMetadata, graphqlEncoding);
        ByteBuf bodyBuf = Unpooled.wrappedBuffer(objectMapper.writeValueAsBytes(invocationData));
        return rsocket.requestResponse(ByteBufPayload.create(bodyBuf, compositeMetadata.getContent())).map(payload -> {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setCacheControl(CacheControl.noCache().getHeaderValue());
            return new ResponseEntity<>(payload.data(), headers, HttpStatus.OK);
        });
    } catch (Exception e) {
        return Mono.error(e);
    }
}
Also used : RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) GSVRoutingMetadata(com.alibaba.rsocket.metadata.GSVRoutingMetadata) ByteBuf(io.netty.buffer.ByteBuf)

Example 7 with RSocketCompositeMetadata

use of com.alibaba.rsocket.metadata.RSocketCompositeMetadata in project alibaba-broker-kotlin-example by alibaba-rsocket-broker.

the class UserServiceRSocketTest method testFindById.

@Test
public void testFindById() throws Exception {
    RSocketCompositeMetadata compositeMetadata = new RSocketCompositeMetadata();
    GSVRoutingMetadata routingMetadata = new GSVRoutingMetadata("", "com.alibaba.user.UserService2", "findById", "");
    compositeMetadata.addMetadata(routingMetadata);
    MessageMimeTypeMetadata dataEncodingMetadata = new MessageMimeTypeMetadata(WellKnownMimeType.APPLICATION_JSON);
    compositeMetadata.addMetadata(dataEncodingMetadata);
    rsocket.requestResponse(DefaultPayload.create(Unpooled.wrappedBuffer(objectMapper.writeValueAsBytes(1)), compositeMetadata.getContent())).doOnTerminate(() -> {
        ReferenceCountUtil.safeRelease(compositeMetadata);
    }).subscribe(payload -> {
        System.out.println(payload.getDataUtf8());
    });
    Thread.sleep(1000);
}
Also used : RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) GSVRoutingMetadata(com.alibaba.rsocket.metadata.GSVRoutingMetadata) MessageMimeTypeMetadata(com.alibaba.rsocket.metadata.MessageMimeTypeMetadata)

Example 8 with RSocketCompositeMetadata

use of com.alibaba.rsocket.metadata.RSocketCompositeMetadata in project alibaba-rsocket-broker by alibaba.

the class UpstreamForwardRSocket method requestResponse.

@Override
@NotNull
public Mono<Payload> requestResponse(@NotNull Payload payload) {
    BinaryRoutingMetadata binaryRoutingMetadata = binaryRoutingMetadata(payload.metadata());
    GSVRoutingMetadata gsvRoutingMetadata;
    if (binaryRoutingMetadata != null) {
        gsvRoutingMetadata = GSVRoutingMetadata.from(new String(binaryRoutingMetadata.getRoutingText(), StandardCharsets.UTF_8));
    } else {
        RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata());
        gsvRoutingMetadata = compositeMetadata.getRoutingMetaData();
        if (gsvRoutingMetadata == null) {
            return Mono.error(new InvalidException(RsocketErrorCode.message("RST-600404")));
        }
    }
    // request filters
    Mono<RSocket> destination = findDestination(gsvRoutingMetadata);
    if (this.filterChain.isFiltersPresent()) {
        RSocketExchange exchange = new RSocketExchange(FrameType.REQUEST_RESPONSE, gsvRoutingMetadata, payload, this.upstreamBrokerMetadata);
        destination = filterChain.filter(exchange).then(destination);
    }
    // call destination
    return destination.flatMap(rsocket -> {
        metrics(gsvRoutingMetadata, "0x05");
        return rsocket.requestResponse(payload);
    });
}
Also used : RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) RSocketExchange(com.alibaba.rsocket.RSocketExchange) GSVRoutingMetadata(com.alibaba.rsocket.metadata.GSVRoutingMetadata) BinaryRoutingMetadata(com.alibaba.rsocket.metadata.BinaryRoutingMetadata) InvalidException(io.rsocket.exceptions.InvalidException) RSocket(io.rsocket.RSocket) AbstractRSocket(com.alibaba.rsocket.AbstractRSocket) NotNull(org.jetbrains.annotations.NotNull)

Example 9 with RSocketCompositeMetadata

use of com.alibaba.rsocket.metadata.RSocketCompositeMetadata in project alibaba-rsocket-broker by alibaba.

the class UpstreamForwardRSocket method fireAndForget.

@Override
@NotNull
public Mono<Void> fireAndForget(@NotNull Payload payload) {
    BinaryRoutingMetadata binaryRoutingMetadata = binaryRoutingMetadata(payload.metadata());
    GSVRoutingMetadata gsvRoutingMetadata;
    if (binaryRoutingMetadata != null) {
        gsvRoutingMetadata = GSVRoutingMetadata.from(new String(binaryRoutingMetadata.getRoutingText(), StandardCharsets.UTF_8));
    } else {
        RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata());
        gsvRoutingMetadata = compositeMetadata.getRoutingMetaData();
        if (gsvRoutingMetadata == null) {
            return Mono.error(new InvalidException(RsocketErrorCode.message("RST-600404")));
        }
    }
    // request filters
    Mono<RSocket> destination = findDestination(gsvRoutingMetadata);
    if (this.filterChain.isFiltersPresent()) {
        RSocketExchange exchange = new RSocketExchange(FrameType.REQUEST_FNF, gsvRoutingMetadata, payload, this.upstreamBrokerMetadata);
        destination = filterChain.filter(exchange).then(destination);
    }
    // call destination
    return destination.flatMap(rsocket -> {
        metrics(gsvRoutingMetadata, "0x05");
        return rsocket.fireAndForget(payload);
    });
}
Also used : RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) RSocketExchange(com.alibaba.rsocket.RSocketExchange) GSVRoutingMetadata(com.alibaba.rsocket.metadata.GSVRoutingMetadata) BinaryRoutingMetadata(com.alibaba.rsocket.metadata.BinaryRoutingMetadata) InvalidException(io.rsocket.exceptions.InvalidException) RSocket(io.rsocket.RSocket) AbstractRSocket(com.alibaba.rsocket.AbstractRSocket) NotNull(org.jetbrains.annotations.NotNull)

Example 10 with RSocketCompositeMetadata

use of com.alibaba.rsocket.metadata.RSocketCompositeMetadata in project alibaba-rsocket-broker by alibaba.

the class RSocketBrokerHandlerRegistryImpl method accept.

@Override
@NotNull
public Mono<RSocket> accept(@NotNull final ConnectionSetupPayload setupPayload, @NotNull final RSocket requesterSocket) {
    // parse setup payload
    RSocketCompositeMetadata compositeMetadata = null;
    AppMetadata appMetadata = null;
    String credentials = "";
    RSocketAppPrincipal principal = null;
    String errorMsg = null;
    try {
        compositeMetadata = RSocketCompositeMetadata.from(setupPayload.metadata());
        if (!authRequired) {
            // authentication not required
            principal = appNameBasedPrincipal("MockApp");
            credentials = UUID.randomUUID().toString();
        } else if (compositeMetadata.contains(RSocketMimeType.BearerToken)) {
            BearerTokenMetadata bearerTokenMetadata = BearerTokenMetadata.from(compositeMetadata.getMetadata(RSocketMimeType.BearerToken));
            credentials = new String(bearerTokenMetadata.getBearerToken());
            principal = authenticationService.auth("JWT", credentials);
        } else {
            // no jwt token supplied
            errorMsg = RsocketErrorCode.message("RST-500405");
        }
        // validate application information
        if (principal != null && compositeMetadata.contains(RSocketMimeType.Application)) {
            AppMetadata temp = AppMetadata.from(compositeMetadata.getMetadata(RSocketMimeType.Application));
            // App registration validation: app id: UUID and unique in server
            if (temp.getUuid() == null || temp.getUuid().isEmpty()) {
                temp.setUuid(UUID.randomUUID().toString());
            }
            String appId = temp.getUuid();
            // validate appId data format
            if (appId != null && appId.length() >= 32) {
                Integer instanceId = MurmurHash3.hash32(credentials + ":" + temp.getUuid());
                temp.setId(instanceId);
                // application instance not connected
                if (!routingSelector.containInstance(instanceId)) {
                    appMetadata = temp;
                    appMetadata.setConnectedAt(new Date());
                } else {
                    // application connected already
                    errorMsg = RsocketErrorCode.message("RST-500409");
                }
            } else {
                // illegal application id, appID should be UUID
                errorMsg = RsocketErrorCode.message("RST-500410", appId == null ? "" : appId);
            }
        }
        if (errorMsg == null) {
            // Security authentication
            if (appMetadata != null) {
                appMetadata.addMetadata("_orgs", String.join(",", principal.getOrganizations()));
                appMetadata.addMetadata("_roles", String.join(",", principal.getRoles()));
                appMetadata.addMetadata("_serviceAccounts", String.join(",", principal.getServiceAccounts()));
            } else {
                errorMsg = RsocketErrorCode.message("RST-500411");
            }
        }
    } catch (Exception e) {
        log.error(RsocketErrorCode.message("RST-500402"), e);
        errorMsg = RsocketErrorCode.message("RST-600500", e.getMessage());
    }
    // validate connection legal or not
    if (principal == null) {
        errorMsg = RsocketErrorCode.message("RST-500405");
    }
    if (errorMsg != null) {
        return returnRejectedRSocket(errorMsg, requesterSocket);
    }
    // create handler
    try {
        RSocketBrokerResponderHandler brokerResponderHandler = new RSocketBrokerResponderHandler(setupPayload, compositeMetadata, appMetadata, principal, requesterSocket, routingSelector, eventProcessor, this, serviceMeshInspector, getUpstreamRSocket());
        brokerResponderHandler.setFilterChain(rsocketFilterChain);
        brokerResponderHandler.setLocalReactiveServiceCaller(localReactiveServiceCaller);
        brokerResponderHandler.onClose().doOnTerminate(() -> onHandlerDisposed(brokerResponderHandler)).subscribeOn(Schedulers.parallel()).subscribe();
        // handler registration notify
        onHandlerRegistered(brokerResponderHandler);
        log.info(RsocketErrorCode.message("RST-500200", appMetadata.getName()));
        return Mono.just(brokerResponderHandler);
    } catch (Exception e) {
        log.error(RsocketErrorCode.message("RST-500406", e.getMessage()), e);
        return returnRejectedRSocket(RsocketErrorCode.message("RST-500406", e.getMessage()), requesterSocket);
    }
}
Also used : RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) BearerTokenMetadata(com.alibaba.rsocket.metadata.BearerTokenMetadata) AppMetadata(com.alibaba.rsocket.metadata.AppMetadata) RSocketAppPrincipal(com.alibaba.spring.boot.rsocket.broker.security.RSocketAppPrincipal) RejectedSetupException(io.rsocket.exceptions.RejectedSetupException) ApplicationErrorException(io.rsocket.exceptions.ApplicationErrorException) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

RSocketCompositeMetadata (com.alibaba.rsocket.metadata.RSocketCompositeMetadata)16 GSVRoutingMetadata (com.alibaba.rsocket.metadata.GSVRoutingMetadata)13 MessageMimeTypeMetadata (com.alibaba.rsocket.metadata.MessageMimeTypeMetadata)7 ByteBuf (io.netty.buffer.ByteBuf)6 NotNull (org.jetbrains.annotations.NotNull)5 AbstractRSocket (com.alibaba.rsocket.AbstractRSocket)4 BinaryRoutingMetadata (com.alibaba.rsocket.metadata.BinaryRoutingMetadata)4 RSocket (io.rsocket.RSocket)4 InvalidException (io.rsocket.exceptions.InvalidException)4 Nullable (org.jetbrains.annotations.Nullable)4 RSocketExchange (com.alibaba.rsocket.RSocketExchange)3 ServiceLocator (com.alibaba.rsocket.ServiceLocator)3 RSocketMimeType (com.alibaba.rsocket.metadata.RSocketMimeType)3 Unpooled (io.netty.buffer.Unpooled)3 Payload (io.rsocket.Payload)3 ByteBufPayload (io.rsocket.util.ByteBufPayload)3 RsocketErrorCode (com.alibaba.rsocket.observability.RsocketErrorCode)2 RSocketBrokerHandlerRegistry (com.alibaba.spring.boot.rsocket.broker.responder.RSocketBrokerHandlerRegistry)2 RSocketBrokerResponderHandler (com.alibaba.spring.boot.rsocket.broker.responder.RSocketBrokerResponderHandler)2 ServiceRoutingSelector (com.alibaba.spring.boot.rsocket.broker.route.ServiceRoutingSelector)2