Skip to content

Commit

Permalink
Implement a transactional actor
Browse files Browse the repository at this point in the history
  • Loading branch information
therustmonk committed Jan 19, 2025
1 parent bb60476 commit 82bdf16
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 1 deletion.
1 change: 1 addition & 0 deletions 2025-01/transactional-actor/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions 2025-01/transactional-actor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ edition = "2021"

[dependencies]
anyhow = "1.0.95"
async-trait = "0.1.85"
crb = "0.0.27"
tokio = "1.43.0"
74 changes: 73 additions & 1 deletion 2025-01/transactional-actor/src/main.rs
Original file line number Diff line number Diff line change
@@ -1 +1,73 @@
fn main() {}
use anyhow::Result;
use async_trait::async_trait;
use crb::agent::{Agent, AgentSession, Context, DoAsync, DoSync, Duty, Next, OnEvent, Runnable};
use crb::core::time::Duration;
use crb::superagent::TimeoutSwitch;

struct Tractor {
timeout: TimeoutSwitch<Tick>,
}

impl Tractor {
fn new() -> Self {
let duration = Duration::from_secs(1);
Self {
timeout: TimeoutSwitch::new(duration, Tick),
}
}
}

impl Agent for Tractor {
type Context = AgentSession<Self>;

fn begin(&mut self) -> Next<Self> {
Next::duty(Initialize)
}
}

struct Initialize;

#[async_trait]
impl Duty<Initialize> for Tractor {
async fn handle(&mut self, _: Initialize, ctx: &mut Context<Self>) -> Result<Next<Self>> {
println!("Initialize");
self.timeout.add_listener(ctx);
self.timeout.start();
Ok(Next::events())
}
}

#[derive(Clone)]
struct Tick;

#[async_trait]
impl OnEvent<Tick> for Tractor {
async fn handle(&mut self, _: Tick, ctx: &mut Context<Self>) -> Result<()> {
println!("Tick");
ctx.do_next(Next::do_async(()));
Ok(())
}
}

#[async_trait]
impl DoAsync for Tractor {
async fn once(&mut self, _: &mut ()) -> Result<Next<Self>> {
println!("Async");
Ok(Next::do_sync(()))
}
}

impl DoSync for Tractor {
fn once(&mut self, _: &mut ()) -> Result<Next<Self>> {
println!("Sync");
Ok(Next::done())
}
}

#[tokio::main]
async fn main() -> Result<()> {
println!("Begin");
Tractor::new().run().await?;
println!("End");
Ok(())
}

0 comments on commit 82bdf16

Please sign in to comment.