Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

CRB 🦀 transactional actors

License

NotificationsYou must be signed in to change notification settings

AI-Robotic-Labs/crb

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Composable Runtime Blocks

Crates.ioMIT licensedDocumentation

A unique framework that implementeshybrid workloads, seamlessly combining synchronous and asynchronous activities, state machines, routines, the actor model, and supervisors.

It’s perfect for building massive applications and serves as an ideal low-level framework for creating your own frameworks, for example AI-agents.The core idea is to ensure all blocks are highly compatible with each other, enabling significant code reuse.

What is a hybrid workload?

A hybrid workload is a concurrent task capable of switching roles - it can function as a synchronous or asynchronous task, a finite state machine, or as an actor exchanging messages.

The implementation is designed as afully portable solution that can run in a standard environment, a WASM virtual machine (e.g., in a browser), or a TEE enclave. This approach significantly reduces development costs by allowing you to reuse code across all parts of your application: backend, frontend, agents, and more.

The key feature is its ability to combine the roles, enabling the implementation of algorithms withcomplex branching that would be impossible in the flat structure of a standard function. This makes it ideal for building the framework of large-scale applications or implementing complex workflows, such as AI pipelines.

Projects

The following projects have been implemented using the framework:

  • Nine - AI agents that work everywhere.
  • Crateful - AI-curated weekly newsletter about Rust crates.
  • Knowledge.Dev - An interactive book for learning practical, idiomatic Rust (product is entirely written in Rust).

Examples

Below, you'll find numerous examples of building hybrid activities using the framework. These examples are functional but simplified for clarity:

  • Type imports are omitted to keep examples clean and focused.
  • Theasync_trait macro is used but not explicitly shown, as exported traits with asynchronous methods are expected in the future.
  • anyhow::Result is used instead of the standardResult for simplicity.
  • Agent context is not specified, as it is alwaysAgentSession in these cases.

The examples demonstrate various combinations of states and modes, but in reality, there are many more possibilities, allowing for any sequence or combination.

Before diving into the examples...

To create a universal hybrid activity, you need to define a structure and implement theAgent trait for it. By default, the agent starts in a reactive actor mode, ready to receive messages and interact with other actors.

However, you can override this behavior by explicitly specifying the agent's initial state in thebegin() method.

