com.linecorp.armeria.common.grpc.GrpcSerializationFormats Java Examples

The following examples show how to use com.linecorp.armeria.common.grpc.GrpcSerializationFormats. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ArmeriaServerCallTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void messageRead_wrappedByteBuf() {
    tearDown();

    call = new ArmeriaServerCall<>(
            HttpHeaders.of(),
            TestServiceGrpc.getUnaryCallMethod(),
            CompressorRegistry.getDefaultInstance(),
            DecompressorRegistry.getDefaultInstance(),
            res,
            MAX_MESSAGE_BYTES,
            MAX_MESSAGE_BYTES,
            ctx,
            GrpcSerializationFormats.PROTO,
            new DefaultJsonMarshaller(MessageMarshaller.builder().build()),
            true,
            false,
            ResponseHeaders.builder(HttpStatus.OK)
                           .contentType(GrpcSerializationFormats.PROTO.mediaType())
                           .build());

    final ByteBuf buf = GrpcTestUtil.requestByteBuf();
    call.messageRead(new DeframedMessage(buf, 0));

    verify(buffersAttr).put(any(), same(buf));
}
 
Example #2
Source File: GrpcMetricsIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static void makeRequest(String name) throws Exception {
    final TestServiceBlockingStub client =
            Clients.builder(server.httpUri(GrpcSerializationFormats.PROTO))
                   .factory(clientFactory)
                   .decorator(MetricCollectingClient.newDecorator(
                           MeterIdPrefixFunction.ofDefault("client")))
                   .build(TestServiceBlockingStub.class);

    final SimpleRequest request =
            SimpleRequest.newBuilder()
                         .setPayload(Payload.newBuilder()
                                            .setBody(ByteString.copyFromUtf8(name)))
                         .build();
    try {
        client.unaryCall(request);
    } catch (Throwable t) {
        // Ignore, we will count these up
    }
}
 
Example #3
Source File: GrpcMessageMarshallerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void deserializeResponse_wrappedByteBuf() throws Exception {
    marshaller = new GrpcMessageMarshaller<>(
            ByteBufAllocator.DEFAULT,
            GrpcSerializationFormats.PROTO,
            TestServiceGrpc.getUnaryCallMethod(),
            DEFAULT_JSON_MARSHALLER,
            true);
    final ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(GrpcTestUtil.RESPONSE_MESSAGE.getSerializedSize());
    assertThat(buf.refCnt()).isEqualTo(1);
    buf.writeBytes(GrpcTestUtil.RESPONSE_MESSAGE.toByteArray());
    final SimpleResponse response = marshaller.deserializeResponse(new DeframedMessage(buf, 0));
    assertThat(response).isEqualTo(GrpcTestUtil.RESPONSE_MESSAGE);
    assertThat(buf.refCnt()).isEqualTo(1);
    buf.release();
}
 
Example #4
Source File: GrpcMessageMarshallerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void deserializeRequest_wrappedByteBuf() throws Exception {
    marshaller = new GrpcMessageMarshaller<>(
            ByteBufAllocator.DEFAULT,
            GrpcSerializationFormats.PROTO,
            TestServiceGrpc.getUnaryCallMethod(),
            DEFAULT_JSON_MARSHALLER,
            true);
    final ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(GrpcTestUtil.REQUEST_MESSAGE.getSerializedSize());
    assertThat(buf.refCnt()).isEqualTo(1);
    buf.writeBytes(GrpcTestUtil.REQUEST_MESSAGE.toByteArray());
    final SimpleRequest request = marshaller.deserializeRequest(new DeframedMessage(buf, 0));
    assertThat(request).isEqualTo(GrpcTestUtil.REQUEST_MESSAGE);
    assertThat(buf.refCnt()).isEqualTo(1);
    buf.release();
}
 
Example #5
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.workerGroup(EventLoopGroups.newEventLoopGroup(1), true);
    sb.maxRequestLength(0);

    sb.serviceUnder("/",
                    GrpcService.builder()
                               .setMaxInboundMessageSizeBytes(MAX_MESSAGE_SIZE)
                               .addService(ServerInterceptors.intercept(
                                       new UnitTestServiceImpl(),
                                       REPLACE_EXCEPTION, ADD_TO_CONTEXT))
                               .enableUnframedRequests(true)
                               .supportedSerializationFormats(
                                       GrpcSerializationFormats.values())
                               .useBlockingTaskExecutor(true)
                               .build()
                               .decorate(LoggingService.newDecorator())
                               .decorate((delegate, ctx, req) -> {
                                   ctx.log().whenComplete().thenAccept(requestLogQueue::add);
                                   return delegate.serve(ctx, req);
                               }));
}
 
