88import threading
99from typing import Any , Awaitable , Callable , List , Optional , Union
1010
11+ import aiohttp
1112from music_assistant .cache import Cache
1213from music_assistant .config import MassConfig
1314from music_assistant .constants import (
@@ -40,6 +41,7 @@ def __init__(self, datapath):
4041 """
4142
4243 self .loop = None
44+ self ._http_session = None
4345 self ._event_listeners = []
4446 self ._providers = {}
4547 self .config = MassConfig (self , datapath )
@@ -57,13 +59,18 @@ def __init__(self, datapath):
5759
5860 async def async_start (self ):
5961 """Start running the music assistant server."""
62+ # initialize loop
6063 self .loop = asyncio .get_event_loop ()
6164 self .loop .set_exception_handler (self .__handle_exception )
6265 if LOGGER .level == logging .DEBUG :
6366 self .loop .set_debug (True )
67+ # create shared aiohttp ClientSession
68+ self ._http_session = aiohttp .ClientSession (
69+ loop = self .loop ,
70+ connector = aiohttp .TCPConnector (enable_cleanup_closed = True , ssl = False ),
71+ )
6472 await self .database .async_setup ()
6573 await self .cache .async_setup ()
66- await self .metadata .async_setup ()
6774 await self .music_manager .async_setup ()
6875 await self .player_manager .async_setup ()
6976 await self .web .async_setup ()
@@ -79,6 +86,13 @@ async def async_stop(self):
7986 for prov in self ._providers .values ():
8087 await prov .async_on_stop ()
8188 await self .player_manager .async_close ()
89+ await self ._http_session .connector .close ()
90+ self ._http_session .detach ()
91+
92+ @property
93+ def http_session (self ):
94+ """Return the default http session."""
95+ return self ._http_session
8296
8397 async def async_register_provider (self , provider : Provider ):
8498 """Register a new Provider/Plugin."""
@@ -184,6 +198,7 @@ def remove_listener():
184198
185199 return remove_listener
186200
201+ @callback
187202 def add_job (
188203 self , target : Callable [..., Any ], * args : Any
189204 ) -> Optional [asyncio .Future ]:
@@ -205,9 +220,7 @@ def add_job(
205220 if threading .current_thread () is not threading .main_thread ():
206221 # called from other thread
207222 if asyncio .iscoroutine (check_target ):
208- task = asyncio .run_coroutine_threadsafe (
209- target , self .loop
210- ) # type: ignore
223+ task = asyncio .run_coroutine_threadsafe (target , self .loop ) # type: ignore
211224 elif asyncio .iscoroutinefunction (check_target ):
212225 task = asyncio .run_coroutine_threadsafe (target (* args ), self .loop )
213226 elif is_callback (check_target ):
0 commit comments