async def handle(self, event):

        event_type = event.data["type"]
        event_data = event.data.get("context", None)
        subclasses = Event.__subclasses__()

        found_cls = False
        self.logger.debug(
            f"Attempting to translate Intent to event of type: {event_type}")
        for cls in subclasses:
            mod = f"{cls.__module__}.{cls.__name__}"
            self.logger.debug(f"Checking: {mod}")
            if event_type == mod:
                found_cls = True
                break

        if not found_cls:
            self.logger.warning(
                f"Failed to translate Intent to Event. Could not find event: {event_type}"
            )
            return

        try:
            new_event = cls().init(event_data)
        except:
            self.logger.exception(
                "While attempting to convert an intent to an event, the event initialization failed "
                "due to a schema validation error")
            return

        get_supervisor().fire_event(new_event)
Esempio n. 2
0
    def test_get_metadata_and_deserialize(self):
        dummy_event = DummyEvent().init({"prop_1": 1, "prop_2": "hello"})
        dummy_event.source("you")
        dummy_event.target("me!")

        raw_dict = dummy_event.get_metadata()

        deserialized = Event.deserialize(raw_dict)

        self.assertEqual(dummy_event, deserialized)
Esempio n. 3
0
async def trigger_event(request):
    """

    :param request:
    :return:
    """
    from msa.core.event import Event

    new_event = Event.deserialize(request.payload)
    get_supervisor().fire_event(new_event)

    return {"text": f"Event {new_event} sucessfully triggered."}
Esempio n. 4
0
async def get_events(self):
    """
    Fetches any events that have not been dispersed to clients.

    :async:
    :return: List[msa.core.event.Event]
    """
    response = await self.client.get("/signals/events")

    if not response:
        return
    if response.status != "success":
        raise Exception(response.raw)

    # load disburse event
    disburse_event = Event.deserialize(response.json)

    # load sent events
    deserialized_events = []
    for raw_event in disburse_event.data["events"]:
        new_event = Event.deserialize(raw_event)
        deserialized_events.append(new_event)

    return deserialized_events
Esempio n. 5
0
    async def connect(self):
        async with aiohttp.ClientSession() as session:
            self.client_session = session
            async with session.ws_connect(self.base_url) as ws:
                self.ws = ws

                self.loop.create_task(self.interact())

                async def prop():
                    await self.propagate(self.propagate_queue)

                self.loop.create_task(prop())

                async for msg in ws:
                    if msg.type == aiohttp.WSMsgType.TEXT:
                        data = json.loads(msg.data)

                        if data["type"] == "response":
                            response = ApiResponse(data["payload"])

                        elif data["type"] == "event_propagate":
                            new_event = Event.deserialize(data["payload"])
                            new_event.network_propagate = False
                            if (
                                new_event.propagate_target == self.client_id
                                or new_event.propagate_target == "all"
                            ):
                                self.propagate_queue.put_nowait(new_event)
                            continue

                        elif data["type"] == "empty_response":
                            pass

                        elif data["type"] == "notify_id":
                            self.client_id = data["payload"]["id"]
                            continue
                        elif data["type"] == "error":
                            raise Exception(f"Bad request:\n{data['message']}")
                        else:
                            raise Exception("Bad payload response:", data)

                        self.queue.put_nowait(response)
Esempio n. 6
0
 def test_deserialize_event_type_does_not_exist(self):
     with self.assertRaises(Exception):
         Event.deserialize(
             {"event_type": "__this_event_type_does_not_exist"})
Esempio n. 7
0
 def test_deserialize_no_event_type(self):
     with self.assertRaises(Exception):
         Event.deserialize({})