예제

예제로 배우기.

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

학습 경로

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

빠른 시작

초급

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

1. hello-world2. typed-state-tree3. testing-patterns4. custom-error-types5. routing-demo

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. auth-jwt-role3. 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> { .. }

라우트 파라미터

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분

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);

장애 복구 & 영속성

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 초급

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

~15분

커스텀 에러 타입

core 초급

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

~15분

재시도 & 데드레터 큐

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분

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 }
모든 예제는 GitHub 리포지토리의 ranvier/examples 에 있습니다. 클론 후 cargo run -p <package>로 실행하세요.