This is a comprehensive request for a Rust web service boilerplate using Hexagonal architecture with Actix-web. Let me create a well-structured project that demonstrates:
- Hexagonal Architecture (Ports & Adapters)
- Actix-web framework
- sqlx for compile-time checked SQL
- Pure business logic separated from HTTP concerns
- Dependency injection patterns
- Error handling
- Database migrations
- Configuration management
- Proper tests
I'll organize it with clear separation:
- Domain layer (traits and entities - pure business logic)
- Application layer (use cases/services)
- Infrastructure layer (database, HTTP handlers)
- Adapters (HTTP handlers, database repositories)
- Configuration and startup
Let me create a complete, production-ready example.
Rust Hexagonal Architecture Web Service with Actix-web
I'll create a comprehensive boilerplate for a Task Management API using hexagonal architecture principles.
Project Structure
task-api/
├── Cargo.toml
├── .env.example
├── sqlx-data.json
├── migrations/
│ └── 001_init.sql
├── src/
│ ├── main.rs
│ ├── config.rs
│ ├── domain/
│ │ ├── mod.rs
│ │ ├── task.rs
│ │ └── errors.rs
│ ├── application/
│ │ ├── mod.rs
│ │ ├── services.rs
│ │ └── dto.rs
│ ├── infrastructure/
│ │ ├── mod.rs
│ │ ├── persistence/
│ │ │ ├── mod.rs
│ │ │ └── postgres.rs
│ │ └── http/
│ │ ├── mod.rs
│ │ ├── handlers.rs
│ │ ├── extractors.rs
│ │ └── responses.rs
│ └── startup.rs
└── tests/
├── integration_tests.rs
└── fixtures.rs
Cargo.toml
[package]
name = "task-api"
version = "0.1.0"
edition = "2021"
[dependencies]
# Web framework
actix-web = "4.4"
actix-rt = "2.9"
# Database
sqlx = { version = "0.7", features = [
"runtime-tokio-rustls",
"postgres",
"uuid",
"chrono",
"macros"
] }
tokio = { version = "1.35", features = ["full"] }
# Serialization
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
# Type safety & validation
uuid = { version = "1.6", features = ["v4", "serde"] }
chrono = { version = "0.4", features = ["serde"] }
# Configuration
dotenv = "0.15"
config = "0.13"
# Error handling
anyhow = "1.0"
thiserror = "1.0"
tracing = "0.1"
tracing-subscriber = "0.3"
# Async
futures = "0.3"
[dev-dependencies]
tokio-test = "0.4"
mockall = "0.12"
testcontainers = "0.15"
src/domain/errors.rs
use serde::Serialize;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum DomainError {
#[error("Task not found")]
TaskNotFound,
#[error("Invalid task title: {0}")]
InvalidTitle(String),
#[error("Invalid task description: {0}")]
InvalidDescription(String),
#[error("Task already exists")]
TaskAlreadyExists,
#[error("Concurrent modification detected")]
ConcurrentModification,
#[error("Internal error: {0}")]
InternalError(String),
}
impl DomainError {
pub fn status_code(&self) -> u16 {
match self {
DomainError::TaskNotFound => 404,
DomainError::InvalidTitle(_) | DomainError::InvalidDescription(_) => 400,
DomainError::TaskAlreadyExists => 409,
DomainError::ConcurrentModification => 409,
DomainError::InternalError(_) => 500,
}
}
}
#[derive(Serialize)]
pub struct ErrorResponse {
pub error: String,
pub details: Option<String>,
}
impl From<DomainError> for ErrorResponse {
fn from(error: DomainError) -> Self {
ErrorResponse {
error: error.to_string(),
details: None,
}
}
}
src/domain/task.rs
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use super::errors::DomainError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TaskStatus {
#[serde(rename = "pending")]
Pending,
#[serde(rename = "in_progress")]
InProgress,
#[serde(rename = "completed")]
Completed,
}
/// Pure domain model - independent of any framework
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Task {
pub id: Uuid,
pub title: String,
pub description: Option<String>,
pub status: TaskStatus,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub version: i64,
}
impl Task {
/// Constructor with validation
pub fn new(title: String, description: Option<String>) -> Result<Self, DomainError> {
Self::validate_title(&title)?;
if let Some(ref desc) = description {
Self::validate_description(desc)?;
}
Ok(Task {
id: Uuid::new_v4(),
title,
description,
status: TaskStatus::Pending,
created_at: Utc::now(),
updated_at: Utc::now(),
version: 1,
})
}
/// Business logic: transition to in-progress
pub fn start(&mut self) -> Result<(), DomainError> {
match self.status {
TaskStatus::Pending => {
self.status = TaskStatus::InProgress;
self.updated_at = Utc::now();
Ok(())
}
TaskStatus::InProgress => Ok(()), // Idempotent
TaskStatus::Completed => Err(DomainError::InternalError(
"Cannot start a completed task".to_string(),
)),
}
}
/// Business logic: mark as completed
pub fn complete(&mut self) -> Result<(), DomainError> {
if self.status == TaskStatus::Completed {
return Ok(()); // Idempotent
}
self.status = TaskStatus::Completed;
self.updated_at = Utc::now();
Ok(())
}
/// Business logic: update title and description
pub fn update_details(
&mut self,
title: Option<String>,
description: Option<Option<String>>,
) -> Result<(), DomainError> {
if let Some(new_title) = title {
Self::validate_title(&new_title)?;
self.title = new_title;
}
if let Some(new_description) = description {
if let Some(ref desc) = new_description {
Self::validate_description(desc)?;
}
self.description = new_description;
}
self.updated_at = Utc::now();
Ok(())
}
// Private validation methods
fn validate_title(title: &str) -> Result<(), DomainError> {
if title.is_empty() || title.len() > 255 {
return Err(DomainError::InvalidTitle(
"Title must be between 1 and 255 characters".to_string(),
));
}
Ok(())
}
fn validate_description(description: &str) -> Result<(), DomainError> {
if description.len() > 2000 {
return Err(DomainError::InvalidDescription(
"Description must not exceed 2000 characters".to_string(),
));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_valid_task() {
let task = Task::new("Buy milk".to_string(), None).unwrap();
assert_eq!(task.title, "Buy milk");
assert_eq!(task.status, TaskStatus::Pending);
}
#[test]
fn test_invalid_empty_title() {
let result = Task::new("".to_string(), None);
assert!(result.is_err());
}
#[test]
fn test_task_transitions() {
let mut task = Task::new("Test".to_string(), None).unwrap();
assert!(task.start().is_ok());
assert_eq!(task.status, TaskStatus::InProgress);
assert!(task.complete().is_ok());
assert_eq!(task.status, TaskStatus::Completed);
// Idempotent
assert!(task.complete().is_ok());
}
}
src/domain/mod.rs
pub mod errors;
pub mod task;
pub use errors::DomainError;
pub use task::{Task, TaskStatus};
src/application/dto.rs
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use chrono::{DateTime, Utc};
use crate::domain::TaskStatus;
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateTaskRequest {
pub title: String,
pub description: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateTaskRequest {
pub title: Option<String>,
pub description: Option<Option<String>>,
pub status: Option<TaskStatus>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TaskResponse {
pub id: Uuid,
pub title: String,
pub description: Option<String>,
pub status: TaskStatus,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub version: i64,
}
impl From<crate::domain::Task> for TaskResponse {
fn from(task: crate::domain::Task) -> Self {
TaskResponse {
id: task.id,
title: task.title,
description: task.description,
status: task.status,
created_at: task.created_at,
updated_at: task.updated_at,
version: task.version,
}
}
}
#[derive(Debug, Serialize)]
pub struct PaginatedResponse<T> {
pub items: Vec<T>,
pub total: i64,
pub page: i64,
pub page_size: i64,
}
src/application/services.rs
use uuid::Uuid;
use crate::domain::{DomainError, Task, TaskStatus};
/// Port: Task Repository trait (depends on application, not infrastructure)
#[async_trait::async_trait]
pub trait TaskRepository: Send + Sync {
async fn create(&self, task: &Task) -> Result<(), DomainError>;
async fn get_by_id(&self, id: Uuid) -> Result<Option<Task>, DomainError>;
async fn list(&self, page: i64, page_size: i64) -> Result<(Vec<Task>, i64), DomainError>;
async fn update(&self, task: &Task) -> Result<(), DomainError>;
async fn delete(&self, id: Uuid) -> Result<(), DomainError>;
}
/// Application Service - orchestrates domain logic and repositories
pub struct TaskService<R: TaskRepository> {
repository: R,
}
impl<R: TaskRepository> TaskService<R> {
pub fn new(repository: R) -> Self {
TaskService { repository }
}
/// Use case: Create a new task
pub async fn create_task(
&self,
title: String,
description: Option<String>,
) -> Result<Task, DomainError> {
let task = Task::new(title, description)?;
self.repository.create(&task).await?;
Ok(task)
}
/// Use case: Get task by ID
pub async fn get_task(&self, id: Uuid) -> Result<Task, DomainError> {
self.repository
.get_by_id(id)
.await?
.ok_or(DomainError::TaskNotFound)
}
/// Use case: List tasks
pub async fn list_tasks(&self, page: i64, page_size: i64) -> Result<(Vec<Task>, i64), DomainError> {
if page < 1 || page_size < 1 || page_size > 100 {
return Err(DomainError::InvalidTitle(
"Invalid pagination parameters".to_string(),
));
}
self.repository.list(page, page_size).await
}
/// Use case: Start a task
pub async fn start_task(&self, id: Uuid) -> Result<Task, DomainError> {
let mut task = self.get_task(id).await?;
task.start()?;
self.repository.update(&task).await?;
Ok(task)
}
/// Use case: Complete a task
pub async fn complete_task(&self, id: Uuid) -> Result<Task, DomainError> {
let mut task = self.get_task(id).await?;
task.complete()?;
self.repository.update(&task).await?;
Ok(task)
}
/// Use case: Update task details
pub async fn update_task(
&self,
id: Uuid,
title: Option<String>,
description: Option<Option<String>>,
) -> Result<Task, DomainError> {
let mut task = self.get_task(id).await?;
task.update_details(title, description)?;
self.repository.update(&task).await?;
Ok(task)
}
/// Use case: Delete a task
pub async fn delete_task(&self, id: Uuid) -> Result<(), DomainError> {
self.repository.delete(id).await?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use mockall::predicate::*;
use mockall::mock;
mock! {
TaskRepositoryMock {}
#[async_trait::async_trait]
impl TaskRepository for TaskRepositoryMock {
async fn create(&self, task: &Task) -> Result<(), DomainError>;
async fn get_by_id(&self, id: Uuid) -> Result<Option<Task>, DomainError>;
async fn list(&self, page: i64, page_size: i64) -> Result<(Vec<Task>, i64), DomainError>;
async fn update(&self, task: &Task) -> Result<(), DomainError>;
async fn delete(&self, id: Uuid) -> Result<(), DomainError>;
}
}
#[tokio::test]
async fn test_create_task_success() {
let mut mock_repo = MockTaskRepositoryMock::new();
mock_repo
.expect_create()
.with(always())
.times(1)
.returning(|_| Ok(()));
let service = TaskService::new(mock_repo);
let result = service
.create_task("Buy milk".to_string(), None)
.await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_create_task_invalid_title() {
let mock_repo = MockTaskRepositoryMock::new();
let service = TaskService::new(mock_repo);
let result = service.create_task("".to_string(), None).await;
assert!(result.is_err());
}
}
src/application/mod.rs
pub mod dto;
pub mod services;
pub use dto::*;
pub use services::*;
src/infrastructure/persistence/postgres.rs
use sqlx::{Pool, Postgres, Row};
use uuid::Uuid;
use crate::application::TaskRepository;
use crate::domain::{DomainError, Task, TaskStatus};
pub struct PostgresTaskRepository {
pool: Pool<Postgres>,
}
impl PostgresTaskRepository {
pub fn new(pool: Pool<Postgres>) -> Self {
PostgresTaskRepository { pool }
}
}
#[async_trait::async_trait]
impl TaskRepository for PostgresTaskRepository {
async fn create(&self, task: &Task) -> Result<(), DomainError> {
let status = match task.status {
TaskStatus::Pending => "pending",
TaskStatus::InProgress => "in_progress",
TaskStatus::Completed => "completed",
};
sqlx::query(
r#"
INSERT INTO tasks (id, title, description, status, created_at, updated_at, version)
VALUES ($1, $2, $3, $4, $5, $6, $7)
"#,
)
.bind(task.id)
.bind(&task.title)
.bind(&task.description)
.bind(status)
.bind(task.created_at)
.bind(task.updated_at)
.bind(task.version)
.execute(&self.pool)
.await
.map_err(|e| {
tracing::error!("Database error creating task: {}", e);
DomainError::InternalError("Failed to create task".to_string())
})?;
Ok(())
}
async fn get_by_id(&self, id: Uuid) -> Result<Option<Task>, DomainError> {
let row = sqlx::query(
r#"
SELECT id, title, description, status, created_at, updated_at, version
FROM tasks
WHERE id = $1
"#,
)
.bind(id)
.fetch_optional(&self.pool)
.await
.map_err(|e| {
tracing::error!("Database error fetching task: {}", e);
DomainError::InternalError("Failed to fetch task".to_string())
})?;
Ok(row.map(|r| {
let status_str: String = r.get("status");
let status = match status_str.as_str() {
"pending" => TaskStatus::Pending,
"in_progress" => TaskStatus::InProgress,
"completed" => TaskStatus::Completed,
_ => TaskStatus::Pending,
};
Task {
id: r.get("id"),
title: r.get("title"),
description: r.get("description"),
status,
created_at: r.get("created_at"),
updated_at: r.get("updated_at"),
version: r.get("version"),
}
}))
}
async fn list(&self, page: i64, page_size: i64) -> Result<(Vec<Task>, i64), DomainError> {
let offset = (page - 1) * page_size;
let total: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM tasks")
.fetch_one(&self.pool)
.await
.map_err(|e| {
tracing::error!("Database error counting tasks: {}", e);
DomainError::InternalError("Failed to count tasks".to_string())
})?;
let rows = sqlx::query(
r#"
SELECT id, title, description, status, created_at, updated_at, version
FROM tasks
ORDER BY created_at DESC
LIMIT $1 OFFSET $2
"#,
)
.bind(page_size)
.bind(offset)
.fetch_all(&self.pool)
.await
.map_err(|e| {
tracing::error!("Database error listing tasks: {}", e);
DomainError::InternalError("Failed to list tasks".to_string())
})?;
let tasks = rows
.into_iter()
.map(|r| {
let status_str: String = r.get("status");
let status = match status_str.as_str() {
"pending" => TaskStatus::Pending,
"in_progress" => TaskStatus::InProgress,
"completed" => TaskStatus::Completed,
_ => TaskStatus::Pending,
};
Task {
id: r.get("id"),
title: r.get("title"),
description: r.get("description"),
status,
created_at: r.get("created_at"),
updated_at: r.get("updated_at"),
version: r.get("version"),
}
})
.collect();
Ok((tasks, total))
}
async fn update(&self, task: &Task) -> Result<(), DomainError> {
let status = match task.status {
TaskStatus::Pending => "pending",
TaskStatus::InProgress => "in_progress",
TaskStatus::Completed => "completed",
};
let result = sqlx::query(
r#"
UPDATE tasks
SET title = $2, description = $3, status = $4, updated_at = $5, version = version + 1
WHERE id = $1 AND version = $6
"#,
)
.bind(task.id)
.bind(&task.title)
.bind(&task.description)
.bind(status)
.bind(task.updated_at)
.bind(task.version)
.execute(&self.pool)
.await
.map_err(|e| {
tracing::error!("Database error updating task: {}", e);
DomainError::InternalError("Failed to update task".to_string())
})?;
if result.rows_affected() == 0 {
return Err(DomainError::ConcurrentModification);
}
Ok(())
}
async fn delete(&self, id: Uuid) -> Result<(), DomainError> {
sqlx::query("DELETE FROM tasks WHERE id = $1")
.bind(id)
.execute(&self.pool)
.await
.map_err(|e| {
tracing::error!("Database error deleting task: {}", e);
DomainError::InternalError("Failed to delete task".to_string())
})?;
Ok(())
}
}
src/infrastructure/persistence/mod.rs
pub mod postgres;
pub use postgres::PostgresTaskRepository;
src/infrastructure/http/responses.rs
use actix_web::{HttpResponse, ResponseError};
use serde_json::json;
use std::fmt;
use crate::domain::DomainError;
use crate::application::TaskResponse;
#[derive(Debug)]
pub struct ApiError(pub DomainError);
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl ResponseError for ApiError {
fn error_response(&self) -> HttpResponse {
let status_code = self.0.status_code();
let body = json!({
"error": self.0.to_string(),
"status": status_code
});
match status_code {
400 => HttpResponse::BadRequest().json(body),
404 => HttpResponse::NotFound().json(body),
409 => HttpResponse::Conflict().json(body),
500 => HttpResponse::InternalServerError().json(body),
_ => HttpResponse::InternalServerError().json(body),
}
}
}
impl From<DomainError> for ApiError {
fn from(error: DomainError) -> Self {
ApiError(error)
}
}
#[derive(serde::Serialize)]
pub struct SuccessResponse<T> {
pub data: T,
pub status: u16,
}
impl<T: serde::Serialize> SuccessResponse<T> {
pub fn ok(data: T) -> HttpResponse {
HttpResponse::Ok().json(SuccessResponse { data, status: 200 })
}
pub fn created(data: T) -> HttpResponse {
HttpResponse::Created().json(SuccessResponse { data, status: 201 })
}
}
src/infrastructure/http/extractors.rs
use actix_web::web::Path;
use uuid::Uuid;
#[derive(serde::Deserialize)]
pub struct TaskIdPath {
pub id: Uuid,
}
#[derive(serde::Deserialize)]
pub struct PaginationQuery {
pub page: Option<i64>,
pub page_size: Option<i64>,
}
impl PaginationQuery {
pub fn get_page(&self) -> i64 {
self.page.unwrap_or(1).max(1)
}
pub fn get_page_size(&self) -> i64 {
self.page_size.unwrap_or(20).min(100).max(1)
}
}
src/infrastructure/http/handlers.rs
use actix_web::{web, HttpResponse};
use uuid::Uuid;
use crate::application::{CreateTaskRequest, TaskService, TaskRepository, UpdateTaskRequest, PaginatedResponse, TaskResponse};
use crate::infrastructure::persistence::PostgresTaskRepository;
use super::extractors::{TaskIdPath, PaginationQuery};
use super::responses::{ApiError, SuccessResponse};
/// POST /tasks - Create a new task
pub async fn create_task(
service: web::Data<TaskService<PostgresTaskRepository>>,
req: web::Json<CreateTaskRequest>,
) -> Result<HttpResponse, ApiError> {
let task = service
.create_task(req.title.clone(), req.description.clone())
.await?;
Ok(SuccessResponse::created(TaskResponse::from(task)))
}
/// GET /tasks/{id} - Get a task by ID
pub async fn get_task(
service: web::Data<TaskService<PostgresTaskRepository>>,
path: web::Path<TaskIdPath>,
) -> Result<HttpResponse, ApiError> {
let task = service.get_task(path.id).await?;
Ok(SuccessResponse::ok(TaskResponse::from(task)))
}
/// GET /tasks - List tasks with pagination
pub async fn list_tasks(
service: web::Data<TaskService<PostgresTaskRepository>>,
query: web::Query<PaginationQuery>,
) -> Result<HttpResponse, ApiError> {
let page = query.get_page();
let page_size = query.get_page_size();
let (tasks, total) = service.list_tasks(page, page_size).await?;
let response = PaginatedResponse {
items: tasks.into_iter().map(TaskResponse::from).collect(),
total,
page,
page_size,
};
Ok(SuccessResponse::ok(response))
}
/// PATCH /tasks/{id} - Update a task
pub async fn update_task(
service: web::Data<TaskService<PostgresTaskRepository>>,
path: web::Path<TaskIdPath>,
req: web::Json<UpdateTaskRequest>,
) -> Result<HttpResponse, ApiError> {
let mut task = service.get_task(path.id).await?;
// Apply status updates
if let Some(status) = req.status {
task.status = status;
}
let title = req.title.clone();
let description = req.description.clone();
let updated_task = service
.update_task(path.id, title, description)
.await?;
Ok(SuccessResponse::ok(TaskResponse::from(updated_task)))
}
/// POST /tasks/{id}/start - Start a task
pub async fn start_task(
service: web::Data<TaskService<PostgresTaskRepository>>,
path: web::Path<TaskIdPath>,
) -> Result<HttpResponse, ApiError> {
let task = service.start_task(path.id).await?;
Ok(SuccessResponse::ok(TaskResponse::from(task)))
}
/// POST /tasks/{id}/complete - Complete a task
pub async fn complete_task(
service: web::Data<TaskService<PostgresTaskRepository>>,
path: web::Path<TaskIdPath>,
) -> Result<HttpResponse, ApiError> {
let task = service.complete_task(path.id).await?;
Ok(SuccessResponse::ok(TaskResponse::from(task)))
}
/// DELETE /tasks/{id} - Delete a task
pub async fn delete_task(
service: web::Data<TaskService<PostgresTaskRepository>>,
path: web::Path<TaskIdPath>,
) -> Result<HttpResponse, ApiError> {
service.delete_task(path.id).await?;
Ok(HttpResponse::NoContent().finish())
}
/// GET /health - Health check
pub async fn health() -> HttpResponse {
HttpResponse::Ok().json(serde_json::json!({
"status": "healthy",
"timestamp": chrono::Utc::now()
}))
}
src/infrastructure/http/mod.rs
pub mod extractors;
pub mod handlers;
pub mod responses;
use actix_web::web;
use crate::application::TaskService;
use crate::infrastructure::persistence::PostgresTaskRepository;
use self::handlers::*;
pub fn configure_routes(
cfg: &mut web::ServiceConfig,
_service: web::Data<TaskService<PostgresTaskRepository>>,
) {
cfg.service(
web::scope("/api")
.route("/health", web::get().to(health))
.service(
web::scope("/tasks")
.route("", web::post().to(create_task))
.route("", web::get().to(list_tasks))
.route("/{id}", web::get().to(get_task))
.route("/{id}", web::patch().to(update_task))
.route("/{id}", web::delete().to(delete_task))
.route("/{id}/start", web::post().to(start_task))
.route("/{id}/complete", web::post().to(complete_task))
),
);
}
src/infrastructure/mod.rs
pub mod http;
pub mod persistence;
pub use http::configure_routes;
pub use persistence::PostgresTaskRepository;
src/config.rs
use serde::Deserialize;
use dotenv::dotenv;
#[derive(Debug, Deserialize, Clone)]
pub struct Config {
pub server: ServerConfig,
pub database: DatabaseConfig,
pub logging: LoggingConfig,
}
#[derive(Debug, Deserialize, Clone)]
pub struct ServerConfig {
pub host: String,
pub port: u16,
}
#[derive(Debug, Deserialize, Clone)]
pub struct DatabaseConfig {
pub url: String,
pub max_connections: u32,
}
#[derive(Debug, Deserialize, Clone)]
pub struct LoggingConfig {
pub level: String,
}
impl Config {
pub fn from_env() -> Self {
dotenv().ok();
Config {
server: ServerConfig {
host: std::env::var("SERVER_HOST").unwrap_or_else(|_| "127.0.0.1".to_string()),
port: std::env::var("SERVER_PORT")
.ok()
.and_then(|p| p.parse().ok())
.unwrap_or(8080),
},
database: DatabaseConfig {
url: std::env::var("DATABASE_URL")
.expect("DATABASE_URL must be set"),
max_connections: std::env::var("DB_MAX_CONNECTIONS")
.ok()
.and_then(|c| c.parse().ok())
.unwrap_or(10),
},
logging: LoggingConfig {
level: std::env::var("LOG_LEVEL").unwrap_or_else(|_| "info".to_string()),
},
}
}
}
src/startup.rs
use actix_web::{web, App, HttpServer};
use sqlx::postgres::PgPoolOptions;
use tracing_subscriber;
use crate::application::TaskService;
use crate::config::Config;
use crate::infrastructure::{configure_routes, PostgresTaskRepository};
pub async fn run(config: Config) -> std::io::Result<()> {
// Setup logging
tracing_subscriber::fmt()
.with_max_level(
config
.logging
.level
.parse()
.unwrap_or(tracing::Level::INFO),
)
.init();
// Setup database connection pool
let pool = PgPoolOptions::new()
.max_connections(config.database.max_connections)
.connect(&config.database.url)
.await
.expect("Failed to create pool");
// Run migrations
sqlx::migrate!("./migrations")
.run(&pool)
.await
.expect("Failed to run migrations");
tracing::info!("Database migrations completed successfully");
// Create repository and service
let repository = PostgresTaskRepository::new(pool);
let service = web::Data::new(TaskService::new(repository));
let address = format!("{}:{}", config.server.host, config.server.port);
tracing::info!("Starting server at http://{}", address);
let listener = tokio::net::TcpListener::bind(&address)
.await
.expect("Failed to bind to address");
HttpServer::new(move || {
App::new()
.app_data(service.clone())
.wrap(actix_web::middleware::Logger::default())
.configure(|cfg| configure_routes(cfg, service.clone()))
})
.listen(listener)
.await
}
src/main.rs
#[macro_use]
extern crate async_trait;
mod application;
mod config;
mod domain;
mod infrastructure;
mod startup;
use config::Config;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let config = Config::from_env();
startup::run(config).await
}
migrations/001_init.sql
-- Create ENUM type for task status
CREATE TYPE task_status AS ENUM ('pending', 'in_progress', 'completed');
-- Create tasks table
CREATE TABLE tasks (
id UUID PRIMARY KEY NOT NULL,
title VARCHAR(255) NOT NULL,
description TEXT,
status task_status NOT NULL DEFAULT 'pending',
version INT8 NOT NULL DEFAULT 1,
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL
);
-- Create indexes
CREATE INDEX idx_tasks_status ON tasks(status);
CREATE INDEX idx_tasks_created_at ON tasks(created_at DESC);
CREATE INDEX idx_tasks_updated_at ON tasks(updated_at DESC);
.env.example
# Server Configuration
SERVER_HOST=127.0.0.1
SERVER_PORT=8080
# Database Configuration
DATABASE_URL=postgresql://postgres:password@localhost:5432/task_api
DB_MAX_CONNECTIONS=10
# Logging
LOG_LEVEL=info
tests/integration_tests.rs
#[cfg(test)]
mod tests {
use actix_web::{test, web, App};
use serde_json::json;
use sqlx::postgres::PgPoolOptions;
use task_api::{
application::TaskService,
config::Config,
infrastructure::{configure_routes, PostgresTaskRepository},
};
use uuid::Uuid;
async fn setup_test_db() -> sqlx::Pool<sqlx::Postgres> {
let database_url = std::env::var("TEST_DATABASE_URL")
.unwrap_or_else(|_| "postgresql://postgres:password@localhost/task_api_test".to_string());
let pool = PgPoolOptions::new()
.max_connections(1)
.connect(&database_url)
.await
.expect("Failed to connect to test database");
// Clean up database
sqlx::query("DROP TABLE IF EXISTS tasks CASCADE")
.execute(&pool)
.await
.ok();
// Create table
sqlx::query(
r#"
CREATE TYPE task_status AS ENUM ('pending', 'in_progress', 'completed');
CREATE TABLE tasks (
id UUID PRIMARY KEY NOT NULL,
title VARCHAR(255) NOT NULL,
description TEXT,
status task_status NOT NULL DEFAULT 'pending',
version INT8 NOT NULL DEFAULT 1,
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL
);
"#,
)
.execute(&pool)
.await
.ok();
pool
}
#[actix_web::test]
async fn test_create_task() {
let pool = setup_test_db().await;
let repository = PostgresTaskRepository::new(pool);
let service = web::Data::new(TaskService::new(repository));
let app = test::init_service(
App::new()
.app_data(service.clone())
.configure(|cfg| configure_routes(cfg, service.clone())),
)
.await;
let payload = json!({
"title": "Test Task",
"description": "A test task"
});
let req = test::TestRequest::post()
.uri("/api/tasks")
.set_json(&payload)
.to_request();
let resp = test::call_service(&app, req).await;
assert!(resp.status().is_success());
}
#[actix_web::test]
async fn test_list_tasks() {
let pool = setup_test_db().await;
let repository = PostgresTaskRepository::new(pool);
let service = web::Data::new(TaskService::new(repository));
let app = test::init_service(
App::new()
.app_data(service.clone())
.configure(|cfg| configure_routes(cfg, service.clone())),
)
.await;
let req = test::TestRequest::get()
.uri("/api/tasks?page=1&page_size=10")
.to_request();
let resp = test::call_service(&app, req).await;
assert!(resp.status().is_success());
}
#[actix_web::test]
async fn test_health_check() {
let pool = setup_test_db().await;
let repository = PostgresTaskRepository::new(pool);
let service = web::Data::new(TaskService::new(repository));
let app = test::init_service(
App::new()
.app_data(service.clone())
.configure(|cfg| configure_routes(cfg, service.clone())),
)
.await;
let req = test::TestRequest::get()
.uri("/api/health")
.to_request();
let resp = test::call_service(&app, req).await;
assert!(resp.status().is_success());
}
}
README.md
# Task API - Hexagonal Architecture with Rust
A production-ready web service demonstrating hexagonal architecture (ports & adapters) using Actix-web and SQLx.
## Architecture
┌─────────────────────────────────────────┐
│ HTTP Handlers (Adapters) │
└───────────────┬─────────────────────────┘
│
▼
┌───────────────────────┐
│ Application Layer │
│ (TaskService) │
│ (Use Cases) │
└───────────┬───────────┘
│
┌───────────┴───────────┐
│ Domain Layer │
│ (Business Logic) │
│ (Pure Traits) │
└───────────┬───────────┘
│
┌──────────┴───────────┐
▼ ▼
[Database Adapter] [HTTP Adapter]
[PostgresRepository] [Actix Handlers]
## Key Features
- **Pure Domain Logic**: Business rules in `domain/` are independent of any framework
- **Compile-time SQL Safety**: SQLx validates queries against the database schema at compile time
- **Loose Coupling**: Ports (traits) define contracts implemented by adapters
- **Easy Testing**: Mock repositories for unit testing services without database
- **Error Handling**: Domain errors properly mapped to HTTP responses
- **Type Safety**: Full type checking with Rust's strong type system
## Project Structure
- `domain/` - Pure business logic (no framework dependencies)
- `task.rs` - Task aggregate with business rules
- `errors.rs` - Domain error types
- `application/` - Application layer
- `services.rs` - TaskService orchestrating use cases
- `dto.rs` - Request/response DTOs
- `infrastructure/` - Framework and external systems
- `persistence/` - Database adapters
- `http/` - HTTP handlers and extractors
## Setup
### Prerequisites
- Rust 1.70+
- PostgreSQL 12+
### Installation
1. Clone and setup:
```bash
git clone <repo>
cd task-api
cp .env.example .env
- Create database:
createdb task_api
- Run:
cargo build
cargo run
API Endpoints
# Create task
POST /api/tasks
{
"title": "Buy milk",
"description": "Get 2L of whole milk"
}
# Get task
GET /api/tasks/{id}
# List tasks
GET /api/tasks?page=1&page_size=20
# Update task
PATCH /api/tasks/{id}
{
"title": "Updated title",
"description": null
}
# Start task
POST /api/tasks/{id}/start
# Complete task
POST /api/tasks/{id}/complete
# Delete task
DELETE /api/tasks/{id}
# Health check
GET /api/health
Testing
# Unit tests
cargo test --lib
# Integration tests
cargo test --test '*'
# Run with output
cargo test -- --nocapture
Design Patterns Used
- Hexagonal Architecture: Clear separation between domain, application, and infrastructure
- Dependency Injection: Service dependencies injected via constructor
- Repository Pattern: Abstract data access through traits
- DTO Pattern: Transform domain models for HTTP transfer
- Error Mapping: Domain errors converted to appropriate HTTP responses
- Compile-time Verification: SQLx validates SQL at compile time
Best Practices
- ✅ Pure domain logic with no framework dependencies
- ✅ Traits for all external dependencies
- ✅ Proper error handling with custom error types
- ✅ Database transaction support for consistency
- ✅ Comprehensive error responses
- ✅ Pagination support
- ✅ Optimistic locking with version numbers
- ✅ Request validation at domain boundary
License
MIT
## Running the Project
```bash
# Install dependencies
cargo fetch
# Create and setup database
createdb task_api
export DATABASE_URL="postgresql://user:password@localhost/task_api"
# Run migrations
sqlx migrate run
# Start server
cargo run
# Test endpoints
curl -X POST http://localhost:8080/api/tasks \
-H "Content-Type: application/json" \
-d '{"title":"Learn Rust"}'
curl http://localhost:8080/api/tasks
# Run tests
cargo test
This boilerplate provides:
- Clean Architecture - Clear separation of concerns with domain logic independent of frameworks
- Compile-time Safety - SQLx validates SQL queries against your database schema
- Type Safety - Full Rust type system for compile-time error detection
- Testability - Pure functions and mockable repositories
- Production Ready - Error handling, migrations, configuration, logging
- Extensibility - Easy to add new features following established patterns