Question

I am working with a system that is extremely modular. Messages can be determined by the by the 3-tuple of src, dest, type.

I'm looking into reimplementing our messages with Protocol Buffers. I've read through Protocol buffer polymorphism, what's the right way to do polymorphism with protocol buffers? and http://www.indelible.org/ink/protobuf-polymorphism/

What I am wondering has anyone implement a solution where:

message header {
    required string src = 1
    required string dest = 2
    required string type = 3
}

And creating separate messages where:

message foo {
    required header h = 1
    required string a = 2
}

Separate file:

message bar {
    required header h = 1
    required uint32 num = 2
}

In the receiving code have something like:

Message.ParseFromString(msgStr)
if (Message.type == foo)
{
  FooMessage.ParseFromString(msgStr)
}
else {
    BarMessage.ParseFromString(msgStr)
}

If this approach has been used, is it better or worse than what's described in the above links?

Was it helpful?

Solution

Only way I found is to serialize/deserialize the message body as byte array. Then you will get needed level of abstraction:

message header {
    required string src = 1;
    required string dest = 2;
    required string type = 3;
}

message foo {
    required string a = 2;
}

message bar {
    required uint32 num = 2;
}

message request {
    required header h;
    required bytes data; // serialize foo or bar here
}

Then your code will be like that (this is a pseudo-code):

request req = request.ParseFromString(buffer);

if (req.h().type() == "foo") {
    foo msg = foo.ParseFromString(req.data);
    // process foo msg
}
else if (req.h().type() == "bar") {
    bar msg = bar.ParseFromString(req.data);
    // process bar msg
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top