예제
예제로 배우기.
핵심 개념, HTTP 라우팅, 인증, 영속성, 관측성, 프로토콜 어댑터를 다루는 분류별 예제를 탐색하세요. 각 카드는 GitHub 리포지토리의 전체 소스로 연결됩니다.
학습 경로
초급에서 고급까지 단계별 가이드를 따라가세요.
빠른 시작
초급30분 안에 첫 번째 Axon 워크플로우를 구축하세요.
HTTP 서비스
중급라우팅, 인증, 실시간 기능을 갖춘 프로덕션 HTTP API를 구축하세요.
고급 패턴
고급장애 복원력, 영속성, 엔터프라이즈 패턴을 마스터하세요.
인증 & 보안
중급Guard 노드, JWT 인증, 역할 기반 접근 제어로 API를 보호하세요.
전체 예제
Hello World
최소 Flat API 예제 — 트랜지션을 체이닝하여 인사말 생성 및 변환.
#[transition]
async fn greet(input: String) -> Outcome<String, String> {
Outcome::Next(format!("Hello, {input}!"))
}타입 안전 상태 트리
Axon, Transition, Outcome을 사용한 타입 안전 의사결정 흐름.
let flow = Axon::new("flow")
.then(validate)
.then(process);기본 스케매틱
디버깅 및 문서화를 위한 스케매틱 추출을 통한 Axon 흐름 시각화.
의사결정 트리 라우팅
Outcome::Branch를 사용한 접두사 기반 경로 라우팅 및 중첩 의사결정 트리.
주문 처리 워크플로우
도메인 주도 워크플로우: 검증, 결제, 재고 예약, 배송 처리.
Axon::new("order")
.then(validate_order)
.then(process_payment)
.then(reserve_inventory)
.then(arrange_shipping)Bus 접근 제어 시스템
@transition bus 속성을 통한 선언적 허용/거부 접근 제어.
#[transition(bus_allow = "db,cache")]
async fn fetch(input: Req) -> Outcome<Resp, String> { .. }Outcome 변형
5가지 Outcome 변형: Next(선형), Fault(에러), Branch(조건부), Jump(루프), Emit(사이드이펙트).
// Outcome<T, E> — control flow as data
Outcome::Next(value) // linear progression
Outcome::Fault(err) // error path
Outcome::Branch("name", v) // conditional routing
Outcome::Jump("node", v) // goto / loop
Outcome::Emit(event) // side-effect event클로저 트랜지션
then_fn(), Axon::typed(), post_typed()를 사용한 인라인 클로저 트랜지션 경량 파이프라인.
Axon::typed::<GreetRequest, String>("greet")
.then_fn("validate", |req, _bus| {
if req.name.is_empty() {
Outcome::Fault("empty".into())
} else {
Outcome::Next(req.name)
}
})
.then_fn("format", |name, _bus| {
Outcome::Next(json!({"message": format!("Hello, {name}!")}))
})라우트 파라미터
HTTP 핸들러에서 경로, 쿼리, 바디 파라미터의 타입 안전 추출.
Flat API 패턴
@transition과 @ranvier_router 매크로를 사용한 간결한 라우트 정의.
#[ranvier_router]
fn routes() -> Router {
route!(GET "/users" => list_users);
route!(POST "/users" => create_user);
}세션 패턴
고급 세션 생명주기 패턴: 생성, 검증, 만료, 정리.
멀티파트 업로드
multipart/form-data 추출 및 검증을 통한 파일 업로드 처리.
WebSocket 인그레스
이벤트 기반 메시징 및 세션 컨텍스트를 갖춘 WebSocket 연결.
WebSocket 에코 루프
에코 루프와 연결 생명주기를 갖춘 양방향 WebSocket 통신.
SSE 스트리밍
클라이언트에 대한 실시간 스트리밍 응답을 위한 Server-Sent Events.
OpenAPI 문서 생성
schemars를 통한 스키마 검증과 자동 생성 OpenAPI/Swagger 문서.
정적 파일 서빙
설정 가능한 디렉토리에서 정적 파일 및 빌드 자산 제공.
SPA 호스팅
폴백 라우팅과 자산 제공을 갖춘 싱글 페이지 애플리케이션 호스팅.
타입 안전 JSON API
get_json_out, post_typed_json_out, BusHttpExt, CorsGuard::permissive()를 사용하는 타입 안전 JSON 엔드포인트.
Ranvier::http()
.get_json_out("/items", list_items_axon)
.post_typed_json_out::<CreateItem, _, _>("/items", create_item_axon)
.delete_json_out("/items/:id", delete_item_axon)Guard 파이프라인
CorsGuard, RateLimitGuard, SecurityHeadersGuard, IpFilterGuard를 시각적 Transition 노드로 사용하는 HTTP 보안 파이프라인.
Axon::new("Guarded API")
.then(CorsGuard::new(cors_config))
.then(RateLimitGuard::new(100, 60_000))
.then(SecurityHeadersGuard::new(policy))
.then(IpFilterGuard::allow_list(["127.0.0.1"]))
.then(HelloHandler)JWT 역할 기반 인증
HS256 JWT를 사용한 IamVerifier 구현, IamPolicy::RequireRole, Axon::with_iam() 경계 검증.
let admin_circuit = Axon::new("admin-dashboard")
.with_iam(
IamPolicy::RequireRole("admin".into()),
JwtVerifier,
)
.then(AdminDashboard);Guard 통합
파이프라인 우선 미들웨어: 10개 Guard(글로벌 + 라우트별), guards![] 매크로, Tower 대체.
Ranvier::http()
.guard(CorsGuard::<()>::new(cors_config))
.guard(CompressionGuard::<()>::new())
.guard(AuthGuard::<()>::bearer(tokens))
.get("/api/hello", hello_circuit)
.post_with_guards("/api/orders", order_circuit, guards![
TimeoutGuard::<()>::new(Duration::from_secs(30)),
ContentTypeGuard::<()>::json(),
IdempotencyGuard::<()>::ttl_5min(),
])Transition 기반 인증
Bus 기반 컨텍스트 전파를 갖춘 조합 가능한 Transition 노드로 구현한 인증.
장애 복구 & 영속성
워크플로우 장애 복구, 체크포인팅, 보상 훅.
Axon::new("resilient")
.then(step_a)
.then(step_b)
.with_persistence(store)
.with_compensation(rollback);Redis 통합
비동기 ConnectionManager를 사용한 세션 저장소 및 캐시용 Redis.
SeaORM 통합
마이그레이션 및 액티브 모델을 사용한 Sea ORM 데이터베이스 작업.
SQLx 데이터베이스 통합
Bus를 통한 SQLx 풀 주입과 인메모리 SQLite를 사용한 Transition 기반 쿼리.
let db = DbPool(pool);
let insert_axon = Axon::new("insert-user")
.then(InsertUser);
insert_axon.execute(req, &db, &mut bus).await;Traced 래퍼
Traced 래퍼와 ConnectionBus를 사용한 트랜지션의 자동 스팬 생성.
Synapse 외부 서비스 통합
타입 안전한 외부 서비스 호출(DB, API, 메시징)을 위한 코어 Synapse 트레이트.
프로덕션 설정
ranvier.toml 설정, 환경변수 오버라이드, 프로파일, 구조화 로깅, 그레이스풀 셧다운.
표준 라이브러리
내장 트랜지션: FilterNode, SwitchNode, LogNode 파이프라인 조합.
멀티테넌시
Bus 주입 TenantId와 범위 지정 데이터 접근을 통한 테넌트 격리 패턴.
외부 서비스 호출
HTTP 서비스 호출을 Transition으로 래핑하여 Outcome 기반 에러 매핑 및 재시도/타임아웃 적용.
테스팅 패턴
Transition 및 Axon 체인을 위한 단위 및 통합 테스트 전략.
커스텀 에러 타입
타입 안전 에러 처리를 위한 thiserror 기반 도메인별 에러 enum.
Outcome 패턴
try_outcome! 매크로, Outcome::from_result(), and_then/map_fault 컴비네이터, Bus::get_cloned(), json_outcome() 시연.
let config = try_outcome!(bus.get_cloned::<AppConfig>(), "AppConfig not in Bus");
let result = Outcome::from_result(service.call().await)
.map_fault(|e| AppError::Service(e.to_string()));재시도 & 데드레터 큐
지수 백오프를 갖춘 DLQ 재시도, 타임아웃 패턴, 서킷 브레이커.
let axon = Axon::new("payment")
.then(gateway)
.with_dlq_policy(DlqPolicy::RetryThenDlq {
max_attempts: 5,
backoff_ms: 100,
})
.with_dlq_sink(dlq);상태 영속성 & 복구
장애 복구, 체크포인팅, 보상을 갖춘 내구성 워크플로우 실행.
장애 복원력 패턴
Axon 수준 복원력: then_with_timeout(), then_with_retry(), 일시적 장애 처리.
let axon = Axon::simple::<String>("resilient-api")
.then_with_retry(flaky_service, 3)
.then_with_timeout(slow_service, Duration::from_secs(5));LLM 콘텐츠 모더레이션
3단계 LLM 파이프라인: 콘텐츠 추출, AI 분류, 정책 적용.
// ExtractContent → ModerateContent → ApplyPolicy
Axon::new("moderate")
.then(extract_content)
.then(moderate_content)
.then(apply_policy)레퍼런스 이커머스 주문
보상 처리, 감사 추적, 멀티테넌시, RFC 7807 에러를 갖춘 완전한 Saga 파이프라인.
// Saga: CreateOrder → ProcessPayment → ReserveInventory → ScheduleShipping
// ↓ (comp) ↓ (comp)
// RefundPayment ReleaseInventory레퍼런스 채팅 서버
JWT 인증, REST + WS 하이브리드 라우팅, 메시지 영속성을 갖춘 멀티룸 WebSocket 채팅.
레퍼런스 Todo API
JWT 인증, Bus 의존성 주입, HTTP 라우팅, 컬렉션 기반 테스트를 갖춘 완전한 CRUD 애플리케이션.
// Single-transition Axon circuits per endpoint
POST /login -> [login] -> JWT token
GET /todos -> [list_todos] -> Vec<Todo>
POST /todos -> [create_todo] -> Todo
PUT /todos/:id -> [update_todo] -> Todo
DELETE /todos/:id -> [delete_todo] -> { deleted }Saga 보상 패턴
다단계 보상 체인 — 단계 실패 시 완료된 단계를 역순으로 롤백.
// Reserve → Charge → Ship (compensate in reverse on failure)
let saga = Axon::<Order, Order, String>::new("OrderSaga")
.then(ReserveInventory)
.then(ChargePayment)
.then(ConfirmShipping);캐스케이드 스크리닝
페일패스트 순차 필터 파이프라인 — 각 스크린이 즉시 거부하고 체인을 단락시킬 수 있음.
// Sanctions → PEP → Risk Score → Documents
let screening = Axon::<Applicant, Applicant, String>::new("Screening")
.then(SanctionsCheck)
.then(PepCheck)
.then(RiskScoring)
.then(DocumentVerification);LLM 에이전트 파이프라인
다단계 타입 파이프라인 — 인텐트 분류, 도구 선택, 실행, 응답 포맷팅.
// Query → ClassifiedQuery → ToolResult → Response
let pipeline = Axon::<Query, Query, String>::new("AgentPipeline")
.then(ClassifyIntent)
.then(ExecuteTool)
.then(FormatResponse);센서 결정 루프
센서 데이터가 임계값 평가를 거쳐 액추에이터 명령을 생성.
// SensorReading → EvaluatedReading → ActuatorCommand
let pipeline = Axon::<SensorReading, SensorReading, String>::new("SensorDecision")
.then(EvaluateThresholds)
.then(MakeDecision);트리아지 분기
Outcome::Branch로 대상을 이름 있는 부서로 라우팅하는 다단계 분류.
// Vitals → Severity → Department routing
let triage = Axon::<Patient, Patient, String>::new("PatientTriage")
.then(AssessVitals)
.then(ClassifySeverity)
.then(RouteToDepartment);자격 규칙 체인
페일패스트 순차 독립 규칙 — 각 규칙이 거부 가능, 규칙 순서 변경 가능.
// Age → Income → Residency → BenefitCap
let rules = Axon::<Applicant, Applicant, String>::new("Eligibility")
.then(AgeRule)
.then(IncomeRule)
.then(ResidencyRule)
.then(BenefitCapRule);cargo run -p <package>로 실행하세요.