示例#1
0
    async def validate_msg(self, msg_forwarder: ID, msg: rpc_pb2.Message) -> None:
        """
        Validate the received message
        :param msg_forwarder: the peer who forward us the message.
        :param msg: the message.
        """
        sync_topic_validators = []
        async_topic_validator_futures: List[Awaitable[bool]] = []
        for topic_validator in self.get_msg_validators(msg):
            if topic_validator.is_async:
                async_topic_validator_futures.append(
                    cast(Awaitable[bool], topic_validator.validator(msg_forwarder, msg))
                )
            else:
                sync_topic_validators.append(
                    cast(SyncValidatorFn, topic_validator.validator)
                )

        for validator in sync_topic_validators:
            if not validator(msg_forwarder, msg):
                raise ValidationError(f"Validation failed for msg={msg}")

        # TODO: Implement throttle on async validators

        if len(async_topic_validator_futures) > 0:
            results = await asyncio.gather(*async_topic_validator_futures)
            if not all(results):
                raise ValidationError(f"Validation failed for msg={msg}")
示例#2
0
    async def validate_msg(self, msg_forwarder: ID,
                           msg: rpc_pb2.Message) -> None:
        """
        Validate the received message.

        :param msg_forwarder: the peer who forward us the message.
        :param msg: the message.
        """
        sync_topic_validators: List[SyncValidatorFn] = []
        async_topic_validators: List[AsyncValidatorFn] = []
        for topic_validator in self.get_msg_validators(msg):
            if topic_validator.is_async:
                async_topic_validators.append(
                    cast(AsyncValidatorFn, topic_validator.validator))
            else:
                sync_topic_validators.append(
                    cast(SyncValidatorFn, topic_validator.validator))

        for validator in sync_topic_validators:
            if not validator(msg_forwarder, msg):
                raise ValidationError(f"Validation failed for msg={msg}")

        # TODO: Implement throttle on async validators

        if len(async_topic_validators) > 0:
            # TODO: Use a better pattern
            final_result: bool = True

            async def run_async_validator(func: AsyncValidatorFn) -> None:
                nonlocal final_result
                result = await func(msg_forwarder, msg)
                final_result = final_result and result

            async with trio.open_nursery() as nursery:
                for async_validator in async_topic_validators:
                    nursery.start_soon(run_async_validator, async_validator)

            if not final_result:
                raise ValidationError(f"Validation failed for msg={msg}")