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
@@ -1,5 +1,5 @@
/*
* Copyright 2020 LINE Corporation
* Copyright 2022 LINE Corporation
Copy link
Member

Choose a reason for hiding this comment

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

revert?

*
* 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
Expand Down Expand Up @@ -39,19 +39,62 @@ 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);
return ofJackson(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 builderForJackson();
}

/**
* Returns a newly-created {@link GrpcJsonMarshaller} which serializes and deserializes a {@link Message}
* 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 ofJackson(ServiceDescriptor serviceDescriptor) {
jrhee17 marked this conversation as resolved.
Show resolved Hide resolved
return builderForJackson().build(serviceDescriptor);
}

/**
* 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 builderForJackson() {
return new GrpcJsonMarshallerBuilder();
}

/**
* Returns a newly-created {@link GrpcJsonMarshaller} which serializes and deserializes {@link Message}.
Copy link
Collaborator

Choose a reason for hiding this comment

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

Should add notes that the performance is much lower and should only be used if the default has problems, for example enum values in proto2 files. In practical terms, ofGson is not fast enough for production workloads - actually I don't know if having these factories solves the user's reported issue since it still requires configuration, as opposed to configuring the serialization formats. AFAICT, the user didn't need JSON, but they were having issues because the default serialization formats includes it. Requiring a different option may not actually help them.

Copy link
Contributor Author

@jrhee17 jrhee17 Jan 19, 2022

Choose a reason for hiding this comment

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

Should add notes that the performance is much lower

Thanks for looking though this PR! Left an additional note in the javadocs that addresses this.

AFAICT, the user didn't need JSON, but they were having issues because the default serialization formats includes it.

I still think this PR has meaning in that users who are committed to using armeria still have an option to use the upstream marshaller implementation if they'd like.

Having said this, if we want to avoid breaking changes and avoid user-side extra configuration, I guess the other option we have is to just swallow the exception and warn when building a MessageMarshaller fails. Let me also consider this.

* 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.
*/
static GrpcJsonMarshaller ofGson() {
return builderForGson().build();
}

/**
* Returns a new {@link GrpcJsonMarshallerBuilder}.
* 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.
*/
static GsonGrpcJsonMarshallerBuilder builderForGson() {
return new GsonGrpcJsonMarshallerBuilder();
}

/**
* Serializes a gRPC message into JSON.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import java.util.function.Consumer;

import org.curioswitch.common.protobuf.json.MessageMarshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.protobuf.Message;

Expand All @@ -34,6 +36,8 @@
*/
final class GrpcJsonUtil {

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

/**
* Returns a {@link MessageMarshaller} with the request/response {@link Message}s of all the {@code methods}
* registered.
Expand All @@ -59,7 +63,13 @@ public static MessageMarshaller jsonMarshaller(
jsonMarshallerCustomizer.accept(builder);
}

return builder.build();
try {
return builder.build();
} catch (RuntimeException e) {
logger.warn("Failed to instantiate a json marshaller for {}." +
" Consider using GrpcJsonMarshaller.ofGson instead.", methods);
jrhee17 marked this conversation as resolved.
Show resolved Hide resolved
throw e;
}
}

@Nullable
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);
}
}
Loading