From d9bf575203583d2b784cd7173e687b377f38b62c Mon Sep 17 00:00:00 2001 From: Ari Seyhun Date: Tue, 10 Sep 2024 00:06:08 +0800 Subject: [PATCH] docs: add book explaining core concepts --- docs.json | 57 ++++++++++++++++++++ docs/core-concepts.mdx | 25 +++++++++ docs/core-concepts/actors.mdx | 48 +++++++++++++++++ docs/core-concepts/messages.mdx | 47 ++++++++++++++++ docs/core-concepts/replies.mdx | 56 +++++++++++++++++++ docs/core-concepts/requests.mdx | 78 +++++++++++++++++++++++++++ docs/core-concepts/supervision.mdx | 41 ++++++++++++++ docs/getting-started.mdx | 87 ++++++++++++++++++++++++++++++ docs/index.mdx | 22 ++++++++ 9 files changed, 461 insertions(+) create mode 100644 docs.json create mode 100644 docs/core-concepts.mdx create mode 100644 docs/core-concepts/actors.mdx create mode 100644 docs/core-concepts/messages.mdx create mode 100644 docs/core-concepts/replies.mdx create mode 100644 docs/core-concepts/requests.mdx create mode 100644 docs/core-concepts/supervision.mdx create mode 100644 docs/getting-started.mdx create mode 100644 docs/index.mdx diff --git a/docs.json b/docs.json new file mode 100644 index 0000000..f68b0e7 --- /dev/null +++ b/docs.json @@ -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" + } + ] + } + ] +} \ No newline at end of file diff --git a/docs/core-concepts.mdx b/docs/core-concepts.mdx new file mode 100644 index 0000000..f26226f --- /dev/null +++ b/docs/core-concepts.mdx @@ -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. diff --git a/docs/core-concepts/actors.mdx b/docs/core-concepts/actors.mdx new file mode 100644 index 0000000..36c10cf --- /dev/null +++ b/docs/core-concepts/actors.mdx @@ -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()`, where `` 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` 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. diff --git a/docs/core-concepts/messages.mdx b/docs/core-concepts/messages.mdx new file mode 100644 index 0000000..e9b8aa0 --- /dev/null +++ b/docs/core-concepts/messages.mdx @@ -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` 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: 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` 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. diff --git a/docs/core-concepts/replies.mdx b/docs/core-concepts/replies.mdx new file mode 100644 index 0000000..331c822 --- /dev/null +++ b/docs/core-concepts/replies.mdx @@ -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 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. diff --git a/docs/core-concepts/requests.mdx b/docs/core-concepts/requests.mdx new file mode 100644 index 0000000..5c82f77 --- /dev/null +++ b/docs/core-concepts/requests.mdx @@ -0,0 +1,78 @@ +--- +title: Requests Overview +--- + +In the context of the Kameo, requests are the means through which actors communicate and interact with each other. These interactions are encapsulated in two primary forms: ask requests and tell requests. Understanding the nuances between these two types of requests is crucial for effectively managing actor behaviors and ensuring the robustness of your application. + +### Ask Requests + +Ask requests are a form of message sending where the sender waits for a response from the receiver. This pattern is useful when the sender requires data or confirmation that an action has been completed before proceeding. Unlike tell requests, ask requests inherently support handling responses and errors, providing a direct way to deal with exceptional conditions. + +Key Features of Ask Requests: + +- **Reply Awaited**: The sender pauses its execution and waits for a reply, making it synchronous in nature within an asynchronous execution model. +- **Error Handling**: If an actor encounters an error while processing an ask request, the responsibility of handling these errors falls to the caller. This allows for more granular error management strategies. +- **Timeouts**: +- **Mailbox Timeout**: For actors with a bounded mailbox, an optional `mailbox_timeout` can be specified. This timeout represents the maximum duration the request will wait in the queue before being processed. If the mailbox is full beyond this duration, the request may be dropped or an error returned. +- **Reply Timeout**: A `reply_timeout` can also be set, indicating how long the sender will wait for a response. This is particularly useful for avoiding indefinite blocking in scenarios where the receiver might be unable to process the request promptly. + +### Tell Requests + +Tell requests, on the other hand, are the "fire-and-forget" type of messages. When a tell request is sent, the sender does not wait for any acknowledgment or reply from the receiver. This approach is ideal for notifications or commands where the outcome does not directly influence the sender's immediate actions. + +Characteristics of Tell Requests: + +- **No Reply**: The sender continues its execution without waiting for a response, embodying a truly asynchronous interaction pattern. +- **Error Handling**: Errors encountered by the actor while processing a tell request are treated as panics. By default, such panics may lead to the stopping of the actor, although this behavior can be customized via the `Actor::on_panic` hook to allow for error recovery or logging. +- **Mailbox Timeout**: Similar to ask requests, a `mailbox_timeout` can be set for tell requests sent to actors with bounded mailboxes. This timeout helps manage the queuing behavior in scenarios where the actor's mailbox might be at capacity, ensuring that the system can gracefully handle backpressure. + +### Request Methods + +Sending a message can be done using one of the traits/methods listed in this table. Each cell describes the behaviour of the implementation depending on the mailbox type. + +The column headings describe the following: + +- **Ask (bounded)**: refers to sending a message using `ask` on an actor with a `BoundedMailbox`. +- **Ask (unbounded)**: refers to sending a message using `ask` on an actor with an `UnboundedMailbox`. +- **Tell (bounded)**: refers to sending a message using `tell` on an actor with a `BoundedMailbox`. +- **Tell (unbounded)**: refers to sending a message using `tell` on an actor with an `UnboundedMailbox`. + + +| **Trait** **::** **Method** | **Ask (bounded)** | **Ask (unbounded)** | **Tell (bounded)** | **Tell (unbounded)** | +| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | ------------------------------ | +| `MessageSend` :: `send` | Sends a message, waiting for mailbox capacity and a reply. | Sends a message, waiting for a reply. | Sends a message, waiting for mailbox capacity. | Sends a message. | +| `MessageSendSync` :: `send_sync` | ❌ | ❌ | ❌ | Sends a message synchronously. | +| `TryMessageSend` :: `try_send` | Tries to send a message, waiting for a reply but failing if the mailbox is full. | Send a message, waiting for a reply. | Tries to send a message, but failing if the mailbox is full. | Sends a message. | +| `TryMessageSendSync` :: `try_send_sync` | ❌ | ❌ | Tries to send a message synchronously, but failing if the mailbox is full. | Sends a message synchronously. | +| `BlockingMessageSend` :: `blocking_send` | Sends a message, blocking the thread while waiting for mailbox capacity and a reply. | Sends a message, blocking the thread while waiting for a reply. | Sends a message, blocking the thread while waiting for mailbox capacity. | Sends a message. | +| `TryBlockingMessageSend` :: `try_blocking_send` | Tries to send a message, blocking the thread while waiting for a reply, but failing if the mailbox is full. | Tries to send a message, blocking the thread while waiting for a reply. | Tries to send a message, failing if the mailbox is full. | Sends a message. | +| `ForwardMessageSend` :: `forward` | Sends a message, waiting for mailbox capacity with the reply being forwarded to a provided ReplySender. | Sends a message, with the reply being forwarded to a provided ReplySender. | ❌ | ❌ | + +#### **Supported Requests** + +Depending on whether a message is being sent with a timeout set or to a remote actor, some methods may not be available. Below is table showing which methods are available under different circumstances. + +| | | | | | +|---|---|---|---|---| +|**Method**|**Ask (bounded)**|**Ask (unbounded)**|**Tell (bounded)**|**Tell (unbounded)**| +|`send`|✅ 📬 ⏳ 🌐|✅ ⏳ 🌐|✅ 📬 🌐|✅ 🌐| +|`send_sync`|❌|❌|❌|✅| +|`try_send`|✅ ⏳ 🌐|✅ ⏳ 🌐|✅ 🌐|✅ 🌐| +|`try_send_sync`|❌|❌|✅|✅| +|`blocking_send`|✅|✅|✅|✅| +|`try_blocking_send`|✅|✅|✅|✅| +|`forward`|✅ 📬|✅|❌|❌| + +**Legend** + +- ✅ **Supported**: Supported for local actors with no timeouts set +- 📬 **With mailbox timeout**: Supported for local actors with a mailbox timeout set +- ⏳ **With reply timeout**: Supported for local actors with a reply timeout set +- 🌐 **Remote**: Supported for remote actor messaging +- ❌ **Unsupported** + +--- + +#### Summary + +Requests, encompassing both the ask and tell patterns, offer versatile communication strategies within Kameo. This duality provides the flexibility to either await responses for critical operations or to proceed without direct feedback for more autonomous actions. Such versatility is key to supporting a broad spectrum of application requirements, from straightforward notifications to intricate data exchanges and control flows, enhancing the dynamism and efficiency of your actor interactions. diff --git a/docs/core-concepts/supervision.mdx b/docs/core-concepts/supervision.mdx new file mode 100644 index 0000000..645e67c --- /dev/null +++ b/docs/core-concepts/supervision.mdx @@ -0,0 +1,41 @@ +--- +title: Supervision Overview +--- + +Supervision is a critical concept in building resilient actor systems, ensuring that the system can recover from failures and continue operating without interruption. In Kameo, supervision and actor lifecycle management are facilitated through a combination of customizable behavior hooks and actor linking. This page discusses how to effectively use these features to create robust actor hierarchies and manage actor failures gracefully. + +### Customizing Actor Behavior on Panic + +When an actor panics, its default behavior can be customized using the `on_panic` hook within the `Actor` trait. This hook allows developers to define custom logic that should execute when an actor encounters a panic, providing a first line of defense in managing unexpected failures. + +### Linking Actors + +Beyond individual actor behavior, Kameo supports linking actors together to create a supervision tree. This structure enables actors to monitor each other's health and respond to failures, forming the backbone of a self-healing system. + +#### Actor Links + +Actors can be linked using two primary methods, which establish parent-child and sibling relationships: + +- `ActorRef::link_child` +- `ActorRef::link_together` + +#### Handling Link Failures + +When a linked actor dies, the surviving actors can react to this event using the `on_link_died` hook in the `Actor` trait. This hook provides the ID of the deceased actor and the reason for its termination, enabling the surviving actors to implement custom logic, such as restarting the failed actor or taking other remedial actions. + +The default behavior for `on_link_died` is to stop the current actor if the linked actor died for any reason other than a normal shutdown. This conservative default ensures that failures are not silently ignored, promoting system stability by preventing dependent actors from continuing in an inconsistent state. + +#### Unlinking Actors + +In some scenarios, it may be necessary to remove links between actors, either to restructure the supervision tree or in response to changing application dynamics. Kameo provides methods for this purpose: + +- `ActorRef::unlink_child`: Removes the link between a parent and its child actor. +- `ActorRef::unlink_together`: Removes the link between sibling actors. + +These methods allow for dynamic adjustments to the actor supervision hierarchy, ensuring that the system can adapt to new requirements or recover from errors by reorganizing actor relationships. + +--- + +#### Summary + +Supervision in Kameo is a powerful mechanism for building resilient, self-healing actor systems. By leveraging customizable panic behavior and actor linking, developers can design systems that are capable of recovering from failures, maintaining consistent operation through disruptions. Whether through parent-child hierarchies or peer relationships, actor links in Kameo provide the foundation for a robust supervision strategy, ensuring that actor systems can gracefully handle and recover from the inevitable challenges they face. diff --git a/docs/getting-started.mdx b/docs/getting-started.mdx new file mode 100644 index 0000000..1ab5771 --- /dev/null +++ b/docs/getting-started.mdx @@ -0,0 +1,87 @@ +--- +title: Getting Started +--- + +Welcome to Kameo, your gateway to building efficient, scalable, and resilient systems in Rust. This guide will walk you through the initial steps of installing Kameo and creating a simple "Hello, World!" application to get your feet wet in the world of asynchronous actors. + +## Installation + +Before diving into the world of Kameo, you'll need to ensure that your Rust development environment is set up. Kameo requires Rust 1.79, which you can install or update via [rustup](https://rustup.rs/). + +With Rust installed, you can add Kameo to your project by editing your `Cargo.toml` file: + +```toml +[dependencies] +kameo = "0.10.0" # Use the latest version +``` + +Alternatively you can run `cargo add kameo`. + +## Hello World Actor + +This example demonstrates a basic "Hello World" actor capable of handling a `Greet` message. It showcases the fundamental concepts of actor creation, message definition, and asynchronous message handling within Kameo. + +### Defining the Actor and Message + +First, we define a `HelloWorldActor` and a `Greet` message. The actor will process messages of type `Greet`, which contain a string greeting. + +```rust +use kameo::Actor; +use kameo::message::{Message, Context}; + +// Define the actor +#[derive(Actor)] +pub struct HelloWorldActor; + +// Define the message +pub struct Greet(String); + +// Implement the message handling for HelloWorldActor +impl Message for HelloWorldActor { + type Reply = (); // This actor sends no reply + + async fn handle( + &mut self, + Greet(greeting): Greet, // Destructure the Greet message to get the greeting string + _: Context<'_, Self, Self::Reply>, // The message handling context + ) -> Self::Reply { + println!("{greeting}"); // Print the greeting to the console + } +} +``` + +### Spawning the Actor and Sending a Message + +To interact with the `HelloWorldActor`, we spawn it and send a `Greet` message. This is done using the `spawn` function from Kameo and the `tell` method provided by the actor's reference, `actor_ref`. + +```rust +use kameo::spawn; +use kameo::request::MessageSend; + +#[tokio::main] // Mark the entry point as an asynchronous main function +async fn main() -> Result<(), Box> { // Use a Result return type for error handling + // Spawn the HelloWorldActor + let actor_ref = spawn(HelloWorldActor); + + // Send a Greet message to the actor + actor_ref + .tell(Greet("Hello, world!".to_string())) + .send() + .await?; + + Ok(()) +} +``` + +### Understanding the Code + +- **Actor Definition**: The `HelloWorldActor` is a simple actor that does not maintain any state and only prints out the greeting it receives. +- Message Handling: The `handle` method asynchronously processes the `Greet` message. It takes ownership of the message and a context parameter, which could be used for more advanced message handling scenarios. +- **Spawning and Messaging**: The `spawn` function creates an instance of the `HelloWorldActor` and returns a reference to it (`actor_ref`). The `tell` method is then used to send a `Greet` message to the actor. The `send` method is awaited to ensure the message is sent to the actors mailbox. +- **Asynchronous Runtime**: The example uses Tokio as the asynchronous runtime, indicated by the `#[tokio::main]` attribute. This is necessary for running asynchronous Rust code. + +### Next Steps + +This example is a starting point for building applications with Kameo. From here, you can explore more complex actor behaviors, state management, actor supervision, and building distributed systems with remote actors. + +Remember, the power of actors comes from their ability to encapsulate state and behavior, process messages concurrently, and interact in a decoupled manner. Experiment with these concepts to build scalable and resilient applications. diff --git a/docs/index.mdx b/docs/index.mdx new file mode 100644 index 0000000..f67ecc4 --- /dev/null +++ b/docs/index.mdx @@ -0,0 +1,22 @@ +--- +title: Welcome to Kameo +image: https://github.com/tqwewe/kameo/blob/main/banner.png?raw=true +--- + +Embarking on the journey of building software, you're often faced with the challenge of managing complexity, ensuring reliability, and achieving scalability. That's where Kameo steps in—a powerful, yet approachable, actor framework built on Tokio, a proven runtime in the Rust ecosystem renowned for its amazing capabilities for asynchronous and concurrent code. Kameo is designed to help you conquer these challenges head-on, offering a simplified approach to building robust applications. + +### Simplifying Concurrency + +At its core, Kameo simplifies the daunting world of concurrent programming. With its actor-based model, it abstracts away the nitty-gritty details of thread management, locking, and synchronization. Instead, you get to focus on what truly matters: designing your system's logic. By encapsulating state and behavior within actors that communicate through messages, Kameo enables you to build systems that are naturally concurrent and resilient. + +### Building Resilient Systems + +Reliability is non-negotiable in today's software landscape. Kameo is built with this principle in mind, offering robust supervision strategies that allow your system to recover from failures gracefully. Instead of painstakingly handling every possible error scenario, you can design your system to "let it crash" and rely on Kameo to manage the recovery process, keeping your application running smoothly and reliably. + +### Scalability Made Easy + +Whether you're developing a small utility or a large-scale distributed system, scalability is key. Kameo's lightweight actor model and efficient message-passing mechanisms make it inherently scalable. Your application can grow from handling dozens to millions of concurrent operations with minimal changes to the underlying architecture. + +### Why Kameo? + +In a world where complexity is the norm, Kameo stands out by offering simplicity, resilience, and scalability. It's not just about making concurrent programming easier—it's about empowering you to build the reliable, efficient, and scalable systems that today's users demand. Whether you're a seasoned developer or just starting out, Kameo is designed to be relatable and accessible, providing you with the tools you need to bring your ideas to life.