본문으로 건너뛰기
Folly Code Review · 19/89

folly::IOBufQueue — chain의 push/pull 추상화

· Hawk · 3분 읽기

한 줄 요약: IOBufQueue는 IOBuf chain의 생산자/소비자 API다. append/prepend/split-at-cursor를 효율적으로 제공해 streaming codec의 backbone이 된다.

#동기 — IOBuf만으로는 불편하다

IOBuf는 자료구조 자체다. chain의 append, prepend, N바이트 split은 사용자가 직접 다뤄야 한다. 그 boilerplate가 너무 많다.

// IOBuf 직접 — append
if (last->tailroom() >= newData.size()) {
std::memcpy(last->writableTail(), newData.data(), newData.size());
last->append(newData.size());
} else {
auto next = folly::IOBuf::create(kPageSize);
std::memcpy(next->writableTail(), newData.data(), newData.size());
next->append(newData.size());
head->prependChain(std::move(next));
}

이 패턴이 모든 streaming codec에서 반복된다. IOBufQueue가 이를 추상화한다.

#기본 사용

IOBufQueue append/trim

#include <folly/io/IOBufQueue.h>
folly::IOBufQueue q{folly::IOBufQueue::cacheChainLength()};
// 1) append
q.append("hello ", 6);
q.append("world", 5);
// 2) IOBuf 자체 append
auto buf = folly::IOBuf::create(1024);
buf->append(100);
q.append(std::move(buf));
// 3) preallocate — 큰 buffer 한 번 할당
auto [data, capacity] = q.preallocate(1024, 4096); // 최소 1024, 최대 4096
size_t written = recv(fd, data, capacity, 0);
q.postallocate(written);
// 4) split — 앞 N바이트 빼오기
auto front = q.split(128); // 정확히 128 bytes, 부족하면 throw
auto front2 = q.splitAtMost(128); // 있는 만큼
// 5) move out
auto allData = q.move(); // queue 비우고 전체 chain 반환

#핵심 메서드

// folly/io/IOBufQueue.h (요약)
class IOBufQueue {
public:
static Options cacheChainLength() { return ...; }
// append
void append(StringPiece);
void append(unique_ptr<IOBuf>&& buf);
void append(IOBufQueue& other);
// preallocate/postallocate — receive buffer 패턴
std::pair<void*, size_t> preallocate(
size_t minSize, size_t maxSize, size_t newAllocSize = 0);
void postallocate(size_t n);
// split
unique_ptr<IOBuf> split(size_t n); // 정확히 n
unique_ptr<IOBuf> splitAtMost(size_t n); // 있는 만큼
// trim
void trimStart(size_t);
void trimEnd(size_t);
// accessors
size_t chainLength() const; // O(1) if cacheChainLength()
bool empty() const;
// ownership transfer
unique_ptr<IOBuf> move();
const IOBuf* front() const;
};

cacheChainLength() 옵션은 총 길이를 캐싱해 O(1)에 알 수 있게 한다. 매번 chain을 순회하지 않는다.

#preallocate/postallocate — recv 패턴

folly::IOBufQueue q{folly::IOBufQueue::cacheChainLength()};
while (running) {
auto [data, cap] = q.preallocate(4096, 65536);
ssize_t n = ::recv(fd, data, cap, 0);
if (n <= 0) break;
q.postallocate(n);
// q에서 framing parser로 넘기기
while (auto frame = parseFrame(q)) {
handle(std::move(frame));
}
}

preallocate큰 빈 buffer를 한 번에 확보한다. recv 한 번에 64KB까지 받아도 단일 IOBuf로 처리된다. postallocate(n)이 실제 받은 만큼 chain에 commit한다.

이 패턴이 모든 zero-copy network read의 표준이다.

#split — framing layer의 핵심

// 5-byte length-prefixed frame parser
std::unique_ptr<folly::IOBuf> parseFrame(folly::IOBufQueue& q) {
if (q.chainLength() < 5) return nullptr; // 헤더 미달
// 헤더 peek (split하지 않고 읽기)
folly::io::Cursor cur(q.front());
uint32_t magic = cur.readBE<uint32_t>();
uint8_t type = cur.read<uint8_t>();
if (q.chainLength() < 5 + bodySize(type)) return nullptr;
q.trimStart(5); // 헤더 버리기
return q.split(bodySize(type)); // body만 추출
}

