Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add book explaining core concepts #40

Merged
merged 1 commit into from
Sep 9, 2024
Merged
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
57 changes: 57 additions & 0 deletions docs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"name": "Kameo",
"description": "Fault-tolerant Async Actors Built on Tokio",
"socialPreview": "https://repository-images.githubusercontent.com/779318723/b1ce92be-760d-427b-b3a6-ffca8cbc2e6a",
"sidebar": [
{
"group": "Getting Started",
"pages": [
{
"title": "Introduction",
"href": "/",
"icon": "globe"
},
{
"title": "Getting Started",
"href": "/getting-started",
"icon": "rocket"
}
]
},
{
"group": "Core Concepts",
"pages": [
{
"title": "Overview",
"href": "/core-concepts",
"icon": "book"
},
{
"title": "Actors",
"href": "/core-concepts/actors",
"icon": "users"
},
{
"title": "Messages",
"href": "/core-concepts/messages",
"icon": "envelope"
},
{
"title": "Requests",
"href": "/core-concepts/requests",
"icon": "question"
},
{
"title": "Replies",
"href": "/core-concepts/replies",
"icon": "reply"
},
{
"title": "Supervision",
"href": "/core-concepts/supervision",
"icon": "shield-alt"
}
]
}
]
}
25 changes: 25 additions & 0 deletions docs/core-concepts.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
title: Core Concepts Overview
---

Welcome to the Core Concepts section of Kameo, where you'll find the foundational principles and components that make up the Kameo actor library. Understanding these concepts is crucial for effectively leveraging Kameo to build resilient, scalable, and concurrent applications. Below is an overview of the key concepts that form the backbone of Kameo's design and functionality.

### Actors

At the heart of Kameo lies the Actor model, a powerful abstraction that encapsulates state and behavior into independent, concurrent units. Actors are the primary building blocks of applications in Kameo, designed to isolate state and handle messages asynchronously. This isolation enhances fault tolerance and system resilience, as actors can fail and recover without affecting the overall system stability.

### Messages

Communication in Kameo is achieved through messages. Actors interact with each other exclusively by sending and receiving messages, ensuring a loose coupling between components. This messaging system underpins the asynchronous, non-blocking nature of Kameo, enabling efficient communication patterns and facilitating the development of responsive applications.

### Requests

Requests represent a specialized form of message exchange in Kameo, supporting both the "ask" and "tell" patterns. This library allows actors to either send messages without expecting a reply ("tell") or send messages and await responses ("ask"). The ask pattern, in particular, introduces a way to handle more complex interaction flows, including synchronous operations and error handling.

### Replies

Replies are responses to requests, completing the communication cycle between actors. By implementing the `Reply` trait, apps can define custom reply types, ensuring that actors can exchange meaningful data and status information. This mechanism is crucial for implementing robust and interactive systems where actors depend on the outcomes of their interactions.

### Supervision

Supervision is a strategy for managing actor lifecycle and failure recovery, embodying the principle of "let it crash." In Kameo, actors can be linked together in supervision trees, allowing parent actors to monitor and respond to the failures of their children. This model provides a structured approach to error handling and recovery, ensuring system resilience and stability.
48 changes: 48 additions & 0 deletions docs/core-concepts/actors.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
title: Actors Overview
---

The core of Kameo is its actors. Actors are objects that encapsulate state and behavior. They interact with the rest of the system asynchronously, primarily through message passing, which allows for a high degree of concurrency and scalability. This section provides an overview of the `Actor` trait in Kameo, detailing its lifecycle, messaging, and supervision.

### Actor Trait Overview

The `Actor` trait defines the essential functionality and lifecycle hooks for an actor in Kameo. Implementing this trait allows you to create custom actors tailored to your application's requirements. Here are the key components of the `Actor` trait:

