cl-gserver

cl-gserver

Erlang风格的消息传递Actor框架

Sento框架实现了Actor、Agent和Router等核心概念,支持异步和同步的ask/tell操作。它还提供事件流功能和并发任务API,可用于构建响应式、并行计算和事件驱动的系统。该框架适用于开发自动化工具、网络通信和高吞吐量Web服务器等需要高并发处理的应用。

SentoActor框架消息传递并行计算事件处理Github开源项目

CI

Introduction - Actor framework featuring actors and agents

Sento is a 'message passing' library/framework with actors similar to Erlang or Akka. It supports creating systems that should work reactive, require parallel computing and event based message handling.

Sento features:

  • Actors with ask (?) and tell (!) operations. ask can be asynchronous or synchronous.
  • Agents: Agents are a specialization of Actors for wrapping state with a standardized interface of init, get and set. There are also specialized Agents for Common Lisps array and hash-map data structures.
  • Router: Router offers a similar interface as Actor with ask and tell but collects multiple Actors for load-balancing.
  • EventStream: all Actors and Agents are connected to an EventStream and can subscribe to messages or publish messages. This is similar to an event-bus.
  • Tasks: a simple API for concurrency.

Intro

(Please also checkout the API documentation for further information) (for migrations from Sento v2, please check below migration guide)

Projects using Sento (for example usage):

Creating an actor-system

The first thing you wanna do is to create an actor system. In simple terms, an actor system is a container where all actors live in. So at any time the actor system knows which actors exist.

To create an actor system we can first change package to :sento-user because it imports the majority of necessary namespaces fopr convenience. Then, do:

(defvar *system* (make-actor-system))

When we look at *system* in the repl we see some information of the actor system:

#<ACTOR-SYSTEM config: (DISPATCHERS (SHARED (WORKERS 4 STRATEGY RANDOM)) TIMEOUT-TIMER (RESOLUTION 500 MAX-SIZE 1000) EVENTSTREAM (DISPATCHER-ID SHARED) SCHEDULER (ENABLED TRUE RESOLUTION 100 MAX-SIZE 500) ), user actors: 0, internal actors: 5>

