async def test_can_use_separate_stores():
    threading_events = {
        'process_started': threading.Event(),
        'process_get_state': threading.Event(),
        'process_get_index': threading.Event(),
        'process_request_snapshot': threading.Event(),
        'process_multiply': threading.Event()
    }

    actor_id = str(uuid.uuid4())
    event_store = InMemoryProvider()
    snapshot_store = InMemoryProvider()
    props = Props.from_producer(lambda: ExamplePersistentActor(
        threading_events, event_store, snapshot_store, actor_id)).with_mailbox(
            MockMailbox)
    pid = root_context.spawn(props)

    await root_context.send(pid, Multiply(2))
    threading_events['process_multiply'].wait()
    threading_events['process_multiply'].clear()

    event_store_messages = []
    await event_store.get_events(actor_id, 0, 1,
                                 lambda msg: event_store_messages.append(msg))
    assert len(event_store_messages) == 1

    snapshot_store_messages = []
    await snapshot_store.get_events(
        actor_id, 0, 1, lambda msg: snapshot_store_messages.append(msg))
    assert len(snapshot_store_messages) == 0
Exemplo n.º 2
0
 async def __process_start_loop_actor_message(self, context, message):
     if self._timer_started:
         return
     self._timer_started = True
     print('MyPersistenceActor - StartLoopActor')
     props = Props.from_producer(lambda: LoopActor())
     self._loop_actor = context.spawn(props)
Exemplo n.º 3
0
    async def setup(self) -> None:
        props = Props.from_producer(lambda: PidCacheWatcher()) \
            .with_guardian_supervisor_strategy(Supervision.always_restart_strategy)

        self._watcher = GlobalRootContext.spawn_named(props, 'PidCacheWatcher')
        self._cluster_topology_evn_sub = GlobalEventStream.subscribe(
            self.process_member_status_event, type(AbstractMemberStatusEvent))
Exemplo n.º 4
0
async def main():
    context = RootContext()
    props = Props.from_producer(HelloActor)
    pid = context.spawn(props)

    await context.send(pid, HelloMessage('Hello World!'))
    input()
Exemplo n.º 5
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()
async def test_can_change_states():
    test_actor_props = Props.from_producer(LightBulb)
    context = RootContext()
    actor = context.spawn(test_actor_props)
    assert await context.request_async(actor, PressSwitch()) == "Turning on"
    assert await context.request_async(actor, Touch())== "Hot!"
    assert await context.request_async(actor, PressSwitch()) == "Turning off"
    assert await context.request_async(actor, Touch()) == "Cold"
async def test_can_use_global_behaviour():
    context = RootContext()
    test_actor_props = Props.from_producer(LightBulb)
    actor = context.spawn(test_actor_props)
    _ = await context.request_async(actor, PressSwitch())
    assert await context.request_async(actor, HitWithHammer()) == "Smashed!"
    assert await context.request_async(actor, PressSwitch()) == "Broken"
    assert await context.request_async(actor, Touch()) == "OW!"
Exemplo n.º 8
0
async def main():
    context = RootContext()
    provider = InMemoryProvider()

    props = Props.from_producer(lambda: MyPersistenceActor(provider))
    pid = context.spawn(props)

    input()
Exemplo n.º 9
0
 def create_transfer(self, actor_name: str, from_account: PID,
                     to_account: PID, amount: float,
                     persistence_id: str) -> PID:
     transfer_props = Props.from_producer(lambda: TransferProcess(
         from_account, to_account, amount, self._provider, persistence_id,
         self._availability)).with_child_supervisor_strategy(
             OneForOneStrategy(
                 lambda pid, reason: SupervisorDirective.Restart,
                 self._retry_attempts, None))
     transfer = self._context.spawn_named(transfer_props, actor_name)
     return transfer
Exemplo n.º 10
0
    def __spawn_writer(self, address: str, context: AbstractContext) -> PID:
        writer_props = Props.from_producer(lambda: EndpointWriter(address,
                                                                  Remote().remote_config.channel_options,
                                                                  Remote().remote_config.call_options,
                                                                  Remote().remote_config.channel_credentials))

        writer_props = writer_props.with_mailbox(lambda: EndpointWriterMailbox(Remote()
                                                                               .remote_config
                                                                               .endpoint_writer_batch_size))
        writer = context.spawn(writer_props)
        return writer
Exemplo n.º 11
0
    async def receive(self, context: AbstractContext):
        if context.children is None or len(context.children) == 0:
            props = Props.from_producer(lambda: ChildActor())
            child = context.spawn(props)
        else:
            child = context.children[0]

        msg = context.message
        if isinstance(msg, Hello) or \
           isinstance(msg, Recoverable) or \
           isinstance(msg, Fatal):
            await context.forward(child)
        elif isinstance(msg, Terminated):
            print(f'Watched actor was Terminated, {msg.who}')
