Files
Downloader-Bot/services/runtime/state_store.py
Mak5erandClaude Fable 5 caffc343af refactor: apply full-project audit — bug fixes, performance, deduplication
Full-codebase audit (149 raw findings, 57 verified and applied).

Fixes:
- download resume: recompute Range header per retry attempt; never resume
  preallocated multipart .part files (silent media corruption)
- inline sends: canonical error tail (rate-limit/queue-busy/timeout/failure)
  for all platforms; YouTube inline no longer strands tokens in
  'processing' for 6h
- admin mailing: exclude banned users; fix Telegram error-text matching
- middlewares: instantiate once and share across message/callback/inline
  so antiflood/ban state no longer fragments
- event loop: move ZIP compression, JSON state persistence, admin FS
  walks, PIL/ffmpeg/ffprobe work off the loop
- download queue: prune idle per-user scopes; cancelled leader releases
  joined duplicate requests
- worker subprocess: disable log sinks (stderr error protocol and log
  rotation no longer race the parent)
- third-party loggers route through app handlers instead of lastResort
- tiktok: fix mojibake reaction emoji; per-user settings in doc callback;
  per-URL locks for short-URL expansion; parallel photo-set downloads
- ci: fix broken yt-dlp auto-bump workflow baseline
- db: drop redundant analytics_events indexes (migration 000010)

Refactoring:
- services/inline/send_flow.py: shared inline delivery flow for all five
  platforms (~640 duplicated lines removed)
- services/media/audio_flow.py: shared MP3 pipeline (was duplicated 6x
  across youtube/youtube_inline/soundcloud/spotify)
- CobaltMediaService base + shared Cobalt response parsing
- services/platforms/ytdlp_helpers.py: shared yt-dlp scaffolding
- register_inline_send_handlers: one chosen_inline_result/callback
  registration factory for 8 handlers
- merge pinterest/threads single-media and media-group flows
- logging decorator factory; remove ~11 dead repository methods

Tests: 470 -> 518 passing, coverage 77.3% -> 80.9% (CI gate 74%).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26 16:25:59 +03:00

110 lines
2.6 KiB
Python

from __future__ import annotations
import asyncio
import atexit
import json
from pathlib import Path
from threading import RLock
from typing import Any, Callable, Optional
_STATE_FILE = Path(__file__).resolve().parents[2] / ".runtime_state.json"
_STATE_LOCK = RLock()
_state: dict[str, Any] = {}
_state_path: Optional[Path] = None
_state_dirty = False
_flush_task: Optional[asyncio.Task] = None
def _load_state_unlocked() -> dict[str, Any]:
if not _STATE_FILE.exists():
return {}
try:
return json.loads(_STATE_FILE.read_text(encoding="utf-8"))
except Exception:
return {}
def _ensure_state_cached_unlocked() -> dict[str, Any]:
global _state, _state_path, _state_dirty
if _state_path != _STATE_FILE:
_state = _load_state_unlocked()
_state_path = _STATE_FILE
_state_dirty = False
return _state
def _write_state_unlocked(state: dict[str, Any]) -> None:
if not state:
if _STATE_FILE.exists():
_STATE_FILE.unlink()
return
_STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
temp_path = _STATE_FILE.with_suffix(".tmp")
temp_path.write_text(
json.dumps(state, ensure_ascii=True, separators=(",", ":")),
encoding="utf-8",
)
temp_path.replace(_STATE_FILE)
def _flush_state() -> None:
global _state_dirty
with _STATE_LOCK:
if not _state_dirty:
return
_state_dirty = False
if _state_path != _STATE_FILE:
return
_write_state_unlocked(_state)
async def _flush_state_async() -> None:
global _flush_task
try:
while True:
await asyncio.to_thread(_flush_state)
with _STATE_LOCK:
if not _state_dirty:
return
finally:
_flush_task = None
def _schedule_flush() -> None:
global _flush_task
try:
loop = asyncio.get_running_loop()
except RuntimeError:
_flush_state()
return
if _flush_task is None or _flush_task.done():
_flush_task = loop.create_task(_flush_state_async())
def load_bucket(name: str, default_factory: Callable[[], Any]) -> Any:
with _STATE_LOCK:
state = _ensure_state_cached_unlocked()
value = state.get(name)
if value is None:
return default_factory()
return value
def save_bucket(name: str, value: Any) -> None:
global _state_dirty
with _STATE_LOCK:
state = _ensure_state_cached_unlocked()
if value:
state[name] = value
else:
state.pop(name, None)
_state_dirty = True
_schedule_flush()
atexit.register(_flush_state)