Example #6
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() {
    requestLogQueue.clear();
    final DecoratingHttpClientFunction requestLogRecorder = (delegate, ctx, req) -> {
        ctx.log().whenComplete().thenAccept(requestLogQueue::add);
        return delegate.execute(ctx, req);
    };

    final URI uri = server.httpUri(GrpcSerializationFormats.PROTO);
    blockingStub = Clients.builder(uri)
                          .maxResponseLength(MAX_MESSAGE_SIZE)
                          .decorator(LoggingClient.builder().newDecorator())
                          .decorator(requestLogRecorder)
                          .build(TestServiceBlockingStub.class);
    asyncStub = Clients.builder(uri.getScheme(), server.httpEndpoint())
                       .decorator(LoggingClient.builder().newDecorator())
                       .decorator(requestLogRecorder)
                       .build(TestServiceStub.class);
}
 
Example #7
Source File: GrpcMessageMarshaller.java    From armeria with Apache License 2.0 6 votes vote down vote up
public GrpcMessageMarshaller(ByteBufAllocator alloc,
                             SerializationFormat serializationFormat,
                             MethodDescriptor<I, O> method,
                             @Nullable GrpcJsonMarshaller jsonMarshaller,
                             boolean unsafeWrapDeserializedBuffer) {
    this.alloc = requireNonNull(alloc, "alloc");
    this.method = requireNonNull(method, "method");
    this.unsafeWrapDeserializedBuffer = unsafeWrapDeserializedBuffer;
    checkArgument(!GrpcSerializationFormats.isJson(serializationFormat) || jsonMarshaller != null,
                  "jsonMarshaller must be non-null when serializationFormat is JSON.");
    isProto = GrpcSerializationFormats.isProto(serializationFormat);
    this.jsonMarshaller = jsonMarshaller;
    requestMarshaller = method.getRequestMarshaller();
    responseMarshaller = method.getResponseMarshaller();
    requestType = marshallerType(requestMarshaller);
    responseType = marshallerType(responseMarshaller);
}
 
Example #8
Source File: ArmeriaAutoConfigurationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Bean
public GrpcServiceRegistrationBean helloGrpcService() {
    return new GrpcServiceRegistrationBean()
            .setServiceName("helloGrpcService")
            .setService(GrpcService.builder()
                                   .addService(new HelloGrpcService())
                                   .supportedSerializationFormats(GrpcSerializationFormats.values())
                                   .enableUnframedRequests(true)
                                   .build())
            .setDecorators(LoggingService.newDecorator())
            .addExampleRequests(HelloServiceGrpc.SERVICE_NAME,
                                "Hello",
                                HelloRequest.newBuilder().setName("Armeria").build())
            .addExampleHeaders(HelloServiceGrpc.SERVICE_NAME, "x-additional-header", "headerVal")
            .addExampleHeaders(HelloServiceGrpc.SERVICE_NAME, "Hello", "x-additional-header",
                               "headerVal");
}
 
Example #9
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static RequestLog clientSocketClosedAfterHalfCloseBeforeCloseCancels(SessionProtocol protocol)
        throws Exception {

    final ClientFactory factory = ClientFactory.builder().build();
    final UnitTestServiceStub stub =
            Clients.builder(server.uri(protocol, GrpcSerializationFormats.PROTO))
                   .factory(factory)
                   .build(UnitTestServiceStub.class);
    final AtomicReference<SimpleResponse> response = new AtomicReference<>();
    stub.streamClientCancelsBeforeResponseClosedCancels(
            SimpleRequest.getDefaultInstance(),
            new StreamObserver<SimpleResponse>() {
                @Override
                public void onNext(SimpleResponse value) {
                    response.set(value);
                }

                @Override
                public void onError(Throwable t) {
                }

                @Override
                public void onCompleted() {
                }
            });
    await().untilAsserted(() -> assertThat(response).hasValue(SimpleResponse.getDefaultInstance()));
    factory.close();
    CLIENT_CLOSED.set(true);
    await().untilAsserted(() -> assertThat(COMPLETED).hasValue(true));

    final RequestLog log = requestLogQueue.take();
    assertThat(log.isComplete()).isTrue();
    assertThat(log.requestContent()).isNotNull();
    assertThat(log.responseContent()).isNull();
    final RpcRequest rpcReq = (RpcRequest) log.requestContent();
    assertThat(rpcReq.method()).isEqualTo(
            "armeria.grpc.testing.UnitTestService/StreamClientCancelsBeforeResponseClosedCancels");
    assertThat(rpcReq.params()).containsExactly(SimpleRequest.getDefaultInstance());
    return log;
}
 
