Skip to content

Commit b1542a6

Browse files
Paul-EPaul Ellenbogen
andauthored
fix: fix resource leak (#136)
When a running service is dropped, its connections should be closed and its resources should be cleaned up. This changes the default from leaving services running to closing them. Library users who want their services to remain running should call `waiting` on their running service, in a new task where necessary. Co-authored-by: Paul Ellenbogen <[email protected]>
1 parent 5e4d447 commit b1542a6

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

crates/rmcp/src/service.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ mod server;
2121
pub use server::*;
2222
#[cfg(feature = "tower")]
2323
mod tower;
24-
use tokio_util::sync::CancellationToken;
24+
use tokio_util::sync::{CancellationToken, DropGuard};
2525
#[cfg(feature = "tower")]
2626
pub use tower::*;
2727
use tracing::instrument;
@@ -429,8 +429,8 @@ pub struct RunningService<R: ServiceRole, S: Service<R>> {
429429
service: Arc<S>,
430430
peer: Peer<R>,
431431
handle: tokio::task::JoinHandle<QuitReason>,
432-
/// cancellation token
433-
ct: CancellationToken,
432+
/// cancellation token with drop guard
433+
dg: DropGuard,
434434
}
435435
impl<R: ServiceRole, S: Service<R>> Deref for RunningService<R, S> {
436436
type Target = Peer<R>;
@@ -453,8 +453,9 @@ impl<R: ServiceRole, S: Service<R>> RunningService<R, S> {
453453
self.handle.await
454454
}
455455
pub async fn cancel(self) -> Result<QuitReason, tokio::task::JoinError> {
456-
self.ct.cancel();
457-
self.waiting().await
456+
let RunningService { dg, handle, .. } = self;
457+
dg.disarm().cancel();
458+
handle.await
458459
}
459460
}
460461

@@ -759,6 +760,6 @@ where
759760
service,
760761
peer: peer_return,
761762
handle,
762-
ct,
763+
dg: ct.drop_guard(),
763764
})
764765
}

examples/servers/src/generic_service.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,6 @@ async fn main() -> Result<(), Box<dyn Error>> {
1313

1414
let io = (tokio::io::stdin(), tokio::io::stdout());
1515

16-
serve_server(generic_service, io).await?;
16+
serve_server(generic_service, io).await?.waiting().await?;
1717
Ok(())
1818
}

0 commit comments

Comments
 (0)