Skip to content

Commit

Permalink
Fix connection counter leak when response timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
james58899 committed Feb 25, 2024
1 parent 3f5c025 commit f33ece5
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/middleware/connection_counter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use axum::{
use futures::future::BoxFuture;
use http_body::{Frame, SizeHint};
use pin_project_lite::pin_project;
use scopeguard::{guard, ScopeGuard};
use tokio::sync::mpsc::Sender;
use tower::{Layer, Service};

Expand Down Expand Up @@ -81,11 +82,16 @@ where
if counter.fetch_add(1, Ordering::Relaxed) > (self.data.settings.max_connection() as f64 * 0.8).ceil() as u64 {
let _ = self.data.command_channel.try_send(Command::Overload);
};
let guard = guard(counter, move |counter| {
counter.fetch_sub(1, Ordering::Relaxed);
});

let fut = self.service.call(req);

Box::pin(async move {
match fut.await {
let res = fut.await;
let counter = ScopeGuard::into_inner(guard); // Cancel counter guard
match res {
Ok(res) => Ok(res.map(|body| ConnectionCounterFinalizer { body, counter })),
Err(err) => {
counter.fetch_sub(1, Ordering::Relaxed);
Expand Down

0 comments on commit f33ece5

Please sign in to comment.