Exemplo n.º 12
0
async def main():
    tracer = init_jaeger_tracer()
    opentracing.set_global_tracer(tracer)
    GlobalEventStream.subscribe(process_dead_letter_event, DeadLetterEvent)

    context = RootContext(middleware=[open_tracing_sender_middleware()])

    props = Props.from_producer(lambda: ChildActor())
    props = OpenTracingFactory.get_props_with_open_tracing(props)

    actor = context.spawn(props)
    await context.send(actor, Hello(who="Alex"))

    await asyncio.sleep(1)
    await GlobalRootContext.stop_future(actor)

    input()
def create_test_actor(strategy):
    events = {'process_started': threading.Event(),
              'process_get_state': threading.Event(),
              'process_get_index': threading.Event(),
              'process_request_snapshot': threading.Event(),
              'process_multiply': threading.Event()}

    actor_id = str(uuid.uuid4())
    in_memory_provider = InMemoryProvider()
    props = Props.from_producer(lambda: ExamplePersistentActor(events,
                                                               in_memory_provider,
                                                               in_memory_provider,
                                                               actor_id,
                                                               strategy)).with_mailbox(MockMailbox)
    pid = root_context.spawn(props)

    return events, pid, props, actor_id, in_memory_provider
Exemplo n.º 14
0
 async def receive(self, context: AbstractContext):
     msg = context.message
     if isinstance(msg, Started):
         pid = context.spawn(Props.from_producer(ScheduleGreetActor))
         await self._scheduler.schedule_tell_once(
             timedelta(milliseconds=100), context.my_self,
             SimpleMessage('test 1'))
         await self._scheduler.schedule_tell_once(
             timedelta(milliseconds=200), context.my_self,
             SimpleMessage('test 2'))
         await self._scheduler.schedule_tell_once(
             timedelta(milliseconds=300), context.my_self,
             SimpleMessage('test 3'))
         await self._scheduler.schedule_tell_once(
             timedelta(milliseconds=400), context.my_self,
             SimpleMessage('test 4'))
         await self._scheduler.schedule_tell_once(
             timedelta(milliseconds=500), context.my_self,
             SimpleMessage('test 5'))
         await self._scheduler.schedule_request_once(
             timedelta(seconds=1), context.my_self, pid, Greet('Daniel'))
         await self._scheduler.schedule_tell_once(timedelta(seconds=5),
                                                  context.my_self, Hello())
     elif isinstance(msg, Hello):
         print(
             "Hello Once, let's give you a hickup every 0.5 second starting in 3 seconds!"
         )
         await self._scheduler.schedule_tell_repeatedly(
             timedelta(seconds=3), timedelta(milliseconds=500),
             context.my_self, HickUp(), self._timer)
     elif isinstance(msg, HickUp):
         self._counter += 1
         print('Hello!')
         if self._counter == 5:
             self._timer.trigger()
             await context.send(context.my_self, AbortHickUp())
     elif isinstance(msg, AbortHickUp):
         print(f'Aborted hickup after {self._counter} times')
         print('All this was scheduled calls, have fun!')
     elif isinstance(msg, Greet):
         print(f'Thanks {msg.who()}')
     elif isinstance(msg, SimpleMessage):
         print(msg.msg())
Exemplo n.º 15
0
async def main():
    context = RootContext()
    number_of_transfers = 5
    interval_between_console_updates = 1
    uptime = 99.99
    retry_attempts = 0
    refusal_probability = 0.01
    busy_probability = 0.01
    verbose = False

    props = Props.from_producer(lambda: Runner(
        number_of_transfers, interval_between_console_updates, uptime,
        refusal_probability, busy_probability, retry_attempts, verbose
    )).with_child_supervisor_strategy(
        OneForOneStrategy(lambda pid, reason: SupervisorDirective.Restart,
                          retry_attempts, None))

    print('Spawning runner')
    context.spawn_named(props, 'runner')
    input()
Exemplo n.º 16
0
async def main():
    context = RootContext()

    logging.basicConfig(
        format='%(name)s - %(levelname)s - %(message)s %(stack_info)s',
        level=logging.DEBUG,
        handlers=[logging.StreamHandler(sys.stdout)])

    props = Props.from_producer(
        lambda: ParentActor()).with_child_supervisor_strategy(
            OneForOneStrategy(Decider.decide, 1, None))
    actor = context.spawn(props)
    await context.send(actor, Hello('Alex'))
    await context.send(actor, Recoverable())
    await context.send(actor, Fatal())

    await asyncio.sleep(1)
    await context.stop(actor)

    input()
