From 118e82d43272c1a33dcbe4fbc2582154720d693f Mon Sep 17 00:00:00 2001 From: Erica Z Date: Fri, 15 Nov 2024 10:25:10 +0100 Subject: [PATCH] semaphores --- src/subsonic.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/subsonic.rs b/src/subsonic.rs index 57d2300..2ffeca6 100644 --- a/src/subsonic.rs +++ b/src/subsonic.rs @@ -6,6 +6,8 @@ pub use album_list::AlbumListType; use adw::glib; use bytes::Bytes; use rand::Rng; +use std::sync::Arc; +use tokio::sync::Semaphore; use tracing::{event, Level}; fn runtime() -> &'static tokio::runtime::Runtime { @@ -56,6 +58,7 @@ impl From for Error { pub struct Client { client: reqwest::Client, base_url: reqwest::Url, + sem: Arc, } fn random_salt(length: usize) -> String { @@ -106,6 +109,7 @@ impl Client { .user_agent(crate::USER_AGENT) .build()?, base_url, + sem: Arc::new(Semaphore::new(20)), // 20 requests at one time }) } @@ -121,7 +125,10 @@ impl Client { // note that this is why those silly bounds on T are needed, because we're // sending back the result of the query from another thread let future = request.send(); + let sem = Arc::clone(&self.sem); runtime().spawn(async move { + let _permit = sem.acquire().await.unwrap(); + // wrap this logic in a fn so we can use ? async fn perform( response: Result, @@ -195,7 +202,10 @@ impl Client { let (sender, receiver) = async_channel::bounded(1); let future = self.client.get(self.cover_art_url(id, size)).send(); + let sem = Arc::clone(&self.sem); runtime().spawn(async move { + let _permit = sem.acquire().await.unwrap(); + async fn perform( response: Result, ) -> Result {