Compare commits

...

4 Commits

Author SHA1 Message Date
f383325276 Bump @types/node to 26.5.1
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (push) Has been cancelled
Tests / test (push) Has been cancelled
The pre-push CI mirror refused the previous push on this one pin.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015mLnUeoJ3mUwGRTowTUH6d
2026-09-13 10:57:02 +02:00
a5abb94d85 Keep Steam Runtime's logger out of the journal
Steam's srt-logger runs inside steam-backlog-enforcer.service's cgroup
and mirrors Steam's console into journald on its own — the DEVNULL
stderr the spawn already uses does not reach it, and the env carried
SRT_LOG_TO_JOURNAL=0, which is not the variable it reads. One boot on
2026-09-12 wrote 481k "joystick FFB effect status" lines (99% of the
journal) and evicted two weeks of history from a 300M journal, along
with the evidence for that night's curfew failure.

- desktop_env_args(): SRT_LOGGER_USE_JOURNAL=0, the variable srt-logger
  actually honours. Steam keeps its own logs/console-linux.txt.
- Unit: LogFilterPatterns for the two known flood patterns plus a
  per-unit rate limit, so a future Steam that ignores the variable still
  cannot take the journal with it.

The unit file is deployed and daemon-reloaded; the running service is
not restarted, because Steam is its child and a restart would kill a
live game. The env fix takes effect on the next enforcer start.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015mLnUeoJ3mUwGRTowTUH6d
2026-09-13 10:51:50 +02:00
2d45515665 pylint: fold the remaining split-era duplicates back into single owners
The 250-line split left function-sized copies behind: the confidence-only
batch fetch was the search half of _fetch_batch verbatim (now
_search_batch, and _SearchCtx carries one _HLTBExtras instead of two of
its dicts); the workout and LeetCode bonuses each had the same loopback
GET and answer cache (now _status_api); the poll-count refetch lived in
both _cmd_done and _polls_reporting (now refetch_poll_counts); the
candidate-selection prelude in both scanning and _scanning_assign; the
/etc/hosts rewrite loop in both block and unblock (now
rewrite_hosts_lines with a per-line rule); the timed HLTB fetch and its
rate line; and the whitelist constants each module only half used.
_hltb_cached's dead facade constants go too. Tests patch where the code
now lives.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HHCbkJWXHjtTUaqvnHRAqA
2026-09-12 20:49:12 +02:00
d6d9a2d1a6 pylint: clear the mechanical residue, the howlongtobeatpy 1.0.23 call, and three duplicate blocks
The pinned howlongtobeatpy (1.0.23) takes a user agent in
send_website_request_getcode and dropped parse_all_scripts; the call
still matched 1.0.20, which only worked because the deployed env was
behind its own pin. Now on the pinned API, and the env upgraded.

Three modules carried the same executable/path constant block since the
250-line split; it is _store_tools. Four carried the same "restore the
hours a refetch lost" loop; it is restore_prior_hours. Both detached
launches go through one helper that returns the process. Thirteen
try/except/else blocks are flat, dataclass fields come from
dataclasses.fields, and the rest are one-line fixes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HHCbkJWXHjtTUaqvnHRAqA
2026-09-12 20:31:27 +02:00
54 changed files with 587 additions and 653 deletions

View File

@ -16,6 +16,15 @@ Environment=STEAM_ENFORCER_DESKTOP_USER=__DESKTOP_USER__
Environment=DISPLAY=:0
# Hardening: enforcer must not be easily killed.
OOMScoreAdjust=-900
# Journal backstop. Steam's srt-logger runs in this unit's cgroup and mirrors
# Steam's console into journald; 2026-09-12 it wrote 481k "joystick FFB"
# lines in one boot (99% of the journal) and evicted two weeks of history.
# SRT_LOGGER_USE_JOURNAL=0 in the spawn env is the fix at source; these two
# make sure a future Steam that ignores it still cannot flood the journal.
LogFilterPatterns=~Failed to get joystick[0-9]+ FFB effect status
LogFilterPatterns=~FFBInterface
LogRateLimitIntervalSec=1min
LogRateLimitBurst=2000
#
# DO NOT ADD PrivateMounts=, PrivateTmp=, ProtectSystem= OR ProtectHome= HERE.
# The daily gaming budget enforces its cutoff by bind-mounting a refusal stub

View File