- **Lifecycle Hooks**: Kameo provides several hooks (`on_start`, `on_stop`, `on_panic`, `on_link_died`) that are called at different points in an actor's lifecycle. These hooks offer points of intervention where custom behavior can be implemented, such as initialization, cleanup, and error handling.
- **Mailbox**: Each actor has a mailbox (`type Mailbox`), which can be bounded or unbounded. The mailbox is where incoming messages are queued before being processed by the actor. Bounded mailboxes help in applying backpressure, preventing the system from being overwhelmed by too many message
- **Messaging**: Actors communicate by sending messages to each other. When an actor is spawned, it returns an `ActorRef`, a reference to the actor that can be used to send messages to it. Messages are sent asynchronously and are processed sequentially by the receiving actor.
- **Supervision**: Actors can supervise other actors, allowing for hierarchical error handling and recovery strategies. The `on_panic` and `on_link_died` hooks are integral to this, enabling actors to respond to failures in their child actors, as well as themselves.

#### **Deriving Actor**

To streamline the creation of actors and reduce repetitive boilerplate, Kameo offers a derive macro for the `Actor` trait. This macro not only simplifies the actor definition process but also provides sensible defaults that adhere to common practices.

When using the derive macro, you can customize your actor with the following attributes:

- `#[actor(name = "...")]`: This attribute allows you to assign a custom name to your actor. By default, Kameo uses the actor's identifier (ident) as its name. Specifying a custom name can be useful for logging.
- `#[actor(mailbox = ...)]`: Through this attribute, you can define the type of mailbox your actor should use. Kameo supports two mailbox types: `bounded` and `unbounded`.
- **Bounded Mailbox**: For a `bounded` mailbox, you have the option to specify its capacity using the syntax `bounded(<size>)`, where `<size>` represents the maximum number of messages the mailbox can hold. If not specified, a default size of 1,000 is used.
- **Unbounded Mailbox**: An `unbounded` mailbox does not have a size limit, meaning it can grow indefinitely as more messages are received. While this ensures that no message is ever rejected due to mailbox capacity, it could potentially lead to increased memory usage under high load or if the actor is unable to process messages quickly enough.

**Example**

### Lifecycle Management

- **Starting**: The `on_start` hook is called before the actor starts processing messages. It's an opportunity to perform any necessary initialization.
- **Stopping**: Actors are stopped either explicitly or when all references to their `ActorRef` are dropped. The `on_stop` hook allows for cleanup activities before the actor is fully stopped.
- **Error Handling**: The `on_panic` hook is invoked when an actor panics or encounters an error while processing a message. This hook can decide whether the actor should be stopped or continue processing messages.
- **Link Failures**: The `on_link_died` hook is called when a linked actor dies, providing a chance to react to the failure of closely related actors.

### Actor Creation and Messaging

Creating an actor involves implementing the `Actor` trait and then spawning the actor using `kameo::spawn`. Upon spawning, an `ActorRef<T>` is returned, which is used to send messages to the actor. The actor processes messages using the `handle` method from the `Message` trait, optionally returning a reply.

#### Example Usage

The above example demonstrates defining a simple actor and spawning it. The actor prints a message upon starting, showcasing the use of the `on_start` lifecycle hook.

---

#### Summary

Actors form the core of Kameo, providing a structured way to encapsulate both logic and state within self-contained units. This design principle facilitates the creation of systems that are inherently more scalable and resilient, enabling you to build applications that efficiently manage concurrency and are robust against failures. Through actors, complex interactions become manageable, allowing for a modular approach to system architecture.
47 changes: 47 additions & 0 deletions docs/core-concepts/messages.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---
title: Messages Overview
---

In Kameo, messages play a central role in the communication between actors. They are the primary means through which actors interact and modify each other's state. Understanding how messages work is fundamental to effectively using Kameo to build concurrent applications.

### **Defining Messages**

Messages in Kameo are any static types that are handled by implementing the `Message<T>` trait for an actor. This design allows for a wide variety of message types, from simple data structures to complex commands with associated data. The flexibility in message definition enables developers to design their actor system with clear and concise communication patterns.

Here's a closer look at the `Message` trait:

```rust
pub trait Message<T>: Actor {
/// The reply sent back to the message caller.
type Reply: Reply;

/// Handler for this message.
async fn handle(
&mut self,
msg: T,
ctx: Context<'_, Self, Self::Reply>,
) -> Self::Reply;
}
```

