Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(personhog-replica): add gzip layer (#60295)

Zach Brown126b9776cb85
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 6bf6b7ff64a6..1d3c37594551 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -6652,8 +6652,12 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
name = "personhog-common"
version = "0.1.0"
dependencies = [
+ "bytes",
+ "flate2",
"futures",
"http 1.4.0",
+ "http-body 1.0.1",
+ "http-body-util",
"metrics",
"pin-project",
"sqlx",
@@ -6769,6 +6773,7 @@ dependencies = [
"common-alloc",
"dashmap 6.1.0",
"envconfig",
+ "flate2",
"futures",
"http 1.4.0",
"http-body 1.0.1",
@@ -10439,7 +10444,6 @@ dependencies = [
"axum 0.7.9",
"base64 0.22.1",
"bytes",
- "flate2",
"h2 0.4.13",
"http 1.4.0",
"http-body 1.0.1",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 56cd86af84d9..b94130bb8830 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -112,6 +112,8 @@ futures-timer = "3.0"
futures-util = { version = "0.3.31" }
governor = { version = "0.5.1", features = ["dashmap"] }
http = { version = "1.1.0" }
+http-body = "1.0"
+http-body-util = "0.1"
httpmock = "0.7.0"
mockito = "1"
hyper = { version = "1.9.0", features = ["server", "http1", "http2"] }
@@ -181,7 +183,7 @@ regex = "1.11.1"
fancy-regex = "0.17"
lz-str = "0.2.1"
opentelemetry-proto = { version = "0.29.0", features = ["with-serde"] }
-tonic = { version = "0.12.3", features = ["zstd", "gzip"] }
+tonic = { version = "0.12.3", features = ["zstd"] }
tonic-build = "0.12"
clickhouse = { version = "0.13.2", features = [
"uuid",
diff --git a/rust/personhog-common/Cargo.toml b/rust/personhog-common/Cargo.toml
index 39a60930c2e8..c9cc33ab815c 100644
--- a/rust/personhog-common/Cargo.toml
+++ b/rust/personhog-common/Cargo.toml
@@ -5,8 +5,12 @@ edition = "2021"
publish = false
[dependencies]
+bytes = { workspace = true }
+flate2 = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
+http-body = { workspace = true }
+http-body-util = { workspace = true }
metrics = { workspace = true }
pin-project = "1.1"
sqlx = { workspace = true }
diff --git a/rust/personhog-common/src/async_gzip.rs b/rust/personhog-common/src/async_gzip.rs
new file mode 100644
index 000000000000..35da427131e1
--- /dev/null
+++ b/rust/personhog-common/src/async_gzip.rs
@@ -0,0 +1,950 @@
+//! Tower layer that offloads gRPC response compression to a blocking thread.
+//!
+//! Tonic's built-in compression runs synchronously inside `poll_next`, blocking
+//! the tokio runtime for the entire duration of gzip deflate. For large protobuf
+//! payloads this is the dominant CPU cost on the service, starving other tasks of
+//! runtime time. This layer replaces tonic's inline compression with one that
+//! collects the uncompressed response, compresses it on `spawn_blocking`, and
+//! returns the compressed frame — freeing the runtime to handle other requests
+//! while compression runs on the blocking thread pool.
+//!
+//! Designed for **unary RPCs only**. The implementation buffers the entire response
+//! body before compressing, which is fine for request-response patterns but would
+//! defeat the purpose of server-streaming RPCs.
+
+use std::fmt;
+use std::future::Future;
+use std::io::Write;
+use std::pin::Pin;
+use std::task::{Context, Poll};
+use std::time::Instant;
+
+use bytes::{BufMut, Bytes, BytesMut};
+use flate2::write::GzEncoder;
+use flate2::Compression;
+use futures::pin_mut;
+use http::{HeaderMap, HeaderValue, Request, Response};
+use http_body::{Body, Frame, SizeHint};
+use http_body_util::BodyExt;
+use metrics::{counter, histogram};
+use tokio::task::spawn_blocking;
+use tonic::Status;
+use tower::{Layer, Service};
+use tracing::warn;
+
+/// gRPC frame header: 1 byte compression flag + 4 byte payload length.
+const GRPC_HEADER_SIZE: usize = 5;
+
+/// Header names used in gRPC compression negotiation.
+const GRPC_ACCEPT_ENCODING: &str = "grpc-accept-encoding";
+const GRPC_ENCODING: &str = "grpc-encoding";
+
+/// Type alias for the boxed body returned by the layer. Both the passthrough
+/// and compressed paths produce bodies that implement this trait, boxed to
+/// keep a single concrete return type on the service.
+pub type ResponseBody = Pin<Box<dyn Body<Data = Bytes, Error = Status> + Send>>;
+
+// ============================================================
+// Configuration
+// ============================================================
+
+/// Configuration for the async gzip compression layer.
+#[derive(Clone, Debug)]
+pub struct AsyncGzipConfig {
+ /// Whether compression is enabled. When false, the layer is a no-cost
+ /// passthrough regardless of client headers.
+ pub enabled: bool,
+
+ /// Gzip compression level (1–9, clamped). Lower levels are faster with
+ /// less compression; higher levels compress more but use more CPU.
+ /// Level 6 is the flate2/zlib default.
+ pub compression_level: u32,
+
+ /// Minimum payload size (bytes) to bother compressing. Responses smaller
+ /// than this pass through uncompressed — the gzip header overhead would
+ /// make them larger, and the CPU cost isn't worth it.
+ pub min_payload_size: usize,
+}
+
+impl AsyncGzipConfig {
+ pub fn new(enabled: bool, compression_level: u32, min_payload_size: usize) -> Self {
+ Self {
+ enabled,
+ compression_level: compression_level.clamp(1, 9),
+ min_payload_size,
+ }
+ }
+}
+
+impl Default for AsyncGzipConfig {
+ fn default() -> Self {
+ Self {
+ enabled: false,
+ compression_level: 6,
+ min_payload_size: 256,
+ }
+ }
+}
+
+// ============================================================
+// Layer
+// ============================================================
+
+/// Tower layer that adds async gzip compression to gRPC responses.
+///
+/// The inner tonic service must have gzip compression **disabled** — this layer
+/// takes over gzip entirely. When disabled via config, the layer is a no-cost
+/// passthrough.
+#[derive(Clone)]
+pub struct AsyncGzipLayer {
+ config: AsyncGzipConfig,
+}
+
+impl AsyncGzipLayer {
+ pub fn new(config: AsyncGzipConfig) -> Self {
+ Self { config }
+ }
+}
+
+impl<S> Layer<S> for AsyncGzipLayer {
+ type Service = AsyncGzipService<S>;
+
+ fn layer(&self, service: S) -> Self::Service {
+ AsyncGzipService {
+ inner: service,
+ config: self.config.clone(),
+ }
+ }
+}
+
+// ============================================================
+// Service
+// ============================================================
+
+#[derive(Clone)]
+pub struct AsyncGzipService<S> {
+ inner: S,
+ config: AsyncGzipConfig,
+}
+
+impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for AsyncGzipService<S>
+where
+ S: Service<Request<ReqBody>, Response = Response<ResBody>> + Clone + Send + 'static,
+ S::Future: Send,
+ S::Error: Send + 'static,
+ ReqBody: Send + 'static,
+ ResBody: Body<Data = Bytes> + Send + 'static,
+ ResBody::Error: fmt::Display + Send,
+{
+ type Response = Response<ResponseBody>;
+ type Error = S::Error;
+ type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
+
+ fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+ self.inner.poll_ready(cx)
+ }
+
+ fn call(&mut self, request: Request<ReqBody>) -> Self::Future {
+ let accepts_gzip = self.config.enabled
+ && request
+ .headers()
+ .get(GRPC_ACCEPT_ENCODING)
+ .and_then(|v| v.to_str().ok())
+ .is_some_and(|v| v.split(',').any(|e| e.trim() == "gzip"));
+
+ let method = request
+ .uri()
+ .path()
+ .rsplit_once('/')
+ .map(|(_, m)| m)
+ .filter(|m| !m.is_empty())
+ .unwrap_or("unknown")
+ .to_string();
+
+ let config = self.config.clone();
+ let mut inner = self.inner.clone();
+
+ Box::pin(async move {
+ let response = inner.call(request).await?;
+ let (mut parts, body) = response.into_parts();
+
+ // When compression isn't requested, pass the original body through
+ // without collecting or copying — zero overhead for the common case
+ // where the client doesn't accept gzip or the feature is disabled.
+ if !accepts_gzip {
+ counter!("grpc_gzip_responses_total", "outcome" => "passthrough", "method" => method.clone()).increment(1);
+ let body = body.map_err(|e| Status::internal(e.to_string()));
+ let boxed: ResponseBody = Box::pin(body);
+ return Ok(Response::from_parts(parts, boxed));
+ }
+
+ // Gather body data chunks and trailers separately. For unary RPCs,
+ // tonic produces one or more data frames (split at ~32KB boundaries)
+ // followed by a trailers frame. We keep chunks as individual Bytes
+ // references to avoid copying them into a contiguous buffer.
+ let mut chunks: Vec<Bytes> = Vec::new();
+ let mut trailers: Option<HeaderMap> = None;
+ let mut total_size: usize = 0;
+ pin_mut!(body);
+ loop {
+ match body.frame().await {
+ Some(Ok(frame)) => match frame.into_data() {
+ Ok(data) => {
+ total_size += data.len();
+ chunks.push(data);
+ }
+ Err(frame) => {
+ if let Ok(t) = frame.into_trailers() {
+ trailers = Some(t);
+ }
+ }
+ },
+ Some(Err(e)) => {
+ warn!(error = %e, "Failed to read response body for compression");
+ counter!("grpc_gzip_responses_total", "outcome" => "collect_error", "method" => method.clone())
+ .increment(1);
+ // Synthesize a grpc-status trailer so the client gets a
+ // clean error instead of a protocol violation from a
+ // missing trailer.
+ let error_trailers = trailers.unwrap_or_else(|| {
+ let mut map = HeaderMap::new();
+ map.insert("grpc-status", HeaderValue::from_static("13"));
+ map.insert(
+ "grpc-message",
+ HeaderValue::from_str(&format!("body collection failed: {e}"))
+ .unwrap_or_else(|_| {
+ HeaderValue::from_static("body collection failed")
+ }),
+ );
+ map
+ });
+ let boxed: ResponseBody =
+ Box::pin(PrecomputedBody::trailers_only(error_trailers));
+ return Ok(Response::from_parts(parts, boxed));
+ }
+ None => break,
+ }
+ }
+
+ let payload_size = total_size.saturating_sub(GRPC_HEADER_SIZE);
+ let already_compressed = chunks.iter().find_map(|c| c.first().copied()) == Some(1);
+
+ // Skip compression when there's no data, the payload is below the
+ // minimum threshold, or the frame is already compressed by tonic.
+ if chunks.is_empty()
+ || total_size <= GRPC_HEADER_SIZE
+ || payload_size < config.min_payload_size
+ || already_compressed
+ {
+ counter!("grpc_gzip_responses_total", "outcome" => "passthrough", "method" => method.clone()).increment(1);
+ let data = concat_chunks(&chunks);
+ let boxed: ResponseBody = Box::pin(PrecomputedBody::new(data, trailers));
+ return Ok(Response::from_parts(parts, boxed));
+ }
+
+ // Compress the protobuf payload on the blocking thread pool.
+ // We move the chunk references directly — the encoder reads each
+ // chunk sequentially without copying them into a contiguous buffer.
+ let level = config.compression_level;
+ let start = Instant::now();
+ let compressed = spawn_blocking(move || gzip_compress_chunks(&chunks, level)).await;
+ let elapsed = start.elapsed();
+
+ match compressed {
+ Ok(Ok(bytes)) => {
+ histogram!("grpc_gzip_compression_duration_ms", "method" => method.clone())
+ .record(elapsed.as_secs_f64() * 1000.0);
+ histogram!("grpc_gzip_uncompressed_bytes", "method" => method.clone())
+ .record(payload_size as f64);
+ histogram!("grpc_gzip_compressed_bytes", "method" => method.clone())
+ .record(bytes.len() as f64);
+ counter!("grpc_gzip_responses_total", "outcome" => "compressed", "method" => method.clone()).increment(1);
+
+ let mut frame = BytesMut::with_capacity(GRPC_HEADER_SIZE + bytes.len());
+ frame.put_u8(1); // compression flag
+ frame.put_u32(bytes.len() as u32);
+ frame.extend_from_slice(&bytes);
+
+ parts
+ .headers
+ .insert(GRPC_ENCODING, HeaderValue::from_static("gzip"));
+
+ let boxed: ResponseBody =
+ Box::pin(PrecomputedBody::new(frame.freeze(), trailers));
+ Ok(Response::from_parts(parts, boxed))
+ }
+ Ok(Err(e)) => {
+ warn!(error = %e, "gzip compression failed, returning uncompressed");
+ counter!("grpc_gzip_responses_total", "outcome" => "compress_error", "method" => method.clone())
+ .increment(1);
+ let boxed: ResponseBody = Box::pin(PrecomputedBody::trailers_only(trailers));
+ Ok(Response::from_parts(parts, boxed))
+ }
+ Err(e) => {
+ warn!(error = %e, "spawn_blocking panicked, returning uncompressed");
+ counter!("grpc_gzip_responses_total", "outcome" => "spawn_error", "method" => method.clone()).increment(1);
+ let boxed: ResponseBody = Box::pin(PrecomputedBody::trailers_only(trailers));
+ Ok(Response::from_parts(parts, boxed))
+ }
+ }
+ })
+ }
+}
+
+// ============================================================
+// Response bodies
+// ============================================================
+
+/// Response body that yields pre-computed data followed by optional trailers.
+/// Used for compressed responses and small-payload passthrough where the chunks
+/// have already been collected.
+struct PrecomputedBody {
+ data: Option<Bytes>,
+ trailers: Option<HeaderMap>,
+}
+
+impl PrecomputedBody {
+ fn new(data: Bytes, trailers: Option<HeaderMap>) -> Self {
+ Self {
+ data: if data.is_empty() { None } else { Some(data) },
+ trailers,
+ }
+ }
+
+ fn trailers_only(trailers: impl Into<Option<HeaderMap>>) -> Self {
+ Self {
+ data: None,
+ trailers: trailers.into(),
+ }
+ }
+}
+
+impl Body for PrecomputedBody {
+ type Data = Bytes;
+ type Error = Status;
+
+ fn poll_frame(
+ mut self: Pin<&mut Self>,
+ _cx: &mut Context<'_>,
+ ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
+ if let Some(data) = self.data.take() {
+ return Poll::Ready(Some(Ok(Frame::data(data))));
+ }
+ if let Some(trailers) = self.trailers.take() {
+ return Poll::Ready(Some(Ok(Frame::trailers(trailers))));
+ }
+ Poll::Ready(None)
+ }
+
+ fn is_end_stream(&self) -> bool {
+ self.data.is_none() && self.trailers.is_none()
+ }
+
+ fn size_hint(&self) -> SizeHint {
+ SizeHint::default()
+ }
+}
+
+// ============================================================
+// Compression helpers
+// ============================================================
+
+/// Concatenate chunks into a contiguous buffer. Only used for the passthrough
+/// path where we already collected but decided not to compress.
+fn concat_chunks(chunks: &[Bytes]) -> Bytes {
+ if chunks.len() == 1 {
+ return chunks[0].clone();
+ }
+ let total: usize = chunks.iter().map(|c| c.len()).sum();
+ let mut buf = BytesMut::with_capacity(total);
+ for chunk in chunks {
+ buf.extend_from_slice(chunk);
+ }
+ buf.freeze()
+}
+
+/// Compress body chunks without copying them into a contiguous buffer first.
+/// Skips the 5-byte gRPC frame header, then feeds each chunk sequentially to
+/// the gzip encoder.
+fn gzip_compress_chunks(chunks: &[Bytes], level: u32) -> std::io::Result<Vec<u8>> {
+ let total: usize = chunks.iter().map(|c| c.len()).sum();
+ let mut encoder = GzEncoder::new(Vec::with_capacity(total / 2), Compression::new(level));
+ let mut skip = GRPC_HEADER_SIZE;
+ for chunk in chunks {
+ if skip >= chunk.len() {
+ skip -= chunk.len();
+ continue;
+ }
+ encoder.write_all(&chunk[skip..])?;
+ skip = 0;
+ }
+ encoder.finish()
+}
+
+/// Compress a contiguous byte slice.
+#[cfg(test)]
+fn gzip_compress(data: &[u8], level: u32) -> std::io::Result<Vec<u8>> {
+ let mut encoder = GzEncoder::new(Vec::with_capacity(data.len() / 2), Compression::new(level));
+ encoder.write_all(data)?;
+ encoder.finish()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use flate2::read::GzDecoder;
+ use http_body_util::BodyExt;
+ use std::convert::Infallible;
+ use std::io::Read;
+ use std::slice;
+
+ use http::response;
+ use tower::{Service, ServiceExt};
+
+ // -- test helpers --
+
+ fn make_grpc_frame(payload: &[u8]) -> Bytes {
+ let mut frame = BytesMut::with_capacity(GRPC_HEADER_SIZE + payload.len());
+ frame.put_u8(0);
+ frame.put_u32(payload.len() as u32);
+ frame.extend_from_slice(payload);
+ frame.freeze()
+ }
+
+ fn parse_grpc_frame(data: &[u8]) -> (bool, Vec<u8>) {
+ assert!(data.len() >= GRPC_HEADER_SIZE, "frame too short");
+ let compressed = data[0] == 1;
+ let len = u32::from_be_bytes(data[1..5].try_into().unwrap()) as usize;
+ assert_eq!(data.len() - GRPC_HEADER_SIZE, len, "frame length mismatch");
+ (compressed, data[GRPC_HEADER_SIZE..].to_vec())
+ }
+
+ fn gzip_decompress(data: &[u8]) -> Vec<u8> {
+ let mut decoder = GzDecoder::new(data);
+ let mut out = Vec::new();
+ decoder.read_to_end(&mut out).unwrap();
+ out
+ }
+
+ fn grpc_ok_trailers() -> HeaderMap {
+ let mut map = HeaderMap::new();
+ map.insert("grpc-status", HeaderValue::from_static("0"));
+ map
+ }
+
+ fn default_test_config() -> AsyncGzipConfig {
+ AsyncGzipConfig {
+ enabled: true,
+ compression_level: 6,
+ min_payload_size: 0,
+ }
+ }
+
+ // -- mock service --
+
+ #[derive(Clone)]
+ struct MockGrpcService {
+ body: Bytes,
+ trailers: Option<HeaderMap>,
+ }
+
+ impl MockGrpcService {
+ fn new(payload: &[u8]) -> Self {
+ Self {
+ body: make_grpc_frame(payload),
+ trailers: Some(grpc_ok_trailers()),
+ }
+ }
+
+ fn with_trailers(mut self, trailers: HeaderMap) -> Self {
+ self.trailers = Some(trailers);
+ self
+ }
+
+ fn without_trailers(mut self) -> Self {
+ self.trailers = None;
+ self
+ }
+ }
+
+ struct MockBody {
+ data: Option<Bytes>,
+ trailers: Option<HeaderMap>,
+ }
+
+ impl Body for MockBody {
+ type Data = Bytes;
+ type Error = Status;
+
+ fn poll_frame(
+ mut self: Pin<&mut Self>,
+ _cx: &mut Context<'_>,
+ ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
+ if let Some(data) = self.data.take() {
+ return Poll::Ready(Some(Ok(Frame::data(data))));
+ }
+ if let Some(trailers) = self.trailers.take() {
+ return Poll::Ready(Some(Ok(Frame::trailers(trailers))));
+ }
+ Poll::Ready(None)
+ }
+ }
+
+ impl Service<Request<()>> for MockGrpcService {
+ type Response = Response<MockBody>;
+ type Error = Infallible;
+ type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
+
+ fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+ Poll::Ready(Ok(()))
+ }
+
+ fn call(&mut self, _request: Request<()>) -> Self::Future {
+ let body = MockBody {
+ data: Some(self.body.clone()),
+ trailers: self.trailers.clone(),
+ };
+ Box::pin(async { Ok(Response::new(body)) })
+ }
+ }
+
+ /// A service whose body yields one data frame then errors before trailers,
+ /// simulating a mid-stream failure.
+ #[derive(Clone)]
+ struct MockErrorService;
+
+ /// Body that yields data then an error — no trailers are ever produced.
+ struct ErrorBody {
+ data: Option<Bytes>,
+ errored: bool,
+ }
+
+ impl Body for ErrorBody {
+ type Data = Bytes;
+ type Error = Status;
+
+ fn poll_frame(
+ mut self: Pin<&mut Self>,
+ _cx: &mut Context<'_>,
+ ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
+ if let Some(data) = self.data.take() {
+ return Poll::Ready(Some(Ok(Frame::data(data))));
+ }
+ if !self.errored {
+ self.errored = true;
+ return Poll::Ready(Some(Err(Status::internal("simulated body error"))));
+ }
+ Poll::Ready(None)
+ }
+ }
+
+ impl Service<Request<()>> for MockErrorService {
+ type Response = Response<ErrorBody>;
+ type Error = Infallible;
+ type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
+
+ fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+ Poll::Ready(Ok(()))
+ }
+
+ fn call(&mut self, _request: Request<()>) -> Self::Future {
+ let body = ErrorBody {
+ data: Some(make_grpc_frame(b"partial data")),
+ errored: false,
+ };
+ Box::pin(async { Ok(Response::new(body)) })
+ }
+ }
+
+ /// Call the layer with a request, returning (response_parts, body_bytes, trailers).
+ async fn call_layer(
+ service: MockGrpcService,
+ config: AsyncGzipConfig,
+ accept_encoding: Option<&str>,
+ ) -> (response::Parts, Bytes, Option<HeaderMap>) {
+ let mut svc = AsyncGzipLayer::new(config).layer(service);
+ let svc = svc.ready().await.unwrap();
+
+ let mut request = Request::new(());
+ if let Some(enc) = accept_encoding {
+ request
+ .headers_mut()
+ .insert(GRPC_ACCEPT_ENCODING, HeaderValue::from_str(enc).unwrap());
+ }
+
+ let response = svc.call(request).await.unwrap();
+ let (parts, body) = response.into_parts();
+ let collected = body.collect().await.unwrap();
+ let trailers = collected.trailers().cloned();
+ let data = collected.to_bytes();
+
+ (parts, data, trailers)
+ }
+
+ // ============================================================
+ // Helper function unit tests
+ // ============================================================
+
+ #[test]
+ fn gzip_roundtrip() {
+ let original = b"hello world, this is a test payload for gzip compression";
+ let compressed = gzip_compress(original, 6).unwrap();
+ assert_eq!(gzip_decompress(&compressed), original);
+ }
+
+ #[test]
+ fn gzip_empty_input() {
+ let compressed = gzip_compress(b"", 6).unwrap();
+ assert_eq!(gzip_decompress(&compressed), b"");
+ }
+
+ #[test]
+ fn gzip_compression_levels() {
+ let data = vec![42u8; 10_000];
+ let fast = gzip_compress(&data, 1).unwrap();
+ let slow = gzip_compress(&data, 9).unwrap();
+ assert_eq!(gzip_decompress(&fast), data);
+ assert_eq!(gzip_decompress(&slow), data);
+ assert!(slow.len() <= fast.len());
+ }
+
+ #[test]
+ fn concat_chunks_single_chunk() {
+ let chunk = Bytes::from_static(b"hello");
+ let result = concat_chunks(slice::from_ref(&chunk));
+ assert_eq!(result, chunk);
+ }
+
+ #[test]
+ fn concat_chunks_multiple() {
+ let chunks = vec![
+ Bytes::from_static(b"hel"),
+ Bytes::from_static(b"lo "),
+ Bytes::from_static(b"world"),
+ ];
+ assert_eq!(concat_chunks(&chunks), Bytes::from_static(b"hello world"));
+ }
+
+ #[test]
+ fn compress_chunks_single_chunk() {
+ let payload = b"protobuf data here";
+ let frame = make_grpc_frame(payload);
+ let compressed = gzip_compress_chunks(&[frame], 6).unwrap();
+ assert_eq!(gzip_decompress(&compressed), payload);
+ }
+
+ #[test]
+ fn compress_chunks_header_in_first_chunk() {
+ // Header (5 bytes) + first part of payload in chunk 1, rest in chunk 2
+ let payload = b"abcdefghijklmnopqrstuvwxyz";
+ let frame = make_grpc_frame(payload);
+ let chunks = vec![frame.slice(..15), frame.slice(15..)];
+ let compressed = gzip_compress_chunks(&chunks, 6).unwrap();
+ assert_eq!(gzip_decompress(&compressed), payload);
+ }
+
+ #[test]
+ fn compress_chunks_header_spans_two_chunks() {
+ // 3 bytes of header in chunk 1, remaining 2 bytes + payload in chunk 2
+ let payload = b"the payload";
+ let frame = make_grpc_frame(payload);
+ let chunks = vec![frame.slice(..3), frame.slice(3..)];
+ let compressed = gzip_compress_chunks(&chunks, 6).unwrap();
+ assert_eq!(gzip_decompress(&compressed), payload);
+ }
+
+ #[test]
+ fn compress_chunks_header_exactly_one_chunk() {
+ // First chunk is exactly the 5-byte header, second chunk is payload
+ let payload = b"payload after header";
+ let frame = make_grpc_frame(payload);
+ let chunks = vec![
+ frame.slice(..GRPC_HEADER_SIZE),
+ frame.slice(GRPC_HEADER_SIZE..),
+ ];
+ let compressed = gzip_compress_chunks(&chunks, 6).unwrap();
+ assert_eq!(gzip_decompress(&compressed), payload);
+ }
+
+ #[test]
+ fn compress_chunks_many_small_chunks() {
+ // Simulate a body split into many small chunks
+ let payload: Vec<u8> = (0..1000).map(|i| (i % 256) as u8).collect();
+ let frame = make_grpc_frame(&payload);
+ let chunks: Vec<Bytes> = frame.chunks(50).map(Bytes::copy_from_slice).collect();
+ assert!(chunks.len() > 10);
+ let compressed = gzip_compress_chunks(&chunks, 6).unwrap();
+ assert_eq!(gzip_decompress(&compressed), payload);
+ }
+
+ // ============================================================
+ // Layer integration tests
+ // ============================================================
+
+ #[tokio::test]
+ async fn compresses_response_when_client_accepts_gzip() {
+ let payload = b"fake protobuf payload that should be compressed";
+ let service = MockGrpcService::new(payload);
+ let (parts, data, trailers) =
+ call_layer(service, default_test_config(), Some("gzip")).await;
+
+ assert_eq!(parts.headers.get(GRPC_ENCODING).unwrap(), "gzip");
+ let (compressed, compressed_payload) = parse_grpc_frame(&data);
+ assert!(compressed, "compression flag should be set");
+ assert_eq!(gzip_decompress(&compressed_payload), payload);
+
+ let trailers = trailers.expect("trailers should be present");
+ assert_eq!(trailers.get("grpc-status").unwrap(), "0");
+ }
+
+ #[tokio::test]
+ async fn no_compression_without_accept_encoding_header() {
+ let payload = b"this payload should not be compressed";
+ let service = MockGrpcService::new(payload);
+ let (parts, data, _trailers) = call_layer(service, default_test_config(), None).await;
+
+ assert!(parts.headers.get(GRPC_ENCODING).is_none());
+ let (compressed, raw_payload) = parse_grpc_frame(&data);
+ assert!(!compressed);
+ assert_eq!(raw_payload, payload);
+ }
+
+ #[tokio::test]
+ async fn no_compression_when_gzip_not_in_accept_encoding() {
+ let payload = b"this payload should not be compressed";
+ let service = MockGrpcService::new(payload);
+ let (parts, data, _trailers) =
+ call_layer(service, default_test_config(), Some("zstd,identity")).await;
+
+ assert!(parts.headers.get(GRPC_ENCODING).is_none());
+ let (compressed, raw_payload) = parse_grpc_frame(&data);
+ assert!(!compressed);
+ assert_eq!(raw_payload, payload);
+ }
+
+ #[tokio::test]
+ async fn compresses_when_gzip_among_multiple_encodings() {
+ let payload = b"mixed encoding header test";
+ let service = MockGrpcService::new(payload);
+ let (parts, data, _trailers) =
+ call_layer(service, default_test_config(), Some("zstd, gzip, identity")).await;
+
+ assert_eq!(parts.headers.get(GRPC_ENCODING).unwrap(), "gzip");
+ let (compressed, compressed_payload) = parse_grpc_frame(&data);
+ assert!(compressed);
+ assert_eq!(gzip_decompress(&compressed_payload), payload);
+ }
+
+ #[tokio::test]
+ async fn preserves_trailers() {
+ let payload = b"trailers test";
+ let mut custom_trailers = grpc_ok_trailers();
+ custom_trailers.insert("grpc-message", HeaderValue::from_static("all good"));
+
+ let service = MockGrpcService::new(payload).with_trailers(custom_trailers);
+ let (_parts, _data, trailers) =
+ call_layer(service, default_test_config(), Some("gzip")).await;
+
+ let trailers = trailers.expect("trailers should be present");
+ assert_eq!(trailers.get("grpc-status").unwrap(), "0");
+ assert_eq!(trailers.get("grpc-message").unwrap(), "all good");
+ }
+
+ #[tokio::test]
+ async fn handles_response_without_trailers() {
+ let payload = b"no trailers";
+ let service = MockGrpcService::new(payload).without_trailers();
+ let (parts, data, trailers) =
+ call_layer(service, default_test_config(), Some("gzip")).await;
+
+ assert_eq!(parts.headers.get(GRPC_ENCODING).unwrap(), "gzip");
+ let (compressed, compressed_payload) = parse_grpc_frame(&data);
+ assert!(compressed);
+ assert_eq!(gzip_decompress(&compressed_payload), payload);
+ assert!(trailers.is_none());
+ }
+
+ #[tokio::test]
+ async fn passthrough_on_trailers_only_response() {
+ // A response with no data frames (only trailers) — e.g. a gRPC error
+ // where the status is sent entirely in the trailers frame.
+ let service = MockGrpcService {
+ body: Bytes::new(),
+ trailers: Some(grpc_ok_trailers()),
+ };
+ let (parts, data, trailers) =
+ call_layer(service, default_test_config(), Some("gzip")).await;
+
+ assert!(parts.headers.get(GRPC_ENCODING).is_none());
+ assert!(data.is_empty());
+ let trailers = trailers.expect("trailers should be present");
+ assert_eq!(trailers.get("grpc-status").unwrap(), "0");
+ }
+
+ #[tokio::test]
+ async fn passthrough_on_empty_grpc_frame() {
+ let mut frame = BytesMut::with_capacity(GRPC_HEADER_SIZE);
+ frame.put_u8(0);
+ frame.put_u32(0);
+
+ let service = MockGrpcService {
+ body: frame.freeze(),
+ trailers: Some(grpc_ok_trailers()),
+ };
+ let (parts, data, _trailers) =
+ call_layer(service, default_test_config(), Some("gzip")).await;
+
+ assert!(parts.headers.get(GRPC_ENCODING).is_none());
+ assert_eq!(data.len(), GRPC_HEADER_SIZE);
+ }
+
+ #[tokio::test]
+ async fn compressed_frame_length_field_matches_payload() {
+ let payload = vec![42u8; 10_000];
+ let service = MockGrpcService::new(&payload);
+ let (_parts, data, _trailers) =
+ call_layer(service, default_test_config(), Some("gzip")).await;
+
+ let (compressed, compressed_payload) = parse_grpc_frame(&data);
+ assert!(compressed);
+ let header_len = u32::from_be_bytes(data[1..5].try_into().unwrap()) as usize;
+ assert_eq!(header_len, compressed_payload.len());
+ assert_eq!(gzip_decompress(&compressed_payload), payload);
+ }
+
+ #[tokio::test]
+ async fn large_payload_compresses_correctly() {
+ let payload: Vec<u8> = (0..100_000).map(|i| (i % 256) as u8).collect();
+ let service = MockGrpcService::new(&payload);
+ let (parts, data, trailers) =
+ call_layer(service, default_test_config(), Some("gzip")).await;
+
+ assert_eq!(parts.headers.get(GRPC_ENCODING).unwrap(), "gzip");
+ let (compressed, compressed_payload) = parse_grpc_frame(&data);
+ assert!(compressed);
+ assert_eq!(gzip_decompress(&compressed_payload), payload);
+ assert!(
+ compressed_payload.len() < payload.len(),
+ "compressed ({}) should be smaller than original ({})",
+ compressed_payload.len(),
+ payload.len()
+ );
+
+ let trailers = trailers.expect("trailers should be present");
+ assert_eq!(trailers.get("grpc-status").unwrap(), "0");
+ }
+
+ #[tokio::test]
+ async fn disabled_flag_skips_compression() {
+ let payload = b"should not be compressed";
+ let service = MockGrpcService::new(payload);
+ let config = AsyncGzipConfig {
+ enabled: false,
+ ..default_test_config()
+ };
+ let (parts, data, _trailers) = call_layer(service, config, Some("gzip")).await;
+
+ assert!(parts.headers.get(GRPC_ENCODING).is_none());
+ let (compressed, raw_payload) = parse_grpc_frame(&data);
+ assert!(!compressed);
+ assert_eq!(raw_payload, payload);
+ }
+
+ #[tokio::test]
+ async fn min_payload_size_skips_small_responses() {
+ let payload = b"tiny";
+ let service = MockGrpcService::new(payload);
+ let config = AsyncGzipConfig {
+ min_payload_size: 1000,
+ ..default_test_config()
+ };
+ let (parts, data, _trailers) = call_layer(service, config, Some("gzip")).await;
+
+ assert!(parts.headers.get(GRPC_ENCODING).is_none());
+ let (compressed, raw_payload) = parse_grpc_frame(&data);
+ assert!(!compressed);
+ assert_eq!(raw_payload, payload);
+ }
+
+ #[tokio::test]
+ async fn min_payload_size_compresses_large_responses() {
+ let payload = vec![42u8; 2000];
+ let service = MockGrpcService::new(&payload);
+ let config = AsyncGzipConfig {
+ min_payload_size: 1000,
+ ..default_test_config()
+ };
+ let (parts, data, _trailers) = call_layer(service, config, Some("gzip")).await;
+
+ assert_eq!(parts.headers.get(GRPC_ENCODING).unwrap(), "gzip");
+ let (compressed, compressed_payload) = parse_grpc_frame(&data);
+ assert!(compressed);
+ assert_eq!(gzip_decompress(&compressed_payload), payload);
+ }
+
+ #[tokio::test]
+ async fn custom_compression_level() {
+ let payload = vec![42u8; 10_000];
+ let service = MockGrpcService::new(&payload);
+ let config = AsyncGzipConfig {
+ compression_level: 1,
+ ..default_test_config()
+ };
+ let (parts, data, _trailers) = call_layer(service, config, Some("gzip")).await;
+
+ assert_eq!(parts.headers.get(GRPC_ENCODING).unwrap(), "gzip");
+ let (compressed, compressed_payload) = parse_grpc_frame(&data);
+ assert!(compressed);
+ assert_eq!(gzip_decompress(&compressed_payload), payload);
+ }
+
+ #[tokio::test]
+ async fn body_error_synthesizes_grpc_status_trailer() {
+ let mut svc = AsyncGzipLayer::new(default_test_config()).layer(MockErrorService);
+ let svc = svc.ready().await.unwrap();
+
+ let mut request = Request::new(());
+ request
+ .headers_mut()
+ .insert(GRPC_ACCEPT_ENCODING, HeaderValue::from_static("gzip"));
+
+ let response = svc.call(request).await.unwrap();
+ let (parts, body) = response.into_parts();
+ let collected = body.collect().await.unwrap();
+ let trailers = collected.trailers().cloned();
+
+ // No grpc-encoding — compression was aborted
+ assert!(parts.headers.get(GRPC_ENCODING).is_none());
+
+ // Body should have no data (empty response on error)
+ let data = collected.to_bytes();
+ assert!(data.is_empty());
+
+ // Should have a synthesized grpc-status: 13 (INTERNAL) trailer
+ let trailers = trailers.expect("error path must produce trailers");
+ assert_eq!(trailers.get("grpc-status").unwrap(), "13");
+ assert!(trailers.get("grpc-message").is_some());
+ }
+
+ #[tokio::test]
+ async fn large_5mb_payload_compresses_correctly() {
+ let payload: Vec<u8> = (0..5_000_000).map(|i| (i % 256) as u8).collect();
+ let service = MockGrpcService::new(&payload);
+ let (parts, data, trailers) =
+ call_layer(service, default_test_config(), Some("gzip")).await;
+
+ assert_eq!(parts.headers.get(GRPC_ENCODING).unwrap(), "gzip");
+ let (compressed, compressed_payload) = parse_grpc_frame(&data);
+ assert!(compressed);
+ assert_eq!(gzip_decompress(&compressed_payload), payload);
+ assert!(
+ compressed_payload.len() < payload.len(),
+ "compressed ({}) should be smaller than original ({})",
+ compressed_payload.len(),
+ payload.len()
+ );
+
+ let trailers = trailers.expect("trailers should be present");
+ assert_eq!(trailers.get("grpc-status").unwrap(), "0");
+ }
+}
diff --git a/rust/personhog-common/src/lib.rs b/rust/personhog-common/src/lib.rs
index 27cc58f59863..15d5f3b159cf 100644
--- a/rust/personhog-common/src/lib.rs
+++ b/rust/personhog-common/src/lib.rs
@@ -1,3 +1,4 @@
+pub mod async_gzip;
pub mod grpc;
mod pool_monitor;
diff --git a/rust/personhog-replica/src/config.rs b/rust/personhog-replica/src/config.rs
index 7747a8769c57..60ddff83236f 100644
--- a/rust/personhog-replica/src/config.rs
+++ b/rust/personhog-replica/src/config.rs
@@ -100,6 +100,21 @@ pub struct Config {
/// so the router retries on another pod. 0 = disabled.
#[envconfig(default = "0")]
pub max_concurrent_requests: usize,
+
+ /// Enable gzip response compression via AsyncGzipLayer. When enabled,
+ /// responses to clients that send `grpc-accept-encoding: gzip` are
+ /// compressed on a blocking thread pool instead of the tokio runtime.
+ #[envconfig(default = "false")]
+ pub gzip_response_compression: bool,
+
+ /// Gzip compression level (1–9). Lower is faster, higher compresses more.
+ #[envconfig(default = "6")]
+ pub gzip_compression_level: u32,
+
+ /// Minimum response payload size (bytes) to compress. Responses smaller
+ /// than this pass through uncompressed.
+ #[envconfig(default = "256")]
+ pub gzip_min_payload_size: usize,
}
impl Config {
diff --git a/rust/personhog-replica/src/main.rs b/rust/personhog-replica/src/main.rs
index a09284843789..174a252533fe 100644
--- a/rust/personhog-replica/src/main.rs
+++ b/rust/personhog-replica/src/main.rs
@@ -6,6 +6,7 @@ use common_database::{get_pool_with_config, PoolConfig};
use envconfig::Envconfig;
use lifecycle::{ComponentOptions, Manager};
use metrics_exporter_prometheus::PrometheusBuilder;
+use personhog_common::async_gzip::{AsyncGzipConfig, AsyncGzipLayer};
use personhog_common::grpc::{tracked_tcp_incoming, GrpcLoadShedLayer, GrpcMetricsLayer};
use personhog_proto::personhog::replica::v1::person_hog_replica_server::PersonHogReplicaServer;
use tonic::codec::CompressionEncoding;
@@ -307,7 +308,19 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let max_send = config.grpc_max_send_message_size;
let max_recv = config.grpc_max_recv_message_size;
let max_concurrent_requests = config.max_concurrent_requests;
+ let gzip_config = AsyncGzipConfig::new(
+ config.gzip_response_compression,
+ config.gzip_compression_level,
+ config.gzip_min_payload_size,
+ );
+ if gzip_config.enabled {
+ tracing::info!(
+ level = gzip_config.compression_level,
+ min_payload_size = gzip_config.min_payload_size,
+ "Async gzip response compression enabled"
+ );
+ }
if max_concurrent_requests > 0 {
tracing::info!(
limit = max_concurrent_requests,
@@ -333,6 +346,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
server = server.max_connection_age(age);
}
if let Err(e) = server
+ .layer(AsyncGzipLayer::new(gzip_config))
.layer(GrpcMetricsLayer::default().with_processing_time_header())
.layer(GrpcLoadShedLayer::new(max_concurrent_requests))
.add_service(
@@ -340,9 +354,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.max_encoding_message_size(max_send)
.max_decoding_message_size(max_recv)
.accept_compressed(CompressionEncoding::Zstd)
- .send_compressed(CompressionEncoding::Zstd)
- .accept_compressed(CompressionEncoding::Gzip)
- .send_compressed(CompressionEncoding::Gzip),
+ .send_compressed(CompressionEncoding::Zstd),
)
.serve_with_incoming_shutdown(incoming, grpc_handle.shutdown_signal())
.await
diff --git a/rust/personhog-router/Cargo.toml b/rust/personhog-router/Cargo.toml
index 1647159998c0..f5157950e81c 100644
--- a/rust/personhog-router/Cargo.toml
+++ b/rust/personhog-router/Cargo.toml
@@ -37,6 +37,8 @@ tracing-subscriber = { workspace = true }
[dev-dependencies]
dashmap = { workspace = true }
+flate2 = { workspace = true }
+prost = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["test-util"] }
tokio-stream = "0.1"
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index 4b2b82f634d9..b5972a571702 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -22,7 +22,6 @@ use personhog_router::router::PersonHogRouter;
use personhog_router::service::PersonHogRouterService;
use personhog_router::stash_handler::RouterStashHandler;
use tokio_util::sync::CancellationToken;
-use tonic::codec::CompressionEncoding;
use tonic::transport::Server;
use tracing::level_filters::LevelFilter;
use tracing_subscriber::fmt;
@@ -339,9 +338,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.add_service(
PersonHogServiceServer::new(service)
.max_encoding_message_size(max_send)
- .max_decoding_message_size(max_recv)
- .accept_compressed(CompressionEncoding::Gzip)
- .send_compressed(CompressionEncoding::Gzip),
+ .max_decoding_message_size(max_recv),
)
.serve_with_incoming_shutdown(incoming, grpc_handle.shutdown_signal())
.await
diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rs
index 0f3069e54c16..86109e827f19 100644
--- a/rust/personhog-router/tests/common/mod.rs
+++ b/rust/personhog-router/tests/common/mod.rs
@@ -6,6 +6,7 @@ use std::sync::Arc;
use std::time::Duration;
use dashmap::DashMap;
+use personhog_common::async_gzip::{AsyncGzipConfig, AsyncGzipLayer};
use personhog_proto::personhog::leader::v1::person_hog_leader_server::{
PersonHogLeader, PersonHogLeaderServer,
};
@@ -53,6 +54,7 @@ use tokio::sync::RwLock;
use tonic::codec::CompressionEncoding;
use tonic::transport::{Channel, Server};
use tonic::{Request, Response, Status};
+use tower::Service;
use personhog_proto::personhog::types::v1::{
CohortMembership, Group, GroupTypeMapping, HashKeyOverrideContext, PersonWithDistinctIds,
@@ -459,6 +461,61 @@ pub async fn start_test_replica(service: TestReplicaService) -> SocketAddr {
addr
}
+/// Start a test replica that uses `AsyncGzipLayer` for response compression,
+/// matching the production configuration where gzip is offloaded to a blocking
+/// thread instead of running inline on the tokio runtime.
+pub async fn start_test_replica_with_async_gzip(service: TestReplicaService) -> SocketAddr {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+
+ tokio::spawn(async move {
+ Server::builder()
+ .layer(AsyncGzipLayer::new(AsyncGzipConfig {
+ enabled: true,
+ min_payload_size: 0,
+ ..AsyncGzipConfig::default()
+ }))
+ .add_service(
+ PersonHogReplicaServer::new(service)
+ .accept_compressed(CompressionEncoding::Zstd)
+ .send_compressed(CompressionEncoding::Zstd),
+ )
+ .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))
+ .await
+ .unwrap();
+ });
+
+ tokio::time::sleep(Duration::from_millis(10)).await;
+
+ addr
+}
+
+/// Start a test replica with `AsyncGzipLayer` disabled, verifying the flag
+/// prevents compression even when clients advertise gzip support.
+pub async fn start_test_replica_with_async_gzip_disabled(
+ service: TestReplicaService,
+) -> SocketAddr {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+
+ tokio::spawn(async move {
+ Server::builder()
+ .layer(AsyncGzipLayer::new(AsyncGzipConfig::default()))
+ .add_service(
+ PersonHogReplicaServer::new(service)
+ .accept_compressed(CompressionEncoding::Zstd)
+ .send_compressed(CompressionEncoding::Zstd),
+ )
+ .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))
+ .await
+ .unwrap();
+ });
+
+ tokio::time::sleep(Duration::from_millis(10)).await;
+
+ addr
+}
+
/// Start a test router server connected to the given replica address
pub async fn start_test_router(replica_addr: SocketAddr) -> SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -513,6 +570,58 @@ pub async fn create_compressed_client(router_addr: SocketAddr) -> PersonHogServi
.accept_compressed(CompressionEncoding::Zstd)
}
+/// Send a raw gRPC unary request with `grpc-accept-encoding: gzip` and return
+/// the response headers and body bytes. Uses tonic's Channel as HTTP/2
+/// transport but bypasses the gRPC codec layer so we can inspect the wire
+/// format — this matches the production scenario where the client is Django's
+/// grpcio, not a tonic client.
+pub async fn raw_grpc_call_with_gzip_accept(
+ addr: SocketAddr,
+ path: &str,
+ proto_msg: &impl prost::Message,
+) -> (http::HeaderMap, bytes::Bytes) {
+ use bytes::{BufMut, BytesMut};
+ use http_body_util::BodyExt;
+ use tower::ServiceExt;
+
+ // Encode protobuf into a gRPC frame: [flag=0][length][protobuf]
+ let proto_bytes = proto_msg.encode_to_vec();
+ let mut frame = BytesMut::with_capacity(5 + proto_bytes.len());
+ frame.put_u8(0);
+ frame.put_u32(proto_bytes.len() as u32);
+ frame.extend_from_slice(&proto_bytes);
+
+ let mut channel = Channel::from_shared(format!("http://{}", addr))
+ .unwrap()
+ .connect()
+ .await
+ .unwrap();
+
+ let body = http_body_util::combinators::UnsyncBoxBody::new(
+ http_body_util::Full::new(frame.freeze())
+ .map_err(|_: std::convert::Infallible| tonic::Status::internal("unreachable")),
+ );
+ let request = http::Request::builder()
+ .method("POST")
+ .uri(format!("http://{}{}", addr, path))
+ .header("content-type", "application/grpc")
+ .header("te", "trailers")
+ .header("grpc-accept-encoding", "gzip")
+ .body(body)
+ .unwrap();
+
+ let response = ServiceExt::ready(&mut channel)
+ .await
+ .unwrap()
+ .call(request)
+ .await
+ .unwrap();
+
+ let headers = response.headers().clone();
+ let body = response.into_body().collect().await.unwrap().to_bytes();
+ (headers, body)
+}
+
pub fn create_test_person() -> Person {
Person {
id: 42,
diff --git a/rust/personhog-router/tests/raw_proxy_integration.rs b/rust/personhog-router/tests/raw_proxy_integration.rs
index 6fc953e39a52..81561fe175e2 100644
--- a/rust/personhog-router/tests/raw_proxy_integration.rs
+++ b/rust/personhog-router/tests/raw_proxy_integration.rs
@@ -1,16 +1,17 @@
mod common;
use common::{
- create_client, create_compressed_client, create_test_person, start_test_leader,
- start_test_replica, start_test_router_raw, start_test_router_raw_with_leader,
- start_test_router_raw_with_leader_and_max_recv, start_test_router_raw_with_max_recv,
- TestLeaderService, TestReplicaService,
+ create_client, create_compressed_client, create_test_person, raw_grpc_call_with_gzip_accept,
+ start_test_leader, start_test_replica, start_test_replica_with_async_gzip,
+ start_test_replica_with_async_gzip_disabled, start_test_router_raw,
+ start_test_router_raw_with_leader, start_test_router_raw_with_leader_and_max_recv,
+ start_test_router_raw_with_max_recv, TestLeaderService, TestReplicaService,
};
use personhog_proto::personhog::service::v1::person_hog_service_client::PersonHogServiceClient;
use personhog_proto::personhog::types::v1::{
CheckCohortMembershipRequest, CohortMembership, ConsistencyLevel, DeletePersonsRequest,
GetGroupTypeMappingsByTeamIdRequest, GetGroupsRequest, GetHashKeyOverrideContextRequest,
- GetPersonByDistinctIdRequest, GetPersonByUuidRequest, GetPersonRequest,
+ GetPersonByDistinctIdRequest, GetPersonByUuidRequest, GetPersonRequest, GetPersonResponse,
GetPersonsByDistinctIdsInTeamRequest, Group, GroupIdentifier, GroupTypeMapping,
HashKeyOverride, HashKeyOverrideContext, Person, PersonWithDistinctIds, ReadOptions,
UpdatePersonPropertiesRequest,
@@ -960,3 +961,206 @@ async fn raw_proxy_compressed_get_persons_by_distinct_ids() {
.into_inner();
assert_eq!(plain_resp, compressed_resp);
}
+
+// ============================================================
+// 8. Async gzip compression
+//
+// These tests verify the AsyncGzipLayer by making raw gRPC requests with
+// `grpc-accept-encoding: gzip` and inspecting the wire format. We bypass
+// tonic's client codec because tonic's `gzip` feature is intentionally
+// disabled — our layer handles gzip instead of tonic's inline compression.
+// This matches production where the client is Django's grpcio.
+// ============================================================
+
+/// Decompress a gRPC frame, returning the protobuf payload.
+fn decompress_grpc_frame(data: &[u8]) -> Vec<u8> {
+ use flate2::read::GzDecoder;
+ use std::io::Read;
+
+ assert!(data.len() >= 5, "frame too short");
+ let flag = data[0];
+ let len = u32::from_be_bytes(data[1..5].try_into().unwrap()) as usize;
+ assert_eq!(data.len() - 5, len, "frame length mismatch");
+
+ if flag == 0 {
+ // Uncompressed
+ data[5..].to_vec()
+ } else {
+ // Gzip compressed
+ let mut decoder = GzDecoder::new(&data[5..]);
+ let mut out = Vec::new();
+ decoder.read_to_end(&mut out).unwrap();
+ out
+ }
+}
+
+#[tokio::test]
+async fn async_gzip_compresses_and_decompresses_correctly() {
+ let person = Person {
+ properties: complex_properties(),
+ ..create_test_person()
+ };
+ let replica_service = TestReplicaService::with_person(person.clone());
+ let replica_addr = start_test_replica_with_async_gzip(replica_service).await;
+
+ let req = GetPersonRequest {
+ team_id: 1,
+ person_id: 42,
+ read_options: None,
+ };
+
+ let (headers, body) = raw_grpc_call_with_gzip_accept(
+ replica_addr,
+ "/personhog.replica.v1.PersonHogReplica/GetPerson",
+ &req,
+ )
+ .await;
+
+ // Response should have grpc-encoding: gzip
+ assert_eq!(headers.get("grpc-encoding").unwrap(), "gzip");
+
+ // Frame should have compression flag set
+ assert_eq!(body[0], 1, "compression flag should be set");
+
+ // Decompress and parse the protobuf
+ let decompressed = decompress_grpc_frame(&body);
+ let response = <GetPersonResponse as prost::Message>::decode(decompressed.as_slice()).unwrap();
+ assert_eq!(response.person.unwrap().id, 42);
+}
+
+#[tokio::test]
+async fn async_gzip_through_raw_proxy() {
+ let person = Person {
+ properties: complex_properties(),
+ ..create_test_person()
+ };
+ let replica_service = TestReplicaService::with_person(person.clone());
+ let replica_addr = start_test_replica_with_async_gzip(replica_service).await;
+ let router_addr = start_test_router_raw(replica_addr).await;
+
+ let req = GetPersonRequest {
+ team_id: 1,
+ person_id: 42,
+ read_options: None,
+ };
+
+ let (headers, body) = raw_grpc_call_with_gzip_accept(
+ router_addr,
+ "/personhog.service.v1.PersonHogService/GetPerson",
+ &req,
+ )
+ .await;
+
+ assert_eq!(headers.get("grpc-encoding").unwrap(), "gzip");
+ assert_eq!(body[0], 1);
+
+ let decompressed = decompress_grpc_frame(&body);
+ let response = <GetPersonResponse as prost::Message>::decode(decompressed.as_slice()).unwrap();
+ assert_eq!(response.person.unwrap().id, 42);
+}
+
+#[tokio::test]
+async fn async_gzip_no_compression_without_accept_header() {
+ let person = Person {
+ properties: complex_properties(),
+ ..create_test_person()
+ };
+ let replica_service = TestReplicaService::with_person(person.clone());
+ let replica_addr = start_test_replica_with_async_gzip(replica_service).await;
+ let router_addr = start_test_router_raw(replica_addr).await;
+
+ // Plain client (no grpc-accept-encoding: gzip) through the router
+ let mut plain = create_client(router_addr).await;
+ let req = GetPersonRequest {
+ team_id: 1,
+ person_id: 42,
+ read_options: None,
+ };
+ let resp = plain.get_person(req).await.unwrap().into_inner();
+ assert_eq!(resp.person.unwrap().id, 42);
+}
+
+#[tokio::test]
+async fn async_gzip_large_payload() {
+ let large_props = serde_json::json!({
+ "key1": "x".repeat(10_000),
+ "key2": (0..100).map(|i| format!("item_{}", i)).collect::<Vec<_>>(),
+ "nested": { "deep": "y".repeat(5_000) },
+ });
+ let person = Person {
+ properties: serde_json::to_vec(&large_props).unwrap(),
+ ..create_test_person()
+ };
+ let replica_service = TestReplicaService::with_person(person.clone());
+ let replica_addr = start_test_replica_with_async_gzip(replica_service).await;
+ let router_addr = start_test_router_raw(replica_addr).await;
+
+ let req = GetPersonRequest {
+ team_id: 1,
+ person_id: 42,
+ read_options: None,
+ };
+
+ let (headers, body) = raw_grpc_call_with_gzip_accept(
+ router_addr,
+ "/personhog.service.v1.PersonHogService/GetPerson",
+ &req,
+ )
+ .await;
+
+ assert_eq!(headers.get("grpc-encoding").unwrap(), "gzip");
+ assert_eq!(body[0], 1);
+
+ let decompressed = decompress_grpc_frame(&body);
+ let response = <GetPersonResponse as prost::Message>::decode(decompressed.as_slice()).unwrap();
+ let resp_person = response.person.unwrap();
+ assert_eq!(resp_person.id, 42);
+ assert_eq!(resp_person.properties, person.properties);
+
+ // Compressed should be smaller than the uncompressed protobuf for large payloads
+ let frame_payload_len = body.len() - 5;
+ assert!(
+ frame_payload_len < decompressed.len(),
+ "compressed ({}) should be smaller than decompressed ({})",
+ frame_payload_len,
+ decompressed.len()
+ );
+}
+
+#[tokio::test]
+async fn async_gzip_disabled_flag_skips_compression() {
+ let person = Person {
+ properties: complex_properties(),
+ ..create_test_person()
+ };
+ let replica_service = TestReplicaService::with_person(person.clone());
+ let replica_addr = start_test_replica_with_async_gzip_disabled(replica_service).await;
+ let router_addr = start_test_router_raw(replica_addr).await;
+
+ let req = GetPersonRequest {
+ team_id: 1,
+ person_id: 42,
+ read_options: None,
+ };
+
+ let (headers, body) = raw_grpc_call_with_gzip_accept(
+ router_addr,
+ "/personhog.service.v1.PersonHogService/GetPerson",
+ &req,
+ )
+ .await;
+
+ // No grpc-encoding header — layer is disabled
+ assert!(
+ headers.get("grpc-encoding").is_none(),
+ "disabled layer should not set grpc-encoding"
+ );
+
+ // Frame should be uncompressed (flag=0)
+ assert_eq!(body[0], 0, "compression flag should be 0 when disabled");
+
+ // Payload is raw protobuf, should parse directly
+ let payload = &body[5..];
+ let response = <GetPersonResponse as prost::Message>::decode(payload).unwrap();
+ assert_eq!(response.person.unwrap().id, 42);
+}