protobuf icon indicating copy to clipboard operation
protobuf copied to clipboard

Allow deferred JSON-decoding of unknown google.protobuf.Any messages

Open creachadair opened this issue 8 years ago • 37 comments

Abstract

When a JSON object representing a proto3 message is decoded, the generated API for many (most?) languages yields an error when decoding a JSON-encoded google.protobuf.Any field whose generated code is not linked in to the program doing the decoding. This is problematic, because an unexpected type for an Any field breaks forward-compatibility in JSON encoding, even though it is fine in wire encoding. I propose herewith a modest extension to the rules for decoding google.protobuf.Any, that could allow generated code to defer JSON decoding of unknown extensions.

Background

The value field of the google.protobuf.Any encodes the wire format of the message. For the JSON decoder, this means the message schema specified by the type_url field must be available to decode the JSON value. Most (maybe all) existing per-language JSON decoders will fail with an error if the indicated message schema is not linked. This makes it difficult to use Any messages as an extension point with JSON encoding: If a message arrives with a hitherto-unknown Any URL attached anywhere, the decoder fails and the message is unusable.

Proposal

To address the issue described above, I propose that a JSON decoder be allowed to defer decoding of unknown message fields, in the following wise:

  1. Introduce a new well-known message type, google.protobuf.RawAny (name for discussion purposes) with the following structure:

    message RawAny {
       string type_url = 1;  // the type URL of the un-decoded JSON.
       string json = 2;      // the raw JSON (encoded as required, UTF-8).
    }
    
  2. When a JSON decoder encounters the encoding of a google.protobuf.Any message whose structure is unknown, it MAY populate the corresponding field with a google.protobuf.Any with the wire-encoding of a google.protobuf.RawAny message carrying the un-decoded JSON.

For example, suppose the decoder receives a JSON-encoded Any value like:

{"@type":"type.googleapis.com/some.unknown.Message","x":"value","y":23}

This would be encoded as the following RawAny message:

type_url: "type.googleapis.com/some.unknown.Message"
json: "{\"@type\":\"type.googleapis.com/some.unknown.Message\",\"x\":\"value\",\"y\":23}"

which in turn becomes an Any message similar to:

type_url: "type.googleapis.com/google.protobuf.RawAny"
value: "\x28\x0a\x79\x74\x65\x70\x67\x2e\x6f\x6f\x6c\x67\x61\x65\x69\x70\x2e\x73\x6f\x63\x2f\x6d\x6f\x73\x65\x6d\x75\x2e\x6b\x6e\x6f\x6e\x6e\x77\x4d\x2e\x73\x65\x61\x73\x65\x67\x47\x12\x22\x7b\x74\x40\x70\x79\x22\x65\x22\x3a\x79\x74\x65\x70\x67\x2e\x6f\x6f\x6c\x67\x61\x65\x69\x70\x2e\x73\x6f\x63\x2f\x6d\x6f\x73\x65\x6d\x75\x2e\x6b\x6e\x6f\x6e\x6e\x77\x4d\x2e\x73\x65\x61\x73\x65\x67\x2c\x22\x78\x22\x3a\x22\x76\x22\x6c\x61\x65\x75\x2c\x22\x79\x22\x3a\x22\x33\x32\x00\x7d"

where the value is the wire encoding of the RawAny message.

Discussion

  • Deferred decoding does not eliminate the need for the message schema: It will still be needed to re-encode the message to wire format, for example.

  • This proposal aims for minimality: It does not require changes to protoc. It requires one small new well-known message type (the one described as google.protobuf.RawAny above), and some documentation about its intended use for language-API authors.

  • Per-language JSON decoding libraries could be updated incrementally: Existing decoders will continue to work as they do now, producing an error for unlinked messages.

    • If the new behaviour is added unconditionally, the only user-visible change is that some decodings that previously failed will now succeed.
    • If the new behaviour is added optionally (default off), there should be no user-visible changes until the caller explicitly requests the new behaviour.

Context: This request arose from https://github.com/golang/protobuf/issues/723. It affects the Kythe project, which makes use of JSON-encoded proto messages in multiple contexts where Any extensions are needed.

creachadair avatar Oct 05 '18 03:10 creachadair

What language are you using? In many languages, we support ignore unknown option in many languages.

TeBoring avatar Oct 07 '18 19:10 TeBoring

Or are you talking about type url cannot be resolved?

TeBoring avatar Oct 07 '18 19:10 TeBoring

[W]e support ignore unknown option in many languages. Or are you talking about type url cannot be resolved?

I'm referring specifically to instances of the google.protobuf.Any message whose type URL cannot be resolved. "Ordinary" unknown fields (e.g., fields with unknown field numbers) seem to work fine in the languages I've tried.

creachadair avatar Oct 08 '18 03:10 creachadair

Is json a requirement in your case? Can you use binary format? On Sun, Oct 7, 2018 at 20:51 M. J. Fromberger [email protected] wrote:

