Getting Started

Last update - 2025. 9. 5.

개요

Orbital은 LUNE 프로토콜을 사용하여 고성능 서버를 구현하기 위한 Rust 라이브러리입니다. Express.js와 유사한 API를 제공하면서도 Rust의 강력한 타입 시스템과 성능을 활용할 수 있습니다.

LUNE 프로토콜이란?

LUNE는 Length-prefixed Universal Network Exchange의 약자로, 헤더와 바디로 구성된 커스텀 네트워크 프로토콜입니다:

  • 헤더 필드 : status, origin, nonce, type, datetime 등의 메타데이터
  • 바디 : JSON 또는 바이너리 데이터를 포함하는 페이로드
  • 지속 연결 : WebSocket처럼 연결을 유지하여 실시간 통신 지원

Orbital의 주요 특징

  • Express 스타일 라우팅 : 직관적인 라우트 정의와 미들웨어 체인
  • 강력한 타입 시스템 : 컴파일 타임에 많은 버그를 방지
  • 비동기 처리 : Tokio 기반의 고성능 비동기 I/O
  • 연결 관리 : 자동 하트비트와 연결 상태 모니터링
  • 이벤트 시스템 : 애플리케이션 전반의 이벤트 기반 아키텍처
  • 미들웨어 지원 : 로깅, CORS, 인증 등의 재사용 가능한 컴포넌트

설치

Orbital을 프로젝트에 추가하려면 Cargo.toml 파일에 다음을 추가하세요:

[dependencies]
orbital = "0.1.0"
tokio = { version = "1.0", features = ["full"] }

또는 cargo 명령어를 사용하여 설치할 수 있습니다:

cargo add orbital --git https://github.com/arcadiasofts/orbital.git
cargo add tokio --features full

빠른 시작

1. 기본 서버 설정

use orbital::application::OrbitApplication;
use orbital::router::{Router, RouteResponse};
use serde_json::json;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 애플리케이션 생성
    let mut app = OrbitApplication::new(
        Some("My LUNE Server".to_string()),
        Some("LUNE 프로토콜 기반 서버".to_string()),
        Some("1.0.0".to_string())
    );

    // 기본 라우터 생성
    let mut router = Router::new("Main Router");

    // 기본 라우트 추가
    router.read("/", Arc::new(|_ctx| {
        Ok(RouteResponse::json(json!({
            "message": "Hello, Orbital!",
            "protocol": "LUNE/1"
        })))
    }));

    // 라우터 등록
    app.register(router)?;

    println!("🚀 서버가 포트 8080에서 시작됩니다...");
    app.listen(8080).await?;

    Ok(())
}

2. Express 스타일 라우팅

use orbital::application::OrbitApplication;
use orbital::router::{Router, RouteResponse};
use serde_json::json;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut app = OrbitApplication::new(
        Some("API Server".to_string()),
        Some("RESTful API with LUNE".to_string()),
        Some("1.0.0".to_string())
    );

    // API 라우터 생성
    let mut api_router = Router::with_base_path("API Router", "/api");

    // 미들웨어 추가
    api_router
        .use_logger()  // 요청 로깅
        .use_cors();   // CORS 지원

    // CRUD 라우트들
    api_router.read("/users", Arc::new(|_ctx| {
        Ok(RouteResponse::json(json!({
            "users": [
                {"id": 1, "name": "Alice"},
                {"id": 2, "name": "Bob"}
            ]
        })))
    }));

    api_router.read("/users/:id", Arc::new(|ctx| {
        if let Some(user_id) = ctx.param("id") {
            Ok(RouteResponse::json(json!({
                "user": {
                    "id": user_id.parse::<i32>().unwrap_or(0),
                    "name": format!("User {}", user_id)
                }
            })))
        } else {
            Ok(RouteResponse::error(400, "User ID is required"))
        }
    }));

    api_router.create("/users", Arc::new(|ctx| {
        let name = ctx.body_field("name")
            .and_then(|v| v.as_str())
            .unwrap_or("Unknown");

        Ok(RouteResponse::created(json!({
            "user": {
                "id": 123,
                "name": name,
                "created_at": chrono::Utc::now().to_rfc3339()
            }
        })))
    }));

    app.register(api_router)?;

    println!("🚀 API 서버가 포트 8080에서 시작됩니다...");
    println!("📡 사용 가능한 엔드포인트:");
    println!("   READ   /api/users     - 사용자 목록");
    println!("   READ   /api/users/:id - 특정 사용자");
    println!("   CREATE /api/users     - 사용자 생성");

    app.listen(8080).await?;

    Ok(())
}

3. 미들웨어와 인증

use orbital::application::OrbitApplication;
use orbital::router::{Router, RouteResponse, MiddlewareBuilder};
use serde_json::json;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut app = OrbitApplication::new(
        Some("Secure API".to_string()),
        Some("인증이 필요한 API 서버".to_string()),
        Some("1.0.0".to_string())
    );

    // 보안 라우터 생성
    let mut secure_router = Router::with_base_path("Secure Router", "/api/secure");

    // 인증 미들웨어 추가
    secure_router
        .use_logger()
        .use_middleware(MiddlewareBuilder::auth(|ctx| {
            // API 키 검증
            ctx.body_field("api_key")
                .and_then(|v| v.as_str())
                .map(|key| key == "secret123")
                .unwrap_or(false)
        }));

    // 보호된 라우트
    secure_router.read("/profile", Arc::new(|_ctx| {
        Ok(RouteResponse::json(json!({
            "user": {
                "id": 1,
                "name": "Admin User",
                "role": "administrator",
                "permissions": ["read", "write", "delete"]
            }
        })))
    }));

    app.register(secure_router)?;

    println!("🔒 보안 API 서버가 시작됩니다...");
    println!("💡 인증 방법: body에 api_key: 'secret123' 포함");

    app.listen(8080).await?;

    Ok(())
}

LUNE 프로토콜 메시지 예시

클라이언트에서 서버로 보내는 LUNE 메시지 형태:

READ /api/users LUNE/1 client
Nonce: "abc123"
DateTime: 1640995200

{"api_key": "secret123"}

서버에서 클라이언트로 보내는 응답:

200 OK LUNE/1 server
Nonce: "abc123"
DateTime: 1640995201

{"users": [{"id": 1, "name": "Alice"}]}

다음 단계

Orbital을 사용하여 더 복잡한 애플리케이션을 구축하려면 다음 문서들을 참고하세요:

  • Application - 애플리케이션 설정 및 구성
  • Router - 라우팅 및 미들웨어 설정
  • Event - 이벤트 처리 및 핸들링
  • Types - 타입 정의 및 데이터 구조

Orbital을 사용하면 LUNE 프로토콜 기반의 서버를 빠르고 안전하게 구현할 수 있습니다.