Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions backend/apps/api/m3u_refresh_handlers.py
Original file line number Diff line number Diff line change
@@ -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')
23 changes: 23 additions & 0 deletions backend/apps/api/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions backend/apps/api/web_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
51 changes: 42 additions & 9 deletions backend/apps/core/api_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,21 +566,54 @@ 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, {})
logger.info("M3U refresh request accepted by Dispatcharr")
return resp
base_url = _get_base_url().rstrip('/')
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).
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(start_account(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)
return start_account(account_id)
except Exception as e:
logger.error(f"Failed to refresh M3U playlists: {e}")
raise


def get_m3u_refresh_guard(base_url: Optional[str] = None):
from apps.core.m3u_refresh_guard import M3URefreshGuard

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}/',
))


def get_m3u_accounts() -> Optional[List[Dict[str, Any]]]:
"""
Fetch all M3U accounts from the UDI cache.
Expand Down
128 changes: 128 additions & 0 deletions backend/apps/core/m3u_refresh_guard.py
Original file line number Diff line number Diff line change
@@ -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')
16 changes: 16 additions & 0 deletions backend/apps/database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down
42 changes: 42 additions & 0 deletions backend/apps/database/repositories/m3u_refresh_repository.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading