refactor: migrate to clean architecture with trait-based DI (v0.2.0)

Complete architectural overhaul across all 12 crates:

- Replace validator crate with zod-rs for all DTO validation
- Replace manual pagination with paginator-rs/paginator-sea-orm
- Migrate all modules (iam, cms, gacha, dimentorin) to clean architecture:
  domain → application → infrastructure layers
- Introduce trait-based DI (Arc<dyn Trait>) at every layer for repositories and services
- Delete all v1/ legacy SurrealDB-era code across every crate
- Replace opaque response helpers with typed IntoResponse structs (ApiSuccess, ApiCreated, ApiPaginated, ApiMessage)
- Remove dual_mode_repository, migration_validation_errors, validator.rs dead code
- Zero cargo clippy warnings; release build clean

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
maulanasdqn
2026-04-02 13:39:52 +07:00
co-authored by Claude Sonnet 4.6
parent 1b3366d735
commit e432a1a743
379 changed files with 9013 additions and 30532 deletions
@@ -0,0 +1,141 @@
use std::sync::Arc;
use async_trait::async_trait;
use rand::prelude::*;
use uuid::Uuid;
use imphnen_utils::AppError;
use crate::gacha_claims::domain::{GachaClaimEntity, GachaClaimRepository};
use crate::gacha_credits::domain::GachaCreditRepository;
use crate::gacha_rolls::domain::{GachaRollEntity, GachaRollRepository, GachaRollService};
pub struct GachaRollServiceImpl {
roll_repo: Arc<dyn GachaRollRepository>,
credit_repo: Arc<dyn GachaCreditRepository>,
claim_repo: Arc<dyn GachaClaimRepository>,
}
impl GachaRollServiceImpl {
pub fn new(
roll_repo: Arc<dyn GachaRollRepository>,
credit_repo: Arc<dyn GachaCreditRepository>,
claim_repo: Arc<dyn GachaClaimRepository>,
) -> Self {
Self {
roll_repo,
credit_repo,
claim_repo,
}
}
fn roll_once(rolls: &[GachaRollEntity]) -> Option<GachaRollEntity> {
let filtered: Vec<&GachaRollEntity> = rolls
.iter()
.filter(|r| !r.is_deleted && r.quantity > 0)
.collect();
if filtered.is_empty() {
return None;
}
let total_weight: f64 = filtered
.iter()
.map(|r| f64::from(r.weight) * f64::from(r.quantity))
.sum();
if total_weight <= 0.0 {
let mut rng = rand::rngs::ThreadRng::default();
let index = rng.random_range(0..filtered.len());
return Some(filtered[index].clone());
}
let mut rng = rand::rngs::ThreadRng::default();
let random_value = rng.random_range(0.0..total_weight);
let mut cumulative_weight = 0.0;
for roll in &filtered {
cumulative_weight += f64::from(roll.weight) * f64::from(roll.quantity);
if random_value <= cumulative_weight {
return Some((*roll).clone());
}
}
Some(filtered[0].clone())
}
}
#[async_trait]
impl GachaRollService for GachaRollServiceImpl {
async fn get_roll(&self, id: Uuid) -> Result<GachaRollEntity, AppError> {
self.roll_repo.find_by_id(id).await
}
async fn create_roll(&self, entity: GachaRollEntity) -> Result<(), AppError> {
self.roll_repo.create(entity).await
}
async fn execute_roll(&self, user_id: Uuid) -> Result<GachaRollEntity, AppError> {
// 1. Check user has credits
let credit = self
.credit_repo
.find_by_user_id(user_id)
.await?
.ok_or_else(|| AppError::BadRequestError("No credit record found".to_string()))?;
if credit.available_rolls <= 0 {
return Err(AppError::BadRequestError(
"Not enough credits to perform this action".to_string(),
));
}
// 2. Consume 1 credit
self.credit_repo.consume_credit(user_id).await?;
// 3. Get all active rolls
let rolls = self.roll_repo.find_all_active().await.map_err(|e| {
AppError::InternalServerError(e.to_string())
})?;
// 4. Weighted random selection
let selected = Self::roll_once(&rolls).ok_or_else(|| {
AppError::NotFoundError("No rollable item available".to_string())
});
let selected = match selected {
Ok(r) => r,
Err(e) => {
// Refund credit on failure
let _ = self.credit_repo.add_credit(user_id, 1).await;
return Err(e);
}
};
// 5. Create claim
let claim_entity = GachaClaimEntity {
id: Uuid::new_v4(),
user_id,
gacha_item_id: selected.item_id,
claim_id: Uuid::new_v4(),
claim_type: "roll".to_string(),
status: "claimed".to_string(),
quantity: 1,
metadata: None,
is_deleted: false,
claimed_at: chrono::Utc::now(),
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
deleted_at: None,
};
if let Err(e) = self.claim_repo.create(claim_entity).await {
// 6. Refund credit on claim creation failure
let _ = self.credit_repo.add_credit(user_id, 1).await;
return Err(e);
}
// 7. Return selected roll entity
Ok(selected)
}
async fn delete_roll(&self, id: Uuid) -> Result<(), AppError> {
self.roll_repo.delete(id).await
}
}
@@ -0,0 +1,3 @@
pub mod gacha_roll_service;
pub use gacha_roll_service::GachaRollServiceImpl;
@@ -0,0 +1,15 @@
use chrono::NaiveDateTime;
use uuid::Uuid;
#[derive(Clone, Debug)]
pub struct GachaRollEntity {
pub id: Uuid,
pub user_id: Uuid,
pub gacha_id: String,
pub item_id: Uuid,
pub weight: f32,
pub quantity: i32,
pub is_deleted: bool,
pub created_at: Option<NaiveDateTime>,
pub updated_at: Option<NaiveDateTime>,
}
@@ -0,0 +1,7 @@
pub mod gacha_roll;
pub mod repository;
pub mod service;
pub use gacha_roll::GachaRollEntity;
pub use repository::GachaRollRepository;
pub use service::GachaRollService;
@@ -0,0 +1,12 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_roll::GachaRollEntity;
#[async_trait]
pub trait GachaRollRepository: Send + Sync {
async fn find_by_id(&self, id: Uuid) -> Result<GachaRollEntity, AppError>;
async fn find_all_active(&self) -> Result<Vec<GachaRollEntity>, AppError>;
async fn create(&self, entity: GachaRollEntity) -> Result<(), AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,12 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_roll::GachaRollEntity;
#[async_trait]
pub trait GachaRollService: Send + Sync {
async fn get_roll(&self, id: Uuid) -> Result<GachaRollEntity, AppError>;
async fn create_roll(&self, entity: GachaRollEntity) -> Result<(), AppError>;
async fn execute_roll(&self, user_id: Uuid) -> Result<GachaRollEntity, AppError>;
async fn delete_roll(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,46 @@
use imphnen_libs::ZodValidate;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::gacha_rolls::domain::gacha_roll::GachaRollEntity;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaRollCreateRequestDto {
pub item_id: String,
pub weight: f32,
pub quantity: i32,
}
impl ZodValidate for GachaRollCreateRequestDto {
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaRollItemDto {
pub id: String,
pub user_id: String,
pub gacha_id: String,
pub item_id: String,
pub weight: f32,
pub quantity: i32,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl From<&GachaRollEntity> for GachaRollItemDto {
fn from(e: &GachaRollEntity) -> Self {
GachaRollItemDto {
id: e.id.to_string(),
user_id: e.user_id.to_string(),
gacha_id: e.gacha_id.clone(),
item_id: e.item_id.to_string(),
weight: e.weight,
quantity: e.quantity,
is_deleted: e.is_deleted,
created_at: e.created_at.map(|d| d.to_string()),
updated_at: e.updated_at.map(|d| d.to_string()),
}
}
}
@@ -0,0 +1,129 @@
use std::sync::Arc;
use axum::{Extension, extract::Path, http::HeaderMap, response::IntoResponse};
use imphnen_libs::{AppState, ValidatedJson};
use imphnen_utils::{ApiSuccess, ApiMessage, extract_email};
use imphnen_entities::ResponseSuccessDto;
use imphnen_iam::{PermissionsEnum, require_permissions};
use imphnen_utils::AppError;
use uuid::Uuid;
use super::dto::{GachaRollCreateRequestDto, GachaRollItemDto};
use crate::gacha_rolls::domain::{GachaRollEntity, GachaRollService};
#[utoipa::path(
get,
security(("Bearer" = [])),
path = "/v1/gacha/rolls/detail/{id}",
params(
("id" = String, Path, description = "Gacha Roll ID")
),
responses(
(status = 200, description = "[ADMIN] Get gacha roll by ID", body = ResponseSuccessDto<GachaRollItemDto>)
),
tag = "Gacha"
)]
pub async fn get_gacha_roll_by_id(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaRollService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::ReadDetailGachaRolls], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
let roll = service.get_roll(uuid).await?;
Ok(ApiSuccess(GachaRollItemDto::from(&roll)))
})
}
#[utoipa::path(
post,
security(("Bearer" = [])),
path = "/v1/gacha/rolls/create",
request_body = GachaRollCreateRequestDto,
responses(
(status = 201, description = "[ADMIN] Create new gacha roll")
),
tag = "Gacha"
)]
pub async fn post_create_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaRollService>>,
ValidatedJson(payload): ValidatedJson<GachaRollCreateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers.clone(), state, [PermissionsEnum::CreateGachaRolls], {
let email = extract_email(&headers)
.ok_or_else(|| AppError::AuthenticationError("Unauthorized".to_string()))?;
let user_info = state.user_lookup_service.get_user_by_email(&email, &state).await
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
let user_id = Uuid::parse_str(&user_info.basic_info.id)
.map_err(|e| AppError::BadRequestError(e.to_string()))?;
let item_id = Uuid::parse_str(&payload.item_id)
.map_err(|e| AppError::BadRequestError(format!("Invalid item_id UUID: {e}")))?;
let entity = GachaRollEntity {
id: Uuid::new_v4(),
user_id,
gacha_id: "default".to_string(),
item_id,
weight: payload.weight,
quantity: payload.quantity,
is_deleted: false,
created_at: Some(chrono::Utc::now().naive_utc()),
updated_at: Some(chrono::Utc::now().naive_utc()),
};
service.create_roll(entity).await?;
Ok(ApiMessage::created("Gacha roll created"))
})
}
#[utoipa::path(
post,
security(("Bearer" = [])),
path = "/v1/gacha/rolls/execute",
responses(
(status = 200, description = "[USER] Execute a gacha roll and receive a result", body = ResponseSuccessDto<GachaRollItemDto>)
),
tag = "Gacha"
)]
pub async fn post_execute_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaRollService>>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers.clone(), state, [PermissionsEnum::ExecuteGachaRolls], {
let email = extract_email(&headers)
.ok_or_else(|| AppError::AuthenticationError("Unauthorized".to_string()))?;
let user_info = state.user_lookup_service.get_user_by_email(&email, &state).await
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
let user_id = Uuid::parse_str(&user_info.basic_info.id)
.map_err(|e| AppError::BadRequestError(e.to_string()))?;
let roll = service.execute_roll(user_id).await?;
Ok(ApiSuccess(GachaRollItemDto::from(&roll)))
})
}
#[utoipa::path(
delete,
security(("Bearer" = [])),
path = "/v1/gacha/rolls/delete/{id}",
params(
("id" = String, Path, description = "Gacha Roll ID")
),
responses(
(status = 200, description = "[ADMIN] Delete gacha roll (soft delete)")
),
tag = "Gacha"
)]
pub async fn delete_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaRollService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::DeleteGachaRolls], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
service.delete_roll(uuid).await?;
Ok(ApiMessage::ok("Gacha roll deleted"))
})
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handlers;
pub mod routes;
pub use routes::gacha_roll_router;
@@ -0,0 +1,31 @@
use std::sync::Arc;
use axum::{Router, routing::{delete, get, post}, Extension};
use sea_orm::DatabaseConnection;
use crate::gacha_claims::infrastructure::persistence::PostgresGachaClaimRepository;
use crate::gacha_credits::infrastructure::persistence::PostgresGachaCreditRepository;
use crate::gacha_rolls::application::GachaRollServiceImpl;
use crate::gacha_rolls::domain::GachaRollService;
use crate::gacha_rolls::infrastructure::persistence::PostgresGachaRollRepository;
use super::handlers::{
delete_gacha_roll, get_gacha_roll_by_id, post_create_gacha_roll, post_execute_gacha_roll,
};
fn build_service(
db: DatabaseConnection,
state: Arc<imphnen_libs::AppState>,
) -> Arc<dyn GachaRollService> {
let roll_repo = Arc::new(PostgresGachaRollRepository::new(db.clone()));
let credit_repo = Arc::new(PostgresGachaCreditRepository::new(db.clone()));
let claim_repo = Arc::new(PostgresGachaClaimRepository::new(db, state));
Arc::new(GachaRollServiceImpl::new(roll_repo, credit_repo, claim_repo))
}
pub fn gacha_roll_router(db: DatabaseConnection, state: Arc<imphnen_libs::AppState>) -> Router {
let service = build_service(db, state);
Router::new()
.route("/detail/{id}", get(get_gacha_roll_by_id))
.route("/create", post(post_create_gacha_roll))
.route("/execute", post(post_execute_gacha_roll))
.route("/delete/{id}", delete(delete_gacha_roll))
.layer(Extension(service))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1,3 @@
pub mod postgres_gacha_roll_repository;
pub use postgres_gacha_roll_repository::PostgresGachaRollRepository;
@@ -0,0 +1,100 @@
use std::sync::Arc;
use async_trait::async_trait;
use sea_orm::prelude::*;
use sea_orm::{ActiveValue, QueryFilter};
use uuid::Uuid;
use imphnen_utils::AppError;
use imphnen_entities::seaorm::gacha::gacha_rolls::{
Entity as GachaRollsEntity, Column as GachaRollColumn,
ActiveModel as GachaRollActiveModel, Model as GachaRollModel,
};
use crate::gacha_rolls::domain::{gacha_roll::GachaRollEntity, repository::GachaRollRepository};
fn to_entity(model: GachaRollModel) -> GachaRollEntity {
GachaRollEntity {
id: model.id,
user_id: model.user_id,
gacha_id: model.gacha_id,
item_id: model.item_id,
weight: model.weight,
quantity: model.quantity,
is_deleted: model.is_deleted,
created_at: model.created_at,
updated_at: model.updated_at,
}
}
pub struct PostgresGachaRollRepository {
db: Arc<DatabaseConnection>,
}
impl PostgresGachaRollRepository {
pub fn new(db: DatabaseConnection) -> Self {
Self { db: Arc::new(db) }
}
}
#[async_trait]
impl GachaRollRepository for PostgresGachaRollRepository {
async fn find_by_id(&self, id: Uuid) -> Result<GachaRollEntity, AppError> {
let roll = GachaRollsEntity::find_by_id(id)
.filter(GachaRollColumn::IsDeleted.eq(false))
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Gacha roll not found".to_string()))?;
Ok(to_entity(roll))
}
async fn find_all_active(&self) -> Result<Vec<GachaRollEntity>, AppError> {
let rolls = GachaRollsEntity::find()
.filter(GachaRollColumn::IsDeleted.eq(false))
.filter(GachaRollColumn::Quantity.gt(0))
.all(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(rolls.into_iter().map(to_entity).collect())
}
async fn create(&self, entity: GachaRollEntity) -> Result<(), AppError> {
let active_model = GachaRollActiveModel {
id: ActiveValue::Set(entity.id),
user_id: ActiveValue::Set(entity.user_id),
gacha_id: ActiveValue::Set(entity.gacha_id),
item_id: ActiveValue::Set(entity.item_id),
weight: ActiveValue::Set(entity.weight),
quantity: ActiveValue::Set(entity.quantity),
is_deleted: ActiveValue::Set(false),
created_at: ActiveValue::Set(Some(chrono::Utc::now().naive_utc())),
updated_at: ActiveValue::Set(Some(chrono::Utc::now().naive_utc())),
};
GachaRollsEntity::insert(active_model)
.exec(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
let mut active_model: GachaRollActiveModel = GachaRollsEntity::find_by_id(id)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Gacha roll not found".to_string()))?
.into();
active_model.is_deleted = ActiveValue::Set(true);
active_model.updated_at = ActiveValue::Set(Some(chrono::Utc::now().naive_utc()));
active_model
.update(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod application;
pub mod domain;
pub mod infrastructure;
pub use infrastructure::http::gacha_roll_router;