pubstructTask;implAgentforTask{fnbegin(&mutself) ->Next<Self>{Next::do_async(())// The next state}}

The next state is defined using theNext object, which provides various methods for controlling the state machine. To perform an asynchronous activity, use thedo_async() method, passing the new state as a parameter (default is()).

Then, implement theDoAsync trait for your agent by defining the asynchronousonce() method:

implDoAsyncforTask{asyncfnonce(&mutself, _:&mut()) ->Result<Next<Self>>{do_something().await?;Ok(Next::done())}}

The result should specify the next state of the state machine. If you want to terminate the agent, simply return the termination state by calling thedone() method on theNext type.

Asynchronous tasks

The simplest example is creating a task that performs an asynchronous activity and then terminates.

pubstructTask;implAgentforTask{fnbegin(&mutself) ->Next<Self>{Next::do_async(())}}implDoAsyncforTask{asyncfnonce(&mutself, _:&mut()) ->Result<Next<Self>>{        reqwest::get("https://www.rust-lang.org").await?.text().await?;Ok(Next::done())}}

Fallbacks

Unlike standard asynchronous activities, you can implement thefallback() method to modify the course of actions in case of an error:

implDoAsyncforTask{asyncfnfallback(&mutself,err:Error) ->Next<Self>{        log::error!("Can't load a page: {err}. Trying again...");Ok(Next::do_async(()))}}

The task will now repeatedly enter the same state until the loading process succeeds.

Repeated routines

The agent already implements a persistent routine in therepeat() method, which repeatedly attempts to succeed by calling theonce() method. To achieve the same effect, we can simply override that method:

implDoAsyncforTask{asyncfnrepeat(&mutself, _:&mut()) ->Result<Option<Next<Self>>>{        reqwest::get("https://www.rust-lang.org").await?.text().await?;Ok(Some(Next::done()))}}

Therepeat() method will continue to run until it returns the next state for the agent to transition to.

Synchronous tasks

To implement a synchronous task simply call thedo_sync() method onNext:

pubstructTask;implAgentforTask{fnbegin(&mutself) ->Next<Self>{Next::do_sync(())}}

Next, implement theDoSync trait to run the task in a thread (either the same or a separate one, depending on the platform):

implDoSyncforTask{fnonce(&mutself, _:&mut()) ->Result<Next<Self>>{let result:u64 =(1u64..=20).map(|x| x.pow(10)).sum();println!("{result}");Ok(Next::done())}}

In the example, it calculates the sum of powers and prints the result to the terminal.

Multiple states (state-machines)

Interestingly, you can define different states and implement unique behavior for each, whether synchronous or asynchronous. This gives you both a state machine and varied execution contexts without the need for manual process management.

Let’s create an agent that prints the content of a webpage to the terminal. The first state the agent should transition to isGetPage, which includes the URL of the page to be loaded. This state will be asynchronous, so call thedo_async() method with theNext state.

pubstructTask;implAgentforTask{fnbegin(&mutself) ->Next<Self>{let url ="https://www.rust-lang.org".into();Next::do_async(GetPage{ url})}}

Asynchronous state

Implement theGetPage state by defining the corresponding structure and using it in theDoAsync trait implementation for our agentTask:

structGetPage{url:String}implDoAsync<GetPage>forTask{asyncfnonce(&mutself,state:&mutGetPage) ->Result<Next<Self>>{let text = reqwest::get(state.url).await?.text().await?;Ok(Next::do_sync(Print{ text}))}}

In theGetPage state, the webpage will be loaded, and its content will be passed to the next state,Print, for printing. Since the next state is synchronous, it is provided as a parameter to thedo_sync() method.

Synchronous state

Now, let’s define thePrint state as a structure and implement theDoSync trait for it:

structPrint{text:String}implDoSync<Print>forTask{fnonce(&mutself,state:&mutPrint) ->Result<Next<Self>>{printlnt!("{}", state.text);Ok(Next::done())}}

The result is a state machine with the flexibility to direct its workflow into different states, enabling the implementation of a robust and sometimes highly nonlinear algorithm that would be extremely difficult to achieve within a single asynchronous function.

Mutable states

Previously, we didn't modify the data stored in a state. However, states provide a convenient context for managing execution flow or collecting statisticswithout cluttering the task's main structure!

pubstructTask;implAgentforTask{fnbegin(&mutself) ->Next<Self>{Next::do_async(Monitor)}}structMonitor{total:u64,success:u64,}implDoAsync<Monitor>forTask{asyncfnrepeat(&mutself,mutstate:&mutMonitor) ->Result<Option<Next<Self>>>{        state.total +=1;        reqwest::get("https://www.rust-lang.org").await?.error_for_status()?;        state.success +=1;sleep(Duration::from_secs(10)).await;Ok(None)}}

Above is an implementation of a monitor that simply polls a website and counts successful attempts. It does this without modifying theTask structure while maintaining access to it.

Concurrent Task

Within an asynchronous activity, all standard tools for concurrently executing multipleFutures are available. For example, in the following code, several web pages are requested simultaneously using thejoin_all() function:

pubstructConcurrentTask;implAgentforConcurrentTask{fnbegin(&mutself) ->Next<Self>{Next::do_async(())}}implDoAsyncforConcurrentTask{asyncfnonce(&mutself, _:&mut()) ->Result<Next<Self>>{let urls =vec!["https://www.rust-lang.org","https://www.crates.io","https://crateful.substack.com","https://knowledge.dev",];let futures = urls.into_iter().map(|url| reqwest::get(url));        future::join_all(futures).awaitOk(Next::done())}}

This approach allows for more efficient utilization of the asynchronous runtime while maintaining the workflow without needing to synchronize the retrieval of multiple results.

Parallel Task

Another option is parallelizing computations. This is easily achieved by implementing a synchronous state. Since it runs in a separate thread, it doesn't block the asynchronous runtime, allowing other agents to continue executing in parallel.

pubstructParallelTask;implAgentforParallelTask{fnbegin(&mutself) ->Next<Self>{Next::do_sync(())}}implDoSyncforParallelTask{fnonce(&mutself, _:&mut()) ->Result<Next<Self>>{let numbers =vec![1,2,3,4,5,6,7,8,9,10];let squares = numbers.into_par_iter().map(|n| n* n).collect();Ok(Next::done())}}

In the example above, parallel computations are performed using therayon crate. The results are awaited asynchronously by the agent sinceDoSync shifts execution to a thread while continuing to wait for the result asynchronously.

Subtask Execution

The framework allows tasks to be reused within other tasks, offering great flexibility in structuring code.

pubstructRunBoth;implAgentforRunBoth{fnbegin(&mutself) ->Next<Self>{Next::do_async(())}}implDoAsyncforRunBoth{asyncfnonce(&mutself, _:&mut()) ->Result<Next<Self>>{join!(ConcurrentTask.run(),ParallelTask.run(),).await;Ok(Next::done())}}

The code example implementes an agent that waits for the simultaneous completion of two tasks we implemented earlier:concurrent andparallel.

Shared state in a state machine

Although the states within a group inherently form a state machine, you can define it more explicitly by adding a field to the agent and describing the states with a dedicatedenum:

enumState{First,Second,Third,}structTask{state:State,}

In this case, theState enumeration can handle transitions between states. Transition rules can be implemented as a function that returns aNext instance with the appropriate state handler.

implState{fnnext(&self) ->Next<Task>{matchself{State::First =>Next::do_async(First),State::Second =>Next::do_async(Second),State::Third =>Next::do_async(Third),}}}

Set the initial state when creating the task (it can even be set in the constructor), and delegate state transitions to thenext() function, called from thebegin() method.

implAgentforTask{fnbegin(&mutself) ->Next<Self>{self.state.next()}}

Implement all state handlers, with theState field determining the transition to the appropriate handler. Simply use itsnext() method so that whenever the state changes, the transition always leads to the correct handler.

structFirst;implDoAsync<First>forTask{asyncfnonce(&mutself, _:&mutFirst) ->Result<Next<Self>>{self.state =State::Second;Ok(self.state.next())}}structSecond;implDoAsync<Second>forTask{asyncfnonce(&mutself, _:&mutSecond) ->Result<Next<Self>>{self.state =State::Third;Ok(self.state.next())}}structThird;implDoAsync<Third>forTask{asyncfnonce(&mutself, _:&mutThird) ->Result<Next<Self>>{Ok(Next::done())}}

💡 The framework is so flexible that it allows you to make this logic even more explicit by implementing a customPerformer for the agent.

Actor Model

Agents handle messages asynchronously. Actor behavior is enabled by default if no transition state is specified in thebegin() method. Alternatively, you can switch to this mode from any state by callingNext::events(), which starts message processing.

In other words, the actor state is the default for the agent, so simply implementing theAgent trait is enough:

structActor;implAgentforActor{}

An actor can accept any data type as a message, as long as it implements theOnEvent trait for that type and itshandle() method. For example, let's teach our actor to accept anAddUrl message, which adds an external resource:

structAddUrl{url:Url}implOnEvent<AddUrl>forActor{async handle(&mutself,event:AddUrl,ctx:&mutContext<Self>) ->Result<()>{todo!()}}

Actors can implement handlers for any number of messages, allowing you to add as manyOnEvent implementations as needed:

structDeleteUrl{url:Url}implOnEvent<DeleteUrl>forActor{async handle(&mutself,event:DeleteUrl,ctx:&mutContext<Self>) ->Result<()>{todo!()}}

The provided context (ctx) allows you to send a message, terminate the actor, or transition to a new state by setting the next state withNext.

State transitions have the highest priority. Even if there are messages in the queue, the state transition will occur first, and messages will wait until the agent returns to the actor state.

Interactions

The actor model is designed to let you add custom handler traits for any type of event. For example, this framework supports interactive actor interactions—special messages that include a request and a channel for sending a response.

The example below implements a server that reserves anId in response to an interactive request and returns it:

structServer{slab:Slab<Record>,}structGetId;implRequestforGetId{typeResponse =usize;}implOnRequest<GetId>forServer{async on_request(&mutself, _:GetId,ctx:&mutContext<Self>) ->Result<usize>{let record =Record{ ...};Ok(self.slab.insert(record))}}

The request must implement theRequest trait to specify theResponse type. As you may have noticed, for theOnRequest trait, we implemented theon_request() method, which expects a response as the result. This eliminates the need to send it manually.

The following code implements aClient that configures itself by sending a request to the server to obtain anId and waits for a response by implementing theOnResponse trait.

structClient{server:Address<Server>,}implAgentforClient{fnbegin(&mutself) ->Next<Self>{Next::do_async(Configure)}}structConfigure;implDoAsync<Configure>forClient{asyncfnonce(&mutself, _:&mutConfigure,ctx:&mutContext<Self>) ->Result<Next<Self>>{self.server.request(GetId)?.forward_to(ctx)?;Ok(Next::events())}}implOnResponse<GetId>forClient{async on_response(&mutself, id:usize,ctx:&mutContext<Self>) ->Result<()>{println!("Reserved id: {id}");Ok(())}}

Supervisor

An actor (or any agent) can be launched from anywhere if it implements theStandalone trait. Otherwise, it can only be started within the context of a supervisor.

The supervisor can also manage all spawned tasks and terminate them in a specific order by implementing theSupervisor trait:

structApp;implAgentforApp{typeContext =SupervisorSession<Self>;}implSuperviorforApp{typeGroup =Group;}

TheGroup type defines a grouping for tasks, where the order of its values determines the sequence in which child agents (tasks, actors) are terminated.

#[derive(Clone,PartialEq,Eq,PartialOrd,Ord,Hash)]enumGroup{Workers,Requests,Server,HealthCheck,DbCleaner,UserSession(Uid),}

Pipelines

The framework includes an experimental implementation of pipelines that automatically trigger tasks as they process input data from the previous stage.

However, creating complex workflows is also possible using just the agent's core implementation.

Functional activities (fn orFuture as tasks)

todo

Key Advantages

WASM Compatibility

One of the library's major advantages is its out-of-the-box compatibility with WebAssembly (WASM). This allows you to write full-stack solutions in Rust while reusing the same codebase across different environments.

Synchronous tasks are currently unavailable in WASM due to its lack of full thread support. However, using them in environments like browsers is generally unnecessary, as they block asynchronous operations.

Actor Model

The library includes a complete implementation of the actor model, enabling you to build a hierarchy of actors and facilitate message passing between them. When the application stops, actors gracefully shut down between messages processing phases, and in the specified order.

Synchronous Tasks

The framework supports not only asynchronous activities (IO-bound) but also allows running synchronous (CPU-bound) tasks using threads. The results of these tasks can seamlessly be consumed by asynchronous activities.

Pipelines

The library offers a Pipeline implementation compatible with actors, routines, and tasks (including synchronous ones), making it ideal for building AI processing workflows.

Trait-Based Design

Unlike many actor frameworks, this library relies heavily on traits. For example, tasks like interactive communication, message handling, orStream processing are implemented through specific trait implementations.

More importantly, the library is designed to be extensible, allowing you to define your own traits for various needs while keeping your code modular and elegant. For instance, actor interruption is implemented on top of this model.

Method Hierarchy

Trait methods are designed and implemented so that you only need to define specific methods to achieve the desired behavior.

Alternatively, you can fully override the behavior and method call order - for instance, customizing an actor’s behavior in any way you like or adding your own intermediate phases and methods.

Error Handling and Resilience

The library provides built-in error handling features, such as managing failures during message processing, making it easier to write robust and resilient applications.

Author

The project was originally created by@therustmonk as a result of extensive experimental research into implementing a hybrid actor model in Rust.

To support the project, consider subscribing toCrateful, my newsletter focused on AI agent development in Rust. It features insights gathered by a group of crab agents built with this framework.

License

This project is licensed under theMIT license.

About

CRB 🦀 transactional actors

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Rust99.7%
  • Just0.3%

[8]ページ先頭

©2009-2025 Movatter.jp