framing layer는 부분 도착을 다룬다. recv 한 번에 frame 하나가 안 올 수도 있다. IOBufQueue는 남은 bytes를 chain에 유지하므로 다음 recv에 자연스레 이어 붙는다.

#IOBuf 직접 vs IOBufQueue

// IOBuf 직접 — boilerplate 많음
unique_ptr<IOBuf> head;
IOBuf* tail = nullptr;
size_t totalLen = 0;
// append:
// - tailroom 체크
// - 부족하면 새 buffer 할당
// - prependChain
// - totalLen += n
// IOBufQueue — 한 줄
q.append(data, n);

queue가 head/tail/length를 내부적으로 관리한다. tailroom 활용, buffer 분할/병합도 모두 자동이다.

#std::deque<std::vector<uint8_t>>와 비교

비슷한 byte queue를 표준으로 만들면 std::deque<std::vector<uint8_t>> 또는 단일 std::vector 다.

작업std::dequefolly::IOBufQueue
append small (n B)새 vector 또는 마지막에 pushtailroom에 memcpy
recv into별도 임시 buffer + 복사preallocate로 직접
split front복사O(1) IOBuf 분리
writev별도 iovec 만들기chain 그대로 iovec

queue 자체의 메모리 효율도 IOBufQueue가 우세하다. 빈 vector의 overhead가 없다.

#코드 리뷰 포인트

  • cacheChainLength() 사용? O(1) chainLength가 필요한 곳이면 켠다.
  • preallocate minSize가 너무 작지 않은가? 매 recv마다 새 buffer면 효율 떨어짐. 4KB 정도가 보통.
  • split/splitAtMost 구분? 정확히 필요하면 split, 부분도 OK면 splitAtMost.
  • 이 queue를 cross-thread share하는가? thread-safe 아님. 각 thread에 자기 queue를 둔다.

#자주 보는 안티패턴

// 1. recv 후 복사
char tmp[4096];
ssize_t n = recv(fd, tmp, sizeof(tmp), 0);
q.append(tmp, n); // tmp → IOBuf로 복사 한 번 더
// 옳음:
auto [data, cap] = q.preallocate(4096, 65536);
ssize_t n = recv(fd, data, cap, 0);
q.postallocate(n);
// 2. chainLength를 매번 호출 (cache 없이)
folly::IOBufQueue q; // cacheChainLength 옵션 없음
while (q.chainLength() < N) ... // 매번 O(chain length)
// 3. split 후 queue를 재사용 안 하고 새로 만듦
auto frame = q.split(n);
folly::IOBufQueue q2; // 새로 만들 이유 없음 — q는 자동으로 줄어듦
// 4. 같은 queue를 두 thread에서 동시 append
std::thread t1([&] { q.append(...); });
std::thread t2([&] { q.append(...); }); // race

#정리

  • IOBufQueue는 IOBuf chain의 producer/consumer 추상화다.
  • preallocate/postallocate는 zero-copy recv 패턴의 표준이다.
  • split/splitAtMost는 framing layer의 핵심 도구다.
  • cacheChainLength()로 O(1) chainLength를 켠다.
  • thread-safe 아니다. 각 thread에 자기 queue를 둔다.
  • streaming codec, RPC framing, protocol layer의 backbone이다.

#다음 편

Part 4-03: Cursor에서 chain 위의 stream-like read/write를 본다.

#관련 항목

