async def process(self, request_id: str, sender_address: str, request_bytes: bytes) -> CommandResponseObject: try: if not request_id: raise offchain.protocol_error( offchain.ErrorCode.missing_http_header, "missing %s" % offchain.X_REQUEST_ID) if not offchain.UUID_REGEX.match(request_id): raise offchain.protocol_error( offchain.ErrorCode.invalid_http_header, "invalid %s" % offchain.X_REQUEST_ID) request = await self.app.offchain.deserialize_inbound_request( sender_address, request_bytes) except offchain.Error as e: err_msg = "process offchain request id or bytes is invalid, request id: %s, bytes: %s" self.app.logger.exception(err_msg, request_id, request_bytes) return offchain.reply_request(cid=None, err=e.obj) cached = self.cache.get(request.cid) if cached: return cached response = await self._process_offchain_request( sender_address, request) self.cache[request.cid] = response return response
async def _process_offchain_request( self, sender_address: str, request: CommandRequestObject) -> CommandResponseObject: try: handler = "_handle_offchain_%s" % utils.to_snake( request.command_type) if not hasattr(self, handler): raise offchain.protocol_error( offchain.ErrorCode.unknown_command_type, "unknown command_type: %s" % request.command_type, field="command_type", ) fn = getattr(self, handler) result = await fn(sender_address, request) return offchain.reply_request(cid=request.cid, result=result) except offchain.Error as e: err_msg = "process offchain request failed, sender_address: %s, request: %s" self.app.logger.exception(err_msg, sender_address, request) return offchain.reply_request(cid=request.cid, err=e.obj)
def process_inbound_request( self, x_request_id: str, request_sender_address: str, request_bytes: bytes) -> typing.Tuple[int, bytes]: cid = None try: if not x_request_id: raise offchain.protocol_error( offchain.ErrorCode.missing_http_header, "missing %s" % offchain.X_REQUEST_ID) inbound_command = self.offchain_client.process_inbound_request( request_sender_address, request_bytes) cid = inbound_command.id() self.save_command(inbound_command) resp = offchain.reply_request(cid) code = 200 except offchain.Error as e: logger.exception(e) resp = offchain.reply_request(cid if cid else None, e.obj) code = 400 return (code, offchain.jws.serialize(resp, self.compliance_key.sign))