Project Icon

Coerce-rs

Rust异步Actor框架 助力构建可扩展分布式系统

Coerce-rs为Rust开发者提供异步Actor运行时和分布式系统框架。它支持Actor模型、分布式分片、持久化和发布订阅等核心功能。框架设计简洁高效,便于构建可扩展和容错的Actor驱动应用。内置HTTP API和全面指标,满足多样化的分布式系统开发需求。

Coerce-rs coerce-rs

Coerce-rs is an asynchronous (async/await) Actor runtime and distributed system framework for Rust. It allows for extremely simple yet powerful actor-based distributed system development. With minimal code, you can build a highly scalable, fault-tolerant modern actor-driven application.

Crates

CratePurposeLatest Version
coerceThe main Coerce runtime and frameworkcrates.io
coerce-redisActor persistence provider for Redis. Enables event source and snapshots to be read and written from Redis.crates.io
coerce-macrosUseful macros allowing for quick implementations of snapshots, JSON-serialisable remote messages and more.crates.io
coerce-k8sKubernetes discovery provider, automatically discover cluster peers hosted in Kubernetes, based on a configurable pod-selection labelcrates.io

Using Coerce in your own project

First step to using Coerce in your project is to add the coerce crate dependency, this can be done by adding the following to your Cargo.toml:

[dependencies]
coerce = { version = "0.8", features = ["full"] }

Optional: enabling tracing/valuable

Coerce provides support for tracing/valuable, which can be used for enriching logs with information on the actor context. This is currently an unstable feature, which can be enabled by adding the coerce/tracing-unstable feature and the following section to your .cargo/config.toml file:

[build]
rustflags = ["--cfg", "tracing_unstable"]

Note: if your project already depends on tracing crate, you'll need to enable the valuable feature too!

Features

Actors

  • Type-safe actors
  • Supervision / child spawning
  • Location-transparent ActorRef<A> types (ActorRef may comprise of a LocalActorRef<A> or a RemoteActorRef<A>)
  • Metrics available out of the box

Remoting

  • Communicate with an actor from anywhere in the cluster
  • Actors can be deployed locally or to other remote nodes
  • Protobuf network protocol
  • Actor-driven networking layer

Distributed Sharding

  • Actor IDs can resolve to specific shards, which can be spread across a cluster of Coerce nodes
  • Automatic load balancing, shards will be fairly allocated across the cluster
  • Self-recovering when nodes are lost, actors can be automatically restarted on other healthy nodes

Persistence

  • Journaling / event sourcing
  • Snapshotting
  • Pluggable storage providers (in-memory and redis readily available, MySQL is planned)

Distributed PubSub

  • Actors can subscribe to programmable topics from anywhere in the cluster
  • System-level topic provided to receive updated system state (e.g new nodes joining, nodes lost etc.)

HTTP API

  • Easily accessible metrics and information useful for diagnosis

Building and testing the Coerce libraries

Building Coerce is easy. All you need is the latest Rust stable or nightly installed, along with Cargo.

# Clone the repository
git clone https://github.com/leonhartley/coerce-rs && cd coerce-rs

## run Cargo build to build the entire workspace, including the examples and the tests
cargo build

## Alternatively, if you'd like to build the library, dependencies and run the tests
cargo test --all-features

How to run the examples

Sharded Chat example

ActorSystem

Every actor belongs to an ActorSystem.

async/await Actors

An actor is just another word for a unit of computation. It can have mutable state, it can receive messages and perform actions. One caveat though.. It can only do one thing at a time. This can be useful because it can alleviate the need for thread synchronisation, usually achieved by locking (using Mutex, RwLock etc).

How is this achieved in Coerce?

Coerce uses Tokio's MPSC channels (tokio::sync::mpsc::channel), every actor created spawns a task listening to messages from a Receiver, handling and awaiting the result of the message. Every reference (ActorRef<A: Actor>) holds a Sender<M> where A: Handler<M>, which can be cloned.

Actors can be stopped and actor references can be retrieved by ID from anywhere in your application. IDs are String but if an ID isn't provided upon creation, a new Uuid will be generated. Anonymous actors are automatically dropped ( and Stopped) when all references are dropped. Tracked actors (using global fn new_actor) must be stopped.

Basic ActorSystem + EchoActor example

Example

pub struct EchoActor {}

#[async_trait]
impl Actor for EchoActor {}

pub struct EchoMessage(String);

impl Message for EchoMessage {
    type Result = String;
}

#[async_trait]
impl Handler<EchoMessage> for EchoActor {
    async fn handle(
        &mut self,
        message: EchoMessage,
        _ctx: &mut ActorContext,
    ) -> String {
        message.0.clone()
    }
}

pub async fn run() {
    let mut actor = new_actor(EchoActor {}).await.unwrap();

    let hello_world = "hello, world".to_string();
    let result = actor.send(EchoMessage(hello_world.clone())).await;

    assert_eq!(result, Ok(hello_world));
}

Timer Example

pub struct EchoActor {}

#[async_trait]
impl Actor for EchoActor {}

pub struct EchoMessage(String);

impl Message for EchoMessage {
    type Result = String;
}

pub struct PrintTimer(String);

impl TimerTick for PrintTimer {}

#[async_trait]
impl Handler<PrintTimer> for EchoActor {
    async fn handle(&mut self, msg: PrintTimer, _ctx: &mut ActorContext) {
        println!("{}", msg.0);
    }
}

pub async fn run() {
    let mut actor = new_actor(EchoActor {}).await.unwrap();
    let hello_world = "hello world!".to_string();

    // print "hello world!" every 5 seconds
    let timer = Timer::start(actor.clone(), Duration::from_secs(5), TimerTick(hello_world));

    // timer is stopped when handle is out of scope or can be stopped manually by calling `.stop()`
    sleep(Duration::from_secs(20)).await;
    timer.stop();
}
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

白日梦AI

白日梦AI提供专注于AI视频生成的多样化功能,包括文生视频、动态画面和形象生成等,帮助用户快速上手,创造专业级内容。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

讯飞绘镜

讯飞绘镜是一个支持从创意到完整视频创作的智能平台,用户可以快速生成视频素材并创作独特的音乐视频和故事。平台提供多样化的主题和精选作品,帮助用户探索创意灵感。

Project Cover

讯飞文书

讯飞文书依托讯飞星火大模型,为文书写作者提供从素材筹备到稿件撰写及审稿的全程支持。通过录音智记和以稿写稿等功能,满足事务性工作的高频需求,帮助撰稿人节省精力,提高效率,优化工作与生活。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

AIWritePaper论文写作

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

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号