Package: actorio
Actorio - a simple actor framework for asyncioActorio is a Python asyncio implementation of theactor model.There already are Python actor model implementation such asThespianorPykkabut they're currently lacking asyncio support.The main goal of the Actor model is to cleanly define the critical section
without having to deal with lock or any other synchronization mechanism.It also helps with theSingle responsibility principle,
eachActorclass should deal with one part of the fonctionnal requirements of the application and its API can be properly defined
(ie, what kind of message does this actor accept and what kind of message does it produce), hence making actor testing easier,
since you don't have to mock the surrounding systems and just check if the message sequence if correct.Current API is crude and provisional and is likely to change as syntax and concepts evolve.Rules of the actor modelAn actor is an execution unit that executes concurrently with other actors.An actor does not share state with anybody else, but it can have its own state.An actor can only communicate with other actors by sending and receiving messages. It can only send messages to actors whose address it has.When an actor receives a message it may take actions like:altering its own state, e.g. so that it can react differently to a future messagesending messages to other actorsstarting new actorsNone of the actions are required, and they may be applied in any order.An actor only processes one message at a time. In other words, a single actor does not give you any concurrency, and it does not need to use locks internally to protect its own state.Hello WorldA Hello world example:Let's start with the typical example of Hello World. In this case, we'll create an Actor, send it a message, wait for a response message, and print that response:fromactorioimportActor,Message,DataMessage,askimportasyncioclassGreeter(Actor):# Here we override the handle_message method to send a `DataMessage` with the data "Hello World!".asyncdefhandle_message(self,message:Message):awaitmessage.sender.tell(DataMessage(data="Hello World!",sender=self))asyncdefmain():# Let's create an instance of a Greeter actor and start it.asyncwithGreeter()asgreeter:# Then we'll just send it an empty message and wait for a responsereply:DataMessage=awaitask(greeter,Message())print(reply.data)asyncio.get_event_loop().run_until_complete(main())Actor spawning actorsActor instances can spawn other actors during their execution. be it at startup, in themainloop_setupasync method or as a reaction to an event in any handler.The actor should first be instanciated (with an__init__call) then be registered on its parent with aregister_childasync call.Whenever a child dies, the parenthandle_child_stoppedasync method is called with the child actor object and theasyncio.taskobject for its execution loop. This way, the parent can take any action required.For example, if we had to handle blocking operations. we could do something like:importrandomimportasynciofromactorioimportActor,Message,DataMessage,EndMainLoop,Referenceasyncdefblocking_operation():#for the sake of this example, the blocking operation is a sleepsleep_time=random.randint(0,10)awaitasyncio.sleep(sleep_time)returnsleep_timeclassRequestMessage(Message):"""A request to do some computation or blocking call"""classResponseMessage(DataMessage):"""The result of a computation"""classWorker(Actor):# Here we override the handle_message method to send a `ResponseMessage`# with the result of the blocking operation as its data.asyncdefhandle_message(self,message:Message):sleep_time=awaitblocking_operation()awaitmessage.sender.tell(ResponseMessage(data=sleep_time,sender=self))# This actor only deals with one message then stops,# raising an EndMainLoop exeception here will properly stop the actorraiseEndMainLoop()classManager(Actor):asyncdefhandle_message(self,message:Message):ifisinstance(message,RequestMessage):# We spawn and register the new child, we get its reference backchild=awaitself.register_child(Worker())# We just transfer the message to the child, that way,# we won't have to process its responseawaitchild.tell(message)asyncdefmain():# We create an inbox for us, this is not an actor,# just somewhere actors can send messagesme=Reference()asyncwithManager()asmanager:# Then we start 10 long computationsfor_inrange(10):awaitmanager.tell(RequestMessage(sender=me))# Then we'll listen to our inbox# to get the responses as they come byfor_inrange(10):message=awaitme.inbox.get()print("Got a response with result{}".format(message.data))asyncio.get_event_loop().run_until_complete(main())Handling external blocking eventsUsing message is great, but, most of the time, we also need to use other APIs that don't provide a message-based interface.It's possible to register external blocking event and handler for those with theregister_input_taskmethod.
This methods takes a factory function for a coroutine and an async function to handle the task result.The handler will not be called if the Actor is currently busy processing anything else
(like a message or any other task), this way, there is no concurrency issue
and each handler is called with a clean actor stateFor now, the order in which those events will be handled is not necessarily the order in which they happenedFor example, to use anaiohttpwebsocket :importaiohttpfromaiohttpimportwebfromactorioimportActor,EndMainLoopimportasyncioclassClient(Actor):def__init__(self,websocket:web.WebSocketResponse):self.websocket=websocketsuper().__init__()# Here we define an input task handler,# It will be called each time its registered event happens.# The resulting `asyncio.Task` object will be passed as argument,# this way, the handler can deal with any exception raised during event collectionasyncdefhandle_websocket_event(self,task:asyncio.Task):try:msg=task.result()exceptExceptionase:# In case of any exception, we just stop the Actorself.logger.exception(e)raiseEndMainLoop()ifmsg.type==aiohttp.WSMsgType.TEXT:# if we receive text, we just send it back# We could also just send a message to our inboxawaitself.websocket.send_str(msg.data)else:# any other request just stops the ActorraiseEndMainLoop()asyncdefmainloop_setup(self):self.register_input_task(self.websocket.receive,self.handle_websocket_event)awaitsuper().mainloop_setup()asyncdefwebsocket_handler(request):ws=web.WebSocketResponse()awaitws.prepare(request)client_actor=Client(websocket=ws)asyncwithclient_actor:# We until the client's mainloop endsawaitclient_actorreturnwsapp=web.Application()app.add_routes([web.get('/',websocket_handler)])web.run_app(app)You can then connect to the websocket and send it some messages, it will act as an echo server.