-
-
Notifications
You must be signed in to change notification settings - Fork 1
ingest-router: add executor and actually return results to client #93
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
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
2315715
ingest-router: Simplify handler type
lynnagara 23d2c80
.
lynnagara f94c2ec
make more stuff generic
lynnagara 83ea0d5
it's used now
lynnagara b4df820
.
lynnagara 9d8824c
fix unwrap
lynnagara a956d70
.
lynnagara 139acf0
revert moving comment
lynnagara b84d372
.
lynnagara 64ca3d4
remove test for deleted func
lynnagara f26e5ac
merge responses
lynnagara db100bb
more refactor
lynnagara 86f3804
finish implementing merge_responses
lynnagara a1d0f09
refactor tests
lynnagara 95b7a70
add todo
lynnagara 4e856e3
add error msg
lynnagara da9ab40
remove commented tests
lynnagara e81bac4
ingest-router: add executor and actually return results to client
lynnagara cbd54f8
rm print
lynnagara 4a3389d
test
lynnagara 2b0f977
add todos
lynnagara 59ca753
more testing diff ports
lynnagara 8d68063
revert
lynnagara 70a6180
ensure timed out cell results are also present
lynnagara 0965ea2
add proper timeout handling
lynnagara d586399
refactor
lynnagara 4b96b8d
Merge remote-tracking branch 'origin/main' into executor
lynnagara 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
Some comments aren't visible on the classic Files Changed page.
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,162 @@ | ||
| use crate::config::RelayTimeouts; | ||
| use crate::errors::IngestRouterError; | ||
| use crate::handler::{CellId, Handler, HandlerBody}; | ||
| use crate::http::send_to_upstream; | ||
| use crate::locale::Cells; | ||
| use http::StatusCode; | ||
| use http_body_util::{BodyExt, Full}; | ||
| use hyper::body::Bytes; | ||
| use hyper::{Request, Response}; | ||
| use hyper_util::client::legacy::Client; | ||
| use hyper_util::client::legacy::connect::HttpConnector; | ||
| use hyper_util::rt::TokioExecutor; | ||
| use shared::http::make_error_response; | ||
| use std::collections::HashSet; | ||
| use std::sync::Arc; | ||
| use tokio::task::JoinSet; | ||
| use tokio::time::{Duration, sleep}; | ||
|
|
||
| #[derive(Clone)] | ||
| pub struct Executor { | ||
| client: Client<HttpConnector, Full<Bytes>>, | ||
| timeouts: RelayTimeouts, | ||
| } | ||
|
|
||
| impl Executor { | ||
| pub fn new(timeouts: RelayTimeouts) -> Self { | ||
| let client = Client::builder(TokioExecutor::new()).build(HttpConnector::new()); | ||
| Self { client, timeouts } | ||
| } | ||
|
|
||
| // Splits, executes, and merges the responses using the provided handler. | ||
| pub async fn execute( | ||
| &self, | ||
| handler: Arc<dyn Handler>, | ||
| request: Request<HandlerBody>, | ||
| cells: Cells, | ||
| ) -> Response<HandlerBody> { | ||
| let (split_requests, metadata) = match handler.split_request(request, &cells).await { | ||
| Ok(result) => result, | ||
| Err(_e) => return make_error_response(StatusCode::INTERNAL_SERVER_ERROR), | ||
| }; | ||
|
|
||
| let results = self.execute_parallel(split_requests, cells).await; | ||
|
|
||
| handler.merge_responses(results, metadata).await | ||
| } | ||
|
|
||
| /// Execute split requests in parallel against their cell upstreams | ||
| async fn execute_parallel( | ||
| &self, | ||
| requests: Vec<(CellId, Request<HandlerBody>)>, | ||
| cells: Cells, | ||
| ) -> Vec<(CellId, Result<Response<HandlerBody>, IngestRouterError>)> { | ||
| let mut join_set = JoinSet::new(); | ||
|
|
||
| let mut pending_cells = HashSet::new(); | ||
|
|
||
| // Spawn requests for each cell | ||
| for (cell_id, request) in requests { | ||
| let cells = cells.clone(); | ||
| let client = self.client.clone(); | ||
| let timeout_secs = self.timeouts.http_timeout_secs; | ||
|
|
||
| pending_cells.insert(cell_id.clone()); | ||
| join_set.spawn(async move { | ||
| let result = send_to_cell(&client, &cell_id, request, &cells, timeout_secs).await; | ||
| (cell_id, result) | ||
| }); | ||
| } | ||
|
|
||
| let mut results = Vec::new(); | ||
|
|
||
| // Use the longer initial timeout for the first result | ||
| let initial_timeout = sleep(Duration::from_secs(self.timeouts.task_initial_timeout_secs)); | ||
|
|
||
| tokio::select! { | ||
| _ = initial_timeout => {}, | ||
| join_result = join_set.join_next() => { | ||
| match join_result { | ||
| Some(Ok((cell_id, result))) => { | ||
| pending_cells.remove(&cell_id); | ||
| results.push((cell_id, result)); | ||
| } | ||
| Some(Err(e)) => tracing::error!("Task panicked: {}", e), | ||
| // The join set is empty -- this should never happen | ||
| None => return results, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Use the shorter subsequent timeout for any remaining results | ||
| let timeout = sleep(Duration::from_secs( | ||
| self.timeouts.task_subsequent_timeout_secs, | ||
| )); | ||
| tokio::pin!(timeout); | ||
|
|
||
| loop { | ||
| tokio::select! { | ||
| _ = &mut timeout => { | ||
| break; | ||
| }, | ||
| join_result = join_set.join_next() => { | ||
| match join_result { | ||
| Some(Ok((cell_id, result))) => { | ||
| pending_cells.remove(&cell_id); | ||
| results.push((cell_id, result)); | ||
| }, | ||
| Some(Err(e)) => tracing::error!("Task panicked: {}", e), | ||
| // No more tasks | ||
| None => break, | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Add all remaining pending cells to results | ||
| for cell_id in pending_cells.drain() { | ||
| results.push(( | ||
| cell_id.clone(), | ||
| Err(IngestRouterError::UpstreamTimeout(cell_id)), | ||
| )); | ||
| } | ||
|
|
||
| results | ||
| } | ||
| } | ||
|
|
||
| /// Send a request to a specific cell's upstream | ||
| /// TODO: simplify body types so these conversions are not needed - consider converting to | ||
| /// Bytes at the boundary and using bytes only throughout the handlers. | ||
| async fn send_to_cell( | ||
| client: &Client<HttpConnector, Full<Bytes>>, | ||
| cell_id: &str, | ||
| request: Request<HandlerBody>, | ||
| cells: &Cells, | ||
| timeout_secs: u64, | ||
| ) -> Result<Response<HandlerBody>, IngestRouterError> { | ||
| // Look up the upstream for this cell | ||
| let upstream = cells | ||
| .cell_to_upstreams() | ||
| .get(cell_id) | ||
| .ok_or_else(|| IngestRouterError::InternalError(format!("Unknown cell: {}", cell_id)))?; | ||
|
|
||
| // Convert HandlerBody to Full<Bytes> for the HTTP client | ||
| let (parts, body) = request.into_parts(); | ||
| let body_bytes = body | ||
| .collect() | ||
| .await | ||
| .map_err(|e| IngestRouterError::RequestBodyError(e.to_string()))? | ||
| .to_bytes(); | ||
|
|
||
| let request = Request::from_parts(parts, Full::new(body_bytes)); | ||
|
|
||
| // Send to upstream (using relay_url) | ||
| let response = send_to_upstream(client, &upstream.relay_url, request, timeout_secs).await?; | ||
|
|
||
| // Convert Response<Bytes> back to Response<HandlerBody> | ||
| let (parts, body_bytes) = response.into_parts(); | ||
| let handler_body: HandlerBody = Full::new(body_bytes).map_err(|e| match e {}).boxed(); | ||
|
|
||
| Ok(Response::from_parts(parts, handler_body)) | ||
| } |
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
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.
This comment was marked as outdated.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.