Function bodies 273 total
makeRequest function · javascript · L232-L263 (32 LOC)acceptance/typescript/test.js
function makeRequest(url, proxyHost, proxyPort) {
return new Promise((resolve, reject) => {
const options = {
hostname: proxyHost,
port: proxyPort,
path: url, // Full URL for proxy request (absolute URI)
method: 'GET',
headers: {
Host: new URL(url).host, // Set Host header for target server
Connection: 'close', // Use close to avoid keep-alive issues
},
};
const req = http.request(options, (res) => {
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
resolve(body);
});
});
req.on('error', reject);
req.setTimeout(10000, () => {
req.destroy();
reject(new Error('Request timeout'));
});
req.end();
});
}encode_deflate function · rust · L88-L93 (6 LOC)e2e/content/src/main.rs
fn encode_deflate(content: &[u8]) -> Vec<u8> {
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
encoder.write_all(content).unwrap();
encoder.finish().unwrap()
}encode_brotli function · rust · L94-L103 (10 LOC)e2e/content/src/main.rs
fn encode_brotli(content: &[u8]) -> Vec<u8> {
let mut compressed = Vec::new();
brotli::BrotliCompress(
&mut std::io::Cursor::new(content),
&mut compressed,
&Default::default(),
).unwrap();
compressed
}start_mock_server function · rust · L361-L543 (183 LOC)e2e/content/src/main.rs
async fn start_mock_server(port: u16) -> Result<()> {
let addr = format!("127.0.0.1:{}", port);
let listener = TcpListener::bind(&addr).await?;
info!("Mock HTTP server listening on http://{}", addr);
loop {
let (stream, _) = listener.accept().await?;
tokio::spawn(async move {
let service = service_fn(handle_request);
if let Err(err) = Builder::new(TokioExecutor::new())
.serve_connection(TokioIo::new(stream), service)
.await
{
error!("Error serving connection: {:?}", err);
}
});
}
}
// Start recording proxy
fn start_recording_proxy(
entry_url: &str,
proxy_port: u16,
inventory_dir: &PathBuf,
) -> Result<Child> {
// Use CARGO_MANIFEST_DIR to get workspace root
let repo_root = Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(Path::parent)
.context("failed to resolve workspace root")?;
// Chstart_recording_proxy function · rust · L384-L482 (99 LOC)e2e/content/src/main.rs
fn start_recording_proxy(
entry_url: &str,
proxy_port: u16,
inventory_dir: &PathBuf,
) -> Result<Child> {
// Use CARGO_MANIFEST_DIR to get workspace root
let repo_root = Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(Path::parent)
.context("failed to resolve workspace root")?;
// Check if binary exists - prefer using binary over cargo run
// This is important because cargo run doesn't properly forward SIGINT to child process
let binary_path = repo_root.join("target/release/http-playback-proxy");
#[cfg(windows)]
let binary_path = binary_path.with_extension("exe");
// Use pre-built binary if in CI or if binary exists
let use_prebuilt = std::env::var("CI").is_ok() || binary_path.exists();
let child = if use_prebuilt {
// CI or Local with binary: Use pre-built binary directly
let binary_path = repo_root.join("target/release/http-playback-proxy");
#[cfg(windows)]
let binwait_for_proxy function · rust · L486-L524 (39 LOC)e2e/content/src/main.rs
async fn wait_for_proxy(port: u16, max_retries: u32) -> Result<()> {
use tokio::net::TcpStream;
use tokio::time::timeout;
for i in 0..max_retries {
// Use short timeout for connection attempt to fail fast
match timeout(
Duration::from_millis(500),
TcpStream::connect(format!("127.0.0.1:{}", port)),
)
.await
{
Ok(Ok(_)) => {
info!(
"Proxy is ready on port {} (took {} seconds)",
port,
i + 1
);
return Ok(());
}
Ok(Err(_)) | Err(_) => {
if i == 0 {
info!("Waiting for proxy to start on port {}...", port);
} else if (i + 1) % 10 == 0 {
info!("Still waiting for proxy... ({}/{} seconds)", i + 1, max_retries);
}
}
}
if i < max_retries - 1 {
sleep(Duratiwait_for_file function · rust · L551-L563 (13 LOC)e2e/content/src/main.rs
async fn wait_for_file(path: &std::path::Path, max_attempts: u32) -> Result<()> {
for attempt in 1..=max_attempts {
if path.exists() {
info!("File found: {:?} (attempt {})", path, attempt);
return Ok(());
}
if attempt < max_attempts {
info!("Waiting for file: {:?} (attempt {}/{})", path, attempt, max_attempts);
sleep(Duration::from_secs(1)).await;
}
}
anyhow::bail!("File not found after {} attempts: {:?}", max_attempts, path)
}Want this analysis on your repo? https://repobility.com/scan/
verify_beautified_content function · rust · L566-L639 (74 LOC)e2e/content/src/main.rs
async fn verify_beautified_content(inventory_dir: &PathBuf) -> Result<()> {
info!("\n--- Verifying Beautified Content ---");
let contents_dir = inventory_dir.join("contents");
if !contents_dir.exists() {
anyhow::bail!("Contents directory not found: {:?}", contents_dir);
}
// Check HTML - wait for file to exist (method is lowercase per generate_file_path_from_url)
let html_path = contents_dir.join("get/http/127.0.0.1/index.html");
wait_for_file(&html_path, 10).await?;
let html_content = fs::read_to_string(&html_path)?;
let html_lines = count_lines(&html_content);
let minified_html_lines = count_lines(MINIFIED_HTML);
info!("HTML:");
info!(" Minified lines: {}", minified_html_lines);
info!(" Beautified lines: {}", html_lines);
info!(" Ratio: {:.2}x", html_lines as f64 / minified_html_lines as f64);
// HTML should have significantly more lines after beautification
if html_lines < minified_html_lines * 2 {
verify_inventory_minify_flags function · rust · L642-L701 (60 LOC)e2e/content/src/main.rs
fn verify_inventory_minify_flags(inventory_dir: &PathBuf) -> Result<()> {
info!("\n--- Verifying Inventory Minify Flags ---");
let inventory_path = inventory_dir.join("index.json");
let inventory_json = fs::read_to_string(&inventory_path)?;
let inventory: Inventory = serde_json::from_str(&inventory_json)?;
info!(
"Verifying inventory with {} resources",
inventory.resources.len()
);
// We expect 3 resources: HTML, CSS, JS
if inventory.resources.len() < 3 {
anyhow::bail!(
"Expected at least 3 resources in inventory, found {}",
inventory.resources.len()
);
}
let mut html_found = false;
let mut css_found = false;
let mut js_found = false;
for resource in &inventory.resources {
info!("Resource: {} {}", resource.method, resource.url);
info!(" minify: {:?}", resource.minify);
// Check if this is one of our test resources
if resource.url.ends_with("verify_charset_in_inventory function · rust · L704-L897 (194 LOC)e2e/content/src/main.rs
fn verify_charset_in_inventory(inventory_dir: &PathBuf) -> Result<()> {
info!("\n--- Verifying Charset Handling in Inventory ---");
let inventory_path = inventory_dir.join("index.json");
let inventory_json = fs::read_to_string(&inventory_path)?;
let inventory: Inventory = serde_json::from_str(&inventory_json)?;
info!("Checking {} resources for charset handling", inventory.resources.len());
for resource in &inventory.resources {
let url = &resource.url;
// Check charset test resources
if url.contains("/charset/") {
info!("\nCharset resource: {}", url);
info!(" contentCharset: {:?}", resource.content_charset);
if url.contains("-shiftjis.") {
if resource.content_charset != Some("Shift_JIS".to_string()) {
anyhow::bail!(
"Shift_JIS resource should have contentCharset=Shift_JIS, got: {:?}",
resource.content_charset
start_playback_proxy function · rust · L900-L964 (65 LOC)e2e/content/src/main.rs
fn start_playback_proxy(proxy_port: u16, inventory_dir: &PathBuf) -> Result<Child> {
let repo_root = Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(Path::parent)
.context("failed to resolve workspace root")?;
// Convert inventory_dir to absolute path to ensure child process can access it
let absolute_inventory_dir = if inventory_dir.is_absolute() {
inventory_dir.clone()
} else {
std::env::current_dir()?.join(inventory_dir)
};
info!("start_playback_proxy: inventory_dir = {:?}", inventory_dir);
info!("start_playback_proxy: absolute_inventory_dir = {:?}", absolute_inventory_dir);
// Check if binary exists - prefer using binary over cargo run
// This is important because cargo run doesn't properly forward SIGINT to child process
let binary_path = repo_root.join("target/release/http-playback-proxy");
#[cfg(windows)]
let binary_path = binary_path.with_extension("exe");
// Use pre-built verify_playback_proxy function · rust · L967-L1147 (181 LOC)e2e/content/src/main.rs
async fn verify_playback_proxy(
inventory_dir: &PathBuf,
playback_proxy_port: u16,
mock_server_host: &str,
mock_server_port: u16,
) -> Result<()> {
info!("\n--- Verifying Playback Charset/Encoding Reproduction ---");
info!("Inventory directory: {:?}", inventory_dir);
info!("Playback proxy port: {}", playback_proxy_port);
// Double-check inventory directory exists before starting playback proxy
info!("Pre-check: inventory_dir exists? {}", inventory_dir.exists());
if inventory_dir.exists() {
info!("Pre-check: inventory_dir is a directory? {}", inventory_dir.is_dir());
info!("Pre-check: inventory_dir path: {:?}", inventory_dir);
// List files
if let Ok(entries) = std::fs::read_dir(inventory_dir) {
for entry in entries {
if let Ok(entry) = entry {
info!(" Pre-check file: {:?}", entry.path());
}
}
}
}
// Start playback proxy
test_scenarios function · rust · L56-L98 (43 LOC)e2e/minimum/src/main.rs
fn test_scenarios() -> Vec<TestScenario> {
vec![
// 500KB scenarios
TestScenario {
name: "500kb-fast".to_string(),
ttfb_ms: 100,
transfer_duration_ms: 200,
file_size: 500 * 1024,
},
TestScenario {
name: "500kb-medium".to_string(),
ttfb_ms: 500,
transfer_duration_ms: 1000,
file_size: 500 * 1024,
},
TestScenario {
name: "500kb-slow".to_string(),
ttfb_ms: 1000,
transfer_duration_ms: 2000,
file_size: 500 * 1024,
},
// 1KB scenarios (longer transfer times to account for system overhead)
TestScenario {
name: "1kb-fast".to_string(),
ttfb_ms: 100,
transfer_duration_ms: 100,
file_size: 1024,
},
TestScenario {
name: "1kb-medium".to_string(),
ttfb_ms: 500,
transfer_duration_ms: 200handle_request function · rust · L101-L172 (72 LOC)e2e/minimum/src/main.rs
async fn handle_request(
req: Request<Incoming>,
scenario: Arc<TestScenario>,
) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
let path = req.uri().path();
info!("Mock server received request for: {}", path);
// Wait for TTFB
sleep(Duration::from_millis(scenario.ttfb_ms)).await;
// After TTFB wait, we immediately return response headers
// This is when the client will measure TTFB
// Calculate chunk size to achieve target transfer duration
let file_size = scenario.file_size;
let chunk_size = if scenario.transfer_duration_ms > 0 {
// Divide into 10 chunks for smooth transfer simulation
file_size / 10
} else {
file_size
};
let num_chunks = if chunk_size > 0 {
(file_size + chunk_size - 1) / chunk_size
} else {
1
};
let delay_per_chunk = if num_chunks > 1 && scenario.transfer_duration_ms > 0 {
scenario.transfer_duration_ms / num_chunks as u64
} else {
start_mock_server function · rust · L175-L315 (141 LOC)e2e/minimum/src/main.rs
async fn start_mock_server(port: u16, scenario: Arc<TestScenario>) -> Result<()> {
let addr = format!("127.0.0.1:{}", port);
let listener = TcpListener::bind(&addr).await?;
info!(
"Mock HTTP server listening on http://{} (scenario: {})",
addr, scenario.name
);
loop {
let (stream, _) = listener.accept().await?;
let scenario = scenario.clone();
tokio::spawn(async move {
let service = service_fn(move |req| {
let scenario = scenario.clone();
handle_request(req, scenario)
});
if let Err(err) = Builder::new(TokioExecutor::new())
.serve_connection(TokioIo::new(stream), service)
.await
{
error!("Error serving connection: {:?}", err);
}
});
}
}
// Start recording proxy
fn start_recording_proxy(
entry_url: &str,
proxy_port: u16,
inventory_dir: &PathBuf,
) -> Result<ChildRepobility · open methodology · https://repobility.com/research/
start_recording_proxy function · rust · L205-L260 (56 LOC)e2e/minimum/src/main.rs
fn start_recording_proxy(
entry_url: &str,
proxy_port: u16,
inventory_dir: &PathBuf,
) -> Result<Child> {
// Use CARGO_MANIFEST_DIR to get workspace root
let repo_root = Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(Path::parent)
.context("failed to resolve workspace root")?;
let manifest_path = repo_root.join("Cargo.toml");
let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
#[cfg(windows)]
let child = {
use std::os::windows::process::CommandExt;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
Command::new(cargo)
.arg("run")
.arg("--release")
.arg("--manifest-path")
.arg(manifest_path)
.arg("--bin")
.arg("http-playback-proxy")
.arg("--")
.arg("recording")
.arg(entry_url)
.arg("--port")
.arg(proxy_port.to_string())
.arg("--istart_playback_proxy function · rust · L263-L289 (27 LOC)e2e/minimum/src/main.rs
fn start_playback_proxy(proxy_port: u16, inventory_dir: &PathBuf) -> Result<Child> {
// Use CARGO_MANIFEST_DIR to get workspace root
let repo_root = Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(Path::parent)
.context("failed to resolve workspace root")?;
let manifest_path = repo_root.join("Cargo.toml");
let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
let child = Command::new(cargo)
.arg("run")
.arg("--release")
.arg("--manifest-path")
.arg(manifest_path)
.arg("--bin")
.arg("http-playback-proxy")
.arg("--")
.arg("playback")
.arg("--port")
.arg(proxy_port.to_string())
.arg("--inventory")
.arg(inventory_dir.to_str().unwrap())
.spawn()?;
Ok(child)
}verify_timing function · rust · L318-L363 (46 LOC)e2e/minimum/src/main.rs
fn verify_timing(
measured: &TimingMeasurement,
expected_ttfb_ms: u64,
expected_total_ms: u64,
tolerance: f64,
) -> Result<()> {
let ttfb_diff_ratio =
((measured.ttfb_ms as f64 - expected_ttfb_ms as f64).abs() / expected_ttfb_ms as f64)
.abs();
let total_diff_ratio =
((measured.total_ms as f64 - expected_total_ms as f64).abs() / expected_total_ms as f64)
.abs();
info!(
" TTFB: measured={}ms, expected={}ms, diff={:.1}%",
measured.ttfb_ms,
expected_ttfb_ms,
ttfb_diff_ratio * 100.0
);
info!(
" Total: measured={}ms, expected={}ms, diff={:.1}%",
measured.total_ms,
expected_total_ms,
total_diff_ratio * 100.0
);
if ttfb_diff_ratio > tolerance {
anyhow::bail!(
"TTFB timing outside tolerance: measured={}ms, expected={}ms, diff={:.1}%",
measured.ttfb_ms,
expected_ttfb_ms,
ttfb_diff_ratio * 1verify_inventory function · rust · L366-L442 (77 LOC)e2e/minimum/src/main.rs
fn verify_inventory(
inventory_dir: &PathBuf,
scenario: &TestScenario,
tolerance: f64,
) -> Result<()> {
let inventory_path = inventory_dir.join("index.json");
let inventory_json = fs::read_to_string(&inventory_path)?;
let inventory: Inventory = serde_json::from_str(&inventory_json)?;
info!(
"Verifying inventory with {} resources",
inventory.resources.len()
);
if inventory.resources.is_empty() {
anyhow::bail!("No resources found in inventory");
}
let resource = &inventory.resources[0];
let expected_ttfb_ms = scenario.ttfb_ms;
let expected_transfer_duration_ms = scenario.transfer_duration_ms;
let recorded_ttfb_ms = resource.ttfb_ms.unwrap_or(0);
// duration_ms already represents the transfer duration
let recorded_transfer_duration_ms = resource.duration_ms.unwrap_or(0);
info!(
"Recording verification for scenario '{}':",
scenario.name
);
info!(
" TTFB: recordmain function · rust · L445-L589 (145 LOC)e2e/minimum/src/main.rs
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
info!("=== Minimum Timing Acceptance Test ===");
info!("Testing files with various sizes, latencies and transfer speeds");
let tolerance = 0.10; // 10% tolerance
// Test all scenarios
for (idx, scenario) in test_scenarios().iter().enumerate() {
info!("\n=== Testing scenario: {} ({} bytes, TTFB={}ms, transfer={}ms) ===",
scenario.name, scenario.file_size, scenario.ttfb_ms, scenario.transfer_duration_ms);
// Use different ports for each scenario to avoid conflicts
let base_port = 17080 + (idx as u16 * 10);
let mock_server_port = base_port;
let recording_proxy_port = base_port + 1;
let playback_proxy_port = base_port + 2;
let scenario = Arc::new(scenario.clone());
// Start mock HTTP server
info!("Starting mock HTTP server on port {}", mock_server_port);
let server_scenario = scenario.clone();
totest_resources function · rust · L56-L111 (56 LOC)e2e/performance/src/main.rs
fn test_resources() -> Vec<TestResource> {
vec![
// Size variations with fixed TTFB and transfer duration
TestResource {
path: "/small-fast".to_string(),
size_bytes: 10 * 1024, // 10KB
ttfb_ms: 100, // 100ms TTFB (fast)
transfer_duration_ms: 50, // 50ms transfer (fast)
},
TestResource {
path: "/medium-fast".to_string(),
size_bytes: 100 * 1024, // 100KB
ttfb_ms: 100, // 100ms TTFB (fast)
transfer_duration_ms: 200, // 200ms transfer (medium)
},
TestResource {
path: "/large-fast".to_string(),
size_bytes: 1024 * 1024, // 1MB
ttfb_ms: 100, // 100ms TTFB (fast)
transfer_duration_ms: 2000, // 2s transfer (slow)
},
// TTFB variations with fixed size and transfer duration
TestResource {
path: "/mediuhandle_request function · rust · L117-L162 (46 LOC)e2e/performance/src/main.rs
async fn handle_request(
req: Request<Incoming>,
resources: Arc<Vec<TestResource>>,
) -> Result<Response<Full<Bytes>>> {
let path = req.uri().path();
info!("Mock server received request for: {}", path);
// Find matching resource
if let Some(resource) = resources.iter().find(|r| r.path == path) {
// Wait for TTFB
sleep(Duration::from_millis(resource.ttfb_ms)).await;
// Generate dummy data
let data = vec![0u8; resource.size_bytes];
// Calculate chunk size to achieve target transfer duration
let chunk_size = if resource.transfer_duration_ms > 0 {
(resource.size_bytes as f64 / (resource.transfer_duration_ms as f64 / 100.0)) as usize
} else {
resource.size_bytes
};
// Simulate chunked transfer
if resource.transfer_duration_ms > 0 && chunk_size < resource.size_bytes {
let chunks = resource.size_bytes / chunk_size;
let delay_per_chunk = restart_recording_proxy function · rust · L192-L284 (93 LOC)e2e/performance/src/main.rs
fn start_recording_proxy(
entry_url: &str,
proxy_port: u16,
inventory_dir: &PathBuf,
) -> Result<Child> {
// Use CARGO_MANIFEST_DIR to get workspace root
let repo_root = Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(Path::parent)
.context("failed to resolve workspace root")?;
// Check if we're in CI environment (binary should be pre-built)
let use_prebuilt = std::env::var("CI").is_ok();
let child = if use_prebuilt {
// CI: Use pre-built binary directly
let binary_path = repo_root.join("target/release/http-playback-proxy");
#[cfg(windows)]
let binary_path = binary_path.with_extension("exe");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
Command::new(binary_path)
.arg("recording")
.arg(entry_url)
.arg("--port")
Repobility · code-quality intelligence platform · https://repobility.com
start_playback_proxy function · rust · L287-L332 (46 LOC)e2e/performance/src/main.rs
fn start_playback_proxy(proxy_port: u16, inventory_dir: &PathBuf) -> Result<Child> {
// Use CARGO_MANIFEST_DIR to get workspace root
let repo_root = Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(Path::parent)
.context("failed to resolve workspace root")?;
// Check if we're in CI environment (binary should be pre-built)
let use_prebuilt = std::env::var("CI").is_ok();
let child = if use_prebuilt {
// CI: Use pre-built binary directly
let binary_path = repo_root.join("target/release/http-playback-proxy");
#[cfg(windows)]
let binary_path = binary_path.with_extension("exe");
Command::new(binary_path)
.arg("playback")
.arg("--port")
.arg(proxy_port.to_string())
.arg("--inventory")
.arg(inventory_dir.to_str().unwrap())
.spawn()?
} else {
// Local: Use cargo run
let manifest_path = repo_root.join("Cargo.towait_for_proxy function · rust · L336-L374 (39 LOC)e2e/performance/src/main.rs
async fn wait_for_proxy(port: u16, max_retries: u32) -> Result<()> {
use tokio::net::TcpStream;
use tokio::time::timeout;
for i in 0..max_retries {
// Use short timeout for connection attempt to fail fast
match timeout(
Duration::from_millis(500),
TcpStream::connect(format!("127.0.0.1:{}", port)),
)
.await
{
Ok(Ok(_)) => {
info!(
"Proxy is ready on port {} (took {} seconds)",
port,
i + 1
);
return Ok(());
}
Ok(Err(_)) | Err(_) => {
if i == 0 {
info!("Waiting for proxy to start on port {}...", port);
} else if (i + 1) % 10 == 0 {
info!("Still waiting for proxy... ({}/{} seconds)", i + 1, max_retries);
}
}
}
if i < max_retries - 1 {
sleep(Durativerify_timing function · rust · L408-L453 (46 LOC)e2e/performance/src/main.rs
fn verify_timing(
measured: &TimingMeasurement,
expected_ttfb_ms: u64,
expected_total_ms: u64,
tolerance: f64,
) -> Result<()> {
let ttfb_diff_ratio = ((measured.ttfb_ms as f64 - expected_ttfb_ms as f64).abs()
/ expected_ttfb_ms as f64)
.abs();
let total_diff_ratio = ((measured.total_ms as f64 - expected_total_ms as f64).abs()
/ expected_total_ms as f64)
.abs();
info!(
"TTFB: measured={}ms, expected={}ms, diff={:.1}%",
measured.ttfb_ms,
expected_ttfb_ms,
ttfb_diff_ratio * 100.0
);
info!(
"Total: measured={}ms, expected={}ms, diff={:.1}%",
measured.total_ms,
expected_total_ms,
total_diff_ratio * 100.0
);
if ttfb_diff_ratio > tolerance {
anyhow::bail!(
"TTFB timing outside tolerance: measured={}ms, expected={}ms, diff={:.1}%",
measured.ttfb_ms,
expected_ttfb_ms,
ttfb_diff_ratio * 100.0
verify_inventory function · rust · L458-L531 (74 LOC)e2e/performance/src/main.rs
fn verify_inventory(
inventory_dir: &PathBuf,
resources: &[TestResource],
tolerance: f64,
) -> Result<()> {
let inventory_path = inventory_dir.join("index.json");
let inventory_json = fs::read_to_string(&inventory_path)?;
let inventory: Inventory = serde_json::from_str(&inventory_json)?;
info!("Verifying inventory with {} resources", inventory.resources.len());
for test_resource in resources {
let found = inventory.resources.iter().find(|r| {
r.url.contains(&test_resource.path)
});
if let Some(resource) = found {
let expected_ttfb_ms = test_resource.ttfb_ms;
let expected_transfer_duration_ms = test_resource.transfer_duration_ms;
let recorded_ttfb_ms = resource.ttfb_ms.unwrap_or(0);
// duration_ms already represents the transfer duration
let recorded_transfer_duration_ms = resource.duration_ms.unwrap_or(0);
info!(
"Resource {}: main function · rust · L534-L587 (54 LOC)e2e/performance/src/main.rs
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
info!("Starting performance acceptance test");
let mock_server_port = 18080;
let recording_proxy_port = 18081;
let playback_proxy_port = 18082;
// Note: Tolerance removed as timing validation is currently disabled (see TODOs below)
let resources = Arc::new(test_resources());
// Start mock HTTP server
info!("Starting mock HTTP server on port {}", mock_server_port);
let server_resources = resources.clone();
let mock_server_handle = tokio::spawn(async move {
if let Err(e) = start_mock_server(mock_server_port, server_resources).await {
error!("Mock server error: {:?}", e);
}
});
// Wait for server to start
sleep(Duration::from_secs(2)).await;
// Create temporary inventory directory
let temp_dir = tempfile::tempdir()?;
let inventory_dir = temp_dir.path().to_path_buf();
info!("Using inventory directory: {:?}", inventory_dirhttpplaybackproxy.getPlatform function · go · L26-L43 (18 LOC)golang/download.go
func getPlatform() string {
platform := runtime.GOOS + "-" + runtime.GOARCH
// Normalize platform strings
switch platform {
case "darwin-amd64":
return "darwin-amd64"
case "darwin-arm64":
return "darwin-arm64"
case "linux-amd64":
return "linux-amd64"
case "linux-arm64":
return "linux-arm64"
case "windows-amd64":
return "windows-amd64"
default:
return platform
}
}httpplaybackproxy.getBinaryName function · go · L46-L51 (6 LOC)golang/download.go
func getBinaryName() string {
if runtime.GOOS == "windows" {
return "http-playback-proxy.exe"
}
return "http-playback-proxy"
}httpplaybackproxy.getCacheDir function · go · L61-L79 (19 LOC)golang/download.go
func getCacheDir() (string, error) {
// Check environment variable first
if cacheDir := os.Getenv("HTTP_PLAYBACK_PROXY_CACHE_DIR"); cacheDir != "" {
return cacheDir, nil
}
// Try XDG_CACHE_HOME
if xdgCache := os.Getenv("XDG_CACHE_HOME"); xdgCache != "" {
return filepath.Join(xdgCache, "http-playback-proxy"), nil
}
// Fall back to user's home directory
homeDir, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("failed to get home directory: %w", err)
}
return filepath.Join(homeDir, ".cache", "http-playback-proxy"), nil
}Want fix-PRs on findings? Install Repobility's GitHub App · github.com/apps/repobility-bot
httpplaybackproxy.getPackageRoot function · go · L85-L107 (23 LOC)golang/download.go
func getPackageRoot() (string, error) {
// Get the location of this source file
_, filename, _, ok := runtime.Caller(0)
if !ok {
return "", fmt.Errorf("failed to get caller information")
}
// This file is in the package root directory
// e.g., /path/to/project/golang/download.go -> /path/to/project/golang
packageDir := filepath.Dir(filename)
// Verify this is the correct package by checking for go.mod
// This prevents accidentally using a different module's directory
goModPath := filepath.Join(packageDir, "go.mod")
if _, err := os.Stat(goModPath); err == nil {
// Found go.mod in the package directory - this is correct
return packageDir, nil
}
// No go.mod found - this is expected in installed packages
// Return the directory anyway (it will contain bin/ subdirectory if binaries are bundled)
return packageDir, nil
}httpplaybackproxy.checkBinaryExists function · go · L114-L134 (21 LOC)golang/download.go
func checkBinaryExists() bool {
// Check package directory first (development only)
packageRoot, err := getPackageRoot()
if err == nil {
binPath := filepath.Join(packageRoot, getBinaryPath())
if _, err := os.Stat(binPath); err == nil {
return true
}
}
// Check cache directory (production)
cacheDir, err := getCacheDir()
if err == nil {
binPath := filepath.Join(cacheDir, getBinaryPath())
if _, err := os.Stat(binPath); err == nil {
return true
}
}
return false
}httpplaybackproxy.downloadBinaryVersion function · go · L147-L251 (105 LOC)golang/download.go
func downloadBinaryVersion(version string) error {
// Try to download to cache directory first
cacheDir, err := getCacheDir()
if err != nil {
return fmt.Errorf("failed to get cache directory: %w", err)
}
// Try cache directory first
targetDir := cacheDir
if err := os.MkdirAll(targetDir, 0755); err != nil {
// If cache directory creation fails, try package directory
packageRoot, projErr := getPackageRoot()
if projErr != nil {
return fmt.Errorf("failed to get target directory: cache=%w, package=%w", err, projErr)
}
targetDir = packageRoot
fmt.Fprintf(os.Stderr, "Warning: Could not create cache directory, using package directory: %v\n", err)
}
platform := getPlatform()
archiveName := fmt.Sprintf("http-playback-proxy-v%s-%s.tar.gz", version, platform)
url := fmt.Sprintf("%s/v%s/%s", baseURL, version, archiveName)
fmt.Printf("Downloading http-playback-proxy binary for %s...\n", platform)
fmt.Printf("URL: %s\n", url)
fmt.Printf("Target: %s\n", targetDir)
/httpplaybackproxy.DownloadBinary function · go · L254-L259 (6 LOC)golang/download.go
func DownloadBinary(version string) error {
if version == "" {
return downloadBinary()
}
return downloadBinaryVersion(version)
}httpplaybackproxy.EnsureBinary function · go · L264-L276 (13 LOC)golang/download.go
func EnsureBinary() error {
if checkBinaryExists() {
return nil
}
fmt.Println("Pre-built binary not found. Attempting to download from GitHub Releases...")
if err := downloadBinary(); err != nil {
return fmt.Errorf("failed to download binary v%s: %w", Version, err)
}
return nil
}httpplaybackproxy.GetBinaryPath function · go · L281-L301 (21 LOC)golang/download.go
func GetBinaryPath() (string, error) {
// Check package directory first (development only)
packageRoot, err := getPackageRoot()
if err == nil {
binPath := filepath.Join(packageRoot, getBinaryPath())
if _, err := os.Stat(binPath); err == nil {
return binPath, nil
}
}
// Check cache directory (production)
cacheDir, err := getCacheDir()
if err == nil {
binPath := filepath.Join(cacheDir, getBinaryPath())
if _, err := os.Stat(binPath); err == nil {
return binPath, nil
}
}
return "", fmt.Errorf("binary not found, please call EnsureBinary() first")
}httpplaybackproxy.getAvailablePort function · go · L53-L61 (9 LOC)golang/proxy.go
func getAvailablePort() (int, error) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return 0, fmt.Errorf("failed to find available port: %w", err)
}
port := listener.Addr().(*net.TCPAddr).Port
listener.Close()
return port, nil
}httpplaybackproxy.waitForPort function · go · L65-L83 (19 LOC)golang/proxy.go
func waitForPort(port int, timeout time.Duration) error {
startTime := time.Now()
delay := 50 * time.Millisecond
for time.Since(startTime) < timeout {
conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", port), time.Second)
if err == nil {
conn.Close()
return nil // Port is open
}
time.Sleep(delay)
delay = time.Duration(float64(delay) * 1.5)
if delay > 500*time.Millisecond {
delay = 500 * time.Millisecond
}
}
return fmt.Errorf("timeout waiting for port %d to become available", port)
}Want this analysis on your repo? https://repobility.com/scan/
httpplaybackproxy.StartRecording function · go · L86-L167 (82 LOC)golang/proxy.go
func StartRecording(opts RecordingOptions) (*Proxy, error) {
if err := EnsureBinary(); err != nil {
return nil, fmt.Errorf("failed to ensure binary: %w", err)
}
binaryPath, err := GetBinaryPath()
if err != nil {
return nil, err
}
// Get an available port if not specified
port := opts.Port
if port == 0 {
port, err = getAvailablePort()
if err != nil {
return nil, err
}
}
deviceType := opts.DeviceType
if deviceType == "" {
deviceType = DeviceTypeMobile
}
inventoryDir := opts.InventoryDir
if inventoryDir == "" {
inventoryDir = "./inventory"
}
// Build command
ctx, cancel := context.WithCancel(context.Background())
args := []string{"recording"}
// Add entry URL if provided
if opts.EntryURL != "" {
args = append(args, opts.EntryURL)
}
// Always specify the port explicitly
args = append(args, "--port", strconv.Itoa(port))
// Add device type
args = append(args, "--device", string(deviceType))
// Add inventory directory
args = append(args, httpplaybackproxy.StartPlayback function · go · L170-L249 (80 LOC)golang/proxy.go
func StartPlayback(opts PlaybackOptions) (*Proxy, error) {
if err := EnsureBinary(); err != nil {
return nil, fmt.Errorf("failed to ensure binary: %w", err)
}
binaryPath, err := GetBinaryPath()
if err != nil {
return nil, err
}
// Get an available port if not specified
port := opts.Port
if port == 0 {
port, err = getAvailablePort()
if err != nil {
return nil, err
}
}
inventoryDir := opts.InventoryDir
if inventoryDir == "" {
inventoryDir = "./inventory"
}
// Verify inventory exists
inventoryPath := GetInventoryPath(inventoryDir)
if _, err := os.Stat(inventoryPath); err != nil {
return nil, fmt.Errorf("inventory file not found at %s: %w", inventoryPath, err)
}
// Build command
ctx, cancel := context.WithCancel(context.Background())
args := []string{"playback"}
// Always specify the port explicitly
args = append(args, "--port", strconv.Itoa(port))
args = append(args, "--inventory", inventoryDir)
if opts.FullThrottle {
args = append(args, "httpplaybackproxy.Proxy.Stop method · go · L253-L266 (14 LOC)golang/proxy.go
func (p *Proxy) Stop() error {
if p.cmd == nil || p.cmd.Process == nil {
return fmt.Errorf("proxy is not running")
}
// Platform-specific process termination (SIGTERM preferred, SIGINT fallback)
if err := stopProcess(p.cmd.Process); err != nil {
// If stop fails, cancel the context
p.cancel()
return fmt.Errorf("failed to stop process: %w", err)
}
return p.waitForExit()
}httpplaybackproxy.Proxy.waitForExit method · go · L269-L303 (35 LOC)golang/proxy.go
func (p *Proxy) waitForExit() error {
done := make(chan error, 1)
go func() {
done <- p.cmd.Wait()
}()
select {
case err := <-done:
if err != nil {
// Exit code 130 is expected for SIGINT, -1 for signals, 0 for success
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode := exitErr.ExitCode()
// Windows: 0xc000013a (STATUS_CONTROL_C_EXIT) = 3221225786 or -1073741510
// Unix: 130 (128 + SIGINT=2) or -1 for signals
if exitCode == 0 || exitCode == 130 || exitCode == -1 ||
exitCode == 3221225786 || exitCode == -1073741510 {
// Normal exit codes for graceful shutdown
return nil
}
}
// For other signal-related errors, also treat as success
if err.Error() == "signal: interrupt" {
return nil
}
return fmt.Errorf("proxy exited with error: %w", err)
}
// Exit code 0 - success
return nil
case <-time.After(10 * time.Second):
// Force kill if graceful shutdown takes too long
p.cancel()
_ = p.cmd.Process.Kill()
rethttpplaybackproxy.Proxy.IsRunning method · go · L306-L313 (8 LOC)golang/proxy.go
func (p *Proxy) IsRunning() bool {
if p.cmd == nil || p.cmd.Process == nil {
return false
}
// Use platform-specific process check (defined in proxy_unix.go and proxy_windows.go)
return isProcessRunning(p.cmd.Process)
}httpplaybackproxy.Proxy.Wait method · go · L316-L321 (6 LOC)golang/proxy.go
func (p *Proxy) Wait() error {
if p.cmd == nil {
return fmt.Errorf("proxy is not running")
}
return p.cmd.Wait()
}httpplaybackproxy.isProcessRunning function · go · L24-L32 (9 LOC)golang/proxy_unix.go
func isProcessRunning(proc *os.Process) bool {
if proc == nil || proc.Pid == -1 {
return false
}
// Signal(0) works reliably on Unix to check process existence
err := proc.Signal(syscall.Signal(0))
return err == nil
}httpplaybackproxy.setProcAttributes function · go · L26-L32 (7 LOC)golang/proxy_windows.go
func setProcAttributes(cmd *exec.Cmd) {
// Create a new process group on Windows
// This is required to send console control events (Ctrl+C/Ctrl+Break)
cmd.SysProcAttr = &syscall.SysProcAttr{
CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP,
}
}Repobility · open methodology · https://repobility.com/research/
httpplaybackproxy.stopProcess function · go · L36-L59 (24 LOC)golang/proxy_windows.go
func stopProcess(proc *os.Process) error {
if proc == nil {
return nil
}
// If the process is already done, that's success
if proc.Pid == -1 {
return nil
}
// Send CTRL_BREAK_EVENT to the process group
// This is the Windows equivalent of SIGTERM for graceful shutdown
r1, _, _ := procGenerateConsoleCtrlEvent.Call(
uintptr(CTRL_BREAK_EVENT),
uintptr(proc.Pid),
)
if r1 == 0 {
// GenerateConsoleCtrlEvent failed, fall back to Kill
return proc.Kill()
}
return nil
}httpplaybackproxy.isProcessRunning function · go · L63-L84 (22 LOC)golang/proxy_windows.go
func isProcessRunning(proc *os.Process) bool {
if proc == nil || proc.Pid == -1 {
return false
}
// Try to open the process with PROCESS_QUERY_INFORMATION access
// If successful, the process exists
handle, _, _ := procOpenProcess.Call(
uintptr(PROCESS_QUERY_INFORMATION),
uintptr(0), // Don't inherit handle
uintptr(proc.Pid),
)
if handle == 0 {
// Failed to open process - it doesn't exist
return false
}
// Close the handle
procCloseHandle.Call(handle)
return true
}httpplaybackproxy.LoadInventory function · go · L56-L68 (13 LOC)golang/types.go
func LoadInventory(inventoryPath string) (*Inventory, error) {
data, err := os.ReadFile(inventoryPath)
if err != nil {
return nil, err
}
var inventory Inventory
if err := json.Unmarshal(data, &inventory); err != nil {
return nil, err
}
return &inventory, nil
}page 1 / 6next ›