Search in sources :

Example 1 with GSVRoutingMetadata

use of org.kin.rsocket.core.metadata.GSVRoutingMetadata in project kin-rsocket-broker by huangjianqin.

the class HttpGatewayController method handle.

@RequestMapping(value = "/{service}/{method}", produces = { MediaType.APPLICATION_JSON_VALUE })
public Mono<ResponseEntity<ByteBuf>> handle(@PathVariable("service") String service, @PathVariable("method") String method, @RequestParam(name = "group", required = false, defaultValue = "") String group, @RequestParam(name = "version", required = false, defaultValue = "") String version, @RequestBody(required = false) ByteBuf body, @RequestHeader(name = HttpHeaders.AUTHORIZATION, required = false, defaultValue = "") String token) {
    boolean authenticated;
    if (!config.isRestApiAuth()) {
        authenticated = true;
    } else {
        authenticated = Objects.nonNull(authenticationService.auth(token));
    }
    if (!authenticated) {
        return Mono.error(new Exception("Failed to validate JWT token, please supply correct token."));
    }
    try {
        GSVRoutingMetadata routingMetadata = GSVRoutingMetadata.of(group, service, method, version);
        RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.of(routingMetadata, JSON_ENCODING_MIME_TYPE);
        ByteBuf bodyBuf = body == null ? EMPTY_BUFFER : body;
        return upstreamClusterManager.getBroker().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(org.kin.rsocket.core.metadata.RSocketCompositeMetadata) GSVRoutingMetadata(org.kin.rsocket.core.metadata.GSVRoutingMetadata) ByteBuf(io.netty.buffer.ByteBuf)

Example 2 with GSVRoutingMetadata

use of org.kin.rsocket.core.metadata.GSVRoutingMetadata in project kin-rsocket-broker by huangjianqin.

the class BrokerRequestHandler method fireAndForget.

@Nonnull
@Override
public Mono<Void> fireAndForget(Payload payload) {
    BinaryRoutingMetadata binaryRoutingMetadata = BinaryRoutingMetadata.extract(payload.metadata());
    GSVRoutingMetadata gsvRoutingMetadata;
    if (binaryRoutingMetadata != null) {
        gsvRoutingMetadata = binaryRoutingMetadata.toGSVRoutingMetadata();
    } else {
        RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.of(payload.metadata());
        gsvRoutingMetadata = compositeMetadata.getMetadata(RSocketMimeType.ROUTING);
        if (gsvRoutingMetadata == null) {
            return Mono.error(new InvalidException("No Routing metadata"));
        }
    }
    // request filters
    Mono<RSocket> destination;
    if (this.filterChain.isFiltersPresent()) {
        RSocketFilterContext filterContext = RSocketFilterContext.of(FrameType.REQUEST_FNF, gsvRoutingMetadata, this.upstreamBrokerMetadata, payload);
        // filter可能会改变gsv metadata的数据, 影响路由结果
        destination = filterChain.filter(filterContext).then(findDestination(gsvRoutingMetadata));
    } else {
        destination = findDestination(gsvRoutingMetadata);
    }
    // call destination
    return destination.flatMap(rsocket -> {
        MetricsUtils.metrics(gsvRoutingMetadata, FrameType.REQUEST_FNF.name());
        return rsocket.fireAndForget(payload);
    });
}
Also used : RSocketCompositeMetadata(org.kin.rsocket.core.metadata.RSocketCompositeMetadata) GSVRoutingMetadata(org.kin.rsocket.core.metadata.GSVRoutingMetadata) BinaryRoutingMetadata(org.kin.rsocket.core.metadata.BinaryRoutingMetadata) InvalidException(io.rsocket.exceptions.InvalidException) RSocket(io.rsocket.RSocket) AbstractRSocket(org.kin.rsocket.core.AbstractRSocket) Nonnull(javax.annotation.Nonnull)

Example 3 with GSVRoutingMetadata

use of org.kin.rsocket.core.metadata.GSVRoutingMetadata in project kin-rsocket-broker by huangjianqin.

the class BrokerRequestHandler method requestStream.

@Nonnull
@Override
public Flux<Payload> requestStream(Payload payload) {
    BinaryRoutingMetadata binaryRoutingMetadata = BinaryRoutingMetadata.extract(payload.metadata());
    GSVRoutingMetadata gsvRoutingMetadata;
    if (binaryRoutingMetadata != null) {
        gsvRoutingMetadata = binaryRoutingMetadata.toGSVRoutingMetadata();
    } else {
        RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.of(payload.metadata());
        gsvRoutingMetadata = compositeMetadata.getMetadata(RSocketMimeType.ROUTING);
        if (gsvRoutingMetadata == null) {
            return Flux.error(new InvalidException("No Routing metadata"));
        }
    }
    // request filters
    Mono<RSocket> destination;
    if (this.filterChain.isFiltersPresent()) {
        RSocketFilterContext filterContext = RSocketFilterContext.of(FrameType.REQUEST_STREAM, gsvRoutingMetadata, this.upstreamBrokerMetadata, payload);
        // filter可能会改变gsv metadata的数据, 影响路由结果
        destination = filterChain.filter(filterContext).then(findDestination(gsvRoutingMetadata));
    } else {
        destination = findDestination(gsvRoutingMetadata);
    }
    return destination.flatMapMany(rsocket -> {
        MetricsUtils.metrics(gsvRoutingMetadata, FrameType.REQUEST_STREAM.name());
        return rsocket.requestStream(payload);
    });
}
Also used : RSocketCompositeMetadata(org.kin.rsocket.core.metadata.RSocketCompositeMetadata) GSVRoutingMetadata(org.kin.rsocket.core.metadata.GSVRoutingMetadata) BinaryRoutingMetadata(org.kin.rsocket.core.metadata.BinaryRoutingMetadata) InvalidException(io.rsocket.exceptions.InvalidException) RSocket(io.rsocket.RSocket) AbstractRSocket(org.kin.rsocket.core.AbstractRSocket) Nonnull(javax.annotation.Nonnull)

Example 4 with GSVRoutingMetadata

use of org.kin.rsocket.core.metadata.GSVRoutingMetadata in project kin-rsocket-broker by huangjianqin.

the class RSocketApiController method handle.

@RequestMapping(value = "/{service}/{method}", produces = { MediaType.APPLICATION_JSON_VALUE })
public Mono<ResponseEntity<String>> handle(@PathVariable("service") String service, @PathVariable("method") String method, @RequestParam(name = "group", required = false, defaultValue = "") String group, @RequestParam(name = "version", required = false, defaultValue = "") String version, @RequestBody(required = false) byte[] body, @RequestHeader(name = "X-Endpoint", required = false, defaultValue = "") String endpoint, @RequestHeader(name = HttpHeaders.AUTHORIZATION, required = false, defaultValue = "") String token) {
    try {
        GSVRoutingMetadata routingMetadata = GSVRoutingMetadata.of(group, service, method, version);
        int serviceId = routingMetadata.serviceId();
        ByteBuf bodyBuf = body == null ? EMPTY_BUFFER : Unpooled.wrappedBuffer(body);
        RSocketEndpoint rsocketEndpoint;
        if (endpoint.startsWith("id:")) {
            // 存在endpoint
            int instanceId = Integer.parseInt(endpoint.substring(3).trim());
            rsocketEndpoint = serviceManager.getByInstanceId(instanceId);
        } else {
            rsocketEndpoint = serviceManager.routeByServiceId(serviceId);
        }
        if (Objects.nonNull(rsocketEndpoint)) {
            if (rsocketBrokerProperties.isAuth()) {
                RSocketAppPrincipal principal = authenticationService.auth(token);
                if (principal == null || !serviceMeshInspector.isAllowed(principal, serviceId, rsocketEndpoint.getPrincipal())) {
                    return Mono.just(error(String.format("Service request not allowed '%s'", routingMetadata.gsv())));
                }
            }
            RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.of(routingMetadata, JSON_ENCODING_METADATA);
            return rsocketEndpoint.requestResponse(DefaultPayload.create(bodyBuf, compositeMetadata.getContent())).map(payload -> {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                headers.setCacheControl(CacheControl.noCache().getHeaderValue());
                return new ResponseEntity<>(payload.getDataUtf8(), headers, HttpStatus.OK);
            });
        }
        return Mono.just(error(String.format("service not found, '%s'", routingMetadata.gsv())));
    } catch (Exception e) {
        return Mono.just(error(e.getMessage()));
    }
}
Also used : RSocketCompositeMetadata(org.kin.rsocket.core.metadata.RSocketCompositeMetadata) GSVRoutingMetadata(org.kin.rsocket.core.metadata.GSVRoutingMetadata) ByteBuf(io.netty.buffer.ByteBuf) RSocketEndpoint(org.kin.rsocket.broker.RSocketEndpoint) RSocketAppPrincipal(org.kin.rsocket.auth.RSocketAppPrincipal) RSocketEndpoint(org.kin.rsocket.broker.RSocketEndpoint)

Example 5 with GSVRoutingMetadata

use of org.kin.rsocket.core.metadata.GSVRoutingMetadata in project kin-rsocket-broker by huangjianqin.

the class RSocketServiceQueryController method queryDefinition.

@GetMapping(value = "/definition/{service}")
public Mono<String> queryDefinition(@RequestParam(name = "group", defaultValue = "") String group, @PathVariable(name = "service") String service, @RequestParam(name = "version", defaultValue = "") String version) {
    ByteBuf bodyBuf = Unpooled.wrappedBuffer(("[\"".concat(service).concat("\"]")).getBytes(StandardCharsets.UTF_8));
    RSocketEndpoint RSocketEndpoint = serviceManager.routeByServiceId(ServiceLocator.of(group, service, version).getId());
    if (Objects.nonNull(RSocketEndpoint)) {
        GSVRoutingMetadata routingMetadata = GSVRoutingMetadata.of("", RSocketServiceInfoSupport.class.getName() + ".getReactiveServiceInfoByName", "");
        RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.of(routingMetadata, JSON_ENCODING_METADATA);
        return RSocketEndpoint.requestResponse(ByteBufPayload.create(bodyBuf, compositeMetadata.getContent())).map(Payload::getDataUtf8);
    }
    return Mono.error(new Exception(String.format("Service not found '%s'", service)));
}
Also used : RSocketCompositeMetadata(org.kin.rsocket.core.metadata.RSocketCompositeMetadata) GSVRoutingMetadata(org.kin.rsocket.core.metadata.GSVRoutingMetadata) Payload(io.rsocket.Payload) ByteBufPayload(io.rsocket.util.ByteBufPayload) ByteBuf(io.netty.buffer.ByteBuf) RSocketEndpoint(org.kin.rsocket.broker.RSocketEndpoint)

Aggregations

GSVRoutingMetadata (org.kin.rsocket.core.metadata.GSVRoutingMetadata)11 InvalidException (io.rsocket.exceptions.InvalidException)7 RSocketCompositeMetadata (org.kin.rsocket.core.metadata.RSocketCompositeMetadata)7 Payload (io.rsocket.Payload)4 RSocket (io.rsocket.RSocket)4 ByteBufPayload (io.rsocket.util.ByteBufPayload)4 AbstractRSocket (org.kin.rsocket.core.AbstractRSocket)4 BinaryRoutingMetadata (org.kin.rsocket.core.metadata.BinaryRoutingMetadata)4 ByteBuf (io.netty.buffer.ByteBuf)3 ReferenceCountUtil (io.netty.util.ReferenceCountUtil)3 Nonnull (javax.annotation.Nonnull)3 LoggerOprs (org.kin.framework.log.LoggerOprs)3 ExceptionUtils (org.kin.framework.utils.ExceptionUtils)3 Codecs (org.kin.rsocket.core.codec.Codecs)3 MessageAcceptMimeTypesMetadata (org.kin.rsocket.core.metadata.MessageAcceptMimeTypesMetadata)3 MessageMimeTypeMetadata (org.kin.rsocket.core.metadata.MessageMimeTypeMetadata)3 Flux (reactor.core.publisher.Flux)3 Mono (reactor.core.publisher.Mono)3 RSocketEndpoint (org.kin.rsocket.broker.RSocketEndpoint)2 RSocketAppPrincipal (org.kin.rsocket.auth.RSocketAppPrincipal)1