@ -141,21 +141,19 @@ def resolve_budget(config: Config) -> BudgetResolution:
)
total = base + workout_seconds + leetcode_seconds
reason = "{:.1f}h: {}, {}".format(
total / _SECONDS_PER_HOUR,
_describe(
answer=workout,
earned="workout counted",
missed="no counted workout",
unknown="workout unknown (screen-locker unreachable)",
),
_describe(
answer=leetcode,
earned="LeetCode solve recorded",
missed="no LeetCode solve recorded",
unknown="LeetCode unknown (ledger and status API both unreadable)",
),
workout_part = _describe(
answer=workout,
earned="workout counted",
missed="no counted workout",
unknown="workout unknown (screen-locker unreachable)",
)
leetcode_part = _describe(
answer=leetcode,
earned="LeetCode solve recorded",
missed="no LeetCode solve recorded",
unknown="LeetCode unknown (ledger and status API both unreadable)",
)
reason = f"{total / _SECONDS_PER_HOUR:.1f}h: {workout_part}, {leetcode_part}"
logger.info("Gaming budget %s", reason)
return BudgetResolution(
seconds=total,

View File

@ -7,11 +7,11 @@ import sys
from typing import TYPE_CHECKING
from steam_backlog_enforcer._hltb_cached import fetch_hltb_times_cached
from steam_backlog_enforcer._hltb_confidence import fetch_hltb_confidence_cached
from steam_backlog_enforcer._hltb_confidence import (
refetch_poll_counts,
)
from steam_backlog_enforcer._hltb_types import (
load_hltb_cache,
load_hltb_polls_cache,
save_hltb_cache,
)
from steam_backlog_enforcer._snapshot import load_snapshot
from steam_backlog_enforcer.game_install import (
@ -83,21 +83,7 @@ def _backfill_polls_for_finished(
return polls_cache
_echo(f" Backfilling HLTB poll counts for {len(missing)} game(s)...")
cache = load_hltb_cache()
preserved_hours = {aid: cache[aid] for aid, _ in missing if aid in cache}
for aid, _name in missing:
cache.pop(aid, None)
save_hltb_cache(cache, polls_cache)
fetch_hltb_confidence_cached(missing)
refreshed_hours = load_hltb_cache()
refreshed_polls = load_hltb_polls_cache()
for aid, prior_hours in preserved_hours.items():
if prior_hours > 0 and refreshed_hours.get(aid, -1) <= 0:
refreshed_hours[aid] = prior_hours
save_hltb_cache(refreshed_hours, refreshed_polls)
return refreshed_polls
return refetch_poll_counts(missing)
def _report_assigned_confidence(

View File

@ -70,6 +70,13 @@ def desktop_env_args(user: str, uid: int) -> list[str]:
f"XAUTHORITY={xauth}",
f"DBUS_SESSION_BUS_ADDRESS={dbus_addr}",
f"XDG_RUNTIME_DIR={runtime_dir}",
# Steam Runtime's srt-logger opts INTO the journal when it finds one
# (it inherits this unit's JOURNAL_STREAM), regardless of the DEVNULL
# stderr the spawn already uses. That wrote 481k "joystick FFB" lines
# in one boot and evicted two weeks of history from a 300M journal.
# Steam still keeps its own logs/console-linux.txt; this only stops
# the copy into journald.
"SRT_LOGGER_USE_JOURNAL=0",
]

View File

@ -70,21 +70,21 @@ def _allowed_names(state: State) -> str:
return ", ".join(names) if names else "your assigned game"
def _guard_installed_games(allowed_app_ids: set[int]) -> int:
def _guard_installed_games(allowed: set[int]) -> int:
"""Remove any unauthorized game manifests + files. Runs every loop.
Args:
allowed_app_ids: Every app id that may stay installed — the assignment
plus any concurrent manual picks.
allowed: Every app id that may stay installed — the assignment plus
any concurrent manual picks.
Returns number of games removed this pass.
"""
if not allowed_app_ids:
if not allowed:
return 0
installed = get_installed_games()
count = 0
for app_id, name in installed:
if app_id in allowed_app_ids:
if app_id in allowed:
continue
if is_protected_app(app_id):
continue

View File

@ -69,7 +69,7 @@ def _protected_name_stems() -> list[str]:
"""
try:
return [name for _, name in allowed_games(State.load()) if name]
except Exception:
except Exception: # pylint: disable=broad-exception-caught
logger.exception("Could not load allowed games for the deletion safety net")
return []

View File

@ -7,7 +7,6 @@ under the 250-line cap.
from __future__ import annotations
import logging
import time
from steam_backlog_enforcer._hltb_types import (
ProgressCb,
@ -19,7 +18,7 @@ from steam_backlog_enforcer._hltb_types import (
load_hltb_rush_cache,
save_hltb_cache,
)
from steam_backlog_enforcer.hltb import fetch_hltb_times
from steam_backlog_enforcer.hltb import fetch_hltb_times_timed, games_per_second
logger = logging.getLogger(__name__)
@ -56,40 +55,20 @@ def fetch_hltb_times_cached(
len(uncached),
len(games) - len(uncached),
)
t0 = time.monotonic()
fetch_hltb_times(
uncached,
cache=cache,
polls=polls,
progress_cb=progress_cb,
extras=extras,
)
elapsed = time.monotonic() - t0
elapsed = fetch_hltb_times_timed(uncached, cache, polls, progress_cb, extras)
# Final save.
save_hltb_cache(cache, polls, extras)
found = sum(1 for aid, _ in uncached if cache.get(aid, -1) > 0)
rate = len(uncached) / elapsed if elapsed > 0 else 0
logger.info(
"HLTB fetch done: %d/%d found in %.1fs (%.0f games/s)",
found,
len(uncached),
elapsed,
rate,
games_per_second(len(uncached), elapsed),
)
else:
logger.info("All %d games found in HLTB cache.", len(games))
return cache
_REEXPORTED_TYPES = frozenset({"HLTB_BASE_URL"})
_MOVED_TO_HLTB_CONFIDENCE = frozenset(
{
"fetch_hltb_confidence_cached",
"fetch_hltb_detail_missing",
"get_hltb_submit_url",
}
)

View File

@ -19,11 +19,14 @@ from steam_backlog_enforcer._hltb_types import (
load_hltb_leisure_100h_cache,
load_hltb_polls_cache,
load_hltb_rush_cache,
restore_prior_hours,
save_hltb_cache,
)
from steam_backlog_enforcer.hltb import (
fetch_hltb_confidence,
fetch_hltb_times,
fetch_hltb_times_timed,
games_per_second,
)
logger = logging.getLogger(__name__)
@ -34,6 +37,30 @@ logger = logging.getLogger(__name__)
# ──────────────────────────────────────────────────────────────
def refetch_poll_counts(missing: list[tuple[int, str]]) -> dict[int, int]:
"""Re-search ``missing`` for poll counts and return the refreshed polls cache.
The search-level fetch skips anything already in the hours cache, so the
hours entries are dropped first to force it -- then put back where the
refetch found nothing better, since a prior leisure/DLC estimate is
trusted over a miss.
"""
cache = load_hltb_cache()
polls = load_hltb_polls_cache()
preserved_hours = {aid: cache[aid] for aid, _ in missing if aid in cache}
for aid, _name in missing:
cache.pop(aid, None)
save_hltb_cache(cache, polls)
fetch_hltb_confidence_cached(missing)
refreshed_hours = load_hltb_cache()
refreshed_polls = load_hltb_polls_cache()
restore_prior_hours(refreshed_hours, preserved_hours)
save_hltb_cache(refreshed_hours, refreshed_polls)
return refreshed_polls
def fetch_hltb_confidence_cached(
games: list[tuple[int, str]],
progress_cb: ProgressCb | None = None,
@ -142,31 +169,19 @@ def fetch_hltb_detail_missing(
)
else:
logger.info("Backfilling HLTB game ID for %d game(s)...", n_id)
t0 = time.monotonic()
fetch_hltb_times(
missing,
cache=cache,
polls=polls,
progress_cb=progress_cb,
extras=extras,
)
elapsed = time.monotonic() - t0
elapsed = fetch_hltb_times_timed(missing, cache, polls, progress_cb, extras)
# Restore prior hours for games the detail fetch didn't re-find.
for app_id, old_hours in prior_hours.items():
if old_hours > 0 and cache.get(app_id, -1.0) <= 0:
cache[app_id] = old_hours
restore_prior_hours(cache, prior_hours)
save_hltb_cache(cache, polls, extras)
fetched = sum(1 for app_id, _ in missing_rush if extras.rush.get(app_id, -1) > 0)
rate = len(missing) / elapsed if elapsed > 0 else 0
logger.info(
"HLTB detail fetch done: %d/%d got rush data in %.1fs (%.0f games/s)",
fetched,
len(missing_rush),
elapsed,
rate,
games_per_second(len(missing), elapsed),
)
return fetched

View File

@ -182,10 +182,13 @@ def _find_best_extended(
entry_name = (entry.get("game_name") or "").lower()
if entry_name.startswith((lower + ":", lower + " -")):
suffix = entry_name[len(lower) :].lstrip(" :-")
if not any(suffix.startswith(kw) for kw in _SUBSET_SUFFIXES) and (
best is None or entry.get("comp_100", 0) > best[0].get("comp_100", 0)
if any(suffix.startswith(kw) for kw in _SUBSET_SUFFIXES):
continue
if best is not None and entry.get("comp_100", 0) <= best[0].get(
"comp_100", 0
):
best = (entry, sim)
continue
best = (entry, sim)
return best

View File

@ -62,12 +62,11 @@ class _SearchCtx:
headers: dict[str, str]
cache: dict[int, float]
polls: dict[int, int] = field(default_factory=dict)
count_comp: dict[int, int] = field(default_factory=dict)
extras: _HLTBExtras = field(default_factory=_HLTBExtras)
auth: _AuthInfo | None = None
counter: dict[str, int] = field(default_factory=dict)
total: int = 0
progress_cb: ProgressCb | None = None
hltb_game_id: dict[int, int] = field(default_factory=dict)
async def _search_one(
@ -123,25 +122,21 @@ async def _search_one(
if result is not None:
ctx.cache[app_id] = result.completionist_hours
ctx.polls[app_id] = result.comp_100_count
ctx.count_comp[app_id] = result.count_comp
ctx.extras.count_comp[app_id] = result.count_comp
if result.hltb_game_id > 0:
ctx.hltb_game_id[app_id] = result.hltb_game_id
ctx.extras.hltb_game_id[app_id] = result.hltb_game_id
ctx.counter["found"] += 1
else:
ctx.cache[app_id] = -1
ctx.polls[app_id] = 0
ctx.count_comp[app_id] = 0
ctx.extras.count_comp[app_id] = 0
ctx.counter["done"] += 1
done = ctx.counter["done"]
# Incremental save every _SAVE_INTERVAL lookups.
if not done % _SAVE_INTERVAL:
save_hltb_cache(
ctx.cache,
ctx.polls,
_HLTBExtras(count_comp=ctx.count_comp, hltb_game_id=ctx.hltb_game_id),
)
save_hltb_cache(ctx.cache, ctx.polls, ctx.extras)
# Report progress.
if ctx.progress_cb is not None:
@ -150,17 +145,18 @@ async def _search_one(
return result
async def _fetch_batch(
async def _search_batch(
games: list[tuple[int, str]],
cache: dict[int, float],
polls: dict[int, int],
progress_cb: ProgressCb | None,
extras: _HLTBExtras | None = None,
extras: _HLTBExtras,
) -> list[HLTBResult]:
"""Fetch HLTB data for a batch of games using one shared session."""
if extras is None:
extras = _HLTBExtras()
"""Run the search-level HLTB lookups for a batch through one session.
Hours, poll counts and the extras come from the search results alone;
:func:`_fetch_batch` layers the per-game detail pages on top of this.
"""
# 1. Discover the search URL (sync, one-time).
search_url = _get_hltb_search_url()
logger.info("HLTB search URL: %s", search_url)
@ -191,9 +187,6 @@ async def _fetch_batch(
# 4. Fire all searches through a single persistent session.
sem = asyncio.Semaphore(MAX_CONCURRENT)
counter = {"done": 0, "found": 0}
total = len(games)
connector = aiohttp.TCPConnector(
limit=MAX_CONCURRENT,
keepalive_timeout=30,
@ -208,25 +201,29 @@ async def _fetch_batch(
headers=headers,
cache=cache,
polls=polls,
count_comp=extras.count_comp,
extras=extras,
auth=auth,
counter=counter,
total=total,
counter={"done": 0, "found": 0},
total=len(games),
progress_cb=progress_cb,
hltb_game_id=extras.hltb_game_id,
)
tasks = [
_search_one(
sem,
ctx,
app_id,
name,
)
for app_id, name in games
]
tasks = [_search_one(sem, ctx, app_id, name) for app_id, name in games]
results = await asyncio.gather(*tasks)
search_results = [r for r in results if r is not None]
return [r for r in results if r is not None]
async def _fetch_batch(
games: list[tuple[int, str]],
cache: dict[int, float],
polls: dict[int, int],
progress_cb: ProgressCb | None,
extras: _HLTBExtras | None = None,
) -> list[HLTBResult]:
"""Fetch HLTB data for a batch of games using one shared session."""
if extras is None:
extras = _HLTBExtras()
search_results = await _search_batch(games, cache, polls, progress_cb, extras)
# 5. Fetch leisure times + DLC from game detail pages.
logger.info(

View File

@ -42,20 +42,19 @@ _EXTENDED_MIN_CONFIDENCE = 3
# ──────────────────────────────────────────────────────────────
_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0"
def _get_hltb_search_url() -> str:
"""Discover the current HLTB search API endpoint.
Scrapes the homepage for JS bundles containing the fetch URL.
Falls back to ``/api/finder`` if extraction fails.
Scrapes the homepage for JS bundles containing the fetch URL, walking
every bundle until one names it (howlongtobeatpy >= 1.0.23 does that
itself; the older ``parse_all_scripts`` two-step is gone). Falls back to
``/api/finder`` if extraction fails.
"""
try:
search_info = HTMLRequests.send_website_request_getcode(
parse_all_scripts=False,
)
if search_info is None:
search_info = HTMLRequests.send_website_request_getcode(
parse_all_scripts=True,
)
search_info = HTMLRequests.send_website_request_getcode(_USER_AGENT)
if search_info and search_info.search_url:
url: str = HTMLRequests.BASE_URL + search_info.search_url
return url
@ -72,9 +71,7 @@ async def _get_auth_info(
init_url = search_url + "/init"
ts = int(time.time() * 1000)
headers = {
"User-Agent": (
"Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0"
),
"User-Agent": _USER_AGENT,
"referer": "https://howlongtobeat.com/",
}
try:

View File

@ -136,6 +136,17 @@ def _read_raw_cache() -> dict[int, dict[str, Any]]:
return out
def restore_prior_hours(refreshed: dict[int, float], prior: dict[int, float]) -> None:
"""Put back known hours a refetch replaced with nothing.
A refetch that finds no (or a zero-hour) match must not erase an estimate
we already had -- prior leisure/DLC figures are trusted over a miss.
"""
for app_id, old_hours in prior.items():
if old_hours > 0 and refreshed.get(app_id, -1.0) <= 0:
refreshed[app_id] = old_hours
def load_hltb_cache() -> dict[int, float]:
"""Load the hours portion of the HLTB cache.

View File

@ -7,44 +7,24 @@ introduces no cycle. Split to keep both files under the 250-line cap.
from __future__ import annotations
import logging
from pathlib import Path
import shutil
import subprocess
from typing import TYPE_CHECKING
from steam_backlog_enforcer._store_tools import (
GUARDCTL,
SUDO,
TEE,
)
from steam_backlog_enforcer.config import (
BLOCKED_DOMAINS,
HOSTS_FILE,
)
if TYPE_CHECKING:
from collections.abc import Callable
logger = logging.getLogger(__name__)
# Path to the hosts install script. _REPO_ROOT resolves to $HOME (this
# module lives two levels below it); the script itself is in the
# linux_configuration checkout under testsAndMisc, not directly under $HOME.
_REPO_ROOT = Path(__file__).resolve().parents[2]
HOSTS_INSTALL_SCRIPT = (
_REPO_ROOT
/ "testsAndMisc"
/ "linux_configuration"
/ "scripts"
/ "periodic_background"
/ "hosts"
/ "install.sh"
)
# iptables chain name for our blocking rules.
IPTABLES_CHAIN = "STEAM_ENFORCER"
# Resolved absolute paths for executables (avoids S607 partial-path warnings).
_SUDO = shutil.which("sudo") or "/usr/bin/sudo"
_IPTABLES = shutil.which("iptables") or "/usr/sbin/iptables"
_BASH = shutil.which("bash") or "/usr/bin/bash"
_GUARDCTL = shutil.which("guardctl") or "/usr/local/bin/guardctl"
_TEE = shutil.which("tee") or "/usr/bin/tee"
# IP address used in /etc/hosts for blocking domains.
_HOSTS_REDIRECT_IP = ".".join(["0"] * 4)
def _disable_hosts_protection() -> None:
"""Temporarily unlock /etc/hosts so its content can be edited.
@ -52,7 +32,7 @@ def _disable_hosts_protection() -> None:
Guard-lib: stop watcher, collapse bind mount, chattr -i.
"""
subprocess.run(
[_SUDO, _GUARDCTL, "file-guard", "pacman-unlock", "hosts"],
[SUDO, GUARDCTL, "file-guard", "pacman-unlock", "hosts"],
capture_output=True,
timeout=10,
check=False,
@ -65,7 +45,7 @@ def _enable_hosts_protection() -> None:
Guard-lib: chattr +i, reapply bind mount, restart watcher.
"""
subprocess.run(
[_SUDO, _GUARDCTL, "file-guard", "sync", "hosts"],
[SUDO, GUARDCTL, "file-guard", "sync", "hosts"],
capture_output=True,
timeout=10,
check=False,
@ -75,7 +55,7 @@ def _enable_hosts_protection() -> None:
def _sudo_write_hosts(content: str) -> None:
"""Write *content* to /etc/hosts via ``sudo tee``."""
subprocess.run(
[_SUDO, _TEE, str(HOSTS_FILE)],
[SUDO, TEE, str(HOSTS_FILE)],
input=content.encode(),
stdout=subprocess.DEVNULL,
timeout=10,
@ -83,32 +63,53 @@ def _sudo_write_hosts(content: str) -> None:
)
def _reblock_hosts() -> bool:
"""Uncomment Steam Store entries in /etc/hosts."""
def rewrite_hosts_lines(
rewrite: Callable[[str], str | None], done_message: str
) -> bool:
"""Apply ``rewrite`` to every /etc/hosts line, under the protection dance.
``rewrite`` returns the replacement for a line, or ``None`` to keep it.
The file is only written -- and ``done_message`` only logged -- when a
line actually changed; protection is lifted before and restored after
either way.
Returns:
Whether the edit (or the no-op) completed without an OSError.
"""
try:
_disable_hosts_protection()
content = HOSTS_FILE.read_text(encoding="utf-8")
new_lines = []
changed = False
for line in content.splitlines(keepends=True):
stripped = line.strip()
if stripped.startswith("# ") and any(
d in stripped for d in BLOCKED_DOMAINS
):
# Remove the '# ' prefix.
uncommented = line.replace("# ", "", 1)
new_lines.append(uncommented)
changed = True
else:
replacement = rewrite(line)
if replacement is None:
new_lines.append(line)
else:
new_lines.append(replacement)
changed = True
if changed:
_sudo_write_hosts("".join(new_lines))
logger.info("Re-enabled Steam Store entries in /etc/hosts.")
logger.info(done_message)
_enable_hosts_protection()
except OSError:
logger.exception("Failed to modify /etc/hosts")
return False
else:
return True
return True
def _uncomment_blocked(line: str) -> str | None:
"""The line with its '# ' prefix removed, if it is a commented-out block."""
stripped = line.strip()
if stripped.startswith("# ") and any(d in stripped for d in BLOCKED_DOMAINS):
return line.replace("# ", "", 1)
return None
def _reblock_hosts() -> bool:
"""Uncomment Steam Store entries in /etc/hosts."""
return rewrite_hosts_lines(
_uncomment_blocked, "Re-enabled Steam Store entries in /etc/hosts."
)

View File

@ -32,29 +32,20 @@ transports, the memo, and the incident on total failure.
from __future__ import annotations
import http.client
import json
import logging
from pathlib import Path
import time as time_module
from typing import TYPE_CHECKING, Final
from urllib.parse import urlsplit
from typing import TYPE_CHECKING
from steam_backlog_enforcer._bonus_incident import report_leetcode_incident
from steam_backlog_enforcer._leetcode_ledger import read_ledger_solved_today
from steam_backlog_enforcer._status_api import AnswerCache, get_status
if TYPE_CHECKING:
from steam_backlog_enforcer.config import Config
logger = logging.getLogger(__name__)
_TIMEOUT_SECONDS: Final = 2.0
_CACHE_TTL_SECONDS: Final = 60.0
# Only successes are cached, matching _workout_budget: a failure is retried on
# the very next tick, so a restarted service takes effect immediately instead
# of costing an hour for another minute.
_cache: dict[str, tuple[float, bool]] = {}
_cache = AnswerCache()
def reset_cache() -> None:
@ -77,22 +68,7 @@ def _fetch_leetcode_today(url: str) -> bool:
could not check.
KeyError: The payload lacked the expected fields.
"""
split = urlsplit(url)
conn = http.client.HTTPConnection(
split.hostname or "127.0.0.1",
split.port or 80,
timeout=_TIMEOUT_SECONDS,
)
try:
conn.request("GET", split.path or "/api/status")
resp = conn.getresponse()
body = resp.read()
if resp.status != http.HTTPStatus.OK:
msg = f"status {resp.status} {resp.reason}"
raise ValueError(msg)
finally:
conn.close()
block = json.loads(body)["leetcode"]
block = get_status(url)["leetcode"]
if not block["checked"]:
# The server answered, but said it could not look. That is not a "no".
msg = f"leetcode-guard could not check: {block.get('reason', 'no reason')}"
@ -113,10 +89,9 @@ def leetcode_solved_today(config: Config) -> bool | None:
incident while an honest "not solved yet" does not.
"""
url = config.leetcode_status_url
now = time_module.monotonic()
cached = _cache.get(url)
if cached is not None and now - cached[0] < _CACHE_TTL_SECONDS:
return cached[1]
cached = _cache.fresh(url)
if cached is not None:
return cached
path = Path(config.leetcode_ledger_path).expanduser()
answer = read_ledger_solved_today(path)
@ -125,8 +100,7 @@ def leetcode_solved_today(config: Config) -> bool | None:
if answer is None:
return None
_cache[url] = (now, answer)
return answer
return _cache.store(url, answer=answer)
def _fallback_to_endpoint(url: str, path: Path) -> bool | None:

View File

@ -106,8 +106,7 @@ def get_all_owned_app_ids(config: Config) -> list[int]:
return snapshot_ids
logger.warning("Could not fetch owned game list for hiding.")
return []
else:
return merged_ids
return merged_ids
# ──────────────────────────────────────────────────────────────

View File

@ -7,7 +7,7 @@ which is what lets the enforcer survive a restart mid-session.
from __future__ import annotations
from dataclasses import dataclass, field
from dataclasses import dataclass, field, fields
from datetime import datetime, timedelta
import json
import logging
@ -220,8 +220,8 @@ def load_state(*, demo: bool) -> PlaytimeState | None:
if not isinstance(data, dict) or data.get("schema_version") != _SCHEMA_VERSION:
logger.warning("Playtime state at %s has an unknown schema.", path)
return None
fields = PlaytimeState.__dataclass_fields__
return PlaytimeState(**{k: v for k, v in data.items() if k in fields})
known = {f.name for f in fields(PlaytimeState)}
return PlaytimeState(**{k: v for k, v in data.items() if k in known})
def save_state(state: PlaytimeState, *, demo: bool) -> None:

View File

@ -9,11 +9,11 @@ import logging
from typing import TYPE_CHECKING
from steam_backlog_enforcer._echo import _echo
from steam_backlog_enforcer._hltb_confidence import fetch_hltb_confidence_cached
from steam_backlog_enforcer._hltb_confidence import (
refetch_poll_counts,
)
from steam_backlog_enforcer._hltb_types import (
load_hltb_cache,
load_hltb_polls_cache,
save_hltb_cache,
)
if TYPE_CHECKING:
@ -48,25 +48,7 @@ def _backfill_polls_for_finished(
"Backfilling HLTB poll counts for %d already-finished games...",
len(missing),
)
# Force a fresh search by removing the hours entries we want to refetch.
# (fetch_hltb_times_cached skips entries already in the hours cache.)
cache = load_hltb_cache()
preserved_hours = {aid: cache[aid] for aid, _ in missing if aid in cache}
for aid, _name in missing:
cache.pop(aid, None)
save_hltb_cache(cache, polls_cache)
fetch_hltb_confidence_cached(missing)
# Restore any previously-known hours that the refetch may have replaced
# with a worse match (we trust prior leisure+dlc estimates).
refreshed_hours = load_hltb_cache()
refreshed_polls = load_hltb_polls_cache()
for aid, prior_hours in preserved_hours.items():
if prior_hours > 0 and refreshed_hours.get(aid, -1) <= 0:
refreshed_hours[aid] = prior_hours
save_hltb_cache(refreshed_hours, refreshed_polls)
return refreshed_polls
return refetch_poll_counts(missing)
def _report_poll_confidence(

View File

@ -100,6 +100,31 @@ def _assign_chosen_game(
)
def _clear_assignment(state: State, message: str) -> None:
"""Say why nothing could be assigned and leave the slot empty."""
_echo(message)
state.current_app_id = None
state.current_game_name = ""
state.save()
def _no_pick_message(confidence_skipped: int, linux_skipped: int) -> str:
"""Why the candidate pass produced nothing: confidence, or ProtonDB."""
if confidence_skipped > 0 and linux_skipped == 0:
return _NO_CONF_MSG
return "\nNo playable games left (all have poor ProtonDB ratings)!"
def _open_candidates(games: list[GameInfo], state: State) -> list[GameInfo]:
"""Unfinished, unskipped games, shortest first, with cached confidence."""
skip = set(state.finished_app_ids) | state.active_skipped_ids()
candidates = [g for g in games if not g.is_complete and g.app_id not in skip]
if candidates:
candidates.sort(key=_sort_key)
_apply_cached_confidence_to_candidates(candidates)
return candidates
def _pick_next_game_sequential(
games: list[GameInfo],
state: State,
@ -113,29 +138,18 @@ def _pick_next_game_sequential(
``state`` for that game and the next candidate is evaluated.
"""
while True:
skip = set(state.finished_app_ids) | state.active_skipped_ids()
candidates = [g for g in games if not g.is_complete and g.app_id not in skip]
candidates = _open_candidates(games, state)
if not candidates:
_echo(_NO_CONF_MSG)
state.current_app_id = None
state.current_game_name = ""
state.save()
_clear_assignment(state, _NO_CONF_MSG)
return
candidates.sort(key=_sort_key)
_apply_cached_confidence_to_candidates(candidates)
chosen, confidence_skipped, linux_skipped = _pick_next_shortest_candidate(
candidates
)
if chosen is None:
_echo(
_NO_CONF_MSG
if confidence_skipped > 0 and linux_skipped == 0
else "\nNo playable games left (all have poor ProtonDB ratings)!"
_clear_assignment(
state, _no_pick_message(confidence_skipped, linux_skipped)
)
state.current_app_id = None
state.current_game_name = ""
state.save()
return
if not on_select(chosen):

View File

@ -32,7 +32,7 @@ def _sort_key(g: GameInfo) -> tuple[int, float]:
"""Sort by known HLTB time (shortest first), then unknown games."""
if g.completionist_hours > 0:
return (0, g.completionist_hours)
return (1, g.name.lower().encode().hex().__hash__())
return (1, hash(g.name.lower().encode().hex()))
def _pick_playable_candidate(

View File

@ -11,18 +11,18 @@ from steam_backlog_enforcer._hltb_types import (
load_hltb_cache,
load_hltb_count_comp_cache,
load_hltb_polls_cache,
restore_prior_hours,
save_hltb_cache,
)
from steam_backlog_enforcer._polls_reporting import (
_backfill_polls_for_finished,
_report_poll_confidence,
)
from steam_backlog_enforcer.game_install import _echo
if TYPE_CHECKING:
from steam_backlog_enforcer.steam_api import GameInfo
from steam_backlog_enforcer._polls_reporting import (
_backfill_polls_for_finished,
_report_poll_confidence,
)
logger = logging.getLogger(__name__)
__all__ = [
@ -123,9 +123,7 @@ def _refresh_candidate_confidence_batch(
refreshed_hours = load_hltb_cache()
refreshed_polls = load_hltb_polls_cache()
refreshed_count_comp = load_hltb_count_comp_cache()
for aid, old_hours in prior_hours.items():
if old_hours > 0 and refreshed_hours.get(aid, -1) <= 0:
refreshed_hours[aid] = old_hours
restore_prior_hours(refreshed_hours, prior_hours)
save_hltb_cache(
refreshed_hours, refreshed_polls, _HLTBExtras(count_comp=refreshed_count_comp)
)

View File

@ -0,0 +1,88 @@
"""One loopback status-API read, shared by the workout and LeetCode bonuses.
Both bonuses ask a sibling daemon's ``/api/status`` endpoint over loopback and
reuse a successful answer for a minute. The transport and the cache policy
are identical, so they live here once; each bonus keeps only the field it
reads out of the payload.
Uses ``http.client`` rather than ``urllib.request`` deliberately, matching
``screen_locker._http_workout_fetch``: it takes a host and a path rather than a
URL, so there is no scheme for a bad config value to turn into a ``file://``
read, and no lint waiver is needed to say so.
"""
from __future__ import annotations
import http.client
import json
import time
from typing import Any, Final
from urllib.parse import urlsplit
# Loopback, so a short timeout is generous. The daemon ticks frequently and
# must never block on this.
_TIMEOUT_SECONDS: Final = 2.0
# A successful answer is reused for this long. The daemon would otherwise make
# one HTTP call per tick, and the answer changes at most a few times a day. The
# cost is that a workout logged now raises the budget within a minute rather
# than instantly -- invisible next to a two-hour swing.
_CACHE_TTL_SECONDS: Final = 60.0
def get_status(url: str) -> dict[str, Any]:
"""GET a status endpoint and return its JSON body.
Args:
url: The status endpoint, e.g. ``http://127.0.0.1:8770/api/status``.
Raises:
OSError: The endpoint could not be reached.
ValueError: The response was not usable JSON, or not a 200.
"""
split = urlsplit(url)
conn = http.client.HTTPConnection(
split.hostname or "127.0.0.1",
split.port or 80,
timeout=_TIMEOUT_SECONDS,
)
try:
conn.request("GET", split.path or "/api/status")
resp = conn.getresponse()
body = resp.read()
if resp.status != http.HTTPStatus.OK:
msg = f"status {resp.status} {resp.reason}"
raise ValueError(msg)
finally:
conn.close()
payload: dict[str, Any] = json.loads(body)
return payload
class AnswerCache:
"""Successful answers by URL, each good for :data:`_CACHE_TTL_SECONDS`.
Only *successes* are stored. A failure is retried on the very next tick, so
a restarted status server takes effect immediately instead of serving the
floor for another minute.
"""
def __init__(self) -> None:
"""Start empty."""
self._entries: dict[str, tuple[float, bool]] = {}
def clear(self) -> None:
"""Drop every cached answer, forcing the next call to re-ask."""
self._entries.clear()
def fresh(self, url: str) -> bool | None:
"""The cached answer for ``url`` if it is still within its TTL."""
cached = self._entries.get(url)
if cached is not None and time.monotonic() - cached[0] < _CACHE_TTL_SECONDS:
return cached[1]
return None
def store(self, url: str, *, answer: bool) -> bool:
"""Remember ``answer`` for ``url`` as of now, and hand it back."""
self._entries[url] = (time.monotonic(), answer)
return answer

View File

@ -77,8 +77,7 @@ class SteamAPIClient:
except requests.RequestException as e:
msg = f"Steam API request failed: {e}"
raise SteamAPIError(msg) from e
else:
return result
return result
def get_owned_games(self) -> list[dict[str, Any]]:
"""Fetch all games owned by the user."""

View File

@ -20,6 +20,7 @@ from steam_backlog_enforcer._desktop_env import (
resolve_desktop_user,
)
from steam_backlog_enforcer._steam_launch import steam_is_installed
from steam_backlog_enforcer._steam_process import spawn_detached
from steam_backlog_enforcer._steam_state import STEAMAPPS_PATH
logger = logging.getLogger(__name__)
@ -42,8 +43,7 @@ def _get_uid_gid_for_user(username: str) -> tuple[int, int]:
pw = pwd.getpwnam(username)
except KeyError:
return 1000, 1000
else:
return pw.pw_uid, pw.pw_gid
return pw.pw_uid, pw.pw_gid
def is_game_installed(app_id: int) -> bool:
@ -106,11 +106,7 @@ def _ensure_steam_running() -> None:
else:
cmd = ["steam", "-silent"]
subprocess.Popen(
cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
spawn_detached(cmd)
# Give Steam time to initialize and start scanning manifests.
time.sleep(15)
except FileNotFoundError:

View File

@ -19,6 +19,20 @@ logger = logging.getLogger(__name__)
_SPAWNED: list[subprocess.Popen[bytes]] = []
def spawn_detached(cmd: list[str]) -> subprocess.Popen[bytes]:
"""Start ``cmd`` and hand back the process, output discarded.
Fire-and-forget on purpose: the process must outlive the calling scope
(Steam itself, a desktop notifier), so it is polled or reaped later rather
than waited on in a ``with`` block here.
"""
return subprocess.Popen(
cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def _reap_spawned() -> None:
"""Clear out previously launched processes that have since exited.
@ -49,10 +63,4 @@ def _run_as_user(cmd: list[str], user: str | None) -> None:
return
full_cmd = desktop_user_cmd(cmd, user)
_SPAWNED.append(
subprocess.Popen(
full_cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
)
_SPAWNED.append(spawn_detached(full_cmd))

View File

@ -9,50 +9,26 @@ from __future__ import annotations
import contextlib
import logging
from pathlib import Path
import shutil
import socket
import subprocess
from steam_backlog_enforcer._store_tools import (
IPTABLES,
IPTABLES_CHAIN,
SUDO,
)
from steam_backlog_enforcer.config import (
BLOCKED_DOMAINS,
)
logger = logging.getLogger(__name__)
# Path to the hosts install script. _REPO_ROOT resolves to $HOME (this
# module lives two levels below it); the script itself is in the
# linux_configuration checkout under testsAndMisc, not directly under $HOME.
_REPO_ROOT = Path(__file__).resolve().parents[2]
HOSTS_INSTALL_SCRIPT = (
_REPO_ROOT
/ "testsAndMisc"
/ "linux_configuration"
/ "scripts"
/ "periodic_background"
/ "hosts"
/ "install.sh"
)
# iptables chain name for our blocking rules.
IPTABLES_CHAIN = "STEAM_ENFORCER"
# Resolved absolute paths for executables (avoids S607 partial-path warnings).
_SUDO = shutil.which("sudo") or "/usr/bin/sudo"
_IPTABLES = shutil.which("iptables") or "/usr/sbin/iptables"
_BASH = shutil.which("bash") or "/usr/bin/bash"
_GUARDCTL = shutil.which("guardctl") or "/usr/local/bin/guardctl"
_TEE = shutil.which("tee") or "/usr/bin/tee"
# IP address used in /etc/hosts for blocking domains.
_HOSTS_REDIRECT_IP = ".".join(["0"] * 4)
def _is_iptables_blocked() -> bool:
"""Check if our iptables chain exists and has rules."""
try:
result = subprocess.run(
[_SUDO, _IPTABLES, "-L", IPTABLES_CHAIN, "-n"],
[SUDO, IPTABLES, "-L", IPTABLES_CHAIN, "-n"],
capture_output=True,
text=True,
timeout=5,
@ -60,8 +36,7 @@ def _is_iptables_blocked() -> bool:
)
except OSError, subprocess.SubprocessError:
return False
else:
return result.returncode == 0 and "DROP" in result.stdout
return result.returncode == 0 and "DROP" in result.stdout
def _block_store_iptables() -> bool:
@ -69,14 +44,14 @@ def _block_store_iptables() -> bool:
try:
# Create chain if it doesn't exist.
subprocess.run(
[_SUDO, _IPTABLES, "-N", IPTABLES_CHAIN],
[SUDO, IPTABLES, "-N", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
# Flush existing rules in our chain.
subprocess.run(
[_SUDO, _IPTABLES, "-F", IPTABLES_CHAIN],
[SUDO, IPTABLES, "-F", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=True,
@ -93,8 +68,8 @@ def _block_store_iptables() -> bool:
for ip in blocked_ips:
subprocess.run(
[
_SUDO,
_IPTABLES,
SUDO,
IPTABLES,
"-A",
IPTABLES_CHAIN,
"-d",
@ -109,14 +84,14 @@ def _block_store_iptables() -> bool:
# Hook our chain into OUTPUT if not already there.
result = subprocess.run(
[_SUDO, _IPTABLES, "-C", "OUTPUT", "-j", IPTABLES_CHAIN],
[SUDO, IPTABLES, "-C", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
if result.returncode != 0:
subprocess.run(
[_SUDO, _IPTABLES, "-I", "OUTPUT", "-j", IPTABLES_CHAIN],
[SUDO, IPTABLES, "-I", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=True,
@ -124,28 +99,27 @@ def _block_store_iptables() -> bool:
except OSError, subprocess.SubprocessError:
logger.exception("Failed to block store via iptables")
return False
else:
logger.info("Steam Store blocked via iptables (%d IPs).", len(blocked_ips))
return True
logger.info("Steam Store blocked via iptables (%d IPs).", len(blocked_ips))
return True
def _unblock_store_iptables() -> bool:
"""Remove iptables-based block."""
try:
subprocess.run(
[_SUDO, _IPTABLES, "-D", "OUTPUT", "-j", IPTABLES_CHAIN],
[SUDO, IPTABLES, "-D", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
subprocess.run(
[_SUDO, _IPTABLES, "-F", IPTABLES_CHAIN],
[SUDO, IPTABLES, "-F", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
subprocess.run(
[_SUDO, _IPTABLES, "-X", IPTABLES_CHAIN],
[SUDO, IPTABLES, "-X", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
@ -153,9 +127,8 @@ def _unblock_store_iptables() -> bool:
except OSError, subprocess.SubprocessError:
logger.exception("Failed to unblock iptables")
return False
else:
logger.info("Steam Store unblocked from iptables.")
return True
logger.info("Steam Store unblocked from iptables.")
return True
def flush_dns_cache() -> None:

View File

@ -0,0 +1,38 @@
"""The executables and paths every store-blocking layer shells out to.
One copy, imported by the hosts, iptables and orchestration modules alike --
each used to carry its own after the 250-line split, three blocks that had
to be kept identical by hand.
"""
from __future__ import annotations
from pathlib import Path
import shutil
# Path to the hosts install script. _REPO_ROOT resolves to $HOME (this
# module lives two levels below it); the script itself is in the
# linux_configuration checkout under testsAndMisc, not directly under $HOME.
_REPO_ROOT = Path(__file__).resolve().parents[2]
HOSTS_INSTALL_SCRIPT = (
_REPO_ROOT
/ "testsAndMisc"
/ "linux_configuration"
/ "scripts"
/ "periodic_background"
/ "hosts"
/ "install.sh"
)
# iptables chain name for our blocking rules.
IPTABLES_CHAIN = "STEAM_ENFORCER"
# Resolved absolute paths for executables (avoids S607 partial-path warnings).
SUDO = shutil.which("sudo") or "/usr/bin/sudo"
IPTABLES = shutil.which("iptables") or "/usr/sbin/iptables"
BASH = shutil.which("bash") or "/usr/bin/bash"
GUARDCTL = shutil.which("guardctl") or "/usr/local/bin/guardctl"
TEE = shutil.which("tee") or "/usr/bin/tee"
# IP address used in /etc/hosts for blocking domains.
HOSTS_REDIRECT_IP = ".".join(["0"] * 4)

View File

@ -11,16 +11,16 @@ from __future__ import annotations
import logging
import subprocess
from steam_backlog_enforcer._hosts_protection import (
_disable_hosts_protection,
_enable_hosts_protection,
_sudo_write_hosts,
)
from steam_backlog_enforcer._total_block_domains import (
_ALL_TOTAL_BLOCK_DOMAINS,
NULL_ROUTE_IP,
)
from steam_backlog_enforcer.config import HOSTS_FILE
from steam_backlog_enforcer.store_blocker import (
_disable_hosts_protection,
_enable_hosts_protection,
_sudo_write_hosts,
)
logger = logging.getLogger(__name__)

View File

@ -159,11 +159,8 @@ def apply_total_block_iptables() -> bool:
except OSError, subprocess.SubprocessError:
logger.exception("Failed to apply total-block iptables rules")
return False
else:
logger.info(
"Total block: %d domain IP(s) blocked via iptables.", len(blocked_ips)
)
return True
logger.info("Total block: %d domain IP(s) blocked via iptables.", len(blocked_ips))
return True
def remove_total_block_iptables() -> bool:
@ -190,6 +187,5 @@ def remove_total_block_iptables() -> bool:
except OSError, subprocess.SubprocessError:
logger.exception("Failed to remove total-block iptables rules")
return False
else:
_IPTABLES_IP_CACHE_FILE.unlink(missing_ok=True)
return True
_IPTABLES_IP_CACHE_FILE.unlink(missing_ok=True)
return True

View File

@ -61,7 +61,7 @@ _STALE_MSG = (
class _Handler(BaseHTTPRequestHandler):
"""Serve the dataset JSON and the static frontend bundle (read-only)."""
def log_message(self, fmt: str, *args: object) -> None:
def log_message(self, fmt: str, /, *args: object) -> None:
"""Route the default request log to ``logging`` at debug level."""
logger.debug("%s - %s", self.address_string(), fmt % args)

View File

@ -6,22 +6,9 @@ from collections import Counter
import logging
import math
import re
from typing import TYPE_CHECKING
from steam_backlog_enforcer.config import CONFIG_DIR
if TYPE_CHECKING:
from pathlib import Path
logger = logging.getLogger(__name__)
# ──────────────────────────────────────────────────────────────
# File paths (patched in tests via conftest)
# ──────────────────────────────────────────────────────────────
APPROVED_EXCEPTIONS_FILE: Path = CONFIG_DIR / "approved_exceptions.json"
EXCEPTION_AUDIT_LOG: Path = CONFIG_DIR / "exception_audit.log"
# ──────────────────────────────────────────────────────────────
# Constants
# ──────────────────────────────────────────────────────────────

View File

@ -35,16 +35,6 @@ logger = logging.getLogger(__name__)
APPROVED_EXCEPTIONS_FILE: Path = CONFIG_DIR / "approved_exceptions.json"
EXCEPTION_AUDIT_LOG: Path = CONFIG_DIR / "exception_audit.log"
# ──────────────────────────────────────────────────────────────
# Constants
# ──────────────────────────────────────────────────────────────
_MIN_REASON_WORDS: int = 5
_MIN_REASON_LENGTH: int = 25
_MIN_ENTROPY: float = 3.0
# Reject runs of the same character longer than this (e.g. "aaaa").
_MAX_CHAR_RUN: int = 3
# ──────────────────────────────────────────────────────────────
# Reason validation

View File

@ -11,42 +11,21 @@ malformed body, non-200 -- yields ``None``, logged at warning with the concrete
reason, and the caller grants no workout bonus. Failing open would let the
whole coupling be defeated by stopping one user service, and a silent bonus
would be indistinguishable from an earned one.
Uses ``http.client`` rather than ``urllib.request`` deliberately, matching
``screen_locker._http_workout_fetch``: it takes a host and a path rather than a
URL, so there is no scheme for a bad config value to turn into a ``file://``
read, and no lint waiver is needed to say so.
"""
from __future__ import annotations
import http.client
import json
import logging
import time
from typing import TYPE_CHECKING, Final
from urllib.parse import urlsplit
from typing import TYPE_CHECKING
from steam_backlog_enforcer._status_api import AnswerCache, get_status
if TYPE_CHECKING:
from steam_backlog_enforcer.config import Config
logger = logging.getLogger(__name__)
# Loopback, so a short timeout is generous. The daemon ticks frequently and
# must never block on this.
_TIMEOUT_SECONDS: Final = 2.0
# A successful answer is reused for this long. The daemon would otherwise make
# one HTTP call per tick, and the answer changes at most a few times a day. The
# cost is that a workout logged now raises the budget within a minute rather
# than instantly -- invisible next to a two-hour swing.
_CACHE_TTL_SECONDS: Final = 60.0
# Only *successes* are cached. A failure is retried on the very next tick, so a
# restarted status server takes effect immediately instead of serving the floor
# for another minute. A dict rather than a module global so no function here
# needs a `global` statement to write it.
_cache: dict[str, tuple[float, bool]] = {}
_cache = AnswerCache()
def reset_cache() -> None:
@ -68,22 +47,7 @@ def _fetch_workout_today(url: str) -> bool:
ValueError: The response was not usable JSON, or not a 200.
KeyError: The payload lacked the expected fields.
"""
split = urlsplit(url)
conn = http.client.HTTPConnection(
split.hostname or "127.0.0.1",
split.port or 80,
timeout=_TIMEOUT_SECONDS,
)
try:
conn.request("GET", split.path or "/api/status")
resp = conn.getresponse()
body = resp.read()
if resp.status != http.HTTPStatus.OK:
msg = f"status {resp.status} {resp.reason}"
raise ValueError(msg)
finally:
conn.close()
return bool(json.loads(body)["gaming"]["workout_today"])
return bool(get_status(url)["gaming"]["workout_today"])
def workout_logged_today(config: Config) -> bool | None:
@ -98,10 +62,9 @@ def workout_logged_today(config: Config) -> bool | None:
distinct from ``False`` so the caller can log which one happened.
"""
url = config.workout_status_url
now = time.monotonic()
cached = _cache.get(url)
if cached is not None and now - cached[0] < _CACHE_TTL_SECONDS:
return cached[1]
cached = _cache.fresh(url)
if cached is not None:
return cached
try:
answer = _fetch_workout_today(url)
@ -123,5 +86,4 @@ def workout_logged_today(config: Config) -> bool | None:
)
return None
_cache[url] = (now, answer)
return answer
return _cache.store(url, answer=answer)

View File

@ -3,7 +3,7 @@
from __future__ import annotations
import contextlib
from dataclasses import dataclass, field
from dataclasses import dataclass, field, fields
from datetime import UTC, datetime, timedelta
import json
import logging
@ -66,6 +66,11 @@ def _atomic_write(path: Path, data: str, *, mode: int | None = None) -> None:
raise
def _field_names(cls: type) -> frozenset[str]:
"""The dataclass's own field names, for filtering a loaded JSON object."""
return frozenset(f.name for f in fields(cls))
@dataclass
class Config:
"""User configuration."""
@ -132,9 +137,7 @@ class Config:
"""Load config from disk, or return defaults."""
if CONFIG_FILE.exists():
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
return cls(
**{k: v for k, v in data.items() if k in cls.__dataclass_fields__}
)
return cls(**{k: v for k, v in data.items() if k in _field_names(cls)})
return cls()
@ -146,14 +149,14 @@ class State:
current_game_name: str = ""
finished_app_ids: list[int] = field(default_factory=list)
skipped_until: dict[str, str] = field(default_factory=dict)
enforcement_started_at: str = ""
"""ISO-8601 UTC timestamp set on the first game assignment."""
"""Map of ``str(app_id)`` → ISO-8601 UTC timestamp when the skip expires.
Games in this map are excluded from auto-assignment until the timestamp
elapses. Populated when the user declines a freshly-picked game via the
interactive prompt in ``cmd_done``.
"""
enforcement_started_at: str = ""
"""ISO-8601 UTC timestamp set on the first game assignment."""
manual_pick_app_id: int | None = None
manual_pick_game_name: str = ""
manual_pick_started_at: str = ""
@ -214,9 +217,7 @@ class State:
except json.JSONDecodeError, OSError, ValueError:
logger.warning("Corrupt state file, using defaults.")
return cls()
state = cls(
**{k: v for k, v in data.items() if k in cls.__dataclass_fields__}
)
state = cls(**{k: v for k, v in data.items() if k in _field_names(cls)})
state._migrate_legacy_manual_pick()
return state
return cls()

View File

@ -99,8 +99,7 @@ def _kill_pid_by_name(pid: int, name: str) -> bool:
except PermissionError:
logger.exception("No permission to kill PID %d (%s).", pid, name)
return False
else:
return True
return True
def enforce_allowed_game(

View File

@ -89,9 +89,8 @@ def _trigger_steam_install(app_id: int, label: str) -> bool:
)
except FileNotFoundError, OSError, subprocess.TimeoutExpired:
return False
else:
logger.info("Triggered Steam install for %s via protocol handler", label)
return True
logger.info("Triggered Steam install for %s via protocol handler", label)
return True
# ──────────────────────────────────────────────────────────────

View File

@ -14,18 +14,10 @@ from __future__ import annotations
import asyncio
import logging
import time
import aiohttp
from steam_backlog_enforcer._hltb_search import (
_fetch_batch,
_get_auth_info,
_get_hltb_search_url,
_search_one,
_SearchCtx,
)
from steam_backlog_enforcer._hltb_search import _fetch_batch, _search_batch
from steam_backlog_enforcer._hltb_types import (
MAX_CONCURRENT,
HLTBResult,
ProgressCb,
_HLTBExtras,
@ -45,74 +37,8 @@ async def _fetch_batch_confidence_only(
count_comp: dict[int, int] | None = None,
) -> list[HLTBResult]:
"""Fetch only search-level HLTB data (hours + confidence), no detail pages."""
# 1. Discover the search URL (sync, one-time).
search_url = _get_hltb_search_url()
logger.info("HLTB search URL: %s", search_url)
timeout = aiohttp.ClientTimeout(total=20, sock_read=15)
# 2. Get auth info (separate session — avoids reuse issues).
async with aiohttp.ClientSession(timeout=timeout) as init_session:
auth = await _get_auth_info(search_url, init_session)
if auth is None:
logger.warning("Could not get HLTB auth info, aborting fetch.")
return []
logger.info("HLTB auth token acquired.")
# 3. Build shared headers for all search requests.
headers: dict[str, str] = {
"content-type": "application/json",
"accept": "*/*",
"User-Agent": (
"Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0"
),
"referer": "https://howlongtobeat.com/",
"x-auth-token": auth.token,
}
if auth.hp_key:
headers["x-hp-key"] = auth.hp_key
headers["x-hp-val"] = auth.hp_val
# 4. Fire all searches through a single persistent session.
sem = asyncio.Semaphore(MAX_CONCURRENT)
counter = {"done": 0, "found": 0}
total = len(games)
if count_comp is None:
count_comp = {}
connector = aiohttp.TCPConnector(
limit=MAX_CONCURRENT,
keepalive_timeout=30,
)
async with aiohttp.ClientSession(
timeout=timeout,
connector=connector,
) as session:
ctx = _SearchCtx(
session=session,
search_url=search_url,
headers=headers,
cache=cache,
polls=polls,
count_comp=count_comp,
auth=auth,
counter=counter,
total=total,
progress_cb=progress_cb,
)
tasks = [
_search_one(
sem,
ctx,
app_id,
name,
)
for app_id, name in games
]
results = await asyncio.gather(*tasks)
return [r for r in results if r is not None]
extras = _HLTBExtras(count_comp=count_comp if count_comp is not None else {})
return await _search_batch(games, cache, polls, progress_cb, extras)
def fetch_hltb_times(
@ -140,6 +66,26 @@ def fetch_hltb_times(
)
def fetch_hltb_times_timed(
games: list[tuple[int, str]],
cache: dict[int, float],
polls: dict[int, int],
progress_cb: ProgressCb | None,
extras: _HLTBExtras,
) -> float:
"""Run :func:`fetch_hltb_times` into the given caches; return the seconds taken."""
t0 = time.monotonic()
fetch_hltb_times(
games, cache=cache, polls=polls, progress_cb=progress_cb, extras=extras
)
return time.monotonic() - t0
def games_per_second(count: int, elapsed: float) -> float:
"""Throughput for a completion log line; 0 when nothing was timed."""
return count / elapsed if elapsed > 0 else 0
def fetch_hltb_confidence(
games: list[tuple[int, str]],
cache: dict[int, float] | None = None,

View File

@ -90,7 +90,6 @@ class ProtonDBRating:
return ""
tier_rank = TIER_ORDER.get(self.tier, 99)
TIER_ORDER[MIN_PLAYABLE_TIER]
silver_rank = TIER_ORDER["silver"]
if not self.trending_tier:

View File

@ -15,6 +15,9 @@ from steam_backlog_enforcer._pick_completion import mark_finished, report_comple
from steam_backlog_enforcer._scanning_assign import (
_NO_CONF_MSG,
_assign_chosen_game,
_clear_assignment,
_no_pick_message,
_open_candidates,
_pick_next_game_sequential,
_prompt_user_pick,
)
@ -23,10 +26,8 @@ from steam_backlog_enforcer._scanning_candidates import (
_collect_top_candidates,
_pick_next_shortest_candidate,
_pick_playable_candidate,
_sort_key,
)
from steam_backlog_enforcer._scanning_confidence import (
_apply_cached_confidence_to_candidates,
_report_poll_confidence,
)
from steam_backlog_enforcer._scanning_tampering import (
@ -95,9 +96,9 @@ def do_scan(config: Config, state: State) -> list[GameInfo]:
pct = done * 100 // total
bar_w = 30
filled = bar_w * done // total
bar = "█" * filled + "░" * (bar_w - filled)
meter = "█" * filled + "░" * (bar_w - filled)
_echo(
f"\r HLTB [{bar}] {done}/{total} ({pct}%) "
f"\r HLTB [{meter}] {done}/{total} ({pct}%) "
f"| {found} found | {name[:30]:<30s}",
end="",
flush=True,
@ -163,31 +164,16 @@ def pick_next_game(
_pick_next_game_sequential(games, state, config, on_select)
return
skip = set(state.finished_app_ids) | state.active_skipped_ids()
candidates = [g for g in games if not g.is_complete and g.app_id not in skip]
candidates = _open_candidates(games, state)
if not candidates:
_echo(_NO_CONF_MSG)
state.current_app_id = None
state.current_game_name = ""
state.save()
_clear_assignment(state, _NO_CONF_MSG)
return
candidates.sort(key=_sort_key)
_apply_cached_confidence_to_candidates(candidates)
qualified, confidence_skipped, linux_skipped = _collect_qualified_candidates(
candidates
)
if not qualified:
_echo(
_NO_CONF_MSG
if confidence_skipped > 0 and linux_skipped == 0
else "\nNo playable games left (all have poor ProtonDB ratings)!"
)
state.current_app_id = None
state.current_game_name = ""
state.save()
_clear_assignment(state, _no_pick_message(confidence_skipped, linux_skipped))
return
idx = _prompt_user_pick(qualified)

View File

@ -12,15 +12,11 @@ blocks via iptables.
from __future__ import annotations
import logging
from pathlib import Path
import shutil
import subprocess
from steam_backlog_enforcer._hosts_protection import (
_disable_hosts_protection,
_enable_hosts_protection,
_reblock_hosts,
_sudo_write_hosts,
rewrite_hosts_lines,
)
from steam_backlog_enforcer._store_iptables import (
_block_store_iptables,
@ -28,6 +24,12 @@ from steam_backlog_enforcer._store_iptables import (
_unblock_store_iptables,
flush_dns_cache,
)
from steam_backlog_enforcer._store_tools import (
BASH,
HOSTS_INSTALL_SCRIPT,
HOSTS_REDIRECT_IP,
SUDO,
)
from steam_backlog_enforcer.config import (
BLOCKED_DOMAINS,
HOSTS_FILE,
@ -35,33 +37,6 @@ from steam_backlog_enforcer.config import (
logger = logging.getLogger(__name__)
# Path to the hosts install script. _REPO_ROOT resolves to $HOME (this
# module lives two levels below it); the script itself is in the
# linux_configuration checkout under testsAndMisc, not directly under $HOME.
_REPO_ROOT = Path(__file__).resolve().parents[2]
HOSTS_INSTALL_SCRIPT = (
_REPO_ROOT
/ "testsAndMisc"
/ "linux_configuration"
/ "scripts"
/ "periodic_background"
/ "hosts"
/ "install.sh"
)
# iptables chain name for our blocking rules.
IPTABLES_CHAIN = "STEAM_ENFORCER"
# Resolved absolute paths for executables (avoids S607 partial-path warnings).
_SUDO = shutil.which("sudo") or "/usr/bin/sudo"
_IPTABLES = shutil.which("iptables") or "/usr/sbin/iptables"
_BASH = shutil.which("bash") or "/usr/bin/bash"
_GUARDCTL = shutil.which("guardctl") or "/usr/local/bin/guardctl"
_TEE = shutil.which("tee") or "/usr/bin/tee"
# IP address used in /etc/hosts for blocking domains.
_HOSTS_REDIRECT_IP = ".".join(["0"] * 4)
def is_store_blocked() -> bool:
"""Check if Steam Store domains are blocked in /etc/hosts."""
@ -75,7 +50,7 @@ def is_store_blocked() -> bool:
if (
not stripped.startswith("#")
and "store.steampowered.com" in stripped
and stripped.startswith(_HOSTS_REDIRECT_IP)
and stripped.startswith(HOSTS_REDIRECT_IP)
):
return True
except OSError:
@ -128,7 +103,7 @@ def _block_via_hosts_install() -> bool:
try:
logger.info("Running hosts install script to block Steam Store...")
result = subprocess.run(
[_SUDO, _BASH, str(HOSTS_INSTALL_SCRIPT), "--no-flush-dns"],
[SUDO, BASH, str(HOSTS_INSTALL_SCRIPT), "--no-flush-dns"],
capture_output=True,
text=True,
timeout=120,
@ -137,16 +112,15 @@ def _block_via_hosts_install() -> bool:
except OSError, subprocess.SubprocessError:
logger.exception("Failed to run hosts install script")
return False
else:
if result.returncode == 0:
logger.info("hosts install script succeeded.")
return True
logger.error(
"hosts install script failed (rc=%d): %s",
result.returncode,
result.stderr[-500:] if result.stderr else result.stdout[-500:],
)
return False
if result.returncode == 0:
logger.info("hosts install script succeeded.")
return True
logger.error(
"hosts install script failed (rc=%d): %s",
result.returncode,
result.stderr[-500:] if result.stderr else result.stdout[-500:],
)
return False
def unblock_store() -> bool:
@ -185,30 +159,18 @@ def _unblock_hosts() -> bool:
logger.info("Steam Store not blocked in /etc/hosts, nothing to do.")
return True
try:
_disable_hosts_protection()
content = HOSTS_FILE.read_text(encoding="utf-8")
new_lines = []
changed = False
for line in content.splitlines(keepends=True):
stripped = line.strip()
if (
not stripped.startswith("#")
and stripped.startswith(_HOSTS_REDIRECT_IP)
and any(d in stripped for d in BLOCKED_DOMAINS)
):
new_lines.append(f"# {line}" if line.endswith("\n") else f"# {line}\n")
changed = True
else:
new_lines.append(line)
return rewrite_hosts_lines(
_comment_out_blocked, "Commented out Steam Store entries in /etc/hosts."
)
if changed:
_sudo_write_hosts("".join(new_lines))
logger.info("Commented out Steam Store entries in /etc/hosts.")
_enable_hosts_protection()
except OSError:
logger.exception("Failed to modify /etc/hosts")
return False
else:
return True
def _comment_out_blocked(line: str) -> str | None:
"""The line commented out, if it is a live redirect of a blocked domain."""
stripped = line.strip()
if (
not stripped.startswith("#")
and stripped.startswith(HOSTS_REDIRECT_IP)
and any(d in stripped for d in BLOCKED_DOMAINS)
):
return f"# {line}" if line.endswith("\n") else f"# {line}\n"
return None

View File

@ -55,6 +55,16 @@ class TestDesktopEnvArgs:
args = desktop_env_args("bob", 1000)
assert _env_value(args, "XDG_RUNTIME_DIR") == "/run/user/1000"
def test_steam_runtime_logger_kept_out_of_the_journal(self) -> None:
"""srt-logger must be told not to mirror Steam's console into journald.
It inherits the service's JOURNAL_STREAM and opts in on its own; one
boot's worth of joystick FFB errors (481k lines) evicted two weeks of
journal history and the evidence for a curfew failure with it.
"""
args = desktop_env_args("bob", 1000)
assert _env_value(args, "SRT_LOGGER_USE_JOURNAL") == "0"
def test_dbus_address_defaults_to_uid_path(self) -> None:
"""DBUS falls back to the uid-derived socket when unset."""
env_copy = os.environ.copy()

View File

@ -11,12 +11,11 @@ import aiohttp
from steam_backlog_enforcer._hltb_matching import _similarity
from steam_backlog_enforcer._hltb_search import _AuthInfo
from steam_backlog_enforcer._hltb_search_api import _get_hltb_search_url
from steam_backlog_enforcer._hltb_search_api import _get_auth_info, _get_hltb_search_url
from steam_backlog_enforcer._hltb_types import (
load_hltb_cache,
save_hltb_cache,
)
from steam_backlog_enforcer.hltb import _get_auth_info
if TYPE_CHECKING:
from pathlib import Path
@ -107,15 +106,16 @@ class TestGetHltbSearchUrl:
url = _get_hltb_search_url()
assert url == "https://howlongtobeat.com/api/finder"
def test_first_returns_none_second_returns_info(self) -> None:
"""Test first returns none second returns info."""
def test_passes_the_user_agent_the_library_now_requires(self) -> None:
"""howlongtobeatpy 1.0.23 takes a user agent, not a parse-all flag."""
mock_info = MagicMock()
mock_info.search_url = "/api/search/xyz"
with patch("steam_backlog_enforcer._hltb_search_api.HTMLRequests") as mock_html:
mock_html.send_website_request_getcode.side_effect = [None, mock_info]
mock_html.send_website_request_getcode.return_value = mock_info
mock_html.BASE_URL = "https://howlongtobeat.com"
url = _get_hltb_search_url()
assert url == "https://howlongtobeat.com/api/search/xyz"
_get_hltb_search_url()
(agent,) = mock_html.send_website_request_getcode.call_args.args
assert agent.startswith("Mozilla/5.0")
def test_exception_fallback(self) -> None:
"""Test exception fallback."""

View File

@ -13,7 +13,7 @@ from steam_backlog_enforcer.hltb import (
fetch_hltb_confidence,
)
PKG = "steam_backlog_enforcer.hltb"
PKG = "steam_backlog_enforcer._hltb_search"
_CONF = "steam_backlog_enforcer._hltb_confidence"

View File

@ -11,6 +11,7 @@ if TYPE_CHECKING:
from steam_backlog_enforcer._hltb_types import _HLTBExtras
PKG = "steam_backlog_enforcer._hltb_confidence"
_HLTB = "steam_backlog_enforcer.hltb"
class _DummySession:
@ -33,7 +34,7 @@ class TestFetchHltbDetailMissing:
with (
patch(f"{PKG}.load_hltb_rush_cache", return_value={440: 15.0}),
patch(f"{PKG}.load_hltb_game_id_cache", return_value={440: 12345}),
patch(f"{PKG}.fetch_hltb_times") as mock_fetch,
patch(f"{_HLTB}.fetch_hltb_times") as mock_fetch,
):
result = fetch_hltb_detail_missing([(440, "TF2")])
assert result == 0
@ -63,7 +64,7 @@ class TestFetchHltbDetailMissing:
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
patch(f"{PKG}.fetch_hltb_times", side_effect=add_rush),
patch(f"{_HLTB}.fetch_hltb_times", side_effect=add_rush),
patch(f"{PKG}.save_hltb_cache") as mock_save,
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 2.0]),
):
@ -90,7 +91,7 @@ class TestFetchHltbDetailMissing:
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
patch(f"{PKG}.fetch_hltb_times"), # no-op, cache stays empty
patch(f"{_HLTB}.fetch_hltb_times"), # no-op, cache stays empty
patch(f"{PKG}.save_hltb_cache", side_effect=capture_save),
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 1.0]),
):
@ -131,7 +132,7 @@ class TestFetchHltbDetailMissing:
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
patch(f"{PKG}.fetch_hltb_times", side_effect=add_hours_and_rush),
patch(f"{_HLTB}.fetch_hltb_times", side_effect=add_hours_and_rush),
patch(f"{PKG}.save_hltb_cache", side_effect=capture_save),
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 1.0]),
):
@ -148,7 +149,7 @@ class TestFetchHltbDetailMissing:
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
patch(f"{PKG}.fetch_hltb_times"),
patch(f"{_HLTB}.fetch_hltb_times"),
patch(f"{PKG}.save_hltb_cache"),
patch(f"{PKG}.time.monotonic", side_effect=[5.0, 5.0]),
):
@ -164,7 +165,7 @@ class TestFetchHltbDetailMissing:
patch(f"{PKG}.load_hltb_count_comp_cache", return_value={}),
patch(f"{PKG}.load_hltb_leisure_100h_cache", return_value={}),
patch(f"{PKG}.load_hltb_game_id_cache", return_value={}),
patch(f"{PKG}.fetch_hltb_times"),
patch(f"{_HLTB}.fetch_hltb_times"),
patch(f"{PKG}.save_hltb_cache"),
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 1.0]),
):

View File

@ -47,9 +47,9 @@ class TestFetchHltbTimesCached:
"""Test uncached games fetched."""
with (
patch(f"{_CACHED}.load_hltb_cache", return_value={440: 50.0}),
patch(f"{_CACHED}.fetch_hltb_times") as mock_fetch,
patch(f"{PKG}.fetch_hltb_times") as mock_fetch,
patch(f"{_CACHED}.save_hltb_cache") as mock_save,
patch(f"{_CACHED}.time.monotonic", side_effect=[0.0, 2.0]),
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 2.0]),
):
# fetch_hltb_times modifies cache in-place
def add_to_cache(
@ -81,9 +81,9 @@ class TestFetchHltbTimesCached:
cb = MagicMock()
with (
patch(f"{_CACHED}.load_hltb_cache", return_value={}),
patch(f"{_CACHED}.fetch_hltb_times") as mock_fetch,
patch(f"{PKG}.fetch_hltb_times") as mock_fetch,
patch(f"{_CACHED}.save_hltb_cache"),
patch(f"{_CACHED}.time.monotonic", side_effect=[0.0, 1.0]),
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 1.0]),
):
mock_fetch.return_value = []
result = fetch_hltb_times_cached(
@ -96,9 +96,9 @@ class TestFetchHltbTimesCached:
"""Covers the elapsed == 0 branch for rate calculation."""
with (
patch(f"{_CACHED}.load_hltb_cache", return_value={}),
patch(f"{_CACHED}.fetch_hltb_times") as mock_fetch,
patch(f"{PKG}.fetch_hltb_times") as mock_fetch,
patch(f"{_CACHED}.save_hltb_cache"),
patch(f"{_CACHED}.time.monotonic", side_effect=[5.0, 5.0]),
patch(f"{PKG}.time.monotonic", side_effect=[5.0, 5.0]),
):
mock_fetch.return_value = []
fetch_hltb_times_cached([(440, "TF2")])
@ -107,9 +107,9 @@ class TestFetchHltbTimesCached:
"""Covers the found count in logging."""
with (
patch(f"{_CACHED}.load_hltb_cache", return_value={}),
patch(f"{_CACHED}.fetch_hltb_times") as mock_fetch,
patch(f"{PKG}.fetch_hltb_times") as mock_fetch,
patch(f"{_CACHED}.save_hltb_cache"),
patch(f"{_CACHED}.time.monotonic", side_effect=[0.0, 3.0]),
patch(f"{PKG}.time.monotonic", side_effect=[0.0, 3.0]),
):
def add_found(

View File

@ -32,6 +32,17 @@ class TestPickBestHltbEntry:
assert result is not None
assert result[0]["game_name"] == "FAITH: The Unholy Trinity"
def test_keeps_the_longer_extended_edition(self) -> None:
"""Two extended editions: the one with more completionist hours wins."""
base: dict[str, Any] = {"game_name": "FAITH", "comp_100": 1800}
longer: dict[str, Any] = {"game_name": "FAITH: Chapter III", "comp_100": 9000}
shorter: dict[str, Any] = {"game_name": "FAITH: Chapter I", "comp_100": 3000}
result = _pick_best_hltb_entry(
"FAITH", [(base, 1.0), (longer, 0.7), (shorter, 0.9)]
)
assert result is not None
assert result[0]["game_name"] == "FAITH: Chapter III"
def test_prefers_full_edition_dash(self) -> None:
"""Test prefers full edition dash."""
demo: dict[str, Any] = {"game_name": "FAITH", "comp_100": 1800}

View File

@ -101,7 +101,7 @@ class TestSearchOne:
ctx = _make_ctx(_make_session(resp))
result = asyncio.run(_search_one(asyncio.Semaphore(1), ctx, 440, "TF2"))
assert result is not None
assert 440 not in ctx.hltb_game_id
assert 440 not in ctx.extras.hltb_game_id
def test_not_found(self) -> None:
"""Test not found."""

View File

@ -22,6 +22,7 @@ if TYPE_CHECKING:
from collections.abc import Iterator
_PKG = "steam_backlog_enforcer._leetcode_bonus"
_API = "steam_backlog_enforcer._status_api"
@pytest.fixture(autouse=True)
@ -104,7 +105,7 @@ class TestFetchLeetcodeToday:
{"leetcode": {"checked": False, "solved_today": False, "reason": "dead"}}
).encode()
with (
patch(f"{_PKG}.http.client.HTTPConnection") as conn,
patch(f"{_API}.http.client.HTTPConnection") as conn,
pytest.raises(ValueError, match="could not check"),
):
resp = conn.return_value.getresponse.return_value
@ -115,7 +116,7 @@ class TestFetchLeetcodeToday:
def test_a_non_200_is_an_error(self) -> None:
"""An error page is not a payload."""
with (
patch(f"{_PKG}.http.client.HTTPConnection") as conn,
patch(f"{_API}.http.client.HTTPConnection") as conn,
pytest.raises(ValueError, match="status 500"),
):
resp = conn.return_value.getresponse.return_value
@ -129,7 +130,7 @@ class TestFetchLeetcodeToday:
payload = json.dumps(
{"leetcode": {"checked": True, "solved_today": True, "reason": "1"}}
).encode()
with patch(f"{_PKG}.http.client.HTTPConnection") as conn:
with patch(f"{_API}.http.client.HTTPConnection") as conn:
resp = conn.return_value.getresponse.return_value
resp.status = 200
resp.read.return_value = payload

View File

@ -14,6 +14,7 @@ if TYPE_CHECKING:
_TYPES = "steam_backlog_enforcer._hltb_types"
_CMD = "steam_backlog_enforcer._cmd_done"
_CONF = "steam_backlog_enforcer._hltb_confidence"
_SCAN = "steam_backlog_enforcer.scanning"
@ -68,7 +69,7 @@ class TestBackfillPollsForFinished:
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
patch(f"{_CMD}.load_snapshot", return_value=[{"app_id": 1, "name": "G"}]),
patch(f"{_CMD}.fetch_hltb_confidence_cached", side_effect=fake_fetch),
patch(f"{_CONF}.fetch_hltb_confidence_cached", side_effect=fake_fetch),
patch(f"{_CMD}._echo"),
):
result = _cmd_done._backfill_polls_for_finished(_state([1]))
@ -93,7 +94,7 @@ class TestBackfillPollsForFinished:
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
patch(f"{_CMD}.load_snapshot", return_value=[{"app_id": 7, "name": "G"}]),
patch(f"{_CMD}.fetch_hltb_confidence_cached", side_effect=fake_fetch),
patch(f"{_CONF}.fetch_hltb_confidence_cached", side_effect=fake_fetch),
patch(f"{_CMD}._echo"),
):
result = _cmd_done._backfill_polls_for_finished(
@ -121,7 +122,7 @@ class TestBackfillPollsForFinished:
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
patch(f"{_CMD}.load_snapshot", return_value=[{"app_id": 3, "name": "G"}]),
patch(f"{_CMD}.fetch_hltb_confidence_cached", side_effect=fake_fetch),
patch(f"{_CONF}.fetch_hltb_confidence_cached", side_effect=fake_fetch),
patch(f"{_CMD}._echo"),
):
_cmd_done._backfill_polls_for_finished(_state([3]))

View File

@ -15,6 +15,7 @@ if TYPE_CHECKING:
_TYPES = "steam_backlog_enforcer._hltb_types"
_CMD = "steam_backlog_enforcer._cmd_done"
_CONF = "steam_backlog_enforcer._hltb_confidence"
_SCAN = "steam_backlog_enforcer.scanning"
_SCANCONF = "steam_backlog_enforcer._scanning_confidence"
_POLLS = "steam_backlog_enforcer._polls_reporting"
@ -160,7 +161,7 @@ class TestScanningPollsIntegration:
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
patch(
f"{_POLLS}.fetch_hltb_confidence_cached",
f"{_CONF}.fetch_hltb_confidence_cached",
side_effect=fake_fetch,
),
):
@ -197,7 +198,7 @@ class TestScanningPollsIntegration:
patch(f"{_TYPES}.HLTB_CACHE_FILE", cache_file),
patch(f"{_TYPES}.CONFIG_DIR", tmp_path),
patch(
f"{_POLLS}.fetch_hltb_confidence_cached",
f"{_CONF}.fetch_hltb_confidence_cached",
side_effect=fake_fetch,
),
):

View File

@ -141,6 +141,11 @@ class TestPickNextGameGroup2:
"steam_backlog_enforcer._scanning_confidence._echo",
side_effect=lambda *a, **_: echoed.append(a[0]),
),
# The "nothing assignable" line is spoken where the slot is cleared.
patch(
"steam_backlog_enforcer._scanning_assign._echo",
side_effect=lambda *a, **_: echoed.append(a[0]),
),
patch(
"steam_backlog_enforcer._scanning_candidates._pick_playable_candidate",
return_value=None,

View File

@ -5,11 +5,13 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import patch
from steam_backlog_enforcer.store_blocker import (
from steam_backlog_enforcer._hosts_protection import (
_disable_hosts_protection,
_enable_hosts_protection,
_reblock_hosts,
_sudo_write_hosts,
)
from steam_backlog_enforcer.store_blocker import (
_unblock_hosts,
flush_dns_cache,
)
@ -18,6 +20,7 @@ if TYPE_CHECKING:
from pathlib import Path
PKG = "steam_backlog_enforcer.store_blocker"
_HP = "steam_backlog_enforcer._hosts_protection"
class TestSudoWriteHosts:
@ -70,10 +73,10 @@ class TestUnblockHosts:
)
with (
patch(f"{PKG}.is_store_blocked", return_value=True),
patch(f"{PKG}.HOSTS_FILE", hosts_file),
patch(f"{PKG}._disable_hosts_protection"),
patch(f"{PKG}._enable_hosts_protection"),
patch(f"{PKG}._sudo_write_hosts") as mock_write,
patch(f"{_HP}.HOSTS_FILE", hosts_file),
patch(f"{_HP}._disable_hosts_protection"),
patch(f"{_HP}._enable_hosts_protection"),
patch(f"{_HP}._sudo_write_hosts") as mock_write,
):
result = _unblock_hosts()
assert result is True
@ -88,10 +91,10 @@ class TestUnblockHosts:
)
with (
patch(f"{PKG}.is_store_blocked", return_value=True),
patch(f"{PKG}.HOSTS_FILE", hosts_file),
patch(f"{PKG}._disable_hosts_protection"),
patch(f"{PKG}._enable_hosts_protection"),
patch(f"{PKG}._sudo_write_hosts") as mock_write,
patch(f"{_HP}.HOSTS_FILE", hosts_file),
patch(f"{_HP}._disable_hosts_protection"),
patch(f"{_HP}._enable_hosts_protection"),
patch(f"{_HP}._sudo_write_hosts") as mock_write,
):
result = _unblock_hosts()
assert result is True
@ -100,7 +103,7 @@ class TestUnblockHosts:
def test_os_error(self) -> None:
with (
patch(f"{PKG}.is_store_blocked", return_value=True),
patch(f"{PKG}._disable_hosts_protection", side_effect=OSError),
patch(f"{_HP}._disable_hosts_protection", side_effect=OSError),
):
result = _unblock_hosts()
assert result is False