Example #10
Source File: GrpcFlowControlTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    client = Clients.builder(server.httpUri(GrpcSerializationFormats.PROTO))
                    .maxResponseLength(0)
                    .responseTimeoutMillis(0)
                    .build(FlowControlTestServiceStub.class);
}
 
Example #11
Source File: Main.java    From armeria with Apache License 2.0 5 votes vote down vote up
static Server newServer(int httpPort, int httpsPort) throws Exception {
    final HelloRequest exampleRequest = HelloRequest.newBuilder().setName("Armeria").build();
    final HttpServiceWithRoutes grpcService =
            GrpcService.builder()
                       .addService(new HelloServiceImpl())
                       // See https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md
                       .addService(ProtoReflectionService.newInstance())
                       .supportedSerializationFormats(GrpcSerializationFormats.values())
                       .enableUnframedRequests(true)
                       // You can set useBlockingTaskExecutor(true) in order to execute all gRPC
                       // methods in the blockingTaskExecutor thread pool.
                       // .useBlockingTaskExecutor(true)
                       .build();
    return Server.builder()
                 .http(httpPort)
                 .https(httpsPort)
                 .tlsSelfSigned()
                 .service(grpcService)
                 // You can access the documentation service at http://127.0.0.1:8080/docs.
                 // See https://armeria.dev/docs/server-docservice for more information.
                 .serviceUnder("/docs",
                         DocService.builder()
                                   .exampleRequestForMethod(
                                           HelloServiceGrpc.SERVICE_NAME,
                                           "Hello", exampleRequest)
                                   .exampleRequestForMethod(
                                           HelloServiceGrpc.SERVICE_NAME,
                                           "LazyHello", exampleRequest)
                                   .exampleRequestForMethod(
                                           HelloServiceGrpc.SERVICE_NAME,
                                           "BlockingHello", exampleRequest)
                                   .exclude(DocServiceFilter.ofServiceName(
                                           ServerReflectionGrpc.SERVICE_NAME))
                                   .build())
                 .build();
}
 
Example #12
Source File: Main.java    From armeria with Apache License 2.0 5 votes vote down vote up
static Server newServer(int httpPort, int httpsPort) throws Exception {
    final HelloRequest exampleRequest = HelloRequest.newBuilder().setName("Armeria").build();
    final HttpServiceWithRoutes grpcService =
            GrpcService.builder()
                       .addService(new HelloServiceImpl())
                       // See https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md
                       .addService(ProtoReflectionService.newInstance())
                       .supportedSerializationFormats(GrpcSerializationFormats.values())
                       .enableUnframedRequests(true)
                       // You can set useBlockingTaskExecutor(true) in order to execute all gRPC
                       // methods in the blockingTaskExecutor thread pool.
                       // .useBlockingTaskExecutor(true)
                       .build();
    return Server.builder()
                 .http(httpPort)
                 .https(httpsPort)
                 .tlsSelfSigned()
                 .service(grpcService)
                 // You can access the documentation service at http://127.0.0.1:8080/docs.
                 // See https://armeria.dev/docs/server-docservice for more information.
                 .serviceUnder("/docs",
                         DocService.builder()
                                   .exampleRequestForMethod(HelloServiceGrpc.SERVICE_NAME,
                                              "Hello", exampleRequest)
                                   .exampleRequestForMethod(HelloServiceGrpc.SERVICE_NAME,
                                              "LazyHello", exampleRequest)
                                   .exampleRequestForMethod(HelloServiceGrpc.SERVICE_NAME,
                                              "BlockingHello", exampleRequest)
                                   .exclude(DocServiceFilter.ofServiceName(
                                                ServerReflectionGrpc.SERVICE_NAME))
                                   .build())
                 .build();
}
 
Example #13
Source File: GrpcMessageMarshallerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {

    marshaller = new GrpcMessageMarshaller<>(
            ByteBufAllocator.DEFAULT,
            GrpcSerializationFormats.PROTO,
            TestServiceGrpc.getUnaryCallMethod(),
            DEFAULT_JSON_MARSHALLER,
            false);
}
 
