Convert from Protocol buffer to heirachical Generic Request - protocol-buffers

We are planning to move grpc micro architecture. So we need a general adapter for converting protocol buffer Request object to existing POJO object vice versa.
In our current scenario, We have :-
message RequestIdentity {
Tenant tenant = 1;
string userToken = 2;
string ipAddress = 3;
}
message StudentRequest {
RequestIdentity requestIdentity = 1;
string id = 2;
string name = 3;
}
As above scenario, we have to convert into our generic ServiceRequest<Student> POJO object . Protocol buffer object has two part:
RequestIdentity - is responsible for creating ServiceRequest.
id and name - are payload of Student.
like wise convert different request using general adapter ? any idea

Related

How to organize proto file to re-use message if possible?

I recently started working with protobuf in my golang project. I created below simple protobuf file. I have three different endpoints.
GetLink takes CustomerRequest as an input parameter and returns back CustomerResponse
GetBulkLinks takes BulkCustomerRequest as an input parameter and returns back BulkCustomerResponse
StreaLinks takes StreamRequest as an input parameter and returns back CustomerResponse
I am wondering if there is any way we can improve below proto file because CustomerRequest and BulkCustomerRequest has mostly everything in common except resources field so there is a duplication. And same goes with StreamRequest input parameter as it only takes clientId as the input parameter. Is there anything in protocol buffer which can reuse stuff from another message type?
Is there any better or efficient way to organize below proto file which reuses message accordingly?
syntax = "proto3";
option go_package = "github.com/david/customerclient/gen/go/data/v1";
package data.v1;
service CustomerService {
rpc GetLink(CustomerRequest) returns (CustomerResponse) {};
rpc GetBulkLinks(BulkCustomerRequest) returns (BulkCustomerResponse) {};
rpc StreaLinks(StreamRequest) returns (CustomerResponse) {};
}
message CustomerRequest {
int32 clientId = 1;
string resources = 2;
bool isProcess = 3;
}
message BulkCustomerRequest {
int32 clientId = 1;
repeated string resources = 2;
bool isProcess = 3;
}
message StreamRequest {
int32 clientId = 1;
}
message CustomerResponse {
string value = 1;
string info = 2;
string baseInfo = 3;
string link = 4;
}
message BulkCustomerResponse {
map<string, CustomerResponse> customerResponse = 1;
}
Is there anything in protocol buffer which can reuse stuff from another message type?
Composition.
However keep in mind that request and response payloads may change over time. Even if it looks like they have something in common today, they may diverge tomorrow. After all they are used in different RPCs. Then excessive coupling achieves the opposite effect and becomes technical debt.
Since your schema has literally no more than three fields for each message, I would leave everything as is. Anyway, if you really must, you may consider the following:
Extract the GetLink and GetBulkLinks common fields in a separate message and compose with that:
message CustomerRequestParams {
int32 clientId = 1;
bool isProcess = 2;
}
message CustomerRequest {
CustomerRequestParams params = 1;
string resources = 2;
}
message BulkCustomerRequest {
CustomerRequestParams params = 1;
repeated string resources = 2;
}
StreamRequest looks just fine with repeating clientId. Arguably a stream is conceptually different from a unary RPC, so just keep them separated. And it's just one field.

In a proto3 message is there a way to mark a field as not required for requests and required for response?

I have the following proto3 message structure:
message BaseBuildContent {
string locale = 1;
string buildVersion = 2;
string buildLabel = 3;
google.protobuf.Timestamp createTime = 4;
}
I am using the "same" structure for some requests and responses on my app. What I want to achieve is to mark somehow (if possible) the createTime field as not required, in case we are talking about a request object, and required in case we are taking about a response object.
Is it possible to do this without creating a separate message ?
Thanks
To my knowledge, it's not possible and I'd discourage pursuing solutions other than defining distinct message types: one which includes the optional field and one which does not.
One way to solve this is to define a message that includes the mandatory fields and another than extends it:
message BaseBuildContent {
string locale = 1;
string buildVersion = 2;
string buildLabel = 3;
}
message SomeRequest {
BaseBuildContent content = 1;
}
message SomeResponse {
BaseBuildContent content = 1;
google.protobuf.Timestamp createTime = 2;
}
NOTE Protobuf style guide recommends message names be PascalCased and field names be snake_cased.

Should I create a message per method or use a shared message in gRPC?

