folly::Future thenValue·thenError·thenTry — continuation 체인 분석
한 줄 요약: continuation은 값을 다룰지, 예외를 다룰지, 둘 다 다룰지 의도를 코드에 적는다. 세 API의 이름이 그 의도를 강제한다.
#동기 — 왜 .then 하나로 안 되는가
초기 Folly는 .then(callback) 하나만 있었다. callback의 시그니처에 따라 정상값 처리, Try 처리, 다른 Future 반환을 모두 분기했다.
// 옛 API — 시그니처로 분기f.then([](int x) { return x + 1; }); // valuef.then([](Try<int> t) { return *t + 1; }); // tryf.then([](int x) { return makeFuture(x); }); // future of future이 방식은 두 가지 문제가 있었다.
- callback signature 변경이 silent.
int를auto로 바꾸면 의도가 흐려진다. - 에러를 다룰지 안 다룰지가 보이지 않음.
t.hasException()을 체크하지 않으면 silent하게 전파된다.
Folly는 .then을 deprecated하고 세 변형으로 분리했다.
#세 변형의 역할
// 정상값만 — 예외는 그대로 전파f.thenValue([](int x) -> R { return f(x); });
// 예외만 — 정상값은 그대로 전파f.thenError(folly::tag_t<MyError>{}, [](MyError const& e) -> int { return -1;});
// 둘 다 — Try<T>로 통합f.thenTry([](Try<int> t) -> R { if (t.hasException()) return R::error(); return process(*t);});| API | 입력 | 예외 처리 |
|---|---|---|
thenValue(fn) | T | 그대로 전파 (catch 안 함) |
thenError<E>(fn) | E const& | 일치하는 예외만 catch |
thenTry(fn) | Try<T> | 직접 처리 |
#체인의 그림
세 변형은 결국 같은 chain 모델 위에 다른 분기 규칙을 얹은 것이다.
값 흐름이 정상 경로를 타다 예외가 나면 thenError 핸들러로 분기. 중간 thenValue들은 자동으로 건너뛴다. callback hell 없이 평탄한 파이프라인을 유지하는 핵심이다.
#thenValue — 가장 흔한 변형
folly::SemiFuture<int> compute();
auto sf = compute() .deferValue([](int x) { return x + 1; }) // int → int .deferValue([](int x) { return folly::makeSemiFuture(x * 2); // int → SemiFuture<int> }) .deferValue([](int x) { return std::to_string(x); }); // int → stringreturn type이 SemiFuture<U>면 flatten된다. SemiFuture<SemiFuture<U>>가 되지 않는다.
// folly/futures/Future.h (개념)template <class F>auto Future<T>::thenValue(F&& fn) && { using R = std::invoke_result_t<F, T>; if constexpr (isSemiFuture<R>) { // flatten return this->then([fn = std::move(fn)](Try<T> t) -> SemiFuture<inner_t<R>> { return fn(*std::move(t)); }); } else { // wrap return ...; }}#thenError — 타입별 예외 처리
auto sf = fetch(url) .deferError(folly::tag_t<TimeoutError>{}, [](auto const&) { return defaultResponse(); }) .deferError(folly::tag_t<NetworkError>{}, [](auto const& e) { LOG(ERROR) << "network: " << e.what(); throw; // 재던지기 });folly::tag_t<E>{}로 catch할 예외 타입을 명시한다. 일치하지 않는 예외는 그대로 전파된다. 마지막 catch-all로 std::exception을 두면 안전망이 된다.
.deferError(folly::tag_t<std::exception>{}, [](auto const& e) { LOG(ERROR) << "fallback: " << e.what(); return Response::error();});#thenTry — 통합 처리
Try<T>를 직접 받으므로 hasValue()/hasException()을 분기한다.
fetch(url).deferValue(parse).thenTry([](folly::Try<Parsed> t) { if (t.hasException()) { metrics->errors.inc(); return Result::fail(t.exception()); } metrics->success.inc(); return Result::ok(*std::move(t));});.thenTry는 모든 결과를 항상 처리해야 할 때 적합하다. logging, metrics 수집이 전형적이다.
#.then의 deprecated 이유
// 옛 API — 사용 금지f.then([](int x) { return x + 1; });f.then([](Try<int> t) { ... });이름이 의도를 드러내지 못한다. 새 코드는 .thenValue, .thenError, .thenTry 중 하나를 명시적으로 골라야 한다. 코드 리뷰에서 .then 사용은 항상 지적한다.
#내부 — callback 등록과 실행
// folly/futures/detail/Core.h (요약)template <class T>void Core::setCallback(Callback callback, Executor::KeepAlive<> e) { // executor 등록 setExecutor(std::move(e));
// FSM 전이 State expected = State::Start; if (state_.compare_exchange_strong(expected, State::OnlyCallback)) { callback_ = std::move(callback); return; } // 이미 result 도착 expected = State::OnlyResult; if (state_.compare_exchange_strong(expected, State::Done)) { executor_->add([cb = std::move(callback), r = std::move(result_)]() mutable { cb(std::move(r)); }); return; }}result와 callback이 어느 쪽이 먼저 도착하든 atomic FSM이 안전하게 처리한다. callback은 executor_->add(...)로 schedule된다.
#std::future / std::expected와의 비교
// std::future — continuation 없음std::future<int> f = std::async(...);int v = f.get();int r = process(v); // 동기 처리만 가능
// std::expected (C++23) — 동기 monadicstd::expected<int, Err> e = compute();auto r = e.and_then([](int x) { return std::expected<int, Err>{x + 1}; }) .or_else([](Err e) { return std::expected<int, Err>{0}; });
// folly::Future — async monadicfolly::Future<int> f = ...;auto r = std::move(f) .thenValue([](int x) { return x + 1; }) // ≈ and_then .thenError(folly::tag_t<Err>{}, [](Err) { return 0; }); // ≈ or_elsestd::expected의 .and_then/.or_else와 Folly의 .thenValue/.thenError는 의도가 같다. 동기 vs 비동기가 차이일 뿐이다.
#코드 리뷰 포인트
.then사용? 즉시.thenValue또는.thenTry로 바꾼다..thenValue체인이 예외 처리를 빠뜨렸는가? 마지막에.thenError<std::exception>을 두거나 caller가 try/catch를 안다.- return type이
SemiFuture<SemiFuture<T>>처럼 nested되는가? flatten이 자동이지만 명시적.unwrap()이 필요한 경우가 있다. thenError의 catch 타입이 너무 넓은가?std::exception을 위쪽에 두면 아래의 더 specific한 catch가 닿지 않는다.
#자주 보는 안티패턴
// 1. .then 사용f.then([](int x) { return x + 1; }); // deprecated
// 2. thenError 순서 잘못f.thenError(folly::tag_t<std::exception>{}, [](auto&) { return 0; }) .thenError(folly::tag_t<MyError>{}, [](auto&) { return 1; });// MyError가 std::exception을 상속하면 위에서 catch됨 — 두 번째 핸들러 도달 불가
// 3. value continuation 안에서 throw — 명시적이 더 낫다f.thenValue([](int x) { if (x < 0) throw std::runtime_error("neg"); return x;});// 차라리:f.thenTry([](Try<int> t) -> Try<int> { if (*t < 0) return Try<int>(make_exception_wrapper<std::runtime_error>("neg")); return t;});
// 4. thenError에서 다른 타입 반환f.thenError(folly::tag_t<MyError>{}, [](auto&) { return "fallback"; // 원래 Future<int>인데 string 반환 — 컴파일 에러});#정리
- continuation은 의도에 따라
.thenValue/.thenError/.thenTry세 변형을 명시적으로 고른다. .thenValue는 정상값만,.thenError<E>는 타입별 예외,.thenTry는 통합 처리다.- 옛
.then은 deprecated. 코드 리뷰에서 항상 지적한다. - callback의 return이
SemiFuture<U>면 자동 flatten된다. thenError체인은 더 specific한 타입을 위쪽에 둔다.- 개념적으로
std::expected의.and_then/.or_else와 같은 monadic 패턴이다.
#다음 편
Part 2-05: collect / collectAll / collectAny에서 여러 Future를 모으는 fan-in 패턴을 본다.
#관련 항목
Folly Code Review · 10 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 사용의 실전
관련 글
folly::CancellationToken — 코루틴·Future 취소 전파
CancellationSource/Token의 전파 모델 — coroutine·Future·callback 트리에서 협력적 취소.
같은 시리즈에서 이어 읽기
folly::Try — Future 결과 wrapper
Try<T>의 세 상태 (value/exception/empty), Future 내부에서의 역할, exception_wrapper와의 관계.
같은 시리즈에서 이어 읽기
folly::Future retry·window·via — 제어 흐름 조합자
Future 조립의 제어 흐름 — 재시도, 동시성 윈도, executor 전환.
같은 시리즈에서 이어 읽기
이 글을 참조하는 글 (6)
- folly::Try vs Expected 선택 기준 — Folly Code Review
- folly::Try — Future 결과 wrapper — Folly Code Review
- folly::Function vs std::function — Folly Code Review
- folly::ManualExecutor — 결정적 테스트를 위한 수동 진행 — Folly Code Review
- folly::collect·collectAll·collectAny — fan-in 패턴 분석 — Folly Code Review
- folly::SemiFuture vs Future — executor binding의 명시화 — Folly Code Review