Example #14
Source File: GrpcDocServicePluginTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void newServiceInfo() throws Exception {
    final ServiceInfo service = generator.newServiceInfo(
            new ServiceEntry(
                    TEST_SERVICE_DESCRIPTOR,
                    ImmutableList.of(
                            EndpointInfo.builder("*", "/foo")
                                        .fragment("a").availableFormats(GrpcSerializationFormats.PROTO)
                                        .build(),
                            EndpointInfo.builder("*", "/debug/foo")
                                        .fragment("b").availableFormats(GrpcSerializationFormats.JSON)
                                        .build())),
            (pluginName, serviceName, methodName) -> true);

    final Map<String, MethodInfo> functions = service.methods()
                                                     .stream()
                                                     .collect(toImmutableMap(MethodInfo::name,
                                                                             Function.identity()));
    assertThat(functions).hasSize(8);
    final MethodInfo emptyCall = functions.get("EmptyCall");
    assertThat(emptyCall.name()).isEqualTo("EmptyCall");
    assertThat(emptyCall.parameters())
            .containsExactly(FieldInfo.builder("request",
                                               TypeSignature.ofNamed("armeria.grpc.testing.Empty",
                                                                     Empty.getDescriptor()))
                                      .requirement(FieldRequirement.REQUIRED)
                                      .build());
    assertThat(emptyCall.returnTypeSignature())
            .isEqualTo(TypeSignature.ofNamed("armeria.grpc.testing.Empty", Empty.getDescriptor()));

    // Just sanity check that all methods are present, function conversion is more thoroughly tested in
    // newMethodInfo()
    assertThat(functions.get("UnaryCall").name()).isEqualTo("UnaryCall");
    assertThat(functions.get("UnaryCall2").name()).isEqualTo("UnaryCall2");
    assertThat(functions.get("StreamingOutputCall").name()).isEqualTo("StreamingOutputCall");
    assertThat(functions.get("StreamingInputCall").name()).isEqualTo("StreamingInputCall");
    assertThat(functions.get("FullDuplexCall").name()).isEqualTo("FullDuplexCall");
    assertThat(functions.get("HalfDuplexCall").name()).isEqualTo("HalfDuplexCall");
    assertThat(functions.get("UnimplementedCall").name()).isEqualTo("UnimplementedCall");
}
 
Example #15
Source File: GrpcDocServicePluginTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void newMethodInfo() throws Exception {
    final MethodInfo methodInfo = GrpcDocServicePlugin.newMethodInfo(
            TEST_SERVICE_DESCRIPTOR.findMethodByName("UnaryCall"),
            new ServiceEntry(
                    TEST_SERVICE_DESCRIPTOR,
                    ImmutableList.of(
                            EndpointInfo.builder("*", "/foo/")
                                        .availableFormats(GrpcSerializationFormats.PROTO)
                                        .build(),
                            EndpointInfo.builder("*", "/debug/foo/")
                                        .availableFormats(GrpcSerializationFormats.JSON)
                                        .build())));
    assertThat(methodInfo.name()).isEqualTo("UnaryCall");
    assertThat(methodInfo.returnTypeSignature().name()).isEqualTo("armeria.grpc.testing.SimpleResponse");
    assertThat(methodInfo.returnTypeSignature().namedTypeDescriptor())
            .isEqualTo(SimpleResponse.getDescriptor());
    assertThat(methodInfo.parameters()).hasSize(1);
    assertThat(methodInfo.parameters().get(0).name()).isEqualTo("request");
    assertThat(methodInfo.parameters().get(0).typeSignature().name())
            .isEqualTo("armeria.grpc.testing.SimpleRequest");
    assertThat(methodInfo.parameters().get(0).typeSignature().namedTypeDescriptor())
            .isEqualTo(SimpleRequest.getDescriptor());
    assertThat(methodInfo.exceptionTypeSignatures()).isEmpty();
    assertThat(methodInfo.docString()).isNull();
    assertThat(methodInfo.endpoints()).containsExactlyInAnyOrder(
            EndpointInfo.builder("*", "/foo/UnaryCall")
                        .availableFormats(GrpcSerializationFormats.PROTO)
                        .build(),
            EndpointInfo.builder("*", "/debug/foo/UnaryCall")
                        .availableFormats(GrpcSerializationFormats.JSON)
                        .build());
}
 
