Skip to content

Commit 65a9a04

Browse files
committed
refactor: Improve shutdown code.
1 parent 0500b69 commit 65a9a04

File tree

9 files changed

+53
-49
lines changed

9 files changed

+53
-49
lines changed

crates/download-manager/src/lib.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ use std::{
88
};
99

1010
use database::YTLocalDatabase;
11-
use flume::Receiver;
1211
use tokio::{select, task::JoinHandle, time::sleep};
1312
use ytpapi2::YoutubeMusicVideoRef;
1413

@@ -51,7 +50,7 @@ impl DownloadManager {
5150
/// HANDLES.lock().unwrap().push(run_service(async move {
5251
/// run_service_stream(sender);
5352
/// }));
54-
pub fn run_service_stream(&'static self, cancelation: Receiver<()>, sender: MessageHandler) {
53+
pub fn run_service_stream(&'static self, cancelation: impl Future<Output = ()> + Clone + Send + 'static, sender: MessageHandler) {
5554
let fut = async move {
5655
loop {
5756
if let Some(id) = self.take() {
@@ -64,19 +63,19 @@ impl DownloadManager {
6463
let service = tokio::task::spawn(async move {
6564
select! {
6665
_ = fut => {},
67-
_ = cancelation.recv_async() => {},
66+
_ = cancelation => {},
6867
}
6968
});
7069
self.handles.lock().unwrap().push(service);
7170
}
7271

73-
pub fn spawn_system(&'static self, cancelation: Receiver<()>, sender: MessageHandler) {
72+
pub fn spawn_system(&'static self, cancelation: impl Future<Output = ()> + Clone + Send + 'static, sender: MessageHandler) {
7473
for _ in 0..DOWNLOADER_COUNT {
7574
self.run_service_stream(cancelation.clone(), sender.clone());
7675
}
7776
}
7877

79-
pub fn clean(&'static self, cancelation: Receiver<()>, sender: MessageHandler) {
78+
pub fn clean(&'static self, cancelation: impl Future<Output = ()> + Clone + Send + 'static, sender: MessageHandler) {
8079
self.download_list.lock().unwrap().clear();
8180
self.in_download.lock().unwrap().clear();
8281
{

crates/download-manager/src/task.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::sync::Arc;
22

3-
use flume::Receiver;
43
use log::error;
54
use rusty_ytdl::{
65
DownloadOptions, Video, VideoError, VideoOptions, VideoQuality, VideoSearchOptions,
@@ -144,15 +143,15 @@ impl DownloadManager {
144143
&'static self,
145144
s: MessageHandler,
146145
song: YoutubeMusicVideoRef,
147-
cancelation: Receiver<()>,
146+
cancelation: impl Future<Output = ()> + Send + 'static,
148147
) {
149148
let fut = async move {
150149
self.start_download(song, s).await;
151150
};
152151
let service = tokio::task::spawn(async move {
153152
select! {
154153
_ = fut => {},
155-
_ = cancelation.recv_async() => {},
154+
_ = cancelation => {},
156155
}
157156
});
158157
self.handles.lock().unwrap().push(service);

crates/ytermusic/src/main.rs

Lines changed: 6 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,7 @@ use structures::performance::STARTUP_TIME;
66
use term::{Manager, ManagerMessage};
77
use tokio::select;
88

9-
use std::{
10-
future::Future,
11-
panic,
12-
path::{Path, PathBuf},
13-
str::FromStr,
14-
sync::RwLock,
15-
};
9+
use std::{future::Future, panic, path::{Path, PathBuf}, str::FromStr, sync::RwLock};
1610
use systems::{logger::init, player::player_system};
1711

1812
use crate::{
@@ -30,7 +24,8 @@ mod structures;
3024
mod systems;
3125
mod term;
3226
mod utils;
33-
27+
mod shutdown;
28+
pub use shutdown::{ShutdownSignal, is_shutdown_sent, shutdown};
3429
mod tasks;
3530

3631
pub use database::DATABASE;
@@ -41,28 +36,18 @@ use mimalloc::MiMalloc;
4136
#[global_allocator]
4237
static GLOBAL: MiMalloc = MiMalloc;
4338

44-
pub static SIGNALING_STOP: Lazy<(Sender<()>, Receiver<()>)> = Lazy::new(flume::unbounded);
45-
4639
fn run_service<T>(future: T) -> tokio::task::JoinHandle<()>
4740
where
4841
T: Future + Send + 'static,
4942
{
5043
tokio::task::spawn(async move {
5144
select! {
5245
_ = future => {},
53-
_ = SIGNALING_STOP.1.recv_async() => {},
46+
_ = ShutdownSignal => {},
5447
}
5548
})
5649
}
5750

58-
fn shutdown() {
59-
info!("Shutdown signal sending");
60-
for _ in 0..1000 {
61-
SIGNALING_STOP.0.send(()).unwrap();
62-
}
63-
info!("Shutdown signal sent");
64-
}
65-
6651
static COOKIES: Lazy<RwLock<Option<String>>> = Lazy::new(|| RwLock::new(None));
6752

6853
pub fn try_get_cookies() -> Option<String> {
@@ -247,7 +232,7 @@ async fn app_start_main(updater_r: Receiver<ManagerMessage>, updater_s: Sender<M
247232
let (sa, player) = player_system(updater_s.clone());
248233
// Spawn the downloader system
249234
DOWNLOAD_MANAGER.spawn_system(
250-
SIGNALING_STOP.1.clone(),
235+
ShutdownSignal,
251236
download_manager_handler(sa.clone()),
252237
);
253238
STARTUP_TIME.log("Spawned system task");
@@ -279,7 +264,7 @@ fn app_start() {
279264
.block_on(async move {
280265
select! {
281266
_ = app_start_main(updater_r, updater_s) => {},
282-
_ = SIGNALING_STOP.1.recv_async() => {},
267+
_ = ShutdownSignal => {},
283268
};
284269
});
285270
info!("Runtime closed");

crates/ytermusic/src/shutdown.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
use std::{future::Future, pin::Pin, sync::atomic::{AtomicBool, Ordering}, task::{Context, Poll}};
2+
3+
use log::info;
4+
5+
6+
static SHUTDOWN_SENT: AtomicBool = AtomicBool::new(false);
7+
8+
pub fn is_shutdown_sent() -> bool {
9+
SHUTDOWN_SENT.load(Ordering::Relaxed)
10+
}
11+
12+
#[derive(Clone)]
13+
pub struct ShutdownSignal;
14+
15+
impl Future for ShutdownSignal {
16+
type Output = ();
17+
18+
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
19+
if SHUTDOWN_SENT.load(Ordering::Relaxed) {
20+
Poll::Ready(())
21+
} else {
22+
Poll::Pending
23+
}
24+
}
25+
}
26+
27+
pub fn shutdown() {
28+
SHUTDOWN_SENT.store(true, Ordering::Relaxed);
29+
info!("Shutdown signal sent, waiting for shutdown");
30+
}

crates/ytermusic/src/structures/media.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -203,10 +203,10 @@ pub fn run_window_handler(updater: &Sender<ManagerMessage>) -> Option<()> {
203203
WindowBuilder::new().with_visible(false).build(&event_loop),
204204
)?;
205205
event_loop.run(move |_event, _window_target, ctrl_flow| {
206-
use crate::SIGNALING_STOP;
207-
if SIGNALING_STOP.1.try_recv() == Ok(()) {
206+
use crate::is_shutdown_sent;
207+
208+
if is_shutdown_sent() {
208209
info!("event loop closed");
209-
SIGNALING_STOP.0.send(()).unwrap();
210210
*ctrl_flow = winit::event_loop::ControlFlow::Exit;
211211
exit(0);
212212
}

crates/ytermusic/src/structures/sound_action.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,7 @@ use std::{fs, sync::Arc, time::Duration};
66
use ytpapi2::YoutubeMusicVideoRef;
77

88
use crate::{
9-
consts::CACHE_DIR,
10-
errors::handle_error_option,
11-
systems::{player::PlayerState, DOWNLOAD_MANAGER},
12-
DATABASE, SIGNALING_STOP,
9+
DATABASE, ShutdownSignal, consts::CACHE_DIR, errors::handle_error_option, systems::{DOWNLOAD_MANAGER, player::PlayerState}
1310
};
1411

1512
/// Actions that can be sent to the player from other services
@@ -168,7 +165,7 @@ impl SoundAction {
168165
Self::ReplaceQueue(videos) => {
169166
player.list.truncate(player.current + 1);
170167
DOWNLOAD_MANAGER.clean(
171-
SIGNALING_STOP.1.clone(),
168+
ShutdownSignal,
172169
download_manager_handler(player.soundaction_sender.clone()),
173170
);
174171
Self::AddVideosToQueue(videos).apply_sound_action(player);

crates/ytermusic/src/term/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use ratatui::{backend::CrosstermBackend, layout::Rect, Frame, Terminal};
2525
use ytpapi2::YoutubeMusicVideoRef;
2626

2727
use crate::{
28-
shutdown, structures::sound_action::SoundAction, systems::player::PlayerState, SIGNALING_STOP,
28+
is_shutdown_sent, shutdown, structures::sound_action::SoundAction, systems::player::PlayerState
2929
};
3030

3131
use self::{device_lost::DeviceLost, item_list::ListItem, playlist::Chooser, search::Search};
@@ -203,7 +203,7 @@ impl Manager {
203203

204204
let mut last_tick = Instant::now();
205205
'a: loop {
206-
if matches!(SIGNALING_STOP.1.try_recv(), Ok(())) {
206+
if is_shutdown_sent() {
207207
break;
208208
}
209209
while let Ok(e) = updater.try_recv() {

crates/ytermusic/src/term/playlist.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use crate::{
1010
structures::sound_action::{download_manager_handler, SoundAction},
1111
systems::DOWNLOAD_MANAGER,
1212
utils::invert,
13-
DATABASE, SIGNALING_STOP,
13+
ShutdownSignal, DATABASE,
1414
};
1515

1616
use super::{
@@ -149,7 +149,7 @@ impl Chooser {
149149
}
150150
self.action_sender.send(SoundAction::Cleanup).unwrap();
151151
DOWNLOAD_MANAGER.clean(
152-
SIGNALING_STOP.1.clone(),
152+
ShutdownSignal,
153153
download_manager_handler(self.action_sender.clone()),
154154
);
155155
self.action_sender

crates/ytermusic/src/term/search.rs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,7 @@ use ytpapi2::{
1616
};
1717

1818
use crate::{
19-
consts::CONFIG,
20-
get_header_file, run_service,
21-
structures::sound_action::{download_manager_handler, SoundAction},
22-
systems::DOWNLOAD_MANAGER,
23-
try_get_cookies,
24-
utils::invert,
25-
DATABASE, SIGNALING_STOP,
19+
DATABASE, ShutdownSignal, consts::CONFIG, get_header_file, run_service, structures::sound_action::{SoundAction, download_manager_handler}, systems::DOWNLOAD_MANAGER, try_get_cookies, utils::invert
2620
};
2721

2822
use super::{
@@ -255,7 +249,7 @@ impl Search {
255249
DOWNLOAD_MANAGER.start_task_unary(
256250
download_manager_handler(self.action_sender.clone()),
257251
e,
258-
SIGNALING_STOP.1.clone(),
252+
ShutdownSignal,
259253
);
260254
if modifiers.contains(KeyModifiers::CONTROL) {
261255
EventResponse::None

0 commit comments

Comments
 (0)