-
Notifications
You must be signed in to change notification settings - Fork 476
Transcribe-proxy replay testing #2438
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| use std::path::PathBuf; | ||
|
|
||
| use super::recording::WsRecording; | ||
|
|
||
| pub fn fixtures_dir() -> PathBuf { | ||
| PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| .join("tests") | ||
| .join("fixtures") | ||
| } | ||
|
|
||
| pub fn load_fixture(name: &str) -> WsRecording { | ||
| let path = fixtures_dir().join(name); | ||
| WsRecording::from_jsonl_file(&path).unwrap() | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,199 @@ | ||
| use std::net::SocketAddr; | ||
| use std::time::Duration; | ||
|
|
||
| use futures_util::{SinkExt, StreamExt}; | ||
| use tokio::net::{TcpListener, TcpStream}; | ||
| use tokio_tungstenite::tungstenite::Message; | ||
| use tokio_tungstenite::tungstenite::protocol::CloseFrame; | ||
| use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode; | ||
| use tokio_tungstenite::{WebSocketStream, accept_async}; | ||
|
|
||
| use super::recording::{MessageKind, WsMessage, WsRecording}; | ||
|
|
||
| #[derive(Debug, Clone)] | ||
| pub struct MockUpstreamConfig { | ||
| pub use_timing: bool, | ||
| pub max_delay_ms: u64, | ||
| } | ||
|
|
||
| impl Default for MockUpstreamConfig { | ||
| fn default() -> Self { | ||
| Self { | ||
| use_timing: false, | ||
| max_delay_ms: 1000, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl MockUpstreamConfig { | ||
| pub fn use_timing(mut self, use_timing: bool) -> Self { | ||
| self.use_timing = use_timing; | ||
| self | ||
| } | ||
|
|
||
| pub fn max_delay_ms(mut self, max_delay_ms: u64) -> Self { | ||
| self.max_delay_ms = max_delay_ms; | ||
| self | ||
| } | ||
| } | ||
|
|
||
| struct MockUpstreamServer { | ||
| recording: WsRecording, | ||
| config: MockUpstreamConfig, | ||
| listener: TcpListener, | ||
| } | ||
|
|
||
| impl MockUpstreamServer { | ||
| async fn with_config( | ||
| recording: WsRecording, | ||
| config: MockUpstreamConfig, | ||
| ) -> std::io::Result<Self> { | ||
| let listener = TcpListener::bind("127.0.0.1:0").await?; | ||
| Ok(Self { | ||
| recording, | ||
| config, | ||
| listener, | ||
| }) | ||
| } | ||
|
|
||
| fn addr(&self) -> SocketAddr { | ||
| self.listener.local_addr().unwrap() | ||
| } | ||
|
|
||
| async fn accept_one(&self) -> Result<(), MockUpstreamError> { | ||
| let (stream, _) = self.listener.accept().await?; | ||
| let ws_stream = accept_async(stream).await?; | ||
| self.handle_connection(ws_stream).await | ||
| } | ||
|
|
||
| async fn handle_connection( | ||
| &self, | ||
| ws_stream: WebSocketStream<TcpStream>, | ||
| ) -> Result<(), MockUpstreamError> { | ||
| let (mut sender, mut receiver) = ws_stream.split(); | ||
|
|
||
| let server_messages: Vec<&WsMessage> = self | ||
| .recording | ||
| .messages | ||
| .iter() | ||
| .filter(|m| m.is_from_upstream()) | ||
| .collect(); | ||
|
|
||
| let mut last_timestamp = 0u64; | ||
| let mut msg_index = 0; | ||
|
|
||
| loop { | ||
| if msg_index >= server_messages.len() { | ||
| break; | ||
| } | ||
|
|
||
| let msg = server_messages[msg_index]; | ||
|
|
||
| if self.config.use_timing && msg.timestamp_ms > last_timestamp { | ||
| let delay = (msg.timestamp_ms - last_timestamp).min(self.config.max_delay_ms); | ||
| tokio::time::sleep(Duration::from_millis(delay)).await; | ||
| } | ||
| last_timestamp = msg.timestamp_ms; | ||
|
|
||
| let ws_msg = ws_message_from_recorded(msg)?; | ||
| let is_close = matches!(msg.kind, MessageKind::Close { .. }); | ||
|
|
||
| sender.send(ws_msg).await?; | ||
| msg_index += 1; | ||
|
|
||
| if is_close { | ||
| break; | ||
| } | ||
|
|
||
| while let Ok(Some(_)) = | ||
| tokio::time::timeout(Duration::from_millis(1), receiver.next()).await | ||
| {} | ||
| } | ||
|
|
||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| fn ws_message_from_recorded(msg: &WsMessage) -> Result<Message, MockUpstreamError> { | ||
| match &msg.kind { | ||
| MessageKind::Text => Ok(Message::Text(msg.content.clone().into())), | ||
| MessageKind::Binary => { | ||
| let data = msg.decode_binary()?; | ||
| Ok(Message::Binary(data.into())) | ||
| } | ||
| MessageKind::Close { code, reason } => Ok(Message::Close(Some(CloseFrame { | ||
| code: CloseCode::from(*code), | ||
| reason: reason.clone().into(), | ||
| }))), | ||
| MessageKind::Ping => { | ||
| let data = if msg.content.is_empty() { | ||
| vec![] | ||
| } else { | ||
| msg.decode_binary()? | ||
| }; | ||
| Ok(Message::Ping(data.into())) | ||
| } | ||
| MessageKind::Pong => { | ||
| let data = if msg.content.is_empty() { | ||
| vec![] | ||
| } else { | ||
| msg.decode_binary()? | ||
| }; | ||
| Ok(Message::Pong(data.into())) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug, thiserror::Error)] | ||
| pub enum MockUpstreamError { | ||
| #[error("IO error: {0}")] | ||
| Io(#[from] std::io::Error), | ||
| #[error("WebSocket error: {0}")] | ||
| WebSocket(#[from] tokio_tungstenite::tungstenite::Error), | ||
| #[error("Base64 decode error: {0}")] | ||
| Base64(#[from] base64::DecodeError), | ||
| } | ||
|
|
||
| pub struct MockServerHandle { | ||
| addr: SocketAddr, | ||
| #[allow(dead_code)] | ||
| shutdown_tx: tokio::sync::oneshot::Sender<()>, | ||
| } | ||
|
|
||
| impl MockServerHandle { | ||
| pub fn ws_url(&self) -> String { | ||
| format!("ws://{}", self.addr) | ||
| } | ||
| } | ||
|
|
||
| /// Starts a mock upstream server that replays recorded WebSocket messages. | ||
| /// | ||
| /// Note: This server only accepts a single connection. After one client connects | ||
| /// and the recording is replayed, the server will shut down. This is intentional | ||
| /// for test isolation - each test should create its own mock server instance. | ||
| pub async fn start_mock_server_with_config( | ||
| recording: WsRecording, | ||
| config: MockUpstreamConfig, | ||
| ) -> std::io::Result<MockServerHandle> { | ||
| let server = MockUpstreamServer::with_config(recording, config).await?; | ||
| let addr = server.addr(); | ||
|
|
||
| let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); | ||
|
|
||
| tokio::spawn(async move { | ||
| tokio::select! { | ||
| result = server.accept_one() => { | ||
| if let Err(e) = result { | ||
| tracing::warn!("mock_server_error: {:?}", e); | ||
| } | ||
| } | ||
| _ = shutdown_rx => { | ||
| tracing::debug!("mock_server_shutdown"); | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| tokio::time::sleep(Duration::from_millis(10)).await; | ||
|
|
||
| Ok(MockServerHandle { addr, shutdown_tx }) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.