Example #16
Source File: GrpcDocServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    if (TestUtil.isDocServiceDemoMode()) {
        sb.http(8080);
    }
    sb.serviceUnder("/test",
                    GrpcService.builder()
                               .addService(new TestService())
                               .supportedSerializationFormats(GrpcSerializationFormats.values())
                               .enableUnframedRequests(true)
                               .build());
    sb.serviceUnder("/docs/",
                    DocService.builder()
                              .exampleRequestForMethod(
                                    TestServiceGrpc.SERVICE_NAME,
                                    "UnaryCall",
                                    SimpleRequest.newBuilder()
                                                 .setPayload(
                                                     Payload.newBuilder()
                                                            .setBody(ByteString.copyFromUtf8("world")))
                                                 .build())
                              .injectedScript(INJECTED_HEADER_PROVIDER1, INJECTED_HEADER_PROVIDER2)
                              .injectedScriptSupplier((ctx, req) -> INJECTED_HEADER_PROVIDER3)
                              .exclude(DocServiceFilter.ofMethodName(
                                                TestServiceGrpc.SERVICE_NAME,
                                                "EmptyCall"))
                              .build()
                              .decorate(LoggingService.newDecorator()));
    sb.serviceUnder("/excludeAll/",
                    DocService.builder()
                              .exclude(DocServiceFilter.ofGrpc())
                              .build());
    sb.serviceUnder("/",
                    GrpcService.builder()
                               .addService(mock(ReconnectServiceImplBase.class))
                               .build());
}
 
Example #17
Source File: UnframedGrpcServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static UnframedGrpcService buildUnframedGrpcService(BindableService bindableService) {
    return (UnframedGrpcService) GrpcService.builder()
                                            .addService(bindableService)
                                            .setMaxInboundMessageSizeBytes(MAX_MESSAGE_BYTES)
                                            .setMaxOutboundMessageSizeBytes(MAX_MESSAGE_BYTES)
                                            .supportedSerializationFormats(
                                                    GrpcSerializationFormats.values())
                                            .enableUnframedRequests(true)
                                            .build();
}
 
Example #18
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void json_preservingFieldNames() throws Exception {
    final AtomicReference<HttpHeaders> requestHeaders = new AtomicReference<>();
    final AtomicReference<byte[]> payload = new AtomicReference<>();
    final Function<ServiceDescriptor, GrpcJsonMarshaller> marshallerFactory = serviceDescriptor -> {
        return GrpcJsonMarshaller.builder()
                                 .jsonMarshallerCustomizer(marshaller -> {
                                     marshaller.preservingProtoFieldNames(true);
                                 })
                                 .build(serviceDescriptor);
    };
    final UnitTestServiceBlockingStub jsonStub =
            Clients.builder(server.httpUri(GrpcSerializationFormats.JSON) + "/json-preserving/")
                   .option(GrpcClientOptions.GRPC_JSON_MARSHALLER_FACTORY.newValue(marshallerFactory))
                   .decorator(client -> new SimpleDecoratingHttpClient(client) {
                       @Override
                       public HttpResponse execute(ClientRequestContext ctx, HttpRequest req)
                               throws Exception {
                           requestHeaders.set(req.headers());
                           return new FilteredHttpResponse(unwrap().execute(ctx, req)) {
                               @Override
                               protected HttpObject filter(HttpObject obj) {
                                   if (obj instanceof HttpData) {
                                       payload.set(((HttpData) obj).array());
                                   }
                                   return obj;
                               }
                           };
                       }
                   })
                   .build(UnitTestServiceBlockingStub.class);
    final SimpleResponse response = jsonStub.staticUnaryCall(REQUEST_MESSAGE);
    assertThat(response).isEqualTo(RESPONSE_MESSAGE);
    assertThat(requestHeaders.get().get(HttpHeaderNames.CONTENT_TYPE)).isEqualTo(
            "application/grpc+json");

    final byte[] deframed = Arrays.copyOfRange(payload.get(), 5, payload.get().length);
    assertThat(new String(deframed, StandardCharsets.UTF_8)).contains("oauth_scope");
}
 