View File

@ -25,6 +25,7 @@ if TYPE_CHECKING:
from collections.abc import Iterator
_PKG = "steam_backlog_enforcer._workout_budget"
_API = "steam_backlog_enforcer._status_api"
@pytest.fixture(autouse=True)
@ -112,7 +113,8 @@ class TestWorkoutLoggedToday:
"""A workout logged later in the day still raises the budget."""
with (
patch(f"{_PKG}._fetch_workout_today", return_value=False) as fetch,
patch(f"{_PKG}.time.monotonic", side_effect=[0.0, 999.0]),
# Stored at 0.0; read back at 999.0 (expired); stored again.
patch(f"{_API}.time.monotonic", side_effect=[0.0, 999.0, 999.0]),
):
workout_logged_today(_config())
workout_logged_today(_config())

View File

@ -22,7 +22,7 @@
"@testing-library/jest-dom": "7.0.1",
"@testing-library/react": "16.3.3",
"@testing-library/user-event": "14.6.7",
"@types/node": "26.4.0",
"@types/node": "26.5.1",
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"@vitejs/plugin-react": "6.1.1",

View File

@ -31,8 +31,8 @@ importers:
specifier: 14.6.7
version: 14.6.7(@testing-library/dom@10.4.1)
'@types/node':
specifier: 26.4.0
version: 26.4.0
specifier: 26.5.1
version: 26.5.1
'@types/react':
specifier: 19.3.0
version: 19.3.0
@ -41,7 +41,7 @@ importers:
version: 19.3.0(@types/react@19.3.0)
'@vitejs/plugin-react':
specifier: 6.1.1
version: 6.1.1(vite@8.3.0(@types/node@26.4.0))
version: 6.1.1(vite@8.3.0(@types/node@26.5.1))
'@vitest/coverage-v8':
specifier: 5.0.0
version: 5.0.0(vitest@5.0.0)
@ -68,10 +68,10 @@ importers:
version: 8.70.0(eslint@10.10.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3)
vite:
specifier: 8.3.0
version: 8.3.0(@types/node@26.4.0)
version: 8.3.0(@types/node@26.5.1)
vitest:
specifier: 5.0.0
version: 5.0.0(@types/node@26.4.0)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.4.0))
version: 5.0.0(@types/node@26.5.1)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.5.1))
packages:
@ -458,8 +458,8 @@ packages:
'@types/json-schema@7.0.15':
resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}
'@types/node@26.4.0':
resolution: {integrity: sha512-faiGnoIrLH/V8cibOMEAZ8pMw6oXqSukl29ra4mN8GdaB2ZewzeaLj+INpV5N+Z1eKWzY+IzaIZH2EIR6YZRNQ==}
'@types/node@26.5.1':
resolution: {integrity: sha512-CzNm2FezW4VR/LjG6yUdiEgLE/rAQ9Slj5gCu/C2VrdcW7I0ahNZ8DRbHT7zOZ6r3ONgd/bsQIeSaoDGrd1C6g==}
'@types/react-dom@19.3.0':
resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==}
@ -1210,8 +1210,8 @@ packages:
engines: {node: '>=14.17'}
hasBin: true
undici-types@8.3.0:
resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==}
undici-types@8.9.0:
resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==}
undici@8.10.0:
resolution: {integrity: sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ==}
@ -1681,7 +1681,7 @@ snapshots:
picocolors: 1.1.1
redent: 3.0.0
optionalDependencies:
vitest: 5.0.0(@types/node@26.4.0)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.4.0))
vitest: 5.0.0(@types/node@26.5.1)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.5.1))
'@testing-library/react@16.3.3(@testing-library/dom@10.4.1)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)':
dependencies:
@ -1712,9 +1712,9 @@ snapshots:
'@types/json-schema@7.0.15': {}
'@types/node@26.4.0':
'@types/node@26.5.1':
dependencies:
undici-types: 8.3.0
undici-types: 8.9.0
'@types/react-dom@19.3.0(@types/react@19.3.0)':
dependencies:
@ -1815,10 +1815,10 @@ snapshots:
'@typescript-eslint/types': 8.70.0
eslint-visitor-keys: 5.0.1
'@vitejs/plugin-react@6.1.1(vite@8.3.0(@types/node@26.4.0))':
'@vitejs/plugin-react@6.1.1(vite@8.3.0(@types/node@26.5.1))':
dependencies:
'@rolldown/pluginutils': 1.0.1
vite: 8.3.0(@types/node@26.4.0)
vite: 8.3.0(@types/node@26.5.1)
'@vitest/coverage-v8@5.0.0(vitest@5.0.0)':
dependencies:
@ -1830,7 +1830,7 @@ snapshots:
obug: 2.1.4
std-env: 4.2.0
tinyrainbow: 3.1.1
vitest: 5.0.0(@types/node@26.4.0)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.4.0))
vitest: 5.0.0(@types/node@26.5.1)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.5.1))
'@vitest/istanbul-lib-coverage@1.0.1': {}
@ -1838,14 +1838,14 @@ snapshots:
dependencies:
'@vitest/istanbul-lib-coverage': 1.0.1
'@vitest/mocker@5.0.0(vite@8.3.0(@types/node@26.4.0))':
'@vitest/mocker@5.0.0(vite@8.3.0(@types/node@26.5.1))':
dependencies:
'@jridgewell/trace-mapping': 0.3.31
'@vitest/spy': 5.0.0
estree-walker: 3.0.3
magic-string: 1.3.1
optionalDependencies:
vite: 8.3.0(@types/node@26.4.0)
vite: 8.3.0(@types/node@26.5.1)
'@vitest/spy@5.0.0': {}
@ -2431,7 +2431,7 @@ snapshots:
typescript@6.0.3: {}
undici-types@8.3.0: {}
undici-types@8.9.0: {}
undici@8.10.0: {}
@ -2445,7 +2445,7 @@ snapshots:
dependencies:
punycode: 2.3.1
vite@8.3.0(@types/node@26.4.0):
vite@8.3.0(@types/node@26.5.1):
dependencies:
lightningcss: 1.33.0
picomatch: 4.0.7
@ -2453,13 +2453,13 @@ snapshots:
rolldown: 1.2.6
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 26.4.0
'@types/node': 26.5.1
fsevents: 2.3.3
vitest@5.0.0(@types/node@26.4.0)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.4.0)):
vitest@5.0.0(@types/node@26.5.1)(@vitest/coverage-v8@5.0.0)(jsdom@30.0.1)(vite@8.3.0(@types/node@26.5.1)):
dependencies:
'@types/chai': 5.2.3
'@vitest/mocker': 5.0.0(vite@8.3.0(@types/node@26.4.0))
'@vitest/mocker': 5.0.0(vite@8.3.0(@types/node@26.5.1))
chai: 6.2.2
es-module-lexer: 2.3.2
expect-type: 1.4.0
@ -2470,10 +2470,10 @@ snapshots:
tinybench: 6.1.4
tinyexec: 1.3.0
tinyglobby: 0.2.17
vite: 8.3.0(@types/node@26.4.0)
vite: 8.3.0(@types/node@26.5.1)
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 26.4.0
'@types/node': 26.5.1
'@vitest/coverage-v8': 5.0.0(vitest@5.0.0)
jsdom: 30.0.1
transitivePeerDependencies: