protocolbuffers / protobuf-javascript

BSD 3-Clause "New" or "Revised" License
351 stars 67 forks source link

ProtoBuf Descriptor #184

Closed sudospaes closed 8 months ago

sudospaes commented 8 months ago

Hello I am trying to communicate from a microservice written with Go via grpc. In some operators, to send a request, it is necessary that I type the message I am sending in the request. I read some sources in golang and python languages. This is how they determine the type of messages.

I have a namespace with TypedMessage in typescript to keeping message type and message value :

export namespace TypedMessage {
    export type AsObject = {
        type: string,
        value: Uint8Array | string,
    }
}

I need to convert every message to this type, so I wrote such a function :

function toTypedMessage(message: proto.Message) {
  const typedMessage = new TypedMessage();
  typedMessage.setType("Its not complete");
  typedMessage.setValue(message.serializeBinary());
  return typedMessage;
}

I inspired this from the Python and Go resources :

Go :

func GetMessageType(message proto.Message) string {
  return string(message.ProtoReflect().Descriptor().FullName())
}

func ToTypedMessage(message proto.Message) *TypedMessage {
  if message == nil {
    return nil
  }
  settings, _ := proto.Marshal(message)
  return &TypedMessage{
    Type:  GetMessageType(message),
    Value: settings,
  }
}

Python :

class Message:
    def __new__(cls, message) -> TypedMessage:
        return TypedMessage(
            type=message.DESCRIPTOR.full_name,
            value=message.SerializeToString()
        )

My problem in this part is the function I wrote typedMessage.setType("");. As it is known, this value must be a string. According to Go and Python sources, a descriptor is needed to return the message to the proto name like message.ProtoReflect().Descriptor().FullName() in go and like message.DESCRIPTOR.full_name in python. But it seems that there is no such thing in nodeJS google-protobuf. Is there another solution or not?

dibenede commented 8 months ago

We do not support reflection for code size and information leakage reasons. You will need to explicitly include the name in your source code.

Also, if I'm understanding correctly, your use case sounds a lot like the built-in protobuf Any type (i.e. a type URL and corresponding payload). You may want to take a look at https://github.com/protocolbuffers/protobuf-javascript/blob/main/docs/index.md#any .

sudospaes commented 8 months ago

We do not support reflection for code size and information leakage reasons. You will need to explicitly include the name in your source code.

Also, if I'm understanding correctly, your use case sounds a lot like the built-in protobuf Any type (i.e. a type URL and corresponding payload). You may want to take a look at https://github.com/protocolbuffers/protobuf-javascript/blob/main/docs/index.md#any .

Thank you ❤️.