Rust
****Layered Architecture
handler (HTTP/gRPC) → service () → repository ()
handler /service IOrepository /
****Hexagonal/Ports & Adapters traitportIO adapter mock trait
**** trait dyn Trait <T: Trait> —— DI
**** tokio::sync::broadcast flume channel /
**** enum match
//
mod handler { // HTTP
pub async fn create_user(Json(payload): Json<CreateUserReq>)
-> Result<Json<User>, AppError> { ... }
}
mod service { //
pub fn create_user(repo: &impl UserRepo, req: CreateUserReq)
-> Result<User, ServiceError> { ... }
}
mod repository { //
#[async_trait]
pub trait UserRepo {
async fn insert(&self, user: User) -> Result<(), DbError>;
async fn find_by_id(&self, id: Uuid) -> Result<User, DbError>;
}
}//
enum Connection {
Disconnected,
Connecting { retries: u32 },
Connected { session_id: Uuid },
Failed(String),
}
impl Connection {
fn next(self, event: Event) -> Self {
match (self, event) {
(Self::Disconnected, Event::Connect) =>
Self::Connecting { retries: 0 },
(Self::Connecting { retries }, Event::Timeout) if retries < 3 =>
Self::Connecting { retries: retries + 1 },
(Self::Connecting { .. }, Event::Authenticated(id)) =>
Self::Connected { session_id: id },
_ => self,
}
}
}