# Copyright 2022 MOSEC Authors## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""MOSEC msgpack worker mixin.Features: * deserialize request body with msgpack * serialize response body with msgpack"""# pylint: disable=import-outside-toplevelfromtypingimportAnyfrommosec.errorsimportDecodingError,EncodingError
[docs]defserialize(self,data:Any)->bytes:"""Serialize with msgpack for the last stage (egress). Arguments: data: the **same type** as returned by :py:meth:`Worker.forward <mosec.worker.Worker.forward>` Returns: the bytes you want to put into the response body Raises: EncodingError: if the data cannot be serialized with msgpack """importmsgpack# type: ignoretry:data_bytes=msgpack.packb(data)exceptExceptionaserr:raiseEncodingErrorfromerrreturndata_bytes# type: ignore
[docs]defdeserialize(self,data:bytes)->Any:"""Deserialize method for the first stage (ingress). Arguments: data: the raw bytes extracted from the request body Returns: the **same type** as the input of :py:meth:`Worker.forward <mosec.worker.Worker.forward>` Raises: DecodingError: if the data cannot be deserialized with msgpack """importmsgpacktry:data_msg=msgpack.unpackb(data,use_list=False)exceptExceptionaserr:raiseDecodingErrorfromerrreturndata_msg