[W]e support ignore unknown option in many languages. Or are you talking about type url cannot be resolved?

I'm referring specifically to instances of the google.protobuf.Any message whose type URL cannot be resolved. "Ordinary" unknown fields (e.g., fields with unknown field numbers) seem to work fine in the languages I've tried.

— You are receiving this because you were assigned.

Reply to this email directly, view it on GitHub https://github.com/protocolbuffers/protobuf/issues/5226#issuecomment-427716047, or mute the thread https://github.com/notifications/unsubscribe-auth/AE9H5dDphSkB7TcxKGi-dkS8-mOW1phDks5uisvagaJpZM4XJfDL .

TeBoring avatar Oct 08 '18 04:10 TeBoring

And if we simply drop the un-parsable Any wrapped value, does it work for your case? On Sun, Oct 7, 2018 at 21:15 Paul Yang [email protected] wrote:

Is json a requirement in your case? Can you use binary format? On Sun, Oct 7, 2018 at 20:51 M. J. Fromberger [email protected] wrote:

[W]e support ignore unknown option in many languages. Or are you talking about type url cannot be resolved?

I'm referring specifically to instances of the google.protobuf.Any message whose type URL cannot be resolved. "Ordinary" unknown fields (e.g., fields with unknown field numbers) seem to work fine in the languages I've tried.

— You are receiving this because you were assigned.

Reply to this email directly, view it on GitHub https://github.com/protocolbuffers/protobuf/issues/5226#issuecomment-427716047, or mute the thread https://github.com/notifications/unsubscribe-auth/AE9H5dDphSkB7TcxKGi-dkS8-mOW1phDks5uisvagaJpZM4XJfDL .

TeBoring avatar Oct 08 '18 04:10 TeBoring

Is json a requirement in your case? Can you use binary format?

Yes, JSON is a requirement for us. We get input from tools with poor or absent protobuf support, running in environments where taking a dependency on our proto definitions (or indeed protobuf at all) often isn't desirable or practical. We use protobuf ourselves to define the wrapper, but clients don't necessarily use protobuf.

[I]f we simply drop the un-parsable Any wrapped value, does it work for your case?

In some instances we could probably reuse the original JSON (pre-decoding), but in others the environment will need to make changes and re-encode (to JSON). That was the motivation for allowing the decoder to preserve the un-decoded field in the above proposal.

Perhaps it will help for me to give more context:

Basically the problem we have is that we have some "generic" plumbing tools that consume JSON-encoded messages from a variety of sources, and dispatch them to other tools. The wrapper messages carry metadata in Any extensions. The dispatcher doesn't need to decode the metadata, but does need to pass it along to other tools need them preserved. (Some tools require protobuf, others operate directly on the JSON; that's an implementation detail for our clients).

Right now anytime anyone adds a new metadata type, we wind up having to build and release new versions of the plumbing. That complicates updates quite a bit. We use protobuf internally in our indexing infrastructure, so I'm hoping for a solution that allows us to continue doing so. This proposal was motivated by symmetry with field-preservation in the wire-decoding case: Ideally json-encode(modify(json-decode(X))) would preserve unknown Any values as wire-encode(modify(wire-decode(X))) does for unknown field indices.

I hope that helps clarify things, but please let me know if not.

creachadair avatar Oct 08 '18 04:10 creachadair

Another potential avenue might be for Any to grow an encoding field/enum { WIRE, TEXT, JSON }

shahms avatar Oct 08 '18 15:10 shahms

  1. Is it possible, in the API you provided, to add a way to let client register the proto type to be wrapped in Any? (e.g., another service to register type, or the API also takes the wrapped type as a parameter). In this way, your service always knows the type of wrapped message.
  2. We have struct.proto to dynamically create generic json object: https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/struct.proto If 1) cannot be done, you may think replacing Any field with Struct field.

TeBoring avatar Oct 08 '18 21:10 TeBoring

Re (1): That would be tricky. Inputs often come from an offline process, not necessarily live RPCs. The dispatcher decodes the message in order to discover which analyzer should receive it—so if the analyzer has to advertise its message formats in advance, we're basically in the situation we have now, where we have to re-bake the dispatching-driver for each new message type that exists.

Re (2): We could replace the typed messages with untyped structs. That loses much of the benefit of using protobuf in the first place, though, which was to have static message types in the code that needs them (e.g., the analyzers). It's fine for our purposes to require an analyzer to bake in the message types it cares about; what we're trying to avoid is having to revise the intermediate plumbing (e.g., dispatching driver, storage libraries, etc.). Switching to structs would help the plumbing, but would hurt the analyzers.

creachadair avatar Oct 08 '18 21:10 creachadair

Your client can work on normal message which has the type checking. The json encoding of the normal message can be parsed as Struct.

TeBoring avatar Oct 08 '18 22:10 TeBoring

Your client can work on normal message which has the type checking. The json encoding of the normal message can be parsed as Struct.

