rabbitmesh/
lib.rs

1//! # RabbitMesh - Zero-Port Microservices Framework
2//!
3//! **Build elegant microservices with simple macros - write only business logic!**
4//!
5//! RabbitMesh revolutionizes microservices by eliminating port management through pure RabbitMQ 
6//! communication. Services are defined with clean Rust macros, and everything else is auto-generated.
7//!
8//! ## ✨ The Magic
9//!
10//! ```rust,no_run
11//! use rabbitmesh_macros::{service_definition, service_impl};
12//! use serde::{Deserialize, Serialize};
13//!
14//! #[derive(Deserialize)]
15//! pub struct CreateUserRequest {
16//!     pub username: String,
17//!     pub email: String,
18//! }
19//!
20//! #[derive(Serialize)]
21//! pub struct UserResponse {
22//!     pub success: bool,
23//!     pub message: String,
24//! }
25//!
26//! // Define your service with macros
27//! #[service_definition]
28//! pub struct UserService;
29//!
30//! // Implement business logic only - framework handles everything else!
31//! #[service_impl]
32//! impl UserService {
33//!     #[service_method("POST /users")]
34//!     pub async fn create_user(request: CreateUserRequest) -> Result<UserResponse, String> {
35//!         // JUST YOUR BUSINESS LOGIC!
36//!         // Framework automatically handles:
37//!         // ✅ HTTP route extraction (POST /users)  
38//!         // ✅ RabbitMQ RPC registration
39//!         // ✅ JSON serialization/deserialization
40//!         // ✅ API Gateway integration
41//!         // ✅ Service discovery
42//!         
43//!         println!("Creating user: {}", request.username);
44//!         Ok(UserResponse {
45//!             success: true,
46//!             message: "User created successfully!".to_string(),
47//!         })
48//!     }
49//!
50//!     #[service_method("GET /users/:id")]
51//!     pub async fn get_user(user_id: String) -> Result<UserResponse, String> {
52//!         // Framework auto-extracts 'user_id' from URL path
53//!         println!("Getting user: {}", user_id);
54//!         Ok(UserResponse {
55//!             success: true,
56//!             message: format!("Retrieved user {}", user_id),
57//!         })
58//!     }
59//! }
60//!
61//! #[tokio::main]
62//! async fn main() -> anyhow::Result<()> {
63//!     // Initialize service (for stateful services)
64//!     // UserService::init().await?;
65//!     
66//!     // Create and start service - that's it!
67//!     let service = UserService::create_service("amqp://guest:guest@localhost:5672/%2f").await?;
68//!     
69//!     println!("🚀 UserService started!");
70//!     println!("🎯 Service name: {}", UserService::service_name());
71//!     
72//!     // Show the magic - auto-discovered routes
73//!     let routes = UserService::get_routes();
74//!     println!("✨ Auto-discovered {} routes:", routes.len());
75//!     for (route, method) in routes {
76//!         println!("   {} -> {}", method, route);
77//!     }
78//!     
79//!     service.start().await?;
80//!     Ok(())
81//! }
82//! ```
83//!
84//! ## 🪄 What RabbitMesh Does Automatically
85//!
86//! When you write `#[service_method("POST /users")]`, the framework automatically:
87//!
88//! - ✅ **Extracts HTTP route** from annotation (`POST /users`)
89//! - ✅ **Registers RPC handler** for the method (`create_user`) 
90//! - ✅ **Sets up RabbitMQ queues** (`rabbitmesh.UserService.create_user`)
91//! - ✅ **Handles serialization** (JSON request/response)
92//! - ✅ **Creates gateway endpoint** (HTTP API automatically available)
93//! - ✅ **Enables service discovery** (other services can call this method)
94//! - ✅ **Provides health checks** and monitoring
95//! - ✅ **Implements fault tolerance** (retries, circuit breakers)
96//!
97//! **You write**: 5-10 lines of business logic  
98//! **Framework provides**: Everything else (hundreds of lines worth!)
99//!
100//! ## 🏗️ Zero-Port Architecture
101//!
102//! **Traditional Microservices:**
103//! ```text
104//! Service A:8080 ←HTTP→ Service B:8081 ←HTTP→ Service C:8082
105//! ❌ Port management hell
106//! ❌ Service discovery complexity  
107//! ❌ Load balancing configuration
108//! ```
109//!
110//! **RabbitMesh:**
111//! ```text
112//! Service A ←RabbitMQ→ Service B ←RabbitMQ→ Service C
113//!          ↘           ↓           ↙
114//!            Auto-Generated Gateway:3000 ←HTTP← Clients
115//! ✅ Zero port management between services
116//! ✅ Automatic service discovery
117//! ✅ Built-in load balancing and fault tolerance
118//! ```
119//!
120//! ## 🎨 Method Signature Patterns
121//!
122//! RabbitMesh supports clean, intuitive method signatures:
123//!
124//! ```rust,no_run
125//! # use rabbitmesh_macros::{service_definition, service_impl};
126//! # use serde::{Deserialize, Serialize};
127//! # #[derive(Deserialize)] pub struct CreateUserRequest { pub name: String }
128//! # #[derive(Deserialize)] pub struct UpdateUserRequest { pub name: String }
129//! # #[derive(Serialize)] pub struct UserResponse { pub success: bool }
130//! # #[service_definition] pub struct UserService;
131//! #[service_impl]
132//! impl UserService {
133//!     // Simple parameter
134//!     #[service_method("GET /users/:id")]
135//!     async fn get_user(user_id: String) -> Result<UserResponse, String> {
136//!         // user_id auto-extracted from URL path
137//!         Ok(UserResponse { success: true })
138//!     }
139//!
140//!     // Request body
141//!     #[service_method("POST /users")]
142//!     async fn create_user(request: CreateUserRequest) -> Result<UserResponse, String> {
143//!         // request auto-deserialized from JSON
144//!         Ok(UserResponse { success: true })
145//!     }
146//!
147//!     // Path parameter + request body (tuple)
148//!     #[service_method("PUT /users/:id")]
149//!     async fn update_user(params: (String, UpdateUserRequest)) -> Result<UserResponse, String> {
150//!         let (user_id, request) = params;
151//!         Ok(UserResponse { success: true })
152//!     }
153//!
154//!     // Multiple path parameters
155//!     #[service_method("GET /users/:user_id/posts/:post_id")]
156//!     async fn get_user_post(params: (String, String)) -> Result<UserResponse, String> {
157//!         let (user_id, post_id) = params;
158//!         Ok(UserResponse { success: true })
159//!     }
160//! }
161//! ```
162//!
163//! ## 🚀 Service-to-Service Communication
164//!
165//! Services communicate via RabbitMQ automatically:
166//!
167//! ```rust,no_run
168//! use rabbitmesh::ServiceClient;
169//!
170//! # #[tokio::main]
171//! # async fn main() -> anyhow::Result<()> {
172//! // From API Gateway or another service
173//! let client = ServiceClient::new("api-gateway", "amqp://localhost:5672").await?;
174//! let response = client.call("user-service", "get_user", "user123").await?;
175//! # Ok(())
176//! # }
177//! ```
178//!
179//! ## 🎯 Key Features
180//!
181//! - **🪄 Zero Configuration**: Routes extracted from code annotations
182//! - **🚀 Auto-Generated Gateway**: HTTP API created from service definitions
183//! - **🔌 Zero Ports**: Services communicate only via RabbitMQ  
184//! - **🔍 Auto-Discovery**: Services find each other automatically
185//! - **⚡ High Performance**: Built on Tokio async runtime
186//! - **🛡️ Fault Tolerance**: Built-in retry mechanisms and circuit breakers
187//! - **📊 Observability**: Structured logging and health checks
188//! - **🎨 Clean Code**: Write only business logic, framework handles the rest
189//!
190//! ## 📚 Examples
191//!
192//! See the `examples/` directory for complete working examples:
193//! - **Simple Todo Service**: Basic CRUD operations with auto-generated routes
194//! - **Authentication Service**: JWT tokens, user management, password hashing
195//! - **Blog Platform**: Multi-service architecture with auto-discovery
196//!
197//! ## 🤖 AI Assistant
198//!
199//! Get help building services with our AI agent:
200//! ```bash
201//! python rabbitmesh_agent.py "build me an authentication service"
202//! ```
203//!
204//! ## 🧪 Requirements
205//!
206//! - **Rust**: 1.70+
207//! - **RabbitMQ**: 3.8+ 
208//! - **Dependencies**: `rabbitmesh-macros`, `serde`, `tokio`
209//!
210//! ---
211//!
212//! **Ready to build the future of microservices?** 🚀
213//!
214//! *Zero ports, maximum power, pure elegance.*
215
216pub mod connection;
217pub mod message;
218pub mod rpc;
219pub mod service;
220pub mod client;
221pub mod error;
222
223pub use connection::{ConnectionManager, ConnectionConfig};
224pub use message::{Message, MessageType, RpcRequest, RpcResponse};
225pub use rpc::{RpcHandler, RpcFramework};
226pub use service::{MicroService, ServiceConfig, ServiceClient as ServiceClientFromService};
227
228// Convenient alias for the main service
229pub use service::MicroService as Service;
230pub use client::ServiceClient;
231pub use error::{RabbitMeshError, Result};