Skip to content
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

feat: respect throttling #184

Merged
merged 1 commit into from
Oct 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 31 additions & 12 deletions src/backoff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ impl Default for BackoffConfig {
pub type BackoffError = std::convert::Infallible;
pub type BackoffResult<T> = Result<T, BackoffError>;

/// Error (which should increase backoff) or throttle for a specific duration (as asked for by the broker).
#[derive(Debug)]
pub enum ErrorOrThrottle<E>
where
E: std::error::Error + Send,
{
Error(E),
Throttle(Duration),
}

/// [`Backoff`] can be created from a [`BackoffConfig`]
///
/// Consecutive calls to [`Backoff::next`] will return the next backoff interval
Expand Down Expand Up @@ -99,23 +109,32 @@ impl Backoff {
) -> BackoffResult<B>
where
F: (Fn() -> F1) + Send + Sync,
F1: std::future::Future<Output = ControlFlow<B, E>> + Send,
F1: std::future::Future<Output = ControlFlow<B, ErrorOrThrottle<E>>> + Send,
E: std::error::Error + Send,
{
loop {
let e = match do_stuff().await {
ControlFlow::Break(r) => break Ok(r),
ControlFlow::Continue(e) => e,
// split match statement from `tokio::time::sleep`, because otherwise rustc requires `B: Send`
let sleep_time = match do_stuff().await {
ControlFlow::Break(r) => {
break Ok(r);
}
ControlFlow::Continue(ErrorOrThrottle::Error(e)) => {
let backoff = self.next();
info!(
e=%e,
request_name,
backoff_secs = backoff.as_secs(),
"request encountered non-fatal error - backing off",
);
backoff
}
ControlFlow::Continue(ErrorOrThrottle::Throttle(throttle)) => {
info!(?throttle, request_name, "broker asked us to throttle",);
throttle
}
};

let backoff = self.next();
info!(
e=%e,
request_name,
backoff_secs = backoff.as_secs(),
"request encountered non-fatal error - backing off",
);
tokio::time::sleep(backoff).await;
tokio::time::sleep(sleep_time).await;
}
}
}
Expand Down
31 changes: 21 additions & 10 deletions src/client/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use tokio::sync::Mutex;
use tracing::{debug, error, info};

use crate::{
backoff::{Backoff, BackoffConfig},
backoff::{Backoff, BackoffConfig, ErrorOrThrottle},
client::{Error, Result},
connection::{
BrokerCache, BrokerConnection, BrokerConnector, MessengerTransport, MetadataLookupMode,
Expand All @@ -16,6 +16,7 @@ use crate::{
messages::{CreateTopicRequest, CreateTopicsRequest},
primitives::{Int16, Int32, String_},
},
throttle::maybe_throttle,
validation::ExactlyOne,
};

Expand Down Expand Up @@ -63,23 +64,28 @@ impl ControllerClient {
};

maybe_retry(&self.backoff_config, self, "create_topic", || async move {
let broker = self.get().await?;
let response = broker.request(request).await?;
let broker = self.get().await.map_err(ErrorOrThrottle::Error)?;
let response = broker
.request(request)
.await
.map_err(|e| ErrorOrThrottle::Error(e.into()))?;

maybe_throttle(response.throttle_time_ms)?;

let topic = response
.topics
.exactly_one()
.map_err(Error::exactly_one_topic)?;
.map_err(|e| ErrorOrThrottle::Error(Error::exactly_one_topic(e)))?;

match topic.error {
None => Ok(()),
Some(protocol_error) => Err(Error::ServerError {
Some(protocol_error) => Err(ErrorOrThrottle::Error(Error::ServerError {
protocol_error,
error_message: topic.error_message.and_then(|s| s.0),
request: RequestContext::Topic(topic.name.0),
response: None,
is_virtual: false,
}),
})),
}
})
.await?;
Expand Down Expand Up @@ -150,15 +156,20 @@ async fn maybe_retry<B, R, F, T>(
where
B: BrokerCache,
R: (Fn() -> F) + Send + Sync,
F: std::future::Future<Output = Result<T>> + Send,
F: std::future::Future<Output = Result<T, ErrorOrThrottle<Error>>> + Send,
{
let mut backoff = Backoff::new(backoff_config);

backoff
.retry_with_backoff(request_name, || async {
let error = match f().await {
Ok(v) => return ControlFlow::Break(Ok(v)),
Err(e) => e,
Ok(v) => {
return ControlFlow::Break(Ok(v));
}
Err(ErrorOrThrottle::Throttle(t)) => {
return ControlFlow::Continue(ErrorOrThrottle::Throttle(t));
}
Err(ErrorOrThrottle::Error(e)) => e,
};

match error {
Expand All @@ -184,7 +195,7 @@ where
return ControlFlow::Break(Err(error));
}
}
ControlFlow::Continue(error)
ControlFlow::Continue(ErrorOrThrottle::Error(error))
})
.await
.map_err(Error::RetryFailed)?
Expand Down
57 changes: 46 additions & 11 deletions src/client/partition.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{
backoff::{Backoff, BackoffConfig},
backoff::{Backoff, BackoffConfig, ErrorOrThrottle},
client::error::{Error, RequestContext, Result},
connection::{
BrokerCache, BrokerConnection, BrokerConnector, MessengerTransport, MetadataLookupMode,
Expand All @@ -19,6 +19,7 @@ use crate::{
record::{Record as ProtocolRecord, *},
},
record::{Record, RecordAndOffset},
throttle::maybe_throttle,
validation::ExactlyOne,
};
use async_trait::async_trait;
Expand Down Expand Up @@ -151,7 +152,7 @@ impl PartitionClient {
&*brokers,
"leader_detection",
|| async move {
scope.get().await?;
scope.get().await.map_err(ErrorOrThrottle::Error)?;
Ok(())
},
)
Expand Down Expand Up @@ -190,9 +191,14 @@ impl PartitionClient {
self,
"produce",
|| async move {
let broker = self.get().await?;
let response = broker.request(&request).await?;
let broker = self.get().await.map_err(ErrorOrThrottle::Error)?;
let response = broker
.request(&request)
.await
.map_err(|e| ErrorOrThrottle::Error(e.into()))?;
maybe_throttle(response.throttle_time_ms)?;
process_produce_response(self.partition, &self.topic, n, response)
.map_err(ErrorOrThrottle::Error)
},
)
.await
Expand Down Expand Up @@ -221,8 +227,16 @@ impl PartitionClient {
self,
"fetch_records",
|| async move {
let response = self.get().await?.request(&request).await?;
let response = self
.get()
.await
.map_err(ErrorOrThrottle::Error)?
.request(&request)
.await
.map_err(|e| ErrorOrThrottle::Error(e.into()))?;
maybe_throttle(response.throttle_time_ms)?;
process_fetch_response(self.partition, &self.topic, response, offset)
.map_err(ErrorOrThrottle::Error)
},
)
.await?;
Expand All @@ -248,8 +262,16 @@ impl PartitionClient {
self,
"get_offset",
|| async move {
let response = self.get().await?.request(&request).await?;
let response = self
.get()
.await
.map_err(ErrorOrThrottle::Error)?
.request(&request)
.await
.map_err(|e| ErrorOrThrottle::Error(e.into()))?;
maybe_throttle(response.throttle_time_ms)?;
process_list_offsets_response(self.partition, &self.topic, response)
.map_err(ErrorOrThrottle::Error)
},
)
.await?;
Expand All @@ -272,8 +294,16 @@ impl PartitionClient {
self,
"delete_records",
|| async move {
let response = self.get().await?.request(&request).await?;
let response = self
.get()
.await
.map_err(ErrorOrThrottle::Error)?
.request(&request)
.await
.map_err(|e| ErrorOrThrottle::Error(e.into()))?;
maybe_throttle(Some(response.throttle_time_ms))?;
process_delete_records_response(&self.topic, self.partition, response)
.map_err(ErrorOrThrottle::Error)
},
)
.await?;
Expand Down Expand Up @@ -462,15 +492,20 @@ async fn maybe_retry<B, R, F, T>(
where
B: BrokerCache,
R: (Fn() -> F) + Send + Sync,
F: std::future::Future<Output = Result<T>> + Send,
F: std::future::Future<Output = Result<T, ErrorOrThrottle<Error>>> + Send,
{
let mut backoff = Backoff::new(backoff_config);

backoff
.retry_with_backoff(request_name, || async {
let error = match f().await {
Ok(v) => return ControlFlow::Break(Ok(v)),
Err(e) => e,
Ok(v) => {
return ControlFlow::Break(Ok(v));
}
Err(ErrorOrThrottle::Throttle(throttle)) => {
return ControlFlow::Continue(ErrorOrThrottle::Throttle(throttle));
}
Err(ErrorOrThrottle::Error(e)) => e,
};

let retry = match error {
Expand Down Expand Up @@ -504,7 +539,7 @@ where
};

if retry {
ControlFlow::Continue(error)
ControlFlow::Continue(ErrorOrThrottle::Error(error))
} else {
error!(
e=%error,
Expand Down
14 changes: 11 additions & 3 deletions src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ use thiserror::Error;
use tokio::{io::BufStream, sync::Mutex};
use tracing::{debug, error, info, warn};

use crate::backoff::ErrorOrThrottle;
use crate::connection::topology::{Broker, BrokerTopology};
use crate::connection::transport::Transport;
use crate::messenger::{Messenger, RequestError};
use crate::protocol::messages::{MetadataRequest, MetadataRequestTopic, MetadataResponse};
use crate::protocol::primitives::String_;
use crate::throttle::maybe_throttle;
use crate::{
backoff::{Backoff, BackoffConfig, BackoffError},
client::metadata_cache::MetadataCache,
Expand Down Expand Up @@ -418,7 +420,7 @@ where
"Failed to connect to any broker, backing off".to_string(),
);
let err: Arc<dyn std::error::Error + Send + Sync> = err.into();
ControlFlow::Continue(err)
ControlFlow::Continue(ErrorOrThrottle::Error(err))
})
.await
.map_err(Error::RetryFailed)
Expand Down Expand Up @@ -449,12 +451,18 @@ where
};

match broker.metadata_request(request_params).await {
Ok(response) => ControlFlow::Break(Ok(response)),
Ok(response) => {
if let Err(e) = maybe_throttle(response.throttle_time_ms) {
return ControlFlow::Continue(e);
}

ControlFlow::Break(Ok(response))
}
Err(e @ RequestError::Poisoned(_) | e @ RequestError::IO(_))
if !matches!(metadata_mode, MetadataLookupMode::SpecificBroker(_)) =>
{
arbitrary_broker_cache.invalidate().await;
ControlFlow::Continue(e)
ControlFlow::Continue(ErrorOrThrottle::Error(e))
}
Err(error) => {
error!(
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ mod protocol;

pub mod record;

mod throttle;

pub mod topic;

// re-exports
Expand Down
Loading