예제

예제로 배우기.

핵심 개념, HTTP 라우팅, 인증, 영속성, 관측성, 프로토콜 어댑터를 다루는 분류별 예제를 탐색하세요. 각 카드는 GitHub 리포지토리의 전체 소스로 연결됩니다.

학습 경로

초급에서 고급까지 단계별 가이드를 따라가세요.

빠른 시작

초급

30분 안에 첫 번째 Axon 워크플로우를 구축하세요.

1. hello-world2. typed-state-tree3. outcome-variants4. testing-patterns5. custom-error-types6. routing-demo7. closure-transition

HTTP 서비스

중급

라우팅, 인증, 실시간 기능을 갖춘 프로덕션 HTTP API를 구축하세요.

1. routing-params2. flat-api3. session-pattern4. multipart-upload5. websocket6. sse-streaming7. openapi8. reference-todo-api

고급 패턴

고급

장애 복원력, 영속성, 엔터프라이즈 패턴을 마스터하세요.

1. order-processing2. retry-dlq3. state-persistence4. multitenancy5. llm-content-moderation6. reference-ecommerce-order

인증 & 보안

중급

Guard 노드, JWT 인증, 역할 기반 접근 제어로 API를 보호하세요.

1. guard-demo2. guard-integration3. auth-jwt-role4. auth-transition5. session-pattern

전체 예제

티어
카테고리
패턴
도메인

Hello World

core 초급

최소 Flat API 예제 — 트랜지션을 체이닝하여 인사말 생성 및 변환.

~5분
#[transition]
async fn greet(input: String) -> Outcome<String, String> {
    Outcome::Next(format!("Hello, {input}!"))
}

타입 안전 상태 트리

core 초급

Axon, Transition, Outcome을 사용한 타입 안전 의사결정 흐름.

~10분
let flow = Axon::new("flow")
    .then(validate)
    .then(process);

기본 스케매틱

core 초급

디버깅 및 문서화를 위한 스케매틱 추출을 통한 Axon 흐름 시각화.

~10분

의사결정 트리 라우팅

core 중급

Outcome::Branch를 사용한 접두사 기반 경로 라우팅 및 중첩 의사결정 트리.

~15분

주문 처리 워크플로우

core 중급

도메인 주도 워크플로우: 검증, 결제, 재고 예약, 배송 처리.

~20분
Axon::new("order")
    .then(validate_order)
    .then(process_payment)
    .then(reserve_inventory)
    .then(arrange_shipping)

Bus 접근 제어 시스템

core 중급

@transition bus 속성을 통한 선언적 허용/거부 접근 제어.

~15분
#[transition(bus_allow = "db,cache")]
async fn fetch(input: Req) -> Outcome<Resp, String> { .. }

Outcome 변형

core 초급

5가지 Outcome 변형: Next(선형), Fault(에러), Branch(조건부), Jump(루프), Emit(사이드이펙트).

~15분
// 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

클로저 트랜지션

core 초급

then_fn(), Axon::typed(), post_typed()를 사용한 인라인 클로저 트랜지션 경량 파이프라인.

~10분
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}!")}))
    })

라우트 파라미터

core 초급

HTTP 핸들러에서 경로, 쿼리, 바디 파라미터의 타입 안전 추출.

~10분

Flat API 패턴

core 초급

@transition과 @ranvier_router 매크로를 사용한 간결한 라우트 정의.

~10분
#[ranvier_router]
fn routes() -> Router {
    route!(GET "/users" => list_users);
    route!(POST "/users" => create_user);
}

세션 패턴

core 중급

고급 세션 생명주기 패턴: 생성, 검증, 만료, 정리.

~15분

멀티파트 업로드

core 중급

multipart/form-data 추출 및 검증을 통한 파일 업로드 처리.

~15분

WebSocket 인그레스

core 중급

이벤트 기반 메시징 및 세션 컨텍스트를 갖춘 WebSocket 연결.

~20분

WebSocket 에코 루프

core 중급

에코 루프와 연결 생명주기를 갖춘 양방향 WebSocket 통신.

~15분

SSE 스트리밍

core 중급

클라이언트에 대한 실시간 스트리밍 응답을 위한 Server-Sent Events.