I think I must be misunderstanding something about your suggestion, can you be slightly more specific?

Our wrapper message currently carries fields of type google.protobuf.Any, and I think if I understood your suggestion correctly you are proposing we replace those with google.protobuf.Struct. Suppose we do that: Decoding JSON into a matching google.protobuf.Struct works fine as expected, but then how does one go from that back to a properly-typed message? For example, we have a message schematically like:

message M {
  string name = 1;
  string kind = 2;
}

If I decode {"name":"foo","kind":"bar"} into a google.protobuf.Struct I get something like:

name: "foo"
kind: "bar"

but I'm not sure I see how I go from the Struct to an M.

creachadair avatar Oct 11 '18 20:10 creachadair

Struct is one option. You may also use string field. For Struct to M, m.parseFromJson(s.serializeToJson()). Does that work?

TeBoring avatar Oct 11 '18 20:10 TeBoring

For Struct to M, m.parseFromJson(s.serializeToJson()). Does that work?

Functionally it looks like it should work, but I would describe that as a workaround rather than a solution. To use this, we would have not only to migrate all our existing protos from Any to Struct but we would also have to (manually) update all the current users of the message to include this decode logic, for each message type they support. As I said above: This makes things better for our plumbing, but worse for our analyzers. That's a poor trade, since the analyzers are often contributed/supported by third parties.

Much of the benefit we get from using protobuf is that the schema defines the layout, and the decoder "just works", whether for wire-format or JSON, and gracefully adapts to forward-compatible changes in the message format. In principle, a new Any message should be forward-compatible. Rather than work around the fact that it's currently not for JSON, I think it would be better to provide a deferral mechanism.

It's worth noting that the proposal above also extends to other encoding schemes like textpb, and although our project doesn't rely on textpb, I'm aware of others that do. Having a standard way to express deferred parsing would have very little down-side I can see.

creachadair avatar Oct 11 '18 20:10 creachadair

The purpose of Any is to replace extension in proto2. For extension, you do need to link every related message in order to make it work. I think same requirement for Any seems reasonable. In order to make Any work, you have to link the related messages.

I also feel type checking is also part of the semantic of Any. Any is used for polymorphism for known types not for any random type. And because the type checking is part of the semantic of Any, if a server sends an undeclared Any to client (like in your case), that is considered as a security attack vector. For clients that assumes the type checking semantic of Any, that would be unacceptable.

TeBoring avatar Oct 11 '18 20:10 TeBoring

The other approach I can think of is to provide a way to let client tell sever the type of wrapped message.

TeBoring avatar Oct 11 '18 21:10 TeBoring

I also feel type checking is also part of the semantic of Any. Any is used for polymorphism for known types not for any random type.

Agreed—but the situation I'm describing isn't one where we want to discard type-checking, only defer it. The end-consumer of the message still has to know the type, and that's appropriate. The goal is not to allow arbitrary messages, but to allow the channel to inspect known parts of the message structure without forcing a full decode of the unknown parts. This works for wire-format, but not for JSON. Given that the cost to protobuf itself is small (i.e., no functional changes are required to the compiler), I'm not clear on the objection.

creachadair avatar Oct 11 '18 21:10 creachadair

The other approach I can think of is to provide a way to let client tell sever the type of wrapped message.

That doesn't work for our case, because we don't know which client we're talking to until after we've inspected the wrapper message. The dispatcher examines the message, figures out which analyzer to invoke, and does so (note too that this isn't necessarily "client-server" interaction in the Stubby/gRPC sense—in some cases these are pipes or stored files).

creachadair avatar Oct 11 '18 21:10 creachadair

"Defer" may mean never. If we allow some decoder to defer parsing unknown Any, how can we guarantee the type checking will be done in the end?

TeBoring avatar Oct 11 '18 21:10 TeBoring

"Defer" may mean never. If we allow some decoder to defer parsing unknown Any, how can we guarantee the type checking will be done in the end?

The same question applies to unknown fields: Nothing can guarantee that type-checking will be done. Similarly, nothing can guaranteed that for Any messages in wire format: The reader can always grab the bytes and do whatever.

For our case, as in the case you're describing, either (a) we won't use the field at all, or (b) it will be decoded with the proper descriptor. The question of whether the message is decoded and used is outside the scope of the protobuf language's concern: The language doesn't define how wire-types are mapped to language types, for example.

This proposal doesn't, as far as I can see, contradict any of the protobuf language goals: A decoder with the descriptor in-harness will still decode the message structure correctly. A decoder without the descriptor in-harness will treat it as an unknown-but-preserved field. Either way, a program in possession of the raw message format could choose to decode and use it some other way—this doesn't make that any easier (or harder).

creachadair avatar Oct 11 '18 21:10 creachadair

Actually, for json unknown fields, the default behavior is fail and the optional behavior is discard. So the json Any behavior still seems consistent to me.

TeBoring avatar Oct 11 '18 21:10 TeBoring