0. ๐ ์ โRust Tonic gRPCโ์ธ๊ฐ์?
๋ง์ดํฌ๋ก์๋น์ค ๊ฐ ๋ด๋ถ ํต์ ์์ JSON/REST๋ ์ง๋ ฌํ ๋น์ฉ๊ณผ ์คํค๋ง ๋ถ์ผ์น ๋ฆฌ์คํฌ๊ฐ ํฝ๋๋ค. Tonic v0.14 (grpc/grpc-rust)๋ Tokio ๋น๋๊ธฐ ๋ฐํ์๊ณผ Tower ์๋น์ค ์ถ์ํ ์์์ ๋์ํ๋ Rust ๋ํ gRPC ํ๋ ์์ํฌ๋ก, HTTP/2 ๋ฉํฐํ๋ ์ฑยท์๋ฐฉํฅ ์คํธ๋ฆฌ๋ฐยท์ ๋ก์นดํผ์ ๊ฐ๊น์ด Protobuf ์ง๋ ฌํ๋ฅผ ํ์
์์ ํ๊ฒ ์ ๊ณตํฉ๋๋ค.
1. ํ์ ์ฌ์ ์๊ฑด & ์์คํ ์๊ตฌ์ฌ์ (Prerequisites & System Requirements)
๐ป ์์คํ ์ค์น ๋ฐ ์คํ ์๊ตฌ์ฌ์ (System Requirements)
| ํญ๋ชฉ | ์ต์ ์ฌ์ (Minimum) | ๊ถ์ฅ ์ฌ์ (Recommended) | ์ฐธ๊ณ ๋ฐ ๋น๊ณ |
|---|---|---|---|
| ์ด์์ฒด์ (OS) | Linux, macOS, Windows (MSVC / WSL2) | Ubuntu 24.04 LTS / macOS Apple Silicon | Protobuf ์ปดํ์ผ๋ฌ protoc ํ์ |
| CPU / RAM | 2 vCPU / 4 GB RAM | 4~8+ vCPU / 8 GB+ RAM | Rust ๋ฆด๋ฆฌ์ค ๋น๋ ๋ฐ ๋ณ๋ ฌ ํฌ๋ ์ดํธ ์ปดํ์ผ |
| ํด์ฒด์ธ / ํฌ๋ ์ดํธ | Rust 1.85+ (Rust 2024 Edition), protoc | tonic 0.14.6, prost 0.14, tokio 1.x | grpcurl CLI๋ก ์ฆ์ ํ
์คํธ ๊ฐ๋ฅ |
# 1. Rust ํ๋ก์ ํธ ์ด๊ธฐํ ๋ฐ ์์กด์ฑ ์ถ๊ฐ
cargo new tonic-order-svc && cd tonic-order-svc
cargo add tonic@0.14 prost@0.14 tokio@1 --features tokio/macros,tokio/rt-multi-thread
cargo add tokio-stream tower
cargo add --build tonic-build@0.14
# 2. Protobuf ์ปดํ์ผ๋ฌ(protoc) ๋ฐ gRPC ํ
์คํธ CLI(grpcurl) ์ค์น
# macOS: brew install protobuf grpcurl
# Ubuntu: sudo apt-get install -y protobuf-compiler
protoc --version
[1๊ฐ] Protobuf ์คํค๋ง & tonic-build ์ฝ๋ ์๋ ์์ฑ
proto/order.proto์ Unary RPC์ Server Streaming RPC๋ฅผ ์ ์ํ๊ณ , build.rs์์ ์ปดํ์ผ ํ์์ Rust ํธ๋ ์ดํธ์ ๊ตฌ์กฐ์ฒด๋ฅผ ์๋ ์์ฑํฉ๋๋ค.
// proto/order.proto
syntax = "proto3";
package order.v1;
service OrderService {
rpc CreateOrder (CreateOrderRequest) returns (OrderResponse);
rpc WatchOrderStatus (WatchOrderRequest) returns (stream OrderStatusEvent);
}
message CreateOrderRequest {
string user_id = 1;
string item_sku = 2;
uint32 quantity = 3;
}
message OrderResponse {
string order_id = 1;
string status = 2;
}
message WatchOrderRequest {
string order_id = 1;
}
message OrderStatusEvent {
string order_id = 1;
string stage = 2;
int64 timestamp_ms = 3;
}
// build.rs
fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_build::configure()
.build_server(true)
.build_client(true)
.compile_protos(&["proto/order.proto"], &["proto"])?;
Ok(())
}
[2๊ฐ] Unary RPC & ์ค์๊ฐ Server Streaming ๊ตฌํ
Tokio mpsc ์ฑ๋๊ณผ ReceiverStream์ ๊ฒฐํฉํ๋ฉด ๋ฐฑํ๋ ์
(Backpressure)๊ฐ ์์ ํ๊ฒ ์ ์ด๋๋ ์ค์๊ฐ ์คํธ๋ฆฌ๋ฐ ์๋ํฌ์ธํธ๋ฅผ ๊ตฌํํ ์ ์์ต๋๋ค.
// src/main.rs
use std::pin::Pin;
use tokio::sync::mpsc;
use tokio_stream::{wrappers::ReceiverStream, Stream};
use tonic::{transport::Server, Request, Response, Status};
pub mod order_v1 {
tonic::include_proto!("order.v1");
}
use order_v1::order_service_server::{OrderService, OrderServiceServer};
use order_v1::{CreateOrderRequest, OrderResponse, OrderStatusEvent, WatchOrderRequest};
#[derive(Default)]
pub struct MyOrderService;
#[tonic::async_trait]
impl OrderService for MyOrderService {
async fn create_order(
&self,
request: Request<CreateOrderRequest>,
) -> Result<Response<OrderResponse>, Status> {
let req = request.into_inner();
if req.quantity == 0 {
return Err(Status::invalid_argument("quantity must be greater than 0"));
}
Ok(Response::new(OrderResponse {
order_id: format!("ord-{}", req.user_id),
status: "CREATED".to_string(),
}))
}
type WatchOrderStatusStream = Pin<Box<dyn Stream<Item = Result<OrderStatusEvent, Status>> + Send>>;
async fn watch_order_status(
&self,
request: Request<WatchOrderRequest>,
) -> Result<Response<Self::WatchOrderStatusStream>, Status> {
let order_id = request.into_inner().order_id;
let (tx, rx) = mpsc::channel(16);
tokio::spawn(async move {
for stage in ["PAID", "PACKING", "SHIPPED"] {
let evt = OrderStatusEvent {
order_id: order_id.clone(),
stage: stage.to_string(),
timestamp_ms: 1795300000000,
};
if tx.send(Ok(evt)).await.is_err() {
break; // ํด๋ผ์ด์ธํธ ์ฐ๊ฒฐ ์ข
๋ฃ ์ ํ์คํฌ ์ ๋ฆฌ
}
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
}
});
Ok(Response::new(Box::pin(ReceiverStream::new(rx))))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = "0.0.0.0:50051".parse()?;
println!("Tonic gRPC Server listening on {}", addr);
Server::builder()
.add_service(OrderServiceServer::new(MyOrderService::default()))
.serve(addr)
.await?;
Ok(())
}
[3๊ฐ] Tower ์ธํฐ์ ํฐ ์ธ์ฆ & ํ์์์/๋์์ฑ ์ ํ
Tonic์ tower::Service ๊ธฐ๋ฐ์ด๋ฏ๋ก ๋ณ๋์ ์ด๋ํฐ ์์ด ์์ฒญ ํ์์์, ๋์์ฑ ์ ํ(Concurrency Limit), JWT/API-Key ์ธํฐ์
ํฐ๋ฅผ ๋ ์ด์ด๋ก ์กฐํฉํ ์ ์์ต๋๋ค.
use std::time::Duration;
use tonic::{Request, Status};
fn auth_interceptor(req: Request<()>) -> Result<Request<()>, Status> {
match req.metadata().get("authorization") {
Some(token) if token == "Bearer prod-secret" => Ok(req),
_ => Err(Status::unauthenticated("์ ํจํ Bearer ํ ํฐ์ด ํ์ํฉ๋๋ค")),
}
}
// Server::builder() ์ฒด์ธ์ Tower ๋ ์ด์ด ๋ฐ ์ธํฐ์
ํฐ ์ ์ฉ
// Server::builder()
// .timeout(Duration::from_secs(5))
// .concurrency_limit_per_connection(256)
// .add_service(OrderServiceServer::with_interceptor(MyOrderService::default(), auth_interceptor))
[4๊ฐ] OpenTelemetry Metadata Span ์ ํ & Graceful Shutdown
๋ถ์ฐ ๋ง์ดํฌ๋ก์๋น์ค์์๋ gRPC MetadataMap์ ํตํด traceparent ํค๋๋ฅผ ์ ํํ๊ณ , Kubernetes SIGTERM ์์ ์ ์งํ ์ค์ธ ์คํธ๋ฆผ์ ์์ ํ๊ฒ ๋ง๋ฌด๋ฆฌํฉ๋๋ค.
// Kubernetes SIGTERM / Ctrl+C ์๊ทธ๋ ๊ธฐ๋ฐ Graceful Shutdown
async fn shutdown_signal() {
let _ = tokio::signal::ctrl_c().await;
println!("SIGTERM/Ctrl+C ์์ : ์ ๊ท gRPC ์ฐ๊ฒฐ ์๋ฝ์ ์ค๋จํ๊ณ ์ ์ ์ข
๋ฃํฉ๋๋ค.");
}
// Server::builder()
// .add_service(...)
// .serve_with_shutdown(addr, shutdown_signal())
// .await?;
# grpcurl์ ์ด์ฉํ ๋ก์ปฌ ๋์ ๊ฒ์ฆ (Reflection ๋๋ -proto ์ง์ )
grpcurl -plaintext \
-import-path ./proto -proto order.proto \
-H "authorization: Bearer prod-secret" \
-d '{"user_id":"u101","item_sku":"SKU-99","quantity":2}' \
127.0.0.1:50051 order.v1.OrderService/CreateOrder
์๊ฒฌ ๋ฐ ์ง๋ฌธ
0์์ง ๋ฑ๋ก๋ ์๊ฒฌ์ด ์์ต๋๋ค. ์ฒซ ๋ฒ์งธ ๋๊ธ์ ๋จ๊ฒจ๋ณด์ธ์!
๋๊ธ ์์
๋๊ธ ์ญ์