Пример #1
0
    async def __adjust_balance(self, reply_to: PID, amount: float):
        if self.__refuse_permanently():
            self._processed_messages[reply_to.to_short_string()] = Refused()
            await reply_to.tell(Refused())

        if self.__busy():
            await reply_to.tell(ServiceUnavailable())

        # generate the behavior to be used whilst processing this message
        behaviour = self.__determine_processing_behavior()
        if behaviour == Behavior.FAIL_BEFORE_PROCESSING:
            await self.__failure(reply_to)

        await asyncio.sleep(
            timedelta(milliseconds=random.randint(0, 150)).total_seconds())

        self._balance += amount
        self._processed_messages[reply_to.to_short_string()] = OK()

        # simulate chance of failure after applying the change. This will
        # force a retry of the operation which will test the operation
        # is idempotent
        if behaviour == Behavior.FAIL_AFTER_PROCESSING:
            await self.__failure(reply_to)

        await reply_to.tell(OK())
def message_envelope():
    message = "test"
    sender = PID()
    sender.address = "test"
    sender.id = "test"
    header = MessageHeader()
    return MessageEnvelope(message, sender, header)
def test_create_new_message_envelope_with_sender(message_envelope):
    sender = PID()
    sender.address = "test"
    sender.id = "test"
    envelope = message_envelope.with_sender(sender)

    assert message_envelope.message == envelope.message
    assert sender == envelope.sender
    assert message_envelope.header == envelope.header
Пример #4
0
async def start(argv):
    tracer = init_jaeger_tracer()
    opentracing.set_global_tracer(tracer)

    middleware = open_tracing_middleware.open_tracing_sender_middleware(tracer)

    Serialization().register_file_descriptor(DESCRIPTOR)
    Remote().start("127.0.0.1", 12001)
    server = PID(address='127.0.0.1:8000', id='chatserver')
    context = RootContext(MessageHeader(), [middleware])

    props = OpenTracingFactory.get_props_with_open_tracing(Props.from_func(process_message), span_setup, span_setup,
                                                           tracer)

    client = context.spawn(props)
    await context.send(server, Connect(sender=client))

    nick = 'Alex'
    while True:
        text = input()
        if text == '/exit':
            return
        elif text.startswith('/nick '):
            new_nick = text.split(' ')[1]
            await context.send(server, NickRequest(old_user_name=nick, new_user_name=new_nick))
            nick = new_nick
        else:
            await context.send(server, SayRequest(user_name=nick, message=text))
Пример #5
0
def test_can_serialize_and_deserialize_protobuf():
    type_name = "actor.PID"
    pid = PID(address='123', id='456')
    data = Serialization().serialize(pid, 0)
    deserialized = Serialization().deserialize(type_name, data, 0)
    assert deserialized.address == "123"
    assert deserialized.id == "456"
Пример #6
0
async def main():
    context = RootContext()
    Serialization().register_file_descriptor(DESCRIPTOR)
    Remote().start("192.168.1.129", 12001)

    wg = asyncio.Event()
    message_count = 10000

    props = Props.from_producer(lambda: LocalClient(0, message_count, wg, asyncio.get_event_loop()))

    pid = context.spawn(props)
    remote = PID(address="192.168.1.77:12000", id="remote")

    await context.request_future(remote, StartRemote(Sender=pid))

    start = datetime.datetime.now()
    print('Starting to send')
    for i in range(message_count):
        await context.send(remote, Ping())
    await wg.wait()

    elapsed = datetime.datetime.now() - start
    print(f'Elapsed {elapsed}')

    t = message_count * 2.0 / elapsed.total_seconds()
    print(f'Throughput {t} msg / sec')

    input()
Пример #7
0
async def test_can_send_and_receive_to_existing_remote(remote_manager):
    remote_actor = PID(address=remote_manager.default_node_address,
                       id='EchoActorInstance')
    pong = await root_context.request_async(remote_actor,
                                            Ping(message="Hello"),
                                            timeout=timedelta(seconds=0.5))
    assert "%s Hello" % remote_manager.default_node_address == pong.message
Пример #8
0
 async def request(self, target: PID, message: any) -> None:
     with OpenTracingHelper.build_started_scope(
             self._tracer, OpenTracingHelper.get_parent_span(self._tracer),
             'request', message, self._send_span_setup) as scope:
         try:
             scope.span.set_tag('proto.targetpid', target.to_short_string())
             await super().request(target, message)
         except Exception as ex:
             OpenTracingHelper.setup_span(ex, scope.span)
             raise Exception()
Пример #9
0
async def test_when_remote_actor_not_found_request_async_timesout(
        remote_manager):
    unknown_remote_actor = PID(address=remote_manager.default_node_address,
                               id="doesn't exist")
    with pytest.raises(TimeoutError) as e:
        await root_context.request_async(unknown_remote_actor,
                                         Ping(message='Hello'),
                                         timeout=timedelta(seconds=0.2))

    assert 'TimeoutError' in str(e)
Пример #10
0
 async def request_future(
         self,
         target: PID,
         message: object,
         timeout: timedelta = None,
         cancellation_token: CancelToken = None) -> asyncio.Future:
     with OpenTracingHelper.build_started_scope(
             self._tracer, OpenTracingHelper.get_parent_span(self._tracer),
             'request_future', message, self._send_span_setup) as scope:
         try:
             scope.span.set_tag('proto.targetpid', target.to_short_string())
             return await super().request_future(target, message, timeout,
                                                 cancellation_token)
         except Exception as ex:
             OpenTracingHelper.setup_span(ex, scope.span)
             raise Exception()
Пример #11
0
 def partition_for_kind(address: str, kind: str) -> PID:
     return PID(address=address, id='partition-' + kind)
Пример #12
0
 def __already_processed(self, reply_to: PID):
     return reply_to.to_short_string() in self._processed_messages
Пример #13
0
 async def __reply(self, reply_to: PID):
     await reply_to.tell(
         self._processed_messages[reply_to.to_short_string()])