コード例 #1
0
async def main():
    context = RootContext()
    props = Props.from_producer(HelloActor)
    pid = context.spawn(props)

    await context.send(pid, HelloMessage('Hello World!'))
    input()
コード例 #2
0
async def run_round_robin_pool_test():
    context = RootContext()
    props = Router.new_round_robin_pool(my_actor_props, 5)
    pid = context.spawn(props)

    for i in range(10):
        await context.send(pid, Message('%s' % (i % 4)))
コード例 #3
0
async def main():
    context = RootContext()
    props = Props.from_func(hello_function)
    pid = context.spawn(props)

    reply = await context.request_async(pid, HelloMessage('Hello'))
    print(reply)
コード例 #4
0
async def run_broadcast_pool_test():
    context = RootContext()
    props = Router.new_broadcast_pool(my_actor_props, 5)

    for i in range(10):
        pid = context.spawn(props)
        await context.send(pid, Message('%s' % (i % 4)))
コード例 #5
0
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!"
コード例 #6
0
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"
コード例 #7
0
async def run_random_group_test():
    context = RootContext()
    props = Router.new_random_group([
        context.spawn(my_actor_props),
        context.spawn(my_actor_props),
        context.spawn(my_actor_props),
        context.spawn(my_actor_props)
    ])

    pid = context.spawn(props)
    for i in range(10):
        await context.send(pid, Message('%s' % (i % 4)))
コード例 #8
0
async def start(argv):
    host = None
    port = None
    opts, args = getopt.getopt(argv, "hp", ["host=", "port="])
    for opt, arg in opts:
        if opt == '--host':
            host = arg
        elif opt == '--port':
            port = arg

    Serialization().register_file_descriptor(DESCRIPTOR)

    context = RootContext()
    Remote().start(host, port)
    props = Props().from_producer(lambda: EchoActor(host, port))
    Remote().register_known_kind('EchoActor', props)
    context.spawn_named(props, "EchoActorInstance")

    input()
コード例 #9
0
async def test_pop_behavior_should_restore_pushed_behavior():
    behavior = Behavior()

    async def func_1(ctx):
        if isinstance(ctx.message, str):
            async def func_2(ctx2):
                await ctx2.respond(42)
                behavior.unbecome_stacked()

            behavior.become_stacked(func_2)
            await ctx.respond(ctx.message)

    behavior.become(func_1)

    props = Props.from_func(behavior.receive_async)
    context = RootContext()
    pid = context.spawn(props)

    reply = await context.request_async(pid, "number")
    reply_after_push = await context.request_async(pid, None)
    reply_after_pop = await context.request_async(pid, "answertolifetheuniverseandeverything")

    assert reply + str(reply_after_push) + reply_after_pop == "number42answertolifetheuniverseandeverything"
コード例 #10
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')
コード例 #11
0
async def main():
    headers = MessageHeader({
        'TraceID': str(uuid.uuid4()),
        'SpanID': str(uuid.uuid4())
    })

    def get_middleware(next_middleware):
        async def process(context, target, envelope):
            new_envelope = envelope \
                .with_header(key='TraceID', value=context.headers.get('TraceID')) \
                .with_header(key='SpanID', value=str(uuid.uuid4())) \
                .with_header(key='ParentSpanID', value=context.headers.get('SpanID'))

            print(' 1 Enter RootContext SenderMiddleware')
            print(' 1 TraceID: ' + new_envelope.header.get('TraceID'))
            print(' 1 SpanID: ' + new_envelope.header.get('SpanID'))
            print(' 1 ParentSpanID: ' +
                  new_envelope.header.get('ParentSpanID'))
            await next_middleware(context, target, new_envelope)
            print(
                ' 1 Exit RootContext SenderMiddleware - Send is async, this is out of order by design'
            )

        return process

    root = RootContext(headers, [get_middleware])

    async def actor_logic(context):
        if isinstance(context.message, str):
            print('   3 Enter Actor')
            print('   3 TraceID = ' + context.headers.get('TraceID'))
            print('   3 SpanID = ' + context.headers.get('SpanID'))
            print('   3 ParentSpanID = ' + context.headers.get('ParentSpanID'))
            print('   3 actor got = %s:%s' %
                  (str(type(context.message)), context.message))
            await context.respond("World !")
            print('   3 Exit Actor')

    def get_receive_middleware(next_middleware):
        async def process(context, envelope):
            if isinstance(envelope.message, str):
                new_envelope = envelope \
                    .with_header(key='TraceID', value=envelope.header.get('TraceID')) \
                    .with_header(key='SpanID', value=str(uuid.uuid4())) \
                    .with_header(key='ParentSpanID', value=envelope.header.get('SpanID'))

                print('  2 Enter Actor ReceiverMiddleware')
                print('  2 TraceID: ' + new_envelope.header.get('TraceID'))
                print('  2 SpanID: ' + new_envelope.header.get('SpanID'))
                print('  2 ParentSpanID: ' +
                      new_envelope.header.get('ParentSpanID'))
                await next_middleware(context, new_envelope)
                print('  2 Exit Actor ReceiverMiddleware')
            else:
                await next_middleware(context, envelope)

        return process

    def get_sender_middleware(next_middleware):
        async def process(context, target, envelope):
            new_envelope = envelope \
                .with_header(key='TraceID', value=context.headers.get('TraceID')) \
                .with_header(key='SpanID', value=str(uuid.uuid4())) \
                .with_header(key='ParentSpanID', value=context.headers.get('SpanID'))

            print('    4 Enter Actor SenderMiddleware')
            print('    4 TraceID: ' + new_envelope.header.get('TraceID'))
            print('    4 SpanID: ' + new_envelope.header.get('SpanID'))
            print('    4 ParentSpanID: ' +
                  new_envelope.header.get('ParentSpanID'))
            await next_middleware(context, target, envelope)
            print('    4 Exit Actor SenderMiddleware')

        return process

    actor = Props.from_func(actor_logic)\
            .with_receive_middleware([get_receive_middleware])\
            .with_sender_middleware([get_sender_middleware])

    pid = root.spawn(actor)

    print('0 TraceID: ' + root.headers.get('TraceID'))
    print('0 SpanID: ' + root.headers.get('SpanID'))
    print('0 ParentSpanID: ' + root.headers.get('ParentSpanID', ''))

    res = await root.request_async(pid, "hello")
    print('Got result ' + res)

    await asyncio.sleep(0.5)
コード例 #12
0
import sys
import threading
import uuid
from datetime import timedelta

import pytest

from protoactor.actor.actor import RootContext, Actor, AbstractContext
from protoactor.actor.messages import Started
from protoactor.actor.props import Props
from protoactor.persistence.persistence import Persistence
from tests.persistence.in_memory_provider import InMemoryProvider
from tests.test_fixtures.mock_mailbox import MockMailbox

root_context = RootContext()
initial_state = 1


@pytest.mark.asyncio
async def test_events_are_saved_to_persistence():
    def callback(o):
        assert isinstance(o, Multiplied)
        assert o.amount == 2

    _, pid, _, actor_id, provider_state = create_test_actor()
    await root_context.send(pid, Multiply(2))
    await provider_state.get_events(actor_id, 0, sys.maxsize, callback)


@pytest.mark.asyncio
async def test_snapshots_are_saved_to_persistence():