Hexser - Zero-Boilerplate Hexagonal Architecture

Zero-boilerplate hexagonal architecture with graph-based introspection for Rust.
The hexser crate provides reusable generic types and traits for implementing Hexagonal Architecture (Ports and Adapters pattern) with automatic graph construction, intent inference, and architectural validation. Write business logic, let hexser handle the architecture.
Table of Contents
Tip: Press Cmd/Ctrl+F and search for βPartβ to jump to tutorials.
Why hexser?
Traditional hexagonal architecture requires significant boilerplate:
- Manual registration of components
- Explicit dependency wiring
- Repetitive trait implementations
- Complex validation logic
hexser eliminates all of this. Through intelligent trait design, compile-time graph construction, and rich error handling, you get:
Quick Start
Add to your Cargo.toml:
[dependencies]
hexser = "0.4.1"
Your First Hexagonal Application
use hexser::prelude::*;
#[derive(HexEntity)]
struct User {
id: String,
email: String,
name: String,
}
#[derive(HexPort)]
trait UserRepository: Repository<User> {
fn find_by_email(&self, email: &str) -> HexResult<Option<User>>;
}
#[derive(HexAdapter)]
struct InMemoryUserRepository {
users: Vec<User>,
}
impl Repository<User> for InMemoryUserRepository {
fn find_by_id(&self, id: &String) -> HexResult<Option<User>> {
Ok(self.users.iter().find(|u| &u.id == id).cloned())
}
fn save(&mut self, user: User) -> HexResult<()> {
self.users.push(user);
Ok(())
}
fn delete(&mut self, id: &String) -> HexResult<()> {
self.users.retain(|u| &u.id != id);
Ok(())
}
fn find_all(&self) -> HexResult<Vec<User>> {
Ok(self.users.clone())
}
}
impl UserRepository for InMemoryUserRepository {
fn find_by_email(&self, email: &str) -> HexResult<Option<User>> {
Ok(self.users.iter().find(|u| u.email == email).cloned())
}
}
fn main() -> HexResult<()> {
let mut repo = InMemoryUserRepository { users: Vec::new() };
let user = User {
id: "1".to_string(),
email: "alice@example.com".to_string(),
name: "Alice".to_string(),
};
repo.save(user)?;
let found = repo.find_by_email("alice@example.com")?;
println!("Found: {:?}", found.map(|u| u.name));
Ok(())
}
That's it! You've just built a hexagonal architecture application with:
- Clear layer separation
- Type-safe interfaces
- Testable components
- Swappable implementations
Complete Tutorial
Part 1: Understanding Hexagonal Architecture
Hexagonal Architecture (also known as Ports and Adapters) structures applications into concentric layers:
βββββββββββββββββββββββββββββββββββββββββββββββ
β Infrastructure Layer β
β (Databases, APIs, External Services) β
β β
β βββββββββββββββββββββββββββββββββββββββββ β
β β Adapters Layer β β
β β (Concrete Implementations) β β
β β β β
β β βββββββββββββββββββββββββββββββββββ β β
β β β Ports Layer β β β
β β β (Interfaces/Contracts) β β β
β β β β β β
β β β βββββββββββββββββββββββββββββ β β β
β β β β Domain Layer β β β β
β β β β (Business Logic) β β β β
β β β βββββββββββββββββββββββββββββ β β β
β β βββββββββββββββββββββββββββββββββββ β β
β βββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββ
Key Principles:
- Dependency Rule: Dependencies point inward (Domain has no dependencies)
- Port Interfaces: Define what the domain needs (don't dictate how)
- Adapter Implementations: Provide concrete implementations using specific tech
- Testability: Mock adapters for testing without infrastructure
Part 2: The Five Layers
- Domain Layer - Your Business Logic
The domain layer contains your core business logic, completely independent of frameworks or infrastructure.
Entities - Things with identity:
use hexser::prelude::*;
#[derive(HexEntity)]
struct Order {
id: OrderId,
customer_id: CustomerId,
items: Vec<OrderItem>,
status: OrderStatus,
}
impl Aggregate for Order {
fn check_invariants(&self) -> HexResult<()> {
if self.items.is_empty() {
return Err(hexser::hex_domain_error!(
hexser::error::codes::domain::INVARIANT_EMPTY,
"Order must contain at least one item"
).with_next_step("Add at least one item"));
}
Ok(())
}
}
Value Objects - Things defined by values:
#[derive(Clone, PartialEq, Eq, HexValueObject)]
struct Email(String);
impl Email {
fn validate(&self) -> HexResult<()> {
if !self.0.contains('@') {
return Err(Hexserror::validation("Email must contain @"));
}
Ok(())
}
}
Domain Events - Things that happened:
#[derive(HexDomainEvent)]
struct OrderPlaced {
order_id: OrderId,
customer_id: CustomerId,
timestamp: u64,
}
Domain Services - Operations spanning multiple entities:
#[derive(HexDomainService)]
struct PricingService;
impl PricingService {
fn calculate_order_total(&self, order: &Order) -> Money {
order.items
.iter()
.map(|item| item.price * item.quantity)
.sum()
}
}
- Ports Layer - Your Interfaces
Ports define the contracts between your domain and the outside world.
Repositories - Persistence abstraction:
#[derive(HexPort)]
trait OrderRepository: Repository<Order> {
fn find_by_customer(&self, customer_id: &CustomerId)
-> HexResult<Vec<Order>>;
fn find_pending(&self) -> HexResult<Vec<Order>>;
}
Use Cases - Business operations:
#[derive(HexPort)]
trait PlaceOrder: UseCase<PlaceOrderInput, PlaceOrderOutput> {}
struct PlaceOrderInput {
customer_id: CustomerId,
items: Vec<OrderItem>,
}
struct PlaceOrderOutput {
order_id: OrderId,
}
Queries - Read operations (CQRS):
#[derive(HexPort)]
trait OrderHistory: Query<OrderHistoryParams, Vec<OrderView>> {}
struct OrderHistoryParams {
customer_id: CustomerId,
from_date: u64,
to_date: u64,
}
struct OrderView {
order_id: String,
total: f64,
status: String,
}
- Adapters Layer - Your Implementations
Adapters implement ports using specific technologies.
Database Adapter:
#[derive(HexAdapter)]
struct PostgresOrderRepository {
pool: PgPool,
}
impl Repository<Order> for PostgresOrderRepository {
fn find_by_id(&self, id: &OrderId) -> HexResult<Option<Order>> {
todo!()
}
fn save(&mut self, order: Order) -> HexResult<()> {
todo!()
}
}
impl OrderRepository for PostgresOrderRepository {
fn find_by_customer(&self, customer_id: &CustomerId)
-> HexResult<Vec<Order>> {
todo!()
}
fn find_pending(&self) -> HexResult<Vec<Order>> {
todo!()
}
}
API Adapter:
#[derive(HexAdapter)]
struct RestPaymentGateway {
client: reqwest::Client,
api_key: String,
}
impl PaymentPort for RestPaymentGateway {
fn charge(&self, amount: Money, card: &Card) -> HexResult<PaymentResult> {
todo!()
}
}
Mapper - Data transformation:
#[derive(HexAdapter)]
struct OrderMapper;
impl Mapper<Order, DbOrderRow> for OrderMapper {
fn map(&self, order: Order) -> HexResult<DbOrderRow> {
Ok(DbOrderRow {
id: order.id.to_string(),
customer_id: order.customer_id.to_string(),
items_json: serde_json::to_string(&order.items)?,
status: order.status.to_string(),
})
}
}
- Application Layer - Your Orchestration
The application layer coordinates domain logic and ports.
Directive (Write Operation):
#[derive(HexDirective)]
struct PlaceOrderDirective {
customer_id: CustomerId,
items: Vec<OrderItem>,
}
impl PlaceOrderDirective {
fn validate(&self) -> HexResult<()> {
if self.items.is_empty() {
return Err(Hexserror::validation("Items cannot be empty"));
}
Ok(())
}
}
Directive Handler:
#[derive(HexDirectiveHandler)]
struct PlaceOrderHandler {
order_repo: Box<dyn OrderRepository>,
payment_port: Box<dyn PaymentPort>,
}
impl PlaceOrderHandler {
fn handle(&self, directive: PlaceOrderDirective) -> HexResult<()> {
directive.validate()?;
let order = Order::new(directive.customer_id, directive.items)?;
order.check_invariants()?;
self.order_repo.save(order)?;
self.payment_port.charge(order.total(), &order.payment_method)?;
Ok(())
}
}
Query Handler:
#[derive(HexQueryHandler)]
struct OrderHistoryHandler {
query_repo: Box<dyn OrderQueryRepository>,
}
impl OrderHistoryHandler {
fn handle(&self, params: OrderHistoryParams) -> HexResult<Vec<OrderView>> {
self.query_repo.get_order_history(
¶ms.customer_id,
params.from_date,
params.to_date
)
}
}
- Infrastructure Layer - Your Technology
Infrastructure provides the concrete technology implementations.
#[derive(HexConfig)]
struct DatabaseConfig {
connection_string: String,
pool_size: u32,
}
impl DatabaseConfig {
fn create_pool(&self) -> PgPool {
todo!()
}
}
Part 3: CQRS Pattern with hex
hexser supports Command Query Responsibility Segregation (CQRS) out of the box.
Write Side (Directives):
#[derive(HexDirective)]
struct UpdateUserEmail {
user_id: UserId,
new_email: Email,
}
impl UpdateUserEmail {
fn validate(&self) -> HexResult<()> {
self.new_email.validate()
}
}
#[derive(HexDirectiveHandler)]
struct UpdateUserEmailHandler {
repo: Box<dyn UserRepository>,
}
impl UpdateUserEmailHandler {
fn handle(&self, directive: UpdateUserEmail) -> HexResult<()> {
let mut user = self.repo.find_by_id(&directive.user_id)?
.ok_or_else(|| Hexserror::not_found("User", &directive.user_id))?;
user.email = directive.new_email;
self.repo.save(user)?;
Ok(())
}
}
Read Side (Queries):
#[derive(HexQuery)]
struct FindUserByEmail {
email: String,
}
#[derive(HexQueryHandler)]
struct FindUserByEmailHandler {
query_repo: Box<dyn UserQueryRepository>,
}
impl FindUserByEmailHandler {
fn handle(&self, query: FindUserByEmail)
-> HexResult<Option<UserView>> {
self.query_repo.find_by_email(&query.email)
}
}
Part 4: Testing Your Hexagonal Application
Hexagonal architecture makes testing trivial - just mock the ports!
Unit Testing Domain Logic:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_order_invariants() {
let order = Order {
id: OrderId::new(),
customer_id: CustomerId::new(),
items: vec![], status: OrderStatus::Pending,
};
assert!(order.check_invariants().is_err());
}
#[test]
fn test_email_validation() {
let invalid = Email("notanemail".to_string());
assert!(invalid.validate().is_err());
let valid = Email("test@example.com".to_string());
assert!(valid.validate().is_ok());
}
}
Testing with Mock Adapters:
#[derive(HexAdapter)]
struct MockUserRepository {
users: std::collections::HashMap<UserId, User>,
}
impl Repository<User> for MockUserRepository {
fn find_by_id(&self, id: &UserId) -> HexResult<Option<User>> {
Ok(self.users.get(id).cloned())
}
fn save(&mut self, user: User) -> HexResult<()> {
self.users.insert(user.id.clone(), user);
Ok(())
}
}
#[test]
fn test_create_user_handler() {
let mut repo = MockUserRepository {
users: std::collections::HashMap::new(),
};
let handler = CreateUserHandler {
repo: Box::new(repo),
};
let directive = CreateUserDirective {
email: "test@example.com".to_string(),
name: "Test User".to_string(),
};
assert!(handler.handle(directive).is_ok());
}
Part 5: Error Handling
hexser provides rich, actionable, code-first errors with automatic source location and layering support. Prefer the new macro-based constructors and error codes over manual struct construction.
Preferred: macro + code + guidance
fn validate_order(order: &Order) -> HexResult<()> {
if order.items.is_empty() {
return Err(
hexser::hex_domain_error!(
hexser::error::codes::domain::INVARIANT_EMPTY,
"Order must contain at least one item"
)
.with_next_steps(&["Add at least one item to the order"]) .with_suggestions(&["order.add_item(item)", "order.items.push(item)"]) .with_more_info("https://docs.rs/hexser/latest/hexser/error/codes/domain")
);
}
Ok(())
}
Display output (example):
E_HEX_001: Order must contain at least one item
at src/domain/order.rs:42:13
Next steps:
- Add at least one item to the order
Suggestions:
- order.add_item(item)
- order.items.push(item)
Cookbook
return Err(hexser::error::hex_error::Hexserror::validation_field(
"Title cannot be empty",
"title",
));
return Err(hexser::error::hex_error::Hexserror::not_found("User", "123")
.with_next_step("Verify the ID and try again"));
let port_err = hexser::hex_port_error!(
hexser::error::codes::port::PORT_TIMEOUT,
"User service timed out"
).with_suggestion("Increase timeout or retry later");
fn fetch_from_api(url: &str) -> HexResult<String> {
let resp = std::fs::read_to_string(url)
.map_err(|ioe| hexser::hex_adapter_error!(
hexser::error::codes::adapter::IO_FAILURE, "Failed to fetch resource"
).with_source(ioe))?;
Ok(resp)
}
π₯ Amazing Example: Layered mapping (Adapter β Port β Domain)
fn db_get_user(id: &str) -> HexResult<User> {
let conn = std::fs::read_to_string("/tmp/mock-db").map_err(|e|
hexser::hex_adapter_error!(
hexser::error::codes::adapter::DB_CONNECTION_FAILURE,
"Database unavailable"
)
.with_source(e)
.with_next_steps(&["Ensure DB is running", "Check connection string"])
)?;
Err(hexser::error::hex_error::Hexserror::not_found("User", id))
}
fn port_get_user(id: &str) -> HexResult<User> {
db_get_user(id).map_err(|e|
hexser::hex_port_error!(
hexser::error::codes::port::COMMUNICATION_FAILURE,
"UserRepository failed"
).with_source(e)
)
}
fn ensure_user_exists(id: &str) -> HexResult<()> {
let _user = port_get_user(id)?; Ok(())
}
Notes
- All hexser errors implement std::error::Error and the RichError trait (code, message, next_steps, suggestions, location, more_info, source).
- Prefer hex_domain_error!, hex_port_error!, hex_adapter_error! and constants from hexser::error::codes::*.
- Use with_source(err) to preserve underlying causes; Display shows a helpful, compact summary.
Part 6: Real-World Example - TODO Application
Let's build a complete TODO application using hexagonal architecture.
Domain Layer:
use hexser::prelude::*;
#[derive(Clone, HexEntity)]
struct Todo {
id: TodoId,
title: String,
description: String,
completed: bool,
}
#[derive(Clone, PartialEq, Eq, Hash)]
struct TodoId(String);
impl TodoId {
fn new() -> Self {
Self(uuid::Uuid::new_v4().to_string())
}
}
Ports Layer:
#[derive(HexPort)]
trait TodoRepository: Repository<Todo> {
fn find_active(&self) -> HexResult<Vec<Todo>>;
fn find_completed(&self) -> HexResult<Vec<Todo>>;
}
Adapters Layer:
#[derive(HexAdapter)]
struct InMemoryTodoRepository {
todos: std::sync::Mutex<Vec<Todo>>,
}
impl Repository<Todo> for InMemoryTodoRepository {
fn find_by_id(&self, id: &TodoId) -> HexResult<Option<Todo>> {
let todos = self.todos.lock().unwrap();
Ok(todos.iter().find(|t| &t.id == id).cloned())
}
fn save(&mut self, todo: Todo) -> HexResult<()> {
let mut todos = self.todos.lock().unwrap();
if let Some(existing) = todos.iter_mut().find(|t| t.id == todo.id) {
*existing = todo;
} else {
todos.push(todo);
}
Ok(())
}
fn delete(&mut self, id: &TodoId) -> HexResult<()> {
let mut todos = self.todos.lock().unwrap();
todos.retain(|t| &t.id != id);
Ok(())
}
fn find_all(&self) -> HexResult<Vec<Todo>> {
let todos = self.todos.lock().unwrap();
Ok(todos.clone())
}
}
impl TodoRepository for InMemoryTodoRepository {
fn find_active(&self) -> HexResult<Vec<Todo>> {
let todos = self.todos.lock().unwrap();
Ok(todos.iter().filter(|t| !t.completed).cloned().collect())
}
fn find_completed(&self) -> HexResult<Vec<Todo>> {
let todos = self.todos.lock().unwrap();
Ok(todos.iter().filter(|t| t.completed).cloned().collect())
}
}
Application Layer:
#[derive(HexDirective)]
struct CreateTodoDirective {
title: String,
description: String,
}
impl CreateTodoDirective {
fn validate(&self) -> HexResult<()> {
if self.title.is_empty() {
return Err(Hexserror::validation_field("Title cannot be empty", "title"));
}
Ok(())
}
}
#[derive(HexDirectiveHandler)]
struct CreateTodoHandler {
repo: Box<dyn TodoRepository>,
}
impl CreateTodoHandler {
fn handle(&self, directive: CreateTodoDirective) -> HexResult<()> {
directive.validate()?;
let todo = Todo {
id: TodoId::new(),
title: directive.title,
description: directive.description,
completed: false,
};
self.repo.save(todo)?;
Ok(())
}
}
π Advanced Patterns
Event Sourcing
#[derive(HexAggregate)]
struct OrderAggregate {
id: OrderId,
uncommitted_events: Vec<Box<dyn DomainEvent>>,
}
impl OrderAggregate {
fn place_order(&mut self, items: Vec<OrderItem>) -> HexResult<()> {
if items.is_empty() {
return Err(hexser::hex_domain_error!(
hexser::error::codes::domain::INVARIANT_EMPTY,
"Order must have items"
));
}
let event = OrderPlaced {
order_id: self.id.clone(),
items,
timestamp: current_timestamp(),
};
self.apply_event(&event);
self.uncommitted_events.push(Box::new(event));
Ok(())
}
fn apply_event(&mut self, event: &dyn DomainEvent) {
}
}
Dependency Injection
struct ApplicationContext {
user_repo: Box<dyn UserRepository>,
order_repo: Box<dyn OrderRepository>,
payment_port: Box<dyn PaymentPort>,
}
impl ApplicationContext {
fn new_production() -> Self {
Self {
user_repo: Box::new(PostgresUserRepository::new()),
order_repo: Box::new(PostgresOrderRepository::new()),
payment_port: Box::new(StripePaymentGateway::new()),
}
}
fn new_test() -> Self {
Self {
user_repo: Box::new(MockUserRepository::new()),
order_repo: Box::new(MockOrderRepository::new()),
payment_port: Box::new(MockPaymentGateway::new()),
}
}
}
π Knowledge Graph
hexser/
βββ domain/ [Core Business Logic - No Dependencies]
β βββ Entity - Identity-based objects
β βββ ValueObject - Value-based objects
β βββ Aggregate - Consistency boundaries
β βββ DomainEvent - Significant occurrences
β βββ DomainService - Cross-entity operations
β
βββ ports/ [Interface Definitions]
β βββ Repository - Persistence abstraction
β βββ UseCase - Business operations
β βββ Query - Read-only operations (CQRS)
β βββ InputPort - Entry points
β βββ OutputPort - External system interfaces
β
βββ adapters/ [Concrete Implementations]
β βββ Adapter - Port implementations
β βββ Mapper - Data transformation
β
βββ application/ [Orchestration Layer]
β βββ Directive - Write operations (CQRS)
β βββ DirectiveHandler - Directive execution
β βββ QueryHandler - Query execution
β
βββ infrastructure/ [Technology Layer]
β βββ Config - Infrastructure setup
β
βββ error/ [Rich Error Types]
β βββ Hexserror - Actionable errors
β
βββ graph/ [Introspection - Phase 2+]
βββ Layer - Architectural layers
βββ Role - Component roles
βββ Relationship - Component connections
βββ NodeId - Unique identification
π‘ Design Philosophy
- "Language of the Language": Use Rust's type system to express architecture
- Zero Boilerplate: Derive everything, configure nothing
- Compile-Time Guarantees: Catch errors before runtime
- Rich Errors: Every error is helpful and actionable
- Self-Documenting: Graph reveals architecture automatically
- Testability First: Mock anything, test everything
π€ Contributing
We welcome contributions! This crate follows strict coding standards:
- One item per file: Each file contains one logical item
- No imports: Fully qualified paths (except std prelude)
- Documentation: Every item has //! and /// docs
- In-file tests: Tests live with the code they test
- No unsafe: Safe Rust only
- Rust 2024: Latest edition
See CONTRIBUTING.md for details.
π License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
at your option.
π Acknowledgments
Inspired by:
- CEQRS by Scott Wyatt
- N Lang by Scott Wyatt
- Domain-Driven Design by Eric Evans
- Hexagonal Architecture by Alistair Cockburn
- Clean Architecture by Robert C. Martin
- Rust's type system and error handling
- The Rust community's commitment to excellence
π Additional Resources
- Hexagonal Architecture Explained
- Domain-Driven Design
- CQRS Pattern
- Ports and Adapters
π― Examples & Tutorials
The hex crate includes comprehensive examples and tutorials to help you learn hexagonal architecture.
Running Examples
cargo run --example simple_todo
π§ͺ Potions (copy-friendly examples)
Looking for concrete, minimal examples you can paste into your app?
Check out the Potions crate in this workspace:
- Path: ./hexser_potions
- Crate: hexser_potions
- Focus: small, mixable examples (auth signup, CRUD, etc.)
Add to your project via workspace path:
[dependencies]
hexser_potions = { path = "../hexser_potions", version = "0.4.1" }
Then in code:
use hexser_potions::auth::{SignUpUser, InMemoryUserRepository, execute_signup};
βοΈ Static (non-dyn) DI β WASM-friendly
When you want zero dynamic dispatch and the smallest possible runtime footprint (including on wasm32-unknown-unknown), use the new static DI utilities.
Feature flags:
- Enabled by default:
static-di
- Opt-in for dyn container (tokio-based):
container
Static DI provides two simple building blocks:
StaticContainer<T>: owns your fully built object graph
hex_static! { ... } macro: builds the graph from a block without any dyn
Example:
use hexser::prelude::*;
#[derive(Clone, Debug)]
struct Repo;
#[derive(Clone, Debug)]
struct Service { repo: Repo }
let app = hexser::hex_static!({
let repo = Repo;
let service = Service { repo: repo.clone() };
(repo, service)
});
let (repo, service) = app.into_inner();
WASM guidance:
- Default features are WASM-friendly (no tokio). Keep
container disabled for wasm.
- Use
static-di (default) and avoid the dyn container for maximum compatibility.
Repository: Filter-based queries (vNext)
We are migrating the repository port away from id-centric methods (find_by_id/find_all) toward a generic, filter-oriented API that better models your domain while staying storage-agnostic. The new QueryRepository trait introduces domain-owned Filter and SortKey types plus FindOptions for sorting and pagination.
Highlights:
- Define small Filter and SortKey enums/structs in your domain
- Use find_one for unique lookups and find for lists with sorting/pagination
- Legacy methods are still available but deprecated; prefer the new API
Example:
use hexser::prelude::*;
use hexser::ports::repository::{QueryRepository, FindOptions, Sort, Direction};
#[derive(HexEntity, Clone, Debug)]
struct User { id: String, email: String, created_at: u64 }
#[derive(Clone, Debug)]
enum UserFilter {
ById(String),
ByEmail(String),
All,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum UserSortKey { CreatedAt, Email }
#[derive(Default)]
struct InMemoryUserRepository { users: Vec<User> }
impl Repository<User> for InMemoryUserRepository {
fn find_by_id(&self, id: &String) -> HexResult<Option<User>> { Ok(self.users.iter().find(|u| &u.id == id).cloned()) }
fn save(&mut self, user: User) -> HexResult<()> { if let Some(i)=self.users.iter().position(|u| u.id==user.id){self.users[i]=user;} else { self.users.push(user);} Ok(()) }
fn delete(&mut self, id: &String) -> HexResult<()> { self.users.retain(|u| &u.id != id); Ok(()) }
fn find_all(&self) -> HexResult<Vec<User>> { Ok(self.users.clone()) }
}
impl QueryRepository<User> for InMemoryUserRepository {
type Filter = UserFilter;
type SortKey = UserSortKey;
fn find_one(&self, f: &Self::Filter) -> HexResult<Option<User>> {
Ok(self.users.iter().find(|u| match f { UserFilter::ById(id)=>&u.id==id, UserFilter::ByEmail(e)=>&u.email==e, UserFilter::All=>true }).cloned())
}
fn find(&self, f: &Self::Filter, opts: FindOptions<Self::SortKey>) -> HexResult<Vec<User>> {
let mut items: Vec<_> = self.users.iter().filter(|u| match f { UserFilter::ById(id)=>&u.id==id, UserFilter::ByEmail(e)=>&u.email==e, UserFilter::All=>true }).cloned().collect();
if let Some(sorts) = opts.sort {
for s in sorts.into_iter().rev() {
match (s.key, s.direction) {
(UserSortKey::CreatedAt, Direction::Asc) => items.sort_by_key(|u| u.created_at),
(UserSortKey::CreatedAt, Direction::Desc) => items.sort_by_key(|u| std::cmp::Reverse(u.created_at)),
(UserSortKey::Email, Direction::Asc) => items.sort_by(|a,b| a.email.cmp(&b.email)),
(UserSortKey::Email, Direction::Desc) => items.sort_by(|a,b| b.email.cmp(&a.email)),
}
}
}
let offset = opts.offset.unwrap_or(0) as usize;
let limit = opts.limit.map(|l| l as usize).unwrap_or_else(|| items.len().saturating_sub(offset));
let end = offset.saturating_add(limit).min(items.len());
Ok(items.into_iter().skip(offset).take(end.saturating_sub(offset)).collect())
}
}
fn main() -> HexResult<()> {
let repo = InMemoryUserRepository::default();
let _ = <InMemoryUserRepository as QueryRepository<User>>::find_one(&repo, &UserFilter::ByEmail("alice@ex.com".into()))?;
let opts = FindOptions { sort: Some(vec![Sort { key: UserSortKey::CreatedAt, direction: Direction::Desc }]), limit: Some(25), offset: Some(0) };
let _page = <InMemoryUserRepository as QueryRepository<User>>::find(&repo, &UserFilter::All, opts)?;
Ok(())
}
Migration tips:
- find_by_id(id) -> find_one(&Filter::ById(id))
- find_all() -> find(&Filter::All, FindOptions::default())
- Add sorting/pagination via FindOptions { sort, limit, offset }
For more details, see MIGRATION_GUIDE.md and docs/core-concepts.md.
v0.4 QueryRepository Examples (5+)
The following focused examples demonstrate the new query-first API using domain-owned Filter and SortKey types. These snippets avoid deprecated methods and illustrate common tasks.
- Unique lookup with find_one
let repo = InMemoryUserRepository::default();
let maybe_user = <InMemoryUserRepository as hexser::ports::repository::QueryRepository<User>>
::find_one(&repo, &UserFilter::ByEmail(String::from("alice@example.com")))?;
- Listing with multi-key sorting (Email asc, CreatedAt desc)
let opts = hexser::ports::repository::FindOptions {
sort: Some(vec![
hexser::ports::repository::Sort { key: UserSortKey::Email, direction: hexser::ports::repository::Direction::Asc },
hexser::ports::repository::Sort { key: UserSortKey::CreatedAt, direction: hexser::ports::repository::Direction::Desc },
]),
limit: None,
offset: None,
};
let users = <InMemoryUserRepository as hexser::ports::repository::QueryRepository<User>>::find(
&repo,
&UserFilter::All,
opts,
)?;
- Pagination (page size 10, second page)
let opts = hexser::ports::repository::FindOptions { sort: None, limit: Some(10), offset: Some(10) };
let page = <InMemoryUserRepository as hexser::ports::repository::QueryRepository<User>>::find(&repo, &UserFilter::All, opts)?;
- Existence check
let exists = <InMemoryUserRepository as hexser::ports::repository::QueryRepository<User>>::exists(
&repo,
&UserFilter::ByEmail(String::from("bob@example.com")),
)?;
- Count matching entities
let total = <InMemoryUserRepository as hexser::ports::repository::QueryRepository<User>>::count(
&repo,
&UserFilter::All,
)?;
- Delete by filter (returns removed count)
let removed = <InMemoryUserRepository as hexser::ports::repository::QueryRepository<User>>::delete_where(
&mut repo.clone(),
&UserFilter::ByEmail(String::from("bob@example.com")),
)?;
π€ AI Context Export (CLI)
Export a machine-readable JSON describing your project's architecture for AI assistants and tooling.
Requirements:
- Enable the
ai feature (serde/serde_json are included automatically).
Commands:
cargo run -p hexser --features ai --bin hex-ai-export
cargo run -p hexser --features ai --bin hex-ai-export --quiet > target/ai-context.json
What it does:
- Builds the current
HexGraph from the component registry
- Generates an
AIContext via hexser::ai::ContextBuilder
- Serializes to JSON with a stable field order
Notes:
- The binary
hex-ai-export is only built when the ai feature is enabled.
- For reproducible diffs, commit
target/ai-context.json or generate it in CI as an artifact.
π§ AI Agent Pack (All-in-One)
Export a comprehensive, single-file JSON that bundles:
- AIContext (machine-readable architecture)
- Guidelines snapshot (rules enforced for agents)
- Embedded key docs (README, ERROR_GUIDE, and local AI/guideline prompts when present)
Commands:
cargo run -p hexser --features ai --bin hex-ai-pack
cargo run -p hexser --features ai --bin hex-ai-pack --quiet > target/ai-pack.json
Notes:
- Missing optional docs are skipped gracefully. The pack remains valid JSON.
- Use this artifact as the single source of truth for external AIs and tools when proposing changes.
π MCP Server (Model Context Protocol)
Hexser includes a built-in MCP (Model Context Protocol) server that exposes your project's architecture to AI assistants via a standardized JSON-RPC interface. This enables AI tools like Claude Desktop, Cline, and other MCP-compatible clients to query your architecture in real-time.
Requirements:
- Enable the
mcp feature (automatically includes ai, serde, and serde_json).
Running the MCP Server
cargo run -p hexser --features mcp --bin hex-mcp-server
Available MCP Resources
The MCP server exposes two primary resources:
-
hexser://context - Machine-readable architecture context (AIContext JSON)
- Current component graph
- Layer relationships
- Architectural constraints
- Validation rules
-
hexser://pack - Comprehensive Agent Pack (all-in-one JSON)
- AIContext (architecture)
- Guidelines snapshot (coding rules)
- Embedded documentation (README, ERROR_GUIDE, etc.)
Integration with AI Assistants
Configure your AI assistant to use the MCP server:
Claude Desktop (config.json):
{
"mcpServers": {
"hexser": {
"command": "cargo",
"args": ["run", "-p", "hexser", "--features", "mcp", "--bin", "hex-mcp-server"],
"cwd": "/path/to/your/hexser/project"
}
}
}
Cline / Other MCP Clients:
Follow the client-specific configuration to add the above command as an MCP server endpoint.
What the MCP Server Does
- Accepts JSON-RPC 2.0 requests via stdin
- Implements the Model Context Protocol specification
- Provides
initialize, resources/list, and resources/read methods
- Serves architecture data from the live
HexGraph registry
- Enables AI assistants to understand your project structure in real-time
Notes:
- The
hex-mcp-server binary is only built when the mcp feature is enabled.
- The server uses stdio transport (line-delimited JSON-RPC messages).
- For production use, consider wrapping in a process manager or systemd service.
π¦ REST Adapter Example: WeatherPort
Hexser includes a complete example of a REST-based adapter using reqwest::blocking and serde_json. This adapter connects to an external weather API and maps JSON responses to domain models with robust error handling.
Domain Model
pub struct Forecast {
city: String,
temperature_c: f64,
condition: String,
observed_at_iso: Option<String>,
}
Port Definition
pub trait WeatherPort {
fn get_forecast(&self, city: &str) -> HexResult<Forecast>;
}
Adapter Implementation
pub struct RestWeatherAdapter {
api_base_url: String,
client: reqwest::blocking::Client,
}
impl RestWeatherAdapter {
pub fn new(api_base_url: String) -> Self {
let client = reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.build()
.expect("Failed to build reqwest client");
Self { api_base_url, client }
}
}
impl WeatherPort for RestWeatherAdapter {
fn get_forecast(&self, city: &str) -> HexResult<Forecast> {
let url = format!("{}?city={}", self.api_base_url, city);
let response = self.client.get(&url)
.send()
.map_err(|e| {
Hexserror::adapter(
codes::adapter::API_FAILURE,
"Failed to connect to weather API"
)
.with_source(e)
.with_next_steps(&["Verify API endpoint", "Check network"])
})?;
let api_response: ApiWeatherResponse = serde_json::from_str(&response.text()?)
.map_err(|e| {
Hexserror::adapter(
codes::adapter::MAPPING_FAILURE,
"Failed to parse JSON response"
)
.with_source(e)
})?;
Forecast::new(
api_response.city,
api_response.temp_c,
api_response.condition,
api_response.observed_at,
)
}
}
This complete example is available at examples/weather_adapter.rs. Run with:
cargo run --example weather_adapter
π Integrating User Authentication Potions
When integrating pre-built authentication patterns from hexser_potions, you must connect the Potion's defined Ports to your own concrete adapters for databases and session management.
Step 1: Define Your Ports
trait UserRepository: Repository<User> {
fn find_by_username(&self, username: &str) -> HexResult<Option<User>>;
fn find_by_email(&self, email: &str) -> HexResult<Option<User>>;
}
trait SessionPort {
fn create_session(&self, user_id: &str, ttl_secs: u64) -> HexResult<String>;
fn validate_session(&self, token: &str) -> HexResult<Option<String>>;
fn revoke_session(&self, token: &str) -> HexResult<()>;
}
Step 2: Implement Database Adapter
struct PostgresUserRepository {
pool: sqlx::PgPool,
}
impl Repository<User> for PostgresUserRepository {
fn save(&mut self, user: User) -> HexResult<()> {
sqlx::query!("INSERT INTO users (id, username, email, password_hash) VALUES ($1, $2, $3, $4)",
user.id, user.username, user.email, user.password_hash)
.execute(&self.pool)
.await
.map_err(|e| Hexserror::adapter(codes::adapter::DB_WRITE_FAILURE, "Failed to save user")
.with_source(e))?;
Ok(())
}
}
impl UserRepository for PostgresUserRepository {
fn find_by_username(&self, username: &str) -> HexResult<Option<User>> {
sqlx::query_as!(User, "SELECT * FROM users WHERE username = $1", username)
.fetch_optional(&self.pool)
.await
.map_err(|e| Hexserror::adapter(codes::adapter::DB_READ_FAILURE, "Query failed")
.with_source(e))
}
}
Step 3: Implement Session Adapter (Redis or In-Memory)
struct RedisSessionAdapter {
client: redis::Client,
}
impl SessionPort for RedisSessionAdapter {
fn create_session(&self, user_id: &str, ttl_secs: u64) -> HexResult<String> {
let token = uuid::Uuid::new_v4().to_string();
let mut conn = self.client.get_connection()
.map_err(|e| Hexserror::adapter(codes::adapter::CONNECTION_FAILURE, "Redis unavailable")
.with_source(e))?;
redis::cmd("SETEX")
.arg(format!("session:{}", token))
.arg(ttl_secs)
.arg(user_id)
.query(&mut conn)
.map_err(|e| Hexserror::adapter(codes::adapter::DB_WRITE_FAILURE, "Session write failed")
.with_source(e))?;
Ok(token)
}
fn validate_session(&self, token: &str) -> HexResult<Option<String>> {
let mut conn = self.client.get_connection()?;
let user_id: Option<String> = redis::cmd("GET")
.arg(format!("session:{}", token))
.query(&mut conn)
.map_err(|e| Hexserror::adapter(codes::adapter::DB_READ_FAILURE, "Session read failed")
.with_source(e))?;
Ok(user_id)
}
fn revoke_session(&self, token: &str) -> HexResult<()> {
let mut conn = self.client.get_connection()?;
redis::cmd("DEL")
.arg(format!("session:{}", token))
.query(&mut conn)
.map_err(|e| Hexserror::adapter(codes::adapter::DB_WRITE_FAILURE, "Session delete failed")
.with_source(e))?;
Ok(())
}
}
Step 4: Wire Adapters to Application
struct AppContext {
user_repo: Box<dyn UserRepository>,
session_port: Box<dyn SessionPort>,
}
impl AppContext {
fn new_production(db_pool: sqlx::PgPool, redis_client: redis::Client) -> Self {
Self {
user_repo: Box::new(PostgresUserRepository { pool: db_pool }),
session_port: Box::new(RedisSessionAdapter { client: redis_client }),
}
}
}
π Transactional Directives: ProcessOrder Example
When a directive involves multiple repository operations that must succeed or fail atomically (e.g., decrementing stock and creating an order), use a database transaction and pass it explicitly to each repository call.
Port Definitions
trait ProductRepository {
fn decrement_stock(&self, tx: &mut PgTransaction, product_id: &str, qty: u32) -> HexResult<()>;
}
trait OrderRepository {
fn create_order(&self, tx: &mut PgTransaction, order: Order) -> HexResult<()>;
}
trait EventBus {
fn publish(&self, event: OrderCreated) -> HexResult<()>;
}
Directive Handler with Transaction
struct ProcessOrderHandler {
product_repo: Box<dyn ProductRepository>,
order_repo: Box<dyn OrderRepository>,
event_bus: Box<dyn EventBus>,
db_pool: sqlx::PgPool,
}
impl ProcessOrderHandler {
async fn handle(&self, directive: ProcessOrderDirective) -> HexResult<()> {
let mut tx = self.db_pool.begin()
.await
.map_err(|e| Hexserror::adapter(codes::adapter::DB_CONNECTION_FAILURE, "Failed to begin transaction")
.with_source(e))?;
for item in &directive.items {
self.product_repo.decrement_stock(&mut tx, &item.product_id, item.quantity)
.await
.map_err(|e| {
Hexserror::domain(codes::domain::INVARIANT_VIOLATION, "Insufficient stock")
.with_source(e)
})?;
}
let order = Order::new(directive.customer_id, directive.items)?;
self.order_repo.create_order(&mut tx, order.clone())
.await
.map_err(|e| {
Hexserror::adapter(codes::adapter::DB_WRITE_FAILURE, "Failed to create order")
.with_source(e)
})?;
tx.commit()
.await
.map_err(|e| Hexserror::adapter(codes::adapter::DB_WRITE_FAILURE, "Transaction commit failed")
.with_source(e))?;
let event = OrderCreated { order_id: order.id.clone(), timestamp: now() };
self.event_bus.publish(event)?;
Ok(())
}
}
Adapter Implementation (PostgreSQL)
struct PostgresProductRepository;
impl ProductRepository for PostgresProductRepository {
async fn decrement_stock(&self, tx: &mut PgTransaction<'_>, product_id: &str, qty: u32) -> HexResult<()> {
let rows_affected = sqlx::query!(
"UPDATE products SET stock = stock - $1 WHERE id = $2 AND stock >= $1",
qty as i32, product_id
)
.execute(tx)
.await
.map_err(|e| Hexserror::adapter(codes::adapter::DB_WRITE_FAILURE, "Stock update failed")
.with_source(e))?
.rows_affected();
if rows_affected == 0 {
return Err(Hexserror::domain(codes::domain::INVARIANT_VIOLATION, "Insufficient stock or product not found"));
}
Ok(())
}
}
Key Points:
- Pass
&mut PgTransaction (or equivalent) to all repository methods within the transaction.
- Rollback is automatic via Rust's
Drop trait if any error occurs before commit().
- Publish events only after successful commit to ensure consistency.
π Composite Adapters: ProfileRepository Example
When data must be fetched from multiple sources (e.g., SQL for core profile, NoSQL for preferences), implement a composite adapter that queries both, handles failures gracefully, and optionally caches results.
Port Definition
trait ProfileRepository {
fn find_by_id(&self, user_id: &str) -> HexResult<Profile>;
}
Composite Adapter Implementation
struct CompositeProfileRepository {
sql_db: sqlx::PgPool,
nosql_client: mongodb::Client,
cache: std::sync::Arc<std::sync::Mutex<lru::LruCache<String, Profile>>>,
}
impl CompositeProfileRepository {
fn new(sql_db: sqlx::PgPool, nosql_client: mongodb::Client, cache_size: usize) -> Self {
Self {
sql_db,
nosql_client,
cache: std::sync::Arc::new(std::sync::Mutex::new(lru::LruCache::new(cache_size))),
}
}
}
impl ProfileRepository for CompositeProfileRepository {
async fn find_by_id(&self, user_id: &str) -> HexResult<Profile> {
{
let mut cache = self.cache.lock().unwrap();
if let Some(cached) = cache.get(user_id) {
return Ok(cached.clone());
}
}
let core_profile: SqlProfileRow = sqlx::query_as!(
SqlProfileRow,
"SELECT id, username, email, created_at FROM users WHERE id = $1",
user_id
)
.fetch_one(&self.sql_db)
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => Hexserror::not_found("Profile", user_id),
_ => Hexserror::adapter(codes::adapter::DB_READ_FAILURE, "SQL query failed")
.with_source(e)
.with_next_step("Check database connectivity"),
})?;
let collection = self.nosql_client.database("app").collection::<bson::Document>("user_prefs");
let prefs_result = collection.find_one(bson::doc! { "user_id": user_id }, None).await;
let preferences = match prefs_result {
Ok(Some(doc)) => {
Preferences::from_bson(&doc).unwrap_or_default()
}
Ok(None) => {
Preferences::default()
}
Err(e) => {
eprintln!("Warning: Failed to fetch preferences for {}: {}", user_id, e);
Preferences::default()
}
};
let profile = Profile {
id: core_profile.id,
username: core_profile.username,
email: core_profile.email,
created_at: core_profile.created_at,
preferences,
};
{
let mut cache = self.cache.lock().unwrap();
cache.put(user_id.to_string(), profile.clone());
}
Ok(profile)
}
}
Handling Data Inconsistencies
- Primary Source Failure: Return
Hexserror::Adapter or Hexserror::NotFound with actionable guidance.
- Secondary Source Failure: Degrade gracefully by logging a warning and using defaults (e.g.,
Preferences::default()).
- Caching Strategy: Use an LRU cache with TTL to reduce load; invalidate on writes.
- Stale Data: Implement cache invalidation hooks or TTL-based expiry for eventually-consistent NoSQL data.
Caching Strategies
- Read-Through Cache: Check cache before querying databases (shown above).
- Write-Through Cache: Invalidate or update cache on writes.
- TTL-Based Expiry: Use a cache with time-to-live for each entry.
struct TtlCache<K, V> {
cache: lru::LruCache<K, (V, std::time::Instant)>,
ttl: std::time::Duration,
}
impl<K: std::hash::Hash + Eq, V: Clone> TtlCache<K, V> {
fn get(&mut self, key: &K) -> Option<V> {
if let Some((value, inserted_at)) = self.cache.get(key) {
if inserted_at.elapsed() < self.ttl {
return Some(value.clone());
}
}
None
}
}