From 069341513219a3b70dfb46b6959e1a82b85440e1 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 15 Nov 2026 11:42:54 +0100 Subject: [PATCH 1/2] Prevent replay of uncertain playlist refresh starts across scheduler runs --- backend/apps/api/m3u_refresh_handlers.py | 28 ++ backend/apps/api/schemas.py | 23 ++ backend/apps/api/web_api.py | 9 + backend/apps/core/api_utils.py | 41 ++- backend/apps/core/m3u_refresh_guard.py | 128 +++++++++ backend/apps/database/models.py | 16 ++ .../repositories/m3u_refresh_repository.py | 42 +++ backend/tests/test_m3u_refresh_handlers.py | 75 ++++++ backend/tests/test_m3u_refresh_replay.py | 248 ++++++++++++++++++ docs/automation.md | 28 ++ .../components/PlaylistRefreshProtection.jsx | 85 ++++++ frontend/src/pages/AutomationSettings.jsx | 2 + frontend/src/services/api.js | 2 + 13 files changed, 720 insertions(+), 7 deletions(-) create mode 100644 backend/apps/api/m3u_refresh_handlers.py create mode 100644 backend/apps/core/m3u_refresh_guard.py create mode 100644 backend/apps/database/repositories/m3u_refresh_repository.py create mode 100644 backend/tests/test_m3u_refresh_handlers.py create mode 100644 backend/tests/test_m3u_refresh_replay.py create mode 100644 frontend/src/components/PlaylistRefreshProtection.jsx diff --git a/backend/apps/api/m3u_refresh_handlers.py b/backend/apps/api/m3u_refresh_handlers.py new file mode 100644 index 00000000..40fe4c9b --- /dev/null +++ b/backend/apps/api/m3u_refresh_handlers.py @@ -0,0 +1,28 @@ +"""Visibility and operator-confirmed resolution of ambiguous refresh starts.""" + +from apps.api.schemas import M3URefreshResolutionSchema +from apps.core.api_responses import error_response, success_response +from apps.core.api_utils import get_m3u_refresh_guard +from apps.core.exceptions import ValidationError +from apps.core.logging_config import setup_logging +from apps.core.m3u_refresh_guard import RefreshStartBlocked + +logger = setup_logging(__name__) + + +def m3u_refresh_attempts_response(*, method, payload=None, get_guard=None): + try: + if method == 'POST': + resolution = M3URefreshResolutionSchema.from_payload(payload) + guard = (get_guard or get_m3u_refresh_guard)() + guard.resolve(resolution.account_id, resolution.attempt_id, resolution.confirmed_finished) + return success_response(message='Protection resolved. Future refresh starts are allowed; no refresh was started by this action.') + guard = (get_guard or get_m3u_refresh_guard)() + return success_response(data={'attempts': guard.pending()}) + except ValidationError as exc: + return error_response(str(exc), status_code=400, code='validation_error') + except RefreshStartBlocked as exc: + return error_response(str(exc), status_code=409, code='refresh_start_unresolved') + except Exception: + logger.exception('Could not access playlist refresh protection') + return error_response('Could not access playlist refresh protection', status_code=500, code='internal_error') diff --git a/backend/apps/api/schemas.py b/backend/apps/api/schemas.py index 881a78df..893fc627 100644 --- a/backend/apps/api/schemas.py +++ b/backend/apps/api/schemas.py @@ -11,6 +11,29 @@ def _ensure_dict(payload: Any, *, message: str) -> Dict[str, Any]: return payload +@dataclass(frozen=True) +class M3URefreshResolutionSchema: + account_id: int + attempt_id: str + confirmed_finished: bool + + @classmethod + def from_payload(cls, payload: Any) -> "M3URefreshResolutionSchema": + from uuid import UUID + + data = _ensure_dict(payload, message='Resolution data is required') + account_id = data.get('account_id') + if type(account_id) is not int or account_id <= 0: + raise ValidationError('account_id must be a positive integer') + try: + attempt_id = str(UUID(data.get('attempt_id', ''))) + except (ValueError, TypeError, AttributeError): + raise ValidationError('attempt_id must identify the pending refresh start') from None + if data.get('confirmed_finished') is not True: + raise ValidationError('Confirm that both live and VOD refresh tasks have finished or stopped in Dispatcharr') + return cls(account_id=account_id, attempt_id=attempt_id, confirmed_finished=True) + + def _parse_bool(value: Any, *, field_name: str) -> bool: if isinstance(value, bool): return value diff --git a/backend/apps/api/web_api.py b/backend/apps/api/web_api.py index a8c91c46..54fea830 100644 --- a/backend/apps/api/web_api.py +++ b/backend/apps/api/web_api.py @@ -1181,6 +1181,15 @@ def handle_global_automation_settings(): get_automation_manager=get_automation_manager, ) + +@app.route('/api/m3u-refresh/attempts', methods=['GET']) +@app.route('/api/m3u-refresh/attempts/resolve', methods=['POST']) +def handle_m3u_refresh_attempts(): + from apps.api.m3u_refresh_handlers import m3u_refresh_attempts_response + + return m3u_refresh_attempts_response(method=request.method, payload=request.get_json(silent=True)) + + @app.route('/api/regex-patterns/mass-edit-preview', methods=['POST']) def mass_edit_preview(): """Preview the results of a mass find/replace operation on regex patterns. diff --git a/backend/apps/core/api_utils.py b/backend/apps/core/api_utils.py index 4e8e28f7..3686346c 100644 --- a/backend/apps/core/api_utils.py +++ b/backend/apps/core/api_utils.py @@ -566,14 +566,32 @@ def refresh_m3u_playlists( Raises: Exception: If the API request fails. """ - base_url = _get_base_url() - if account_id: - url = f"{base_url}/api/m3u/refresh/{account_id}/" - else: - url = f"{base_url}/api/m3u/refresh/" - try: - resp = post_request(url, {}) + base_url = _get_base_url().rstrip('/') + guard = get_m3u_refresh_guard() + if account_id is None: + # Split bulk starts so a pending individual operation cannot be + # bypassed by the refresh-all endpoint (or vice versa). + accounts = fetch_data_from_url(f'{base_url}/api/m3u/accounts/') + if not isinstance(accounts, list) or not accounts: + raise requests.exceptions.RequestException('Could not verify M3U accounts; bulk refresh was not sent') + responses, failed = [], [] + for account in accounts: + if not account.get('is_active', True) or str(account.get('name', '')).lower() == 'custom': + continue + try: + responses.append(refresh_m3u_playlists(int(account['id']))) + except requests.exceptions.RequestException: + failed.append(account['id']) + if failed: + raise requests.exceptions.RequestException( + f'M3U refresh could not start for account IDs {failed}; other eligible accounts were processed' + ) + if not responses: + raise requests.exceptions.RequestException('No eligible accounts for bulk refresh') + return responses[-1] + account_id = int(account_id) + resp = guard.start(account_id, lambda: post_request(f'{base_url}/api/m3u/refresh/{account_id}/', {})) logger.info("M3U refresh request accepted by Dispatcharr") return resp except Exception as e: @@ -581,6 +599,15 @@ def refresh_m3u_playlists( raise +def get_m3u_refresh_guard(): + from apps.core.m3u_refresh_guard import M3URefreshGuard + + base_url = _get_base_url().rstrip('/') + return M3URefreshGuard(base_url, lambda account_id: fetch_data_from_url( + f'{base_url}/api/m3u/accounts/{account_id}/', + )) + + def get_m3u_accounts() -> Optional[List[Dict[str, Any]]]: """ Fetch all M3U accounts from the UDI cache. diff --git a/backend/apps/core/m3u_refresh_guard.py b/backend/apps/core/m3u_refresh_guard.py new file mode 100644 index 00000000..1a5ec89e --- /dev/null +++ b/backend/apps/core/m3u_refresh_guard.py @@ -0,0 +1,128 @@ +"""Prevent replays of refresh POSTs whose admission cannot be established. + +Dispatcharr's account status describes live imports. In particular, a terminal +live status does not establish completion of the separately queued VOD work. +An ambiguous start therefore needs an operator-confirmed resolution; neither a +timeout nor a stale/idle account snapshot is permission to submit it again. +""" + +import hashlib +import json +import time +import uuid + +import requests + +from apps.database.repositories.m3u_refresh_repository import M3URefreshRepository + + +BUSY_STATUSES = frozenset({ + 'building', 'downloading', 'fetching', 'importing', 'refreshing', 'in_progress', + 'loading', 'parsing', 'pending', 'preparing', 'processing', 'queued', 'running', + 'started', 'syncing', 'updating', +}) +BUSY_KEYS = ('is_refreshing', 'refreshing', 'is_updating', 'updating', 'processing', + 'in_progress', 'task_running', 'queued', 'is_queued') + + +def account_is_busy(account): + return any( + account.get(key) is True or str(account.get(key)).strip().lower() in {'true', 'yes', '1', 'running'} + for key in BUSY_KEYS + ) or any( + str(account.get(key, '')).strip().lower() in BUSY_STATUSES + for key in ('status', 'state', 'refresh_status', 'last_refresh_status') + ) + + +class RefreshStartBlocked(requests.exceptions.RequestException): + """A previous start may still be running; a new POST is not permitted.""" + + +def accepted_existing_response(): + response = requests.Response() + response.status_code = 202 + response._content = json.dumps({'success': True, 'already_running': True}).encode() + return response + + +class M3URefreshGuard: + def __init__(self, base_url, fetch_account, repository=None): + self.scope = hashlib.sha256(base_url.rstrip('/').encode()).hexdigest() + self.fetch_account = fetch_account + self.repository = repository or M3URefreshRepository() + + def _account(self, account_id): + account = self.fetch_account(account_id) + if not isinstance(account, dict) or account.get('id') != account_id: + raise RefreshStartBlocked( + f'Could not verify current Dispatcharr status for M3U account {account_id}; refresh was not sent' + ) + return account + + def start(self, account_id, send): + attempt_id = str(uuid.uuid4()) + # Commit before sending: a crash at any later point leaves a durable guard. + if not self.repository.claim(self.scope, account_id, attempt_id, time.time()): + raise RefreshStartBlocked( + f'M3U account {account_id} has an unresolved refresh start; no new POST was sent. ' + 'Check live and VOD tasks in Dispatcharr, then resolve it under ' + 'Settings -> Scheduling -> Playlist refresh protection.' + ) + try: + account = self._account(account_id) + if account_is_busy(account): + self.repository.release(self.scope, account_id, attempt_id) + return accepted_existing_response() + except Exception: + # No start has been attempted yet; there is no ambiguous POST to protect. + self.repository.release(self.scope, account_id, attempt_id) + raise + + try: + response = send() + except requests.exceptions.ConnectTimeout: + self.repository.release(self.scope, account_id, attempt_id) + raise + except requests.exceptions.HTTPError as exc: + status = getattr(exc.response, 'status_code', None) + if status is not None and 400 <= status < 500 and status != 408: + self.repository.release(self.scope, account_id, attempt_id) + else: + self.repository.uncertain(self.scope, account_id, attempt_id) + raise + except BaseException: + self.repository.uncertain(self.scope, account_id, attempt_id) + raise + # An explicit acceptance resolves admission uncertainty. The existing + # refresh monitor owns completion; this is not a claim that VOD is done. + self.repository.release(self.scope, account_id, attempt_id) + return response + + def pending(self): + result = [] + for attempt in self.repository.pending(self.scope): + item = {key: value for key, value in attempt.items() if key != 'server_scope'} + item['request_in_flight'] = attempt['state'] == 'sending' and time.time() - attempt['started_at'] < 180 + try: + account = self._account(attempt['account_id']) + item.update(name=account.get('name'), status=account.get('status'), + busy=account_is_busy(account), status_available=True) + except requests.exceptions.RequestException: + item.update(status_available=False, busy=None) + result.append(item) + return result + + def resolve(self, account_id, attempt_id, confirmed_finished): + if confirmed_finished is not True: + raise ValueError('Confirm that both live and VOD refresh tasks have finished or stopped in Dispatcharr') + attempt = next((item for item in self.repository.pending(self.scope) + if item['account_id'] == account_id and item['attempt_id'] == attempt_id), None) + if attempt is None: + raise RefreshStartBlocked('This refresh attempt no longer exists; reload its status') + if attempt['state'] == 'sending' and time.time() - attempt['started_at'] < 180: + raise RefreshStartBlocked('The refresh start request may still be in flight; wait and reload its status') + if account_is_busy(self._account(account_id)): + raise RefreshStartBlocked('Dispatcharr still reports a running refresh; no protection was removed') + if not self.repository.release(self.scope, account_id, attempt_id): + raise RefreshStartBlocked('The refresh attempt changed; reload its status') diff --git a/backend/apps/database/models.py b/backend/apps/database/models.py index ef2b7d9b..dbadc652 100644 --- a/backend/apps/database/models.py +++ b/backend/apps/database/models.py @@ -104,6 +104,22 @@ class M3UAccount(Base): groups = relationship("ChannelGroup", secondary=group_accounts, back_populates="accounts") +class M3URefreshAttempt(Base): + """Write-ahead protection for refresh starts with an uncertain outcome. + + Independent of the UDI cache lifecycle and scoped to the Dispatcharr server. + No foreign key: refreshing/rebuilding cached accounts must not lose protection. + """ + + __tablename__ = 'm3u_refresh_attempts' + + server_scope = Column(String(64), primary_key=True) + account_id = Column(Integer, primary_key=True) + attempt_id = Column(String(36), nullable=False) + started_at = Column(Float, nullable=False) + state = Column(String(20), nullable=False) + + class M3UAccountProfile(Base): __tablename__ = 'm3u_account_profiles' diff --git a/backend/apps/database/repositories/m3u_refresh_repository.py b/backend/apps/database/repositories/m3u_refresh_repository.py new file mode 100644 index 00000000..69a42cf8 --- /dev/null +++ b/backend/apps/database/repositories/m3u_refresh_repository.py @@ -0,0 +1,42 @@ +"""Atomic, durable admission of individual Dispatcharr refresh starts.""" + +from sqlalchemy.dialects.sqlite import insert + +from apps.database import connection +from apps.database.models import M3URefreshAttempt + + +def _values(row): + return {column.name: getattr(row, column.name) for column in row.__table__.columns} + + +class M3URefreshRepository: + def claim(self, scope, account_id, attempt_id, started_at): + with connection.get_session() as session: + result = session.execute(insert(M3URefreshAttempt).values( + server_scope=scope, account_id=account_id, attempt_id=attempt_id, + started_at=started_at, state='sending', + ).on_conflict_do_nothing()) + session.commit() + return result.rowcount == 1 + + def pending(self, scope): + with connection.get_session() as session: + return [_values(row) for row in session.query(M3URefreshAttempt).filter_by( + server_scope=scope, + ).order_by(M3URefreshAttempt.account_id).all()] + + def uncertain(self, scope, account_id, attempt_id): + with connection.get_session() as session: + session.query(M3URefreshAttempt).filter_by( + server_scope=scope, account_id=account_id, attempt_id=attempt_id, + ).update({'state': 'unknown'}) + session.commit() + + def release(self, scope, account_id, attempt_id): + with connection.get_session() as session: + count = session.query(M3URefreshAttempt).filter_by( + server_scope=scope, account_id=account_id, attempt_id=attempt_id, + ).delete() + session.commit() + return count == 1 diff --git a/backend/tests/test_m3u_refresh_handlers.py b/backend/tests/test_m3u_refresh_handlers.py new file mode 100644 index 00000000..120038e7 --- /dev/null +++ b/backend/tests/test_m3u_refresh_handlers.py @@ -0,0 +1,75 @@ +"""The recovery API requires an explicit, current operator resolution.""" + +from unittest.mock import Mock +from uuid import uuid4 + +from flask import Flask +import pytest +import requests + +from apps.api.m3u_refresh_handlers import m3u_refresh_attempts_response +from apps.core.m3u_refresh_guard import M3URefreshGuard + + +@pytest.fixture +def pending(): + account = {'id': 9, 'name': 'Fixture', 'status': 'success'} + guard = M3URefreshGuard('http://private-target.invalid', lambda _: account) + send = Mock(side_effect=requests.exceptions.ReadTimeout()) + with pytest.raises(requests.exceptions.ReadTimeout): + guard.start(9, send) + return guard, account, guard.pending()[0] + + +def call(guard, method='GET', payload=None): + with Flask(__name__).app_context(): + response, code = m3u_refresh_attempts_response(method=method, payload=payload, get_guard=lambda: guard) + return response.get_json(), code + + +def test_pending_status_reports_unknown_without_exposing_server_scope(pending): + guard, _, attempt = pending + data, code = call(guard) + assert code == 200 + assert data['data']['attempts'][0]['attempt_id'] == attempt['attempt_id'] + assert data['data']['attempts'][0]['state'] == 'unknown' + assert data['data']['attempts'][0]['status_available'] is True + assert 'server_scope' not in data['data']['attempts'][0] + assert 'private-target' not in str(data) + + +@pytest.mark.parametrize('change', [ + {'confirmed_finished': False}, {'confirmed_finished': 'true'}, + {'confirmed_finished': None}, {'account_id': True}, {'account_id': '9'}, + {'account_id': -1}, {'attempt_id': ''}, {'attempt_id': []}, +]) +def test_invalid_resolution_cannot_remove_protection(pending, change): + guard, _, attempt = pending + payload = {'account_id': 9, 'attempt_id': attempt['attempt_id'], 'confirmed_finished': True, **change} + data, code = call(guard, 'POST', payload) + assert code == 400 + assert data['success'] is False + assert len(guard.pending()) == 1 + + +def test_resolution_is_conditional_and_does_not_start_a_refresh(pending): + guard, _, attempt = pending + payload = {'account_id': 9, 'attempt_id': str(uuid4()), 'confirmed_finished': True} + assert call(guard, 'POST', payload)[1] == 409 + payload['attempt_id'] = attempt['attempt_id'] + data, code = call(guard, 'POST', payload) + assert code == 200 + assert 'no refresh was started' in data['message'] + assert guard.pending() == [] + assert call(guard, 'POST', payload)[1] == 409 + + +def test_live_busy_status_denies_resolution(pending): + guard, account, attempt = pending + account['status'] = 'parsing' + data, code = call(guard, 'POST', { + 'account_id': 9, 'attempt_id': attempt['attempt_id'], 'confirmed_finished': True, + }) + assert code == 409 + assert 'running refresh' in data['error'] + assert len(guard.pending()) == 1 diff --git a/backend/tests/test_m3u_refresh_replay.py b/backend/tests/test_m3u_refresh_replay.py new file mode 100644 index 00000000..140436ce --- /dev/null +++ b/backend/tests/test_m3u_refresh_replay.py @@ -0,0 +1,248 @@ +"""Refresh starts must not replay an operation whose outcome is unknown.""" + +from datetime import datetime, timedelta +from unittest.mock import Mock + +import pytest +import requests + +from apps.automation import automated_stream_manager as automation +from apps.core import api_utils +from apps.core.m3u_refresh_guard import M3URefreshGuard, RefreshStartBlocked + + +def accepted(): + response = requests.Response() + response.status_code = 202 + response._content = b'{"success":true}' + return response + + +@pytest.fixture +def account(): + return {'id': 9, 'name': 'Fixture', 'status': 'success', 'enable_vod': True} + + +@pytest.fixture +def guard(account): + return M3URefreshGuard('http://dispatcharr.invalid', lambda _: account) + + +def unknown_start(guard): + send = Mock(side_effect=requests.exceptions.ReadTimeout('Reply lost after admission')) + with pytest.raises(requests.exceptions.ReadTimeout): + guard.start(9, send) + return send + + +def test_daily_period_does_not_repost_after_unknown_refresh(monkeypatch): + manager = automation.AutomatedStreamManager.__new__(automation.AutomatedStreamManager) + manager.config = { + 'enabled_features': {'auto_playlist_update': True, 'changelog_tracking': False}, + 'enabled_m3u_accounts': [], + 'm3u_refresh_wait': {'timeout_seconds': 600, 'retry_failed_providers': False}, + } + manager.period_last_run = {'daily': datetime.now() - timedelta(days=1, minutes=5)} + manager._get_period_scheduler_retry = lambda _: None + manager._get_missed_run_grace_minutes = lambda _: 0 + now = datetime.now() + period = {'schedule': {'type': 'cron', 'value': f'{now.minute} {now.hour} * * *'}} + post = Mock(side_effect=requests.exceptions.ReadTimeout('Start may have been accepted')) + monkeypatch.setattr(api_utils, '_get_base_url', lambda: 'http://dispatcharr.invalid') + monkeypatch.setattr(api_utils, '_get_auth_headers', lambda: {}) + monkeypatch.setattr(api_utils, 'fetch_data_from_url', lambda _: { + 'id': 9, 'name': 'Fixture', 'status': 'idle', + }) + monkeypatch.setattr(api_utils.http_transport, 'post', post) + monkeypatch.setattr(automation, 'get_m3u_accounts', lambda: [ + {'id': 9, 'name': 'Fixture', 'is_active': True, 'status': 'idle'}, + ]) + + for _ in range(2): + assert manager._is_period_due('daily', period) + assert not manager.refresh_playlists(account_id=9, skip_changelog=True) + assert not manager._advance_period_run_timestamps({('daily', 'Daily'): {}}, 'failed') + + assert post.call_count == 1 + + +def test_unknown_survives_new_coordinator_and_terminal_live_status(guard, account): + send = unknown_start(guard) + account['updated_at'] = '2099-01-01T00:00:00Z' + restarted = M3URefreshGuard('http://dispatcharr.invalid/', lambda _: account) + with pytest.raises(RefreshStartBlocked, match='unresolved'): + restarted.start(9, send) + assert send.call_count == 1 + assert restarted.pending()[0]['state'] == 'unknown' + + +@pytest.mark.parametrize('status', ['idle', 'success', 'processing', 'fetching', 'error']) +def test_account_status_alone_never_replays_unknown_start(guard, account, status): + send = unknown_start(guard) + account['status'] = status + with pytest.raises(RefreshStartBlocked): + guard.start(9, send) + assert send.call_count == 1 + + +def test_write_ahead_claim_protects_crash_before_result_is_saved(guard): + send = Mock(side_effect=KeyboardInterrupt) + with pytest.raises(KeyboardInterrupt): + guard.start(9, send) + with pytest.raises(RefreshStartBlocked): + guard.start(9, send) + assert send.call_count == 1 + + +def test_unavailable_status_prevents_new_start_without_leaving_false_uncertainty(account): + guard = M3URefreshGuard('http://dispatcharr.invalid', lambda _: None) + send = Mock(return_value=accepted()) + with pytest.raises(RefreshStartBlocked, match='Could not verify'): + guard.start(9, send) + send.assert_not_called() + assert guard.repository.pending(guard.scope) == [] + + +def test_unknown_remains_protected_when_status_cannot_be_read(guard): + send = unknown_start(guard) + guard.fetch_account = lambda _: None + assert guard.pending()[0]['status_available'] is False + attempt = guard.repository.pending(guard.scope)[0] + with pytest.raises(RefreshStartBlocked): + guard.resolve(9, attempt['attempt_id'], True) + assert len(guard.repository.pending(guard.scope)) == 1 + assert send.call_count == 1 + + +def test_operator_resolution_requires_confirmation_and_matching_attempt(guard): + send = unknown_start(guard) + attempt = guard.pending()[0] + with pytest.raises(ValueError): + guard.resolve(9, attempt['attempt_id'], False) + with pytest.raises(RefreshStartBlocked): + guard.resolve(9, 'stale-attempt', True) + guard.resolve(9, attempt['attempt_id'], True) + assert guard.pending() == [] + assert send.call_count == 1 # Resolving never starts another refresh itself. + send.side_effect = None + send.return_value = accepted() + assert guard.start(9, send).status_code == 202 + assert send.call_count == 2 + + +def test_running_account_cannot_be_resolved_even_with_operator_confirmation(guard, account): + unknown_start(guard) + attempt = guard.pending()[0] + account['status'] = 'processing' + with pytest.raises(RefreshStartBlocked, match='still reports'): + guard.resolve(9, attempt['attempt_id'], True) + assert len(guard.pending()) == 1 + + +def test_recent_in_flight_request_cannot_be_resolved(guard): + assert guard.repository.claim(guard.scope, 9, 'in-flight', datetime.now().timestamp()) + with pytest.raises(RefreshStartBlocked, match='in flight'): + guard.resolve(9, 'in-flight', True) + + +def test_old_sending_claim_survives_restart_until_explicit_resolution(guard): + assert guard.repository.claim(guard.scope, 9, 'crashed', 1) + send = Mock(return_value=accepted()) + with pytest.raises(RefreshStartBlocked): + guard.start(9, send) + guard.resolve(9, 'crashed', True) + send.assert_not_called() + + +def test_known_acceptance_and_busy_account_preserve_normal_behavior(guard, account): + send = Mock(return_value=accepted()) + assert guard.start(9, send).status_code == 202 + assert guard.pending() == [] + account['status'] = 'fetching' + assert guard.start(9, send).json()['already_running'] is True + assert send.call_count == 1 + + +def test_different_accounts_and_servers_are_independent(guard, account): + unknown_start(guard) + other = M3URefreshGuard('http://other-dispatcharr.invalid', lambda _: account) + assert other.start(9, accepted).status_code == 202 + guard.fetch_account = lambda aid: {**account, 'id': aid} + assert guard.start(10, accepted).status_code == 202 + assert [item['account_id'] for item in guard.pending()] == [9] + + +@pytest.mark.parametrize('code', [400, 401, 403, 404, 409, 429]) +def test_explicit_rejection_allows_safe_later_attempt(guard, code): + response = accepted() + response.status_code = code + send = Mock(side_effect=requests.exceptions.HTTPError(response=response)) + with pytest.raises(requests.exceptions.HTTPError): + guard.start(9, send) + assert guard.pending() == [] + + +@pytest.mark.parametrize('error', [requests.exceptions.ConnectTimeout()]) +def test_connection_establishment_failure_does_not_leave_uncertainty(guard, error): + send = Mock(side_effect=error) + with pytest.raises(type(error)): + guard.start(9, send) + assert guard.pending() == [] + + +@pytest.mark.parametrize('code', [408, 500, 502, 503]) +def test_ambiguous_server_error_stays_protected(guard, code): + response = accepted() + response.status_code = code + send = Mock(side_effect=requests.exceptions.HTTPError(response=response)) + with pytest.raises(requests.exceptions.HTTPError): + guard.start(9, send) + assert guard.pending()[0]['state'] == 'unknown' + + +def test_bulk_refresh_cannot_bypass_pending_account_and_continues_other_accounts(monkeypatch, account): + monkeypatch.setattr(api_utils, '_get_base_url', lambda: 'http://dispatcharr.invalid') + accounts = [account, {**account, 'id': 10}] + monkeypatch.setattr(api_utils, 'fetch_data_from_url', lambda url: accounts if url.endswith('/accounts/') + else accounts[1] if url.endswith('/10/') else account) + guard = api_utils.get_m3u_refresh_guard() + unknown_start(guard) + send = Mock(return_value=accepted()) + monkeypatch.setattr(api_utils, 'post_request', send) + with pytest.raises(requests.exceptions.RequestException, match='account IDs'): + api_utils.refresh_m3u_playlists() + assert send.call_count == 1 + assert send.call_args.args[0].endswith('/refresh/10/') + + +def test_concurrent_process_style_claims_use_database_atomicity(tmp_path, monkeypatch, account): + from concurrent.futures import ThreadPoolExecutor + import threading + from sqlalchemy import create_engine + from sqlalchemy.orm import sessionmaker + from apps.database import connection + + engine = create_engine(f'sqlite:///{tmp_path / "refresh.db"}', connect_args={'check_same_thread': False}) + connection.Base.metadata.create_all(engine) + monkeypatch.setattr(connection, 'get_session', sessionmaker(bind=engine)) + first = M3URefreshGuard('http://dispatcharr.invalid', lambda _: account) + second = M3URefreshGuard('http://dispatcharr.invalid', lambda _: account) + entered, finish = threading.Event(), threading.Event() + + def send(): + entered.set() + assert finish.wait(5) + return accepted() + + try: + with ThreadPoolExecutor(max_workers=2) as pool: + future = pool.submit(first.start, 9, send) + assert entered.wait(5) + try: + with pytest.raises(RefreshStartBlocked): + second.start(9, Mock()) + finally: + finish.set() + assert future.result(timeout=5).status_code == 202 + finally: + engine.dispose() diff --git a/docs/automation.md b/docs/automation.md index 2fdf6dd8..941290ac 100644 --- a/docs/automation.md +++ b/docs/automation.md @@ -30,6 +30,34 @@ Profiles live in `automation_config.json` under `profiles`. A profile has three - `enabled` — run the M3U refresh step - `playlists` — list of playlist IDs to update (empty = all) +### Playlist refresh protection + +If Dispatcharr may have accepted a refresh start but its HTTP reply is lost, +StreamFlow stores that uncertainty in its database before allowing any further +start. The protection survives restarts and applies to automatic, manual, +single-channel and bulk refresh requests for the same Dispatcharr account. +Other accounts can still refresh. A failed run can remain due without sending +another POST for the protected account. + +Inspect unresolved starts under **Settings → Scheduling → Playlist refresh +protection**. Select **Reload refresh status** to read the current account +status directly from Dispatcharr. A successful or idle live-import status does +not establish completion of the separately queued VOD work in Dispatcharr 0.33. + +After verifying in Dispatcharr that both the live import and any VOD tasks have +finished or stopped, select the confirmation checkbox and **Allow future +refreshes**. This removes protection for that specific start; it does not trigger +a refresh. The action is rejected while a current start request may still be +in flight, Dispatcharr reports a busy account, its status is unavailable, or +the displayed attempt has changed. Protection does not expire automatically. + +The HTTP start acknowledgement still has a 30-second timeout (backend-only). +Refresh-completion monitoring has a separate timeout; increasing that wait or +switching **Settings → Scheduling → Automation Run Policy → Retry failed M3U +providers** off does not resolve an ambiguous start. To let Dispatcharr own the +schedule while investigating, disable **Settings → Profiles → edit profile → +Playlist Updating** for the affected profile. + ### `stream_matching` ```json diff --git a/frontend/src/components/PlaylistRefreshProtection.jsx b/frontend/src/components/PlaylistRefreshProtection.jsx new file mode 100644 index 00000000..95665608 --- /dev/null +++ b/frontend/src/components/PlaylistRefreshProtection.jsx @@ -0,0 +1,85 @@ +import { useEffect, useState } from 'react' +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card.jsx' +import { Button } from '@/components/ui/button.jsx' +import { Checkbox } from '@/components/ui/checkbox.jsx' +import { automationAPI } from '@/services/api.js' + +export default function PlaylistRefreshProtection() { + const [attempts, setAttempts] = useState([]) + const [loading, setLoading] = useState(true) + const [resolving, setResolving] = useState(null) + const [confirmed, setConfirmed] = useState({}) + const [error, setError] = useState(null) + const [message, setMessage] = useState(null) + + const load = async () => { + setLoading(true) + setError(null) + setConfirmed({}) + try { + const response = await automationAPI.getRefreshAttempts() + setAttempts(response.data.data.attempts) + } catch (err) { + setError(err.response?.data?.error || 'Could not load playlist refresh protection. Reload before resolving a start.') + } finally { + setLoading(false) + } + } + useEffect(() => { load() }, []) + + const resolve = async (attempt) => { + setResolving(attempt.attempt_id) + setError(null) + setMessage(null) + try { + const response = await automationAPI.resolveRefreshAttempt({ + account_id: attempt.account_id, attempt_id: attempt.attempt_id, confirmed_finished: true, + }) + setMessage(response.data.message) + await load() + } catch (err) { + setError(err.response?.data?.error || 'Could not resolve this start. Reload its current status before trying again.') + setConfirmed({}) + } finally { + setResolving(null) + } + } + + return + + Playlist refresh protection + + When Dispatcharr may have accepted a refresh but its reply is missing, StreamFlow blocks another start for that playlist, including after a restart. + + + + + {loading &&