- **Trait Generics**: The `Message<T>` trait is generic over `T`, which represents the type of the message being sent to the actor. This allows for the implementation of message handlers that are type-safe and specific to the message being handled.
- **Reply Type**: Each message has an associated `Reply` type, which is the type of the response that the message sender can expect to receive. This reply must implement the `Reply` trait, which ensures that it can be properly handled and sent back to the caller.
- **Message Handler**: The core of the Message trait is the handle function. This function is where the logic for handling a specific message is defined. It takes mutable access to the actor (&mut self), the message itself (msg), and a context (ctx) that provides access to actor-specific functionality like sending messages to other actors or accessing the actor's state. The handle function returns a future that resolves to the message's reply type, allowing for asynchronous processing of messages. This design supports non-blocking message handling, which is essential for building responsive and scalable actor systems.

### Sequential Processing

Messages in Kameo are processed sequentially, one at a time, with exclusive mutable access to the actor's state. This sequential processing model simplifies state management within actors, as there is no need for explicit synchronization mechanisms like locks. When an actor is handling a message, it can safely modify its state without worrying about concurrent modifications from other messages.

This model also ensures that messages are processed in the order they are received, which can be critical for maintaining consistency and correctness in certain applications.

### Asynchronous and Concurrent

While messages are processed sequentially within a single actor, Kameo allows for concurrent processing across multiple actors. This is where the actor model shines, enabling high levels of concurrency without the complexity associated with traditional multithreading and synchronization.

The asynchronous nature of the `handle` function, combined with Rust's powerful futures and async/await syntax, makes it straightforward to perform non-blocking operations, such as I/O tasks or querying other actors, within a message handler.

---

#### Summary

Messages are the primary means of communication between actors in Kameo, serving as the backbone for asynchronous information exchange. This approach promotes a high degree of decoupling, allowing components within a system to interact flexibly and evolve over time. By effectively utilizing messages, you can design interactions that are both clear and adaptable, driving the functionality and responsiveness of your application.
56 changes: 56 additions & 0 deletions docs/core-concepts/replies.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
---
title: Replies Overview
---

In Kameo, replies are the responses sent back from an actor following the receipt and processing of a message. These replies are fundamental to the ask pattern of actor communication, where a sender awaits a response to proceed. Ensuring that replies are properly structured and handled is crucial for maintaining the flow of information and control within your actor system.

### The Reply Trait

All reply types must implement the `Reply` trait. This trait signifies that the type can be used as a valid response from an actor to a message. Implementing the `Reply` trait correctly is essential for the seamless operation of ask requests, where a response from the actor is expected.

Errors are a special consideration in the context of replies. When a message is sent using the tell method, any errors generated during its processing are treated as panics within the actor. This behavior underscores the importance of robust error handling and validation within the actor's message processing logic to prevent unintended stops.

### Deriving the Reply Trait

Kameo simplifies the implementation of the `Reply` trait through the `#[derive(Reply)]` macro. This macro automatically provides the necessary trait implementations for a type, making it straightforward to create custom reply types that integrate seamlessly with Kameo's messaging system.

#### Example Usage

```rust
use kameo::Reply;

#[derive(Reply)]
pub struct MyReply {
pub data: String,
pub status: bool,
}

// Usage within an actor
impl Message<MyRequest> for MyActor {
type Reply = MyReply;

async fn handle(
&mut self,
msg: MyRequest,
_: Context<'_, Self, Self::Reply>,
) -> Self::Reply {
// Logic to process the message and generate a reply
MyReply {
data: "Processed data".to_string(),
status: true,
}
}
}
```

In this example, `MyReply` is defined as a struct with data relevant to the response expected by a sender. By deriving the `Reply` trait, `MyReply` is automatically equipped to serve as a response in Kameo's messaging system. This pattern allows for rich, structured data to be communicated back to senders, facilitating complex interactions and workflows within your actor system.

### Handling Replies

When dealing with ask requests, it's important to handle replies gracefully. This involves not only receiving the reply but also managing potential timeouts and errors that might occur during the interaction. Kameo's design encourages clear, concise handling of these scenarios, ensuring that your actor system remains robust and resilient under various operational conditions.

---

#### Summary

Replies play a crucial role in the communication loop between actors in Kameo, particularly when direct feedback or data needs to be conveyed back to the requester. They enrich the interaction model, enabling more structured and predictable exchanges. By defining clear and meaningful replies, you ensure smoother and more reliable communication flows, which is essential for handling complex and evolving workflows within your applications.
Loading