: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(personhog): configurable http2 receive windows across services (#109449)
Nick Best874337b2818f
diff --git a/rust/personhog-common/src/client.rs b/rust/personhog-common/src/client.rsindex 15df08451bce..d5bd9e344c14 100644--- a/rust/personhog-common/src/client.rs+++ b/rust/personhog-common/src/client.rs@@ -16,6 +16,7 @@ use tonic::transport::{Channel, Endpoint};use tonic::{Request, Response, Status};use crate::grpc::{code_as_str, CLIENT_NAME_HEADER};+use crate::h2_window::Http2Windows;use personhog_proto::personhog::service::v1::person_hog_service_client::PersonHogServiceClient;use personhog_proto::personhog::types::v1::{@@ -75,13 +76,27 @@ impl RouterClient {router_url: &str,request_timeout: Duration,channels: usize,+ ) -> Result<Self, tonic::transport::Error> {+ Self::with_channels_and_windows(+ router_url,+ request_timeout,+ channels,+ Http2Windows::default(),+ )+ }++ pub fn with_channels_and_windows(+ router_url: &str,+ request_timeout: Duration,+ channels: usize,+ http2_windows: Http2Windows,) -> Result<Self, tonic::transport::Error> {let clients = (0..channels.max(1)).map(|_| {- let channel = Endpoint::from_shared(router_url.to_string())?+ let endpoint = Endpoint::from_shared(router_url.to_string())?.connect_timeout(CONNECT_TIMEOUT)- .tcp_nodelay(true)- .connect_lazy();+ .tcp_nodelay(true);+ let channel = http2_windows.apply_to_endpoint(endpoint).connect_lazy();Ok(PersonHogServiceClient::new(channel))}).collect::<Result<Vec<_>, tonic::transport::Error>>()?;diff --git a/rust/personhog-common/src/h2_window.rs b/rust/personhog-common/src/h2_window.rsnew file mode 100644index 000000000000..b478d13d746d--- /dev/null+++ b/rust/personhog-common/src/h2_window.rs@@ -0,0 +1,109 @@+use std::fmt;+use std::str::FromStr;++use tonic::transport::server::Server;+use tonic::transport::Endpoint;++pub const MAX_WINDOW_BYTES: u32 = (1 << 31) - 1;++#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct WindowSize(Option<u32>);++impl WindowSize {+ pub const DEFAULT: WindowSize = WindowSize(None);++ pub fn bytes(bytes: u32) -> Result<Self, WindowSizeError> {+ if bytes > MAX_WINDOW_BYTES {+ return Err(WindowSizeError::TooLarge(bytes));+ }+ Ok(Self(if bytes == 0 { None } else { Some(bytes) }))+ }++ pub fn get(self) -> Option<u32> {+ self.0+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum WindowSizeError {+ NotANumber(String),+ TooLarge(u32),+}++impl fmt::Display for WindowSizeError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ WindowSizeError::NotANumber(raw) => {+ write!(f, "window size must be a byte count, got {raw:?}")+ }+ WindowSizeError::TooLarge(bytes) => write!(+ f,+ "window size {bytes} exceeds the HTTP/2 maximum of {MAX_WINDOW_BYTES} bytes"+ ),+ }+ }+}++impl std::error::Error for WindowSizeError {}++impl FromStr for WindowSize {+ type Err = WindowSizeError;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ let bytes: u32 = s+ .trim()+ .parse()+ .map_err(|_| WindowSizeError::NotANumber(s.to_string()))?;+ Self::bytes(bytes)+ }+}++#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct Http2Windows {+ pub stream: WindowSize,+ pub connection: WindowSize,+}++impl Http2Windows {+ pub fn new(stream: WindowSize, connection: WindowSize) -> Self {+ Self { stream, connection }+ }++ pub fn is_default(self) -> bool {+ self == Self::default()+ }++ pub fn apply_to_server<L>(self, server: Server<L>) -> Server<L> {+ server+ .initial_stream_window_size(self.stream.get())+ .initial_connection_window_size(self.connection.get())+ }++ pub fn apply_to_endpoint(self, endpoint: Endpoint) -> Endpoint {+ endpoint+ .initial_stream_window_size(self.stream.get())+ .initial_connection_window_size(self.connection.get())+ }+}++#[cfg(test)]+mod tests {+ use rstest::rstest;++ use super::*;++ #[rstest]+ #[case::unset("0", Ok(None))]+ #[case::four_mib("4194304", Ok(Some(4 << 20)))]+ #[case::padded(" 65535 ", Ok(Some(65535)))]+ #[case::max("2147483647", Ok(Some(MAX_WINDOW_BYTES)))]+ #[case::over_max("2147483648", Err(WindowSizeError::TooLarge(1 << 31)))]+ #[case::negative("-1", Err(WindowSizeError::NotANumber("-1".to_string())))]+ #[case::unit_suffix("4MiB", Err(WindowSizeError::NotANumber("4MiB".to_string())))]+ fn window_size_parses_bytes_and_refuses_what_h2_would(+ #[case] raw: &str,+ #[case] expected: Result<Option<u32>, WindowSizeError>,+ ) {+ assert_eq!(raw.parse::<WindowSize>().map(WindowSize::get), expected);+ }+}diff --git a/rust/personhog-common/src/lib.rs b/rust/personhog-common/src/lib.rsindex 274c8ff87e33..3298ea96a87a 100644--- a/rust/personhog-common/src/lib.rs+++ b/rust/personhog-common/src/lib.rs@@ -1,6 +1,7 @@pub mod async_gzip;pub mod client;pub mod grpc;+pub mod h2_window;pub mod metrics;pub mod partitioning;pub mod persons;diff --git a/rust/personhog-identity/src/config.rs b/rust/personhog-identity/src/config.rsindex be476c62c42d..9102ad62270c 100644--- a/rust/personhog-identity/src/config.rs+++ b/rust/personhog-identity/src/config.rs@@ -1,5 +1,6 @@use common_database::PoolConfig;use envconfig::Envconfig;+use personhog_common::h2_window::{Http2Windows, WindowSize};use std::net::SocketAddr;use std::time::Duration;@@ -118,6 +119,12 @@ pub struct Config {#[envconfig(default = "4")]pub router_channels: usize,+ #[envconfig(default = "0")]+ pub router_initial_stream_window_bytes: WindowSize,++ #[envconfig(default = "0")]+ pub router_initial_connection_window_bytes: WindowSize,+/// Per-call timeout for leader-routed property writes (ms).#[envconfig(default = "5000")]pub leader_request_timeout_ms: u64,@@ -138,6 +145,12 @@ pub struct Config {#[envconfig(default = "10")]pub grpc_keepalive_timeout_secs: u64,+ #[envconfig(default = "0")]+ pub grpc_initial_stream_window_bytes: WindowSize,++ #[envconfig(default = "0")]+ pub grpc_initial_connection_window_bytes: WindowSize,+/// Maximum gRPC message size to encode (send), in bytes. Defaults to 128 MiB.#[envconfig(default = "134217728")]pub grpc_max_send_message_size: usize,@@ -353,6 +366,20 @@ impl Config {}}+ pub fn router_http2_windows(&self) -> Http2Windows {+ Http2Windows::new(+ self.router_initial_stream_window_bytes,+ self.router_initial_connection_window_bytes,+ )+ }++ pub fn grpc_http2_windows(&self) -> Http2Windows {+ Http2Windows::new(+ self.grpc_initial_stream_window_bytes,+ self.grpc_initial_connection_window_bytes,+ )+ }+pub fn grpc_max_connection_age(&self) -> Option<Duration> {if self.grpc_max_connection_age_secs == 0 {Nonediff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rsindex 401e628026c2..1424701d4f2d 100644--- a/rust/personhog-identity/src/main.rs+++ b/rust/personhog-identity/src/main.rs@@ -264,10 +264,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {);let property_writer = Arc::new(- RouterClient::with_channels(+ RouterClient::with_channels_and_windows(&config.router_url,config.leader_request_timeout(),config.router_channels,+ config.router_http2_windows(),).expect("Invalid router URL").with_client_name("personhog-identity"),@@ -361,6 +362,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let grpc_addr = config.grpc_address;let keepalive_interval = config.grpc_keepalive_interval();let keepalive_timeout = config.grpc_keepalive_timeout();+ let http2_windows = config.grpc_http2_windows();let max_connection_age = config.grpc_max_connection_age();let max_send = config.grpc_max_send_message_size;let max_recv = config.grpc_max_recv_message_size;@@ -383,9 +385,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {}};let incoming = tracked_tcp_incoming(listener);- let mut server = Server::builder()- .http2_keepalive_interval(keepalive_interval)- .http2_keepalive_timeout(keepalive_timeout);+ let mut server = http2_windows.apply_to_server(+ Server::builder()+ .http2_keepalive_interval(keepalive_interval)+ .http2_keepalive_timeout(keepalive_timeout),+ );if let Some(age) = max_connection_age {server = server.max_connection_age(age);}diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rsindex 8e369129b7bb..ed6af64986e2 100644--- a/rust/personhog-leader/src/config.rs+++ b/rust/personhog-leader/src/config.rs@@ -4,6 +4,7 @@ use std::time::Duration;use common_kafka::config::KafkaConfig;use envconfig::Envconfig;+use personhog_common::h2_window::{Http2Windows, WindowSize};use personhog_coordination::authority::AuthorityClock;use personhog_coordination::pod::{PodConfig, DRAIN_SETUP_BOUND, REVOKE_TIMEOUT, SHUTDOWN_FENCE_BOUND,@@ -77,6 +78,12 @@ pub struct Config {#[envconfig(default = "10")]pub grpc_keepalive_timeout_secs: u64,+ #[envconfig(default = "0")]+ pub grpc_initial_stream_window_bytes: WindowSize,++ #[envconfig(default = "0")]+ pub grpc_initial_connection_window_bytes: WindowSize,+/// Maximum gRPC message size to encode (send), in bytes. Defaults to 128 MiB.#[envconfig(default = "134217728")]pub grpc_max_send_message_size: usize,@@ -779,6 +786,13 @@ impl Config {}}+ pub fn grpc_http2_windows(&self) -> Http2Windows {+ Http2Windows::new(+ self.grpc_initial_stream_window_bytes,+ self.grpc_initial_connection_window_bytes,+ )+ }+pub fn grpc_max_connection_age(&self) -> Option<Duration> {if self.grpc_max_connection_age_secs == 0 {Nonediff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rsindex 306c1321dc76..0bfa72467b27 100644--- a/rust/personhog-leader/src/main.rs+++ b/rust/personhog-leader/src/main.rs@@ -659,6 +659,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let grpc_addr = config.grpc_address;let keepalive_interval = config.grpc_keepalive_interval();let keepalive_timeout = config.grpc_keepalive_timeout();+ let http2_windows = config.grpc_http2_windows();let max_connection_age = config.grpc_max_connection_age();let max_send = config.grpc_max_send_message_size;let max_recv = config.grpc_max_recv_message_size;@@ -700,9 +701,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {}};let incoming = tracked_tcp_incoming(listener);- let mut server = Server::builder()- .http2_keepalive_interval(keepalive_interval)- .http2_keepalive_timeout(keepalive_timeout);+ let mut server = http2_windows.apply_to_server(+ Server::builder()+ .http2_keepalive_interval(keepalive_interval)+ .http2_keepalive_timeout(keepalive_timeout),+ );if let Some(age) = max_connection_age {server = server.max_connection_age(age);}diff --git a/rust/personhog-replica/src/config.rs b/rust/personhog-replica/src/config.rsindex 4cf3892c4c4b..7b8e05142e41 100644--- a/rust/personhog-replica/src/config.rs+++ b/rust/personhog-replica/src/config.rs@@ -1,4 +1,5 @@use envconfig::Envconfig;+use personhog_common::h2_window::{Http2Windows, WindowSize};use std::net::SocketAddr;use std::time::Duration;@@ -87,6 +88,12 @@ pub struct Config {#[envconfig(default = "10")]pub grpc_keepalive_timeout_secs: u64,+ #[envconfig(default = "0")]+ pub grpc_initial_stream_window_bytes: WindowSize,++ #[envconfig(default = "0")]+ pub grpc_initial_connection_window_bytes: WindowSize,+/// Maximum gRPC message size to encode (send), in bytes. Defaults to 128 MiB.#[envconfig(default = "134217728")]pub grpc_max_send_message_size: usize,@@ -184,6 +191,13 @@ impl Config {}}+ pub fn grpc_http2_windows(&self) -> Http2Windows {+ Http2Windows::new(+ self.grpc_initial_stream_window_bytes,+ self.grpc_initial_connection_window_bytes,+ )+ }+pub fn grpc_max_connection_age(&self) -> Option<Duration> {if self.grpc_max_connection_age_secs == 0 {Nonediff --git a/rust/personhog-replica/src/main.rs b/rust/personhog-replica/src/main.rsindex 47473c718687..f6ac6cb02bea 100644--- a/rust/personhog-replica/src/main.rs+++ b/rust/personhog-replica/src/main.rs@@ -310,6 +310,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let grpc_addr = config.grpc_address;let keepalive_interval = config.grpc_keepalive_interval();let keepalive_timeout = config.grpc_keepalive_timeout();+ let http2_windows = config.grpc_http2_windows();let max_connection_age = config.grpc_max_connection_age();let max_send = config.grpc_max_send_message_size;let max_recv = config.grpc_max_recv_message_size;@@ -358,9 +359,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {}};let incoming = tracked_tcp_incoming(listener);- let mut server = Server::builder()- .http2_keepalive_interval(keepalive_interval)- .http2_keepalive_timeout(keepalive_timeout);+ let mut server = http2_windows.apply_to_server(+ Server::builder()+ .http2_keepalive_interval(keepalive_interval)+ .http2_keepalive_timeout(keepalive_timeout),+ );if let Some(age) = max_connection_age {server = server.max_connection_age(age);}diff --git a/rust/personhog-router/src/backend/channel.rs b/rust/personhog-router/src/backend/channel.rsindex d26582da3c96..8ee36843837e 100644--- a/rust/personhog-router/src/backend/channel.rs+++ b/rust/personhog-router/src/backend/channel.rs@@ -5,7 +5,7 @@ use tonic::transport::{Channel, Endpoint};use tracing::info;use crate::backend::discovery::DiscoveryReadiness;-use crate::config::RetryConfig;+use crate::config::{Http2Windows, RetryConfig};/// Channels to a backend whose pods are interchangeable (replica or/// identity), handed out round-robin.@@ -24,6 +24,7 @@ pub struct DnsBackendConfig {pub retry_config: RetryConfig,pub keepalive_interval: Option<Duration>,pub keepalive_timeout: Option<Duration>,+ pub http2_windows: Http2Windows,pub num_channels: usize,}@@ -40,7 +41,7 @@ fn build_dns_endpoint(role: &str, config: &DnsBackendConfig) -> Endpoint {if let Some(timeout) = config.keepalive_timeout {endpoint = endpoint.keep_alive_timeout(timeout);}- endpoint+ config.http2_windows.apply_to_endpoint(endpoint)}impl ChannelBackend {@@ -128,6 +129,7 @@ mod tests {},keepalive_interval: None,keepalive_timeout: None,+ http2_windows: Http2Windows::default(),num_channels: 4,},)diff --git a/rust/personhog-router/src/backend/discovery.rs b/rust/personhog-router/src/backend/discovery.rsindex 44f2c3399785..e3c9be34945d 100644--- a/rust/personhog-router/src/backend/discovery.rs+++ b/rust/personhog-router/src/backend/discovery.rs@@ -10,6 +10,8 @@ use tonic::transport::{Channel, Endpoint};use tower::discover::Change;use tracing::{info, warn};+use crate::config::Http2Windows;+const DISCOVERY_CHANNEL_BUFFER: usize = 64;pub struct EndpointConfig {@@ -17,6 +19,7 @@ pub struct EndpointConfig {pub connect_timeout: Duration,pub keepalive_interval: Option<Duration>,pub keepalive_timeout: Option<Duration>,+ pub http2_windows: Http2Windows,}/// Feeds replica endpoints into a tonic balance channel, driven by the shared@@ -106,6 +109,7 @@ impl EndpointDiscovery {connect_timeout: Duration::from_secs(2),keepalive_interval: None,keepalive_timeout: None,+ http2_windows: Http2Windows::default(),},tx,ready_tx,@@ -182,23 +186,27 @@ impl EndpointDiscovery {}fn build_endpoint(&self, addr: SocketAddr) -> Endpoint {- let mut ep = Endpoint::from_shared(format!("http://{addr}"))- .expect("valid endpoint URL")- .timeout(self.endpoint_config.timeout)- .connect_timeout(self.endpoint_config.connect_timeout)- .tcp_nodelay(true);-- if let Some(interval) = self.endpoint_config.keepalive_interval {- ep = ep- .http2_keep_alive_interval(interval)- .keep_alive_while_idle(true);- }- if let Some(timeout) = self.endpoint_config.keepalive_timeout {- ep = ep.keep_alive_timeout(timeout);- }+ build_discovered_endpoint(addr, &self.endpoint_config)+ }+}- ep+pub fn build_discovered_endpoint(addr: SocketAddr, config: &EndpointConfig) -> Endpoint {+ let mut ep = Endpoint::from_shared(format!("http://{addr}"))+ .expect("valid endpoint URL")+ .timeout(config.timeout)+ .connect_timeout(config.connect_timeout)+ .tcp_nodelay(true);++ if let Some(interval) = config.keepalive_interval {+ ep = ep+ .http2_keep_alive_interval(interval)+ .keep_alive_while_idle(true);+ }+ if let Some(timeout) = config.keepalive_timeout {+ ep = ep.keep_alive_timeout(timeout);}++ config.http2_windows.apply_to_endpoint(ep)}#[cfg(test)]diff --git a/rust/personhog-router/src/backend/leader.rs b/rust/personhog-router/src/backend/leader.rsindex 71742d978b03..b8713cc9aeb1 100644--- a/rust/personhog-router/src/backend/leader.rs+++ b/rust/personhog-router/src/backend/leader.rs@@ -22,6 +22,7 @@ const FENCED_OP_ID_METADATA_KEY: &str = "x-person-fenced-op-id";use personhog_common::partitioning::partition_for_person;use super::stash::{StashDecision, StashTable};+use crate::config::Http2Windows;use crate::grpc_http::{grpc_error_response, grpc_status_code};pub type AddressResolver = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;@@ -117,6 +118,7 @@ pub enum ForwardDecision {pub struct LeaderBackendConfig {pub num_partitions: u32,pub timeout: Duration,+ pub http2_windows: Http2Windows,}/// Backend that routes person writes and strong reads to leader pods@@ -220,11 +222,15 @@ impl LeaderBackend {// timeout: dialing a pod whose IP has been unassigned black-holes// at TCP connect (no RST ever arrives), and the request timeout// only starts once a connection exists.- let channel = Channel::from_shared(address.clone())+ let endpoint = Channel::from_shared(address.clone()).map_err(|e| Status::internal(format!("invalid leader address: {e}")))?.timeout(self.config.timeout).connect_timeout(self.config.timeout)- .tcp_nodelay(true)+ .tcp_nodelay(true);+ let channel = self+ .config+ .http2_windows+ .apply_to_endpoint(endpoint).connect_lazy();self.channels.insert(address, channel.clone());Ok(channel)@@ -525,6 +531,7 @@ mod tests {LeaderBackendConfig {num_partitions,timeout: Duration::from_secs(5),+ http2_windows: Http2Windows::default(),}}diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rsindex 634e87675051..6c3ea822487a 100644--- a/rust/personhog-router/src/config.rs+++ b/rust/personhog-router/src/config.rs@@ -2,6 +2,7 @@ use std::fmt;use std::str::FromStr;use envconfig::Envconfig;+pub use personhog_common::h2_window::{Http2Windows, WindowSize};use personhog_coordination::authority::AuthorityClock;use personhog_coordination::coordinator::REVOKE_TIMEOUT as COORDINATOR_REVOKE_TIMEOUT;use std::net::SocketAddr;@@ -180,6 +181,18 @@ pub struct Config {#[envconfig(default = "10")]pub backend_keepalive_timeout_secs: u64,+ #[envconfig(default = "0")]+ pub grpc_initial_stream_window_bytes: WindowSize,++ #[envconfig(default = "0")]+ pub grpc_initial_connection_window_bytes: WindowSize,++ #[envconfig(default = "0")]+ pub backend_initial_stream_window_bytes: WindowSize,++ #[envconfig(default = "0")]+ pub backend_initial_connection_window_bytes: WindowSize,+/// Maximum request body size the proxy will collect before forwarding,/// in bytes. Oversized requests are rejected with RESOURCE_EXHAUSTED./// Responses stream through unbounded (see `response_size_warn_bytes`).@@ -764,6 +777,20 @@ impl Config {}}+ pub fn grpc_http2_windows(&self) -> Http2Windows {+ Http2Windows::new(+ self.grpc_initial_stream_window_bytes,+ self.grpc_initial_connection_window_bytes,+ )+ }++ pub fn backend_http2_windows(&self) -> Http2Windows {+ Http2Windows::new(+ self.backend_initial_stream_window_bytes,+ self.backend_initial_connection_window_bytes,+ )+ }+pub fn retry_config(&self) -> RetryConfig {RetryConfig {max_retries: self.max_retries,diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rsindex 2091b2df3a35..fff644dbfcf2 100644--- a/rust/personhog-router/src/main.rs+++ b/rust/personhog-router/src/main.rs@@ -296,6 +296,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {LeaderBackendConfig {num_partitions,timeout: config.backend_timeout(),+ http2_windows: config.backend_http2_windows(),},StashTable::with_bounds(config.stash_max_messages_per_partition,@@ -392,6 +393,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let grpc_addr = config.grpc_address;let keepalive_interval = config.grpc_keepalive_interval();let keepalive_timeout = config.grpc_keepalive_timeout();+ let http2_windows = config.grpc_http2_windows();let max_recv = config.grpc_max_recv_message_size;let retry_config = config.retry_config();tracing::info!("Starting gRPC server on {}", grpc_addr);@@ -415,9 +417,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {max_recv,config.response_size_warn_bytes,);- let result = Server::builder()+ let server = Server::builder().http2_keepalive_interval(keepalive_interval)- .http2_keepalive_timeout(keepalive_timeout)+ .http2_keepalive_timeout(keepalive_timeout);+ let result = http2_windows+ .apply_to_server(server).layer(GrpcMetricsLayer::default()).add_service(proxy.clone()).add_service(IdentityProxyService(proxy.clone()))@@ -466,6 +470,7 @@ async fn build_channel_backend(retry_config: config.retry_config(),keepalive_interval: config.backend_keepalive_interval(),keepalive_timeout: config.backend_keepalive_timeout(),+ http2_windows: config.backend_http2_windows(),num_channels: spec.num_channels,},)),@@ -491,6 +496,7 @@ async fn build_channel_backend(connect_timeout: config.backend_connect_timeout(),keepalive_interval: config.backend_keepalive_interval(),keepalive_timeout: config.backend_keepalive_timeout(),+ http2_windows: config.backend_http2_windows(),},discovery_handle.shutdown_token(),);diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rsindex fe36573f9c13..183b957034d8 100644--- a/rust/personhog-router/tests/common/mod.rs+++ b/rust/personhog-router/tests/common/mod.rs@@ -60,7 +60,7 @@ use personhog_proto::personhog::types::v1::{use personhog_router::backend::{ChannelBackend, DnsBackendConfig, LeaderBackend, LeaderBackendConfig, StashTable,};-use personhog_router::config::RetryConfig;+use personhog_router::config::{Http2Windows, RetryConfig};use personhog_router::proxy::{IdentityProxyService, LifecycleProxyService, RawProxyService};use tokio::net::TcpListener;use tokio::sync::RwLock;@@ -948,6 +948,7 @@ fn make_channel_backend(role: &'static str, addr: SocketAddr) -> Arc<ChannelBackretry_config,keepalive_interval: None,keepalive_timeout: None,+ http2_windows: Http2Windows::default(),num_channels: 1,},))@@ -968,6 +969,7 @@ fn make_leader_backend(leader_addr: SocketAddr, num_partitions: u32) -> Arc<LeadLeaderBackendConfig {num_partitions,timeout: Duration::from_secs(5),+ http2_windows: Http2Windows::default(),},StashTable::with_bounds(usize::MAX, usize::MAX),))@@ -1000,6 +1002,7 @@ fn make_dying_leader_backend(leader_addr: SocketAddr, num_partitions: u32) -> ArLeaderBackendConfig {num_partitions,timeout: Duration::from_millis(200),+ http2_windows: Http2Windows::default(),},StashTable::with_bounds(usize::MAX, usize::MAX),))diff --git a/rust/personhog-router/tests/h2_window_wiring.rs b/rust/personhog-router/tests/h2_window_wiring.rsnew file mode 100644index 000000000000..9bce872146fe--- /dev/null+++ b/rust/personhog-router/tests/h2_window_wiring.rs@@ -0,0 +1,254 @@+mod common;++use std::collections::HashMap;+use std::net::SocketAddr;+use std::sync::Arc;+use std::time::Duration;++use common::TestLeaderService;+use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;+use personhog_router::backend::discovery::{build_discovered_endpoint, EndpointConfig};+use personhog_router::backend::{+ ChannelBackend, DnsBackendConfig, LeaderBackend, LeaderBackendConfig, StashTable,+};+use personhog_router::config::{Http2Windows, RetryConfig, WindowSize};+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::{TcpListener, TcpStream};+use tokio::sync::RwLock;+use tonic::transport::{Channel, Server};+use tower::{Service, ServiceExt};++const PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";+const DEFAULT_WINDOW: u32 = 65_535;+const HYPER_SERVER_STREAM_WINDOW: u32 = 1 << 20;+const HYPER_SERVER_CONNECTION_WINDOW: u32 = 1 << 20;+const HYPER_CLIENT_STREAM_WINDOW: u32 = 2 << 20;+const HYPER_CLIENT_CONNECTION_WINDOW: u32 = 5 << 20;+const STREAM_WINDOW: u32 = 4 << 20;+const CONNECTION_WINDOW: u32 = 8 << 20;+const FRAME_SETTINGS: u8 = 0x4;+const FRAME_WINDOW_UPDATE: u8 = 0x8;+const SETTINGS_INITIAL_WINDOW_SIZE: u16 = 0x4;++#[derive(Debug, Default, PartialEq, Eq)]+struct AdvertisedWindows {+ stream: Option<u32>,+ connection_increment: Option<u32>,+}++async fn read_advertised_windows(stream: &mut TcpStream) -> AdvertisedWindows {+ let mut seen = AdvertisedWindows::default();+ let read_all = async {+ while seen.stream.is_none() || seen.connection_increment.is_none() {+ let mut header = [0u8; 9];+ stream.read_exact(&mut header).await.expect("frame header");+ let len = u32::from_be_bytes([0, header[0], header[1], header[2]]) as usize;+ let frame_type = header[3];+ let stream_id =+ u32::from_be_bytes([header[5], header[6], header[7], header[8]]) & 0x7fff_ffff;+ let mut payload = vec![0u8; len];+ stream+ .read_exact(&mut payload)+ .await+ .expect("frame payload");+ match frame_type {+ FRAME_SETTINGS => {+ for entry in payload.chunks_exact(6) {+ let id = u16::from_be_bytes([entry[0], entry[1]]);+ let value = u32::from_be_bytes([entry[2], entry[3], entry[4], entry[5]]);+ if id == SETTINGS_INITIAL_WINDOW_SIZE {+ seen.stream = Some(value);+ }+ }+ }+ FRAME_WINDOW_UPDATE if stream_id == 0 => {+ let increment =+ u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]])+ & 0x7fff_ffff;+ seen.connection_increment = Some(increment);+ }+ _ => {}+ }+ }+ };+ tokio::time::timeout(Duration::from_secs(5), read_all)+ .await+ .expect("peer advertised both windows");+ seen+}++fn settings_frame(entries: &[(u16, u32)]) -> Vec<u8> {+ let len = (entries.len() * 6) as u32;+ let mut frame = vec![+ (len >> 16) as u8,+ (len >> 8) as u8,+ len as u8,+ FRAME_SETTINGS,+ 0,+ 0,+ 0,+ 0,+ 0,+ ];+ for (id, value) in entries {+ frame.extend_from_slice(&id.to_be_bytes());+ frame.extend_from_slice(&value.to_be_bytes());+ }+ frame+}++fn windows(configured: bool) -> Http2Windows {+ if configured {+ Http2Windows::new(+ WindowSize::bytes(STREAM_WINDOW).unwrap(),+ WindowSize::bytes(CONNECTION_WINDOW).unwrap(),+ )+ } else {+ Http2Windows::default()+ }+}++fn expected(configured: bool, library_stream: u32, library_connection: u32) -> AdvertisedWindows {+ let (stream, connection) = if configured {+ (STREAM_WINDOW, CONNECTION_WINDOW)+ } else {+ (library_stream, library_connection)+ };+ AdvertisedWindows {+ stream: Some(stream),+ connection_increment: Some(connection - DEFAULT_WINDOW),+ }+}++fn retry_config() -> RetryConfig {+ RetryConfig {+ max_retries: 0,+ initial_backoff_ms: 1,+ max_backoff_ms: 1,+ }+}++fn dns_channel(addr: SocketAddr, http2_windows: Http2Windows) -> Channel {+ ChannelBackend::new_dns(+ "replica",+ DnsBackendConfig {+ url: format!("http://{addr}"),+ timeout: Duration::from_secs(5),+ retry_config: retry_config(),+ keepalive_interval: None,+ keepalive_timeout: None,+ http2_windows,+ num_channels: 1,+ },+ )+ .channel()+}++fn discovered_channel(addr: SocketAddr, http2_windows: Http2Windows) -> Channel {+ build_discovered_endpoint(+ addr,+ &EndpointConfig {+ timeout: Duration::from_secs(5),+ connect_timeout: Duration::from_secs(5),+ keepalive_interval: None,+ keepalive_timeout: None,+ http2_windows,+ },+ )+ .connect_lazy()+}++async fn leader_channel(addr: SocketAddr, http2_windows: Http2Windows) -> Channel {+ let mut routing = HashMap::new();+ routing.insert(0, "leader-0".to_string());+ let backend = LeaderBackend::new(+ Arc::new(RwLock::new(routing)),+ Arc::new(move |_| Some(format!("http://{addr}"))),+ LeaderBackendConfig {+ num_partitions: 1,+ timeout: Duration::from_secs(5),+ http2_windows,+ },+ StashTable::with_bounds(usize::MAX, usize::MAX),+ );+ backend.resolve_leader_channel(0).await.unwrap()+}++fn drive(mut channel: Channel) {+ tokio::spawn(async move {+ let request = http::Request::builder()+ .method(http::Method::POST)+ .uri("http://unused/svc/Method")+ .version(http::Version::HTTP_2)+ .body(tonic::body::empty_body())+ .unwrap();+ if let Ok(ready) = channel.ready().await {+ drop(ready.call(request).await);+ }+ });+}++#[tokio::test]+async fn every_outbound_channel_builder_advertises_the_configured_windows() {+ for configured in [true, false] {+ for builder in ["dns", "discovery", "leader"] {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let http2_windows = windows(configured);+ let channel = match builder {+ "dns" => dns_channel(addr, http2_windows),+ "discovery" => discovered_channel(addr, http2_windows),+ _ => leader_channel(addr, http2_windows).await,+ };+ drive(channel);++ let (mut peer, _) = listener.accept().await.unwrap();+ let mut preface = [0u8; PREFACE.len()];+ peer.read_exact(&mut preface).await.unwrap();+ assert_eq!(&preface, PREFACE, "{builder}");+ peer.write_all(&settings_frame(&[])).await.unwrap();++ let seen = read_advertised_windows(&mut peer).await;+ assert_eq!(+ seen,+ expected(+ configured,+ HYPER_CLIENT_STREAM_WINDOW,+ HYPER_CLIENT_CONNECTION_WINDOW+ ),+ "{builder} configured={configured}"+ );+ }+ }+}++#[tokio::test]+async fn the_server_advertises_the_configured_windows() {+ for configured in [true, false] {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let mut server = windows(configured).apply_to_server(Server::builder());+ tokio::spawn(async move {+ server+ .add_service(PersonHogLeaderServer::new(TestLeaderService::new()))+ .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))+ .await+ .unwrap();+ });++ let mut peer = TcpStream::connect(addr).await.unwrap();+ peer.write_all(PREFACE).await.unwrap();+ peer.write_all(&settings_frame(&[])).await.unwrap();++ let seen = read_advertised_windows(&mut peer).await;+ assert_eq!(+ seen,+ expected(+ configured,+ HYPER_SERVER_STREAM_WINDOW,+ HYPER_SERVER_CONNECTION_WINDOW+ ),+ "configured={configured}"+ );+ }+}diff --git a/rust/personhog-router/tests/stash_integration.rs b/rust/personhog-router/tests/stash_integration.rsindex 644a65b279f7..614e49c00be5 100644--- a/rust/personhog-router/tests/stash_integration.rs+++ b/rust/personhog-router/tests/stash_integration.rs@@ -21,6 +21,7 @@ use personhog_proto::personhog::types::v1::{Person, SealedSourceSnapshot, UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,};use personhog_router::backend::{LeaderBackend, LeaderBackendConfig, StashTable};+use personhog_router::config::Http2Windows;use personhog_router::stash_handler::RouterStashHandler;use prost::Message;use tokio::sync::RwLock;@@ -65,6 +66,7 @@ async fn make_backend(leader_addr: std::net::SocketAddr, stash: StashTable) -> ALeaderBackendConfig {num_partitions: NUM_PARTITIONS,timeout: Duration::from_secs(5),+ http2_windows: Http2Windows::default(),},stash,))