refactor stop logic

This commit is contained in:
dignifiedquire
2020-03-21 19:05:50 +01:00
parent 4d6a9e4f14
commit d798356c19
4 changed files with 51 additions and 30 deletions

View File

@@ -128,8 +128,8 @@ impl Context {
}
pub async fn run(&self) {
if self.inner.scheduler.read().await.is_running() {
panic!("Already running");
if self.is_running().await {
return;
}
let l = &mut *self.inner.scheduler.write().await;
@@ -137,7 +137,7 @@ impl Context {
}
pub async fn is_running(&self) -> bool {
self.inner.scheduler.read().await.is_running()
self.inner.is_running().await
}
pub async fn stop(&self) {
@@ -480,19 +480,21 @@ impl Context {
}
impl InnerContext {
async fn stop(&self) {
if self.scheduler.read().await.is_running() {
self.scheduler.write().await.stop().await;
}
async fn is_running(&self) -> bool {
self.scheduler.read().await.is_running()
}
}
impl Drop for InnerContext {
fn drop(&mut self) {
async_std::task::block_on(async move {
self.stop().await;
self.sql.close().await;
});
async fn stop(&self) {
if self.is_running().await {
let token = {
let lock = &*self.scheduler.read().await;
lock.pre_stop().await
};
{
let lock = &mut *self.scheduler.write().await;
lock.stop(token).await;
}
}
}
}

View File

@@ -9,6 +9,8 @@ use crate::imap::Imap;
use crate::job::{self, Thread};
use crate::smtp::Smtp;
pub(crate) struct StopToken;
/// Job and connection scheduler.
#[derive(Debug)]
pub(crate) enum Scheduler {
@@ -287,8 +289,8 @@ impl Scheduler {
}
}
/// Halt the scheduler, panics if it is already stopped.
pub async fn stop(&mut self) {
/// Halts the scheduler, must be called first, and then `stop`.
pub(crate) async fn pre_stop(&self) -> StopToken {
match self {
Scheduler::Stopped => {
panic!("WARN: already stopped");
@@ -306,6 +308,19 @@ impl Scheduler {
.join(sentbox.stop())
.join(smtp.stop())
.await;
StopToken
}
}
}
/// Halt the scheduler, must only be called after pre_stop.
pub(crate) async fn stop(&mut self, _t: StopToken) {
match self {
Scheduler::Stopped => {
panic!("WARN: already stopped");
}
Scheduler::Running { .. } => {
*self = Scheduler::Stopped;
}
}