steam-backlog-enforcer/steam_backlog_enforcer/_research_net.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

109 lines
3.9 KiB
Python

"""Making the network and the Steam package match an open research window.
Every pass of an open window calls :func:`reconcile_open_window`, which is
idempotent and cheap once converged (one /etc/hosts read, one ``iptables -S``,
one ``pacman -Qi``). The daemon is the only actor: the command just records the
window, so a daemon that still runs the old code, or a restart half way, cannot
leave two writers fighting over hosts, the firewall and pacman.
The opening is deliberately narrower than "the block is off":
* /etc/hosts keeps the browser-game sites null-routed; only Steam names open
(:data:`steam_backlog_enforcer._total_block_domains.RESEARCH_BLOCKED_DOMAINS`);
* the normal Steam-store block (hosts lines + its iptables chain) is lifted for
checkout, and re-lifted whenever the hourly hosts reinstall puts it back;
* the total-block iptables chain is taken down, its IP cache kept for expiry;
* Steam is reinstalled if the block removed it, with only the guard-lib
package-block pacman hook masked for that one transaction. The hook file, the
lock file and the lock's end date are never touched.
"""
from __future__ import annotations
import logging
from pathlib import Path
import time
from typing import TYPE_CHECKING, Final
from steam_backlog_enforcer._pacman import install_package
from steam_backlog_enforcer._total_block import _PACKAGE_BLOCK_NAME
from steam_backlog_enforcer._total_block_hosts import refresh_total_block_hosts
from steam_backlog_enforcer._total_block_iptables import (
release_total_block_iptables,
total_block_chain_exists,
)
from steam_backlog_enforcer._total_block_purge import STEAM_PACKAGE, is_steam_installed
from steam_backlog_enforcer.store_blocker import (
flush_dns_cache,
hosts_blocks_store,
unblock_store,
)
if TYPE_CHECKING:
from steam_backlog_enforcer._research_window import ResearchRecord
logger = logging.getLogger(__name__)
DB_LOCK_FILE: Final = Path("/var/lib/pacman/db.lck")
RETRY_AFTER_SECONDS: Final = 60.0
# Next monotonic time each retried action ("steam", "store") may run again.
RETRY: Final[dict[str, float]] = {}
# Windows (by opened_at) whose one-time release this daemon process has done.
RELEASED: Final[set[float]] = set()
def monotonic() -> float:
"""Monotonic seconds (a seam for tests)."""
return time.monotonic()
def attempt_due(key: str) -> bool:
"""Whether the action *key* may run now (it is not in its backoff)."""
return monotonic() >= RETRY.get(key, 0.0)
def note_failure(key: str) -> None:
"""Hold the action *key* back for :data:`RETRY_AFTER_SECONDS`."""
RETRY[key] = monotonic() + RETRY_AFTER_SECONDS
def block_hook_name() -> str:
"""File name of guard-lib's pacman hook for the steam package-block."""
return f"guard-lib-block-{_PACKAGE_BLOCK_NAME}.hook"
def ensure_steam_installed() -> bool:
"""Reinstall Steam if the total block removed it.
Returns:
True when the package is installed afterwards. A running pacman
transaction is not raced and a failure backs off, so a broken mirror
cannot turn the 3 s tick into an install loop.
"""
if is_steam_installed():
return True
if DB_LOCK_FILE.exists() or not attempt_due("steam"):
return False
if install_package(STEAM_PACKAGE, masked_hooks=(block_hook_name(),)):
logger.info("Research window: Steam reinstalled")
return True
note_failure("steam")
return False
def reconcile_open_window(record: ResearchRecord) -> None:
"""One idempotent pass making the machine match the open window *record*."""
first = record.opened_at not in RELEASED
hosts_ok = refresh_total_block_hosts(steam_open=True)
if first:
flush_dns_cache()
store_ok = True
if first or hosts_blocks_store():
store_ok = unblock_store()
if total_block_chain_exists():
release_total_block_iptables()
if first and hosts_ok and store_ok:
RELEASED.add(record.opened_at)
ensure_steam_installed()