Coverage for downtify/mobile_track_ids.py: 97%

35 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""Bounded, asynchronous resolution of mobile track-id batches.""" 

2 

3from __future__ import annotations 

4 

5import asyncio 

6from collections.abc import Callable, Sequence 

7from typing import Any 

8 

9from fastapi import HTTPException 

10 

11from .manual_playlists import MAX_TRACKS_PER_EDIT 

12 

13 

14async def resolve_mobile_track_ids( 

15 sync: Any, 

16 raw_ids: Sequence[Any], 

17 request: Any, 

18 *, 

19 refresh: Callable[[], Any], 

20 filter_paths: Callable[[list[str], Any], list[str]], 

21 max_items: int = MAX_TRACKS_PER_EDIT, 

22) -> list[str]: 

23 """Resolve ids to paths, preserving the input order and duplicates. 

24 

25 Validation and the combined-reference limit must be checked before this 

26 function is called by request handlers. This function also checks both so 

27 it can safely be used directly. SQLite and visibility work run off-loop. 

28 """ 

29 

30 if len(raw_ids) > max_items: 

31 raise HTTPException( 

32 status_code=400, detail='Too many track references' 

33 ) 

34 normalized: list[str] = [] 

35 for value in raw_ids: 

36 if not isinstance(value, str) or not value.strip(): 

37 raise HTTPException( 

38 status_code=400, detail='track_ids must be strings' 

39 ) 

40 normalized.append(value.strip()) 

41 

42 unique = list(dict.fromkeys(normalized)) 

43 if not unique: 

44 return [] 

45 

46 async def lookup() -> dict[str, dict[str, Any]]: 

47 # Keep chunks bounded even when the request uses the full allowance. 

48 merged: dict[str, dict[str, Any]] = {} 

49 for start in range(0, len(unique), 400): 

50 merged.update( 

51 await asyncio.to_thread( 

52 sync.rows_for, unique[start : start + 400] 

53 ) 

54 ) 

55 return merged 

56 

57 rows = await lookup() 

58 if len(rows) != len(unique): 

59 await asyncio.to_thread(refresh) 

60 rows = await lookup() 

61 if len(rows) != len(unique): 

62 raise HTTPException(status_code=404, detail='Track not found') 

63 

64 paths = [str(rows[track_id].get('file') or '') for track_id in unique] 

65 visible = await asyncio.to_thread(filter_paths, paths, request) 

66 visible_set = set(visible) 

67 if any(not path or path not in visible_set for path in paths): 

68 raise HTTPException(status_code=404, detail='Track not found') 

69 by_id = dict(zip(unique, paths)) 

70 return [by_id[track_id] for track_id in normalized]