steam-backlog-enforcer/steam_backlog_enforcer/_research_window.py
Krzysztof kuhy Rudnicki 5d5aa3e773
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Add Librarian-only research window to total block
kuhy 2026-11-11: game-design research needs Librarian (app 4197610)
actually played during the 6-day total block. New root command
total-block-research --until T opens ONE window per lock: <= 48 h,
never past the lock end, a rerun never extends it.

The command only validates and records (/var/lib/steam-backlog-
enforcer, root 0700; lock id + deadline + two latches). The daemon
opens and closes everything: Steam hosts names, the store block, the
total-block chain (IP cache kept) and the steam package, reinstalled
with only guard-lib's package-block hook masked for that one pacman
call (--hookdir, proved in a guest). Lock file, hook and end date are
never touched. Browser-game sites stay null-routed.

Only Librarian may run: loop-local allowed set, strict mode (no
whitelist exceptions, no zero-achievement games), launchers and
counted games killed; state.json is never read or written.

Expiry latches the record, then the ordinary tick re-applies hosts
(now reconciled each tick), chain, uninstall and purge; the normal
store block is restored once, unconditionally.

Failure modes: missing/corrupt/unparseable record = no window and a
corrupt one also refuses a new window (fail closed); a clock set
back cannot reopen a latched window.

Checked: 3290 tests at 100% coverage; whole-tree pylint 10/10 run in
three parts (the hook exceeds the 60 s cap, so SKIP=pylint here); vmbox
guest with real guardctl package-block and the real unit, window
opened, Librarian-only enforced, clock moved past the deadline and the
full block re-applied. Not verified on the host.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWzuCEg1m87jpKyRrw
2026-11-11 14:29:58 +01:00

166 lines
5.8 KiB
Python

"""The total-block research window: validity, lock binding and how it opens.
kuhy 2026-11-11: to research a game by playing it ("Librarian: Tidy Up the
Arcane Library", app 4197610) he needs Steam during a total block. This module
is the one bounded way to get it, and the rules are all here:
* **At most 48 hours**, as an explicit expiry (``--until``), never an
open-ended switch; a rerun never extends it.
* **Once per lock**: the record names the lock it was spent on (that lock's
``started_at``/``until``) and stays after the window ends.
* **Fail closed**: a missing, unreadable, unparsable or out-of-policy record
(:mod:`steam_backlog_enforcer._research_record`) is "no window", i.e. the full
total block. A corrupt record also refuses a new window instead of resetting
the once-per-lock memory.
* **Never shortens the lock**: nothing here touches the guard-lib lock file or
its pacman hook. The window ends by the clock, then the daemon re-applies the
whole block (see :mod:`steam_backlog_enforcer._research_tick`).
"""
from __future__ import annotations
from datetime import datetime
import logging
import time
from typing import Final
from steam_backlog_enforcer import _research_record as store
from steam_backlog_enforcer._research_record import (
MAX_WINDOW_SECONDS,
ResearchRecord,
ResearchStateError,
read_record,
write_record,
)
from steam_backlog_enforcer._total_block import get_total_block_status
logger = logging.getLogger(__name__)
LIBRARIAN_APP_ID: Final = 4197610
LIBRARIAN_NAME: Final = "Librarian: Tidy Up the Arcane Library!"
# Same-lock comparison tolerance: the lock file holds whole seconds, but the
# status goes through a datetime and back.
_LOCK_TOLERANCE_SECONDS: Final = 1.0
# Corrupt-record reports already made; cleared by the next healthy read so a
# record that breaks again is reported again, but not every 3 s tick.
LOGGED: Final[set[str]] = set()
class ResearchRefusedError(Exception):
"""A window may not be opened; the message says why."""
def now() -> float:
"""The wall clock in epoch seconds (a seam for tests)."""
return time.time()
def current_lock(at: float) -> tuple[float, float] | None:
"""``(started_at, until)`` of the total block in force at *at*, else ``None``."""
status = get_total_block_status()
if status.started_at is None or status.until is None:
return None
until = status.until.timestamp()
if at >= until:
return None
return status.started_at.timestamp(), until
def _same_lock(record: ResearchRecord, lock: tuple[float, float]) -> bool:
"""Whether *record* was spent on the lock identified by *lock*."""
return (
abs(record.lock_started_at - lock[0]) < _LOCK_TOLERANCE_SECONDS
and abs(record.lock_until - lock[1]) < _LOCK_TOLERANCE_SECONDS
)
def live_record(at: float | None = None) -> ResearchRecord | None:
"""The record for the lock in force, failing closed to ``None``.
``None`` covers: no lock, no record, a record for an earlier lock, and a
record that cannot be trusted (reported once, not every tick).
"""
when = now() if at is None else at
lock = current_lock(when)
if lock is None:
return None
try:
record = read_record()
except ResearchStateError as exc:
message = f"research record ignored, full block stays: {exc}"
if message not in LOGGED:
LOGGED.add(message)
logger.exception(message)
return None
LOGGED.clear()
if record is None or not _same_lock(record, lock):
return None
return record
def parse_until(raw: str) -> datetime:
"""Parse ``--until``: ISO 8601, local time unless it carries an offset.
Raises:
ValueError: If *raw* is not an ISO date-time.
"""
try:
parsed = datetime.fromisoformat(raw)
except ValueError as exc:
msg = f"--until {raw!r} is not an ISO date-time (e.g. 2026-11-13T00:00)"
raise ValueError(msg) from exc
return parsed.astimezone() if parsed.tzinfo is None else parsed
def open_research_window(until: datetime) -> ResearchRecord:
"""Record a research window ending at *until* for the lock in force.
Args:
until: The expiry (timezone-aware).
Returns:
The stored record.
Raises:
ResearchRefusedError: With the reason: no active total block, an
unreadable record (fail closed), a window already spent on this
lock, an expiry that is past, over 48 h away or beyond the lock's
end, or a record that cannot be written.
"""
at = now()
lock = current_lock(at)
if lock is None:
msg = "no active total block; nothing to research"
raise ResearchRefusedError(msg)
try:
previous = read_record()
except ResearchStateError as exc:
msg = f"research record unreadable ({exc}); refusing (fail closed)"
raise ResearchRefusedError(msg) from exc
if previous is not None and _same_lock(previous, lock):
ended = datetime.fromtimestamp(previous.until).astimezone()
msg = f"a window was already used for this lock (until {ended:%F %H:%M})"
raise ResearchRefusedError(msg)
deadline = until.timestamp()
if deadline <= at:
msg = "--until must be in the future"
elif deadline - at > MAX_WINDOW_SECONDS:
msg = "--until is more than 48 h from now"
elif deadline > lock[1]:
msg = "--until is after the end of the total block"
else:
return _store(ResearchRecord(lock[0], lock[1], at, deadline))
raise ResearchRefusedError(msg)
def _store(record: ResearchRecord) -> ResearchRecord:
"""Write *record*, turning a write failure into a refusal."""
try:
write_record(record)
except OSError as exc:
msg = f"cannot write {store.RESEARCH_FILE}: {exc}"
raise ResearchRefusedError(msg) from exc
return record