66import logging
77import sys
88from pathlib import Path
9- from typing import List , Optional
9+ from typing import Awaitable , List , Optional , Sequence , TypeVar
1010
1111import click
1212import httpx
3636
3737logger = logging .getLogger (__name__ )
3838
39+ T = TypeVar ("T" )
40+
41+
42+ async def _gather_in_batches (
43+ tasks : Sequence [Awaitable [T ]], batch_size : int
44+ ) -> List [T ]:
45+ """Gather awaitable tasks in fixed-size batches."""
46+
47+ results : List [T ] = []
48+ for i in range (0 , len (tasks ), batch_size ):
49+ batch = tasks [i : i + batch_size ]
50+ results .extend (await asyncio .gather (* batch ))
51+ return results
52+
3953
4054async def _fetch_imdb (client : httpx .AsyncClient , imdb_id : str ) -> Optional [IMDbTitle ]:
4155 """Fetch metadata for an IMDb ID."""
@@ -137,7 +151,9 @@ def _build_plex_item(item: PlexPartialObject) -> PlexItem:
137151 )
138152
139153
140- async def _load_from_plex (server : PlexServer , tmdb_api_key : str ) -> List [AggregatedItem ]:
154+ async def _load_from_plex (
155+ server : PlexServer , tmdb_api_key : str , * , batch_size : int = 50
156+ ) -> List [AggregatedItem ]:
141157 """Load items from a live Plex server."""
142158
143159 async def _augment_movie (client : httpx .AsyncClient , movie : PlexPartialObject ) -> AggregatedItem :
@@ -174,11 +190,9 @@ async def _augment_episode(
174190 results : List [AggregatedItem ] = []
175191 async with httpx .AsyncClient (timeout = 30 ) as client :
176192 movie_section = server .library .section ("Movies" )
177- movie_tasks = [
178- _augment_movie (client , movie ) for movie in movie_section .all ()
179- ]
193+ movie_tasks = [_augment_movie (client , movie ) for movie in movie_section .all ()]
180194 if movie_tasks :
181- results .extend (await asyncio . gather ( * movie_tasks ))
195+ results .extend (await _gather_in_batches ( movie_tasks , batch_size ))
182196
183197 show_section = server .library .section ("TV Shows" )
184198 for show in show_section .all ():
@@ -187,10 +201,11 @@ async def _augment_episode(
187201 if show_ids .tmdb :
188202 show_tmdb = await _fetch_tmdb_show (client , show_ids .tmdb , tmdb_api_key )
189203 episode_tasks = [
190- _augment_episode (client , episode , show_tmdb ) for episode in show .episodes ()
204+ _augment_episode (client , episode , show_tmdb )
205+ for episode in show .episodes ()
191206 ]
192207 if episode_tasks :
193- results .extend (await asyncio . gather ( * episode_tasks ))
208+ results .extend (await _gather_in_batches ( episode_tasks , batch_size ))
194209 return results
195210
196211
0 commit comments