Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Spawned - Project Context

Rust actor framework inspired by Erlang OTP. Provides `Actor` trait (similar to GenServer) that separates concurrency logic from business logic.

## Project Structure

```
spawned/
├── concurrency/ # Main library: Actor trait, timers, streams
│ └── src/
│ ├── tasks/ # Async version (requires tokio runtime)
│ └── threads/ # Sync version (native OS threads)
├── rt/ # Runtime abstractions (wraps tokio, provides CancellationToken)
│ └── src/
│ ├── tasks/ # Tokio-based runtime
│ └── threads/ # Thread-based runtime
└── examples/ # Usage examples (name_server, bank, ping_pong, etc.)
```

## Two Execution Modes

- **tasks**: Async/await with tokio. Use `spawned_rt::tasks` and `spawned_concurrency::tasks`
- **threads**: Blocking, no async. Use `spawned_rt::threads` and `spawned_concurrency::threads`

Both provide identical Actor API. The `tasks` module has `Backend` enum: `Async`, `Blocking`, `Thread`.

## Key Types

| Type | Description |
|------|-------------|
| `Actor` | Trait for stateful message handlers |
| `ActorRef<T>` | Handle to communicate with a running actor |
| `ActorRef::request()` | Sync call, waits for reply (like Erlang `call`) |
| `ActorRef::send()` | Async fire-and-forget (like Erlang `cast`) |
| `ActorRef::join()` | Wait for actor to stop |
| `CancellationToken` | Signal cancellation to timers/actors |
| `TimerHandle` | Handle for `send_after`/`send_interval` |

## Actor Lifecycle

1. `init()` - Setup before main loop
2. `handle_request()` / `handle_message()` - Process messages
3. `teardown()` - Cleanup after stop

## Common Patterns

```rust
// Start an actor
let mut handle = MyActor::new().start();

// Request (sync call)
let reply = handle.request(MyRequest::GetValue).await?;

// Send (fire-and-forget)
handle.send(MyMessage::DoSomething).await?;

// Timer that wakes on cancellation
send_after(Duration::from_secs(5), handle.clone(), Msg::Timeout);

// Wait for actor to stop
handle.join().await;
```

## Testing

```bash
cargo test --workspace # Run all tests
cargo test -p spawned-concurrency # Test concurrency crate only
```

## Conventions

- Use `tracing` for logging (not `println!`)
- Prefer `&self` over `&mut self` for thread-safe methods
- Handle poisoned mutexes with `unwrap_or_else(|p| p.into_inner())`
- Use conventional commits: `feat:`, `fix:`, `refactor:`, `docs:`, `test:`

## PR List Format

When listing PRs, output raw markdown in a code block so it can be copied directly:
- Format: [#NUMBER](URL) title (+additions/-deletions) ✅
- Use ⏳ instead of ✅ when approvals are 0
- Group by label/topic with a header
- No bullet points on PR lines
- End with: **Summary:** X PRs | **Total:** (+A/-D) | **Net:** ±N lines
39 changes: 39 additions & 0 deletions Cargo.lock

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

5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ resolver = "3"
members = [
"rt",
"concurrency",
"macros",
"examples/bank",
"examples/bank_threads",
"examples/name_server",
Expand All @@ -15,11 +16,15 @@ members = [
"examples/busy_genserver_warning",
"examples/signal_test",
"examples/signal_test_threads",
"examples/chat_room",
"examples/chat_room_threads",
"examples/service_discovery",
]

[workspace.dependencies]
spawned-rt = { path = "rt", version = "0.4.5" }
spawned-concurrency = { path = "concurrency", version = "0.4.5" }
spawned-macros = { path = "macros", version = "0.4.5" }
tracing = { version = "0.1.41", features = ["log"] }
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }

Expand Down
1 change: 1 addition & 0 deletions concurrency/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ license.workspace = true

[dependencies]
spawned-rt = { workspace = true }
spawned-macros = { workspace = true }
tracing = { workspace = true }
futures = "0.3.1"
thiserror = "2.0.12"
Expand Down
20 changes: 6 additions & 14 deletions concurrency/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,20 @@
#[derive(Debug, thiserror::Error)]
pub enum ActorError {
#[error("Callback Error")]
Callback,
#[error("Initialization error")]
Initialization,
#[error("Server error")]
Server,
#[error("Unsupported Request on this Actor")]
RequestUnused,
#[error("Unsupported Message on this Actor")]
MessageUnused,
#[error("Actor stopped")]
ActorStopped,
#[error("Request to Actor timed out")]
RequestTimeout,
}

impl<T> From<spawned_rt::threads::mpsc::SendError<T>> for ActorError {
fn from(_value: spawned_rt::threads::mpsc::SendError<T>) -> Self {
Self::Server
Self::ActorStopped
}
}

impl<T> From<spawned_rt::tasks::mpsc::SendError<T>> for ActorError {
fn from(_value: spawned_rt::tasks::mpsc::SendError<T>) -> Self {
Self::Server
Self::ActorStopped
}
}

Expand All @@ -32,7 +24,7 @@ mod tests {

#[test]
fn test_error_into_std_error() {
let error: &dyn std::error::Error = &ActorError::Callback;
assert_eq!(error.to_string(), "Callback Error");
let error: &dyn std::error::Error = &ActorError::ActorStopped;
assert_eq!(error.to_string(), "Actor stopped");
}
}
5 changes: 2 additions & 3 deletions concurrency/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
//! spawned concurrency
//! Some basic traits and structs to implement concurrent code à-la-Erlang.
pub mod error;
pub mod messages;
pub mod message;
pub mod registry;
pub mod tasks;
pub mod threads;
Loading
Loading