-
Notifications
You must be signed in to change notification settings - Fork 898
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
[ObjectStore] Add SpawnService for running requests on different tokio runtime/Handle
#7253
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
// Licensed to the Apache Software Foundation (ASF) under one | ||
// or more contributor license agreements. See the NOTICE file | ||
// distributed with this work for additional information | ||
// regarding copyright ownership. The ASF licenses this file | ||
// to you under the Apache License, Version 2.0 (the | ||
// "License"); you may not use this file except in compliance | ||
// with the License. You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, | ||
// software distributed under the License is distributed on an | ||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
// KIND, either express or implied. See the License for the | ||
// specific language governing permissions and limitations | ||
// under the License. | ||
|
||
//! Generic HTTP client abstraction | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It was a little confusing having the public HTTP client abstraction mixed in with the client utilities for implementing object_store - so split it out into a separate module |
||
|
||
mod body; | ||
pub use body::*; | ||
|
||
mod connection; | ||
pub use connection::*; | ||
|
||
mod spawn; | ||
pub use spawn::*; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,162 @@ | ||
// Licensed to the Apache Software Foundation (ASF) under one | ||
// or more contributor license agreements. See the NOTICE file | ||
// distributed with this work for additional information | ||
// regarding copyright ownership. The ASF licenses this file | ||
// to you under the Apache License, Version 2.0 (the | ||
// "License"); you may not use this file except in compliance | ||
// with the License. You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, | ||
// software distributed under the License is distributed on an | ||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
// KIND, either express or implied. See the License for the | ||
// specific language governing permissions and limitations | ||
// under the License. | ||
|
||
use crate::client::{ | ||
HttpError, HttpErrorKind, HttpRequest, HttpResponse, HttpResponseBody, HttpService, | ||
}; | ||
use async_trait::async_trait; | ||
use bytes::Bytes; | ||
use http::Response; | ||
use http_body_util::BodyExt; | ||
use hyper::body::{Body, Frame}; | ||
use std::pin::Pin; | ||
use std::task::{Context, Poll}; | ||
use thiserror::Error; | ||
use tokio::runtime::Handle; | ||
use tokio::task::JoinHandle; | ||
|
||
/// Spawn error | ||
#[derive(Debug, Error)] | ||
#[error("SpawnError")] | ||
struct SpawnError {} | ||
|
||
impl From<SpawnError> for HttpError { | ||
fn from(value: SpawnError) -> Self { | ||
Self::new(HttpErrorKind::Interrupted, value) | ||
} | ||
} | ||
|
||
/// Wraps a provided [`HttpService`] and runs it on a separate tokio runtime | ||
#[derive(Debug)] | ||
pub struct SpawnService<T: HttpService + Clone> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I always find templated code like this harder to use and understand than just When it is important to make type specialized code for performance I understand the need But when the usecase is to make a function call for an http request I think the mental overhead is unecessary I realize this is a style opinion / point of view and that others may not feel the same way There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. So I originally actually had this wrapping HttpClient, but it ended up a bit weird as you ended up doing
As opposed to composing the services to yield the final client
|
||
inner: T, | ||
runtime: Handle, | ||
} | ||
|
||
impl<T: HttpService + Clone> SpawnService<T> { | ||
/// Creates a new [`SpawnService`] from the provided | ||
pub fn new(inner: T, runtime: Handle) -> Self { | ||
Self { inner, runtime } | ||
} | ||
} | ||
|
||
#[async_trait] | ||
impl<T: HttpService + Clone> HttpService for SpawnService<T> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's a bit ouroborosy but I wonder if we should implement |
||
async fn call(&self, req: HttpRequest) -> Result<HttpResponse, HttpError> { | ||
let inner = self.inner.clone(); | ||
let (send, recv) = tokio::sync::oneshot::channel(); | ||
|
||
// We use an unbounded channel to prevent backpressure across the runtime boundary | ||
// which could in turn starve the underlying IO operations | ||
let (sender, receiver) = tokio::sync::mpsc::unbounded_channel(); | ||
|
||
let handle = SpawnHandle(self.runtime.spawn(async move { | ||
let r = match HttpService::call(&inner, req).await { | ||
Ok(resp) => resp, | ||
Err(e) => { | ||
let _ = send.send(Err(e)); | ||
return; | ||
} | ||
}; | ||
|
||
let (parts, mut body) = r.into_parts(); | ||
if send.send(Ok(parts)).is_err() { | ||
return; | ||
} | ||
|
||
while let Some(x) = body.frame().await { | ||
sender.send(x).unwrap(); | ||
} | ||
})); | ||
|
||
let parts = recv.await.map_err(|_| SpawnError {})??; | ||
|
||
Ok(Response::from_parts( | ||
parts, | ||
HttpResponseBody::new(SpawnBody { | ||
stream: receiver, | ||
_worker: handle, | ||
}), | ||
)) | ||
} | ||
} | ||
|
||
/// A wrapper around a [`JoinHandle`] that aborts on drop | ||
struct SpawnHandle(JoinHandle<()>); | ||
impl Drop for SpawnHandle { | ||
fn drop(&mut self) { | ||
self.0.abort(); | ||
} | ||
} | ||
|
||
type StreamItem = Result<Frame<Bytes>, HttpError>; | ||
|
||
struct SpawnBody { | ||
stream: tokio::sync::mpsc::UnboundedReceiver<StreamItem>, | ||
_worker: SpawnHandle, | ||
} | ||
|
||
impl Body for SpawnBody { | ||
type Data = Bytes; | ||
type Error = HttpError; | ||
|
||
fn poll_frame(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<StreamItem>> { | ||
self.stream.poll_recv(cx) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use crate::client::mock_server::MockServer; | ||
use crate::client::retry::RetryExt; | ||
use crate::client::HttpClient; | ||
use crate::RetryConfig; | ||
|
||
async fn test_client(client: HttpClient) { | ||
let (send, recv) = tokio::sync::oneshot::channel(); | ||
|
||
let mock = MockServer::new().await; | ||
mock.push(Response::new("BANANAS".to_string())); | ||
|
||
let url = mock.url().to_string(); | ||
let thread = std::thread::spawn(|| { | ||
futures::executor::block_on(async move { | ||
let retry = RetryConfig::default(); | ||
let ret = client.get(url).send_retry(&retry).await.unwrap(); | ||
let payload = ret.into_body().bytes().await.unwrap(); | ||
assert_eq!(payload.as_ref(), b"BANANAS"); | ||
let _ = send.send(()); | ||
}) | ||
}); | ||
recv.await.unwrap(); | ||
thread.join().unwrap(); | ||
} | ||
|
||
#[tokio::test] | ||
async fn test_spawn() { | ||
let client = HttpClient::new(SpawnService::new(reqwest::Client::new(), Handle::current())); | ||
test_client(client).await; | ||
} | ||
|
||
#[tokio::test] | ||
#[should_panic] | ||
async fn test_no_spawn() { | ||
let client = HttpClient::new(reqwest::Client::new()); | ||
test_client(client).await; | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a drive-by improvement, and allows using HttpResponseBody with
http_body_util::BodyExt
.It technically isn't necessary, as object_store ignores any non-data frames and therefore
HttpResponseBody::bytes
is sufficient, but this is cleanerThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That is probably good context to add as an inline comment for future readers