def serialize_config(artifact: Artifact, data: Any) -> PbAny: json_data = json.dumps(data) msg = get_service_config_structure(artifact.module, artifact.module)() json_format.Parse(json_data, msg) output = PbAny() output.Pack(msg) return output
def test_unpack(self): # arrange fake_req = common_v1.InvokeRequest(method="test") test_data = GrpcAny() test_data.Pack(fake_req) # act resp = InvokeServiceResponse(data=test_data) resp_proto = common_v1.InvokeRequest() resp.unpack(resp_proto) # assert self.assertEqual("test", resp_proto.method)
class InvokeServiceRequestData: """A request data representation for invoke_service API. This stores the request data with the proper serialization. This seralizes data to :obj:`google.protobuf.any_pb2.Any` if data is the type of protocol buffer message. Attributes: data (:obj:`google.protobuf.any_pb2.Any`): the serialized data for invoke_service request. content_type (str, optional): the content type of data which is valid only for bytes array data. """ def __init__(self, data: Union[bytes, str, GrpcMessage], content_type: Optional[str] = None): """Inits InvokeServiceRequestData with data and content_type. Args: data (bytes, str, or :obj:`google.protobuf.message.Message`): the data which is used for invoke_service request. content_type (str): the content_type of data when the data is bytes. The default content type is application/json. Raises: ValueError: data is not bytes or :obj:`google.protobuf.message.Message`. """ self._data = GrpcAny() if isinstance(data, str): data = data.encode('utf-8') if isinstance(data, bytes): self._data.value = data self._content_type = content_type if not content_type: self._content_type = DEFAULT_JSON_CONTENT_TYPE elif isinstance(data, GrpcMessage): self._data.Pack(data) self._content_type = None else: raise ValueError(f'invalid data type {type(data)}') @property def data(self) -> GrpcAny: return self._data @property def content_type(self) -> Optional[str]: return self._content_type
def test_is_proto_for_protobuf(self): fake_req = common_v1.InvokeRequest(method="test") test_data = GrpcAny() test_data.Pack(fake_req) resp = InvokeServiceResponse(data=test_data) self.assertTrue(resp.is_proto())
def test_proto(self): fake_req = common_v1.InvokeRequest(method="test") test_data = GrpcAny() test_data.Pack(fake_req) resp = InvokeServiceResponse(data=test_data) self.assertIsNotNone(resp.data)
class InvokeServiceRequest(DaprRequest): """A request data representation for invoke_service API. This stores the request data with the proper serialization. This seralizes data to :obj:`google.protobuf.any_pb2.Any` if data is the type of protocol buffer message. Attributes: metadata(dict): A dict to include the headers from Dapr Request. data (str, bytes, GrpcAny, GrpcMessage, optional): the serialized data for invoke_service request. content_type (str, optional): the content type of data which is valid only for bytes array data. """ HTTP_METHODS = [ 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE' ] def __init__(self, data: Union[str, bytes, GrpcAny, GrpcMessage, None] = None, content_type: Optional[str] = None): """Inits InvokeServiceRequestData with data and content_type. Args: data (bytes, str, GrpcAny, GrpcMessage, optional): the data which is used for invoke_service request. content_type (str): the content_type of data when the data is bytes. The default content type is application/json. Raises: ValueError: data is not supported. """ super(InvokeServiceRequest, self).__init__(()) self._content_type = content_type self._http_verb = None self._http_querystring: Dict[str, str] = {} self.set_data(data) # Set content_type to application/json type if content_type # is not given and date is bytes or str type. if not self.is_proto() and not content_type: self.content_type = DEFAULT_JSON_CONTENT_TYPE @property def http_verb(self) -> Optional[str]: """Gets HTTP method in Dapr invocation request.""" return self._http_verb @http_verb.setter def http_verb(self, val: Optional[str]) -> None: """Sets HTTP method to Dapr invocation request.""" if val not in self.HTTP_METHODS: raise ValueError(f'{val} is the invalid HTTP verb.') self._http_verb = val @property def http_querystring(self) -> Dict[str, str]: """Gets HTTP querystring as dict.""" return self._http_querystring def is_http(self) -> bool: """Return true if this request is http compatible.""" return hasattr(self, '_http_verb') and not (not self._http_verb) @property def proto(self) -> GrpcAny: """Gets raw data as proto any type.""" return self._data def is_proto(self) -> bool: """Returns true if data is protocol-buffer serialized.""" return hasattr(self, '_data') and self._data.type_url != '' def pack(self, val: Union[GrpcAny, GrpcMessage]) -> None: """Serializes protocol buffer message. Args: message (:class:`GrpcMessage`, :class:`GrpcAny`): the protocol buffer message object Raises: ValueError: message is neither GrpcAny nor GrpcMessage. """ if isinstance(val, GrpcAny): self._data = val elif isinstance(val, GrpcMessage): self._data = GrpcAny() self._data.Pack(val) else: raise ValueError('invalid data type') def unpack(self, message: GrpcMessage) -> None: """Deserializes the serialized protocol buffer message. Args: message (:obj:`GrpcMessage`): the protocol buffer message object to which the response data is deserialized. Raises: ValueError: message is not protocol buffer message object or message's type is not matched with the response data type """ unpack(self.proto, message) @property def data(self) -> bytes: """Gets request data as bytes.""" if self.is_proto(): raise ValueError('data is protocol buffer message object.') return self._data.value @data.setter def data(self, val: Union[str, bytes]) -> None: """Sets str or bytes type data to request data.""" self.set_data(to_bytes(val)) def set_data(self, val: Union[str, bytes, GrpcAny, GrpcMessage, None]) -> None: """Sets data to request data.""" if val is None: self._data = GrpcAny() elif isinstance(val, (bytes, str)): self._data = GrpcAny(value=to_bytes(val)) elif isinstance(val, (GrpcAny, GrpcMessage)): self.pack(val) else: raise ValueError(f'invalid data type {type(val)}') def text(self) -> str: """Gets the request data as str.""" return to_str(self.data) @property def content_type(self) -> Optional[str]: """Gets content_type for bytes data.""" return self._content_type @content_type.setter def content_type(self, val: Optional[str]) -> None: """Sets content type for bytes data.""" self._content_type = val
class InvokeServiceResponse(DaprResponse): """The response of invoke_service API. This inherits from DaprResponse and has the helpers to handle bytes array and protocol buffer data. Attributes: headers (tuple, optional): the tuple for the headers from response. data (str, bytes, GrpcAny, GrpcMessage, optional): the serialized protocol buffer raw message content (bytes, optional): bytes data if response data is not serialized protocol buffer message content_type (str, optional): the type of `content` """ def __init__(self, data: Union[str, bytes, GrpcAny, GrpcMessage, None] = None, content_type: Optional[str] = None, headers: MetadataTuple = ()): """Initializes InvokeServiceReponse from :obj:`common_v1.InvokeResponse`. Args: data (str, bytes, GrpcAny, GrpcMessage, optional): the response data from Dapr response content_type (str, optional): the content type of the bytes data headers (tuple, optional): the headers from Dapr gRPC response """ super(InvokeServiceResponse, self).__init__(headers) self._content_type = content_type self.set_data(data) # Set content_type to application/json type if content_type # is not given and date is bytes or str type. if not self.is_proto() and not content_type: self.content_type = DEFAULT_JSON_CONTENT_TYPE @property def proto(self) -> GrpcAny: """Gets raw serialized protocol buffer message. Raises: ValueError: data is not protocol buffer message object """ return self._data def is_proto(self) -> bool: """Returns True if the response data is the serialized protocol buffer message.""" return hasattr(self, '_data') and self._data.type_url != '' @property def data(self) -> bytes: """Gets raw bytes data if the response data content is not serialized protocol buffer message. Raises: ValueError: the response data is the serialized protocol buffer message """ if self.is_proto(): raise ValueError('data is protocol buffer message object.') return self._data.value @data.setter def data(self, val: Union[str, bytes]) -> None: """Sets str or bytes type data to request data.""" self.set_data(val) def set_data(self, val: Union[str, bytes, GrpcAny, GrpcMessage, None]) -> None: """Sets data to request data.""" if val is None: self._data = GrpcAny() elif isinstance(val, (bytes, str)): self._data = GrpcAny(value=to_bytes(val)) elif isinstance(val, (GrpcAny, GrpcMessage)): self.pack(val) else: raise ValueError(f'invalid data type {type(val)}') def text(self) -> str: """Gets content as str if the response data content is not serialized protocol buffer message. Raises: ValueError: the response data is the serialized protocol buffer message """ return to_str(self.data) @property def content_type(self) -> Optional[str]: """Gets the content type of content attribute.""" return self._content_type @content_type.setter def content_type(self, val: Optional[str]) -> None: """Sets content type for bytes data.""" self._content_type = val def pack(self, val: Union[GrpcAny, GrpcMessage]) -> None: """Serializes protocol buffer message. Args: message (:class:`GrpcMessage`, :class:`GrpcAny`): the protocol buffer message object Raises: ValueError: message is neither GrpcAny nor GrpcMessage. """ if isinstance(val, GrpcAny): self._data = val elif isinstance(val, GrpcMessage): self._data = GrpcAny() self._data.Pack(val) else: raise ValueError('invalid data type') def unpack(self, message: GrpcMessage) -> None: """Deserializes the serialized protocol buffer message. Args: message (:class:`GrpcMessage`): the protocol buffer message object to which the response data is deserialized. Raises: ValueError: message is not protocol buffer message object or message's type is not matched with the response data type """ unpack(self.proto, message)
def send_packet(self, packet): any = Any() Any.Pack(any, packet) return self.__send(any.SerializeToString())