~15분

OpenAPI 문서 생성

core 중급

schemars를 통한 스키마 검증과 자동 생성 OpenAPI/Swagger 문서.

~20분

정적 파일 서빙

core 초급

설정 가능한 디렉토리에서 정적 파일 및 빌드 자산 제공.

~10분

SPA 호스팅

core 초급

폴백 라우팅과 자산 제공을 갖춘 싱글 페이지 애플리케이션 호스팅.

~10분

타입 안전 JSON API

core 중급

get_json_out, post_typed_json_out, BusHttpExt, CorsGuard::permissive()를 사용하는 타입 안전 JSON 엔드포인트.

~20분
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 파이프라인

core 중급

CorsGuard, RateLimitGuard, SecurityHeadersGuard, IpFilterGuard를 시각적 Transition 노드로 사용하는 HTTP 보안 파이프라인.

~15분
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 역할 기반 인증

core 중급

HS256 JWT를 사용한 IamVerifier 구현, IamPolicy::RequireRole, Axon::with_iam() 경계 검증.

~20분
let admin_circuit = Axon::new("admin-dashboard")
    .with_iam(
        IamPolicy::RequireRole("admin".into()),
        JwtVerifier,
    )
    .then(AdminDashboard);

Guard 통합

core 중급

파이프라인 우선 미들웨어: 10개 Guard(글로벌 + 라우트별), guards![] 매크로, Tower 대체.

~25분
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 기반 인증

core 중급

Bus 기반 컨텍스트 전파를 갖춘 조합 가능한 Transition 노드로 구현한 인증.

~20분

장애 복구 & 영속성

core 중급

워크플로우 장애 복구, 체크포인팅, 보상 훅.

~20분
Axon::new("resilient")
    .then(step_a)
    .then(step_b)
    .with_persistence(store)
    .with_compensation(rollback);

Redis 통합

core 중급

비동기 ConnectionManager를 사용한 세션 저장소 및 캐시용 Redis.

~20분

SeaORM 통합

core 중급

마이그레이션 및 액티브 모델을 사용한 Sea ORM 데이터베이스 작업.

~25분

SQLx 데이터베이스 통합

core 중급

Bus를 통한 SQLx 풀 주입과 인메모리 SQLite를 사용한 Transition 기반 쿼리.

~20분
let db = DbPool(pool);
let insert_axon = Axon::new("insert-user")
    .then(InsertUser);
insert_axon.execute(req, &db, &mut bus).await;

Traced 래퍼

core 중급

Traced 래퍼와 ConnectionBus를 사용한 트랜지션의 자동 스팬 생성.

~20분

Synapse 외부 서비스 통합

core 중급

타입 안전한 외부 서비스 호출(DB, API, 메시징)을 위한 코어 Synapse 트레이트.

~20분

프로덕션 설정

core 중급

ranvier.toml 설정, 환경변수 오버라이드, 프로파일, 구조화 로깅, 그레이스풀 셧다운.

~15분

표준 라이브러리

core 중급

내장 트랜지션: FilterNode, SwitchNode, LogNode 파이프라인 조합.

~15분

멀티테넌시

core 중급

Bus 주입 TenantId와 범위 지정 데이터 접근을 통한 테넌트 격리 패턴.

~20분

외부 서비스 호출

core 중급

HTTP 서비스 호출을 Transition으로 래핑하여 Outcome 기반 에러 매핑 및 재시도/타임아웃 적용.

~15분

테스팅 패턴

core 초급

Transition 및 Axon 체인을 위한 단위 및 통합 테스트 전략.

~15분

커스텀 에러 타입

core 초급

타입 안전 에러 처리를 위한 thiserror 기반 도메인별 에러 enum.

~15분

Outcome 패턴

core 중급

try_outcome! 매크로, Outcome::from_result(), and_then/map_fault 컴비네이터, Bus::get_cloned(), json_outcome() 시연.

~20분
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()));

재시도 & 데드레터 큐

core 중급

지수 백오프를 갖춘 DLQ 재시도, 타임아웃 패턴, 서킷 브레이커.

~25분
let axon = Axon::new("payment")
    .then(gateway)
    .with_dlq_policy(DlqPolicy::RetryThenDlq {
        max_attempts: 5,
        backoff_ms: 100,
    })
    .with_dlq_sink(dlq);