Example #19
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void json() throws Exception {
    final AtomicReference<HttpHeaders> requestHeaders = new AtomicReference<>();
    final AtomicReference<byte[]> payload = new AtomicReference<>();
    final UnitTestServiceBlockingStub jsonStub =
            Clients.builder(server.httpUri(GrpcSerializationFormats.JSON))
                   .decorator(client -> new SimpleDecoratingHttpClient(client) {
                       @Override
                       public HttpResponse execute(ClientRequestContext ctx, HttpRequest req)
                               throws Exception {
                           requestHeaders.set(req.headers());
                           return new FilteredHttpResponse(unwrap().execute(ctx, req)) {
                               @Override
                               protected HttpObject filter(HttpObject obj) {
                                   if (obj instanceof HttpData) {
                                       payload.set(((HttpData) obj).array());
                                   }
                                   return obj;
                               }
                           };
                       }
                   })
                   .build(UnitTestServiceBlockingStub.class);
    final SimpleResponse response = jsonStub.staticUnaryCall(REQUEST_MESSAGE);
    assertThat(response).isEqualTo(RESPONSE_MESSAGE);
    assertThat(requestHeaders.get().get(HttpHeaderNames.CONTENT_TYPE)).isEqualTo(
            "application/grpc+json");

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.method()).isEqualTo("armeria.grpc.testing.UnitTestService/StaticUnaryCall");
        assertThat(rpcReq.params()).containsExactly(REQUEST_MESSAGE);
        assertThat(rpcRes.get()).isEqualTo(RESPONSE_MESSAGE);
    });

    final byte[] deframed = Arrays.copyOfRange(payload.get(), 5, payload.get().length);
    assertThat(new String(deframed, StandardCharsets.UTF_8)).contains("oauthScope");
}
 
Example #20
Source File: GrpcServiceBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the {@link SerializationFormat}s supported by this server. If not set, defaults to supporting binary
 * protobuf formats. JSON formats are currently very inefficient and not recommended for use in production.
 *
 * <p>TODO(anuraaga): Use faster JSON marshalling.
 */
public GrpcServiceBuilder supportedSerializationFormats(Iterable<SerializationFormat> formats) {
    requireNonNull(formats, "formats");
    for (SerializationFormat format : formats) {
        if (!GrpcSerializationFormats.isGrpc(format)) {
            throw new IllegalArgumentException("Not a gRPC serialization format: " + format);
        }
    }
    supportedSerializationFormats = ImmutableSet.copyOf(formats);
    return this;
}
 
Example #21
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void ignoreClientTimeout() {
    final UnitTestServiceBlockingStub client =
            Clients.builder(server.httpUri(GrpcSerializationFormats.PROTO) + "/no-client-timeout/")
                   .build(UnitTestServiceBlockingStub.class)
                   .withDeadlineAfter(10, TimeUnit.SECONDS);
    assertThatThrownBy(() -> client.timesOut(
            SimpleRequest.getDefaultInstance())).isInstanceOfSatisfying(
            StatusRuntimeException.class, t ->
                    assertThat(t.getStatus().getCode()).isEqualTo(Code.CANCELLED));
}
 
Example #22
Source File: ArmeriaServerCall.java    From armeria with Apache License 2.0 5 votes vote down vote up
private void doClose(Status status, Metadata metadata) {
    checkState(!closeCalled, "call already closed");

    closeCalled = true;
    if (cancelled) {
        // No need to write anything to client if cancelled already.
        closeListener(status);
        return;
    }

    final HttpHeaders trailers = statusToTrailers(ctx, status, metadata, sendHeadersCalled);
    final HttpObject trailersObj;
    if (sendHeadersCalled && GrpcSerializationFormats.isGrpcWeb(serializationFormat)) {
        // Normal trailers are not supported in grpc-web and must be encoded as a message.
        // Message compression is not supported in grpc-web, so we don't bother using the normal
        // ArmeriaMessageFramer.
        trailersObj = serializeTrailersAsMessage(trailers);
    } else {
        trailersObj = trailers;
    }
    try {
        if (res.tryWrite(trailersObj)) {
            res.close();
        }
    } finally {
        closeListener(status);
    }
}
 