Exemplo n.º 17
0
 def __try_debit(target_actor: PID, amount: float) -> Props:
     return Props.from_producer(lambda: AccountProxy(
         target_actor, lambda sender: Debit(amount, sender)))
Exemplo n.º 18
0
 def __spawn_watcher(self, address: str, context: AbstractContext) -> PID:
     watcher_props = Props.from_producer(lambda: EndpointWatcher(address))
     watcher = context.spawn(watcher_props)
     return watcher
import asyncio
import logging
import threading
from datetime import timedelta

import pytest

from protoactor.actor.actor import Actor
from protoactor.actor.actor_context import RootContext, AbstractContext
from protoactor.actor.props import Props
from protoactor.router.messages import RemoveRoutee, GetRoutees, AddRoutee, BroadcastMessage
from protoactor.router.router import Router

context = RootContext()
timeout = timedelta(milliseconds=1000)
my_actor_props = Props.from_producer(lambda: MyTestActor())


@pytest.mark.asyncio
async def test_broadcast_group_router_all_routees_receive_messages():
    router, routee1, routee2, routee3 = create_broadcast_group_router_with3_routees(
    )

    await context.send(router, 'hello')

    assert await context.request_future(routee1, 'received?',
                                        timeout) == 'hello'
    assert await context.request_future(routee2, 'received?',
                                        timeout) == 'hello'
    assert await context.request_future(routee3, 'received?',
                                        timeout) == 'hello'
Exemplo n.º 20
0
from datetime import timedelta

import pytest

from protoactor.actor.actor import RootContext, Actor, AbstractContext
from protoactor.actor.props import Props
from protoactor.router.messages import RemoveRoutee, GetRoutees, AddRoutee, BroadcastMessage
from protoactor.router.router import Router
from tests.test_fixtures.test_mailbox import MockMailbox

context = RootContext()
timeout = timedelta(milliseconds=1000)
my_actor_props = Props.from_producer(lambda: MyTestActor()).with_mailbox(
    MockMailbox)


@pytest.mark.asyncio
async def test_round_robin_group_router_routees_receive_messages_in_round_robin_style(
):
    router, routee1, routee2, routee3 = create_router_with3_routees()

    await context.send(router, '1')

    # only routee1 has received the message
    assert await context.request_async(routee1, 'received?', timeout) == '1'
    assert await context.request_async(routee2, 'received?', timeout) is None
    assert await context.request_async(routee3, 'received?', timeout) is None

    await context.send(router, '2')
    await context.send(router, '3')
Exemplo n.º 21
0
async def main():
    context = RootContext()
    props = Props.from_producer(ScheduleActor)
    pid = context.spawn(props)

    input()
Exemplo n.º 22
0
async def spawn_local_actor_and_watch(remote_actors):
    props = Props.from_producer(lambda: LocalActor(remote_actors))
    actor = root_context.spawn(props)
    await asyncio.sleep(2)
    return actor
Exemplo n.º 23
0
 def __create_account(self, name: str) -> PID:
     account_props = Props.from_producer(
         lambda: Account(name, self._uptime, self._refusal_probability, self
                         ._busy_probability))
     return self._context.spawn_named(account_props, name)
Exemplo n.º 24
0
async def main():
    context = RootContext()
    Serialization().register_file_descriptor(DESCRIPTOR)
    Remote().start("192.168.1.77", 12000)
    context.spawn_named(Props.from_producer(lambda: EchoActor()), 'remote')
    input()
Exemplo n.º 25
0
    async def spawn_partition_actor(kind: str) -> PID:
        props = Props.from_producer(lambda: PartitionActor(kind)) \
            .with_guardian_supervisor_strategy(Supervision.always_restart_strategy)

        return GlobalRootContext.spawn_named(props, 'partition-' + kind)
Exemplo n.º 26
0
            for i in range(msg.div):
                child = GlobalRootContext.spawn(props)
                await context.request(
                    child,
                    Request(num=msg.num + i * (msg.size // msg.div),
                            size=msg.size // msg.div,
                            div=msg.div))
        elif isinstance(msg, int):
            self._sum += msg
            self._replies -= 1
            if self._replies == 0:
                await context.send(self._reply_to, self._sum)


props = Props.from_producer(MyActor)


async def main():
    context = RootContext()
    pr = cProfile.Profile()
    while True:
        pid = context.spawn(props)
        pr.clear()
        pr.enable()
        response = await context.request_future(
            pid, Request(num=0, size=100, div=10))
        pr.disable()
        pr.print_stats(sort='time')
        print(response)
        await context.stop_future(pid)