_codec.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from __future__ import annotations
  2. from typing import TypeVar
  3. from google.protobuf.json_format import MessageToJson
  4. from google.protobuf.json_format import Parse as MessageFromJson
  5. from google.protobuf.message import Message
  6. from connectrpc.codec import Codec
  7. CODEC_NAME_PROTO = "proto"
  8. CODEC_NAME_JSON = "json"
  9. T_contra = TypeVar("T_contra", contravariant=True)
  10. U = TypeVar("U")
  11. V = TypeVar("V", bound=Message)
  12. class ProtoBinaryCodec(Codec[Message, V]):
  13. """Codec for Protocol bytes | bytearrays binary format."""
  14. def name(self) -> str:
  15. return "proto"
  16. def encode(self, message: Message) -> bytes:
  17. return message.SerializeToString()
  18. def decode(self, data: bytes | bytearray, message_class: type[V]) -> V:
  19. return message_class.FromString(data) # ty:ignore[invalid-argument-type] type is incorrect
  20. class ProtoJSONCodec(Codec[Message, V]):
  21. """Codec for Protocol bytes | bytearrays JSON format."""
  22. def __init__(self, name: str = "json") -> None:
  23. self._name = name
  24. def name(self) -> str:
  25. return self._name
  26. def encode(self, message: Message) -> bytes:
  27. return MessageToJson(message).encode()
  28. def decode(self, data: bytes | bytearray, message_class: type[V]) -> V:
  29. message = message_class()
  30. MessageFromJson(data, message) # ty:ignore[invalid-argument-type] type is incorrect
  31. return message
  32. _proto_binary_codec = ProtoBinaryCodec()
  33. _proto_json_codec = ProtoJSONCodec()
  34. _default_codecs: list[Codec] = [_proto_binary_codec, _proto_json_codec]
  35. def google_protobuf_codecs() -> list[Codec]:
  36. """Returns the codecs for marshaling Protocol Buffers using google.protobuf."""
  37. return _default_codecs
  38. def google_protobuf_binary_codec() -> Codec:
  39. """Returns the Protocol Buffers binary codec using google.protobuf."""
  40. return _proto_binary_codec
  41. def google_protobuf_json_codec() -> Codec:
  42. """Returns the Protocol Buffers JSON codec using google.protobuf."""
  43. return _proto_json_codec