folly::Uri — URL 파서
한 줄 요약:
folly::Uri는 RFC 3986 기반 URL 파서다. C++ 표준에는 URL 파서가 없어 fbcode·외부 모두 같은 빈자리를 채우는 도구가 필요했다.
#동기
C++ 표준 라이브러리에는 URL 파서가 없다. WHATWG URL Spec 구현은 옵션이지만 모든 라이브러리가 fbcode 패턴(scheme://user:pass@host:port/path?query#fragment)을 정확히 다뤄야 한다.
매번 strtok나 regex로 짜는 건 위험하다. percent-encoding, IPv6 bracket, IDN, default port 같은 함정이 많다. Boost.URL도 비교적 최근(2022). Folly는 일찍 자체 파서를 만들어 fbcode 내부 RPC client·log 전체가 사용한다.
folly::Uri u("https://user:pw@api.example.com:8080/v1/items?id=42#section");
u.scheme(); // "https"u.username(); // "user"u.password(); // "pw"u.host(); // "api.example.com"u.port(); // 8080u.path(); // "/v1/items"u.query(); // "id=42"u.fragment(); // "section"#API
#include <folly/Uri.h>
folly::Uri u("https://example.com/path?a=1&b=2");
u.scheme(); // "https"u.host(); // "example.com"u.path(); // "/path"u.query(); // "a=1&b=2"
// query parameter 분해auto params = u.getQueryParams();// std::vector<std::pair<std::string, std::string>>// { {"a", "1"}, {"b", "2"} }
// authority 재조립u.authority(); // "example.com"
// 전체 재조립u.toString(); // "https://example.com/path?a=1&b=2"URI parsing은 생성자에서 일어난다. 잘못된 URI면 std::invalid_argument throw.
try { folly::Uri u("not a valid url");} catch (const std::invalid_argument& e) { LOG(ERROR) << e.what();}#Query string 처리
folly::Uri u("https://api/search?q=hello+world&limit=10&page=1");
auto params = u.getQueryParams();for (const auto& [k, v] : params) { std::cout << k << " = " << v << "\n";}// q = hello world ← + 가 space로 변환됨// limit = 10// page = 1+/%20 → space, %XX percent-encoding 처리가 표준대로. 잘못된 encoding은 ignore 또는 verbatim 보존 (구현 정책).
#직접 query 조작
folly::Uri u("https://api/search");u.setQuery("q=foo&limit=20");auto s = u.toString(); // "https://api/search?q=foo&limit=20"setter도 있다. 단 setter 호출 후 내부 파싱이 다시 일어나야 일관성이 유지된다.
#내부 구현 — 정규식
// folly/Uri.cpp 약식const boost::regex uriRegex( "([a-zA-Z][a-zA-Z0-9+.-]*):" // scheme "(?://" // :// "(?:([^@/?#]*)@)?" // userinfo "([^:/?#]+)" // host "(?::(\\d+))?" // port ")?" "([^?#]*)" // path "(?:\\?([^#]*))?" // query "(?:#(.*))?" // fragment);
Uri::Uri(folly::StringPiece s) { boost::cmatch m; if (!boost::regex_match(s.begin(), s.end(), m, uriRegex)) { throw std::invalid_argument("invalid URI"); } scheme_ = m[1]; username_ = ...; // userinfo split host_ = m[3]; port_ = m[4].matched ? std::stoi(m[4]) : 0; path_ = m[5]; query_ = m[6]; fragment_ = m[7];}내부적으로 boost::regex(또는 std::regex)로 한 번에 파싱. RFC 3986의 grammar가 거의 그대로 regex가 된다. percent-decode는 별도 단계.
성능이 critical하면 hand-rolled parser가 낫지만 fbcode use case는 RPC URL 한 번 파싱이라 regex로 충분.
#RFC 3986과의 충실도
URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]hier-part = "//" authority path-abempty / path-absolute / path-rootless / path-emptyauthority = [ userinfo "@" ] host [ ":" port ]folly는 위 grammar 대부분을 다룬다. 단 다음은 완벽하진 않다.
- IPv6 host with bracket —
[::1]:8080형태 — 지원하나 일부 corner case가 다를 수 있음. - IDN (international domain) — punycode 변환은 안 함. raw 문자열로 보관.
- Percent-decoding — query에서는 한다. path는 raw 보관(decode는 호출자 책임).
- Relative URI 해석 — base URI에 대한 resolution은 별도 API 필요.
WHATWG URL Spec(브라우저용)과는 다른 RFC 3986 grammar 기반. 브라우저용 URL을 완벽히 처리해야 한다면 별도 라이브러리(Boost.URL, ada-url 등).
#std와의 비교
| 항목 | 표준 | folly::Uri | Boost.URL | ada-url |
|---|---|---|---|---|
| C++ 표준 | 없음 | folly 내부 | Boost 1.81+ | 외부 |
| RFC 3986 | N/A | 거의 충실 | 충실 | 충실 |
| WHATWG URL | N/A | 부분 | 부분 | 완전 |
| IDN punycode | N/A | 안 함 | 안 함 | 함 |
| 성능 | N/A | regex 기반 (보통) | hand-rolled (빠름) | SIMD (가장 빠름) |
| 의존성 | N/A | folly | boost | 없음 |
fbcode 내부 RPC는 percent-encoded ASCII 위주라 folly::Uri로 충분. 브라우저 fidelity가 필요하면 ada-url.
#코드 리뷰 포인트
- 입력 URL의 신뢰성 — 사용자 입력이면 catch
std::invalid_argument필수. port()가 0을 반환하면 URI에 port가 없다는 뜻 (default port resolution은 호출자).- query parameter가 순서를 유지해야 하면
getQueryParams()(vector<pair>) 사용. unordered map 변환은 정보 손실. - path가 percent-encoded인 채로 반환됨 — 사용 전 decode 필요할 수 있다.
- HTTPS/HTTP 같은 scheme 비교는 case-insensitive (RFC). 직접
==비교 전 lower-case 정규화.
#자주 보는 안티패턴
// 1. regex로 직접 URL 파싱std::regex r(R"(^(https?)://([^/]+))");// → 표준 도구로 percent-encoding/IPv6 처리 누락 가능
// 2. port 비교 없이 host만 비교if (u.host() == "api.example.com") { ... }// → 같은 host의 다른 port가 다른 서비스일 수 있음
// 3. percent-encoded path 직접 file system에 사용auto path = u.path();std::ifstream f(path); // %20 같은 인코딩이 그대로 들어감
// 4. setter 후 내부 일관성 무시folly::Uri u("https://a/p");u.setHost("[::1"); // 잘못된 IPv6 — setter가 throw하지 않을 수 있음#실전 예 — RPC client URL 처리
folly::Uri ParseEndpoint(const std::string& raw) { folly::Uri u(raw); // throw if invalid
if (u.scheme() != "http" && u.scheme() != "https") { throw std::invalid_argument("unsupported scheme: " + u.scheme().str()); }
if (u.host().empty()) { throw std::invalid_argument("missing host"); }
// default port if (u.port() == 0) { u_port = (u.scheme() == "https") ? 443 : 80; }
return u;}scheme 검증, host 존재 확인, default port 채우기 — RPC client에서 매번 하는 작업.
#정리
- C++ 표준에 URL 파서가 없어 folly가 그 자리를 채운다.
- RFC 3986 grammar 기반, regex로 한 번 파싱.
- scheme/userinfo/host/port/path/query/fragment 모두 추출.
- query parameter는 vector
로 순서 보존. - 브라우저 fidelity가 필요하면 ada-url, RPC 정도면
folly::Uri로 충분.
#다음 편
Part 17-03: folly::hash::Fingerprint에서 분산 hash 함수를 본다.
#관련 항목
Folly Code Review · 74 of 89
- 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
- 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
- 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
- 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
- 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
- 6 Folly production validation 문화 — peta-scale에서 단련된 코드
- 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
- 8 folly::Promise·makeFuture — Future를 만드는 두 길
- 9 folly::SemiFuture vs Future — executor binding의 명시화
- 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
- 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
- 12 folly::Future retry·window·via — 제어 흐름 조합자
- 13 folly::fibers 분석 — M:N stackful coroutine
- 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
- 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
- 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
- 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
- 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
- 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
- 20 folly::IOBufQueue — chain의 push/pull 추상화
- 21 folly::io::Cursor·RWCursor — chain 위의 stream
- 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
- 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
- 24 folly::FBString 분석 — SSO + COW 구현
- 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
- 26 folly::StringPiece — string_view 호환 분석
- 27 folly Join·Split utilities — 문자열 분해와 결합
- 28 folly::to·tryTo — text↔num 변환 분석
- 29 folly Conv Customization — 사용자 타입 지원
- 30 folly Conv 성능 비교 — sprintf·stringstream 대비
- 31 folly::F14ValueMap vs std::unordered_map
- 32 folly::F14NodeMap — stable pointer가 필요할 때
- 33 folly::F14VectorMap — cache-friendly iteration
- 34 folly::F14FastMap — auto-select 동작
- 35 folly F14 internals — SIMD probing 메커니즘
- 36 folly::small_vector — inline storage 분석
- 37 folly::FixedString — compile-time string
- 38 folly::AtomicHashMap — lock-free read 분석
- 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
- 40 folly::EvictingCacheMap — LRU 구현 분석
- 41 folly::Synchronized — lock wrapper 패턴
- 42 folly::SharedMutex 분석
- 43 folly::Baton — one-shot wait 동기화
- 44 folly::RWSpinLock 분석
- 45 folly::PicoSpinLock — 1-byte spinlock
- 46 folly::ProducerConsumerQueue — SPSC 큐 분석
- 47 folly::MPMCQueue — multi-producer multi-consumer
- 48 folly::UnboundedQueue — 동적 크기 lock-free
- 49 folly::fibers::Channel — Go-like channel
- 50 folly::dynamic — JSON-like dynamic type 분석
- 51 folly JSON conversion — toJson·parseJson
- 52 folly dynamic ↔ struct — manual marshaling
- 53 folly dynamic Visitor pattern — type별 분기
- 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
- 55 folly::SingletonVault 분석 — 등록·소멸·의존성
- 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
- 57 folly::ExceptionWrapper — type-erased exception holder
- 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
- 59 folly::Optional vs std::optional
- 60 folly::Function vs std::function
- 61 folly::Lazy — 지연 초기화 wrapper
- 62 folly Meta 스타일 code review 패턴
- 63 folly anti-patterns — 잘못 쓰면 std보다 느림
- 64 folly vs std 선택 기준 분석
- 65 folly::coro 개요 — production C++20 코루틴 어댑터
- 66 folly::coro::Task — lazy single-shot 코루틴
- 67 folly::coro::AsyncGenerator — 비동기 스트림
- 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
- 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
- 70 folly::Expected — 결과 또는 오류
- 71 folly::Try — Future 결과 wrapper
- 72 folly::Try vs Expected 선택 기준
- 73 folly::Range — 일반 iterator pair
- 74 folly::Uri — URL 파서
- 75 folly Fingerprint64·128 — 분산 hash
- 76 folly SpookyHashV2 — fast non-crypto hash
- 77 folly::Init — main() 부트스트랩
- 78 folly::Indestructible — global lifetime 패턴
- 79 folly::MicroLock — 1-byte 락
- 80 folly::MicroSpinLock — 가장 좁은 spin lock
- 81 folly::format — legacy formatter 분석
- 82 folly::demangle — typeid 디망글링
- 83 folly::DynamicConverter — dynamic ↔ struct
- 84 folly::RecordIO — append-only 로그 파일 포맷
- 85 folly::io::Compression — zstd·lz4·snappy wrapper
- 86 folly::AsyncIO — io_uring·Linux AIO
- 87 folly::CancellationToken — 코루틴·Future 취소 전파
- 88 folly::observer — hot config의 atomic refresh
- 89 fbcode 패턴 모음 — folly 사용의 실전
관련 글
fbcode 패턴 모음 — folly 사용의 실전
Meta fbcode 코드 리뷰에서 반복적으로 등장하는 folly 사용 패턴 — overview + 시리즈 마무리.
같은 시리즈에서 이어 읽기
folly::observer — hot config의 atomic refresh
folly::observer — read mostly 값의 atomic refresh, hot config·feature flag·LB weight 같은 패턴의 표준.
같은 시리즈에서 이어 읽기
folly::CancellationToken — 코루틴·Future 취소 전파
CancellationSource/Token의 전파 모델 — coroutine·Future·callback 트리에서 협력적 취소.
같은 시리즈에서 이어 읽기