Folly Code Review · 20 of 89

  1. 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
  2. 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
  3. 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
  4. 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
  5. 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
  6. 6 Folly production validation 문화 — peta-scale에서 단련된 코드
  7. 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
  8. 8 folly::Promise·makeFuture — Future를 만드는 두 길
  9. 9 folly::SemiFuture vs Future — executor binding의 명시화
  10. 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
  11. 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
  12. 12 folly::Future retry·window·via — 제어 흐름 조합자
  13. 13 folly::fibers 분석 — M:N stackful coroutine
  14. 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
  15. 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
  16. 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
  17. 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
  18. 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
  19. 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
  20. 20 folly::IOBufQueue — chain의 push/pull 추상화
  21. 21 folly::io::Cursor·RWCursor — chain 위의 stream
  22. 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
  23. 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
  24. 24 folly::FBString 분석 — SSO + COW 구현
  25. 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
  26. 26 folly::StringPiece — string_view 호환 분석
  27. 27 folly Join·Split utilities — 문자열 분해와 결합
  28. 28 folly::to·tryTo — text↔num 변환 분석
  29. 29 folly Conv Customization — 사용자 타입 지원
  30. 30 folly Conv 성능 비교 — sprintf·stringstream 대비
  31. 31 folly::F14ValueMap vs std::unordered_map
  32. 32 folly::F14NodeMap — stable pointer가 필요할 때
  33. 33 folly::F14VectorMap — cache-friendly iteration
  34. 34 folly::F14FastMap — auto-select 동작
  35. 35 folly F14 internals — SIMD probing 메커니즘
  36. 36 folly::small_vector — inline storage 분석
  37. 37 folly::FixedString — compile-time string
  38. 38 folly::AtomicHashMap — lock-free read 분석
  39. 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
  40. 40 folly::EvictingCacheMap — LRU 구현 분석
  41. 41 folly::Synchronized — lock wrapper 패턴
  42. 42 folly::SharedMutex 분석
  43. 43 folly::Baton — one-shot wait 동기화
  44. 44 folly::RWSpinLock 분석
  45. 45 folly::PicoSpinLock — 1-byte spinlock
  46. 46 folly::ProducerConsumerQueue — SPSC 큐 분석
  47. 47 folly::MPMCQueue — multi-producer multi-consumer
  48. 48 folly::UnboundedQueue — 동적 크기 lock-free
  49. 49 folly::fibers::Channel — Go-like channel
  50. 50 folly::dynamic — JSON-like dynamic type 분석
  51. 51 folly JSON conversion — toJson·parseJson
  52. 52 folly dynamic ↔ struct — manual marshaling
  53. 53 folly dynamic Visitor pattern — type별 분기
  54. 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
  55. 55 folly::SingletonVault 분석 — 등록·소멸·의존성
  56. 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
  57. 57 folly::ExceptionWrapper — type-erased exception holder
  58. 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
  59. 59 folly::Optional vs std::optional
  60. 60 folly::Function vs std::function
  61. 61 folly::Lazy — 지연 초기화 wrapper
  62. 62 folly Meta 스타일 code review 패턴
  63. 63 folly anti-patterns — 잘못 쓰면 std보다 느림
  64. 64 folly vs std 선택 기준 분석
  65. 65 folly::coro 개요 — production C++20 코루틴 어댑터
  66. 66 folly::coro::Task — lazy single-shot 코루틴
  67. 67 folly::coro::AsyncGenerator — 비동기 스트림
  68. 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
  69. 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
  70. 70 folly::Expected — 결과 또는 오류
  71. 71 folly::Try — Future 결과 wrapper
  72. 72 folly::Try vs Expected 선택 기준
  73. 73 folly::Range — 일반 iterator pair
  74. 74 folly::Uri — URL 파서
  75. 75 folly Fingerprint64·128 — 분산 hash
  76. 76 folly SpookyHashV2 — fast non-crypto hash
  77. 77 folly::Init — main() 부트스트랩
  78. 78 folly::Indestructible — global lifetime 패턴
  79. 79 folly::MicroLock — 1-byte 락
  80. 80 folly::MicroSpinLock — 가장 좁은 spin lock
  81. 81 folly::format — legacy formatter 분석
  82. 82 folly::demangle — typeid 디망글링
  83. 83 folly::DynamicConverter — dynamic ↔ struct
  84. 84 folly::RecordIO — append-only 로그 파일 포맷
  85. 85 folly::io::Compression — zstd·lz4·snappy wrapper
  86. 86 folly::AsyncIO — io_uring·Linux AIO
  87. 87 folly::CancellationToken — 코루틴·Future 취소 전파
  88. 88 folly::observer — hot config의 atomic refresh
  89. 89 fbcode 패턴 모음 — folly 사용의 실전