wrolpi/wrolpi/files/progress.py
lrnselfreliance 946043450e
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
Database configs carry a version the database keeps too (#866)
* Benchmark every database config import (#865)

An opt-in test (WROLPI_CONFIG_BENCH=1) that builds a large library in bulk,
writes each config with its own dump_config, then times every import in
startup order: a steady pass (the database already matches) and a rebuild
(config-owned rows deleted, everything restored from the configs).  It
prints seconds, SQL statements and writes per import, and asserts the
rebuild restored every row so no timed import silently skipped its work.
WROLPI_CONFIG_BENCH_SCALE multiplies the row counts.

The baseline for the config import rework.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* Database configs carry a version the database keeps too

Step 1 of the config import rework.  A database config (tags, downloads,
channels, domains, playlists, repos, recently viewed) and the database now
each carry an integer version, so an import can tell which side is newer
without a clock (a Raspberry Pi's resets at boot):

- config_version (new table) holds the database's version of each config.
- An after_flush hook adds one to it for every config whose rows a flush
  changed, in the same transaction.  Each config registers what it owns
  (register_ownership): models, optionally only some columns, optionally
  only some rows (a Collection's kind; a Download's Collection's kind).
  Raw SQL writes to owned tables count explicitly.
- dump_config writes the database's version, read with the rows it saves;
  save() no longer adds one for these configs.
- An import compares versions first: file == database or newer imports
  with deletes; file older (the database changed and was not saved before a
  restart) saves the database instead of undoing that change; no database
  row (a config this code never imported) imports without deletes.  The
  import records the file's version last.
- The Import button and backup imports apply the file whatever its version
  (import_forced).

Importers only gate their existing deletes on the decision here; they are
otherwise unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Config versions: keep unsaved rows after a no-delete import, count every owned write

Review fixes:

- An import without deletes (no database version yet) no longer records the
  file's version, which let the next startup delete the rows it had kept.
  The version stays unknown, and the database is saved into the file instead;
  a successful save records the version.  A save after a partial import is
  refused, so the version stays unknown until an import applies the whole file.
- An import removes the database's version while it runs, so its own writes
  do not count: one that fails partway no longer looks newer than the file
  and gets saved over it on the next startup.
- Playlists imported without deletes keep their database items in order; the
  file's other items are added after their neighbor from the file.
- A Download leaving a Channel or Repo counts for that Collection's config
  (collection_id loads its previous value).
- Bulk writes count: untagging, retrying Downloads, deleting a duplicate's
  Download, removing many items from a playlist.  Deleting Downloads by id
  counts channels.yaml/repos.yaml only for their Downloads.
- Only a playlist's items count for playlists.yaml (author and subject
  Collections have items too).  Collection kinds are looked up once per flush.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Config versions count only the columns each config saves

A Repo's fetch (head_sha, last_fetch), a Channel's refresh (video_count,
info_json), a Collection's counts, and a Download attempt (attempts, error)
counted as config changes, so the next import of that config saved instead of
importing: a hand edit to repos.yaml was overwritten after any fetch.  Each
model now registers only the columns its config saves.

domains.yaml saves its domains' Downloads, which now count for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 14:58:18 -06:00

269 lines
12 KiB
Python

"""How far the User is through a file, and the recently viewed files config.
`FileGroup.progress` is the fraction consumed (0.0 to 1.0, where 1.0 is finished), and `FileGroup.position`
is where to resume. A position is a dict with a `kind`:
{"kind": "time", "seconds": 512.3} video and audio
{"kind": "epub", "cfi": "epubcfi(/6/14!/4/2)"} EPUB
{"kind": "page", "page": 12} comic books (0-based)
The client may add `updated_at` (milliseconds since the epoch) so it can compare the server's position with
one it holds locally.
The database is the working store. `recently_viewed.yaml` holds the most recently viewed files so viewing
history and positions survive a database rebuild.
"""
import math
import os
import pathlib
from dataclasses import dataclass, field
from datetime import datetime
from typing import List, Optional, Tuple
import pytz
from wrolpi import dates
from wrolpi.common import ConfigFile, logger, get_media_directory, get_paths_in_media_directory
from wrolpi.config_version import SAVE
from wrolpi.db import get_db_session
from wrolpi.errors import ValidationError, NoPrimaryFile
from wrolpi.events import Events
from wrolpi.switches import register_switch_handler, ActivateSwitchMethod
logger = logger.getChild(__name__)
# A file this far through is finished; the rest is credits, an end screen, or an index.
FINISHED_PROGRESS = 0.95
# A position this close to the start is not worth resuming.
MINIMUM_SECONDS = 10
MINIMUM_PROGRESS = 0.01
MAXIMUM_CFI_LENGTH = 1_000
# The most recently viewed files kept in the config. The database keeps every `viewed`.
RECENTLY_VIEWED_LIMIT = 1_000
def _number(value, name: str) -> float:
# bool is an int; reject it so `true` is not a position.
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
raise ValidationError(f'{name} must be a number')
return value
def validate_position(position: Optional[dict]) -> Optional[dict]:
"""Return a clean copy of `position`, or raise ValidationError."""
if position is None:
return None
if not isinstance(position, dict):
raise ValidationError('position must be an object')
kind = position.get('kind')
if kind == 'time':
clean = dict(kind=kind, seconds=float(_number(position.get('seconds'), 'seconds')))
if clean['seconds'] < 0:
raise ValidationError('seconds cannot be negative')
elif kind == 'page':
page = position.get('page')
if isinstance(page, bool) or not isinstance(page, int) or page < 0:
raise ValidationError('page must be a non-negative integer')
clean = dict(kind=kind, page=page)
elif kind == 'epub':
cfi = position.get('cfi')
if not isinstance(cfi, str) or not cfi.startswith('epubcfi(') or len(cfi) > MAXIMUM_CFI_LENGTH:
raise ValidationError('cfi must be an epubcfi')
clean = dict(kind=kind, cfi=cfi)
else:
raise ValidationError(f'Unknown position kind: {kind!r}')
if (updated_at := position.get('updated_at')) is not None:
clean['updated_at'] = int(_number(updated_at, 'updated_at'))
return clean
def normalize_progress(progress, position: Optional[dict]) -> Tuple[float, Optional[dict]]:
"""Apply the progress rules: a finished file has no position, nor does one barely started.
@return: (progress, position) to store.
"""
progress = min(max(float(_number(progress, 'progress')), 0.0), 1.0)
position = validate_position(position)
if progress >= FINISHED_PROGRESS:
return 1.0, None
too_early = progress < MINIMUM_PROGRESS
if position and position['kind'] == 'time':
too_early = too_early or position['seconds'] < MINIMUM_SECONDS
elif position and position['kind'] == 'page':
too_early = too_early or position['page'] == 0
if too_early:
return 0.0, None
return progress, position
@dataclass
class RecentlyViewedConfigValidator:
version: int = None
files: list = field(default_factory=list)
def _parse_entry(entry) -> Optional[Tuple[str, datetime, Optional[float], Optional[dict]]]:
"""Return (path, viewed, progress, position) from a config entry, or None if it is malformed."""
if not isinstance(entry, dict) or not isinstance(entry.get('path'), str) or not entry.get('viewed'):
return None
try:
viewed = entry['viewed']
if isinstance(viewed, datetime):
# YAML parses an unquoted timestamp (a hand edit) into a naive UTC datetime.
viewed = viewed if viewed.tzinfo else viewed.replace(tzinfo=pytz.UTC)
else:
viewed = dates.strptime_ms(viewed)
progress, position = None, None
if entry.get('progress') is not None:
progress, position = normalize_progress(entry['progress'], entry.get('position'))
return entry['path'], viewed, progress, position
except Exception as e:
logger.warning(f'Ignoring invalid recently viewed entry {entry!r}: {e}')
return None
class RecentlyViewedConfig(ConfigFile):
file_name = 'recently_viewed.yaml'
default_config = dict(
version=0,
files=[],
)
validator = RecentlyViewedConfigValidator
width = 500
@property
def files(self) -> List[dict]:
return list(self._config.get('files', []))
def dump_config(self, file=None, send_events=False, overwrite=False):
if self.get_file().exists() and not self.successful_import and not overwrite:
# Dumping now would replace history the import has not yet applied.
logger.debug(f'Not dumping {self.file_name} because it has not been imported')
return
try:
# wrolpi.files.models imports this module.
from wrolpi.files.models import FileGroup
media_directory = get_media_directory()
with get_db_session() as session:
version = self.db_version_for_dump(session)
file_groups = session.query(FileGroup) \
.filter(FileGroup.viewed.isnot(None)) \
.order_by(FileGroup.viewed.desc(), FileGroup.id) \
.limit(RECENTLY_VIEWED_LIMIT)
files = list()
for file_group in file_groups:
if not get_paths_in_media_directory([file_group.primary_path]):
# One bad row must not stop every later save.
logger.warning(f'Not saving recently viewed file outside the media directory:'
f' {file_group.primary_path}')
continue
entry = dict(
path=str(file_group.primary_path.relative_to(media_directory)),
viewed=file_group.viewed.isoformat(),
)
if file_group.progress is not None:
entry['progress'] = file_group.progress
if file_group.position:
entry['position'] = file_group.position
files.append(entry)
self.update({'files': files, 'version': version}, overwrite=overwrite)
except Exception as e:
message = f'Failed to save {self.get_relative_file()} config'
logger.error(message, exc_info=e)
if send_events:
Events.send_config_save_failed(message)
def import_config(self, file=None, send_events=False):
"""Apply the config to the database. Progress written after the config (e.g. while WROLPi was starting)
is kept; a newer plain view keeps its `viewed`, but takes the config's position."""
super().import_config(file, send_events)
if self.import_decision() == SAVE:
self.save_database_instead()
return
try:
# wrolpi.files.models imports this module.
from wrolpi.files.lib import glob_shared_stem
from wrolpi.files.models import FileGroup
media_directory = get_media_directory()
entries = list()
for path, viewed, progress, position in filter(None, map(_parse_entry, self.files)):
# An absolute `path` replaces the media directory in the join, and `..` can leave it.
absolute_path = pathlib.Path(os.path.normpath(media_directory / path))
if not get_paths_in_media_directory([absolute_path]):
logger.warning(f'Not importing recently viewed file outside the media directory: {path}')
continue
entries.append((absolute_path, viewed, progress, position))
absolute_paths = [i[0] for i in entries]
# Glob the files which are not yet in the DB before the write transaction; stat'ing a thousand files on
# a slow disk would block every other writer.
with get_db_session() as session:
known = {i for (i,) in session.query(FileGroup.primary_path)
.filter(FileGroup.primary_path.in_(absolute_paths))}
new_files = {i: glob_shared_stem(i) for i in absolute_paths if i not in known and i.is_file()}
with get_db_session(commit=True) as session:
file_groups = session.query(FileGroup).filter(FileGroup.primary_path.in_(absolute_paths))
file_groups_by_path = {i.primary_path: i for i in file_groups}
applied = 0
for absolute_path, viewed, progress, position in entries:
file_group = file_groups_by_path.get(absolute_path)
if not file_group:
if not (files := new_files.pop(absolute_path, None)):
# The file was deleted; its history goes with it.
logger.debug(f'Not importing recently viewed file which does not exist: {absolute_path}')
continue
try:
file_group = FileGroup.from_paths(session, *files)
except NoPrimaryFile:
logger.warning(f'Cannot import recently viewed file: {absolute_path}')
continue
session.add(file_group)
session.flush([file_group])
file_groups_by_path[absolute_path] = file_group
db_is_newer = file_group.viewed is not None and file_group.viewed >= viewed
if db_is_newer and file_group.progress is not None:
# Progress was written after the config (e.g. while WROLPi was starting).
continue
# A newer plain view is kept, but it is not a newer place to resume.
if not db_is_newer:
file_group.viewed = viewed
file_group.progress = progress
file_group.position = position
applied += 1
logger.info(f'Imported {applied} of {len(entries)} recently viewed files')
self.record_import_version()
self.successful_import = True
except Exception as e:
self.successful_import = False
message = f'Failed to import {self.get_relative_file()} config'
logger.error(message, exc_info=e)
if send_events:
Events.send_config_import_failed(message)
raise
RECENTLY_VIEWED_CONFIG: RecentlyViewedConfig = RecentlyViewedConfig()
def get_recently_viewed_config() -> RecentlyViewedConfig:
return RECENTLY_VIEWED_CONFIG
@register_switch_handler('save_recently_viewed_config')
def save_recently_viewed_config():
get_recently_viewed_config().dump_config()
save_recently_viewed_config: ActivateSwitchMethod