Example #23
Source File: ArmeriaGrpcServer.java    From grpc-by-example-java with Apache License 2.0 5 votes vote down vote up
static Server newServer(int httpPort, int httpsPort) throws Exception {
    final HelloRequest exampleRequest = HelloRequest.newBuilder().setName("Armeria").build();
    final HttpServiceWithRoutes grpcService =
            GrpcService.builder()
                       .addService(new HelloServiceImpl())
                       // See https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md
                       .addService(ProtoReflectionService.newInstance())
                       .supportedSerializationFormats(GrpcSerializationFormats.values())
                       .enableUnframedRequests(true)
                       // You can set useBlockingTaskExecutor(true) in order to execute all gRPC
                       // methods in the blockingTaskExecutor thread pool.
                       // .useBlockingTaskExecutor(true)
                       .build();

    return Server.builder()
                 .http(httpPort)
                 .https(httpsPort)
                 .tlsSelfSigned()
                 .service(grpcService)
                 // You can access the documentation service at http://127.0.0.1:8080/docs.
                 // See https://line.github.io/armeria/server-docservice.html for more information.
                 .serviceUnder("/docs", DocService.builder()
                                                  .exampleRequestForMethod(HelloServiceGrpc.SERVICE_NAME,
                                                                           "Hello", exampleRequest)
                                                  .exampleRequestForMethod(HelloServiceGrpc.SERVICE_NAME,
                                                                           "LazyHello", exampleRequest)
                                                  .exampleRequestForMethod(HelloServiceGrpc.SERVICE_NAME,
                                                                           "BlockingHello", exampleRequest)
                                                  .exclude(DocServiceFilter.ofServiceName(
                                                          ServerReflectionGrpc.SERVICE_NAME))
                                                  .build())
                 .build();
}
 
Example #24
Source File: ArmeriaServerCallTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    completionFuture = new CompletableFuture<>();
    when(res.whenComplete()).thenReturn(completionFuture);

    ctx = ServiceRequestContext.builder(HttpRequest.of(HttpMethod.POST, "/"))
                               .eventLoop(eventLoop.get())
                               .build();

    call = new ArmeriaServerCall<>(
            HttpHeaders.of(),
            TestServiceGrpc.getUnaryCallMethod(),
            CompressorRegistry.getDefaultInstance(),
            DecompressorRegistry.getDefaultInstance(),
            res,
            MAX_MESSAGE_BYTES,
            MAX_MESSAGE_BYTES,
            ctx,
            GrpcSerializationFormats.PROTO,
            new DefaultJsonMarshaller(MessageMarshaller.builder().build()),
            false,
            false,
            ResponseHeaders.builder(HttpStatus.OK)
                           .contentType(GrpcSerializationFormats.PROTO.mediaType())
                           .build());
    call.setListener(listener);
    call.messageReader().onSubscribe(subscription);

    ctx.setAttr(GrpcUnsafeBufferUtil.BUFFERS, buffersAttr);
}
 
Example #25
Source File: GrpcServiceLogNameTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void logNameInAccessLog() {
    final TestServiceBlockingStub client = Clients.builder(server.httpUri(GrpcSerializationFormats.PROTO))
                                                  .build(TestServiceBlockingStub.class);
    client.emptyCall(Empty.newBuilder().build());

    await().untilAsserted(() -> {
        verify(appender, atLeast(0)).doAppend(eventCaptor.capture());
        assertThat(eventCaptor.getAllValues()).anyMatch(evt -> {
            return evt.getMessage().contains("POST /armeria.grpc.testing.TestService/EmptyCall h2c");
        });
    });
}
 
Example #26
Source File: GrpcServiceLogNameTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void logName() {
    final TestServiceBlockingStub client = Clients.builder(server.httpUri(GrpcSerializationFormats.PROTO))
                                                  .build(TestServiceBlockingStub.class);
    client.emptyCall(Empty.newBuilder().build());

    final RequestLog log = capturedCtx.log().partial();
    assertThat(log.serviceName()).isEqualTo(TestServiceGrpc.SERVICE_NAME);
    assertThat(log.name()).isEqualTo("EmptyCall");
    assertThat(log.fullName()).isEqualTo(TestServiceGrpc.getEmptyCallMethod().getFullMethodName());
}
 
Example #27
Source File: AbstractUnaryGrpcServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void normal_downstream() {
    final TestServiceBlockingStub stub =
            Clients.newClient(server.httpUri(GrpcSerializationFormats.PROTO),
                              TestServiceBlockingStub.class);
    assertThat(stub.unaryCall(SimpleRequest.newBuilder()
                                           .setPayload(Payload.newBuilder()
                                                              .setBody(
                                                                      ByteString.copyFromUtf8("hello"))
                                                              .build())
                                           .build()).getPayload().getBody().toStringUtf8())
            .isEqualTo("hello");
}
 
Example #28
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void emptyUnary_grpcWeb() throws Exception {
    final TestServiceBlockingStub stub =
            Clients.newClient(server.httpUri(GrpcSerializationFormats.PROTO_WEB),
                              TestServiceBlockingStub.class);
    assertThat(stub.emptyCall(EMPTY)).isEqualTo(EMPTY);
}
 
