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

Serverのtrait書くぞ3 #61

Merged
merged 4 commits into from
Jan 24, 2025
Merged
Changes from 1 commit
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
Prev Previous commit
♻️ Use TaskTracket in TaskManager
H1rono committed Jan 24, 2025
commit f7aed627c70894266747d3e536689588747644f8
2 changes: 1 addition & 1 deletion server/src/main.rs
Original file line number Diff line number Diff line change
@@ -170,7 +170,7 @@ impl State {
async fn graceful_shutdown(&self) -> anyhow::Result<()> {
let duration = std::time::Duration::from_secs(5);
let fut = self.task_manager.graceful_shutdown();
tokio::time::timeout(duration, fut).await??;
tokio::time::timeout(duration, fut).await?;
Ok(())
}
}
27 changes: 7 additions & 20 deletions server/src/task.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
use std::{future::Future, sync::Arc};

use tokio::{
sync::Mutex,
task::{JoinError, JoinSet},
};
use tokio_util::sync::CancellationToken;
use tokio_util::{sync::CancellationToken, task::TaskTracker};

#[derive(Debug, Clone)]
pub struct TaskManager(Arc<Inner>);

#[derive(Debug)]
struct Inner {
cancel: CancellationToken,
join_set: Mutex<JoinSet<()>>,
task_tracker: TaskTracker,
}

impl Default for TaskManager {
@@ -25,7 +21,7 @@ impl TaskManager {
pub fn new() -> Self {
let inner = Inner {
cancel: CancellationToken::new(),
join_set: Mutex::new(JoinSet::new()),
task_tracker: TaskTracker::new(),
};
Self(Arc::new(inner))
}
@@ -37,24 +33,15 @@ impl TaskManager {
{
let child = self.0.cancel.child_token();
let fut = func(child.clone());
self.0.join_set.lock().await.spawn(fut);
self.0.task_tracker.spawn(fut);
child
}

#[tracing::instrument(skip_all)]
pub async fn graceful_shutdown(&self) -> Result<(), JoinError> {
pub async fn graceful_shutdown(&self) {
self.0.cancel.cancel();
let mut join_set = self.0.join_set.lock().await;
while let Some(res) = join_set.join_next().await {
match res {
Ok(()) => {}
Err(e) => {
tracing::error!(error = &e as &dyn std::error::Error, "join error");
return Err(e);
}
}
}
self.0.task_tracker.close();
self.0.task_tracker.wait().await;
tracing::info!("Gracefully shut down");
Ok(())
}
}