Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce GsonGrpcJsonMarshaller and catch JsonMarshaller initialization failure #4033

Merged
merged 14 commits into from
Jan 25, 2022
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,54 @@ public interface GrpcJsonMarshaller {

/**
* Returns a newly-created {@link GrpcJsonMarshaller} which serializes and deserializes a {@link Message}
* served by the {@linkplain ServiceDescriptor service}.
* served by the {@linkplain ServiceDescriptor service}. This implementation internally uses
* <a href="https://github.com/curioswitch/protobuf-jackson">protobuf-jackson</a>
* to serialize and deserialize messages.
*/
static GrpcJsonMarshaller of(ServiceDescriptor serviceDescriptor) {
return builder().build(serviceDescriptor);
}

/**
* Returns a new {@link GrpcJsonMarshallerBuilder}.
* Returns a new {@link GrpcJsonMarshallerBuilder}. This implementation internally uses
* <a href="https://github.com/curioswitch/protobuf-jackson">protobuf-jackson</a>
* to serialize and deserialize messages.
*/
static GrpcJsonMarshallerBuilder builder() {
return new GrpcJsonMarshallerBuilder();
}

/**
* Returns a newly-created {@link GrpcJsonMarshaller} which serializes and deserializes a {@link Message}.
* This implementation internally uses
* <a href="https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/util/JsonFormat">JsonFormat</a>
* and {@code Gson} to serialize and deserialize messages.
* Note:
* <a href="https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/util/JsonFormat">JsonFormat</a>
* has a known <a href="https://github.com/curioswitch/protobuf-jackson#benchmarks">performance issue</a>.
* Use this method only when
* 1) you're using Protobuf 2 or 2) you have an issue with
* <a href="https://github.com/curioswitch/protobuf-jackson">protobuf-jackson</a>.
*/
static GrpcJsonMarshaller ofGson() {
return builderForGson().build();
}

/**
* Returns a new {@link GsonGrpcJsonMarshallerBuilder}. This implementation internally uses
* <a href="https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/util/JsonFormat">JsonFormat</a>
* and {@code Gson} to serialize and deserialize messages.
* Note:
* <a href="https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/util/JsonFormat">JsonFormat</a>
* has a known <a href="https://github.com/curioswitch/protobuf-jackson#benchmarks">performance issue</a>.
* Use this method only when
* 1) you're using Protobuf 2 or 2) you have an issue with
* <a href="https://github.com/curioswitch/protobuf-jackson">protobuf-jackson</a>.
*/
static GsonGrpcJsonMarshallerBuilder builderForGson() {
return new GsonGrpcJsonMarshallerBuilder();
}

/**
* Serializes a gRPC message into JSON.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Copyright 2022 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package com.linecorp.armeria.common.grpc;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;

import io.grpc.MethodDescriptor.Marshaller;
import io.grpc.MethodDescriptor.PrototypeMarshaller;

final class GsonGrpcJsonMarshaller implements GrpcJsonMarshaller {

final JsonFormat.Printer printer;
final JsonFormat.Parser parser;

GsonGrpcJsonMarshaller(JsonFormat.Printer printer, JsonFormat.Parser parser) {
this.printer = printer;
this.parser = parser;
}

@Override
public <T> void serializeMessage(Marshaller<T> marshaller, T message, OutputStream os) throws IOException {
os.write(printer.print((MessageOrBuilder) message).getBytes(StandardCharsets.UTF_8));
}

@Override
public <T> T deserializeMessage(Marshaller<T> marshaller, InputStream is) throws IOException {
final PrototypeMarshaller<T> prototypeMarshaller = (PrototypeMarshaller<T>) marshaller;
final Message prototype = (Message) prototypeMarshaller.getMessagePrototype();
assert prototype != null;
final Message.Builder builder = prototype.newBuilderForType();
parser.merge(new InputStreamReader(is, StandardCharsets.UTF_8), builder);
@SuppressWarnings("unchecked")
final T cast = (T) builder.build();
return cast;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* Copyright 2020 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package com.linecorp.armeria.common.grpc;

import static java.util.Objects.requireNonNull;

import java.util.function.Consumer;

import com.google.protobuf.Message;
import com.google.protobuf.util.JsonFormat;

import com.linecorp.armeria.common.annotation.Nullable;

/**
* A builder for creating a new {@link GrpcJsonMarshaller} that serializes and deserializes a {@link Message}
* to and from JSON.
*/
public final class GsonGrpcJsonMarshallerBuilder {

@Nullable
private Consumer<JsonFormat.Parser> jsonParserCustomizer;

@Nullable
private Consumer<JsonFormat.Printer> jsonPrinterCustomizer;

GsonGrpcJsonMarshallerBuilder() {}

/**
* Adds a {@link Consumer} that can customize the {@link JsonFormat.Parser}
* used when deserializing a JSON payload into a {@link Message}.
*/
public GsonGrpcJsonMarshallerBuilder jsonParserCustomizer(
Consumer<? super JsonFormat.Parser> jsonParserCustomizer) {
requireNonNull(jsonParserCustomizer, "jsonParserCustomizer");
if (this.jsonParserCustomizer == null) {
@SuppressWarnings("unchecked")
final Consumer<JsonFormat.Parser> cast = (Consumer<JsonFormat.Parser>) jsonParserCustomizer;
this.jsonParserCustomizer = cast;
} else {
this.jsonParserCustomizer = this.jsonParserCustomizer.andThen(jsonParserCustomizer);
}
return this;
}

/**
* Adds a {@link Consumer} that can customize the {@link JsonFormat.Printer}
* used when serializing a {@link Message} into a JSON payload.
*/
public GsonGrpcJsonMarshallerBuilder jsonPrinterCustomizer(
Consumer<? super JsonFormat.Printer> jsonPrinterCustomizer) {
requireNonNull(jsonPrinterCustomizer, "jsonPrinterCustomizer");
if (this.jsonPrinterCustomizer == null) {
@SuppressWarnings("unchecked")
final Consumer<JsonFormat.Printer> cast = (Consumer<JsonFormat.Printer>) jsonPrinterCustomizer;
this.jsonPrinterCustomizer = cast;
} else {
this.jsonPrinterCustomizer = this.jsonPrinterCustomizer.andThen(jsonPrinterCustomizer);
}
return this;
}

/**
* Returns a newly-created {@link GrpcJsonMarshaller}.
*/
public GrpcJsonMarshaller build() {
final JsonFormat.Printer printer = JsonFormat.printer().omittingInsignificantWhitespace();
if (jsonPrinterCustomizer != null) {
jsonPrinterCustomizer.accept(printer);
}

final JsonFormat.Parser parser = JsonFormat.parser().ignoringUnknownFields();
if (jsonParserCustomizer != null) {
jsonParserCustomizer.accept(parser);
}
return new GsonGrpcJsonMarshaller(printer, parser);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
import java.util.Set;
import java.util.function.Function;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;

Expand All @@ -39,6 +42,7 @@
import com.linecorp.armeria.client.ClientOptionsBuilder;
import com.linecorp.armeria.client.DecoratingClientFactory;
import com.linecorp.armeria.client.HttpClient;
import com.linecorp.armeria.client.grpc.GrpcClientBuilder;
import com.linecorp.armeria.client.grpc.GrpcClientOptions;
import com.linecorp.armeria.client.grpc.GrpcClientStubFactory;
import com.linecorp.armeria.client.grpc.protocol.UnaryGrpcClient;
Expand All @@ -62,6 +66,8 @@
*/
final class GrpcClientFactory extends DecoratingClientFactory {

private static final Logger logger = LoggerFactory.getLogger(GrpcClientFactory.class);

private static final Set<Scheme> SUPPORTED_SCHEMES =
Arrays.stream(SessionProtocol.values())
.flatMap(p -> GrpcSerializationFormats.values()
Expand Down Expand Up @@ -130,8 +136,16 @@ public Object newClient(ClientBuilderParams params) {

final GrpcJsonMarshaller jsonMarshaller;
if (GrpcSerializationFormats.isJson(serializationFormat)) {
jsonMarshaller = options.get(GrpcClientOptions.GRPC_JSON_MARSHALLER_FACTORY)
.apply(serviceDescriptor);
try {
jsonMarshaller = options.get(GrpcClientOptions.GRPC_JSON_MARSHALLER_FACTORY)
.apply(serviceDescriptor);
} catch (RuntimeException e) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about catching Exception like FramedGrpcService?

logger.warn("Failed to instantiate a JSON marshaller for gRPC-JSON. " +
"Consider using a different serialization format with {}.serializationFormat() " +
"or using {}.ofGson() instead.",
GrpcClientBuilder.class.getName(), GrpcJsonMarshaller.class.getName(), e);
throw e;
}
} else {
jsonMarshaller = null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,28 @@ final class FramedGrpcService extends AbstractHttpService implements GrpcService
static final AttributeKey<ServerMethodDefinition<?, ?>> RESOLVED_GRPC_METHOD =
AttributeKey.valueOf(FramedGrpcService.class, "RESOLVED_GRPC_METHOD");

private static Map<String, GrpcJsonMarshaller> getJsonMarshallers(
HandlerRegistry registry,
Set<SerializationFormat> supportedSerializationFormats,
Function<? super ServiceDescriptor, ? extends GrpcJsonMarshaller> jsonMarshallerFactory) {
if (supportedSerializationFormats.stream().noneMatch(GrpcSerializationFormats::isJson)) {
return ImmutableMap.of();
} else {
try {
return registry.services().stream()
.map(ServerServiceDefinition::getServiceDescriptor)
.distinct()
.collect(toImmutableMap(ServiceDescriptor::getName, jsonMarshallerFactory));
} catch (Exception e) {
logger.warn("Failed to instantiate a JSON marshaller. Consider disabling gRPC-JSON " +
"serialization with {}.supportedSerializationFormats() " +
"or using {}.ofGson() instead.",
GrpcServiceBuilder.class.getName(), GrpcJsonMarshaller.class.getName(), e);
return ImmutableMap.of();
}
}
}

private final HandlerRegistry registry;
private final Set<Route> routes;
private final DecompressorRegistry decompressorRegistry;
Expand Down Expand Up @@ -124,15 +146,7 @@ final class FramedGrpcService extends AbstractHttpService implements GrpcService
this.compressorRegistry = requireNonNull(compressorRegistry, "compressorRegistry");
this.supportedSerializationFormats = supportedSerializationFormats;
this.useClientTimeoutHeader = useClientTimeoutHeader;
if (supportedSerializationFormats.stream().noneMatch(GrpcSerializationFormats::isJson)) {
jsonMarshallers = ImmutableMap.of();
} else {
jsonMarshallers =
registry.services().stream()
.map(ServerServiceDefinition::getServiceDescriptor)
.distinct()
.collect(toImmutableMap(ServiceDescriptor::getName, jsonMarshallerFactory));
}
jsonMarshallers = getJsonMarshallers(registry, supportedSerializationFormats, jsonMarshallerFactory);
this.protoReflectionServiceInterceptor = protoReflectionServiceInterceptor;
this.statusFunction = statusFunction;
this.maxRequestMessageLength = maxRequestMessageLength;
Expand Down
Loading