Currently I'm using gRPC as the communication between my servers, but I don't know which is the best pattern.
Should I create a shared request message (UserRequest is treated like an User object):
service User {
rpc Create (UserRequest) returns (Reply) {}
rpc Update (UserRequest) returns (Reply) {}
rpc Delete (UserRequest) returns (Reply) {}
}
message UserRequest {
string username = 1;
string password = 2;
string email = 3;
string gender = 4;
string birthday = 5;
}
Or create a message per method like this to define the fields that the method actually needed? But since the methods are using almost the same fields, this is kinda verbose for me.
service User {
rpc Create (CreateUserRequest) returns (Reply) {}
rpc Update (UpdateUserRequest) returns (Reply) {}
rpc Delete (DeleteUserRequest) returns (Reply) {}
}
message CreateUserRequest {
string username = 1;
string password = 2;
}
message UpdateUserRequest {
string username = 1;
string password = 2;
string email = 3;
string gender = 4;
string birthday = 5;
}
//...
Generally, create a different message for each RPC, to allow you to extend them separately. There are exceptions, but it would be unlikely when the methods do different things (create, update, delete).
As an example similar to your situation, take a look at pubsub:
rpc CreateSubscription(Subscription) returns (Subscription) {...}
rpc UpdateSubscription(UpdateSubscriptionRequest) returns (Subscription) {...}
rpc DeleteSubscription(DeleteSubscriptionRequest) returns (google.protobuf.Empty) {...}
I will note it uses google.protobuf.Empty, which I generally wouldn't suggest using for your own service as it prevents further extension. It also would have been fine to have created a CreateSubscriptionRequest that just contained a Subscription. I expect they didn't so as to make REST API to feel more natural (those google.api.http options).

Partial Message Serialize using Protocol buffer java api

I want to serialize the below message partially i.e. I want to serialize first three properties id, name, companyName and don't want to serialize the age.
I am working Protocol Buffer Java API.
message Person{
required int32 id = 1;
required string name = 2;
optional string companyName = 3;
`optional int32 age = 3;`
}
can somebody help me on that?
Reetesh
You'll need to make a copy of the message, then remove age from the copy, then serialize:
person.toBuilder().clearAge().build().toByteArray()

Many subclasses for one base class - protobuf performance

Right now I have an application where my iPhone app sends a request that is handled in .NET/C#, serialized to XML, and parsed on the app in objective-c. The current response class structure has one base class (BaseResponse) and many (over 25) subclasses for each type of request that corresponds to different things that need to be returned. Right now I'm looking to see if protobuf would be faster and easier than XML. From what I understand, a .proto file for this class structure is:
Message BaseResponse {
Required Int field1 = 1;
Optional SubResponse1 sub1= 2;
Optional SubResponse2 sub2 = 3;
Etc....
}
Message SubResponse1 {
....
}
Message SubResponse2 {
....
}
Etc for each sub response.
My question is: if I have over 25 of these optional elements (of which only 1 will be non null), does that completely wipe away the size and performance benefit of using protobuf? Does protobuf make sense for this application?
No, it does not impact the performance benefit - you'll just need to check which one is non-null in the objective-C code. Since protobuf only serializes the non-null values it will still be very efficient over the wire. The protobuf specification itself doesn't actually include inheritance, so you are right to say that you need to spoof it via encapsulation - but since you mention C#, note that what you have described (including how the data appears on the wire, i.e. it will be 100% comptible) can be done directly via inheritance if you use protobuf-net as the C# implementation - which should be possible with your existing model. For example:
[ProtoContract]
[ProtoInclude(2, typeof(SubResponse1))]
[ProtoInclude(3, typeof(SubResponse2))]
public class BaseResponse
{
// note Name and IsRequired here are optional - only
// included to match your example
[ProtoMember(1, IsRequired = true, Name="field1")]
public int Field1 { get; set; }
/*...*/
}
[ProtoContract]
public class SubResponse1 : BaseResponse
{/*...*/}
[ProtoContract]
public class SubResponse2 : BaseResponse
{/*...*/}
You can get the .proto via:
var proto = Serializer.GetProto<BaseResponse>();
Which gives:
message BaseResponse {
required int32 field1 = 1 [default = 0];
// the following represent sub-types; at most 1 should have a value
optional SubResponse1 SubResponse1 = 2;
optional SubResponse2 SubResponse2 = 3;
}
message SubResponse1 {
}
message SubResponse2 {
}

Resources