Example #29
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.workerGroup(EventLoopGroups.newEventLoopGroup(1), true);
    sb.maxRequestLength(0);

    sb.service(
            GrpcService.builder()
                       .setMaxInboundMessageSizeBytes(MAX_MESSAGE_SIZE)
                       .addService(ServerInterceptors.intercept(
                               new UnitTestServiceImpl(),
                               REPLACE_EXCEPTION, ADD_TO_CONTEXT))
                       .enableUnframedRequests(true)
                       .supportedSerializationFormats(GrpcSerializationFormats.values())
                       .build(),
            service -> service
                    .decorate(LoggingService.newDecorator())
                    .decorate((delegate, ctx, req) -> {
                        ctx.log().whenComplete().thenAccept(requestLogQueue::add);
                        return delegate.serve(ctx, req);
                    }));

    // For simplicity, mount onto subpaths with custom options
    sb.serviceUnder(
            "/json-preserving/",
            GrpcService.builder()
                       .addService(new UnitTestServiceImpl())
                       .supportedSerializationFormats(GrpcSerializationFormats.values())
                       .jsonMarshallerFactory(serviceDescriptor -> {
                           return GrpcJsonMarshaller.builder()
                                                    .jsonMarshallerCustomizer(marshaller -> {
                                                        marshaller.preservingProtoFieldNames(true);
                                                    })
                                                    .build(serviceDescriptor);
                       })
                       .build());
    sb.serviceUnder(
            "/no-client-timeout/",
            GrpcService.builder()
                       .addService(new UnitTestServiceImpl())
                       .useClientTimeoutHeader(false)
                       .build());

    sb.service(
            GrpcService.builder()
                       .addService(ProtoReflectionService.newInstance())
                       .build(),
            service -> service.decorate(LoggingService.newDecorator()));
}
 
Example #30
Source File: GrpcDocServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
public void testOk() throws Exception {
    if (TestUtil.isDocServiceDemoMode()) {
        Thread.sleep(Long.MAX_VALUE);
    }
    final List<ServiceEntry> entries = ImmutableList.of(
            new ServiceEntry(TEST_SERVICE_DESCRIPTOR, ImmutableList.of(
                    EndpointInfo.builder("*", "/test/armeria.grpc.testing.TestService/")
                                .availableMimeTypes(GrpcSerializationFormats.PROTO.mediaType(),
                                                    GrpcSerializationFormats.JSON.mediaType(),
                                                    GrpcSerializationFormats.PROTO_WEB.mediaType(),
                                                    GrpcSerializationFormats.JSON_WEB.mediaType(),
                                                    MediaType.PROTOBUF.withParameter("protocol", "gRPC"),
                                                    MediaType.JSON_UTF_8.withParameter("protocol", "gRPC"))
                                .build())),
            new ServiceEntry(RECONNECT_SERVICE_DESCRIPTOR, ImmutableList.of(
                    EndpointInfo.builder("*", "/armeria.grpc.testing.ReconnectService/")
                                .availableFormats(GrpcSerializationFormats.PROTO,
                                                  GrpcSerializationFormats.PROTO_WEB)
                                .build())));
    final JsonNode expectedJson = mapper.valueToTree(new GrpcDocServicePlugin().generate(
            entries, unifyFilter((plugin, service, method) -> true,
                                 DocServiceFilter.ofMethodName(TestServiceGrpc.SERVICE_NAME,
                                                               "EmptyCall"))));

    // The specification generated by GrpcDocServicePlugin does not include the examples specified
    // when building a DocService, so we add them manually here.
    addExamples(expectedJson);

    final WebClient client = WebClient.of(server.httpUri());
    final AggregatedHttpResponse res = client.get("/docs/specification.json").aggregate().join();
    assertThat(res.status()).isSameAs(HttpStatus.OK);

    final JsonNode actualJson = mapper.readTree(res.contentUtf8());

    // The specification generated by ThriftDocServicePlugin does not include the docstrings
    // because it's injected by the DocService, so we remove them here for easier comparison.
    removeDocStrings(actualJson);
    assertThatJson(actualJson).isEqualTo(expectedJson);

    final AggregatedHttpResponse injected = client.get("/docs/injected.js").aggregate().join();

    assertThat(injected.status()).isSameAs(HttpStatus.OK);
    assertThat(injected.contentUtf8()).isEqualTo(INJECTED_HEADER_PROVIDER1 + '\n' +
                                                 INJECTED_HEADER_PROVIDER2 + '\n' +
                                                 INJECTED_HEADER_PROVIDER3);
}