The actor-system has, by default, four shared message dispatcher workers. Depending on how busy the system tends to be this default can be increased. Those four workers are part of the 'internal actors'. The 5th actor drives the event-stream (later more on that, but in a nutshell it's something like an event bus).

There are none 'user actors' yet, and the 'config' is the default config specifying the number of message dispatch workers (4) and the strategy they use to balance throughput, 'random' here.

Using a custom config is it possible to change much of those defaults. For instance, create custom dispatchers, i.e. a dedicated dispatcher used for the 'Tasks' api (see later for more info). The event-stream by default uses the global 'shared' dispatcher. Changing the config it would be possible to have the event-stream actor use a :pinned dispatcher (more on dispatchers later) to optimize throughput. Etc.

Actors live in the actor system, but more concrete in an actor-context. An actor-context contains a collection (of actors) and represents a Common Lisp protocol that defines a set of generic functions for creating, removing and finding actors in an actor-context. The actor system itself is also implementing the actor-context protocol, so it also acts as such and hence the protocol ac (actor-context) is used to operate on the actor system.

I.e. to shutdown the actor system one has to execute: (ac:shutdown *system*).

Creating and using actors

Now we want to create actors.

(actor-of *system* :name "answerer" :receive (lambda (msg) (let ((output (format nil "Hello ~a" msg))) (reply output))))

This creates an actor in *system*. Notice that the actor is not assigned to a variable (but you can). It is now registered in the system. Using function ac:find-actors you'll be able to find it again. Of course it makes sense to store important actors that are frequently used in a defparameter variable.

The :receive key argument to actor-of is a function which implements the message processing behaviour of an actor. The parameter to the 'receive' function is just the received message (msg).

actor-of also allows to specify the initial state, a name, and a custom actor type via key parameters. By default a standard actor of type 'actor is created. It is possible to subclass 'actor and specify your own. It is further possible to specify an 'after initialization' function, using the :init key, and 'after destroy' function using :destroy keyword. :init can, for example, be used to subscribe to the event-stream for listening to important messages.

The return value of 'receive' function is only used when using the synchronous ask-s function to 'ask' the actor. Using ask (equivalent: ?) the return value is ignored. If an answer should be provided to an asking actor, or if replying is part of an interface contract, then reply should be used.

The above actor was stored to a variable *answerer*. We can evaluate this in repl and see:

#<ACTOR path: /user/answerer, cell: #<ACTOR answerer, running: T, state: NIL, message-box: #<SENTO.MESSAGEB:MESSAGE-BOX/DP mesgb-1356, processed messages: 1, max-queue-size: 0, queue: #<SENTO.QUEUE:QUEUE-UNBOUNDED 82701A6D13>>>>

We'll see the 'path' of the actor. The prefix '/user' means that the actor was created in a user actor context of the actor system. Further we see whether the actor is 'running', its 'state' and the used 'message-box' type, by default it uses an unbounded queue.

Now, when sending a message using 'ask' pattern to the above actor like so:

(? *answerer* "FooBar")

we'll get a 'future' as result, because ?/ask is asynchronous.

#<FUTURE promise: #<BLACKBIRD-BASE:PROMISE finished: NIL errored: NIL forward: NIL 80100E8B7B>>

We can check for a 'future' result. By now the answer from the *answerer* (via reply) should be available:

USER> (fresult *) "Hello FooBar"

If the reply had not been received yet, fresult would return :not-ready. So, fresult doesn't block, it is necessary to repeatedly probe using fresult until result is other than :not-ready.

A nicer and asynchronous way without querying is to use fcompleted. Using fcompleted you setup a callback function that is called with the result when it is available. Like this:

(fcompleted (? *answerer* "Buzz") (result) (format t "The answer is: ~a~%" result))

Which will asynchronously print "The answer is: Hello Buzz" after a short while. This will also work when the ask/? was used with a timeout, in which case result will be a tuple of (:handler-error . <ask-timeout condition>) if the operation timed out.

Creating child actors

To build actor hierarchies one has to create actors in actors. This is of course possible. There are two options for this.

  1. Actors are created as part of actor-ofs :init function like so:
(actor-of *system* :name "answerer-with-child" :receive (lambda (msg) (let ((output (format nil "Hello ~a" msg))) (reply output))) :init (lambda (self) (actor-of self :name "child-answerer" :receive (lambda (msg) (let ((output (format nil "Hello-child ~a" msg))) (format nil "~a~%" output))))))

Notice the context for creating 'child-answerer', it is self, which is 'answerer-with-child'.

  1. Or it is possible externally like so:
(actor-of *answerer* :name "child-answerer" :receive (lambda (msg) (let ((output (format nil "~a" "Hello-child ~a" msg))) (format nil "~a~%" output))))

This uses *answerer* context as parameter of actor-of. But has the same effect as above.

Now we can check if there is an actor in context of 'answerer-with-child':

USER> (all-actors *actor-with-child*) (#<ACTOR path: /user/answerer-with-child/child-answerer, cell: #<ACTOR child-answerer, running: T, state: NIL, message-box: #<SENTO.MESSAGEB:MESSAGE-BOX/DP mesgb-1374, processed messages: 0, max-queue-size: 0, queue: #<SENTO.QUEUE:QUEUE-UNBOUNDED 8200A195FB>>>>)

The 'path' is what we expected: '/user/answerer-with-child/child-answerer'.

Ping Pong

Another example that only works with tell/! (fire and forget).

We have those two actors.

The 'ping' actor:

(defparameter *ping* (actor-of *system* :receive (lambda (msg) (cond ((consp msg) (case (car msg) (:start-ping (progn (format t "Starting ping...~%") (! (cdr msg) :ping *self*))))) ((eq msg :pong) (progn (format t "pong~%") (sleep 2) (reply :ping)))))))

And the 'pong' actor:

(defparameter *pong* (actor-of *system* :receive (lambda (msg) (case msg (:ping (progn (format t "ping~%") (sleep 2) (reply :pong)))))))

The 'ping' actor understands a :start-ping message which is a cons and has as cdr the 'pong' actor instance. It also understands a :pong message as received from 'pong' actor.

The 'pong' actor only understands a :ping message. Each of the actors respond with either :ping or :pong respectively after waiting 2 seconds.

We trigger the ping-pong by doing:

(! *ping* `(:start-ping . ,*pong*))

And then see in the console like:

Starting ping... ping pong ping ...

To stop the ping-pong one just has to send (! *ping* :stop) to one of them.

:stop will completely stop the actors message processing, and the actor will not be useable anymore.

Synchronous ask

At last an example for the synchronous 'ask', ask-s. It is insofar similar to ask that it provides a result to the caller. However, it is not bound to reply as with ask. Here, the return value of the 'receive' function is returned to the caller, and ask-s will block until 'receive' function returns.
Beware that ask-s will dead-lock your actor when ask-s is used to call itself.
Let's make an example:

(defparameter *s-asker* (actor-of *system* :receive (lambda (msg) (cond ((stringp msg) (format nil "Hello ~a" msg)) (t (format nil "Unknown message!"))))))

So we can do:

USER> (ask-s *s-asker* "Foo") "Hello Foo" USER> (ask-s *s-asker* 'foo) "Unknown message!"

Dispatchers :pinned vs. :shared

Dispatchers are somewhat alike thread pools. Dispatchers of the :shared type are a pool of workers. Workers are actors using a :pinned dispatcher. :pinned just means that an actor spawns its own mailbox thread.

So :pinned and :shared are types of dispatchers. :pinned spawns its own mailbox thread, :shared uses a worker pool to handle the mailbox messages.

By default an actor created using actor-of uses a :shared dispatcher type which uses the shared message dispatcher that is automatically setup in the system.

When creating an actor it is possible to specify the dispatcher-id. This parameter specifies which 'dispatcher' should handle the mailbox queue/messages.

Please see below for more info on dispatchers.

Finding actors in the context

If actors are not directly stored in a dynamic or lexical context they can still be looked up and used. The actor-context protocol contains a function find-actors which can lookup actors in various ways. Checkout the API documentation.

Mapping futures with fmap

Let's asume we have such a simple actor that just increments the value passed to it.

(defparameter *incer*
  (actor-of *system*
            :receive (lambda (value)
                       (reply (1+ value)))))

Since ask returns a future it is possible to map multiple ask operations like this:

(-> (ask *incer* 0)
  (fmap (result)
      (ask *incer* result))
  (fmap (result)
      (ask *incer* result))
  (fcompleted (result)
      (format t "result: ~a~%" result)
    (assert (= result 3))))

ask-s and ask with timeout

A timeout (in seconds) can be specified for both ask-s and ask and is done like so:

To demonstrate this we could setup an example 'sleeper' actor:

(ac:actor-of *system* :receive (lambda (msg) (sleep 5)))

If we store this to *sleeper* and do the following, the ask-s will return a handler-error with an ask-timeout condition.

(act:ask-s *sleeper* "Foo" :time-out 2)
(:HANDLER-ERROR . #<CL-GSERVER.UTILS:ASK-TIMEOUT #x30200319F97D>)

This works similar with the ask only that the future will be fulfilled with the handler-error cons.

To get a readable error message of the condition we can do:

CL-USER> (format t "~a" (cdr *))
A timeout set to 2 seconds occurred. Cause: 
#<BORDEAUX-THREADS:TIMEOUT #x302002FAB73D> 

Note that ask-s uses the calling thread for the timeout checks.
ask uses a wheel timer to handle timeouts. The default resolution for ask timeouts is 500ms with a maximum size of wheel slots (registered timeouts) of 1000. What this means is that you can have timeouts of a multiple of 500ms and 1000 ask operations with timeouts. This default can be tweaked when creating an actor-system, see API documentation for more details.

Long running and asynchronous operations in receive

Be careful with doing long running computations in the receive function message handler, because it will block message processing. It is advised to use a third-party thread-pool or a library like lparallel to do the computations with, and return early from the receive message handler.

The computation result can be 'awaited' for in an asynchronous manner and a response to *sender* can be sent manually (via reply). The sender of the original message is set to the dynamic variable *sender*.

Due to an asynchronous callback of a computation running is a separate thread, the *sender* must be copied into a lexical environment because at the time of when the callback is executed the *sender* can have a different value.

For instance, if there is a potentially long running and asynchronous operation happening in 'receive', the original sender must be captured and the async operation executed in a lexical context, like so (receive function):

(lambda (msg) (case msg (:do-lengthy-op (let ((sender *sender*)) ;; do lengthy computation (reply :my-later-reply sender))) (otherwise ;; do other non async stuff (reply :my-reply))))

Notice that for the lengthy operation the sender must be captured because if the lengthy operation is asynchronous 'receive' function is perhaps called for another message where *sender* is different. In that case sender must be supplied explicitly for reply.

See this test for more info.

NOTE: you should not change actor state from within an asynchronously executed operation in receive. This is not

编辑推荐精选

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

iTerms

iTerms

企业专属的AI法律顾问

iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。

SimilarWeb流量提升

SimilarWeb流量提升

稳定高效的流量提升解决方案,助力品牌曝光

稳定高效的流量提升解决方案,助力品牌曝光

Sora2视频免费生成

Sora2视频免费生成

最新版Sora2模型免费使用,一键生成无水印视频

最新版Sora2模型免费使用,一键生成无水印视频

下拉加载更多