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
- Why hexser?
- Quick Start
- Complete Tutorial
- CQRS Pattern with hex
- Testing Your Hexagonal Application
- Error Handling
- Real-World Example - TODO Application
- Advanced Patterns
- Knowledge Graph
- Static (non-dyn) DI β WASM-friendly
- Repository: Filter-based queries (vNext)
- AI Context Export (CLI)
- Examples & Tutorials
- Potions (copy-friendly examples)
- Contributing
- License
- Acknowledgments
- Additional Resources
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:
- Zero Boilerplate - Define your types, derive traits, done
- Type-Safe Architecture - Compiler enforces layer boundaries
- Self-Documenting - Graph visualization shows your architecture
- Intent Inference - System understands itself through structure
- Rich Errors - Helpful, actionable error messages
- Zero Runtime Overhead - Everything happens at compile time
- AI Completion - Expose your Rust architecture to AI agents
π Quick Start
Add to your Cargo.toml:
[]
= "0.3.0"
Your First Hexagonal Application
use *;
// 1. Define your domain entity
// 2. Define a port (interface)
// 3. Implement an adapter
// 4. Use it!
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 *;
Value Objects - Things defined by values:
;
Domain Events - Things that happened:
Domain Services - Operations spanning multiple entities:
;
- Ports Layer - Your Interfaces Ports define the contracts between your domain and the outside world. Repositories - Persistence abstraction:
Use Cases - Business operations:
Queries - Read operations (CQRS):
- Adapters Layer - Your Implementations Adapters implement ports using specific technologies.
Database Adapter:
API Adapter:
Mapper - Data transformation:
;
- Application Layer - Your Orchestration The application layer coordinates domain logic and ports. Directive (Write Operation):
Directive Handler:
Query Handler:
- Infrastructure Layer - Your Technology Infrastructure provides the concrete technology implementations.
Part 3: CQRS Pattern with hex
hexser supports Command Query Responsibility Segregation (CQRS) out of the box.
Write Side (Directives):
// Directive represents intent to change state
// Handler executes the directive
Read Side (Queries):
// Query represents read operation
// Handler executes the query
Part 4: Testing Your Hexagonal Application
Hexagonal architecture makes testing trivial - just mock the ports!
Unit Testing Domain Logic:
Testing with Mock Adapters:
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
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
// Validation errors (field-aware)
return Err;
// Not Found errors (resource + id)
return Err;
// Port errors (communication issues)
let port_err = hex_port_error!.with_suggestion;
// Adapter errors (infra failures) with source error
π₯ Amazing Example: Layered mapping (Adapter β Port β Domain)
// Adapter layer
// Port layer wraps adapter failure with port context
// Domain layer consumes rich errors
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 *;
;
Ports Layer:
Adapters Layer:
Application Layer:
π Advanced Patterns
Event Sourcing
Dependency Injection
π 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
π§ͺ 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:
[]
= { = "../hexser_potions", = "0.3.0" }
Then in code:
use ;
βοΈ 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 graphhex_static! { ... }macro: builds the graph from a block without anydyn
Example:
use *;
;
let app = hex_static!;
let = app.into_inner;
WASM guidance:
- Default features are WASM-friendly (no tokio). Keep
containerdisabled 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 *;
use ;
// Domain-owned query types
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.
π€ AI Context Export (CLI)
Export a machine-readable JSON describing your project's architecture for AI assistants and tooling.
Requirements:
- Enable the
aifeature (serde/serde_json are included automatically).
Commands:
# Build and run the exporter (prints JSON to stdout)
# Save to a file
What it does:
- Builds the current
HexGraphfrom the component registry - Generates an
AIContextviahexser::ai::ContextBuilder - Serializes to JSON with a stable field order
Notes:
- The binary
hex-ai-exportis only built when theaifeature is enabled. - For reproducible diffs, commit
target/ai-context.jsonor 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:
# Print Agent Pack JSON to stdout
# Save to a file
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.