Loading refresh protection…

} + {error &&

{error}

} + {message &&

{message}

} + {!loading && !error && attempts.length === 0 &&

No unresolved playlist refresh starts.

} + {attempts.map(attempt => { + const disabled = loading || resolving !== null || !!error || !attempt.status_available || attempt.busy || attempt.request_in_flight + const checkboxId = `confirm-refresh-${attempt.attempt_id}` + return
+

{attempt.name || `Playlist ${attempt.account_id}`}

+

+ Start outcome {attempt.state === 'sending' ? 'unconfirmed' : 'unknown'} since {new Date(attempt.started_at * 1000).toLocaleString()}. + {' '}Current account status: {attempt.status_available ? (attempt.status || 'not reported') : 'unavailable'}. +

+

Check Dispatcharr and verify that both the live import and any VOD refresh tasks have finished or stopped. An idle or successful account status alone does not prove that VOD has finished.

+ {attempt.request_in_flight &&

The start request may still be in flight. Wait and reload its status.

} + {attempt.busy &&

Dispatcharr still reports a running refresh.

} +
+ setConfirmed(prev => ({ ...prev, [attempt.attempt_id]: checked === true }))} /> + +
+ +
+ })} +
+
+} diff --git a/frontend/src/pages/AutomationSettings.jsx b/frontend/src/pages/AutomationSettings.jsx index 8a58f75c..121efec4 100644 --- a/frontend/src/pages/AutomationSettings.jsx +++ b/frontend/src/pages/AutomationSettings.jsx @@ -13,6 +13,7 @@ import { automationAPI, dispatcharrAPI, openstreamAPI, sessionSettingsAPI, sched import AutomationProfileStudio from '@/components/Automation/AutomationProfileStudio.jsx' import AutomationPeriods from '@/components/Automation/AutomationPeriods.jsx' import PlaybackStabilitySettings from '@/components/PlaybackStability.jsx' +import PlaylistRefreshProtection from '@/components/PlaylistRefreshProtection.jsx' import { saveSettingsSection, SETTINGS_SAVE_DEPENDENCIES } from '@/lib/settings-save.js' const DEFAULT_UDI_REFRESH_INTERVAL_MINUTES = 240 @@ -278,6 +279,7 @@ export default function AutomationSettings() { + Event Scheduling diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js index a43f68ff..0b739f53 100644 --- a/frontend/src/services/api.js +++ b/frontend/src/services/api.js @@ -47,6 +47,8 @@ api.interceptors.response.use( export const automationAPI = { // Status and Control getStatus: (options) => api.get('/automation/status', options), + getRefreshAttempts: () => api.get('/m3u-refresh/attempts'), + resolveRefreshAttempt: (resolution) => api.post('/m3u-refresh/attempts/resolve', resolution), start: () => api.post('/automation/start'), stop: () => api.post('/automation/stop'), abortRun: () => api.post('/automation/abort-run'), From 969de4f1beb64f82bcac6c670d79c1d5ec334e8d Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 15 Nov 2026 12:10:51 +0100 Subject: [PATCH 2/2] Keep refresh admission and bulk starts scoped to the captured Dispatcharr target --- backend/apps/core/api_utils.py | 20 +++++++++++++------- backend/tests/test_m3u_refresh_replay.py | 20 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/backend/apps/core/api_utils.py b/backend/apps/core/api_utils.py index 3686346c..6027c12a 100644 --- a/backend/apps/core/api_utils.py +++ b/backend/apps/core/api_utils.py @@ -568,7 +568,15 @@ def refresh_m3u_playlists( """ try: base_url = _get_base_url().rstrip('/') - guard = get_m3u_refresh_guard() + guard = get_m3u_refresh_guard(base_url) + + def start_account(target_id): + response = guard.start(target_id, lambda: post_request( + f'{base_url}/api/m3u/refresh/{target_id}/', {}, + )) + logger.info("M3U refresh request accepted by Dispatcharr") + return response + if account_id is None: # Split bulk starts so a pending individual operation cannot be # bypassed by the refresh-all endpoint (or vice versa). @@ -580,7 +588,7 @@ def refresh_m3u_playlists( if not account.get('is_active', True) or str(account.get('name', '')).lower() == 'custom': continue try: - responses.append(refresh_m3u_playlists(int(account['id']))) + responses.append(start_account(int(account['id']))) except requests.exceptions.RequestException: failed.append(account['id']) if failed: @@ -591,18 +599,16 @@ def refresh_m3u_playlists( raise requests.exceptions.RequestException('No eligible accounts for bulk refresh') return responses[-1] account_id = int(account_id) - resp = guard.start(account_id, lambda: post_request(f'{base_url}/api/m3u/refresh/{account_id}/', {})) - logger.info("M3U refresh request accepted by Dispatcharr") - return resp + return start_account(account_id) except Exception as e: logger.error(f"Failed to refresh M3U playlists: {e}") raise -def get_m3u_refresh_guard(): +def get_m3u_refresh_guard(base_url: Optional[str] = None): from apps.core.m3u_refresh_guard import M3URefreshGuard - base_url = _get_base_url().rstrip('/') + base_url = (base_url if base_url is not None else _get_base_url()).rstrip('/') return M3URefreshGuard(base_url, lambda account_id: fetch_data_from_url( f'{base_url}/api/m3u/accounts/{account_id}/', )) diff --git a/backend/tests/test_m3u_refresh_replay.py b/backend/tests/test_m3u_refresh_replay.py index 140436ce..afdff3a6 100644 --- a/backend/tests/test_m3u_refresh_replay.py +++ b/backend/tests/test_m3u_refresh_replay.py @@ -215,6 +215,26 @@ def test_bulk_refresh_cannot_bypass_pending_account_and_continues_other_accounts assert send.call_args.args[0].endswith('/refresh/10/') +@pytest.mark.parametrize('target', [9, None]) +def test_refresh_keeps_its_original_target_if_connection_settings_change(monkeypatch, account, target): + base_url = Mock(side_effect=['http://original.invalid', 'http://changed.invalid']) + monkeypatch.setattr(api_utils, '_get_base_url', base_url) + accounts = [account, {**account, 'id': 10}] + reads = [] + + def fetch(url): + reads.append(url) + return accounts if url.endswith('/accounts/') else accounts[1] if url.endswith('/10/') else account + + monkeypatch.setattr(api_utils, 'fetch_data_from_url', fetch) + send = Mock(return_value=accepted()) + monkeypatch.setattr(api_utils, 'post_request', send) + assert api_utils.refresh_m3u_playlists(target).status_code == 202 + assert base_url.call_count == 1 + assert all(url.startswith('http://original.invalid/') for url in reads) + assert all(call.args[0].startswith('http://original.invalid/') for call in send.call_args_list) + + def test_concurrent_process_style_claims_use_database_atomicity(tmp_path, monkeypatch, account): from concurrent.futures import ThreadPoolExecutor import threading