Пример #1
0
    def _generate_answers(self, user, commands, message, **kwargs):
        topic_key = kwargs["topic_key"]
        kafka_key = kwargs["kafka_key"]
        answers = []
        commands = commands or []

        commands = combine_commands(commands, user)

        for command in commands:
            request = SmartKitKafkaRequest(id=None, items=command.request_data)
            request.update_empty_items({
                "topic_key": topic_key,
                "kafka_key": kafka_key
            })
            answer = SmartAppToMessage(command=command,
                                       message=message,
                                       request=request,
                                       masking_fields=self.masking_fields,
                                       validators=self.to_msg_validators)
            if answer.validate():
                answers.append(answer)
            else:
                answers.append(
                    SmartAppToMessage(self.BAD_ANSWER_COMMAND,
                                      message=message,
                                      request=request))

            smart_kit_metrics.counter_outgoing(self.app_name, command.name,
                                               answer, user)

        return answers
Пример #2
0
    def handle_message(
        self, message: SmartAppFromMessage
    ) -> typing.Tuple[int, str, SmartAppToMessage]:
        if not message.validate():
            return 400, "BAD REQUEST", SmartAppToMessage(
                self.BAD_REQUEST_COMMAND, message=message, request=None)

        answer, stats = self.process_message(message)
        if not answer:
            return 204, "NO CONTENT", SmartAppToMessage(self.NO_ANSWER_COMMAND,
                                                        message=message,
                                                        request=None)

        return 200, "OK", SmartAppToMessage(answer, message, request=None)
Пример #3
0
    def iterate(self, environ, start_response):
        stats = ""
        with StatsTimer() as poll_timer:
            try:
                content_length = int(environ.get('CONTENT_LENGTH', '0'))
                request = environ["wsgi.input"].read(content_length).decode()
                headers = self._get_headers(environ)
            except KeyError:
                log("Error in request data", level="ERROR")
                raise Exception("Error in request data")

        stats += "Polling time: {} msecs\n".format(poll_timer.msecs)

        message = SmartAppFromMessage(request,
                                      headers=headers,
                                      headers_required=False)
        if not message.validate():
            start_response("400 BAD REQUEST",
                           self._get_outgoing_headers(headers))
            return [b'{"message": "invalid message"}']

        answer, stats = self.handle_message(message, stats)
        with StatsTimer() as publish_timer:
            if not answer:
                start_response("204 NO CONTENT",
                               self._get_outgoing_headers(headers))
                return [b'{"message": "no answer"}']
            start_response("200 OK",
                           self._get_outgoing_headers(headers, answer))
            answer = SmartAppToMessage(answer, message, request=None)

        stats += "Publishing time: {} msecs".format(publish_timer.msecs)
        log(stats, params={log_const.KEY_NAME: "timings"})
        return [answer.value.encode()]
    def handle_message(
        self, message: SmartAppFromMessage
    ) -> typing.Tuple[int, str, SmartAppToMessage]:
        if not message.validate():
            result = 400, "BAD REQUEST", SmartAppToMessage(
                self.BAD_REQUEST_COMMAND,
                message=message,
                request=None,
            )
            try:
                result[2].as_dict
            except (json.JSONDecodeError, KeyError):
                result = 400, "BAD REQUEST", SmartAppToMessage(
                    self.BAD_REQUEST_COMMAND,
                    message=basic_error_message,
                    request=None,
                )
            finally:
                return result

        answer, stats = self.process_message(message)
        if not answer:
            return 204, "NO CONTENT", SmartAppToMessage(self.NO_ANSWER_COMMAND,
                                                        message=message,
                                                        request=None)

        answer_message = SmartAppToMessage(answer,
                                           message,
                                           request=None,
                                           validators=self.to_msg_validators)
        if answer_message.validate():
            return 200, "OK", answer_message
        else:
            return 500, "BAD ANSWER", SmartAppToMessage(
                self.BAD_ANSWER_COMMAND, message=message, request=None)
Пример #5
0
    def _generate_answers(self, user, commands, message):

        answers = []
        commands = commands or []

        commands = combine_commands(commands, user)

        for command in commands:
            request = SmartKitKafkaRequest(id=None, items=command.request_data)
            answer = SmartAppToMessage(command=command, message=message, request=request)
            answers.append(answer)
        return answers
Пример #6
0
 def test_smart_app_to_message_1(self):
     obj = SmartAppToMessage(self.command_, self.message_, self.request_)
     self.assertTrue(obj.command.name == "AnyName")
     self.assertTrue(obj.incoming_message.uuid == '1234-5678-9012')
     self.assertTrue(obj.request.header == "json")
     self.assertTrue(obj.forward_fields == ())
     self.assertTrue(obj.payload == {"z": 1})
     self.assertTrue(
         obj.as_dict == {
             "messageId": 111,
             "sessionId": 11,
             "messageName": "AnyName",
             "payload": {
                 "z": 1
             },
             "uuid": '1234-5678-9012'
         })
     self.assertTrue(obj.value == self.output_json)
    async def handle_message(self, message: SmartAppFromMessage) -> typing.Tuple[int, str, SmartAppToMessage]:
        if not message.validate():
            return 400, "BAD REQUEST", SmartAppToMessage(self.BAD_REQUEST_COMMAND, message=message, request=None)

        answer, stats = await self.process_message(message)
        if not answer:
            return 204, "NO CONTENT", SmartAppToMessage(self.NO_ANSWER_COMMAND, message=message, request=None)

        answer_message = SmartAppToMessage(
            answer, message, request=None,
            validators=self.to_msg_validators)
        if answer_message.validate():
            return 200, "OK", answer_message
        else:
            return 500, "BAD ANSWER", SmartAppToMessage(self.BAD_ANSWER_COMMAND, message=message, request=None)
Пример #8
0
    def test_validation(self):
        command_ = PicklableMock()
        request_ = PicklableMock()
        message_ = PicklableMock()
        command_.payload = {"pi": 3.14159265358979}
        command_.name = "AnyName"
        request_.header = "json"
        message_.payload = {"q": 0}
        message_.incremental_id = 111
        message_.session_id = 11
        message_.uuid = '1234-5678-9012'

        message = SmartAppToMessage(command_,
                                    message_,
                                    request_,
                                    validators=(PieMessageValidator(), ))
        self.assertTrue(message.validate())

        command_.payload["pi"] = 2.7182818284
        message = SmartAppToMessage(command_,
                                    message_,
                                    request_,
                                    validators=(PieMessageValidator(), ))
        self.assertFalse(message.validate())
Пример #9
0
 def test_smart_app_to_message_4(self):
     obj = SmartAppToMessage(self.command_, self.message_, self.request_,
                             ["q"])
     self.assertTrue(obj.forward_fields == ["q"])
     self.assertTrue(obj.payload == {"z": 1, "q": 0})