887 lines
32 KiB
Rust
887 lines
32 KiB
Rust
#![expect(clippy::unwrap_used)]
|
|
|
|
use std::{
|
|
future::{Future, IntoFuture},
|
|
net::SocketAddr,
|
|
sync::{Arc, Mutex},
|
|
time::Instant,
|
|
};
|
|
|
|
use axum::{
|
|
Router,
|
|
response::{Sse, sse::Event},
|
|
routing::post,
|
|
};
|
|
use futures_util::StreamExt;
|
|
use provider_proxy::{Args, CacheMode, run_server};
|
|
use rand::RngExt;
|
|
use reqwest_sse_stream::RequestBuilderExt;
|
|
use serde_json::Value;
|
|
use tokio::{sync::oneshot, task::JoinHandle};
|
|
|
|
async fn start_target_server(
|
|
shutdown_signal: impl Future<Output = ()> + Send + 'static,
|
|
) -> (SocketAddr, JoinHandle<Result<(), std::io::Error>>) {
|
|
let app = Router::new()
|
|
.route(
|
|
"/timestamp-good",
|
|
post(|| async {
|
|
let mut res = http::Response::new(format!(
|
|
"Hello at {:?} {}",
|
|
Instant::now(),
|
|
rand::rng().random::<u32>()
|
|
));
|
|
res.headers_mut().insert(
|
|
"x-my-custom-header",
|
|
http::HeaderValue::from_str(&format!("{}", rand::rng().random::<u32>()))
|
|
.unwrap(),
|
|
);
|
|
res
|
|
}),
|
|
)
|
|
.route(
|
|
"/timestamp-bad",
|
|
post(|| async {
|
|
let mut resp = http::Response::new(format!(
|
|
"Bad request at {:?} {}",
|
|
Instant::now(),
|
|
rand::rng().random::<u32>()
|
|
));
|
|
*resp.status_mut() = http::StatusCode::BAD_REQUEST;
|
|
resp
|
|
}),
|
|
)
|
|
.route(
|
|
"/slow",
|
|
post(|| async {
|
|
Sse::new(async_stream::stream! {
|
|
yield Ok::<_, String>(Event::default().data("Hello"));
|
|
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
|
|
yield Ok(Event::default().data("World"));
|
|
yield Ok(Event::default().data("[DONE]"));
|
|
})
|
|
}),
|
|
)
|
|
.route(
|
|
"/slow-short",
|
|
post(|| async {
|
|
Sse::new(async_stream::stream! {
|
|
yield Ok::<_, String>(Event::default().data("Hello"));
|
|
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
|
yield Ok(Event::default().data("World"));
|
|
yield Ok(Event::default().data("[DONE]"));
|
|
})
|
|
}),
|
|
);
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let addr = listener.local_addr().unwrap();
|
|
// TODO(https://github.com/tensorzero/tensorzero/issues/3983): Audit this callsite
|
|
#[expect(clippy::disallowed_methods)]
|
|
let handle = tokio::spawn(
|
|
axum::serve(listener, app)
|
|
.with_graceful_shutdown(shutdown_signal)
|
|
.into_future(),
|
|
);
|
|
(addr, handle)
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn test_provider_proxy() {
|
|
let (server_started_tx, server_started_rx) = oneshot::channel();
|
|
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
// TODO(https://github.com/tensorzero/tensorzero/issues/3983): Audit this callsite
|
|
#[expect(clippy::disallowed_methods)]
|
|
let _proxy_handle = tokio::spawn(run_server(
|
|
Args {
|
|
cache_path: temp_dir.path().to_path_buf(),
|
|
port: 0,
|
|
sanitize_traceparent: true,
|
|
sanitize_bearer_auth: true,
|
|
sanitize_aws_sigv4: true,
|
|
sanitize_model_headers: true,
|
|
remove_user_agent_non_amazon: false,
|
|
health_port: 0,
|
|
mode: CacheMode::ReadWrite,
|
|
save_request_body: true,
|
|
check_openrouter_headers: true,
|
|
},
|
|
server_started_tx,
|
|
));
|
|
|
|
let (shutdown_tx, shutdown_rx) = oneshot::channel();
|
|
let shutdown_fut = async {
|
|
shutdown_rx.await.unwrap();
|
|
};
|
|
|
|
let (target_server_addr, target_server_handle) = start_target_server(shutdown_fut).await;
|
|
|
|
let proxy_addr = server_started_rx.await.unwrap();
|
|
|
|
let client = reqwest::Client::builder()
|
|
.proxy(reqwest::Proxy::all(format!("http://{proxy_addr}")).unwrap())
|
|
.danger_accept_invalid_certs(true)
|
|
.build()
|
|
.unwrap();
|
|
|
|
let request_body = r#"{"test": "request body for debugging"}"#;
|
|
let first_local_response = client
|
|
.post(format!("http://{target_server_addr}/timestamp-good"))
|
|
.body(request_body)
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(first_local_response.status(), 200);
|
|
let mut first_local_headers = first_local_response.headers().clone();
|
|
assert!(first_local_headers.contains_key("x-my-custom-header"));
|
|
// Remove this header so that we can compare the remaining headers between requests
|
|
let cached = first_local_headers
|
|
.remove("x-tensorzero-provider-proxy-cache")
|
|
.unwrap();
|
|
assert_eq!(cached, "false");
|
|
let first_local_response_body = first_local_response.text().await.unwrap();
|
|
|
|
// Wait for a file to show up on disk and verify the request body is saved on the second line
|
|
let cache_file_path = loop {
|
|
let temp_path = temp_dir.path().to_path_buf();
|
|
let found_file = tokio::task::spawn_blocking(move || {
|
|
let files = std::fs::read_dir(temp_path).unwrap();
|
|
for file in files {
|
|
let file = file.unwrap();
|
|
if file.path().to_string_lossy().contains("127.0.0.1") {
|
|
return Some(file.path());
|
|
}
|
|
}
|
|
None
|
|
})
|
|
.await
|
|
.unwrap();
|
|
if let Some(path) = found_file {
|
|
break path;
|
|
}
|
|
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
|
};
|
|
|
|
// Verify the cache file format: first line is response JSON, second line is serialized request
|
|
let cache_content = std::fs::read_to_string(&cache_file_path).unwrap();
|
|
let mut lines = cache_content.lines();
|
|
let first_line = lines.next().unwrap();
|
|
// Verify first line is valid JSON (the response)
|
|
let _: Value = serde_json::from_str(first_line).unwrap();
|
|
// Verify second line contains the full serialized request (including headers, method, uri, body)
|
|
let second_line = lines.next().unwrap();
|
|
let serialized_request: Value = serde_json::from_str(second_line)
|
|
.expect("Second line should be valid JSON (the serialized request)");
|
|
// The serialized request has a "head" and "body" structure similar to responses
|
|
// head contains: method, uri, headers, version
|
|
let head = &serialized_request["head"];
|
|
// Verify it contains the request body (as a string)
|
|
assert_eq!(
|
|
serialized_request["body"].as_str().unwrap(),
|
|
request_body,
|
|
"Serialized request should contain the request body as a string"
|
|
);
|
|
// Verify it contains request metadata
|
|
assert_eq!(head["method"], "POST");
|
|
assert!(
|
|
head["uri"].as_str().unwrap().contains("/timestamp-good"),
|
|
"URI should contain the endpoint path"
|
|
);
|
|
|
|
let second_local_response = client
|
|
.post(format!("http://{target_server_addr}/timestamp-good"))
|
|
.body(request_body)
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(second_local_response.status(), 200);
|
|
let mut second_local_headers = second_local_response.headers().clone();
|
|
let cached = second_local_headers
|
|
.remove("x-tensorzero-provider-proxy-cache")
|
|
.unwrap();
|
|
assert_eq!(cached, "true");
|
|
assert_eq!(first_local_headers, second_local_headers);
|
|
let second_local_response_body = second_local_response.text().await.unwrap();
|
|
|
|
tracing::info!("first_local_response_body: {}", first_local_response_body);
|
|
tracing::info!("second_local_response_body: {}", second_local_response_body);
|
|
|
|
// The response should be cached, so we should get back the same value
|
|
assert_eq!(first_local_response_body, second_local_response_body);
|
|
|
|
// An error response should not be cached
|
|
let first_bad_response = client
|
|
.post(format!("http://{target_server_addr}/timestamp-bad"))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(first_bad_response.status(), 400);
|
|
let first_bad_response_body = first_bad_response.text().await.unwrap();
|
|
|
|
// Sleep for a little bit, to try to catch a bug where we incorrectly write the bad response to disk
|
|
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
|
|
|
let second_bad_response = client
|
|
.post(format!("http://{target_server_addr}/timestamp-bad"))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(second_bad_response.status(), 400);
|
|
let second_bad_response_body = second_bad_response.text().await.unwrap();
|
|
|
|
assert_ne!(first_bad_response_body, second_bad_response_body);
|
|
|
|
shutdown_tx.send(()).unwrap();
|
|
target_server_handle.await.unwrap().unwrap();
|
|
|
|
// When the target server is down, we should get an error
|
|
let bad_gateway_response = client
|
|
.post(format!("http://{target_server_addr}/timestamp-bad"))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(bad_gateway_response.status(), 502);
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn test_read_old_write_new() {
|
|
let (server_started_tx, server_started_rx) = oneshot::channel();
|
|
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
// TODO(https://github.com/tensorzero/tensorzero/issues/3983): Audit this callsite
|
|
#[expect(clippy::disallowed_methods)]
|
|
let _proxy_handle = tokio::spawn(run_server(
|
|
Args {
|
|
cache_path: temp_dir.path().to_path_buf(),
|
|
port: 0,
|
|
sanitize_traceparent: true,
|
|
sanitize_bearer_auth: true,
|
|
sanitize_aws_sigv4: true,
|
|
health_port: 0,
|
|
sanitize_model_headers: true,
|
|
remove_user_agent_non_amazon: false,
|
|
mode: CacheMode::ReadOldWriteNew,
|
|
save_request_body: true,
|
|
check_openrouter_headers: true,
|
|
},
|
|
server_started_tx,
|
|
));
|
|
|
|
let (shutdown_tx, shutdown_rx) = oneshot::channel();
|
|
let shutdown_fut = async {
|
|
shutdown_rx.await.unwrap();
|
|
};
|
|
|
|
let (target_server_addr, target_server_handle) = start_target_server(shutdown_fut).await;
|
|
|
|
let proxy_addr = server_started_rx.await.unwrap();
|
|
|
|
let client = reqwest::Client::builder()
|
|
.proxy(reqwest::Proxy::all(format!("http://{proxy_addr}")).unwrap())
|
|
.danger_accept_invalid_certs(true)
|
|
.build()
|
|
.unwrap();
|
|
|
|
let first_local_response = client
|
|
.post(format!("http://{target_server_addr}/timestamp-good"))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(first_local_response.status(), 200);
|
|
let mut first_local_headers = first_local_response.headers().clone();
|
|
assert!(first_local_headers.contains_key("x-my-custom-header"));
|
|
// Remove this header so that we can compare the remaining headers between requests
|
|
let cached = first_local_headers
|
|
.remove("x-tensorzero-provider-proxy-cache")
|
|
.unwrap();
|
|
assert_eq!(cached, "false");
|
|
|
|
let file_path = Arc::new(Mutex::new(None));
|
|
let file_mtime = Arc::new(Mutex::new(None));
|
|
|
|
// Wait for a file to show up on disk
|
|
loop {
|
|
let temp_path = temp_dir.path().to_path_buf();
|
|
|
|
let file_path_clone = file_path.clone();
|
|
let file_mtime_clone = file_mtime.clone();
|
|
|
|
let found_file = tokio::task::spawn_blocking(move || {
|
|
let files = std::fs::read_dir(temp_path).unwrap();
|
|
for file in files {
|
|
let file = file.unwrap();
|
|
if file.path().to_string_lossy().contains("127.0.0.1") {
|
|
file_path_clone.lock().unwrap().replace(file.path());
|
|
file_mtime_clone
|
|
.lock()
|
|
.unwrap()
|
|
.replace(file.path().metadata().unwrap().modified().unwrap());
|
|
return true;
|
|
}
|
|
}
|
|
false
|
|
})
|
|
.await
|
|
.unwrap();
|
|
if found_file {
|
|
break;
|
|
}
|
|
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
|
}
|
|
|
|
// The cache file was written after the proxy started, so we should get a cache miss
|
|
let second_local_response = client
|
|
.post(format!("http://{target_server_addr}/timestamp-good"))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(second_local_response.status(), 200);
|
|
let mut second_local_headers = second_local_response.headers().clone();
|
|
let cached = second_local_headers
|
|
.remove("x-tensorzero-provider-proxy-cache")
|
|
.unwrap();
|
|
assert_eq!(cached, "false");
|
|
let second_local_response_body = second_local_response.text().await.unwrap();
|
|
|
|
shutdown_tx.send(()).unwrap();
|
|
target_server_handle.await.unwrap().unwrap();
|
|
|
|
let file_path = file_path.lock().unwrap().as_ref().unwrap().clone();
|
|
let file_mtime = *file_mtime.lock().unwrap().as_ref().unwrap();
|
|
|
|
// Wait for the file to be modified on disk
|
|
loop {
|
|
let new_mtime = file_path.metadata().unwrap().modified().unwrap();
|
|
if new_mtime > file_mtime {
|
|
break;
|
|
}
|
|
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
|
}
|
|
|
|
// Start a new proxy server with the same settings
|
|
let (server_started_tx, server_started_rx) = oneshot::channel();
|
|
|
|
// TODO(https://github.com/tensorzero/tensorzero/issues/3983): Audit this callsite
|
|
#[expect(clippy::disallowed_methods)]
|
|
let _proxy_handle = tokio::spawn(run_server(
|
|
Args {
|
|
cache_path: temp_dir.path().to_path_buf(),
|
|
port: 0,
|
|
sanitize_traceparent: true,
|
|
sanitize_bearer_auth: true,
|
|
sanitize_aws_sigv4: true,
|
|
health_port: 0,
|
|
sanitize_model_headers: true,
|
|
remove_user_agent_non_amazon: false,
|
|
mode: CacheMode::ReadOldWriteNew,
|
|
save_request_body: true,
|
|
check_openrouter_headers: true,
|
|
},
|
|
server_started_tx,
|
|
));
|
|
|
|
let proxy_addr = server_started_rx.await.unwrap();
|
|
|
|
let client = reqwest::Client::builder()
|
|
.proxy(reqwest::Proxy::all(format!("http://{proxy_addr}")).unwrap())
|
|
.danger_accept_invalid_certs(true)
|
|
.build()
|
|
.unwrap();
|
|
|
|
let third_local_response = client
|
|
.post(format!("http://{target_server_addr}/timestamp-good"))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
|
|
// We should now get a cache hit, because the cache file was written before the proxy started
|
|
assert_eq!(third_local_response.status(), 200);
|
|
let mut third_local_headers = third_local_response.headers().clone();
|
|
let cached = third_local_headers
|
|
.remove("x-tensorzero-provider-proxy-cache")
|
|
.unwrap();
|
|
assert_eq!(cached, "true");
|
|
let third_local_response_body = third_local_response.text().await.unwrap();
|
|
// We should use the second response body (from the original run of provider-proxy), which
|
|
// should have overwritten the first response body on disk.
|
|
assert_eq!(second_local_response_body, third_local_response_body);
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn test_dropped_stream_body() {
|
|
let (server_started_tx, server_started_rx) = oneshot::channel();
|
|
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
// TODO(https://github.com/tensorzero/tensorzero/issues/3983): Audit this callsite
|
|
#[expect(clippy::disallowed_methods)]
|
|
let _proxy_handle = tokio::spawn(run_server(
|
|
Args {
|
|
cache_path: temp_dir.path().to_path_buf(),
|
|
port: 0,
|
|
sanitize_traceparent: true,
|
|
sanitize_bearer_auth: true,
|
|
sanitize_aws_sigv4: true,
|
|
health_port: 0,
|
|
sanitize_model_headers: true,
|
|
remove_user_agent_non_amazon: false,
|
|
mode: CacheMode::ReadOldWriteNew,
|
|
save_request_body: true,
|
|
check_openrouter_headers: true,
|
|
},
|
|
server_started_tx,
|
|
));
|
|
|
|
let (_shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
|
|
let shutdown_fut = async {
|
|
shutdown_rx.await.unwrap();
|
|
};
|
|
|
|
let proxy_addr = server_started_rx.await.unwrap();
|
|
|
|
let (target_server_addr, _target_server_handle) = start_target_server(shutdown_fut).await;
|
|
|
|
{
|
|
let good_client = reqwest::Client::builder()
|
|
.proxy(reqwest::Proxy::all(format!("http://{proxy_addr}")).unwrap())
|
|
.danger_accept_invalid_certs(true)
|
|
.build()
|
|
.unwrap();
|
|
|
|
let good_stream = good_client
|
|
.post(format!("http://{target_server_addr}/slow"))
|
|
.eventsource()
|
|
.await
|
|
.unwrap();
|
|
let mut good_stream = std::pin::pin!(good_stream);
|
|
// Read the entire stream, so that we're sure that provider-proxy will write the file to disk
|
|
while let Some(event) = good_stream.next().await {
|
|
match event {
|
|
Err(e) => panic!("Unexpected error: {e:?}"),
|
|
Ok(_) => continue,
|
|
}
|
|
}
|
|
}
|
|
|
|
// Check that the file is on disk
|
|
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
|
let mut files = std::fs::read_dir(temp_dir.path())
|
|
.unwrap()
|
|
.collect::<Vec<_>>();
|
|
assert!(files.len() == 1);
|
|
let file = files.pop().unwrap().unwrap();
|
|
let file_content = std::fs::read_to_string(file.path()).unwrap();
|
|
let mut lines = file_content.lines();
|
|
// First line is the response JSON
|
|
let first_line = lines.next().unwrap();
|
|
let file_json = serde_json::from_str::<Value>(first_line).unwrap();
|
|
assert_eq!(
|
|
file_json["body"],
|
|
"data: Hello\n\ndata: World\n\ndata: [DONE]\n\n"
|
|
);
|
|
// Second line is the request body (for debugging) - may be empty for POST without body
|
|
let _second_line = lines.next();
|
|
|
|
// Now, make the same request, but drop the stream (due to a timeout) before it's done
|
|
|
|
let client = reqwest::Client::builder()
|
|
.proxy(reqwest::Proxy::all(format!("http://{proxy_addr}")).unwrap())
|
|
.danger_accept_invalid_certs(true)
|
|
.timeout(std::time::Duration::from_secs(5))
|
|
.build()
|
|
.unwrap();
|
|
|
|
let first_stream = client
|
|
.post(format!("http://{target_server_addr}/slow"))
|
|
.eventsource()
|
|
.await
|
|
.unwrap();
|
|
let mut first_stream = std::pin::pin!(first_stream);
|
|
|
|
let open_message = first_stream.next().await.unwrap().unwrap();
|
|
assert_eq!(open_message, reqwest_sse_stream::Event::Open);
|
|
|
|
let first_event = first_stream.next().await.unwrap().unwrap();
|
|
assert_eq!(
|
|
first_event,
|
|
reqwest_sse_stream::Event::Message(reqwest_sse_stream::MessageEvent {
|
|
event: String::new(),
|
|
data: "Hello".to_string(),
|
|
id: String::new(),
|
|
})
|
|
);
|
|
|
|
// We should get a timeout
|
|
let err = first_stream.next().await.unwrap().unwrap_err();
|
|
assert!(
|
|
format!("{err:?}").contains("TimedOut"),
|
|
"Unexpected error: {err:?}"
|
|
);
|
|
|
|
// first_stream gets dropped here (at end of scope)
|
|
// Nothing should be on disk
|
|
// The previous cache file should have been *deleted* at the start of the second request,
|
|
// and no new file should have been written (because the stream was dropped before it was done)
|
|
let files = std::fs::read_dir(temp_dir.path()).unwrap();
|
|
assert!(files.count() == 0);
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn test_read_only_require_hit() {
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
|
|
// Phase 1: Populate the cache using a ReadWrite proxy
|
|
let (server_started_tx, server_started_rx) = oneshot::channel();
|
|
// We don't care about shutdown handling in this test
|
|
#[expect(clippy::disallowed_methods)]
|
|
let _proxy_handle = tokio::spawn(run_server(
|
|
Args {
|
|
cache_path: temp_dir.path().to_path_buf(),
|
|
port: 0,
|
|
sanitize_traceparent: true,
|
|
sanitize_bearer_auth: true,
|
|
sanitize_aws_sigv4: true,
|
|
health_port: 0,
|
|
sanitize_model_headers: true,
|
|
remove_user_agent_non_amazon: false,
|
|
mode: CacheMode::ReadWrite,
|
|
save_request_body: true,
|
|
check_openrouter_headers: true,
|
|
},
|
|
server_started_tx,
|
|
));
|
|
|
|
let (shutdown_tx, shutdown_rx) = oneshot::channel();
|
|
let shutdown_fut = async {
|
|
shutdown_rx.await.unwrap();
|
|
};
|
|
|
|
let (target_server_addr, target_server_handle) = start_target_server(shutdown_fut).await;
|
|
|
|
let proxy_addr = server_started_rx.await.unwrap();
|
|
|
|
let client = reqwest::Client::builder()
|
|
.proxy(reqwest::Proxy::all(format!("http://{proxy_addr}")).unwrap())
|
|
.danger_accept_invalid_certs(true)
|
|
.build()
|
|
.unwrap();
|
|
|
|
let request_body = r#"{"test": "read_only_require_hit"}"#;
|
|
let first_response = client
|
|
.post(format!("http://{target_server_addr}/timestamp-good"))
|
|
.body(request_body)
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(first_response.status(), 200);
|
|
let cached = first_response
|
|
.headers()
|
|
.get("x-tensorzero-provider-proxy-cache")
|
|
.unwrap();
|
|
assert_eq!(cached, "false");
|
|
let first_response_body = first_response.text().await.unwrap();
|
|
|
|
// Wait for the cache file to be written to disk
|
|
loop {
|
|
let temp_path = temp_dir.path().to_path_buf();
|
|
let found = tokio::task::spawn_blocking(move || {
|
|
std::fs::read_dir(temp_path)
|
|
.unwrap()
|
|
.any(|f| f.unwrap().path().to_string_lossy().contains("127.0.0.1"))
|
|
})
|
|
.await
|
|
.unwrap();
|
|
if found {
|
|
break;
|
|
}
|
|
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
|
}
|
|
|
|
// Phase 2: Start a ReadOnlyRequireHit proxy with the same cache directory
|
|
let (server_started_tx, server_started_rx) = oneshot::channel();
|
|
// We don't care about shutdown handling in this test
|
|
#[expect(clippy::disallowed_methods)]
|
|
let _proxy_handle2 = tokio::spawn(run_server(
|
|
Args {
|
|
cache_path: temp_dir.path().to_path_buf(),
|
|
port: 0,
|
|
sanitize_traceparent: true,
|
|
sanitize_bearer_auth: true,
|
|
sanitize_aws_sigv4: true,
|
|
health_port: 0,
|
|
sanitize_model_headers: true,
|
|
remove_user_agent_non_amazon: false,
|
|
mode: CacheMode::ReadOnlyRequireHit,
|
|
save_request_body: true,
|
|
check_openrouter_headers: true,
|
|
},
|
|
server_started_tx,
|
|
));
|
|
|
|
let proxy_addr2 = server_started_rx.await.unwrap();
|
|
|
|
let client2 = reqwest::Client::builder()
|
|
.proxy(reqwest::Proxy::all(format!("http://{proxy_addr2}")).unwrap())
|
|
.danger_accept_invalid_certs(true)
|
|
.build()
|
|
.unwrap();
|
|
|
|
// A request that hits the cache should succeed
|
|
let hit_response = client2
|
|
.post(format!("http://{target_server_addr}/timestamp-good"))
|
|
.body(request_body)
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(hit_response.status(), 200);
|
|
let cached = hit_response
|
|
.headers()
|
|
.get("x-tensorzero-provider-proxy-cache")
|
|
.unwrap();
|
|
assert_eq!(cached, "true");
|
|
let hit_response_body = hit_response.text().await.unwrap();
|
|
assert_eq!(first_response_body, hit_response_body);
|
|
|
|
// A request to a fixed dummy address that misses the cache should return a 502.
|
|
// We use a fixed address so the hash (and thus the error message) is deterministic.
|
|
let miss_response = client2
|
|
.post("http://127.0.0.1:99/timestamp-good")
|
|
.body(r#"{"test": "different body causes cache miss"}"#)
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(miss_response.status(), 502);
|
|
let miss_body = miss_response.text().await.unwrap();
|
|
let temp_dir_str = temp_dir.path().to_string_lossy();
|
|
assert_eq!(
|
|
miss_body,
|
|
format!(
|
|
"provider-proxy: Cache miss in ReadOnlyRequireHit mode: {temp_dir_str}/127.0.0.1-956f127f4ff98a5480c095dba545cef89dda20a6a3f4b9fd147abdee5d7db4ff"
|
|
)
|
|
);
|
|
|
|
shutdown_tx.send(()).unwrap();
|
|
target_server_handle.await.unwrap().unwrap();
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn test_stream_body() {
|
|
let (server_started_tx, server_started_rx) = oneshot::channel();
|
|
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
// TODO(https://github.com/tensorzero/tensorzero/issues/3983): Audit this callsite
|
|
#[expect(clippy::disallowed_methods)]
|
|
let _proxy_handle = tokio::spawn(run_server(
|
|
Args {
|
|
cache_path: temp_dir.path().to_path_buf(),
|
|
port: 0,
|
|
sanitize_traceparent: true,
|
|
sanitize_bearer_auth: true,
|
|
sanitize_aws_sigv4: true,
|
|
health_port: 0,
|
|
sanitize_model_headers: true,
|
|
remove_user_agent_non_amazon: false,
|
|
mode: CacheMode::ReadOldWriteNew,
|
|
save_request_body: true,
|
|
check_openrouter_headers: true,
|
|
},
|
|
server_started_tx,
|
|
));
|
|
|
|
let (_shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
|
|
let shutdown_fut = async {
|
|
shutdown_rx.await.unwrap();
|
|
};
|
|
|
|
let (target_server_addr, _target_server_handle) = start_target_server(shutdown_fut).await;
|
|
|
|
let proxy_addr = server_started_rx.await.unwrap();
|
|
|
|
let client = reqwest::Client::builder()
|
|
.proxy(reqwest::Proxy::all(format!("http://{proxy_addr}")).unwrap())
|
|
.danger_accept_invalid_certs(true)
|
|
.build()
|
|
.unwrap();
|
|
|
|
let second_stream = client
|
|
.post(format!("http://{target_server_addr}/slow"))
|
|
.eventsource()
|
|
.await
|
|
.unwrap();
|
|
let mut second_stream = std::pin::pin!(second_stream);
|
|
|
|
while let Some(event) = second_stream.next().await {
|
|
let event = event.unwrap();
|
|
if let reqwest_sse_stream::Event::Message(event) = event
|
|
&& event.data == "[DONE]"
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
|
|
|
// We should see a file on disk
|
|
let files = std::fs::read_dir(temp_dir.path()).unwrap();
|
|
let files = files.collect::<Vec<_>>();
|
|
assert!(files.len() == 1);
|
|
let file = files[0].as_ref().unwrap();
|
|
let file_content = std::fs::read_to_string(file.path()).unwrap();
|
|
let mut lines = file_content.lines();
|
|
// First line is the response JSON
|
|
let first_line = lines.next().unwrap();
|
|
let file_json = serde_json::from_str::<Value>(first_line).unwrap();
|
|
assert_eq!(
|
|
file_json["body"],
|
|
"data: Hello\n\ndata: World\n\ndata: [DONE]\n\n"
|
|
);
|
|
// Second line is the request body (for debugging) - may be empty for POST without body
|
|
let _second_line = lines.next();
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn test_skip_write_when_newer_file_exists() {
|
|
// Verify that if a concurrent run wrote a newer file at the cache path after our
|
|
// request started, the in-flight request skips its own write and leaves the newer
|
|
// file untouched.
|
|
let (server_started_tx, server_started_rx) = oneshot::channel();
|
|
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
// TODO(https://github.com/tensorzero/tensorzero/issues/3983): Audit this callsite
|
|
#[expect(clippy::disallowed_methods)]
|
|
let _proxy_handle = tokio::spawn(run_server(
|
|
Args {
|
|
cache_path: temp_dir.path().to_path_buf(),
|
|
port: 0,
|
|
sanitize_traceparent: true,
|
|
sanitize_bearer_auth: true,
|
|
sanitize_aws_sigv4: true,
|
|
health_port: 0,
|
|
sanitize_model_headers: true,
|
|
remove_user_agent_non_amazon: false,
|
|
mode: CacheMode::ReadWrite,
|
|
save_request_body: true,
|
|
check_openrouter_headers: true,
|
|
},
|
|
server_started_tx,
|
|
));
|
|
|
|
let (_shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
|
|
let shutdown_fut = async {
|
|
shutdown_rx.await.unwrap();
|
|
};
|
|
|
|
let (target_server_addr, _target_server_handle) = start_target_server(shutdown_fut).await;
|
|
|
|
let proxy_addr = server_started_rx.await.unwrap();
|
|
|
|
let client = reqwest::Client::builder()
|
|
.proxy(reqwest::Proxy::all(format!("http://{proxy_addr}")).unwrap())
|
|
.danger_accept_invalid_certs(true)
|
|
.build()
|
|
.unwrap();
|
|
|
|
// Warmup: make a request so the cache file is written and we learn its path.
|
|
let request_body = r#"{"test": "skip_write_when_newer_file_exists"}"#;
|
|
let warmup_stream = client
|
|
.post(format!("http://{target_server_addr}/slow-short"))
|
|
.body(request_body)
|
|
.eventsource()
|
|
.await
|
|
.unwrap();
|
|
let mut warmup_stream = std::pin::pin!(warmup_stream);
|
|
while let Some(event) = warmup_stream.next().await {
|
|
let event = event.unwrap();
|
|
if let reqwest_sse_stream::Event::Message(event) = event
|
|
&& event.data == "[DONE]"
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Wait for save_cache_body to finish writing the file.
|
|
let cache_file_path = loop {
|
|
let temp_path = temp_dir.path().to_path_buf();
|
|
let found_file = tokio::task::spawn_blocking(move || {
|
|
std::fs::read_dir(temp_path)
|
|
.unwrap()
|
|
.filter_map(|f| f.ok())
|
|
.find(|f| f.path().to_string_lossy().contains("127.0.0.1"))
|
|
.map(|f| f.path())
|
|
})
|
|
.await
|
|
.unwrap();
|
|
if let Some(path) = found_file {
|
|
break path;
|
|
}
|
|
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
|
};
|
|
|
|
// Delete the file so the next identical request is a cache miss and will try to write.
|
|
std::fs::remove_file(&cache_file_path).unwrap();
|
|
|
|
// Start a second request. While its upstream is still sleeping, we will drop in a
|
|
// "newer" file at the cache path. When save_cache_body runs, it should detect the
|
|
// newer mtime and skip the write.
|
|
let second_stream = client
|
|
.post(format!("http://{target_server_addr}/slow-short"))
|
|
.body(request_body)
|
|
.eventsource()
|
|
.await
|
|
.unwrap();
|
|
let mut second_stream = std::pin::pin!(second_stream);
|
|
|
|
// Consume the Open + "Hello" events so we know request_start_time has been captured
|
|
// inside check_cache and the upstream /slow-short is now sleeping.
|
|
let open = second_stream.next().await.unwrap().unwrap();
|
|
assert_eq!(open, reqwest_sse_stream::Event::Open);
|
|
let hello = second_stream.next().await.unwrap().unwrap();
|
|
assert_eq!(
|
|
hello,
|
|
reqwest_sse_stream::Event::Message(reqwest_sse_stream::MessageEvent {
|
|
event: String::new(),
|
|
data: "Hello".to_string(),
|
|
id: String::new(),
|
|
})
|
|
);
|
|
|
|
// Sleep briefly so the manual file's mtime is strictly after request_start_time,
|
|
// regardless of filesystem/clock resolution.
|
|
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
|
|
|
let concurrent_content = "CONCURRENT_RUN_WROTE_THIS";
|
|
std::fs::write(&cache_file_path, concurrent_content).unwrap();
|
|
|
|
// Finish consuming the stream so the proxy receives the full upstream body and
|
|
// fires the save_cache_body callback.
|
|
while let Some(event) = second_stream.next().await {
|
|
let event = event.unwrap();
|
|
if let reqwest_sse_stream::Event::Message(event) = event
|
|
&& event.data == "[DONE]"
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Give save_cache_body a chance to run.
|
|
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
|
|
|
// The cache file should still contain the manually-written "concurrent run" content,
|
|
// because save_cache_body saw the newer mtime and skipped its own rename.
|
|
let final_content = std::fs::read_to_string(&cache_file_path).unwrap();
|
|
assert_eq!(
|
|
final_content, concurrent_content,
|
|
"save_cache_body should have skipped the write because a newer file was present"
|
|
);
|
|
|
|
// Sanity check: no leftover NamedTempFile tempfiles should be sitting in the dir.
|
|
let files: Vec<_> = std::fs::read_dir(temp_dir.path())
|
|
.unwrap()
|
|
.map(|f| f.unwrap().path())
|
|
.collect();
|
|
assert_eq!(
|
|
files.len(),
|
|
1,
|
|
"expected only the cache file, got: {files:?}"
|
|
);
|
|
}
|