: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(capture): add capture-load-gen load generator (#66600)
José Sequeira9a43ed195441
diff --git a/.github/rust-images.yml b/.github/rust-images.ymlindex dc7c8d345323..dc88f9583e90 100644--- a/.github/rust-images.yml+++ b/.github/rust-images.yml@@ -11,6 +11,13 @@dockerfile: ./rust/Dockerfileproject: kshskj225r+# Dev/on-demand load generator for the capture /batch endpoint. Built and+# pushed for use as a Kubernetes Job; not deployed as a standing service, so+# it has no entry in the deploy matrix of rust-docker-build.yml.+- image: capture-load-gen+ dockerfile: ./rust/Dockerfile+ project: kshskj225r+- image: sqlx-migratedockerfile: ./rust/Dockerfile.sqlx-migrateproject: jmsz6gms8gdiff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex be32322e672e..08e963190a01 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -122,6 +122,7 @@ jobs:"assignment-coordination": 11,"batch-import-worker": 124,"capture": 169,+ "capture-load-gen": 25,"capture-logs": 108,"common-alloc": 13,"common-compression": 6,diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex db42f3493f2a..7b02fee9efb6 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -1834,6 +1834,27 @@ dependencies = ["zstd",]+[[package]]+name = "capture-load-gen"+version = "0.1.0"+dependencies = [+ "anyhow",+ "clap",+ "common-types",+ "flate2",+ "governor",+ "hdrhistogram",+ "humantime",+ "rand 0.8.5",+ "reqwest 0.12.28",+ "serde",+ "serde_json",+ "tokio",+ "tracing",+ "tracing-subscriber",+ "uuid",+]+[[package]]name = "capture-logs"version = "0.1.0"@@ -2209,7 +2230,7 @@ version = "3.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"dependencies = [- "windows-sys 0.48.0",+ "windows-sys 0.61.2",][[package]]@@ -3442,7 +3463,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -4379,6 +4400,20 @@ dependencies = ["hashbrown 0.15.5",]+[[package]]+name = "hdrhistogram"+version = "7.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "765c9198f173dd59ce26ff9f95ef0aafd0a0fe01fb9d72841bc5066a4c06511d"+dependencies = [+ "base64 0.21.7",+ "byteorder",+ "crossbeam-channel",+ "flate2",+ "nom",+ "num-traits",+]+[[package]]name = "headers"version = "0.4.1"@@ -4781,7 +4816,7 @@ dependencies = ["libc","percent-encoding","pin-project-lite",- "socket2 0.5.10",+ "socket2 0.6.3","system-configuration 0.7.0","tokio","tower-service",@@ -5187,7 +5222,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"dependencies = ["hermit-abi","libc",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -6477,7 +6512,7 @@ version = "0.50.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"dependencies = [- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -8386,7 +8421,7 @@ dependencies = ["quinn-udp","rustc-hash 2.1.1","rustls 0.23.37",- "socket2 0.5.10",+ "socket2 0.6.3","thiserror 2.0.18","tokio","tracing",@@ -8424,7 +8459,7 @@ dependencies = ["cfg_aliases","libc","once_cell",- "socket2 0.5.10",+ "socket2 0.6.3","tracing","windows-sys 0.59.0",]@@ -9087,7 +9122,7 @@ dependencies = ["errno","libc","linux-raw-sys 0.12.1",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -9189,7 +9224,7 @@ dependencies = ["security-framework 3.7.0","security-framework-sys","webpki-root-certs",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -10651,7 +10686,7 @@ dependencies = ["getrandom 0.4.1","once_cell","rustix 1.1.4",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -11941,7 +11976,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.48.0",+ "windows-sys 0.61.2",][[package]]diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex de0e9ef84afd..7a9299d20b88 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -5,6 +5,7 @@ members = ["property-defs-rs","batch-import-worker","capture",+ "capture-load-gen","capture-logs","cohort-event-shuffler","cohort-stream-processor",@@ -118,7 +119,9 @@ futures = { version = "0.3.29" }futures-timer = "3.0"futures-util = { version = "0.3.31" }governor = { version = "0.5.1", features = ["dashmap"] }+hdrhistogram = "7.5"http = { version = "1.1.0" }+humantime = "2.1"http-body = "1.0"http-body-util = "0.1"httpmock = "0.7.0"diff --git a/rust/capture-load-gen/Cargo.toml b/rust/capture-load-gen/Cargo.tomlnew file mode 100644index 000000000000..2fdb79ea5970--- /dev/null+++ b/rust/capture-load-gen/Cargo.toml@@ -0,0 +1,25 @@+[package]+name = "capture-load-gen"+version = "0.1.0"+edition = "2021"+publish = false++[lints]+workspace = true++[dependencies]+common-types = { path = "../common/types" }+anyhow = { workspace = true }+clap = { workspace = true, features = ["env"] }+flate2 = { workspace = true }+governor = { workspace = true }+hdrhistogram = { workspace = true }+humantime = { workspace = true }+rand = { workspace = true }+reqwest = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+tokio = { workspace = true }+tracing = { workspace = true }+tracing-subscriber = { workspace = true }+uuid = { workspace = true }diff --git a/rust/capture-load-gen/README.md b/rust/capture-load-gen/README.mdnew file mode 100644index 000000000000..306c5070093d--- /dev/null+++ b/rust/capture-load-gen/README.md@@ -0,0 +1,89 @@+# capture-load-gen++High-throughput load generator for the PostHog [capture](../capture) `/batch`+endpoint. Generates synthetic events shaped like real traffic (via+`common_types::RawEvent`) and drives capture at a target rate, sharding cleanly+across pods so a fleet can sum to a single cluster-wide target.++## Modes++Pick exactly one:++- **Rate** — fire at a target events/s for a fixed time:++ ```bash+ capture-load-gen --token phc_xxx --rate 50000 --duration 3m+ ```++- **Count** — send a fixed number of events then stop:++ ```bash+ capture-load-gen --token phc_xxx --count 1000000+ ```++Every request is a `/batch` POST carrying `--batch-size` events, so requests/s =+rate / batch-size. `--rate` and `--count` are expressed in **events**, not+requests.++## Common flags++| Flag | Default | Meaning |+| --- | --- | --- |+| `--endpoint` | `http://localhost:8000` (`$CAPTURE_ENDPOINT`) | Capture base URL; `/batch` is appended |+| `--token` | (`$CAPTURE_TOKEN`) | Project API token, sent as `api_key` |+| `--batch-size` | `100` | Events per `/batch` request |+| `--concurrency` | `32` | In-flight requests |+| `--no-gzip` | off | Disable gzip of the request body |+| `--distinct-ids` | `10000` | Synthetic-user cardinality |+| `--event-name` | `$pageview`, `$autocapture`, `custom_event` | Event names to pick from (repeatable) |+| `--prop-bytes` | `256` | Approx filler bytes per event |+| `--dry-run` | off | Print one sample batch as JSON and exit |++Output is a once-per-second throughput line plus a final summary with+HdrHistogram latency percentiles (p50/p95/p99).++## Sharding++One pod can't saturate capture at high rates, so the workload is split across+shards. Each shard does `1/N` of the rate (or count); the remainder goes to the+lowest indices so the fleet total is exact.++- `--shard-total N` — total shards (defaults to `$SHARD_TOTAL`, else 1)+- `--shard-index I` — this shard, 0-based (defaults to `$JOB_COMPLETION_INDEX`, else 0)++With `--rate 50000 --shard-total 10`, each shard fires at 5000 events/s; ten+shards sum to 50000.++## Deploying as a Kubernetes Indexed Job++A [Kubernetes Indexed Job](https://kubernetes.io/docs/tasks/job/indexed-parallel-processing-static/)+is the natural fit: finite work, off when idle, scales by `parallelism`.+Kubernetes injects `$JOB_COMPLETION_INDEX` per pod, and we wire `$SHARD_TOTAL`+to `completions`, so the binary self-partitions with no per-pod config.++```yaml+spec:+ completionMode: Indexed+ completions: 10 # shard total+ parallelism: 10 # all pods at once+ template:+ spec:+ restartPolicy: Never+ containers:+ - name: capture-load-gen+ image: ghcr.io/posthog/posthog/capture-load-gen:<tag>+ # The shared rust image entrypoint is `sh -c "$BIN"` and does not+ # forward args, so override command to pass flags directly.+ command: ["/usr/local/bin/capture-load-gen"]+ args: ["--rate", "50000", "--duration", "3m"]+ env:+ - name: SHARD_TOTAL+ value: "10"+ - name: CAPTURE_ENDPOINT+ value: "http://capture:8000"+ - name: CAPTURE_TOKEN+ valueFrom: { secretKeyRef: { name: load-gen, key: token } }+```++Scaling to 100k events/s is just bumping `completions`/`parallelism` and+`SHARD_TOTAL` — the args stay the same.diff --git a/rust/capture-load-gen/src/client.rs b/rust/capture-load-gen/src/client.rsnew file mode 100644index 000000000000..84cc2dafb56b--- /dev/null+++ b/rust/capture-load-gen/src/client.rs@@ -0,0 +1,135 @@+use std::io::Write;+use std::time::{Duration, Instant};++use anyhow::{Context, Result};+use common_types::RawEvent;+use flate2::write::GzEncoder;+use flate2::Compression as GzLevel;+use reqwest::header::{CONTENT_ENCODING, CONTENT_TYPE};++use crate::event::BatchPayload;++/// Sends event batches to a capture `/batch` endpoint.+pub struct CaptureClient {+ http: reqwest::Client,+ url: String,+ token: String,+ gzip: bool,+}++/// Outcome of a single batch request.+pub struct SendResult {+ pub latency: Duration,+ pub ok: bool,+}++impl CaptureClient {+ pub fn new(endpoint: &str, token: String, gzip: bool, timeout: Duration) -> Result<Self> {+ let http = reqwest::Client::builder()+ .timeout(timeout)+ .pool_max_idle_per_host(256)+ .build()+ .context("building reqwest client")?;++ Ok(Self {+ http,+ url: format!("{}/batch", endpoint.trim_end_matches('/')),+ token,+ gzip,+ })+ }++ /// Serialize (and optionally gzip) a batch into a request body.+ pub fn encode(&self, events: &[RawEvent]) -> Result<Vec<u8>> {+ let payload = BatchPayload {+ api_key: &self.token,+ batch: events,+ };+ let json = serde_json::to_vec(&payload).context("serializing batch")?;++ if !self.gzip {+ return Ok(json);+ }++ let mut encoder = GzEncoder::new(Vec::new(), GzLevel::fast());+ encoder.write_all(&json).context("gzip write")?;+ encoder.finish().context("gzip finish")+ }++ pub async fn send(&self, body: Vec<u8>) -> SendResult {+ let started = Instant::now();+ let mut req = self+ .http+ .post(&self.url)+ .header(CONTENT_TYPE, "application/json")+ .body(body);+ if self.gzip {+ req = req.header(CONTENT_ENCODING, "gzip");+ }++ let ok = match req.send().await {+ Ok(resp) => {+ let ok = resp.status().is_success();+ // Drain the body so hyper can return the connection to the pool+ // rather than closing it — matters most at high error rates.+ resp.bytes().await.ok();+ ok+ }+ Err(_) => false,+ };++ SendResult {+ latency: started.elapsed(),+ ok,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use flate2::read::GzDecoder;+ use std::io::Read;++ fn sample_events(n: usize) -> Vec<RawEvent> {+ (0..n)+ .map(|i| RawEvent {+ event: format!("e{i}"),+ ..Default::default()+ })+ .collect()+ }++ fn client(gzip: bool) -> CaptureClient {+ CaptureClient::new(+ "http://localhost:0",+ "tok".into(),+ gzip,+ Duration::from_secs(1),+ )+ .unwrap()+ }++ #[test]+ fn encode_plain_is_a_valid_batch_payload() {+ let body = client(false).encode(&sample_events(3)).unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();++ assert_eq!(value["api_key"], "tok");+ let batch: Vec<RawEvent> = serde_json::from_value(value["batch"].clone()).unwrap();+ assert_eq!(batch.len(), 3);+ assert_eq!(batch[0].event, "e0");+ }++ #[test]+ fn encode_gzip_roundtrips_to_the_same_payload() {+ let body = client(true).encode(&sample_events(5)).unwrap();++ let mut json = String::new();+ GzDecoder::new(&body[..]).read_to_string(&mut json).unwrap();+ let value: serde_json::Value = serde_json::from_str(&json).unwrap();++ assert_eq!(value["api_key"], "tok");+ assert_eq!(value["batch"].as_array().unwrap().len(), 5);+ }+}diff --git a/rust/capture-load-gen/src/event.rs b/rust/capture-load-gen/src/event.rsnew file mode 100644index 000000000000..58499f36bdab--- /dev/null+++ b/rust/capture-load-gen/src/event.rs@@ -0,0 +1,117 @@+use std::collections::HashMap;++use common_types::RawEvent;+use rand::Rng;+use serde::Serialize;+use serde_json::Value;+use uuid::Uuid;++/// Generates synthetic [`RawEvent`]s shaped like real capture traffic.+///+/// Distinct IDs are drawn from a fixed pool so person cardinality is+/// controllable, and each event is padded with filler properties to roughly+/// match a target serialized size.+pub struct EventFactory {+ distinct_ids: Vec<String>,+ event_names: Vec<String>,+ filler: String,+}++impl EventFactory {+ pub fn new(distinct_ids: u64, event_names: Vec<String>, prop_bytes: usize) -> Self {+ let distinct_ids = (0..distinct_ids.max(1))+ .map(|i| format!("loadgen-user-{i}"))+ .collect();+ Self {+ distinct_ids,+ event_names,+ filler: "x".repeat(prop_bytes),+ }+ }++ fn next(&self, rng: &mut impl Rng) -> RawEvent {+ let distinct_id = &self.distinct_ids[rng.gen_range(0..self.distinct_ids.len())];+ let event = &self.event_names[rng.gen_range(0..self.event_names.len())];++ let mut properties: HashMap<String, Value> = HashMap::new();+ properties.insert("$lib".to_string(), Value::String("capture-load-gen".into()));+ if !self.filler.is_empty() {+ properties.insert("filler".to_string(), Value::String(self.filler.clone()));+ }++ RawEvent {+ event: event.clone(),+ distinct_id: Some(Value::String(distinct_id.clone())),+ uuid: Some(Uuid::now_v7()),+ properties,+ ..Default::default()+ }+ }++ /// Build a batch of `size` events.+ pub fn batch(&self, size: usize, rng: &mut impl Rng) -> Vec<RawEvent> {+ (0..size).map(|_| self.next(rng)).collect()+ }+}++/// Body of a POST to `/batch`. Capture accepts `api_key` as an alias for the+/// project token at the batch level, with the events under `batch`.+#[derive(Serialize)]+pub struct BatchPayload<'a> {+ pub api_key: &'a str,+ pub batch: &'a [RawEvent],+}++#[cfg(test)]+mod tests {+ use super::*;+ use rand::rngs::StdRng;+ use rand::SeedableRng;++ fn factory() -> EventFactory {+ EventFactory::new(100, vec!["a".into(), "b".into()], 32)+ }++ #[test]+ fn batch_has_requested_size_and_shape() {+ let f = factory();+ let mut rng = StdRng::seed_from_u64(1);+ let batch = f.batch(10, &mut rng);++ assert_eq!(batch.len(), 10);+ for event in &batch {+ assert!(["a", "b"].contains(&event.event.as_str()));+ let distinct_id = event.distinct_id.as_ref().unwrap().as_str().unwrap();+ assert!(distinct_id.starts_with("loadgen-user-"));+ assert_eq!(event.properties["filler"].as_str().unwrap().len(), 32);+ assert_eq!(+ event.properties["$lib"],+ Value::String("capture-load-gen".into())+ );+ }+ }++ #[test]+ fn uuids_are_unique_within_a_batch() {+ let f = factory();+ let mut rng = StdRng::seed_from_u64(2);+ let batch = f.batch(50, &mut rng);++ let mut ids: Vec<_> = batch.iter().map(|e| e.uuid.unwrap()).collect();+ ids.sort();+ ids.dedup();+ assert_eq!(+ ids.len(),+ 50,+ "every generated event should have a unique uuid"+ );+ }++ #[test]+ fn zero_prop_bytes_omits_filler() {+ let f = EventFactory::new(10, vec!["x".into()], 0);+ let mut rng = StdRng::seed_from_u64(3);+ let batch = f.batch(1, &mut rng);+ assert!(!batch[0].properties.contains_key("filler"));+ }+}diff --git a/rust/capture-load-gen/src/main.rs b/rust/capture-load-gen/src/main.rsnew file mode 100644index 000000000000..dbce3ef6fba8--- /dev/null+++ b/rust/capture-load-gen/src/main.rs@@ -0,0 +1,390 @@+mod client;+mod event;+mod stats;++use std::num::NonZeroU32;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Arc;+use std::time::{Duration, Instant};++use anyhow::{bail, Context, Result};+use clap::Parser;+use governor::clock::DefaultClock;+use governor::state::{InMemoryState, NotKeyed};+use governor::{Quota, RateLimiter};+use hdrhistogram::Histogram;+use rand::rngs::StdRng;+use rand::SeedableRng;+use tokio::sync::Notify;++use crate::client::CaptureClient;+use crate::event::{BatchPayload, EventFactory};+use crate::stats::Counters;++type Limiter = RateLimiter<NotKeyed, InMemoryState, DefaultClock>;++/// High-throughput load generator for the PostHog capture `/batch` endpoint.+///+/// Two modes: rate (`--rate` + `--duration`) fires at a target events/s for a+/// fixed time; count (`--count`) sends a fixed number of events then stops.+/// When sharded across pods, the rate/count is divided so the cluster total+/// matches the value you asked for.+#[derive(Parser, Debug)]+#[command(version, about)]+struct Cli {+ /// Capture base URL. The `/batch` path is appended automatically.+ #[arg(+ long,+ env = "CAPTURE_ENDPOINT",+ default_value = "http://localhost:8000"+ )]+ endpoint: String,++ /// PostHog project API token, sent as `api_key` on the batch.+ #[arg(long, env = "CAPTURE_TOKEN")]+ token: String,++ /// Target events per second (rate mode). Requires `--duration`.+ #[arg(long)]+ rate: Option<u32>,++ /// How long to run in rate mode, e.g. "3m", "90s".+ #[arg(long, value_parser = humantime::parse_duration)]+ duration: Option<Duration>,++ /// Total events to send then stop (count mode). Conflicts with `--rate`.+ #[arg(long, conflicts_with = "rate")]+ count: Option<u64>,++ /// Events per `/batch` request.+ #[arg(long, default_value_t = 100)]+ batch_size: usize,++ /// Number of concurrent in-flight requests.+ #[arg(long, default_value_t = 32)]+ concurrency: usize,++ /// Disable gzip of the request body.+ #[arg(long)]+ no_gzip: bool,++ /// Distinct-id cardinality (number of synthetic users).+ #[arg(long, default_value_t = 10_000)]+ distinct_ids: u64,++ /// Event names to pick from (repeatable).+ #[arg(+ long = "event-name",+ default_values_t = ["$pageview".to_string(), "$autocapture".to_string(), "custom_event".to_string()],+ )]+ event_names: Vec<String>,++ /// Approximate filler bytes added to each event's properties.+ #[arg(long, default_value_t = 256)]+ prop_bytes: usize,++ /// Per-request HTTP timeout in seconds.+ #[arg(long, default_value_t = 30)]+ timeout_secs: u64,++ /// This shard's index (0-based). Defaults to $JOB_COMPLETION_INDEX, else 0.+ #[arg(long)]+ shard_index: Option<u64>,++ /// Total number of shards. Defaults to $SHARD_TOTAL, else 1.+ #[arg(long)]+ shard_total: Option<u64>,++ /// Print one sample batch as JSON and exit without sending anything.+ #[arg(long)]+ dry_run: bool,+}++/// Arcs shared by every worker.+#[derive(Clone)]+struct Shared {+ client: Arc<CaptureClient>,+ factory: Arc<EventFactory>,+ counters: Arc<Counters>,+}++enum Mode {+ Rate {+ limiter: Arc<Limiter>,+ batch_n: NonZeroU32,+ deadline: tokio::time::Instant,+ batch_size: usize,+ },+ Count {+ remaining: Arc<AtomicU64>,+ batch_size: usize,+ },+}++/// Split `total` across `shards`, handing the remainder to the lowest indices+/// so the per-shard values sum back to `total`.+fn split(total: u64, shards: u64, index: u64) -> u64 {+ let base = total / shards;+ let rem = total % shards;+ base + u64::from(index < rem)+}++fn resolve_shard(cli: &Cli) -> Result<(u64, u64)> {+ let total = match cli.shard_total {+ Some(t) => t,+ None => std::env::var("SHARD_TOTAL")+ .ok()+ .and_then(|v| v.parse().ok())+ .unwrap_or(1),+ }+ .max(1);++ let index = match cli.shard_index {+ Some(i) => i,+ None => std::env::var("JOB_COMPLETION_INDEX")+ .ok()+ .and_then(|v| v.parse().ok())+ .unwrap_or(0),+ };++ if index >= total {+ bail!("shard index {index} must be < shard total {total}");+ }+ Ok((index, total))+}++/// Claim up to `batch` events from the shared remaining counter (count mode).+fn claim(remaining: &AtomicU64, batch: usize) -> u64 {+ let mut cur = remaining.load(Ordering::Relaxed);+ loop {+ if cur == 0 {+ return 0;+ }+ let take = cur.min(batch as u64);+ match remaining.compare_exchange_weak(cur, cur - take, Ordering::AcqRel, Ordering::Relaxed)+ {+ Ok(_) => return take,+ Err(actual) => cur = actual,+ }+ }+}++async fn run_worker(shared: Shared, mode: Mode) -> Histogram<u64> {+ let mut hist = stats::new_histogram();+ let mut rng = StdRng::from_entropy();++ loop {+ let take = match &mode {+ Mode::Rate {+ limiter,+ batch_n,+ deadline,+ batch_size,+ } => {+ tokio::select! {+ biased;+ _ = tokio::time::sleep_until(*deadline) => break,+ res = limiter.until_n_ready(*batch_n) => {+ if res.is_err() {+ break;+ }+ }+ }+ *batch_size as u64+ }+ Mode::Count {+ remaining,+ batch_size,+ } => {+ let take = claim(remaining, *batch_size);+ if take == 0 {+ break;+ }+ take+ }+ };++ let events = shared.factory.batch(take as usize, &mut rng);+ let body = match shared.client.encode(&events) {+ Ok(body) => body,+ Err(e) => {+ tracing::warn!("encode error: {e:#}");+ shared.counters.record(false, 0);+ continue;+ }+ };++ let result = shared.client.send(body).await;+ hist.saturating_record(result.latency.as_micros() as u64);+ shared.counters.record(result.ok, take);+ }++ hist+}++#[tokio::main]+async fn main() -> Result<()> {+ let cli = Cli::parse();+ tracing_subscriber::fmt()+ .with_env_filter(+ tracing_subscriber::EnvFilter::try_from_default_env()+ .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),+ )+ .init();++ if cli.batch_size == 0 {+ bail!("--batch-size must be > 0");+ }+ if cli.concurrency == 0 {+ bail!("--concurrency must be > 0");+ }++ let factory = Arc::new(EventFactory::new(+ cli.distinct_ids,+ cli.event_names.clone(),+ cli.prop_bytes,+ ));++ if cli.dry_run {+ let mut rng = StdRng::from_entropy();+ let events = factory.batch(cli.batch_size, &mut rng);+ let payload = BatchPayload {+ api_key: &cli.token,+ batch: &events,+ };+ println!("{}", serde_json::to_string_pretty(&payload)?);+ return Ok(());+ }++ let (index, total) = resolve_shard(&cli)?;+ let batch_n = NonZeroU32::new(cli.batch_size as u32).context("batch size too large")?;++ let client = Arc::new(CaptureClient::new(+ &cli.endpoint,+ cli.token.clone(),+ !cli.no_gzip,+ Duration::from_secs(cli.timeout_secs),+ )?);+ let counters = Arc::new(Counters::default());+ let shared = Shared {+ client,+ factory,+ counters: counters.clone(),+ };++ // Validate mode selection up front.+ let duration = match (cli.rate, cli.count) {+ (Some(_), Some(_)) => bail!("--rate and --count are mutually exclusive"),+ (Some(_), None) => match cli.duration {+ Some(d) => Some(d),+ None => bail!("--rate requires --duration"),+ },+ (None, Some(_)) => None,+ (None, None) => bail!("specify either --rate (+ --duration) or --count"),+ };++ // Shared mode state.+ let limiter: Option<Arc<Limiter>> = cli.rate.map(|rate| {+ let local_rate = split(u64::from(rate), total, index).max(1) as u32;+ let burst = local_rate.max(cli.batch_size as u32);+ let quota = Quota::per_second(NonZeroU32::new(local_rate).unwrap())+ .allow_burst(NonZeroU32::new(burst).unwrap());+ Arc::new(RateLimiter::direct(quota))+ });+ let remaining: Option<Arc<AtomicU64>> = cli+ .count+ .map(|count| Arc::new(AtomicU64::new(split(count, total, index))));++ // Nothing to do for this shard (e.g. rate < shard count).+ if cli.rate.is_some() && split(u64::from(cli.rate.unwrap()), total, index) == 0 {+ println!("[load] shard {index}/{total} has no work (rate too low to split)");+ return Ok(());+ }+ if let Some(rem) = &remaining {+ if rem.load(Ordering::Relaxed) == 0 {+ println!("[load] shard {index}/{total} has no work (count too low to split)");+ return Ok(());+ }+ }++ let stop = Arc::new(Notify::new());+ let reporter = tokio::spawn(stats::report_loop(counters.clone(), stop.clone()));++ let started = Instant::now();+ let deadline = duration.map(|d| tokio::time::Instant::now() + d);++ let mut handles = Vec::with_capacity(cli.concurrency);+ for _ in 0..cli.concurrency {+ let mode = match (&limiter, &remaining) {+ (Some(limiter), _) => Mode::Rate {+ limiter: limiter.clone(),+ batch_n,+ deadline: deadline.expect("rate mode has deadline"),+ batch_size: cli.batch_size,+ },+ (None, Some(remaining)) => Mode::Count {+ remaining: remaining.clone(),+ batch_size: cli.batch_size,+ },+ (None, None) => unreachable!("mode validated above"),+ };+ handles.push(tokio::spawn(run_worker(shared.clone(), mode)));+ }++ let mut merged = stats::new_histogram();+ for handle in handles {+ if let Ok(hist) = handle.await {+ merged.add(&hist).ok();+ }+ }++ stop.notify_one();+ reporter.await.ok();++ stats::print_summary(&counters, &merged, started.elapsed());+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn split_divides_evenly() {+ let parts: Vec<u64> = (0..10).map(|i| split(1000, 10, i)).collect();+ assert!(parts.iter().all(|&p| p == 100));+ assert_eq!(parts.iter().sum::<u64>(), 1000);+ }++ #[test]+ fn split_gives_remainder_to_low_indices() {+ let parts: Vec<u64> = (0..10).map(|i| split(1003, 10, i)).collect();+ assert_eq!(+ parts,+ vec![101, 101, 101, 100, 100, 100, 100, 100, 100, 100]+ );+ assert_eq!(parts.iter().sum::<u64>(), 1003);+ }++ #[test]+ fn split_handles_more_shards_than_work() {+ let parts: Vec<u64> = (0..10).map(|i| split(5, 10, i)).collect();+ assert_eq!(parts.iter().sum::<u64>(), 5);+ assert_eq!(parts.iter().filter(|&&p| p == 0).count(), 5);+ }++ #[test]+ fn claim_drains_the_counter_exactly() {+ let remaining = AtomicU64::new(250);+ let mut taken = Vec::new();+ loop {+ let n = claim(&remaining, 100);+ if n == 0 {+ break;+ }+ taken.push(n);+ }+ assert_eq!(taken, vec![100, 100, 50]);+ assert_eq!(remaining.load(Ordering::Relaxed), 0);+ }+}diff --git a/rust/capture-load-gen/src/stats.rs b/rust/capture-load-gen/src/stats.rsnew file mode 100644index 000000000000..826b5eb1b4b9--- /dev/null+++ b/rust/capture-load-gen/src/stats.rs@@ -0,0 +1,93 @@+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Arc;+use std::time::Duration;++use hdrhistogram::Histogram;+use tokio::sync::Notify;++/// Shared, lock-free counters updated on the request hot path.+#[derive(Default)]+pub struct Counters {+ pub requests_ok: AtomicU64,+ pub requests_err: AtomicU64,+ pub events_ok: AtomicU64,+}++impl Counters {+ pub fn record(&self, ok: bool, events: u64) {+ if ok {+ self.requests_ok.fetch_add(1, Ordering::Relaxed);+ self.events_ok.fetch_add(events, Ordering::Relaxed);+ } else {+ self.requests_err.fetch_add(1, Ordering::Relaxed);+ }+ }+}++/// A per-worker latency histogram. Each worker owns one so recording never+/// contends; they are merged once at the end.+pub fn new_histogram() -> Histogram<u64> {+ // 1µs .. 60s range, 3 significant figures. Auto-resizes if exceeded.+ Histogram::new_with_bounds(1, 60_000_000, 3).expect("valid histogram bounds")+}++/// Prints a throughput line once per second until `stop` is notified.+pub async fn report_loop(counters: Arc<Counters>, stop: Arc<Notify>) {+ let mut ticker = tokio::time::interval(Duration::from_secs(1));+ ticker.tick().await; // consume the immediate first tick so we don't print 0 req/s+ let mut prev_ok = 0u64;+ let mut prev_err = 0u64;+ let mut prev_events = 0u64;++ loop {+ tokio::select! {+ _ = stop.notified() => break,+ _ = ticker.tick() => {+ let ok = counters.requests_ok.load(Ordering::Relaxed);+ let err = counters.requests_err.load(Ordering::Relaxed);+ let events = counters.events_ok.load(Ordering::Relaxed);++ println!(+ "[load] {:>8} req/s | {:>10} events/s | ok {ok} err {err}",+ ok + err - prev_ok - prev_err,+ events - prev_events,+ );++ prev_ok = ok;+ prev_err = err;+ prev_events = events;+ }+ }+ }+}++/// Prints the final summary once all workers have stopped.+pub fn print_summary(counters: &Counters, latency: &Histogram<u64>, elapsed: Duration) {+ let ok = counters.requests_ok.load(Ordering::Relaxed);+ let err = counters.requests_err.load(Ordering::Relaxed);+ let events = counters.events_ok.load(Ordering::Relaxed);+ let secs = elapsed.as_secs_f64().max(f64::MIN_POSITIVE);++ println!("\n=== capture-load-gen summary ===");+ println!("duration: {:.1}s", elapsed.as_secs_f64());+ println!("requests ok: {ok}");+ println!("requests err: {err}");+ println!("events ok: {events}");+ println!("avg req/s: {:.0}", (ok + err) as f64 / secs);+ println!("avg events/s: {:.0}", events as f64 / secs);+ if !latency.is_empty() {+ println!(+ "latency p50: {} ms",+ latency.value_at_quantile(0.50) / 1000+ );+ println!(+ "latency p95: {} ms",+ latency.value_at_quantile(0.95) / 1000+ );+ println!(+ "latency p99: {} ms",+ latency.value_at_quantile(0.99) / 1000+ );+ println!("latency max: {} ms", latency.max() / 1000);+ }+}