-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
enhancement(vector source): implement client connection limits for grpc server #21072
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,110 @@ | ||
use std::{ | ||
sync::{Arc, Mutex}, | ||
time::{Duration, Instant}, | ||
task::{Context, Poll}, | ||
}; | ||
|
||
use http::{Request, Response}; | ||
use hyper::Body; | ||
use std::future::Future; | ||
use std::pin::Pin; | ||
|
||
use tonic::{ | ||
Status, | ||
body::BoxBody, | ||
transport::server::NamedService, | ||
}; | ||
use tower::{Layer, Service}; | ||
|
||
/// A service that tracks the number of requests and elapsed time, | ||
/// shutting down the connection gracefully if the configured limits are reached. | ||
#[derive(Clone)] | ||
pub struct ConnectionLimit<S> { | ||
inner: S, | ||
request_count: Arc<Mutex<usize>>, | ||
max_requests: usize, | ||
max_duration: Duration, | ||
start_time: Instant, | ||
} | ||
|
||
impl<S> ConnectionLimit<S> { | ||
pub fn new(inner: S, max_requests: usize, max_duration: Duration) -> Self { | ||
Self { | ||
inner, | ||
request_count: Arc::new(Mutex::new(0)), | ||
max_requests: max_requests, | ||
max_duration: max_duration, | ||
start_time: Instant::now(), | ||
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. Nit: I think it might be better to initialize the |
||
} | ||
} | ||
} | ||
|
||
impl<S> Service<Request<Body>> for ConnectionLimit<S> | ||
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 think this would end up applying one duration and request limit across all clients. In an ideal world, I think we would apply the limits per-client (that is per socket). |
||
where | ||
S: Service<Request<Body>, Response = Response<BoxBody>, Error = tonic::Status> | ||
+ NamedService | ||
+ Clone | ||
+ Send | ||
+ 'static, | ||
S::Future: Send + 'static, | ||
{ | ||
type Response = Response<BoxBody>; | ||
type Error = S::Error; | ||
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>; | ||
|
||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { | ||
self.inner.poll_ready(cx) | ||
} | ||
|
||
fn call(&mut self, req: Request<Body>) -> Self::Future { | ||
let max_requests = self.max_requests; | ||
let max_duration = self.max_duration; | ||
let request_count = Arc::clone(&self.request_count); | ||
let start_time = self.start_time; | ||
|
||
let elapsed_time = start_time.elapsed(); | ||
|
||
let future = self.inner.call(req); | ||
|
||
Box::pin(async move { | ||
let response = future.await?; | ||
|
||
// After processing the request, increment the request count and check the limits. | ||
let mut count = request_count.lock().unwrap(); | ||
*count += 1; | ||
|
||
if *count > max_requests || elapsed_time > max_duration { | ||
// If the limit is reached, return a ResourceExhausted error to close the connection. | ||
return Err(Status::resource_exhausted( | ||
"Connection closed after reaching the limit.", | ||
)); | ||
Comment on lines
+78
to
+80
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. Will the server close the connection if this error is returned? Or are we depending on the client closing it when it sees this error? |
||
} | ||
|
||
Ok(response) | ||
}) | ||
} | ||
} | ||
|
||
/// A layer that adds the ConnectionLimit functionality to a service. | ||
#[derive(Clone, Default)] | ||
pub struct ConnectionLimitLayer { | ||
max_requests: usize, | ||
max_duration: Duration, | ||
} | ||
|
||
impl ConnectionLimitLayer { | ||
pub fn new(max_requests: usize, max_duration: Duration) -> Self { | ||
Self { | ||
max_requests, | ||
max_duration, | ||
} | ||
} | ||
} | ||
|
||
impl<S> Layer<S> for ConnectionLimitLayer { | ||
type Service = ConnectionLimit<S>; | ||
|
||
fn layer(&self, inner: S) -> Self::Service { | ||
ConnectionLimit::new(inner, self.max_requests, self.max_duration) | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,13 +6,14 @@ | |
use futures::FutureExt; | ||
use http::{Request, Response}; | ||
use hyper::Body; | ||
use std::{convert::Infallible, net::SocketAddr, time::Duration}; | ||
use std::{net::SocketAddr, time::Duration}; | ||
use tonic::transport::server::Routes; | ||
use tonic::{ | ||
Status, | ||
body::BoxBody, | ||
transport::server::{NamedService, Server}, | ||
}; | ||
use tower::Service; | ||
use tower::{Layer, Service}; | ||
use tower_http::{ | ||
classify::{GrpcErrorsAsFailures, SharedClassifier}, | ||
trace::TraceLayer, | ||
|
@@ -22,14 +23,19 @@ | |
mod decompression; | ||
pub use self::decompression::{DecompressionAndMetrics, DecompressionAndMetricsLayer}; | ||
|
||
mod connectionlimit; | ||
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. Nit: module names usually use |
||
pub use self::connectionlimit::{ConnectionLimit, ConnectionLimitLayer}; | ||
|
||
pub async fn run_grpc_server<S>( | ||
address: SocketAddr, | ||
max_requests: usize, | ||
max_duration: Duration, | ||
tls_settings: MaybeTlsSettings, | ||
service: S, | ||
shutdown: ShutdownSignal, | ||
) -> crate::Result<()> | ||
where | ||
S: Service<Request<Body>, Response = Response<BoxBody>, Error = Infallible> | ||
S: Service<Request<Body>, Response = Response<BoxBody>, Error = tonic::Status> | ||
+ NamedService | ||
+ Clone | ||
+ Send | ||
|
@@ -43,6 +49,9 @@ | |
|
||
info!(%address, "Building gRPC server."); | ||
|
||
// Conditionally apply the ConnectionLimitLayer if any limits are set | ||
let service = ConnectionLimitLayer::new(max_requests, max_duration).layer(service); | ||
Comment on lines
+52
to
+53
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 think this could be added in the list before as another layer after (or before) the DecompressionAndMetricsLayer. |
||
|
||
Server::builder() | ||
.layer(build_grpc_trace_layer(span.clone())) | ||
// This layer explicitly decompresses payloads, if compressed, and reports the number of message bytes we've | ||
|
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.
I think an atomic could be used here instead: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicUsize.html