상태 영속성 & 복구

core 중급

장애 복구, 체크포인팅, 보상을 갖춘 내구성 워크플로우 실행.

~25분

장애 복원력 패턴

core 중급

Axon 수준 복원력: then_with_timeout(), then_with_retry(), 일시적 장애 처리.

~20분
let axon = Axon::simple::<String>("resilient-api")
    .then_with_retry(flaky_service, 3)
    .then_with_timeout(slow_service, Duration::from_secs(5));

LLM 콘텐츠 모더레이션

core 중급

3단계 LLM 파이프라인: 콘텐츠 추출, AI 분류, 정책 적용.

~25분
// ExtractContent → ModerateContent → ApplyPolicy
Axon::new("moderate")
    .then(extract_content)
    .then(moderate_content)
    .then(apply_policy)

레퍼런스 이커머스 주문

core 고급

보상 처리, 감사 추적, 멀티테넌시, RFC 7807 에러를 갖춘 완전한 Saga 파이프라인.

~40분
// Saga: CreateOrder → ProcessPayment → ReserveInventory → ScheduleShipping
//          ↓ (comp)          ↓ (comp)
//      RefundPayment    ReleaseInventory

레퍼런스 채팅 서버

core 고급

JWT 인증, REST + WS 하이브리드 라우팅, 메시지 영속성을 갖춘 멀티룸 WebSocket 채팅.

~35분

레퍼런스 Todo API

core 중급

JWT 인증, Bus 의존성 주입, HTTP 라우팅, 컬렉션 기반 테스트를 갖춘 완전한 CRUD 애플리케이션.

~30분
// 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 보상 패턴

core 중급

다단계 보상 체인 — 단계 실패 시 완료된 단계를 역순으로 롤백.

~20분
// Reserve → Charge → Ship (compensate in reverse on failure)
let saga = Axon::<Order, Order, String>::new("OrderSaga")
    .then(ReserveInventory)
    .then(ChargePayment)
    .then(ConfirmShipping);

캐스케이드 스크리닝

core 중급

페일패스트 순차 필터 파이프라인 — 각 스크린이 즉시 거부하고 체인을 단락시킬 수 있음.

~20분
// Sanctions → PEP → Risk Score → Documents
let screening = Axon::<Applicant, Applicant, String>::new("Screening")
    .then(SanctionsCheck)
    .then(PepCheck)
    .then(RiskScoring)
    .then(DocumentVerification);

LLM 에이전트 파이프라인

core 중급

다단계 타입 파이프라인 — 인텐트 분류, 도구 선택, 실행, 응답 포맷팅.

~20분
// Query → ClassifiedQuery → ToolResult → Response
let pipeline = Axon::<Query, Query, String>::new("AgentPipeline")
    .then(ClassifyIntent)
    .then(ExecuteTool)
    .then(FormatResponse);

센서 결정 루프

core 중급

센서 데이터가 임계값 평가를 거쳐 액추에이터 명령을 생성.

~20분
// SensorReading → EvaluatedReading → ActuatorCommand
let pipeline = Axon::<SensorReading, SensorReading, String>::new("SensorDecision")
    .then(EvaluateThresholds)
    .then(MakeDecision);

트리아지 분기

core 중급

Outcome::Branch로 대상을 이름 있는 부서로 라우팅하는 다단계 분류.

~20분
// Vitals → Severity → Department routing
let triage = Axon::<Patient, Patient, String>::new("PatientTriage")
    .then(AssessVitals)
    .then(ClassifySeverity)
    .then(RouteToDepartment);

자격 규칙 체인

core 중급

페일패스트 순차 독립 규칙 — 각 규칙이 거부 가능, 규칙 순서 변경 가능.

~20분
// Age → Income → Residency → BenefitCap
let rules = Axon::<Applicant, Applicant, String>::new("Eligibility")
    .then(AgeRule)
    .then(IncomeRule)
    .then(ResidencyRule)
    .then(BenefitCapRule);
모든 예제는 GitHub 리포지토리의 ranvier/examples 에 있습니다. 클론 후 cargo run -p <package>로 실행하세요.